From 93dd48b9f15a4676b6c998208f74b1884ebb8923 Mon Sep 17 00:00:00 2001 From: Omar Sy Date: Fri, 23 Oct 2026 20:18:01 +0200 Subject: [PATCH] =?UTF-8?q?feat(custom-app):=20the=20inline=20compose=20tr?= =?UTF-8?q?ansport=20on=20start=20(Feature=204,=20LLD=20=C2=A74.2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GreffonStartRequest grows compose_yaml (str | None, bounded to the same 1 MiB order as the preflight request): when present, the pinned compose bytes travel in the start request and the URL fetch is skipped — a custom version has no URL to fetch. repository_url becomes conditionally required (exactly one compose source per start: neither is the same 400 the old required field produced; both is refused rather than silently preferring one). The containment Feature 3 trust discriminator (_compose_strict) is live on this path: inline bytes are unreviewed input and get the strict allowlist set. Version 0.13.0 — the release the manager's min_greffer_version floor must name (0.9.x-0.12.x pass a 0.9.0 floor but extra=ignore the bytes). Adversarial-review round folded: - P0 alias-DAG: a sub-KiB anchor DAG under an allowed key (e.g. environment) passes every shape check AND returned a green preflight (its own walk is id-deduped), but /start/'s render accounting walks the tree in the parent process with no dedup — 2^25 visits measured at ~71s, ~2^35 possible, pinning the single worker. Fix at the boundary: compose_shape.parse_compose_yaml (SafeLoader subclass refusing AliasEvent — anchor definitions without references stay legal) used by BOTH tenant parse sites (start inline branch and preflight). The allowlist permits no x- extension fields, so the anchor-and-merge pattern was never deployable; refusing the reference names it at preflight instead of a green light that pins a node. The preflight's dedup walker keeps its direct unit test as defense in depth. - P2 RecursionError (deeply nested inline YAML) is not a YAMLError — escaped both handlers and 500'd; now mapped to the same clean 422 at both sites. - P3 InlineComposeError bound at import time in the controller (the file's own convention — an except on a mocked module attribute TypeErrors mid-handler); the both/neither comment says 400 (the request-validation handler), not 422. Suite: 1112 passed; the only failure is the pre-existing-on-main oracle/catalog-pin environment artifact. --- app/__init__.py | 2 +- app/models/controller.py | 43 +++++++++++-- app/routers/controller.py | 15 +++-- apps/utils/greffon/compose_shape.py | 38 ++++++++++++ apps/utils/greffon/preflight.py | 21 ++++++- apps/utils/greffon/repository.py | 32 +++++++++- pyproject.toml | 2 +- tests/test_controller_models.py | 64 +++++++++++++++++++ tests/test_controller_routes.py | 95 +++++++++++++++++++++++++++++ tests/test_preflight.py | 36 +++++++++-- tests/test_repository.py | 84 +++++++++++++++++++++++++ 11 files changed, 413 insertions(+), 19 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 9fc35d90..4f1bed8a 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -2,4 +2,4 @@ # per-greffon ``min_greffer_version`` compatibility gate can refuse deploying an # L4 (or any version-floored) greffon onto a greffer too old to run it. Keep in # sync with pyproject.toml. Single source for the register report. -__version__ = "0.12.0" +__version__ = "0.13.0" diff --git a/app/models/controller.py b/app/models/controller.py index 47388e4c..3d3b522c 100644 --- a/app/models/controller.py +++ b/app/models/controller.py @@ -2,7 +2,7 @@ from typing import Any, Literal -from pydantic import BaseModel, Field, field_validator +from pydantic import BaseModel, Field, field_validator, model_validator # Defense-in-depth: restrict `id` to safe filename-like characters. The id @@ -44,10 +44,27 @@ class GreffonStartRequest(BaseModel): # sends today (e.g. "test-instance-123"). Pattern kept permissive to # accept UUIDs and existing ID formats; rejects path-traversal. id: str = Field(pattern=_ID_PATTERN, min_length=1, max_length=128) - # `min_length=1` matches DRF's `CharField` default (rejects blank). - # Otherwise an empty URL reaches `requests.get('')` and 500s instead - # of returning a 400 validation error. - repository_url: str = Field(min_length=1) + # Catalog starts fetch their compose from `repository_url`; custom-app + # starts (foundation Feature 4, LLD §4.2) carry the pinned bytes inline + # and omit the URL. The requirement is therefore conditional, enforced + # by the `_require_compose_source` validator (no inline bytes and no + # URL is the same 400 the old required field produced via the + # request-validation handler). The min_length floor + # stays for the catalog path: an EMPTY string URL must not reach + # `requests.get('')` and 500. + repository_url: str | None = Field(default=None, min_length=1) + # Custom-app foundation Feature 4 (LLD §4.2): the compose bytes travel + # in the start request — a custom version has no URL (its compose_path + # is ''). Additive and wire-compatible both ways: an old manager omits + # it (None -> the URL-fetch path, exactly today's behavior) and an old + # greffer ignores it via extra=ignore, then 422s on the missing + # repository_url — which the manager's min_greffer_version gate (set to + # the release carrying this field) exists to prevent. Bounded to the + # same 1 MiB order as GREFFER_RENDER_MAX_INPUT and the preflight + # request: an unbounded body is tenant-triggerable memory before any + # render budget runs. + compose_yaml: str | None = Field(default=None, min_length=1, + max_length=1048576) cert: Certificate # Optional in the DRF sense (may be omitted from the payload), but # defaulted to an empty container here so the dumped dict always has @@ -100,6 +117,22 @@ class GreffonStartRequest(BaseModel): # and the rollout-ordering section. tunnel_client_toml: str | None = None + @model_validator(mode="after") + def _require_compose_source(self): + # Exactly one compose source per start: inline bytes (custom apps) + # or a repository URL (catalog). Omitting both is the malformed + # payload the old required `repository_url` field rejected; sending + # both is contradictory (which bytes would run?), so it is refused + # rather than silently preferring one. + if self.compose_yaml is None and not self.repository_url: + raise ValueError( + "repository_url is required when compose_yaml is absent " + "(catalog starts fetch their compose)") + if self.compose_yaml is not None and self.repository_url: + raise ValueError( + "send compose_yaml or repository_url, not both") + return self + class GreffonStopRequest(BaseModel): id: str = Field(pattern=_ID_PATTERN, min_length=1, max_length=128) diff --git a/app/routers/controller.py b/app/routers/controller.py index 3adfd3db..7e92cb2d 100644 --- a/app/routers/controller.py +++ b/app/routers/controller.py @@ -65,7 +65,7 @@ # Bound at import time, NOT accessed as repository.ComposeShapeError at # exception time: the route tests patch the whole repository module, and an # except clause on a Mock attribute raises TypeError mid-handler. -from apps.utils.greffon.repository import ComposeShapeError +from apps.utils.greffon.repository import ComposeShapeError, InlineComposeError from apps.utils.nginx import conf logger = logging.getLogger("greffer") @@ -265,7 +265,13 @@ def start_greffon( # about, so the extra field is harmless to pass through. _refuse_if_updating(_settings(request)) greffon = payload.model_dump() - compose_file = repository.get_compose_file_from_repository(greffon) + try: + compose_file = repository.get_compose_file_from_repository(greffon) + except InlineComposeError as exc: + # Custom-app inline transport (Feature 4): unparsable inline bytes + # are a 422 like every other refusal the manager can relay, never + # a 500. Raised before any port allocation or volume write. + raise HTTPException(status_code=422, detail=str(exc)) from exc # L4 (Tier-C) ports are published directly on their service. The bind # interface depends on this greffer's mode: proxy publishes on the public # interface; tunnel binds host-internal (reached by the rathole-client, not @@ -284,8 +290,9 @@ def start_greffon( # compose-containment Feature 3: the trust discriminator for the key # allowlist. An inline compose (custom-app foundation Feature 4) is # unreviewed input -> the strict set; the URL-fetch path stays catalog. - # The compose_yaml field does not exist on the payload yet, so this is - # False for every start today and activates with the inline transport. + # Live since the inline transport shipped: True exactly when the + # payload carried compose_yaml (the model validator guarantees the + # URL path never sets it). _compose_strict = bool(greffon.get('compose_yaml')) try: greffon_info = repository.get_greffon_info( diff --git a/apps/utils/greffon/compose_shape.py b/apps/utils/greffon/compose_shape.py index 69065e82..557f02a9 100644 --- a/apps/utils/greffon/compose_shape.py +++ b/apps/utils/greffon/compose_shape.py @@ -33,6 +33,8 @@ import re +import yaml + # Access modes docker documents for the third short-syntax mount field (the # long-syntax ``mode`` key honours ro/rw). A preserved mode is re-rendered # onto the rebuilt mapping (Feature 2: a read-only declaration stays @@ -53,6 +55,42 @@ _NGINX_SAFE_NAME = re.compile(r"[a-zA-Z0-9._-]+\Z") +class AliasForbiddenError(ValueError): + """The compose text uses a YAML alias reference (``*anchor``). + Raised at PARSE time, before any walk: alias references are what + construct shared-object DAGs, and a sub-KiB anchor DAG expands to + exponentially many visits in every downstream tree walk that lacks + per-id dedup (the start path's render accounting walks in the parent + process, outside the child render timeout). Anchor DEFINITIONS + without references construct nothing shared and stay legal.""" + + +class _NoAliasLoader(yaml.SafeLoader): + """SafeLoader minus alias references. The compose allowlist permits + no ``x-`` extension fields (top level is exactly version/services/ + volumes/networks), so the standard anchor-and-merge pattern was never + deployable — refusing the reference at load names that early, at + preflight, instead of letting a green preflight relay the bytes to a + start that pins the controller on the expanded walk.""" + + def compose_node(self, parent, index): + if self.check_event(yaml.AliasEvent): + event = self.peek_event() + raise AliasForbiddenError( + f"YAML alias reference *{getattr(event, 'anchor', '?')} " + f"is not permitted in compose input") + return super().compose_node(parent, index) + + +def parse_compose_yaml(text): + """Parse compose YAML refusing alias references (AliasForbiddenError) + and leaving every other error to the caller as yaml.YAMLError. Used + for the inline/tenant paths (start transport and preflight); the + catalog URL path keeps its plain safe_load — trusted, curated input, + byte-identical behavior.""" + return yaml.load(text, Loader=_NoAliasLoader) + + class ComposeShapeError(Exception): """A compose the pipeline cannot honour, with the offending path. diff --git a/apps/utils/greffon/preflight.py b/apps/utils/greffon/preflight.py index 55f3c951..9b5f9eb7 100644 --- a/apps/utils/greffon/preflight.py +++ b/apps/utils/greffon/preflight.py @@ -22,7 +22,10 @@ import yaml from apps.utils.docker import compose as compose_mod -from apps.utils.greffon.compose_shape import ComposeShapeError, normalize_compose +from apps.utils.greffon.compose_shape import ( + AliasForbiddenError, ComposeShapeError, normalize_compose, + parse_compose_yaml, +) logger = logging.getLogger("greffer") @@ -201,9 +204,21 @@ def _resolve_image_digests(services: dict) -> dict: def run_preflight(compose_yaml: str, extra_keys=None) -> dict: """Validate a custom compose for deployability. Raises PreflightError with 422 rows; returns the LLD §4.1 payload on success.""" + # parse_compose_yaml (compose_shape) refuses alias REFERENCES at + # load: the preflight's own walks are alias-safe, but a green + # preflight's bytes go on to /start/, whose render-accounting walk + # runs in the parent process outside the child render timeout — a + # sub-KiB anchor DAG there pins the single-worker controller + # (adversarial review on the transport PR). The allowlist permits no + # x- extension fields, so an anchor pattern was never deployable; + # refusing it here names it for the user at create time. try: - compose = yaml.safe_load(compose_yaml) - except yaml.YAMLError as exc: + compose = parse_compose_yaml(compose_yaml) + except AliasForbiddenError as exc: + raise PreflightError([{ + "service": None, "key": "compose_yaml", "message": str(exc), + }]) from exc + except (yaml.YAMLError, RecursionError) as exc: raise PreflightError([{ "service": None, "key": "compose_yaml", "message": f"not valid YAML " diff --git a/apps/utils/greffon/repository.py b/apps/utils/greffon/repository.py index 3ad60eff..6c8c04b7 100644 --- a/apps/utils/greffon/repository.py +++ b/apps/utils/greffon/repository.py @@ -4,12 +4,42 @@ import yaml from apps.utils.os.network import get_free_ports from apps.utils.greffon import sticky_ports -from apps.utils.greffon.compose_shape import ComposeShapeError, normalize_compose +from apps.utils.greffon.compose_shape import ( + AliasForbiddenError, ComposeShapeError, normalize_compose, + parse_compose_yaml, +) from apps.utils.docker import l4_ports logger = logging.getLogger("greffer") +class InlineComposeError(Exception): + """The inline compose bytes are not parseable YAML. Distinct from + ComposeShapeError on purpose: these bytes were green-lit by the SAME + parse in /preflight/, so unparsable bytes at start mean the manager + stored or sent something different from what the node verified — a + 422 naming the transport, never a 500.""" + + def get_compose_file_from_repository(greffon): + # Custom-app inline transport (foundation Feature 4, LLD §4.2): when + # the payload carries the compose bytes the URL fetch is SKIPPED — + # repository_url is None on that path (the model guarantees exactly + # one source), so no empty string ever reaches requests.get. + inline = greffon.get('compose_yaml') + if inline: + # parse_compose_yaml, not plain safe_load: tenant input. It + # refuses alias references (an anchor DAG expands exponentially + # in every downstream walk — adversarial-review P0) and the + # RecursionError catch maps pathologically deep nesting to the + # same clean 422 instead of a 500 (P2). + try: + return parse_compose_yaml(inline) + except AliasForbiddenError as exc: + raise InlineComposeError(str(exc)) from exc + except (yaml.YAMLError, RecursionError) as exc: + raise InlineComposeError( + f"inline compose_yaml is not valid YAML " + f"({getattr(exc, 'problem', None) or exc})") from exc r = requests.get(greffon['repository_url']) if r.status_code != 200: raise Exception( diff --git a/pyproject.toml b/pyproject.toml index bf6c83e4..5bd24824 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "greffer" -version = "0.12.0" +version = "0.13.0" description = "" authors = ["Greffon "] license = "AGPL-3.0-only" diff --git a/tests/test_controller_models.py b/tests/test_controller_models.py index a6eb4dc2..4e78e06c 100644 --- a/tests/test_controller_models.py +++ b/tests/test_controller_models.py @@ -89,6 +89,70 @@ def test_stop_request_missing_id() -> None: GreffonStopRequest() # type: ignore[call-arg] +def test_start_request_explicit_null_compose_yaml_is_catalog() -> None: + """Explicit null == absent: the wire-compat story for a manager that + always includes the key.""" + req = GreffonStartRequest( + id="x", + repository_url="https://example.com/docker-compose.yml", + compose_yaml=None, + cert=Certificate(**SAMPLE_CERT), + ) + assert req.compose_yaml is None + assert req.repository_url.startswith("https://") + + +def test_start_request_inline_compose_without_url() -> None: + """Custom-app inline transport (foundation Feature 4): compose_yaml + replaces the URL entirely — repository_url omitted, not empty.""" + req = GreffonStartRequest( + id="x", + compose_yaml="services:\n app:\n image: nginx\n", + cert=Certificate(**SAMPLE_CERT), + ) + assert req.compose_yaml.startswith("services:") + assert req.repository_url is None + + +def test_start_request_inline_and_url_both_refused() -> None: + """Exactly one compose source: sending both is contradictory (which + bytes would run?), so it is refused rather than silently preferring + one.""" + with pytest.raises(ValidationError): + GreffonStartRequest( + id="x", + repository_url="https://example.com/compose.yml", + compose_yaml="services: {}", + cert=Certificate(**SAMPLE_CERT), + ) + + +def test_start_request_empty_inline_compose_refused() -> None: + with pytest.raises(ValidationError): + GreffonStartRequest( + id="x", compose_yaml="", cert=Certificate(**SAMPLE_CERT) + ) + + +def test_start_request_oversized_inline_compose_refused() -> None: + """Same 1 MiB bound as the preflight request: an unbounded body is + tenant-triggerable memory before any render budget runs.""" + with pytest.raises(ValidationError): + GreffonStartRequest( + id="x", compose_yaml="a" * 1048577, + cert=Certificate(**SAMPLE_CERT), + ) + + +def test_start_request_empty_repository_url_still_refused() -> None: + """The catalog path's min_length floor survives the field becoming + optional: '' must not reach requests.get('') and 500.""" + with pytest.raises(ValidationError): + GreffonStartRequest( + id="x", repository_url="", cert=Certificate(**SAMPLE_CERT) + ) + + def test_start_request_accepts_any_shape_in_ports() -> None: """ports is `Any`-typed to match DRF's DictField; anything hashable goes.""" req = GreffonStartRequest( diff --git a/tests/test_controller_routes.py b/tests/test_controller_routes.py index 8e99f9df..7aba048c 100644 --- a/tests/test_controller_routes.py +++ b/tests/test_controller_routes.py @@ -92,6 +92,97 @@ async def test_start_compose_body_render_failure_returns_422(client: AsyncClient mock_compose.start.assert_not_called() +@pytest.mark.asyncio +async def test_start_inline_compose_strict_and_no_fetch( + client: AsyncClient) -> None: + """Custom-app inline transport (foundation Feature 4): a start whose + payload carries compose_yaml and NO repository_url passes validation, + renders the inline bytes, and the strict allowlist discriminator is + True (the containment Feature 3 gate goes live on this path).""" + inline = "services:\n app:\n image: nginx\n" + with patch( + "app.routers.controller.repository.get_greffon_info" + ) as mock_info, patch( + "app.routers.controller.compose" + ) as mock_compose, patch("app.routers.controller.conf"): + mock_info.return_value = {"ports": [], "id": "test-instance-123"} + mock_compose.get_compose_template.return_value = {} + mock_compose.get_status.return_value = {"status": "running"} + + payload = {k: v for k, v in SAMPLE_START_PAYLOAD.items() + if k != "repository_url"} + payload["compose_yaml"] = inline + r = await client.post( + "/api/controller/start/", + json=payload, + headers={TOKEN_HEADER: "test-token"}, + ) + + assert r.status_code == 200, r.text + # the discriminator: inline bytes => the strict allowlist set + self_kwargs = mock_info.call_args.kwargs + assert self_kwargs.get("strict") is True + # the inline bytes are what get_greffon_info received, parsed + compose_arg = mock_info.call_args.args[0] + assert compose_arg["services"]["app"]["image"] == "nginx" + + +@pytest.mark.asyncio +async def test_start_inline_invalid_yaml_returns_422( + client: AsyncClient) -> None: + """Unparsable inline bytes are the SAME class of clean 422 as a + shape refusal: these bytes passed the identical parse in preflight, + so divergence means the manager sent something else — name the + transport, never a 500, and allocate nothing.""" + with patch( + "app.routers.controller.repository.get_greffon_info" + ) as mock_info, patch( + "app.routers.controller.compose" + ) as mock_compose, patch("app.routers.controller.conf"): + payload = {k: v for k, v in SAMPLE_START_PAYLOAD.items() + if k != "repository_url"} + payload["compose_yaml"] = "services: [unclosed" + r = await client.post( + "/api/controller/start/", + json=payload, + headers={TOKEN_HEADER: "test-token"}, + ) + + assert r.status_code == 422 + assert "not valid YAML" in r.json()["detail"] + mock_info.assert_not_called() + mock_compose.start.assert_not_called() + + +@pytest.mark.asyncio +async def test_start_inline_alias_dag_returns_422(client: AsyncClient) -> None: + """The adversarial-review P0 end-to-end: an anchor DAG small enough + to fit any body cap must be refused at the route (parse boundary), + never reach a walk. Nothing is allocated.""" + bomb = ["services:", " app:", " image: nginx", " environment:", + " a0: &a0 [x]"] + for i in range(1, 25): + bomb.append(f" a{i}: &a{i} [*a{i-1}, *a{i-1}]") + with patch( + "app.routers.controller.repository.get_greffon_info" + ) as mock_info, patch( + "app.routers.controller.compose" + ) as mock_compose, patch("app.routers.controller.conf"): + payload = {k: v for k, v in SAMPLE_START_PAYLOAD.items() + if k != "repository_url"} + payload["compose_yaml"] = "\n".join(bomb) + "\n" + r = await client.post( + "/api/controller/start/", + json=payload, + headers={TOKEN_HEADER: "test-token"}, + ) + + assert r.status_code == 422 + assert "alias" in r.json()["detail"] + mock_info.assert_not_called() + mock_compose.start.assert_not_called() + + @pytest.mark.asyncio async def test_start_success(client: AsyncClient) -> None: with patch("app.routers.controller.repository") as mock_repo, patch( @@ -128,6 +219,10 @@ async def test_start_success(client: AsyncClient) -> None: assert "ports" in body assert body["ports"][0]["port_name"] == "app_80" + # the discriminator's other side: a URL-fetch (catalog) start never + # gets the strict set — an inverted discriminator would flip both. + assert mock_repo.get_greffon_info.call_args.kwargs.get("strict") is False + mock_repo.get_compose_file_from_repository.assert_called_once() mock_repo.get_greffon_info.assert_called_once() mock_compose.get_compose_template.assert_called_once() diff --git a/tests/test_preflight.py b/tests/test_preflight.py index bf8dfa82..3538e16e 100644 --- a/tests/test_preflight.py +++ b/tests/test_preflight.py @@ -78,6 +78,21 @@ def test_invalid_yaml_is_a_named_error(self): run_preflight("services: [unclosed") assert e.value.errors[0]["key"] == "compose_yaml" + def test_alias_reference_refused_at_parse(self): + """The preflight's own walks are alias-safe, but a GREEN + preflight's bytes go on to /start/, whose render accounting + walks in the parent process — refusing the reference at load is + what keeps green-preflight bytes safe to relay (transport-PR + adversarial review).""" + bomb = ("services:\n app:\n image: nginx\n" + " environment:\n" + " a0: &a0 [x]\n" + " a1: &a1 [*a0, *a0]\n") + with pytest.raises(PreflightError) as e: + run_preflight(bomb) + assert e.value.errors[0]["key"] == "compose_yaml" + assert "alias" in e.value.errors[0]["message"] + def test_unresolvable_image_is_an_error_naming_it(self): with patch.object(pf.compose_mod, "client") as client: client.images.pull.side_effect = RuntimeError("registry down") @@ -108,8 +123,17 @@ def test_alias_bomb_neutered_by_dedup(self): # leaf walk (outside every render guard). The fix visits each # SHARED container once, so the exponential alias chain resolves # in linear visits — this must complete fast, not raise. + # + # Since the inline-transport PR, tenant composes with alias + # REFERENCES are refused at parse (see + # test_alias_reference_refused_at_parse) — this test feeds the + # walker a DAG built with plain safe_load to keep proving the + # dedup itself, as defense in depth for any future parse + # boundary that lets aliases through. import time + import yaml as _yaml + compose = "services:\n app:\n image: x\n labels:\n" prev_ref = None for i in range(20): # 2^20 nodes if expanded naively @@ -119,11 +143,15 @@ def test_alias_bomb_neutered_by_dedup(self): else: compose += f" - &a{i} [{prev_ref}, {prev_ref}]\n" prev_ref = f"*a{i}" - with patch.object(pf.compose_mod, "client") as client: - client.images = _mock_images_ok() - t0 = time.monotonic() - result = run_preflight(compose) # completes + # plain safe_load still constructs the shared-object DAG; the + # walker under test is the preflight's own leaf iterator + tree = _yaml.safe_load(compose) + t0 = time.monotonic() + leaves = list(pf._string_leaves(tree)) # completes assert time.monotonic() - t0 < 5.0 + # linear visits: 20 chain levels + the literal leaves, nothing + # exponential + assert len(leaves) < 50 def test_visit_budget_catches_huge_structures(self): # A genuinely large NON-aliased structure (no dedup to save it) diff --git a/tests/test_repository.py b/tests/test_repository.py index 58371844..9f2aca04 100644 --- a/tests/test_repository.py +++ b/tests/test_repository.py @@ -45,6 +45,90 @@ def test_get_compose_file_from_repository(self, mock_requests): self.assertEqual(result['services']['app']['image'], 'wordpress:latest') +class GetComposeInlineTests(TestCase): + """The inline transport branch of get_compose_file_from_repository + (custom-app foundation Feature 4).""" + + @patch('apps.utils.greffon.repository.requests') + def test_inline_bytes_skip_the_fetch(self, mock_requests): + from apps.utils.greffon.repository import ( + get_compose_file_from_repository, + ) + greffon = {'id': 'i', + 'compose_yaml': 'services:\n app:\n image: nginx\n'} + result = get_compose_file_from_repository(greffon) + mock_requests.get.assert_not_called() + self.assertEqual(result['services']['app']['image'], 'nginx') + + def test_invalid_inline_yaml_raises_inline_compose_error(self): + from apps.utils.greffon.repository import ( + InlineComposeError, get_compose_file_from_repository, + ) + with self.assertRaises(InlineComposeError) as cm: + get_compose_file_from_repository( + {'compose_yaml': 'services: [unclosed'}) + self.assertIn('inline compose_yaml', str(cm.exception)) + + def test_alias_dag_refused_at_parse(self): + """The adversarial-review P0: a sub-KiB anchor DAG under any + allowed key passes every shape check and expands exponentially + in the downstream walks. Alias REFERENCES are refused at load — + the boundary — not hoped away by walk hardening.""" + from apps.utils.greffon.repository import ( + InlineComposeError, get_compose_file_from_repository, + ) + bomb = ['services:', ' app:', ' image: nginx', + ' environment:'] + # 25 levels: ~600 bytes, 2^25 expanded visits if walked naively + bomb.append(' a0: &a0 [x]') + for i in range(1, 25): + bomb.append(f' a{i}: &a{i} [*a{i-1}, *a{i-1}]') + with self.assertRaises(InlineComposeError) as cm: + get_compose_file_from_repository( + {'compose_yaml': '\n'.join(bomb) + '\n'}) + self.assertIn('alias', str(cm.exception)) + + def test_anchor_without_reference_is_fine(self): + """An anchor DEFINITION constructs nothing shared; only the + reference is the DAG. Refusing definitions would reject benign + input.""" + from apps.utils.greffon.repository import ( + get_compose_file_from_repository, + ) + result = get_compose_file_from_repository( + {'compose_yaml': + 'services:\n app:\n image: &img nginx\n' + ' environment:\n K: &k v\n'}) + self.assertEqual(result['services']['app']['image'], 'nginx') + + def test_deeply_nested_inline_yaml_maps_to_inline_compose_error(self): + """RecursionError is not a YAMLError; unmapped it escapes the + handlers and 500s (adversarial-review P2).""" + from apps.utils.greffon.repository import ( + InlineComposeError, get_compose_file_from_repository, + ) + with self.assertRaises(InlineComposeError): + get_compose_file_from_repository( + {'compose_yaml': '[' * 1000 + ']' * 1000}) + + @patch('apps.utils.greffon.repository.requests') + def test_absent_inline_still_fetches_the_url(self, mock_requests): + """The catalog path is byte-for-byte the old behavior: no + compose_yaml key at all -> requests.get(repository_url).""" + from apps.utils.greffon.repository import ( + get_compose_file_from_repository, + ) + mock_response = MagicMock() + mock_response.status_code = 200 + mock_response.text = 'services:\n app:\n image: nginx\n' + mock_requests.get.return_value = mock_response + result = get_compose_file_from_repository( + {'repository_url': 'https://example.com/docker-compose.yml'}) + mock_requests.get.assert_called_once_with( + 'https://example.com/docker-compose.yml') + self.assertIn('services', result) + + class CreateGreffonInfoTests(TestCase): """Tests for create_greffon_info."""