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
13 changes: 13 additions & 0 deletions app/models/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,19 @@ class GreffonField(BaseModel):
destinations: Any


class GreffonPreflightRequest(BaseModel):
"""Custom-app LLD §4.1: the preflight validates a custom compose for
deployability (parse + strict allowlist + artifact pinning) before the
manager persists anything. Read-only apart from the digest-resolution
pull."""

# Bounded to the same order as GREFFER_RENDER_MAX_INPUT (1 MiB): an
# unbounded body is tenant-triggerable CPU/memory before any budget
# runs (yaml.safe_load + expression scans) — everything else in this
# model caps at 64-512.
compose_yaml: str = Field(min_length=1, max_length=1048576)


class GreffonStartRequest(BaseModel):
# `id` is a free-form str in DRF (not UUID), matching what the manager
# sends today (e.g. "test-instance-123"). Pattern kept permissive to
Expand Down
26 changes: 26 additions & 0 deletions app/routers/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

import anyio
from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.responses import JSONResponse

from app import backup
from app.auth import require_token
Expand All @@ -34,6 +35,7 @@
GreffonDecommissionRequest,
GreffonDecommissionResponse,
GreffonForgetRequest,
GreffonPreflightRequest,
GreffonRepoOpRequest,
GreffonRestoreRequest,
GreffonRestoreResponse,
Expand Down Expand Up @@ -221,6 +223,30 @@ def wrapper(payload, request, *args, **kwargs):
return wrapper


@router.post("/preflight/")
def preflight_greffon(
payload: GreffonPreflightRequest,
request: Request,
_: None = Depends(require_token),
) -> JSONResponse:
"""compose-containment Feature 6 / custom-app LLD §4.1: validate a
custom compose on the node that would deploy it. The SAME parse and
strict-allowlist path as a real start, so a green preflight provably
implies a start that parses; image references are pinned to digests by
pull+inspect (the one node-side write; unresolvable = error, never an
unpinned fallback). Sync def: digest pulls are blocking and run on the
threadpool like start."""
from apps.utils.greffon import preflight as preflight_mod

try:
result = preflight_mod.run_preflight(
payload.compose_yaml,
extra_keys=_settings(request).greffer_compose_extra_allowed_keys)
except preflight_mod.PreflightError as exc:
return JSONResponse({"errors": exc.errors}, status_code=422)
return JSONResponse(result)


