equipo: Task 22 review 2, renewals capped by the current deadline
The controller's admission record now carries the job's current deadline (AdmissionView.DeadlineInMS, counted from the answer, signed as before), so a deadline moved earlier after launch reaches the instance. The dispatcher's refresh and every renewal keep the earliest deadline seen, and a renewal reads the record outside its write transaction before issuing a credential capped by it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
12 files changed,
+231
−47
.rastrillo/budgets.txt+3 −3docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md+30 −1internal/equipo/chat/hosted_enrol.go+21 −0internal/equipo/chat/hosted_run.go+17 −9internal/equipo/hosted_enrol.go+61 −13internal/equipo/hosted_enrol_test.go+56 −1internal/hostedclient/client.go+2 −2internal/hostedclient/client_test.go+18 −0internal/hostedctl/admission.go+3 −2internal/hostedctl/admission_test.go+5 −4internal/hostedwire/hosted.go+13 −10internal/hostedwire/hosted_test.go+2 −2
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 081ff40b..52479163 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -15,7 +15,7 @@ time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial re |
| time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage. |
| time internal/equipo/hostedrun 60s Hosted slice 2 Task 21: TestDispatcherSimulation runs 200 seeds of the real chat store (SQLite) and dispatcher against a fake controller, with unlinked VMs that run to their 90-minute lifetime since review round 1, and one test drives the real controller over TLS for 90 simulated minutes; about 35 s of CPU in parallel subtests; measured 14 s on a 16 CPU docs-t1 under load 2.4; 60s covers a loaded 4 CPU runner. |
| -size internal/equipo 25256 8669 Preview, retry, merges, kept work, check-db, notifications, places, GitHub routes, installer, abilities, lookups, Mac waits, slice F codes, D1, probe details, Design's copy, /api/team; measured 24735. Hosted slice 2 Task 15 review 1: work.reason.pack_incomplete (pending); 24736. Task 17: work.reason.deps_conflict, deps_new_module, deps_missing, deps_too_large and token_renewal_failed (pending); 24741. Task 18: the owner setting "Run checks in a hosted VM" (config flag, routes, section, handler, four pending keys); 24825. Its review round 1: chatMe reports a roster denial as chat.ErrForbidden too (chatDenied); 24837. Task 21: the hosted dispatcher started only with EQUIPO_HOSTED_RUNNERS=1, execution on and a controller configured (EQUIPO_HOSTED_* config, RevokeRunner wiring), and the work.reason words for hosted_enrol_timeout, hosted_vm_lost and hosted_unavailable (pending); 24867. Task 22: hosted_enrol.go, a hosted VM's enrolment (POST /api/hosted/enrol) and its runner's challenge and renewal under /api/runner/v2 (the store methods over the runner and credential rows, the handlers, the routes only with EQUIPO_HOSTED_RUNNERS=1 and an admission reader), and mintRunnerCredential's lifetime and cap; 25248. Its tests (hosted_enrol_test.go: the routes through the whole application, and the runner's hosted.Start end to end through the test proxy) drive the unexported store, router and admission reader, so they live beside them and take the directory past the 8000-line test default; measured 8563 test lines. Task 22 review 1: the controller's deadline in the credential cap, and tests for a stale admission after a newer refusal, the first sighting and its window, code single use alone and the controller's deadline; 25256/8669. |
| +size internal/equipo 25304 8724 Preview, retry, merges, kept work, check-db, notifications, places, GitHub routes, installer, abilities, lookups, Mac waits, slice F codes, D1, probe details, Design's copy, /api/team; measured 24735. Hosted slice 2 Task 15 review 1: work.reason.pack_incomplete (pending); 24736. Task 17: work.reason.deps_conflict, deps_new_module, deps_missing, deps_too_large and token_renewal_failed (pending); 24741. Task 18: the owner setting "Run checks in a hosted VM" (config flag, routes, section, handler, four pending keys); 24825. Its review round 1: chatMe reports a roster denial as chat.ErrForbidden too (chatDenied); 24837. Task 21: the hosted dispatcher started only with EQUIPO_HOSTED_RUNNERS=1, execution on and a controller configured (EQUIPO_HOSTED_* config, RevokeRunner wiring), and the work.reason words for hosted_enrol_timeout, hosted_vm_lost and hosted_unavailable (pending); 24867. Task 22: hosted_enrol.go, a hosted VM's enrolment (POST /api/hosted/enrol) and its runner's challenge and renewal under /api/runner/v2 (the store methods over the runner and credential rows, the handlers, the routes only with EQUIPO_HOSTED_RUNNERS=1 and an admission reader), and mintRunnerCredential's lifetime and cap; 25248. Its tests (hosted_enrol_test.go: the routes through the whole application, and the runner's hosted.Start end to end through the test proxy) drive the unexported store, router and admission reader, so they live beside them and take the directory past the 8000-line test default; measured 8563 test lines. Task 22 review 1: the controller's deadline in the credential cap, and tests for a stale admission after a newer refusal, the first sighting and its window, code single use alone and the controller's deadline; 25256/8669. Review 2: a renewal reads the controller's admission record first, outside the transaction, and is capped by its current deadline; its tests (a deadline moved earlier after launch, the controller away or without a record); 25304/8724. |
| size internal/wire 9899 - Protocols 31 to 35 (facts, diffs, evidence, CI units, files, places), abilities, 36 lookups, 37 Mac Engineering, 38 Design, unproven and probe detail codes, 39 hosted runners (hosted.go: placement, hosted_pack and deps transfer limits, enrolment types); measured 9848. Task 15 opened TransferHeader.Valid to hosted_pack (inbound, base then candidate) and added ReasonPackIncomplete; 9860. Its review round 1 registered it in StepReasons; 9862. Task 17: the hosted worker's reasons (deps_conflict, deps_new_module, deps_missing, deps_too_large, token_renewal_failed) registered in StepReasons, and TransferHeader.Valid opened to deps with the hosted_pack rules (the worker accepts the bundle; Task 23 sends it); 9884. Task 21: ReasonHostedEnrolTimeout, ReasonHostedVMLost and ReasonHostedUnavailable, registered in StepReasons; 9899. |
| size internal/equipotest - 12693 GitHub connect value search, lifecycle and sweep-log contracts; Task 21 migration fixtures, Rastrillo asset contract, renderer archive link; measured 0/12693 source/test lines. |
| time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded); |
| @@ -60,7 +60,7 @@ perf GET /api/v1/assistant/snapshot skip Assistant person API: bearer-only JSON |
| perf GET /api/v1/assistant/messages skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen. |
| perf GET /api/v1/assistant/events skip Assistant event stream (Server-Sent Events), bearer-only and long-lived; not a screen. |
| perf GET /api/v1/assistant/abilities skip Assistant person API: bearer-only JSON for Base's Settings line, not a browser screen. |
| -size internal/equipo/chat 46903 20971 File facts/diffs, previews, merges, unfinished work, CI, receipts, Assistant files, places, abilities, lookups, go-aheads, Mac work, D1, Design specialists, grants, captures; 45093/18782. Hosted slice 2 Task 15: openHostedPack (the instance's send_pack for a hosted pack) and its test; 45105/18883. Its review round 1 added the report-ingestion test for pack_incomplete; 45105/18911. Task 18: hosted_setting.go (SetHostedChecks, hostedChecks, HostedSettings; owner only, roster in the transaction, audited) and its tests; 45208/19070. Its review round 1: the audit atomicity test; 45208/19113. Task 19: hosted_jobs.go (the hosted_jobs and hosted_challenges tables, HostedJob and its lifecycle: newHostedJob, the listed moves only, ended and failed only with stop proof or never-launched evidence, settleHostedJob once, hostedJobForRunner; each move audited in its transaction) and its tests, TestMigrationAdditive included; 45658/19577. Its review round 1: the never-launched evidence contract (HostedNeverLaunched, launch_by and launching_since, hostedLaunchReturned) and tests for it, settlement of unproven terminal records and audit atomicity; 45728/19739. Task 20: hosted_limits.go (per-person hosted limits, S2-9: hostedAdmit held in the write by a per-person lock row, hostedHoldFor, Allocate, hostedSettle at 4x the baseline, SetHostedLimits owner only with the roster, revision and audit in the transaction) and its tests; 46013/20214. Its coordinator ruling: a limit counts only while its setting owner is a current owner (defaults otherwise, checked in the admission transaction) and TestOwnerRaisesLimitRevoked; 46022/20284. Its review round 1: Allocate returns nothing for an empty or reversed span before widening, and its assertions; 46025/20290. Hosted slice 2 Task 21: placement on hosted VMs (placeHosted before the checks early return, its five rules), the bound runner's fits, Authorize by job identity, the hosted offline rule and withdrawal exemption, the hosted pack at dispatch, the step-terminal hook, and the dispatcher's store methods (HostedLive, HostedSweep, HostedLaunching with relaunch, HostedLaunched, HostedAdmitted, HostedFailed, HostedStopped, HostedNeverLaunched, HostedReplaces, PlaceHosted; end, settle, revoke, step moved on) in hosted_run.go, and hosted_place_test.go; 46665/20804. Task 21 review round 1: abandoned-intent evidence waits for the job's lifetime, the job keeps its lifetime and first running sight, admission takes the placing transaction's step attempt, provider-valid attempt IDs, HostedRunning, and the Retry, replacement-runner, cancelled-task and stopping-VM tests; 46709/20937. Its review round 2: TestHostedReplacesNeedsProof; 46709/20971. Task 22: hosted_enrol.go (the enrolment and renewal store steps inside the instance's write transaction: HostedClaimCode, HostedEnrolAdmit, HostedEnrolBind, HostedRunnerJob, HostedNewChallenge, HostedUseChallenge; hostedAdmitted shared with HostedAdmitted); its tests drive it through the instance's routes (internal/equipo); 46848/20971. Its review round 1: hostedAdmitted reports whether the record was kept, the enrolment records the first sighting and applies the window from it, and the launch view's deadline is kept (hosted_jobs.deadline, earliest wins); 46903/20971. |
| +size internal/equipo/chat 46932 20971 File facts/diffs, previews, merges, unfinished work, CI, receipts, Assistant files, places, abilities, lookups, go-aheads, Mac work, D1, Design specialists, grants, captures; 45093/18782. Hosted slice 2 Task 15: openHostedPack (the instance's send_pack for a hosted pack) and its test; 45105/18883. Its review round 1 added the report-ingestion test for pack_incomplete; 45105/18911. Task 18: hosted_setting.go (SetHostedChecks, hostedChecks, HostedSettings; owner only, roster in the transaction, audited) and its tests; 45208/19070. Its review round 1: the audit atomicity test; 45208/19113. Task 19: hosted_jobs.go (the hosted_jobs and hosted_challenges tables, HostedJob and its lifecycle: newHostedJob, the listed moves only, ended and failed only with stop proof or never-launched evidence, settleHostedJob once, hostedJobForRunner; each move audited in its transaction) and its tests, TestMigrationAdditive included; 45658/19577. Its review round 1: the never-launched evidence contract (HostedNeverLaunched, launch_by and launching_since, hostedLaunchReturned) and tests for it, settlement of unproven terminal records and audit atomicity; 45728/19739. Task 20: hosted_limits.go (per-person hosted limits, S2-9: hostedAdmit held in the write by a per-person lock row, hostedHoldFor, Allocate, hostedSettle at 4x the baseline, SetHostedLimits owner only with the roster, revision and audit in the transaction) and its tests; 46013/20214. Its coordinator ruling: a limit counts only while its setting owner is a current owner (defaults otherwise, checked in the admission transaction) and TestOwnerRaisesLimitRevoked; 46022/20284. Its review round 1: Allocate returns nothing for an empty or reversed span before widening, and its assertions; 46025/20290. Hosted slice 2 Task 21: placement on hosted VMs (placeHosted before the checks early return, its five rules), the bound runner's fits, Authorize by job identity, the hosted offline rule and withdrawal exemption, the hosted pack at dispatch, the step-terminal hook, and the dispatcher's store methods (HostedLive, HostedSweep, HostedLaunching with relaunch, HostedLaunched, HostedAdmitted, HostedFailed, HostedStopped, HostedNeverLaunched, HostedReplaces, PlaceHosted; end, settle, revoke, step moved on) in hosted_run.go, and hosted_place_test.go; 46665/20804. Task 21 review round 1: abandoned-intent evidence waits for the job's lifetime, the job keeps its lifetime and first running sight, admission takes the placing transaction's step attempt, provider-valid attempt IDs, HostedRunning, and the Retry, replacement-runner, cancelled-task and stopping-VM tests; 46709/20937. Its review round 2: TestHostedReplacesNeedsProof; 46709/20971. Task 22: hosted_enrol.go (the enrolment and renewal store steps inside the instance's write transaction: HostedClaimCode, HostedEnrolAdmit, HostedEnrolBind, HostedRunnerJob, HostedNewChallenge, HostedUseChallenge; hostedAdmitted shared with HostedAdmitted); its tests drive it through the instance's routes (internal/equipo); 46848/20971. Its review round 1: hostedAdmitted reports whether the record was kept, the enrolment records the first sighting and applies the window from it, and the launch view's deadline is kept (hosted_jobs.deadline, earliest wins); 46903/20971. Its review round 2: an admission record's current deadline is kept too (hostedAdmitted, for the dispatcher's refresh and the renewal's HostedRenewAdmit); 46932/20971. |
| perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}. |
| perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}. |
| perf GET /api/v1/connections/preference skip Connections slice 1 person API: bearer-only JSON for devices; the browser shows the preference on /conversation/connections. |
| @@ -86,4 +86,4 @@ perf GET /native/preview/exchange skip Rejects GET with 404; only a same-origin, |
| # branch uses an indexed primary-key lookup, one current-member/device check, |
| # and the same bounded cardView as the snapshot; no list scan or new route. |
| perf GET /api/v1/tasks/{id}/changes/diff skip Device-only bounded display patch JSON: indexed step/attempt lookup, 64 KiB patch and 128 KiB response, no Git or network work at read time; not an HTML screen. |
| -size internal/hostedctl 6049 10016 Hosted controller core plus its lifecycle simulation; split planned for slice 1b; measured 5313/8516 source/test lines after the Task 17 pre-flight review rounds (R36, R38 ref checks); slice 2 Task 2 wires the egress manifest snapshot and LaunchRequest.Validate into Launch (logic in ctlegress), and maps ErrServiceUnset to 503 service_unset; measured 5341/8729; slice 2 Task 3 replaces Config.Images with the certificate set (logic in hostedcert and ctlcert), keeps the certificate digest and launch-by time on each intent, enforces launch-by before saving and before every provider call (it gates the dispatch path, so it stays here), and adds the admission record and route; measured 5444/9119; Task 3 review round 1 returns ErrLaunchExpired to a Launch whose own intent expired during dispatch (binding certificates to provider image versions is in ctlcert); measured 5462/9279; round 2 reports the launch-by time whichever abandonment reason is given; measured 5465/9325; slice 2 Task 4 wires the proxy client CA and feed (logic in ctlproxy): the three proxy routes and their transaction (proxy.go), the proxy role, Config.ProxyCA, the BootstrapV2 launch payload with its proxy code minted at intent save, revocation on stop, proof and resume, the code window opened by the first running sighting, the silent-proxy check in the reaper pass and its metric; measured 5662/9340. Task 4 review round 1: the proxy code is derived (HMAC key in Config, stripped from the saved bootstrap, derived again at each provider call; a changed key abandons the intent), and silence alerts are delivered from the store; measured 5689/9355. Slice 2 Task 5 wires the operator routes (ops.go: certification launch, certificate list, reload, restart, alert test, status; candidates, reload and the certification attempt are in ctlops): Launch and CertLaunch share one launch path, a certification intent is gated at dispatch by its image still being a candidate, the restart hook answers 202, and the reaper keeps its last clean pass for the status; operator_test.go is the brief's; measured 5939/9749. Task 5 review round 1: the reload fetches through an injected Deps.Fetcher first (ctlops.FetchAndReload; the S3 fetcher is in the command), the status reads the audit under one lock, and operator_test.go gains a fake config bucket and the fetch, failure and snapshot tests; measured 5954/9907. Slice 2 Task 13 wires certification reports (logic in ctlcert/report.go and hostedcert): the cert-report proxy route, its transaction and the controller's own stop of the reported VM (proxy.go), the operator evidence route, the proxy header check and two error codes (http.go), the Handler's signing key kept for evidence (controller.go), the stop reason, and schema version 5; measured 6022/9907. Task 13 review round 1: the report's stop is recorded in the transaction that keeps its evidence (recordStop, split out of requestStop so both share it) and driven on a context the request's end does not cancel; measured 6037/9907. Round 2: the stop rule moves to schema version 6 (the migration list line wraps) with TestUpgradeFromVersion5 upgrading a database made at bec02feb; measured 6038/9990. Round 3: the upgrade test also starts from a116d330's version 5; measured 6038/9996. Task 21 ruling: Get and Admission answer a signed 404 absent for an attempt with no record at all (ErrAbsent), keeping the 403 for another key's attempt, and the tests that pin it; measured 6049/10016. |
| +size internal/hostedctl 6050 10017 Hosted controller core plus its lifecycle simulation; split planned for slice 1b; measured 5313/8516 source/test lines after the Task 17 pre-flight review rounds (R36, R38 ref checks); slice 2 Task 2 wires the egress manifest snapshot and LaunchRequest.Validate into Launch (logic in ctlegress), and maps ErrServiceUnset to 503 service_unset; measured 5341/8729; slice 2 Task 3 replaces Config.Images with the certificate set (logic in hostedcert and ctlcert), keeps the certificate digest and launch-by time on each intent, enforces launch-by before saving and before every provider call (it gates the dispatch path, so it stays here), and adds the admission record and route; measured 5444/9119; Task 3 review round 1 returns ErrLaunchExpired to a Launch whose own intent expired during dispatch (binding certificates to provider image versions is in ctlcert); measured 5462/9279; round 2 reports the launch-by time whichever abandonment reason is given; measured 5465/9325; slice 2 Task 4 wires the proxy client CA and feed (logic in ctlproxy): the three proxy routes and their transaction (proxy.go), the proxy role, Config.ProxyCA, the BootstrapV2 launch payload with its proxy code minted at intent save, revocation on stop, proof and resume, the code window opened by the first running sighting, the silent-proxy check in the reaper pass and its metric; measured 5662/9340. Task 4 review round 1: the proxy code is derived (HMAC key in Config, stripped from the saved bootstrap, derived again at each provider call; a changed key abandons the intent), and silence alerts are delivered from the store; measured 5689/9355. Slice 2 Task 5 wires the operator routes (ops.go: certification launch, certificate list, reload, restart, alert test, status; candidates, reload and the certification attempt are in ctlops): Launch and CertLaunch share one launch path, a certification intent is gated at dispatch by its image still being a candidate, the restart hook answers 202, and the reaper keeps its last clean pass for the status; operator_test.go is the brief's; measured 5939/9749. Task 5 review round 1: the reload fetches through an injected Deps.Fetcher first (ctlops.FetchAndReload; the S3 fetcher is in the command), the status reads the audit under one lock, and operator_test.go gains a fake config bucket and the fetch, failure and snapshot tests; measured 5954/9907. Slice 2 Task 13 wires certification reports (logic in ctlcert/report.go and hostedcert): the cert-report proxy route, its transaction and the controller's own stop of the reported VM (proxy.go), the operator evidence route, the proxy header check and two error codes (http.go), the Handler's signing key kept for evidence (controller.go), the stop reason, and schema version 5; measured 6022/9907. Task 13 review round 1: the report's stop is recorded in the transaction that keeps its evidence (recordStop, split out of requestStop so both share it) and driven on a context the request's end does not cancel; measured 6037/9907. Round 2: the stop rule moves to schema version 6 (the migration list line wraps) with TestUpgradeFromVersion5 upgrading a database made at bec02feb; measured 6038/9990. Round 3: the upgrade test also starts from a116d330's version 5; measured 6038/9996. Task 21 ruling: Get and Admission answer a signed 404 absent for an attempt with no record at all (ErrAbsent), keeping the 403 for another key's attempt, and the tests that pin it; measured 6049/10016. Task 22 review 2: Admission answers the job's current deadline (DeadlineInMS, counted from the answer) so the instance caps hosted credentials by a deadline moved earlier after launch, and its assertion; measured 6050/10017. |
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md| index 744d8695..02c658b7 100644 |
| --- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| +++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| @@ -1739,4 +1739,33 @@ Mutations (Edit tool, restored, brief's command green after): |
| Green: the brief's command passes (6.3 s). Also passing: the whole `./internal/equipo/chat` (25.3 s, `TestMigrationAdditive` included), `./internal/equipo/hostedrun` (14.4 s), `personapi`, `setup`, the hostedclient import guard, `./internal/equipotest -run 'Migration|Schema|TestRunnerAppCSRF'`, and `./internal/equipo -run 'Migration|Schema'`. `make migration-check budget build vet` exits 0. Budgets: `internal/equipo` 25256/8669, `internal/equipo/chat` 46903 source, each with its reason. |
| -The instance reads the controller's deadline only from launch views (Launch, and Get while launching). A deadline the controller shortens later is not re-read, but the earliest one is never extended. |
| +The instance reads the controller's deadline only from launch views (Launch, and Get while launching). A deadline the controller shortens later is not re-read, but the earliest one is never extended. (Superseded by review round 2, below.) |
| + |
| +### Task 22 review round 2 (t22-r2.md: items 1, 3 and 4 addressed; finding 2, a deadline shortened after launch) |
| + |
| +The controller can move a job's deadline earlier after launch (`hostedctl/refresh.go:287`), and the instance now re-reads it: |
| +- **Wire:** `hostedwire.AdmissionView` gains `DeadlineInMS`, the time from the answer to the job's current deadline, 0 once it has passed. It is signed with the rest of the record. |
| + - `hostedctl.Admission` fills it from `deadline_t`: `until(now, deadline_t)`. |
| + - `hostedclient.Admission` refuses a negative value (`ErrBadResponse`). |
| +- **Store:** `chat.hostedAdmitted` keeps `asked + DeadlineInMS` for a record naming the job's launch and VM, whatever the record's age, earliest wins (`hostedDeadlineSeen`, now shared with the launch view). So the dispatcher's admission refresh each pass and the enrolment both keep the current deadline. |
| +- **Renewal:** `Store.HostedRenew` first finds the runner's job, then reads the admission record outside any transaction (`hostedAdmission`, shared with the enrolment; no answer is 503, absent or refused is 403). In the write transaction it records the record and its deadline (`chat.Store.HostedRenewAdmit`: the job enrolled; a fresh record must show the certified VM running; an older one leaves the held one to decide). It then re-reads the job and caps the credential at `min(launch_by + lifetime, deadline)`. A refusal after the record keeps the record and the deadline. |
| + |
| +Tests: |
| +- `TestHostedCredentialCappedAtDeadline`: after a renewal capped at the launch view's +39m, the controller's deadline moves to +30m (at +20m). The next renewal expires at +30m and the job keeps +30m. Two dispatcher refreshes, with 5 minutes and then an hour left, keep +25m. |
| +- `TestRenewThroughFullMiddleware`: a renewal with the controller away is 503, and with no record 403. |
| +- `TestAdmissionRecordsCertDigest` (hostedctl): the answer carries the job's deadline, and a minute later a minute less. |
| +- `TestClientAdmissionVerified` (hostedclient): a signed `deadline_in_ms` arrives and a negative one is `ErrBadResponse`. |
| +- The hostedwire codec case includes the field. |
| +- The equipo tests' fake controller answers its current deadline from the fake clock. |
| + |
| +Mutations (Edit tool, restored, green after): |
| +- **328** the renewal's refresh skipped (`running, err := true, error(nil)` in place of `HostedRenewAdmit`). `CGO_ENABLED=0 go test ./internal/equipo -run TestHostedCredentialCappedAtDeadline -count=1`: exit 1, `hosted_enrol_test.go:705: credential {... ExpiresAt:2026-12-01 10:39:00 +0000 UTC ...} epoch 2 deadline 2026-12-01 10:39:00 +0000 UTC; want ... deadline 2026-12-01 10:30:00 +0000 UTC`. Restored. |
| +- **329** (extra) an admission record's deadline not kept (`if false && ...` in `hostedAdmitted`). Same command: the same failure at `:705` (10:39, want 10:30). Restored. |
| +- **330** (extra) the controller not filling the deadline. `CGO_ENABLED=0 go test ./internal/hostedctl -run TestAdmissionRecordsCertDigest -count=1`: exit 1, `admission_test.go:186: Admission = {... DeadlineInMS:0 ...}, want {...}`. Restored. |
| + |
| +Green: |
| +- The brief's command passes (6.3 s). |
| +- Also passing: `./internal/hostedctl/...` (9.7 s), `./internal/hostedclient`, `./internal/hostedwire`, `./internal/equipo/hostedrun` (17.2 s, simulation included), `./internal/equipo/personapi`, the whole `./internal/equipo/chat` (25.1 s), `./internal/runner/hosted`, `./internal/hostedproxy`, `./cmd/equipo-hosted-controller` and `./cmd/equipo-hosted-certify`. |
| +- `make migration-check budget build vet` exits 0. |
| + |
| +Budgets, each with its reason: `internal/hostedctl` 6050/10017, `internal/equipo` 25304/8724, `internal/equipo/chat` 46932. |
diff --git a/internal/equipo/chat/hosted_enrol.go b/internal/equipo/chat/hosted_enrol.go| index 5706981d..a555b245 100644 |
| --- a/internal/equipo/chat/hosted_enrol.go |
| +++ b/internal/equipo/chat/hosted_enrol.go |
| @@ -107,6 +107,27 @@ func (s *Store) HostedEnrolAdmit(tx *gorm.DB, attempt, launchID, vmRef string, a |
| return j, now.Before(seen.Add(HostedEnrolTimeout)), nil |
| } |
| +// HostedRenewAdmit records, before a renewal, the controller's admission |
| +// record a for the enrolled job attempt, asked at asked, with the job's |
| +// current deadline (the earliest is kept). It reports false when a was |
| +// recorded and does not show the job's certified VM running; a record |
| +// older than the one held leaves the held one to decide. A job not |
| +// enrolled is a refusal. |
| +func (s *Store) HostedRenewAdmit(tx *gorm.DB, attempt string, a hostedwire.AdmissionView, asked time.Time) (bool, error) { |
| + var j HostedJob |
| + if err := tx.Where("attempt_id = ?", attempt).First(&j).Error; err != nil { |
| + return false, err |
| + } |
| + if j.State != HostedJobEnrolled { |
| + return false, ErrForbidden |
| + } |
| + valid, accepted, err := s.hostedTx(tx).hostedAdmitted(j, a, asked) |
| + if err != nil { |
| + return false, err |
| + } |
| + return !accepted || valid && a.State == hostedRunning, nil |
| +} |
| + |
| // HostedEnrolBind binds the enrolling job attempt to the worker runner |
| // runnerID its VM enrolled as, with the machine key (base64url) that |
| // signs its renewals. |
diff --git a/internal/equipo/chat/hosted_run.go b/internal/equipo/chat/hosted_run.go| index e0296227..3ddcf834 100644 |
| --- a/internal/equipo/chat/hosted_run.go |
| +++ b/internal/equipo/chat/hosted_run.go |
| @@ -318,20 +318,21 @@ func (s *Store) HostedLaunched(ctx context.Context, attempt string, v hostedwire |
| if err != nil { |
| return err |
| } |
| - return t.hostedDeadlineSeen(attempt, v, asked) |
| + return t.hostedDeadlineSeen(attempt, v.DeadlineInMS, asked) |
| }) |
| } |
| -// hostedDeadlineSeen keeps the controller's deadline v gives for |
| -// attempt's job: asked plus v's deadline_in_ms. The controller counts it |
| -// from its answer, which comes after asked, so this is never later than |
| -// its deadline. An earlier deadline already kept stays: it is never |
| -// extended. |
| -func (t *txn) hostedDeadlineSeen(attempt string, v hostedwire.JobView, asked time.Time) error { |
| - if asked.IsZero() || v.DeadlineInMS < 0 { |
| +// hostedDeadlineSeen keeps the controller's deadline an answer gives for |
| +// attempt's job (a launch view's or an admission record's): asked, when |
| +// the request was made, plus the answer's deadline_in_ms. The controller |
| +// counts it from its answer, which comes after asked, so this is never |
| +// later than its deadline. An earlier deadline already kept stays: it is |
| +// never extended, and one the controller moves earlier is kept. |
| +func (t *txn) hostedDeadlineSeen(attempt string, inMS int64, asked time.Time) error { |
| + if asked.IsZero() || inMS < 0 { |
| return fmt.Errorf("%w: deadline for %s", ErrHostedTransition, attempt) |
| } |
| - at := asked.UTC().Add(time.Duration(v.DeadlineInMS) * time.Millisecond) |
| + at := asked.UTC().Add(time.Duration(inMS) * time.Millisecond) |
| return t.db.Model(&HostedJob{}).Where("attempt_id = ? AND (deadline IS NULL OR deadline > ?)", attempt, at).Update("deadline", at).Error |
| } |
| @@ -360,6 +361,13 @@ func (t *txn) hostedAdmitted(j HostedJob, a hostedwire.AdmissionView, at time.Ti |
| if a.AttemptID != attempt || !j.Live() || j.VMRef == "" || at.IsZero() { |
| return false, false, fmt.Errorf("%w: admission for %s", ErrHostedTransition, attempt) |
| } |
| + if a.LaunchID == j.LaunchID && string(a.VMRef) == j.VMRef { |
| + // The job's current deadline, whatever the record's age: the |
| + // earliest is kept. |
| + if err := t.hostedDeadlineSeen(attempt, a.DeadlineInMS, at); err != nil { |
| + return false, false, err |
| + } |
| + } |
| valid = a.CertValid && a.LaunchID == j.LaunchID && string(a.VMRef) == j.VMRef && a.Epoch == j.Epoch && a.CertDigest != "" && |
| (j.CertDigest == "" || j.CertDigest == a.CertDigest) |
| digest := j.CertDigest |
diff --git a/internal/equipo/hosted_enrol.go b/internal/equipo/hosted_enrol.go| index 2bbe4f6e..da5f8f90 100644 |
| --- a/internal/equipo/hosted_enrol.go |
| +++ b/internal/equipo/hosted_enrol.go |
| @@ -142,13 +142,9 @@ func (s *Store) HostedEnrol(ctx context.Context, q wire.HostedEnrolRequest) (run |
| if denied != nil { |
| return none, denied |
| } |
| - asked := s.runnerClock.Now().UTC() |
| - a, err := s.hostedAdmitter.Admission(ctx, job.AttemptID) |
| - switch { |
| - case errors.Is(err, hostedrun.ErrNotAdmitted): |
| - return none, ErrForbidden |
| - case err != nil: |
| - return none, fmt.Errorf("%w: hosted admission: %w", ErrUnavailable, err) |
| + a, asked, err := s.hostedAdmission(ctx, job.AttemptID) |
| + if err != nil { |
| + return none, err |
| } |
| var result runnerproto.HostedEnrolResponse |
| err = s.write(ctx, func(tx *gorm.DB) error { |
| @@ -200,6 +196,25 @@ func (s *Store) HostedEnrol(ctx context.Context, q wire.HostedEnrolRequest) (run |
| return result, nil |
| } |
| +// hostedAdmission reads attempt's admission record from the controller, |
| +// outside any transaction, and the time it was asked for (its deadline |
| +// counts from no earlier). The controller's signed absence or refusal is |
| +// ErrForbidden; no answer is ErrUnavailable, which the runner retries. |
| +func (s *Store) hostedAdmission(ctx context.Context, attempt string) (hostedwire.AdmissionView, time.Time, error) { |
| + asked := s.runnerClock.Now().UTC() |
| + if s.hostedAdmitter == nil { |
| + return hostedwire.AdmissionView{}, asked, ErrUnavailable |
| + } |
| + a, err := s.hostedAdmitter.Admission(ctx, attempt) |
| + switch { |
| + case errors.Is(err, hostedrun.ErrNotAdmitted): |
| + return a, asked, ErrForbidden |
| + case err != nil: |
| + return a, asked, fmt.Errorf("%w: hosted admission: %w", ErrUnavailable, err) |
| + } |
| + return a, asked, nil |
| +} |
| + |
| // hostedLiveJob is the job p's runner is bound to, at now: the runner's |
| // credential and its person current, the job enrolled with a valid |
| // certificate, before its deadline. |
| @@ -264,8 +279,11 @@ func (s *Store) HostedChallenge(ctx context.Context, p RunnerPrincipal) (wire.Ho |
| // /api/runner/v2/hosted/renew): q names p's runner and the job's current |
| // epoch, and carries an unused, unexpired challenge of that runner's |
| // signed by the machine key it enrolled with; the job is live. The |
| -// challenge is used and the credential lasts an hour, never past the |
| -// job's deadline. |
| +// controller's admission record is read first, outside any transaction, |
| +// and recorded with the job's current deadline (the controller may have |
| +// moved it earlier since launch); a fresh record must show the certified |
| +// VM running. The challenge is used and the credential lasts an hour, |
| +// never past the job's deadline as it now stands. |
| func (s *Store) HostedRenew(ctx context.Context, p RunnerPrincipal, q wire.HostedRenewRequest) (runnerproto.HostedEnrolResponse, error) { |
| var result runnerproto.HostedEnrolResponse |
| if len(q.Nonce) != hostedNonceSize || len(q.Signature) != ed25519.SignatureSize || q.RunnerID == "" { |
| @@ -274,19 +292,46 @@ func (s *Store) HostedRenew(ctx context.Context, p RunnerPrincipal, q wire.Hoste |
| if q.RunnerID != p.RunnerID { |
| return result, ErrForbidden |
| } |
| + var attempt string |
| err := s.write(ctx, func(tx *gorm.DB) error { |
| + _, j, _, err := s.hostedLiveJob(tx, p, s.runnerClock.Now().UTC()) |
| + attempt = j.AttemptID |
| + return err |
| + }) |
| + if err != nil { |
| + return result, err |
| + } |
| + a, asked, err := s.hostedAdmission(ctx, attempt) |
| + if err != nil { |
| + return result, err |
| + } |
| + var denied error |
| + err = s.write(ctx, func(tx *gorm.DB) error { |
| + running, err := s.Chat().HostedRenewAdmit(tx, attempt, a, asked) |
| + if err != nil { |
| + return hostedStoreError(err) |
| + } |
| + // From here a refusal keeps the record and the deadline. |
| now := s.runnerClock.Now().UTC() |
| runner, j, deadline, err := s.hostedLiveJob(tx, p, now) |
| + if errors.Is(err, ErrForbidden) { |
| + denied = err |
| + return nil |
| + } |
| if err != nil { |
| return err |
| } |
| pub, err := runnerproto.DecodeBytes(j.MachinePublicKey, ed25519.PublicKeySize) |
| - if err != nil || q.Epoch != j.Epoch || runnerproto.MachineKeyHash(j.MachinePublicKey) != runner.MachineKeyHash || |
| + if !running || j.AttemptID != attempt || err != nil || q.Epoch != j.Epoch || runnerproto.MachineKeyHash(j.MachinePublicKey) != runner.MachineKeyHash || |
| !ed25519.Verify(pub, wire.HostedRenewMessage(runner.ID, q.Epoch, q.Nonce), q.Signature) { |
| - return ErrForbidden |
| + denied = ErrForbidden |
| + return nil |
| } |
| - if err := s.Chat().HostedUseChallenge(tx, runner.ID, q.Nonce, now); err != nil { |
| - return hostedStoreError(err) |
| + if err := s.Chat().HostedUseChallenge(tx, runner.ID, q.Nonce, now); errors.Is(err, chat.ErrForbidden) { |
| + denied = ErrForbidden |
| + return nil |
| + } else if err != nil { |
| + return storeError(err) |
| } |
| cred, err := mintRunnerCredential(tx, runner, now, hostedCredentialLifetime, deadline) |
| if err != nil { |
| @@ -298,6 +343,9 @@ func (s *Store) HostedRenew(ctx context.Context, p RunnerPrincipal, q wire.Hoste |
| if err != nil { |
| return runnerproto.HostedEnrolResponse{}, err |
| } |
| + if denied != nil { |
| + return runnerproto.HostedEnrolResponse{}, denied |
| + } |
| return result, nil |
| } |
diff --git a/internal/equipo/hosted_enrol_test.go b/internal/equipo/hosted_enrol_test.go| index 53f69375..0f63f83b 100644 |
| --- a/internal/equipo/hosted_enrol_test.go |
| +++ b/internal/equipo/hosted_enrol_test.go |
| @@ -56,6 +56,10 @@ type fakeAdmitter struct { |
| // during runs while the call is in flight, before its answer. |
| during map[string]func() |
| calls int |
| + // deadlines are the controller's current job deadlines: an answer |
| + // carries the time from clock's now to its attempt's. |
| + deadlines map[string]time.Time |
| + clock *team.FakeClock |
| } |
| func (f *fakeAdmitter) Admission(_ context.Context, attempt string) (hostedwire.AdmissionView, error) { |
| @@ -75,6 +79,9 @@ func (f *fakeAdmitter) Admission(_ context.Context, attempt string) (hostedwire. |
| if !ok { |
| return hostedwire.AdmissionView{}, hostedrun.ErrNotAdmitted |
| } |
| + if d, ok := f.deadlines[attempt]; ok { |
| + v.DeadlineInMS = max(0, d.Sub(f.clock.Now()).Milliseconds()) |
| + } |
| return v, nil |
| } |
| @@ -105,7 +112,9 @@ func newHostedRig(t *testing.T, now time.Time, opts ...hostedJobOpts) *hostedRig |
| t.Fatal(err) |
| } |
| t.Cleanup(func() { d.Close() }) |
| - r := &hostedRig{s: NewStore(d), clock: team.NewFakeClock(now), adm: &fakeAdmitter{views: map[string]hostedwire.AdmissionView{}, errs: map[string]error{}, during: map[string]func(){}}} |
| + r := &hostedRig{s: NewStore(d), clock: team.NewFakeClock(now), adm: &fakeAdmitter{views: map[string]hostedwire.AdmissionView{}, errs: map[string]error{}, during: map[string]func(){}, |
| + deadlines: map[string]time.Time{}}} |
| + r.adm.clock = r.clock |
| r.s.runnerClock = r.clock |
| r.s.hostedAdmitter = r.adm |
| r.h = hostedApp(t, r.s, true) |
| @@ -157,6 +166,9 @@ func (r *hostedRig) vm(t *testing.T, n int, opts ...hostedJobOpts) *hostedRig { |
| o(&v.job) |
| } |
| v.rawWrite(t, func(tx *gorm.DB) error { return tx.Create(&v.job).Error }) |
| + if v.job.Deadline != nil { |
| + v.setDeadline(*v.job.Deadline) |
| + } |
| v.setView(func(a *hostedwire.AdmissionView) { |
| *a = hostedwire.AdmissionView{AttemptID: v.job.AttemptID, LaunchID: v.job.LaunchID, State: "running", VMRef: isolatedjob.Ref(v.job.VMRef), |
| Epoch: v.job.Epoch, CertDigest: "cd", CertValid: true} |
| @@ -180,6 +192,13 @@ func (r *hostedRig) setErr(err error) { |
| r.adm.errs[r.job.AttemptID] = err |
| } |
| +// setDeadline sets the controller's current deadline for the rig's job. |
| +func (r *hostedRig) setDeadline(at time.Time) { |
| + r.adm.mu.Lock() |
| + defer r.adm.mu.Unlock() |
| + r.adm.deadlines[r.job.AttemptID] = at |
| +} |
| + |
| // setDuring runs fn while the rig's job's admission call is in flight. |
| func (r *hostedRig) setDuring(fn func()) { |
| r.adm.mu.Lock() |
| @@ -575,6 +594,15 @@ func TestRenewThroughFullMiddleware(t *testing.T) { |
| // The renewed bearer renews in turn; a signature by another key, or |
| // a renewal naming another runner, does not. |
| ch = r.challenge(t, next.Credential.Token) |
| + // A renewal reads the controller's record first: no answer is a |
| + // temporary failure, an absent record a refusal. |
| + r.setErr(errors.New("connection refused")) |
| + if w := r.post("/api/runner/v2/hosted/renew", r.renewBody(next.Credential.RunnerID, r.job.Epoch, ch.Nonce), next.Credential.Token, ""); w.Code != http.StatusServiceUnavailable { |
| + t.Fatalf("renewal with the controller away: %d %s, want 503", w.Code, w.Body) |
| + } |
| + r.setErr(hostedrun.ErrNotAdmitted) |
| + refused(t, "a renewal the controller has no record for", r.post("/api/runner/v2/hosted/renew", r.renewBody(next.Credential.RunnerID, r.job.Epoch, ch.Nonce), next.Credential.Token, "")) |
| + r.setErr(nil) |
| _, other, _ := ed25519.GenerateKey(rand.Reader) |
| sig := ed25519.Sign(other, wire.HostedRenewMessage(next.Credential.RunnerID, r.job.Epoch, ch.Nonce)) |
| raw, _ := json.Marshal(wire.HostedRenewRequest{RunnerID: next.Credential.RunnerID, Epoch: r.job.Epoch, Nonce: ch.Nonce, Signature: sig}) |
| @@ -660,12 +688,39 @@ func TestHostedCredentialCappedAtDeadline(t *testing.T) { |
| ctl.setView(func(a *hostedwire.AdmissionView) { |
| a.LaunchID, a.VMRef, a.Epoch = view.LaunchID, view.VMRef, view.Epoch |
| }) |
| + ctl.setDeadline(hostedNow.Add(40 * time.Minute)) |
| ctlOut := ctl.enrol(t) |
| ctl.wantCredential(t, ctlOut, ctlDeadline) |
| r.clock.Advance(20 * time.Minute) |
| r.wantCredential(t, r.renew(t, out.Credential), deadline) |
| ctl.wantCredential(t, ctl.renew(t, ctlOut.Credential), ctlDeadline) |
| + |
| + // The controller moves the deadline earlier after launch (as its |
| + // restart reconciliation can): the renewal reads it, keeps it and is |
| + // capped by it. |
| + short := hostedNow.Add(30 * time.Minute) |
| + ctl.setDeadline(short) |
| + ctl.job.Deadline = &short |
| + ctl.wantCredential(t, ctl.renew(t, ctlOut.Credential), short) |
| + if j := ctl.jobRow(t); !j.Deadline.Equal(short) { |
| + t.Fatalf("kept deadline %v, want the controller's new %v", j.Deadline, short) |
| + } |
| + // The dispatcher's admission refresh keeps an earlier one too, and a |
| + // later answer never moves it back. |
| + refresh := func(in time.Duration) { |
| + t.Helper() |
| + a := hostedwire.AdmissionView{AttemptID: ctl.job.AttemptID, LaunchID: view.LaunchID, State: "running", VMRef: view.VMRef, Epoch: view.Epoch, |
| + CertDigest: "cd", CertValid: true, DeadlineInMS: in.Milliseconds()} |
| + if err := r.s.Chat().HostedAdmitted(context.Background(), ctl.job.AttemptID, a, r.clock.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + refresh(5 * time.Minute) |
| + refresh(time.Hour) |
| + if j := ctl.jobRow(t); !j.Deadline.Equal(hostedNow.Add(25 * time.Minute)) { |
| + t.Fatalf("kept deadline %v after the refreshes, want %v", j.Deadline, hostedNow.Add(25*time.Minute)) |
| + } |
| ch := r.challenge(t, out.Credential.Token) |
| r.clock.Advance(10 * time.Minute) |
| refused(t, "a renewal at the deadline", r.post("/api/runner/v2/hosted/renew", r.renewBody(out.Credential.RunnerID, r.job.Epoch, ch.Nonce), out.Credential.Token, "")) |
diff --git a/internal/hostedclient/client.go b/internal/hostedclient/client.go| index b9240ef2..e56f84ea 100644 |
| --- a/internal/hostedclient/client.go |
| +++ b/internal/hostedclient/client.go |
| @@ -277,8 +277,8 @@ func (c *Client) Admission(ctx context.Context, attempt string) (hostedwire.Admi |
| if err := c.call(ctx, "admission", http.MethodGet, p, nil, &a); err != nil { |
| return hostedwire.AdmissionView{}, err |
| } |
| - if a.AttemptID != attempt { |
| - return hostedwire.AdmissionView{}, fmt.Errorf("%w: admission: the record is for another attempt", ErrBadResponse) |
| + if a.AttemptID != attempt || a.DeadlineInMS < 0 { |
| + return hostedwire.AdmissionView{}, fmt.Errorf("%w: admission: the record is for another attempt or has no deadline", ErrBadResponse) |
| } |
| return a, nil |
| } |
diff --git a/internal/hostedclient/client_test.go b/internal/hostedclient/client_test.go| index 66d84360..2ade942d 100644 |
| --- a/internal/hostedclient/client_test.go |
| +++ b/internal/hostedclient/client_test.go |
| @@ -326,6 +326,24 @@ func TestClientAdmissionVerified(t *testing.T) { |
| if a, err := other.Admission(ctx, "a1"); !errors.Is(err, ErrBadResponse) || a != (hostedwire.AdmissionView{}) { |
| t.Fatalf("Admission answered for another attempt = (%+v, %v), want ErrBadResponse and nothing", a, err) |
| } |
| + |
| + // The job's current deadline arrives signed; a negative one is not a |
| + // deadline. |
| + for _, tc := range []struct { |
| + body string |
| + ok bool |
| + }{ |
| + {`{"attempt_id":"a1","state":"running","cert_valid":true,"deadline_in_ms":60000}`, true}, |
| + {`{"attempt_id":"a1","state":"running","cert_valid":true,"deadline_in_ms":-1}`, false}, |
| + } { |
| + c := newClient(t, fakeCtl(t, func(w http.ResponseWriter, nonce string) { |
| + signedAnswer(w, http.StatusOK, []byte(tc.body), nonce, keyCtl) |
| + }), keyInst, ctlPublic()) |
| + a, err := c.Admission(ctx, "a1") |
| + if tc.ok && (err != nil || a.DeadlineInMS != 60000) || !tc.ok && !errors.Is(err, ErrBadResponse) { |
| + t.Fatalf("Admission of %s = (%+v, %v)", tc.body, a, err) |
| + } |
| + } |
| } |
| // fakeCtl answers every request with whatever answer returns, given the |
diff --git a/internal/hostedctl/admission.go b/internal/hostedctl/admission.go| index 44b7500d..ea1db3f7 100644 |
| --- a/internal/hostedctl/admission.go |
| +++ b/internal/hostedctl/admission.go |
| @@ -19,7 +19,8 @@ const actionAdmissionRefused = "admission_refused" |
| // the digest of the certificate its launch was admitted under, and whether |
| // that certificate is valid at this moment (Config.Certs, re-verified on |
| // every call, never remembered from launch time). CheckedNS is the |
| -// controller time of the answer. Only the instance key that launched the |
| +// answer's controller time, DeadlineInMS the job's deadline as it stands |
| +// now, counted from the answer. Only the instance key that launched the |
| // attempt may read it; the refusals are Get's, audited as |
| // admission_refused. Admission makes no provider call. |
| func (c *Controller) Admission(ctx context.Context, by hostedwire.KeyID, attemptID string) (hostedwire.AdmissionView, error) { |
| @@ -31,7 +32,7 @@ func (c *Controller) Admission(ctx context.Context, by hostedwire.KeyID, attempt |
| } |
| a = hostedwire.AdmissionView{AttemptID: j.attempt, LaunchID: j.launchID, State: j.state, VMRef: isolatedjob.Ref(j.ref.String), |
| Epoch: j.epoch, Image: spec.Image, CertDigest: j.certDigest, CertValid: c.cfg.Certs.Valid(j.certDigest), |
| - CheckedNS: int64(now)} |
| + CheckedNS: int64(now), DeadlineInMS: until(now, T(j.deadlineT)).Milliseconds()} |
| return nil |
| }) |
| if err != nil { |
diff --git a/internal/hostedctl/admission_test.go b/internal/hostedctl/admission_test.go| index 80507311..236b3fe9 100644 |
| --- a/internal/hostedctl/admission_test.go |
| +++ b/internal/hostedctl/admission_test.go |
| @@ -181,13 +181,14 @@ func TestAdmissionRecordsCertDigest(t *testing.T) { |
| } |
| a := e.admission("att-1") |
| want := hostedwire.AdmissionView{AttemptID: "att-1", LaunchID: v.LaunchID, State: v.State, VMRef: v.VMRef, Epoch: v.Epoch, |
| - Image: imgA, CertDigest: certA(), CertValid: true, CheckedNS: int64(e.store.Clock().Now())} |
| - if a != want { |
| + Image: imgA, CertDigest: certA(), CertValid: true, CheckedNS: int64(e.store.Clock().Now()), DeadlineInMS: v.DeadlineIn.Milliseconds()} |
| + if a != want || want.DeadlineInMS <= 0 { |
| t.Fatalf("Admission = %+v, want %+v", a, want) |
| } |
| e.clk.AdvanceMono(time.Minute) |
| - if a := e.admission("att-1"); a.CheckedNS != want.CheckedNS+int64(time.Minute) { |
| - t.Fatalf("CheckedNS a minute later = %d, want %d", a.CheckedNS, want.CheckedNS+int64(time.Minute)) |
| + // The deadline is the job's as it stands, counted from each answer. |
| + if a := e.admission("att-1"); a.CheckedNS != want.CheckedNS+int64(time.Minute) || a.DeadlineInMS != want.DeadlineInMS-time.Minute.Milliseconds() { |
| + t.Fatalf("a minute later: CheckedNS %d deadline in %d ms, want %d and %d", a.CheckedNS, a.DeadlineInMS, want.CheckedNS+int64(time.Minute), want.DeadlineInMS-time.Minute.Milliseconds()) |
| } |
| newer := hostedcert.Sign(ctlcerttest.Snapshot(imgA, testHosts...), ctlcerttest.KeyID, ctlcerttest.Key, ctlcerttest.IssuedAt.Add(time.Hour)) |
diff --git a/internal/hostedwire/hosted.go b/internal/hostedwire/hosted.go| index 8b3542f7..c9d11b49 100644 |
| --- a/internal/hostedwire/hosted.go |
| +++ b/internal/hostedwire/hosted.go |
| @@ -168,17 +168,20 @@ func listener(p netip.AddrPort) bool { |
| // AdmissionView is the controller's answer to the creating instance's |
| // admission check for one attempt: the VM, its epoch and image, and |
| // whether the image's certificate is valid now. CheckedNS is controller |
| -// time. |
| +// time. DeadlineInMS is how long from the answer until the job's current |
| +// deadline (0 once it has passed): the controller may move it earlier |
| +// after launch, so the instance caps its credentials by the latest one. |
| type AdmissionView struct { |
| - AttemptID string `json:"attempt_id"` |
| - LaunchID string `json:"launch_id"` |
| - State string `json:"state"` |
| - VMRef isolatedjob.Ref `json:"vm_ref"` |
| - Epoch int64 `json:"epoch"` |
| - Image isolatedjob.ImageDigest `json:"image"` |
| - CertDigest string `json:"cert_digest"` |
| - CertValid bool `json:"cert_valid"` |
| - CheckedNS int64 `json:"checked_ns"` |
| + AttemptID string `json:"attempt_id"` |
| + LaunchID string `json:"launch_id"` |
| + State string `json:"state"` |
| + VMRef isolatedjob.Ref `json:"vm_ref"` |
| + Epoch int64 `json:"epoch"` |
| + Image isolatedjob.ImageDigest `json:"image"` |
| + CertDigest string `json:"cert_digest"` |
| + CertValid bool `json:"cert_valid"` |
| + CheckedNS int64 `json:"checked_ns"` |
| + DeadlineInMS int64 `json:"deadline_in_ms"` |
| } |
| // ProxyFeed is the controller's signed list of live launches for the |
diff --git a/internal/hostedwire/hosted_test.go b/internal/hostedwire/hosted_test.go| index a2640691..5fd2e51c 100644 |
| --- a/internal/hostedwire/hosted_test.go |
| +++ b/internal/hostedwire/hosted_test.go |
| @@ -169,9 +169,9 @@ func TestHostedWireNames(t *testing.T) { |
| into func() any |
| want string |
| }{ |
| - {AdmissionView{AttemptID: "a1", LaunchID: "l1", State: "running", VMRef: "vm-1", Epoch: 2, Image: img, CertDigest: "cd", CertValid: true, CheckedNS: 7}, |
| + {AdmissionView{AttemptID: "a1", LaunchID: "l1", State: "running", VMRef: "vm-1", Epoch: 2, Image: img, CertDigest: "cd", CertValid: true, CheckedNS: 7, DeadlineInMS: 8}, |
| func() any { return &AdmissionView{} }, |
| - `{"attempt_id":"a1","launch_id":"l1","state":"running","vm_ref":"vm-1","epoch":2,"image":"sha256:ab","cert_digest":"cd","cert_valid":true,"checked_ns":7}`}, |
| + `{"attempt_id":"a1","launch_id":"l1","state":"running","vm_ref":"vm-1","epoch":2,"image":"sha256:ab","cert_digest":"cd","cert_valid":true,"checked_ns":7,"deadline_in_ms":8}`}, |
| {ProxyFeed{Version: 1, Serial: 3, IssuedNS: 4, TTLMS: 5, Launches: []FeedLaunch{{LaunchID: "l1", AttemptID: "a1", VMRef: "vm-1", Epoch: 2, Services: svc, ProxyCodeHash: "ph", DeadlineNS: 6}}, Revoked: []string{"s1"}}, |
| func() any { return &ProxyFeed{} }, |
| `{"version":1,"serial":3,"issued_ns":4,"ttl_ms":5,"launches":[{"launch_id":"l1","attempt_id":"a1","vm_ref":"vm-1","epoch":2,"services":[{"host":"base.example.com","port":443,"class":"instance"}],"proxy_code_hash":"ph","deadline_ns":6}],"revoked":["s1"]}`}, |