Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

fix(api): harden plugin manager OCI install path (H-3) (#121)

Beenu Aroraf550a65c8181
diff --git a/apps/docs/docs/deployment/env-vars.md b/apps/docs/docs/deployment/env-vars.md
index a68a59694..21d2a08b7 100644
--- a/apps/docs/docs/deployment/env-vars.md
+++ b/apps/docs/docs/deployment/env-vars.md
@@ -112,6 +112,8 @@ Source: [`services/api/app/auth/saml.py`](https://github.com/beenuar/AiSOC/blob/
| `MAX_TENANTS` | `1000` | Hard cap for multi-tenant deployments |
| `DEFAULT_TENANT_PLAN` | `starter` | Default plan for newly provisioned tenants |
| `AISOC_PLUGINS_DIR` | `/opt/aisoc/plugins` | Filesystem path the plugin loader scans |
+| `PLUGIN_TRUST_MODE` | `warn` | `disabled` skips signature checks, `warn` records `signature_status` but loads anyway, `strict` rejects unsigned/invalid plugins (including OCI installs). See [Operations → Security → OCI install hardening](../operations/security#oci-install-hardening-h-3). |
+| `PLUGIN_TRUSTED_KEYS_DIR` | `/etc/aisoc/plugin-keys` | Directory of Ed25519 public keys (`*.pem`/`*.pub`) that are allowed to sign plugins. |
| `AISOC_DEMO_MODE` | `false` | When `true`, mutating requests outside the demo tenant return 403 |
| `AISOC_DEMO_TENANT` | `demo` | Tenant slug allowed to write in demo mode |
| `AISOC_DEMO_BANNER` | `Demo data resets daily at 00:00 UTC. All write actions are disabled.` | Banner text rendered by the web app |
diff --git a/apps/docs/docs/operations/security.md b/apps/docs/docs/operations/security.md
index 2501a31fc..040b677e8 100644
--- a/apps/docs/docs/operations/security.md
+++ b/apps/docs/docs/operations/security.md
@@ -153,6 +153,27 @@ Verification entry point: `verify_ed25519_signature()` in `services/api/app/core
If you run private plugins (not from the public marketplace), the same flow applies — register the publisher's public key and AiSOC will refuse unsigned or tampered manifests.
+### OCI install hardening (H-3)
+
+Plugins can be installed from an OCI image via `oras pull` (`POST /api/v1/plugins/install/oci`). Because the install path writes arbitrary files into `AISOC_PLUGINS_DIR` and then imports them, it is wrapped with several non-negotiable checks. They live in `services/api/app/services/plugin_manager.py` and are exercised by the test suite at `services/api/tests/test_plugin_manager.py`.
+
+| Check | What it prevents |
+| --- | --- |
+| `_validate_oci_ref()` | Argv injection into `oras pull`. Refs must match `[A-Za-z0-9][A-Za-z0-9._:/@-]{0,254}`, must not start with `-`, and must not target the well-known cloud metadata hosts (`169.254.169.254`, `metadata.google.internal`, `metadata.azure.com`). |
+| `_validate_plugin_id()` | Path traversal and module shadowing. Plugin ids must match `[A-Za-z0-9][A-Za-z0-9._-]{1,63}` — no slashes, no `..`, no NULs. The same rule runs at `discover()` time so legacy on-disk ids that fail to validate are skipped with a loud log instead of silently loaded. |
+| `argv` ordering | `oras pull --output <tmpdir> -- <ref>` is constructed as a Python list (no shell). `--output` comes before `--` so flags are parsed before the ref; the ref is the sole positional. Both invariants are pinned by `test_oras_argv_uses_double_dash`. |
+| `_assert_no_symlinks()` | A hostile image cannot pack a symlink that points at `/etc/passwd`, the instance-metadata service, or another tenant's plugin dir. The whole extracted tree is rejected on the first symlink encountered. |
+| `_select_extracted_plugin_dir()` | The plugin root is chosen by looking for a manifest, not by sorting subdirectories. Multiple candidate dirs raise `PluginError`, so a tarball that packs a stray `docs/` next to the real plugin cannot accidentally install the wrong directory. |
+| Signature-before-copy | `_verify_plugin_signature()` runs against the temp dir *before* anything is copied into `AISOC_PLUGINS_DIR`. In `strict` mode an unsigned/tampered image is rejected and the temp dir is cleaned up — no malicious `plugin.py` ever lands somewhere the runtime would later import it. |
+| `_safe_copytree()` | Defence in depth: `shutil.copytree(..., symlinks=True)` so even if a symlink slipped past the check above it would be copied as a link, not followed. |
+
+Operator implications:
+
+- The `oras` CLI must be on `PATH`. The 120 s subprocess timeout is fixed and not currently tunable.
+- Plugin manifests with non-conforming ids (slashes, leading dots, > 64 chars) will fail to load after upgrading. Rename the id in `plugin.yaml` and reinstall.
+- If you have a private registry that is reachable only by IP and that IP happens to be one of the forbidden metadata hosts, use a DNS name instead. There is no per-deployment override for the deny list — it's small on purpose.
+- The signature trust mode is still controlled by `PLUGIN_TRUST_MODE` (`disabled` | `warn` | `strict`) and `PLUGIN_TRUSTED_KEYS_DIR`. In `strict` mode an OCI install with no signature or a bad signature is rejected before the copy step.
+
## Network and transport
AiSOC is HTTP-first. The expected production deployment terminates TLS at an ingress (nginx, Envoy, ALB, Cloud Run, …) and forwards plaintext to the API service over a private network. The API trusts `X-Forwarded-For` and `X-Forwarded-Proto` for IP attribution and HTTPS-redirect logic; configure your ingress to strip and replace those headers from external traffic.
diff --git a/services/api/app/services/plugin_manager.py b/services/api/app/services/plugin_manager.py
index 36a2e62af..cbdd9721a 100644
--- a/services/api/app/services/plugin_manager.py
+++ b/services/api/app/services/plugin_manager.py
@@ -45,6 +45,8 @@ import importlib.util
import inspect
import json
import os
+import re
+import shutil
import subprocess
import sys
import tempfile
@@ -81,6 +83,147 @@ TRUST_MODE_WARN = "warn"
TRUST_MODE_DISABLED = "disabled"
_VALID_TRUST_MODES = {TRUST_MODE_STRICT, TRUST_MODE_WARN, TRUST_MODE_DISABLED}
+# ── Hardening primitives (H-3) ────────────────────────────────────────────────
+#
+# Plugin IDs end up as path components beneath ``PLUGINS_DIR`` and as Python
+# module names; OCI references end up as argv to a CLI process. We constrain
+# both to safe, well-known shapes so a hostile manifest or operator-supplied
+# reference cannot pivot into path traversal, argv injection, or namespace
+# collisions with real Python packages.
+
+# Plugin id: lowercase alphanumerics + ``.``/``-``/``_``, must start with an
+# alphanumeric, 2–64 chars. This rules out ``..``, ``../escape``, absolute
+# paths, NULs, slashes, whitespace, and shell metacharacters. The regex is
+# intentionally narrower than what some manifests historically accepted —
+# new plugins MUST conform; ``discover()`` swallows the resulting
+# ``PluginError`` for legacy ids, so the user-visible impact is the
+# offending plugin being skipped with a loud log.
+_PLUGIN_ID_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9._-]{1,63}$")
+
+# OCI reference: ``host[:port]/repo[:tag][@digest]`` with the usual character
+# set. We additionally forbid a leading ``-`` (which would be parsed as a
+# flag by ``oras``), whitespace, NULs, and shell metacharacters. The exact
+# OCI grammar is broader than this but every valid reference in the wild
+# satisfies the constraints below.
+_OCI_REF_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/@-]{0,254}$")
+
+# Cloud-metadata-style hosts that must never end up as the registry, even
+# if the regex above accepts them syntactically. ``install_from_oci`` is
+# operator-driven so this is mostly belt-and-braces, but plugins are
+# privileged enough that we keep the list.
+_OCI_FORBIDDEN_HOST_SUBSTRINGS = (
+ "169.254.169.254",
+ "metadata.google.internal",
+ "metadata.azure.com",
+)
+
+
+def _validate_plugin_id(plugin_id: str) -> str:
+ """Return ``plugin_id`` if it is a safe path/module component.
+
+ Raises ``PluginError`` otherwise. Plugin ids are user-controlled via
+ manifests, so this is the canonical chokepoint before they touch the
+ filesystem or ``importlib``.
+ """
+ if not isinstance(plugin_id, str) or not _PLUGIN_ID_RE.match(plugin_id):
+ raise PluginError(
+ str(plugin_id),
+ "invalid plugin id; must match [A-Za-z0-9][A-Za-z0-9._-]{1,63}",
+ )
+ # Extra hardening: even if the regex says yes, paranoid path-component
+ # checks make path-traversal impossible.
+ if plugin_id in {".", ".."} or "/" in plugin_id or "\\" in plugin_id or "\x00" in plugin_id:
+ raise PluginError(plugin_id, "invalid plugin id; path separators or NUL not allowed")
+ return plugin_id
+
+
+def _validate_oci_ref(oci_ref: str) -> str:
+ """Return ``oci_ref`` if it is safe to pass as argv to ``oras pull``.
+
+ Rejects empty refs, leading ``-`` (flag injection), whitespace, NULs,
+ shell metacharacters, and the well-known metadata-service hosts that
+ have no business being a plugin registry.
+ """
+ if not isinstance(oci_ref, str) or not oci_ref:
+ raise PluginError("oci", "oci_ref must be a non-empty string")
+ if oci_ref.startswith("-"):
+ raise PluginError(oci_ref, "oci_ref must not start with '-' (argv injection guard)")
+ if not _OCI_REF_RE.match(oci_ref):
+ raise PluginError(
+ oci_ref,
+ "oci_ref contains characters that are not allowed; expected host[:port]/repo[:tag][@digest]",
+ )
+ lowered = oci_ref.lower()
+ if any(bad in lowered for bad in _OCI_FORBIDDEN_HOST_SUBSTRINGS):
+ raise PluginError(oci_ref, "oci_ref host is on the forbidden metadata-service deny list")
+ return oci_ref
+
+
+def _assert_no_symlinks(root: Path) -> None:
+ """Raise ``PluginError`` if ``root`` contains *any* symbolic link.
+
+ OCI layers can legally pack symlinks; for plugin payloads we treat any
+ symlink as hostile because they can point at ``/etc/passwd``, the
+ instance-metadata service over a network share, the ``PLUGINS_DIR``
+ of another tenant, or back into the temp dir to create a loop. The
+ plugin contract is "ordinary files only".
+ """
+ if root.is_symlink():
+ raise PluginError(root.name, f"refusing to ingest symlink: {root}")
+ for entry in root.rglob("*"):
+ if entry.is_symlink():
+ raise PluginError(
+ root.name,
+ f"plugin payload contains a symlink and is rejected: {entry.relative_to(root)}",
+ )
+
+
+def _safe_copytree(src: Path, dest: Path) -> None:
+ """Copy ``src`` to ``dest`` without following symlinks.
+
+ Callers must run :func:`_assert_no_symlinks` first; this helper is the
+ second line of defence in case the validation/copy steps ever drift
+ out of order.
+ """
+ shutil.copytree(src, dest, symlinks=True)
+
+
+def _select_extracted_plugin_dir(tmp_path: Path) -> Path:
+ """Pick the plugin root from a freshly-pulled OCI tree.
+
+ The historical behaviour of just ``subdirs[0]`` was order-dependent and
+ could silently install whichever directory happened to sort first when
+ a tarball packed multiple top-level dirs (e.g. a stray ``docs/``). We
+ instead prefer a subdir that actually contains a manifest, fall back to
+ the temp dir itself for flat pulls, and refuse to pick when more than
+ one candidate looks plugin-shaped.
+ """
+ if (tmp_path / _MANIFEST_YAML).exists() or (tmp_path / _MANIFEST_JSON).exists():
+ return tmp_path
+
+ subdirs = sorted(d for d in tmp_path.iterdir() if d.is_dir())
+ if not subdirs:
+ return tmp_path
+
+ candidates = [d for d in subdirs if (d / _MANIFEST_YAML).exists() or (d / _MANIFEST_JSON).exists()]
+ if len(candidates) == 1:
+ return candidates[0]
+ if len(candidates) > 1:
+ names = ", ".join(c.name for c in candidates)
+ raise PluginError(
+ "oci",
+ f"OCI image contains multiple plugin directories ({names}); expected exactly one",
+ )
+
+ # No manifest in any subdir — fall back to the single-subdir behaviour
+ # for legacy images, but only if there is exactly one candidate.
+ if len(subdirs) == 1:
+ return subdirs[0]
+ raise PluginError(
+ "oci",
+ "OCI image contains multiple top-level directories but no manifest; unable to pick plugin root",
+ )
+
# ── Manifest model ────────────────────────────────────────────────────────────
@@ -391,6 +534,11 @@ class PluginManager:
if missing:
raise PluginError(plugin_dir.name, f"manifest missing fields: {missing}")
+ # Plugin ids end up as path components and synthesized module names.
+ # Reject anything that would let a hostile manifest pivot via
+ # ``../`` or shell metacharacters before we touch the filesystem.
+ _validate_plugin_id(str(raw["id"]))
+
if raw["plugin_type"] not in VALID_PLUGIN_TYPES:
raise PluginError(
raw.get("id", plugin_dir.name),
@@ -471,32 +619,60 @@ class PluginManager:
async def install_from_oci(self, oci_ref: str, plugin_id_hint: str | None = None) -> str:
"""
- Pull a plugin OCI image using the `oras` CLI and install it into PLUGINS_DIR.
+ Pull a plugin OCI image using the ``oras`` CLI and install it into PLUGINS_DIR.
The OCI image must contain a single layer whose media type is
``application/vnd.aisoc.plugin.v1+tar`` or any tar/gzip layer.
The extracted directory must contain a valid plugin manifest.
- Prerequisites: `oras` CLI must be installed and on PATH.
+ Hardening (H-3):
+
+ * ``oci_ref`` and any caller-supplied ``plugin_id_hint`` are validated
+ before they reach ``argv`` so a hostile reference cannot inject a
+ flag (e.g. ``--config /etc/passwd``) or run a different binary.
+ * The freshly extracted tree is scanned for symbolic links; if any
+ are present the install is rejected outright. OCI tarballs can
+ legally pack symlinks but a plugin payload that does is treated
+ as adversarial — they trivially break out of ``PLUGINS_DIR``.
+ * Signature verification runs against the *temp* directory before
+ anything is copied into ``PLUGINS_DIR``. An attacker who can publish
+ an image but not the signing key never gets to write malicious
+ ``plugin.py`` to a place the runtime will later import.
+ * The final copy uses ``copytree`` with ``symlinks=True`` so links are
+ preserved as links rather than followed (defence in depth — the
+ symlink check above should have already failed the install).
+
+ Prerequisites: ``oras`` CLI must be installed and on PATH.
Install: https://oras.land/docs/installation
Returns the plugin_id after successful installation.
"""
+ # 1) Input validation — argv hygiene before any subprocess work.
+ _validate_oci_ref(oci_ref)
+ if plugin_id_hint is not None:
+ _validate_plugin_id(plugin_id_hint)
+
self._plugins_dir.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="aisoc-oci-") as tmp:
tmp_path = Path(tmp)
logger.info("pulling OCI image", ref=oci_ref, tmp=str(tmp_path))
- # oras pull into tmp directory
+ # 2) Pull. We pass argv as a list (no shell). The ref has already
+ # been regex-validated, so a hostile ref cannot inject flags;
+ # ``--`` is defence-in-depth and MUST come after the ``--output``
+ # flag so oras parses ``--output`` as a flag and the ref as the
+ # sole positional argument. Swapping the order silently breaks
+ # ``oras pull`` at runtime ("unexpected positional argument").
try:
proc = await asyncio.get_event_loop().run_in_executor(
None,
lambda: subprocess.run(
- ["oras", "pull", oci_ref, "--output", str(tmp_path)],
+ ["oras", "pull", "--output", str(tmp_path), "--", oci_ref],
capture_output=True,
text=True,
timeout=120,
+ check=False,
),
)
except FileNotFoundError as exc:
@@ -510,30 +686,50 @@ class PluginManager:
if proc.returncode != 0:
raise PluginError(oci_ref, f"oras pull failed: {proc.stderr.strip()}")
- # Determine extracted plugin directory
- subdirs = [d for d in tmp_path.iterdir() if d.is_dir()]
- if not subdirs:
- # Flat pull — treat tmp itself as the plugin directory
- extracted = tmp_path
- else:
- extracted = subdirs[0]
+ # 3) Reject symlinks at the temp-dir level before we even read
+ # the manifest. A hostile ``plugin.yaml`` could be a symlink
+ # into ``/etc`` and we don't want ``_read_manifest`` reading
+ # arbitrary files.
+ _assert_no_symlinks(tmp_path)
- # Read manifest to get the canonical id
+ # 4) Find the extracted plugin directory. Prefer a subdir that
+ # actually contains a manifest; fall back to the temp dir
+ # itself for "flat" pulls.
+ extracted = _select_extracted_plugin_dir(tmp_path)
+
+ # 5) Read manifest and bind the canonical plugin_id. The id
+ # must satisfy the same shape rules as discovered plugins
+ # so it cannot escape ``PLUGINS_DIR`` or shadow another id.
raw = _read_manifest(extracted)
- plugin_id = raw.get("id") or plugin_id_hint or extracted.name
+ plugin_id = str(raw.get("id") or plugin_id_hint or extracted.name)
+ _validate_plugin_id(plugin_id)
+ if plugin_id_hint is not None and raw.get("id") and raw["id"] != plugin_id_hint:
+ raise PluginError(
+ plugin_id,
+ f"manifest id '{raw['id']}' does not match plugin_id_hint '{plugin_id_hint}'",
+ )
+ # 6) Verify the signature against the *temp* directory, BEFORE
+ # we copy anything into PLUGINS_DIR. In ``strict`` mode this
+ # raises and the temp dir is cleaned up by the context
+ # manager — nothing malicious ever lands on disk inside the
+ # plugins root.
+ trust_mode, trusted_keys = self._trust_config()
+ _verify_plugin_signature(extracted, raw, trust_mode, trusted_keys)
+
+ # 7) Atomically install into PLUGINS_DIR. We use ``symlinks=True``
+ # so links would be preserved-as-links rather than followed,
+ # but ``_assert_no_symlinks`` above should already have made
+ # that path unreachable.
dest = self._plugins_dir / plugin_id
if dest.exists():
- import shutil
-
shutil.rmtree(dest)
-
- import shutil
-
- shutil.copytree(extracted, dest)
+ _safe_copytree(extracted, dest)
logger.info("OCI plugin extracted", ref=oci_ref, dest=str(dest))
- # Load the freshly extracted plugin
+ # 8) Load the freshly extracted plugin. ``_load_plugin`` re-runs the
+ # signature gate against the final location, which is what
+ # ``LoadedPlugin.signature_status`` ultimately reflects.
loaded_id = await self._load_plugin(dest)
logger.info("OCI plugin installed and loaded", plugin_id=loaded_id, ref=oci_ref)
return loaded_id
diff --git a/services/api/tests/test_plugin_manager.py b/services/api/tests/test_plugin_manager.py
index ae7d8ae66..e45371796 100644
--- a/services/api/tests/test_plugin_manager.py
+++ b/services/api/tests/test_plugin_manager.py
@@ -636,3 +636,594 @@ class TestPluginSignatureGate:
(d / "plugin.py").write_text("class Plugin:\n POISONED = True\n")
after = _canonical_plugin_digest(d, raw)
assert before != after
+
+
+# ── H-3 hardening primitives ──────────────────────────────────────────────────
+#
+# These tests cover the OCI / supply-chain hardening helpers added in
+# Batch 6. They are pure-Python unit tests; no network or ``oras`` CLI
+# is touched.
+
+
+class TestValidatePluginId:
+ """``_validate_plugin_id`` is the chokepoint between manifest data and
+ the filesystem / ``importlib``. Anything it accepts may later become a
+ path component or module name, so the bar is "regex-narrow"."""
+
+ @pytest.mark.parametrize(
+ "good",
+ [
+ "foo",
+ "foo.bar",
+ "foo-bar",
+ "foo_bar",
+ "Foo.Bar-baz_v2",
+ "a1.b2.c3",
+ "x" * 64, # exactly the documented max length
+ ],
+ )
+ def test_accepts_well_formed_ids(self, good):
+ from app.services.plugin_manager import _validate_plugin_id # noqa: PLC0415
+
+ assert _validate_plugin_id(good) == good
+
+ @pytest.mark.parametrize(
+ "bad",
+ [
+ "",
+ ".",
+ "..",
+ "../escape",
+ "foo/bar",
+ "foo\\bar",
+ "foo bar",
+ "foo\x00bar",
+ "-foo", # must start with alnum
+ "_foo", # must start with alnum
+ ".foo", # must start with alnum
+ "x" * 65, # one over the cap
+ ],
+ )
+ def test_rejects_unsafe_ids(self, bad):
+ from app.services.plugin_manager import PluginError, _validate_plugin_id # noqa: PLC0415
+
+ with pytest.raises(PluginError):
+ _validate_plugin_id(bad)
+
+ def test_rejects_non_string(self):
+ from app.services.plugin_manager import PluginError, _validate_plugin_id # noqa: PLC0415
+
+ with pytest.raises(PluginError):
+ _validate_plugin_id(None) # type: ignore[arg-type]
+ with pytest.raises(PluginError):
+ _validate_plugin_id(42) # type: ignore[arg-type]
+
+
+class TestValidateOciRef:
+ """``_validate_oci_ref`` is the argv-injection guard for ``oras pull``."""
+
+ @pytest.mark.parametrize(
+ "good",
+ [
+ "ghcr.io/owner/plugin:v1",
+ "registry.example.com:5000/team/plugin:1.2.3",
+ "ghcr.io/owner/plugin@sha256:abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890",
+ "r/p",
+ ],
+ )
+ def test_accepts_well_formed_refs(self, good):
+ from app.services.plugin_manager import _validate_oci_ref # noqa: PLC0415
+
+ assert _validate_oci_ref(good) == good
+
+ @pytest.mark.parametrize(
+ "bad",
+ [
+ "",
+ "-rf", # would be parsed as an oras flag
+ "--config=/etc/passwd",
+ "ghcr.io/owner/p v1", # whitespace
+ "ghcr.io/owner/p;ls", # shell metacharacter
+ "ghcr.io/owner/p|cat",
+ "ghcr.io/owner/p`id`",
+ "ghcr.io/owner/p$(id)",
+ "ghcr.io/owner/p\x00null",
+ "ghcr.io/owner/p\nfoo",
+ "a" * 256, # one over the 255-char cap
+ ],
+ )
+ def test_rejects_unsafe_refs(self, bad):
+ from app.services.plugin_manager import PluginError, _validate_oci_ref # noqa: PLC0415
+
+ with pytest.raises(PluginError):
+ _validate_oci_ref(bad)
+
+ @pytest.mark.parametrize(
+ "metadata_host",
+ [
+ "169.254.169.254/owner/plugin:v1",
+ "metadata.google.internal/team/plugin:v1",
+ "Metadata.Google.Internal/team/plugin:v1", # case-insensitive
+ "metadata.azure.com/team/plugin:v1",
+ ],
+ )
+ def test_rejects_metadata_service_hosts(self, metadata_host):
+ from app.services.plugin_manager import PluginError, _validate_oci_ref # noqa: PLC0415
+
+ with pytest.raises(PluginError, match="metadata-service deny list"):
+ _validate_oci_ref(metadata_host)
+
+ def test_rejects_non_string(self):
+ from app.services.plugin_manager import PluginError, _validate_oci_ref # noqa: PLC0415
+
+ with pytest.raises(PluginError):
+ _validate_oci_ref(None) # type: ignore[arg-type]
+
+
+class TestAssertNoSymlinks:
+ """Plugin payloads are "ordinary files only" — symlinks anywhere in the
+ extracted tree must be rejected before the loader touches them."""
+
+ def test_passes_on_clean_tree(self, tmp_path):
+ from app.services.plugin_manager import _assert_no_symlinks # noqa: PLC0415
+
+ (tmp_path / "aisoc-plugin.json").write_text("{}")
+ sub = tmp_path / "sub"
+ sub.mkdir()
+ (sub / "plugin.py").write_text("class Plugin: pass\n")
+
+ # Must not raise.
+ _assert_no_symlinks(tmp_path)
+
+ def test_rejects_symlink_at_root_level(self, tmp_path):
+ from app.services.plugin_manager import PluginError, _assert_no_symlinks # noqa: PLC0415
+
+ target = tmp_path / "real.txt"
+ target.write_text("hello")
+ (tmp_path / "link.txt").symlink_to(target)
+
+ with pytest.raises(PluginError, match="symlink"):
+ _assert_no_symlinks(tmp_path)
+
+ def test_rejects_symlink_nested_deep(self, tmp_path):
+ from app.services.plugin_manager import PluginError, _assert_no_symlinks # noqa: PLC0415
+
+ deep = tmp_path / "a" / "b" / "c"
+ deep.mkdir(parents=True)
+ target = tmp_path / "outside.txt"
+ target.write_text("x")
+ (deep / "evil").symlink_to(target)
+
+ with pytest.raises(PluginError, match="symlink"):
+ _assert_no_symlinks(tmp_path)
+
+ def test_rejects_when_root_itself_is_a_symlink(self, tmp_path):
+ from app.services.plugin_manager import PluginError, _assert_no_symlinks # noqa: PLC0415
+
+ real_dir = tmp_path / "real"
+ real_dir.mkdir()
+ link_root = tmp_path / "link_root"
+ link_root.symlink_to(real_dir, target_is_directory=True)
+
+ with pytest.raises(PluginError, match="symlink"):
+ _assert_no_symlinks(link_root)
+
+ def test_rejects_dangling_symlink(self, tmp_path):
+ """A symlink pointing at a non-existent target is still hostile —
+ the rejection must not depend on the target being readable."""
+ from app.services.plugin_manager import PluginError, _assert_no_symlinks # noqa: PLC0415
+
+ (tmp_path / "dangling").symlink_to(tmp_path / "does-not-exist")
+
+ with pytest.raises(PluginError, match="symlink"):
+ _assert_no_symlinks(tmp_path)
+
+
+class TestSelectExtractedPluginDir:
+ """``_select_extracted_plugin_dir`` picks the plugin root from a freshly-
+ pulled OCI tree. The selection rule must be deterministic and refuse
+ ambiguous layouts so we never silently install the wrong directory."""
+
+ def test_flat_layout_with_yaml_manifest(self, tmp_path):
+ from app.services.plugin_manager import _select_extracted_plugin_dir # noqa: PLC0415
+
+ (tmp_path / "plugin.yaml").write_text("id: x\n")
+ assert _select_extracted_plugin_dir(tmp_path) == tmp_path
+
+ def test_flat_layout_with_json_manifest(self, tmp_path):
+ from app.services.plugin_manager import _select_extracted_plugin_dir # noqa: PLC0415
+
+ (tmp_path / "aisoc-plugin.json").write_text("{}")
+ assert _select_extracted_plugin_dir(tmp_path) == tmp_path
+
+ def test_single_subdir_with_manifest_is_picked(self, tmp_path):
+ from app.services.plugin_manager import _select_extracted_plugin_dir # noqa: PLC0415
+
+ plugin = tmp_path / "real-plugin"
+ plugin.mkdir()
+ (plugin / "aisoc-plugin.json").write_text("{}")
+ # A sibling "docs" dir that historically would have been order-
+ # dependent ("d" sorts before "r"): the selector must skip it.
+ docs = tmp_path / "docs"
+ docs.mkdir()
+ (docs / "README.md").write_text("readme")
+
+ assert _select_extracted_plugin_dir(tmp_path) == plugin
+
+ def test_multiple_subdirs_with_manifests_raises(self, tmp_path):
+ from app.services.plugin_manager import PluginError, _select_extracted_plugin_dir # noqa: PLC0415
+
+ for name in ("first", "second"):
+ d = tmp_path / name
+ d.mkdir()
+ (d / "aisoc-plugin.json").write_text("{}")
+
+ with pytest.raises(PluginError, match="multiple plugin directories"):
+ _select_extracted_plugin_dir(tmp_path)
+
+ def test_legacy_single_subdir_without_manifest_is_picked(self, tmp_path):
+ from app.services.plugin_manager import _select_extracted_plugin_dir # noqa: PLC0415
+
+ legacy = tmp_path / "legacy"
+ legacy.mkdir()
+ (legacy / "plugin.py").write_text("class Plugin: pass\n")
+
+ assert _select_extracted_plugin_dir(tmp_path) == legacy
+
+ def test_multiple_subdirs_without_manifest_raises(self, tmp_path):
+ from app.services.plugin_manager import PluginError, _select_extracted_plugin_dir # noqa: PLC0415
+
+ for name in ("a", "b"):
+ (tmp_path / name).mkdir()
+
+ with pytest.raises(PluginError, match="unable to pick plugin root"):
+ _select_extracted_plugin_dir(tmp_path)
+
+ def test_empty_dir_returns_itself(self, tmp_path):
+ """If oras delivers nothing useful, the downstream manifest read
+ will fail with a clear PluginError — the selector should not raise
+ on an empty dir."""
+ from app.services.plugin_manager import _select_extracted_plugin_dir # noqa: PLC0415
+
+ assert _select_extracted_plugin_dir(tmp_path) == tmp_path
+
+
+class TestSafeCopytree:
+ """``_safe_copytree`` is defence-in-depth for the symlink guard. It must
+ preserve symlinks as links rather than following them, so even if
+ ``_assert_no_symlinks`` is ever bypassed the link target is not read."""
+
+ def test_copies_ordinary_files(self, tmp_path):
+ from app.services.plugin_manager import _safe_copytree # noqa: PLC0415
+
+ src = tmp_path / "src"
+ src.mkdir()
+ (src / "plugin.py").write_text("class Plugin: pass\n")
+ (src / "aisoc-plugin.json").write_text('{"id": "x"}')
+ sub = src / "sub"
+ sub.mkdir()
+ (sub / "more.py").write_text("# more\n")
+
+ dest = tmp_path / "dest"
+ _safe_copytree(src, dest)
+
+ assert (dest / "plugin.py").read_text() == "class Plugin: pass\n"
+ assert (dest / "aisoc-plugin.json").read_text() == '{"id": "x"}'
+ assert (dest / "sub" / "more.py").read_text() == "# more\n"
+
+ def test_preserves_symlinks_as_links(self, tmp_path):
+ from app.services.plugin_manager import _safe_copytree # noqa: PLC0415
+
+ src = tmp_path / "src"
+ src.mkdir()
+ secret = tmp_path / "secret.txt"
+ secret.write_text("DO NOT READ")
+ (src / "evil").symlink_to(secret)
+
+ dest = tmp_path / "dest"
+ _safe_copytree(src, dest)
+
+ # The link is preserved AS A LINK; copytree did not follow it and
+ # write the secret content into the destination.
+ assert (dest / "evil").is_symlink()
+
+
+# ── install_from_oci hardening integration tests ──────────────────────────────
+#
+# These tests mock the ``oras pull`` subprocess and the trusted-keys reader so
+# the whole install pipeline runs against a controlled temp-dir layout. They
+# verify the layered defences (argv validation → pull → symlink check →
+# directory selection → manifest read → id validation → signature gate →
+# atomic copy) all engage in the right order.
+
+
+def _fake_oras(populate=None, *, returncode: int = 0, stderr: str = ""):
+ """Return a fake ``subprocess.run`` that recognises our oras argv and
+ optionally populates the tmp dir with a real plugin payload.
+
+ ``populate`` is a callable ``(tmp_path: Path) -> None``. The argv layout
+ is the one used by ``install_from_oci``:
+
+ ["oras", "pull", "--", <ref>, "--output", <tmp_path>]
+ """
+ from types import SimpleNamespace # noqa: PLC0415
+
+ calls: list[list[str]] = []
+
+ def _runner(argv, **_kwargs):
+ calls.append(list(argv))
+ if returncode == 0 and populate is not None:
+ # Find the value passed to --output; argv layout is stable.
+ out_idx = argv.index("--output") + 1
+ populate(Path(argv[out_idx]))
+ return SimpleNamespace(returncode=returncode, stdout="", stderr=stderr)
+
+ _runner.calls = calls # type: ignore[attr-defined]
+ return _runner
+
+
+def _stub_oras_pull(monkeypatch, fake):
+ """Replace ``subprocess.run`` *inside* the plugin_manager module so
+ ``install_from_oci`` exercises our fake without touching the real CLI."""
+ import app.services.plugin_manager as pm # noqa: PLC0415
+
+ monkeypatch.setattr(pm.subprocess, "run", fake)
+
+
+class TestInstallFromOciHardening:
+ """Defensive behaviours added in Batch 6 (H-3)."""
+
+ @pytest.mark.asyncio
+ async def test_rejects_flag_injection_before_subprocess(self, tmp_path, monkeypatch):
+ """A ref that starts with ``-`` is rejected before ``oras`` runs;
+ the subprocess must not be invoked at all."""
+ from app.services.plugin_manager import PluginError, PluginManager # noqa: PLC0415
+
+ fake = _fake_oras() # would raise if accidentally invoked
+ _stub_oras_pull(monkeypatch, fake)
+
+ mgr = PluginManager(plugins_dir=tmp_path / "plugins")
+ with pytest.raises(PluginError, match="argv injection guard"):
+ await mgr.install_from_oci("--config=/etc/passwd")
+ assert fake.calls == [] # type: ignore[attr-defined]
+
+ @pytest.mark.asyncio
+ async def test_rejects_bad_plugin_id_hint_before_subprocess(self, tmp_path, monkeypatch):
+ from app.services.plugin_manager import PluginError, PluginManager # noqa: PLC0415
+
+ fake = _fake_oras()
+ _stub_oras_pull(monkeypatch, fake)
+
+ mgr = PluginManager(plugins_dir=tmp_path / "plugins")
+ with pytest.raises(PluginError, match="invalid plugin id"):
+ await mgr.install_from_oci("ghcr.io/owner/plugin:v1", plugin_id_hint="../escape")
+ assert fake.calls == [] # type: ignore[attr-defined]
+
+ @pytest.mark.asyncio
+ async def test_rejects_metadata_host_before_subprocess(self, tmp_path, monkeypatch):
+ from app.services.plugin_manager import PluginError, PluginManager # noqa: PLC0415
+
+ fake = _fake_oras()
+ _stub_oras_pull(monkeypatch, fake)
+
+ mgr = PluginManager(plugins_dir=tmp_path / "plugins")
+ with pytest.raises(PluginError, match="metadata-service deny list"):
+ await mgr.install_from_oci("169.254.169.254/owner/plugin:v1")
+ assert fake.calls == [] # type: ignore[attr-defined]
+
+ @pytest.mark.asyncio
+ async def test_oras_nonzero_exit_raises_and_installs_nothing(self, tmp_path, monkeypatch):
+ from app.services.plugin_manager import PluginError, PluginManager # noqa: PLC0415
+
+ fake = _fake_oras(returncode=1, stderr="unauthorized: pull access denied")
+ _stub_oras_pull(monkeypatch, fake)
+
+ plugins_dir = tmp_path / "plugins"
+ mgr = PluginManager(plugins_dir=plugins_dir)
+ with pytest.raises(PluginError, match="oras pull failed"):
+ await mgr.install_from_oci("ghcr.io/owner/plugin:v1")
+
+ assert not plugins_dir.exists() or list(plugins_dir.iterdir()) == []
+
+ @pytest.mark.asyncio
+ async def test_oras_argv_uses_double_dash(self, tmp_path, monkeypatch):
+ """``oras pull`` argv must be flag-safe AND functionally correct.
+
+ Two invariants together prevent ``argv`` injection without breaking
+ the underlying ``oras pull`` invocation:
+ 1. argv is built from a Python list (no shell).
+ 2. ``--output <dir>`` is parsed as a flag pair, then ``--`` ends
+ flag parsing, then the ref is the sole positional. If a future
+ maintainer flips the order and puts ``--`` before ``--output``,
+ ``oras`` would treat ``--output`` as a positional and the pull
+ would fail at runtime — so this test pins the order.
+ """
+ from app.services.plugin_manager import PluginManager # noqa: PLC0415
+
+ def populate(tp: Path) -> None:
+ _write_plugin(tp, "argv-shape")
+
+ fake = _fake_oras(populate)
+ _stub_oras_pull(monkeypatch, fake)
+
+ mgr = PluginManager(plugins_dir=tmp_path / "plugins")
+ await mgr.install_from_oci("ghcr.io/owner/plugin:v1", plugin_id_hint="test.argv-shape")
+
+ assert len(fake.calls) == 1 # type: ignore[attr-defined]
+ argv = fake.calls[0] # type: ignore[attr-defined]
+ assert argv[0] == "oras"
+ assert argv[1] == "pull"
+ assert "--output" in argv and "--" in argv
+ out_idx = argv.index("--output")
+ sep_idx = argv.index("--")
+ # --output / <path> come before --, so they are parsed as a flag pair.
+ assert out_idx < sep_idx
+ # The ref must be the sole positional, immediately after --.
+ assert argv[sep_idx + 1] == "ghcr.io/owner/plugin:v1"
+ assert sep_idx + 2 == len(argv), "ref must be the only positional"
+
+ @pytest.mark.asyncio
+ async def test_rejects_symlink_in_extracted_tree(self, tmp_path, monkeypatch):
+ """A hostile OCI image that packs a symlink must be rejected and
+ nothing must land in PLUGINS_DIR."""
+ from app.services.plugin_manager import PluginError, PluginManager # noqa: PLC0415
+
+ def populate_with_symlink(tp: Path) -> None:
+ _write_plugin(tp, "bad-plugin")
+ # Drop a symlink anywhere in the tree.
+ target = tp / "bad-plugin" / "real.txt"
+ target.write_text("ok")
+ (tp / "bad-plugin" / "evil").symlink_to(target)
+
+ fake = _fake_oras(populate_with_symlink)
+ _stub_oras_pull(monkeypatch, fake)
+
+ plugins_dir = tmp_path / "plugins"
+ mgr = PluginManager(plugins_dir=plugins_dir)
+ with pytest.raises(PluginError, match="symlink"):
+ await mgr.install_from_oci("ghcr.io/owner/plugin:v1")
+
+ assert not plugins_dir.exists() or list(plugins_dir.iterdir()) == []
+
+ @pytest.mark.asyncio
+ async def test_rejects_manifest_id_hint_mismatch(self, tmp_path, monkeypatch):
+ from app.services.plugin_manager import PluginError, PluginManager # noqa: PLC0415
+
+ def populate(tp: Path) -> None:
+ _write_plugin(tp, "real-id")
+
+ fake = _fake_oras(populate)
+ _stub_oras_pull(monkeypatch, fake)
+
+ plugins_dir = tmp_path / "plugins"
+ mgr = PluginManager(plugins_dir=plugins_dir)
+ with pytest.raises(PluginError, match="does not match plugin_id_hint"):
+ await mgr.install_from_oci("ghcr.io/owner/plugin:v1", plugin_id_hint="test.wrong-id")
+
+ # Mismatch fails AFTER pull but BEFORE copy.
+ assert not plugins_dir.exists() or list(plugins_dir.iterdir()) == []
+
+ @pytest.mark.asyncio
+ async def test_rejects_manifest_id_that_fails_validation(self, tmp_path, monkeypatch):
+ """A hostile manifest with ``id: "../escape"`` must be rejected
+ before any path is built from it."""
+ from app.services.plugin_manager import PluginError, PluginManager # noqa: PLC0415
+
+ def populate(tp: Path) -> None:
+ d = tp / "evil-plugin"
+ d.mkdir()
+ (d / "aisoc-plugin.json").write_text(
+ json.dumps(
+ {
+ "id": "../escape",
+ "name": "evil",
+ "version": "1.0.0",
+ "plugin_type": "enricher",
+ }
+ )
+ )
+ (d / "plugin.py").write_text("class Plugin: pass\n")
+
+ fake = _fake_oras(populate)
+ _stub_oras_pull(monkeypatch, fake)
+
+ plugins_dir = tmp_path / "plugins"
+ mgr = PluginManager(plugins_dir=plugins_dir)
+ with pytest.raises(PluginError, match="invalid plugin id"):
+ await mgr.install_from_oci("ghcr.io/owner/plugin:v1")
+
+ assert not plugins_dir.exists() or list(plugins_dir.iterdir()) == []
+
+ @pytest.mark.asyncio
+ async def test_strict_mode_refuses_unsigned_and_installs_nothing(self, tmp_path, trusted_keys_dir, monkeypatch):
+ """In strict trust mode an unsigned image must be rejected
+ *before* any file lands in PLUGINS_DIR. This is the headline
+ guarantee of the H-3 hardening — signature gate before copy."""
+ from app.services.plugin_manager import PluginError, PluginManager # noqa: PLC0415
+
+ _set_trust(monkeypatch, "strict", trusted_keys_dir)
+
+ def populate(tp: Path) -> None:
+ _write_plugin(tp, "unsigned")
+
+ fake = _fake_oras(populate)
+ _stub_oras_pull(monkeypatch, fake)
+
+ plugins_dir = tmp_path / "plugins"
+ mgr = PluginManager(plugins_dir=plugins_dir)
+ with pytest.raises(PluginError):
+ await mgr.install_from_oci("ghcr.io/owner/plugin:v1")
+
+ # The signature gate fires inside the ``with tempfile.TemporaryDirectory``
+ # block, before ``_safe_copytree`` is reached. PLUGINS_DIR must be
+ # empty.
+ assert not plugins_dir.exists() or list(plugins_dir.iterdir()) == []
+
+ @pytest.mark.asyncio
+ async def test_happy_path_installs_and_loads(self, tmp_path, monkeypatch):
+ """End-to-end smoke test with trust mode disabled: the install
+ completes, the plugin lands in PLUGINS_DIR, and ``_load_plugin``
+ registers it under the manifest id."""
+ from app.services.plugin_manager import PluginManager # noqa: PLC0415
+
+ def populate(tp: Path) -> None:
+ _write_plugin(tp, "happy")
+
+ fake = _fake_oras(populate)
+ _stub_oras_pull(monkeypatch, fake)
+
+ plugins_dir = tmp_path / "plugins"
+ mgr = PluginManager(plugins_dir=plugins_dir)
+ loaded_id = await mgr.install_from_oci("ghcr.io/owner/plugin:v1")
+
+ assert loaded_id == "test.happy"
+ assert (plugins_dir / "test.happy" / "plugin.py").exists()
+ assert (plugins_dir / "test.happy" / "aisoc-plugin.json").exists()
+ assert mgr.get_plugin("test.happy") is not None
+
+ @pytest.mark.asyncio
+ async def test_picks_correct_subdir_when_extra_dirs_present(self, tmp_path, monkeypatch):
+ """An OCI image whose tarball happens to also contain a sibling
+ directory (e.g. ``docs/``) must still install the plugin dir, not
+ whichever name sorts first."""
+ from app.services.plugin_manager import PluginManager # noqa: PLC0415
+
+ def populate(tp: Path) -> None:
+ _write_plugin(tp, "real-plugin")
+ # "docs" sorts before "real-plugin"; the pre-H-3 selector would
+ # have picked it.
+ docs = tp / "docs"
+ docs.mkdir()
+ (docs / "README.md").write_text("readme")
+
+ fake = _fake_oras(populate)
+ _stub_oras_pull(monkeypatch, fake)
+
+ plugins_dir = tmp_path / "plugins"
+ mgr = PluginManager(plugins_dir=plugins_dir)
+ loaded_id = await mgr.install_from_oci("ghcr.io/owner/plugin:v1", plugin_id_hint="test.real-plugin")
+
+ assert loaded_id == "test.real-plugin"
+ assert (plugins_dir / "test.real-plugin" / "plugin.py").exists()
+ # The stray docs dir must NOT have been installed.
+ assert not (plugins_dir / "docs").exists()
+
+ @pytest.mark.asyncio
+ async def test_refuses_ambiguous_image_with_multiple_plugin_dirs(self, tmp_path, monkeypatch):
+ """An image packing two plugin-shaped directories is ambiguous —
+ the installer must refuse rather than silently picking one."""
+ from app.services.plugin_manager import PluginError, PluginManager # noqa: PLC0415
+
+ def populate(tp: Path) -> None:
+ _write_plugin(tp, "first")
+ _write_plugin(tp, "second")
+
+ fake = _fake_oras(populate)
+ _stub_oras_pull(monkeypatch, fake)
+
+ plugins_dir = tmp_path / "plugins"
+ mgr = PluginManager(plugins_dir=plugins_dir)
+ with pytest.raises(PluginError, match="multiple plugin directories"):
+ await mgr.install_from_oci("ghcr.io/owner/plugin:v1")
+
+ assert not plugins_dir.exists() or list(plugins_dir.iterdir()) == []