@router.post("/start/")
@_serialize_instance_op
def start_greffon(
Expand Down
22 changes: 16 additions & 6 deletions apps/utils/docker/compose.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
from apps.utils.docker.render_budget import ( # noqa: F401 (re-export)
_COMPOSE_RENDER_ENV,
_FILE_RENDER_ENV,
render_compose_tree_bounded,
render_json_bounded,
)

Expand Down Expand Up @@ -645,9 +646,12 @@ def create_compose(compose, greffon_info):
# a user-supplied `{{ config.X }}` reaches these today. Inside this try
# nothing but template evaluation runs, and the env has no custom filters
# or globals that could raise a greffer bug, so a broad catch cannot
# mislabel a greffer fault as a catalog error. yaml.dump stays OUTSIDE the
# try: a dict that cannot be represented is greffer-side, and a 500 is the
# honest answer there.
# mislabel a greffer fault as a catalog error. The FINAL yaml.dump
# (serializing the already-rendered tree, post-Feature-6) is inside
# this try: with safe_load'ed input the render output contains only
# str/int/float/bool/None/dict/list, which yaml can always represent,
# so an exception from it would be a greffer bug — and wrapping it
# 422s rather than 500s, the conservative direction either way.
#
# The forwarded detail names the exception TYPE only, never str(exc). With
# the lenient undefined the body keeps, a rendered value can land inside
Expand All @@ -658,12 +662,18 @@ def create_compose(compose, greffon_info):
# know whether the compose is unsafe, malformed, or references something
# unset; the full reason goes to the greffer log, which is not caller-
# reachable. The compose file is only written after the render succeeds.
dumped = yaml.dump(compose)
try:
# Feature 1b: the render runs under the budget (input/output caps,
# child-process memory + time bound) — see render_budget.py. A cap
# child-process memory + time bound). Feature 6: STRUCTURE-
# PRESERVING — every string LEAF renders in one child job and the
# tree is yaml.dump'd once afterwards, replacing
# Template(yaml.dump(compose)) whose single-quote escaping could
# corrupt Jinja expressions containing single-quoted literals
# (TemplateSyntaxError on legal compose; the catalog worked around
# it by double-quote convention). Keys never render. A cap
# violation re-raises below as its own bounded message.
compose_file = render_bounded('body', dumped, greffon_info)
rendered = render_compose_tree_bounded(compose, greffon_info)
compose_file = yaml.dump(rendered)
except RenderBudgetExceeded as exc:
raise ConfigRenderError(str(exc)) from exc
except Exception as exc:
Expand Down
93 changes: 74 additions & 19 deletions apps/utils/docker/render_budget.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,13 @@ def _harden(env):
return env


_COMPOSE_RENDER_ENV = _harden(ImmutableSandboxedEnvironment(autoescape=False))
# keep_trailing_newline: the per-LEAF render must preserve a value's own
# trailing \n (multi-line entrypoints, heredocs, env-file style content) —
# Jinja strips one trailing newline by default, which silently truncated
# every multi-line leaf by exactly one \n (found by adversarial review:
# 4 catalog snapshots diffed by exactly that).
_COMPOSE_RENDER_ENV = _harden(ImmutableSandboxedEnvironment(
autoescape=False, keep_trailing_newline=True))
_harden(_FILE_RENDER_ENV)


Expand Down Expand Up @@ -254,51 +260,100 @@ def _child_render(which: str, source: str, context: dict) -> str:
raise rebuilt from None


def _child_render_json(tree, context):
"""Runs IN THE CHILD: render every STRING LEAF of a json-destination
value in one job. Per-leaf submission re-pickled the entire context
(cert material included) for every leaf — quadratic on real realm
documents (codex review: a 5k-leaf doc went 0.6s -> 10.4s)."""
def _child_render_tree(tree, context, which, _budget=None):
"""Runs IN THE CHILD: render every STRING LEAF of a tree value in one
job (per-leaf submission re-pickled the entire context for every leaf
— quadratic on real documents; codex review). which selects the env
('file' for json destinations, 'body' for the compose tree — the
Feature-6 structure-preserving render).

_budget is a one-element JOB-WIDE output accumulator: per-leaf caps
alone let N leaves each render just under the cap, so the assembled
document exceeded GREFFER_RENDER_MAX_OUTPUT unbounded (codex review).
"""
if _budget is None:
_budget = [_knob("GREFFER_RENDER_MAX_OUTPUT", _DEFAULT_OUTPUT)]
if isinstance(tree, str):
max_in = _knob("GREFFER_RENDER_MAX_INPUT", _DEFAULT_INPUT)
if max_in and len(tree.encode("utf-8", "surrogatepass")) > max_in:
raise RenderBudgetExceeded("input_too_large", max_in)
return _child_render("file", tree, context)
out = _child_render(which, tree, context)
if _budget[0]:
_budget[0] -= len(out.encode("utf-8", "surrogatepass"))
if _budget[0] < 0:
raise RenderBudgetExceeded(
"output_too_large",
_knob("GREFFER_RENDER_MAX_OUTPUT", _DEFAULT_OUTPUT))
return out
if isinstance(tree, dict):
return {k: _child_render_json(v, context) for k, v in tree.items()}
return {k: _child_render_tree(v, context, which, _budget)
for k, v in tree.items()}
if isinstance(tree, list):
return [_child_render_json(v, context) for v in tree]
return [_child_render_tree(v, context, which, _budget)
for v in tree]
return tree


def _child_render_json(tree, context):
return _child_render_tree(tree, context, "file")


def render_json_bounded(tree, context) -> object:
"""Budgeted render of a json-destination value's string leaves, in one
child round-trip (input cap applies per leaf via the child render)."""
return _run_tree_job(tree, context, "file")


def render_compose_tree_bounded(compose, context) -> object:
"""Feature 6 structure-preserving render: render every string LEAF of
the compose tree under the body env, in ONE child job; the caller then
yaml.dump's the result ONCE. Replacing Template(yaml.dump(compose))
kills the round-trip fragility class structurally: yaml single-quote
escaping (an embedded ' doubled to '') could corrupt any Jinja
expression containing a single-quoted literal into a
TemplateSyntaxError — and every catalog workaround-by-convention
disappears, because values are rendered as Python strings and then
serialized by yaml with correct quoting applied exactly once.
Keys are NOT rendered (same intentional choice as the json walker).
"""
return _run_tree_job(compose, context, "body")


def _run_tree_job(tree, context, which):
src_len = sum(
len(leaf.encode("utf-8", "surrogatepass"))
for leaf in _iter_string_leaves(tree))
for leaf in _iter_string_leaves(tree, keys=True))
Comment on lines 320 to +322

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 Bound alias traversal before starting the render child

When a compose contains a short chain of YAML aliases where each container references the preceding container twice, yaml.safe_load preserves that shared graph but this generator revisits every reference. Consequently sum() can perform roughly 2^N work in the parent before _submit_budgeted starts, so neither the render timeout nor the child memory limit applies; the alias-safe preflight walker can approve the same input while deployment ties up a request worker. Track visited container identities and impose a visit budget during this accounting pass.

Useful? React with 👍 / 👎.

max_in = _knob("GREFFER_RENDER_MAX_INPUT", _DEFAULT_INPUT)
if max_in and src_len > max_in * 100:
# A sane guard for pathological leaf counts; each leaf is itself
# input-capped in the child.
# Aggregate guard for pathological leaf counts (values AND keys
# are counted; each rendered leaf is additionally input-capped in
# the child — keys render never, so this aggregate is their only
# bound).
raise RenderBudgetExceeded("input_too_large", max_in * 100)
mem = _knob("GREFFER_RENDER_MEM_BYTES", _DEFAULT_MEM)
timeout = _knob("GREFFER_RENDER_TIMEOUT_SECONDS", _DEFAULT_TIMEOUT,
as_float=True)
return _submit_budgeted(
lambda pool: pool.submit(_child_render_json, tree, context),
lambda pool: pool.submit(_child_render_tree, tree, context, which),
mem, timeout)


def _iter_string_leaves(tree):
def _iter_string_leaves(tree, keys: bool = False):
"""Yield every string leaf. keys=False (the render path) walks VALUES
only — keys never render (an intentional hardening over the old whole-
document template, which templated them: a structure-injection vector).
keys=True (the budget accounting path) walks keys TOO, so a compose
whose bulk hides in keys cannot exceed the input cap un-counted
(review finding: a 3 MiB key passed a 1 MiB cap as 1 counted byte)."""
if isinstance(tree, str):
yield tree
elif isinstance(tree, dict):
if keys:
for k in tree:
if isinstance(k, str):
yield k
for v in tree.values():
yield from _iter_string_leaves(v)
yield from _iter_string_leaves(v, keys)
elif isinstance(tree, list):
for v in tree:
yield from _iter_string_leaves(v)
yield from _iter_string_leaves(v, keys)


# --- the pool ----------------------------------------------------------------
Expand Down
Loading
Loading