Skip to content

feat(templates): serve the agent catalog from a remote registry (trinity-enterprise#14) - #2033

Merged
vybe merged 16 commits into
devfrom
feature/ent14-remote-template-registry
Aug 9, 2026
Merged

vybe merged 16 commits into
devfrom
feature/ent14-remote-template-registry

Conversation

@AndriiPasternak31

@AndriiPasternak31 AndriiPasternak31 commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Refs trinity-enterprise#14

(Refs, deliberately not a closing keyword — the issue lives in the private tracker and GitHub's auto-close/auto-promote is same-repo only. After merge, status-in-dev on abilityai/trinity-enterprise#14 has to be set by hand.)

What this does

The GitHub half of the agent-template catalog is sourced at runtime from a registry.yaml fetched over HTTPS, so curating an install's starter fleet is a vendor file edit rather than a Trinity release.

Purely additive. DEFAULT_GITHUB_TEMPLATE_REPOS has been [] since #1931, so this fills a branch that is empty today, and an admin-curated list still wins outright — that install never even issues the fetch. Precedence: admin DB override → remote registry → bundled list.

Fail-open is structural, not an except branch. get_all_templates() returns local + github; local needs no network, and the registry can only add to github. So unreachable / 5xx / timeout / malformed / alias-bombed / oversize / redirected / empty all reduce github toward [] — the already-shipping default state. Proven mode-by-mode through the real parser and a real transport, asserting on catalog output rather than on whether an except branch ran.

Registry entries are parsed into a frozen four-field allowlist (repo, display_name, description, priority) and never splatted, so a registry cannot assert fork_to_own, credentials, schedules, data_paths, hidden or id. The requirements entry states the uncomfortable half plainly: repo is a capability pointer — choosing the repo chooses which template.yaml Trinity fetches and trusts, so the allowlist bounds the direct blast radius, not the indirect one.

Review-round fixes (the last two commits)

Four findings, each a case where the control was present and correct one level above where the attack lands. Worth reading as a set — that is the pattern.

S1 — a byte ceiling on decoded bytes is not a byte ceiling. The fetch streamed under a 256 KiB running total with a docstring correctly explaining why Content-Length can't be the gate. Both true, both defeated one level down: a custom headers= dict does not override httpx's default Accept-Encoding: gzip, deflate, and iter_bytes() yields decompressed chunks. A 199 KiB wire body — under the cap, so the early abort passes it — inflated ~1030:1 to 458 MB of transient allocation on the event-loop thread. Now counts wire bytes via iter_raw() and refuses any Content-Encoding outright; same body peaks at 0.01 MB. The harness hid it: httpx.Response(content=…) decodes in the constructor, so every fixture built a response the production path cannot even read — the byte-ceiling tests were green against a shape incapable of expressing the failure.

S2 — the fork_to_own gate read the catalog cache, not its own read. It consulted metadata from the global platform PAT, off the default branch, through a 600 s cache — while crud.py had already read the same file one line earlier with the caller's resolved PAT and parsed ref. Both directions broke: GitHub answers 404, not 403, for a repo a token cannot see, so a private fork_to_own: required template readable only by the creator's PAT was classified absent, the gate passed, and the agent bound to the shared upstream — the exact outcome the gate exists to prevent, no attacker involved; and a poisoned cache entry 503'd creators whose own PAT read the file fine. Note that fixing only the availability half would not have closed the false pass — the fork_to_own value is None for the same reason the verdict is wrong, so both inputs now come from the creation-path read, and required from either source enforces (a union — can only remove a false pass).

S3 — RFC 6598 (100.64.0.0/10) was admitted. Python's ipaddress reports CGNAT as neither is_private nor is_reserved. Not reachable in Trinity's own topology, but several cloud providers address internal endpoints there. Both /10 boundaries held public so a legitimate registry isn't blackholed.

Packaging — the hard kill switch was inert. Caught by /validate-pr. config.py read TEMPLATE_REGISTRY_ENABLED / TEMPLATE_REGISTRY_URL; neither compose file injected them. Prod compose launches standalone (no base merge, no env_file:) and is what every deploy path uses, so both levers did nothing on every real instance while working fine on a laptop — a default-ON feature making outbound requests with no way to stop it. The irony is the reason it's now pinned rather than just fixed: the comment block directly above that os.getenv argues at length against _resolve_bool_flag because it would ship an inert kill switch (#1039 class) — and the flag shipped inert anyway, by the other route, ~15 lines away. Sixth recurrence of the #1039/#1056 class.

Verification

  • Full unit suite: 8783 passed, 17 skipped, 0 failed — run twice, fixed-order and pytest-randomly, post-rebase onto dev @ ef3b0eb.
  • Packaging proven by rendering, not grepping — docker compose config shows both vars on backend in each file, and TEMPLATE_REGISTRY_ENABLED=false propagates through to "false".
  • The new packaging guard was proven by deleting the real prod line and watching it go red. (First attempt at that proof used grep -v 'VAR=${VAR', where $ is an end-of-line anchor — nothing was removed and the suite reported a false green against an unmodified tree. Noted in the guard's docstring.)
  • enterprise-docs-guard pattern run locally: clean. tests/lint_sys_modules.py: 194 violations vs baseline 240, no new.
  • Invariant Setup improvements #5 vendored safe_yaml.py mirror: byte-identical.

Rebase onto current dev (ef3b0eb)

Rebased over 38 new dev commits. Four conflicts, all additive-vs-additive
(feature-flows.md and learnings.md index rows, tests/registry.json
entries, and url_validation.py, where dev's #2052/ent#347 authority grammar
and this branch's CGNAT constant are disjoint module-level additions). Each
resolution was verified as a union: zero removed lines against either
side for the two files that merge as text, and the registry JSON proven
lossless set-wise (dev 142 ∪ this branch 137 = 150 merged, no dupes).

Two suites then needed adapting, both because the change that landed under
them is the one that is right:

  • ent#15 (feat: GitHub-repo import wizard — fork / copy / clone with inline compat check (abilityai/trinity-enterprise#15) #2040) inserted an import-intent gate into _resolve_template
    ahead of the fork gate; two SimpleNamespace config doubles predate the
    field and raised AttributeError before reaching their assertion. A stub
    gap, not a production one — the S2 fail-closed gate is untouched, and dev's
    copy intent carries its own fork_to_own: required refusal.
  • fix(security): admin gates reject agent-scoped keys #1890 made require_admin itself reject agent-scoped principals. This
    branch asserted an agent key could still read the registry setting, on
    the reasoning that the human check belongs on the writes. Overruled, and
    correctly: the GET returns the registry URL plus a live status block,
    which for a private catalog is exactly the pointer an agent should not be
    able to enumerate. The explicit reject_agent_principal on PUT/DELETE is
    kept as belt-and-braces.

For the reviewer — one thing I found but did not fix

Dev's new copy import intent gates fork_to_own: required from
get_github_template(template_lookup) — the catalog read. That is the
same shape as S2 above: the catalog read uses the global platform PAT off the
default branch through a 600 s cache, so a private required template reads
as absent (GitHub answers 404, not 403) and the gate passes. It is materially
less severe on that path than on the fork path — a copy is a detached
snapshot with no GitHub env, no PAT and no push, so the outcome S2 prevents
(the agent bound to the shared upstream) cannot occur; what is lost is the
user-owned remote, not containment. Left alone deliberately: it is dev's
code, fixing it here is scope drift, and it deserves its own issue. Flagging
it because it is the seventh instance of "the create path is never one call
site" and worth a decision rather than a silent inheritance.

Docs

Requirements TMPL-002 (requirements/core-agent.md §4.2.2), architecture.md, new feature-flows/template-registry.md + index row, platform-settings.md / library-page.md / template-processing.md / scheduling.md cross-refs, and three learnings.md entries for the transferable classes.

Ship prerequisite (not code)

A valid document — possibly empty (version: 1 / templates: []) — must exist at the default URL before or with the release. Day-one behaviour is then "fetch succeeds, zero entries, catalog unchanged, no warnings", and publishing the curated fleet becomes a pure content edit.

Named residuals

No signature/provenance verification of the registry document; no allowlist on which repo owners a registry may list; DNS rebinding not closed (validate-then-connect TOCTOU — accepted for v1: admin-and-human-set URL, parsed into a display-only allowlisted record, never reaching a deserialize path). The first two belong to the private/per-customer-catalog phase, where the trust model is genuinely different.

🤖 Generated with Claude Code

@github-actions

github-actions Bot commented Aug 6, 2026

Copy link
Copy Markdown

⚠️ Nightly unit-suite check skipped — merge conflict against dev.

Resolve by running git merge dev locally and pushing the result. The next nightly run will re-test once the conflict is gone.

AndriiPasternak31 and others added 15 commits August 9, 2026 18:03
Rule of Engagement #1 — requirements land before implementation.

New §4.2.2 in core-agent.md, placed immediately after §4.2.1 because the
registry is a new *source* for the seam TMPL-001 documents: a reader who lands
on 4.2.1 must find it in the next paragraph, not in another file. §4.2.1's
"None = use defaults" sentence gets the one-line cross-reference that keeps it
true.

Two things the entry states plainly rather than comfortably:

- `repo` is a capability pointer. It is literally true that the four
  allowlisted fields only change which repos are listed and how they are
  labelled/ordered; as a security statement that is misleading. Choosing the
  repo chooses which template.yaml Trinity fetches and trusts, and that
  document declares mcp_servers, credentials, schedules, data_paths,
  persistent_state and fork_to_own. The allowlist bounds the direct blast
  radius, not the indirect one.

- The honest GitHub cost. A non-empty registry re-introduces the per-repo
  metadata fetches #1931 had driven to zero: workers x windows/hr x entries.
  On a PAT-less install that exceeds the 60/hr anonymous budget above ~5
  entries, which is exactly the precondition that makes the fork_to_own
  fail-open reachable.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>
The TWO ALIAS POLICIES docstring says a "template catalog entry" may
legitimately anchor a repeated block, and that clause reads as an argument for
giving the remote registry a BUDGET policy. It is not one — the only shipped
BUDGET caller is load_template_yaml, a per-repo template.yaml, which really can
anchor a repeated block. The remote index cannot: it is a flat list of unique
entries carrying one pointer and three display scalars each.

Amend the clause so the next author cannot make the same misread, and add
load_template_registry_yaml() pinning REJECT + the 256 KiB cap at the utils
layer — the same reason load_template_yaml exists, so the decision is never
relitigated at a call site.

Duplicate-key rejection is load-bearing for this document specifically: a
registry with two `templates:` keys would silently last-wins, showing one
catalog to the human editing the file and serving another to Trinity.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>
TEMPLATE_REGISTRY_URL / TEMPLATE_REGISTRY_ENABLED on the OPERATOR_INTAKE_ENABLED
shape, plus validate_template_registry_url().

Two choices worth their comments:

The switch is deliberately NOT settings_service._resolve_bool_flag. That
helper's env leg is opt-in only ("true"/"1"/"yes" -> True, anything else falls
through to `default`), so with default=True it would silently swallow
TEMPLATE_REGISTRY_ENABLED=false and ship a kill switch that does nothing —
#1039's inert-by-obscurity class, caught before a line of it was written.

The validator is a sibling of validate_skills_library_url, not a reuse: that one
is github.com-only, which is right for a clone target and wrong for a registry
an operator may self-host. What carries over is the perimeter check; what is new
is refusing userinfo outright rather than stripping it (a stripped credential
gets persisted into a settings row and echoed through a status payload) and
refusing an unresolvable host rather than deferring, since unlike a later git
clone nothing downstream will fail loudly on our behalf.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>
The fetch/parse/cache half. Never raises; every failure returns [].

Fail-open here is structural, not an except branch: get_all_templates() returns
local + github, local needs no network, github is empty by default, and this
module can only ADD to github. So unreachable / 5xx / timeout / malformed /
bombed / oversize / redirected / empty all reduce github toward [], which is the
already-shipping default state of the product. The except layers are a second
layer on top, because fail-open must not depend on this module being bug-free.

Decisions that are load-bearing and easy to undo by accident:

- The byte cap is enforced on bytes RECEIVED, not on Content-Length, which is
  absent on chunked responses and trivially lied about. resp.text on a 10 GB
  body OOMs the worker before any parse-time cap can act, so the transport
  ceiling is the gate and the parser's max_bytes is the belt.

- follow_redirects=False is a security control. A URL that passed the SSRF gate
  and then redirects is a bypass; a redirect is a fetch failure.

- TTL is 3600s + jitter, deliberately NOT aligned with the 600s per-repo cache.
  Aligning them is a correlated thundering herd, not a shared rhythm: one expiry
  fires the registry fetch and N per-repo GitHub fetches in the same instant,
  and --workers 2 drift into phase. It is also the cheapest lever on the
  anonymous GitHub budget, so it is doing security work, not tidiness.

- Serve-stale is capped at 7 days. Unbounded stale keeps a de-curated, renamed
  or compromised repo listed indefinitely while the operator sees a catalog that
  still renders — no signal at all.

- Invalidation is a generation counter read at cache-hit time, not a per-process
  clear. A per-process clear half-applies under --workers 2, and a
  nondeterministic setting is worse than a slow one. Coupled to the TTL raise;
  the two must not be split.

Found while smoke-testing the parser: `../evil` matches all four copies of the
owner/repo regex, because `.` is inside the character class. That breaks the one
invariant the catalog card rests on — the id would render "../evil" while both
the API and clone URLs normalize to a different repo. This gate now refuses dot
segments explicitly and is deliberately stricter than its three siblings, which
share the hole on paths reachable only by hand-typed ids.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>
…k gate closed

Two changes that only make sense together.

get_all_templates() was never the only resolver. get_github_template() resolves
the same repo list for GET /api/templates/{id} and for agent creation
(crud._resolve_github_repo_and_pat), and its ladder ended in a dynamic
fallthrough calling _build_template with no override dict at all. Landing the
registry in one of them would have listed a template as "Cornelius - your second
brain" and resolved it by id as "cornelius" - and under a rate limit the detail
view degrades to the repo basename, so the hardening the registry buys would not
have reached the detail path. Both now share one ladder; a test pins list,
detail and create to it. learnings.md 2026-07-10, on schedule.

The second change is why the first one matters. An unreadable template.yaml and
an absent one were the same value: _fetch_template_yaml_result already
distinguishes them and the catalog wrapper threw the reason away one frame below
the code that computed it. So a 403 produced fork_to_own: None, `== "required"`
was False, and creation bound the agent to the shared upstream template repo
instead of a user-owned copy. Silent, and the thing in the wrong place is the
user's knowledge base.

That bug is pre-existing. This feature is what makes it expected rather than
theoretical: it re-introduces per-repo fetches on a default install, ships
default-on, and its own arithmetic puts a PAT-less install over GitHub's 60/hr
anonymous limit above ~5 listed repos - while the fleet the registry exists to
serve very likely includes the fork_to_own template.

The reason is now cached alongside the metadata and surfaced as
metadata_unavailable, and creation refuses (503, retryable) rather than
guessing. Scoped to the branch that is unsafe: a caller who IS forking gets a
user-owned repo whatever the template declares, so an outage does not block
them. A clean 404 stays "absent", so a repo that ships no template.yaml creates
as it always has.

Also here, because it is the same builder: priority becomes overridable, which
is the only dimension of "curate freely - feature, order, add, deprecate" that
had no mechanism.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>
Same shape as /api/settings/github-templates deliberately — the registry is a
new source for that seam, not a second settings idiom. Registered before the
/{key} catch-all (Invariant #4), verified by inspecting the router's own route
order rather than by reading it.

reject_agent_principal on both writes is not optional. assert_admin answers what
role, never whether this is a human: get_current_user resolves an agent-scoped
MCP key to its owner carrying the owner's role, so on a default admin-owned
install any agent's injected TRINITY_MCP_API_KEY passes a bare admin gate
(trinity-ops-agent#232). The consequence here is total — an agent could repoint
the platform's template registry at a URL it controls and every operator
browsing templates would see its catalog.

The catch-all blocks all four registry keys, on PUT *and* DELETE. PUT because
the generic route takes an unvalidated Dict[str, str], which would leave the
SSRF gate one request away from bypass. DELETE because — unlike the #1644
retention acks, where deleting an ack re-arms a guard and fails safe — deleting
template_registry_enabled reverts it to its default of ON, re-enabling egress an
operator deliberately switched off, and that route carries no human gate.
generation and lkg are blocked because they are the cache itself.

The status block on GET is part of the contract, not decoration: fail-open makes
every registry failure invisible in the catalog by design, so this is the only
place an operator can see that their registry 404s.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>
…ription

The panel is a new file specifically so Settings.vue's raw-color counts cannot
move — the ratchet only lets per-file counts shrink, and Settings.vue sits at 63
non-gray. It gains one import and one tag, neither carrying a class. Measured:
the new panel is 0 non-gray / 0 hex / 32 semantic tokens, and Settings.vue is
byte-identical to origin/dev at 63/832/1 (the gray drift vs the committed
baseline predates this branch).

The status block is the point of the panel, not decoration. Fail-open means a
broken registry looks exactly like a working empty one from the catalog, so this
is the only surface where an operator can see that their registry 404s. The
backend publishes a fixed lowercase code and never prose — a hostile server's
response text must not reach an admin's screen — so the explanations are ours,
keyed by code, and each one names the remedy.

Uses LoadFailed for a failed fetch and InlineError for a failed verb rather than
sharing one error line: "couldn't load the settings" and "couldn't save the URL"
point at different remedies, and principle 18 says a failed verb persists next
to the control rather than becoming a toast.

The MCP fix: create_agent's `template` description asserted that list_templates
"on a default install returns local templates only until an admin curates GitHub
repos in Settings". With a default-enabled registry that is false, and a wrong
tool description actively misleads a model. Description only — no parameter,
client method, type or behaviour change, so Invariant #13 stays satisfied
without touching the tool.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>
309 tests across five files. Every failure mode is driven through the real
parser and a real httpx client over MockTransport, and every assertion is on the
CATALOG OUTPUT — not on whether an except branch ran. A test that asserts the
except branch ran would still pass if that branch returned garbage.

The matrix: unreachable, read timeout, 404/403/500/503, redirect, oversize body,
lying Content-Length, malformed YAML, level-6 alias bomb, duplicate keys, HTML
captive portal, binary body, top-level list, future schema version, non-list
templates, empty body, empty registry — each asserted twice, once for "the
catalog equals the bundled floor" and once through the router's own sort, which
is where a non-int priority used to 500 the endpoint. Plus a registry service
that simply raises, because fail-open must not depend on it being bug-free.

Two tests exist to stop the matrix being vacuous: one pins that the real bundled
floor is non-empty (otherwise every "degrades to the floor" assertion is
trivially true), and one re-probes the lying Content-Length through a second
client to prove the header really said 12 while the body was 100 KB — otherwise
a future refactor could start trusting Content-Length and these would still be
green.

The F2 regression test was verified to be red without its fix: neutralising the
guard fails 10 of its 24 assertions.

The parity test encodes a real divergence rather than papering over it. `.` is
inside the shared owner/repo character class, so `../evil` matches all three
older copies of the pattern; the registry gate refuses dot segments and the test
pins BOTH halves — the shared corpus where all four agree, and the containment
that everything the registry accepts, the others accept. If somebody later
tightens those copies, the test fails and points at deleting the assertion
rather than leaving a stale comment.

tests/unit/pytest.ini overrides pyproject.toml, so asyncio_mode = auto does not
apply here and a bare `async def test_*` is collected and silently never
awaited. Everything is sync; the one async call under test is driven through an
explicit asyncio.run.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>
…istry

architecture.md x3, in place — the registry is one source feeding one existing
service, not a cross-cutting subsystem: the template_service catalog entry gains
the ladder, template_registry_service gets its own <=2-line catalog entry, and
the Platform Settings table gets the three endpoint rows.

The flow doc is standalone rather than a section inside platform-settings.md.
The plan named that as an escape hatch if the section ran past ~60 lines; it ran
to 495, because the fail-open matrix, the cache semantics and the fork_to_own
fix each need their own argument. So platform-settings.md gets a short section
with the three things a reader of THAT file needs, and the index gets a catalog
row — a new doc always gets one.

library-page.md's `GET /api/templates` row said the GitHub half was the
admin-configured list or config.py defaults. That becomes wrong on merge, so it
now names the three-tier ladder. The page itself is unchanged, which is the
point: registry entries are source: "github" and land in the existing grid.

platform-settings.md already carried the sentence "trinity-enterprise#14 will
repoint this seam". This change is what makes it past tense.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>
…estated

/sync-feature-flows found this and my own docs pass had missed it.
template-processing.md carried, as a Known Limitation:

  "fork_to_own: required enforcement is fail-open when the template.yaml
   metadata fetch fails (advisory gate; empty metadata -> flag unseen for that
   10-min cache window)"

That was an accurate description of a real defect, written down and left. It is
now false, and a stale limitation is worse than none — the next reader would
have designed around a gate that no longer behaves that way.

Replaced with what actually happens, keeping the old sentence quoted so the
history is legible: the fetch reason rides the metadata cache as
metadata_unavailable, the non-forking creation path refuses with a retryable
503, a clean 404 still means "declares nothing", and a caller who is forking is
never blocked. The trade-off is stated rather than buried — creation now depends
on GitHub API reachability where it previously depended only on git clone.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>
Three regressions the full unit run caught that the targeted runs could not.

1. safe_yaml.py is a BYTE-IDENTICAL vendored mirror into the agent server
   (Invariant #5, ent#314/#1965) and I edited only the canonical copy. The
   parity guard is exactly the CI mechanism that exists for this and it worked;
   re-copied. Worth noting the architecture doc's own warning applies here: a
   guard that walks only one tree is not a guard, and this one walks both.

2. get_all_templates() had moved onto a renamed bulk fetch
   (_fetch_all_metadata_results), which silently bypassed two existing test
   doubles — test_ent89's fence stub and test_1931's network stub — so both
   fell through to real code. _fetch_all_metadata keeps its name and its
   `repo -> metadata` return shape; the fetch reason rides _metadata_cache
   instead and is read back by _metadata_reason_from_cache. No caller pays a
   signature change, and routers/settings.py's direct call is untouched.

   The bulk path still submits the reason-preserving variant, deliberately: a
   cache entry written with reason=None for a repo whose fetch actually 403'd
   would tell the creation path "readable, declares nothing" for a full TTL —
   reopening the fork-gate bypass through the catalog's own cache.

3. Two test doubles updated where the seam genuinely moved rather than the code
   being wrong: test_ent89's _build_template stub was one parameter short (a
   short stub raises TypeError *inside* the fence that class exists to test, so
   the assertion failed for an unrelated reason), and test_1931's stub set now
   includes _fetch_template_yaml_logged — without it the counter-test silently
   stops counting, which is the failure mode that test was written to prevent.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>
…object

43 of my own tests passed in isolation and failed under the full run — the exact
trap test_ent89_template_schedules.py documents, walked into anyway.

Both consumers resolve the module lazily, at call time: template_service's
`from services.settings_service import get_github_templates` and the registry
service's `from services.settings_service import settings_service` each read
sys.modules by key. Patching an attribute on a separately-imported reference
works right up until an earlier file has swapped the module object, after which
the stub is silently ignored.

The resulting failure was worse than confusing, it was inverted: with the stub
bypassed the real accessor read the real tmp SQLite database, found the durable
last-known-good a previous ent14 test had legitimately persisted, and served it
— so a test asserting "a connect error degrades to the floor" reported a
fail-open bug that does not exist. A green isolated run and a red full run
disagreeing about a security property is the worst shape this could have taken.

Fixed with monkeypatch.setitem on the exact key, and the stub built from a copy
of the real module's namespace so SettingsService and the key constants still
resolve through it.

Full unit suite: 7781 passed, 16 skipped, 0 failed.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>
… into both composes

config.py read TEMPLATE_REGISTRY_ENABLED and TEMPLATE_REGISTRY_URL from the
environment, and neither compose file injected them. Prod compose launches
standalone — no base merge, no env_file: on any service — and it is what every
deploy path uses, so the explicit environment: list is the only route into the
container. Both levers were inert on every real instance while working fine on a
laptop, where the shell environment reaches the process directly.

TEMPLATE_REGISTRY_ENABLED is the feature's hard kill switch: the documented
air-gap answer that no system_settings row may override. An inert one is not a
missing convenience — it is a default-ON feature making outbound requests with no
way to stop it.

The irony is the reason this is pinned rather than just fixed. The comment block
directly above the os.getenv call argues at length, and correctly, against
routing the flag through settings_service._resolve_bool_flag, because that
helper's opt-in-only env leg would "silently swallow
TEMPLATE_REGISTRY_ENABLED=false and ship an inert kill switch (#1039 class)".
The flag then shipped inert anyway, by the other route, ~15 lines away. Avoiding
a known failure mode in the layer you are looking at does not avoid it in the
layer you are not.

Sixth recurrence of the #1039/#1056 packaging-gap class (#1056 VOIP_*, ent#31
LOG_*, #1039, #1871 AGENT_LOG_*, #411 CANARY_*), so it gets a guard shaped like
test_canary_env_prod_parity.py — the guard for the fifth.

What the guard asserts, and why presence is the wrong property:
  - injection in BOTH composes; drift between them IS the bug
  - the ${VAR:-true} form, not a hardcoded `- TEMPLATE_REGISTRY_ENABLED=true`,
    which satisfies a presence check while re-breaking the switch
  - the URL's full non-empty default; a bare `:-` arrives set-but-empty,
    os.getenv returns "" instead of falling back, and the registry points at
    nothing (#1076) — strictly worse than absent, because it looks wired
  - compose and config.py defaults are equal, since two spellings of one default
    drift invisibly (the container always wins, so the code default becomes
    decorative while still reading as authoritative)
  - a meta-test that goes red on pre-fix content AND on the hardcoded revert

Verified by rendering rather than grepping: `docker compose config` shows both
vars on backend for each file, and TEMPLATE_REGISTRY_ENABLED=false propagates
through to "false". The guard was additionally proven by deleting the real prod
line and watching it go red — the first attempt at that used
`grep -v 'VAR=${VAR'`, where $ is an end-of-line anchor, so nothing was removed
and the suite reported a false green against an unmodified tree.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>
… gate, CGNAT

Three findings from the security review of this branch, each a case where the
control was present and correct one level above where the attack lands.

S1 — a byte ceiling on decoded bytes is not a byte ceiling.
_fetch_registry_text streamed under a 256 KiB running total, with a docstring
correctly explaining why Content-Length cannot be the gate and why resp.text on
a huge body OOMs the worker. Both true, both defeated one level down: a custom
headers= dict does not override httpx's default Accept-Encoding: gzip, deflate,
and iter_bytes() yields DECOMPRESSED chunks. A 199 KiB wire body — under the cap,
so the early abort passes it — inflated ~1030:1 before the running total was ever
consulted: 458 MB of transient allocation on the event-loop thread. The cap
bounded the decoded total, which is not the resource under attack; the peak is.
Now the ceiling counts wire bytes via iter_raw(), any Content-Encoding is refused
outright before the body is read (encoding_refused, named rather than folded into
bad_shape so gzip bytes hitting a UTF-8 decode don't report as a shape problem),
and Accept-Encoding: identity is sent as the polite half only — a request header
is a preference, never a control over a hostile server. Same body post-fix peaks
at 0.01 MB.

The harness hid it and then inflated it: httpx.Response(content=…) decodes and
buffers in the CONSTRUCTOR, so every fixture built a response the production
iter_raw() path cannot even read and that could only ever exercise iter_bytes().
The byte-ceiling tests were green against a shape incapable of expressing the
failure. Both transport fixtures now convert every mock to a real stream — a
transport test whose mock does not stream is not a transport test.

S2 — the fork_to_own gate read the catalog cache, not its own read.
The gate is correct in direction and was wrong in source: it consulted
gh_template["metadata_unavailable"], derived from the global platform PAT, off
the default branch, through a 600 s cache — while crud.py had already read the
same template.yaml one line earlier with the caller's resolved PAT and parsed
ref, cache-bypassed, for ent#89's schedules. ent#89's own docstring had written
the warning: "the exact silent-ignore class this feature exists to close,
reintroduced one layer up."

Both error directions followed. FALSE PASS: GitHub answers 404, not 403, for a
repo a token cannot see, so a private fork_to_own: required template readable
only by the creator's own PAT was classified absent, the gate passed, and the
agent bound to the shared upstream — the precise outcome the gate exists to
prevent, with no attacker involved. FALSE REFUSE: a poisoned shared cache entry
503'd a creator whose own PAT read the file fine, for a full TTL.

Fixing only the availability half would NOT have closed the false pass — for a
private template the catalog's fork_to_own VALUE is None for the same reason its
verdict is wrong, so the gate would sail past a `required` it still could not
see. Both inputs now come from _read_source_template, and `required` from EITHER
read enforces: a union, so this can only remove a false pass, never add one.
Costs zero extra GitHub calls, and the read that DECIDES is now made with the
same credentials as the clone that follows.

S3 — RFC 6598 shared address space (100.64.0.0/10) was admitted.
Python's ipaddress reports CGNAT as neither is_private nor is_reserved, so the
standard predicate stack passed it. Not reachable in Trinity's own topology
(both Docker networks are 172.28/16 and 172.29/16, which are is_private), but
several cloud providers address internal endpoints out of that range, so a
Trinity deployed there had a hole the same shape as 10.0.0.0/8. Both /10
boundaries are held public so a legitimate registry is not blackholed, and one
CGNAT record among public ones is enough to refuse.

Docs: requirements TMPL-002, architecture, template-registry + scheduling flows,
and three learnings entries for the transferable classes: a decoded-byte
ceiling; a gate reading the catalog's cached metadata instead of the
creation-path read standing one line above it; and the packaging class from the
preceding commit — its ledger entry rides here because learnings.md is a single
append-only file and the compose fix was committed on its own to stay
self-contained.

Full unit suite: 7851 passed, 17 skipped, 0 failed (pytest-randomly).

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>
Rebasing onto dev picked up two changes that landed under this branch and
moved what its own tests assert. Both are the other change being right.

- ent#15 (#2040) inserted an import-intent gate into `_resolve_template`
  ahead of the fork gate. Two `SimpleNamespace` config doubles predate the
  field, so `config.import_intent` raised AttributeError before reaching the
  assertion — a stub gap, not a production one. The fork/clone path and the
  S2 fail-closed gate are unchanged, and dev's `copy` intent carries its own
  `fork_to_own: required` refusal before its early return.

- #1890 made `require_admin` itself reject agent-scoped principals, closing
  the class at the gate rather than per-endpoint. This suite asserted an
  agent key could still READ the registry setting, on the reasoning that the
  human check belongs on the writes. That is now overruled, and correctly:
  the GET returns the registry URL plus a live status block, which for a
  private catalog is exactly the pointer an agent should not enumerate. The
  explicit `reject_agent_principal` on PUT/DELETE is kept as belt-and-braces
  — it states the intent locally and survives any relaxation of the gate.

Co-Authored-By: Claude Opus 5 <[email protected]>
@AndriiPasternak31
AndriiPasternak31 force-pushed the feature/ent14-remote-template-registry branch from b4034a9 to 2c6c41b Compare August 9, 2026 17:15
@AndriiPasternak31
AndriiPasternak31 marked this pull request as ready for review August 9, 2026 17:28
@AndriiPasternak31 AndriiPasternak31 self-assigned this Aug 9, 2026
@AndriiPasternak31
AndriiPasternak31 requested review from dolho and vybe August 9, 2026 17:28
Resolves the tests/registry.json conflict. Both sides were purely
additive — dev added the four #1823 timezone test files (#2071), this
branch adds the eight ent#14 registry test files — with no shared entry
modified and no entry removed on either side. Rebuilt from the git
stages rather than by splicing the markers: dev's file plus this
branch's eight new entries, 154 total, same indent=2 + trailing-newline
formatting.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified rather than taken on trust:

Invariant #5 (vendored mirror) — src/backend/utils/safe_yaml.py and docker/base-image/agent_server/safe_yaml.py are byte-identical (14,728 bytes, diff clean). The #1965/ent#314 parity guards pass (37 tests).

Config packaging (#1056 class) — TEMPLATE_REGISTRY_ENABLED and TEMPLATE_REGISTRY_URL are each wired into docker-compose.yml, docker-compose.prod.yml and .env.example. No inert lever on prod, which launches standalone. Build packaging is fine by construction — the backend Dockerfile now uses COPY src/backend/*.py, so #1033's explicit-name hazard no longer applies.

Security (the CSO diff's three findings, spot-checked independently)

  • S3 (CGNAT): 100.64.0.0/10 is not merely defined — it is enforced in the deny predicate at url_validation.py:428, with the correct rationale that Python's ipaddress reports it as neither is_private nor is_reserved. The test fixtures pin the exact boundary (100.63.255.255, 100.128.0.1, 99.64.0.1, 101.64.0.1).
  • S1 (decompression bomb): the fix is iter_raw() + Accept-Encoding: identity + rejecting a non-identity encoding rather than trusting the declared length. Correct — peak allocation is the resource under attack, not the total, and iter_bytes() is exactly the difference.

Tests — 374 pass across the eight ent#14 files; 230 more across the adjacent suites (test_1484_create_agent_characterization, test_fork_to_own, test_ent89_*, test_1931_*).

Merge resolution I pushed (f7bacbf)

Merged origin/dev in rather than rebasing, so a contributor's branch isn't force-pushed. Only tests/registry.json conflicted; every doc file auto-merged.

Both sides were purely additive — dev added the four #1823 entries (#2071), this branch adds eight ent#14 entries, with no shared entry modified and none removed on either side. Rebuilt from the git stages rather than splicing markers, preserving the file's indent=2 + trailing-newline formatting. Result: 154 entries, diff vs dev has zero deletions and exactly 8 additions. Whole-tree scan confirms no stray conflict markers.

Post-merge, all six PRs in this batch pass together: 540 passed, 2 skipped (ent#14 + #1823 + #2068 + #1897 + adjacent).

One non-blocking observation for a future issue: url_validation.py now holds two IP-deny predicates with different deny sets — validate_skills_library_url (L322: private/loopback/reserved/link-local) and validate_template_registry_url (L422–428: the same plus multicast, unspecified and CGNAT). Defensible today because the skills-library validator is locked to a github.com allowlist earlier in the same function, so the weaker set isn't reachable the same way. But if that allowlist is ever loosened the asymmetry becomes a bypass, and the two are far enough apart in the file that nobody will notice. Worth folding into one shared predicate eventually.

@vybe
vybe merged commit 1bbe2d1 into dev Aug 9, 2026
22 of 23 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants