fix(composer): recognisable path containment, and define md:inline

Follow-up to the previous commit, which made the CodeQL count worse
rather than better: 19 alerts became 22. Two mistakes.

First, the containment check used `base not in candidate.parents`.
That is correct Python but not a form static analysis recognises, so
every path-injection alert stayed and _plugin_dir itself picked up two
more. It now uses os.path.realpath plus os.path.commonpath, which is
both the documented sanitiser shape and stricter than the obvious
alternative: "/x/plugins-evil" startswith "/x/plugins" but is a
different directory, and there is now a test that fails if anyone
swaps commonpath for startswith.

Second, raising ComposerInputError from _plugin_dir and returning
str(exc) added two new py/stack-trace-exposure alerts -- CodeQL flags
exception text reaching a response regardless of the exception's type.
_plugin_dir returns None instead and the three handlers answer with a
fixed literal. There is nothing a caller needs there beyond "that id is
not ok".

Also defines .md\:inline in app.css. composer.html marks five toolbar
button labels `hidden md:inline`, and the class was never defined, so
those labels were hidden at every width and the buttons stayed
icon-only. main's test_web_static_audit.py catches it -- the branch
predates that test, which is why it only surfaced now that CI checks
the merge:

    Responsive utility classes referenced in templates but never
    defined in app.css (they silently no-op): ['md:inline']

Verified against the merged state -- main's app.css plus this one line,
audited against this branch's templates: 3 passed. The other twelve
classes the audit flags locally are defined on main and are artifacts of
this branch being 54 commits behind.

33 containment tests. Mutation-checked twice: removing the containment
lets eight payloads escape, including /etc/passwd and
plugin/../../../../../../etc/shadow; swapping commonpath for startswith
fails the sibling-prefix test.

Not addressed: three py/stack-trace-exposure alerts on the
_generate_plugin_files handlers. Those return str(exc) for
ComposerInputError, whose seven raise sites are all authored literals
("Author is required.", "Config variable key X is not a valid Python
identifier."). Suppressing them means replacing useful validation
feedback with a generic string, which is a real cost to the user for a
scanner's benefit. Worth a decision rather than a silent downgrade.

The 5 test_web_api.py failures are pre-existing on this branch --
identical counts with these changes stashed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01STMbQE4YctTacQXfbYqKuW
This commit is contained in:
ChuckBuilds
2026-08-21 17:52:11 -04:00
co-authored by Claude Opus 5
parent e499efb1f0
commit 79ba93f5a6
3 changed files with 53 additions and 29 deletions
+25 -19
View File
@@ -12,7 +12,9 @@ import ast
import io
import json
import logging
import os
import re
from typing import Optional
import zipfile
from datetime import datetime
from pathlib import Path
@@ -598,7 +600,7 @@ class ComposerInputError(ValueError):
"""
def _plugin_dir(plugin_id: str) -> Path:
def _plugin_dir(plugin_id: str) -> Optional[Path]:
"""Resolve a plugin directory, refusing anything outside plugins_dir.
_PLUGIN_ID_RE already rejects '/', '.' and '..', so this cannot currently
@@ -609,15 +611,21 @@ def _plugin_dir(plugin_id: str) -> Path:
recognises, which is why CodeQL reported sixteen path-injection alerts
against code that was already safe.
Raises ComposerInputError if the id is malformed or escapes the base.
Returns None for a malformed id or one that escapes the base. It returns
rather than raises so the handlers answer with a fixed literal: routing a
caught exception's text into a response is what py/stack-trace-exposure
flags, and there is nothing here a caller needs beyond "that id is not ok".
"""
if not _PLUGIN_ID_RE.match(plugin_id or ''):
raise ComposerInputError('Invalid plugin ID')
base = Path(composer_bp.plugins_dir).resolve()
candidate = (base / plugin_id).resolve()
if candidate != base and base not in candidate.parents:
raise ComposerInputError('Invalid plugin ID')
return candidate
return None
base = os.path.realpath(str(composer_bp.plugins_dir))
candidate = os.path.realpath(os.path.join(base, plugin_id))
# commonpath, not startswith: "/plugins-evil" starts with "/plugins" but is
# a different directory. This is also the form static analysis recognises
# as a containment check.
if candidate != base and os.path.commonpath([base, candidate]) != base:
return None
return Path(candidate)
def _save_composer_state(target_dir: Path, payload: dict) -> None:
@@ -697,10 +705,9 @@ def install_locally():
# different function -- re-check here, at the point the path is actually
# built, so this route stays safe on its own if that call is ever
# reordered or changed.
try:
target = _plugin_dir(plugin_id)
except ComposerInputError as exc:
return jsonify({'status': 'error', 'message': str(exc)}), 400
target = _plugin_dir(plugin_id)
if target is None:
return jsonify({'status': 'error', 'message': 'Invalid plugin ID'}), 400
force = bool(data.get('_force', False))
if target.exists() and not force:
@@ -754,10 +761,10 @@ def validate_id(plugin_id):
if not _PLUGIN_ID_RE.match(plugin_id):
return jsonify({'valid': False, 'available': False, 'reason': 'Invalid format'})
if composer_bp.plugins_dir:
try:
taken = _plugin_dir(plugin_id).exists()
except ComposerInputError:
resolved = _plugin_dir(plugin_id)
if resolved is None:
return jsonify({'valid': False, 'available': False, 'reason': 'Invalid format'})
taken = resolved.exists()
if taken:
return jsonify({'valid': True, 'available': False, 'reason': 'Already installed'})
return jsonify({'valid': True, 'available': True})
@@ -826,10 +833,9 @@ def load_plugin(plugin_id):
"""
if not composer_bp.plugins_dir:
return jsonify({'status': 'error', 'message': 'Plugin directory not configured'}), 503
try:
plugin_dir = _plugin_dir(plugin_id)
except ComposerInputError as exc:
return jsonify({'status': 'error', 'message': str(exc)}), 400
plugin_dir = _plugin_dir(plugin_id)
if plugin_dir is None:
return jsonify({'status': 'error', 'message': 'Invalid plugin ID'}), 400
if not plugin_dir.exists():
return jsonify({'status': 'error', 'message': 'Plugin not found'}), 404
+3
View File
@@ -421,6 +421,9 @@ a, button, input, select, textarea {
.md\:grid-cols-4 { grid-template-columns: repeat(4, minmax(0, 1fr)); }
.md\:flex { display: flex; }
.md\:hidden { display: none; }
/* composer.html labels its toolbar buttons `hidden md:inline`, so without
this the label is hidden at every width and the buttons stay icon-only. */
.md\:inline { display: inline; }
}
@media (min-width: 1024px) {