Open native previews with single-use task-bound passes
38 files changed,
+2,535
−30
.rastrillo/budgets.txt+4 −3docs/api/equipo-v1.openapi.json+110 −1docs/superpowers/plans/2026-11-26-preview-pass.md+124 −0docs/superpowers/plans/CONTROLLER-REPORT-preview-pass.md+129 −0internal/equipo/app.go+4 −2internal/equipo/chat/tasks.go+15 −9internal/equipo/migrations/0108_preview_passes.sql+14 −0internal/equipo/migrations/schema.sql+15 −0internal/equipo/person_api.go+1 −0internal/equipo/personapi/handler.go+4 −0internal/equipo/preview_pass.go+240 −0internal/equipo/preview_pass_browser_test.go+122 −0internal/equipo/preview_pass_fixture_test.go+55 −0internal/equipo/preview_pass_http.go+184 −0internal/equipo/preview_pass_http_test.go+180 −0internal/equipo/preview_pass_models.go+3 −0internal/equipo/preview_pass_security_test.go+283 −0internal/equipo/preview_pass_store.go+162 −0internal/equipo/preview_pass_test.go+168 −0internal/equipo/preview_wrapper.go+3 −6internal/plan3test/person_api_contract_test.go+4 −0internal/plan3test/person_api_device_contract_test.go+1 −1internal/plan3test/preview_pass_contract_test.go+47 −0native/apple/Sources/EquipoActivity/Resources/Localizable.xcstrings+44 −0native/apple/Sources/EquipoKit/API/PreviewPass.swift+56 −0native/apple/Sources/EquipoKit/Presentation/TaskDetailModel.swift+4 −1native/apple/Sources/EquipoKit/Preview/PreviewBrowser.swift+87 −0native/apple/Sources/EquipoKit/Preview/PreviewFixture.swift+58 −0native/apple/Sources/EquipoKit/Preview/PreviewPresentation.swift+112 −0native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings+44 −0native/apple/Sources/EquipoKit/Session/EquipoSession.swift+3 −0native/apple/Sources/EquipoKit/UI/Screens/AppModel.swift+5 −1native/apple/Sources/EquipoKit/UI/Screens/TaskDetailScreen.swift+16 −1native/apple/Sources/EquipoMac/EquipoMacApp.swift+3 −2native/apple/Tests/EquipoKitTests/PreviewPassTests.swift+223 −0native/ios/Sources/EquipoPhoneApp.swift+2 −1native/scripts/check-parity.py+1 −1native/scripts/strings.json+5 −1
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 12bbad0a..9ab13b35 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -14,7 +14,7 @@ perf GET /* skip Unknown private paths render 404; this fallback contains no scr |
| time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial reruns measured 18.079s and 22.031s. Keep migration, recovery, accounting and concurrency assertions; 60s leaves 30 percent headroom above loaded CI. |
| 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. |
| -size internal/equipo 22600 - Stuck tasks' Retry and timeline (2026-11-25), merge_credential and amadan_unreachable copy (2026-11-26); measured 22600 source lines. |
| +size internal/equipo 23189 - Native preview pass issuance, exact bound grant exchange and wrapper-only authority (2026-11-26); measured 23189 source lines. |
| size internal/wire 7088 - Native task evidence fields, merge_credential and amadan_unreachable reasons (2026-11-26); measured 7088 source lines. |
| size internal/equipotest - 12017 Task 21 repairs historical migration and conversation fixtures after Plan 3, and the Rastrillo upgrade contract comparing served assets with what Assets serves; measured 0/12017 source/test lines. |
| time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded); |
| @@ -30,7 +30,7 @@ size internal/runner/provider 5731 - Fable follow-up: base and diagnostic gates, |
| time internal/plan3test 300s Initial cap for combined browser and runner acceptance; measure at both usable stops. |
| -size internal/plan3test - 11913 Paused-work, Assistant, stuck-task and merge credential strings in the release inventory (2026-11-26); measured 11913 test lines. |
| +size internal/plan3test - 11964 Native preview pass device contract alongside existing release inventory (2026-11-26); measured 11964 test lines. |
| time internal/runner/forge 20s Plan 3 CI repair measured 10.527s for the full package (controller CI 10.407s). |
| time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full package (controller CI 10.709s); |
| @@ -56,7 +56,7 @@ perf GET /api/v1/tasks/{id} skip Thin v1 person API: bearer-only JSON for device |
| perf GET /api/v1/assistant/snapshot skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen. |
| 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. |
| -size internal/equipo/chat 34839 9685 Native task hosted projection and stable completion time with regressions; measured 34839/9685 (2026-11-26). |
| +size internal/equipo/chat 34845 9685 Task read authority shared within the preview pass transaction; measured 34845/9685 (2026-11-26). |
| 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. |
| @@ -76,3 +76,4 @@ size internal/thintest - 35085 Stuck-task contracts plus paused-job fixed-clock |
| perf GET /api/v1/projects/{id}/merge-policy skip Merge authority person API: bearer-only JSON for devices; the browser reads the policy on /projects/{id}. |
| perf GET /api/v1/usage skip Thin v1 person API: bearer-only JSON for devices; the browser reads usage through /usage. |
| perf GET /api/v1/advice skip Thin v1 person API: bearer-only JSON for devices; the browser reads advice through /usage and /conversation. |
| +perf GET /native/preview/exchange skip Rejects GET with 404; only a same-origin, body-only POST can consume a preview pass. |
diff --git a/docs/api/equipo-v1.openapi.json b/docs/api/equipo-v1.openapi.json| index 7aca4bcf..b792ad36 100644 |
| --- a/docs/api/equipo-v1.openapi.json |
| +++ b/docs/api/equipo-v1.openapi.json |
| @@ -14245,6 +14245,90 @@ |
| "x-rejectUnknownFields": true |
| } |
| } |
| + }, |
| + "/tasks/{id}/preview-pass": { |
| + "post": { |
| + "operationId": "post_tasks_id_preview_pass", |
| + "summary": "Mint a one-use preview pass", |
| + "description": "Device bearer only. Returns an opaque 32-byte pass bound to the current person, device, task, candidate and preview deployment. Expires in at most 60 seconds. Exchange only by POST body at /native/preview/exchange on the instance origin; never put the pass in a URL. The exchange issues a host-only, Secure, HttpOnly, SameSite=Strict cookie scoped to GET /tasks/{id}/preview, expiring at grant_expires_at (at most 15 minutes, no renewal). No general browser sign-in. Unknown or wrong bindings are indistinguishable; valid-bound stale and expired states use preview_changed and preview_expired. Both device and IP are rate limited.", |
| + "security": [ |
| + { |
| + "personBearer": [] |
| + } |
| + ], |
| + "parameters": [ |
| + { |
| + "name": "id", |
| + "in": "path", |
| + "required": true, |
| + "schema": { |
| + "type": "string", |
| + "minLength": 1 |
| + } |
| + } |
| + ], |
| + "responses": { |
| + "401": { |
| + "$ref": "#/components/responses/unauthenticated" |
| + }, |
| + "default": { |
| + "description": "An error, with one of the codes in `Error`", |
| + "headers": { |
| + "Cache-Control": { |
| + "schema": { |
| + "const": "no-store" |
| + } |
| + } |
| + }, |
| + "content": { |
| + "application/json": { |
| + "schema": { |
| + "$ref": "#/components/schemas/Error" |
| + } |
| + } |
| + } |
| + }, |
| + "201": { |
| + "description": "Created", |
| + "headers": { |
| + "Cache-Control": { |
| + "schema": { |
| + "const": "no-store" |
| + } |
| + } |
| + }, |
| + "content": { |
| + "application/json": { |
| + "schema": { |
| + "$ref": "#/components/schemas/PreviewPass" |
| + } |
| + } |
| + } |
| + } |
| + }, |
| + "requestBody": { |
| + "required": true, |
| + "content": { |
| + "application/json": { |
| + "schema": { |
| + "type": "object", |
| + "additionalProperties": false, |
| + "required": [ |
| + "candidate_sha" |
| + ], |
| + "properties": { |
| + "candidate_sha": { |
| + "type": "string", |
| + "pattern": "^[0-9a-f]{40}$" |
| + } |
| + } |
| + } |
| + } |
| + }, |
| + "x-maxBytes": 4096, |
| + "x-rejectUnknownFields": true |
| + } |
| + } |
| } |
| }, |
| "components": { |
| @@ -14306,7 +14390,9 @@ |
| "question_ended", |
| "host_not_allowed", |
| "already_running", |
| - "offer_changed" |
| + "offer_changed", |
| + "preview_changed", |
| + "preview_expired" |
| ] |
| }, |
| "copy_key": { |
| @@ -24171,6 +24257,29 @@ |
| ], |
| "additionalProperties": false, |
| "x-go-type": "wire.StepHosted" |
| + }, |
| + "PreviewPass": { |
| + "type": "object", |
| + "additionalProperties": false, |
| + "required": [ |
| + "pass", |
| + "expires_at", |
| + "grant_expires_at" |
| + ], |
| + "properties": { |
| + "pass": { |
| + "type": "string", |
| + "pattern": "^[A-Za-z0-9_-]{43}$" |
| + }, |
| + "expires_at": { |
| + "type": "string", |
| + "format": "date-time" |
| + }, |
| + "grant_expires_at": { |
| + "type": "string", |
| + "format": "date-time" |
| + } |
| + } |
| } |
| }, |
| "responses": { |
diff --git a/docs/superpowers/plans/2026-11-26-preview-pass.md b/docs/superpowers/plans/2026-11-26-preview-pass.md| new file mode 100644 |
| index 00000000..06da9953 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-26-preview-pass.md |
| @@ -0,0 +1,124 @@ |
| +# Device preview pass |
| + |
| +Approved by the controller, 2026-11-26. Branch `preview/pass`, main `7c113ac8`. |
| +No implementation changes precede this note. |
| + |
| +## Contract and binding |
| + |
| +A tap on Preview calls bearer-authenticated |
| +`POST /api/v1/tasks/{id}/preview-pass` with the candidate SHA the person saw. |
| +Use the same current-person and task-read authority as `GET /tasks/{id}`, |
| +including team visibility. Recheck the active roster and originating device |
| +credential inside the write transaction. Refuse a stale candidate or a preview |
| +that the existing wrapper would refuse. Do not mint authority to approve an |
| +unsafe preview; an already approved preview keeps the wrapper's warning. |
| + |
| +Return an opaque, cryptographically random 32-byte base64url pass and an |
| +RFC 3339 UTC expiry, never a raw preview address. Store only its SHA-256 hash, |
| +with a separate non-secret audit ID. Bind the record to this instance, person, |
| +device credential and session epoch, task ID, candidate SHA, Preview step ID |
| +and attempt, and a fingerprint of that deployment (URL, digest, expiry and |
| +unsafe flag). The fingerprint prevents a redeployment of the same candidate |
| +from silently changing what the pass opens. The pass expires after 60 seconds, |
| +or earlier if the device credential or preview expires. Use the injected |
| +server clock throughout. A pass is a bearer capability; its person binding |
| +comes from minting, not a second sign-in or a submitted address at exchange. |
| + |
| +## Exchange and browser session |
| + |
| +The native web view POSTs the pass to the fixed same-origin path |
| +`/native/preview/exchange`. No pass in a URL, fragment, redirect, HTML or logs. |
| +The request has a bounded form body and the configured Origin; it passes the |
| +existing same-origin CSRF checks. There is no wildcard CSRF exemption and no |
| +GET exchange. Reject conflicting Origin/Referer/fetch-site headers, unexpected |
| +fields, and any device Authorization header here. A browser session cookie |
| +alone cannot mint or exchange a pass. |
| + |
| +In one transaction, hash and find the pass, conditionally consume it once, |
| +recheck membership/device/session epoch and the full preview binding, create a |
| +fresh random browser grant, and append the audit event. Concurrent exchanges |
| +have one winner. A known expired or stale pass is terminal, with no grant. |
| +DB or audit failures cannot issue a cookie. A lost exchange response requires |
| +a new pass; replay does not reproduce a grant. |
| + |
| +Success sets a host-only `__Secure-equipo-preview` cookie, Secure, HttpOnly, |
| +SameSite=Strict, with Path `/tasks/{id}/preview`, and redirects with 303 to |
| +that exact wrapper URL constructed by the server. No caller-provided redirect. |
| +The cookie contains a fresh opaque secret, stored hashed. Its lifetime is at |
| +most 15 minutes, capped by the device and preview expiries, without sliding |
| +renewal. All exchange/wrapper responses use no-store and no-referrer. |
| + |
| +This is an ordinary cookie-based browser session with restricted authority, |
| +implemented as an app-owned preview grant. It must not create a general |
| +Rastrillo/Oficina ID sign-in session. Cookie Path is only delivery scoping: |
| +server checks also permit exactly GET of the bound task's wrapper. No task |
| +page, API, event stream, attachment, other task, unsafe-preview POST or other |
| +mutation accepts it. General session authentication never recognizes this |
| +cookie. Keep normal browser sign-in behavior for requests without a preview |
| +grant; an invalid grant must not fall through to a broader signed-in session. |
| + |
| +## Wrapper, expiry and candidate changes |
| + |
| +Share the existing `previewWrapper` renderer and preview eligibility checks. |
| +Keep its CSP, iframe sandbox (`allow-scripts allow-same-origin`), origin |
| +validation, header warnings and referrer policy. Never load the raw origin as |
| +the top-level document. Each wrapper request rechecks the originating device, |
| +current roster, task visibility, expiry and exact deployment binding. It does |
| +not switch to a newer candidate. Candidate changes return 409 with the reviewed |
| +`evidence.candidate_changed` words; expired passes/grants/previews show the |
| +reviewed `question.expired` label. Other failures use existing reviewed words. |
| + |
| +Native drops the web view at expiry, sign-out or a task update that changes the |
| +binding, and revalidates when returning to the foreground. A new tap can mint |
| +a new pass. Server expiry prevents further wrapper reads; it cannot retract |
| +HTML already delivered to a browser or revoke the preview origin itself. |
| + |
| +## Native choice |
| + |
| +Use a dedicated WKWebView sheet on both platforms with a fresh |
| +`WKWebsiteDataStore.nonPersistent()` per presentation. WKWebView accepts a |
| +URLRequest, allowing the POST-body exchange, and isolates this cookie from |
| +ordinary browser sign-ins. Load the actual server response, not an HTML string |
| +or a native proxy, so the wrapper's response headers and iframe remain intact. |
| +SFSafariViewController's URL initializer is less suitable for this exchange. |
| + |
| +Extend the allowlisted opener with a typed preview destination: exact session |
| +origin plus the fixed exchange and wrapper paths for a validated task ID. |
| +Allow only those top-level navigations; reject unexpected redirects, popups, |
| +downloads and custom schemes. Keep the preview within its sandboxed child |
| +frame. No injected scripts, native script-message bridge, relaxed TLS, device |
| +bearer in WebKit, or automatic opening of blocked links. Test subframe loading |
| +separately so the navigation policy does not accidentally block the preview. |
| + |
| +Apple references: [WKWebView request loading](https://developer.apple.com/documentation/webkit/wkwebview/load(_:)-5siv6), |
| +[nonpersistent storage](https://developer.apple.com/documentation/webkit/wkwebsitedatastore/nonpersistent()), |
| +[Safari view controller](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller/). |
| + |
| +## Storage, audit and proof |
| + |
| +Add app-owned pass/grant tables via additive migration and register them in |
| +Models/Schema; do not modify framework session tables. Bound issuance per |
| +person/device/task, rate-limit exchange, and prune expired records. Audit mint, |
| +exchange and identifiable refusals with actor/task/non-secret grant ID and |
| +reason, transactionally; never include secrets, cookies, preview URLs or body |
| +contents. Unknown-token refusals remain generic and rate-limited. |
| + |
| +Test first and mutate: task visibility, revoked member/device/backing native |
| +session, person/instance/task/candidate/deployment binding, exact expiry, |
| +concurrent single use and replay, failed-audit rollback, cookie attributes, |
| +GET-only route isolation, CSRF/redirect refusal, wrapper sandbox/CSP and raw |
| +origin refusal. Native fake-server tests cover request/expiry, stale candidate, |
| +allowlist, redirects, foreground revalidation and sign-out. Browser tests cover |
| +the real exchange-to-wrapper flow. Add OpenAPI contracts and a perf-budget |
| +record for any new GET, then native and Go gates and Linux CI. No runner |
| +protocol change is needed. |
| + |
| +## Approved refinements |
| + |
| +Pass and grant lookups are indexed exact hash matches. Unknown, consumed and |
| +wrong-binding requests share the same generic refusal; stale/expired copy is |
| +available only after the capability's identity and submitted context validate. |
| +Device and IP limits apply separately. Any preview-cookie presence selects the |
| +restricted lane, even malformed or expired cookies alongside a general session. |
| +Host-only scope and a different iframe cookie host are tested in a real browser. |
| +Dismissal, expiry, sign-out and account replacement drop both native resources. |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-preview-pass.md b/docs/superpowers/plans/CONTROLLER-REPORT-preview-pass.md| new file mode 100644 |
| index 00000000..c03624b2 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-preview-pass.md |
| @@ -0,0 +1,129 @@ |
| +# Preview pass controller report |
| + |
| +Branch: `preview/pass`. Base: `7c113ac8`. Design approved by the controller on |
| +2026-11-26 in `2026-11-26-preview-pass.md`. |
| + |
| +## Delivered behavior |
| + |
| +A device tap mints a 32-byte pass through the device bearer API. A dedicated |
| +non-persistent WKWebView posts it in a bounded form body to the instance. The |
| +single-use exchange issues a separate, hashed, task-bound browser grant and |
| +redirects to the existing preview wrapper. It creates no general sign-in. |
| +The host-only Secure/HttpOnly/SameSite=Strict cookie is scoped to that wrapper |
| +path. Server authority permits only its exact GET. Invalid cookies do not fall |
| +through to the ordinary signed-in browser, including on unsafe-preview POST. |
| + |
| +Pass lifetime is at most 60 seconds; grant lifetime is at most 15 minutes, |
| +capped by the originating credential and preview. Reads never extend it. |
| +The transaction rechecks the roster, device, backing native session, task, |
| +candidate, step attempt and deployment fingerprint. Secret lookup uses an exact |
| +indexed SHA-256 hash. The tested query plan and executed SQL both pin that down. |
| +Issuance and exchange are limited by device and IP; unknown tokens consume the |
| +IP allowance. Cookie values and pass bodies do not enter audit records. |
| + |
| +The shared renderer preserves its CSP, sandbox and referrer policy. The native |
| +sheet allows only the fixed POST exchange and exact GET wrapper as main-frame |
| +navigation; no popups, downloads, custom schemes or device bearer enter it. |
| +Each presentation owns a new non-persistent WebKit store. Dismissal, expiry, |
| +changed deployment, sign-out and account replacement dispose it. Foreground |
| +revalidation checks the task and reloads only the same bound wrapper. |
| + |
| +No runner protocol change. The additive app-owned tables are in Models and the |
| +migration snapshot. The device endpoint and response are in OpenAPI. Existing |
| +browser sign-in continues for requests that have no preview cookie. |
| + |
| +## Copy |
| + |
| +Reused the reviewed web `evidence.candidate_changed` and `question.expired` |
| +byte-identically under parity. Imported the two already-reviewed stop reasons |
| +missing on this base (`merge_credential`, `amadan_unreachable`) to restore the |
| +existing parity gate. No new copy. |
| + |
| +## Test-first evidence |
| + |
| +Initial store stubs refused all mint requests: `go test ./internal/equipo -run |
| +'^TestPreview' -count=1` failed the new single-use/lifetime and binding tests. |
| +Initial HTTP stubs left the mint route absent and allowed normal-session |
| +fall-through: the HTTP tests failed on 401 mint and 200 invalid-cookie fallback. |
| +Native stubs failed nine assertions across the first four tests. Implementation |
| +then passed those tests. Evidence is retained in `site/build/slice6/validation`. |
| + |
| +The real Chromium browser lane posts a pass, follows the 303, loads the wrapper |
| +and its iframe, then proves replay returns 404. The actual iframe request has |
| +no Cookie, Authorization or Referer. Test-only TLS trust is confined to Chromium |
| +for the two local HTTPS test servers; production WebKit has no TLS override. |
| + |
| +## Mutations |
| + |
| +33 server guards and 19 native guards were broken deliberately, tested, and |
| +restored. All 52 logical mutations were killed by assertions, not compile errors. |
| +The scripts, individual test logs and result JSON are retained in the validation |
| +folder. Each server invocation uses `GOTOOLCHAIN=go1.26.11 CGO_ENABLED=0` and |
| +`go test ./internal/equipo -run <named test/subtest> -count=1`. Native mutations |
| +use `swift test --package-path native/apple --filter 'Preview(Pass|Lifecycle)Tests'`. |
| + |
| +Server: pass and grant duration; both indexed hash lookups; task and candidate |
| +binding; pass and grant expiry; hashed storage; revoked device and native |
| +session; instance, attempt, current candidate and deployment fingerprint; |
| +iframe cookie host and canonical trailing-dot host; Preview step candidate; |
| +final task; preview and device expiry caps; device and IP rate limits; Secure, |
| +HttpOnly and Strict cookie flags; no ambient-session fallback; GET-only grant; |
| +bounded exchange body; transactional audit; known refusal audit and device |
| +limit; single-use consumption. |
| + |
| +Native: private store; releasing web view, store and browser; session invalidation |
| +and permanent invalidation; exact expiry boundary; observed deployment change; |
| +foreground binding check; late-response generation; busy guard; pass alphabet; |
| +pass expiry and grant maximum; newest Preview selection; HTTPS; exact wrapper |
| +origin; GET-only wrapper; iframe cookie-host refusal. |
| + |
| +Initial survivors led to stronger tests: query SQL is checked as well as the |
| +query plan; the device check is tested independently of task authority; the |
| +body-bound test uses valid form padding; permanent model invalidation is tested |
| +with an otherwise usable client (session invalidation also disables its client). |
| +Initial mutation filters/targets were corrected to hit the intended |
| +subtest or occurrence. No surviving mutation is counted as killed. |
| + |
| +## Validation |
| + |
| +- Native gate passed: 359 tests in 48 suites, one existing known issue; |
| + 334 web-parity strings, security scripts, fixtures and both platform builds. |
| + Recorded in `preview-native-final-gate.log`. |
| +- `GOOS=linux GOARCH=amd64 make build` passed, including the Darwin runner build. |
| +- `GOOS=linux GOARCH=amd64 make vet` passed, including the Make target's Darwin |
| + runner check. The ordinary Mac all-package build hits the existing Linux-only |
| + toolproxy `unix.O_PATH` use. Linux hub CI is the authoritative full gate. |
| +- `make fmt-check budget spacing copy-release-check migration-check` passed; |
| + `PATH="$(GOTOOLCHAIN=go1.26.11 go env GOROOT)/bin:$PATH"` used for gofmt. |
| + Size records name the new code and measured totals. |
| +- Host-built staticcheck v0.7.0 with `GOOS=linux GOARCH=amd64`, tags |
| + `browser,perf,testbuild`, passed. Host-built govulncheck v1.8.0 targeting Linux |
| + found no reachable vulnerabilities. `make gitleaks` found no leaks. |
| +- `make lanes-check` passed: 18 regular and 5 browser lanes cover every test. |
| +- Preview store/HTTP/security tests passed, as did the device/OpenAPI contract |
| + and migration tests. Final targeted and browser logs are retained. |
| +- The Make perf harness, targeted to `./internal/equipotest` on Mac, passed: |
| + wrapper median 1.041 ms, worst 1.125 ms against 150 ms; cold boot median |
| + 154 ms against 500 ms. The new GET exchange refusal has an explicit skip record. |
| +- An initial validation attempt lost files from the shared Go cache. On the |
| + controller's instruction, retried without clearing it. The retry passed. |
| + |
| +## Native captures and limitations |
| + |
| +`iphone-preview.png` and `mac-preview.png` are captured from the branch's built |
| +apps against the tagged manual Go fixture, using the actual bearer mint, |
| +POST-body exchange, wrapper cookie, shared wrapper and iframe. The external |
| +example page is disposable fixture content. The server is loopback-only behind |
| +a temporary HTTPS tailnet port. The fixture config contains a disposable test |
| +credential, stays private, and is deleted at teardown. It is not committed or |
| +archived. No production account or credential is used. The Mac capture hosts |
| +the production sheet content in a normal NSHostingView with the actual loaded |
| +WKWebView: macOS SheetHostingView omits its SwiftUI layer from cacheDisplay. |
| + |
| +The iframe's external service remains responsible for its own availability. |
| +Grant expiry prevents new wrapper reads; it cannot retract HTML already |
| +received by an arbitrary browser. Native disposes the delivered view at expiry. |
| +The pass does not approve an unsafe preview or confer any merge authority. |
| + |
| +Final commit and Linux CI verdict are sent to the controller after pushing; |
| +no merge, deployment or release is performed. |
diff --git a/internal/equipo/app.go b/internal/equipo/app.go| index fca880fe..0de853b4 100644 |
| --- a/internal/equipo/app.go |
| +++ b/internal/equipo/app.go |
| @@ -285,6 +285,10 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| w.Header().Set("Cache-Control", "no-store") |
| _ = json.NewEncoder(w).Encode(wire.RunnerProtocol{Protocol: wire.ProtocolCurrent}) |
| }) |
| + a.Post("/native/preview/exchange", a.exchangePreviewHTTP) |
| + a.Get("/native/preview/exchange", a.exchangePreviewHTTP) |
| + a.Get("/tasks/{id}/preview", a.previewGrantOrBrowser(a.requireMember(http.HandlerFunc(a.previewPage))).ServeHTTP) |
| + a.Post("/tasks/{id}/preview", a.previewGrantOrBrowser(a.requireMember(http.HandlerFunc(a.allowUnsafePreview))).ServeHTTP) |
| a.Post("/auth/begin", a.auth.Begin) |
| a.Get("/auth/callback", a.rememberSignIn(a.auth.Callback)) |
| a.Get("/auth/verify", a.rememberSignIn(a.auth.Verify)) |
| @@ -335,8 +339,6 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| r.Post("/conversation/tasks/{id}/merge", a.workTaskMerge) |
| r.Get("/tasks/new", a.taskForm) |
| r.Get("/tasks/{id}", a.taskDetail) |
| - r.Get("/tasks/{id}/preview", a.previewPage) |
| - r.Post("/tasks/{id}/preview", a.allowUnsafePreview) |
| r.Get("/tasks/{id}/rendered-change", a.renderedPage) |
| r.Get("/tasks/{id}/rendered-change/{hash}.png", a.renderedImage) |
| r.Get("/tasks/{id}/files/{file}", a.workTaskFile) |
diff --git a/internal/equipo/chat/tasks.go b/internal/equipo/chat/tasks.go| index 8f907e6f..976c1edc 100644 |
| --- a/internal/equipo/chat/tasks.go |
| +++ b/internal/equipo/chat/tasks.go |
| @@ -1931,20 +1931,26 @@ func (t *txn) recentTasks(limit int) ([]wire.Task, error) { |
| // Task reads one task. |
| func (s *Store) Task(ctx context.Context, person, id string) (out wire.Task, err error) { |
| err = s.read(ctx, func(tx *gorm.DB) error { |
| - if err := s.authority.CurrentPerson(ctx, tx); err != nil { |
| - return err |
| - } |
| - t := &txn{s: s, db: tx} |
| - k, err := t.loadTask(id) |
| - if err != nil { |
| - return err |
| - } |
| - out, err = t.taskView(k) |
| + out, err = s.TaskAt(ctx, tx, id) |
| return err |
| }) |
| return out, err |
| } |
| +// TaskAt uses task-read authority on the caller's transaction. Preview grants |
| +// need that same read atomically with their credential and single-use checks. |
| +func (s *Store) TaskAt(ctx context.Context, tx *gorm.DB, id string) (wire.Task, error) { |
| + if err := s.authority.CurrentPerson(ctx, tx); err != nil { |
| + return wire.Task{}, err |
| + } |
| + t := &txn{s: s, db: tx} |
| + k, err := t.loadTask(id) |
| + if err != nil { |
| + return wire.Task{}, err |
| + } |
| + return t.taskView(k) |
| +} |
| + |
| // CancelTask is POST /tasks/{id}/cancel: owners only. |
| func (s *Store) CancelTask(ctx context.Context, person, id string) (attempt int64, err error) { |
| err = s.tx(ctx, func(t *txn) error { |
diff --git a/internal/equipo/migrations/0108_preview_passes.sql b/internal/equipo/migrations/0108_preview_passes.sql| new file mode 100644 |
| index 00000000..8fae413b |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0108_preview_passes.sql |
| @@ -0,0 +1,14 @@ |
| +-- Device passes and wrapper-only grants never create a general sign-in session. |
| +CREATE TABLE preview_passes ( |
| + hash text PRIMARY KEY, id text, instance text, person text, credential text, |
| + task_id text, candidate text, step_id text, fingerprint text, |
| + epoch integer, attempt integer, expires_at datetime, grant_expires_at datetime, |
| + consumed_at datetime |
| +); |
| +CREATE INDEX preview_pass_expiry ON preview_passes(expires_at); |
| +CREATE TABLE preview_grants ( |
| + hash text PRIMARY KEY, id text, instance text, person text, credential text, |
| + task_id text, candidate text, step_id text, fingerprint text, |
| + epoch integer, attempt integer, expires_at datetime |
| +); |
| +CREATE INDEX preview_grant_expiry ON preview_grants(expires_at); |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index b766173e..b64239e8 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -777,3 +777,18 @@ ALTER TABLE chat_cards ADD COLUMN carry_on numeric; |
| ALTER TABLE chat_cards ADD COLUMN carry_on_connection text; |
| ALTER TABLE chat_releases ADD COLUMN connection text; |
| ALTER TABLE chat_steps ADD COLUMN coordinator_attempt integer; |
| + |
| +-- Device passes and wrapper-only grants never create a general sign-in session. |
| +CREATE TABLE preview_passes ( |
| + hash text PRIMARY KEY, id text, instance text, person text, credential text, |
| + task_id text, candidate text, step_id text, fingerprint text, |
| + epoch integer, attempt integer, expires_at datetime, grant_expires_at datetime, |
| + consumed_at datetime |
| +); |
| +CREATE INDEX preview_pass_expiry ON preview_passes(expires_at); |
| +CREATE TABLE preview_grants ( |
| + hash text PRIMARY KEY, id text, instance text, person text, credential text, |
| + task_id text, candidate text, step_id text, fingerprint text, |
| + epoch integer, attempt integer, expires_at datetime |
| +); |
| +CREATE INDEX preview_grant_expiry ON preview_grants(expires_at); |
diff --git a/internal/equipo/person_api.go b/internal/equipo/person_api.go| index cc04f5ae..2112891d 100644 |
| --- a/internal/equipo/person_api.go |
| +++ b/internal/equipo/person_api.go |
| @@ -49,6 +49,7 @@ func (s *Store) personAPIRouter() chi.Router { |
| c := s.chatHTTP(auth.Authenticate, h.Failure) |
| c.Old = old |
| c.Mount(r) |
| + r.Post("/tasks/{id}/preview-pass", s.mintPreviewHTTP(auth)) |
| return r |
| } |
| func (s *Store) personAPIReader(a Actor) *conversation.Application { |
diff --git a/internal/equipo/personapi/handler.go b/internal/equipo/personapi/handler.go| index c4fde992..a7a83924 100644 |
| --- a/internal/equipo/personapi/handler.go |
| +++ b/internal/equipo/personapi/handler.go |
| @@ -271,6 +271,10 @@ func errorCopyKey(r *http.Request, code string) string { |
| return "notifications." + code |
| } |
| switch code { |
| + case "preview_changed": |
| + return "evidence.candidate_changed" |
| + case "preview_expired": |
| + return "question.expired" |
| case "invalid_input", "forbidden", "revision_conflict": |
| switch op { |
| case "roster", "set_roster": |
diff --git a/internal/equipo/preview_pass.go b/internal/equipo/preview_pass.go| new file mode 100644 |
| index 00000000..75727255 |
| --- /dev/null |
| +++ b/internal/equipo/preview_pass.go |
| @@ -0,0 +1,240 @@ |
| +package equipo |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/personapi" |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "gorm.io/gorm" |
| +) |
| + |
| +var ErrPreviewAccess = errors.New("preview access refused") |
| +var ErrPreviewExpired = errors.New("preview access expired") |
| +var ErrPreviewChanged = errors.New("preview candidate changed") |
| + |
| +type previewPass struct { |
| + Pass string `json:"pass"` |
| + ExpiresAt time.Time `json:"expires_at"` |
| + GrantExpiresAt time.Time `json:"grant_expires_at"` |
| +} |
| +type previewGrant struct { |
| + Secret string |
| + ExpiresAt time.Time |
| + TaskID string |
| +} |
| + |
| +func (s *Store) mintPreviewPass(ctx context.Context, p PersonPrincipal, taskID, candidate, ip string) (out previewPass, err error) { |
| + if !previewPrincipal(ctx, p) { |
| + return out, ErrPreviewAccess |
| + } |
| + var refusal error |
| + err = s.write(ctx, func(tx *gorm.DB) error { |
| + ok, e := s.previewRate(tx, "mint", ip, p.CredentialID) |
| + if e != nil { |
| + return e |
| + } |
| + if !ok { |
| + refusal = ErrPreviewAccess |
| + return nil |
| + } |
| + device, e := s.previewDevice(tx, p) |
| + if e != nil { |
| + refusal = ErrPreviewAccess |
| + return nil |
| + } |
| + task, e := s.Chat().TaskAt(ctx, tx, taskID) |
| + if e != nil { |
| + refusal = ErrPreviewAccess |
| + return nil |
| + } |
| + deny := func(reason error) error { |
| + refusal = reason |
| + return previewRefusal(tx, previewBinding{Person: p.Address, TaskID: taskID}, "mint", reason) |
| + } |
| + if candidate == "" || candidate != task.CandidateSHA { |
| + return deny(ErrPreviewChanged) |
| + } |
| + step, fingerprint, e := s.previewDeployment(task) |
| + if e != nil { |
| + return deny(ErrPreviewAccess) |
| + } |
| + binding := previewBinding{Instance: device.InstanceID, Person: p.Address, Credential: p.CredentialID, Epoch: p.SessionEpoch, TaskID: taskID, Candidate: candidate, StepID: step.ID, Attempt: step.Attempt, Fingerprint: fingerprint} |
| + if e = s.validatePreview(task, binding); e != nil { |
| + return deny(e) |
| + } |
| + now := s.runnerClock.Now().UTC() |
| + grantExpiry := minPreviewTime(now.Add(15*time.Minute), device.TokenExpiresAt) |
| + if step.Preview.ExpiresAt != nil { |
| + grantExpiry = minPreviewTime(grantExpiry, *step.Preview.ExpiresAt) |
| + } |
| + out = previewPass{Pass: runnerSecret(), ExpiresAt: minPreviewTime(now.Add(time.Minute), grantExpiry), GrantExpiresAt: grantExpiry} |
| + if e = s.prunePreviews(tx); e != nil { |
| + return e |
| + } |
| + // One pending pass per device/task; another tap replaces an unexchanged pass. |
| + if e = tx.Model(&previewPassRecord{}).Where("credential = ? AND task_id = ? AND consumed_at IS NULL", p.CredentialID, taskID).Select("consumed_at").Updates(map[string]any{"consumed_at": now}).Error; e != nil { |
| + return e |
| + } |
| + row := previewPassRecord{Hash: previewHash(out.Pass), ID: runnerSecret(), Binding: binding, ExpiresAt: out.ExpiresAt, GrantExpiresAt: grantExpiry} |
| + if e = tx.Create(&row).Error; e != nil { |
| + return e |
| + } |
| + return appendAudit(tx, Actor{Address: p.Address}, "preview.pass.mint", row.ID+":"+taskID) |
| + }) |
| + if err == nil { |
| + err = refusal |
| + } |
| + if err != nil { |
| + out = previewPass{} |
| + } |
| + return |
| +} |
| + |
| +func (s *Store) exchangePreviewPass(ctx context.Context, token, taskID, candidate, ip string) (out previewGrant, err error) { |
| + var refusal error |
| + // Browser exchange authenticates only this pass; no ambient principal grants access. |
| + ctx = personapi.WithVerifiedPrincipal(ctx, PersonPrincipal{}) |
| + err = s.write(ctx, func(tx *gorm.DB) error { |
| + ok, e := s.previewRate(tx, "exchange", ip, "") |
| + if e != nil { |
| + return e |
| + } |
| + if !ok { |
| + refusal = ErrPreviewAccess |
| + return nil |
| + } |
| + hash := previewHash(token) |
| + if hash == "" { |
| + refusal = ErrPreviewAccess |
| + return nil |
| + } |
| + var row previewPassRecord |
| + if e = tx.Where("hash = ?", hash).First(&row).Error; e != nil { |
| + if errors.Is(e, gorm.ErrRecordNotFound) { |
| + refusal = ErrPreviewAccess |
| + return nil |
| + } |
| + return e |
| + } |
| + // Device rate is separate from IP: a new source address cannot evade it. |
| + ok, e = runnerRateAt(tx, "preview:exchange:device:"+row.Binding.Credential, s.runnerClock.Now(), time.Minute, 10) |
| + if e != nil { |
| + return e |
| + } |
| + if !ok { |
| + refusal = ErrPreviewAccess |
| + return nil |
| + } |
| + if row.ConsumedAt != nil || row.Binding.TaskID != taskID || row.Binding.Candidate != candidate { |
| + refusal = ErrPreviewAccess |
| + return previewRefusal(tx, row.Binding, row.ID, refusal) |
| + } |
| + task, e := s.previewTask(tx, row.Binding) |
| + if e != nil { |
| + refusal = ErrPreviewAccess |
| + return previewRefusal(tx, row.Binding, row.ID, refusal) |
| + } |
| + now := s.runnerClock.Now().UTC() |
| + consumed := tx.Model(&previewPassRecord{}).Where("hash = ? AND consumed_at IS NULL", hash).Select("consumed_at").Updates(map[string]any{"consumed_at": now}) |
| + if consumed.Error != nil { |
| + return consumed.Error |
| + } |
| + if consumed.RowsAffected != 1 { |
| + refusal = ErrPreviewAccess |
| + return nil |
| + } |
| + refusal = s.validatePreview(task, row.Binding) |
| + if refusal == nil && (!now.Before(row.ExpiresAt) || !now.Before(row.GrantExpiresAt)) { |
| + refusal = ErrPreviewExpired |
| + } |
| + if refusal != nil { |
| + return previewRefusal(tx, row.Binding, row.ID, refusal) |
| + } |
| + out = previewGrant{Secret: runnerSecret(), TaskID: taskID, ExpiresAt: row.GrantExpiresAt} |
| + // Only the current presentation for this device/task retains a grant. |
| + if e = tx.Where("credential = ? AND task_id = ?", row.Binding.Credential, taskID).Delete(&previewGrantRecord{}).Error; e != nil { |
| + return e |
| + } |
| + grant := previewGrantRecord{Hash: previewHash(out.Secret), ID: runnerSecret(), Binding: row.Binding, ExpiresAt: out.ExpiresAt} |
| + if e = tx.Create(&grant).Error; e != nil { |
| + return e |
| + } |
| + return appendAudit(tx, Actor{Address: row.Binding.Person}, "preview.pass.exchange", grant.ID+":"+taskID) |
| + }) |
| + if err == nil { |
| + err = refusal |
| + } |
| + if err != nil { |
| + out = previewGrant{} |
| + } |
| + return |
| +} |
| + |
| +func (s *Store) readPreviewGrant(ctx context.Context, token, taskID, ip string) (out wire.Task, err error) { |
| + var refusal error |
| + ctx = personapi.WithVerifiedPrincipal(ctx, PersonPrincipal{}) |
| + err = s.write(ctx, func(tx *gorm.DB) error { |
| + ok, e := s.previewRate(tx, "read", ip, "") |
| + if e != nil { |
| + return e |
| + } |
| + if !ok { |
| + refusal = ErrPreviewAccess |
| + return nil |
| + } |
| + hash := previewHash(token) |
| + if hash == "" { |
| + refusal = ErrPreviewAccess |
| + return nil |
| + } |
| + var row previewGrantRecord |
| + if e = tx.Where("hash = ?", hash).First(&row).Error; e != nil { |
| + if errors.Is(e, gorm.ErrRecordNotFound) { |
| + refusal = ErrPreviewAccess |
| + return nil |
| + } |
| + return e |
| + } |
| + ok, e = runnerRateAt(tx, "preview:read:device:"+row.Binding.Credential, s.runnerClock.Now(), time.Minute, 120) |
| + if e != nil { |
| + return e |
| + } |
| + if !ok { |
| + refusal = ErrPreviewAccess |
| + return nil |
| + } |
| + if row.Binding.TaskID != taskID { |
| + refusal = ErrPreviewAccess |
| + return previewRefusal(tx, row.Binding, row.ID, refusal) |
| + } |
| + task, e := s.previewTask(tx, row.Binding) |
| + if e != nil { |
| + refusal = ErrPreviewAccess |
| + return previewRefusal(tx, row.Binding, row.ID, refusal) |
| + } |
| + refusal = s.validatePreview(task, row.Binding) |
| + if refusal == nil && !s.runnerClock.Now().Before(row.ExpiresAt) { |
| + refusal = ErrPreviewExpired |
| + } |
| + if refusal != nil { |
| + return previewRefusal(tx, row.Binding, row.ID, refusal) |
| + } |
| + out = task |
| + return nil |
| + }) |
| + if err == nil { |
| + err = refusal |
| + } |
| + if err != nil { |
| + out = wire.Task{} |
| + } |
| + return |
| +} |
| + |
| +// Audit only hashed-record identities, never submitted identity or credential text. |
| +func previewRefusal(tx *gorm.DB, binding previewBinding, id string, reason error) error { |
| + _, code, _ := previewError(reason) |
| + return appendAudit(tx, Actor{Address: binding.Person}, "preview.pass.refused", id+":"+binding.TaskID+":"+code) |
| +} |
diff --git a/internal/equipo/preview_pass_browser_test.go b/internal/equipo/preview_pass_browser_test.go| new file mode 100644 |
| index 00000000..07ebf575 |
| --- /dev/null |
| +++ b/internal/equipo/preview_pass_browser_test.go |
| @@ -0,0 +1,122 @@ |
| +//go:build browser |
| + |
| +package equipo |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/rastrillo/rastrillo/harness" |
| + "github.com/chromedp/chromedp" |
| +) |
| + |
| +// Real POST, CSRF, one-use exchange, 303, browser cookie jar, wrapper CSP and |
| +// child-frame request. No browser authentication bypass or injected grant. |
| +func TestBrowserPreviewPassExchange(t *testing.T) { |
| + rig := newPreviewPassRig(t) |
| + childRequests := make(chan *http.Request, 10) |
| + child := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + select { |
| + case childRequests <- r.Clone(context.Background()): |
| + default: |
| + } |
| + fmt.Fprint(w, `<h1>Candidate preview</h1>`) |
| + })) |
| + defer child.Close() |
| + // Cookies do not distinguish ports. Different hosts are essential here. |
| + childURL := strings.Replace(child.URL, "127.0.0.1", "localhost", 1) |
| + var stored map[string]any |
| + var preview string |
| + if err := rig.s.db.Reader().QueryRow("SELECT preview FROM chat_steps WHERE id = ?", "preview_step").Scan(&preview); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := json.Unmarshal([]byte(preview), &stored); err != nil { |
| + t.Fatal(err) |
| + } |
| + stored["url"] = childURL + "/" |
| + data, _ := json.Marshal(stored) |
| + if _, err := rig.s.db.Writer().Exec("UPDATE chat_steps SET preview = ? WHERE id = ?", string(data), "preview_step"); err != nil { |
| + t.Fatal(err) |
| + } |
| + exchangeCodes := make(chan int, 8) |
| + var handler http.Handler |
| + parent := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Path == "/native/preview/exchange" { |
| + recorder := httptest.NewRecorder() |
| + handler.ServeHTTP(recorder, r) |
| + for k, values := range recorder.Header() { |
| + for _, v := range values { |
| + w.Header().Add(k, v) |
| + } |
| + } |
| + w.WriteHeader(recorder.Code) |
| + _, _ = w.Write(recorder.Body.Bytes()) |
| + exchangeCodes <- recorder.Code |
| + } else { |
| + handler.ServeHTTP(w, r) |
| + } |
| + })) |
| + defer parent.Close() |
| + parentURL := strings.Replace(parent.URL, "127.0.0.1", "equipo.example", 1) |
| + rig.s.personOrigin = parentURL |
| + handler = Mux(previewPassRouter(t, rig)) |
| + pass := rig.mint(t) |
| + form := url.Values{"pass": {pass.Pass}, "task": {"tk_preview"}, "candidate": {strings.Repeat("1", 40)}}.Encode() |
| + opts := append(chromedp.DefaultExecAllocatorOptions[:], chromedp.ExecPath(harness.ChromePath(t)), chromedp.NoSandbox, chromedp.Flag("host-resolver-rules", "MAP equipo.example 127.0.0.1"), chromedp.Flag("no-proxy-server", true), chromedp.Flag("ignore-certificate-errors", true), chromedp.UserDataDir(t.TempDir())) |
| + alloc, stop := chromedp.NewExecAllocator(context.Background(), opts...) |
| + defer stop() |
| + ctx, cancel := chromedp.NewContext(alloc) |
| + defer cancel() |
| + ctx, timeout := context.WithTimeout(ctx, 30*time.Second) |
| + defer timeout() |
| + // Load a same-origin public page, then submit a body-only form as WebKit does. |
| + if _, err := chromedp.Run(ctx, chromedp.Navigate(parentURL+"/")); err != nil { |
| + t.Fatal(err) |
| + } |
| + script := fmt.Sprintf(`(()=>{const f=document.createElement('form');f.method='POST';f.action='/native/preview/exchange';for(const [name,value] of new URLSearchParams(%q)){const i=document.createElement('input');i.name=name;i.value=value;f.append(i)}document.body.append(f);f.submit()})()`, form) |
| + if _, err := chromedp.Run(ctx, chromedp.Evaluate[any](script)); err != nil { |
| + t.Fatal(err) |
| + } |
| + select { |
| + case r := <-childRequests: |
| + if r.Header.Get("Cookie") != "" || r.Header.Get("Authorization") != "" || r.Header.Get("Referer") != "" { |
| + t.Fatalf("preview received Equipo authority: %v", r.Header) |
| + } |
| + case <-ctx.Done(): |
| + t.Fatal("wrapper iframe never loaded") |
| + } |
| + location, err := chromedp.Run(ctx, chromedp.Evaluate[string](`location.href`)) |
| + if err != nil || location != parentURL+"/tasks/tk_preview/preview" { |
| + t.Fatalf("location=%q err=%v", location, err) |
| + } |
| + sandbox, err := chromedp.Run(ctx, chromedp.Evaluate[string](`document.querySelector('iframe').getAttribute('sandbox')`)) |
| + if err != nil || sandbox != "allow-scripts allow-same-origin" { |
| + t.Fatalf("sandbox=%q err=%v", sandbox, err) |
| + } |
| + if code := <-exchangeCodes; code != 303 { |
| + t.Fatalf("exchange status %d", code) |
| + } |
| + // Reuse is refused by the actual browser route. Start from a public |
| + // page, since the wrapper deliberately prohibits injected scripts. |
| + if _, err = chromedp.Run(ctx, chromedp.Navigate(parentURL+"/")); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = chromedp.Run(ctx, chromedp.Evaluate[any](script)); err != nil { |
| + t.Fatal(err) |
| + } |
| + select { |
| + case code := <-exchangeCodes: |
| + if code != 404 { |
| + t.Fatalf("replay status %d", code) |
| + } |
| + case <-ctx.Done(): |
| + t.Fatal("replay did not reach exchange") |
| + } |
| +} |
diff --git a/internal/equipo/preview_pass_fixture_test.go b/internal/equipo/preview_pass_fixture_test.go| new file mode 100644 |
| index 00000000..ffdc3bf8 |
| --- /dev/null |
| +++ b/internal/equipo/preview_pass_fixture_test.go |
| @@ -0,0 +1,55 @@ |
| +//go:build previewfixture |
| + |
| +package equipo |
| + |
| +import ( |
| + "encoding/json" |
| + "net" |
| + "net/http" |
| + "os" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| +) |
| + |
| +// Manual native screenshot fixture. Real routes, fresh temporary database and |
| +// device credential; only the deployed example page is external. No production |
| +// team or credential is read. The config is private and deleted on teardown. |
| +func TestPreviewScreenshotServer(t *testing.T) { |
| + path := os.Getenv("EQUIPO_PREVIEW_CONFIG") |
| + origin := os.Getenv("EQUIPO_PREVIEW_ORIGIN") |
| + if path == "" || origin == "" { |
| + t.Skip("manual screenshot fixture") |
| + } |
| + r := newPreviewPassRigAt(t, time.Now().UTC().Truncate(time.Second)) |
| + r.s.runnerClock = team.RealClock{} |
| + r.s.personOrigin = origin |
| + if _, e := r.s.db.Writer().Exec("UPDATE chat_steps SET preview=json_set(preview,'$.url','https://example.com/') WHERE id='preview_step'"); e != nil { |
| + t.Fatal(e) |
| + } |
| + if _, e := r.s.db.Writer().Exec("UPDATE chat_tasks SET title='Review the example page',brief='Check the page in the sandboxed preview before merging.' WHERE id='tk_preview'"); e != nil { |
| + t.Fatal(e) |
| + } |
| + h := previewPassRouter(t, r) |
| + listener, e := net.Listen("tcp", "127.0.0.1:18146") |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + server := &http.Server{Handler: Mux(h), ReadHeaderTimeout: 5 * time.Second} |
| + defer server.Close() |
| + defer CloseLive(h) |
| + go func() { _ = server.Serve(listener) }() |
| + data, _ := json.Marshal(map[string]string{"origin": origin, "token": r.credential.Token}) |
| + if e = os.WriteFile(path, data, 0600); e != nil { |
| + t.Fatal(e) |
| + } |
| + defer os.Remove(path) |
| + ticker := time.NewTicker(time.Second) |
| + defer ticker.Stop() |
| + for range ticker.C { |
| + if _, e := os.Stat(path + ".stop"); e == nil { |
| + return |
| + } |
| + } |
| +} |
diff --git a/internal/equipo/preview_pass_http.go b/internal/equipo/preview_pass_http.go| new file mode 100644 |
| index 00000000..e4f7dc59 |
| --- /dev/null |
| +++ b/internal/equipo/preview_pass_http.go |
| @@ -0,0 +1,184 @@ |
| +package equipo |
| + |
| +import ( |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "html" |
| + "io" |
| + "mime" |
| + "net/http" |
| + "regexp" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/personapi" |
| + "amadan.net/rastrillo/rastrillo/carlos" |
| + "amadan.net/rastrillo/rastrillo/clientip" |
| + "amadan.net/rastrillo/rastrillo/csrf" |
| + "github.com/go-chi/chi/v5" |
| +) |
| + |
| +const previewCookie = "__Secure-equipo-preview" |
| + |
| +var previewTaskID = regexp.MustCompile(`^[A-Za-z0-9_-]{1,128}$`) |
| +var previewCandidate = regexp.MustCompile(`^[0-9a-f]{40}$`) |
| + |
| +func previewIP(r *http.Request) string { |
| + hops := 0 |
| + if carlos.Running() { |
| + hops = clientip.DefaultHops |
| + } |
| + return clientip.From(r, hops) |
| +} |
| +func previewHeaders(w http.ResponseWriter) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + w.Header().Set("Referrer-Policy", "no-referrer") |
| + w.Header().Set("X-Content-Type-Options", "nosniff") |
| +} |
| +func previewError(err error) (int, string, string) { |
| + switch { |
| + case errors.Is(err, ErrPreviewChanged): |
| + return 409, "preview_changed", "evidence.candidate_changed" |
| + case errors.Is(err, ErrPreviewExpired): |
| + return 410, "preview_expired", "question.expired" |
| + case errors.Is(err, ErrUnavailable): |
| + return 503, "unavailable", "api.unavailable" |
| + default: |
| + return 404, "not_found", "api.not_found" |
| + } |
| +} |
| +func previewErrorPage(w http.ResponseWriter, err error) { |
| + status, _, key := previewError(err) |
| + previewHeaders(w) |
| + w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| + w.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'self'; font-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'") |
| + w.WriteHeader(status) |
| + fmt.Fprintf(w, `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><link rel="stylesheet" href="/static/tokens.css"><link rel="stylesheet" href="/static/theme.css"><title>%s</title><p>%s</p></html>`, html.EscapeString(copyText("preview.wrapper_title")), html.EscapeString(copyText(key))) |
| +} |
| +func (s *Store) mintPreviewHTTP(auth personapi.Authenticator) http.HandlerFunc { |
| + return func(w http.ResponseWriter, r *http.Request) { |
| + previewHeaders(w) |
| + if len(r.Header.Values("Authorization")) == 0 { |
| + personapi.WriteError(w, r, 401, "unauthenticated", nil) |
| + return |
| + } |
| + p, e := auth.Authenticate(r) |
| + if e != nil { |
| + personapi.WriteError(w, r, 401, "unauthenticated", nil) |
| + return |
| + } |
| + var input struct { |
| + Candidate string `json:"candidate_sha"` |
| + } |
| + r.Body = http.MaxBytesReader(w, r.Body, 4096) |
| + decoder := json.NewDecoder(r.Body) |
| + decoder.DisallowUnknownFields() |
| + var extra any |
| + if r.URL.RawQuery != "" || decoder.Decode(&input) != nil || decoder.Decode(&extra) != io.EOF || !previewCandidate.MatchString(input.Candidate) || !previewTaskID.MatchString(chi.URLParam(r, "id")) { |
| + personapi.WriteError(w, r, 422, "invalid_input", nil) |
| + return |
| + } |
| + out, e := s.mintPreviewPass(personapi.WithVerifiedPrincipal(r.Context(), p), p, chi.URLParam(r, "id"), input.Candidate, previewIP(r)) |
| + if e != nil { |
| + status, code, _ := previewError(e) |
| + personapi.WriteError(w, r, status, code, nil) |
| + return |
| + } |
| + w.Header().Set("Content-Type", "application/json") |
| + w.WriteHeader(201) |
| + _ = json.NewEncoder(w).Encode(out) |
| + } |
| +} |
| +func (a *application) exchangePreviewHTTP(w http.ResponseWriter, r *http.Request) { |
| + previewHeaders(w) |
| + kind, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")) |
| + if r.Method != "POST" || r.URL.RawQuery != "" || len(r.Header.Values("Authorization")) != 0 || !personapi.OriginAllowed(r, a.origin) || !csrf.SameOrigin(r, a.origin) || kind != "application/x-www-form-urlencoded" { |
| + previewErrorPage(w, ErrPreviewAccess) |
| + return |
| + } |
| + r.Body = http.MaxBytesReader(w, r.Body, 4096) |
| + if r.ParseForm() != nil || len(r.PostForm) != 3 { |
| + previewErrorPage(w, ErrPreviewAccess) |
| + return |
| + } |
| + for _, key := range []string{"pass", "task", "candidate"} { |
| + if len(r.PostForm[key]) != 1 { |
| + previewErrorPage(w, ErrPreviewAccess) |
| + return |
| + } |
| + } |
| + task, candidate := r.PostForm.Get("task"), r.PostForm.Get("candidate") |
| + if !previewTaskID.MatchString(task) || !previewCandidate.MatchString(candidate) { |
| + previewErrorPage(w, ErrPreviewAccess) |
| + return |
| + } |
| + grant, e := a.store.exchangePreviewPass(r.Context(), r.PostForm.Get("pass"), task, candidate, previewIP(r)) |
| + if e != nil { |
| + previewErrorPage(w, e) |
| + return |
| + } |
| + path := "/tasks/" + grant.TaskID + "/preview" |
| + left := int(grant.ExpiresAt.Sub(a.store.runnerClock.Now()) / time.Second) |
| + if left <= 0 { |
| + previewErrorPage(w, ErrPreviewExpired) |
| + return |
| + } |
| + http.SetCookie(w, &http.Cookie{Name: previewCookie, Value: grant.Secret, Path: path, Secure: true, HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: left, Expires: grant.ExpiresAt}) |
| + w.Header().Set("Location", path) |
| + w.WriteHeader(http.StatusSeeOther) |
| +} |
| + |
| +// Presence is checked independently of cookie parsing. Malformed and duplicate |
| +// grant cookies must not restore the broader authority of an ambient session. |
| +func hasPreviewCookie(r *http.Request) bool { |
| + for _, header := range r.Header.Values("Cookie") { |
| + for _, part := range strings.Split(header, ";") { |
| + name, _, _ := strings.Cut(part, "=") |
| + if strings.TrimSpace(name) == previewCookie { |
| + return true |
| + } |
| + } |
| + } |
| + return false |
| +} |
| +func (a *application) previewGrantOrBrowser(next http.Handler) http.Handler { |
| + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if !hasPreviewCookie(r) { |
| + next.ServeHTTP(w, r) |
| + return |
| + } |
| + var value string |
| + count := 0 |
| + for _, c := range r.Cookies() { |
| + if c.Name == previewCookie { |
| + value = c.Value |
| + count++ |
| + } |
| + } |
| + taskID := chi.URLParam(r, "id") |
| + if count != 1 || r.Method != "GET" || r.URL.RawQuery != "" || !previewTaskID.MatchString(taskID) || r.URL.EscapedPath() != "/tasks/"+taskID+"/preview" { |
| + previewErrorPage(w, ErrPreviewAccess) |
| + return |
| + } |
| + task, e := a.store.readPreviewGrant(r.Context(), value, taskID, previewIP(r)) |
| + if e != nil { |
| + previewErrorPage(w, e) |
| + return |
| + } |
| + step, _, e := a.store.previewDeployment(task) |
| + if e != nil { |
| + previewErrorPage(w, ErrPreviewAccess) |
| + return |
| + } |
| + policy, page, e := previewWrapper(step.Preview.URL, step.Preview.Unsafe) |
| + if e != nil { |
| + previewErrorPage(w, ErrPreviewAccess) |
| + return |
| + } |
| + previewHeaders(w) |
| + w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| + w.Header().Set("Content-Security-Policy", policy) |
| + _, _ = io.WriteString(w, page) |
| + }) |
| +} |
diff --git a/internal/equipo/preview_pass_http_test.go b/internal/equipo/preview_pass_http_test.go| new file mode 100644 |
| index 00000000..3236d9b3 |
| --- /dev/null |
| +++ b/internal/equipo/preview_pass_http_test.go |
| @@ -0,0 +1,180 @@ |
| +package equipo |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/go-chi/chi/v5" |
| +) |
| + |
| +func previewPassRouter(t *testing.T, r *previewPassRig) http.Handler { |
| + t.Helper() |
| + env := agentEnv(t) |
| + cfg, e := LoadConfig(func(k string) string { return env[k] }) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + cfg.Origin = r.s.personOrigin |
| + // Keep the fixture's verified native session while using the actual app router. |
| + session := r.s.personNativeSession |
| + h, e := RouterWithStore(r.s.db, cfg, agentMail{}, nil, r.s) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + r.s.personNativeSession = session |
| + t.Cleanup(func() { CloseLive(h) }) |
| + return h |
| +} |
| +func passExchangeRequest(token, task, candidate string) *http.Request { |
| + form := url.Values{"pass": {token}, "task": {task}, "candidate": {candidate}} |
| + r := httptest.NewRequest("POST", "https://equipo.example/native/preview/exchange", strings.NewReader(form.Encode())) |
| + r.Header.Set("Origin", "https://equipo.example") |
| + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + return r |
| +} |
| +func TestPreviewPassHTTPFlowAndIsolation(t *testing.T) { |
| + r := newPreviewPassRig(t) |
| + h := previewPassRouter(t, r) |
| + minted := agentRequest(h, "POST", "/api/v1/tasks/tk_preview/preview-pass", `{"candidate_sha":"`+passCandidate+`"}`, r.credential.Token) |
| + if minted.Code != 201 { |
| + t.Fatalf("mint: %d %s", minted.Code, minted.Body) |
| + } |
| + var pass previewPass |
| + if e := json.Unmarshal(minted.Body.Bytes(), &pass); e != nil { |
| + t.Fatal(e) |
| + } |
| + w := httptest.NewRecorder() |
| + h.ServeHTTP(w, passExchangeRequest(pass.Pass, "tk_preview", passCandidate)) |
| + if w.Code != 303 || w.Header().Get("Location") != "/tasks/tk_preview/preview" { |
| + t.Fatalf("exchange: %d %v %s", w.Code, w.Header(), w.Body) |
| + } |
| + cookies := w.Result().Cookies() |
| + if len(cookies) != 1 { |
| + t.Fatal("cookies", cookies) |
| + } |
| + cookie := cookies[0] |
| + if cookie.Name != "__Secure-equipo-preview" || cookie.Domain != "" || cookie.Path != "/tasks/tk_preview/preview" || !cookie.HttpOnly || !cookie.Secure || cookie.SameSite != http.SameSiteStrictMode || cookie.MaxAge != 900 { |
| + t.Fatalf("cookie attributes: %+v", cookie) |
| + } |
| + for _, route := range []struct { |
| + method, path string |
| + allowed bool |
| + }{{"GET", "/tasks/tk_preview/preview", true}, {"POST", "/tasks/tk_preview/preview", false}, {"GET", "/tasks/tk_other/preview", false}, {"GET", "/tasks/tk_preview", false}, {"GET", "/api/v1/tasks/tk_preview", false}, {"GET", "/api/v1/events", false}, {"GET", "/api/v1/attachments/nope", false}} { |
| + req := httptest.NewRequest(route.method, "https://equipo.example"+route.path, nil) |
| + req.AddCookie(cookie) |
| + req.Header.Set("Origin", "https://equipo.example") |
| + answer := httptest.NewRecorder() |
| + h.ServeHTTP(answer, req) |
| + if route.allowed { |
| + if answer.Code != 200 || !strings.Contains(answer.Header().Get("Content-Security-Policy"), "frame-src https://eq-preview.example.test;") || !strings.Contains(answer.Body.String(), `sandbox="allow-scripts allow-same-origin"`) { |
| + t.Fatalf("wrapper %d %s", answer.Code, answer.Body) |
| + } |
| + } else if answer.Code >= 200 && answer.Code < 300 { |
| + t.Fatalf("grant escaped scope: %s %s", route.method, route.path) |
| + } |
| + } |
| + for _, input := range []struct{ token, task, candidate string }{{pass.Pass, "tk_preview", passCandidate}, {strings.Repeat("a", 43), "tk_preview", passCandidate}, {pass.Pass, "tk_other", passCandidate}} { |
| + w = httptest.NewRecorder() |
| + h.ServeHTTP(w, passExchangeRequest(input.token, input.task, input.candidate)) |
| + if w.Code != 404 || strings.Contains(w.Body.String(), pass.Pass) { |
| + t.Fatalf("observable refusal: %d %s", w.Code, w.Body) |
| + } |
| + } |
| +} |
| +func TestPreviewCookiePresenceNeverFallsThrough(t *testing.T) { |
| + r := newPreviewPassRig(t) |
| + // Even an otherwise valid browser session must not rescue a refused grant. |
| + normal := 0 |
| + app := &application{store: r.s, origin: r.s.personOrigin} |
| + for _, raw := range []string{"__Secure-equipo-preview=invalid", "__Secure-equipo-preview=", "__Secure-equipo-preview=\"broken", "__Secure-equipo-preview=a; __Secure-equipo-preview=b"} { |
| + route := chi.NewRouter() |
| + route.Get("/tasks/{id}/preview", app.previewGrantOrBrowser(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { normal++; w.WriteHeader(200) })).ServeHTTP) |
| + req := httptest.NewRequest("GET", "https://equipo.example/tasks/tk_preview/preview", nil) |
| + req.Header.Set("Cookie", raw+"; normal-session=valid") |
| + w := httptest.NewRecorder() |
| + route.ServeHTTP(w, req) |
| + if w.Code != 404 { |
| + t.Fatalf("invalid cookie %q: %d", raw, w.Code) |
| + } |
| + } |
| + if normal != 0 { |
| + t.Fatal("fell through to normal sign-in", normal) |
| + } |
| +} |
| + |
| +func TestPreviewExchangeRejectsConflictingContext(t *testing.T) { |
| + r := newPreviewPassRig(t) |
| + h := previewPassRouter(t, r) |
| + p := r.mint(t) |
| + changes := []struct { |
| + name string |
| + change func(*http.Request) |
| + }{ |
| + {"query", func(q *http.Request) { q.URL.RawQuery = "redirect=https://evil.example" }}, |
| + {"origin", func(q *http.Request) { q.Header.Set("Origin", "https://evil.example") }}, |
| + {"referer", func(q *http.Request) { q.Header.Set("Referer", "https://evil.example/") }}, |
| + {"fetch-site", func(q *http.Request) { q.Header.Set("Sec-Fetch-Site", "cross-site") }}, |
| + {"bearer", func(q *http.Request) { q.Header.Set("Authorization", "Bearer "+r.credential.Token) }}, |
| + {"type", func(q *http.Request) { q.Header.Set("Content-Type", "text/plain") }}, |
| + {"get", func(q *http.Request) { q.Method = "GET" }}, |
| + {"extra", func(q *http.Request) { |
| + q.Body = io.NopCloser(strings.NewReader("pass=" + p.Pass + "&task=tk_preview&candidate=" + passCandidate + "&redirect=x")) |
| + }}, |
| + {"duplicate", func(q *http.Request) { |
| + q.Body = io.NopCloser(strings.NewReader("pass=" + p.Pass + "&pass=" + p.Pass + "&task=tk_preview&candidate=" + passCandidate)) |
| + }}, |
| + {"bound", func(q *http.Request) { |
| + q.Body = io.NopCloser(strings.NewReader("pass=" + p.Pass + "&task=tk_preview&candidate=" + passCandidate + strings.Repeat("&", 4096))) |
| + }}, |
| + } |
| + for _, tt := range changes { |
| + t.Run(tt.name, func(t *testing.T) { |
| + request := passExchangeRequest(p.Pass, "tk_preview", passCandidate) |
| + tt.change(request) |
| + response := httptest.NewRecorder() |
| + h.ServeHTTP(response, request) |
| + if response.Code < 400 || response.Header().Get("Set-Cookie") != "" || response.Header().Get("Location") != "" { |
| + t.Fatalf("accepted conflicting context: %d %v", response.Code, response.Header()) |
| + } |
| + }) |
| + } |
| + response := httptest.NewRecorder() |
| + h.ServeHTTP(response, passExchangeRequest(p.Pass, "tk_preview", passCandidate)) |
| + if response.Code != 303 { |
| + t.Fatalf("refused requests consumed pass: %d %s", response.Code, response.Body) |
| + } |
| +} |
| + |
| +func TestPreviewExpiredCookieAndUnsafePOSTNeverFallThrough(t *testing.T) { |
| + r := newPreviewPassRig(t) |
| + pass := r.mint(t) |
| + grant, err := r.s.exchangePreviewPass(r.ctx, pass.Pass, "tk_preview", passCandidate, "192.0.2.1") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + app := &application{store: r.s, origin: r.s.personOrigin} |
| + calls := 0 |
| + handler := app.previewGrantOrBrowser(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++; w.WriteHeader(200) })) |
| + for _, method := range []string{"POST", "GET"} { |
| + if method == "GET" { |
| + r.clock.Advance(15 * time.Minute) |
| + } |
| + req := httptest.NewRequest(method, "https://equipo.example/tasks/tk_preview/preview", nil) |
| + ctx := chi.NewRouteContext() |
| + ctx.URLParams.Add("id", "tk_preview") |
| + req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, ctx)) |
| + req.Header.Set("Cookie", previewCookie+"="+grant.Secret+"; normal-session=valid-browser-session") |
| + out := httptest.NewRecorder() |
| + handler.ServeHTTP(out, req) |
| + if out.Code < 400 || calls != 0 { |
| + t.Fatalf("%s grant fell through: code=%d calls=%d", method, out.Code, calls) |
| + } |
| + } |
| +} |
diff --git a/internal/equipo/preview_pass_models.go b/internal/equipo/preview_pass_models.go| new file mode 100644 |
| index 00000000..4bd6ec13 |
| --- /dev/null |
| +++ b/internal/equipo/preview_pass_models.go |
| @@ -0,0 +1,3 @@ |
| +package equipo |
| + |
| +func init() { Models = append(Models, &previewPassRecord{}, &previewGrantRecord{}) } |
diff --git a/internal/equipo/preview_pass_security_test.go b/internal/equipo/preview_pass_security_test.go| new file mode 100644 |
| index 00000000..e28744dc |
| --- /dev/null |
| +++ b/internal/equipo/preview_pass_security_test.go |
| @@ -0,0 +1,283 @@ |
| +package equipo |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "gorm.io/gorm" |
| +) |
| + |
| +func TestPreviewSecretsAreHashedAndIndexed(t *testing.T) { |
| + r := newPreviewPassRig(t) |
| + var lookups []string |
| + if err := r.s.db.G.Callback().Query().After("gorm:query").Register("preview_exact_hash", func(tx *gorm.DB) { |
| + if tx.Statement.Table == "preview_passes" || tx.Statement.Table == "preview_grants" { |
| + lookups = append(lookups, tx.Statement.SQL.String()) |
| + } |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + p := r.mint(t) |
| + g, e := r.s.exchangePreviewPass(r.ctx, p.Pass, "tk_preview", passCandidate, "192.0.2.1") |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if _, err := r.s.readPreviewGrant(r.ctx, g.Secret, "tk_preview", "192.0.2.1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(lookups) != 2 { |
| + t.Fatal("unexpected secret lookups", len(lookups)) |
| + } |
| + for _, query := range lookups { |
| + if !strings.Contains(query, "WHERE hash = ?") { |
| + t.Fatal("secret lookup is not an exact hash predicate") |
| + } |
| + } |
| + for _, item := range []struct{ table, secret string }{{"preview_passes", p.Pass}, {"preview_grants", g.Secret}} { |
| + var hash string |
| + if e := r.s.db.Reader().QueryRow("SELECT hash FROM " + item.table).Scan(&hash); e != nil { |
| + t.Fatal(e) |
| + } |
| + if hash != previewHash(item.secret) || hash == item.secret || len(hash) != 64 { |
| + t.Fatal("plaintext or wrong hash") |
| + } |
| + var a, b, c int |
| + var plan string |
| + if e := r.s.db.Reader().QueryRow("EXPLAIN QUERY PLAN SELECT * FROM "+item.table+" WHERE hash = ?", hash).Scan(&a, &b, &c, &plan); e != nil { |
| + t.Fatal(e) |
| + } |
| + if !strings.Contains(plan, "SEARCH") || !strings.Contains(plan, "INDEX") || !strings.Contains(plan, "hash=?") { |
| + t.Fatal("unindexed lookup", plan) |
| + } |
| + } |
| + rows, e := r.s.db.Reader().Query("SELECT record_id FROM audit_events WHERE kind LIKE 'preview.%'") |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer rows.Close() |
| + count := 0 |
| + for rows.Next() { |
| + var id string |
| + if e = rows.Scan(&id); e != nil { |
| + t.Fatal(e) |
| + } |
| + count++ |
| + if strings.Contains(id, p.Pass) || strings.Contains(id, g.Secret) || strings.Contains(id, "https://") { |
| + t.Fatal("audit contains credential or URL") |
| + } |
| + } |
| + if count != 2 { |
| + t.Fatal("missing audit", count) |
| + } |
| +} |
| +func TestPreviewPassAuditFailureRollsBackExchange(t *testing.T) { |
| + r := newPreviewPassRig(t) |
| + p := r.mint(t) |
| + _, e := r.s.db.Writer().Exec(`CREATE TRIGGER deny_preview_audit BEFORE INSERT ON audit_events WHEN NEW.kind = 'preview.pass.exchange' BEGIN SELECT RAISE(ABORT, 'fixture'); END`) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + g, e := r.s.exchangePreviewPass(r.ctx, p.Pass, "tk_preview", passCandidate, "192.0.2.1") |
| + if e == nil || g.Secret != "" { |
| + t.Fatal("issued grant without audit") |
| + } |
| + var grants int |
| + if e = r.s.db.Reader().QueryRow("SELECT count(*) FROM preview_grants").Scan(&grants); e != nil || grants != 0 { |
| + t.Fatal("grant survived rollback", e, grants) |
| + } |
| + if _, e = r.s.db.Writer().Exec("DROP TRIGGER deny_preview_audit"); e != nil { |
| + t.Fatal(e) |
| + } |
| + if _, e = r.s.exchangePreviewPass(r.ctx, p.Pass, "tk_preview", passCandidate, "192.0.2.1"); e != nil { |
| + t.Fatal("failed transaction consumed pass", e) |
| + } |
| +} |
| +func TestPreviewPassRatesCannotBeEvadedByChangingIP(t *testing.T) { |
| + r := newPreviewPassRig(t) |
| + for i := 0; i < 10; i++ { |
| + if _, e := r.s.mintPreviewPass(r.ctx, r.principal, "tk_preview", passCandidate, fmt.Sprintf("192.0.2.%d", i)); e != nil { |
| + t.Fatal(e) |
| + } |
| + } |
| + if _, e := r.s.mintPreviewPass(r.ctx, r.principal, "tk_preview", passCandidate, "198.51.100.1"); !errors.Is(e, ErrPreviewAccess) { |
| + t.Fatal("device mint limit", e) |
| + } |
| + r.clock.Advance(time.Minute) |
| + p := r.mint(t) |
| + if _, e := r.s.db.Writer().Exec("UPDATE members SET active=0"); e != nil { |
| + t.Fatal(e) |
| + } |
| + for i := 0; i < 10; i++ { |
| + _, _ = r.s.exchangePreviewPass(context.Background(), p.Pass, "tk_preview", passCandidate, fmt.Sprintf("192.0.2.%d", i)) |
| + } |
| + if _, e := r.s.db.Writer().Exec("UPDATE members SET active=1"); e != nil { |
| + t.Fatal(e) |
| + } |
| + if _, e := r.s.exchangePreviewPass(context.Background(), p.Pass, "tk_preview", passCandidate, "198.51.100.1"); !errors.Is(e, ErrPreviewAccess) { |
| + t.Fatal("device exchange limit", e) |
| + } |
| +} |
| +func TestPreviewPassUnknownTokensCountAgainstIPLimit(t *testing.T) { |
| + r := newPreviewPassRig(t) |
| + p := r.mint(t) |
| + for range 30 { |
| + _, _ = r.s.exchangePreviewPass(context.Background(), "invalid", "tk_preview", passCandidate, "198.51.100.2") |
| + } |
| + if _, e := r.s.exchangePreviewPass(context.Background(), p.Pass, "tk_preview", passCandidate, "198.51.100.2"); !errors.Is(e, ErrPreviewAccess) { |
| + t.Fatal("unknown tokens evaded IP limit", e) |
| + } |
| + if _, e := r.s.exchangePreviewPass(context.Background(), p.Pass, "tk_preview", passCandidate, "198.51.100.3"); e != nil { |
| + t.Fatal("IP limit blocked different IP", e) |
| + } |
| +} |
| +func TestPreviewGrantBindingAndNoSlidingExpiry(t *testing.T) { |
| + for _, field := range []string{"instance", "person", "credential", "epoch", "task_id", "candidate", "step_id", "attempt", "fingerprint"} { |
| + t.Run(field, func(t *testing.T) { |
| + r := newPreviewPassRig(t) |
| + p := r.mint(t) |
| + g, e := r.s.exchangePreviewPass(r.ctx, p.Pass, "tk_preview", passCandidate, "192.0.2.1") |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + r.clock.Advance(14 * time.Minute) |
| + if _, e = r.s.readPreviewGrant(r.ctx, g.Secret, "tk_preview", "192.0.2.1"); e != nil { |
| + t.Fatal(e) |
| + } |
| + var expires time.Time |
| + if e = r.s.db.Reader().QueryRow("SELECT expires_at FROM preview_grants").Scan(&expires); e != nil { |
| + t.Fatal(e) |
| + } |
| + if !expires.Equal(g.ExpiresAt) { |
| + t.Fatal("sliding expiry") |
| + } |
| + value := any("different") |
| + if field == "epoch" || field == "attempt" { |
| + value = int64(99) |
| + } |
| + if e = r.s.write(context.Background(), func(tx *gorm.DB) error { |
| + return tx.Model(&previewGrantRecord{}).Where("hash = ?", previewHash(g.Secret)).Select(field).Updates(map[string]any{field: value}).Error |
| + }); e != nil { |
| + t.Fatal(e) |
| + } |
| + if _, e = r.s.readPreviewGrant(r.ctx, g.Secret, "tk_preview", "192.0.2.1"); e == nil { |
| + t.Fatal("ignored binding", field) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestPreviewPassCapsAndDeploymentEligibility(t *testing.T) { |
| + for _, kind := range []string{"preview-cap", "device-cap", "same-host", "same-host-dot", "unsafe-pending", "preview-candidate", "preview-expired", "final", "unknown-grant", "revoked-grant", "audit-read"} { |
| + t.Run(kind, func(t *testing.T) { |
| + r := newPreviewPassRig(t) |
| + exec := func(q string, args ...any) { |
| + t.Helper() |
| + if _, e := r.s.db.Writer().Exec(q, args...); e != nil { |
| + t.Fatal(e) |
| + } |
| + } |
| + switch kind { |
| + case "preview-cap": |
| + exec("UPDATE chat_steps SET preview=json_set(preview,'$.expires_at',?) WHERE id='preview_step'", r.clock.Now().Add(30*time.Second).Format(time.RFC3339)) |
| + case "device-cap": |
| + exec("UPDATE person_devices SET token_expires_at=?", r.clock.Now().Add(30*time.Second)) |
| + case "same-host": |
| + exec("UPDATE chat_steps SET preview=json_set(preview,'$.url','https://equipo.example:8443/') WHERE id='preview_step'") |
| + case "same-host-dot": |
| + exec("UPDATE chat_steps SET preview=json_set(preview,'$.url','https://equipo.example.:8443/') WHERE id='preview_step'") |
| + case "unsafe-pending": |
| + exec("UPDATE chat_steps SET preview=json_set(preview,'$.outcome','failed'),reason='preview_headers' WHERE id='preview_step'") |
| + case "preview-candidate": |
| + exec("UPDATE chat_steps SET candidate_sha=? WHERE id='preview_step'", strings.Repeat("2", 40)) |
| + case "preview-expired": |
| + exec("UPDATE chat_steps SET preview=json_set(preview,'$.expires_at',?) WHERE id='preview_step'", r.clock.Now().Format(time.RFC3339)) |
| + case "final": |
| + exec("UPDATE chat_tasks SET stage='done'") |
| + } |
| + p, e := r.s.mintPreviewPass(r.ctx, r.principal, "tk_preview", passCandidate, "192.0.2.1") |
| + switch kind { |
| + case "same-host", "same-host-dot", "unsafe-pending", "preview-candidate", "preview-expired", "final": |
| + if e == nil || p.Pass != "" { |
| + t.Fatal("ineligible preview minted", kind) |
| + } |
| + return |
| + } |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if strings.HasSuffix(kind, "-cap") && (!p.ExpiresAt.Equal(r.clock.Now().Add(30*time.Second)) || !p.GrantExpiresAt.Equal(p.ExpiresAt)) { |
| + t.Fatal("expiry cap lost") |
| + } |
| + grant, e := r.s.exchangePreviewPass(r.ctx, p.Pass, "tk_preview", passCandidate, "192.0.2.1") |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + switch kind { |
| + case "unknown-grant": |
| + grant.Secret = strings.Repeat("A", 43) |
| + case "revoked-grant": |
| + exec("UPDATE members SET active=0") |
| + case "audit-read": |
| + r.clock.Advance(15 * time.Minute) |
| + default: |
| + return |
| + } |
| + if task, e := r.s.readPreviewGrant(r.ctx, grant.Secret, "tk_preview", "192.0.2.1"); e == nil || task.ID != "" { |
| + t.Fatal("invalid grant read succeeded") |
| + } |
| + if kind == "audit-read" { |
| + var count int |
| + if e := r.s.db.Reader().QueryRow("SELECT count(*) FROM audit_events WHERE kind='preview.pass.refused'").Scan(&count); e != nil || count != 1 { |
| + t.Fatal("missing refusal audit", count, e) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestPreviewDeviceGuardBeforeTaskRead(t *testing.T) { |
| + r := newPreviewPassRig(t) |
| + if _, err := r.s.db.Writer().Exec("UPDATE person_devices SET revoked_at=?", r.clock.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + var refused error |
| + err := r.s.write(context.Background(), func(tx *gorm.DB) error { _, refused = r.s.previewDevice(tx, r.principal); return nil }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !errors.Is(refused, ErrPreviewAccess) { |
| + t.Fatal("device helper accepted revoked credential") |
| + } |
| +} |
| + |
| +func TestPreviewKnownRefusalsAreAuditedAndDeviceLimited(t *testing.T) { |
| + r := newPreviewPassRig(t) |
| + pass := r.mint(t) |
| + for i := 0; i < 10; i++ { |
| + _, err := r.s.exchangePreviewPass(r.ctx, pass.Pass, "tk_other", passCandidate, fmt.Sprintf("198.51.100.%d", i)) |
| + if !errors.Is(err, ErrPreviewAccess) { |
| + t.Fatal("wrong binding accepted", err) |
| + } |
| + } |
| + if _, err := r.s.exchangePreviewPass(r.ctx, pass.Pass, "tk_preview", passCandidate, "203.0.113.1"); !errors.Is(err, ErrPreviewAccess) { |
| + t.Fatal("known refusals bypassed device rate", err) |
| + } |
| + var count int |
| + if err := r.s.db.Reader().QueryRow("SELECT count(*) FROM audit_events WHERE kind='preview.pass.refused'").Scan(&count); err != nil || count != 10 { |
| + t.Fatal("known refusals missing audit", count, err) |
| + } |
| +} |
| +func TestPreviewStaleMintHasRefusalAudit(t *testing.T) { |
| + r := newPreviewPassRig(t) |
| + if _, err := r.s.mintPreviewPass(r.ctx, r.principal, "tk_preview", strings.Repeat("2", 40), "192.0.2.1"); !errors.Is(err, ErrPreviewChanged) { |
| + t.Fatal(err) |
| + } |
| + var count int |
| + if err := r.s.db.Reader().QueryRow("SELECT count(*) FROM audit_events WHERE kind='preview.pass.refused'").Scan(&count); err != nil || count != 1 { |
| + t.Fatal("stale mint missing audit", count, err) |
| + } |
| +} |
diff --git a/internal/equipo/preview_pass_store.go b/internal/equipo/preview_pass_store.go| new file mode 100644 |
| index 00000000..1dfcd1f8 |
| --- /dev/null |
| +++ b/internal/equipo/preview_pass_store.go |
| @@ -0,0 +1,162 @@ |
| +package equipo |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "encoding/json" |
| + "net/url" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/oficinaid" |
| + "amadan.net/oficina/equipo/internal/equipo/personapi" |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "golang.org/x/net/idna" |
| + "gorm.io/gorm" |
| +) |
| + |
| +type previewBinding struct { |
| + Instance, Person, Credential, TaskID, Candidate, StepID, Fingerprint string |
| + Epoch, Attempt int64 |
| +} |
| +type previewPassRecord struct { |
| + Hash string `gorm:"primaryKey"` |
| + ID string |
| + Binding previewBinding `gorm:"embedded"` |
| + ExpiresAt time.Time `gorm:"index:preview_pass_expiry"` |
| + GrantExpiresAt time.Time |
| + ConsumedAt *time.Time |
| +} |
| + |
| +func (previewPassRecord) TableName() string { return "preview_passes" } |
| + |
| +type previewGrantRecord struct { |
| + Hash string `gorm:"primaryKey"` |
| + ID string |
| + Binding previewBinding `gorm:"embedded"` |
| + ExpiresAt time.Time `gorm:"index:preview_grant_expiry"` |
| +} |
| + |
| +func (previewGrantRecord) TableName() string { return "preview_grants" } |
| + |
| +func previewHash(secret string) string { |
| + raw, err := base64.RawURLEncoding.Strict().DecodeString(secret) |
| + if err != nil || len(raw) != 32 || base64.RawURLEncoding.EncodeToString(raw) != secret { |
| + return "" |
| + } |
| + sum := sha256.Sum256(raw) |
| + return hex.EncodeToString(sum[:]) |
| +} |
| +func (s *Store) previewDevice(tx *gorm.DB, p PersonPrincipal) (personapi.DeviceRecord, error) { |
| + var row personapi.DeviceRecord |
| + if p.CredentialID == "" || p.Address == "" || p.Pending { |
| + return row, ErrPreviewAccess |
| + } |
| + current, err := s.personDevices().VerifyAt(tx, p.CredentialID, "") |
| + if err != nil || current.Address != p.Address || current.SessionEpoch != p.SessionEpoch { |
| + return row, ErrPreviewAccess |
| + } |
| + if err = tx.Where("id = ?", p.CredentialID).First(&row).Error; err != nil { |
| + return row, ErrPreviewAccess |
| + } |
| + if row.NativeSessionHash != "" { |
| + if s.personNativeSession == nil { |
| + return row, ErrPreviewAccess |
| + } |
| + sess, e := s.personNativeSession(tx, row.NativeSessionHash) |
| + if e != nil || sess.Subject != p.Address || string(sess.Method) != oficinaid.NativeMethod || sess.At.Unix() != p.SessionEpoch || !s.runnerClock.Now().Before(sess.At.Add(oficinaid.NativeLifetime)) { |
| + return row, ErrPreviewAccess |
| + } |
| + } |
| + return row, nil |
| +} |
| +func (s *Store) previewTask(tx *gorm.DB, b previewBinding) (wire.Task, error) { |
| + p := PersonPrincipal{Address: b.Person, CredentialID: b.Credential, SessionEpoch: b.Epoch} |
| + device, err := s.previewDevice(tx, p) |
| + if err != nil || device.InstanceID != b.Instance { |
| + return wire.Task{}, ErrPreviewAccess |
| + } |
| + task, err := s.Chat().TaskAt(personapi.WithVerifiedPrincipal(tx.Statement.Context, p), tx, b.TaskID) |
| + if err != nil { |
| + return wire.Task{}, ErrPreviewAccess |
| + } |
| + return task, nil |
| +} |
| +func selectedPreview(task wire.Task) (wire.Step, bool) { |
| + for i := len(task.Steps) - 1; i >= 0; i-- { |
| + if task.Steps[i].Specialist == wire.SpecialistPreview { |
| + return task.Steps[i], true |
| + } |
| + } |
| + return wire.Step{}, false |
| +} |
| +func (s *Store) previewDeployment(task wire.Task) (wire.Step, string, error) { |
| + step, ok := selectedPreview(task) |
| + if !ok || step.Preview == nil || step.Preview.Outcome != wire.PreviewDeployed || step.Preview.URL == "" { |
| + return step, "", ErrPreviewAccess |
| + } |
| + p := step.Preview |
| + u, e := url.Parse(p.URL) |
| + own, ownErr := url.Parse(s.personOrigin) |
| + if e != nil || ownErr != nil || canonicalPreviewHost(u.Hostname()) == "" || canonicalPreviewHost(u.Hostname()) == canonicalPreviewHost(own.Hostname()) { |
| + return step, "", ErrPreviewAccess |
| + } |
| + if _, _, err := previewWrapper(p.URL, p.Unsafe); err != nil { |
| + return step, "", ErrPreviewAccess |
| + } |
| + raw, _ := json.Marshal(p) |
| + sum := sha256.Sum256(raw) |
| + return step, hex.EncodeToString(sum[:]), nil |
| +} |
| +func (s *Store) validatePreview(task wire.Task, b previewBinding) error { |
| + step, fingerprint, err := s.previewDeployment(task) |
| + if task.CandidateSHA != b.Candidate || err != nil || step.CandidateSHA != b.Candidate || step.ID != b.StepID || step.Attempt != b.Attempt || fingerprint != b.Fingerprint { |
| + return ErrPreviewChanged |
| + } |
| + if (step.Preview.ExpiresAt != nil && !s.runnerClock.Now().Before(*step.Preview.ExpiresAt)) || (strings.HasPrefix(step.Preview.App, "eq-") && wire.FinalStage(task.Stage)) { |
| + return ErrPreviewExpired |
| + } |
| + return nil |
| +} |
| +func (s *Store) previewRate(tx *gorm.DB, kind, ip, device string) (bool, error) { |
| + limit := 10 |
| + if kind == "read" { |
| + limit = 120 |
| + } |
| + ok, e := runnerRateAt(tx, "preview:"+kind+":ip:"+runnerHash(s.personKey, ip), s.runnerClock.Now(), time.Minute, limit*3) |
| + if e != nil || !ok { |
| + return ok, e |
| + } |
| + if device != "" { |
| + return runnerRateAt(tx, "preview:"+kind+":device:"+device, s.runnerClock.Now(), time.Minute, limit) |
| + } |
| + return true, nil |
| +} |
| +func (s *Store) prunePreviews(tx *gorm.DB) error { |
| + // Indexed expiry predicates; no secret lookup ever scans these tables. |
| + cutoff := s.runnerClock.Now().Add(-time.Hour) |
| + if err := tx.Where("expires_at < ?", cutoff).Delete(&previewPassRecord{}).Error; err != nil { |
| + return err |
| + } |
| + return tx.Where("expires_at < ?", cutoff).Delete(&previewGrantRecord{}).Error |
| +} |
| +func minPreviewTime(a, b time.Time) time.Time { |
| + if b.Before(a) { |
| + return b |
| + } |
| + return a |
| +} |
| +func previewPrincipal(ctx context.Context, p PersonPrincipal) bool { |
| + actual, ok := personapi.PrincipalFrom(ctx) |
| + return ok && actual.Address == p.Address && actual.CredentialID == p.CredentialID && actual.SessionEpoch == p.SessionEpoch |
| +} |
| + |
| +func canonicalPreviewHost(host string) string { |
| + ascii, err := idna.Lookup.ToASCII(strings.TrimSuffix(host, ".")) |
| + if err != nil { |
| + return "" |
| + } |
| + return strings.ToLower(ascii) |
| +} |
diff --git a/internal/equipo/preview_pass_test.go b/internal/equipo/preview_pass_test.go| new file mode 100644 |
| index 00000000..647dff09 |
| --- /dev/null |
| +++ b/internal/equipo/preview_pass_test.go |
| @@ -0,0 +1,168 @@ |
| +package equipo |
| + |
| +import ( |
| + "context" |
| + "encoding/base64" |
| + "encoding/json" |
| + "errors" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/oficinaid" |
| + "amadan.net/oficina/equipo/internal/equipo/personapi" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| + "gorm.io/gorm" |
| +) |
| + |
| +const passCandidate = "1111111111111111111111111111111111111111" |
| + |
| +type previewPassRig struct { |
| + s *Store |
| + clock *team.FakeClock |
| + principal PersonPrincipal |
| + credential PersonCredential |
| + ctx context.Context |
| +} |
| + |
| +func newPreviewPassRig(t *testing.T) *previewPassRig { |
| + return newPreviewPassRigAt(t, time.Date(2026, 11, 26, 12, 0, 0, 0, time.UTC)) |
| +} |
| +func newPreviewPassRigAt(t *testing.T, now time.Time) *previewPassRig { |
| + t.Helper() |
| + s, cfg, _ := agentFixture(t) |
| + clock := team.NewFakeClock(now) |
| + s.runnerClock = clock |
| + s.personOrigin = cfg.Origin |
| + s.personKey = cfg.InstanceKey |
| + if _, err := s.db.Writer().Exec("UPDATE members SET session_epoch=?", now.Add(-time.Hour).Unix()); err != nil { |
| + t.Fatal(err) |
| + } |
| + s.personNativeSession = func(*gorm.DB, string) (sessions.Session, error) { |
| + return sessions.Session{Subject: cfg.Owners[0], At: now, Method: oficinaid.NativeMethod}, nil |
| + } |
| + p := PersonPrincipal{Address: cfg.Owners[0], SessionEpoch: now.Unix(), SessionHash: "native-test-session"} |
| + cred, err := s.personDevices().RegisterNative(personapi.WithVerifiedPrincipal(context.Background(), p), Actor{Address: p.Address}, base64.RawURLEncoding.EncodeToString(make([]byte, 32)), "Phone") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + p.CredentialID = cred.ID |
| + p.SessionHash = "" |
| + ctx := personapi.WithVerifiedPrincipal(context.Background(), p) |
| + exec := func(q string, args ...any) { |
| + t.Helper() |
| + if _, e := s.db.Writer().Exec(q, args...); e != nil { |
| + t.Fatal(e) |
| + } |
| + } |
| + exec("INSERT INTO chat_projects(id,repo,state,title) VALUES('p_preview','oficina/equipo','active','Equipo')") |
| + exec("INSERT INTO chat_tasks(id,project_id,title,stage,creator,revision) VALUES('tk_preview','p_preview','Preview','in_review',?,1)", p.Address) |
| + exec("INSERT INTO chat_steps(id,task_id,idx,specialist,state,attempt,candidate_sha,pushed,terminated,revision) VALUES('eng_preview','tk_preview',0,'engineering','done',1,?,1,1,1)", passCandidate) |
| + expiry := now.Add(time.Hour) |
| + result, _ := json.Marshal(wire.PreviewResult{Phase: wire.PreviewDone, Outcome: wire.PreviewDeployed, URL: "https://eq-preview.example.test/", App: "eq-preview", Digest: strings.Repeat("a", 64), ExpiresAt: &expiry}) |
| + exec("INSERT INTO chat_steps(id,task_id,idx,specialist,state,attempt,candidate_sha,preview,revision) VALUES('preview_step','tk_preview',1,'preview','done',1,?,?,1)", passCandidate, string(result)) |
| + return &previewPassRig{s, clock, p, cred, ctx} |
| +} |
| +func (r *previewPassRig) mint(t *testing.T) previewPass { |
| + t.Helper() |
| + p, e := r.s.mintPreviewPass(r.ctx, r.principal, "tk_preview", passCandidate, "192.0.2.1") |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + return p |
| +} |
| +func TestPreviewPassSingleUseAndLifetime(t *testing.T) { |
| + r := newPreviewPassRig(t) |
| + p := r.mint(t) |
| + raw, e := base64.RawURLEncoding.DecodeString(p.Pass) |
| + if e != nil || len(raw) != 32 { |
| + t.Fatal("pass is not 32 random bytes") |
| + } |
| + if !p.ExpiresAt.Equal(r.clock.Now().Add(time.Minute)) || !p.GrantExpiresAt.Equal(r.clock.Now().Add(15*time.Minute)) { |
| + t.Fatal("wrong lifetimes", p.ExpiresAt, p.GrantExpiresAt) |
| + } |
| + var wg sync.WaitGroup |
| + results := make(chan error, 2) |
| + grants := make(chan previewGrant, 2) |
| + for range 2 { |
| + wg.Go(func() { |
| + g, e := r.s.exchangePreviewPass(r.ctx, p.Pass, "tk_preview", passCandidate, "192.0.2.1") |
| + results <- e |
| + grants <- g |
| + }) |
| + } |
| + wg.Wait() |
| + close(results) |
| + close(grants) |
| + wins := 0 |
| + for e := range results { |
| + if e == nil { |
| + wins++ |
| + } else if !errors.Is(e, ErrPreviewAccess) { |
| + t.Fatal(e) |
| + } |
| + } |
| + if wins != 1 { |
| + t.Fatal("exchange winners", wins) |
| + } |
| + for g := range grants { |
| + if g.Secret == "" { |
| + continue |
| + } |
| + if g.Secret == p.Pass { |
| + t.Fatal("grant reused pass") |
| + } |
| + if _, e := r.s.readPreviewGrant(r.ctx, g.Secret, "tk_preview", "192.0.2.1"); e != nil { |
| + t.Fatal(e) |
| + } |
| + r.clock.Advance(15 * time.Minute) |
| + if _, e := r.s.readPreviewGrant(r.ctx, g.Secret, "tk_preview", "192.0.2.1"); !errors.Is(e, ErrPreviewExpired) { |
| + t.Fatal("expiry", e) |
| + } |
| + } |
| +} |
| +func TestPreviewPassRefusals(t *testing.T) { |
| + for _, kind := range []string{"unknown", "task", "candidate", "expired", "revoked", "member", "session", "redeployed", "moved"} { |
| + t.Run(kind, func(t *testing.T) { |
| + r := newPreviewPassRig(t) |
| + p := r.mint(t) |
| + token, task, candidate := p.Pass, "tk_preview", passCandidate |
| + want := ErrPreviewAccess |
| + exec := func(q string, args ...any) { |
| + t.Helper() |
| + if _, e := r.s.db.Writer().Exec(q, args...); e != nil { |
| + t.Fatal(e) |
| + } |
| + } |
| + switch kind { |
| + case "unknown": |
| + token = base64.RawURLEncoding.EncodeToString(make([]byte, 32)) |
| + case "task": |
| + task = "tk_other" |
| + case "candidate": |
| + candidate = strings.Repeat("2", 40) |
| + case "expired": |
| + r.clock.Advance(time.Minute) |
| + want = ErrPreviewExpired |
| + case "revoked": |
| + exec("UPDATE person_devices SET revoked_at=? WHERE id=?", r.clock.Now(), r.credential.ID) |
| + case "member": |
| + exec("UPDATE members SET active=0") |
| + case "session": |
| + r.s.personNativeSession = func(*gorm.DB, string) (sessions.Session, error) { return sessions.Session{}, errors.New("revoked") } |
| + case "redeployed": |
| + exec("UPDATE chat_steps SET attempt=2 WHERE id='preview_step'") |
| + want = ErrPreviewChanged |
| + case "moved": |
| + exec("UPDATE chat_steps SET candidate_sha=? WHERE id='eng_preview'", strings.Repeat("2", 40)) |
| + want = ErrPreviewChanged |
| + } |
| + if _, e := r.s.exchangePreviewPass(r.ctx, token, task, candidate, "192.0.2.1"); !errors.Is(e, want) { |
| + t.Fatalf("got %v, want %v", e, want) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/equipo/preview_wrapper.go b/internal/equipo/preview_wrapper.go| index 68dbf881..a4c42989 100644 |
| --- a/internal/equipo/preview_wrapper.go |
| +++ b/internal/equipo/preview_wrapper.go |
| @@ -9,7 +9,6 @@ import ( |
| "net/url" |
| "strconv" |
| "strings" |
| - "time" |
| "amadan.net/oficina/equipo/internal/wire" |
| "github.com/go-chi/chi/v5" |
| @@ -51,11 +50,9 @@ func (a *application) previewPage(w http.ResponseWriter, r *http.Request) { |
| continue |
| } |
| if p != nil && p.Outcome == wire.PreviewDeployed && p.URL != "" { |
| - if u, err := url.Parse(p.URL); err == nil && strings.EqualFold(u.Host, r.Host) { |
| - a.failure(w, r, ErrForbidden) |
| - return |
| - } |
| - if (p.ExpiresAt != nil && !time.Now().Before(*p.ExpiresAt)) || (strings.HasPrefix(p.App, "eq-") && wire.FinalStage(task.Stage)) || step.CandidateSHA != task.CandidateSHA { |
| + selected, fingerprint, err := a.store.previewDeployment(task) |
| + binding := previewBinding{Candidate: task.CandidateSHA, StepID: selected.ID, Attempt: selected.Attempt, Fingerprint: fingerprint} |
| + if err != nil || a.store.validatePreview(task, binding) != nil { |
| http.NotFound(w, r) |
| return |
| } |
diff --git a/internal/plan3test/person_api_contract_test.go b/internal/plan3test/person_api_contract_test.go| index 1b8ac088..ec839338 100644 |
| --- a/internal/plan3test/person_api_contract_test.go |
| +++ b/internal/plan3test/person_api_contract_test.go |
| @@ -84,6 +84,10 @@ func personAPIContractCoverage(t *testing.T) { |
| } |
| } |
| must(t, chi.Walk(f.Store.PersonAPIHandler().(chi.Routes), func(method, path string, _ http.Handler, _ ...func(http.Handler) http.Handler) error { |
| + // The app-owned preview capability has a separate contract test. |
| + if method == "POST" && path == "/tasks/{id}/preview-pass" { |
| + return nil |
| + } |
| if thin[method+" "+path] { |
| return nil |
| } |
diff --git a/internal/plan3test/person_api_device_contract_test.go b/internal/plan3test/person_api_device_contract_test.go| index 18751758..b8bdfc83 100644 |
| --- a/internal/plan3test/person_api_device_contract_test.go |
| +++ b/internal/plan3test/person_api_device_contract_test.go |
| @@ -95,7 +95,7 @@ func TestPersonAPIDeviceContract(t *testing.T) { |
| for _, methods := range paths { |
| documented += len(methods.(map[string]any)) |
| } |
| - all := map[string]bool{"POST /native/oficina-id": true} |
| + all := map[string]bool{"POST /native/oficina-id": true, "POST /tasks/{id}/preview-pass": true} |
| for key := range engine { |
| all[key] = true |
| } |
diff --git a/internal/plan3test/preview_pass_contract_test.go b/internal/plan3test/preview_pass_contract_test.go| new file mode 100644 |
| index 00000000..c75ea563 |
| --- /dev/null |
| +++ b/internal/plan3test/preview_pass_contract_test.go |
| @@ -0,0 +1,47 @@ |
| +package plan3test |
| + |
| +import ( |
| + "encoding/json" |
| + "net/http" |
| + "os" |
| + "testing" |
| + |
| + "github.com/go-chi/chi/v5" |
| +) |
| + |
| +func TestPreviewPassContract(t *testing.T) { |
| + f := newFixture(t) |
| + found := false |
| + must(t, chi.Walk(f.Store.PersonAPIHandler().(chi.Routes), func(method, path string, _ http.Handler, _ ...func(http.Handler) http.Handler) error { |
| + if method == "POST" && path == "/tasks/{id}/preview-pass" { |
| + found = true |
| + } |
| + return nil |
| + })) |
| + if !found { |
| + t.Fatal("preview pass route missing") |
| + } |
| + raw, err := os.ReadFile("../../docs/api/equipo-v1.openapi.json") |
| + must(t, err) |
| + var doc map[string]any |
| + must(t, json.Unmarshal(raw, &doc)) |
| + op := doc["paths"].(map[string]any)["/tasks/{id}/preview-pass"].(map[string]any)["post"].(map[string]any) |
| + if op["operationId"] != "post_tasks_id_preview_pass" { |
| + t.Fatal("wrong operation") |
| + } |
| + security := op["security"].([]any) |
| + if len(security) != 1 || security[0].(map[string]any)["personBearer"] == nil { |
| + t.Fatal("pass must be device-only") |
| + } |
| + request := op["requestBody"].(map[string]any) |
| + if request["x-maxBytes"] != float64(4096) || request["x-rejectUnknownFields"] != true { |
| + t.Fatal("unbounded pass input") |
| + } |
| + if op["responses"].(map[string]any)["201"] == nil { |
| + t.Fatal("missing created response") |
| + } |
| + schema := doc["components"].(map[string]any)["schemas"].(map[string]any)["PreviewPass"].(map[string]any) |
| + if schema["additionalProperties"] != false || len(schema["required"].([]any)) != 3 || len(schema["properties"].(map[string]any)) != 3 { |
| + t.Fatal("unexpected pass representation") |
| + } |
| +} |
diff --git a/native/apple/Sources/EquipoActivity/Resources/Localizable.xcstrings b/native/apple/Sources/EquipoActivity/Resources/Localizable.xcstrings| index b61fab3a..d84a36e0 100644 |
| --- a/native/apple/Sources/EquipoActivity/Resources/Localizable.xcstrings |
| +++ b/native/apple/Sources/EquipoActivity/Resources/Localizable.xcstrings |
| @@ -1212,6 +1212,17 @@ |
| } |
| } |
| }, |
| + "evidence.candidate_changed": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "The change has been updated. Review it again." |
| + } |
| + } |
| + } |
| + }, |
| "fact.branch": { |
| "extractionState": "manual", |
| "localizations": { |
| @@ -2510,6 +2521,17 @@ |
| } |
| } |
| }, |
| + "question.expired": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Expired" |
| + } |
| + } |
| + } |
| + }, |
| "read.failed": { |
| "extractionState": "manual", |
| "localizations": { |
| @@ -4567,6 +4589,17 @@ |
| } |
| } |
| }, |
| + "work.reason.amadan_unreachable": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Amadan could not be reached to confirm Equipo may merge here" |
| + } |
| + } |
| + } |
| + }, |
| "work.reason.base_checks_failed": { |
| "extractionState": "manual", |
| "localizations": { |
| @@ -4732,6 +4765,17 @@ |
| } |
| } |
| }, |
| + "work.reason.merge_credential": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "the runner has no Amadan credential for this repository" |
| + } |
| + } |
| + } |
| + }, |
| "work.reason.merge_failed": { |
| "extractionState": "manual", |
| "localizations": { |
diff --git a/native/apple/Sources/EquipoKit/API/PreviewPass.swift b/native/apple/Sources/EquipoKit/API/PreviewPass.swift| new file mode 100644 |
| index 00000000..c3ac5ee4 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/API/PreviewPass.swift |
| @@ -0,0 +1,56 @@ |
| +import Foundation |
| + |
| +struct PreviewPass: Codable, Sendable { |
| + let pass: String |
| + let expiresAt: Date |
| + let grantExpiresAt: Date |
| +} |
| +extension EquipoClient { |
| + func previewPass(task: String, candidate: String) async throws -> PreviewPass { |
| + try await post("/tasks/\(escape(task))/preview-pass", try .json(["candidate_sha": candidate])) |
| + } |
| +} |
| + |
| +struct PreviewDestination: Equatable, Sendable { |
| + let origin: URL |
| + let taskID: String |
| + let candidate: String |
| + let wrapper: URL |
| + let exchangeURL: URL |
| + init?(origin: URL, taskID: String, candidate: String) { |
| + guard origin.scheme == "https", origin.host != nil, origin.user == nil, origin.password == nil, |
| + taskID.range(of: #"^[A-Za-z0-9_-]{1,128}\z"#, options: .regularExpression) != nil, |
| + candidate.range(of: #"^[0-9a-f]{40}\z"#, options: .regularExpression) != nil, |
| + var parts = URLComponents(url: origin, resolvingAgainstBaseURL: false) else { return nil } |
| + parts.path = ""; parts.query = nil; parts.fragment = nil |
| + guard let base = parts.url else { return nil } |
| + self.origin = base; self.taskID = taskID; self.candidate = candidate |
| + parts.path = "/tasks/\(taskID)/preview" |
| + guard let wrapper = parts.url else { return nil }; self.wrapper = wrapper |
| + parts.path = "/native/preview/exchange" |
| + guard let exchange = parts.url else { return nil }; self.exchangeURL = exchange |
| + } |
| + func exchange(pass: String) -> URLRequest { |
| + var request = URLRequest(url: exchangeURL) |
| + request.httpMethod = "POST" |
| + request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") |
| + request.setValue(origin.absoluteString, forHTTPHeaderField: "Origin") |
| + // Every value uses a validated ASCII alphabet, never arbitrary URL text. |
| + request.httpBody = Data("pass=\(pass)&task=\(taskID)&candidate=\(candidate)".utf8) |
| + request.cachePolicy = .reloadIgnoringLocalCacheData |
| + return request |
| + } |
| + private static func cookieHost(_ url: URL) -> String? { |
| + url.host?.lowercased().trimmingCharacters(in: CharacterSet(charactersIn: ".")) |
| + } |
| + func allows(_ request: URLRequest, mainFrame: Bool, initial: Bool) -> Bool { |
| + guard let url = request.url, url.user == nil, url.password == nil, url.scheme == "https" else { return false } |
| + if !mainFrame { |
| + // The response's frame-src CSP pins the preview origin. Never let a |
| + // child navigate onto the Equipo cookie host (ports do not isolate cookies). |
| + return Self.cookieHost(url) != Self.cookieHost(origin) |
| + } |
| + if initial && request.httpMethod == "POST" && url == exchangeURL { return true } |
| + return request.httpMethod == "GET" && url == wrapper |
| + } |
| +} |
diff --git a/native/apple/Sources/EquipoKit/Presentation/TaskDetailModel.swift b/native/apple/Sources/EquipoKit/Presentation/TaskDetailModel.swift| index 64c6e206..d4889483 100644 |
| --- a/native/apple/Sources/EquipoKit/Presentation/TaskDetailModel.swift |
| +++ b/native/apple/Sources/EquipoKit/Presentation/TaskDetailModel.swift |
| @@ -44,7 +44,10 @@ import Observation |
| return TaskActionRules(task: task, viewer: session.me?.address ?? "", owner: session.me?.role == "owner", cards: session.cards) |
| } |
| func load() async { |
| - do { loaded = try await session.client.task(taskID); readFailure = nil } |
| + do { |
| + loaded = try await session.client.task(taskID); readFailure = nil |
| + if let loaded { session.previews.observe([loaded]) } |
| + } |
| catch { readFailure = StoppedWorkActions.logFailure(error) } |
| } |
| func beginMove() async { |
diff --git a/native/apple/Sources/EquipoKit/Preview/PreviewBrowser.swift b/native/apple/Sources/EquipoKit/Preview/PreviewBrowser.swift| new file mode 100644 |
| index 00000000..d46cd720 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/Preview/PreviewBrowser.swift |
| @@ -0,0 +1,87 @@ |
| +import SwiftUI |
| +import WebKit |
| + |
| +@MainActor final class PreviewBrowser: NSObject, PreviewBrowserResource, WKNavigationDelegate, WKUIDelegate { |
| + private(set) var webView: WKWebView? |
| + private(set) var dataStore: WKWebsiteDataStore? |
| + private let destination: PreviewDestination |
| + private var initial = true |
| + init(destination: PreviewDestination, request: URLRequest) { |
| + self.destination = destination |
| + super.init() |
| + let configuration = WKWebViewConfiguration() |
| + let store = WKWebsiteDataStore.nonPersistent() |
| + configuration.websiteDataStore = store |
| + configuration.preferences.javaScriptCanOpenWindowsAutomatically = false |
| + let web = WKWebView(frame: .zero, configuration: configuration) |
| + web.navigationDelegate = self; web.uiDelegate = self |
| + web.allowsBackForwardNavigationGestures = false |
| + dataStore = store; webView = web |
| + web.load(request) |
| + } |
| + func close() { |
| + webView?.stopLoading(); webView?.navigationDelegate = nil; webView?.uiDelegate = nil |
| + webView?.removeFromSuperview(); webView = nil |
| + dataStore?.removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), modifiedSince: .distantPast) {} |
| + dataStore = nil |
| + } |
| + func reload() { webView?.load(URLRequest(url: destination.wrapper)) } |
| + func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction, decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void) { |
| + guard let frame = action.targetFrame, !action.shouldPerformDownload else { decisionHandler(.cancel); return } |
| + let allowed = destination.allows(action.request, mainFrame: frame.isMainFrame, initial: initial) |
| + if frame.isMainFrame { initial = false } |
| + decisionHandler(allowed ? .allow : .cancel) |
| + } |
| + func webView(_ webView: WKWebView, decidePolicyFor response: WKNavigationResponse, decisionHandler: @escaping @MainActor (WKNavigationResponsePolicy) -> Void) { |
| + guard response.canShowMIMEType, let url = response.response.url else { decisionHandler(.cancel); return } |
| + // Initial exchange errors are HTML at the exchange URL. Its successful |
| + // response redirects to the exact wrapper; no other top document loads. |
| + let allowed = !response.isForMainFrame || url == destination.wrapper || url == destination.exchangeURL |
| + decisionHandler(allowed ? .allow : .cancel) |
| + } |
| + func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for action: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { nil } |
| +} |
| + |
| +struct PreviewSheetPresenter: ViewModifier { |
| + let session: EquipoSession |
| + func body(content: Content) -> some View { |
| + content.sheet(isPresented: Binding(get: { session.previews.page != nil }, set: { if !$0 { session.previews.dismiss() } })) { |
| + if let page = session.previews.page, let browser = page.resource as? PreviewBrowser, let web = browser.webView { |
| + PreviewSheetContent(web: web, dismiss: session.previews.dismiss) |
| + #if os(macOS) |
| + .frame(minWidth: 640, minHeight: 520) |
| + #endif |
| + .onDisappear { session.previews.dismiss() } |
| + } |
| + } |
| + } |
| +} |
| +struct PreviewSheetContent: View { |
| + let web: WKWebView |
| + let dismiss: () -> Void |
| + var body: some View { |
| + VStack(spacing: 0) { |
| + HStack { |
| + Text(EquipoStrings.text("work.specialist.preview")).font(.headline) |
| + Spacer() |
| + Button(EquipoStrings.text("team.close"), action: dismiss).frame(minHeight: 44) |
| + }.padding(.horizontal) |
| + Divider() |
| + PreviewWebView(web: web) |
| + } |
| + } |
| +} |
| + |
| +#if os(iOS) |
| +private struct PreviewWebView: UIViewRepresentable { |
| + let web: WKWebView |
| + func makeUIView(context: Context) -> WKWebView { web } |
| + func updateUIView(_ view: WKWebView, context: Context) {} |
| +} |
| +#else |
| +private struct PreviewWebView: NSViewRepresentable { |
| + let web: WKWebView |
| + func makeNSView(context: Context) -> WKWebView { web } |
| + func updateNSView(_ view: WKWebView, context: Context) {} |
| +} |
| +#endif |
diff --git a/native/apple/Sources/EquipoKit/Preview/PreviewFixture.swift b/native/apple/Sources/EquipoKit/Preview/PreviewFixture.swift| new file mode 100644 |
| index 00000000..d10d3b10 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/Preview/PreviewFixture.swift |
| @@ -0,0 +1,58 @@ |
| +#if DEBUG |
| +import SwiftUI |
| +#if os(macOS) |
| +import AppKit |
| +#endif |
| + |
| +/// Production task screen and private WebKit sheet against the manual Go |
| +/// screenshot fixture. The private config contains only a disposable test bearer. |
| +public struct PreviewFixture: View { |
| + @State private var session: EquipoSession? |
| + public init() {} |
| + public var body: some View { |
| + Group { |
| + if let session { |
| + NavigationStack { TaskScreen(session: session, taskID: "tk_preview") } |
| + } else { ProgressView() } |
| + } |
| + .preferredColorScheme(.light) |
| + .task { |
| + guard let path = ProcessInfo.processInfo.environment["EQUIPO_PREVIEW_FIXTURE"], |
| + let data = try? Data(contentsOf: URL(fileURLWithPath: path)), |
| + let config = try? JSONDecoder().decode([String: String].self, from: data), |
| + let origin = config["origin"].flatMap(URL.init(string:)), let token = config["token"] else { return } |
| + var account = DeviceAccount.new(origin: origin, label: "Preview fixture") |
| + account.credential = DeviceCredential(id: "fixture", token: token, audience: "equipo.person.v1", instanceId: "fixture", expiresAt: .distantFuture) |
| + let session = EquipoSession(account: account, accounts: DeviceAccounts(store: MemorySecretStore())) |
| + self.session = session |
| + await session.refresh() |
| + if let task = try? await session.client.task("tk_preview") { |
| + await session.previews.open(client: session.client, task: task) |
| + #if os(macOS) |
| + if let capture = ProcessInfo.processInfo.environment["EQUIPO_FIXTURE_CAPTURE"] { |
| + try? await Task.sleep(for: .seconds(5)) |
| + // SheetHostingView omits its SwiftUI layer in cacheDisplay. |
| + // Host the identical content with the actual loaded WebKit view. |
| + if let browser = session.previews.page?.resource as? PreviewBrowser, let web = browser.webView { |
| + let host = NSHostingView(rootView: PreviewSheetContent(web: web, dismiss: session.previews.dismiss) |
| + .frame(width: 800, height: 620).preferredColorScheme(.light)) |
| + let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 800, height: 620), styleMask: [.titled], backing: .buffered, defer: false) |
| + window.isReleasedWhenClosed = false; window.contentView = host |
| + window.orderFront(nil) |
| + try? await Task.sleep(for: .seconds(1)) |
| + host.layoutSubtreeIfNeeded(); window.displayIfNeeded() |
| + if let bitmap = host.bitmapImageRepForCachingDisplay(in: host.bounds) { |
| + host.cacheDisplay(in: host.bounds, to: bitmap) |
| + if let data = bitmap.representation(using: .png, properties: [:]) { |
| + _ = FileManager.default.createFile(atPath: capture, contents: data) |
| + } |
| + } |
| + window.close() |
| + } |
| + } |
| + #endif |
| + } |
| + } |
| + } |
| +} |
| +#endif |
diff --git a/native/apple/Sources/EquipoKit/Preview/PreviewPresentation.swift b/native/apple/Sources/EquipoKit/Preview/PreviewPresentation.swift| new file mode 100644 |
| index 00000000..1209be76 |
| --- /dev/null |
| +++ b/native/apple/Sources/EquipoKit/Preview/PreviewPresentation.swift |
| @@ -0,0 +1,112 @@ |
| +import Foundation |
| +import Observation |
| + |
| +@MainActor protocol PreviewBrowserResource: AnyObject { |
| + func close() |
| + func reload() |
| +} |
| + |
| +/// One task-bound browser, owned by the signed-in session. Every terminal |
| +/// transition releases the web view and its private data store together. |
| +@MainActor @Observable final class PreviewPresentation { |
| + struct Binding: Equatable { |
| + let taskID: String |
| + let candidate: String |
| + let step: String |
| + let attempt: Int64? |
| + let deployment: ThinPreviewResult |
| + init?(_ task: ThinTask) { |
| + guard let step = task.steps?.last(where: { $0.specialist == "preview" }), |
| + step.candidateSha == task.candidateSha, let preview = step.preview, |
| + preview.outcome == "deployed", preview.url != nil else { return nil } |
| + taskID = task.id; candidate = task.candidateSha; self.step = step.id |
| + attempt = step.attempt; deployment = preview |
| + } |
| + } |
| + struct Page: Identifiable { |
| + let id = UUID() |
| + let binding: Binding |
| + let expiry: Date |
| + let resource: any PreviewBrowserResource |
| + } |
| + private(set) var page: Page? |
| + private(set) var busy = false |
| + private(set) var failure: String? |
| + private(set) var taskID: String? |
| + private var generation = UUID() |
| + private var valid = true |
| + private var timer: Task<Void, Never>? |
| + private let makeBrowser: @MainActor (PreviewDestination, URLRequest) -> any PreviewBrowserResource |
| + private let elapsedSince: @MainActor (ContinuousClock.Instant) -> TimeInterval |
| + init(elapsedSince: @escaping @MainActor (ContinuousClock.Instant) -> TimeInterval = { started in |
| + let elapsed = started.duration(to: .now).components |
| + return Double(elapsed.seconds) + Double(elapsed.attoseconds) / 1e18 |
| + }, makeBrowser: @escaping @MainActor (PreviewDestination, URLRequest) -> any PreviewBrowserResource = { PreviewBrowser(destination: $0, request: $1) }) { |
| + self.makeBrowser = makeBrowser; self.elapsedSince = elapsedSince |
| + } |
| + func open(client: EquipoClient, task: ThinTask, now: Date = Date()) async { |
| + guard valid, !busy else { return } |
| + dismiss(); taskID = task.id; failure = nil |
| + guard let binding = Binding(task), let destination = PreviewDestination(origin: client.origin, taskID: task.id, candidate: task.candidateSha) else { |
| + failure = EquipoStrings.text("read.failed_title"); return |
| + } |
| + busy = true |
| + let operation = generation |
| + let started = ContinuousClock.now |
| + do { |
| + let pass = try await client.previewPass(task: task.id, candidate: task.candidateSha) |
| + guard valid, generation == operation else { return } |
| + let received = now.addingTimeInterval(elapsedSince(started)) |
| + // Never extend a server deadline by the time spent minting. |
| + guard pass.pass.range(of: #"^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]\z"#, options: .regularExpression) != nil, |
| + pass.expiresAt > received, pass.expiresAt <= received.addingTimeInterval(60), |
| + pass.grantExpiresAt >= pass.expiresAt, pass.grantExpiresAt <= received.addingTimeInterval(900) else { |
| + throw EquipoAPIError.undecodable |
| + } |
| + page = Page(binding: binding, expiry: pass.grantExpiresAt, resource: makeBrowser(destination, destination.exchange(pass: pass.pass))) |
| + busy = false |
| + let interval = pass.grantExpiresAt.timeIntervalSince(received) |
| + timer = Task { [weak self] in |
| + do { try await Task.sleep(for: .seconds(interval)) } catch { return } |
| + guard let self, self.generation == operation else { return } |
| + self.expire() |
| + } |
| + } catch { |
| + guard valid, generation == operation else { return } |
| + busy = false |
| + if let error = error as? EquipoAPIError, error.code == "preview_changed" { |
| + failure = EquipoStrings.text("evidence.candidate_changed") |
| + } else if let error = error as? EquipoAPIError, error.code == "preview_expired" { |
| + failure = EquipoStrings.text("question.expired") |
| + } else { failure = StoppedWorkActions.logFailure(error) } |
| + } |
| + } |
| + func dismiss() { |
| + generation = UUID(); timer?.cancel(); timer = nil |
| + page?.resource.close(); page = nil; busy = false |
| + } |
| + func invalidate() { valid = false; dismiss() } |
| + func background() { checkExpiry() } |
| + func checkExpiry(now: Date = Date()) { |
| + if let page, now >= page.expiry { expire() } |
| + } |
| + private func expire() { dismiss(); failure = EquipoStrings.text("question.expired") } |
| + func observe(_ tasks: [ThinTask]) { |
| + guard let page, let task = tasks.first(where: { $0.id == page.binding.taskID }) else { return } |
| + if Binding(task) != page.binding { |
| + dismiss(); failure = EquipoStrings.text("evidence.candidate_changed") |
| + } |
| + } |
| + func foreground(client: EquipoClient, now: Date = Date()) async { |
| + checkExpiry(now: now) |
| + guard let page else { return } |
| + do { |
| + let task = try await client.task(page.binding.taskID) |
| + guard self.page?.id == page.id else { return } |
| + observe([task]); self.page?.resource.reload() |
| + } catch { |
| + guard self.page?.id == page.id else { return } |
| + dismiss(); failure = StoppedWorkActions.logFailure(error) |
| + } |
| + } |
| +} |
diff --git a/native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings b/native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings| index b61fab3a..d84a36e0 100644 |
| --- a/native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings |
| +++ b/native/apple/Sources/EquipoKit/Resources/Localizable.xcstrings |
| @@ -1212,6 +1212,17 @@ |
| } |
| } |
| }, |
| + "evidence.candidate_changed": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "The change has been updated. Review it again." |
| + } |
| + } |
| + } |
| + }, |
| "fact.branch": { |
| "extractionState": "manual", |
| "localizations": { |
| @@ -2510,6 +2521,17 @@ |
| } |
| } |
| }, |
| + "question.expired": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Expired" |
| + } |
| + } |
| + } |
| + }, |
| "read.failed": { |
| "extractionState": "manual", |
| "localizations": { |
| @@ -4567,6 +4589,17 @@ |
| } |
| } |
| }, |
| + "work.reason.amadan_unreachable": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "Amadan could not be reached to confirm Equipo may merge here" |
| + } |
| + } |
| + } |
| + }, |
| "work.reason.base_checks_failed": { |
| "extractionState": "manual", |
| "localizations": { |
| @@ -4732,6 +4765,17 @@ |
| } |
| } |
| }, |
| + "work.reason.merge_credential": { |
| + "extractionState": "manual", |
| + "localizations": { |
| + "en": { |
| + "stringUnit": { |
| + "state": "translated", |
| + "value": "the runner has no Amadan credential for this repository" |
| + } |
| + } |
| + } |
| + }, |
| "work.reason.merge_failed": { |
| "extractionState": "manual", |
| "localizations": { |
diff --git a/native/apple/Sources/EquipoKit/Session/EquipoSession.swift b/native/apple/Sources/EquipoKit/Session/EquipoSession.swift| index 12748263..cb274be0 100644 |
| --- a/native/apple/Sources/EquipoKit/Session/EquipoSession.swift |
| +++ b/native/apple/Sources/EquipoKit/Session/EquipoSession.swift |
| @@ -30,6 +30,7 @@ public final class EquipoSession { |
| /// or credential renewal ignores cancellation and completes later. |
| public let lifetime: SignInLifetime |
| let settings = SettingsPresentation() |
| + let previews = PreviewPresentation() |
| public let markdown = MarkdownTranscript() |
| private var questionDrafts: [String: QuestionAnswerDraft] = [:] |
| /// The zone this session told Equipo (paused work): sent once, and again |
| @@ -151,6 +152,7 @@ public final class EquipoSession { |
| guard !isInvalidated else { return } |
| apply(snapshot, projectGeneration: projectGeneration) |
| tasks = taskList.items ?? [] |
| + previews.observe(tasks) |
| needsYou = needsList.items ?? [] |
| status = .ready |
| refreshFailed = false |
| @@ -521,6 +523,7 @@ public final class EquipoSession { |
| /// not prevent a completed network response from reaching persistence. |
| func invalidate() { |
| lifetime.end() |
| + previews.invalidate() |
| attachments.clear() |
| markdown.removeAll() |
| status = .signedOut |
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/AppModel.swift b/native/apple/Sources/EquipoKit/UI/Screens/AppModel.swift| index 85bcf1c8..ce1cbcaa 100644 |
| --- a/native/apple/Sources/EquipoKit/UI/Screens/AppModel.swift |
| +++ b/native/apple/Sources/EquipoKit/UI/Screens/AppModel.swift |
| @@ -192,6 +192,10 @@ public final class EquipoAppModel { |
| public func foreground() { |
| isForeground = true |
| + if let session { |
| + session.previews.checkExpiry() |
| + Task { await session.previews.foreground(client: session.client) } |
| + } |
| NativeConnectivity.shared.foregrounded() |
| let push = self.push |
| Task { await push.sync() } |
| @@ -204,5 +208,5 @@ public final class EquipoAppModel { |
| if isForeground { session?.startLive() } |
| } |
| } |
| - public func background() { isForeground = false; session?.stopLive() } |
| + public func background() { isForeground = false; session?.previews.background(); session?.stopLive() } |
| } |
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/TaskDetailScreen.swift b/native/apple/Sources/EquipoKit/UI/Screens/TaskDetailScreen.swift| index fd584897..a83cc8a5 100644 |
| --- a/native/apple/Sources/EquipoKit/UI/Screens/TaskDetailScreen.swift |
| +++ b/native/apple/Sources/EquipoKit/UI/Screens/TaskDetailScreen.swift |
| @@ -47,7 +47,7 @@ public struct TaskScreen: View { |
| case .overview: overview(task) |
| case .checks: TaskChecksView(task: task, client: model.session.client) |
| case .changes: webEvidence(task, preview: false) |
| - case .preview: webEvidence(task, preview: true) |
| + case .preview: previewEvidence(task) |
| } |
| }.padding(16).frame(maxWidth: 760).frame(maxWidth: .infinity, alignment: .topLeading) |
| } |
| @@ -68,6 +68,8 @@ public struct TaskScreen: View { |
| .refreshable { await model.session.refresh(); await model.load() } |
| .sheet(item: $model.confirmation) { confirm in TaskConfirmationSheet(model: model, confirmation: confirm) } |
| .sheet(isPresented: $model.moving) { TaskMoveSheet(model: model) } |
| + .modifier(PreviewSheetPresenter(session: model.session)) |
| + .onDisappear { model.session.previews.dismiss() } |
| .onChange(of: model.decision.card?.id) { model.directionNote = "" } |
| } |
| @@ -110,6 +112,19 @@ public struct TaskScreen: View { |
| Text(verbatim: value).font(.system(.caption, design: .monospaced)).textSelection(.enabled) |
| } |
| } |
| + private func previewEvidence(_ task: ThinTask) -> some View { |
| + VStack(alignment: .leading, spacing: 12) { |
| + if model.session.previews.taskID == task.id, let failure = model.session.previews.failure { |
| + Text(failure).foregroundStyle(Palette.negative) |
| + } |
| + if PreviewPresentation.Binding(task) != nil { |
| + Button(EquipoStrings.text("work.specialist.preview")) { |
| + Task { await model.session.previews.open(client: model.session.client, task: task) } |
| + }.buttonStyle(.bordered).disabled(model.session.previews.busy) |
| + if model.session.previews.busy { ProgressView().accessibilityLabel(EquipoStrings.text("work.specialist.preview")) } |
| + } else { webEvidence(task, preview: true) } |
| + } |
| + } |
| private func webEvidence(_ task: ThinTask, preview: Bool) -> some View { |
| Button { |
| if preview { model.session.settings.open(origin: model.session.origin, path: "/tasks/\(task.id)/preview") } |
diff --git a/native/apple/Sources/EquipoMac/EquipoMacApp.swift b/native/apple/Sources/EquipoMac/EquipoMacApp.swift| index 76ff8087..cebc01f4 100644 |
| --- a/native/apple/Sources/EquipoMac/EquipoMacApp.swift |
| +++ b/native/apple/Sources/EquipoMac/EquipoMacApp.swift |
| @@ -19,7 +19,7 @@ import SwiftUI |
| #if DEBUG |
| // Offline fixture captures must run this build, without an updater |
| // replacing it with a published app during the capture. |
| - if ProcessInfo.processInfo.environment["EQUIPO_TASK_FIXTURE"] != nil || ProcessInfo.processInfo.environment["EQUIPO_NEEDS_FIXTURE"] != nil || ProcessInfo.processInfo.environment["EQUIPO_STOPPED_FIXTURE"] != nil || ProcessInfo.processInfo.environment["EQUIPO_ATTACHMENTS_FIXTURE"] != nil { return nil } |
| + if ProcessInfo.processInfo.environment["EQUIPO_PREVIEW_FIXTURE"] != nil || ProcessInfo.processInfo.environment["EQUIPO_TASK_FIXTURE"] != nil || ProcessInfo.processInfo.environment["EQUIPO_NEEDS_FIXTURE"] != nil || ProcessInfo.processInfo.environment["EQUIPO_STOPPED_FIXTURE"] != nil || ProcessInfo.processInfo.environment["EQUIPO_ATTACHMENTS_FIXTURE"] != nil { return nil } |
| #endif |
| return NativeUpdater(policy: .quiet) |
| }() |
| @@ -29,7 +29,8 @@ import SwiftUI |
| WindowGroup(EquipoStrings.text("app.name")) { |
| Group { |
| #if DEBUG |
| - if ProcessInfo.processInfo.environment["EQUIPO_NEEDS_FIXTURE"] != nil { MacNeedsFixture() } |
| + if ProcessInfo.processInfo.environment["EQUIPO_PREVIEW_FIXTURE"] != nil { PreviewFixture() } |
| + else if ProcessInfo.processInfo.environment["EQUIPO_NEEDS_FIXTURE"] != nil { MacNeedsFixture() } |
| else if ProcessInfo.processInfo.environment["EQUIPO_STOPPED_FIXTURE"]?.hasPrefix("conversation-") == true { StoppedConversationFixture() } |
| else if ProcessInfo.processInfo.environment["EQUIPO_STOPPED_FIXTURE"] != nil { StoppedWorkFixture() } |
| else if ProcessInfo.processInfo.environment["EQUIPO_TASK_FIXTURE"] != nil { TaskViewFixture() } |
diff --git a/native/apple/Tests/EquipoKitTests/PreviewPassTests.swift b/native/apple/Tests/EquipoKitTests/PreviewPassTests.swift| new file mode 100644 |
| index 00000000..42a910a4 |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/PreviewPassTests.swift |
| @@ -0,0 +1,223 @@ |
| +import Foundation |
| +import Testing |
| +@testable import EquipoKit |
| + |
| +@MainActor @Suite struct PreviewPassTests { |
| + static let now = Date(timeIntervalSince1970: 1_795_694_400) |
| + static let sha = String(repeating: "1", count: 40) |
| + static let pass = String(repeating: "A", count: 43) |
| + static func destination() throws -> PreviewDestination { |
| + try #require(PreviewDestination(origin: URL(string: "https://team.example/old?q=1#x")!, taskID: "tk_preview", candidate: sha)) |
| + } |
| + @Test func exactAllowlistAndBodyOnlySecret() throws { |
| + let d = try Self.destination(), request = d.exchange(pass: Self.pass) |
| + #expect(request.url?.absoluteString == "https://team.example/native/preview/exchange") |
| + #expect(request.httpMethod == "POST") |
| + #expect(request.value(forHTTPHeaderField: "Authorization") == nil) |
| + #expect(request.value(forHTTPHeaderField: "Cookie") == nil) |
| + #expect(request.value(forHTTPHeaderField: "Origin") == "https://team.example") |
| + #expect(String(data: try #require(request.httpBody), encoding: .utf8) == "pass=\(Self.pass)&task=tk_preview&candidate=\(Self.sha)") |
| + #expect(d.allows(request, mainFrame: true, initial: true)) |
| + #expect(!d.allows(request, mainFrame: true, initial: false)) |
| + #expect(d.allows(URLRequest(url: d.wrapper), mainFrame: true, initial: false)) |
| + for url in ["https://evil.example/tasks/tk_preview/preview", "https://team.example/tasks/other/preview", "https://team.example/tasks/tk_preview/preview?x=1", "https://team.example/tasks/tk_preview/preview#x", "https://user@team.example/tasks/tk_preview/preview", "https://team.example/native/preview/exchange", "https://team.example/evil", "http://team.example/tasks/tk_preview/preview"] { |
| + #expect(!d.allows(URLRequest(url: URL(string: url)!), mainFrame: true, initial: false)) |
| + } |
| + var post = URLRequest(url: d.wrapper); post.httpMethod = "POST" |
| + #expect(!d.allows(post, mainFrame: true, initial: false)) |
| + #expect(d.allows(URLRequest(url: URL(string: "https://preview.example/")!), mainFrame: false, initial: false)) |
| + #expect(!d.allows(URLRequest(url: d.wrapper), mainFrame: false, initial: false)) |
| + #expect(!d.allows(URLRequest(url: URL(string: "https://team.example.:8443/")!), mainFrame: false, initial: false)) |
| + for candidate in ["", String(repeating: "a", count: 39), String(repeating: "a", count: 41), String(repeating: "G", count: 40)] { |
| + #expect(PreviewDestination(origin: d.origin, taskID: "t", candidate: candidate) == nil) |
| + } |
| + for id in ["../x", "a/b", "a?x", "", String(repeating: "a", count: 129)] { |
| + #expect(PreviewDestination(origin: d.origin, taskID: id, candidate: Self.sha) == nil) |
| + } |
| + #expect(PreviewDestination(origin: URL(string: "http://team.example")!, taskID: "t", candidate: Self.sha) == nil) |
| + } |
| + @Test func lifecycleDisposesOnDismissExpiryInvalidationAndCandidateChange() async throws { |
| + for action in ["dismiss", "expiry", "invalidate", "candidate"] { |
| + let browser = FakePreviewBrowser(), model = PreviewPresentation(elapsedSince: { _ in 0 }, makeBrowser: { _, _ in browser }) |
| + let server = ScriptedTransport(), task = try Self.task() |
| + Self.answer(server) |
| + await model.open(client: EquipoClient(transport: server, token: "device-bearer"), task: task, now: Self.now) |
| + #expect(model.page != nil) |
| + let request = try #require(server.sent("POST /tasks/\(task.id)/preview-pass").first) |
| + #expect(request.bearer == "device-bearer") |
| + #expect(try JSONSerialization.jsonObject(with: #require(request.body)) as? [String: String] == ["candidate_sha": Self.sha]) |
| + switch action { |
| + case "dismiss": model.dismiss() |
| + case "expiry": model.background(); model.checkExpiry(now: Self.now.addingTimeInterval(900)) |
| + case "candidate": var changed = task; changed.candidateSha = String(repeating: "2", count: 40); model.observe([changed]) |
| + default: model.invalidate() |
| + } |
| + #expect(model.page == nil) |
| + #expect(browser.closed == 1) |
| + } |
| + } |
| + @Test func expiredOrOverlongResponsesNeverCreateAWebView() async throws { |
| + for times in [(0.0, 900.0), (61, 900), (60, 901), (60, 0)] { |
| + let browser = FakePreviewBrowser(), model = PreviewPresentation(elapsedSince: { _ in 0 }, makeBrowser: { _, _ in browser }) |
| + let server = ScriptedTransport(); Self.answer(server, passLife: times.0, grantLife: times.1) |
| + await model.open(client: EquipoClient(transport: server, token: "t"), task: try Self.task(), now: Self.now) |
| + #expect(model.page == nil); #expect(model.failure != nil) |
| + } |
| + } |
| + @Test func latestPreviewMustMatchTheCurrentCandidate() throws { |
| + var task = try Self.task(), old = task.steps![0] |
| + old.id = "old-preview"; old.candidateSha = String(repeating: "2", count: 40) |
| + task.steps = [old] + task.steps! |
| + #expect(PreviewPresentation.Binding(task)?.step == "preview") |
| + task.steps![1].preview = nil |
| + #expect(PreviewPresentation.Binding(task) == nil) |
| + } |
| + @Test func malformedPassCannotEnterTheFormBody() async throws { |
| + for token in ["", String(repeating: "A", count: 42) + "B", "x&task=other", String(repeating: "A", count: 44)] { |
| + let server = ScriptedTransport(), model = PreviewPresentation(elapsedSince: { _ in 0 }, makeBrowser: { _, _ in FakePreviewBrowser() }) |
| + Self.answer(server, passValue: token) |
| + await model.open(client: EquipoClient(transport: server, token: "device"), task: try Self.task(), now: Self.now) |
| + #expect(model.page == nil); #expect(model.failure != nil) |
| + } |
| + } |
| + @Test func staleAndExpiredWordsComeFromReviewedCatalog() async throws { |
| + for (status, code, key) in [(409, "preview_changed", "evidence.candidate_changed"), (410, "preview_expired", "question.expired")] { |
| + let server = ScriptedTransport(), model = PreviewPresentation(elapsedSince: { _ in 0 }, makeBrowser: { _, _ in FakePreviewBrowser() }) |
| + let task = try Self.task() |
| + server.on("POST /tasks/\(task.id)/preview-pass", .success(APIResponse(status: status, data: Data("{\"code\":\"\(code)\",\"copy_key\":\"\(key)\",\"request_id\":\"r\"}".utf8)))) |
| + await model.open(client: EquipoClient(transport: server, token: "t"), task: task, now: Self.now) |
| + #expect(model.page == nil); #expect(model.failure == EquipoStrings.text(String.LocalizationValue(key))) |
| + } |
| + } |
| + static func task() throws -> ThinTask { |
| + var task: ThinTask = try Fixture.decode("thin/task") |
| + task.id = "tk_preview"; task.candidateSha = sha |
| + var step = task.steps![0] |
| + step.id = "preview"; step.specialist = "preview"; step.state = "done" |
| + step.candidateSha = sha; step.attempt = 1 |
| + step.preview = ThinPreviewResult(url: "https://preview.example/", digest: "d", expiresAt: now.addingTimeInterval(3600), outcome: "deployed") |
| + task.steps = [step] |
| + return task |
| + } |
| + |
| + static func answer(_ server: ScriptedTransport, passLife: Double = 60, grantLife: Double = 900, passValue: String = PreviewPassTests.pass) { |
| + let response = PreviewPass(pass: passValue, expiresAt: now.addingTimeInterval(passLife), grantExpiresAt: now.addingTimeInterval(grantLife)) |
| + let encoder = EquipoJSON.encoder; encoder.dateEncodingStrategy = .iso8601 |
| + server.on("POST /tasks/tk_preview/preview-pass", .success(APIResponse(status: 201, data: try! encoder.encode(response)))) |
| + } |
| +} |
| +@MainActor final class FakePreviewBrowser: PreviewBrowserResource { |
| + var closed = 0 |
| + func close() { closed += 1 } |
| + func reload() {} |
| +} |
| + |
| +@MainActor @Suite struct PreviewLifecycleTests { |
| + @Test func actualBrowserUsesAndDropsPrivateStore() throws { |
| + let destination = try PreviewPassTests.destination() |
| + let browser = PreviewBrowser(destination: destination, request: destination.exchange(pass: PreviewPassTests.pass)) |
| + let view = try #require(browser.webView), store = try #require(browser.dataStore) |
| + #expect(!store.isPersistent) |
| + #expect(view.configuration.userContentController.userScripts.isEmpty) |
| + #expect(!view.configuration.preferences.javaScriptCanOpenWindowsAutomatically) |
| + browser.close() |
| + #expect(browser.webView == nil); #expect(browser.dataStore == nil) |
| + #expect(view.navigationDelegate == nil); #expect(view.uiDelegate == nil) |
| + } |
| + @Test func signOutAndAccountSwitchDisposeTheOwnedBrowser() async throws { |
| + for switching in [false, true] { |
| + let server = ScriptedTransport(), app = EquipoAppModel(store: MemorySecretStore(), makeTransport: { _ in server }) |
| + var account = DeviceAccount.new(origin: server.origin, label: "First") |
| + account.credential = DeviceCredential(id: "device", token: "device", audience: "equipo.person.v1", instanceId: "instance", expiresAt: .distantFuture) |
| + app.adopt(account, transport: server) |
| + let session = try #require(app.session) |
| + PreviewPassTests.answer(server) |
| + await session.previews.open(client: session.client, task: try PreviewPassTests.task(), now: PreviewPassTests.now) |
| + let browser = try #require(session.previews.page?.resource as? PreviewBrowser) |
| + if switching { |
| + let next = DeviceAccount.new(origin: URL(string: "https://second.example")!, label: "Second") |
| + app.adopt(next, transport: ScriptedTransport(origin: next.origin)) |
| + } else { await session.signOut() } |
| + #expect(session.previews.page == nil) |
| + #expect(browser.webView == nil); #expect(browser.dataStore == nil) |
| + PreviewPassTests.answer(server) |
| + await session.previews.open(client: session.client, task: try PreviewPassTests.task(), now: PreviewPassTests.now) |
| + #expect(session.previews.page == nil) |
| + } |
| + } |
| + @Test func invalidatedPresentationCannotMintAgain() async throws { |
| + let server = ScriptedTransport(), browser = FakePreviewBrowser() |
| + let model = PreviewPresentation(elapsedSince: { _ in 0 }, makeBrowser: { _, _ in browser }) |
| + PreviewPassTests.answer(server) |
| + model.invalidate() |
| + await model.open(client: EquipoClient(transport: server, token: "device"), task: try PreviewPassTests.task(), now: PreviewPassTests.now) |
| + #expect(model.page == nil) |
| + #expect(server.sent("POST /tasks/tk_preview/preview-pass").isEmpty) |
| + } |
| + @Test func backgroundBeyondExpiryCannotReloadDeliveredHTML() async throws { |
| + let server = ScriptedTransport(), browser = FakePreviewBrowser() |
| + let model = PreviewPresentation(elapsedSince: { _ in 0 }, makeBrowser: { _, _ in browser }) |
| + PreviewPassTests.answer(server) |
| + let client = EquipoClient(transport: server, token: "device") |
| + await model.open(client: client, task: try PreviewPassTests.task(), now: PreviewPassTests.now) |
| + await model.foreground(client: client, now: PreviewPassTests.now.addingTimeInterval(900)) |
| + #expect(model.page == nil); #expect(browser.closed == 1) |
| + #expect(server.sent("GET /tasks/tk_preview").isEmpty) |
| + #expect(model.failure == EquipoStrings.text("question.expired")) |
| + } |
| + @Test func foregroundRefusesChangedOrRevokedTask() async throws { |
| + for revoked in [false, true] { |
| + let server = ScriptedTransport(), browser = FakePreviewBrowser() |
| + let model = PreviewPresentation(elapsedSince: { _ in 0 }, makeBrowser: { _, _ in browser }) |
| + PreviewPassTests.answer(server) |
| + let client = EquipoClient(transport: server, token: "device") |
| + var task = try PreviewPassTests.task() |
| + await model.open(client: client, task: task, now: PreviewPassTests.now) |
| + task.steps![0].attempt = 2 |
| + let encoder = EquipoJSON.encoder; encoder.dateEncodingStrategy = .iso8601 |
| + server.on("GET /tasks/tk_preview", .success(APIResponse(status: revoked ? 401 : 200, data: revoked ? Data() : try encoder.encode(task)))) |
| + await model.foreground(client: client, now: PreviewPassTests.now.addingTimeInterval(1)) |
| + #expect(model.page == nil); #expect(browser.closed == 1) |
| + } |
| + } |
| + @Test func doubleTapMintsOnlyOnePass() async throws { |
| + let server = DelayedPreviewTransport(), model = PreviewPresentation(elapsedSince: { _ in 0 }, makeBrowser: { _, _ in FakePreviewBrowser() }) |
| + let task = try PreviewPassTests.task(), client = EquipoClient(transport: server, token: "device") |
| + let first = Task { await model.open(client: client, task: task, now: PreviewPassTests.now) } |
| + while !(await server.waiting) { await Task.yield() } |
| + let second = Task { await model.open(client: client, task: task, now: PreviewPassTests.now) } |
| + for _ in 0..<20 { await Task.yield() } |
| + #expect(await server.calls == 1) |
| + await server.complete(); await first.value; await second.value |
| + model.dismiss() |
| + } |
| + @Test func lateMintCannotRestoreDismissedOrInvalidatedSheet() async throws { |
| + for invalidate in [false, true] { |
| + let server = DelayedPreviewTransport(), browser = FakePreviewBrowser() |
| + let model = PreviewPresentation(elapsedSince: { _ in 0 }, makeBrowser: { _, _ in browser }) |
| + let task = try PreviewPassTests.task() |
| + let opening = Task { await model.open(client: EquipoClient(transport: server, token: "device"), task: task, now: PreviewPassTests.now) } |
| + while !(await server.waiting) { await Task.yield() } |
| + if invalidate { model.invalidate() } else { model.dismiss() } |
| + await server.complete() |
| + await opening.value |
| + #expect(model.page == nil); #expect(!model.busy) |
| + } |
| + } |
| +} |
| +actor DelayedPreviewTransport: EquipoTransport { |
| + func lines(_ request: APIRequest) async throws -> AsyncThrowingStream<String, Error> { throw EquipoAPIError.offline } |
| + nonisolated let origin = URL(string: "https://team.example")! |
| + var calls = 0 |
| + var waiting: Bool { !continuations.isEmpty } |
| + var continuations: [CheckedContinuation<APIResponse, Never>] = [] |
| + func send(_ request: APIRequest) async throws -> APIResponse { |
| + calls += 1 |
| + return await withCheckedContinuation { continuations.append($0) } |
| + } |
| + func complete() { |
| + for continuation in continuations { continuation.resume(returning: APIResponse(status: 201, data: Data("{\"pass\":\"\(String(repeating: "A", count: 43))\",\"expires_at\":\"2026-11-26T12:01:00Z\",\"grant_expires_at\":\"2026-11-26T12:15:00Z\"}".utf8))) |
| + } |
| + continuations = [] |
| + } |
| +} |
diff --git a/native/ios/Sources/EquipoPhoneApp.swift b/native/ios/Sources/EquipoPhoneApp.swift| index aaef4355..11b79cc6 100644 |
| --- a/native/ios/Sources/EquipoPhoneApp.swift |
| +++ b/native/ios/Sources/EquipoPhoneApp.swift |
| @@ -7,7 +7,8 @@ struct EquipoPhoneApp: App { |
| var body: some Scene { |
| WindowGroup { |
| #if DEBUG |
| - if ProcessInfo.processInfo.environment["EQUIPO_NEEDS_FIXTURE"] != nil { PhoneNeedsFixture() } |
| + if ProcessInfo.processInfo.environment["EQUIPO_PREVIEW_FIXTURE"] != nil { PreviewFixture() } |
| + else if ProcessInfo.processInfo.environment["EQUIPO_NEEDS_FIXTURE"] != nil { PhoneNeedsFixture() } |
| else if ProcessInfo.processInfo.environment["EQUIPO_TASK_FIXTURE"] != nil { TaskViewFixture() } |
| else if ProcessInfo.processInfo.environment["EQUIPO_STOPPED_FIXTURE"] != nil { StoppedWorkFixture() } |
| else { PhoneRoot(model: delegate.model) } |
diff --git a/native/scripts/check-parity.py b/native/scripts/check-parity.py| index af5e9096..e0be86b9 100755 |
| --- a/native/scripts/check-parity.py |
| +++ b/native/scripts/check-parity.py |
| @@ -22,7 +22,7 @@ for key in sorted(set(re.findall(r'"(work\.reason\.[^"]+)":', copy))): |
| if key not in strings: |
| problems.append(f'{key}: native must carry every reviewed stop reason') |
| for key, text in sorted(strings.items()): |
| - if not key.startswith(('chat.day.today', 'runner.verdict.skipped', 'work.', 'placement.', 'chat.card.', 'chat.paste.', 'chat.attach.', 'work.tl.', 'roster.', 'projects.', 'work.star.', 'api.', 'nav.projects', 'chat.connections.connected', 'counts.unavailable', 'team.close', 'work.pause.', 'work.reason.', 'work.needs.', 'chat.held.', 'work.hold.', 'work.stage.', 'time.', 'work.hold.run_now', 'work.recover')): |
| + if not key.startswith(('evidence.candidate_changed', 'question.expired', 'chat.day.today', 'runner.verdict.skipped', 'work.', 'placement.', 'chat.card.', 'chat.paste.', 'chat.attach.', 'work.tl.', 'roster.', 'projects.', 'work.star.', 'api.', 'nav.projects', 'chat.connections.connected', 'counts.unavailable', 'team.close', 'work.pause.', 'work.reason.', 'work.needs.', 'chat.held.', 'work.hold.', 'work.stage.', 'time.', 'work.hold.run_now', 'work.recover')): |
| continue |
| found = re.findall(r'"' + re.escape(key) + r'":\s*"((?:[^"\\]|\\.)*)"', copy) |
| if len(found) != 1: |
diff --git a/native/scripts/strings.json b/native/scripts/strings.json| index 3aff3910..9eec1b67 100644 |
| --- a/native/scripts/strings.json |
| +++ b/native/scripts/strings.json |
| @@ -490,5 +490,9 @@ |
| "native.needs.finished_today": "Finished today", |
| "native.needs.done_at": "Done at %@", |
| "work.merged": "Merged into %@ at %@", |
| - "native.needs.merged_at": "Merged into %1$@ at %2$@" |
| + "native.needs.merged_at": "Merged into %1$@ at %2$@", |
| + "evidence.candidate_changed": "The change has been updated. Review it again.", |
| + "question.expired": "Expired", |
| + "work.reason.merge_credential": "the runner has no Amadan credential for this repository", |
| + "work.reason.amadan_unreachable": "Amadan could not be reached to confirm Equipo may merge here" |
| } |