Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .github/workflows/integrations-ghcr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,7 @@ jobs:

- name: Install Syft (SBOM)
if: ${{ matrix.generate_sbom && steps.meta.outputs.has_tags == 'true' }}
uses: anchore/sbom-action/download-syft@v0.21.0
uses: anchore/sbom-action/download-syft@v0.22.2

- name: Generate SBOMs (CycloneDX)
id: sbom
Expand Down Expand Up @@ -377,7 +377,7 @@ jobs:

- name: Trivy vulnerability scan (HIGH/CRITICAL)
if: ${{ steps.meta.outputs.has_tags == 'true' }}
uses: aquasecurity/trivy-action@0.33.1
uses: aquasecurity/trivy-action@0.34.0
with:
# Gate on HIGH/CRITICAL with fixes available (vendor/unfixed CVEs are still surfaced by the next step).
# This avoids blocking nightly builds on upstream issues we can't remediate immediately, while keeping
Expand All @@ -393,7 +393,7 @@ jobs:

- name: Trivy vulnerability scan report (includes unfixed)
if: ${{ steps.meta.outputs.has_tags == 'true' }}
uses: aquasecurity/trivy-action@0.33.1
uses: aquasecurity/trivy-action@0.34.0
with:
image-ref: ${{ steps.meta.outputs.primary_tag }}
format: table
Expand Down
6 changes: 3 additions & 3 deletions .github/workflows/self-hosted-builds-hardened.yml
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ jobs:

- name: Scan Ollama CUDA with Trivy
if: github.event_name != 'pull_request'
uses: aquasecurity/trivy-action@0.33.1
uses: aquasecurity/trivy-action@0.34.0
with:
image-ref: ${{ env.IMAGE_PREFIX }}/pmoves-ollama:cuda-${{ github.sha }}
format: sarif
Expand Down Expand Up @@ -130,7 +130,7 @@ jobs:

- name: Scan Hi-RAG GPU with Trivy
if: github.event_name != 'pull_request'
uses: aquasecurity/trivy-action@0.33.1
uses: aquasecurity/trivy-action@0.34.0
with:
image-ref: ${{ env.IMAGE_PREFIX }}/pmoves-hirag-gateway:gpu-${{ github.sha }}
format: sarif
Expand Down Expand Up @@ -249,7 +249,7 @@ jobs:

- name: Scan ${{ matrix.service.name }} with Trivy
if: github.event_name != 'pull_request'
uses: aquasecurity/trivy-action@0.33.1
uses: aquasecurity/trivy-action@0.34.0
with:
image-ref: ${{ env.IMAGE_PREFIX }}/pmoves-${{ matrix.service.name }}:${{ github.sha }}
format: sarif
Expand Down
39 changes: 29 additions & 10 deletions pmoves/services/gateway/gateway/api/chit.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@
constellation_ids: List[str] = Field(default_factory=list)
per_constellation: int = 10
codebook_path: Optional[str] = None
sig: Optional[Dict[str, Any]] = None


def ingest_cgp(cgp: Dict[str, Any]) -> str:
Expand Down Expand Up @@ -205,22 +206,31 @@
raise HTTPException(status_code=404, detail="point not found")
return {"ok": True, "locator": loc}

def _load_codebook(path: str):
items=[];
if not os.path.exists(path): path="tests/data/codebook.jsonl"
if not os.path.exists(path): return items
with open(path,"r",encoding="utf-8") as f:
def _load_codebook(codebook_path: Optional[str] = None):
if codebook_path:
safe_name = os.path.basename(codebook_path)
if not safe_name:
safe_name = os.path.basename(CHIT_CODEBOOK_PATH or "codebook.jsonl")
codebook_dir = os.path.dirname(CHIT_CODEBOOK_PATH or "tests/data/codebook.jsonl") or "."
path = os.path.join(codebook_dir, safe_name)
else:
path = CHIT_CODEBOOK_PATH or "tests/data/codebook.jsonl"
items = []
if not os.path.exists(path):

Check failure

Code scanning / CodeQL

Uncontrolled data used in path expression High

This path depends on a
user-provided value
.
This path depends on a
user-provided value
.
This path depends on a
user-provided value
.
This path depends on a
user-provided value
.

Copilot Autofix

AI 9 months ago

In general, the fix is to validate any user‑influenced path before using it for filesystem access. A robust pattern is to (1) define a trusted root directory, (2) normalize/resolve the candidate path, and (3) enforce that the final path remains under the trusted root, and optionally (4) restrict to an allow‑list of filenames.

For this specific code, the unsafe part is _load_codebook in pmoves/services/gateway/gateway/api/chit.py. The function currently takes codebook_path, extracts os.path.basename(codebook_path), and joins it with codebook_dir (derived from CHIT_CODEBOOK_PATH). To keep behavior while adding safety:

  • Keep the idea that codebooks must reside in the same directory as the default CHIT_CODEBOOK_PATH.
  • Normalize both the root directory and the final candidate file path with os.path.abspath.
  • After constructing the candidate path, verify that it is still inside the trusted root with os.path.commonpath.
  • Optionally fall back to the default basename when no safe basename can be obtained.
  • Leave the public API (decode_constellations, endpoints in viz.py/chit.py) unchanged; only harden _load_codebook.

Concretely, in _load_codebook:

  1. Compute codebook_root = os.path.dirname(CHIT_CODEBOOK_PATH or "tests/data/codebook.jsonl") or ".", then normalize with os.path.abspath.
  2. When codebook_path is provided, compute safe_name = os.path.basename(codebook_path), and if it’s empty, fall back to os.path.basename(CHIT_CODEBOOK_PATH or "codebook.jsonl").
  3. Build candidate = os.path.abspath(os.path.join(codebook_root, safe_name)).
  4. Check os.path.commonpath([codebook_root, candidate]) == codebook_root. If not, log a warning and fall back to the default file under the root (or return an empty list).
  5. Use the validated candidate (or the default) as path.

This approach keeps existing behavior (user can still choose among files in the configured codebook directory) but ensures the path stays in that directory and removes CodeQL’s “uncontrolled path” concern.

Only pmoves/services/gateway/gateway/api/chit.py needs code edits; viz.py just passes strings through and does not itself access the filesystem.


Suggested changeset 1
pmoves/services/gateway/gateway/api/chit.py

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/pmoves/services/gateway/gateway/api/chit.py b/pmoves/services/gateway/gateway/api/chit.py
--- a/pmoves/services/gateway/gateway/api/chit.py
+++ b/pmoves/services/gateway/gateway/api/chit.py
@@ -213,15 +213,47 @@
     return {"ok": True, "locator": loc}
 
 def _load_codebook(codebook_path: Optional[str] = None):
+    """
+    Load a codebook file from a trusted directory.
+
+    If a codebook_path is provided, only its basename is honored, and the final
+    path is constrained to live under the directory of CHIT_CODEBOOK_PATH.
+    """
+    # Determine the trusted root directory for codebook files.
+    default_codebook = CHIT_CODEBOOK_PATH or "tests/data/codebook.jsonl"
+    codebook_root = os.path.dirname(default_codebook) or "."
+    codebook_root = os.path.abspath(codebook_root)
+
+    path: str
     if codebook_path:
+        # Only allow selecting a file by basename within the trusted root.
         safe_name = os.path.basename(codebook_path)
         if not safe_name:
-            safe_name = os.path.basename(CHIT_CODEBOOK_PATH or "codebook.jsonl")
-        codebook_dir = os.path.dirname(CHIT_CODEBOOK_PATH or "tests/data/codebook.jsonl") or "."
-        path = os.path.join(codebook_dir, safe_name)
+            safe_name = os.path.basename(default_codebook)
+        candidate = os.path.abspath(os.path.join(codebook_root, safe_name))
+        try:
+            # Ensure the candidate path stays within the trusted root directory.
+            if os.path.commonpath([codebook_root, candidate]) != codebook_root:
+                logger.warning(
+                    "Rejected codebook_path %r outside trusted directory %r",
+                    codebook_path,
+                    codebook_root,
+                )
+                path = default_codebook
+            else:
+                path = candidate
+        except ValueError:
+            # In case of invalid path components, fall back to default.
+            logger.warning(
+                "Invalid codebook_path %r; falling back to default %r",
+                codebook_path,
+                default_codebook,
+            )
+            path = default_codebook
     else:
