Skip to content

feat(setup): first-run setup from an emailed link, with an email-bound claim - #4683

Merged
vybe merged 9 commits into
devfrom
feature/1312-setup-link-pinned-email
Nov 20, 2026
Merged

vybe merged 9 commits into
devfrom
feature/1312-setup-link-pinned-email

Conversation

@vybe

@vybe vybe commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

What

First-run setup can be opened from an emailed link, and the admin email can be bound to the claim (trinity-enterprise#1312).

  • Email-bound claim. The claim file /data/setup-claim may hold email-bound:<64 hex secret>. Setup then succeeds only for an email and a code where the code is the HMAC-SHA256 of the trimmed, lowercased email under that secret. Any other pair gets the one generic refusal and a failed-attempt record, before any password work. The email becomes the admin's sign-in identity. The instance-ID claim (PROV-018) is unchanged in every byte of behaviour; browser and unset modes are untouched.
  • Setup link. /setup#claim=<code>&email=<email> (the fragment form, which reaches no server) and /setup?claim=…&email=… both open the page with the values in place; the person only chooses a password. The values are cleared from the address bar on read and kept in memory only. A refused, incomplete or reloaded link shows one plain card with the next step. A used link lands on sign-in with a one-line notice.
  • /setup is not logged. nginx serves /setup in place with the access log off, no-store, and exactly one Referrer-Policy: no-referrer, so a query-form link cannot leak through the log or the Referer of follow-up requests.
  • Safer take and restore. After taking the claim file the request re-reads and re-verifies it, and a put-back never overwrites a claim written meanwhile (a provisioner may replace the claim on an unclaimed install).

Journey Impact: extends: J01

The J01 catalog entry gains the variant link-claim.

Provisioner contract

The binding text is PROV-020 in docs/memory/requirements/infrastructure.md: file path, owner and mode, the email-bound: line, the tmp + rename write, recycle by replacing the file, the stray taken copy, the .env marker that makes start.sh skip its own claim step, the link form, the reference computation and the test vector (asserted by tests/unit/test_ent1312_setup_link_claim.py).

Rulings carried (orchestrator, on the operator's behalf — plan file, 2026-11-20)

  • The email is bound by the claim itself rather than by a second file: an install is prepared before the email is known and nothing touches the server when the link is issued.
  • The fragment is the sent form; the query form is accepted; the nginx change stays regardless.
  • The link value survives a reload only as a non-secret flag; the code is never stored.
  • The "already set up" notice shows only when the visit carried link values.

Review + security

Review verdict: MERGEABLE AFTER FIXES; fixed in b210d69b5 (the documented and asserted test vector was not the shared one; the code was right). Four mutations red (no re-verify at take, overwriting restore, no failed-attempt record, try_files $uri /index.html). The review's security pass was a condensed inline one with no finding; the full pass runs at validation.

Tests

Backend: the two new files plus the setup neighbours, 226 passed. Frontend: the two new specs, the claim and meter specs and the ratchets, 79 passed. The full frontend unit run on the build agent had 6 files red from a stale shared node_modules (unresolved widget package, a vendored-copy byte check), none touched here: CI decides.

Before merge

  • nginx -t and a curl showing exactly one Referrer-Policy on /setup, on a real frontend image (no nginx on the build agent; the checks here are text and render-script tests).
  • A look at the link card and the login notice in light and dark.
  • The reviewer's repo-wide guard run did not finish in its time budget: this PR's Tier 1 is the first full run.

Handoffs

  • The bug-intake scrub that utils/scrub.js is kept aligned with lives in another repo and does not yet redact claim=.

🤖 Generated with Claude Code

Trinity Agent (trinity) and others added 5 commits November 20, 2026 06:30
The setup claim file /data/setup-claim gains a second form for an emailed
setup link: one line 'email-bound:<secret>' (64 lowercase hex). The request
must carry an email, and its claim code must equal
hex(HMAC-SHA256(secret, email.strip().lower())), so the claim binds the admin
email without a second file. A malformed secret refuses every setup. The
instance-ID form is unchanged.

The take re-reads the taken file and re-verifies it, so a claim replaced
between the check and the take is refused; restores use os.link so they never
overwrite a newer claim. Nothing logs the code, secret or email.

Mutations: dropping the take re-verify turns the recycle test red; a
clobbering rename restore turns both no-clobber tests red.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…#1312)

An emailed setup link may carry the setup code in its query string. The
default access log records the request line, and the page's
strict-origin-when-cross-origin policy sends the full URL as Referer on every
same-origin follow-up request, which the log also records.

/setup and /setup/ now get their own location in nginx-server.conf (included by
both listeners): access_log off, no-store, try_files /index.html =404 (served
in place, not by an internal redirect to = /index.html), and exactly one
Referrer-Policy: no-referrer. render-nginx.sh writes a copy of the served
security headers without their Referrer-Policy line for that location, and
refuses to start if the source does not set exactly one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…prise#1312)

On an instance-id install, /setup reads the setup code and admin email from
the link's fragment (/setup#claim=…&email=…) or query, clears them from the
address bar at once, hides the instance-ID field, shows the link's email
read-only and posts the code as claim_code. A refused, incomplete or reloaded
link shows one card naming the next step (never "instance ID"); only a
non-secret sessionStorage flag survives a reload, never the code. On any other
install the values are ignored but still cleared.

The router guard sends a /setup visit that carried link values on a completed
install to /login?notice=setup-complete, forwarding nothing of the link; Login
shows one status line for it. scrub.js redacts claim= in queries and fragments.

Mutations: removing the address-bar clear turns 6 link tests red; without the
guard change both link-redirect tests are red.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…(trinity-enterprise#1312)

PROV-020 in requirements/infrastructure.md states the emailed-link claim and
carries the one-column provisioner contract: claim file path, owner/mode, the
email-bound:<64 hex> line, tmp + rename write, recycle by replacing the file,
the .env marker that makes start.sh skip its own claim step, the fragment link
form, the code computation, a three-line reference and one test vector. The
test vector is asserted, as literals, through the endpoint.

Also: the link path in feature-flows/first-time-setup.md, the /setup log and
Referer closure in architecture/security.md, a user-docs paragraph, the J01
link-claim journey variant (JOURNEYS.md regenerated; the ent#580 variant pin
becomes a superset check), and registry entries for the four new test files.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rprise#1312)

Replace the PROV-020 test vector with the shared one (secret 00..1f, email
posted as ' [email protected] ', stored as [email protected]) in the contract and
the test. Document the stray setup-claim.<random> file a killed process leaves
between take and restore, in PROV-020 and the feature flow. No code change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@vybe vybe added the ui PR touches the frontend UI — triggers Playwright e2e tests label Nov 20, 2026
…se#1312)

The restore used os.link, which the repo-wide ent819 guard forbids. It now
creates the claim path exclusively (O_EXCL), copies the taken bytes with the
taken file's owner and mode, fsyncs, then removes the taken copy; an existing
path means a newer claim, so only the taken copy is removed.

Mutations: O_EXCL -> O_TRUNC and a plain-rename restore each turn both
never-overwrite tests red; dropping fchmod turns the new mode test red.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@trinity-ability

Copy link
Copy Markdown
Contributor

PR Validation Report — #4683 (tip d668223ab)

Verdict: APPROVE (with warnings, none blocking) · merge gate: Tier 1 ✅, journey-smoke + e2e ✅ on the PR, dev-ci ✅ on dev

Lane: the path classifier says B (routers/setup.py and the nginx files are not in the lane-C set). It was run at lane-C depth anyway, including a full security pass, because this is an unauthenticated route.

Category Status Notes
Base / size / commits ✅ dev, 23 files, 6 conventional commits
Closing keyword ✅ ➖ cross-tracker issue; the body names it in prose. The reviewer sets the private issue's status by hand after merge
Journey Impact ✅ check_journey_impact.py: PASSED (extends: J01)
Requirements / flows / user docs ✅ ⚠️ PROV-020, feature flow and user docs updated. Two docs are stale after d668223ab, see W1
Security greps §4.1–4.3, §4.10 ✅ no keys; the emails are test fixtures; the IPs are documentation ranges (198.51.100.0/24, 100.64.0.0/10); no mode flips or host paths
Config / build packaging ➖ no new env var, no new backend package
Audit rows §4.11 ➖ no gated write handler touched (unauthenticated first-run route)
Cross-surface §5.5 ➖ setup is a by-design MCP exclusion; no agent-server twin
Enterprise-docs guard ✅ 0 hits on added lines
Merge gate ✅ every check on d668223ab passes, incl. regression diff, schema-parity, verify-non-root, journey-smoke, e2e; dev-ci: success; no open dev-ci red issue

Security pass (diff-scoped)

  • Email-bound check and its order: ✅. _check_claim applies the per-IP rate limit, reads the file, then compares with hmac.compare_digest over the normalised hex. A blank email, another email, another secret's code, or a malformed or prefix-only line all fail the compare. Every failure records a failed attempt, then returns the one 403, before validate_password_strength and hash_password. The HMAC email and the stored sign-in email use the same normalisation (strip().lower()). A 64-hex secret is 2^256, behind the login rate limit.
  • Instance-ID path, browser, unset: ✅ unchanged in the compare. For a non-prefixed file, _expected_claim returns _normalise_claim(stored), the same as before. The missing or empty warning and the 403 are the same. browser and unset never reach the claim code. Two intended changes reach the instance-ID form too: the re-verify at take, and a no-clobber restore that copies the file instead of renaming it.
  • Take / re-verify / exclusive-create restore: ✅ for the paths that are tested, ⚠️ for the write-failure branch (W2, W3).
  • Link values after the page reads them: ✅. The code is held in component memory only. sessionStorage holds only a '1' flag. router.replace({path:'/setup'}) drops both the query and the fragment. The guard and the 403 path redirect to /login?notice=setup-complete and forward nothing. scrub.js now redacts #claim= / ?claim=. Backend logs carry only exception type names.
  • nginx /setup location: read from the config, not run. This host has no nginx binary and no Docker daemon. Reading the config, these hold: a regex location beats the location / prefix, and no earlier regex matches /setup. try_files /index.html =404 serves the file in place, so access_log off and this location's own add_headers apply. The server-level headers are not inherited, and the include is the rendered copy without its policy line, so exactly one Referrer-Policy: no-referrer is sent. Both listeners include the same server body. render-nginx.sh refuses to start unless the source has exactly one policy line (tested). Not verified: that nginx -t accepts the rendered config, and the live header count. I could not establish that any CI job loads the production nginx config: prod-image-smoke boots the backend only. The PR's own "Before merge" item (nginx -t plus a curl on a real frontend image) is still owed.
  • Out of the bundled nginx's reach: a query-form link still reaches any front proxy or tunnel ahead of it. That is why the fragment is the form the provisioner sends. Worth one line in PROV-020 if it is not already there.
  • No new high-confidence vulnerability.

Mutations (run here, each restored after)

Backend: test_ent1312_setup_link_claim.py plus test_3004_setup_instance_id_claim.py, 65 green at head.

mutation result
O_EXCL → O_TRUNC 2 red
drop fchmod 1 red
keep the taken copy after a restore 5 red
drop the re-verify at take 1 red
re-verify refuses without restoring 1 red
FileExistsError → return (skip the tidy) 1 red
claim check moved after the password checks 25 red
no failed-attempt record 18 red (link file alone)
write failure keeps the half-written file (drop the unlink) survives
write failure also deletes the taken copy survives
drop fsync survives (not testable in a unit test, expected)

Frontend: 5 specs, 39 green at head. All 11 valid mutations go red, 1 to 12 failing tests each. The mutations: no strip; strip keeps the hash; strip keeps the query; push instead of replace; the code stored in sessionStorage; strip only on claim installs; guard forwards the query; guard forwards the hash; the 403 path forwards the email; scrub drops #; scrub drops claim.

Warnings

  • W1 (docs drift): docs/memory/architecture/security.md:33 and docs/memory/feature-flows/first-time-setup.md:82 still say the restore uses a no-clobber os.link. d668223ab replaced that with an exclusive create plus copy, and only infrastructure.md was updated. These are two one-line fixes.
  • W2 (untested branch): nothing exercises the fchmod / write / fsync failure branch in _restore_claim, so both mutations of it survive. A test that patches os.write to raise would assert that no file is left at the claim path and the taken copy stays on disk.
  • W3 (the window the author named): the exclusive create succeeds, and then the write fails. If a provisioner renames a new claim onto the path before the unlink, that unlink deletes the new claim. The old claim then survives only as the taken copy. The result fails closed: no claim at the path, setup refused until the next recycle, and the provisioner believes it placed a claim. It needs a disk-write failure and a recycle at the same moment, so it is availability-only and not exploitable. It can be narrowed by unlinking only when os.stat(path).st_ino == os.fstat(fd).st_ino, or the PROV-020 contract can say a stray setup-claim.* means "recycle".
  • W4 (low, hypothesis): os.write's return value is not checked, so a short write without an error would be kept. On a regular file holding about 80 bytes this is practically unreachable. If it happened, an email-bound line would become malformed and refuse every setup (fail closed).
  • W5 (low, hypothesis): on the link path the email is the admin's sign-in identity, but the profile write that binds it still swallows errors ("never block setup on a profile write"). If it failed, setup would complete with no email bound. That is pre-existing behaviour, but it matters more here because the link person never sees the username.

Not run

The live nginx check (nginx -t, the header count, no access-log line); the light/dark look at the link card and the login notice; the suites the review and CI already ran (not repeated, per the request).

Trinity Agent (trinity) and others added 3 commits November 20, 2026 08:52
… every byte (trinity-enterprise#1312)

On a failed copy, _restore_claim now removes the claim path only while it
is still the file this call created (inode and device of the path match the
open descriptor), so a claim renamed onto the path meanwhile survives. The
write loops until every byte is written and treats no progress as a failure.

Mutations recorded, each red: unconditional unlink ->
test_a_restore_write_failure_never_removes_a_claim_renamed_on_meanwhile;
unlink dropped / return dropped ->
test_a_restore_whose_write_fails_leaves_no_file_and_keeps_the_taken_copy;
single unchecked write -> test_a_restore_completes_a_short_write and
test_a_restore_write_that_makes_no_progress_is_a_failure.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…d or fail cleanly (trinity-enterprise#1312)

The email-bound setup link's email is the admin's only sign-in identity, so
it is now bound in the same transaction as the password
(update_user_password(..., email=)). If that write fails, nothing was
written: the claim is restored (no-clobber), setup is not marked complete,
the person gets a retryable 503 rather than the claim refusal, and no
failed attempt is recorded. Every other mode keeps the separate profile
write that never blocks setup.

Mutation recorded: routing the email-bound form back through the separate
profile write turns test_email_bound_store_failure_fails_setup_cleanly_and_can_be_retried
and test_email_bound_password_and_email_are_one_write red.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…es the fragment (trinity-enterprise#1312)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@trinity-ability

Copy link
Copy Markdown
Contributor

PR validation, round 2: d668223ab..6a2811f26 (tip 6a2811f26)

Recommendation: APPROVE. W1–W5 from round 1 are answered, and the tests prove each answer.

c4dbce2: on the email-bound form, password and email are one write

  • Other callers are unchanged. The startup admin seed (database.py ×2), password_service.py and the instance-ID branch of setup.py pass no email. They take the untouched else branch and run the same SQL as before.
  • The census still holds. The email path writes through _update_user_row / _insert_user, the checked writers the census pins, inside one engine.begin(). test_ent720_email_binding.py was run as a whole file, together with test_ent1312_setup_link_claim.py, test_3004_*, test_2381_* and test_setup_operator_profile.py: 137 passed.
  • Both database tracks run the same SQLAlchemy Core code. update_user already uses this savepoint-in-transaction pattern on both.
  • An email held by another account: EmailInUseError rolls the transaction back, so the password is not written (new DB test). The route's outer handler then puts the claim back.
  • The 503 path records no failed attempt, returns a generic detail and logs only the exception type.
  • The instance-ID form still completes with a blank email, and also when the email write fails.

Mutations over the range

mutation result
inode/device check removed (unconditional unlink) red
compare st_dev only red
single os.write, no loop red
zero-progress guard <= 0 → < 0 test hangs: caught only by the timeout
email-bound path omits email= red
email_bound forced False red
503 path records a failed attempt red
password and email in separate transactions red
insert branch drops the email red

Security pass (range only)

No keys, real emails, host paths or mode changes. The two IPs in the diff are unchanged context lines in a requirements doc. No new route, env var or gated write handler.

Suggestions (non-blocking)

  1. If another account holds the email, the bound form returns the same 503 "please try again". For that address a retry can never succeed. Nothing is written and the claim is restored, so this is safe; only the message is off.
  2. The zero-progress write test catches its mutation by hanging rather than by an assertion. A bounded call or a write counter would turn it into a clean failure.

Not run

  • The email= path executed against PostgreSQL: there is no PG harness locally, and pg-migrations does not execute this function.
  • /review and /cso --diff over the range.

Merge gate: every check on 6a2811f26 is green (Tier 1 plus journey-smoke/e2e), and dev-ci on dev is success.

@vybe
vybe marked this pull request as ready for review November 20, 2026 14:31

@trinity-ability trinity-ability 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.

Approve, per my validation of d668223..6a2811f (round 2 report above) and of d668223 (round 1). Tip 6a2811f.

@vybe
vybe merged commit 820c9db into dev Nov 20, 2026
29 checks passed
vybe pushed a commit that referenced this pull request Nov 21, 2026
…4679/#4677 (#4680)

Accepted growth, ruled at merge-train Gate 2 (2026-11-21):
- routers/setup.py 6 -> 9 (ent#1329 setup terms, #4683/#4694/#4698)
- client_portal/work/service.py 8 -> 10, agent_service/autonomy.py 12 -> 14
  (#4679's batch prefetch reads: fewer queries, more call sites)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
vybe pushed a commit that referenced this pull request Nov 23, 2026
)

* test(backend): ratchet on blocking calls inside async def (#4674)

A sync db, Docker, HTTP or sleep call written directly inside an
`async def` runs on the event loop and blocks the whole worker.
scripts/ci/check_sync_on_loop.py counts them per file by parsing (never
importing) and compares with scripts/ci/sync_on_loop_baseline.json:

- a file's count may not exceed its entry;
- a file with no entry starts at zero;
- an entry above reality fails too, so a paydown lowers the baseline.

Today: 1,911 call sites in 831 async functions across 194 files
(db 1,363; through a module's own sync function 386; Docker 161).

Counted: db / core_db / _db / *.db method calls, get_agent_container,
list_all_agents_fast, agent_container_states, time.sleep,
subprocess.run, requests.*, and calls to the same module's plain defs
that make one. Not counted: plain def handlers, nested defs, and the
arguments of to_thread / run_in_executor / run_in_threadpool.

The ratchet runs in the unit suite (test_4674_sync_on_loop_ratchet.py).
The helper list is one constant, for trinity-dev#82 to share.

Related to #4674

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* test(backend): the ratchet does not pin the offenders it exists to remove (#4674)

Review finding. One test asserted that heartbeat_service's watch loop
and dependencies.py are in the scan. Those are exactly what #4674 goes
on to fix, so the test would have failed on the fix. It now asserts
only that the live scan sees both families. The backend is parsed once
per module instead of once per test.

Related to #4674

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* test(backend): regenerate the sync-on-loop baseline on current dev (#4674)

dev moved under the branch and changed two files' counts, which is the
ratchet doing its job on its own PR.

Related to #4674

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* merge-train: regenerate the sync-on-loop baseline on dev after #4676/#4679/#4677 (#4680)

Accepted growth, ruled at merge-train Gate 2 (2026-11-21):
- routers/setup.py 6 -> 9 (ent#1329 setup terms, #4683/#4694/#4698)
- client_portal/work/service.py 8 -> 10, agent_service/autonomy.py 12 -> 14
  (#4679's batch prefetch reads: fewer queries, more call sites)

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(backend): --write refuses to absorb growth into the baseline (#4674)

Regenerating the baseline wrote whatever the scan found, so a regeneration
could wave new blocking calls through and only the JSON diff showed it.
--write now prints each file whose count grew and writes nothing unless
--allow-growth is passed; a paydown is written as before.

Also: main() reads and writes the baseline path it names (the helpers'
default argument was bound at import), and the docstring no longer claims
a /code-health consumer that does not exist.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

---------

Co-authored-by: Claude Fable 5.2 <[email protected]>
Co-authored-by: trinity-ability <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ui PR touches the frontend UI — triggers Playwright e2e tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants