Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
43 changes: 38 additions & 5 deletions app/models/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
15 changes: 11 additions & 4 deletions app/routers/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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
Expand All @@ -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(
Expand Down
38 changes: 38 additions & 0 deletions apps/utils/greffon/compose_shape.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.

Expand Down
21 changes: 18 additions & 3 deletions apps/utils/greffon/preflight.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down Expand Up @@ -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 "
Expand Down
32 changes: 31 additions & 1 deletion apps/utils/greffon/repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "greffer"
version = "0.12.0"
version = "0.13.0"
description = ""
authors = ["Greffon <admin@greffon.io>"]
license = "AGPL-3.0-only"
Expand Down
64 changes: 64 additions & 0 deletions tests/test_controller_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Loading
Loading