-        path = CHIT_CODEBOOK_PATH or "tests/data/codebook.jsonl"
-    items = []
+        path = default_codebook
+
+    items: List[Dict[str, Any]] = []
     if not os.path.exists(path):
         return items
     with open(path, "r", encoding="utf-8") as f:
EOF
@@ -213,15 +213,47 @@
return {"ok": True, "locator": loc}

def _load_codebook(codebook_path: Optional[str] = None):
"""
Load a codebook file from a trusted directory.

If a codebook_path is provided, only its basename is honored, and the final
path is constrained to live under the directory of CHIT_CODEBOOK_PATH.
"""
# Determine the trusted root directory for codebook files.
default_codebook = CHIT_CODEBOOK_PATH or "tests/data/codebook.jsonl"
codebook_root = os.path.dirname(default_codebook) or "."
codebook_root = os.path.abspath(codebook_root)

path: str
if codebook_path:
# Only allow selecting a file by basename within the trusted root.
safe_name = os.path.basename(codebook_path)
if not safe_name:
safe_name = os.path.basename(CHIT_CODEBOOK_PATH or "codebook.jsonl")
codebook_dir = os.path.dirname(CHIT_CODEBOOK_PATH or "tests/data/codebook.jsonl") or "."
path = os.path.join(codebook_dir, safe_name)
safe_name = os.path.basename(default_codebook)
candidate = os.path.abspath(os.path.join(codebook_root, safe_name))
try:
# Ensure the candidate path stays within the trusted root directory.
if os.path.commonpath([codebook_root, candidate]) != codebook_root:
logger.warning(
"Rejected codebook_path %r outside trusted directory %r",
codebook_path,
codebook_root,
)
path = default_codebook
else:
path = candidate
except ValueError:
# In case of invalid path components, fall back to default.
logger.warning(
"Invalid codebook_path %r; falling back to default %r",
codebook_path,
default_codebook,
)
path = default_codebook
else:
path = CHIT_CODEBOOK_PATH or "tests/data/codebook.jsonl"
items = []
path = default_codebook

items: List[Dict[str, Any]] = []
if not os.path.exists(path):
return items
with open(path, "r", encoding="utf-8") as f:
Copilot is powered by AI and may make mistakes. Always verify output.
return items
with open(path, "r", encoding="utf-8") as f:
Comment thread Fixed

Check failure

Code scanning / CodeQL

Uncontrolled data used in path expression High

This path depends on a
user-provided value
.
This path depends on a
user-provided value
.
This path depends on a
user-provided value
.
This path depends on a
user-provided value
.

Copilot Autofix

AI 9 months ago

At a high level, the fix is to ensure that any path derived from untrusted input is both (1) rooted inside a designated safe directory and (2) restricted to a safe filename pattern, so that user input can’t cause access to arbitrary files. This can be done by combining os.path.basename or a stricter sanitization with a configured codebook directory, normalizing the result, and verifying that it still lies under that directory. We should also avoid silently accepting environment defaults that might point outside that controlled area.

For this codebase, the most straightforward fix without changing behavior is:

  1. Introduce a dedicated, normalized “codebook directory” derived from CHIT_CODEBOOK_PATH once, and use that as the root for all dynamic loads.
  2. In _load_codebook:
    • If a codebook_path argument is provided, treat it as a filename only (drop any directory elements with os.path.basename).
    • If the resulting name is empty, fall back to the basename of CHIT_CODEBOOK_PATH.
    • Join this filename with the safe directory, normalize with os.path.normpath, and verify it is still within the safe directory (prefix check after ensuring the directory has a trailing separator).
    • Only then, open the file.
  3. For the default case where codebook_path is not provided, we likewise normalize CHIT_CODEBOOK_PATH and ensure it resides under the same safe directory. Since we cannot change semantics much, we will continue to allow the configured CHIT_CODEBOOK_PATH, but we’ll still normalize it and keep the canonical directory for user‑supplied overrides.

We do not need to touch viz.py directly for the taint issue, since the risky open() is in chit.py; we instead ensure that _load_codebook is robust regardless of where its codebook_path comes from. No new external libraries are necessary beyond os, which is already imported.

Concretely, in pmoves/services/gateway/gateway/api/chit.py:

  • Precompute CHIT_CODEBOOK_DIR as the directory of CHIT_CODEBOOK_PATH (or a default), and normalize it to an absolute path.
  • Rewrite _load_codebook to:
    • Compute a target_path based on a sanitized filename (if codebook_path is given) or the configured default file (if not).
    • Normalize target_path and ensure it starts with CHIT_CODEBOOK_DIR + os.sep (or equals the directory itself plus filename) to prevent escaping.
    • Use target_path in os.path.exists and open.

This approach preserves the existing feature (selecting alternative codebook files by name) but prevents users from specifying arbitrary directories or traversal paths, addressing all variants of the alert at the shared sink.

Suggested changeset 1
pmoves/services/gateway/gateway/api/chit.py

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/pmoves/services/gateway/gateway/api/chit.py b/pmoves/services/gateway/gateway/api/chit.py
--- a/pmoves/services/gateway/gateway/api/chit.py
+++ b/pmoves/services/gateway/gateway/api/chit.py
@@ -14,6 +14,8 @@
 CHIT_DECRYPT_ANCHORS = os.getenv("CHIT_DECRYPT_ANCHORS","false").lower()=="true"
 CHIT_PASSPHRASE = os.getenv("CHIT_PASSPHRASE","change-me")
 CHIT_CODEBOOK_PATH = os.getenv("CHIT_CODEBOOK_PATH","tests/data/codebook.jsonl")
+# Normalized base directory for codebook files; user-supplied filenames are restricted to this directory.
+CHIT_CODEBOOK_DIR = os.path.dirname(os.path.abspath(CHIT_CODEBOOK_PATH or "tests/data/codebook.jsonl")) or os.path.abspath(".")
 CHIT_LEARNED_TEXT = os.getenv("CHIT_LEARNED_TEXT","false").lower()=="true"
 CHIT_T5_MODEL = os.getenv("CHIT_T5_MODEL")  # optional HF model path/name
 
@@ -213,25 +215,44 @@
     return {"ok": True, "locator": loc}
 
 def _load_codebook(codebook_path: Optional[str] = None):
+    """
+    Load codebook entries from a file.
+
+    If codebook_path is provided, it is treated as a filename only and forced to reside
+    under CHIT_CODEBOOK_DIR. This avoids using arbitrary filesystem paths based on
+    untrusted input.
+    """
+    # Determine the target path within the configured codebook directory.
     if codebook_path:
         safe_name = os.path.basename(codebook_path)
         if not safe_name:
             safe_name = os.path.basename(CHIT_CODEBOOK_PATH or "codebook.jsonl")
-        codebook_dir = os.path.dirname(CHIT_CODEBOOK_PATH or "tests/data/codebook.jsonl") or "."
-        path = os.path.join(codebook_dir, safe_name)
+        target_path = os.path.join(CHIT_CODEBOOK_DIR, safe_name)
     else:
-        path = CHIT_CODEBOOK_PATH or "tests/data/codebook.jsonl"
-    items = []
-    if not os.path.exists(path):
+        # Use the configured default path, but normalize it to an absolute path.
+        target_path = os.path.abspath(CHIT_CODEBOOK_PATH or "tests/data/codebook.jsonl")
+
+    # Normalize and enforce that the path stays within the configured codebook directory
+    norm_path = os.path.normpath(target_path)
+    # Only enforce the directory constraint for user-supplied filenames; the default path
+    # is assumed to be trusted configuration.
+    if codebook_path:
+        codebook_dir_with_sep = CHIT_CODEBOOK_DIR.rstrip(os.sep) + os.sep
+        if not norm_path.startswith(codebook_dir_with_sep):
+            logger.warning("Rejected codebook_path outside of CHIT_CODEBOOK_DIR: %s", norm_path)
+            return []
+
+    items: List[Dict[str, Any]] = []
+    if not os.path.exists(norm_path):
         return items
-    with open(path, "r", encoding="utf-8") as f:
+    with open(norm_path, "r", encoding="utf-8") as f:
         for ln in f:
             ln = ln.strip()
             if ln:
                 try:
                     items.append(json.loads(ln))
                 except json.JSONDecodeError:
-                    logger.warning("Skipping malformed codebook line in %s", path)
+                    logger.warning("Skipping malformed codebook line in %s", norm_path)
                     continue
     return items
 
EOF
@@ -14,6 +14,8 @@
CHIT_DECRYPT_ANCHORS = os.getenv("CHIT_DECRYPT_ANCHORS","false").lower()=="true"
CHIT_PASSPHRASE = os.getenv("CHIT_PASSPHRASE","change-me")
CHIT_CODEBOOK_PATH = os.getenv("CHIT_CODEBOOK_PATH","tests/data/codebook.jsonl")
# Normalized base directory for codebook files; user-supplied filenames are restricted to this directory.
CHIT_CODEBOOK_DIR = os.path.dirname(os.path.abspath(CHIT_CODEBOOK_PATH or "tests/data/codebook.jsonl")) or os.path.abspath(".")
CHIT_LEARNED_TEXT = os.getenv("CHIT_LEARNED_TEXT","false").lower()=="true"
CHIT_T5_MODEL = os.getenv("CHIT_T5_MODEL") # optional HF model path/name

@@ -213,25 +215,44 @@
return {"ok": True, "locator": loc}

def _load_codebook(codebook_path: Optional[str] = None):
"""
Load codebook entries from a file.

If codebook_path is provided, it is treated as a filename only and forced to reside
under CHIT_CODEBOOK_DIR. This avoids using arbitrary filesystem paths based on
untrusted input.
"""
# Determine the target path within the configured codebook directory.
if codebook_path:
safe_name = os.path.basename(codebook_path)
if not safe_name:
safe_name = os.path.basename(CHIT_CODEBOOK_PATH or "codebook.jsonl")
codebook_dir = os.path.dirname(CHIT_CODEBOOK_PATH or "tests/data/codebook.jsonl") or "."
path = os.path.join(codebook_dir, safe_name)
target_path = os.path.join(CHIT_CODEBOOK_DIR, safe_name)
else:
path = CHIT_CODEBOOK_PATH or "tests/data/codebook.jsonl"
items = []
if not os.path.exists(path):
# Use the configured default path, but normalize it to an absolute path.
target_path = os.path.abspath(CHIT_CODEBOOK_PATH or "tests/data/codebook.jsonl")

# Normalize and enforce that the path stays within the configured codebook directory
norm_path = os.path.normpath(target_path)
# Only enforce the directory constraint for user-supplied filenames; the default path
# is assumed to be trusted configuration.
if codebook_path:
codebook_dir_with_sep = CHIT_CODEBOOK_DIR.rstrip(os.sep) + os.sep
if not norm_path.startswith(codebook_dir_with_sep):
logger.warning("Rejected codebook_path outside of CHIT_CODEBOOK_DIR: %s", norm_path)
return []

items: List[Dict[str, Any]] = []
if not os.path.exists(norm_path):
return items
with open(path, "r", encoding="utf-8") as f:
with open(norm_path, "r", encoding="utf-8") as f:
for ln in f:
ln = ln.strip()
if ln:
try:
items.append(json.loads(ln))
except json.JSONDecodeError:
logger.warning("Skipping malformed codebook line in %s", path)
logger.warning("Skipping malformed codebook line in %s", norm_path)
continue
return items

Copilot is powered by AI and may make mistakes. Always verify output.
for ln in f:
ln=ln.strip();
if ln: items.append(json.loads(ln))
ln = ln.strip()
if ln:
items.append(json.loads(ln))
return items
Comment on lines +215 to 236

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

CodeQL alerts #34, #35, #36 are NOT resolved — path still derives from user input, and json.loads has no error handling.

Path traversal (CodeQL lines 219 & 221): os.path.basename() constrains traversal to the codebook directory, but CodeQL's taint analysis correctly observes that safe_name still originates from user-supplied codebook_path. The pipeline confirms this — both alerts remain open. The PR description states that "_load_codebook() now always reads the path from the CHIT_CODEBOOK_PATH environment variable", but codebook_path: Optional[str] = None remains in GeometryDecodeTextRequest (line 125) and in the geometry_calibration_report signature. The only fix that closes these alerts is removing codebook_path from all public API surfaces and reading exclusively from the env var.

Malformed codebook lines (line 225): json.loads(ln) has no error handling. A single malformed JSON line causes a JSONDecodeError that propagates as a 500 error. The reference implementation in pmoves/services/hi-rag-gateway/gateway.py (lines 193–196) wraps each line in a try/except and continues — this PR regresses that behaviour.

🛡️ Proposed fix — remove user input from path construction entirely
-def _load_codebook(codebook_path: Optional[str] = None):
-    if codebook_path:
-        safe_name = os.path.basename(codebook_path)
-        if not safe_name:
-            safe_name = os.path.basename(CHIT_CODEBOOK_PATH or "codebook.jsonl")
-        codebook_dir = os.path.dirname(CHIT_CODEBOOK_PATH or "tests/data/codebook.jsonl") or "."
-        path = os.path.join(codebook_dir, safe_name)
-    else:
-        path = CHIT_CODEBOOK_PATH or "tests/data/codebook.jsonl"
+def _load_codebook():
+    path = CHIT_CODEBOOK_PATH or "tests/data/codebook.jsonl"
     items = []
     if not os.path.exists(path):
         return items
     with open(path, "r", encoding="utf-8") as f:
         for ln in f:
             ln = ln.strip()
             if ln:
-                items.append(json.loads(ln))
+                try:
+                    items.append(json.loads(ln))
+                except json.JSONDecodeError:
+                    continue
     return items

Then update all call sites (decode_constellations, geometry_decode_text, geometry_calibration_report) to remove the codebook_path argument, and remove the field from GeometryDecodeTextRequest (line 125) and from the geometry_calibration_report route signature.

🧰 Tools
🪛 GitHub Check: CodeQL

[failure] 219-219: Uncontrolled data used in path expression
This path depends on a user-provided value.
This path depends on a user-provided value.
This path depends on a user-provided value.
This path depends on a user-provided value.
This path depends on a user-provided value.
This path depends on a user-provided value.
This path depends on a user-provided value.


[failure] 221-221: Uncontrolled data used in path expression
This path depends on a user-provided value.
This path depends on a user-provided value.
This path depends on a user-provided value.
This path depends on a user-provided value.
This path depends on a user-provided value.
This path depends on a user-provided value.
This path depends on a user-provided value.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pmoves/services/gateway/gateway/api/chit.py` around lines 209 - 226, The
_load_codebook function still accepts and uses a user-supplied codebook_path
(taint source) and calls json.loads without handling JSONDecodeError; remove the
user-input surface by deleting the codebook_path parameter from all public APIs
and call sites (remove the field from GeometryDecodeTextRequest and drop the
codebook_path argument in decode_constellations, geometry_decode_text, and
geometry_calibration_report) so _load_codebook reads exclusively from
CHIT_CODEBOOK_PATH (or the test default); also harden _load_codebook by wrapping
each json.loads(ln) in a try/except JSONDecodeError and continue on error so a
single bad line does not raise a 500.


def decode_constellations(
constellations: Sequence[Constellation],
per_constellation: int = 10,
codebook_path: Optional[str] = None,
) -> Dict[str, Any]:
Comment on lines 238 to 242

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Restore decode_constellations call compatibility

Removing the codebook_path parameter from decode_constellations breaks existing callers that still pass that keyword (pmoves/services/gateway/gateway/api/viz.py:144 and :175). In practice, hitting /preview/decode or /mix/decode now raises TypeError: decode_constellations() got an unexpected keyword argument 'codebook_path', so these routes return 500 instead of a decode payload.

Useful? React with 👍 / 👎.

items = _load_codebook(codebook_path or CHIT_CODEBOOK_PATH)
items = _load_codebook(codebook_path)
if not items:
return {"items": []}
out: List[Dict[str, Any]] = []
Expand Down Expand Up @@ -269,6 +279,9 @@

@router.post("/geometry/decode/text")
def geometry_decode_text(body: GeometryDecodeTextRequest):
if body.codebook_path and CHIT_REQUIRE_SIGNATURE:
if not verify_hmac(body.model_dump()):
raise HTTPException(status_code=403, detail="codebook_path requires CHIT-signed request")
Comment on lines +292 to +294

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

codebook_path guard is inert under the default configuration.

CHIT_REQUIRE_SIGNATURE defaults to false, so body.codebook_path and CHIT_REQUIRE_SIGNATURE is always False in a vanilla deployment. Any caller can freely supply codebook_path values with no HMAC check — the only protection is the basename() restriction in _load_codebook. This means the file-probing risk (enumerating files in the codebook directory) is not mitigated by default.

The fundamental fix is to remove codebook_path from the public API (see comment on _load_codebook), which makes this guard unnecessary.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pmoves/services/gateway/gateway/api/chit.py` around lines 282 - 284, The
endpoint currently accepts body.codebook_path (checked only under
CHIT_REQUIRE_SIGNATURE which defaults false), leaving the API able to receive
arbitrary codebook_path values; remove codebook_path from the public request
model and all uses of body.codebook_path in the handler, delete the inert
CHIT_REQUIRE_SIGNATURE/verify_hmac guard around it, and instead keep codebook
loading internal via _load_codebook (ensure _load_codebook enforces basename()
restriction and only accepts server-side known names or an internal enum/id),
and update any callers/tests to supply only internal identifiers rather than a
public codebook_path.

if shape_store is None:
raise HTTPException(status_code=503, detail="ShapeStore unavailable")

Expand Down Expand Up @@ -307,8 +320,14 @@
return resp

@router.post("/geometry/calibration/report")
def geometry_calibration_report(cgp: CGP, codebook_path: Optional[str] = None):
items = _load_codebook(codebook_path or CHIT_CODEBOOK_PATH)
def geometry_calibration_report(cgp: CGP, codebook_path: Optional[str] = None, sig: Optional[Dict[str, Any]] = None):
if codebook_path and CHIT_REQUIRE_SIGNATURE:
payload = {"codebook_path": codebook_path, "cgp": cgp.model_dump()}
if sig:
payload["sig"] = sig
if not verify_hmac(payload):
raise HTTPException(status_code=403, detail="codebook_path requires CHIT-signed request")
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
items = _load_codebook(codebook_path)
if not items: return {"KL": None, "JS": None, "coverage": 0.0}
const = cgp.super_nodes[0].constellations[0]
anchor = const.anchor or []
Expand Down
22 changes: 17 additions & 5 deletions pmoves/services/gateway/web/client.html
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,23 @@
};
const links = (shapeId, base) => {
const el = $("#links");
if (!shapeId) { el.textContent = ""; return; }
const svg = `${base}/viz/shape/${shapeId}.svg`;
const raw = `${base}/data/${shapeId}.json`;
const dec = `${base}/viz/decode/${shapeId}.html`;
el.innerHTML = `View: <a href="${svg}" target="_blank">Shape SVG</a> · <a href="${raw}" target="_blank">Raw JSON</a> · <a href="${dec}" target="_blank">Decode</a>`;
el.textContent = "";
if (!shapeId) return;
const pairs = [
[`${base}/viz/shape/${shapeId}.svg`, "Shape SVG"],
[`${base}/data/${shapeId}.json`, "Raw JSON"],
[`${base}/viz/decode/${shapeId}.html`, "Decode"],
];
el.appendChild(document.createTextNode("View: "));
pairs.forEach(([href, label], i) => {
const a = document.createElement("a");
a.href = href;

Check failure

Code scanning / CodeQL

DOM text reinterpreted as HTML High

DOM text
is reinterpreted as HTML without escaping meta-characters.

Copilot Autofix

AI 9 months ago

In general, to fix “DOM text reinterpreted as HTML” findings, ensure that any data that originated as DOM text or user input is either: (a) encoded/escaped appropriately before being placed into HTML/URLs, or (b) strictly validated and normalized so only safe, expected forms are allowed. Avoid passing arbitrary untrusted strings directly into sensitive properties like href without such validation.

For this specific case, the best fix with minimal functional change is to tighten safeBase so that it never returns untrusted text verbatim. Instead, parse the input with URL, verify the protocol is http: or https:, and then reconstruct and return a canonical base URL string built from the parsed object (origin plus optional pathname), excluding any unexpected characters. For the “starts with /” case, interpret the value as a path on the current origin (or default localhost origin) and return a safe, normalized URL. This way, even if the user types something malicious into #base, the value that flows into href is constrained to a well-formed HTTP(S) URL under an expected origin, eliminating the taint and satisfying CodeQL.

Concretely: in pmoves/services/gateway/web/client.html, update the safeBase function (lines 38–46). Replace the current logic that returns the raw input with one that (1) attempts to parse raw as a URL, (2) if valid and http(s), returns u.origin + u.pathname.replace(/[^-A-Za-z0-9._~\/]/g, "") (or similar conservative filter), (3) if parsing fails but raw starts with /, builds a URL such as new URL(raw, "http://localhost:8000").toString(), and (4) otherwise falls back to "http://localhost:8000". This keeps the same conceptual behavior (“base URL for the server”) while ensuring only normalized, limited-character URLs are ever used as href. No new imports or external dependencies are required.

Suggested changeset 1
pmoves/services/gateway/web/client.html

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/pmoves/services/gateway/web/client.html b/pmoves/services/gateway/web/client.html
--- a/pmoves/services/gateway/web/client.html
+++ b/pmoves/services/gateway/web/client.html
@@ -38,9 +38,16 @@
 const safeBase = (raw) => {
   try {
     const u = new URL(raw);
-    if (u.protocol === "http:" || u.protocol === "https:") return raw;
+    if (u.protocol === "http:" || u.protocol === "https:") {
+      const safePath = u.pathname.replace(/[^-A-Za-z0-9._~\/]/g, "");
+      return u.origin + safePath;
+    }
   } catch (_) {
-    if (raw.startsWith("/")) return raw;
+    if (raw.startsWith("/")) {
+      const base = new URL("http://localhost:8000");
+      const safePath = raw.replace(/[^-A-Za-z0-9._~\/]/g, "");
+      return base.origin + safePath;
+    }
   }
   return "http://localhost:8000";
 };
EOF
@@ -38,9 +38,16 @@
const safeBase = (raw) => {
try {
const u = new URL(raw);
if (u.protocol === "http:" || u.protocol === "https:") return raw;
if (u.protocol === "http:" || u.protocol === "https:") {
const safePath = u.pathname.replace(/[^-A-Za-z0-9._~\/]/g, "");
return u.origin + safePath;
}
} catch (_) {
if (raw.startsWith("/")) return raw;
if (raw.startsWith("/")) {
const base = new URL("http://localhost:8000");
const safePath = raw.replace(/[^-A-Za-z0-9._~\/]/g, "");
return base.origin + safePath;
}
}
return "http://localhost:8000";
};
Copilot is powered by AI and may make mistakes. Always verify output.
a.target = "_blank";
a.rel = "noopener noreferrer";
a.textContent = label;
el.appendChild(a);
if (i < pairs.length - 1) el.appendChild(document.createTextNode(" \u00b7 "));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
});
};
const cloneCgp = cgp => {
if (typeof structuredClone === 'function') return structuredClone(cgp);
Expand Down
5 changes: 3 additions & 2 deletions pmoves/services/mcp_youtube_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -559,11 +559,12 @@ async def ingest_youtube_video(
# Extract video ID from URL
parsed = urlparse(url)
video_id = None
if "youtube.com" in parsed.netloc:
netloc = parsed.netloc.lower()
if netloc == "youtube.com" or netloc == "www.youtube.com" or netloc.endswith(".youtube.com"):
from urllib.parse import parse_qs
query_params = parse_qs(parsed.query)
video_id = query_params.get("v", [None])[0]
elif "youtu.be" in parsed.netloc:
elif netloc == "youtu.be" or netloc.endswith(".youtu.be"):
video_id = parsed.path.lstrip("/")

if not video_id:
Expand Down
8 changes: 7 additions & 1 deletion pmoves/services/pmoves-yt/yt.py
Original file line number Diff line number Diff line change
Expand Up @@ -1101,8 +1101,14 @@ def _infer_platform(url: Optional[str], entry_meta: Optional[Dict[str, Any]] = N
return value.strip().lower()
if url:
lowered = url.lower()
if "soundcloud.com" in lowered or lowered.startswith("soundcloud:"):
if lowered.startswith("soundcloud:"):
return "soundcloud"
try:
netloc = urlparse(lowered).netloc
if netloc == "soundcloud.com" or netloc.endswith(".soundcloud.com"):
return "soundcloud"
except Exception:
pass
return "youtube"

def _apply_provider_defaults(
Expand Down
Loading