diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7381b6e5d..1d7946fd4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -144,6 +144,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false + fetch-depth: 0 - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: node-version: 26 @@ -157,8 +158,16 @@ jobs: with: go-version-file: go.mod cache: false + - name: Generate pinned administration predecessor bundle + run: bash tools/ci/generate-admin-parent-fixture.sh "$RUNNER_TEMP/admin-parent-fixture" + - name: Verify genuine predecessor inactive restore + env: + FC_ADMIN_PARENT_FIXTURE: ${{ runner.temp }}/admin-parent-fixture + run: go test -race -v -count=1 -run '^(TestProjectManagementRealParentBundleRemainsInactive|TestProjectManagementRealParentUpgradePreservesAllRowsAndSchemas|TestProjectManagementRealParentMigrationFailureRollsBack|TestWorkerRetirementRealParentEmptyACKAndRetiredSendReplay)$' ./internal/backup ./internal/core ./internal/inbox - run: make build - name: Smoke packaged binaries + env: + FC_ADMIN_PARENT_FIXTURE: ${{ runner.temp }}/admin-parent-fixture run: make smoke - name: Install pinned Chromium working-directory: webapp diff --git a/Makefile b/Makefile index 543cfe9af..828f817e2 100644 --- a/Makefile +++ b/Makefile @@ -44,6 +44,7 @@ browser-build: # Requires the actual outputs from make build; no implicit rebuild. smoke: + $(GO) test -v -tags=packaged_smoke -run '^TestPackagedProjectManagementSmoke$$' -count=1 -timeout=60s ./tools/packagedsmoke $(GO) test -v -tags=packaged_smoke -run '^TestPackagedRunSelectionSmoke$$' -count=1 -timeout=60s ./tools/packagedsmoke $(GO) test -v -tags=packaged_smoke -run '^TestPackagedOperationReadsSmoke$$' -count=1 -timeout=60s ./tools/packagedsmoke $(GO) test -v -tags=packaged_smoke -run '^TestPackagedCarriedAdoptionSmoke$$' -count=1 -timeout=60s ./tools/packagedsmoke diff --git a/docs/README.md b/docs/README.md index 57d4af03a..e794c7122 100644 --- a/docs/README.md +++ b/docs/README.md @@ -8,6 +8,9 @@ The [Hosted source foundation](delivery.md#hosted-source-foundation) records the ## Documents +- [Project management](local-api.md#project-management-and-guarded-retirement): explicit scoped grants, permission-set CAS and native administration. +- [Worker retirement](worker-retirement.md): blocker cleanup, active/archive reads and retained historical identities. + - [Carried review obligations](adoption-obligations.md): original source-bound holds, minimum-only rules, guarded resolution and retargeting. - [Retained review history](review-history-growth.md): immutable versions, compact summaries, bounded archives and backup integrity. diff --git a/docs/adoption-obligations.md b/docs/adoption-obligations.md index a31490ebe..c24794b93 100644 --- a/docs/adoption-obligations.md +++ b/docs/adoption-obligations.md @@ -12,11 +12,11 @@ Optional source tooling exports the selected effective policy and its current un ## Carried obligations -The native service accepts generic source-bound obligations through an administrator preview/apply facility, independently of display history and captured native evidence. A carried obligation identifies its source namespace and immutable key, repository and snapshot digest, kind (finding, route or result), retained summary and evidence references, and explicitly affected PRs. The service retains private original provenance. It does not interpret imported text as instructions, merge authority or proof of current-code coverage. +The native service accepts generic source-bound obligations through a project-management preview/apply facility, independently of display history and captured native evidence. A carried obligation identifies its source namespace and immutable key, repository and snapshot digest, kind (finding, route or result), retained summary and evidence references, and explicitly affected PRs. The service retains private original provenance. It does not interpret imported text as instructions, merge authority or proof of current-code coverage. Open obligations hold new review admission and existing review progression for their affected PRs in both channels. The guard applies before provider preparation and again at transactional operation admission and final dispatch. A finished grant, existing capture, channel closure, head change, reordered queue or another channel cannot bypass it. Unrelated PRs and projects retain their existing behavior. Local assessment reads explain the hold with bounded counts and a deliberate detail read; ordinary calls do not print the imported ledger. -Preview is read-only and binds the complete selected batch to the destination instance, project, administrator, worker and expected revision. Apply rechecks scope and current authority and atomically records obligations, provenance, receipt and compact events. An original-key replay returns the original result. Reimport cannot reopen a resolved obligation, erase a native action or silently replace changed source facts. Omission is additive, never deletion or resolution. Admission refuses conflicting provenance. A protective hold may arrive during queued or prepared work; final dispatch guards must observe it. It does not cancel or relabel an existing intent, or prevent consuming and finalizing a result that was already posted. +Preview is read-only and binds the complete selected batch to the destination instance, project, authenticated principal, worker and expected revision. Apply rechecks scope and current authority and atomically records obligations, provenance, receipt and compact events. An original-key replay returns the original result. Reimport cannot reopen a resolved obligation, erase a native action or silently replace changed source facts. Omission is additive, never deletion or resolution. Admission refuses conflicting provenance. A protective hold may arrive during queued or prepared work; final dispatch guards must observe it. It does not cancel or relabel an existing intent, or prevent consuming and finalizing a result that was already posted. Resolution is an explicit revision-guarded action retaining actor, reason and evidence pointers. The worker must establish that the carried obligation has been addressed; importing it or merging its original PR is insufficient. Preserve original source state and later native resolution as distinct facts. Resolution neither changes original finalized review counts nor creates a captured review, comparison coverage, CI observation or merge permission. @@ -26,7 +26,7 @@ Admission validates each selected obligation, target list and resolution in boun ## Bound commands and authority -Import preview/apply use the private administrator profile. Listing, reading, retargeting and resolving use the selected project profile; retargeting and resolution require ordinary project write permission and a valid project worker, without an administrator or Overseer handoff. Ordinary commands remain compact and provider-free: +Import preview/apply require `manage` permission for the selected project or instance administration, plus a valid project worker. Ordinary project read/write permission is insufficient. CLI and MCP use the explicitly selected bound profile, and current authority is rechecked for preview, apply and exact-key replay. Listing, reading, retargeting and resolving use the selected project profile; retargeting and resolution require ordinary project write permission and a valid project worker, without an administrator or Overseer handoff. Ordinary commands remain compact and provider-free: ```sh fc reviews obligations adopt preview --file /private/obligations.json @@ -39,7 +39,7 @@ fc reviews obligations resolve OBLIGATION_ID --expected-revision 1 --reason "Cor The version-one batch contains `source: {namespace, repository_id, snapshot_sha256}`, `expected_revision` and one to one hundred `obligations`. Each obligation contains `source_key`, `kind` (`finding`, `route` or `result`), `affected_pull_numbers`, `summary`, `evidence` and `original_status` (`pending` or `open`). Original evidence may be an explicit empty array when unavailable; a native resolution requires at least one evidence pointer. Each normalized original JSON record is bounded to 32 KiB, each combined normalized resolution or retarget request to 16 KiB, and the complete normalized apply wrapper to 256 KiB. These encoded bounds include escaping. Full-detail reads have a 96 KiB HTTP response budget in the shared CLI/MCP client, preserving previously accepted originals, resolutions and retargets without tightening their limits. The three retained content blocks contribute at most 64 KiB; replacing request revisions with retained revisions and adding attribution, source identity and current scope adds less than 16 KiB. A conservative overhead bound allows eight 128-byte IDs, a 200-byte namespace, the 64-byte digest and three 64-byte timestamps at up to six encoded bytes per input byte, 101 ten-digit affected PRs plus separators, ten 20-byte numeric values, and 2 KiB for field names and JSON punctuation. The resulting bound is below 80 KiB, leaving headroom within the finite 96 KiB transport cap. Detail contains only the latest retarget, not its unbounded history. Backup validation retains the original admission limits. The CLI validates the owner-private regular input before reading credentials or making a request. Preview changes no state; apply binds its exact normalized content and preserves original-key recovery after lost output or later resolution. -`list` returns identity, status, revision and affected PRs, without expanding summaries or evidence. Its 512 KiB response budget accommodates one hundred items with maximally escaped 200-byte namespace and source keys and up to 101 affected PRs per route. `read` deliberately returns retained originals, current scope, the latest retarget if present and any native resolution. The HTTP owner is `/api/v1/projects/{project_id}/reviews/adoption-obligations`, with `GET`, `GET /{id}`, `POST /preview`, `POST /apply`, `POST /{id}/retarget` and `POST /{id}/resolve`; import preview/apply require administrator authority and a valid project worker. Resolution requires project write permission and a valid project worker, rechecked before the first mutation and original-key replay; read-only access cannot resolve obligations. Reads and mutations retain the ordinary short command budget and never call a review provider. +`list` returns identity, status, revision and affected PRs, without expanding summaries or evidence. Its 512 KiB response budget accommodates one hundred items with maximally escaped 200-byte namespace and source keys and up to 101 affected PRs per route. `read` deliberately returns retained originals, current scope, the latest retarget if present and any native resolution. The HTTP owner is `/api/v1/projects/{project_id}/reviews/adoption-obligations`, with `GET`, `GET /{id}`, `POST /preview`, `POST /apply`, `POST /{id}/retarget` and `POST /{id}/resolve`; import preview/apply retain the management authority and worker requirement above. Resolution requires project write permission and a valid project worker, rechecked before the first mutation and original-key replay; read-only access cannot resolve obligations. Reads and mutations retain the ordinary short command budget and never call a review provider. ### Refusals and recovery @@ -56,7 +56,7 @@ The native HTTP contract uses the following codes for guarded changes and source | `not_found` | The selected project, worker, obligation or linked retained source is absent in the bound scope. | Verify the binding and identifier. A policy link requires its matching obligation source to be retained in that project first; do not treat absence as clearance. | | `repository_changed` | A retained obligation source belongs to a different repository from the project's current binding. | Stop and have the repository/source binding verified. Retrying with a newer revision does not repair provenance. | | `adoption_obligation_not_route` | Retargeting an open `finding` or `result` obligation after its revision/status guard passes. | Stop retargeting it. Only `route` obligations can change receiver; resolution still requires actual completion evidence. | -| `forbidden` | Required administrator/project permission or worker attribution is missing, including on exact-key replay. | Stop until the required authority and valid project-worker binding are available. A previous receipt does not authorize its retrieval after permission loss. | +| `forbidden` | Required project-management, instance-administration or project-write permission or worker attribution is missing, including on exact-key replay. | Stop until the required authority and valid project-worker binding are available. A previous receipt does not authorize its retrieval after permission loss. | | `unauthorized` | Authentication is missing, invalid, expired or revoked, including on exact-key replay. | Restore valid authentication before retrying the unchanged original request/key; do not replace the key to bypass revocation. | ## Policy and obligation linkage diff --git a/docs/architecture.md b/docs/architecture.md index 8ff5b4cac..e3fef6bce 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -2,7 +2,7 @@ ## Implementation status -This document owns the service contract. The coordination slice implements local SQLite storage, scoped project/worker/access endpoints, basic jobs/history and durable messages with atomic receipts/events. See the [local API](local-api.md) for that boundary. The [incoming-message feed](message-events.md) implements scoped snapshot/replay, bounded waits and browser SSE; the [embedded browser](browser-guide.md) provides read-only jobs, workers and live incoming conversations. [Job checkpoints](job-checkpoints.md) record immutable progress independently of current job state. The [native review workspace](review-workspace.md) adds explicit administrator observations and indexed stored review reads; optional [native review execution](review-execution.md) and [source refresh](review-source.md) supply separately owned provider workers. Explicit [required CI observations](review-ci.md) supply a separate retained assessment. Explicit [observed readiness](review-readiness.md) combines retained provider facts with current local policy without provider work in reads. Explicit [public checkpoint publication](review-publication.md) owns a separate bounded provider worker and retained posting intent. Local operator [backup and activation](backups.md), [provider resumption](provider-resumption.md), and the focused job capabilities have their implementation status and proof at their owning contracts in the [documentation index](README.md). Design decisions are recorded in [decisions](decisions.md). +This document owns the service contract. The coordination slice implements local SQLite storage, scoped project/worker/access endpoints, basic jobs/history and durable messages with atomic receipts/events. See the [local API](local-api.md) for that boundary. The [incoming-message feed](message-events.md) implements scoped snapshot/replay, bounded waits and browser SSE; the [embedded browser](browser-guide.md) provides read-only jobs, workers and live incoming conversations. [Job checkpoints](job-checkpoints.md) record immutable progress independently of current job state. The [native review workspace](review-workspace.md) adds explicit administrator and project-manager observations and indexed stored review reads; optional [native review execution](review-execution.md) and [source refresh](review-source.md) supply separately owned provider workers. Explicit [required CI observations](review-ci.md) supply a separate retained assessment. Explicit [observed readiness](review-readiness.md) combines retained provider facts with current local policy without provider work in reads. Explicit [public checkpoint publication](review-publication.md) owns a separate bounded provider worker and retained posting intent. Local operator [backup and activation](backups.md), [provider resumption](provider-resumption.md), and the focused job capabilities have their implementation status and proof at their owning contracts in the [documentation index](README.md). Design decisions are recorded in [decisions](decisions.md). ## Boundaries @@ -18,7 +18,7 @@ Every stored project-owned resource has a project identifier. Names are unique o For the initial GitHub integration, one project binds one repository and a repository may belong to only one project within an instance. Creation/binding verifies GitHub's stable repository ID and atomically enforces that uniqueness; a renamed repository or alternate remote URL cannot bypass it. A duplicate returns `repository_already_configured` with the existing project reference when the caller may see it, otherwise an opaque conflict. An interrupted or concurrent binding must not leave two owners. Separate service instances are independent; GitHub Projects boards do not define this application boundary. Broader repository groupings require a separately reviewed design. -Credentials bind an authenticated principal to allowed projects and operations. A supplied worker name is attribution metadata, not permission. Project creation, access management, provider credentials, and project policy changes require administrative permission. The initial access model supports instance administrators and project-scoped read/write clients; additional roles require their own reviewed contract. +Credentials bind an authenticated principal to allowed projects and operations. A supplied worker name is attribution metadata, not permission. Project creation/listing, provider credentials, public publication configuration/preview/apply/unpublish and initial or changed capability binding require instance administration. Explicit project management grants permit project access administration and policy/configuration changes within the selected project; they never elevate a client to instance administration. Management implies read/write, but existing writers receive no automatic management grant. Current exact credentials and project permissions are rechecked for reads, mutations and receipt replay. The [local API](local-api.md) owns permission-set CAS and the [worker retirement contract](worker-retirement.md) owns guarded cleanup and retained identities. Every read, write, pagination cursor, review task, and event subscription validates project scope at the server. Cross-project references are rejected before mutation. The first release does not route messages across projects; Recipient names resolve only within the selected project. A future cross-project route must state both destination project and authorization explicitly. diff --git a/docs/backups.md b/docs/backups.md index 51c39070f..dcaf397d2 100644 --- a/docs/backups.md +++ b/docs/backups.md @@ -148,3 +148,11 @@ Registering a new successful managed backup clears the previous pruning result i The `review_comparison` and `review_route_policy` domains are each present when their corresponding `schema:` metadata marker is present. A marker without its required tables, or domain tables without their marker, refuses bundle creation, inspection and inactive restore. Each present domain must match its owning table, index, foreign-key and invalidation/retention trigger definitions exactly. Manual and scheduled backup creation, inspection and inactive restore independently rederive every native completion proof or receiving-route fact for the present domains from original retained authority. Missing, dirty, mismatched or forged cached facts in those domains refuse all three operations, including inspection and restore of resealed bundles. Creation fails before publishing a completed bundle; none of these operations repairs the facts. Supported predecessor bundles without an optional domain's marker and tables remain valid; inspection and inactive restore do not install the absent domain. Restore preserves original capture bytes, source anchors and frozen counts, and retains pending obligations across heads. For persistent failures, follow the owning recovery guidance for [completion proofs](reviews.md#retained-native-channel-completion) and [receiving-route facts](review-routes.md#source-and-receiving-authority). The [completion foundation qualification](delivery.md#native-channel-completion-foundation) records the executable proof limits. Rederivation can exceed the configured deadline even on a valid installation and return `backup_unavailable`. If the deadline was reached, a longer manual [`--timeout`](#operator-commands) or scheduled [`--backup-timeout`](#managed-scheduling-and-retention), up to the supported twenty-four-hour maximum, may allow it to finish. `backup_unavailable` alone does not establish that a timeout occurred. + +## Administration domains + +`project_management:1` adds explicit default-zero management to existing grants; `worker_retirements:1` retains scoped worker retirement facts without deleting worker identities. Inventory inspection validates these optional versions, physical schema, foreign keys and semantic records. Old bundles without either domain remain readable and restore without an inspection-time migration. Inactive restore preserves grant/retirement history while revoking all copied credentials, so retained management never automatically restores access. Unknown newer administration formats are refused before either core administration migration runs. + +Focused compatibility proof includes a genuine predecessor-binary bundle, unchanged predecessor rows through startup upgrade, exact predecessor empty-body acknowledgement replay, and resealed authority/retirement corruption rejection before target creation. This does not imply compatibility with unrelated newer integrated domain versions or replace the existing provider-resumption hold. + +CI qualification generates the administration compatibility bundle from pinned predecessor commit `383ce8c0bc4505dd89cf5cdec7fb2da1d7e556c8` with `tools/ci/generate-admin-parent-fixture.sh`, then runs the inactive-restore regression with `FC_ADMIN_PARENT_FIXTURE` set. The fixture contains a live synthetic bootstrap credential before restore and neither administration domain. No retained private bundle is committed. Focused SQL-reader tests cancel each administration semantic query deterministically; separate operation-level tests cover canceled inspect, restore, manual and managed creation without publishing or modifying source state. diff --git a/docs/development.md b/docs/development.md index 8d52f4e83..f0fc058fc 100644 --- a/docs/development.md +++ b/docs/development.md @@ -75,7 +75,7 @@ Supply `FC_PROFILE` through the agent host's process environment or select `--pr | Command | Returned scope | | --- | --- | | `fc doctor` | Verified instance/project/worker binding, without credentials or a PR scan. | -| `fc workers list` | One compact worker page in the bound project. | +| `fc workers list` | One compact active-worker page in the bound project; `--include-retired` also includes retired workers. | | `fc jobs context JOB_ID [--limit N]` | Complete current brief/checkpoint/checklist plus bound-worker focus/pause and pending previews, explicit omissions, continuation cursors and incoming-event watermark. | | `fc notes read NOTE_ID` | One full current note. | | `fc notes list` | One compact pending page for the bound worker and its currently assigned jobs; explicit scope/filter flags narrow or broaden selection. | @@ -104,7 +104,7 @@ Supply `FC_PROFILE` through the agent host's process environment or select `--pr | `fc inbox list` | Bound worker's compact message previews; optional unread/unacknowledged filters. | | `fc inbox thread ID` | Explicit bounded conversation page with full bodies. | -Administrator setup also supports [prepared review import](review-import.md) through `fc reviews import-preview --file ABSOLUTE_PATH` and `fc reviews import-apply --file ABSOLUTE_PATH --preview SHA256 --key KEY`. Preview is provider-free and read-only; apply uses the existing guarded observation receipt. These commands require deliberately selected administrator access rather than an ordinary worker credential. +Project management also supports [prepared review import](review-import.md#selected-sources-and-destination) through `fc reviews import-preview --file ABSOLUTE_PATH` and `fc reviews import-apply --file ABSOLUTE_PATH --preview SHA256 --key KEY`. Preview is provider-free and read-only; apply uses the existing guarded observation receipt. Select a profile with the owning contract's project-management or instance-administration authority; ordinary project read/write permission is insufficient. Review queue/run lists accept `--limit` and `--cursor`; omitted limits select five entries. Review selectors validate before credentials or HTTP, and reads perform no provider refresh or review execution. Source timestamps and completeness remain observations, not readiness. @@ -137,7 +137,7 @@ Quick local mutations use the same private profile and a five-second operation b | `fc jobs checklist-set ID --key KEY --expect-revision N --expect-checklist-revision C` | Exactly one of `--items JSON` or `--items-file PATH`; guarded ordered replacement, with unchanged content reported explicitly. | | `fc inbox send --key KEY --to WORKER_ID --body TEXT` | Optional `--reply-to MESSAGE_ID`; the bound worker is the sender. | | `fc inbox seen MESSAGE_ID --key KEY` | Only the bound actual recipient can change seen state. | -| `fc inbox ack MESSAGE_ID --key KEY` | Only the bound actual recipient can acknowledge; acknowledgment also establishes seen state. | +| `fc inbox ack MESSAGE_ID --key KEY [--worker WORKER_ID]` | Acknowledgment also establishes seen state; selecting another recipient requires project management. | The parser rejects incomplete, repeated, oversized and malformed arguments before opening profiles or credentials or contacting the service. Brief and body text remain exact UTF-8; selected title/assignment normalization follows the API. Omitted edit fields stay unchanged. Guarded edits return the current revision on conflict. A retained key replays the original receipt after current authorization; it never overwrites a newer revision. @@ -184,3 +184,9 @@ Use `reviews operations` to discover one page of retained operations and `review ## Explicit channel-front selection Use `fc reviews start --channel cli --key KEY` for one durable selection and at most one native child, or `--channel hosted` for the independent Hosted channel. Optional `--expect-pr NUMBER` and `--expected-configuration-revision REVISION` assert the selected target and accepted configuration. `fc reviews run-read --selection-id ID --wait-seconds SECONDS` observes the same selection and original child; it never starts another request. `start` defaults to a two-second wait and `run-read` to no wait; use `--wait-seconds 0` for an immediate receipt. Keep the original key when stdout is lost. A terminal hold requires a fresh authorized request after its cause is resolved. The [selection contract](review-round-controls.md#one-explicit-channel-front-run) owns bounds, recovery and the deferred automatic-scheduling boundary. + +## Native administration + +Use `reviews policy`, `reviews policy-configure --file /absolute/private.json --key KEY`, `reviews execution-configure --file /absolute/private.json --key KEY`, `workers create --name NAME --key KEY`, and `credentials grant|update|revoke`. Operation `--help` is local and runs before profiles or private files are read. Credential grant accepts either `--token-sha256` or an owner-private `--credential-file`; only the digest is transmitted. Permission replacement uses a private JSON file with complete expected and desired permission sets. Retain the original key and arguments after uncertain output; mutations are never automatically reposted. + +Use `workers retirement WORKER_ID` before `workers retire WORKER_ID --key KEY`. `workers list --include-retired` explicitly includes historical identities. `inbox list --worker WORKER_ID` selects a recipient without changing the acting worker; `inbox ack MESSAGE_ID --worker WORKER_ID --key KEY` requires current project management when acknowledging for another recipient. See [retirement](worker-retirement.md) for blockers and race semantics. diff --git a/docs/hosting.md b/docs/hosting.md index 25b6ec9f3..142f56add 100644 --- a/docs/hosting.md +++ b/docs/hosting.md @@ -48,7 +48,7 @@ Local [operator backup, inspection, inactive restore and managed scheduling](bac `fcd --schema-migration-timeout DURATION` selects a positive startup budget of at most `24h`, defaulting to `30s`. The value is validated before filesystem work or operator credential loading. It applies separately to each versioned domain schema installation or upgrade, including that domain's migration statements, metadata update and backfill. Each domain receives a fresh budget; this is not a total daemon startup deadline or a change to base database initialization, live writes, HTTP requests, provider work or backup-command deadlines. The option is process-local and does not change stored configuration. Parent cancellation or an earlier parent deadline still stops the work. -Every domain migration remains one exclusive transaction, with complete retained-authority validation and no intermediate commits. A failed domain rolls back its new schema, derived rows and version metadata together; domains completed earlier in startup may already be committed. The daemon does not listen until all required schemas complete. A timeout after exclusive work begins reports `schema_migration_timeout`; admission or lock contention retains `overloaded`. Preserve the installation and diagnostics for investigation, especially if rollback cannot be confirmed. The timeout alone does not establish corruption. +Every domain migration remains one exclusive transaction, with complete retained-authority validation and no intermediate commits. A failed domain rolls back its new schema, derived rows and version metadata together; domains completed earlier in startup may already be committed. Each administration migration checks both administration schema versions under its own exclusive writer transaction before changing its domain; this does not support concurrent service replicas. The daemon does not listen until all required schemas complete. A timeout after exclusive work begins reports `schema_migration_timeout`; admission or lock contention retains `overloaded`. Preserve the installation and diagnostics for investigation, especially if rollback cannot be confirmed. The timeout alone does not establish corruption. A valid large retained history can exceed the default. After diagnosing the failure, confirming rollback and checking storage/resources, an operator can retry with an explicit larger budget, for example `fcd --data-dir /private/firecontroller --schema-migration-timeout 10m`. Allow the service manager or orchestrator enough startup time for all domains; the example is not a capacity guarantee. The failed domain restarts from the beginning and reruns all validation, rather than resuming or accepting partial work. Increasing the budget does not repair invalid retained authority, remove records, bypass validation or permit unbounded waits. Preserve the single-writer replacement strategy and the [validated backup and inactive-restore procedure](backups.md) when recovery is needed. Restarting with an unchanged insufficient budget or restoring identical over-budget data can repeat the failure. diff --git a/docs/local-api.md b/docs/local-api.md index a30de83f6..ab7a3afb7 100644 --- a/docs/local-api.md +++ b/docs/local-api.md @@ -2,7 +2,7 @@ ## Implemented boundary -`fcd` serves scoped projects, workers, access grants, basic jobs and durable messages. The CLI implements local `version`/`context` and the profile-bound [read commands](development.md#read-only-agent-commands). The [explicit-key CLI mutations](development.md#explicit-agent-mutations) cover jobs, checkpoints, progress, focus, pause, notes and messages. The [stdio MCP adapter](mcp.md) exposes read and explicit-key mutation tools against these same endpoints. The [incoming-message event API](message-events.md) supplies scoped snapshot/replay, bounded waits and a persistent SSE transport. The [embedded browser](browser-guide.md) displays projects, jobs/checkpoint details, read-only checklists and narrative updates, workers, live incoming conversations and stored review queue, PR and run views. [Job checkpoints](job-checkpoints.md) provide immutable progress records through the same API and agent clients. The [review workspace](review-workspace.md) implements administrator observation and scoped read routes. Optional [native review execution](review-execution.md) and explicit [source refresh and observed policy](review-source.md) use separate project-scoped routes and owned background workers. [Deferred notes](notes.md) add explicit scoped reminder/source reads and guarded mutations. The scoped project feed updates current stored views; explicit opt-in browser messaging and administrator appearance controls use attenuated session authority; a backup API remains a separate boundary. The [public project website](public-site.md) uses administrator publication routes and independent anonymous reads/events. +`fcd` serves scoped projects, workers, access grants, basic jobs and durable messages. The CLI implements local `version`/`context` and the profile-bound [read commands](development.md#read-only-agent-commands). The [explicit-key CLI mutations](development.md#explicit-agent-mutations) cover jobs, checkpoints, progress, focus, pause, notes and messages. The [stdio MCP adapter](mcp.md) exposes read and explicit-key mutation tools against these same endpoints. The [incoming-message event API](message-events.md) supplies scoped snapshot/replay, bounded waits and a persistent SSE transport. The [embedded browser](browser-guide.md) displays projects, jobs/checkpoint details, read-only checklists and narrative updates, workers, live incoming conversations and stored review queue, PR and run views. [Job checkpoints](job-checkpoints.md) provide immutable progress records through the same API and agent clients. The [review workspace](review-workspace.md) implements observation appends for project managers and instance administrators, with scoped read routes. Optional [native review execution](review-execution.md) and explicit [source refresh and observed policy](review-source.md) use separate project-scoped routes and owned background workers. [Deferred notes](notes.md) add explicit scoped reminder/source reads and guarded mutations. The scoped project feed updates current stored views; explicit opt-in browser messaging and administrator appearance controls use attenuated session authority; a backup API remains a separate boundary. The [public project website](public-site.md) uses administrator publication routes and independent anonymous reads/events. The [architecture](architecture.md) owns target behavior. This page describes the current implementation and its limits. @@ -18,7 +18,7 @@ The service creates an owner-only data directory when absent and stores its data The daemon supports only loopback listeners. Remote HTTPS access through deployment-owned reverse proxies has [hosted proof](hosting.md#executed-deployment-proof); the daemon does not terminate TLS itself. SQLite must use local storage, with one active service process; network-mounted databases and multiple active replicas are unsupported. -Clients send `Authorization: Bearer ` on API requests. Administrative project creation, project listing, and access management require the bootstrap administrator. Project clients receive explicit `read` and/or `write` grants. `X-FC-Worker` selects an existing worker in the request's project for attribution; it never grants permission. Sending messages and changing seen/ack state require that worker selection. +Clients send `Authorization: Bearer ` on API requests. Project creation and project listing require instance administration. Project access management accepts explicit project-management grants or an instance administrator. Project clients receive explicit `read`, `write` and `manage` permissions; `manage` implies read and write, while a writer is not implicitly a manager. `X-FC-Worker` selects an existing worker in the request's project for attribution; it never grants permission. Sending messages and changing seen/ack state require that worker selection. The authenticated `GET /api/v1/instance` returns the durable instance ID. Bound clients supply `X-FC-Instance` on every request; a mismatch returns `instance_mismatch` before domain reads, writes or provider work, including replacement after a client handshake. Missing headers remain supported for explicit administrative bootstrap. The local `fc context` command only reports configuration. @@ -28,7 +28,7 @@ The embedded browser derives an explicitly attenuated session after its bearer-a HTTPS deployments use a Secure, host-only `__Host-fc-browser-{session_id}` cookie at `/`. Only literal localhost or loopback HTTP origins use `fc-local-browser-{session_id}` without Secure. Forwarding headers never weaken cookie security. The deployment must preserve the public Host header; HTTPS termination belongs to [hosting infrastructure](hosting.md). Successful connection retains at most eight valid session cookies issued by this instance, within a 6 KiB cookie-header budget. The new connection is always kept; older retained sessions are expired as needed. Closing a tab without Disconnect therefore cannot grow this instance’s cookie header indefinitely. Other instances’ undecodable cookies and unrelated applications’ cookies are left alone. An evicted tab must connect again; ordinary reload preserves its retained session. -Session reads send exactly one `X-FC-Browser-Session` selector and its matching cookie, with the expected instance header and optional worker selector. Authorization plus a session selector is rejected; cookies without the selector do not authenticate requests. GET/HEAD requests retain project-read attenuation, including the verified instance handshake. Explicit write approval permits only message send/seen/ack and administrator presentation replacement, with a mandatory exact same-origin Origin. It never permits administrative listing, provider/review actions, publication, jobs or access changes. Encrypted initial write/admin allowances intersect current grants; later credential promotion does not broaden an existing session. `GET` on the browser-session endpoint requires the cookie plus selector and returns the same six current identity/capability fields for resume. Current credential revocation, grants, project binding and absolute expiry are enforced again during authorization, including active message streams. Durable instance signing material permits sessions to survive service restart; replacing the instance does not silently rebind them. +Session reads send exactly one `X-FC-Browser-Session` selector and its matching cookie, with the expected instance header and optional worker selector. Authorization plus a session selector is rejected; cookies without the selector do not authenticate requests. GET/HEAD requests retain project-read attenuation, including the verified instance handshake. Explicit write approval permits only message send/seen/ack and project-management presentation replacement, with a mandatory exact same-origin Origin. It never permits administrative listing, provider/review actions, publication, jobs or access changes. Encrypted initial write/management allowances intersect current grants; later credential promotion does not broaden an existing session. `GET` on the browser-session endpoint requires the cookie plus selector and returns the same six current identity/capability fields for resume. Current credential revocation, grants, project binding and absolute expiry are enforced again during authorization, including active message streams. Durable instance signing material permits sessions to survive service restart; replacing the instance does not silently rebind them. `DELETE` on the same endpoint takes the selector header and exactly `{}`, with no bearer header, and expires only that selector's cookie. The response is `{"session_id":"","logged_out":true}`. Clearing works for an expired or missing cookie and never revokes the original credential. POST and DELETE reject a supplied mismatched Origin or cross-site fetch metadata and do not enable cross-origin access. See [browser connection behavior](browser-guide.md#connect-and-navigate) for per-tab storage, reload and disconnect semantics. @@ -46,8 +46,9 @@ Receipt keys include their originating instance. Startup upgrades base schema ve | `POST /api/v1/projects/{project_id}/workers` | Scoped write sends `{name}`; returns compact worker receipt. | | `GET /api/v1/projects/{project_id}/workers` | Scoped bounded worker page. | | `GET /api/v1/projects/{project_id}/workers/{worker_id}` | Scoped worker detail. | -| `POST /api/v1/projects/{project_id}/credentials` | Administrator sends `{token_sha256, permissions}`; returns credential/principal IDs and project ID. | -| `DELETE /api/v1/projects/{project_id}/credentials/{credential_id}` | Administrator revokes access; requires an idempotency key. | +| `POST /api/v1/projects/{project_id}/credentials` | Project manager or instance administrator sends `{token_sha256, permissions}`; returns credential/principal IDs and project ID. | +| `PUT /api/v1/projects/{project_id}/credentials/{credential_id}` | Project manager or instance administrator sends `{expected_permissions, permissions}` with an idempotency key; stale permissions return `credential_permissions_changed`. | +| `DELETE /api/v1/projects/{project_id}/credentials/{credential_id}` | Project manager or instance administrator revokes access; requires an idempotency key. | For a project client, generate a high-entropy secret privately and register its lowercase SHA-256 hex digest, with permissions such as `["read", "write"]`. Keep the raw secret in the client's protected credential file. The service stores its hash; API receipts do not return the raw secret. Each registered credential currently establishes a separate principal. @@ -83,7 +84,7 @@ Statuses are `active`, `parked`, `blocked` and `completed`; creation defaults to | `GET /inbox/{worker_id}` | Compact previews and seen/ack state; optional `unread=true` and `unacknowledged=true` filters. | | `GET /conversations/{conversation_id}` | Explicit chronological full-body page with root/reply identities. | | `POST /messages/{message_id}/seen` | Strict `{}` body; only the selected actual recipient can mark seen. | -| `POST /messages/{message_id}/ack` | Strict `{}` body; only the selected actual recipient can acknowledge, atomically establishing seen. | +| `POST /messages/{message_id}/ack` | Strict object with optional recipient `worker_id`, defaulting to the acting worker. Acknowledging for another recipient requires current project management and preserves the acting worker. Atomically establishes seen. See [guarded retirement](#project-management-and-guarded-retirement). | Sender, recipient and reply references must belong to the selected project. Body is nonblank UTF-8, bounded to 16 KiB. Inbox previews contain at most 160 Unicode runes with explicit `preview_truncated`. Replies preserve conversation identity, and pages use a durable insertion sequence rather than timestamp ordering alone. @@ -103,7 +104,7 @@ See [development proof](development.md) for executed checks and unproven boundar Jobs and inbox schemas have separate ordered migration versions stored in instance metadata. Startup applies only missing migrations under the same exclusive transaction as their version records and refuses a newer domain version before running its DDL. Failed migrations roll back their schema changes and version updates together. The original unversioned domain tables enter this sequence at version zero using their idempotent initial DDL; this does not validate an arbitrarily modified database. Use a compatible binary for a newer schema rather than deleting version records. Migration checks run before serving requests, never during ordinary reads or writes. -The [native review workspace](review-workspace.md) owns its administrator observation and project-scoped queue/PR/run read routes. [Prepared review import](review-import.md) adds an explicit administrator preview/apply flow against that same observation transaction. Queue/PR/run reads and import preview read indexed stored evidence; observation and apply are guarded writes. None of these handlers performs provider refresh or job/message effects. +The [native review workspace](review-workspace.md) owns observation appends for project managers and instance administrators, and project-scoped queue/PR/run read routes. [Prepared review import](review-import.md) adds an explicit preview/apply flow for administrators and project managers with `manage` permission against that same observation transaction. Queue/PR/run reads and import preview read indexed stored evidence; observation and apply are guarded writes. None of these handlers performs provider refresh or job/message effects. The [source refresh contract](review-source.md) owns its explicit POST, operation read and observed-policy read. Its short default wait returns a completed result directly where possible, with a pending receipt only when the work remains active; ordinary review reads never trigger that refresh. @@ -122,3 +123,13 @@ The [source refresh contract](review-source.md) owns its explicit POST, operatio ## Job resume context [Job resume context](job-context.md) owns `GET /jobs/{job_id}/context`, with an explicit worker binding and optional bounded limit. One authorized snapshot combines the complete current brief/latest checkpoint/checklist, worker focus/pause, selected pending-note/inbox previews and incoming-event watermark. Required content is never truncated; the response states which bodies or additional pages need explicit reads. This deliberate operation does not expand routine job reads or perform provider work. + +## Project management and guarded retirement + +A project manager can grant a new credential with `POST /api/v1/projects/{project_id}/credentials`, change an existing active non-administrator grant with `PUT /api/v1/projects/{project_id}/credentials/{credential_id}`, or revoke that project's grant with DELETE. All mutations require an explicit idempotency key. Grant accepts `{token_sha256, permissions}`; the lowercase SHA-256 digest is supplied instead of a raw secret. PUT requires complete `expected_permissions` and `permissions` arrays. Unique read/write/manage values normalize in that order, with manage implying read/write. Mismatched current permissions return `credential_permissions_changed` and only the selected grant's current permission set. A no-op returns `unchanged`; an update preserves credential/principal identity and records old/new permissions. Foreign, revoked and instance-administrator credentials are unavailable to this route. + +Revocation clears only this project's grant. Another active project grant remains usable; the credential is marked revoked only when none remain. Exact-key receipt replay retains the original result but still requires current management authority. Self-demotion or revocation cannot recover a privileged receipt. No grant operation creates instance authority. Initial and changed review capability binding remain operator-only; a manager may reconfigure an already bound capability within the project. + +Native CLI and MCP offer policy read/configuration, execution configuration, worker creation and credential grant/update/revoke. Policy replacement requires the complete existing `paused_channels` field as well as required channels and the revision. Execution replacement retains the current nonempty queue contract. The [retirement API](worker-retirement.md) adds preview, guarded retirement, active/archive lists and explicit manager-on-behalf acknowledgement without changing the acting identity. + +Existing browser presentation authority intersects the encrypted initial management ceiling with current grants. This slice keeps the existing explicit allow-writes opt-in and mutation allowlist; browser retirement controls and new browser scheduling controls are not implemented here. diff --git a/docs/mcp.md b/docs/mcp.md index 94f1e25a8..af10ec30f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -28,18 +28,38 @@ Startup validates configuration without opening the credential or contacting the | Tool | Input and result | | --- | --- | -| `review_round_adoption_preview` | Administrator and valid project worker; required document. Preview the native [round-adoption document](review-round-controls.md#carried-rule-adoption) against its original-source and current revision guards; no live reviews are requested. | -| `review_round_adoption_apply` | Administrator and valid project worker; required document/preview_sha256/idempotency_key. Apply the exact previewed [round-adoption document](review-round-controls.md#carried-rule-adoption). Preserves retained attribution and accounting rules; tooling access is not review authorization. | +| `review_round_adoption_preview` | Project management or instance administration, and a valid project worker; required document. Preview the native [round-adoption document](review-round-controls.md#carried-rule-adoption) against its original-source and current revision guards; no live reviews are requested. | +| `review_round_adoption_apply` | Project management or instance administration, and a valid project worker; required document/preview_sha256/idempotency_key. Apply the exact previewed [round-adoption document](review-round-controls.md#carried-rule-adoption). Preserves retained attribution and accounting rules; tooling access is not review authorization. | | `review_obligations_list` | Project read access; optional pull_number/status/limit/cursor, with status open or resolved. Read one compact [carried-obligation](adoption-obligations.md#bound-commands-and-authority) page. Full bodies require review_obligation_read. | | `review_obligation_read` | Project read access; required obligation_id. Read one retained carried obligation and original evidence, without marking it resolved; see [carried-obligation reads](adoption-obligations.md#bound-commands-and-authority). | | `review_obligation_retarget` | Project write access and valid project worker; required obligation_id/expected_revision/target_pull_number/reason/idempotency_key. Move an open carried route to one receiving PR; target_pull_number zero means unassigned backlog. Preserves original provenance and source scope; does not resolve work or grant review credit. See [route receivers](adoption-obligations.md#current-receivers-of-carried-routes). | -| `review_obligations_import_preview` | Administrator and valid project worker; required document. Preview one strict native [carried-obligation batch](adoption-obligations.md#bound-commands-and-authority), preserving original evidence and provenance; no application or new review. | -| `review_obligations_import_apply` | Administrator and valid project worker; required document/preview_sha256/idempotency_key. Apply the exact previewed [carried-obligation batch](adoption-obligations.md#bound-commands-and-authority). Existing source conflicts and evidence requirements remain enforced. | +| `review_obligations_import_preview` | Project management or instance administration, and a valid project worker; required document. Preview one strict native [carried-obligation batch](adoption-obligations.md#bound-commands-and-authority), preserving original evidence and provenance; no application or new review. | +| `review_obligations_import_apply` | Project management or instance administration, and a valid project worker; required document/preview_sha256/idempotency_key. Apply the exact previewed [carried-obligation batch](adoption-obligations.md#bound-commands-and-authority). Existing source conflicts and evidence requirements remain enforced. | | `review_obligation_resolve` | Project write access and valid project worker; required obligation_id/document/idempotency_key. Resolve one carried obligation using the native {expected_revision,reason,evidence} document. Requires an evidence-backed [resolution](adoption-obligations.md#bound-commands-and-authority); grants no review credit. | | `context` | No fields; configured local identity, without service verification. | +| `review_policy_read` | Read current policy including paused_channels. | +| `review_policy_configure` | Complete policy replacement with expected_revision, paused_channels and explicit idempotency_key. | +| `review_execution_configure` | Guarded existing capability/configuration replacement with nonempty queue and explicit key. | +| `worker_create` | Create a named worker using an explicit key. | +| `worker_retirement_read` | Read bounded unfinished-job, pending-note and incoming-message blockers. | +| `worker_retire` | Guarded one-way retirement; explicit worker_id and key. | +| `project_credential_grant` | Grant a distinct credential digest scoped permissions; explicit key. | +| `project_credential_update` | Full expected_permissions/permissions CAS for credential_id and explicit key. | +| `project_credential_revoke` | Revoke only this project grant for credential_id and explicit key. | +| `presentation_replace` | Apply a strict native presentation document and key. | +| `presentation_history` | One bounded retained history page. | +| `presentation_revision_read` | Read one retained revision. | +| `publication_configuration_read` | Read selected public publication configuration; requires instance administration. | +| `publication_preview` | Preview a complete native publication document without publishing; requires instance administration. | +| `publication_apply` | Apply exact native document, preview_sha256 and key; requires instance administration. | +| `publication_unpublish` | Disable publication using expected_revision and key; requires instance administration. | +| `review_import_preview` | Project management or instance administration; preview a complete native [review import](review-import.md#selected-sources-and-destination). | +| `review_import_apply` | Project management or instance administration; apply exact native [review import](review-import.md#selected-sources-and-destination), preview_sha256 and key. | +| `review_transfer_preview` | Project management or instance administration; preview a bounded native [review-history transfer](review-import.md#additive-mixed-producer-transfer). | +| `review_transfer_apply` | Project management or instance administration; apply exact native [review-history transfer](review-import.md#additive-mixed-producer-transfer), preview_sha256 and key. | | `presentation_read` | Explicit bound-project appearance snapshot and project-metadata watermark; no provider work or mutation. | | `doctor` | No fields; verified instance/project/worker identity. | -| `workers_list` | Optional limit/cursor; one compact worker page. | +| `workers_list` | Optional limit/cursor/include_retired; one compact active or explicitly historical worker page. | | `worker_pause_read` | No fields; bound worker’s explicit pause, reason and independent revision. | | `worker_pause_history` | Optional limit/cursor; one explicit newest-first pause-history page. | | `jobs_list` | Optional worker_id/status/limit/cursor; one compact job page. | @@ -67,7 +87,7 @@ Startup validates configuration without opening the credential or contacting the | `note_list` | Optional worker_id/all_workers/direct_only/job_id/phase/kind/status/limit/cursor; compact notes for the bound worker and its currently assigned jobs by default. | | `note_history` | Required note_id and optional limit/cursor; one compact revision page. | | `note_revision_read` | Required note_id/revision; one full immutable note revision. | -| `inbox_list` | Optional unread/unacknowledged/limit/cursor; bound worker's compact preview page. | +| `inbox_list` | Optional unread/unacknowledged/limit/cursor/worker_id; selected recipient compact preview page without changing acting identity. | | `inbox_thread` | Required conversation_id and optional limit/cursor; explicit full-body conversation page. | | `inbox_snapshot` | Optional unread/unacknowledged/limit/cursor; one inbox page plus its atomic incoming-event watermark. | | `inbox_events` | Required event cursor; optional limit and wait_ms 0–4000; one bounded incoming-event page. | @@ -98,7 +118,7 @@ Startup validates configuration without opening the credential or contacting the | `review_rounds_read` | Required pull_number/channel; compact native per-PR/channel grant, limits, cumulative consumed and clean counts, taper and closure. No provider work. | | `review_rounds_configure` | Required idempotency_key/pull_number/channel/expected_revision/action; grant requires minimum/maximum, taper requires taper, and close omits allocation fields. Project-write permission; original-key replay does not buy another round. See [round controls](review-round-controls.md). | | `review_queue` | Optional limit/cursor; stored queue, default five PRs. | -| `review_queue_edit` | Administrator-only native `document` plus `idempotency_key`; selected metadata, explicit retirement/reactivation and relative ordering through [bounded queue edits](review-workspace.md#bounded-queue-edits). No provider work or automatic retry. | +| `review_queue_edit` | Project management or instance administration; native `document` plus `idempotency_key`; selected metadata, explicit retirement/reactivation and relative ordering through [bounded queue edits](review-workspace.md#selected-queue-edits). No provider work or automatic retry. | | `review_pull` | Required pull_number, optional snapshot; compact PR summary with latest attempts per channel. | | `review_attempts` | Required pull_number, optional snapshot/limit/cursor; default five newest-first attempts with original producer and explicit continuation. | | `review_runs` | Required pull_number, optional snapshot/limit/cursor; default five stored run summaries. | @@ -118,7 +138,7 @@ Startup validates configuration without opening the credential or contacting the | `note_update` | Required idempotency_key/note_id/expected_revision plus selected scope/kind/body/status/status_reason fields; compact changed/unchanged receipt. | | `inbox_send` | Required idempotency_key/recipient_worker_id/body; optional reply_to_message_id; compact message receipt. | | `inbox_seen` | Required idempotency_key/message_id; explicit recipient seen transition. | -| `inbox_ack` | Required idempotency_key/message_id; explicit recipient acknowledgment, also establishing seen. | +| `inbox_ack` | Required idempotency_key/message_id; optional worker_id selects a recipient. Acknowledgment also establishes seen; another recipient requires project management. | Review queue/run/attempt lists default to five entries; other limits use the API default when omitted and accept explicit values from 1 to 100. Reads never advance seen/ack state, change a job or write a checkpoint. Assigned jobs do not claim to contain primary-job or full resume context. Snapshot and event cursors have different scopes. Event reads retain no cursor and never automatically poll or resubscribe; an explicitly requested bounded wait can return an empty `timed_out` page. The finite snapshot/event operations are separate from the explicit quiet wait; none establishes idle-agent wakeup. Invalid, unknown, duplicate, exactly mis-cased, null or oversized tool fields fail before service work. Profile selectors cannot be supplied as tool arguments. @@ -163,3 +183,11 @@ Clean source `e65315f3141fcba180499110cb0a5ad6f4948d6c` passed the actual packag ## Explicit review selection tools `review_start` accepts one durable channel selection with the caller's key and optional target/configuration assertions. `review_selection_read` observes a retained selection ID and its original native child, with optional bounded waiting. A `review_busy` response identifies another pending selection but creates no receipt and does not satisfy the refused caller's target assertion. Reads and canceled waits never authorize replacement work. See the [selection contract](review-round-controls.md#one-explicit-channel-front-run) for exact lifetime, authority and recovery semantics. + +## Native project administration + +The bound service exposes `review_policy_read`, `review_policy_configure`, `review_execution_configure`, `worker_create`, `project_credential_grant`, `project_credential_update` and `project_credential_revoke`. Mutation schemas require explicit keys and complete CAS inputs. Policy replacement includes `paused_channels`; execution configuration keeps an existing operator-bound capability and a nonempty queue. Grant takes a digest, never a raw secret. Management permissions and receipt replay follow the [local API](local-api.md#project-management-and-guarded-retirement). + +`worker_retirement_read` reports bounded blockers; `worker_retire` rechecks them atomically with ordinary write permission. `workers_list` defaults to active identities and accepts explicit `include_retired`. `inbox_list` and `inbox_ack` accept a selected `worker_id`; only acknowledgement for another recipient requires management. The authenticated acting worker remains unchanged. The existing inbox snapshot and seen operations do not accept another worker selector. + +Native presentation replacement/history/revision, public publication configuration/preview/apply/unpublish, and review import/transfer preview/apply tools delegate strict native documents to the existing validators. Public publication configuration, preview, apply and unpublish require instance administration; project management does not authorize them. Publication apply retains the explicit preview hash and revision. Existing round-adoption and adoption-obligation tools remain registered once. Read and preview tools perform no provider action; write/destructive annotations distinguish guarded mutations. New operation-control, settlement, history-collection and publication-prepare adapters are not part of this prerequisite. diff --git a/docs/review-execution.md b/docs/review-execution.md index 89b5f2cd4..59ffe0bb5 100644 --- a/docs/review-execution.md +++ b/docs/review-execution.md @@ -301,3 +301,7 @@ Focused proof covers parser-to-native source identity, strict HTTP/client varian ## Explicit selection entry point A [durable channel selection](review-round-controls.md#one-explicit-channel-front-run) may link one ordinary request through the same transactional admission helper used by exact-target requests. The selector adds no provider privilege, round allowance or completion credit. Native preparation and final provider guards remain authoritative after selection. + +## Project management authority + +Explicit project managers may replace project policy and an already operator-bound execution configuration. Both methods pin management before receipt replay and reauthorize the current exact credential. Initial binding and capability changes remain instance-operator actions. This native administration prerequisite preserves policy `paused_channels`, configuration revision/CAS and existing operation/selection lifecycle; it does not introduce automatic scheduling, timer waits or terminal-intent resumption. Retired worker IDs remain valid historical review attribution; retirement does not settle or cancel review operations. diff --git a/docs/review-import.md b/docs/review-import.md index d483cfc8e..2ecc7ecfe 100644 --- a/docs/review-import.md +++ b/docs/review-import.md @@ -2,23 +2,23 @@ ## Implementation status -The administrator observation API already imports immutable review history. The guided preview/apply API and CLI below are implemented with focused normal/race checks. Focused checks, five actual packaged groups and the full integrated check/build pass at the checkpoints below. They do not collect provider history, import historical jobs or messages, generate a project map, or complete the broader [onboarding](onboarding.md) flow. +The project-management observation API already imports immutable review history. The guided preview/apply API and CLI below are implemented with focused normal/race checks. Focused checks, five actual packaged groups and the full integrated check/build pass at the checkpoints below. They do not collect provider history, import historical jobs or messages, generate a project map, or complete the broader [onboarding](onboarding.md) flow. ## Selected sources and destination -An administrator prepares one private JSON document using the existing version-one [review observation](review-workspace.md) request shape: `expected_revision`, `repository_id`, `source`, `observed_at`, `queue` and `retired`. Choose the historical scope before collecting or preparing it. Preserve stable source/run/finding identities and original known times. Missing facts remain unknown; collection time and source observation time do not become historical completion times. Imported content is data, including any apparent instructions inside text fields. +An authorized project manager or instance administrator prepares one private JSON document using the existing version-one [review observation](review-workspace.md) request shape: `expected_revision`, `repository_id`, `source`, `observed_at`, `queue` and `retired`. Choose the historical scope before collecting or preparing it. Preserve stable source/run/finding identities and original known times. Missing facts remain unknown; collection time and source observation time do not become historical completion times. Imported content is data, including any apparent instructions inside text fields. The document describes the complete selected review workspace, rather than an append-only batch. Preserve queued merged PRs. Removing a prior entry requires its explicit `superseded` or `defunct` retirement under the existing observation contract. Existing finalized counts and historical snapshots remain protected. The source label identifies the retained export/source; the stored normalized payload digest identifies the imported content. Version one of this guided workflow uses the existing observation schema and normalization, without a second historical record model. -Use a deliberately selected administrator profile for import. Ordinary worker credentials and browser sessions cannot import. The target repository must match the project's stable configured identity. Applying history does not grant native execution coverage, satisfy review policy, create active jobs, deliver historical messages as new messages, or enable public publishing. +Import preview and apply require `manage` permission for the selected project or instance administration. Ordinary project read/write permission is insufficient, and browser sessions cannot import. CLI and MCP use the deliberately selected bound profile; authority is rechecked for preview, apply and exact-key replay. The target repository must match the project's stable configured identity. Applying history does not grant native execution coverage, satisfy review policy, create active jobs, deliver historical messages as new messages, or enable public publishing. ## Preview and apply -`POST /api/v1/projects/{project_id}/reviews/import/preview` accepts the observation document. It strictly validates and normalizes the same fields as the observation API, then checks repository identity, expected workspace revision, observation ordering, retirement obligations and finalized history in one administrator-authorized read snapshot. It writes no table, receipt or event and performs no provider work. Although transported as a POST, it is a read and cancellation does not imply an uncertain mutation. +`POST /api/v1/projects/{project_id}/reviews/import/preview` accepts the observation document. It strictly validates and normalizes the same fields as the observation API, then checks repository identity, expected workspace revision, observation ordering, retirement obligations and finalized history in one authorized read snapshot. It writes no table, receipt or event and performs no provider work. Although transported as a POST, it is a read and cancellation does not imply an uncertain mutation. The compact response contains `version: 1`, project/repository/source/observation identity, `expected_revision`, `payload_sha256`, `preview_sha256`, counts of pulls/runs/attempts/findings/retirements, `imported_history: true` and `native_coverage: false`. It does not echo PR titles, finding text, credentials or the full export. It describes a locally validated destination snapshot, not newly verified provider facts. -The preview fingerprint uses a versioned domain and binds the exact normalized observation, durable instance, project, authenticated administrator principal and selected worker. Formatting changes and the observation API's existing null-to-empty collection normalization do not change its meaning. Array order, source text and timestamp spelling retain their existing meaning. Changed content or destination requires another preview. The fingerprint is a stateless content binding, not a reservation, capability or proof that a human approved anything. +The preview fingerprint uses a versioned domain and binds the exact normalized observation, durable instance, project, authenticated principal and selected worker. Formatting changes and the observation API's existing null-to-empty collection normalization do not change its meaning. Array order, source text and timestamp spelling retain their existing meaning. Changed content or destination requires another preview. The fingerprint is a stateless content binding, not a reservation, capability or proof that a human approved anything. `POST /api/v1/projects/{project_id}/reviews/import/apply` accepts `{"preview_sha256":"64 lowercase hex characters","observation":{...}}` and an explicit `Idempotency-Key`. It verifies the binding and uses the same `reviews.observe` / `workspace` mutation, normalized request identity, admission guards and compact `observed` receipt as the original observation endpoint. Exact key/request replay returns that original receipt before rechecking a newer workspace revision. A changed source under the same key conflicts. A fresh key rechecks current authorization and every observation guard inside the write transaction; a preview never bypasses those checks. @@ -36,19 +36,19 @@ fc reviews queue Both commands use the selected private profile. The CLI checks its arguments and reads a bounded regular JSON file before accessing credentials or making requests. It also verifies that this document's compact wire encoding fits the future apply wrapper, so the same file remains usable for apply. Invalid syntax, encoding, duplicate keys, special files and oversized inputs produce safe diagnostics without file contents. The service owns complete observation and destination validation. No temporary file, preview record, generated key, automatic apply, provider collection or polling is hidden behind these commands. Calls keep the ordinary five-second client budget. Successful apply returns the compact existing receipt; failed output reports an unknown mutation outcome and exact-retry guidance. Preview output failure makes no mutation claim. -This administrator setup boundary is available through HTTP and CLI. It adds no ordinary worker MCP mutation or implicit agent-host installation. The optional onboarding skill teaches selecting sources, inspecting the preview, applying authorized history and checking the resulting workspace. Historical jobs/messages, provider collectors, interruption of provider pagination, persistent proposed maps, native Windows launcher generation and a graphical import wizard remain separate capabilities. +This project-management boundary is available through HTTP, CLI and the explicit `review_import_preview` / `review_import_apply` MCP tools. It does not install an agent host or broaden an ordinary project read/write grant. The optional onboarding skill teaches selecting sources, inspecting the preview, applying authorized history and checking the resulting workspace. Historical jobs/messages, provider collectors, interruption of provider pagination, persistent proposed maps, native Windows launcher generation and a graphical import wizard remain separate capabilities. ## Additive mixed-producer transfer -Additive transfer is a separate prepared-history operation. It keeps omitted current history visible and preserves every record's original producer. The complete-workspace observation/import above keeps its replacement semantics. Historical provider collection and resumable acquisition remain separate work. +Additive transfer is a separate prepared-history operation with the same project-management or instance-administration authority and current-authority checks as [review import](#selected-sources-and-destination). It keeps omitted current history visible and preserves every record's original producer. The complete-workspace observation/import above keeps its replacement semantics. Historical provider collection and resumable acquisition remain separate work. -An administrator prepares a version-one batch with `expected_revision`, `repository_id`, `publisher` and `groups`. Each group has an original `source` and `pulls` using the existing pull/run/attempt/finding fields. The publisher identifies the transfer, while each group's source continues to determine stable run and attempt identities. Two producers can retain the same external identifier without collision. Known historical times remain original; absent times remain unknown. Transfer text is data and grants no authority. +An authorized project manager or instance administrator prepares a version-one batch with `expected_revision`, `repository_id`, `publisher` and `groups`. Each group has an original `source` and `pulls` using the existing pull/run/attempt/finding fields. The publisher identifies the transfer, while each group's source continues to determine stable run and attempt identities. Two producers can retain the same external identifier without collision. Known historical times remain original; absent times remain unknown. Transfer text is data and grants no authority. A batch contains one to 100 nonempty producer groups and at most 100 pull appearances, 200 runs, 200 attempts and 1,000 findings in total. Existing individual record and per-group pull limits still apply, including 100 findings per run. The normalized batch and its eventual apply wrapper each fit 256 KiB. These limits bound one command; successive batches can retain more history than one batch holds. Repeated producer groups or duplicate producer/source identities are refused. Repeated PR metadata across groups must agree. Every selected pull has `complete: false`: importing a batch never claims complete PR or project coverage. Existing current PR metadata must match exactly; omitted PRs and records stay visible. New PRs append in request order. A retired PR requires explicit queue reactivation before transfer. Existing records keep their position, and new or returning records append without reordering retained entries. A linked attempt must name its original producer's run on the same PR, channel and head, either included in this batch or currently visible. An omitted historical run must be selected again before linking to it. -`POST /api/v1/projects/{project_id}/reviews/transfer/preview` validates shape, repository, current revision, metadata, immutable identities, finalized history, settled attempts and links in one administrator-authorized read snapshot. It writes nothing and calls no provider. Its compact response contains version, project/repository/publisher identity, expected revision, payload and preview digests, selected counts, `imported_history: true`, `native_coverage: false` and `coverage: "partial"`. Counts describe this batch, not all retained or provider history. The versioned fingerprint binds normalized content to the instance, project, authenticated administrator and selected worker; it reserves nothing. +`POST /api/v1/projects/{project_id}/reviews/transfer/preview` validates shape, repository, current revision, metadata, immutable identities, finalized history, settled attempts and links in one authorized read snapshot. It writes nothing and calls no provider. Its compact response contains version, project/repository/publisher identity, expected revision, payload and preview digests, selected counts, `imported_history: true`, `native_coverage: false` and `coverage: "partial"`. Counts describe this batch, not all retained or provider history. The versioned fingerprint binds normalized content to the instance, project, authenticated principal and selected worker; it reserves nothing. `POST /api/v1/projects/{project_id}/reviews/transfer/apply` accepts `{"preview_sha256":"64 lowercase hex characters","batch":{...}}` and an explicit `Idempotency-Key`. Fresh apply rechecks admission inside the original two-second write transaction. Snapshot provenance/digest, immutable versions, memberships, current references, compact summaries, event, optional public projection and compact `transferred` receipt commit together. An error rolls them back together. Exact same-key/batch replay rechecks current authority and returns the original receipt even after later workspace changes or restart. A changed batch or worker under that key conflicts. A preview mismatch uses `import_preview_mismatch`; changing the revision or content requires another preview and a deliberately selected new key. @@ -61,7 +61,7 @@ fc reviews transfer-preview --file /private/import/batch.json fc reviews transfer-apply --file /private/import/batch.json --preview SHA256 --key retained-batch-key ``` -They validate a bounded owner-private regular file before credentials or network access, use the ordinary five-second client budget and return useful local results directly. Preserve the exact file, profile, preview hash and key for uncertain apply recovery. There is no automatic key generation, application, provider collection, polling or worker MCP mutation. Focused validation covers service/client/CLI admission, replay, native-authority separation and retained backup behavior; implementation validation and installed qualification remain separate. +They validate a bounded owner-private regular file before credentials or network access, use the ordinary five-second client budget and return useful local results directly. Preserve the exact file, profile, preview hash and key for uncertain apply recovery. MCP `review_transfer_preview` and `review_transfer_apply` expose the same explicitly authorized operations. There is no automatic key generation, application, provider collection or polling. Focused validation covers service/client/CLI admission, replay, native-authority separation and retained backup behavior; implementation validation and installed qualification remain separate. ## Required proof diff --git a/docs/review-round-controls.md b/docs/review-round-controls.md index 0c492ce6a..f58246dfb 100644 --- a/docs/review-round-controls.md +++ b/docs/review-round-controls.md @@ -26,7 +26,7 @@ Candidate, base, effective-parent or history movement after start preserves earn ## Native control semantics -A per-PR/channel grant is an explicit project write operation, separate from administrator-owned project-wide required channels. Requested additional maximum is between one and 1,000; additional minimum is between zero and that maximum. The service stores checked cumulative stopping thresholds while preserving consumed counts, the accounting epoch, imported provenance and original operation attribution. Cumulative counters stay within 9,007,199,254,740,991. Historical controls retain their original representation and proof; an explicit edit moves the current rule to cumulative semantics. Existing unconfigured allocations remain unconfigured when already enrolled or re-added with retained native operations; eligible missing controls receive the selected [project defaults](#project-defaults) under the [enrollment rules](#operational-controls). Earned completion follows the [PR/channel rule](reviews.md#retained-native-channel-completion) in either case. +A per-PR/channel grant is an explicit project write operation, separate from project-management configuration of project-wide required channels. Requested additional maximum is between one and 1,000; additional minimum is between zero and that maximum. The service stores checked cumulative stopping thresholds while preserving consumed counts, the accounting epoch, imported provenance and original operation attribution. Cumulative counters stay within 9,007,199,254,740,991. Historical controls retain their original representation and proof; an explicit edit moves the current rule to cumulative semantics. Existing unconfigured allocations remain unconfigured when already enrolled or re-added with retained native operations; eligible missing controls receive the selected [project defaults](#project-defaults) under the [enrollment rules](#operational-controls). Earned completion follows the [PR/channel rule](reviews.md#retained-native-channel-completion) in either case. One eligible completion has a completed native operation/attempt, validated attributable complete capture and finalized source counts. An operation counts once, independently of whether its accepted findings have been fixed. Original finalized accepted counts determine its historical streak contribution; later decision/fix corrections remain separate obligations and do not rewrite consumed rounds. Failed, rate-limited and incomplete attempts consume no completed round. Queued, preparing, posting, active and uncertain work occupies capacity. An attributable complete terminal result awaiting finalization also occupies its original capacity, without receiving completion credit early. @@ -44,7 +44,7 @@ Per-PR changes use their own revision and actor attribution rather than changing If a queued request’s target no longer matches its original comparison, preparation holds that request rather than rebinding it. Follow the [review-execution](review-execution.md) contract with a qualified current comparison and fresh authorized request/key; preserve retained rounds and known cooldowns instead of resetting grants. The recovery does not itself change configured PR queue order. -Control reads are local, compact and provider-free. Project write mutations use the ordinary authorization, expected revision, idempotency and atomic event/receipt rules. Their compact change events identify the affected PR/channel resource and its revision; the durable event cursor remains the delivery deduplication identity. Storing a grant does not authorize provider calls. Carried adoption uses the separate administrator controls below; explicit channel-front selection uses the independently durable contract below. +Control reads are local, compact and provider-free. Project write mutations use the ordinary authorization, expected revision, idempotency and atomic event/receipt rules. Their compact change events identify the affected PR/channel resource and its revision; the durable event cursor remains the delivery deduplication identity. Storing a grant does not authorize provider calls. Carried adoption uses the separate project-management controls below; explicit channel-front selection uses the independently durable contract below. ## Refusals and recovery @@ -88,7 +88,7 @@ Focused tests exercise native grant, close, taper, replay, permission and admiss ## Carried rule adoption -An administrator can preview and apply one prepared effective PR/channel rule before execution enrollment. Adoption requires revision zero, no configured destination control and no unresolved native operation for that channel. Enrollment preserves the adopted rule. Preview binds the normalized input to the instance, project, administrator and worker; apply rechecks repository identity, authority and guards transactionally. Exact-key replay returns its original receipt without overwriting subsequent changes. +A caller with `manage` permission for the selected project or instance administration, plus a valid project worker, can preview and apply one prepared effective PR/channel rule before execution enrollment. Ordinary project read/write permission is insufficient. Adoption requires revision zero, no configured destination control and no unresolved native operation for that channel. Enrollment preserves the adopted rule. Preview binds the normalized input to the instance, project, authenticated principal and worker; apply rechecks repository identity, authority and guards transactionally. Exact-key replay returns its original receipt without overwriting subsequent changes. The prepared record retains remaining minimum and maximum, dry streak, taper threshold, reached taper and closure with source identity/key and digest. Native used starts at zero: imported configuration is not a native attempt, captured result or completed round. Genuine native completions advance the carried policy. Explicit additional grants stay finite and clear minimum-only state while retaining the carried origin and cumulative history. diff --git a/docs/review-workspace.md b/docs/review-workspace.md index 928ecb2d9..f2c86d5fb 100644 --- a/docs/review-workspace.md +++ b/docs/review-workspace.md @@ -2,7 +2,7 @@ ## Implemented boundary -The service stores project-scoped review observations and serves queue, PR history, run, finding, decision and fix-proof views from its own indexed database. Importing an observation is an explicit administrator action. Ordinary reads and browser refresh make no provider calls and do not construct another controller or renderer. Jobs and messaging do not depend on the reviews domain. +The service stores project-scoped review observations and serves queue, PR history, run, finding, decision and fix-proof views from its own indexed database. Importing an observation is an explicit project-management action. Ordinary reads and browser refresh make no provider calls and do not construct another controller or renderer. Jobs and messaging do not depend on the reviews domain. This slice provides the read model for the [review engine](reviews.md). Optional native execution and revision-bound policy admission are described in the [execution boundary](review-execution.md); [automatic provider observation](github-observation.md) separately updates existing enrolled PRs and retained external Hosted history. Fresh-source aggregate policy and merge-readiness assessment remain separate contracts. Explicit [captured-comparison policy assessment](review-controls.md#captured-comparison-assessment) is a separate provider-free read. Historical counts, a completed attempt, CI success and a matching head are separate facts. This API never returns a merge-ready verdict or authorizes a merge. Projects without observations return an explicitly unconfigured workspace. @@ -12,12 +12,12 @@ All paths below are relative to `/api/v1/projects/{project_id}`. Existing instan | Method and path | Result | | --- | --- | -| `POST /reviews/observations` | Administrator-only, revision-guarded observation append with a required idempotency key. | -| `POST /reviews/import/preview` | Administrator-only, provider-free prepared observation preview; no receipt or write. | -| `POST /reviews/import/apply` | Administrator-only prepared observation apply bound to its preview, with the existing observation receipt semantics. | -| `POST /reviews/transfer/preview` | Read-only administrator preview of bounded additive original-producer history. | -| `POST /reviews/transfer/apply` | Exact preview-bound administrator additive history apply. | -| `POST /reviews/queue/edits` | Selected metadata/order edits, retirement and reactivation (administrator). | +| `POST /reviews/observations` | Project management or instance administration; revision-guarded observation append with a required idempotency key. | +| `POST /reviews/import/preview` | Project management or instance administration; provider-free prepared observation preview; no receipt or write. | +| `POST /reviews/import/apply` | Project management or instance administration; prepared observation apply bound to its preview, with the existing observation receipt semantics. | +| `POST /reviews/transfer/preview` | Project management or instance administration; read-only preview of bounded additive original-producer history. | +| `POST /reviews/transfer/apply` | Project management or instance administration; exact preview-bound additive history apply. | +| `POST /reviews/queue/edits` | Selected metadata/order edits, retirement and reactivation (project management or instance administration). | | `GET /reviews/queue` | Compact ordered PR summaries, including merged and closed history. | | `GET /reviews/pulls/{number}` | One compact PR summary; no lifetime attempt array. | | `GET /reviews/pulls/{number}/attempts` | Newest-first original-producer attempt archive with cursor pagination. | @@ -28,9 +28,9 @@ Queue, run and attempt lists default to 20 items and accept `limit` up to 100 an Cursors bind the principal, project, route, order and retained snapshot. New imports cannot change a continuation page from an older snapshot. Detail links retain that snapshot for consistent drill-down. Access is checked again on every request, including historical reads and exact mutation retries. Unknown, duplicate and malformed query fields are rejected. PR numbers use canonical positive decimal values through 2147483647. -## Administrator observations +## Project-managed observations -The [prepared import contract](review-import.md) owns guided preview/apply and profile-bound administrator CLI commands. These routes share the observation transaction below; preview does not reserve a workspace revision. +Observation append requires `manage` permission for the selected project or instance administration; ordinary project read/write permission is insufficient. The [prepared import contract](review-import.md#selected-sources-and-destination) owns guided preview/apply and profile-bound CLI/MCP commands. These routes share the observation transaction below; preview does not reserve a workspace revision. The strict JSON body requires `expected_revision` (zero for the first observation), the configured stable GitHub `repository_id`, a bounded `source`, an RFC3339 `observed_at`, ordered `queue` entries and explicit `retired` entries. Omitted arrays normalize to empty arrays. The body and its normalized form are bounded to 256 KiB. A changed request under an existing idempotency key conflicts; an exact retained replay returns the original receipt before re-evaluating the revision. Replay still requires current authorization. @@ -64,7 +64,7 @@ Merged PRs remain in the queue as completed history. Removing a previously visib The browser exposes Reviews, PR history and run-finding pages, with source timestamps, incomplete or missing data, head mismatches, historical counts and source coverage limitations visible. It escapes imported text and generates external PR/commit links only from the verified project repository. It does not render imported HTML or accept arbitrary link destinations. “Refresh visible data” rereads the stored snapshot; it neither refreshes GitHub nor starts a review. These pages have no timer-based polling or new live transport. The [browser guide](browser-guide.md) owns connection privacy and packaging. -An initial installation may populate this boundary through a small explicit import. Profile-bound CLI commands `reviews queue`, `reviews pull`, `reviews runs`, `reviews attempts` and `reviews run`, plus the five matching [MCP read tools](mcp.md), inspect these stored projections without provider work. Queue/run/attempt tools default to five entries, while explicit run detail loads full findings. Snapshot selectors retain historical consistency. Startup conversion is limited to the supported retained-review schema. Optional [native executors](review-execution.md) publish retained native evidence through their own trusted path. Review observation writes are not exposed as worker tools. +An initial installation may populate this boundary through a small explicit import. Profile-bound CLI commands `reviews queue`, `reviews pull`, `reviews runs`, `reviews attempts` and `reviews run`, plus the five matching [MCP read tools](mcp.md), inspect these stored projections without provider work. Queue/run/attempt tools default to five entries, while explicit run detail loads full findings. Snapshot selectors retain historical consistency. Startup conversion is limited to the supported retained-review schema. Optional [native executors](review-execution.md) publish retained native evidence through their own trusted path. Direct observation append is not exposed as a worker tool; explicit prepared import and transfer use the project-management CLI/MCP boundary. ## Validation status @@ -80,11 +80,11 @@ These checks use synthetic observations on Linux/WSL Chromium. They do not estab ### Selected queue edits -Administrator queue edits maintain selected stored metadata, relative ordering and explicit retirement/reactivation without resubmitting a complete retained workspace. They are an administrator maintenance boundary, not another ordinary worker enrollment step. +Project-management queue edits maintain selected stored metadata, relative ordering and explicit retirement/reactivation without resubmitting a complete retained workspace. They are a project-management maintenance boundary, not another ordinary worker enrollment step. Complete observations replace a small workspace and retain their per-request bounds. A large workspace uses additive transfer for selected history and `POST /api/v1/projects/{project_id}/reviews/queue/edits` for selected metadata, retirement and reactivation. Neither operation requires a complete project export or a lifetime PR ceiling. -Queue edits require administrator access, an explicit idempotency key, the current `expected_revision`, the configured `repository_id` and a bounded `source` label for administrator provenance. The strict JSON document is limited to 256 KiB. Its `queue` and `retired` arrays select at most one hundred entries in total, with unique, disjoint PR numbers. At least one entry is required unless `order` is supplied. Omitted metadata and retirement arrays become empty; explicit null fields, unknown fields and duplicate keys are refused. +Queue edits require `manage` permission for the selected project or instance administration, an explicit idempotency key, the current `expected_revision`, the configured `repository_id` and a bounded `source` label for management provenance. The strict JSON document is limited to 256 KiB. Its `queue` and `retired` arrays select at most one hundred entries in total, with unique, disjoint PR numbers. At least one entry is required unless `order` is supplied. Omitted metadata and retirement arrays become empty; explicit null fields, unknown fields and duplicate keys are refused. Each `queue` entry contains `number`, `title`, `state`, `head_sha`, `base_ref`, `base_sha`, `ci_state` and `mergeability`, with optional `diff`, `is_draft` and `merged_at` under the [PR display metadata contract](#optional-pr-display-metadata). CI permits `unknown`, `pending`, `success`, `failure` and `not_required`. Omitted optional SHA/base strings become empty. Runs, attempts, findings, counts and completeness cannot be supplied. Without an explicit order, an existing PR keeps its position and retained producer histories; changing its head clears completeness. A new or previously absent PR appends with partial coverage. Explicitly selecting a retired PR reactivates it without inventing review evidence. @@ -94,13 +94,13 @@ Each `retired` entry names a currently visible PR and its `superseded` or `defun Omitted PRs and records remain unchanged. Revision admission, the new snapshot, history references, compact summaries, receipt, event and public projection refresh commit together. A queue edit inherits the prior observation time and does no provider work; it cannot claim freshly collected source facts. Exact original-key replay returns its original receipt after later changes or restart, subject to current authorization. A changed request under the same key conflicts. Successful HTTP 201 returns only the snapshot `id`, new `revision` and `outcome: queue_edited`. -The bound administrator CLI is: +The bound project-management CLI is: ```sh fc reviews queue-edit --file /private/queue-edit.json --key retained-action-key ``` -It validates a bounded regular file before credentials or network access, retains the ordinary five-second budget and never generates a key or retries automatically. A lost or invalid mutation response requires recovery with the original request, key and binding. MCP `review_queue_edit` sends the same native document and explicit `idempotency_key`; service administrator admission still applies. It does not request reviews or change scheduling configuration. +It validates a bounded regular file before credentials or network access, retains the ordinary five-second budget and never generates a key or retries automatically. A lost or invalid mutation response requires recovery with the original request, key and binding. MCP `review_queue_edit` sends the same native document and explicit `idempotency_key`; the same project-management or instance-administration admission still applies, including on original-key replay. It does not request reviews or change scheduling configuration. Focused regressions grow the workspace through actual native publication beyond 200 PRs, apply selected edits without dropping omitted merged history, preserve original cursor/detail and evidence bytes, retain retirement through later native publication, and prove exact original-key replay after intervening edits and database reopen. Optional-metadata, relative-order, rollback and client tests cover the same selected-edit boundary. CLI and SDK MCP tests exercise strict/authenticated native calls and lost-receipt recovery. These source checks do not establish live-provider behavior or installed rollout. diff --git a/docs/worker-retirement.md b/docs/worker-retirement.md new file mode 100644 index 000000000..a3cd9603d --- /dev/null +++ b/docs/worker-retirement.md @@ -0,0 +1,21 @@ +# Worker retirement + +Retirement removes a worker from ordinary active lists and new coordination targets while preserving its identity and history. Completed jobs, conversations, focus and pause history remain readable. Fresh focus and pause mutations are rejected after retirement; exact earlier receipts remain replayable without another effect. Credentials remain separate project access controls; retirement never revokes them or cancels review operations. + +## Clear unfinished work first + +Preview reports exact totals and up to twenty IDs for unfinished assigned jobs, pending notes attached directly to the worker or to its assigned jobs, and unacknowledged incoming messages. Reassign or complete jobs, move/consume/dismiss notes and explicitly acknowledge messages first. Retirement performs none of that cleanup automatically. Refresh the preview after each cleanup batch and repeat until `can_retire` is true. + +The mutation rechecks blockers in the same transaction as retirement. Concurrent job assignment, reopened work, pending-note targeting and message delivery either prevent retirement or are rejected after it. New message sends also require an active sender. Historical references and exact prior receipt replay remain valid. + +## Native operations + +GET `/api/v1/projects/{project_id}/workers/{worker_id}/retirement` reads preview. POST to the sibling `/retire` route takes `{}` and an explicit key with ordinary project-write permission. A successful receipt contains the worker ID, revision two and `retired`; another deliberate retirement returns `unchanged`. `worker_retirement_blocked` includes current blocker handles; active-target admission returns `worker_retired`. Keep the exact key after an unknown outcome. + +CLI exposes `workers retirement WORKER_ID`, `workers retire WORKER_ID --key KEY`, and `workers list --include-retired`. MCP exposes `worker_retirement_read`, `worker_retire` and the explicit `workers_list.include_retired` option. Cursors are bound to active versus archive views. Direct worker reads retain historical identities. + +Any project reader may inspect a selected worker's inbox. Acknowledging a message for another recipient requires project management, using `inbox ack MESSAGE_ID --worker WORKER_ID --key KEY` or MCP `inbox_ack` with `worker_id`. The selected recipient is in the request body; the authenticated principal and actual acting worker are unchanged. Current management is checked before receipt replay and inside the mutation. Ordinary acknowledgement with an empty JSON object (`{}`) keeps its original wire and receipt identity. Added durable acting-worker audit detail is not exposed through the legacy incoming-message feed. + +## Persistence and scope + +The additive `worker_retirements:1` domain retains worker-table identities and foreign keys. Backups and inactive restore preserve retirement facts and reject malformed physical schemas or records. Existing bundles need no inspection-time migration. Native tests cover blockers, races, historical reads, peer acknowledgement, exact-key recovery and backup compatibility. Browser retirement controls, Delivery lanes and automatic scheduling remain later capabilities rather than implied by this native prerequisite. diff --git a/internal/backup/administration_cancel_test.go b/internal/backup/administration_cancel_test.go new file mode 100644 index 000000000..d07f0dac0 --- /dev/null +++ b/internal/backup/administration_cancel_test.go @@ -0,0 +1,221 @@ +package backup + +import ( + "context" + "database/sql" + "errors" + "os" + "path/filepath" + "reflect" + "runtime" + "strings" + "sync" + "sync/atomic" + "testing" + + "github.com/benhook1013/FireController/internal/core" +) + +// Intercept only the selected semantic query, leaving schema reads untouched. +type administrationCancellationReader struct { + sqlReader + cancel context.CancelFunc + phase string + once sync.Once + fired bool +} + +func (r *administrationCancellationReader) interrupt(query string) { + match := r.phase == "project_management" && strings.HasPrefix(query, "SELECT COUNT(*) FROM grants WHERE typeof(can_manage)") || r.phase == "worker_retirements" && strings.Contains(query, "FROM worker_retirements r LEFT JOIN workers") + match = match || r.phase == "grants_schema" && strings.Contains(query, "FROM sqlite_schema WHERE type='table' AND name='grants'") + if match { + r.once.Do(func() { r.fired = true; r.cancel() }) + } +} +func (r *administrationCancellationReader) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row { + r.interrupt(query) + return r.sqlReader.QueryRowContext(ctx, query, args...) +} +func (r *administrationCancellationReader) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) { + if r.phase == "retirement_schema" && strings.Contains(query, "FROM sqlite_schema") { + for _, arg := range args { + if arg == "worker_retirements" { + r.once.Do(func() { r.fired = true; r.cancel() }) + } + } + } + r.interrupt(query) + return r.sqlReader.QueryContext(ctx, query, args...) +} + +func TestAdministrationQueryCancellationIsUnavailableAndRetryable(t *testing.T) { + for _, phase := range []string{"project_management", "worker_retirements"} { + t.Run(phase, func(t *testing.T) { + store, err := core.Open(t.Context(), filepath.Join(t.TempDir(), "source")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + versions, err := validateSchema(t.Context(), store.DB(), false) + if err != nil { + t.Fatal(err) + } + before := backupRows(t, store.DB()) + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + reader := &administrationCancellationReader{sqlReader: store.DB(), cancel: cancel, phase: phase} + err = validateAdministrationContent(ctx, reader, versions) + if !reader.fired || !errors.Is(ctx.Err(), context.Canceled) { + t.Fatal("selected SQL query was not interrupted", err) + } + backupCode(t, err, "backup_unavailable") + if !reflect.DeepEqual(before, backupRows(t, store.DB())) { + t.Fatal("validation changed source") + } + if err := validateAdministrationContent(t.Context(), store.DB(), versions); err != nil { + t.Fatal("retry failed", err) + } + }) + } +} + +// Intercept database/sql's context check in the real semantic validator, +// rather than canceling before the operation starts. Stack selection avoids +// production hooks, sleeps, and dependence on query timing. +type administrationOperationCancellation struct { + context.Context + cancel context.CancelFunc + phase string + operation string + target string + once sync.Once + fired atomic.Bool + copied atomic.Bool +} + +func (c *administrationOperationCancellation) Done() <-chan struct{} { + if c.Context.Err() == nil { + var pcs [64]uintptr + n := runtime.Callers(2, pcs[:]) + frames := runtime.CallersFrames(pcs[:n]) + administration, retirement, sqlQuery, inspecting := false, false, false, false + for { + frame, more := frames.Next() + administration = administration || frame.Function == "github.com/benhook1013/FireController/internal/backup.validateAdministrationContent" + retirement = retirement || frame.Function == "github.com/benhook1013/FireController/internal/core.ValidateWorkerRetirementsSnapshot" + sqlQuery = sqlQuery || frame.Function == "database/sql.(*Tx).QueryContext" + inspecting = inspecting || frame.Function == "github.com/benhook1013/FireController/internal/backup.inspectManifest" + if !more { + break + } + } + selected := administration && sqlQuery && ((c.phase == "worker_retirements") == retirement) + if c.operation == "restore_post_copy" { + selected = selected && !inspecting + } + if selected { + c.once.Do(func() { + if info, err := os.Stat(filepath.Join(c.target, "firecontroller.sqlite")); err == nil && info.Size() > 0 { + c.copied.Store(true) + } + c.fired.Store(true) + c.cancel() + }) + } + } + return c.Context.Done() +} + +func TestAdministrationOperationCancellationIsUnavailableAndRetryable(t *testing.T) { + for _, operation := range []string{"inspect", "restore", "restore_post_copy", "create", "managed_create"} { + for _, phase := range []string{"project_management", "worker_retirements"} { + t.Run(operation+"/"+phase, func(t *testing.T) { + source := filepath.Join(t.TempDir(), "source") + store, err := core.Open(t.Context(), source) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = store.Close() }) + versions, err := validateSchema(t.Context(), store.DB(), false) + if err != nil || versions["project_management"] != 1 || versions["worker_retirements"] != 1 || versions["recovery_history"] != 0 { + t.Fatal("fixture must select the two administration validators without recovery history", versions, err) + } + bundle, err := Create(t.Context(), store, source, filepath.Join(t.TempDir(), "bundles")) + if err != nil { + t.Fatal(err) + } + beforeBundle := restoreTree(t, bundle.Path) + beforeSource := backupRows(t, store.DB()) + target := filepath.Join(t.TempDir(), "destination") + run := func(ctx context.Context) error { + switch operation { + case "inspect": + _, err := Inspect(ctx, bundle.Path) + return err + case "restore", "restore_post_copy": + _, err := Restore(ctx, bundle.Path, target) + return err + case "create": + _, err := Create(ctx, store, source, target) + return err + default: + _, err := createManaged(ctx, store, source, target) + return err + } + } + base, cancel := context.WithCancel(t.Context()) + defer cancel() + ctx := &administrationOperationCancellation{Context: base, cancel: cancel, phase: phase, operation: operation, target: target} + err = run(ctx) + if !ctx.fired.Load() || !errors.Is(base.Err(), context.Canceled) { + t.Fatal("operation context was not canceled", err) + } + backupCode(t, err, "backup_unavailable") + if ctx.copied.Load() != (operation == "restore_post_copy") { + t.Fatal("cancellation reached the wrong restore copy phase", ctx.copied.Load()) + } + if operation == "create" || operation == "managed_create" { + entries, err := os.ReadDir(target) + if err != nil && !errors.Is(err, os.ErrNotExist) || len(entries) != 0 { + t.Fatal("interrupted validation retained an unpublished bundle", entries, err) + } + } else if _, err := os.Lstat(target); !errors.Is(err, os.ErrNotExist) { + t.Fatal("interrupted verification created a restore destination", err) + } + if !reflect.DeepEqual(beforeBundle, restoreTree(t, bundle.Path)) || !reflect.DeepEqual(beforeSource, backupRows(t, store.DB())) { + t.Fatal("interrupted validation changed the source or bundle") + } + if err := run(t.Context()); err != nil { + t.Fatal("uncanceled retry failed", err) + } + }) + } + } +} + +func TestAdministrationSchemaCancellationIsUnavailableAndRetryable(t *testing.T) { + for _, phase := range []string{"grants_schema", "retirement_schema"} { + t.Run(phase, func(t *testing.T) { + store, err := core.Open(t.Context(), filepath.Join(t.TempDir(), "source")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + before := backupRows(t, store.DB()) + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + reader := &administrationCancellationReader{sqlReader: store.DB(), cancel: cancel, phase: phase} + _, err = validateSchema(ctx, reader, false) + if !reader.fired || !errors.Is(ctx.Err(), context.Canceled) { + t.Fatal("selected schema query not interrupted", err) + } + backupCode(t, err, "backup_unavailable") + if !reflect.DeepEqual(before, backupRows(t, store.DB())) { + t.Fatal("schema validation changed source") + } + if _, err := validateSchema(t.Context(), store.DB(), false); err != nil { + t.Fatal("retry failed", err) + } + }) + } +} diff --git a/internal/backup/inventory.go b/internal/backup/inventory.go index cca0737d4..1ca240b61 100644 --- a/internal/backup/inventory.go +++ b/internal/backup/inventory.go @@ -15,6 +15,7 @@ import ( "strings" "github.com/benhook1013/FireController/internal/adoptionholds" + "github.com/benhook1013/FireController/internal/core" "github.com/benhook1013/FireController/internal/jobs" "github.com/benhook1013/FireController/internal/presentation" "github.com/benhook1013/FireController/internal/projectmap" @@ -232,9 +233,10 @@ type tableVersion struct { // Fixed application schema bounds are intentionally independent of migration // execution. Inspection never opens a Store or installs/rewrites a schema. -var supportedDomains = map[string]int{"review_selection": 1, "review_adoption_obligations": 2, "review_round_adoption": 1, "review_rounds": 5, "review_comparison": 2, "review_route_policy": 1, "public_site": 1, "project_presentation": 1, "project_map": 1, "jobs": 6, "inbox": 1, "reviews": 11, "review_policy": 1, "review_execution": 10, "review_execution_indexes": 4, "review_evidence": 4, "review_adjudication": 2, "review_source_refresh": 3, "review_checkpoint_publication": 1, "managed_backups": 1, "managed_backup_publications": 1, "recovery_history": 1} +var supportedDomains = map[string]int{"project_management": 1, "worker_retirements": 1, "review_selection": 1, "review_adoption_obligations": 2, "review_round_adoption": 1, "review_rounds": 5, "review_comparison": 2, "review_route_policy": 1, "public_site": 1, "project_presentation": 1, "project_map": 1, "jobs": 6, "inbox": 1, "reviews": 11, "review_policy": 1, "review_execution": 10, "review_execution_indexes": 4, "review_evidence": 4, "review_adjudication": 2, "review_source_refresh": 3, "review_checkpoint_publication": 1, "managed_backups": 1, "managed_backup_publications": 1, "recovery_history": 1} var tables = map[string]tableVersion{ "review_operation_waits": {"review_execution", 9, "operation_id baseline_attempt_id retry_not_before paused"}, + "worker_retirements": {"worker_retirements", 1, "project_id worker_id retired_at actor_id"}, "review_selections": {"review_selection", 1, "id project_id actor_id worker_id channel configuration_revision policy_revision capability_fingerprint expected_pull_number state reason revision operation_id created_at updated_at"}, "review_hosted_discovery_state": {"reviews", 11, "project_id repository_id pull_number cutoff_at initialized_at"}, "review_pull_versions": {"reviews", 4, "project_id number version_revision title state head_sha base_ref base_sha ci_state mergeability complete run_count attempt_count recent_runs_json latest_attempts_json"}, @@ -606,6 +608,23 @@ func validateSchema(ctx context.Context, db sqlReader, allowInactive bool) (map[ return nil, err } } + if versions["project_management"] > 0 { + var statement string + if err := db.QueryRowContext(ctx, `SELECT CASE WHEN length(CAST(sql AS BLOB))<=16384 THEN sql ELSE NULL END FROM sqlite_schema WHERE type='table' AND name='grants'`).Scan(&statement); err != nil || historyDefinitionSQL(statement) != historyDefinitionSQL(`CREATE TABLE grants(credential_id TEXT NOT NULL REFERENCES credentials(id),project_id TEXT NOT NULL REFERENCES projects(id),can_read INTEGER NOT NULL CHECK(can_read IN(0,1)),can_write INTEGER NOT NULL CHECK(can_write IN(0,1)), can_manage INTEGER NOT NULL DEFAULT 0 CHECK(can_manage IN(0,1) AND (can_manage=0 OR (can_read=1 AND can_write=1))),PRIMARY KEY(credential_id,project_id))`) { + if contextErr := checkContext(ctx); contextErr != nil { + return nil, contextErr + } + return nil, invalid() + } + } + if versions["worker_retirements"] > 0 { + if err := validatePhysicalSchemaObjects(ctx, db, map[string]physicalSchemaObject{"worker_retirements": {"table", `CREATE TABLE worker_retirements(project_id TEXT NOT NULL REFERENCES projects(id),worker_id TEXT NOT NULL,retired_at TEXT NOT NULL,actor_id TEXT NOT NULL,PRIMARY KEY(project_id,worker_id),FOREIGN KEY(project_id,worker_id) REFERENCES workers(project_id,id))`}}, []string{"worker_retirements"}); err != nil { + if contextErr := checkContext(ctx); contextErr != nil { + return nil, contextErr + } + return nil, err + } + } if versions["review_execution_indexes"] < 4 { var count int if err := db.QueryRowContext(ctx, `SELECT count(*) FROM sqlite_schema WHERE name='review_operations_draft_probe'`).Scan(&count); err != nil || count != 0 { @@ -668,6 +687,9 @@ func validateSchema(ctx context.Context, db sqlReader, allowInactive bool) (map[ continue } columns := spec.columns + if name == "grants" && versions["project_management"] > 0 { + columns += " can_manage" + } if name == "review_current_totals" && versions["reviews"] >= 9 { columns += " hosted_run_count cli_run_count subagent_run_count manual_run_count" } @@ -735,6 +757,10 @@ func validateSchema(ctx context.Context, db sqlReader, allowInactive bool) (map[ columnRows.Close() return nil, invalid() } + if name == "grants" && col == "can_manage" && (kind != "INTEGER" || notnull != 1 || defaultValue != "0" || pk != 0) { + columnRows.Close() + return nil, invalid() + } if name == "receipts" && (kind != "TEXT" || notnull != 1 || defaultValue != nil || pk != receiptPK[col]) { columnRows.Close() return nil, invalid() @@ -898,6 +924,9 @@ func validateSnapshotContent(ctx context.Context, dataDir string, m Manifest, al return invalid() } } + if err := validateAdministrationContent(ctx, tx, versions); err != nil { + return err + } var identity, key string var sequence int64 if tx.QueryRowContext(ctx, `SELECT value FROM metadata WHERE key='instance_id'`).Scan(&identity) != nil || identity != m.SourceInstanceID || !instanceID.MatchString(identity) || tx.QueryRowContext(ctx, `SELECT value FROM metadata WHERE key='signing_key'`).Scan(&key) != nil || !digest.MatchString(key) || tx.QueryRowContext(ctx, `SELECT coalesce(max(sequence),0) FROM events`).Scan(&sequence) != nil || sequence != m.EventSequence { @@ -1282,6 +1311,7 @@ var canonicalForeignKeys = map[string][]foreignKey{ "job_checklist_history": {canonicalFK("jobs", "project_id,job_id", "project_id,id", "CASCADE")}, "restore_history": {}, "workers": {canonicalFK("projects", "project_id", "id", "NO ACTION")}, + "worker_retirements": {canonicalFK("projects", "project_id", "id", "NO ACTION"), canonicalFK("workers", "project_id,worker_id", "project_id,id", "NO ACTION")}, "grants": {canonicalFK("credentials", "credential_id", "id", "NO ACTION"), canonicalFK("projects", "project_id", "id", "NO ACTION")}, "events": {canonicalFK("projects", "project_id", "id", "NO ACTION")}, "jobs": {canonicalFK("projects", "project_id", "id", "CASCADE"), canonicalFK("workers", "project_id,worker_id", "project_id,id", "NO ACTION")}, @@ -1619,6 +1649,27 @@ func validateExternalHostedEvidenceIndexes(ctx context.Context, db sqlReader, ve return nil } +func validateAdministrationContent(ctx context.Context, db sqlReader, versions map[string]int) error { + if versions["project_management"] > 0 { + var bad int + if err := db.QueryRowContext(ctx, `SELECT COUNT(*) FROM grants WHERE typeof(can_manage)<>'integer' OR can_manage NOT IN (0,1) OR (can_manage=1 AND (can_read<>1 OR can_write<>1))`).Scan(&bad); err != nil || bad != 0 { + if checkContext(ctx) != nil { + return unavailable() + } + return invalid() + } + } + if versions["worker_retirements"] > 0 { + if err := core.ValidateWorkerRetirementsSnapshot(ctx, db); err != nil { + if checkContext(ctx) != nil { + return unavailable() + } + return invalid() + } + } + return nil +} + // Validate the exact copied private bytes, without opening a mutable runtime // store or requiring an extant SQL preflight row or repository workspace. func validateCLIExhaustionArtifact(ctx context.Context, root string, a Artifact) error { diff --git a/internal/backup/project_management_compatibility_test.go b/internal/backup/project_management_compatibility_test.go new file mode 100644 index 000000000..f2cf65a8c --- /dev/null +++ b/internal/backup/project_management_compatibility_test.go @@ -0,0 +1,76 @@ +package backup + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestProjectManagementRealParentBundleRemainsInactive(t *testing.T) { + root := os.Getenv("FC_ADMIN_PARENT_FIXTURE") + if root == "" { + t.Skip("requires genuine pinned-parent bundle") + } + provenance, err := os.ReadFile(filepath.Join(root, "parent-commit")) + if err != nil || strings.TrimSpace(string(provenance)) != "383ce8c0bc4505dd89cf5cdec7fb2da1d7e556c8" { + t.Fatal("fixture must come from pinned predecessor", err) + } + entries, err := os.ReadDir(root) + var matches []string + for _, entry := range entries { + if entry.IsDir() && strings.HasPrefix(entry.Name(), "backup_") { + matches = append(matches, filepath.Join(root, entry.Name())) + } + } + if err != nil || len(matches) != 1 { + t.Fatal("parent bundle missing", err) + } + bundle := matches[0] + if _, err := Inspect(t.Context(), bundle); err != nil { + t.Fatal(err) + } + dir := filepath.Join(t.TempDir(), "restored") + if _, err := Restore(t.Context(), bundle, dir); err != nil { + t.Fatal(err) + } + db, err := openSnapshot(t.Context(), filepath.Join(dir, "firecontroller.sqlite")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + var live, domains int + if err := db.QueryRow(`SELECT count(*) FROM credentials WHERE revoked=0`).Scan(&live); err != nil || live != 0 { + t.Fatal("old credentials revived", live, err) + } + if err := db.QueryRow(`SELECT count(*) FROM metadata WHERE key IN ('schema:project_management','schema:worker_retirements')`).Scan(&domains); err != nil || domains != 0 { + t.Fatal("inspection/restore migrated old bundle", domains, err) + } +} +func TestProjectManagementBackupRejectsResealedAuthorityCorruption(t *testing.T) { + for _, statement := range []string{ + `PRAGMA writable_schema=ON; UPDATE sqlite_schema SET sql=sql || replace(hex(zeroblob(8192)),'0',' ') WHERE name='grants'; PRAGMA writable_schema=OFF`, + `PRAGMA writable_schema=ON; UPDATE sqlite_schema SET sql=replace(sql,'CHECK(can_manage IN(0,1) AND (can_manage=0 OR (can_read=1 AND can_write=1)))','CHECK(1)') WHERE name='grants'; PRAGMA writable_schema=OFF`, + `UPDATE metadata SET value='2' WHERE key='schema:project_management'`, + `DELETE FROM metadata WHERE key='schema:project_management'`, + `PRAGMA writable_schema=ON; UPDATE sqlite_schema SET sql=replace(sql,'DEFAULT 0','DEFAULT 1') WHERE name='grants'; PRAGMA writable_schema=OFF`, + `PRAGMA writable_schema=ON; UPDATE sqlite_schema SET sql=replace(sql,'can_manage INTEGER NOT NULL','can_manage TEXT NOT NULL') WHERE name='grants'; PRAGMA writable_schema=OFF`, + `PRAGMA ignore_check_constraints=ON; UPDATE grants SET can_manage=0.5; PRAGMA ignore_check_constraints=OFF`, + `PRAGMA ignore_check_constraints=ON; UPDATE grants SET can_manage=1,can_write=0; PRAGMA ignore_check_constraints=OFF`, + `PRAGMA foreign_keys=OFF; UPDATE grants SET credential_id='missing'; PRAGMA foreign_keys=ON`, + } { + t.Run(statement, func(t *testing.T) { + f := newRestoreFixture(t) + bundle := restoreBundle(t, f) + mutateBundleSQL(t, bundle.Path, statement) + _, err := Inspect(t.Context(), bundle.Path) + backupCode(t, err, "backup_invalid") + dest := filepath.Join(t.TempDir(), "must-not-exist") + _, err = Restore(t.Context(), bundle.Path, dest) + backupCode(t, err, "backup_invalid") + if _, err := os.Stat(dest); !os.IsNotExist(err) { + t.Fatal("target written before validation", err) + } + }) + } +} diff --git a/internal/backup/project_management_test.go b/internal/backup/project_management_test.go new file mode 100644 index 000000000..bab43e8f3 --- /dev/null +++ b/internal/backup/project_management_test.go @@ -0,0 +1,70 @@ +package backup + +import ( + "path/filepath" + "testing" +) + +func TestProjectManagementBackupRetainsOnlyExplicitScopedManagement(t *testing.T) { + f := newRestoreFixture(t) + var credential string + if err := f.store.DB().QueryRow(`SELECT credential_id FROM grants WHERE project_id=? AND can_write=1 LIMIT 1`, f.project).Scan(&credential); err != nil { + t.Fatal(err) + } + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=1,can_read=1,can_write=1 WHERE credential_id=? AND project_id=?`, credential, f.project); err != nil { + t.Fatal(err) + } + bundle := restoreBundle(t, f) + if _, err := Inspect(t.Context(), bundle.Path); err != nil { + t.Fatal(err) + } + dest := filepath.Join(t.TempDir(), "inactive") + if _, err := Restore(t.Context(), bundle.Path, dest); err != nil { + t.Fatal(err) + } + db, err := openSnapshot(t.Context(), filepath.Join(dest, "firecontroller.sqlite")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + var version string + if err := db.QueryRow(`SELECT value FROM metadata WHERE key='schema:project_management'`).Scan(&version); err != nil || version != "1" { + t.Fatal("management format gate lost", version, err) + } + var total, selected, live int + if err := db.QueryRow(`SELECT COUNT(*) FROM grants WHERE can_manage=1`).Scan(&total); err != nil { + t.Fatal(err) + } + if err := db.QueryRow(`SELECT COUNT(*) FROM grants WHERE credential_id=? AND project_id=? AND can_manage=1 AND can_read=1 AND can_write=1`, credential, f.project).Scan(&selected); err != nil { + t.Fatal(err) + } + if err := db.QueryRow(`SELECT COUNT(*) FROM credentials WHERE revoked=0`).Scan(&live); err != nil { + t.Fatal(err) + } + if total != 1 || selected != 1 || live != 0 { + t.Fatal("management broadened or restored access revived", total, selected, live) + } +} + +func TestProjectManagementBackupRefusesContradictoryGrant(t *testing.T) { + f := newRestoreFixture(t) + connection, err := f.store.DB().Conn(t.Context()) + if err != nil { + t.Fatal(err) + } + if _, err = connection.ExecContext(t.Context(), `PRAGMA ignore_check_constraints=ON`); err != nil { + t.Fatal(err) + } + if _, err = connection.ExecContext(t.Context(), `UPDATE grants SET can_manage=1,can_write=0 WHERE project_id=?`, f.project); err != nil { + t.Fatal(err) + } + if _, err = connection.ExecContext(t.Context(), `PRAGMA ignore_check_constraints=OFF`); err != nil { + t.Fatal(err) + } + if err = connection.Close(); err != nil { + t.Fatal(err) + } + if _, err := Create(t.Context(), f.store, f.dir, filepath.Join(t.TempDir(), "bundles")); err == nil { + t.Fatal("contradictory management authority accepted") + } +} diff --git a/internal/backup/worker_retirement_test.go b/internal/backup/worker_retirement_test.go new file mode 100644 index 000000000..df70ee8a5 --- /dev/null +++ b/internal/backup/worker_retirement_test.go @@ -0,0 +1,64 @@ +package backup + +import ( + "github.com/benhook1013/FireController/internal/core" + "path/filepath" + "testing" +) + +func retirementBackup(t *testing.T) (*restoreFixture, string, Summary) { + t.Helper() + f := newRestoreFixture(t) + worker := core.NewID("worker") + if _, err := f.store.DB().Exec(`INSERT INTO workers(project_id,id,name) VALUES(?,?,?)`, f.project, worker, "Retired worker"); err != nil { + t.Fatal(err) + } + if _, err := f.store.DB().Exec(`INSERT INTO worker_retirements(project_id,worker_id,retired_at,actor_id) VALUES(?,?,?,?)`, f.project, worker, "2026-11-01T00:00:00Z", "principal-backup-proof"); err != nil { + t.Fatal(err) + } + return f, worker, restoreBundle(t, f) +} + +func TestWorkerRetirementBackupPreservesIdentityAndRetirement(t *testing.T) { + _, worker, bundle := retirementBackup(t) + if _, err := Inspect(t.Context(), bundle.Path); err != nil { + t.Fatal(err) + } + dest := filepath.Join(t.TempDir(), "inactive") + if _, err := Restore(t.Context(), bundle.Path, dest); err != nil { + t.Fatal(err) + } + db, err := openSnapshot(t.Context(), filepath.Join(dest, "firecontroller.sqlite")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + var name, at, actor, version string + if err := db.QueryRow(`SELECT w.name,r.retired_at,r.actor_id FROM workers w JOIN worker_retirements r ON r.project_id=w.project_id AND r.worker_id=w.id WHERE w.id=?`, worker).Scan(&name, &at, &actor); err != nil { + t.Fatal(err) + } + if err := db.QueryRow(`SELECT value FROM metadata WHERE key='schema:worker_retirements'`).Scan(&version); err != nil || version != "1" || name != "Retired worker" || at != "2026-11-01T00:00:00Z" || actor != "principal-backup-proof" { + t.Fatal(name, at, actor, version, err) + } +} + +func TestWorkerRetirementBackupRejectsMalformedFacts(t *testing.T) { + for _, statement := range []string{ + `UPDATE worker_retirements SET retired_at='invalid'`, + `UPDATE worker_retirements SET actor_id=''`, + `UPDATE metadata SET value='2' WHERE key='schema:worker_retirements'`, + `DELETE FROM metadata WHERE key='schema:worker_retirements'`, + } { + t.Run(statement, func(t *testing.T) { + _, _, bundle := retirementBackup(t) + mutateBundleSQL(t, bundle.Path, statement) + if _, err := Inspect(t.Context(), bundle.Path); err == nil { + t.Fatal("malformed retirement accepted") + } + dest := filepath.Join(t.TempDir(), "must-not-exist") + if _, err := Restore(t.Context(), bundle.Path, dest); err == nil { + t.Fatal("malformed retirement restored") + } + }) + } +} diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 843393183..050260a07 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -46,6 +46,8 @@ type options struct { } type invocation struct { + ownerManagement *ownerManagementInvocation + includeRetired bool ciWatch *ciWatchInvocation reviewRun *reviewRunInvocation operationHelp string @@ -100,6 +102,11 @@ func RunContext(ctx context.Context, args []string, env map[string]string, stdou } return report(stderr, ExitUsage, "invalid_arguments", "The command or its arguments are not supported.", action) } + if call.ownerManagement != nil { + if err := prepareOwnerManagement(ctx, call.ownerManagement); err != nil { + return reportClientError(stderr, err, ctx) + } + } if call.operationHelp != "" { return emitOperationHelp(call.operationHelp, stdout, stderr) } @@ -280,6 +287,9 @@ func RunContext(ctx context.Context, args []string, env map[string]string, stdou } return emit(stdout, stderr, value) } + if call.ownerManagement != nil { + return executeOwnerManagement(requestCtx, ctx, service, call.ownerManagement, stdout, stderr) + } if call.mutation != nil { value, err := executeMutation(requestCtx, service, call.mutation) if err != nil { @@ -308,7 +318,7 @@ func RunContext(ctx context.Context, args []string, env map[string]string, stdou case call.command == "workers" && call.subcommand == "pause-history": value, err = service.WorkerPauseHistory(requestCtx, client.PageOptions{Limit: call.limit, Cursor: call.cursor}) case call.command == "workers": - value, err = service.Workers(requestCtx, client.PageOptions{Limit: call.limit, Cursor: call.cursor}) + value, err = service.WorkersWithRetired(requestCtx, client.PageOptions{Limit: call.limit, Cursor: call.cursor}, call.includeRetired) case call.command == "jobs" && call.subcommand == "context": value, err = service.JobContext(requestCtx, call.position[0], call.limit) case call.command == "jobs" && call.subcommand == "primary": @@ -334,7 +344,7 @@ func RunContext(ctx context.Context, args []string, env map[string]string, stdou case call.command == "jobs" && call.subcommand == "checklist-history": value, err = service.JobChecklistHistory(requestCtx, call.position[0], client.PageOptions{Limit: call.limit, Cursor: call.cursor}) case call.command == "inbox" && call.subcommand == "list": - value, err = service.Inbox(requestCtx, client.PageOptions{Limit: call.limit, Cursor: call.cursor}, client.InboxFilter{Unread: call.unread, Unacknowledged: call.unack}) + value, err = service.Inbox(requestCtx, client.PageOptions{Limit: call.limit, Cursor: call.cursor}, client.InboxFilter{Unread: call.unread, Unacknowledged: call.unack}, call.worker) case call.command == "inbox" && call.subcommand == "snapshot": value, err = service.InboxSnapshot(requestCtx, client.PageOptions{Limit: call.limit, Cursor: call.cursor}, client.InboxFilter{Unread: call.unread, Unacknowledged: call.unack}) case call.command == "inbox" && call.subcommand == "wait": @@ -403,6 +413,14 @@ func parseInvocation(args []string) (invocation, bool) { return call, false } call.command = remaining[0] + if len(remaining) == 2 && (remaining[1] == "help" || remaining[1] == "--help") && (call.command == "credentials" || call.command == "workers" || call.command == "reviews") { + call.operationHelp = call.command + " help" + return call, true + } + if len(remaining) == 3 && remaining[0] == "help" && ownerManagementOperation(remaining[1]+" "+remaining[2]) { + call.operationHelp = remaining[1] + " " + remaining[2] + return call, true + } if len(remaining) == 3 && remaining[0] == "help" && remaining[1] == "reviews" && (remaining[2] == "operations" || remaining[2] == "operation-control" || remaining[2] == "operation") { call.operationHelp = remaining[2] return call, true @@ -419,11 +437,20 @@ func parseInvocation(args []string) (invocation, bool) { call.setup, ok = parseProfileSetup(call.subcommand, remaining[2:]) return call, ok && (!call.hasProfile || validSetupText(call.profile)) && (!call.hasProfilesFile || validSetupText(call.profilesFile)) } - if call.command != "workers" && call.command != "jobs" && call.command != "inbox" && call.command != "reviews" && call.command != "notes" && call.command != "map" && call.command != "presentation" && call.command != "publication" || len(remaining) < 2 { + if call.command != "workers" && call.command != "jobs" && call.command != "inbox" && call.command != "reviews" && call.command != "notes" && call.command != "map" && call.command != "presentation" && call.command != "publication" && call.command != "credentials" || len(remaining) < 2 { return call, false } call.subcommand = remaining[1] operationArgs := remaining[2:] + if ownerManagementOperation(call.command + " " + call.subcommand) { + if len(operationArgs) == 1 && operationArgs[0] == "--help" { + call.operationHelp = call.command + " " + call.subcommand + return call, true + } + var ok bool + call.ownerManagement, ok = parseOwnerManagement(call.command+" "+call.subcommand, operationArgs) + return call, ok + } if call.command == "reviews" && (call.subcommand == "ci-wait" || call.subcommand == "operations" || call.subcommand == "operation-control" || call.subcommand == "operation" || call.subcommand == "start" || call.subcommand == "run-read") && len(operationArgs) == 1 && operationArgs[0] == "--help" { call.operationHelp = call.subcommand return call, true @@ -493,6 +520,7 @@ func parseInvocation(args []string) (invocation, bool) { case "jobs assigned": allowed["--limit"], allowed["--cursor"], allowed["--status"] = true, true, true case "inbox list": + allowed["--worker"] = true allowed["--limit"], allowed["--cursor"], allowed["--unread"], allowed["--unacknowledged"] = true, true, true, true case "inbox snapshot": allowed["--limit"], allowed["--cursor"], allowed["--unread"], allowed["--unacknowledged"] = true, true, true, true @@ -502,6 +530,9 @@ func parseInvocation(args []string) (invocation, bool) { default: return call, false } + if call.command == "workers" && call.subcommand == "list" { + allowed["--include-retired"] = true + } seen := make(map[string]bool) for i := 0; i < len(operationArgs); i++ { argument := operationArgs[i] @@ -515,6 +546,11 @@ func parseInvocation(args []string) (invocation, bool) { } seen[flag] = true switch flag { + case "--include-retired": + if assigned { + return call, false + } + call.includeRetired = true case "--unread": if assigned { return call, false @@ -528,7 +564,7 @@ func parseInvocation(args []string) (invocation, bool) { default: if !assigned { i++ - if i >= len(operationArgs) { + if i >= len(operationArgs) || (call.command == "inbox" && call.subcommand == "list" && flag == "--worker" && strings.HasPrefix(operationArgs[i], "-")) { return call, false } value = operationArgs[i] diff --git a/internal/cli/mutations.go b/internal/cli/mutations.go index 90cd65e33..16d85d90a 100644 --- a/internal/cli/mutations.go +++ b/internal/cli/mutations.go @@ -10,6 +10,7 @@ import ( ) type mutationInvocation struct { + targetWorker string reviewCheckpoint client.ReviewCheckpointRequest reviewCheckpointRecovery client.ReviewCheckpointRecovery operation string @@ -73,6 +74,8 @@ func parseMutation(command, operation string, args []string) (*mutationInvocatio call := &mutationInvocation{operation: command + " " + operation} allowed := map[string]bool{"--key": true} switch call.operation { + case "inbox ack": + allowed["--worker"] = true case "jobs create", "jobs edit": for _, flag := range []string{"--title", "--brief", "--worker", "--status"} { allowed[flag] = true @@ -102,7 +105,7 @@ func parseMutation(command, operation string, args []string) (*mutationInvocatio } if !assigned { i++ - if i >= len(args) { + if i >= len(args) || (call.operation == "inbox ack" && strings.HasPrefix(args[i], "-")) { return nil, false } value = args[i] @@ -131,9 +134,10 @@ func parseMutation(command, operation string, args []string) (*mutationInvocatio if len(values["--brief"]) > 32<<10 { return nil, false } - if worker := values["--worker"]; worker != "" && !validResourceID(worker) { + if worker, present := values["--worker"]; present && (worker != "" || call.operation == "inbox ack") && !validResourceID(worker) { return nil, false } + call.targetWorker = values["--worker"] if status, present := values["--status"]; present && !validStatus(status) { return nil, false } @@ -217,6 +221,6 @@ func executeMutation(ctx context.Context, service *client.Client, call *mutation case "reviews finalize": return service.FinalizeReviewSource(ctx, call.key, call.id, call.reviewFinalize) default: - return service.Acknowledge(ctx, call.key, call.id) + return service.Acknowledge(ctx, call.key, call.id, call.targetWorker) } } diff --git a/internal/cli/operation_help.go b/internal/cli/operation_help.go index f6d64342f..533541c84 100644 --- a/internal/cli/operation_help.go +++ b/internal/cli/operation_help.go @@ -2,7 +2,22 @@ package cli import "io" +type operationHelpResponse struct { + Usage string `json:"usage"` + Required []string `json:"required"` + Optional []string `json:"optional"` + Semantics []string `json:"semantics"` + Example string `json:"example"` + FileExample map[string]any `json:"file_example,omitempty"` + FileFields map[string]string `json:"file_fields,omitempty"` + Next string `json:"next,omitempty"` + Documentation string `json:"documentation"` +} + func emitOperationHelp(operation string, stdout, stderr io.Writer) int { + if help, ok := ownerManagementHelp(operation); ok { + return emit(stdout, stderr, help) + } usage := " reviews operations [--pr NUMBER] [--channel cli|hosted] [--all] [--limit N] [--cursor CURSOR]" semantics := "Read one compact newest-first page of retained project operations. Default five pending; --all includes held and terminal history. Reuse the same filters with a cursor. No provider reads, automatic pagination, execution or retry." documentation := "docs/review-operations.md" diff --git a/internal/cli/owner_review_regression_test.go b/internal/cli/owner_review_regression_test.go new file mode 100644 index 000000000..6f4af3063 --- /dev/null +++ b/internal/cli/owner_review_regression_test.go @@ -0,0 +1,64 @@ +package cli + +import ( + "context" + "errors" + "github.com/benhook1013/FireController/internal/client" + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +func TestOwnerReviewInboxOptionValues(t *testing.T) { + for _, args := range [][]string{ + {"inbox", "list", "--worker", "--unread"}, + {"inbox", "ack", "message-one", "--key", "--worker"}, + {"inbox", "ack", "message-one", "--key", "good", "--worker", "--key"}, + } { + if _, ok := parseInvocation(args); ok { + t.Errorf("accepted missing option value: %v", args) + } + } + for _, args := range [][]string{ + {"inbox", "list", "--worker=--unread"}, + {"inbox", "ack", "message-one", "--key=--key", "--worker=--worker"}, + } { + if _, ok := parseInvocation(args); !ok { + t.Errorf("rejected explicit value: %v", args) + } + } +} +func TestOwnerReviewPrivateInputDiagnostics(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + for _, in := range []*ownerManagementInvocation{{credentialFile: "/missing"}, {file: "/missing"}} { + if err := prepareOwnerManagement(ctx, in); !errors.Is(err, context.Canceled) { + t.Fatalf("cancellation replaced: %v", err) + } + } + dir := t.TempDir() + public := filepath.Join(dir, "public.json") + if err := os.WriteFile(public, []byte("{}"), 0644); err != nil { + t.Fatal(err) + } + paths := []string{filepath.Join(dir, "missing"), dir} + if runtime.GOOS != "windows" { + paths = append(paths, public) + } + for _, path := range paths { + err := prepareOwnerManagement(context.Background(), &ownerManagementInvocation{file: path}) + var e *client.Error + if !errors.As(err, &e) || e.Code != "invalid_management_input" { + t.Fatalf("wrong local diagnostic for %s: %v", path, err) + } + } +} +func TestOwnerReviewGrantHelpAcceptsManageAlone(t *testing.T) { + var out, err strings.Builder + code := Run([]string{"credentials", "grant", "--help"}, nil, &out, &err) + if code != ExitSuccess || !strings.Contains(out.String(), "| --permission manage") || !strings.Contains(out.String(), "manage implies read/write") { + t.Fatal(code, out.String(), err.String()) + } +} diff --git a/internal/cli/project_owner.go b/internal/cli/project_owner.go new file mode 100644 index 000000000..eeca3d82a --- /dev/null +++ b/internal/cli/project_owner.go @@ -0,0 +1,242 @@ +package cli + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "io" + "path/filepath" + "strings" + + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/strictjson" +) + +type ownerManagementInvocation struct { + operation, key, id, file, credentialFile string + policy client.ConfigureReviewPolicyRequest + execution client.ConfigureReviewExecutionRequest + worker client.CreateWorkerRequest + grant client.GrantProjectCredentialRequest + update client.UpdateProjectCredentialRequest +} + +func ownerManagementOperation(operation string) bool { + switch operation { + case "reviews policy", "reviews policy-configure", "reviews execution-configure", "workers create", "workers retirement", "workers retire", "credentials grant", "credentials revoke", "credentials update": + return true + } + return false +} +func parseOwnerManagement(operation string, args []string) (*ownerManagementInvocation, bool) { + in := &ownerManagementInvocation{operation: operation} + if operation == "workers retirement" { + if len(args) != 1 || !validResourceID(args[0]) { + return nil, false + } + in.id = args[0] + return in, true + } + if operation == "reviews policy" { + return in, len(args) == 0 + } + positions := []string{} + values := map[string]string{} + var permissions []string + for i := 0; i < len(args); i++ { + if !strings.HasPrefix(args[i], "-") { + positions = append(positions, args[i]) + continue + } + flag, value, assigned := strings.Cut(args[i], "=") + switch flag { + case "--file", "--key", "--name", "--token-sha256", "--credential-file", "--permission": + default: + return nil, false + } + if _, ok := values[flag]; ok && flag != "--permission" { + return nil, false + } + if !assigned { + i++ + if i >= len(args) || strings.HasPrefix(args[i], "-") { + return nil, false + } + value = args[i] + } + if value == "" { + return nil, false + } + values[flag] = value + if flag == "--permission" { + permissions = append(permissions, value) + } + } + in.key, in.file, in.credentialFile = values["--key"], values["--file"], values["--credential-file"] + if !validMutationKey(in.key) { + return nil, false + } + allowed := map[string]bool{"--key": true} + idRequired := operation == "workers retire" || operation == "credentials revoke" || operation == "credentials update" + if idRequired { + if len(positions) != 1 || !validResourceID(positions[0]) { + return nil, false + } + in.id = positions[0] + } else if len(positions) != 0 { + return nil, false + } + switch operation { + case "reviews policy-configure", "reviews execution-configure", "credentials update": + allowed["--file"] = true + if !filepath.IsAbs(in.file) { + return nil, false + } + case "workers create": + allowed["--name"] = true + in.worker.Name = values["--name"] + if client.ValidateCreateWorker(in.worker) != nil { + return nil, false + } + case "credentials grant": + allowed["--token-sha256"], allowed["--credential-file"], allowed["--permission"] = true, true, true + in.grant = client.GrantProjectCredentialRequest{TokenSHA256: values["--token-sha256"], Permissions: permissions} + if (in.credentialFile == "") == (in.grant.TokenSHA256 == "") { + return nil, false + } + if in.credentialFile != "" { + if !filepath.IsAbs(in.credentialFile) { + return nil, false + } + in.grant.TokenSHA256 = strings.Repeat("a", 64) + } + if client.ValidateGrantProjectCredential(in.grant) != nil { + return nil, false + } + case "workers retire", "credentials revoke": + default: + return nil, false + } + for flag := range values { + if !allowed[flag] { + return nil, false + } + } + return in, true +} +func decodeOwnerJSON(body []byte, out any, required ...string) bool { + if strictjson.Decode(body, out) != nil { + return false + } + var fields map[string]json.RawMessage + if json.Unmarshal(body, &fields) != nil || fields == nil { + return false + } + for _, raw := range fields { + if string(raw) == "null" { + return false + } + } + for _, key := range required { + raw, ok := fields[key] + if !ok || string(raw) == "null" { + return false + } + } + return true +} +func prepareOwnerManagement(ctx context.Context, in *ownerManagementInvocation) error { + bad := func() error { + return &client.Error{Code: "invalid_management_input", Message: "Use the declared complete management fields in a bounded owner-private input file.", Action: "Check local help and correct the selected file; no service request was sent.", Status: 400} + } + if in.credentialFile != "" { + rawToken, err := readOwnerPrivateJSON(ctx, in.credentialFile) + if err != nil && ctx.Err() != nil { + return err + } + if err != nil || len(rawToken) > 4096 { + return bad() + } + token := strings.TrimSpace(string(rawToken)) + if len(token) < 32 || len(token) > 256 { + return bad() + } + for _, r := range token { + if r < 33 || r > 126 { + return bad() + } + } + sum := sha256.Sum256([]byte(token)) + in.grant.TokenSHA256 = hex.EncodeToString(sum[:]) + } + if in.file == "" { + return nil + } + body, err := readOwnerPrivateJSON(ctx, in.file) + if errors.Is(err, errInvalidOwnerPrivateJSONFile) { + return bad() + } + if err != nil { + return err + } + switch in.operation { + case "reviews policy-configure": + if !decodeOwnerJSON(body, &in.policy, "expected_revision", "required_channels", "max_review_files", "paused_channels") || client.ValidateConfigureReviewPolicy(in.policy) != nil { + return bad() + } + case "reviews execution-configure": + if !decodeOwnerJSON(body, &in.execution, "expected_revision", "capability_id", "mode", "queue", "channels", "paused") || client.ValidateConfigureReviewExecution(in.execution) != nil { + return bad() + } + case "credentials update": + if !decodeOwnerJSON(body, &in.update, "expected_permissions", "permissions") || client.ValidateUpdateProjectCredential(in.id, in.update) != nil { + return bad() + } + } + return nil +} +func executeOwnerManagement(ctx, parent context.Context, c *client.Client, in *ownerManagementInvocation, stdout, stderr io.Writer) int { + var v any + var err error + switch in.operation { + case "reviews policy": + v, err = c.ReviewPolicy(ctx) + case "reviews policy-configure": + v, err = c.ConfigureReviewPolicy(ctx, in.key, in.policy) + case "reviews execution-configure": + v, err = c.ConfigureReviewExecution(ctx, in.key, in.execution) + case "workers retirement": + v, err = c.WorkerRetirement(ctx, in.id) + case "workers retire": + v, err = c.RetireWorker(ctx, in.key, in.id) + case "workers create": + v, err = c.CreateWorker(ctx, in.key, in.worker) + case "credentials grant": + v, err = c.GrantProjectCredential(ctx, in.key, in.grant) + case "credentials revoke": + v, err = c.RevokeProjectCredential(ctx, in.key, in.id) + case "credentials update": + v, err = c.UpdateProjectCredential(ctx, in.key, in.id, in.update) + } + if err != nil { + return reportClientError(stderr, err, parent) + } + if in.operation == "reviews policy" || in.operation == "workers retirement" { + return emit(stdout, stderr, v) + } + b, err := json.Marshal(v) + if err == nil { + b = append(b, '\n') + var n int + n, err = stdout.Write(b) + if n != len(b) && err == nil { + err = io.ErrShortWrite + } + } + if err != nil { + return reportDetails(stderr, ExitConfig, diagnostic{Code: "output_failed", Message: "The management receipt could not be written.", Action: "Retain the original request values, idempotency key and selected binding for recovery. Preserve original file contents; for credential grants, the original digest can be reused with --token-sha256.", OutcomeUnknown: true}) + } + return ExitSuccess +} diff --git a/internal/cli/project_owner_help.go b/internal/cli/project_owner_help.go new file mode 100644 index 000000000..ea6b16bca --- /dev/null +++ b/internal/cli/project_owner_help.go @@ -0,0 +1,68 @@ +package cli + +func ownerManagementHelp(operation string) (operationHelpResponse, bool) { + out := operationHelpResponse{Usage: " " + operation, Required: []string{}, Optional: []string{}, Semantics: []string{"Uses only the selected project and acting worker. Management capability never grants permission to merge or request unauthorized provider work.", "For mutations, retain the exact request, binding and explicit key after an unknown outcome; no automatic retry."}, Documentation: "docs/review-execution.md"} + switch operation { + case "credentials help": + out.Optional = []string{"credentials grant --help", "credentials update --help", "credentials revoke --help"} + out.Semantics = []string{"Project-manager access changes use this bound project. Grant accepts only a digest or local private credential-file reference; update preserves an existing binding under an exact permission-set guard. No raw token arguments or instance administration."} + out.Documentation = "docs/local-api.md" + case "workers help": + out.Optional = []string{"workers create --help", "workers retirement --help", "workers retire --help", "workers list [--include-retired]"} + out.Semantics = []string{"Local worker command index; no profile, credential or service access. Use operation --help for permissions and retirement guards."} + out.Documentation = "docs/worker-retirement.md" + case "reviews help": + out.Optional = []string{"reviews policy --help", "reviews policy-configure --help", "reviews execution-configure --help", "reviews start --help", "reviews run-read --help"} + out.Semantics = []string{"Local review command index; no profile, credential or service access. Use operation --help for permissions and execution guards."} + case "reviews policy": + out.Documentation = "docs/review-controls.md" + out.Semantics = []string{"Read the current configured project review requirements and policy revision. No provider work or source refresh."} + case "reviews policy-configure": + out.Documentation = "docs/review-controls.md" + out.Usage += " --file POLICY_JSON --key KEY" + out.Required = []string{"--file (owner-private absolute JSON path)", "--key KEY"} + out.FileExample = map[string]any{"expected_revision": 0, "required_channels": []string{"cli", "hosted"}, "paused_channels": []string{}, "max_review_files": 0} + out.Semantics = append(out.Semantics, "Project manager; full policy replacement. max_review_files zero disables the optional project ceiling; provider restrictions remain independent. For initial configuration use expected_revision zero; reviews policy returns reviews_policy_unconfigured until configured. For replacement, read reviews policy for the current revision. Optional round_defaults provides hosted/cli objects with explicit minimum/maximum for newly initialized PR controls only. Omission uses product defaults; existing controls and taper are unchanged. See docs/review-round-controls.md. No review request.") + case "reviews execution-configure": + out.Usage += " --file CONFIG_JSON --key KEY" + out.Required = []string{"--file (owner-private absolute JSON path)", "--key KEY"} + out.FileExample = map[string]any{"expected_revision": 1, "capability_id": "configured-capability", "mode": "stacked", "queue": []int{42}, "channels": []string{"cli", "hosted"}, "paused": false} + out.Semantics = append(out.Semantics, "Project manager; full execution replacement. Read reviews execution and preserve unrelated fields. queue must retain at least one PR. Preserve the current capability_id; capability installation and initial binding are instance-owned. Existing limits/history remain; this requests no review.") + case "workers retirement", "workers retire": + out.Usage += " WORKER_ID" + out.Required = []string{"WORKER_ID"} + out.Semantics = []string{"Retirement is one-way and preserves historical worker references. Unfinished assigned jobs, pending direct/assigned-job notes and unacknowledged messages block retirement. Reassign or resolve work and explicitly acknowledge messages first; nothing is moved or acknowledged automatically."} + if operation == "workers retire" { + out.Usage += " --key KEY" + out.Required = append(out.Required, "--key KEY") + out.Semantics = append(out.Semantics, "Project writer; atomic blocker checks run again at retirement. Retain the exact request/key after an uncertain result; no automatic retry.") + } else { + out.Semantics = append(out.Semantics, "Read-only preview reports total blocker counts and up to 20 IDs per category. It is not a reservation or a guarantee a later retirement will succeed.") + } + out.Documentation = "docs/worker-retirement.md" + case "workers create": + out.Usage += " --name TEXT --key KEY" + out.Required = []string{"--name TEXT (1-200 UTF-8 bytes, no surrounding whitespace)", "--key KEY"} + out.Semantics = append(out.Semantics, "Project writer; create one named worker. Does not change the acting worker, create credentials or start an agent.") + out.Documentation = "docs/local-api.md" + case "credentials grant": + out.Usage += " (--token-sha256 HASH | --credential-file PATH) (--permission read [--permission write] | --permission manage) --key KEY" + out.Required = []string{"exactly one --token-sha256 (64 lowercase hex) or --credential-file (existing private absolute path)", "--permission (repeat for unique read/write/manage)", "--key KEY"} + out.Semantics = append(out.Semantics, "Project manager; create one distinct non-admin project credential grant. Only a SHA-256 digest is sent. An explicitly selected owner-private credential file is hashed locally; use a high-entropy token of 32-256 printable nonspace ASCII bytes after surrounding whitespace is trimmed. No raw token is accepted as an argument or printed. manage implies read/write. Existing credentials use update instead.") + out.Documentation = "docs/local-api.md" + case "credentials revoke": + out.Usage += " CREDENTIAL_ID --key KEY" + out.Required = []string{"CREDENTIAL_ID", "--key KEY"} + out.Semantics = append(out.Semantics, "Project manager; revoke only this project's grant. Other-project grants remain. No credential secret is read or printed.") + out.Documentation = "docs/local-api.md" + case "credentials update": + out.Usage += " CREDENTIAL_ID --file PERMISSIONS_JSON --key KEY" + out.Required = []string{"CREDENTIAL_ID", "--file (owner-private absolute JSON path)", "--key KEY"} + out.FileExample = map[string]any{"expected_permissions": []string{"read", "write"}, "permissions": []string{"read", "write", "manage"}} + out.Semantics = append(out.Semantics, "Project manager; exact permission-set guard on one active non-admin credential's grant. Preserves credential, token, principal and worker binding. Changes no other project. manage implies read/write.") + out.Documentation = "docs/local-api.md" + default: + return operationHelpResponse{}, false + } + return out, true +} diff --git a/internal/cli/project_owner_test.go b/internal/cli/project_owner_test.go new file mode 100644 index 000000000..43afca15c --- /dev/null +++ b/internal/cli/project_owner_test.go @@ -0,0 +1,309 @@ +package cli_test + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "sync/atomic" + "testing" + + "github.com/benhook1013/FireController/internal/cli" + "github.com/benhook1013/FireController/internal/client" +) + +func TestProjectOwnerCLIExistingOperationsAndPrivateCredentialHash(t *testing.T) { + f, project, worker := reviewExecutionFixture(t) + const rawToken = "synthetic-private-delegated-token" + var leaked bool + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + r.Body = io.NopCloser(bytes.NewReader(body)) + if bytes.Contains(body, []byte(rawToken)) { + leaked = true + } + if strings.Contains(r.URL.RawQuery, rawToken) { + leaked = true + } + f.handler.ServeHTTP(w, r) + })) + defer server.Close() + profiles := mutationProfiles(t, f, server.URL, map[string][2]string{"owner": {project, worker}}) + invoke := func(args ...string) string { + t.Helper() + code, out, stderr := mutationInvoke(t, profiles, "owner", args...) + if code != 0 || stderr != "" || strings.Contains(out, rawToken) || strings.Contains(stderr, rawToken) { + t.Fatal(code, out, stderr) + } + return out + } + file := func(name string, value any) string { + t.Helper() + p := filepath.Join(t.TempDir(), name) + b, _ := json.Marshal(value) + if os.WriteFile(p, b, 0600) != nil { + t.Fatal("private request fixture") + } + return p + } + policyFile := file("policy.json", client.ConfigureReviewPolicyRequest{PausedChannels: []string{}, ExpectedRevision: 1, RequiredChannels: []string{"cli", "hosted"}, MaxReviewFiles: 88, RoundDefaults: &client.ReviewRoundDefaults{Hosted: client.ReviewRoundBounds{Minimum: 2, Maximum: 5}, CLI: client.ReviewRoundBounds{Minimum: 0, Maximum: 8}}}) + var policy client.ReviewRequestReceipt + if json.Unmarshal([]byte(invoke("reviews", "policy-configure", "--file", policyFile, "--key", "policy-change")), &policy) != nil || policy.Revision != 2 { + t.Fatal(policy) + } + var current client.ReviewPolicyRecord + if json.Unmarshal([]byte(invoke("reviews", "policy")), ¤t) != nil || current.Policy.MaxReviewFiles != 88 || current.Policy.RoundDefaults == nil || current.Policy.RoundDefaults.Hosted.Maximum != 5 || current.Policy.RoundDefaults.CLI.Minimum != 0 { + t.Fatal(current) + } + executionFile := file("execution.json", client.ConfigureReviewExecutionRequest{ExpectedRevision: 1, CapabilityID: "fixture", Mode: "independent", Queue: []int64{2}, Channels: []string{"cli", "hosted"}, Paused: true}) + invoke("reviews", "execution-configure", "--file", executionFile, "--key", "execution-change") + var created client.WorkerCreateReceipt + if json.Unmarshal([]byte(invoke("workers", "create", "--name", "CLI Inspector", "--key", "create-worker")), &created) != nil || created.ID == "" { + t.Fatal(created) + } + credentialFile := filepath.Join(t.TempDir(), "new.token") + if os.WriteFile(credentialFile, []byte(rawToken+"\n"), 0600) != nil { + t.Fatal("private token fixture") + } + var grant client.ProjectCredentialReceipt + if json.Unmarshal([]byte(invoke("credentials", "grant", "--credential-file", credentialFile, "--permission", "read", "--key", "grant-reader")), &grant) != nil || grant.ID == "" { + t.Fatal(grant) + } + updateFile := file("permissions.json", client.UpdateProjectCredentialRequest{ExpectedPermissions: []string{"read"}, Permissions: []string{"read", "write"}}) + invoke("credentials", "update", grant.ID, "--file", updateFile, "--key", "update-reader") + staleCode, staleOut, staleErr := mutationInvoke(t, profiles, "owner", "credentials", "update", grant.ID, "--file", updateFile, "--key", "stale-update") + if staleCode != cli.ExitConflict || staleOut != "" || !strings.Contains(staleErr, "returned current_permissions") { + t.Fatal(staleCode, staleOut, staleErr) + } + invoke("credentials", "revoke", grant.ID, "--key", "revoke-reader") + message := f.call(t, "POST", "/api/v1/projects/"+project+"/messages", f.admin, worker, map[string]any{"recipient_worker_id": created.ID, "body": "Selected inbox"})["id"].(string) + f.call(t, "POST", "/api/v1/projects/"+project+"/messages", f.admin, created.ID, map[string]any{"recipient_worker_id": worker, "body": "Selected outbox"}) + var inbox client.Page[client.InboxItem] + if json.Unmarshal([]byte(invoke("inbox", "list", "--worker", created.ID)), &inbox) != nil || len(inbox.Items) != 1 || inbox.Items[0].RecipientWorkerID != created.ID { + t.Fatal(inbox) + } + denied, _, deniedErr := mutationInvoke(t, profiles, "owner", "inbox", "ack", message, "--key", "no-impersonation") + if denied == 0 || !strings.Contains(deniedErr, "forbidden") { + t.Fatal(denied, deniedErr) + } + if leaked { + t.Fatal("credential reached query output") + } +} + +func TestProjectOwnerCLIHelpAndMalformedBeforeProfiles(t *testing.T) { + for _, op := range [][]string{{"reviews", "policy"}, {"reviews", "policy-configure"}, {"reviews", "execution-configure"}, {"workers", "create"}, {"credentials", "grant"}, {"credentials", "revoke"}, {"credentials", "update"}} { + code, out, stderr := run(append(op, "--help"), nil) + if code != 0 || stderr != "" || !strings.Contains(out, "documentation") { + t.Fatal(op, code, out, stderr) + } + if op[0] == "reviews" && op[1] == "policy-configure" { + var help struct { + FileExample struct { + ExpectedRevision *int64 `json:"expected_revision"` + } `json:"file_example"` + } + if err := json.Unmarshal([]byte(out), &help); err != nil || help.FileExample.ExpectedRevision == nil || *help.FileExample.ExpectedRevision != 0 || !strings.Contains(out, "reviews_policy_unconfigured") || !strings.Contains(out, "For replacement") { + t.Fatal("initial policy guidance missing", out, err) + } + } + if op[0] == "credentials" && op[1] == "grant" && (!strings.Contains(out, "32-256 printable nonspace ASCII bytes") || !strings.Contains(out, "surrounding whitespace is trimmed")) { + t.Fatal("credential-file bounds missing from local help", out) + } + } + p := filepath.Join(t.TempDir(), "incomplete.json") + if os.WriteFile(p, []byte(`{"expected_revision":1,"capability_id":"fixture","mode":"independent","queue":[],"channels":["cli"]}`), 0600) != nil { + t.Fatal("private fixture") + } + code, out, stderr := run([]string{"--profiles-file", "/missing/private-profiles", "reviews", "execution-configure", "--file", p, "--key", "bad"}, nil) + if code == cli.ExitSuccess || out != "" || !strings.Contains(stderr, "invalid_management_input") { + t.Fatal(code, out, stderr) + } + for _, defaults := range []string{`null`, `{"hosted":{"minimum":0,"maximum":1}}`, `{"hosted":{"minimum":0,"maximum":1},"cli":{"minimum":2,"maximum":1}}`} { + body := `{"expected_revision":0,"paused_channels":[],"required_channels":["cli"],"max_review_files":0,"round_defaults":` + defaults + `}` + if err := os.WriteFile(p, []byte(body), 0600); err != nil { + t.Fatal(err) + } + code, out, stderr := run([]string{"--profiles-file", "/missing/private-profiles", "reviews", "policy-configure", "--file", p, "--key", "bad"}, nil) + if code == cli.ExitSuccess || out != "" || !strings.Contains(stderr, "invalid_management_input") { + t.Fatal("invalid policy defaults reached profile loading", code, out, stderr) + } + } + for _, args := range [][]string{{"workers", "create", "--name", " padded ", "--key", "x"}, {"credentials", "grant", "--token-sha256", "raw secret", "--permission", "read", "--key", "x"}, {"credentials", "update", "bad/id", "--file", p, "--key", "x"}} { + code, out, stderr := run(append([]string{"--profiles-file", "/missing"}, args...), nil) + if code != cli.ExitUsage || out != "" || !strings.Contains(stderr, "invalid_arguments") { + t.Fatal(args, code, out, stderr) + } + } +} + +func TestProjectOwnerCLICredentialFileBoundsPreserveHashAndReceipt(t *testing.T) { + for _, tc := range []struct { + name, token, padding string + }{ + {"minimum", strings.Repeat("!", 32), " \t\r\n"}, + {"maximum", strings.Repeat("~", 256), "\r\n"}, + } { + t.Run(tc.name, func(t *testing.T) { + f := setupServiceFixture(t) + project := f.project(t, "credential-boundary") + worker := f.worker(t, project, "Owner") + var leaked atomic.Bool + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + r.Body = io.NopCloser(bytes.NewReader(body)) + if r.Method == "POST" && strings.HasSuffix(r.URL.Path, "/credentials") { + var grant map[string]json.RawMessage + var digest string + var permissions []string + sum := sha256.Sum256([]byte(tc.token)) + if r.URL.RawQuery != "" || json.Unmarshal(body, &grant) != nil || len(grant) != 2 || json.Unmarshal(grant["token_sha256"], &digest) != nil || digest != hex.EncodeToString(sum[:]) || json.Unmarshal(grant["permissions"], &permissions) != nil || !slices.Equal(permissions, []string{"read"}) { + t.Error("grant must contain only exact digest and permissions without query") + } + } + if bytes.Contains(body, []byte(tc.token)) || strings.Contains(r.URL.RawQuery, tc.token) { + leaked.Store(true) + } + f.handler.ServeHTTP(w, r) + })) + defer server.Close() + profiles := mutationProfiles(t, f, server.URL, map[string][2]string{"owner": {project, worker}}) + credentialFile := filepath.Join(t.TempDir(), "boundary.token") + if err := os.WriteFile(credentialFile, []byte(tc.padding+tc.token+tc.padding), 0600); err != nil { + t.Fatal(err) + } + code, out, stderr := mutationInvoke(t, profiles, "owner", "credentials", "grant", "--credential-file", credentialFile, "--permission", "read", "--key", "boundary-grant") + if code != cli.ExitSuccess || stderr != "" || strings.Contains(out, tc.token) || strings.Contains(out, credentialFile) { + t.Fatal(code, out, stderr) + } + var grant client.ProjectCredentialReceipt + if json.Unmarshal([]byte(out), &grant) != nil || grant.ID == "" || grant.PrincipalID == "" || grant.ProjectID != project || grant.Outcome != "granted" { + t.Fatal("invalid boundary grant receipt", out) + } + // Digest input must preserve the exact receipt and principal from the trimmed file input. + sum := sha256.Sum256([]byte(tc.token)) + code, replay, stderr := mutationInvoke(t, profiles, "owner", "credentials", "grant", "--token-sha256", hex.EncodeToString(sum[:]), "--permission", "read", "--key", "boundary-grant") + if code != cli.ExitSuccess || stderr != "" || replay != out || leaked.Load() { + t.Fatal("credential digest or replay changed", code, replay, stderr) + } + if got := f.call(t, "GET", "/api/v1/projects/"+project, tc.token, worker, nil); got["id"] != project { + t.Fatal("granted boundary token cannot authenticate", got) + } + }) + } +} + +func TestProjectOwnerCLICredentialFileRejectsInvalidTokensBeforeHTTP(t *testing.T) { + f := setupServiceFixture(t) + project := f.project(t, "invalid-credentials") + worker := f.worker(t, project, "Owner") + var requests atomic.Int64 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + f.handler.ServeHTTP(w, r) + })) + defer server.Close() + profiles := mutationProfiles(t, f, server.URL, map[string][2]string{"owner": {project, worker}}) + for _, tc := range []struct { + name, token string + }{ + {"empty", ""}, + {"one-byte", "!"}, + {"short", strings.Repeat("!", 31)}, + {"short-padded", " \t" + strings.Repeat("!", 31) + "\r\n"}, + {"long", strings.Repeat("!", 257)}, + {"long-padded", "\t" + strings.Repeat("!", 257) + "\n"}, + {"raw-limit", strings.Repeat("!", 4096)}, + {"past-raw-limit", strings.Repeat("!", 4097)}, + {"excessive-padding", strings.Repeat(" ", 4096) + strings.Repeat("!", 32)}, + {"whitespace-only", " \t\r\n"}, + {"interior-space", strings.Repeat("!", 16) + " " + strings.Repeat("!", 16)}, + {"interior-newline", strings.Repeat("!", 16) + "\n" + strings.Repeat("!", 16)}, + {"control", strings.Repeat("!", 32) + "\x7f"}, + {"non-ascii", strings.Repeat("!", 32) + "é"}, + } { + t.Run(tc.name, func(t *testing.T) { + credentialFile := filepath.Join(t.TempDir(), "rejected.token") + if err := os.WriteFile(credentialFile, []byte(tc.token), 0600); err != nil { + t.Fatal(err) + } + for _, profileFile := range []string{profiles, filepath.Join(t.TempDir(), "missing-profiles.json")} { + code, out, stderr := mutationInvoke(t, profileFile, "owner", "credentials", "grant", "--credential-file", credentialFile, "--permission", "read", "--key", "invalid-grant") + if code != cli.ExitUsage || out != "" || !strings.Contains(stderr, "invalid_management_input") || !strings.Contains(stderr, "no service request was sent") || requests.Load() != 0 { + t.Fatal("invalid token reached profiles or HTTP", code, out, stderr, requests.Load()) + } + if strings.Contains(stderr, credentialFile) || tc.token != "" && strings.TrimSpace(tc.token) != "" && strings.Contains(stderr, tc.token) { + t.Fatal("private credential input reached diagnostics") + } + } + }) + } +} + +func TestManagementGroupHelpIsStructuredAndLocal(t *testing.T) { + for _, tc := range []struct { + group, documentation string + operations []string + }{ + {"credentials", "docs/local-api.md", []string{"credentials grant --help", "credentials update --help", "credentials revoke --help"}}, + {"workers", "docs/worker-retirement.md", []string{"workers create --help", "workers retirement --help", "workers retire --help", "workers list [--include-retired]"}}, + {"reviews", "docs/review-execution.md", []string{"reviews policy --help", "reviews policy-configure --help", "reviews execution-configure --help", "reviews start --help", "reviews run-read --help"}}, + } { + for _, argument := range []string{"help", "--help"} { + t.Run(tc.group+"/"+argument, func(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + cancel() + var out, errout bytes.Buffer + code := cli.RunContext(ctx, []string{"--profiles-file", "/missing/private-profile.json", tc.group, argument}, nil, &out, &errout) + if code != cli.ExitSuccess || errout.Len() != 0 || out.Len() > 4096 || strings.Contains(out.String(), "private-profile") { + t.Fatalf("local group help: code=%d stdout=%s stderr=%s", code, &out, &errout) + } + var help struct { + Usage string `json:"usage"` + Required []string `json:"required"` + Optional []string `json:"optional"` + Semantics []string `json:"semantics"` + Documentation string `json:"documentation"` + } + if err := json.Unmarshal(out.Bytes(), &help); err != nil { + t.Fatalf("help must be a structured object: %v; stdout=%s", err, &out) + } + if help.Usage != " "+tc.group+" help" || help.Required == nil || len(help.Required) != 0 || !slices.Equal(help.Optional, tc.operations) || len(help.Semantics) == 0 || help.Documentation != tc.documentation { + t.Fatalf("group help lost its command contract: %+v", help) + } + }) + } + } +} + +func TestProjectOwnerReceiptOutputFailurePreservesRequestValues(t *testing.T) { + f := setupServiceFixture(t) + project := f.project(t, "receipt-recovery") + worker := f.worker(t, project, "Owner") + server := httptest.NewServer(f.handler) + defer server.Close() + profiles := mutationProfiles(t, f, server.URL, map[string][2]string{"owner": {project, worker}}) + tokenFile := filepath.Join(t.TempDir(), "original.token") + if err := os.WriteFile(tokenFile, []byte(strings.Repeat("x", 32)), 0600); err != nil { + t.Fatal(err) + } + args := []string{"--profiles-file", profiles, "--profile", "owner", "credentials", "grant", "--credential-file", tokenFile, "--permission", "read", "--key", "original-grant"} + var diagnostic bytes.Buffer + code := cli.RunContext(t.Context(), args, nil, failedMutationOutput{}, &diagnostic) + if code != cli.ExitConfig || !strings.Contains(diagnostic.String(), "output_failed") || !strings.Contains(diagnostic.String(), "original request values") || !strings.Contains(diagnostic.String(), "original file contents") || !strings.Contains(diagnostic.String(), "--token-sha256") { + t.Fatal(code, diagnostic.String()) + } + sum := sha256.Sum256([]byte(strings.Repeat("x", 32))) + code, out, stderr := mutationInvoke(t, profiles, "owner", "credentials", "grant", "--token-sha256", hex.EncodeToString(sum[:]), "--permission", "read", "--key", "original-grant") + if code != cli.ExitSuccess || out == "" || stderr != "" { + t.Fatal(code, out, stderr) + } +} diff --git a/internal/client/client.go b/internal/client/client.go index 7883c5dd4..73466d8fe 100644 --- a/internal/client/client.go +++ b/internal/client/client.go @@ -572,7 +572,13 @@ func (c *Client) serviceError(data []byte, status int) (*Error, bool) { return invalidResponse(), false } details, err := json.Marshal(value.Error.Details) - if err != nil || len(details) > 4096 || c.hasSensitive(&value) { + if err != nil || c.hasSensitive(&value) { + return invalidResponse(), false + } + // Three groups of twenty 128-byte identities can exceed the ordinary + // detail budget. Allow only the validated blocker shape in a 48 KiB + // envelope, including worst-case six-byte JSON escapes per identity byte. + if len(details) > 4096 && (value.Error.Code != "worker_retirement_blocked" || len(details) > 48<<10 || safeWorkerRetirementBlockers(value.Error.Details) == nil) { return invalidResponse(), false } result := fail(value.Error.Code, "The service refused this scoped request.", "Check the selected instance, project, worker and current access.", status) @@ -670,6 +676,16 @@ func (c *Client) safeDetails(value any, code string) any { return nil } result := make(map[string]any) + if code == "credential_permissions_changed" { + for key, item := range safeCredentialPermissionDetails(object) { + result[key] = item + } + } + if code == "worker_retirement_blocked" { + if blocks := safeWorkerRetirementBlockers(object); blocks != nil { + return blocks + } + } for key, item := range object { switch key { case "reason": diff --git a/internal/client/mutations.go b/internal/client/mutations.go index e7c191f4a..243bea04f 100644 --- a/internal/client/mutations.go +++ b/internal/client/mutations.go @@ -113,17 +113,31 @@ func (c *Client) MarkSeen(ctx context.Context, key, id string) (MessageReceipt, return c.transition(ctx, key, id, "seen") } -func (c *Client) Acknowledge(ctx context.Context, key, id string) (MessageReceipt, error) { - return c.transition(ctx, key, id, "ack") +func (c *Client) Acknowledge(ctx context.Context, key, id string, selectedWorker ...string) (MessageReceipt, error) { + worker, err := c.selectedWorker(selectedWorker) + if err != nil { + return MessageReceipt{}, err + } + // Keep the default receipt identity for both omitted and explicit self selections. + if worker == c.identity.WorkerID { + return c.transition(ctx, key, id, "ack") + } + return c.transition(ctx, key, id, "ack", worker) } -func (c *Client) transition(ctx context.Context, key, id, action string) (MessageReceipt, error) { +func (c *Client) transition(ctx context.Context, key, id, action string, selectedWorker ...string) (MessageReceipt, error) { if !validMutationKey(key) || !validID(id) { return MessageReceipt{}, mutationValidation() } var result MessageReceipt path := c.projectPath("messages", id, action) - if err := c.mutate(ctx, http.MethodPost, path, key, struct{}{}, http.StatusOK, &result); err != nil { + var input struct { + WorkerID string `json:"worker_id,omitempty"` + } + if len(selectedWorker) == 1 { + input.WorkerID = selectedWorker[0] + } + if err := c.mutate(ctx, http.MethodPost, path, key, input, http.StatusOK, &result); err != nil { return MessageReceipt{}, err } want := action diff --git a/internal/client/owner_review_regression_test.go b/internal/client/owner_review_regression_test.go new file mode 100644 index 000000000..0b551424d --- /dev/null +++ b/internal/client/owner_review_regression_test.go @@ -0,0 +1,49 @@ +package client_test + +import ( + "errors" + "github.com/benhook1013/FireController/internal/client" + "net/http" + "net/http/httptest" + "testing" +) + +func TestOwnerReviewPermissionReceiptRequiresExactElements(t *testing.T) { + for _, permissions := range [][]string{{"read,write"}, {"read", "write"}} { + service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/instance" { + handshake(w) + return + } + write(w, 200, client.ProjectCredentialUpdateReceipt{ID: "credential-one", ProjectID: "project-one", Outcome: "updated", Permissions: permissions}) + })) + c := newClient(t, service) + _, err := c.UpdateProjectCredential(t.Context(), "update-key", "credential-one", client.UpdateProjectCredentialRequest{ExpectedPermissions: []string{"read"}, Permissions: []string{"read", "write"}}) + if len(permissions) == 1 { + var e *client.Error + if !errors.As(err, &e) || !e.OutcomeUnknown || e.Code != "invalid_response" { + t.Errorf("malformed receipt accepted: %v", err) + } + } else if err != nil { + t.Error(err) + } + service.Close() + } +} +func TestOwnerReviewActiveWorkerPageRejectsRetiredEntries(t *testing.T) { + service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/instance" { + handshake(w) + return + } + write(w, 200, client.Page[client.Worker]{Items: []client.Worker{{ID: "worker-old", ProjectID: "project-one", Name: "Old", Retired: true}}}) + })) + defer service.Close() + c := newClient(t, service) + _, err := c.Workers(t.Context(), client.PageOptions{}) + checkError(t, err, "invalid_response") + page, err := c.WorkersWithRetired(t.Context(), client.PageOptions{}, true) + if err != nil || len(page.Items) != 1 || !page.Items[0].Retired { + t.Fatal(page, err) + } +} diff --git a/internal/client/project_owner.go b/internal/client/project_owner.go new file mode 100644 index 000000000..788f3f355 --- /dev/null +++ b/internal/client/project_owner.go @@ -0,0 +1,375 @@ +package client + +import ( + "context" + "encoding/json" + "errors" + "github.com/benhook1013/FireController/internal/strictjson" + "math" + "net/http" + "slices" + "strings" + "unicode" + "unicode/utf8" +) + +type ReviewPolicy struct { + PausedChannels []string `json:"paused_channels"` + RequiredChannels []string `json:"required_channels"` + MaxReviewFiles int64 `json:"max_review_files"` + RoundDefaults *ReviewRoundDefaults `json:"round_defaults,omitempty"` +} +type ReviewPolicyRecord struct { + ProjectID string `json:"project_id"` + Revision int64 `json:"revision"` + ActorID string `json:"actor_id"` + RecordedAt string `json:"recorded_at"` + Policy ReviewPolicy `json:"policy"` +} +type ConfigureReviewPolicyRequest struct { + ExpectedRevision int64 `json:"expected_revision"` + PausedChannels []string `json:"paused_channels"` + RequiredChannels []string `json:"required_channels"` + MaxReviewFiles int64 `json:"max_review_files"` + RoundDefaults *ReviewRoundDefaults `json:"round_defaults,omitempty"` +} +type ConfigureReviewExecutionRequest struct { + ExpectedRevision int64 `json:"expected_revision"` + CapabilityID string `json:"capability_id"` + Mode string `json:"mode"` + Queue []int64 `json:"queue"` + Channels []string `json:"channels"` + Paused bool `json:"paused"` +} +type CreateWorkerRequest struct { + Name string `json:"name"` +} +type WorkerCreateReceipt struct { + ID string `json:"id"` + Revision int64 `json:"revision"` + Outcome string `json:"outcome"` +} +type GrantProjectCredentialRequest struct { + TokenSHA256 string `json:"token_sha256"` + Permissions []string `json:"permissions"` +} +type ProjectCredentialReceipt struct { + ID string `json:"id"` + PrincipalID string `json:"principal_id,omitempty"` + ProjectID string `json:"project_id"` + Outcome string `json:"outcome"` +} + +func ownerChannels(values []string) bool { + if values == nil || len(values) < 1 || len(values) > 2 { + return false + } + seen := map[string]bool{} + for _, v := range values { + if !oneReviewOf(v, "cli", "hosted") || seen[v] { + return false + } + seen[v] = true + } + return true +} +func ownerText(s string, max int, multiline bool) bool { + if !utf8.ValidString(s) || len(s) < 1 || len(s) > max || strings.TrimSpace(s) != s { + return false + } + for _, r := range s { + if unicode.IsControl(r) && !(multiline && (r == '\n' || r == '\t')) { + return false + } + } + return true +} +func ValidateConfigureReviewPolicy(r ConfigureReviewPolicyRequest) error { + if r.PausedChannels == nil || len(r.PausedChannels) > 2 || !validPausedChannels(r.PausedChannels) || r.ExpectedRevision < 0 || r.ExpectedRevision == math.MaxInt64 || !ownerChannels(r.RequiredChannels) || r.MaxReviewFiles < 0 || r.MaxReviewFiles > 100000 || !validReviewRoundDefaults(r.RoundDefaults) { + return mutationValidation() + } + return nil +} +func ValidateConfigureReviewExecution(r ConfigureReviewExecutionRequest) error { + if r.ExpectedRevision < 0 || r.ExpectedRevision == math.MaxInt64 || !validExecutionIdentifier(r.CapabilityID) || !oneReviewOf(r.Mode, "independent", "stacked") || len(r.Queue) == 0 || len(r.Queue) > 100 || !ownerChannels(r.Channels) { + return mutationValidation() + } + seen := map[int64]bool{} + for _, n := range r.Queue { + if !validPullNumber(n) || seen[n] { + return mutationValidation() + } + seen[n] = true + } + return nil +} + +func ValidateCreateWorker(r CreateWorkerRequest) error { + if !ownerText(r.Name, 200, false) { + return mutationValidation() + } + return nil +} +func ValidateGrantProjectCredential(r GrantProjectCredentialRequest) error { + if len(r.TokenSHA256) != 64 || !lowerHex(r.TokenSHA256) || r.Permissions == nil || len(r.Permissions) < 1 || len(r.Permissions) > 3 { + return mutationValidation() + } + seen := map[string]bool{} + for _, p := range r.Permissions { + if !oneReviewOf(p, "read", "write", "manage") || seen[p] { + return mutationValidation() + } + seen[p] = true + } + if !seen["read"] && !seen["manage"] { + return mutationValidation() + } + return nil +} +func lowerHex(s string) bool { + for _, r := range s { + if !(r >= '0' && r <= '9' || r >= 'a' && r <= 'f') { + return false + } + } + return true +} +func (c *Client) ReviewPolicy(ctx context.Context) (ReviewPolicyRecord, error) { + var v ReviewPolicyRecord + err := c.requestBounded(ctx, http.MethodGet, c.projectPath("reviews", "policy"), nil, true, "", nil, http.StatusOK, false, &v, 8<<10, decodeResponse) + if err != nil { + return v, err + } + if v.ProjectID != c.identity.ProjectID || v.Revision < 1 || !validID(v.ActorID) || !validJobProgressTime(v.RecordedAt) || !ownerChannels(v.Policy.RequiredChannels) || v.Policy.PausedChannels == nil || !validPausedChannels(v.Policy.PausedChannels) || v.Policy.MaxReviewFiles < 0 || v.Policy.MaxReviewFiles > 100000 || !validReviewRoundDefaults(v.Policy.RoundDefaults) { + return ReviewPolicyRecord{}, invalidResponse() + } + return v, nil +} +func (c *Client) ConfigureReviewPolicy(ctx context.Context, key string, r ConfigureReviewPolicyRequest) (ReviewRequestReceipt, error) { + var v ReviewRequestReceipt + if !validMutationKey(key) || ValidateConfigureReviewPolicy(r) != nil { + return v, mutationValidation() + } + if err := c.mutate(ctx, http.MethodPost, c.projectPath("reviews", "policy"), key, r, http.StatusOK, &v); err != nil { + return v, err + } + if v.ID != c.identity.ProjectID || v.State != "policy_configured" || v.Revision != r.ExpectedRevision+1 { + return ReviewRequestReceipt{}, unknownMutation("invalid_response", "The policy receipt was invalid; retain the original key and request.", 200) + } + return v, nil +} +func (c *Client) ConfigureReviewExecution(ctx context.Context, key string, r ConfigureReviewExecutionRequest) (ReviewRequestReceipt, error) { + var v ReviewRequestReceipt + if !validMutationKey(key) || ValidateConfigureReviewExecution(r) != nil { + return v, mutationValidation() + } + if err := c.mutate(ctx, http.MethodPost, c.projectPath("reviews", "execution", "configuration"), key, r, http.StatusCreated, &v); err != nil { + return v, err + } + if v.ID != c.identity.ProjectID || v.State != "configured" || v.Revision != r.ExpectedRevision+1 { + return ReviewRequestReceipt{}, unknownMutation("invalid_response", "The execution receipt was invalid; retain the original key and request.", 201) + } + return v, nil +} + +func (c *Client) CreateWorker(ctx context.Context, key string, r CreateWorkerRequest) (WorkerCreateReceipt, error) { + var v WorkerCreateReceipt + if !validMutationKey(key) || ValidateCreateWorker(r) != nil { + return v, mutationValidation() + } + if err := c.mutate(ctx, http.MethodPost, c.projectPath("workers"), key, r, http.StatusOK, &v); err != nil { + return v, err + } + if !validID(v.ID) || v.Revision != 1 || v.Outcome != "created" { + return WorkerCreateReceipt{}, unknownMutation("invalid_response", "The worker receipt was invalid; retain original name and key.", 200) + } + return v, nil +} +func (c *Client) GrantProjectCredential(ctx context.Context, key string, r GrantProjectCredentialRequest) (ProjectCredentialReceipt, error) { + var v ProjectCredentialReceipt + if !validMutationKey(key) || ValidateGrantProjectCredential(r) != nil { + return v, mutationValidation() + } + if err := c.mutate(ctx, http.MethodPost, c.projectPath("credentials"), key, r, http.StatusOK, &v); err != nil { + return v, err + } + if !validID(v.ID) || !validID(v.PrincipalID) || v.ProjectID != c.identity.ProjectID || v.Outcome != "granted" { + return ProjectCredentialReceipt{}, unknownMutation("invalid_response", "The credential receipt was invalid; retain the digest, permissions and key.", 200) + } + return v, nil +} +func (c *Client) RevokeProjectCredential(ctx context.Context, key, id string) (ProjectCredentialReceipt, error) { + var v ProjectCredentialReceipt + if !validMutationKey(key) || !validID(id) { + return v, mutationValidation() + } + if err := c.mutate(ctx, http.MethodDelete, c.projectPath("credentials", id), key, struct{}{}, http.StatusOK, &v); err != nil { + return v, err + } + if v.ID != id || v.ProjectID != c.identity.ProjectID || v.PrincipalID != "" || v.Outcome != "revoked" { + return ProjectCredentialReceipt{}, unknownMutation("invalid_response", "The revoke receipt was invalid; retain the credential ID and key.", 200) + } + return v, nil +} + +type UpdateProjectCredentialRequest struct { + ExpectedPermissions []string `json:"expected_permissions"` + Permissions []string `json:"permissions"` +} +type ProjectCredentialUpdateReceipt struct { + ID string `json:"id"` + ProjectID string `json:"project_id"` + Outcome string `json:"outcome"` + Permissions []string `json:"permissions"` +} + +func ValidateUpdateProjectCredential(id string, r UpdateProjectCredentialRequest) error { + if !validID(id) || ValidateGrantProjectCredential(GrantProjectCredentialRequest{TokenSHA256: strings.Repeat("a", 64), Permissions: r.ExpectedPermissions}) != nil || ValidateGrantProjectCredential(GrantProjectCredentialRequest{TokenSHA256: strings.Repeat("a", 64), Permissions: r.Permissions}) != nil { + return mutationValidation() + } + return nil +} +func normalizedPermissions(p []string) []string { + read, write, manage := false, false, false + for _, v := range p { + switch v { + case "read": + read = true + case "write": + write = true + case "manage": + read, write, manage = true, true, true + } + } + r := []string{} + if read { + r = append(r, "read") + } + if write { + r = append(r, "write") + } + if manage { + r = append(r, "manage") + } + return r +} +func (c *Client) UpdateProjectCredential(ctx context.Context, key, id string, r UpdateProjectCredentialRequest) (ProjectCredentialUpdateReceipt, error) { + var v ProjectCredentialUpdateReceipt + if !validMutationKey(key) || ValidateUpdateProjectCredential(id, r) != nil { + return v, mutationValidation() + } + if err := c.mutate(ctx, http.MethodPut, c.projectPath("credentials", id), key, r, http.StatusOK, &v); err != nil { + return v, projectCredentialError(err, id) + } + want := normalizedPermissions(r.Permissions) + if v.ID != id || v.ProjectID != c.identity.ProjectID || !oneReviewOf(v.Outcome, "updated", "unchanged") || !slices.Equal(v.Permissions, want) { + return ProjectCredentialUpdateReceipt{}, unknownMutation("invalid_response", "The access update receipt was invalid; preserve original credential ID, permissions and key.", 200) + } + return v, nil +} + +// selectedWorker changes the resource selector, never the authenticated acting identity. +func (c *Client) selectedWorker(selected []string) (string, error) { + if len(selected) > 1 { + return "", validation() + } + worker := c.identity.WorkerID + if len(selected) == 1 && selected[0] != "" { + worker = selected[0] + } + if !validID(worker) { + return "", validation() + } + return worker, nil +} + +func safeCredentialPermissionDetails(object map[string]any) map[string]any { + id, ok := object["credential_id"].(string) + if !ok || !validID(id) { + return nil + } + raw, ok := object["current_permissions"].([]any) + if !ok { + return nil + } + var permissions []string + for _, v := range raw { + s, ok := v.(string) + if !ok { + return nil + } + permissions = append(permissions, s) + } + if ValidateGrantProjectCredential(GrantProjectCredentialRequest{TokenSHA256: strings.Repeat("a", 64), Permissions: permissions}) != nil || strings.Join(permissions, ",") != strings.Join(normalizedPermissions(permissions), ",") { + return nil + } + return map[string]any{"credential_id": id, "current_permissions": permissions} +} + +func projectCredentialError(err error, id string) error { + var e *Error + if !errors.As(err, &e) || e.Code != "credential_permissions_changed" || e.OutcomeUnknown { + return err + } + details, ok := e.Details.(map[string]any) + if !ok || details["credential_id"] != id { + return fail("invalid_response", "The service returned an unverifiable permission conflict.", "Preserve the intended credential change and verify the selected service; no new key was generated.", 409) + } + e.Message = "The selected credential's project permissions changed." + e.Action = "Compare returned current_permissions with the intended change. If still appropriate, use that set as expected_permissions with a new explicit key. This refused request changed no permissions." + return e +} + +func validPausedChannels(values []string) bool { + seen := map[string]bool{} + for _, value := range values { + if !oneReviewOf(value, "cli", "hosted") || seen[value] { + return false + } + seen[value] = true + } + return true +} + +type ReviewRoundBounds struct { + Minimum int64 `json:"minimum"` + Maximum int64 `json:"maximum"` +} + +// ReviewRoundDefaults affect only the first installation of a PR/channel control. +type ReviewRoundDefaults struct { + Hosted ReviewRoundBounds `json:"hosted"` + CLI ReviewRoundBounds `json:"cli"` +} + +func (d *ReviewRoundDefaults) UnmarshalJSON(body []byte) error { + type plain ReviewRoundDefaults + var value plain + if strictjson.Decode(body, &value) != nil { + return strictjson.ErrSyntax + } + var channels map[string]map[string]json.RawMessage + if json.Unmarshal(body, &channels) != nil || len(channels) != 2 { + return strictjson.ErrSyntax + } + for _, channel := range []string{"hosted", "cli"} { + bounds := channels[channel] + if len(bounds) != 2 || string(bounds["minimum"]) == "null" || len(bounds["minimum"]) == 0 || string(bounds["maximum"]) == "null" || len(bounds["maximum"]) == 0 { + return strictjson.ErrSyntax + } + } + *d = ReviewRoundDefaults(value) + return nil +} + +func validReviewRoundDefaults(value *ReviewRoundDefaults) bool { + if value == nil { + return true + } + for _, bounds := range []ReviewRoundBounds{value.Hosted, value.CLI} { + if bounds.Minimum < 0 || bounds.Maximum < 1 || bounds.Maximum > 1000 || bounds.Minimum > bounds.Maximum { + return false + } + } + return true +} diff --git a/internal/client/project_owner_test.go b/internal/client/project_owner_test.go new file mode 100644 index 000000000..d92869947 --- /dev/null +++ b/internal/client/project_owner_test.go @@ -0,0 +1,160 @@ +package client_test + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "testing" + + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/reviewexec" + "github.com/benhook1013/FireController/internal/reviews" +) + +func TestProjectOwnerClientActualScopedManagement(t *testing.T) { + f := newMutationFixture(t) + if err := reviewexec.EnsureSchema(t.Context(), f.store); err != nil { + t.Fatal(err) + } + if err := reviews.EnsureSchema(t.Context(), f.store); err != nil { + t.Fatal(err) + } + engine, err := reviewexec.New(f.store, []reviewexec.Capability{{ID: "owner-capability", Provider: "synthetic", Account: "fixture", Channels: []string{"cli", "hosted"}}}, reviewexec.WithNativeProjection()) + if err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + mux.Handle("/", f.handler) + engine.Register(mux) + f.handler = mux + service := httptest.NewServer(f.handler) + defer service.Close() + grant := func(token string, p []string) string { + sum := sha256.Sum256([]byte(token)) + return f.call(t, "POST", "/api/v1/projects/"+f.project+"/credentials", f.admin, f.sender, map[string]any{"token_sha256": hex.EncodeToString(sum[:]), "permissions": p})["id"].(string) + } + const ownerToken = "synthetic-private-manager-token" + grant(ownerToken, []string{"manage"}) + grant("synthetic-writer-token", []string{"read", "write"}) + grant("synthetic-reader-token", []string{"read"}) + owner := f.newClient(t, ownerToken, f.sender, service.URL) + writer := f.newClient(t, "synthetic-writer-token", f.sender, service.URL) + reader := f.newClient(t, "synthetic-reader-token", f.sender, service.URL) + policy := client.ConfigureReviewPolicyRequest{PausedChannels: []string{}, RequiredChannels: []string{"cli", "hosted"}, MaxReviewFiles: 99, RoundDefaults: &client.ReviewRoundDefaults{Hosted: client.ReviewRoundBounds{Minimum: 2, Maximum: 5}, CLI: client.ReviewRoundBounds{Minimum: 0, Maximum: 8}}} + _, err = writer.ConfigureReviewPolicy(t.Context(), "writer-policy", policy) + checkError(t, err, "forbidden") + first, err := owner.ConfigureReviewPolicy(t.Context(), "owner-policy", policy) + if err != nil || first.Revision != 1 { + t.Fatal(first, err) + } + replay, err := owner.ConfigureReviewPolicy(t.Context(), "owner-policy", policy) + if err != nil || !reflect.DeepEqual(first, replay) { + t.Fatal(replay, err) + } + record, err := reader.ReviewPolicy(t.Context()) + if err != nil || record.Policy.MaxReviewFiles != 99 || record.ProjectID != f.project || !reflect.DeepEqual(record.Policy.RoundDefaults, policy.RoundDefaults) { + t.Fatal(record, err) + } + _, err = owner.ConfigureReviewPolicy(t.Context(), "stale-policy", policy) + checkError(t, err, "review_conflict") + initial := client.ConfigureReviewExecutionRequest{CapabilityID: "owner-capability", Mode: "independent", Queue: []int64{2}, Channels: []string{"cli", "hosted"}} + f.call(t, "POST", "/api/v1/projects/"+f.project+"/reviews/execution/configuration", f.admin, f.sender, initial) + config := client.ConfigureReviewExecutionRequest{ExpectedRevision: 1, CapabilityID: "owner-capability", Mode: "independent", Queue: []int64{2}, Channels: []string{"cli", "hosted"}} + _, err = writer.ConfigureReviewExecution(t.Context(), "writer-execution", config) + checkError(t, err, "forbidden") + configured, err := owner.ConfigureReviewExecution(t.Context(), "owner-execution", config) + if err != nil || configured.Revision != 2 { + t.Fatalf("configuration: %+v error: %#v", configured, err) + } + current, err := reader.ReviewExecution(t.Context()) + if err != nil || current.Queue == nil || len(current.Queue) != 1 { + t.Fatal(current, err) + } + worker, err := writer.CreateWorker(t.Context(), "create-inspector", client.CreateWorkerRequest{Name: "Inspector"}) + if err != nil || worker.Outcome != "created" { + t.Fatal(worker, err) + } + _, err = reader.CreateWorker(t.Context(), "read-create", client.CreateWorkerRequest{Name: "Denied"}) + checkError(t, err, "forbidden") + digest := sha256.Sum256([]byte("synthetic-new-nonadmin-token")) + newGrant, err := owner.GrantProjectCredential(t.Context(), "create-grant", client.GrantProjectCredentialRequest{TokenSHA256: hex.EncodeToString(digest[:]), Permissions: []string{"read"}}) + if err != nil || newGrant.PrincipalID == "" { + t.Fatal(newGrant, err) + } + update := client.UpdateProjectCredentialRequest{ExpectedPermissions: []string{"read"}, Permissions: []string{"manage"}} + changed, err := owner.UpdateProjectCredential(t.Context(), "update-grant", newGrant.ID, update) + if err != nil || !reflect.DeepEqual(changed.Permissions, []string{"read", "write", "manage"}) { + t.Fatal(changed, err) + } + _, err = owner.UpdateProjectCredential(t.Context(), "stale-grant", newGrant.ID, update) + checkError(t, err, "credential_permissions_changed") + var mismatch *client.Error + if !errors.As(err, &mismatch) || mismatch.Details == nil { + t.Fatal("permission guard lost current set", err) + } + revoked, err := owner.RevokeProjectCredential(t.Context(), "revoke-grant", newGrant.ID) + if err != nil || revoked.Outcome != "revoked" { + t.Fatal(revoked, err) + } + other := f.call(t, "POST", "/api/v1/projects", f.admin, "", map[string]any{"name": "other", "repository": "owner/other"})["id"].(string) + otherDigest := sha256.Sum256([]byte("other-project-credential")) + foreign := f.call(t, "POST", "/api/v1/projects/"+other+"/credentials", f.admin, "", map[string]any{"token_sha256": hex.EncodeToString(otherDigest[:]), "permissions": []string{"read"}})["id"].(string) + _, err = owner.RevokeProjectCredential(t.Context(), "foreign-revoke", foreign) + var unavailable *client.Error + if !errors.As(err, &unavailable) || unavailable.Status != 404 { + t.Fatal(err) + } +} + +func TestOwnerClientLocalValidation(t *testing.T) { + c := &client.Client{} + for _, invoke := range []func() error{ + func() error { + _, e := c.ConfigureReviewPolicy(t.Context(), "k", client.ConfigureReviewPolicyRequest{PausedChannels: []string{}}) + return e + }, + func() error { + _, e := c.ConfigureReviewExecution(t.Context(), "k", client.ConfigureReviewExecutionRequest{CapabilityID: "x", Mode: "independent", Channels: []string{"cli"}}) + return e + }, + + func() error { + _, e := c.GrantProjectCredential(t.Context(), "k", client.GrantProjectCredentialRequest{TokenSHA256: "raw credential", Permissions: []string{"manage"}}) + return e + }, + func() error { + _, e := c.CreateWorker(t.Context(), "k", client.CreateWorkerRequest{Name: " padded "}) + return e + }, + } { + if err := invoke(); err == nil { + t.Fatal("invalid management input reached service") + } + } +} + +func TestOwnerCredentialConflictFiltersPrivateDetails(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/instance" { + handshake(w) + return + } + write(w, 409, map[string]any{"request_id": "request-one", "error": map[string]any{"code": "credential_permissions_changed", "message": "PRIVATE narrative", "details": map[string]any{"credential_id": "credential-one", "current_permissions": []string{"read", "write"}, "private_evidence": "PRIVATE evidence"}}}) + })) + defer server.Close() + c := newClient(t, server) + _, err := c.UpdateProjectCredential(t.Context(), "guarded-access", "credential-one", client.UpdateProjectCredentialRequest{ExpectedPermissions: []string{"read"}, Permissions: []string{"manage"}}) + var e *client.Error + if !errors.As(err, &e) || e.Code != "credential_permissions_changed" || !strings.Contains(e.Action, "returned current_permissions") { + t.Fatal(err) + } + raw, _ := json.Marshal(e.Details) + if strings.Contains(string(raw), "PRIVATE") || !strings.Contains(string(raw), "current_permissions") { + t.Fatal(string(raw)) + } +} diff --git a/internal/client/reads.go b/internal/client/reads.go index 2d18872bc..b3259d945 100644 --- a/internal/client/reads.go +++ b/internal/client/reads.go @@ -48,10 +48,16 @@ func (c *Client) Worker(ctx context.Context) (Worker, error) { return value, nil } func (c *Client) Workers(ctx context.Context, options PageOptions) (Page[Worker], error) { + return c.WorkersWithRetired(ctx, options, false) +} +func (c *Client) WorkersWithRetired(ctx context.Context, options PageOptions, includeRetired bool) (Page[Worker], error) { q, err := pageQuery(options) if err != nil { return Page[Worker]{}, err } + if includeRetired { + q.Set("include_retired", "true") + } var value Page[Worker] if err = c.get(ctx, c.projectPath("workers"), q, true, &value); err != nil { return Page[Worker]{}, err @@ -60,7 +66,7 @@ func (c *Client) Workers(ctx context.Context, options PageOptions) (Page[Worker] return Page[Worker]{}, invalidResponse() } for _, item := range value.Items { - if !validID(item.ID) || item.ProjectID != c.identity.ProjectID || !cleanText(item.Name, 200) { + if !validID(item.ID) || item.ProjectID != c.identity.ProjectID || !cleanText(item.Name, 200) || (!includeRetired && item.Retired) { return Page[Worker]{}, invalidResponse() } } @@ -127,7 +133,11 @@ func (c *Client) JobHistory(ctx context.Context, id string, options PageOptions) } return value, nil } -func (c *Client) Inbox(ctx context.Context, options PageOptions, filter InboxFilter) (Page[InboxItem], error) { +func (c *Client) Inbox(ctx context.Context, options PageOptions, filter InboxFilter, selectedWorker ...string) (Page[InboxItem], error) { + worker, err := c.selectedWorker(selectedWorker) + if err != nil { + return Page[InboxItem]{}, err + } q, err := pageQuery(options) if err != nil { return Page[InboxItem]{}, err @@ -139,14 +149,16 @@ func (c *Client) Inbox(ctx context.Context, options PageOptions, filter InboxFil q.Set("unacknowledged", "true") } var value Page[InboxItem] - if err = c.get(ctx, c.projectPath("inbox", c.identity.WorkerID), q, true, &value); err != nil { + if err = c.get(ctx, c.projectPath("inbox", worker), q, true, &value); err != nil { return Page[InboxItem]{}, err } if !validPage(value, options) { return Page[InboxItem]{}, invalidResponse() } for _, item := range value.Items { - if !c.validInboxItem(item, filter) { + validationClient := *c + validationClient.identity.WorkerID = worker + if !validationClient.validInboxItem(item, filter) { return Page[InboxItem]{}, invalidResponse() } } diff --git a/internal/client/types.go b/internal/client/types.go index 1b504e7fe..5f1175c12 100644 --- a/internal/client/types.go +++ b/internal/client/types.go @@ -58,6 +58,7 @@ type Page[T any] struct { HasMore bool `json:"has_more"` } type Worker struct { + Retired bool `json:"retired,omitempty"` ID string `json:"id"` ProjectID string `json:"project_id"` Name string `json:"name"` diff --git a/internal/client/worker_retirement.go b/internal/client/worker_retirement.go new file mode 100644 index 000000000..a2d0d1fad --- /dev/null +++ b/internal/client/worker_retirement.go @@ -0,0 +1,82 @@ +package client + +import ( + "context" + "encoding/json" + "net/http" + + "github.com/benhook1013/FireController/internal/strictjson" +) + +type WorkerRetirementBlocker struct { + Count int64 `json:"count"` + IDs []string `json:"ids"` +} +type WorkerRetirementBlockers struct { + Jobs WorkerRetirementBlocker `json:"jobs"` + Notes WorkerRetirementBlocker `json:"notes"` + Messages WorkerRetirementBlocker `json:"messages"` +} +type WorkerRetirement struct { + WorkerID string `json:"worker_id"` + Retired bool `json:"retired"` + CanRetire bool `json:"can_retire"` + Blockers WorkerRetirementBlockers `json:"blockers"` +} +type WorkerRetirementReceipt struct { + ID string `json:"id"` + Revision int64 `json:"revision"` + Outcome string `json:"outcome"` +} + +func validWorkerRetirementBlockers(b WorkerRetirementBlockers) bool { + for _, group := range []WorkerRetirementBlocker{b.Jobs, b.Notes, b.Messages} { + if group.Count < 0 || group.Count >= 1<<53 || group.IDs == nil || len(group.IDs) != int(min(group.Count, 20)) { + return false + } + seen := map[string]bool{} + for _, id := range group.IDs { + if !validID(id) || seen[id] { + return false + } + seen[id] = true + } + } + return true +} +func (c *Client) WorkerRetirement(ctx context.Context, worker string) (WorkerRetirement, error) { + if !validID(worker) { + return WorkerRetirement{}, validation() + } + var value WorkerRetirement + if err := c.get(ctx, c.projectPath("workers", worker, "retirement"), nil, true, &value); err != nil { + return WorkerRetirement{}, err + } + empty := value.Blockers.Jobs.Count == 0 && value.Blockers.Notes.Count == 0 && value.Blockers.Messages.Count == 0 + if value.WorkerID != worker || !validWorkerRetirementBlockers(value.Blockers) || value.CanRetire != (!value.Retired && empty) { + return WorkerRetirement{}, invalidResponse() + } + return value, nil +} +func (c *Client) RetireWorker(ctx context.Context, key, worker string) (WorkerRetirementReceipt, error) { + if !validID(worker) || !validMutationKey(key) { + return WorkerRetirementReceipt{}, mutationValidation() + } + var value WorkerRetirementReceipt + if err := c.mutate(ctx, http.MethodPost, c.projectPath("workers", worker, "retire"), key, struct{}{}, http.StatusOK, &value); err != nil { + return WorkerRetirementReceipt{}, err + } + if value.ID != worker || value.Revision != 2 || !oneReviewOf(value.Outcome, "retired", "unchanged") { + return WorkerRetirementReceipt{}, unknownMutation("invalid_response", "The worker retirement receipt was invalid; its outcome is unknown.", http.StatusOK) + } + return value, nil +} + +func safeWorkerRetirementBlockers(value any) any { + body, err := json.Marshal(value) + var blockers WorkerRetirementBlockers + if err != nil || strictjson.Decode(body, &blockers) != nil || !completeShape(body, &blockers) || !validWorkerRetirementBlockers(blockers) { + return nil + } + return blockers +} diff --git a/internal/client/worker_retirement_test.go b/internal/client/worker_retirement_test.go new file mode 100644 index 000000000..077c855c7 --- /dev/null +++ b/internal/client/worker_retirement_test.go @@ -0,0 +1,311 @@ +package client_test + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "sync/atomic" + "testing" + + "github.com/benhook1013/FireController/internal/client" +) + +func retirementPreview() client.WorkerRetirement { + empty := client.WorkerRetirementBlocker{IDs: []string{}} + return client.WorkerRetirement{WorkerID: "worker-target", CanRetire: true, Blockers: client.WorkerRetirementBlockers{Jobs: empty, Notes: empty, Messages: empty}} +} +func TestWorkerRetirementStrictBoundTransportAndSingleShotReceipt(t *testing.T) { + preview := retirementPreview() + receipt := client.WorkerRetirementReceipt{ID: preview.WorkerID, Revision: 2, Outcome: "retired"} + var reads, writes atomic.Int64 + service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/instance" { + handshake(w) + return + } + if r.Header.Get("X-FC-Worker") != "worker-one" { + t.Error("resource selection changed actor") + } + switch r.Method { + case "GET": + reads.Add(1) + if r.URL.Path != "/api/v1/projects/project-one/workers/worker-target/retirement" || r.Header.Get("Idempotency-Key") != "" { + t.Error("preview routing") + } + write(w, 200, preview) + case "POST": + writes.Add(1) + body, _ := io.ReadAll(r.Body) + if r.URL.Path != "/api/v1/projects/project-one/workers/worker-target/retire" || string(body) != "{}" || r.Header.Get("Idempotency-Key") != "explicit-retirement" { + t.Error("retirement request identity changed", string(body)) + } + write(w, 200, receipt) + default: + t.Error("unexpected request") + w.WriteHeader(500) + } + })) + defer service.Close() + c := newClient(t, service) + if got, err := c.WorkerRetirement(t.Context(), preview.WorkerID); err != nil || !reflect.DeepEqual(got, preview) { + t.Fatal(got, err) + } + for _, retired := range []bool{false, true} { + preview = retirementPreview() + preview.Retired = retired + preview.CanRetire = !retired + if _, err := c.WorkerRetirement(t.Context(), preview.WorkerID); err != nil { + t.Fatal(err) + } + } + for name, corrupt := range map[string]func(*client.WorkerRetirement){ + "other worker": func(v *client.WorkerRetirement) { v.WorkerID = "foreign" }, + "retired eligible": func(v *client.WorkerRetirement) { v.Retired = true }, + "blocked eligible": func(v *client.WorkerRetirement) { + v.Blockers.Jobs = client.WorkerRetirementBlocker{Count: 1, IDs: []string{"job-one"}} + }, + "missing IDs": func(v *client.WorkerRetirement) { v.Blockers.Notes.Count = 1 }, + "nil IDs": func(v *client.WorkerRetirement) { v.Blockers.Notes.IDs = nil }, + "negative": func(v *client.WorkerRetirement) { v.Blockers.Messages.Count = -1 }, + "duplicate": func(v *client.WorkerRetirement) { + v.CanRetire = false + v.Blockers.Messages = client.WorkerRetirementBlocker{Count: 2, IDs: []string{"message-one", "message-one"}} + }, + "unsafe ID": func(v *client.WorkerRetirement) { + v.CanRetire = false + v.Blockers.Jobs = client.WorkerRetirementBlocker{Count: 1, IDs: []string{"../private"}} + }, + } { + t.Run(name, func(t *testing.T) { + preview = retirementPreview() + corrupt(&preview) + _, err := c.WorkerRetirement(t.Context(), "worker-target") + checkError(t, err, "invalid_response") + }) + } + preview = retirementPreview() + preview.CanRetire = false + preview.Blockers.Jobs.Count = 21 + for i := 0; i < 20; i++ { + preview.Blockers.Jobs.IDs = append(preview.Blockers.Jobs.IDs, "job-"+strings.Repeat("a", i+1)) + } + if _, err := c.WorkerRetirement(t.Context(), preview.WorkerID); err != nil { + t.Fatal("bounded count larger than IDs rejected", err) + } + for _, outcome := range []string{"retired", "unchanged"} { + receipt.Outcome = outcome + if got, err := c.RetireWorker(t.Context(), "explicit-retirement", "worker-target"); err != nil || got != receipt { + t.Fatal(got, err) + } + } + receipt.ID = "foreign" + _, err := c.RetireWorker(t.Context(), "explicit-retirement", "worker-target") + failure, ok := err.(*client.Error) + if !ok { + t.Fatal(err) + } + if failure.Code != "invalid_response" || !failure.OutcomeUnknown || writes.Load() != 3 { + t.Fatal("invalid receipt retried or treated as known", err, writes.Load()) + } + if reads.Load() != 12 { + t.Fatal("preview retry/fanout", reads.Load()) + } +} + +func TestWorkerArchiveAndSelectedAcknowledgementPreserveDefaultWire(t *testing.T) { + var requests atomic.Int64 + service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/instance" { + handshake(w) + return + } + requests.Add(1) + if r.Header.Get("X-FC-Worker") != "worker-one" { + t.Error("selected ACK changed actor") + } + if r.Method == "GET" { + retired := r.URL.Query().Get("include_retired") == "true" + if !retired && r.URL.Query().Has("include_retired") { + t.Error("default list changed cursor query") + } + write(w, 200, client.Page[client.Worker]{Items: []client.Worker{{ID: "worker-target", ProjectID: "project-one", Name: "Target", Retired: retired}}}) + return + } + b, _ := io.ReadAll(r.Body) + want := "{}" + switch r.Header.Get("Idempotency-Key") { + case "selected": + want = `{"worker_id":"worker-target"}` + case "default": + default: + t.Error("missing or unexpected ACK key") + } + if string(b) != want || r.URL.Path != "/api/v1/projects/project-one/messages/message-one/ack" { + t.Error("ACK body/binding", string(b)) + } + write(w, 200, client.MessageReceipt{ID: "message-one", ConversationID: "conversation-one", Outcome: "acknowledged"}) + })) + defer service.Close() + c := newClient(t, service) + if page, err := c.Workers(t.Context(), client.PageOptions{}); err != nil || page.Items[0].Retired { + t.Fatal(page, err) + } + if page, err := c.WorkersWithRetired(t.Context(), client.PageOptions{}, true); err != nil || !page.Items[0].Retired { + t.Fatal(page, err) + } + if _, err := c.Acknowledge(t.Context(), "default", "message-one"); err != nil { + t.Fatal(err) + } + if _, err := c.Acknowledge(t.Context(), "selected", "message-one", "worker-target"); err != nil { + t.Fatal(err) + } + before := requests.Load() + for _, id := range []string{"", "../escape"} { + _, err := c.RetireWorker(t.Context(), "key", id) + checkError(t, err, "validation_failed") + } + if _, err := c.Acknowledge(t.Context(), "selected", "message-one", "../escape"); err == nil { + t.Fatal("invalid selected recipient") + } + if requests.Load() != before { + t.Fatal("malformed operation sent") + } +} + +func longRetirementBlockers(fill string) client.WorkerRetirementBlockers { + var groups [3]client.WorkerRetirementBlocker + for i := range groups { + groups[i].Count = (1 << 53) - 1 + for j := 0; j < 20; j++ { + groups[i].IDs = append(groups[i].IDs, strings.Repeat(fill, 125/len(fill))+strings.Repeat("x", 125%len(fill))+fmt.Sprintf("%03d", j)) + } + } + return client.WorkerRetirementBlockers{Jobs: groups[0], Notes: groups[1], Messages: groups[2]} +} + +func TestWorkerRetirementLongBlockersRemainDefinitive(t *testing.T) { + for _, fill := range []string{"a", "<", "\"", "é"} { + t.Run(fmt.Sprintf("fill-%x", fill), func(t *testing.T) { + blocks := longRetirementBlockers(fill) + details, err := json.Marshal(blocks) + if err != nil || len(details) <= 4096 || len(details) > 48<<10 { + t.Fatal("fixture must exceed the ordinary detail budget within the bounded blocker envelope", len(details), err) + } + var calls atomic.Int64 + service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/instance" { + handshake(w) + return + } + calls.Add(1) + if r.Header.Get("X-FC-Worker") != "worker-one" { + t.Error("retirement selection changed actor") + } + if r.Method == "POST" { + body, _ := io.ReadAll(r.Body) + if string(body) != "{}" || r.Header.Get("Idempotency-Key") != "blocked-long" || r.URL.Path != "/api/v1/projects/project-one/workers/worker-target/retire" { + t.Error("retirement request identity changed") + } + } + write(w, http.StatusConflict, map[string]any{"error": map[string]any{"code": "worker_retirement_blocked", "message": "Clear blockers first.", "details": blocks}, "request_id": "request-long-blockers"}) + })) + defer service.Close() + c := newClient(t, service) + for _, mutate := range []bool{false, true} { + var err error + if mutate { + _, err = c.RetireWorker(t.Context(), "blocked-long", "worker-target") + } else { + _, err = c.WorkerRetirement(t.Context(), "worker-target") + } + checkError(t, err, "worker_retirement_blocked") + failure := err.(*client.Error) + if failure.Status != http.StatusConflict || failure.OutcomeUnknown || failure.RequestID != "request-long-blockers" || !reflect.DeepEqual(failure.Details, blocks) { + t.Fatal("definitive refusal lost bounded blocker handles", failure) + } + } + if calls.Load() != 2 { + t.Fatal("blocked retirement was retried or fanned out", calls.Load()) + } + }) + } +} + +func TestWorkerRetirementErrorDetailBoundsStayStrict(t *testing.T) { + blocks := longRetirementBlockers("a") + encode := func(value any) string { + t.Helper() + b, err := json.Marshal(value) + if err != nil { + t.Fatal(err) + } + return string(b) + } + valid := encode(blocks) + duplicate := longRetirementBlockers("a") + duplicate.Jobs.IDs[1] = duplicate.Jobs.IDs[0] + oversizedID := longRetirementBlockers("a") + oversizedID.Jobs.IDs[0] += "b" + extraID := longRetirementBlockers("a") + extraID.Jobs.IDs = append(extraID.Jobs.IDs, "extra") + sensitive := longRetirementBlockers("a") + sensitive.Jobs.IDs[0] = testToken + for _, test := range []struct { + name, code, details string + valid bool + }{ + {"ordinary-at-limit", "conflict", `"` + strings.Repeat("a", 4094) + `"`, true}, + {"ordinary-over-limit", "conflict", `"` + strings.Repeat("a", 4095) + `"`, false}, + {"other-code-blocker-shape", "conflict", valid, false}, + {"blocker-over-envelope", "worker_retirement_blocked", `"` + strings.Repeat("a", 48<<10) + `"`, false}, + {"transport-over-limit", "worker_retirement_blocked", `"` + strings.Repeat("a", 64<<10) + `"`, false}, + {"unknown-blocker-field", "worker_retirement_blocked", strings.Replace(valid, `"jobs":{`, `"jobs":{"unknown":0,`, 1), false}, + {"duplicate-blocker-field", "worker_retirement_blocked", strings.Replace(valid, `"jobs":{`, `"jobs":{"count":1,`, 1), false}, + {"null-count", "worker_retirement_blocked", strings.Replace(valid, `"count":9007199254740991`, `"count":null`, 1), false}, + {"unsafe-count", "worker_retirement_blocked", strings.Replace(valid, `9007199254740991`, `9007199254740992`, 1), false}, + {"duplicate-id", "worker_retirement_blocked", encode(duplicate), false}, + {"oversized-id", "worker_retirement_blocked", encode(oversizedID), false}, + {"extra-id", "worker_retirement_blocked", encode(extraID), false}, + {"sensitive-id", "worker_retirement_blocked", encode(sensitive), false}, + } { + t.Run(test.name, func(t *testing.T) { + var calls atomic.Int64 + service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/instance" { + handshake(w) + return + } + calls.Add(1) + write(w, http.StatusConflict, map[string]any{"error": map[string]any{"code": test.code, "message": "Request refused.", "details": json.RawMessage(test.details)}, "request_id": "request-bounds"}) + })) + defer service.Close() + c := newClient(t, service) + for _, mutate := range []bool{false, true} { + var err error + if mutate { + _, err = c.RetireWorker(t.Context(), "bounded-error", "worker-target") + } else { + _, err = c.WorkerRetirement(t.Context(), "worker-target") + } + want := "invalid_response" + if test.valid { + want = test.code + } else if mutate && test.name != "transport-over-limit" { + want = "unexpected_status" + } + checkError(t, err, want) + failure := err.(*client.Error) + if failure.OutcomeUnknown != (mutate && !test.valid) || failure.Details != nil { + t.Fatal("invalid detail or outcome escaped its bounds", failure) + } + } + if calls.Load() != 2 { + t.Fatal("error was retried or fanned out", calls.Load()) + } + }) + } +} diff --git a/internal/core/admin_read_test.go b/internal/core/admin_read_test.go index 0f1ab2663..83b1bbbae 100644 --- a/internal/core/admin_read_test.go +++ b/internal/core/admin_read_test.go @@ -39,7 +39,7 @@ func TestReadReauthorizesAdministrativeScopeInSnapshot(t *testing.T) { } // Preserve ordinary project read access while withdrawing administrative // authority after the HTTP boundary obtained its scope. - if _, err := store.DB().Exec(`INSERT INTO grants SELECT id,'read-project',1,0 FROM credentials WHERE principal_id=?`, admin.PrincipalID); err != nil { + if _, err := store.DB().Exec(`INSERT INTO grants(credential_id,project_id,can_read,can_write) SELECT id,'read-project',1,0 FROM credentials WHERE principal_id=?`, admin.PrincipalID); err != nil { t.Fatal(err) } if _, err := store.DB().Exec(`UPDATE credentials SET is_admin=0 WHERE principal_id=?`, admin.PrincipalID); err != nil { diff --git a/internal/core/auth.go b/internal/core/auth.go index 1e1244570..85e19c693 100644 --- a/internal/core/auth.go +++ b/internal/core/auth.go @@ -15,10 +15,30 @@ type querier interface { QueryRowContext(context.Context, string, ...any) *sql.Row } -// Administrative reports whether this scope was obtained through AdminScope. -// It pins the requirement; store reads and mutations reauthorize the credential. +// Administrative pins project-management authority for a project scope, or +// instance administration otherwise. Current credentials are rechecked. func (scope Scope) Administrative() bool { return scope.admin } +func (scope Scope) RequireAdministration() Scope { + scope.admin = true + return scope +} + +// RequireInstanceAdministration preserves the instance-only boundary for +// operations that project management must not authorize. Store reads and +// mutations recheck the authenticated credential, including receipt replay. +func (scope Scope) RequireInstanceAdministration() Scope { + scope.admin = true + scope.instanceAdmin = true + return scope +} + +func IsInstanceAdministrator(ctx context.Context, tx *sql.Tx, principal string) (bool, error) { + var allowed bool + err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM credentials WHERE principal_id=? AND revoked=0 AND is_admin=1)`, principal).Scan(&allowed) + return allowed, err +} + // Authenticate validates a current credential for instance identity inspection. // Project data still requires Scope and administrative actions AdminScope. func (s *Store) Authenticate(r *http.Request) (Scope, error) { return s.authenticate(r) } @@ -102,7 +122,7 @@ func (s *Store) authorize(ctx context.Context, q querier, scope Scope, permissio if scope.expiresAt.IsZero() || !time.Now().Before(scope.expiresAt) { return Fail("unauthorized", "The browser session has expired; connect again.", 401) } - if scope.sessionProject == "" || scope.ProjectID != scope.sessionProject || scope.readOnly && permission != "read" { + if scope.sessionProject == "" || scope.ProjectID != scope.sessionProject || scope.readOnly && permission != "read" || permission == "admin" && !scope.sessionManage { return Fail("forbidden", "The browser session does not permit this project operation.", 403) } } @@ -118,7 +138,7 @@ func (s *Store) authorize(ctx context.Context, q querier, scope Scope, permissio if err != nil { return storageError(err) } - if permission == "admin" && admin != 1 { + if permission == "admin" && admin != 1 && (scope.ProjectID == "" || scope.instanceAdmin) { return Fail("forbidden", "Administrative permission is required.", 403) } if scope.ProjectID != "" { @@ -129,9 +149,9 @@ func (s *Store) authorize(ctx context.Context, q querier, scope Scope, permissio return storageError(err) } if admin != 1 { - var read, write int - err = q.QueryRowContext(ctx, "SELECT can_read,can_write FROM grants WHERE credential_id=? AND project_id=?", credential, scope.ProjectID).Scan(&read, &write) - if errors.Is(err, sql.ErrNoRows) || (err == nil && (read != 1 || permission == "write" && write != 1)) { + var read, write, manage int + err = q.QueryRowContext(ctx, "SELECT can_read,can_write,can_manage FROM grants WHERE credential_id=? AND project_id=?", credential, scope.ProjectID).Scan(&read, &write, &manage) + if errors.Is(err, sql.ErrNoRows) || (err == nil && (read != 1 || permission == "write" && write != 1 || permission == "admin" && (manage != 1 || write != 1))) { return Fail("forbidden", "The credential does not grant this project operation.", 403) } if err != nil { diff --git a/internal/core/browser_session.go b/internal/core/browser_session.go index 2b16fa3f8..9fe3e422b 100644 --- a/internal/core/browser_session.go +++ b/internal/core/browser_session.go @@ -148,11 +148,17 @@ func (s *Store) browserCapabilities(ctx context.Context, q querier, scope Scope, } return false, false, err } - var admin int - if err := q.QueryRowContext(ctx, `SELECT is_admin FROM credentials WHERE token_sha256=? AND revoked=0`, scope.tokenHash).Scan(&admin); err != nil { - return false, false, storageError(err) + if !allowPresentation { + return true, false, nil } - return true, allowPresentation && admin == 1, nil + if err := s.authorize(ctx, q, scope, "admin"); err != nil { + var e *Error + if errors.As(err, &e) && e.Code == "forbidden" { + return true, false, nil + } + return false, false, err + } + return true, true, nil } // ExpireBrowserSession clears only the explicitly selected tab's cookie. It @@ -208,7 +214,7 @@ func (s *Store) browserScope(r *http.Request) (Scope, browserSessionClaims, erro if project != claims.ProjectID { return Scope{}, browserSessionClaims{}, Fail("forbidden", "The browser session permits only its project reads.", 403) } - scope := Scope{ProjectID: project, WorkerID: r.Header.Get("X-FC-Worker"), tokenHash: claims.CredentialHash, instanceID: s.instanceID, readOnly: true, expiresAt: time.Unix(claims.ExpiresAt, 0), sessionProject: claims.ProjectID} + scope := Scope{ProjectID: project, WorkerID: r.Header.Get("X-FC-Worker"), tokenHash: claims.CredentialHash, instanceID: s.instanceID, readOnly: true, expiresAt: time.Unix(claims.ExpiresAt, 0), sessionProject: claims.ProjectID, sessionManage: claims.CanEditPresentation} if len(r.Header.Values("X-FC-Worker")) > 1 || len(scope.WorkerID) > 128 { return Scope{}, browserSessionClaims{}, Fail("validation_failed", "Select at most one valid worker identity.", 400) } diff --git a/internal/core/event_project.go b/internal/core/event_project.go index 55e0adba8..6324bc2b4 100644 --- a/internal/core/event_project.go +++ b/internal/core/event_project.go @@ -16,7 +16,7 @@ const projectFeed = "events:project-metadata" var projectEventTypes = [...]string{ "project.presentation_changed", "map.entry_created", "map.entry_updated", "job.workstream_changed", "job.created", "job.updated", "job.checkpointed", "job.update_appended", "job.checklist_replaced", - "workers.created", "worker.pause_changed", "worker.primary_job_changed", + "workers.created", "workers.retired", "worker.pause_changed", "worker.primary_job_changed", "note.created", "note.updated", "review.observed", "reviews.policy_configured", "reviews.rounds_configured", "reviews.adoption_obligations_imported", "reviews.adoption_obligation_resolved", "reviews.adoption_obligation_retargeted", diff --git a/internal/core/event_stream_test.go b/internal/core/event_stream_test.go index 08a1a541d..485762c5f 100644 --- a/internal/core/event_stream_test.go +++ b/internal/core/event_stream_test.go @@ -21,7 +21,7 @@ func streamFixture(t *testing.T) (*Store, Scope, string) { t.Cleanup(func() { s.Close() }) token := "synthetic-core-stream-token-1234567" sum := sha256.Sum256([]byte(token)) - _, err = s.DB().Exec(`INSERT INTO projects VALUES('project','project',1,'synthetic/project');INSERT INTO workers VALUES('project','worker','worker');INSERT INTO credentials VALUES('credential','principal',?,0,0);INSERT INTO grants VALUES('credential','project',1,1)`, hex.EncodeToString(sum[:])) + _, err = s.DB().Exec(`INSERT INTO projects VALUES('project','project',1,'synthetic/project');INSERT INTO workers VALUES('project','worker','worker');INSERT INTO credentials VALUES('credential','principal',?,0,0);INSERT INTO grants(credential_id,project_id,can_read,can_write) VALUES('credential','project',1,1)`, hex.EncodeToString(sum[:])) if err != nil { t.Fatal(err) } diff --git a/internal/core/events.go b/internal/core/events.go index ac34be4bd..3d4e28f54 100644 --- a/internal/core/events.go +++ b/internal/core/events.go @@ -74,7 +74,10 @@ func (s *Store) readMessageEvents(ctx context.Context, scope Scope, after int64, if err := rows.Scan(&event.Sequence, &event.ProjectID, &event.Type, &event.ResourceID, &event.Revision, &event.ActorID, &payload, &event.CreatedAt); err != nil { return err } - event.Payload = json.RawMessage(payload) + event.Payload, err = messageFeedPayload(event.Type, payload) + if err != nil { + return err + } page.Items = append(page.Items, event) } if err := rows.Err(); err != nil { @@ -90,3 +93,17 @@ func (s *Store) readMessageEvents(ctx context.Context, scope Scope, after int64, }) return page, err } + +// Preserve the existing feed bytes and bounds unless the new peer-ACK audit +// field needs attenuation. The true actor remains in durable event storage. +func messageFeedPayload(kind, payload string) (json.RawMessage, error) { + var retained map[string]json.RawMessage + if err := json.Unmarshal([]byte(payload), &retained); err != nil { + return nil, err + } + if _, ok := retained["actor_worker_id"]; !ok { + return json.RawMessage(payload), nil + } + delete(retained, "actor_worker_id") + return json.Marshal(retained) +} diff --git a/internal/core/live_project_events_test.go b/internal/core/live_project_events_test.go index ad0d5dc1d..b0093c8c4 100644 --- a/internal/core/live_project_events_test.go +++ b/internal/core/live_project_events_test.go @@ -15,7 +15,7 @@ func TestLiveProjectReplayVisibleStateOnly(t *testing.T) { kinds := []string{ "project.presentation_changed", "map.entry_created", "map.entry_updated", "job.workstream_changed", "job.created", "job.updated", "job.checkpointed", "job.update_appended", "job.checklist_replaced", - "workers.created", "worker.pause_changed", "worker.primary_job_changed", "note.created", "note.updated", + "workers.created", "workers.retired", "worker.pause_changed", "worker.primary_job_changed", "note.created", "note.updated", "review.observed", "reviews.policy_configured", "review.evidence.adjudicated", "review.evidence.finalized", "review.evidence.fix_recorded", "review.evidence.routed", "review.route.routed", "review.route.superseded", "review.route.adjudicated", "review.route.fix_recorded", @@ -34,7 +34,7 @@ func TestLiveProjectReplayVisibleStateOnly(t *testing.T) { } { commitProjectEvent(t, s, scope, kind, fmt.Sprintf("excluded-%d", i)) } - if _, err := s.DB().Exec(`INSERT INTO projects VALUES('foreign','Foreign',2,'synthetic/foreign'); INSERT INTO workers VALUES('foreign','worker','Worker'); INSERT INTO grants VALUES('credential','foreign',1,1)`); err != nil { + if _, err := s.DB().Exec(`INSERT INTO projects VALUES('foreign','Foreign',2,'synthetic/foreign'); INSERT INTO workers VALUES('foreign','worker','Worker'); INSERT INTO grants(credential_id,project_id,can_read,can_write) VALUES('credential','foreign',1,1)`); err != nil { t.Fatal(err) } foreign := scope diff --git a/internal/core/project_management.go b/internal/core/project_management.go new file mode 100644 index 000000000..f13e38003 --- /dev/null +++ b/internal/core/project_management.go @@ -0,0 +1,39 @@ +package core + +import ( + "context" + "database/sql" + "errors" + "strconv" +) + +// Project management is an explicit grant alongside read/write, never an +// instance-administrator credential or an automatic upgrade of existing writers. +func (s *Store) ensureProjectManagement(ctx context.Context) error { + return s.ensureSchemaWithPreflight(ctx, "project_management", [][]string{{ + `ALTER TABLE grants ADD COLUMN can_manage INTEGER NOT NULL DEFAULT 0 CHECK(can_manage IN(0,1) AND (can_manage=0 OR (can_read=1 AND can_write=1)))`, + }}, checkAdministrationVersions, nil) +} + +// Before each administration migration writes, check both formats under its own +// exclusive writer transaction. This preserves independent domain commits. +func checkAdministrationVersions(ctx context.Context, conn *sql.Conn) error { + for _, domain := range []string{"project_management", "worker_retirements"} { + var raw string + err := conn.QueryRowContext(ctx, "SELECT value FROM metadata WHERE key=?", "schema:"+domain).Scan(&raw) + if errors.Is(err, sql.ErrNoRows) { + continue + } + if err != nil { + return storageError(err) + } + version, err := strconv.Atoi(raw) + if err != nil || version < 1 || strconv.Itoa(version) != raw { + return Fail("schema_invalid", "Domain schema version metadata is invalid.", 500) + } + if version > 1 { + return Fail("schema_unsupported", "A domain schema is newer than this service; use a compatible binary.", 500) + } + } + return nil +} diff --git a/internal/core/project_management_test.go b/internal/core/project_management_test.go new file mode 100644 index 000000000..c15743c40 --- /dev/null +++ b/internal/core/project_management_test.go @@ -0,0 +1,109 @@ +package core + +import ( + "context" + "database/sql" + "errors" + "net/http/httptest" + "path/filepath" + "testing" +) + +func TestProjectManagementScopeCannotEscapeOrSurviveDowngrade(t *testing.T) { + ctx := context.Background() + s, err := Open(ctx, filepath.Join(t.TempDir(), "private")) + if err != nil { + t.Fatal(err) + } + defer s.Close() + for _, q := range []string{ + `INSERT INTO projects VALUES('one','One',1,'owner/one'),('two','Two',2,'owner/two')`, + `INSERT INTO credentials VALUES('manager','principal-manager','` + tokenHash("synthetic-project-manager") + `',0,0)`, + `INSERT INTO grants(credential_id,project_id,can_read,can_write,can_manage) VALUES('manager','one',1,1,1),('manager','two',1,1,0)`, + } { + if _, err := s.DB().Exec(q); err != nil { + t.Fatal(err) + } + } + r := httptest.NewRequest("POST", "/owned-operation", nil) + r.SetPathValue("project_id", "one") + r.Header.Set("Authorization", "Bearer synthetic-project-manager") + managed, err := s.AdminScope(r) + if err != nil || !managed.Administrative() { + t.Fatalf("own management scope: %v", err) + } + ordinary, err := s.Scope(r, "write") + if err != nil { + t.Fatal(err) + } + for _, project := range []string{"two", ""} { + r.SetPathValue("project_id", project) + if _, err := s.AdminScope(r); err == nil { + t.Fatal("manager gained another project's or instance administration") + } + } + mutation := Mutation{Operation: "test.project.manage", Target: "settings", Key: "original-key", Request: struct{}{}} + _, err = s.Mutate(ctx, managed, mutation, func(context.Context, *sql.Tx) (any, error) { return map[string]string{"outcome": "saved"}, nil }) + if err != nil { + t.Fatal(err) + } + if _, err := s.DB().Exec(`UPDATE grants SET can_manage=0 WHERE credential_id='manager' AND project_id='one'`); err != nil { + t.Fatal(err) + } + called := false + err = s.Read(ctx, managed, func(context.Context, *sql.Tx) error { called = true; return nil }) + var failure *Error + if !errors.As(err, &failure) || failure.Code != "forbidden" || called { + t.Fatal("management read survived downgrade", err) + } + if _, _, err := s.Replay(ctx, managed, mutation); !errors.As(err, &failure) || failure.Code != "forbidden" { + t.Fatal("management receipt leaked after downgrade", err) + } + if _, err := s.Mutate(ctx, managed, mutation, func(context.Context, *sql.Tx) (any, error) { called = true; return nil, nil }); !errors.As(err, &failure) || failure.Code != "forbidden" || called { + t.Fatal("management mutation survived downgrade", err) + } + if err := s.Read(ctx, ordinary, func(context.Context, *sql.Tx) error { return nil }); err != nil { + t.Fatal("ordinary read/write grant changed", err) + } + copy := ordinary + copy.ProjectID = "two" + copy.admin = true + if err := s.Read(ctx, copy, func(context.Context, *sql.Tx) error { return nil }); !errors.As(err, &failure) || failure.Code != "forbidden" { + t.Fatal("copied project scope escaped management boundary", err) + } +} + +func TestProjectManagementMigrationPreservesExistingGrantsWithoutElevation(t *testing.T) { + ctx := context.Background() + dir := filepath.Join(t.TempDir(), "private") + s, err := Open(ctx, dir) + if err != nil { + t.Fatal(err) + } + for _, q := range []string{ + `INSERT INTO projects VALUES('one','One',1,'owner/one')`, + `INSERT INTO credentials VALUES('writer','principal-writer','` + tokenHash("synthetic-writer") + `',0,0)`, + `INSERT INTO grants(credential_id,project_id,can_read,can_write) VALUES('writer','one',1,1)`, + `DELETE FROM metadata WHERE key='schema:project_management'`, + `ALTER TABLE grants DROP COLUMN can_manage`, + } { + if _, err = s.DB().Exec(q); err != nil { + t.Fatal(err) + } + } + if err = s.Close(); err != nil { + t.Fatal(err) + } + s, err = Open(ctx, dir) + if err != nil { + t.Fatal(err) + } + defer s.Close() + var read, write, manage int + if err = s.DB().QueryRow(`SELECT can_read,can_write,can_manage FROM grants WHERE credential_id='writer'`).Scan(&read, &write, &manage); err != nil || read != 1 || write != 1 || manage != 0 { + t.Fatal("existing writer changed or elevated", err) + } + if _, err = s.DB().Exec(`UPDATE grants SET can_read=0,can_manage=1 WHERE credential_id='writer'`); err == nil { + t.Fatal("management without read/write was stored") + } +} diff --git a/internal/core/project_management_upgrade_test.go b/internal/core/project_management_upgrade_test.go new file mode 100644 index 000000000..1b928650f --- /dev/null +++ b/internal/core/project_management_upgrade_test.go @@ -0,0 +1,321 @@ +package core + +import ( + "context" + "database/sql" + "encoding/json" + "io/fs" + "os" + "path/filepath" + "strings" + "testing" +) + +func copyManagementFixture(t *testing.T, from, to string) { + t.Helper() + if err := filepath.WalkDir(from, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + rel, err := filepath.Rel(from, path) + if err != nil { + return err + } + target := filepath.Join(to, rel) + if d.IsDir() { + return os.MkdirAll(target, 0700) + } + body, err := os.ReadFile(path) + if err != nil { + return err + } + return os.WriteFile(target, body, 0600) + }); err != nil { + t.Fatal(err) + } +} +func managementRows(t *testing.T, db *sql.DB, query string) string { + t.Helper() + rows, err := db.Query(query) + if err != nil { + t.Fatal(err) + } + defer rows.Close() + columns, err := rows.Columns() + if err != nil { + t.Fatal(err) + } + out := [][]any{} + for rows.Next() { + values := make([]any, len(columns)) + dest := make([]any, len(columns)) + for i := range values { + dest[i] = &values[i] + } + if err := rows.Scan(dest...); err != nil { + t.Fatal(err) + } + out = append(out, values) + } + if err := rows.Err(); err != nil { + t.Fatal(err) + } + b, err := json.Marshal(out) + if err != nil { + t.Fatal(err) + } + return string(b) +} +func TestProjectManagementRealParentUpgradePreservesAllRowsAndSchemas(t *testing.T) { + parent := os.Getenv("FC_ADMIN_PARENT_FIXTURE") + if parent == "" { + t.Skip("requires genuine pinned-parent binary fixture; see administration proof") + } + dir := filepath.Join(t.TempDir(), "source") + copyManagementFixture(t, filepath.Join(parent, "source"), dir) + db, err := sql.Open("sqlite", filepath.Join(dir, "firecontroller.sqlite")) + if err != nil { + t.Fatal(err) + } + tables, err := db.Query(`SELECT name FROM sqlite_schema WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name`) + if err != nil { + t.Fatal(err) + } + names := []string{} + for tables.Next() { + var name string + if err := tables.Scan(&name); err != nil { + t.Fatal(err) + } + names = append(names, name) + } + tables.Close() + before := map[string]string{} + queries := map[string]string{} + for _, name := range names { + q := `SELECT * FROM "` + name + `" ORDER BY rowid` + if name == "metadata" { + q = `SELECT * FROM metadata WHERE key NOT IN ('schema:project_management','schema:worker_retirements') ORDER BY rowid` + } + queries[name] = q + before[name] = managementRows(t, db, q) + } + schema := managementRows(t, db, `SELECT type,name,tbl_name,sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%' AND name<>'grants' ORDER BY type,name`) + if got := managementRows(t, db, `SELECT key FROM metadata WHERE key IN ('schema:project_management','schema:worker_retirements')`); got != "[]" { + t.Fatal("fixture already has new domains", got) + } + db.Close() + s, err := Open(t.Context(), dir) + if err != nil { + t.Fatal(err) + } + defer s.Close() + queries["grants"] = `SELECT credential_id,project_id,can_read,can_write FROM grants ORDER BY rowid` + for _, name := range names { + if got := managementRows(t, s.DB(), queries[name]); got != before[name] { + t.Fatalf("old rows changed in %s", name) + } + } + if got := managementRows(t, s.DB(), `SELECT type,name,tbl_name,sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%' AND name NOT IN ('grants','worker_retirements') ORDER BY type,name`); got != schema { + t.Fatal("unrelated physical schema changed") + } + if got := managementRows(t, s.DB(), `SELECT can_manage FROM grants WHERE can_manage<>0`); got != "[]" { + t.Fatal("writer silently promoted", got) + } + if got := managementRows(t, s.DB(), `SELECT key,value FROM metadata WHERE key IN ('schema:project_management','schema:worker_retirements') ORDER BY key`); got != `[["schema:project_management","1"],["schema:worker_retirements","1"]]` { + t.Fatal(got) + } +} +func TestProjectManagementPrincipalUniquenessAndExactCredentialReauthorization(t *testing.T) { + s, scope, _ := streamFixture(t) + ctx := t.Context() + var principal, hash string + if err := s.DB().QueryRow(`SELECT principal_id,token_sha256 FROM credentials WHERE id='credential'`).Scan(&principal, &hash); err != nil { + t.Fatal(err) + } + if _, err := s.DB().Exec(`INSERT INTO credentials VALUES('sibling',?, ?,1,0)`, principal, strings.Repeat("b", 64)); err == nil { + t.Fatal("principal uniqueness lost") + } + for _, mutate := range []func(Scope) Scope{func(v Scope) Scope { v.PrincipalID = "other"; return v }, func(v Scope) Scope { v.tokenHash = strings.Repeat("c", 64); return v }, func(v Scope) Scope { v.instanceID = "other"; return v }} { + called := false + err := s.Read(ctx, mutate(scope), func(_ context.Context, _ *sql.Tx) error { called = true; return nil }) + if err == nil || called { + t.Fatal("forged credential accepted") + } + } + if _, err := s.DB().Exec(`UPDATE credentials SET token_sha256=? WHERE principal_id=?`, strings.Repeat("d", 64), principal); err != nil { + t.Fatal(err) + } + called := false + err := s.Read(ctx, scope, func(_ context.Context, _ *sql.Tx) error { called = true; return nil }) + if err == nil || called { + t.Fatal("old exact credential survived replacement") + } +} + +func TestProjectManagementNewerRetirementBlocksBeforeManagementMigration(t *testing.T) { + dir := filepath.Join(t.TempDir(), "db") + s, err := Open(t.Context(), dir) + if err != nil { + t.Fatal(err) + } + for _, query := range []string{`DELETE FROM metadata WHERE key='schema:project_management'`, `ALTER TABLE grants DROP COLUMN can_manage`, `UPDATE metadata SET value='2' WHERE key='schema:worker_retirements'`} { + if _, err = s.DB().Exec(query); err != nil { + t.Fatal(err) + } + } + s.Close() + if next, err := Open(t.Context(), dir); err == nil { + next.Close() + t.Fatal("unknown retirement accepted") + } + db, err := sql.Open("sqlite", filepath.Join(dir, "firecontroller.sqlite")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + if got := managementRows(t, db, `SELECT key FROM metadata WHERE key='schema:project_management'`); got != "[]" { + t.Fatal("management migrated before newer-domain refusal") + } + var count int + if err := db.QueryRow(`SELECT count(*) FROM pragma_table_info('grants') WHERE name='can_manage'`).Scan(&count); err != nil || count != 0 { + t.Fatal("column changed before version refusal", count, err) + } +} + +func TestProjectManagementRechecksRetirementVersionAtMigrationBoundary(t *testing.T) { + dir := filepath.Join(t.TempDir(), "db") + s, err := Open(t.Context(), dir) + if err != nil { + t.Fatal(err) + } + defer s.Close() + other, err := sql.Open("sqlite", filepath.Join(dir, "firecontroller.sqlite")) + if err != nil { + t.Fatal(err) + } + defer other.Close() + for _, query := range []string{ + `DELETE FROM metadata WHERE key='schema:project_management'`, + `ALTER TABLE grants DROP COLUMN can_manage`, + } { + if _, err = other.ExecContext(t.Context(), query); err != nil { + t.Fatal(err) + } + } + conn, err := s.db.Conn(t.Context()) + if err != nil { + t.Fatal(err) + } + earlierCheck := checkAdministrationVersions(t.Context(), conn) + if err = conn.Close(); err != nil { + t.Fatal(err) + } + if earlierCheck != nil { + t.Fatal("initial administrative versions are supported", earlierCheck) + } + result, err := other.ExecContext(t.Context(), `UPDATE metadata SET value='2' WHERE key='schema:worker_retirements'`) + if err != nil { + t.Fatal(err) + } + if changed, err := result.RowsAffected(); err != nil || changed != 1 { + t.Fatal("retirement version did not advance exactly once", changed, err) + } + err = s.ensureProjectManagement(t.Context()) + if failure, ok := err.(*Error); !ok || failure.Code != "schema_unsupported" { + t.Fatal("management migration did not refuse newer retirement version", err) + } + if got := managementRows(t, other, `SELECT key FROM metadata WHERE key='schema:project_management'`); got != "[]" { + t.Fatal("management migration left version metadata") + } + var count int + if err = other.QueryRow(`SELECT count(*) FROM pragma_table_info('grants') WHERE name='can_manage'`).Scan(&count); err != nil || count != 0 { + t.Fatal("management migration left column", count, err) + } +} + +func TestAdministrationLaterFailurePreservesEarlierDomainCommit(t *testing.T) { + dir := filepath.Join(t.TempDir(), "db") + s, err := Open(t.Context(), dir) + if err != nil { + t.Fatal(err) + } + if err = s.Close(); err != nil { + t.Fatal(err) + } + db, err := sql.Open("sqlite", filepath.Join(dir, "firecontroller.sqlite")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + for _, query := range []string{ + `DELETE FROM metadata WHERE key IN ('schema:project_management','schema:worker_retirements')`, + `ALTER TABLE grants DROP COLUMN can_manage`, + `DROP TABLE worker_retirements`, + `CREATE TRIGGER reject_retirement_version BEFORE INSERT ON metadata WHEN NEW.key='schema:worker_retirements' BEGIN SELECT RAISE(ABORT,'synthetic retirement failure'); END`, + } { + if _, err = db.ExecContext(t.Context(), query); err != nil { + t.Fatal(err) + } + } + next, err := Open(t.Context(), dir) + if err == nil { + next.Close() + t.Fatal("startup ignored the retirement migration failure") + } + if failure, ok := err.(*Error); !ok || failure.Code != "storage_unavailable" { + t.Fatal("startup did not return the retirement SQL failure", err) + } + if got := managementRows(t, db, `SELECT key,value FROM metadata WHERE key IN ('schema:project_management','schema:worker_retirements') ORDER BY key`); got != `[["schema:project_management","1"]]` { + t.Fatal("migration metadata did not preserve only the earlier committed domain", got) + } + if got := managementRows(t, db, `SELECT name FROM pragma_table_info('grants') WHERE name='can_manage'`); got != `[["can_manage"]]` { + t.Fatal("earlier management schema change did not persist", got) + } + if got := managementRows(t, db, `SELECT name FROM sqlite_schema WHERE type='table' AND name='worker_retirements'`); got != "[]" { + t.Fatal("failed retirement domain left its table behind", got) + } +} + +func TestProjectManagementRealParentMigrationFailureRollsBack(t *testing.T) { + parent := os.Getenv("FC_ADMIN_PARENT_FIXTURE") + if parent == "" { + t.Skip("requires genuine pinned-parent binary fixture") + } + dir := filepath.Join(t.TempDir(), "source") + copyManagementFixture(t, filepath.Join(parent, "source"), dir) + db, err := sql.Open("sqlite", filepath.Join(dir, "firecontroller.sqlite")) + if err != nil { + t.Fatal(err) + } + defer db.Close() + before := managementRows(t, db, `SELECT * FROM grants ORDER BY credential_id,project_id`) + if _, err := db.Exec(`CREATE TRIGGER reject_management_version BEFORE INSERT ON metadata WHEN NEW.key='schema:project_management' BEGIN SELECT RAISE(ABORT,'synthetic migration failure'); END`); err != nil { + t.Fatal(err) + } + if next, err := Open(t.Context(), dir); err == nil { + next.Close() + t.Fatal("injected migration failure ignored") + } + if got := managementRows(t, db, `SELECT * FROM grants ORDER BY credential_id,project_id`); got != before { + t.Fatal("failed migration changed grants") + } + var columns, versions int + if err := db.QueryRow(`SELECT count(*) FROM pragma_table_info('grants') WHERE name='can_manage'`).Scan(&columns); err != nil { + t.Fatal(err) + } + if err := db.QueryRow(`SELECT count(*) FROM metadata WHERE key IN ('schema:project_management','schema:worker_retirements')`).Scan(&versions); err != nil { + t.Fatal(err) + } + if columns != 0 || versions != 0 { + t.Fatal("failed migration left schema or version", columns, versions) + } + if _, err := db.Exec(`DROP TRIGGER reject_management_version`); err != nil { + t.Fatal(err) + } + next, err := Open(t.Context(), dir) + if err != nil { + t.Fatal("retry after injected failure", err) + } + next.Close() +} diff --git a/internal/core/schema.go b/internal/core/schema.go index 9493cc96e..1d41b0a4d 100644 --- a/internal/core/schema.go +++ b/internal/core/schema.go @@ -34,7 +34,11 @@ func (s *Store) EnsureSchema(ctx context.Context, domain string, migrations ...[ // migration deadline and atomic rollback, including schema version metadata. // Work must honor the context and use bounded batches, with no filesystem, network or // provider calls, and must not commit or roll back the connection itself. -func (s *Store) EnsureSchemaWithBackfill(ctx context.Context, domain string, migrations [][]string, backfill func(context.Context, *sql.Conn) error) (resultErr error) { +func (s *Store) EnsureSchemaWithBackfill(ctx context.Context, domain string, migrations [][]string, backfill func(context.Context, *sql.Conn) error) error { + return s.ensureSchemaWithPreflight(ctx, domain, migrations, nil, backfill) +} + +func (s *Store) ensureSchemaWithPreflight(ctx context.Context, domain string, migrations [][]string, preflight, backfill func(context.Context, *sql.Conn) error) (resultErr error) { if domain == "" || len(migrations) == 0 { return Fail("schema_invalid", "A domain schema requires an identity and migrations.", 500) } @@ -70,6 +74,11 @@ func (s *Store) EnsureSchemaWithBackfill(ctx context.Context, domain string, mig } } }() + if preflight != nil { + if err = preflight(ctx, conn); err != nil { + return err + } + } key := "schema:" + domain var raw string version := 0 diff --git a/internal/core/store.go b/internal/core/store.go index f2d2c40c0..75a117850 100644 --- a/internal/core/store.go +++ b/internal/core/store.go @@ -120,6 +120,14 @@ func Open(ctx context.Context, dataDir string, options ...OpenOption) (*Store, e _ = s.Close() return nil, storageError(err) } + if err = s.ensureProjectManagement(ctx); err != nil { + _ = s.Close() + return nil, err + } + if err = s.ensureWorkerRetirements(ctx); err != nil { + _ = s.Close() + return nil, err + } return s, nil } diff --git a/internal/core/types.go b/internal/core/types.go index 78bdad0f4..c3213e73a 100644 --- a/internal/core/types.go +++ b/internal/core/types.go @@ -17,8 +17,10 @@ type Scope struct { tokenHash string instanceID string admin bool + instanceAdmin bool readOnly bool expiresAt time.Time + sessionManage bool sessionProject string } diff --git a/internal/core/worker_retirement.go b/internal/core/worker_retirement.go new file mode 100644 index 000000000..44bf2ee8a --- /dev/null +++ b/internal/core/worker_retirement.go @@ -0,0 +1,63 @@ +package core + +import ( + "context" + "database/sql" + "strings" + "time" + "unicode" + "unicode/utf8" +) + +func (s *Store) ensureWorkerRetirements(ctx context.Context) error { + return s.ensureSchemaWithPreflight(ctx, "worker_retirements", [][]string{{ + `CREATE TABLE worker_retirements(project_id TEXT NOT NULL REFERENCES projects(id),worker_id TEXT NOT NULL,retired_at TEXT NOT NULL,actor_id TEXT NOT NULL,PRIMARY KEY(project_id,worker_id),FOREIGN KEY(project_id,worker_id) REFERENCES workers(project_id,id))`, + }}, checkAdministrationVersions, nil) +} + +// CheckActiveWorker is for new coordination targets. CheckWorker and ordinary +// authorization intentionally retain access to historical worker identities. +func CheckActiveWorker(ctx context.Context, tx *sql.Tx, projectID, workerID string) error { + if err := CheckWorker(ctx, tx, projectID, workerID); err != nil { + return err + } + var retired bool + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM worker_retirements WHERE project_id=? AND worker_id=?)`, projectID, workerID).Scan(&retired); err != nil { + return storageError(err) + } + if retired { + return Fail("worker_retired", "This worker is retired; select an active worker for new coordination work.", 409) + } + return nil +} + +// RequireProjectManagementTx rechecks the actual authenticated management grant +// inside a mutation. Callers also pin the stronger scope before receipt replay. +func (s *Store) RequireProjectManagementTx(ctx context.Context, tx *sql.Tx, scope Scope) error { + return s.authorize(ctx, tx, scope, "admin") +} + +func ValidateWorkerRetirementsSnapshot(ctx context.Context, tx interface { + QueryContext(context.Context, string, ...any) (*sql.Rows, error) +}) error { + // Canonical UTC RFC3339Nano uses at most 30 bytes (four-digit year, + // nine fractional digits and Z). Bound bytes before values cross into Go; + // invalid sentinels preserve oversized rows so validation rejects them. + rows, err := tx.QueryContext(ctx, `SELECT CASE WHEN length(CAST(r.retired_at AS BLOB))<=30 THEN r.retired_at ELSE '' END,CASE WHEN length(CAST(r.actor_id AS BLOB))<=256 THEN r.actor_id ELSE '' END,w.id IS NOT NULL FROM worker_retirements r LEFT JOIN workers w ON w.project_id=r.project_id AND w.id=r.worker_id`) + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + var at, actor string + var workerExists bool + if err := rows.Scan(&at, &actor, &workerExists); err != nil { + return err + } + timestamp, err := time.Parse(time.RFC3339Nano, at) + if err != nil || timestamp.IsZero() || at != timestamp.UTC().Format(time.RFC3339Nano) || !workerExists || actor == "" || len(actor) > 256 || !utf8.ValidString(actor) || strings.TrimSpace(actor) != actor || strings.IndexFunc(actor, unicode.IsControl) >= 0 { + return Fail("storage_unavailable", "Stored worker retirement facts are invalid.", 500) + } + } + return rows.Err() +} diff --git a/internal/core/worker_retirement_bounds_test.go b/internal/core/worker_retirement_bounds_test.go new file mode 100644 index 000000000..1db967138 --- /dev/null +++ b/internal/core/worker_retirement_bounds_test.go @@ -0,0 +1,90 @@ +package core + +import ( + "context" + "database/sql" + "path/filepath" + "strings" + "testing" +) + +// Observe the actual SQL result, not just the final rejection: checking in Go +// after Scan would still materialize an unbounded attacker-controlled value. +type retirementBoundedReader struct { + db *sql.DB + t *testing.T + rows int +} + +func (r *retirementBoundedReader) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) { + rows, err := r.db.QueryContext(ctx, query, args...) + if err != nil { + return nil, err + } + for rows.Next() { + var at, actor string + var worker sql.NullString + if err := rows.Scan(&at, &actor, &worker); err != nil { + r.t.Fatal(err) + } + if len(at) > 30 || len(actor) > 256 { + r.t.Fatalf("SQL returned unbounded values: timestamp=%d actor=%d", len(at), len(actor)) + } + r.rows++ + } + err = rows.Err() + rows.Close() + if err != nil { + return nil, err + } + return r.db.QueryContext(ctx, query, args...) +} + +func TestWorkerRetirementSnapshotByteBounds(t *testing.T) { + const maximumTimestamp = "9999-12-31T23:59:59.999999999Z" + if len(maximumTimestamp) != 30 { + t.Fatal("incorrect canonical UTC timestamp bound") + } + for _, tc := range []struct { + name, at, actor string + valid bool + }{ + {"maximum", maximumTimestamp, strings.Repeat("a", 256), true}, + {"maximum_utf8", maximumTimestamp, strings.Repeat("é", 128), true}, + {"whole_second", "2026-11-01T00:00:00Z", "actor", true}, + {"timestamp_over_boundary", maximumTimestamp + "0", "actor", false}, + {"timestamp_large", strings.Repeat("t", 1<<20), "actor", false}, + {"actor_over_boundary", maximumTimestamp, strings.Repeat("a", 257), false}, + {"actor_utf8_over_boundary", maximumTimestamp, strings.Repeat("é", 129), false}, + {"actor_large", maximumTimestamp, strings.Repeat("a", 1<<20), false}, + {"actor_nul_large", maximumTimestamp, "a\x00" + strings.Repeat("a", 1<<20), false}, + } { + t.Run(tc.name, func(t *testing.T) { + store, err := Open(t.Context(), filepath.Join(t.TempDir(), "store")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + _, err = store.DB().ExecContext(t.Context(), `INSERT INTO projects(id,name,github_repository_id,repository) VALUES('project','Project',1,'owner/repo'); INSERT INTO workers(project_id,id,name) VALUES('project','valid','Valid'),('project','test','Test'); INSERT INTO worker_retirements VALUES('project','valid','2026-11-01T00:00:00Z','actor')`) + if err != nil { + t.Fatal(err) + } + _, err = store.DB().ExecContext(t.Context(), `INSERT INTO worker_retirements VALUES('project','test',?,?)`, tc.at, tc.actor) + if err != nil { + t.Fatal(err) + } + reader := &retirementBoundedReader{db: store.DB(), t: t} + err = ValidateWorkerRetirementsSnapshot(t.Context(), reader) + if reader.rows != 2 { + t.Fatal("SQL silently discarded retirement rows", reader.rows) + } + if tc.valid { + if err != nil { + t.Fatal("valid boundary rejected", err) + } + } else { + receiptCode(t, err, "storage_unavailable") + } + }) + } +} diff --git a/internal/core/worker_retirement_test.go b/internal/core/worker_retirement_test.go new file mode 100644 index 000000000..154097df6 --- /dev/null +++ b/internal/core/worker_retirement_test.go @@ -0,0 +1,65 @@ +package core + +import ( + "context" + "database/sql" + "path/filepath" + "testing" +) + +func TestWorkerRetirementCoreOnlyStartupAndHistoricalIdentity(t *testing.T) { + dir := filepath.Join(t.TempDir(), "store") + store, err := Open(t.Context(), dir) + if err != nil { + t.Fatal(err) + } + firstStore := store + closed := false + defer func() { + if !closed { + _ = firstStore.Close() + } + }() + err = store.BackgroundWrite(t.Context(), func(ctx context.Context, tx *sql.Tx) error { + if _, err := tx.ExecContext(ctx, `INSERT INTO projects(id,name,github_repository_id,repository) VALUES('project','Project',1,'owner/repo'); INSERT INTO workers(project_id,id,name) VALUES('project','worker','Worker')`); err != nil { + return err + } + if err := CheckActiveWorker(ctx, tx, "project", "worker"); err != nil { + return err + } + _, err := tx.ExecContext(ctx, `INSERT INTO worker_retirements(project_id,worker_id,retired_at,actor_id) VALUES('project','worker','2026-11-01T00:00:00Z','synthetic-actor')`) + return err + }) + if err != nil { + t.Fatal(err) + } + if err := store.Close(); err != nil { + t.Fatal(err) + } + closed = true + store, err = Open(t.Context(), dir) + if err != nil { + t.Fatal("retirement schema did not survive ordinary startup", err) + } + defer store.Close() + tx, err := store.DB().BeginTx(t.Context(), &sql.TxOptions{ReadOnly: true}) + if err != nil { + t.Fatal(err) + } + defer tx.Rollback() + if err := CheckWorker(t.Context(), tx, "project", "worker"); err != nil { + t.Fatal("historical identity was deleted", err) + } + receiptCode(t, CheckActiveWorker(t.Context(), tx, "project", "worker"), "worker_retired") + if err := ValidateWorkerRetirementsSnapshot(t.Context(), tx); err != nil { + t.Fatal(err) + } + var version string + if err := tx.QueryRowContext(t.Context(), `SELECT value FROM metadata WHERE key='schema:worker_retirements'`).Scan(&version); err != nil || version != "1" { + t.Fatal("retirement domain version missing", version, err) + } + var domains int + if err := tx.QueryRowContext(t.Context(), `SELECT count(*) FROM sqlite_schema WHERE name IN('jobs','notes','inbox_messages')`).Scan(&domains); err != nil || domains != 0 { + t.Fatal("active identity check required application domains", domains, err) + } +} diff --git a/internal/inbox/inbox.go b/internal/inbox/inbox.go index 818bd2a79..31e95a009 100644 --- a/internal/inbox/inbox.go +++ b/internal/inbox/inbox.go @@ -115,10 +115,10 @@ func (h *handler) send(w http.ResponseWriter, r *http.Request) { return } result, err := h.store.Mutate(r.Context(), scope, core.Mutation{Operation: "messages.send", Target: "collection", Key: key, Request: request}, func(ctx context.Context, tx *sql.Tx) (any, error) { - if err := core.CheckWorker(ctx, tx, scope.ProjectID, scope.WorkerID); err != nil { + if err := core.CheckActiveWorker(ctx, tx, scope.ProjectID, scope.WorkerID); err != nil { return nil, err } - if err := core.CheckWorker(ctx, tx, scope.ProjectID, request.RecipientWorkerID); err != nil { + if err := core.CheckActiveWorker(ctx, tx, scope.ProjectID, request.RecipientWorkerID); err != nil { return nil, err } id := core.NewID("msg") @@ -399,19 +399,44 @@ func (h *handler) transition(w http.ResponseWriter, r *http.Request, ack bool) { core.WriteError(w, err) return } - if scope.WorkerID == "" { - core.WriteError(w, core.Fail("validation_failed", "Select the recipient with X-FC-Worker.", http.StatusBadRequest)) - return - } if _, err := core.QueryKeys(r, "validation_failed"); err != nil { core.WriteError(w, err) return } - var request struct{} - if err := core.ReadJSON(w, r, &request); err != nil { + var request struct { + WorkerID string `json:"worker_id,omitempty"` + } + var input struct { + WorkerID json.RawMessage `json:"worker_id,omitempty"` + } + var body any = &input + if !ack { + body = &struct{}{} + } + if err := core.ReadJSON(w, r, body); err != nil { core.WriteError(w, err) return } + if input.WorkerID != nil && (json.Unmarshal(input.WorkerID, &request.WorkerID) != nil || !cleanID(request.WorkerID)) { + core.WriteError(w, core.Fail("validation_failed", "An explicit worker_id must identify the message recipient.", http.StatusBadRequest)) + return + } + recipientWorker := scope.WorkerID + if request.WorkerID != "" { + recipientWorker = request.WorkerID + } + if !cleanID(recipientWorker) { + core.WriteError(w, core.Fail("validation_failed", "Select the recipient with X-FC-Worker or an explicit worker_id for acknowledgement.", http.StatusBadRequest)) + return + } + onBehalf := recipientWorker != scope.WorkerID + if onBehalf { + if scope.WorkerID == "" { + core.WriteError(w, core.Fail("validation_failed", "Select the acting worker with X-FC-Worker for acknowledgement on behalf of another recipient.", http.StatusBadRequest)) + return + } + scope = scope.RequireAdministration() + } id := r.PathValue("message_id") operation, outcome := "messages.seen", "seen" if ack { @@ -423,26 +448,35 @@ func (h *handler) transition(w http.ResponseWriter, r *http.Request, ack bool) { return } result, err := h.store.Mutate(r.Context(), scope, core.Mutation{Operation: operation, Target: id, Key: key, Request: request}, func(ctx context.Context, tx *sql.Tx) (any, error) { + if onBehalf { + if err := h.store.RequireProjectManagementTx(ctx, tx, scope); err != nil { + return nil, err + } + } var conversationID, recipient string if err := tx.QueryRowContext(ctx, "SELECT conversation_id,recipient_worker_id FROM inbox_messages WHERE project_id=? AND id=?", scope.ProjectID, id).Scan(&conversationID, &recipient); err != nil { return nil, missing(err) } - if recipient != scope.WorkerID { + if recipient != recipientWorker { return nil, core.Fail("forbidden", "Only the message recipient can change receipt state.", http.StatusForbidden) } var seen, acknowledged bool var revision int64 - if err := tx.QueryRowContext(ctx, "SELECT seen,acknowledged,revision FROM inbox_recipient_state WHERE project_id=? AND message_id=? AND worker_id=?", scope.ProjectID, id, scope.WorkerID).Scan(&seen, &acknowledged, &revision); err != nil { + if err := tx.QueryRowContext(ctx, "SELECT seen,acknowledged,revision FROM inbox_recipient_state WHERE project_id=? AND message_id=? AND worker_id=?", scope.ProjectID, id, recipientWorker).Scan(&seen, &acknowledged, &revision); err != nil { return nil, err } if (ack && acknowledged) || (!ack && seen) { return receipt{ID: id, ConversationID: conversationID, Outcome: "unchanged"}, nil } acknowledged = acknowledged || ack - if _, err := tx.ExecContext(ctx, "UPDATE inbox_recipient_state SET seen=1,acknowledged=?,revision=revision+1 WHERE project_id=? AND message_id=? AND worker_id=?", acknowledged, scope.ProjectID, id, scope.WorkerID); err != nil { + if _, err := tx.ExecContext(ctx, "UPDATE inbox_recipient_state SET seen=1,acknowledged=?,revision=revision+1 WHERE project_id=? AND message_id=? AND worker_id=?", acknowledged, scope.ProjectID, id, recipientWorker); err != nil { return nil, err } - if err := core.AppendEvent(ctx, tx, scope, "message."+outcome, id, revision+1, map[string]string{"conversation_id": conversationID, "recipient_worker_id": scope.WorkerID}); err != nil { + payload := map[string]string{"conversation_id": conversationID, "recipient_worker_id": recipientWorker} + if onBehalf { + payload["actor_worker_id"] = scope.WorkerID + } + if err := core.AppendEvent(ctx, tx, scope, "message."+outcome, id, revision+1, payload); err != nil { return nil, err } return receipt{ID: id, ConversationID: conversationID, Outcome: outcome}, nil diff --git a/internal/inbox/worker_retirement_test.go b/internal/inbox/worker_retirement_test.go new file mode 100644 index 000000000..51086a6fb --- /dev/null +++ b/internal/inbox/worker_retirement_test.go @@ -0,0 +1,227 @@ +package inbox_test + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/inbox" + "github.com/benhook1013/FireController/internal/server" + "io/fs" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestWorkerRetirementRealParentEmptyACKAndRetiredSendReplay(t *testing.T) { + root := os.Getenv("FC_ADMIN_PARENT_FIXTURE") + if root == "" { + t.Skip("requires actual parent-produced receipts") + } + body, err := os.ReadFile(filepath.Join(root, "fixture.json")) + if err != nil { + t.Fatal(err) + } + var f map[string]string + if json.Unmarshal(body, &f) != nil { + t.Fatal("fixture metadata") + } + dir := filepath.Join(t.TempDir(), "copy") + err = filepath.WalkDir(filepath.Join(root, "source"), func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + rel, err := filepath.Rel(filepath.Join(root, "source"), path) + if err != nil { + return err + } + dest := filepath.Join(dir, rel) + if d.IsDir() { + return os.MkdirAll(dest, 0700) + } + b, err := os.ReadFile(path) + if err != nil { + return err + } + return os.WriteFile(dest, b, 0600) + }) + if err != nil { + t.Fatal(err) + } + s, err := core.Open(t.Context(), dir) + if err != nil { + t.Fatal(err) + } + defer s.Close() + mux := server.New(s) + inbox.Register(mux, s) + call := func(path, key, body string) *httptest.ResponseRecorder { + r := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) + r.Header.Set("Authorization", "Bearer "+f["token"]) + r.Header.Set("X-FC-Worker", f["worker"]) + r.Header.Set("Idempotency-Key", key) + r.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + mux.ServeHTTP(w, r) + return w + } + base := "/api/v1/projects/" + f["project"] + var before int + if err := s.DB().QueryRow(`SELECT count(*) FROM receipts`).Scan(&before); err != nil { + t.Fatal(err) + } + w := call(base+"/messages/"+f["message"]+"/ack", "parent-empty-ack", "{}") + if w.Code != 200 || w.Body.String() != f["ack_response"] { + t.Fatal("legacy ACK changed", w.Code, w.Body.String()) + } + explicit, _ := json.Marshal(map[string]string{"worker_id": f["worker"]}) + w = call(base+"/messages/"+f["message"]+"/ack", "parent-empty-ack", string(explicit)) + if w.Code != 409 { + t.Fatal("different body reused parent receipt", w.Code) + } + var after int + s.DB().QueryRow(`SELECT count(*) FROM receipts`).Scan(&after) + if before != after { + t.Fatal("replay mutated receipts") + } + var sendKey, original string + if err := s.DB().QueryRow(`SELECT key,response_json FROM receipts WHERE project_id=? AND operation='messages.send'`, f["project"]).Scan(&sendKey, &original); err != nil { + t.Fatal(err) + } + if _, err := s.DB().Exec(`INSERT INTO worker_retirements VALUES(?,?, '2026-11-01T00:00:00Z','synthetic-actor')`, f["project"], f["worker"]); err != nil { + t.Fatal(err) + } + message, _ := json.Marshal(map[string]string{"recipient_worker_id": f["worker"], "body": "Retained message with literal "}) + w = call(base+"/messages", sendKey, string(message)) + if w.Code != 201 || strings.TrimSpace(w.Body.String()) != original { + t.Fatal("retired sender lost exact history", w.Code, w.Body.String(), original) + } + w = call(base+"/messages", "new-after-retirement", string(message)) + if w.Code != 409 || !strings.Contains(w.Body.String(), "worker_retired") { + t.Fatal("new retired send admitted", w.Code, w.Body.String()) + } +} + +func TestWorkerRetirementACKRequiresActingWorker(t *testing.T) { + for _, tc := range []struct { + name string + onBehalf bool + explicitRecipient bool + }{ + {name: "manager", onBehalf: true, explicitRecipient: true}, + {name: "administrator", onBehalf: true, explicitRecipient: true}, + {name: "writer-default"}, + {name: "writer-explicit", explicitRecipient: true}, + } { + t.Run(tc.name, func(t *testing.T) { + f := setup(t) + token := f.clientA + switch tc.name { + case "manager": + token = "synthetic-ack-manager-token" + f.grant(f.a, token, []string{"manage"}) + case "administrator": + token = f.admin + } + actor := f.recipient + if tc.onBehalf { + actor = f.sender + } + body := map[string]string{} + if tc.explicitRecipient { + body["worker_id"] = f.recipient + } + sent := f.send(f.a, f.clientA, f.sender, f.recipient, "Synthetic pending acknowledgement", "", "send") + path := f.path(f.a, "messages/"+sent.ID+"/ack") + before := f.receiptStateSnapshot(f.a, sent.ID, f.recipient) + if before.seen || before.acknowledged || before.revision != 1 { + t.Fatalf("unexpected initial recipient state: %+v", before) + } + + errorCode(t, f.request(http.MethodPost, path, token, "", "ack", body), http.StatusBadRequest, "validation_failed") + if got := f.receiptStateSnapshot(f.a, sent.ID, f.recipient); got != before { + t.Fatalf("missing acting worker changed durable state: before=%+v after=%+v", before, got) + } + if tc.onBehalf { + errorCode(t, f.request(http.MethodPost, path, f.clientA, actor, "writer-ack", body), http.StatusForbidden, "forbidden") + if got := f.receiptStateSnapshot(f.a, sent.ID, f.recipient); got != before { + t.Fatalf("ordinary writer changed another recipient's state: %+v", got) + } + } + + // A rejected request must not reserve its key or poison a corrected retry. + first := f.request(http.MethodPost, path, token, actor, "ack", body) + var result receipt + decode(t, first, http.StatusOK, &result) + if result != (receipt{ID: sent.ID, ConversationID: sent.ConversationID, Outcome: "acknowledged"}) { + t.Fatalf("unexpected acknowledgement receipt: %+v", result) + } + want := before + want.receipts++ + want.events++ + want.seen, want.acknowledged = true, true + want.revision++ + if got := f.receiptStateSnapshot(f.a, sent.ID, f.recipient); got != want { + t.Fatalf("acknowledgement did not commit exactly one transition: want=%+v got=%+v", want, got) + } + + var eventActor, payloadJSON, principal string + var revision int64 + if err := f.store.DB().QueryRow(`SELECT actor_id,payload_json,revision FROM events WHERE project_id=? AND resource_id=? AND event_type='message.acknowledged'`, f.a, sent.ID).Scan(&eventActor, &payloadJSON, &revision); err != nil { + t.Fatal(err) + } + sum := sha256.Sum256([]byte(token)) + if err := f.store.DB().QueryRow(`SELECT principal_id FROM credentials WHERE token_sha256=?`, hex.EncodeToString(sum[:])).Scan(&principal); err != nil { + t.Fatal(err) + } + var payload map[string]string + if err := json.Unmarshal([]byte(payloadJSON), &payload); err != nil { + t.Fatal(err) + } + if eventActor != principal || revision != want.revision || payload["recipient_worker_id"] != f.recipient || payload["conversation_id"] != sent.ConversationID { + t.Fatalf("acknowledgement lost principal or recipient attribution: actor=%q revision=%d payload=%v", eventActor, revision, payload) + } + actingWorker, hasActingWorker := payload["actor_worker_id"] + if tc.onBehalf && (!hasActingWorker || actingWorker != actor) || !tc.onBehalf && hasActingWorker { + t.Fatalf("acting-worker audit attribution changed: %v", payload) + } + + replay := f.request(http.MethodPost, path, token, actor, "ack", body) + decode(t, replay, http.StatusOK, nil) + if replay.Body.String() != first.Body.String() { + t.Fatal("exact-key replay changed the original acknowledgement receipt") + } + if got := f.receiptStateSnapshot(f.a, sent.ID, f.recipient); got != want { + t.Fatalf("exact-key replay changed durable state: %+v", got) + } + errorCode(t, f.request(http.MethodPost, path, token, "", "ack", body), http.StatusBadRequest, "validation_failed") + if got := f.receiptStateSnapshot(f.a, sent.ID, f.recipient); got != want { + t.Fatalf("replay without acting worker changed durable state: %+v", got) + } + }) + } +} + +type receiptStateSnapshot struct { + receipts, events int + seen, acknowledged bool + revision int64 +} + +func (f *fixture) receiptStateSnapshot(project, message, worker string) receiptStateSnapshot { + f.t.Helper() + var snapshot receiptStateSnapshot + if err := f.store.DB().QueryRow(`SELECT count(*) FROM receipts`).Scan(&snapshot.receipts); err != nil { + f.t.Fatal(err) + } + if err := f.store.DB().QueryRow(`SELECT count(*) FROM events`).Scan(&snapshot.events); err != nil { + f.t.Fatal(err) + } + if err := f.store.DB().QueryRow(`SELECT seen,acknowledged,revision FROM inbox_recipient_state WHERE project_id=? AND message_id=? AND worker_id=?`, project, message, worker).Scan(&snapshot.seen, &snapshot.acknowledged, &snapshot.revision); err != nil { + f.t.Fatal(err) + } + return snapshot +} diff --git a/internal/jobs/jobs.go b/internal/jobs/jobs.go index 6479bc2dd..6c0b8b525 100644 --- a/internal/jobs/jobs.go +++ b/internal/jobs/jobs.go @@ -148,7 +148,7 @@ func createJob(store *core.Store) http.HandlerFunc { Operation: "jobs.create", Target: "jobs", Key: key, Request: req, }, func(ctx context.Context, tx *sql.Tx) (any, error) { if req.WorkerID != "" { - if err := core.CheckWorker(ctx, tx, scope.ProjectID, req.WorkerID); err != nil { + if err := core.CheckActiveWorker(ctx, tx, scope.ProjectID, req.WorkerID); err != nil { return nil, err } } @@ -327,7 +327,11 @@ func editJob(store *core.Store) http.HandlerFunc { next.Status = *req.Status } if next.WorkerID != "" { - if err := core.CheckWorker(ctx, tx, scope.ProjectID, next.WorkerID); err != nil { + checkWorker := core.CheckWorker + if next.WorkerID != current.WorkerID || next.Status != "completed" { + checkWorker = core.CheckActiveWorker + } + if err := checkWorker(ctx, tx, scope.ProjectID, next.WorkerID); err != nil { return nil, err } } diff --git a/internal/jobs/notes.go b/internal/jobs/notes.go index 29ae32c88..6fd51ae1b 100644 --- a/internal/jobs/notes.go +++ b/internal/jobs/notes.go @@ -159,17 +159,26 @@ func readNote(ctx context.Context, tx *sql.Tx, project, id string) (note, error) } func checkNoteTargets(ctx context.Context, tx *sql.Tx, n note) error { if n.WorkerID != "" { - if err := primaryWorker(ctx, tx, n.ProjectID, n.WorkerID); err != nil { + check := primaryWorker + if n.Status == "pending" { + check = activePrimaryWorker + } + if err := check(ctx, tx, n.ProjectID, n.WorkerID); err != nil { return err } } if n.JobID != "" { - var exists int - err := tx.QueryRowContext(ctx, `SELECT 1 FROM jobs WHERE project_id=? AND id=?`, n.ProjectID, n.JobID).Scan(&exists) + var assigned string + err := tx.QueryRowContext(ctx, `SELECT COALESCE(worker_id,'') FROM jobs WHERE project_id=? AND id=?`, n.ProjectID, n.JobID).Scan(&assigned) if errors.Is(err, sql.ErrNoRows) { return core.Fail("job_not_found", "The target job is unavailable in this project.", 404) } - return err + if err != nil { + return err + } + if n.Status == "pending" && assigned != "" { + return core.CheckActiveWorker(ctx, tx, n.ProjectID, assigned) + } } return nil } diff --git a/internal/jobs/primary.go b/internal/jobs/primary.go index 7fb24a6d4..9e5afcbf6 100644 --- a/internal/jobs/primary.go +++ b/internal/jobs/primary.go @@ -58,6 +58,16 @@ func primaryWorker(ctx context.Context, tx *sql.Tx, project, worker string) erro } return err } + +func activePrimaryWorker(ctx context.Context, tx *sql.Tx, project, worker string) error { + err := core.CheckActiveWorker(ctx, tx, project, worker) + var failure *core.Error + if errors.As(err, &failure) && failure.Code == "not_found" { + return core.Fail("worker_not_found", "The target worker is unavailable in this project.", 404) + } + return err +} + func primaryAssignment(ctx context.Context, tx *sql.Tx, project, worker, job string) error { var assigned string err := tx.QueryRowContext(ctx, `SELECT COALESCE(worker_id,'') FROM jobs WHERE project_id=? AND id=?`, project, job).Scan(&assigned) @@ -162,7 +172,7 @@ func replacePrimaryJob(store *core.Store) http.HandlerFunc { return } result, err := store.Mutate(r.Context(), scope, core.Mutation{Operation: "workers.primary-job", Target: worker, Key: key, Request: req}, func(ctx context.Context, tx *sql.Tx) (any, error) { - if err := primaryWorker(ctx, tx, scope.ProjectID, worker); err != nil { + if err := activePrimaryWorker(ctx, tx, scope.ProjectID, worker); err != nil { return nil, err } current, err := readPrimaryJob(ctx, tx, scope.ProjectID, worker) diff --git a/internal/jobs/worker_pause.go b/internal/jobs/worker_pause.go index be3238594..cf32cc310 100644 --- a/internal/jobs/worker_pause.go +++ b/internal/jobs/worker_pause.go @@ -132,7 +132,7 @@ func replaceWorkerPause(store *core.Store) http.HandlerFunc { return } result, err := store.Mutate(r.Context(), scope, core.Mutation{Operation: "workers.pause", Target: worker, Key: key, Request: req}, func(ctx context.Context, tx *sql.Tx) (any, error) { - if err := primaryWorker(ctx, tx, scope.ProjectID, worker); err != nil { + if err := activePrimaryWorker(ctx, tx, scope.ProjectID, worker); err != nil { return nil, err } current, err := readWorkerPause(ctx, tx, scope.ProjectID, worker) diff --git a/internal/jobs/worker_retirement_test.go b/internal/jobs/worker_retirement_test.go new file mode 100644 index 000000000..2b93db084 --- /dev/null +++ b/internal/jobs/worker_retirement_test.go @@ -0,0 +1,81 @@ +package jobs_test + +import ( + "fmt" + "reflect" + "testing" +) + +func TestWorkerRetirementFreezesFocusAndPauseButPreservesReadsAndReplay(t *testing.T) { + a := setupAPI(t) + p := a.createProject("Retirement focus", "owner/retirement-focus") + actor := a.createWorker(p, "actor") + target := a.createWorker(p, "target") + token := a.grant(p, "synthetic-retirement-focus-writer", "read", "write") + base := "/api/v1/projects/" + p + var completed [2]string + for i := range completed { + w := noteCall(a, "POST", base+"/jobs", token, actor, fmt.Sprint("completed-job-", i), map[string]any{"title": "Historical work", "status": "completed", "worker_id": target}) + noteOK(t, w, 201) + var created receipt + decodeResponse(t, w, &created) + completed[i] = created.ID + } + focusPath := base + "/workers/" + target + "/primary-job" + pausePath := base + "/workers/" + target + "/pause" + focusRequest := map[string]any{"expected_revision": 0, "job_id": completed[0]} + pauseRequest := map[string]any{"expected_revision": 0, "paused": true, "reason": "Retaining historical pause"} + focusReceipt := noteCall(a, "PUT", focusPath, token, actor, "old-focus", focusRequest) + pauseReceipt := noteCall(a, "PUT", pausePath, token, actor, "old-pause", pauseRequest) + noteOK(t, focusReceipt, 200) + noteOK(t, pauseReceipt, 200) + if _, err := a.store.DB().Exec(`INSERT INTO worker_retirements VALUES(?,?, '2026-11-01T00:00:00Z','synthetic-actor')`, p, target); err != nil { + t.Fatal(err) + } + before := pauseCounts(t, a) + for i, req := range []map[string]any{{"expected_revision": 1, "job_id": completed[1]}, {"expected_revision": 1, "job_id": ""}} { + noteError(t, noteCall(a, "PUT", focusPath, token, actor, fmt.Sprint("new-focus-", i), req), 409, "worker_retired") + } + noteError(t, noteCall(a, "PUT", pausePath, token, actor, "new-pause", map[string]any{"expected_revision": 1, "paused": false, "reason": ""}), 409, "worker_retired") + if !reflect.DeepEqual(before, pauseCounts(t, a)) { + t.Fatal("retired target mutation changed durable coordination state") + } + for _, path := range []string{focusPath, focusPath + "/history", pausePath, pausePath + "/history"} { + noteOK(t, noteCall(a, "GET", path, token, actor, "", nil), 200) + } + for _, replay := range []struct { + path, key, expected string + request map[string]any + }{{focusPath, "old-focus", focusReceipt.Body.String(), focusRequest}, {pausePath, "old-pause", pauseReceipt.Body.String(), pauseRequest}} { + got := noteCall(a, "PUT", replay.path, token, actor, replay.key, replay.request) + noteOK(t, got, 200) + if got.Body.String() != replay.expected { + t.Fatal("retirement changed an exact prior receipt") + } + } +} + +func TestWorkerRetirementPendingNotesAndReopenedJobsRefuseHistoricalTarget(t *testing.T) { + a := setupAPI(t) + p := a.createProject("Retirement", "owner/retirement") + actor := a.createWorker(p, "actor") + target := a.createWorker(p, "target") + token := a.grant(p, "synthetic-retirement-writer", "read", "write") + base := "/api/v1/projects/" + p + w := noteCall(a, "POST", base+"/jobs", token, actor, "completed-job", map[string]any{"title": "Historical work", "status": "completed", "worker_id": target}) + noteOK(t, w, 201) + var created receipt + decodeResponse(t, w, &created) + if _, err := a.store.DB().Exec(`INSERT INTO worker_retirements VALUES(?,?, '2026-11-01T00:00:00Z','synthetic-actor')`, p, target); err != nil { + t.Fatal(err) + } + for i, req := range []map[string]any{{"expected_revision": 1, "status": "active"}, {"expected_revision": 1, "worker_id": target, "status": "parked"}} { + noteError(t, noteCall(a, "PATCH", base+"/jobs/"+created.ID, token, actor, fmt.Sprint("reopen-", i), req), 409, "worker_retired") + } + for i, req := range []map[string]any{{"worker_id": target, "job_id": "", "phase": "", "kind": "reminder", "body": "Pending direct note"}, {"job_id": created.ID, "worker_id": "", "phase": "", "kind": "reminder", "body": "Pending historical job note"}} { + noteError(t, noteCall(a, "POST", base+"/notes", token, actor, fmt.Sprint("note-", i), req), 409, "worker_retired") + } + // Editing completed history must remain possible without making new work. + noteOK(t, noteCall(a, "PATCH", base+"/jobs/"+created.ID, token, actor, "history-title", map[string]any{"expected_revision": 1, "title": "Updated historical title"}), 200) + noteOK(t, noteCall(a, "GET", base+"/jobs/"+created.ID, token, actor, "", nil), 200) +} diff --git a/internal/mcpadapter/adapter_test.go b/internal/mcpadapter/adapter_test.go index 5617b6333..5511d5d0c 100644 --- a/internal/mcpadapter/adapter_test.go +++ b/internal/mcpadapter/adapter_test.go @@ -158,6 +158,38 @@ func allDiscoveredTools(t *testing.T, session *mcp.ClientSession) (*mcp.ListTool return nil, nil } +func TestAdministrationDiscoveryDescribesAuthority(t *testing.T) { + path := profiles(t, map[string]profile.Context{"alpha": localContext()}, "missing-private-token") + for _, version := range mcp.SupportedProtocolVersions() { + t.Run(version, func(t *testing.T) { + cs := connect(t, adapter(t, path, "alpha"), version) + tools, err := allDiscoveredTools(t, cs) + if err != nil { + t.Fatal(err) + } + contracts := map[string][]string{ + "inbox_list": {"bound worker", "worker_id", "project read permission", "acting identity unchanged", "never mark seen or acknowledged"}, + "inbox_ack": {"bound recipient", "worker_id", "another recipient requires project management", "acting identity unchanged", "also establishing seen", "supplied key"}, + "publication_configuration_read": {"Requires instance administration"}, + "publication_preview": {"Requires instance administration"}, + "publication_apply": {"Requires instance administration"}, + "publication_unpublish": {"Requires instance administration"}, + } + for _, tool := range tools.Tools { + for _, fragment := range contracts[tool.Name] { + if !strings.Contains(tool.Description, fragment) { + t.Errorf("%s discovery omits %q: %s", tool.Name, fragment, tool.Description) + } + } + delete(contracts, tool.Name) + } + if len(contracts) != 0 { + t.Fatal("authority-described tools missing from discovery", contracts) + } + }) + } +} + func TestDiscoveryAndLocalContextAcrossSDKProtocolVersions(t *testing.T) { c := localContext() path := profiles(t, map[string]profile.Context{"alpha": c}, "missing-private-token") @@ -222,6 +254,9 @@ func TestDiscoveryAndLocalContextAcrossSDKProtocolVersions(t *testing.T) { expected["review_source_ci_assess"], expected["review_source_readiness"] = true, true expected["review_source_refresh"], expected["review_source_refresh_read"], expected["review_source_policy_assess"] = true, true, true expected["review_checkpoint_publish"], expected["review_checkpoint_read"], expected["review_checkpoint_recover"] = true, true, true + for _, name := range []string{"review_policy_read", "review_policy_configure", "review_execution_configure", "worker_create", "worker_retirement_read", "worker_retire", "project_credential_grant", "project_credential_update", "project_credential_revoke", "presentation_replace", "presentation_history", "presentation_revision_read", "publication_configuration_read", "publication_preview", "publication_apply", "publication_unpublish", "review_import_preview", "review_import_apply", "review_transfer_preview", "review_transfer_apply"} { + expected[name] = true + } if len(first.Tools) != len(expected) { t.Fatalf("first discovery page has %d tools, expected complete inventory of %d", len(first.Tools), len(expected)) } @@ -242,14 +277,35 @@ func TestDiscoveryAndLocalContextAcrossSDKProtocolVersions(t *testing.T) { writes["review_finding_decide"], writes["review_finding_fix"], writes["review_source_finalize"] = true, true, true writes["review_finding_route"], writes["review_route_decide"], writes["review_route_fix"] = true, true, true writes["review_checkpoint_publish"], writes["review_checkpoint_recover"] = true, true + for _, name := range []string{"review_policy_configure", "review_execution_configure", "worker_create", "worker_retire", "project_credential_grant", "project_credential_update", "project_credential_revoke", "presentation_replace", "publication_apply", "publication_unpublish", "review_import_apply", "review_transfer_apply"} { + writes[name] = true + } for _, tool := range tools.Tools { if !expected[tool.Name] { t.Fatalf("unexpected tool %q", tool.Name) } delete(expected, tool.Name) a := tool.Annotations - if a == nil || a.ReadOnlyHint == writes[tool.Name] || !a.IdempotentHint || a.DestructiveHint == nil || *a.DestructiveHint != (tool.Name == "review_operation_control" || tool.Name == "review_round_adoption_apply" || tool.Name == "review_obligations_import_apply" || tool.Name == "review_obligation_retarget" || tool.Name == "review_obligation_resolve" || tool.Name == "review_rounds_configure" || tool.Name == "review_queue_edit" || tool.Name == "worker_pause_replace" || tool.Name == "job_primary_replace" || tool.Name == "map_entry_replace" || tool.Name == "job_workstream_replace" || tool.Name == "note_update" || tool.Name == "job_edit" || tool.Name == "job_checklist_replace" || tool.Name == "review_finding_decide" || tool.Name == "review_finding_fix" || tool.Name == "review_finding_route" || tool.Name == "review_route_decide" || tool.Name == "review_route_fix") || a.OpenWorldHint == nil || *a.OpenWorldHint != (tool.Name == "wait_for_ci" || tool.Name == "review_start" || tool.Name == "review_request" || tool.Name == "review_source_refresh" || tool.Name == "review_checkpoint_publish" || tool.Name == "review_checkpoint_recover") { - t.Fatal("untruthful operation annotation") + if a == nil { + t.Fatalf("%s: missing annotations", tool.Name) + } + if a.ReadOnlyHint != !writes[tool.Name] { + t.Errorf("%s readOnlyHint: want %v, got %v", tool.Name, !writes[tool.Name], a.ReadOnlyHint) + } + if !a.IdempotentHint { + t.Errorf("%s idempotentHint: want true, got false", tool.Name) + } + wantDestructive := tool.Name == "review_operation_control" || tool.Name == "review_policy_configure" || tool.Name == "review_execution_configure" || tool.Name == "worker_retire" || tool.Name == "project_credential_update" || tool.Name == "project_credential_revoke" || tool.Name == "presentation_replace" || tool.Name == "publication_apply" || tool.Name == "publication_unpublish" || tool.Name == "review_import_apply" || tool.Name == "review_transfer_apply" || tool.Name == "review_round_adoption_apply" || tool.Name == "review_obligations_import_apply" || tool.Name == "review_obligation_retarget" || tool.Name == "review_obligation_resolve" || tool.Name == "review_rounds_configure" || tool.Name == "review_queue_edit" || tool.Name == "worker_pause_replace" || tool.Name == "job_primary_replace" || tool.Name == "map_entry_replace" || tool.Name == "job_workstream_replace" || tool.Name == "note_update" || tool.Name == "job_edit" || tool.Name == "job_checklist_replace" || tool.Name == "review_finding_decide" || tool.Name == "review_finding_fix" || tool.Name == "review_finding_route" || tool.Name == "review_route_decide" || tool.Name == "review_route_fix" + if a.DestructiveHint == nil { + t.Errorf("%s destructiveHint: want %v, got nil", tool.Name, wantDestructive) + } else if *a.DestructiveHint != wantDestructive { + t.Errorf("%s destructiveHint: want %v, got %v", tool.Name, wantDestructive, *a.DestructiveHint) + } + wantOpen := tool.Name == "wait_for_ci" || tool.Name == "review_start" || tool.Name == "review_request" || tool.Name == "review_source_refresh" || tool.Name == "review_checkpoint_publish" || tool.Name == "review_checkpoint_recover" + if a.OpenWorldHint == nil { + t.Errorf("%s openWorldHint: want %v, got nil", tool.Name, wantOpen) + } else if *a.OpenWorldHint != wantOpen { + t.Errorf("%s openWorldHint: want %v, got %v", tool.Name, wantOpen, *a.OpenWorldHint) } data, _ := json.Marshal(tool.InputSchema) if strings.Contains(string(data), "profile") || strings.Contains(string(data), "project_id") { diff --git a/internal/mcpadapter/adoption.go b/internal/mcpadapter/adoption.go index 55b952ebc..5b5045dbf 100644 --- a/internal/mcpadapter/adoption.go +++ b/internal/mcpadapter/adoption.go @@ -39,12 +39,12 @@ type adoptionSpec struct { } var adoptionSpecs = []adoptionSpec{ - {"review_round_adoption_preview", "Preview the existing native round-adoption document against its original-source and current revision guards; no live reviews are requested.", []string{"document"}, []string{"document"}, false, false, false}, - {"review_round_adoption_apply", "Apply the exact previewed native round-adoption document with preview_sha256 and explicit key. Preserves retained attribution and accounting rules; tooling access is not review authorization.", []string{"document", "preview_sha256", "idempotency_key"}, []string{"document", "preview_sha256", "idempotency_key"}, true, true, false}, + {"review_round_adoption_preview", "Preview the existing native round-adoption document against its original-source and current revision guards; no live reviews are requested. Requires project management or instance administration and a valid project worker.", []string{"document"}, []string{"document"}, false, false, false}, + {"review_round_adoption_apply", "Apply the exact previewed native round-adoption document with preview_sha256 and explicit key. Preserves retained attribution and accounting rules; tooling access is not review authorization. Requires project management or instance administration and a valid project worker.", []string{"document", "preview_sha256", "idempotency_key"}, []string{"document", "preview_sha256", "idempotency_key"}, true, true, false}, {"review_obligations_list", "Read one compact carried-obligation page, optionally scoped to pull_number and open/resolved status. Full bodies require review_obligation_read.", []string{"pull_number", "status", "limit", "cursor"}, nil, false, false, false}, {"review_obligation_read", "Read one explicit retained carried obligation and original evidence, without marking it resolved.", []string{"obligation_id"}, []string{"obligation_id"}, false, false, false}, - {"review_obligations_import_preview", "Preview one strict native carried-obligation batch, preserving original evidence and provenance; no application or new review.", []string{"document"}, []string{"document"}, false, false, false}, - {"review_obligations_import_apply", "Apply the exact previewed carried-obligation batch with preview_sha256 and explicit key. Existing source conflicts and evidence requirements remain enforced.", []string{"document", "preview_sha256", "idempotency_key"}, []string{"document", "preview_sha256", "idempotency_key"}, true, true, false}, + {"review_obligations_import_preview", "Preview one strict native carried-obligation batch, preserving original evidence and provenance; no application or new review. Requires project management or instance administration and a valid project worker.", []string{"document"}, []string{"document"}, false, false, false}, + {"review_obligations_import_apply", "Apply the exact previewed carried-obligation batch with preview_sha256 and explicit key. Existing source conflicts and evidence requirements remain enforced. Requires project management or instance administration and a valid project worker.", []string{"document", "preview_sha256", "idempotency_key"}, []string{"document", "preview_sha256", "idempotency_key"}, true, true, false}, {"review_obligation_retarget", "Change the receiving PR of one open carried route with expected_revision, explicit target_pull_number (zero means unassigned backlog), reason and key. Preserves original provenance and open status; no provider work or resolution. Findings/results cannot be retargeted.", []string{"obligation_id", "expected_revision", "target_pull_number", "reason", "idempotency_key"}, []string{"obligation_id", "expected_revision", "target_pull_number", "reason", "idempotency_key"}, true, true, false}, {"review_obligation_resolve", "Resolve one carried obligation using the native {expected_revision,reason,evidence} document and explicit key. Requires a real evidence-backed resolution; grants no review credit.", []string{"obligation_id", "document", "idempotency_key"}, []string{"obligation_id", "document", "idempotency_key"}, true, true, false}, } diff --git a/internal/mcpadapter/arguments.go b/internal/mcpadapter/arguments.go index 8a87f1de1..5554bf7b8 100644 --- a/internal/mcpadapter/arguments.go +++ b/internal/mcpadapter/arguments.go @@ -12,6 +12,11 @@ import ( "github.com/benhook1013/FireController/internal/strictjson" ) +type workersInput struct { + Limit *int `json:"limit,omitempty"` + Cursor string `json:"cursor,omitempty"` + IncludeRetired bool `json:"include_retired,omitempty"` +} type pageInput struct { Limit *int `json:"limit,omitempty"` Cursor string `json:"cursor,omitempty"` @@ -36,6 +41,7 @@ type historyInput struct { Cursor string `json:"cursor,omitempty"` } type inboxInput struct { + WorkerID string `json:"worker_id,omitempty"` Limit *int `json:"limit,omitempty"` Cursor string `json:"cursor,omitempty"` Unread bool `json:"unread,omitempty"` @@ -128,7 +134,7 @@ func parseArguments(name string, data json.RawMessage) (arguments, error) { case "context", "doctor", "presentation_read": dst = &struct{}{} case "workers_list": - dst = new(pageInput) + dst = new(workersInput) case "jobs_list": dst = new(jobsInput) case "jobs_assigned": @@ -152,6 +158,8 @@ func parseArguments(name string, data json.RawMessage) (arguments, error) { return args, invalidArguments() } switch v := dst.(type) { + case *workersInput: + limit, args.cursor, args.includeRetired = v.Limit, v.Cursor, v.IncludeRetired case *pageInput: limit, args.cursor = v.Limit, v.Cursor case *jobsInput: @@ -163,6 +171,10 @@ func parseArguments(name string, data json.RawMessage) (arguments, error) { case *historyInput: limit, args.cursor, args.id = v.Limit, v.Cursor, v.JobID case *inboxInput: + if name != "inbox_list" && v.WorkerID != "" { + return args, invalidArguments() + } + args.worker = v.WorkerID limit, args.cursor, args.unread, args.unack = v.Limit, v.Cursor, v.Unread, v.Unacknowledged case *inboxEventsInput: limit, args.cursor, waitMS = v.Limit, v.Cursor, v.WaitMS @@ -321,7 +333,28 @@ func mutationArguments(name string, data json.RawMessage) (arguments, error) { } args.key = input.Key args.send = client.SendMessageRequest{RecipientWorkerID: input.Recipient, Body: input.Body, ReplyToMessageID: input.Reply} - case "inbox_seen", "inbox_ack": + case "inbox_ack": + var fields map[string]json.RawMessage + if json.Unmarshal(data, &fields) != nil { + return args, invalidArguments() + } + if v, ok := fields["worker_id"]; ok { + var id string + if json.Unmarshal(v, &id) != nil || !validID(id) { + return args, invalidArguments() + } + } + var input struct { + Key string `json:"idempotency_key"` + ID string `json:"message_id"` + Worker string `json:"worker_id,omitempty"` + } + if strictjson.Decode(data, &input) != nil || !validKey(input.Key) || !validID(input.ID) || input.Worker != "" && !validID(input.Worker) { + return args, invalidArguments() + } + args.key, args.id, args.worker = input.Key, input.ID, input.Worker + return args, nil + case "inbox_seen": var input struct { Key string `json:"idempotency_key"` ID string `json:"message_id"` @@ -386,7 +419,7 @@ func toolDefinitions() []definition { {"presentation_read", "Read the bound project appearance and metadata watermark explicitly. No ordinary job or inbox call includes settings; no provider work or mutation.", schema(map[string]any{})}, {"context", "Inspect the immutable local profile configuration; no service verification or credential read.", schema(map[string]any{})}, {"doctor", "Verify the configured service instance, project and worker without provider work.", schema(map[string]any{})}, - {"workers_list", "Read one compact worker page in the bound project.", schema(map[string]any{"limit": limit, "cursor": cursor})}, + {"workers_list", "Read one compact active-worker page; include_retired explicitly includes retained historical identities.", schema(map[string]any{"limit": limit, "cursor": cursor, "include_retired": map[string]any{"type": "boolean"}})}, {"jobs_list", "Read one compact job page with explicit optional worker/status filters.", schema(map[string]any{"limit": limit, "cursor": cursor, "worker_id": id, "status": status})}, {"jobs_assigned", "Read one compact job page assigned to the bound worker; no primary/resume-context claim.", schema(map[string]any{"limit": limit, "cursor": cursor, "status": status})}, {"job_read", "Read explicit full detail and brief for one job.", schema(map[string]any{"job_id": id}, "job_id")}, @@ -394,7 +427,7 @@ func toolDefinitions() []definition { {"job_checkpoint_append", "Append an immutable checkpoint with an explicit key and current expected job revision; return a compact receipt without changing the job or automatically retrying.", schema(map[string]any{"job_id": id, "idempotency_key": key, "expected_job_revision": map[string]any{"type": "integer", "minimum": 1, "maximum": int64(math.MaxInt64)}, "done": checkpointText(8<<10, true), "next": checkpointText(8<<10, true), "blocker": checkpointText(4<<10, false), "evidence": map[string]any{"type": "array", "maxItems": 10, "items": checkpointText(1024, true)}}, "job_id", "idempotency_key", "expected_job_revision", "done", "next")}, {"job_checkpoint_latest", "Read the current job revision and latest checkpoint, or explicit null when none exists; the captured checkpoint revision may be older.", schema(map[string]any{"job_id": id}, "job_id")}, {"job_checkpoint_history", "Read one explicit full checkpoint archive page in descending sequence order; no automatic archive reads.", schema(map[string]any{"job_id": id, "limit": limit, "cursor": cursor}, "job_id")}, - {"inbox_list", "Read one compact preview page for the bound worker; never mark seen or acknowledged.", schema(map[string]any{"limit": limit, "cursor": cursor, "unread": map[string]any{"type": "boolean"}, "unacknowledged": map[string]any{"type": "boolean"}})}, + {"inbox_list", "Read one compact preview page for the bound worker, or a recipient selected by worker_id, with project read permission and the acting identity unchanged; never mark seen or acknowledged.", schema(map[string]any{"worker_id": id, "limit": limit, "cursor": cursor, "unread": map[string]any{"type": "boolean"}, "unacknowledged": map[string]any{"type": "boolean"}})}, {"inbox_snapshot", "Read one bounded compact inbox page and its explicit scoped event cursor; no cursor is saved, no messages are marked seen or acknowledged, and no provider work occurs.", schema(map[string]any{"limit": limit, "cursor": cursor, "unread": map[string]any{"type": "boolean"}, "unacknowledged": map[string]any{"type": "boolean"}})}, {"inbox_events", "Read one bounded incoming-message event page after an explicit cursor, optionally waiting up to 4000 ms. No cursor is saved, no automatic polling or subscription occurs, messages are never marked seen or acknowledged, and no provider work occurs.", schema(map[string]any{"cursor": map[string]any{"type": "string", "minLength": 1, "maxLength": 4096, "description": "Required explicit cursor from a scoped snapshot or replay page."}, "limit": limit, "wait_ms": map[string]any{"type": "integer", "minimum": 0, "maximum": 4000, "description": "One bounded wait; omission returns immediately."}}, "cursor")}, {"inbox_thread", "Read one explicit conversation page with full immutable bodies; no receipt-state change.", schema(map[string]any{"conversation_id": id, "limit": limit, "cursor": cursor}, "conversation_id")}, @@ -402,6 +435,6 @@ func toolDefinitions() []definition { {"job_edit", "Edit selected job fields with an explicit key and expected revision; empty brief/worker clears those fields. No automatic retry.", editSchema}, {"inbox_send", "Send an immutable message as the bound worker with an explicit key, optionally replying to a message; return a compact receipt.", schema(map[string]any{"idempotency_key": key, "recipient_worker_id": id, "body": map[string]any{"type": "string", "minLength": 1, "maxLength": 16 << 10}, "reply_to_message_id": id}, "idempotency_key", "recipient_worker_id", "body")}, {"inbox_seen", "Explicitly mark a message seen as its bound recipient worker using the supplied key.", schema(map[string]any{"idempotency_key": key, "message_id": id}, "idempotency_key", "message_id")}, - {"inbox_ack", "Explicitly acknowledge a message as its bound recipient worker, also establishing seen, using the supplied key.", schema(map[string]any{"idempotency_key": key, "message_id": id}, "idempotency_key", "message_id")}, + {"inbox_ack", "Explicitly acknowledge a message, also establishing seen, using the supplied key. Defaults to the bound recipient; an explicit worker_id for another recipient requires project management and keeps the acting identity unchanged.", schema(map[string]any{"worker_id": id, "idempotency_key": key, "message_id": id}, "idempotency_key", "message_id")}, }, reviewDefinitions()...) } diff --git a/internal/mcpadapter/existing_management.go b/internal/mcpadapter/existing_management.go new file mode 100644 index 000000000..66f1fb018 --- /dev/null +++ b/internal/mcpadapter/existing_management.go @@ -0,0 +1,265 @@ +package mcpadapter + +// Existing project-management tools expose named typed-client operations only. +// Documents are native operation inputs, never URLs, HTTP verbs or credentials. +import ( + "bytes" + "context" + "encoding/json" + "math" + "time" + + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/strictjson" +) + +type existingManagementInput struct { + Document json.RawMessage `json:"document,omitempty"` + Changes json.RawMessage `json:"changes,omitempty"` + IdempotencyKey string `json:"idempotency_key,omitempty"` + PreviewSHA256 string `json:"preview_sha256,omitempty"` + ExpectedRevision *int64 `json:"expected_revision,omitempty"` + Revision int64 `json:"revision,omitempty"` + Limit int `json:"limit,omitempty"` + Cursor string `json:"cursor,omitempty"` + PullNumber int64 `json:"pull_number,omitempty"` + Status string `json:"status,omitempty"` + ObligationID string `json:"obligation_id,omitempty"` + CollectionID string `json:"collection_id,omitempty"` + PageID string `json:"page_id,omitempty"` + SourceKey string `json:"source_key,omitempty"` + PullNumbers []int64 `json:"pull_numbers,omitempty"` + WaitSeconds int `json:"wait_seconds,omitempty"` + TargetPullNumber *int64 `json:"target_pull_number,omitempty"` + Reason string `json:"reason,omitempty"` +} +type existingManagementArgs struct { + name string + input existingManagementInput + presentation client.ReplacePresentationRequest + publication client.PublicationInput +} +type existingManagementSpec struct { + name, description string + fields, required []string + write, destructive, external bool +} + +var existingManagementSpecs = []existingManagementSpec{ + {"presentation_replace", "Replace this project's presentation using the native {expected_revision,presentation} document. Requires project management and an explicit key; preserves the normal theme/config validation.", []string{"document", "idempotency_key"}, []string{"document", "idempotency_key"}, true, true, false}, + {"presentation_history", "Read one presentation history page; no automatic continuation.", []string{"limit", "cursor"}, nil, false, false, false}, + {"presentation_revision_read", "Read one retained presentation revision.", []string{"revision"}, []string{"revision"}, false, false, false}, + {"publication_configuration_read", "Read this project's selected public publication configuration. Requires instance administration. Private edits are not published implicitly.", nil, nil, false, false, false}, + {"publication_preview", "Preview a complete native publication input {expected_revision,enabled,manifest}; returns its content and preview_sha256, without publishing. Requires instance administration.", []string{"document"}, []string{"document"}, false, false, false}, + {"publication_apply", "Apply the exact approved publication input with its preview_sha256, expected revision and explicit key. Requires instance administration. Makes only explicitly selected public content available.", []string{"document", "preview_sha256", "idempotency_key"}, []string{"document", "preview_sha256", "idempotency_key"}, true, true, false}, + {"publication_unpublish", "Disable the selected project's public publication with current expected_revision and an explicit key. Requires instance administration. Retains private content and publication history.", []string{"expected_revision", "idempotency_key"}, []string{"expected_revision", "idempotency_key"}, true, true, false}, + {"review_import_preview", "Validate and preview a complete native review-import document without applying it or inventing review evidence. Requires project management or instance administration.", []string{"document"}, []string{"document"}, false, false, false}, + {"review_import_apply", "Apply the exact previewed native review-import document with preview_sha256 and explicit key. Requires project management or instance administration; retains original evidence and existing admission guards.", []string{"document", "preview_sha256", "idempotency_key"}, []string{"document", "preview_sha256", "idempotency_key"}, true, true, false}, + {"review_transfer_preview", "Preview one bounded additive native review-history transfer without applying it; no lifetime-project export or provider work. Requires project management or instance administration.", []string{"document"}, []string{"document"}, false, false, false}, + {"review_transfer_apply", "Apply the exact previewed additive native review-history transfer with preview_sha256 and explicit key; does not reset controls or manufacture completion credit. Requires project management or instance administration.", []string{"document", "preview_sha256", "idempotency_key"}, []string{"document", "preview_sha256", "idempotency_key"}, true, true, false}, +} + +func existingManagementSpecFor(name string) (existingManagementSpec, bool) { + for _, s := range existingManagementSpecs { + if s.name == name { + return s, true + } + } + return existingManagementSpec{}, false +} +func existingManagementTool(name string) bool { _, ok := existingManagementSpecFor(name); return ok } +func existingManagementWrite(name string) bool { + s, ok := existingManagementSpecFor(name) + return ok && s.write +} +func existingManagementDestructive(name string) bool { + s, ok := existingManagementSpecFor(name) + return ok && s.destructive +} +func existingManagementExternal(name string) bool { + s, ok := existingManagementSpecFor(name) + return ok && s.external +} +func existingManagementDefinitions() []definition { + var out []definition + for _, s := range existingManagementSpecs { + properties := map[string]any{} + for _, name := range s.fields { + p := map[string]any{"type": "string", "minLength": 1, "maxLength": 128} + switch name { + case "document", "changes": + p = map[string]any{"type": "object", "description": "Strict native operation document. The existing typed client validates its exact fields, values and byte budget before any service call."} + case "revision": + p = map[string]any{"type": "integer", "minimum": 1, "maximum": int64(math.MaxInt64 - 1)} + case "expected_revision": + p = map[string]any{"type": "integer", "minimum": 0, "maximum": int64(math.MaxInt64 - 1)} + case "pull_number": + p = map[string]any{"type": "integer", "minimum": 1, "maximum": 2147483647} + case "target_pull_number": + p = map[string]any{"type": "integer", "minimum": 0, "maximum": 2147483647} + case "reason": + p = map[string]any{"type": "string", "minLength": 1, "maxLength": 4096} + case "pull_numbers": + p = map[string]any{"type": "array", "minItems": 1, "maxItems": 100, "uniqueItems": true, "items": map[string]any{"type": "integer", "minimum": 1, "maximum": 2147483647}} + case "limit": + p = map[string]any{"type": "integer", "minimum": 1, "maximum": 100} + case "wait_seconds": + p = map[string]any{"type": "integer", "minimum": 0, "maximum": maxToolWaitSeconds} + case "preview_sha256": + p = map[string]any{"type": "string", "pattern": "^[a-f0-9]{64}$"} + case "cursor": + p = map[string]any{"type": "string", "minLength": 1, "maxLength": 4096} + case "status": + p = map[string]any{"type": "string", "enum": []string{"open", "resolved"}} + } + properties[name] = p + } + required := s.required + if required == nil { + required = []string{} + } + out = append(out, definition{s.name, s.description, map[string]any{"type": "object", "additionalProperties": false, "properties": properties, "required": required}}) + } + return out +} +func parseExistingManagementArguments(name string, raw json.RawMessage) (*existingManagementArgs, error) { + spec, ok := existingManagementSpecFor(name) + if len(raw) == 0 { + raw = json.RawMessage("{}") + } + if !ok || len(raw) > (256<<10)+1024 || strictjson.Validate(raw) != nil { + return nil, invalidArguments() + } + var fields map[string]json.RawMessage + if json.Unmarshal(raw, &fields) != nil || fields == nil { + return nil, invalidArguments() + } + allowed := map[string]bool{} + for _, f := range spec.fields { + allowed[f] = true + } + for k, v := range fields { + if !allowed[k] || bytes.Equal(bytes.TrimSpace(v), []byte("null")) { + return nil, invalidArguments() + } + } + for _, k := range spec.required { + var text string + if value, exists := fields[k]; exists && json.Unmarshal(value, &text) == nil && text == "" { + return nil, invalidArguments() + } + if _, ok := fields[k]; !ok { + return nil, invalidArguments() + } + } + a := &existingManagementArgs{name: name} + if strictjson.Decode(raw, &a.input) != nil { + return nil, invalidArguments() + } + in := &a.input + if _, ok := fields["idempotency_key"]; ok && !validKey(in.IdempotencyKey) { + return nil, invalidArguments() + } + if _, ok := fields["preview_sha256"]; ok && !managementHash(in.PreviewSHA256) { + return nil, invalidArguments() + } + if in.ExpectedRevision != nil && (*in.ExpectedRevision < 0 || *in.ExpectedRevision == math.MaxInt64) { + return nil, invalidArguments() + } + if _, ok := fields["revision"]; ok && (in.Revision < 1 || in.Revision == math.MaxInt64) { + return nil, invalidArguments() + } + if _, ok := fields["pull_number"]; ok && (in.PullNumber < 1 || in.PullNumber > 2147483647) { + return nil, invalidArguments() + } + if _, ok := fields["limit"]; ok && (in.Limit < 1 || in.Limit > 100) { + return nil, invalidArguments() + } + if _, ok := fields["cursor"]; ok && !validEventCursor(in.Cursor) { + return nil, invalidArguments() + } + if _, present := fields["status"]; present && in.Status != "open" && in.Status != "resolved" { + return nil, invalidArguments() + } + if in.WaitSeconds < 0 || in.WaitSeconds > maxToolWaitSeconds { + return nil, invalidArguments() + } + var err error + switch name { + case "presentation_replace": + var document map[string]json.RawMessage + if json.Unmarshal(in.Document, &document) != nil { + return nil, invalidArguments() + } + if revision, present := document["expected_revision"]; !present || bytes.Equal(bytes.TrimSpace(revision), []byte("null")) { + return nil, invalidArguments() + } + if _, err := client.DecodePresentationConfig(document["presentation"]); err != nil { + return nil, invalidArguments() + } + err = strictjson.Decode(in.Document, &a.presentation) + if err == nil { + err = client.ValidateReplacePresentationRequest(a.presentation) + } + case "publication_preview", "publication_apply": + a.publication, err = client.DecodePublicationInput(in.Document) + if err == nil && name == "publication_apply" { + err = client.ValidatePublicationApply(in.IdempotencyKey, in.PreviewSHA256, a.publication) + } + case "publication_unpublish": + err = client.ValidatePublicationUnpublish(in.IdempotencyKey, *in.ExpectedRevision) + case "review_import_preview": + err = client.ValidateReviewImportDocument(in.Document) + case "review_import_apply": + err = client.ValidateReviewImportApply(in.IdempotencyKey, in.PreviewSHA256, in.Document) + case "review_transfer_preview": + err = client.ValidateReviewTransferDocument(in.Document) + case "review_transfer_apply": + err = client.ValidateReviewTransferApply(in.IdempotencyKey, in.PreviewSHA256, in.Document) + } + if err != nil { + return nil, invalidArguments() + } + return a, nil +} +func managementHash(value string) bool { + if len(value) != 64 { + return false + } + for _, r := range value { + if !(r >= 'a' && r <= 'f' || r >= '0' && r <= '9') { + return false + } + } + return true +} +func existingManagementBudget(a *existingManagementArgs) time.Duration { return 15 * time.Second } +func executeExistingManagement(ctx context.Context, c *client.Client, a *existingManagementArgs) (any, error) { + in := a.input + page := client.PageOptions{Limit: in.Limit, Cursor: in.Cursor} + switch a.name { + case "presentation_replace": + return c.ReplacePresentation(ctx, in.IdempotencyKey, a.presentation) + case "presentation_history": + return c.PresentationHistory(ctx, page) + case "presentation_revision_read": + return c.PresentationRevision(ctx, in.Revision) + case "publication_configuration_read": + return c.Publication(ctx) + case "publication_preview": + return c.PreviewPublication(ctx, a.publication) + case "publication_apply": + return c.ApplyPublication(ctx, in.IdempotencyKey, in.PreviewSHA256, a.publication) + case "publication_unpublish": + return c.Unpublish(ctx, in.IdempotencyKey, *in.ExpectedRevision) + case "review_import_preview": + return c.PreviewReviewImport(ctx, in.Document) + case "review_import_apply": + return c.ApplyReviewImport(ctx, in.IdempotencyKey, in.PreviewSHA256, in.Document) + case "review_transfer_preview": + return c.PreviewReviewTransfer(ctx, in.Document) + case "review_transfer_apply": + return c.ApplyReviewTransfer(ctx, in.IdempotencyKey, in.PreviewSHA256, in.Document) + } + return nil, invalidArguments() +} diff --git a/internal/mcpadapter/existing_management_native_test.go b/internal/mcpadapter/existing_management_native_test.go new file mode 100644 index 000000000..5dd87493c --- /dev/null +++ b/internal/mcpadapter/existing_management_native_test.go @@ -0,0 +1,111 @@ +package mcpadapter_test + +import ( + "crypto/sha256" + "encoding/hex" + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/publicsite" + "net/http" + "net/http/httptest" + "testing" +) + +func TestExistingManagementOfficialSDKNativePublicationAndCurrentAuthority(t *testing.T) { + f := presentationSDKFixture(t) + if err := publicsite.EnsureSchema(t.Context(), f.store); err != nil { + t.Fatal(err) + } + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=1 WHERE project_id=?`, f.project); err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + mux.Handle("/", f.handler) + publicsite.New(f.store, nil).Register(mux, t.Context()) + service := httptest.NewServer(mux) + defer service.Close() + session := reviewControlsStdio(t, reviewControlsProfile(t, f, service.URL), "chosen") + replace := map[string]any{"document": map[string]any{"expected_revision": 0, "presentation": map[string]string{"name": "Selected display"}}, "idempotency_key": "appearance-one"} + var first client.PresentationReceipt + decodeResult(t, call(t, session, "presentation_replace", replace), &first) + if first.ProjectID != f.project || first.Revision != 1 { + t.Fatal(first) + } + var replay client.PresentationReceipt + decodeResult(t, call(t, session, "presentation_replace", replace), &replay) + if replay != first { + t.Fatal("lost-response replay changed mutation", replay) + } + var revision client.PresentationRevision + decodeResult(t, call(t, session, "presentation_revision_read", map[string]any{"revision": 1}), &revision) + if revision.State.Name != "Selected display" || revision.Revision != 1 { + t.Fatal(revision) + } + input, err := client.DecodePublicationInput([]byte(`{"expected_revision":0,"enabled":true,"manifest":{"slug":"published-example","presentation":{"name":"Approved public display"},"description":"Explicitly approved public text"}}`)) + if err != nil { + t.Fatal(err) + } + // Project management still permits presentation changes, but publication + // requires the selected credential's current instance-administrator grant. + diagnosticResult(t, call(t, session, "publication_configuration_read", map[string]any{}), "forbidden", false) + diagnosticResult(t, call(t, session, "publication_preview", map[string]any{"document": input}), "forbidden", false) + diagnosticResult(t, call(t, session, "publication_unpublish", map[string]any{"expected_revision": 0, "idempotency_key": "manager-unpublish"}), "forbidden", false) + digest := sha256.Sum256([]byte(token)) + setAdministrator := func(enabled bool) { + t.Helper() + result, err := f.store.DB().Exec(`UPDATE credentials SET is_admin=? WHERE token_sha256=?`, enabled, hex.EncodeToString(digest[:])) + if err != nil { + t.Fatal(err) + } + if rows, err := result.RowsAffected(); err != nil || rows != 1 { + t.Fatal("selected fixture credential was not updated", rows, err) + } + } + setAdministrator(true) + var preview client.PublicationPreview + decodeResult(t, call(t, session, "publication_preview", map[string]any{"document": input}), &preview) + if preview.SHA256 == "" { + t.Fatal("preview lost native guard") + } + apply := map[string]any{"document": input, "preview_sha256": preview.SHA256, "idempotency_key": "publish-one"} + setAdministrator(false) + diagnosticResult(t, call(t, session, "publication_apply", apply), "forbidden", false) + setAdministrator(true) + var unchanged client.PublicationConfiguration + decodeResult(t, call(t, session, "publication_configuration_read", map[string]any{}), &unchanged) + if unchanged.Enabled || unchanged.Revision != 0 { + t.Fatal("denied publication changed configuration", unchanged) + } + var published client.PublicationReceipt + decodeResult(t, call(t, session, "publication_apply", apply), &published) + if published.Revision != 1 { + t.Fatal(published) + } + var configuration client.PublicationConfiguration + decodeResult(t, call(t, session, "publication_configuration_read", map[string]any{}), &configuration) + if configuration.Revision != 1 || !configuration.Enabled || configuration.Manifest == nil || configuration.Manifest.Description != input.Manifest.Description { + t.Fatal("publication selection changed", configuration) + } + var disabled client.PublicationReceipt + decodeResult(t, call(t, session, "publication_unpublish", map[string]any{"expected_revision": 1, "idempotency_key": "unpublish-one"}), &disabled) + if disabled.Revision != 2 { + t.Fatal(disabled) + } + // Demotion must reject the exact retained publication receipts without + // taking away the independent project-management presentation permission. + setAdministrator(false) + diagnosticResult(t, call(t, session, "publication_apply", apply), "forbidden", false) + diagnosticResult(t, call(t, session, "publication_unpublish", map[string]any{"expected_revision": 1, "idempotency_key": "unpublish-one"}), "forbidden", false) + decodeResult(t, call(t, session, "presentation_replace", replace), &replay) + if replay != first { + t.Fatal("instance-admin demotion changed project-management replay", replay) + } + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=0 WHERE project_id=?`, f.project); err != nil { + t.Fatal(err) + } + diagnosticResult(t, call(t, session, "presentation_replace", replace), "forbidden", false) + var retained client.PresentationRevision + decodeResult(t, call(t, session, "presentation_revision_read", map[string]any{"revision": 1}), &retained) + if retained.State.Name != "Selected display" { + t.Fatal("downgrade changed retained content") + } +} diff --git a/internal/mcpadapter/existing_management_sdk_test.go b/internal/mcpadapter/existing_management_sdk_test.go new file mode 100644 index 000000000..e4dda6b98 --- /dev/null +++ b/internal/mcpadapter/existing_management_sdk_test.go @@ -0,0 +1,144 @@ +package mcpadapter_test + +import ( + "encoding/json" + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/profile" + "github.com/benhook1013/FireController/internal/reviews" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" +) + +type managementWireCase struct { + name, method, path string + args map[string]any + write bool +} + +func managementWireCases(t *testing.T) []managementWireCase { + zero := int64(0) + hash := strings.Repeat("a", 64) + raw := func(v any) json.RawMessage { + b, err := json.Marshal(v) + if err != nil { + t.Fatal(err) + } + return b + } + pub := json.RawMessage(`{"expected_revision":0,"enabled":true,"manifest":{"slug":"example","presentation":{"name":"Approved public project"},"description":"Approved content"}}`) + imported := json.RawMessage(`{"expected_revision":0,"repository_id":1,"source":"prepared archive","observed_at":"2026-01-01T00:00:00Z","queue":[],"retired":[]}`) + transferred := raw(reviews.TransferRequest{Version: 1, ExpectedRevision: &zero, RepositoryID: 1, Publisher: "prepared archive", Groups: []reviews.TransferGroup{{Source: "original", Pulls: []reviews.PullInput{{Number: 2, Title: "Retained PR", State: "open", CIState: "unknown", Mergeability: "unknown", Runs: []reviews.RunInput{}, Attempts: []reviews.Attempt{}}}}}}) + preview := func(doc json.RawMessage) map[string]any { return map[string]any{"document": doc} } + apply := func(doc json.RawMessage) map[string]any { + return map[string]any{"document": doc, "preview_sha256": hash, "idempotency_key": "chosen"} + } + return []managementWireCase{ + {"presentation_replace", "PUT", "presentation", map[string]any{"document": raw(map[string]any{"expected_revision": 0, "presentation": map[string]string{"name": "Selected project"}}), "idempotency_key": "chosen"}, true}, + {"presentation_history", "GET", "presentation/history", map[string]any{}, false}, {"presentation_revision_read", "GET", "presentation/history/1", map[string]any{"revision": 1}, false}, + {"publication_configuration_read", "GET", "publication", map[string]any{}, false}, + {"publication_preview", "POST", "publication/preview", preview(pub), false}, {"publication_apply", "PUT", "publication", apply(pub), true}, {"publication_unpublish", "POST", "publication/unpublish", map[string]any{"expected_revision": 0, "idempotency_key": "chosen"}, true}, + {"review_import_preview", "POST", "reviews/import/preview", preview(imported), false}, {"review_import_apply", "POST", "reviews/import/apply", apply(imported), true}, + {"review_transfer_preview", "POST", "reviews/transfer/preview", preview(transferred), false}, {"review_transfer_apply", "POST", "reviews/transfer/apply", apply(transferred), true}, + } +} +func TestExistingManagementOfficialSDKBoundTransportAndPermissionRefusal(t *testing.T) { + var count atomic.Int64 + var active atomic.Value + active.Store(managementWireCase{}) + service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.URL.Path == "/api/v1/instance" { + json.NewEncoder(w).Encode(map[string]string{"instance_id": "instance-one"}) + return + } + count.Add(1) + current := active.Load().(managementWireCase) + if r.Method != current.method || r.URL.Path != "/api/v1/projects/project-one/"+current.path || r.Header.Get("X-FC-Instance") != "instance-one" || r.Header.Get("X-FC-Worker") != "worker-one" || r.Header.Get("Authorization") != "Bearer "+token { + t.Error("management request lost selected route or binding", r.Method, r.URL.Path, current.name) + } + if current.write && r.Header.Get("Idempotency-Key") != "chosen" || !current.write && r.Header.Get("Idempotency-Key") != "" { + t.Error("mutation key changed", current.name) + } + core.WriteError(w, core.Fail("forbidden", "Project management is required.", 403)) + })) + defer service.Close() + c := localContext() + c.ServerURL = service.URL + session := reviewControlsStdio(t, profiles(t, map[string]profile.Context{"alpha": c}, credential(t)), "alpha") + listed, err := allDiscoveredTools(t, session) + if err != nil { + t.Fatal(err) + } + names := map[string]bool{} + for _, tool := range listed.Tools { + names[tool.Name] = true + } + for _, entry := range managementWireCases(t) { + t.Run(entry.name, func(t *testing.T) { + if !names[entry.name] { + t.Fatal("management tool missing from real discovery") + } + active.Store(entry) + before := count.Load() + diagnosticResult(t, call(t, session, entry.name, entry.args), "forbidden", false) + if count.Load() != before+1 { + t.Fatal("management call failed locally or retried/fanned out", count.Load()-before) + } + }) + } +} + +func TestPresentationReplacementRevisionGuardStaysLocal(t *testing.T) { + var calls, writes atomic.Int64 + service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + w.Header().Set("Content-Type", "application/json") + if r.URL.Path == "/api/v1/instance" { + json.NewEncoder(w).Encode(map[string]string{"instance_id": "instance-one"}) + return + } + writes.Add(1) + if r.Method != "PUT" || r.URL.Path != "/api/v1/projects/project-one/presentation" || r.Header.Get("Idempotency-Key") != "chosen" || r.Header.Get("X-FC-Worker") != "worker-one" { + t.Error("presentation request identity changed") + } + var raw map[string]json.RawMessage + if err := json.NewDecoder(r.Body).Decode(&raw); err != nil { + t.Fatal(err) + } + if string(raw["expected_revision"]) != "0" { + t.Errorf("expected explicit JSON revision 0, got %s", raw["expected_revision"]) + } + var body client.ReplacePresentationRequest + encoded, _ := json.Marshal(raw) + if json.Unmarshal(encoded, &body) != nil || body.ExpectedRevision != 0 || body.Presentation.Name != "Selected" { + t.Error("explicit zero revision was not preserved") + } + core.WriteError(w, core.Fail("forbidden", "Project management is required.", http.StatusForbidden)) + })) + defer service.Close() + binding := localContext() + binding.ServerURL = service.URL + session := reviewControlsStdio(t, profiles(t, map[string]profile.Context{"alpha": binding}, credential(t)), "alpha") + for name, doc := range map[string]map[string]any{ + "missing": {"presentation": map[string]any{"name": "Selected"}}, + "null": {"expected_revision": nil, "presentation": map[string]any{"name": "Selected"}}, + "unknown": {"expected_revision": 0, "unknown": true, "presentation": map[string]any{"name": "Selected"}}, + } { + t.Run(name, func(t *testing.T) { + before := calls.Load() + diagnosticResult(t, call(t, session, "presentation_replace", map[string]any{"document": doc, "idempotency_key": "chosen"}), "invalid_arguments", false) + if calls.Load() != before { + t.Fatal("invalid document performed service work", calls.Load()-before) + } + }) + } + before := writes.Load() + diagnosticResult(t, call(t, session, "presentation_replace", map[string]any{"document": map[string]any{"expected_revision": 0, "presentation": map[string]string{"name": "Selected"}}, "idempotency_key": "chosen"}), "forbidden", false) + if writes.Load() != before+1 { + t.Fatal("explicit zero was rejected or automatically retried", writes.Load()-before) + } +} diff --git a/internal/mcpadapter/existing_management_test.go b/internal/mcpadapter/existing_management_test.go new file mode 100644 index 000000000..3eca53dfc --- /dev/null +++ b/internal/mcpadapter/existing_management_test.go @@ -0,0 +1,114 @@ +package mcpadapter + +import ( + "encoding/json" + "strings" + "testing" +) + +func TestExistingManagementSchemasAndMalformedInputsStayLocal(t *testing.T) { + names := map[string]bool{} + for _, d := range existingManagementDefinitions() { + if names[d.name] || d.schema["additionalProperties"] != false { + t.Fatal("ambiguous management tool", d.name) + } + names[d.name] = true + for _, raw := range []json.RawMessage{[]byte(`null`), []byte(`{"project_id":"other-project"}`), []byte(`{"document":{},"idempotency_key":"a","idempotency_key":"b"}`)} { + if _, err := parseExistingManagementArguments(d.name, raw); err == nil { + t.Fatal("unsafe outer arguments accepted", d.name, string(raw)) + } + } + } + for name, raw := range map[string]string{ + "publication_unpublish": `{"expected_revision":null,"idempotency_key":"chosen"}`, + "presentation_replace": `{"document":{},"idempotency_key":"chosen"}`, + "review_import_apply": `{"document":{},"preview_sha256":"short","idempotency_key":"chosen"}`, + } { + if _, err := parseExistingManagementArguments(name, []byte(raw)); err == nil { + t.Fatal("malformed native input accepted", name) + } + } +} + +func TestReviewManagementToolDescriptionsStateAuthority(t *testing.T) { + want := map[string]bool{ + "review_import_preview": false, + "review_import_apply": false, + "review_transfer_preview": false, + "review_transfer_apply": false, + "review_round_adoption_preview": true, + "review_round_adoption_apply": true, + "review_obligations_import_preview": true, + "review_obligations_import_apply": true, + "review_queue_edit": false, + } + definitions := append(existingManagementDefinitions(), adoptionDefinitions()...) + definitions = append(definitions, queueEditDefinition()) + for _, d := range definitions { + workerRequired, ok := want[d.name] + if !ok { + continue + } + if !strings.Contains(d.description, "Requires project management or instance administration") || workerRequired && !strings.Contains(d.description, "valid project worker") { + t.Errorf("%s omits its required authority: %s", d.name, d.description) + } + delete(want, d.name) + } + if len(want) != 0 { + t.Fatalf("management tools missing from discovery: %v", want) + } +} + +func TestPresentationReplacementRequiresExplicitRevision(t *testing.T) { + for name, document := range map[string]string{ + "missing": `{"presentation":{"name":"Selected"}}`, + "null": `{"expected_revision":null,"presentation":{"name":"Selected"}}`, + "duplicate": `{"expected_revision":0,"expected_revision":1,"presentation":{"name":"Selected"}}`, + "unknown": `{"expected_revision":0,"unknown":true,"presentation":{"name":"Selected"}}`, + "mis-cased": `{"Expected_Revision":0,"presentation":{"name":"Selected"}}`, + "string": `{"expected_revision":"0","presentation":{"name":"Selected"}}`, + "negative": `{"expected_revision":-1,"presentation":{"name":"Selected"}}`, + "fractional": `{"expected_revision":0.5,"presentation":{"name":"Selected"}}`, + "exhausted": `{"expected_revision":9223372036854775807,"presentation":{"name":"Selected"}}`, + "nested-unknown": `{"expected_revision":0,"presentation":{"name":"Selected","unknown":true}}`, + "nested-duplicate": `{"expected_revision":0,"presentation":{"name":"Selected","name":"Other"}}`, + } { + t.Run(name, func(t *testing.T) { + raw := `{"document":` + document + `,"idempotency_key":"chosen"}` + if _, err := parseExistingManagementArguments("presentation_replace", []byte(raw)); err == nil { + t.Fatal("malformed revision document accepted", document) + } + }) + } + for _, revision := range []string{"0", "1", "9223372036854775806"} { + raw := `{"document":{"expected_revision":` + revision + `,"presentation":{"name":"Selected"}},"idempotency_key":"chosen"}` + args, err := parseExistingManagementArguments("presentation_replace", []byte(raw)) + if err != nil || args == nil { + t.Fatal("explicit valid revision rejected", revision, err) + } + encoded, err := json.Marshal(args.presentation.ExpectedRevision) + if err != nil || string(encoded) != revision { + t.Fatal("explicit revision changed", revision, string(encoded), err) + } + } +} + +func TestPresentationReplacementRejectsExplicitNullConfig(t *testing.T) { + for _, field := range []string{"name", "brand_name", "tagline", "headings", "theme"} { + t.Run(field, func(t *testing.T) { + config := map[string]any{"name": "Selected", field: nil} + raw, err := json.Marshal(map[string]any{"document": map[string]any{"expected_revision": 7, "presentation": config}, "idempotency_key": "chosen"}) + if err != nil { + t.Fatal(err) + } + if _, err := parseExistingManagementArguments("presentation_replace", raw); err == nil { + t.Fatal("explicit null accepted", field) + } + }) + } + raw := `{"document":{"expected_revision":7,"presentation":{"name":"Selected","brand_name":"Custom","tagline":"Custom tagline","headings":{},"theme":{}}},"idempotency_key":"chosen"}` + args, err := parseExistingManagementArguments("presentation_replace", []byte(raw)) + if err != nil || args.presentation.ExpectedRevision != 7 || args.presentation.Presentation.BrandName != "Custom" { + t.Fatal("valid replacement changed", args, err) + } +} diff --git a/internal/mcpadapter/mutations_test.go b/internal/mcpadapter/mutations_test.go index cb490cefe..5227ea446 100644 --- a/internal/mcpadapter/mutations_test.go +++ b/internal/mcpadapter/mutations_test.go @@ -202,7 +202,7 @@ func TestMutationArgumentsRejectBeforeCredentialAndHTTP(t *testing.T) { {"jobs_create", `{"title":"x"}`}, {"jobs_create", `{"idempotency_key":"","title":"x"}`}, {"jobs_create", `{"idempotency_key":" key","title":"x"}`}, {"jobs_create", `{"idempotency_key":"é","title":"x"}`}, {"jobs_create", `{"idempotency_key":"a\nb","title":"x"}`}, {"jobs_create", `{"idempotency_key":"` + strings.Repeat("k", 129) + `","title":"x"}`}, {"jobs_create", `{"idempotency_key":"k","title":" "}`}, {"jobs_create", `{"idempotency_key":"k","title":"` + strings.Repeat("x", 241) + `"}`}, {"jobs_create", `{"idempotency_key":"k","title":"x","brief":"` + strings.Repeat("x", (32<<10)+1) + `"}`}, {"jobs_create", `{"idempotency_key":"k","title":"x","worker_id":"../other"}`}, {"jobs_create", `{"idempotency_key":"k","title":"x","status":"ready"}`}, {"jobs_create", `{"idempotency_key":"k","title":"x","profile":"other"}`}, {"jobs_create", `{"idempotency_key":"k","idempotency_key":"other","title":"x"}`}, {"jobs_create", `{"idempotency_key":"k","Title":"x"}`}, {"jobs_create", `{"idempotency_key":"k","title":null}`}, {"jobs_create", `{"idempotency_key":"k","title":"bad\ud800"}`}, {"job_edit", `{"idempotency_key":"k","job_id":"job","expected_revision":1}`}, {"job_edit", `{"idempotency_key":"k","job_id":"job","title":"x"}`}, {"job_edit", `{"idempotency_key":"k","job_id":"job","expected_revision":0,"title":"x"}`}, {"job_edit", `{"idempotency_key":"k","job_id":"job","expected_revision":1.5,"title":"x"}`}, {"job_edit", `{"idempotency_key":"k","job_id":"job","expected_revision":9223372036854775807,"title":"x"}`}, {"job_edit", `{"idempotency_key":"k","job_id":"job","expected_revision":9223372036854775808,"title":"x"}`}, {"job_edit", `{"idempotency_key":"k","job_id":"job","expected_revision":1,"brief":null}`}, {"job_edit", `{"idempotency_key":"k","job_id":"job","expected_revision":1,"status":""}`}, {"job_edit", `{"idempotency_key":"k","job_id":"..","expected_revision":1,"title":"x"}`}, {"inbox_send", `{"idempotency_key":"k","recipient_worker_id":"worker","body":" "}`}, {"inbox_send", `{"idempotency_key":"k","recipient_worker_id":"worker","body":"` + strings.Repeat("x", (16<<10)+1) + `"}`}, {"inbox_send", `{"idempotency_key":"k","recipient_worker_id":"worker","body":"x","reply_to_message_id":"a/b"}`}, {"inbox_send", `{"idempotency_key":"k","recipient_worker_id":"worker","body":"x","sender_worker_id":"other"}`}, {"inbox_send", `{"idempotency_key":"k","recipient_worker_id":"worker","body":"x","reply_to_message_id":null}`}, - {"inbox_seen", `{"message_id":"message"}`}, {"inbox_seen", `{"idempotency_key":"k","message_id":".."}`}, {"inbox_ack", `{"idempotency_key":"k","message_id":"message","worker_id":"other"}`}, {"inbox_ack", `{"idempotency_key":"k","message_id":null}`}, + {"inbox_seen", `{"message_id":"message"}`}, {"inbox_seen", `{"idempotency_key":"k","message_id":".."}`}, {"inbox_ack", `{"idempotency_key":"k","message_id":"message","worker_id":""}`}, {"inbox_ack", `{"idempotency_key":"k","message_id":null}`}, } for i, tc := range cases { t.Run(tc.name+string(rune('A'+i)), func(t *testing.T) { diff --git a/internal/mcpadapter/project_owner.go b/internal/mcpadapter/project_owner.go new file mode 100644 index 000000000..f50da1484 --- /dev/null +++ b/internal/mcpadapter/project_owner.go @@ -0,0 +1,181 @@ +package mcpadapter + +import ( + "bytes" + "context" + "encoding/json" + "math" + + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/strictjson" +) + +type ownerManagementInvocation struct { + name, key, id string + policy client.ConfigureReviewPolicyRequest + execution client.ConfigureReviewExecutionRequest + worker client.CreateWorkerRequest + grant client.GrantProjectCredentialRequest + update client.UpdateProjectCredentialRequest +} + +func ownerManagementTool(name string) bool { + switch name { + case "review_policy_read", "review_policy_configure", "review_execution_configure", "worker_create", "worker_retirement_read", "worker_retire", "project_credential_grant", "project_credential_revoke", "project_credential_update": + return true + } + return false +} +func ownerManagementWrite(name string) bool { + return ownerManagementTool(name) && name != "review_policy_read" && name != "worker_retirement_read" +} +func ownerManagementDestructive(name string) bool { + return ownerManagementWrite(name) && name != "worker_create" && name != "project_credential_grant" +} +func ownerDecode(raw json.RawMessage, out any, required ...string) bool { + if len(raw) == 0 { + raw = []byte("{}") + } + if len(raw) > 32<<10 || strictjson.Decode(raw, out) != nil { + return false + } + var fields map[string]json.RawMessage + if json.Unmarshal(raw, &fields) != nil || fields == nil { + return false + } + for _, v := range fields { + if bytes.Equal(bytes.TrimSpace(v), []byte("null")) { + return false + } + } + for _, k := range required { + if _, ok := fields[k]; !ok { + return false + } + } + return true +} +func ownerManagementArguments(name string, raw json.RawMessage) (arguments, error) { + var args arguments + in := &ownerManagementInvocation{name: name} + if name == "worker_retirement_read" { + var input struct { + Worker string `json:"worker_id"` + } + if !ownerDecode(raw, &input, "worker_id") || !validID(input.Worker) { + return args, invalidArguments() + } + in.id = input.Worker + args.ownerManagement = in + return args, nil + } + if name == "review_policy_read" { + if !ownerDecode(raw, &struct{}{}) { + return args, invalidArguments() + } + args.ownerManagement = in + return args, nil + } + if len(raw) > 32<<10 || strictjson.Validate(raw) != nil { + return args, invalidArguments() + } + var fields map[string]json.RawMessage + if json.Unmarshal(raw, &fields) != nil || fields == nil { + return args, invalidArguments() + } + if json.Unmarshal(fields["idempotency_key"], &in.key) != nil || !validKey(in.key) { + return args, invalidArguments() + } + delete(fields, "idempotency_key") + idField := "" + switch name { + case "worker_retire": + idField = "worker_id" + case "project_credential_revoke", "project_credential_update": + idField = "credential_id" + } + if idField != "" { + if json.Unmarshal(fields[idField], &in.id) != nil || !validID(in.id) { + return args, invalidArguments() + } + delete(fields, idField) + } + body, _ := json.Marshal(fields) + valid := false + switch name { + case "review_policy_configure": + valid = ownerDecode(body, &in.policy, "expected_revision", "required_channels", "max_review_files", "paused_channels") && client.ValidateConfigureReviewPolicy(in.policy) == nil + case "review_execution_configure": + valid = ownerDecode(body, &in.execution, "expected_revision", "capability_id", "mode", "queue", "channels", "paused") && client.ValidateConfigureReviewExecution(in.execution) == nil + case "worker_create": + valid = ownerDecode(body, &in.worker, "name") && client.ValidateCreateWorker(in.worker) == nil + case "project_credential_grant": + valid = ownerDecode(body, &in.grant, "token_sha256", "permissions") && client.ValidateGrantProjectCredential(in.grant) == nil + case "worker_retire", "project_credential_revoke": + valid = ownerDecode(body, &struct{}{}) + case "project_credential_update": + valid = ownerDecode(body, &in.update, "expected_permissions", "permissions") && client.ValidateUpdateProjectCredential(in.id, in.update) == nil + } + if !valid { + return args, invalidArguments() + } + args.ownerManagement = in + return args, nil +} +func executeOwnerManagement(ctx context.Context, c *client.Client, in *ownerManagementInvocation) (any, error) { + switch in.name { + case "review_policy_read": + return c.ReviewPolicy(ctx) + case "review_policy_configure": + return c.ConfigureReviewPolicy(ctx, in.key, in.policy) + case "review_execution_configure": + return c.ConfigureReviewExecution(ctx, in.key, in.execution) + case "worker_retirement_read": + return c.WorkerRetirement(ctx, in.id) + case "worker_retire": + return c.RetireWorker(ctx, in.key, in.id) + case "worker_create": + return c.CreateWorker(ctx, in.key, in.worker) + case "project_credential_grant": + return c.GrantProjectCredential(ctx, in.key, in.grant) + case "project_credential_revoke": + return c.RevokeProjectCredential(ctx, in.key, in.id) + case "project_credential_update": + return c.UpdateProjectCredential(ctx, in.key, in.id, in.update) + } + return nil, invalidArguments() +} +func ownerManagementDefinitions() []definition { + text := func(max int) map[string]any { return map[string]any{"type": "string", "maxLength": max} } + integer := func(min, max int64) map[string]any { + return map[string]any{"type": "integer", "minimum": min, "maximum": max} + } + strEnum := func(values ...string) map[string]any { return map[string]any{"type": "string", "enum": values} } + channels := map[string]any{"type": "array", "minItems": 1, "maxItems": 2, "uniqueItems": true, "items": strEnum("cli", "hosted")} + permissions := map[string]any{"type": "array", "minItems": 1, "maxItems": 3, "uniqueItems": true, "items": strEnum("read", "write", "manage"), "contains": strEnum("read", "manage")} + key := text(128) + key["minLength"] = 1 + revision := integer(0, math.MaxInt64-1) + var defs []definition + add := func(name, desc string, props map[string]any, required ...string) { + schema := map[string]any{"type": "object", "additionalProperties": false, "properties": props} + if len(required) > 0 { + schema["required"] = required + } + defs = append(defs, definition{name, desc, schema}) + } + add("review_policy_read", "Read this project's current configured review requirements, policy revision and attribution. No source refresh or provider action.", map[string]any{}) + roundBounds := map[string]any{"type": "object", "additionalProperties": false, "properties": map[string]any{"minimum": integer(0, 1000), "maximum": integer(1, 1000)}, "required": []string{"minimum", "maximum"}} + roundDefaults := map[string]any{"type": "object", "additionalProperties": false, "properties": map[string]any{"hosted": roundBounds, "cli": roundBounds}, "required": []string{"hosted", "cli"}} + add("review_policy_configure", "Project manager: replace current review requirements with exact expected_revision and explicit key. max_review_files zero means no project ceiling; provider limits remain separate. Optional round_defaults sets hosted/cli minimum and maximum for newly initialized PR controls only; omission uses product defaults. Existing controls and taper are unchanged; no review request. See docs/review-round-controls.md.", map[string]any{"idempotency_key": key, "expected_revision": revision, "required_channels": channels, "paused_channels": map[string]any{"type": "array", "maxItems": 2, "uniqueItems": true, "items": strEnum("cli", "hosted")}, "max_review_files": integer(0, 100000), "round_defaults": roundDefaults}, "idempotency_key", "expected_revision", "required_channels", "max_review_files", "paused_channels") + add("review_execution_configure", "Project manager: full guarded replacement of existing capability selection, mode, ordered scheduling queue, channels and pause. Read current configuration and preserve fields outside the intended change. Preserve the current capability_id; capability installation and initial binding are instance-owned. Existing controls/history remain; this requests no review.", map[string]any{"idempotency_key": key, "expected_revision": revision, "capability_id": text(128), "mode": strEnum("independent", "stacked"), "queue": map[string]any{"type": "array", "minItems": 1, "maxItems": 100, "uniqueItems": true, "items": integer(1, 2147483647)}, "channels": channels, "paused": map[string]any{"type": "boolean"}}, "idempotency_key", "expected_revision", "capability_id", "mode", "queue", "channels", "paused") + add("worker_retirement_read", "Read a worker retirement preview: unfinished assigned jobs, pending direct/assigned-job notes and unacknowledged messages, with total counts and up to 20 IDs each. Reassign/finish jobs, reassign/resolve notes and explicitly acknowledge messages first; no automatic changes. Preview is not a reservation.", map[string]any{"worker_id": text(128)}, "worker_id") + add("worker_retire", "Project writer: retire one worker after atomic unfinished-job, pending-note and unacknowledged-message checks. One-way, preserves historical references; never reassigns work, acknowledges messages, deletes credentials or changes acting identity. Use retirement preview first. Exact-key replay is retained; no automatic mutation retry.", map[string]any{"worker_id": text(128), "idempotency_key": key}, "worker_id", "idempotency_key") + add("worker_create", "Project writer: create one named worker in this bound project. Returns its ID; does not switch the acting worker, create credentials or start an agent.", map[string]any{"idempotency_key": key, "name": text(200)}, "idempotency_key", "name") + digest := text(64) + digest["pattern"] = "^[a-f0-9]{64}$" + add("project_credential_grant", "Project manager: grant this project to a distinct non-admin credential using only its lowercase SHA-256 digest. Raw tokens never enter tool arguments/output; generate/store credentials privately through onboarding. manage implies read/write. Explicit key; no other-project or instance authority.", map[string]any{"idempotency_key": key, "token_sha256": digest, "permissions": permissions}, "idempotency_key", "token_sha256", "permissions") + add("project_credential_revoke", "Project manager: revoke a known credential's access to this project only. Preserves its other-project grants; no token or acting identity change. Explicit key, original ID retained after unknown outcome.", map[string]any{"idempotency_key": key, "credential_id": text(128)}, "idempotency_key", "credential_id") + add("project_credential_update", "Project manager: replace one existing non-admin credential's permissions in this project under an exact expected_permissions guard. Preserves credential, principal, token and worker binding; changes no other project. manage implies read/write. No hidden role or identity switching.", map[string]any{"idempotency_key": key, "credential_id": text(128), "expected_permissions": permissions, "permissions": permissions}, "idempotency_key", "credential_id", "expected_permissions", "permissions") + return defs +} diff --git a/internal/mcpadapter/project_owner_schema_test.go b/internal/mcpadapter/project_owner_schema_test.go new file mode 100644 index 000000000..d13932d36 --- /dev/null +++ b/internal/mcpadapter/project_owner_schema_test.go @@ -0,0 +1,94 @@ +package mcpadapter + +import ( + "encoding/json" + "github.com/google/jsonschema-go/jsonschema" + "reflect" + "testing" +) + +func TestOwnerManagementSchemasNeverEmitNullRequired(t *testing.T) { + expected := map[string][]string{ + "review_policy_read": nil, + "review_policy_configure": {"idempotency_key", "expected_revision", "required_channels", "max_review_files", "paused_channels"}, + "review_execution_configure": {"idempotency_key", "expected_revision", "capability_id", "mode", "queue", "channels", "paused"}, + "worker_retirement_read": {"worker_id"}, + "worker_retire": {"worker_id", "idempotency_key"}, + "worker_create": {"idempotency_key", "name"}, + "project_credential_grant": {"idempotency_key", "token_sha256", "permissions"}, + "project_credential_revoke": {"idempotency_key", "credential_id"}, + "project_credential_update": {"idempotency_key", "credential_id", "expected_permissions", "permissions"}, + } + for _, def := range ownerManagementDefinitions() { + t.Run(def.name, func(t *testing.T) { + want, known := expected[def.name] + if !known { + t.Fatalf("missing required-field expectation for %s", def.name) + } + if got, _ := def.schema["required"].([]string); !reflect.DeepEqual(got, want) { + t.Fatalf("required fields: want %v, got %v", want, got) + } + raw, err := json.Marshal(def.schema) + if err != nil { + t.Fatal(err) + } + var decoded map[string]any + if err := json.Unmarshal(raw, &decoded); err != nil { + t.Fatal(err) + } + required, present := decoded["required"] + if def.name == "review_policy_read" { + if present { + t.Fatalf("argument-free tool unexpectedly has required: %v", required) + } + return + } + values, ok := required.([]any) + if !present || !ok || len(values) == 0 { + t.Fatalf("required arguments lost: %s", raw) + } + props := decoded["properties"].(map[string]any) + for _, value := range values { + name, ok := value.(string) + if !ok { + t.Fatalf("non-string required argument: %v", value) + } + if _, ok := props[name]; !ok { + t.Fatalf("missing required property %q", name) + } + } + }) + } +} + +func TestOwnerPermissionSchemasRequireReadOrManage(t *testing.T) { + for _, def := range ownerManagementDefinitions() { + props := def.schema["properties"].(map[string]any) + for _, field := range []string{"permissions", "expected_permissions"} { + raw, exists := props[field] + if !exists { + continue + } + data, _ := json.Marshal(raw) + var schema jsonschema.Schema + if err := json.Unmarshal(data, &schema); err != nil { + t.Fatal(err) + } + resolved, err := schema.Resolve(nil) + if err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + values []any + valid bool + }{ + {[]any{"write"}, false}, {[]any{"read", "write"}, true}, {[]any{"manage"}, true}, + } { + err := resolved.Validate(tc.values) + if (err == nil) != tc.valid { + t.Errorf("%s.%s permissions %v: valid=%v, error=%v", def.name, field, tc.values, tc.valid, err) + } + } + } + } +} diff --git a/internal/mcpadapter/project_owner_test.go b/internal/mcpadapter/project_owner_test.go new file mode 100644 index 000000000..5e14ae925 --- /dev/null +++ b/internal/mcpadapter/project_owner_test.go @@ -0,0 +1,247 @@ +package mcpadapter_test + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "reflect" + "strings" + "sync/atomic" + "testing" + + "github.com/benhook1013/FireController/internal/cli" + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/profile" + "github.com/benhook1013/FireController/internal/reviewexec" + "github.com/benhook1013/FireController/internal/reviews" +) + +func TestProjectOwnerSDKManagementAndSelectedWorker(t *testing.T) { + f := mutationFixture(t) + if err := reviewexec.EnsureSchema(t.Context(), f.store); err != nil { + t.Fatal(err) + } + if err := reviews.EnsureSchema(t.Context(), f.store); err != nil { + t.Fatal(err) + } + engine, err := reviewexec.New(f.store, []reviewexec.Capability{{ID: "sdk-capability", Provider: "synthetic", Account: "fixture", Channels: []string{"cli", "hosted"}}}, reviewexec.WithNativeProjection()) + if err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + mux.Handle("/", f.handler) + engine.Register(mux) + f.handler = mux + setup := func(method, path string, body any, selected ...string) map[string]any { + t.Helper() + raw, _ := json.Marshal(body) + r := httptest.NewRequest(method, path, bytes.NewReader(raw)) + r.Header.Set("Authorization", "Bearer "+f.admin) + r.Header.Set("Idempotency-Key", core.NewID("setup")) + actor := f.sender + if len(selected) > 0 { + actor = selected[0] + } + r.Header.Set("X-FC-Worker", actor) + w := httptest.NewRecorder() + f.handler.ServeHTTP(w, r) + if w.Code < 200 || w.Code > 299 { + t.Fatal(w.Code, w.Body.String()) + } + var v map[string]any + if json.Unmarshal(w.Body.Bytes(), &v) != nil { + t.Fatal("setup response") + } + return v + } + const managerToken = "synthetic-private-sdk-manager" + digest := sha256.Sum256([]byte(managerToken)) + setup("POST", "/api/v1/projects/"+f.project+"/credentials", map[string]any{"token_sha256": hex.EncodeToString(digest[:]), "permissions": []string{"manage"}}) + setup("POST", "/api/v1/projects/"+f.project+"/reviews/execution/configuration", map[string]any{"expected_revision": 0, "capability_id": "sdk-capability", "mode": "independent", "queue": []int{2}, "channels": []string{"cli", "hosted"}, "paused": false}) + tokenFile := filepath.Join(t.TempDir(), "owner.token") + if os.WriteFile(tokenFile, []byte(managerToken), 0600) != nil { + t.Fatal("private token fixture") + } + var lose atomic.Bool + var originalWorker client.WorkerCreateReceipt + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == "POST" && strings.HasSuffix(r.URL.Path, "/workers") && lose.Swap(false) { + rec := httptest.NewRecorder() + f.handler.ServeHTTP(rec, r) + if rec.Code != 200 { + t.Error(rec.Code, rec.Body.String()) + } + if err := json.Unmarshal(rec.Body.Bytes(), &originalWorker); err != nil { + t.Error(err) + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(rec.Code) + w.Write([]byte("{")) + return + } + f.handler.ServeHTTP(w, r) + })) + defer server.Close() + identity := profile.Context{Profile: "owner", ServerURL: server.URL, InstanceID: f.store.InstanceID(), ProjectID: f.project, WorkerID: f.sender} + session := reviewControlsStdio(t, profiles(t, map[string]profile.Context{"owner": identity}, tokenFile), "owner") + var policy client.ReviewRequestReceipt + decodeResult(t, call(t, session, "review_policy_configure", map[string]any{"expected_revision": 0, "paused_channels": []string{}, "required_channels": []string{"cli", "hosted"}, "max_review_files": 100, "round_defaults": map[string]any{"hosted": map[string]any{"minimum": 2, "maximum": 5}, "cli": map[string]any{"minimum": 0, "maximum": 8}}, "idempotency_key": "policy"}), &policy) + var current client.ReviewPolicyRecord + decodeResult(t, call(t, session, "review_policy_read", nil), ¤t) + if current.Revision != policy.Revision || current.Policy.MaxReviewFiles != 100 || current.Policy.RoundDefaults == nil || current.Policy.RoundDefaults.Hosted.Maximum != 5 || current.Policy.RoundDefaults.CLI.Maximum != 8 { + t.Fatal(current) + } + var configured client.ReviewRequestReceipt + decodeResult(t, call(t, session, "review_execution_configure", map[string]any{"expected_revision": 1, "capability_id": "sdk-capability", "mode": "independent", "queue": []int{2, 4}, "channels": []string{"cli", "hosted"}, "paused": false, "idempotency_key": "execution"}), &configured) + if configured.Revision != 2 { + t.Fatal(configured) + } + for _, pair := range []struct { + pull int64 + channel string + maximum, minimum int64 + }{{2, "hosted", 3, 2}, {2, "cli", 6, 2}, {4, "hosted", 5, 2}, {4, "cli", 8, 0}} { + var control client.ReviewRoundControl + decodeResult(t, call(t, session, "review_rounds_read", map[string]any{"pull_number": pair.pull, "channel": pair.channel}), &control) + if !control.Configured || control.Minimum != pair.minimum || control.Maximum != pair.maximum || control.Used != 0 || control.Closed { + t.Fatal("SDK enrollment changed existing controls or missed defaults", control) + } + } + create := map[string]any{"name": "SDK Inspector", "idempotency_key": "create-worker"} + lose.Store(true) + diagnosticResult(t, call(t, session, "worker_create", create), "invalid_response", true) + var worker client.WorkerCreateReceipt + decodeResult(t, call(t, session, "worker_create", create), &worker) + if worker.Outcome != "created" || !reflect.DeepEqual(worker, originalWorker) { + t.Fatal(worker) + } + for i := 0; i < 2; i++ { + setup("POST", "/api/v1/projects/"+f.project+"/messages", map[string]any{"recipient_worker_id": f.recipient, "body": "Synthetic selected inbox"}) + } + var inbox client.Page[client.InboxItem] + decodeResult(t, call(t, session, "inbox_list", map[string]any{"worker_id": f.recipient, "limit": 1}), &inbox) + if len(inbox.Items) != 1 || !inbox.HasMore || inbox.Items[0].RecipientWorkerID != f.recipient { + t.Fatal(inbox) + } + diagnosticResult(t, call(t, session, "inbox_list", map[string]any{"worker_id": f.sender, "limit": 1, "cursor": inbox.Cursor}), "validation_failed", false) + newDigest := sha256.Sum256([]byte("new-private-sdk-credential")) + var grant client.ProjectCredentialReceipt + decodeResult(t, call(t, session, "project_credential_grant", map[string]any{"token_sha256": hex.EncodeToString(newDigest[:]), "permissions": []string{"read"}, "idempotency_key": "grant"}), &grant) + var update client.ProjectCredentialUpdateReceipt + decodeResult(t, call(t, session, "project_credential_update", map[string]any{"credential_id": grant.ID, "expected_permissions": []string{"read"}, "permissions": []string{"manage"}, "idempotency_key": "update"}), &update) + if len(update.Permissions) != 3 { + t.Fatal(update) + } + stale := diagnosticResult(t, call(t, session, "project_credential_update", map[string]any{"credential_id": grant.ID, "expected_permissions": []string{"read"}, "permissions": []string{"manage"}, "idempotency_key": "stale-update"}), "credential_permissions_changed", false) + details, ok := stale.Details.(map[string]any) + if !strings.Contains(stale.Action, "returned current_permissions") || !ok || !reflect.DeepEqual(details["current_permissions"], []any{"read", "write", "manage"}) { + t.Fatal(stale) + } + var revoke client.ProjectCredentialReceipt + decodeResult(t, call(t, session, "project_credential_revoke", map[string]any{"credential_id": grant.ID, "idempotency_key": "revoke"}), &revoke) + if revoke.Outcome != "revoked" { + t.Fatal(revoke) + } +} + +func TestProjectOwnerSDKInvalidBeforeCredentials(t *testing.T) { + identity := localContext() + session := reviewControlsStdio(t, profiles(t, map[string]profile.Context{"chosen": identity}, "missing-owner-token"), "chosen") + for _, v := range []struct{ name, raw string }{ + {"inbox_snapshot", `{"worker_id":"other"}`}, + {"inbox_ack", `{"message_id":"msg-one","worker_id":"","idempotency_key":"x"}`}, + {"review_policy_configure", `{"expected_revision":0,"paused_channels":[],"required_channels":["cli"],"idempotency_key":"x"}`}, + {"review_policy_configure", `{"expected_revision":0,"paused_channels":[],"required_channels":["cli"],"max_review_files":0,"round_defaults":null,"idempotency_key":"x"}`}, + {"review_policy_configure", `{"expected_revision":0,"paused_channels":[],"required_channels":["cli"],"max_review_files":0,"round_defaults":{"hosted":{"minimum":2,"maximum":1},"cli":{"minimum":0,"maximum":8}},"idempotency_key":"x"}`}, + {"review_policy_configure", `{"expected_revision":0,"paused_channels":[],"required_channels":["cli"],"max_review_files":0,"round_defaults":{"hosted":{"minimum":2,"maximum":5},"cli":{"maximum":8}},"idempotency_key":"x"}`}, + {"review_execution_configure", `{"expected_revision":0,"capability_id":"x","mode":"independent","queue":[],"channels":["cli"],"idempotency_key":"x"}`}, + {"worker_create", `{"name":" padded ","idempotency_key":"x"}`}, + {"project_credential_grant", `{"token":"raw secret","permissions":["manage"],"idempotency_key":"x"}`}, + {"project_credential_update", `{"credential_id":"credential-one","expected_permissions":["read"],"permissions":null,"idempotency_key":"x"}`}, + {"project_credential_revoke", `{"credential_id":"bad/id","idempotency_key":"x"}`}, + } { + diagnosticResult(t, call(t, session, v.name, json.RawMessage(v.raw)), "invalid_arguments", false) + } +} + +func TestInboxAcknowledgementOwnRecipientFormsReplay(t *testing.T) { + for _, explicitFirst := range []bool{false, true} { + t.Run(fmt.Sprint(explicitFirst), func(t *testing.T) { + f := mutationFixture(t) + service := httptest.NewServer(f.handler) + defer service.Close() + sender := connect(t, f.adapter(t, service.URL, f.sender), "") + recipient := connect(t, f.adapter(t, service.URL, f.recipient), "") + var message client.MessageReceipt + decodeResult(t, call(t, sender, "inbox_send", map[string]any{"idempotency_key": "send", "recipient_worker_id": f.recipient, "body": "ack forms"}), &message) + args := map[string]any{"idempotency_key": "ack", "message_id": message.ID} + if explicitFirst { + args["worker_id"] = f.recipient + } + var first, replay client.MessageReceipt + decodeResult(t, call(t, recipient, "inbox_ack", args), &first) + if explicitFirst { + delete(args, "worker_id") + } else { + args["worker_id"] = f.recipient + } + decodeResult(t, call(t, recipient, "inbox_ack", args), &replay) + if first != replay { + t.Fatalf("equivalent forms changed receipt: %v != %v", first, replay) + } + args["worker_id"] = f.sender + // Another recipient remains a distinct, unauthorized request, not a receipt replay. + diagnosticResult(t, call(t, recipient, "inbox_ack", args), "forbidden", false) + }) + } +} + +func TestInboxAcknowledgementExplicitSelfReplaysAcrossAdapters(t *testing.T) { + for _, cliFirst := range []bool{false, true} { + t.Run(fmt.Sprintf("cli-first=%v", cliFirst), func(t *testing.T) { + f := mutationFixture(t) + service := httptest.NewServer(f.handler) + defer service.Close() + sender := connect(t, f.adapter(t, service.URL, f.sender), "") + recipient := connect(t, f.adapter(t, service.URL, f.recipient), "") + profilePath := profiles(t, map[string]profile.Context{"chosen": { + ServerURL: service.URL, InstanceID: f.store.InstanceID(), ProjectID: f.project, WorkerID: f.recipient, + }}, f.credential) + + var message client.MessageReceipt + decodeResult(t, call(t, sender, "inbox_send", map[string]any{"idempotency_key": "send", "recipient_worker_id": f.recipient, "body": "cross-adapter ACK"}), &message) + mcpAck := func() (got client.MessageReceipt) { + decodeResult(t, call(t, recipient, "inbox_ack", map[string]any{"idempotency_key": "ack", "message_id": message.ID, "worker_id": f.recipient}), &got) + return got + } + cliAck := func() (got client.MessageReceipt) { + var out, diagnostic bytes.Buffer + args := []string{"--profiles-file", profilePath, "--profile", "chosen", "inbox", "ack", message.ID, "--worker", f.recipient, "--key", "ack"} + if code := cli.RunContext(t.Context(), args, nil, &out, &diagnostic); code != cli.ExitSuccess { + t.Fatalf("CLI ACK exited %d: %s", code, diagnostic.String()) + } + if err := json.Unmarshal(out.Bytes(), &got); err != nil { + t.Fatal(err) + } + return got + } + + var first, replay client.MessageReceipt + if cliFirst { + first, replay = cliAck(), mcpAck() + } else { + first, replay = mcpAck(), cliAck() + } + if first.Outcome != "acknowledged" || replay != first { + t.Fatalf("expected the original acknowledgement receipt on replay: first=%+v replay=%+v", first, replay) + } + }) + } +} diff --git a/internal/mcpadapter/review_queue_edit.go b/internal/mcpadapter/review_queue_edit.go index f8995cde3..945536547 100644 --- a/internal/mcpadapter/review_queue_edit.go +++ b/internal/mcpadapter/review_queue_edit.go @@ -7,7 +7,7 @@ import ( "github.com/benhook1013/FireController/internal/strictjson" ) -// This is the canonical administrator queue-edit document, independent of +// This is the canonical project-management queue-edit document, independent of // native review request policy and scheduling configuration. func queueEditArguments(raw json.RawMessage) (arguments, error) { var in struct { @@ -21,5 +21,5 @@ func queueEditArguments(raw json.RawMessage) (arguments, error) { } func queueEditDefinition() definition { - return definition{"review_queue_edit", "Apply the existing administrator queue edit document for selected metadata, explicit defunct/superseded retirement, reactivation or relative ordering. Requires expected_revision, repository_id and source inside document plus an explicit idempotency key. Preserves evidence and execution policy; performs no provider work.", map[string]any{"type": "object", "additionalProperties": false, "required": []string{"document", "idempotency_key"}, "properties": map[string]any{"document": map[string]any{"type": "object", "description": "Strict native queue edit document, at most 256 KiB; up to 100 metadata/retirement entries plus up to 100 order entries. Validated by the typed client before service I/O."}, "idempotency_key": map[string]any{"type": "string", "minLength": 1, "maxLength": 128}}}} + return definition{"review_queue_edit", "Apply the existing native queue edit document for selected metadata, explicit defunct/superseded retirement, reactivation or relative ordering. Requires project management or instance administration. Requires expected_revision, repository_id and source inside document plus an explicit idempotency key. Preserves evidence and execution policy; performs no provider work.", map[string]any{"type": "object", "additionalProperties": false, "required": []string{"document", "idempotency_key"}, "properties": map[string]any{"document": map[string]any{"type": "object", "description": "Strict native queue edit document, at most 256 KiB; up to 100 metadata/retirement entries plus up to 100 order entries. Validated by the typed client before service I/O."}, "idempotency_key": map[string]any{"type": "string", "minLength": 1, "maxLength": 128}}}} } diff --git a/internal/mcpadapter/tools.go b/internal/mcpadapter/tools.go index 92bd30d21..fb60b931b 100644 --- a/internal/mcpadapter/tools.go +++ b/internal/mcpadapter/tools.go @@ -21,6 +21,9 @@ const maxToolWaitSeconds = 50 type arguments struct { operationControl client.ReviewOperationControl ciWatchTargets []client.CIWatchTarget + ownerManagement *ownerManagementInvocation + existingManagement *existingManagementArgs + includeRetired bool reviewRun client.ReviewRunRequest reviewOperations client.ReviewOperationsOptions operationStatus *operationStatusInput @@ -67,6 +70,8 @@ type definition struct { func boundServer(binding profile.Binding) *mcp.Server { s := mcp.NewServer(&mcp.Implementation{Name: "firecontroller", Version: Version}, &mcp.ServerOptions{Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), Capabilities: &mcp.ServerCapabilities{Tools: &mcp.ToolCapabilities{}}, PageSize: 128}) definitions := append(toolDefinitions(), checkpointDefinitions()...) + definitions = append(definitions, ownerManagementDefinitions()...) + definitions = append(definitions, existingManagementDefinitions()...) definitions = append(definitions, reviewRunDefinitions()...) definitions = append(definitions, operationListDefinition(), operationControlDefinition()) definitions = append(definitions, roundControlDefinitions()...) @@ -83,14 +88,18 @@ func boundServer(binding profile.Binding) *mcp.Server { transports := sessionTransports{pools: make(map[*mcp.ServerSession]*client.TransportPool)} for _, tool := range definitions { known[tool.name] = true - write := tool.name == "review_operation_control" || adoptionWrite(tool.name) || tool.name == "review_rounds_configure" || tool.name == "review_queue_edit" || projectMapWrite(tool.name) || noteWrite(tool.name) || tool.name == "worker_pause_replace" || checkpointWrite(tool.name) || mutationTool(tool.name) || tool.name == "review_request" || tool.name == "review_source_refresh" + write := ownerManagementWrite(tool.name) || existingManagementWrite(tool.name) || tool.name == "review_operation_control" || adoptionWrite(tool.name) || tool.name == "review_rounds_configure" || tool.name == "review_queue_edit" || projectMapWrite(tool.name) || noteWrite(tool.name) || tool.name == "worker_pause_replace" || checkpointWrite(tool.name) || mutationTool(tool.name) || tool.name == "review_request" || tool.name == "review_source_refresh" openWorld := tool.name == "wait_for_ci" || tool.name == "review_start" || checkpointWrite(tool.name) || tool.name == "review_request" || tool.name == "review_source_refresh" - destructive := tool.name == "review_operation_control" || adoptionDestructive(tool.name) || tool.name == "review_rounds_configure" || tool.name == "review_queue_edit" || tool.name == "worker_pause_replace" || tool.name == "job_primary_replace" || tool.name == "map_entry_replace" || tool.name == "job_workstream_replace" || tool.name == "note_update" || tool.name == "job_edit" || tool.name == "job_checklist_replace" || tool.name == "review_finding_decide" || tool.name == "review_finding_fix" || tool.name == "review_finding_route" || tool.name == "review_route_decide" || tool.name == "review_route_fix" + destructive := ownerManagementDestructive(tool.name) || existingManagementDestructive(tool.name) || tool.name == "review_operation_control" || adoptionDestructive(tool.name) || tool.name == "review_rounds_configure" || tool.name == "review_queue_edit" || tool.name == "worker_pause_replace" || tool.name == "job_primary_replace" || tool.name == "map_entry_replace" || tool.name == "job_workstream_replace" || tool.name == "note_update" || tool.name == "job_edit" || tool.name == "job_checklist_replace" || tool.name == "review_finding_decide" || tool.name == "review_finding_fix" || tool.name == "review_finding_route" || tool.name == "review_route_decide" || tool.name == "review_route_fix" s.AddTool(&mcp.Tool{Name: tool.name, Description: tool.description, InputSchema: tool.schema, Annotations: &mcp.ToolAnnotations{ReadOnlyHint: !write, IdempotentHint: true, DestructiveHint: &destructive, OpenWorldHint: &openWorld}}, func(ctx context.Context, request *mcp.CallToolRequest) (*mcp.CallToolResult, error) { var args arguments var err error if tool.name == "wait_for_ci" { args, err = ciWatchArguments(request.Params.Arguments) + } else if ownerManagementTool(tool.name) { + args, err = ownerManagementArguments(tool.name, request.Params.Arguments) + } else if existingManagementTool(tool.name) { + args.existingManagement, err = parseExistingManagementArguments(tool.name, request.Params.Arguments) } else if adoptionTool(tool.name) { args.adoption, err = parseAdoptionArguments(tool.name, request.Params.Arguments) } else if tool.name == "review_rounds_read" || tool.name == "review_rounds_configure" { @@ -141,6 +150,20 @@ func boundServer(binding profile.Binding) *mcp.Server { } options := client.PageOptions{Limit: args.limit, Cursor: args.cursor} var value any + if ownerManagementTool(tool.name) { + value, err = executeOwnerManagement(ctx, service, args.ownerManagement) + if err != nil { + return resultFailure(err), nil + } + return result(value, false), nil + } + if existingManagementTool(tool.name) { + value, err = executeExistingManagement(ctx, service, args.existingManagement) + if err != nil { + return resultFailure(err), nil + } + return result(value, false), nil + } switch tool.name { case "review_start": var result client.ReviewRunResult @@ -248,7 +271,7 @@ func boundServer(binding profile.Binding) *mcp.Server { case "worker_pause_history": value, err = service.WorkerPauseHistory(ctx, options) case "workers_list": - value, err = service.Workers(ctx, options) + value, err = service.WorkersWithRetired(ctx, options, args.includeRetired) case "jobs_list": value, err = service.Jobs(ctx, options, client.JobFilter{WorkerID: args.worker, Status: args.status}) case "jobs_assigned": @@ -280,7 +303,7 @@ func boundServer(binding profile.Binding) *mcp.Server { case "job_checklist_history": value, err = service.JobChecklistHistory(ctx, args.id, options) case "inbox_list": - value, err = service.Inbox(ctx, options, client.InboxFilter{Unread: args.unread, Unacknowledged: args.unack}) + value, err = service.Inbox(ctx, options, client.InboxFilter{Unread: args.unread, Unacknowledged: args.unack}, args.worker) case "inbox_snapshot": value, err = service.InboxSnapshot(ctx, options, client.InboxFilter{Unread: args.unread, Unacknowledged: args.unack}) case "inbox_events": @@ -296,7 +319,7 @@ func boundServer(binding profile.Binding) *mcp.Server { case "inbox_seen": value, err = service.MarkSeen(ctx, args.key, args.id) case "inbox_ack": - value, err = service.Acknowledge(ctx, args.key, args.id) + value, err = service.Acknowledge(ctx, args.key, args.id, args.worker) } if err != nil { return resultFailure(err), nil diff --git a/internal/mcpadapter/worker_retirement_test.go b/internal/mcpadapter/worker_retirement_test.go new file mode 100644 index 000000000..944d7ca10 --- /dev/null +++ b/internal/mcpadapter/worker_retirement_test.go @@ -0,0 +1,133 @@ +package mcpadapter_test + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "reflect" + "strings" + "sync/atomic" + "testing" + + "github.com/benhook1013/FireController/internal/cli" + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/profile" +) + +func TestWorkerRetirementSDKAndCLIExplicitRecipientWithoutIdentitySwitch(t *testing.T) { + f := mutationFixture(t) + var retirePosts atomic.Int64 + service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/retire") { + retirePosts.Add(1) + } + if r.Method == "POST" && (strings.HasSuffix(r.URL.Path, "/retire") || strings.HasSuffix(r.URL.Path, "/ack")) && r.Header.Get("X-FC-Worker") != f.sender { + t.Error("selected resource impersonated recipient") + } + f.handler.ServeHTTP(w, r) + })) + defer service.Close() + binding := profile.Context{Profile: "writer", ServerURL: service.URL, InstanceID: f.store.InstanceID(), ProjectID: f.project, WorkerID: f.sender} + adminFile := filepath.Join(t.TempDir(), "admin.token") + if err := os.WriteFile(adminFile, []byte(f.admin), 0600); err != nil { + t.Fatal(err) + } + writerPath := profiles(t, map[string]profile.Context{"writer": binding}, f.credential) + adminPath := profiles(t, map[string]profile.Context{"admin": binding}, adminFile) + sdk := reviewControlsStdio(t, writerPath, "writer") + invoke := func(path, selected string, args ...string) []byte { + t.Helper() + var out, diag bytes.Buffer + full := append([]string{"--profiles-file", path, "--profile", selected}, args...) + if code := cli.RunContext(t.Context(), full, nil, &out, &diag); code != cli.ExitSuccess || diag.Len() != 0 { + t.Fatal(code, diag.String()) + } + return out.Bytes() + } + var message client.MessageReceipt + decodeResult(t, call(t, sdk, "inbox_send", map[string]any{"recipient_worker_id": f.recipient, "body": "Retirement must not silently acknowledge this", "idempotency_key": "retirement-message"}), &message) + var preview client.WorkerRetirement + decodeResult(t, call(t, sdk, "worker_retirement_read", map[string]any{"worker_id": f.recipient}), &preview) + if preview.CanRetire || preview.Retired || preview.Blockers.Messages.Count != 1 || !reflect.DeepEqual(preview.Blockers.Messages.IDs, []string{message.ID}) { + t.Fatal("unacknowledged message not visible", preview) + } + blocked := diagnosticResult(t, call(t, sdk, "worker_retire", map[string]any{"worker_id": f.recipient, "idempotency_key": "blocked-retirement"}), "worker_retirement_blocked", false) + var blockers client.WorkerRetirementBlockers + data, _ := json.Marshal(blocked.Details) + if json.Unmarshal(data, &blockers) != nil || blockers.Messages.Count != 1 || !reflect.DeepEqual(blockers.Messages.IDs, []string{message.ID}) { + t.Fatal("blocked retirement lost current safe handles", blocked) + } + diagnosticResult(t, call(t, sdk, "inbox_ack", map[string]any{"message_id": message.ID, "worker_id": f.recipient, "idempotency_key": "writer-cannot-ack-other"}), "forbidden", false) + diagnosticResult(t, call(t, sdk, "inbox_seen", map[string]any{"message_id": message.ID, "worker_id": f.recipient, "idempotency_key": "seen-stays-own"}), "invalid_arguments", false) + var ack client.MessageReceipt + if json.Unmarshal(invoke(adminPath, "admin", "inbox", "ack", message.ID, "--worker", f.recipient, "--key", "manager-selected-ack"), &ack) != nil || ack.Outcome != "acknowledged" { + t.Fatal("manager recipient ACK failed", ack) + } + if json.Unmarshal(invoke(writerPath, "writer", "workers", "retirement", f.recipient), &preview) != nil || !preview.CanRetire { + t.Fatal(preview) + } + var retired client.WorkerRetirementReceipt + request := map[string]any{"worker_id": f.recipient, "idempotency_key": "shared-retirement"} + decodeResult(t, call(t, sdk, "worker_retire", request), &retired) + var replay client.WorkerRetirementReceipt + if json.Unmarshal(invoke(writerPath, "writer", "workers", "retire", f.recipient, "--key", "shared-retirement"), &replay) != nil || replay != retired || retired.Outcome != "retired" || retired.Revision != 2 { + t.Fatal("CLI/SDK replay diverged", retired, replay) + } + if json.Unmarshal(invoke(writerPath, "writer", "workers", "retire", f.recipient, "--key", "already-retired"), &replay) != nil || replay.Outcome != "unchanged" { + t.Fatal(replay) + } + var active, archive client.Page[client.Worker] + decodeResult(t, call(t, sdk, "workers_list", map[string]any{}), &active) + decodeResult(t, call(t, sdk, "workers_list", map[string]any{"include_retired": true}), &archive) + if len(active.Items) != 1 || active.Items[0].ID != f.sender || len(archive.Items) != 2 { + t.Fatal("active/archive list wrong", active, archive) + } + found := false + for _, w := range archive.Items { + if w.ID == f.recipient { + found = w.Retired + } + } + if !found { + t.Fatal("retired identity lost", archive) + } + var cliArchive client.Page[client.Worker] + if json.Unmarshal(invoke(writerPath, "writer", "workers", "list", "--include-retired"), &cliArchive) != nil || !reflect.DeepEqual(cliArchive, archive) { + t.Fatal("CLI archive differs", cliArchive, archive) + } + if retirePosts.Load() != 4 || f.providers.Load() != 1 { + t.Fatal("automatic retry/provider work", retirePosts.Load(), f.providers.Load()) + } + var retirementEvents int + if err := f.store.DB().QueryRow("SELECT count(*) FROM events WHERE project_id=? AND event_type='workers.retired'", f.project).Scan(&retirementEvents); err != nil || retirementEvents != 1 { + t.Fatal("retirement duplicated", retirementEvents, err) + } +} + +func TestWorkerRetirementSDKAndCLIInvalidStayOffline(t *testing.T) { + sdk := reviewControlsStdio(t, profiles(t, map[string]profile.Context{"chosen": localContext()}, "missing-private-credential"), "chosen") + for _, tc := range []struct{ name, raw string }{ + {"worker_retirement_read", `{"worker_id":null}`}, + {"worker_retire", `{"worker_id":"worker-one"}`}, + {"worker_retire", `{"worker_id":"worker-one","idempotency_key":"x","expected_revision":1}`}, + {"workers_list", `{"include_retired":null}`}, + {"inbox_ack", `{"message_id":"message-one","worker_id":null,"idempotency_key":"x"}`}, + } { + diagnosticResult(t, call(t, sdk, tc.name, json.RawMessage(tc.raw)), "invalid_arguments", false) + } + for _, operation := range []string{"retirement", "retire"} { + var out, diag bytes.Buffer + if code := cli.RunContext(t.Context(), []string{"workers", operation, "--help"}, nil, &out, &diag); code != 0 || diag.Len() != 0 || !strings.Contains(out.String(), "unacknowledged") || !strings.Contains(out.String(), "nothing is moved") { + t.Fatal("missing offline retirement help", code, out.String(), diag.String()) + } + } + for _, args := range [][]string{{"workers", "retirement"}, {"workers", "retire", "worker-one"}, {"workers", "list", "--include-retired=false"}, {"inbox", "seen", "message-one", "--worker", "worker-other", "--key", "x"}, {"inbox", "ack", "message-one", "--worker", "", "--key", "x"}} { + var out, diag bytes.Buffer + if code := cli.RunContext(t.Context(), append([]string{"--profile", "absent", "--profiles-file", "/unavailable"}, args...), nil, &out, &diag); code != cli.ExitUsage || out.Len() != 0 { + t.Fatal(args, code, diag.String()) + } + } +} diff --git a/internal/publicsite/administration_test.go b/internal/publicsite/administration_test.go new file mode 100644 index 000000000..b6c7c25ee --- /dev/null +++ b/internal/publicsite/administration_test.go @@ -0,0 +1,147 @@ +package publicsite + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "errors" + "net/http/httptest" + "testing" + + "github.com/benhook1013/FireController/internal/core" +) + +func publicationScope(t *testing.T, f *publicationFixture, token string) core.Scope { + t.Helper() + r := httptest.NewRequest("GET", f.base()+"/publication", nil) + r.SetPathValue("project_id", f.project) + r.Header.Set("Authorization", "Bearer "+token) + r.Header.Set("X-FC-Worker", f.worker) + scope, err := f.store.AdminScope(r) + if err != nil { + t.Fatal(err) + } + return scope +} + +func requirePublicationForbidden(t *testing.T, err error) { + t.Helper() + var failure *core.Error + if !errors.As(err, &failure) || failure.Code != "forbidden" { + t.Errorf("want forbidden, got %v", err) + } +} + +func TestPublicationRejectsProjectManager(t *testing.T) { + f := newPublicationFixture(t) + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=1 WHERE project_id=?`, f.project); err != nil { + t.Fatal(err) + } + scope := publicationScope(t, f, f.reader) + input := Approved{0, true, testPublicManifest()} + preview := f.service.previewHash(scope, input) + base := f.base() + "/publication" + for _, call := range []struct { + method, path string + body any + }{ + {"GET", base, nil}, + {"POST", base + "/preview", input}, + {"PUT", base, map[string]any{"expected_revision": 0, "enabled": true, "manifest": input.Manifest, "preview_sha256": preview}}, + {"POST", base + "/unpublish", map[string]any{"expected_revision": 1}}, + } { + t.Run(call.method+call.path, func(t *testing.T) { + w := f.call(t, call.method, call.path, f.reader, "manager-publication", call.body) + if w.Code != 403 { + t.Fatalf("manager publication returned %d: %s", w.Code, w.Body.String()) + } + }) + } + // Service callers must receive the same boundary, even with a valid project + // administrative scope constructed outside the HTTP publication handlers. + _, err := f.service.Configuration(t.Context(), scope) + requirePublicationForbidden(t, err) + _, err = f.service.Preview(t.Context(), scope, input) + requirePublicationForbidden(t, err) + _, err = f.service.Apply(t.Context(), scope, "manager-apply", input, preview) + requirePublicationForbidden(t, err) + _, err = f.service.Unpublish(t.Context(), scope, "manager-unpublish", 0) + requirePublicationForbidden(t, err) + var count int + if err := f.store.DB().QueryRow(`SELECT count(*) FROM project_publications`).Scan(&count); err != nil || count != 0 { + t.Fatal("manager changed publication", count, err) + } +} + +func TestPublicationRechecksCurrentAdministratorBeforeReceiptReplay(t *testing.T) { + for _, mode := range []string{"demoted", "revoked"} { + t.Run(mode, func(t *testing.T) { + f := newPublicationFixture(t) + scope := publicationScope(t, f, f.admin) + input := Approved{0, true, testPublicManifest()} + preview, err := f.service.Preview(t.Context(), scope, input) + if err != nil { + t.Fatal(err) + } + applied, err := f.service.Apply(t.Context(), scope, "admin-apply", input, preview.SHA256) + if err != nil { + t.Fatal(err) + } + replay, err := f.service.Apply(t.Context(), scope, "admin-apply", input, preview.SHA256) + if err != nil || !bytes.Equal(applied, replay) { + t.Fatal("admin apply replay", err) + } + unpublished, err := f.service.Unpublish(t.Context(), scope, "admin-unpublish", 1) + if err != nil { + t.Fatal(err) + } + replay, err = f.service.Unpublish(t.Context(), scope, "admin-unpublish", 1) + if err != nil || !bytes.Equal(unpublished, replay) { + t.Fatal("admin unpublish replay", err) + } + // Demotion retains project management, so the ordinary AdminScope contract + // still permits it. Publication must not leak either retained receipt. + digest := sha256.Sum256([]byte(f.admin)) + hash := hex.EncodeToString(digest[:]) + if _, err = f.store.DB().Exec(`INSERT INTO grants(credential_id,project_id,can_read,can_write,can_manage) SELECT id,?,1,1,1 FROM credentials WHERE token_sha256=?`, f.project, hash); err != nil { + t.Fatal(err) + } + query := `UPDATE credentials SET is_admin=0 WHERE token_sha256=?` + if mode == "revoked" { + query = `UPDATE credentials SET revoked=1 WHERE token_sha256=?` + } + if _, err = f.store.DB().Exec(query, hash); err != nil { + t.Fatal(err) + } + check := func(err error) { + t.Helper() + var e *core.Error + want := "forbidden" + if mode == "revoked" { + want = "unauthorized" + } + if !errors.As(err, &e) || e.Code != want { + t.Errorf("want %s, got %v", want, err) + } + } + _, err = f.service.Configuration(t.Context(), scope) + check(err) + _, err = f.service.Preview(t.Context(), scope, Approved{2, true, input.Manifest}) + check(err) + _, err = f.service.Apply(t.Context(), scope, "admin-apply", input, preview.SHA256) + check(err) + _, err = f.service.Unpublish(t.Context(), scope, "admin-unpublish", 1) + check(err) + next := Approved{2, true, input.Manifest} + _, err = f.service.Apply(t.Context(), scope, "new-apply", next, f.service.previewHash(scope, next)) + check(err) + _, err = f.service.Unpublish(t.Context(), scope, "new-unpublish", 2) + check(err) + var enabled bool + var revision int64 + if err = f.store.DB().QueryRow(`SELECT enabled,revision FROM project_publications WHERE project_id=?`, f.project).Scan(&enabled, &revision); err != nil || enabled || revision != 2 { + t.Fatal("stale admin changed publication", enabled, revision, err) + } + }) + } +} diff --git a/internal/publicsite/service.go b/internal/publicsite/service.go index 443ea4adf..c688d0f18 100644 --- a/internal/publicsite/service.go +++ b/internal/publicsite/service.go @@ -229,6 +229,7 @@ func preserveReviewFacts(ctx context.Context, tx *sql.Tx, project string, m Mani } func (s *Service) Configuration(ctx context.Context, scope core.Scope) (Configuration, error) { + scope = scope.RequireInstanceAdministration() out := Configuration{} err := s.store.Read(ctx, scope, func(ctx context.Context, tx *sql.Tx) error { r, found, err := readRecord(ctx, tx, scope.ProjectID) @@ -246,6 +247,7 @@ func (s *Service) Configuration(ctx context.Context, scope core.Scope) (Configur } func (s *Service) Preview(ctx context.Context, scope core.Scope, input Approved) (Preview, error) { + scope = scope.RequireInstanceAdministration() input, err := approved(input) if err != nil { return Preview{}, err @@ -269,6 +271,7 @@ func (s *Service) Preview(ctx context.Context, scope core.Scope, input Approved) } func (s *Service) Apply(ctx context.Context, scope core.Scope, key string, input Approved, preview string) (json.RawMessage, error) { + scope = scope.RequireInstanceAdministration() input, err := approved(input) if err != nil { return nil, err @@ -334,6 +337,7 @@ func (s *Service) Apply(ctx context.Context, scope core.Scope, key string, input } func (s *Service) Unpublish(ctx context.Context, scope core.Scope, key string, revision int64) (json.RawMessage, error) { + scope = scope.RequireInstanceAdministration() if revision < 0 || revision >= math.MaxInt64 { return nil, invalid() } diff --git a/internal/reviewexec/cli_draft_wait.go b/internal/reviewexec/cli_draft_wait.go index 3505809bd..fed5ea605 100644 --- a/internal/reviewexec/cli_draft_wait.go +++ b/internal/reviewexec/cli_draft_wait.go @@ -98,7 +98,9 @@ func (e *Engine) checkCLIDraft(ctx context.Context, o Operation, drivers map[str var refusal *core.Error if errors.As(err, &refusal) { if refusal.Code == "overloaded" { - return false, false, false, nil + // The worker still defers this row but must not acknowledge + // exhausted work when storage prevented the readiness read. + return false, false, false, err } if refusal.Status >= 400 && refusal.Status < 500 { // Let the normal claim settle a local refusal. A draft wait diff --git a/internal/reviewexec/cli_wait_test.go b/internal/reviewexec/cli_wait_test.go index 7595c3eb7..d051d5925 100644 --- a/internal/reviewexec/cli_wait_test.go +++ b/internal/reviewexec/cli_wait_test.go @@ -1191,10 +1191,17 @@ func TestSupervisorRetriesStartupCLIExhaustionWithoutRestart(t *testing.T) { }() deadline := time.Now().Add(12 * time.Second) for time.Now().Before(deadline) { - current, err := readOperation(t.Context(), f.store.DB(), attemptProject, o.ID) + // The supervisor atomically writes the operation and its wait. + // Read both from one snapshot, not across a concurrent commit. + tx, err := f.store.DB().BeginTx(t.Context(), &sql.TxOptions{ReadOnly: true}) if err != nil { t.Fatal(err) } + current, readErr := readOperation(t.Context(), tx, attemptProject, o.ID) + closeErr := tx.Rollback() + if err := errors.Join(readErr, closeErr); err != nil { + t.Fatal(err) + } if current.State == "queued" && current.Wait != nil { return } diff --git a/internal/reviewexec/pending_cursor_timeout_test.go b/internal/reviewexec/pending_cursor_timeout_test.go new file mode 100644 index 000000000..590394d4f --- /dev/null +++ b/internal/reviewexec/pending_cursor_timeout_test.go @@ -0,0 +1,282 @@ +package reviewexec + +import ( + "context" + "errors" + "fmt" + "github.com/benhook1013/FireController/internal/core" + "runtime" + "strings" + "testing" + "time" +) + +func TestPendingCandidateReadKeepsCompletedValidationAtExpiry(t *testing.T) { + ctx, cancel := context.WithDeadline(t.Context(), time.Unix(1, 0)) + defer cancel() + if err := pendingCandidateReadError(ctx, Operation{ID: "validated"}, nil, true); err != nil { + t.Fatal("discarded a validated ordinary candidate", err) + } + if err := pendingCandidateReadError(ctx, Operation{}, nil, true); !errors.Is(err, context.DeadlineExceeded) { + t.Fatal("empty classification hid row-local expiry", err) + } + if err := pendingCandidateReadError(ctx, Operation{}, nil, false); err != nil { + t.Fatal("rewound an unavailable row with no returned prefix or recorded retry", err) + } + storageFailure := errors.New("ordinary test storage failure") + if err := pendingCandidateReadError(ctx, Operation{}, storageFailure, false); !errors.Is(err, storageFailure) { + t.Fatal("expiry concealed a storage error", err) + } +} + +func TestPendingDraftOnlyExhaustionRetainsCursorUntilSettlement(t *testing.T) { + e := &Engine{} + const lane = 1 + cursor := pendingScanPosition{"2020", "ordinary-origin"} + before := pendingScanPosition{"2021", "last examined"} + slow := pendingScanPosition{"2022", "slow"} + advance := func(pos pendingScanPosition) { e.pendingScanCursor[lane] = pos } + var receipt pendingExhaustion + + // A Draft was returned, but no ordinary item was available before expiry. + retainPendingExhaustion(advance, cursor, nil, before, slow, &receipt) + if receipt.timedOut != slow || e.pendingScanCursor[lane] != cursor { + t.Fatal("draft-only batch failed to retain ordinary replay and exhaustion", receipt) + } + e.finishPendingBatch(lane, receipt, false, false) + e.finishPendingBatch(lane, receipt, true, true) + if e.pendingScanCursor[lane] != cursor || e.pendingScanTimeout[lane] != (pendingScanPosition{}) { + t.Fatal("an unconfirmed or overloaded draft-only batch advanced ordinary work") + } + e.finishPendingBatch(lane, receipt, true, false) + if e.pendingScanCursor[lane] != before || e.pendingScanTimeout[lane] != slow { + t.Fatal("the slow ordinary row did not gain a fresh scan") + } + e.rewindTimedOutPendingCandidate(lane, before, slow) + if e.pendingScanCursor[lane] != slow || e.pendingScanTimeout[lane] != (pendingScanPosition{}) { + t.Fatal("a genuinely repeated deadline did not rotate past the slow row") + } +} + +func TestPendingOrdinaryExhaustionUsesSlowRowPredecessorOnlyAfterSettlement(t *testing.T) { + e := &Engine{} + prefix := pendingScanPosition{"2020", "prefix"} + before := pendingScanPosition{"2021", "slow-predecessor"} + slow := pendingScanPosition{"2022", "slow"} + var receipt pendingExhaustion + retainPendingExhaustion(func(pos pendingScanPosition) { e.pendingScanCursor[0] = pos }, + pendingScanPosition{}, &prefix, before, slow, &receipt) + if e.pendingScanCursor[0] != prefix { + t.Fatal("ordinary prefix was not retained for replay before settlement") + } + e.finishPendingBatch(0, receipt, true, false) + if e.pendingScanCursor[0] != before || e.pendingScanTimeout[0] != slow { + t.Fatal("confirmed prefix was substituted for the slow row's predecessor") + } +} + +func TestPendingCandidateTimeoutRetriesOnceThenRotates(t *testing.T) { + e := &Engine{} + prefix := pendingScanPosition{"2020", "prefix"} + slow := pendingScanPosition{"2021", "slow"} + later := pendingScanPosition{"2022", "later"} + e.rewindTimedOutPendingCandidate(0, prefix, slow) + if e.pendingScanCursor[0] != prefix { + t.Fatal("late-budget candidate did not get a fresh retry") + } + e.rewindTimedOutPendingCandidate(1, prefix, slow) + if e.pendingScanCursor[1] != prefix { + t.Fatal("independent draft worker inherited ordinary worker retry") + } + e.rewindTimedOutPendingCandidate(0, prefix, slow) + if e.pendingScanCursor[0] != slow || e.pendingScanTimeout[0] != (pendingScanPosition{}) { + t.Fatal("repeated offender still blocks traversal to later candidates") + } + e.rewindTimedOutPendingCandidate(0, slow, later) + if e.pendingScanCursor[0] != slow || e.pendingScanTimeout[0] != later { + t.Fatal("a different candidate did not get its own retry") + } + e.finishPendingCandidateValidation(0, later) + e.rewindTimedOutPendingCandidate(0, slow, later) + if e.pendingScanCursor[0] != slow { + t.Fatal("successful intervening validation did not break the streak") + } + e.rewindTimedOutPendingCandidate(1, prefix, slow) + if e.pendingScanCursor[1] != slow { + t.Fatal("draft worker did not rotate past its own repeat") + } +} + +func TestPendingCandidateTimeoutRotationReachesLaterWorkAndWraps(t *testing.T) { + f := supervisorFixture(t) + f.configure(t, otherAttemptProject, "other-account", 0, false) + slow := f.enqueue(t, attemptProject, "slow-ordinary", "hosted", 2, 1) + later := f.enqueue(t, otherAttemptProject, "later-ordinary", "hosted", 2, 1) + const old = "2020-01-01T00:00:00Z" + admissionSQL(t, f, "UPDATE review_operations SET created_at=? WHERE id=?", old, slow.ID) + start := pendingScanPosition{} + offender := pendingScanPosition{old, slow.ID} + // Inject the scan's already-classified per-row deadline outcome rather + // than racing SQLite or sleeping for the actual two-second budget. + f.e.rewindTimedOutPendingCandidate(0, start, offender) + f.e.rewindTimedOutPendingCandidate(0, start, offender) + operations, err := f.e.pendingForWorker(t.Context(), false) + if err != nil || len(operations) != 1 || operations[0].ID != later.ID { + t.Fatal("later eligible work was starved after repeated timeout", operations, err) + } + if f.e.pendingScanCursor[0] != start || f.e.pendingScanTimeout[0] != start { + t.Fatal("end of traversal did not reset to the oldest queued candidate") + } + operations, err = f.e.pendingForWorker(t.Context(), false) + if err != nil || len(operations) != 2 || operations[0].ID != slow.ID { + t.Fatal("wrapped scan dropped the retained candidate", operations, err) + } + if operations[0].State != "queued" || operations[0].AttemptID != "" { + t.Fatal("rotation changed the retained request", operations[0]) + } +} + +func TestMixedPendingBatchRotatesOnlyAfterRowLocalExhaustion(t *testing.T) { + f := supervisorFixture(t) + f.configure(t, otherAttemptProject, "other-account", 0, false) + prefix := f.enqueue(t, attemptProject, "mixed-prefix-rotate", "cli", 2, 1) + slow := f.enqueue(t, otherAttemptProject, "mixed-slow-rotate", "cli", 2, 1) + later := f.enqueue(t, attemptProject, "mixed-later-rotate", "hosted", 2, 1) + for i, id := range []string{prefix.ID, slow.ID, later.ID} { + admissionSQL(t, f, "UPDATE review_operations SET created_at=? WHERE id=?", fmt.Sprintf("2020-01-01T00:00:0%dZ", i), id) + } + admissionSQL(t, f, "UPDATE review_execution_config SET body_json='broken' WHERE project_id=?", otherAttemptProject) + for i := range 2 { + scanCtx, cancel := context.WithTimeout(t.Context(), time.Second) + hitSlow := false + f.e.schedulingNow = func() time.Time { + var pcs [8]uintptr + frames := runtime.CallersFrames(pcs[:runtime.Callers(2, pcs[:])]) + for { + frame, more := frames.Next() + if strings.HasSuffix(frame.Function, ".skipUnavailableConfiguration") { + hitSlow = true + <-scanCtx.Done() + break + } + if !more { + break + } + } + return time.Now().UTC() + } + var receipt pendingExhaustion + operations, err := f.e.scanPendingInLane(scanCtx, false, 256, 0, &receipt) + cancel() + f.e.schedulingNow = nil + if i == 1 { + if !hitSlow || !errors.Is(err, context.DeadlineExceeded) || len(operations) != 0 { + t.Fatal("fresh retry did not start directly at slow row", operations, receipt, err) + } + break + } + if err != nil || !hitSlow || len(operations) != 1 || operations[0].ID != prefix.ID || receipt.timedOut.id != slow.ID { + t.Fatal("missing exact prefix and offender", operations, receipt, err) + } + // Simulate an operation read superseded before the guarded claim; + // the durable operation and its journal remain internally consistent. + operations[0].Revision++ + if err := f.e.processPendingBatch(t.Context(), nil, func() {}, 0, operations, receipt); err != nil { + t.Fatal(err) + } + if state := supervisorOperationState(t, f, prefix.ID); state != "queued" { + t.Fatal("stale prefix claimed", state) + } + if i == 0 && f.e.pendingScanCursor[0].id != prefix.ID { + t.Fatal("first receipt did not retry from immediately before the slow row") + } + } + if f.e.pendingScanCursor[0].id != slow.ID { + t.Fatal("mixed timeout did not rotate") + } + var chosen string + d := &controlledDriver{prepare: func(_ context.Context, o Operation, _ Configuration, _ Attempt) (Preparation, error) { + chosen = o.ID + return Preparation{}, core.Fail("review_evidence_pending", "fixture hold", 409) + }} + if err := f.e.processNextForWorker(t.Context(), map[string]Driver{"test-capability": d}, false); err != nil || chosen != later.ID { + t.Fatal("not later unrelated work", chosen, err) + } + got, err := f.e.pendingForWorker(t.Context(), false) + if err != nil || len(got) != 1 || got[0].ID != prefix.ID || got[0].AttemptID != "" { + t.Fatal("oldest was not retained after wrap", got, err) + } +} + +func TestMixedPendingBatchUnconfirmedExitsKeepReplay(t *testing.T) { + e := &Engine{} + prefix := pendingScanPosition{"2020", "prefix"} + timedOut := pendingScanPosition{"2021", "slow"} + receipt := pendingExhaustion{prefix, timedOut} + e.pendingScanCursor[0] = prefix + e.pendingScanTimeout[0] = timedOut + for _, x := range []struct{ examined, overloaded bool }{{false, false}, {true, true}, {false, true}} { + e.finishPendingBatch(0, receipt, x.examined, x.overloaded) + if e.pendingScanCursor[0] != prefix || e.pendingScanTimeout[0] != timedOut { + t.Fatal("partial claim, cancel, or overload advanced replay", x) + } + } +} + +func TestMixedPendingWorkerKeepsReplayOnOverloadCancelAndEarlyClaim(t *testing.T) { + f := supervisorFixture(t) + firstReceipt := f.enqueue(t, attemptProject, "mixed-control-first", "cli", 2, 1) + tailReceipt := f.enqueue(t, attemptProject, "mixed-control-tail", "hosted", 2, 1) + operations, err := f.e.pendingForWorker(t.Context(), false) + if err != nil || len(operations) != 2 { + t.Fatal(operations, err) + } + byID := map[string]Operation{operations[0].ID: operations[0], operations[1].ID: operations[1]} + first, tail := byID[firstReceipt.ID], byID[tailReceipt.ID] + if first.ID == "" || tail.ID == "" { + t.Fatal("missing exact test operations", operations) + } + replay := pendingScanPosition{} + slow := pendingScanPosition{"2020", "slow"} + receipt := pendingExhaustion{replay, slow} + f.e.pendingScanTimeout[0] = slow + assertReplay := func() { + t.Helper() + if f.e.pendingScanCursor[0] != replay || f.e.pendingScanTimeout[0] != slow { + t.Fatal("did not preserve prefix replay") + } + if state := supervisorOperationState(t, f, tail.ID); state != "queued" { + t.Fatal("unvisited tail changed", state) + } + } + cancelled, cancel := context.WithCancel(t.Context()) + cancel() + if err := f.e.processPendingBatch(cancelled, nil, func() {}, 0, []Operation{first, tail}, receipt); err != nil { + t.Fatal(err) + } + assertReplay() + db := f.store.DB() + maxConns := db.Stats().MaxOpenConnections + db.SetMaxOpenConns(1) + connection, err := db.Conn(t.Context()) + if err != nil { + t.Fatal(err) + } + // Retain this connection for the worker's actual two-second read budget. + err = f.e.processPendingBatch(t.Context(), nil, func() {}, 0, []Operation{first}, receipt) + connection.Close() + db.SetMaxOpenConns(maxConns) + if err != nil { + t.Fatal(err) + } + assertReplay() + var chosen string + d := &controlledDriver{prepare: func(_ context.Context, o Operation, _ Configuration, _ Attempt) (Preparation, error) { + chosen = o.ID + return Preparation{}, core.Fail("review_evidence_pending", "fixture hold", 409) + }} + if err := f.e.processPendingBatch(t.Context(), map[string]Driver{"test-capability": d}, func() {}, 0, []Operation{first, tail}, receipt); err != nil || chosen != first.ID { + t.Fatal("wrong early claim", chosen, err) + } + assertReplay() +} diff --git a/internal/reviewexec/policy.go b/internal/reviewexec/policy.go index 121dc170a..7bdf8cce1 100644 --- a/internal/reviewexec/policy.go +++ b/internal/reviewexec/policy.go @@ -78,6 +78,7 @@ func clonePolicyConfiguration(value PolicyConfiguration) PolicyConfiguration { // ConfigurePolicy stores one immutable administrator-attributed revision. It // performs no admission, provider observation, execution or policy assessment. func (e *Engine) ConfigurePolicy(ctx context.Context, scope core.Scope, key string, input PolicyConfiguration) (json.RawMessage, error) { + scope = scope.RequireAdministration() // Bound collection copying even for trusted direct callers. if len(input.RequiredChannels) > 2 || len(input.PausedChannels) > 2 { return nil, invalid() @@ -88,14 +89,6 @@ func (e *Engine) ConfigurePolicy(ctx context.Context, scope core.Scope, key stri return nil, invalid() } return e.store.Mutate(ctx, scope, core.Mutation{Operation: "reviews.policy.configure", Target: "policy", Key: key, Request: input}, func(ctx context.Context, tx *sql.Tx) (any, error) { - // A write-capable scope is insufficient even for direct Go callers. - var admin int - if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM credentials WHERE principal_id=? AND is_admin=1 AND revoked=0`, scope.PrincipalID).Scan(&admin); err != nil { - return nil, err - } - if admin != 1 { - return nil, core.Fail("forbidden", "Administrative permission is required.", 403) - } var revision int64 if err := tx.QueryRowContext(ctx, `SELECT COALESCE(MAX(revision),0) FROM review_policy_config WHERE project_id=?`, scope.ProjectID).Scan(&revision); err != nil { return nil, err diff --git a/internal/reviewexec/project_management_test.go b/internal/reviewexec/project_management_test.go new file mode 100644 index 000000000..a04e78f74 --- /dev/null +++ b/internal/reviewexec/project_management_test.go @@ -0,0 +1,67 @@ +package reviewexec + +import "testing" + +func TestProjectManagerConfiguresPolicyAndExecutionWithReplayReauthorization(t *testing.T) { + f := newAttemptFixtureWithPolicy(t, false) + if err := EnsurePolicySchema(t.Context(), f.store); err != nil { + t.Fatal(err) + } + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=1 WHERE credential_id='exec-writer-cred'`); err != nil { + t.Fatal(err) + } + scope := f.scope(t, attemptProject, f.writer, false) + revision := int64(0) + initial := Configuration{ExpectedRevision: &revision, CapabilityID: "test-capability", Mode: "independent", Queue: []int64{2}, Channels: []string{"cli"}} + _, err := f.e.Configure(t.Context(), scope, "manager-cannot-bind", initial) + attemptCode(t, err, "operator_capability_binding_required") + if _, err := f.e.Configure(t.Context(), f.scope(t, attemptProject, f.admin, true), "operator-initial-binding", initial); err != nil { + t.Fatal(err) + } + revision = 1 + config := Configuration{ExpectedRevision: &revision, CapabilityID: "test-capability", Mode: "independent", Queue: []int64{2}, Channels: []string{"cli"}} + switched := config + switched.CapabilityID = "other-account" + _, err = f.e.Configure(t.Context(), scope, "manager-cannot-switch-account", switched) + attemptCode(t, err, "operator_capability_binding_required") + if _, err = f.e.Configure(t.Context(), scope, "owner-config", config); err != nil { + t.Fatal("manager execution config refused", err) + } + policy := policyInput(0) + if _, err := f.e.ConfigurePolicy(t.Context(), scope, "owner-policy", policy); err != nil { + t.Fatal("manager policy refused", err) + } + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=0 WHERE credential_id='exec-writer-cred'`); err != nil { + t.Fatal(err) + } + _, err = f.e.Configure(t.Context(), scope, "owner-config", config) + attemptCode(t, err, "forbidden") + _, err = f.e.ConfigurePolicy(t.Context(), scope, "owner-policy", policy) + attemptCode(t, err, "forbidden") +} + +func TestProjectManagerStaleCapabilityBindingReturnsRevisionConflict(t *testing.T) { + f := newAttemptFixtureWithPolicy(t, false) + if _, err := f.store.DB().Exec("UPDATE grants SET can_manage=1 WHERE credential_id='exec-writer-cred'"); err != nil { + t.Fatal(err) + } + scope := f.scope(t, attemptProject, f.writer, false) + admin := f.scope(t, attemptProject, f.admin, true) + f.e.capabilities["other-account"] = Capability{ID: "other-account", Channels: []string{"cli"}} + revision := int64(0) + config := Configuration{ExpectedRevision: &revision, CapabilityID: "test-capability", Mode: "independent", Queue: []int64{2}, Channels: []string{"cli"}} + if _, err := f.e.Configure(t.Context(), admin, "initial-bind", config); err != nil { + t.Fatal(err) + } + revision = 1 + changed := config + changed.CapabilityID = "other-account" + if _, err := f.e.Configure(t.Context(), admin, "operator-rebind", changed); err != nil { + t.Fatal(err) + } + _, err := f.e.Configure(t.Context(), scope, "stale-manager", config) + attemptCode(t, err, "review_conflict") + revision = 2 + _, err = f.e.Configure(t.Context(), scope, "current-manager-rebind", config) + attemptCode(t, err, "operator_capability_binding_required") +} diff --git a/internal/reviewexec/requests.go b/internal/reviewexec/requests.go index b5e8fcaa1..102663b68 100644 --- a/internal/reviewexec/requests.go +++ b/internal/reviewexec/requests.go @@ -52,21 +52,11 @@ func (e *Engine) validateConfiguration(c Configuration) error { // Configure retains every configuration revision. An update never silently // rebinds an already queued request to another provider or source policy. func (e *Engine) Configure(ctx context.Context, scope core.Scope, key string, c Configuration) (json.RawMessage, error) { + scope = scope.RequireAdministration() if err := validateConfigurationShape(c); err != nil { return nil, err } return e.store.Mutate(ctx, scope, core.Mutation{Operation: "reviews.configure", Target: "configuration", Key: key, Request: c}, func(ctx context.Context, tx *sql.Tx) (any, error) { - // Recheck admin at the transaction boundary even for direct Go callers. - var admin int - if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM credentials WHERE principal_id=? AND is_admin=1 AND revoked=0`, scope.PrincipalID).Scan(&admin); err != nil { - return nil, err - } - if admin != 1 { - return nil, core.Fail("forbidden", "Administrative permission is required.", 403) - } - if err := e.validateConfiguration(c); err != nil { - return nil, err - } var revision int64 if err := tx.QueryRowContext(ctx, `SELECT COALESCE(MAX(revision),0) FROM review_execution_config WHERE project_id=?`, scope.ProjectID).Scan(&revision); err != nil { return nil, err @@ -82,6 +72,16 @@ func (e *Engine) Configure(ctx context.Context, scope core.Scope, key string, c return nil, err } } + operator, err := core.IsInstanceAdministrator(ctx, tx, scope.PrincipalID) + if err != nil { + return nil, err + } + if !operator && (revision == 0 || c.CapabilityID != previous.CapabilityID) { + return nil, core.Fail("operator_capability_binding_required", "A service operator must establish or change this project's provider capability; preserve its current capability_id for project management.", 403) + } + if err := e.validateConfiguration(c); err != nil { + return nil, err + } defaults, err := enrollmentRoundDefaults(ctx, tx, scope.ProjectID) if err != nil { return nil, err diff --git a/internal/reviewexec/retained_configuration_scan_test.go b/internal/reviewexec/retained_configuration_scan_test.go index 2a8eb49d0..d2a3c5454 100644 --- a/internal/reviewexec/retained_configuration_scan_test.go +++ b/internal/reviewexec/retained_configuration_scan_test.go @@ -166,14 +166,15 @@ func TestPendingScanDoesNotSkipReturnedBatch(t *testing.T) { t.Run(fmt.Sprint(probe), func(t *testing.T) { f := supervisorFixture(t) seed := f.enqueue(t, attemptProject, "batch-seed", "cli", 2, 1) - for i := range 260 { + for i := range 2 { admissionSQL(t, f, `INSERT INTO review_operations (id,project_id,actor_id,worker_id,configuration_revision,pull_number,channel,head_sha,state,revision,reason,attempt_id,created_at,updated_at,capability_fingerprint,policy_revision) SELECT ?,project_id,actor_id,worker_id,configuration_revision,pull_number,channel,head_sha,state,revision,reason,attempt_id,created_at,updated_at,capability_fingerprint,policy_revision FROM review_operations WHERE id=?`, fmt.Sprintf("batch-%03d", i), seed.ID) } - first, err := f.e.pendingForWorker(t.Context(), probe) - // A deadline may produce a partial batch. This regression needs two - // candidates to prove processing preserves the unprocessed remainder, - // not a full batch whose size depends on runner throughput. - if err != nil || len(first) < 2 || len(first) > 256 { + // Force a full batch with an unreturned successor without relying on + // hundreds of SQLite reads fitting within the worker throughput budget. + ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second) + defer cancel() + first, err := f.e.scanPendingForWorker(ctx, probe, 2) + if err != nil || len(first) != 2 { t.Fatal(len(first), err) } var seen []string diff --git a/internal/reviewexec/settlement_test.go b/internal/reviewexec/settlement_test.go index 3eb30f6ae..bf43c33c7 100644 --- a/internal/reviewexec/settlement_test.go +++ b/internal/reviewexec/settlement_test.go @@ -141,7 +141,13 @@ func TestSettlementConfigurationReplayAfterCapabilityRemovalOrNarrowing(t *testi if err != nil || !bytes.Equal(first, replay) { t.Fatal("exact successful configuration retry did not retain its original receipt", err) } - _, err = f.e.Configure(context.Background(), scope, "new-unavailable-configuration", c) + _, err = f.e.Configure(context.Background(), scope, "stale-unavailable-configuration", c) + attemptCode(t, err, "review_conflict") + // A fresh request must pass CAS before capability availability is checked. + current := c + currentRevision := int64(1) + current.ExpectedRevision = ¤tRevision + _, err = f.e.Configure(context.Background(), scope, "new-unavailable-configuration", current) attemptCode(t, err, "validation_failed") changed := c changed.Mode = "stacked" diff --git a/internal/reviewexec/supervisor.go b/internal/reviewexec/supervisor.go index 9c8c17277..b756fdcb9 100644 --- a/internal/reviewexec/supervisor.go +++ b/internal/reviewexec/supervisor.go @@ -99,7 +99,7 @@ func (e *Engine) supervise(ctx context.Context, owned map[string]Driver, skipped cancelWork() } }) - for range 2 { + for worker := range 2 { workers.Go(func() { timer := time.NewTimer(0) defer timer.Stop() @@ -113,7 +113,7 @@ func (e *Engine) supervise(ctx context.Context, owned map[string]Driver, skipped if workCtx.Err() != nil { return } - if err := e.processNext(workCtx, owned); err != nil { + if err := e.processNextInLane(workCtx, owned, worker); err != nil { select { case failures <- err: default: @@ -140,6 +140,68 @@ func (e *Engine) pending(ctx context.Context) ([]Operation, error) { type pendingScanPosition struct{ createdAt, id string } +type pendingExhaustion struct { + beforeTimedOut, timedOut pendingScanPosition +} + +// Record the slow row only after retaining the prefix replay cursor. A Draft +// probe does not advance the ordinary cursor and may be the only returned item. +func retainPendingExhaustion(advance func(pendingScanPosition), cursor pendingScanPosition, firstOrdinary *pendingScanPosition, before, timedOut pendingScanPosition, receipt *pendingExhaustion) { + if firstOrdinary != nil { + cursor = *firstOrdinary + } + advance(cursor) + if receipt != nil { + *receipt = pendingExhaustion{before, timedOut} + } +} + +// Expiry can surface as an empty, row-local unavailable classification. A +// nonempty successful validation stays eligible for guarded admission. +func pendingCandidateReadError(ctx context.Context, o Operation, err error, chargeEmptyExpiry bool) error { + if err == nil && o.ID == "" && chargeEmptyExpiry { + return ctx.Err() + } + return pendingScanError(ctx, err) +} + +func (e *Engine) finishPendingBatch(worker int, receipt pendingExhaustion, examined, overloaded bool) { + if examined && !overloaded && receipt.timedOut != (pendingScanPosition{}) { + e.rewindTimedOutPendingCandidate(worker, receipt.beforeTimedOut, receipt.timedOut) + } +} + +// Allow a candidate whose remaining snapshot budget ran out one fresh retry. +// A second timeout rotates past it for this traversal only; the normal wrap +// revisits it without changing eligibility or the queued operation. +func (e *Engine) rewindTimedOutPendingCandidate(worker int, before, candidate pendingScanPosition) { + e.pendingScanMu.Lock() + defer e.pendingScanMu.Unlock() + if e.pendingScanTimeout[worker] == candidate { + e.pendingScanTimeout[worker] = pendingScanPosition{} + e.pendingScanCursor[worker] = candidate + return + } + e.pendingScanTimeout[worker] = candidate + e.pendingScanCursor[worker] = before +} + +func (e *Engine) pendingCandidateHasFreshRetry(worker int, candidate pendingScanPosition) bool { + e.pendingScanMu.Lock() + defer e.pendingScanMu.Unlock() + return e.pendingScanTimeout[worker] == candidate +} + +// A completed candidate validation ends its timeout streak, including when +// current admission says there is no eligible work for that row. +func (e *Engine) finishPendingCandidateValidation(worker int, candidate pendingScanPosition) { + e.pendingScanMu.Lock() + defer e.pendingScanMu.Unlock() + if e.pendingScanTimeout[worker] == candidate { + e.pendingScanTimeout[worker] = pendingScanPosition{} + } +} + // Transaction rollback caused by this scan's own deadline is not a storage // outage. Preserve unrelated failures even if the deadline happens concurrently. func pendingScanError(ctx context.Context, err error) error { @@ -149,9 +211,23 @@ func pendingScanError(ctx context.Context, err error) error { return err } -func (e *Engine) pendingForWorker(ctx context.Context, probeDrafts bool) (operations []Operation, resultErr error) { +func (e *Engine) pendingForWorker(ctx context.Context, probeDrafts bool) ([]Operation, error) { ctx, cancel := context.WithTimeout(ctx, 2*time.Second) defer cancel() + return e.scanPendingForWorker(ctx, probeDrafts, 256) +} + +// scanPendingForWorker separates bounded batch traversal from the worker budget. +// Callers supply the snapshot deadline and maximum ordinary candidates. +func (e *Engine) scanPendingForWorker(ctx context.Context, probeDrafts bool, batchLimit int) ([]Operation, error) { + worker := 0 + if probeDrafts { + worker = 1 + } + return e.scanPendingInLane(ctx, probeDrafts, batchLimit, worker, nil) +} + +func (e *Engine) scanPendingInLane(ctx context.Context, probeDrafts bool, batchLimit, worker int, receipt *pendingExhaustion) (operations []Operation, resultErr error) { // SQL may report ErrTxDone after the scan deadline rolls back its transaction. defer func() { resultErr = pendingScanError(ctx, resultErr) @@ -325,10 +401,6 @@ func (e *Engine) pendingForWorker(ctx context.Context, probeDrafts bool) (operat // Each supervisor worker retains only a scan position, never eligibility. // Advance before validating a row so a single expensive blocked candidate // cannot restart the same prefix after every bounded-snapshot timeout. - worker := 0 - if probeDrafts { - worker = 1 - } e.pendingScanMu.Lock() cursor := e.pendingScanCursor[worker] e.pendingScanMu.Unlock() @@ -346,7 +418,7 @@ func (e *Engine) pendingForWorker(ctx context.Context, probeDrafts bool) (operat defer rows.Close() // Apply the dispatch bound after filtering known waits and unavailable // accounts. The read transaction supplies the overall scan deadline. - limit := len(out) + 256 + limit := len(out) + batchLimit position := cursor var firstReturned *pendingScanPosition resumeReturned := func() { @@ -370,17 +442,22 @@ func (e *Engine) pendingForWorker(ctx context.Context, probeDrafts bool) (operat filterArgs := append(append([]any(nil), args...), operation) filterErr := tx.QueryRowContext(ctx, `SELECT id FROM (`+query+` AND o.id=?)`, filterArgs...).Scan(&eligible) if errors.Is(filterErr, sql.ErrNoRows) { + e.finishPendingCandidateValidation(worker, position) continue } if filterErr != nil { filterErr = pendingScanError(ctx, filterErr) if errors.Is(filterErr, context.DeadlineExceeded) { - advance(before) + if len(out) == 0 { + e.rewindTimedOutPendingCandidate(worker, before, position) + } else { + advance(before) + } } else { advance(cursor) } if len(out) != 0 && errors.Is(filterErr, context.DeadlineExceeded) { - resumeReturned() + retainPendingExhaustion(advance, cursor, firstReturned, before, position, receipt) return out, nil } return nil, filterErr @@ -390,25 +467,35 @@ func (e *Engine) pendingForWorker(ctx context.Context, probeDrafts bool) (operat if capability, ok := e.capabilities[cfg.configuration.CapabilityID]; ok && capability.Fingerprint == fingerprint { key := accountKey{capability.Provider, capability.Account} if cliUnavailable[key] || now.Before(cliRetryDeadlines[key]) { + e.finishPendingCandidateValidation(worker, position) continue } } } } o, err := readCandidate(project, operation) - if err != nil { - err = pendingScanError(ctx, err) + // Without a returned prefix, a known unavailable row may consume the + // budget while classifying its local failure. Keep traversal progress + // unless this exact row is already on its recorded fresh retry. + chargeEmptyExpiry := len(out) != 0 || + (ctx.Err() != nil && e.pendingCandidateHasFreshRetry(worker, position)) + if err = pendingCandidateReadError(ctx, o, err, chargeEmptyExpiry); err != nil { if errors.Is(err, context.DeadlineExceeded) { - advance(before) + if len(out) == 0 { + e.rewindTimedOutPendingCandidate(worker, before, position) + } else { + advance(before) + } } else { advance(cursor) // Never rotate past an operational storage failure. } if len(out) != 0 && errors.Is(err, context.DeadlineExceeded) { - resumeReturned() + retainPendingExhaustion(advance, cursor, firstReturned, before, position, receipt) return out, nil } return nil, err } + e.finishPendingCandidateValidation(worker, position) if o.ID != "" { if firstReturned == nil { firstReturned = &before @@ -428,7 +515,10 @@ func (e *Engine) pendingForWorker(ctx context.Context, probeDrafts bool) (operat return nil, err } if len(out) < limit { - advance(pendingScanPosition{}) + e.pendingScanMu.Lock() + e.pendingScanCursor[worker] = pendingScanPosition{} + e.pendingScanTimeout[worker] = pendingScanPosition{} + e.pendingScanMu.Unlock() } else { // Selection processes at most one returned candidate. Do not rotate past // the unprocessed remainder merely because the scan filled its batch. @@ -545,6 +635,11 @@ func (e *Engine) skipUnavailableWait(ctx context.Context, o Operation, err error } func (e *Engine) processNext(ctx context.Context, drivers map[string]Driver) error { + return e.processNextInLane(ctx, drivers, 0) +} + +// Each supervised worker owns its ordinary scan lane across Draft permit changes. +func (e *Engine) processNextInLane(ctx context.Context, drivers map[string]Driver, worker int) error { probe := e.draftProbePermit.CompareAndSwap(false, true) release := func() { if probe { @@ -553,21 +648,34 @@ func (e *Engine) processNext(ctx context.Context, drivers map[string]Driver) err } } defer release() - return e.processNextWithProbe(ctx, drivers, probe, release) + return e.processNextWithProbe(ctx, drivers, probe, release, worker) } func (e *Engine) processNextForWorker(ctx context.Context, drivers map[string]Driver, probeDrafts bool) error { - return e.processNextWithProbe(ctx, drivers, probeDrafts, func() {}) + worker := 0 + if probeDrafts { + worker = 1 + } + return e.processNextWithProbe(ctx, drivers, probeDrafts, func() {}, worker) } -func (e *Engine) processNextWithProbe(ctx context.Context, drivers map[string]Driver, probeDrafts bool, releaseProbe func()) error { - operations, err := e.pendingForWorker(ctx, probeDrafts) +func (e *Engine) processNextWithProbe(ctx context.Context, drivers map[string]Driver, probeDrafts bool, releaseProbe func(), worker int) error { + scanCtx, cancelScan := context.WithTimeout(ctx, 2*time.Second) + var receipt pendingExhaustion + operations, err := e.scanPendingInLane(scanCtx, probeDrafts, 256, worker, &receipt) + cancelScan() if err != nil { if ctx.Err() != nil || errors.Is(err, context.DeadlineExceeded) { return nil } return persistenceFailure() } + return e.processPendingBatch(ctx, drivers, releaseProbe, worker, operations, receipt) +} + +func (e *Engine) processPendingBatch(ctx context.Context, drivers map[string]Driver, releaseProbe func(), worker int, operations []Operation, receipt pendingExhaustion) error { + overloaded := false + claimed := false for _, o := range operations { if ctx.Err() != nil { return nil @@ -586,6 +694,7 @@ func (e *Engine) processNextWithProbe(ctx context.Context, drivers map[string]Dr } var refusal *core.Error if errors.As(err, &refusal) && (refusal.Code == "overloaded" || refusal.Code == "review_conflict") { + overloaded = overloaded || refusal.Code == "overloaded" continue } return persistenceFailure() @@ -609,6 +718,7 @@ func (e *Engine) processNextWithProbe(ctx context.Context, drivers map[string]Dr if errors.As(err, &failure) { switch failure.Code { case "review_busy", "review_conflict", "overloaded": + overloaded = overloaded || failure.Code == "overloaded" continue } } @@ -617,6 +727,7 @@ func (e *Engine) processNextWithProbe(ctx context.Context, drivers map[string]Dr if a.ID == "" { continue } + claimed = true // The operation retained its exact configuration revision; StartAttempt // has already checked that this is still the current configuration. c, err := e.configurationRevision(ctx, o.ProjectID, o.ConfigurationRevision) @@ -738,6 +849,7 @@ func (e *Engine) processNextWithProbe(ctx context.Context, drivers map[string]Dr _, err = e.persistAdvance(a, result.State, result.Reason, result.ExternalID) return err } + e.finishPendingBatch(worker, receipt, ctx.Err() == nil && !claimed, overloaded) return nil } diff --git a/internal/reviewexec/types.go b/internal/reviewexec/types.go index 8a708d17f..7876477e6 100644 --- a/internal/reviewexec/types.go +++ b/internal/reviewexec/types.go @@ -123,6 +123,7 @@ type Engine struct { draftProbeCursor string pendingScanMu sync.Mutex pendingScanCursor [2]pendingScanPosition + pendingScanTimeout [2]pendingScanPosition runWake chan struct{} runRunning atomic.Bool hostedObserverMu sync.Mutex diff --git a/internal/server/access.go b/internal/server/access.go index 9e4b5d40c..fed623005 100644 --- a/internal/server/access.go +++ b/internal/server/access.go @@ -7,11 +7,66 @@ import ( "encoding/hex" "errors" "net/http" + "slices" "strings" "github.com/benhook1013/FireController/internal/core" ) +type projectPermissions struct{ read, write, manage int } + +func permissionSet(values []string) (projectPermissions, []string, error) { + var p projectPermissions + invalid := func() (projectPermissions, []string, error) { + return projectPermissions{}, nil, core.Fail("validation_failed", "Permissions must be unique read/write/manage values and include read or manage.", 400) + } + if len(values) > 3 { + return invalid() + } + for _, value := range values { + switch value { + case "read": + if p.read != 0 { + return invalid() + } + p.read = 1 + case "write": + if p.write != 0 { + return invalid() + } + p.write = 1 + case "manage": + if p.manage != 0 { + return invalid() + } + p.manage = 1 + default: + return invalid() + } + } + if p.manage == 1 { + p.read, p.write = 1, 1 + } + if p.read != 1 { + return invalid() + } + return p, p.values(), nil +} + +func (p projectPermissions) values() []string { + values := []string{} + if p.read == 1 { + values = append(values, "read") + } + if p.write == 1 { + values = append(values, "write") + } + if p.manage == 1 { + values = append(values, "manage") + } + return values +} + func (a *api) grant(w http.ResponseWriter, r *http.Request) { scope, err := a.store.AdminScope(r) if err != nil { @@ -31,35 +86,12 @@ func (a *api) grant(w http.ResponseWriter, r *http.Request) { core.WriteError(w, core.Fail("validation_failed", "Provide the lowercase SHA-256 hash of a client credential.", 400)) return } - read, write := 0, 0 - for _, permission := range request.Permissions { - switch permission { - case "read": - if read != 0 { - core.WriteError(w, core.Fail("validation_failed", "Permissions must be unique read/write values.", 400)) - return - } - read = 1 - case "write": - if write != 0 { - core.WriteError(w, core.Fail("validation_failed", "Permissions must be unique read/write values.", 400)) - return - } - write = 1 - default: - core.WriteError(w, core.Fail("validation_failed", "Permissions must be unique read/write values.", 400)) - return - } - } - if read != 1 { - core.WriteError(w, core.Fail("validation_failed", "A project credential requires read permission.", 400)) + permissions, normalized, err := permissionSet(request.Permissions) + if err != nil { + core.WriteError(w, err) return } - // Canonical ordering makes equivalent permission sets the same request. - request.Permissions = []string{"read"} - if write == 1 { - request.Permissions = append(request.Permissions, "write") - } + request.Permissions = normalized k, err := key(r) if err != nil { core.WriteError(w, err) @@ -78,10 +110,10 @@ func (a *api) grant(w http.ResponseWriter, r *http.Request) { if _, err = tx.ExecContext(ctx, "INSERT INTO credentials(id,principal_id,token_sha256,is_admin,revoked) VALUES(?,?,?,0,0)", id, principal, request.TokenSHA256); err != nil { return nil, err } - if _, err = tx.ExecContext(ctx, "INSERT INTO grants(credential_id,project_id,can_read,can_write) VALUES(?,?,?,?)", id, scope.ProjectID, read, write); err != nil { + if _, err = tx.ExecContext(ctx, "INSERT INTO grants(credential_id,project_id,can_read,can_write,can_manage) VALUES(?,?,?,?,?)", id, scope.ProjectID, permissions.read, permissions.write, permissions.manage); err != nil { return nil, err } - if err = core.AppendEvent(ctx, tx, scope, "credentials.granted", id, 1, map[string]string{"id": id, "principal_id": principal}); err != nil { + if err = core.AppendEvent(ctx, tx, scope, "credentials.granted", id, 1, map[string]any{"id": id, "principal_id": principal, "permissions": request.Permissions}); err != nil { return nil, err } return map[string]string{"id": id, "principal_id": principal, "project_id": scope.ProjectID, "outcome": "granted"}, nil @@ -89,6 +121,76 @@ func (a *api) grant(w http.ResponseWriter, r *http.Request) { complete(w, result, err) } +func (a *api) replaceGrant(w http.ResponseWriter, r *http.Request) { + scope, err := a.store.AdminScope(r) + if err != nil { + core.WriteError(w, err) + return + } + if _, err = core.QueryKeys(r, "validation_failed"); err != nil { + core.WriteError(w, err) + return + } + var wire struct { + ExpectedPermissions *[]string `json:"expected_permissions"` + Permissions *[]string `json:"permissions"` + } + if err = core.ReadJSON(w, r, &wire); err != nil { + core.WriteError(w, err) + return + } + if wire.ExpectedPermissions == nil || wire.Permissions == nil { + core.WriteError(w, core.Fail("validation_failed", "Provide expected_permissions and permissions arrays.", 400)) + return + } + _, expected, err := permissionSet(*wire.ExpectedPermissions) + if err != nil { + core.WriteError(w, err) + return + } + next, permissions, err := permissionSet(*wire.Permissions) + if err != nil { + core.WriteError(w, err) + return + } + k, err := key(r) + if err != nil { + core.WriteError(w, err) + return + } + id := r.PathValue("credential_id") + input := struct { + ExpectedPermissions []string `json:"expected_permissions"` + Permissions []string `json:"permissions"` + }{expected, permissions} + value, err := a.store.Mutate(r.Context(), scope, core.Mutation{Operation: "credentials.permissions.replace", Target: id, Key: k, Request: input}, func(ctx context.Context, tx *sql.Tx) (any, error) { + var previous projectPermissions + err := tx.QueryRowContext(ctx, `SELECT g.can_read,g.can_write,g.can_manage FROM grants g JOIN credentials c ON c.id=g.credential_id WHERE c.id=? AND g.project_id=? AND c.is_admin=0 AND c.revoked=0 AND g.can_read=1`, id, scope.ProjectID).Scan(&previous.read, &previous.write, &previous.manage) + if errors.Is(err, sql.ErrNoRows) { + return nil, core.Fail("not_found", "The active credential grant is unavailable in this project.", 404) + } + if err != nil { + return nil, err + } + current := previous.values() + if !slices.Equal(current, expected) { + return nil, &core.Error{Code: "credential_permissions_changed", Message: "The credential permissions changed; compare the returned current_permissions with the intended change before retrying.", Status: 409, Details: map[string]any{"credential_id": id, "current_permissions": current}} + } + outcome := "unchanged" + if !slices.Equal(current, permissions) { + if _, err = tx.ExecContext(ctx, `UPDATE grants SET can_read=?,can_write=?,can_manage=? WHERE credential_id=? AND project_id=?`, next.read, next.write, next.manage, id, scope.ProjectID); err != nil { + return nil, err + } + if err = core.AppendEvent(ctx, tx, scope, "credentials.permissions_changed", id, 1, map[string]any{"id": id, "previous_permissions": current, "permissions": permissions}); err != nil { + return nil, err + } + outcome = "updated" + } + return map[string]any{"id": id, "project_id": scope.ProjectID, "outcome": outcome, "permissions": permissions}, nil + }) + complete(w, value, err) +} + func (a *api) revoke(w http.ResponseWriter, r *http.Request) { scope, err := a.store.AdminScope(r) if err != nil { @@ -102,16 +204,21 @@ func (a *api) revoke(w http.ResponseWriter, r *http.Request) { } id := r.PathValue("credential_id") result, err := a.store.Mutate(r.Context(), scope, core.Mutation{Operation: "credentials.revoke", Target: id, Key: k, Request: struct{}{}}, func(ctx context.Context, tx *sql.Tx) (any, error) { - var revoked int - err := tx.QueryRowContext(ctx, "SELECT c.revoked FROM credentials c JOIN grants g ON g.credential_id=c.id WHERE c.id=? AND g.project_id=? AND c.is_admin=0", id, scope.ProjectID).Scan(&revoked) + var revoked, read, write, manage int + err := tx.QueryRowContext(ctx, "SELECT c.revoked,g.can_read,g.can_write,g.can_manage FROM credentials c JOIN grants g ON g.credential_id=c.id WHERE c.id=? AND g.project_id=? AND c.is_admin=0", id, scope.ProjectID).Scan(&revoked, &read, &write, &manage) if errors.Is(err, sql.ErrNoRows) { return nil, core.Fail("not_found", "The credential is unavailable in this project.", 404) } if err != nil { return nil, err } - if revoked == 0 { - if _, err = tx.ExecContext(ctx, "UPDATE credentials SET revoked=1 WHERE id=?", id); err != nil { + if revoked == 0 && (read != 0 || write != 0 || manage != 0) { + // This URL revokes only its project's authority. A credential may + // retain a grant elsewhere; never revoke another project's access. + if _, err = tx.ExecContext(ctx, "UPDATE grants SET can_read=0,can_write=0,can_manage=0 WHERE credential_id=? AND project_id=?", id, scope.ProjectID); err != nil { + return nil, err + } + if _, err = tx.ExecContext(ctx, "UPDATE credentials SET revoked=1 WHERE id=? AND NOT EXISTS(SELECT 1 FROM grants WHERE credential_id=? AND (can_read=1 OR can_write=1 OR can_manage=1))", id, id); err != nil { return nil, err } if err = core.AppendEvent(ctx, tx, scope, "credentials.revoked", id, 1, map[string]string{"id": id}); err != nil { diff --git a/internal/server/project_management_test.go b/internal/server/project_management_test.go new file mode 100644 index 000000000..8a2d384d8 --- /dev/null +++ b/internal/server/project_management_test.go @@ -0,0 +1,226 @@ +package server_test + +import ( + "bytes" + "context" + "crypto/sha256" + "database/sql" + "encoding/hex" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/benhook1013/FireController/internal/core" +) + +func projectManagerGrant(t *testing.T, f *fixture, project, token string) string { + t.Helper() + sum := sha256.Sum256([]byte(token)) + v := require(t, request(f.handler, "POST", "/api/v1/projects/"+project+"/credentials", f.admin, core.NewID("key"), "", `{"token_sha256":"`+hex.EncodeToString(sum[:])+`","permissions":["manage"]}`), http.StatusOK) + return v["id"].(string) +} + +func TestProjectManagerDelegatesOnlyItsProjectAndCannotCreateInstanceAuthority(t *testing.T) { + f := setup(t) + one, two := f.project(t, "owner/one"), f.project(t, "owner/two") + manager := "synthetic-project-manager-token" + id := projectManagerGrant(t, f, one, manager) + var read, write, manage, admin int + if err := f.store.DB().QueryRow(`SELECT g.can_read,g.can_write,g.can_manage,c.is_admin FROM grants g JOIN credentials c ON c.id=g.credential_id WHERE g.credential_id=? AND g.project_id=?`, id, one).Scan(&read, &write, &manage, &admin); err != nil || read != 1 || write != 1 || manage != 1 || admin != 0 { + t.Fatal("management did not imply project read/write only", err) + } + sum := sha256.Sum256([]byte("synthetic-delegated-manager")) + body := `{"token_sha256":"` + hex.EncodeToString(sum[:]) + `","permissions":["read","write","manage"]}` + v := require(t, request(f.handler, "POST", "/api/v1/projects/"+one+"/credentials", manager, "delegate-same-project", "", body), 200) + child := v["id"].(string) + if err := f.store.DB().QueryRow(`SELECT is_admin FROM credentials WHERE id=?`, child).Scan(&admin); err != nil || admin != 0 { + t.Fatal("delegation created global administration", err) + } + require(t, request(f.handler, "POST", "/api/v1/projects/"+two+"/credentials", manager, "not-other-project", "", body), 403) + require(t, request(f.handler, "POST", "/api/v1/projects", manager, "not-global-create", "", `{"name":"Other","repository":"owner/three"}`), 403) + require(t, request(f.handler, "GET", "/api/v1/projects", manager, "", "", ""), 403) + writer := "synthetic-ordinary-project-writer" + f.grant(t, one, writer, true) + require(t, request(f.handler, "POST", "/api/v1/projects/"+one+"/credentials", writer, "writer-cannot-delegate", "", body), 403) + // Same-key replay must be reauthorized after management is withdrawn. + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=0 WHERE credential_id=?`, id); err != nil { + t.Fatal(err) + } + require(t, request(f.handler, "POST", "/api/v1/projects/"+one+"/credentials", manager, "delegate-same-project", "", body), 403) +} + +func TestProjectManagerRevocationPreservesAnotherProjectsSharedGrant(t *testing.T) { + f := setup(t) + one, two := f.project(t, "owner/one"), f.project(t, "owner/two") + manager := "synthetic-project-manager-token" + projectManagerGrant(t, f, one, manager) + shared := "synthetic-shared-project-token" + id := f.grant(t, one, shared, true) + if _, err := f.store.DB().Exec(`INSERT INTO grants(credential_id,project_id,can_read,can_write) VALUES(?,?,1,1)`, id, two); err != nil { + t.Fatal(err) + } + before := count(t, f.store, "events") + path := "/api/v1/projects/" + one + "/credentials/" + id + require(t, request(f.handler, "DELETE", path, manager, "revoke-own-project", "", ""), 200) + require(t, request(f.handler, "GET", "/api/v1/projects/"+one, shared, "", "", ""), 403) + require(t, request(f.handler, "GET", "/api/v1/projects/"+two, shared, "", "", ""), 200) + var revoked int + if err := f.store.DB().QueryRow(`SELECT revoked FROM credentials WHERE id=?`, id).Scan(&revoked); err != nil || revoked != 0 { + t.Fatal("revocation affected other project", err) + } + if count(t, f.store, "events") != before+1 { + t.Fatal("revocation audit missing") + } + require(t, request(f.handler, "DELETE", path, manager, "another-key-same-revocation", "", ""), 200) + if count(t, f.store, "events") != before+1 { + t.Fatal("already withdrawn grant produced another event") + } + foreign := "synthetic-foreign-project-token" + foreignID := f.grant(t, two, foreign, true) + require(t, request(f.handler, "DELETE", "/api/v1/projects/"+one+"/credentials/"+foreignID, manager, "not-foreign-credential", "", ""), 404) + require(t, request(f.handler, "GET", "/api/v1/projects/"+two, foreign, "", "", ""), 200) +} + +func TestProjectManagerBrowserAppearanceCeilingAndDowngrade(t *testing.T) { + f := browserActionsFixture(t) + p := f.project(t, "owner/one") + worker := f.worker(t, p, "Owner") + manager := "synthetic-project-manager-token" + credential := projectManagerGrant(t, f, p, manager) + session := strings.Repeat("e", 32) + cookie := browserActionsLogin(t, f, p, manager, session, true) + body := `{"expected_revision":0,"presentation":{"name":"Owned project"}}` + r := browserActionRequest(f, "PUT", "/api/v1/projects/"+p+"/presentation", session, cookie, worker, "owner-appearance", body) + require(t, serveBrowserAction(f, r), 200) + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=0 WHERE credential_id=?`, credential); err != nil { + t.Fatal(err) + } + r = browserActionRequest(f, "PUT", "/api/v1/projects/"+p+"/presentation", session, cookie, worker, "owner-appearance", body) + require(t, serveBrowserAction(f, r), 403) + // An original writer cookie must not acquire appearance authority later. + id := strings.Repeat("f", 32) + plain := browserActionsLogin(t, f, p, manager, id, false) + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=1 WHERE credential_id=?`, credential); err != nil { + t.Fatal(err) + } + r = browserActionRequest(f, "PUT", "/api/v1/projects/"+p+"/presentation", id, plain, worker, "no-cookie-elevation", body) + require(t, serveBrowserAction(f, r), 403) +} + +func TestProjectManagerChangesExistingGrantWithExactPermissionCAS(t *testing.T) { + f := setup(t) + one, two := f.project(t, "owner/one"), f.project(t, "owner/two") + manager := "synthetic-project-manager-token" + projectManagerGrant(t, f, one, manager) + token := "synthetic-retained-worker-token" + id := f.grant(t, one, token, true) + var principal, hash string + if err := f.store.DB().QueryRow(`SELECT principal_id,token_sha256 FROM credentials WHERE id=?`, id).Scan(&principal, &hash); err != nil { + t.Fatal(err) + } + path := "/api/v1/projects/" + one + "/credentials/" + id + body := `{"expected_permissions":["write","read"],"permissions":["manage"]}` + before := count(t, f.store, "events") + v := require(t, request(f.handler, "PUT", path, manager, "retain-identity-promote", "", body), 200) + if v["outcome"] != "updated" { + t.Fatal("grant was not updated") + } + var afterPrincipal, afterHash string + var admin int + if err := f.store.DB().QueryRow(`SELECT principal_id,token_sha256,is_admin FROM credentials WHERE id=?`, id).Scan(&afterPrincipal, &afterHash, &admin); err != nil || principal != afterPrincipal || hash != afterHash || admin != 0 { + t.Fatal("role edit replaced or globally elevated identity", err) + } + if count(t, f.store, "events") != before+1 { + t.Fatal("management edit was not audited") + } + // The retained credential now administers this project's grants itself. + sum := sha256.Sum256([]byte("synthetic-delegation-after-promotion")) + require(t, request(f.handler, "POST", "/api/v1/projects/"+one+"/credentials", token, "promoted-client-own-project", "", `{"token_sha256":"`+hex.EncodeToString(sum[:])+`","permissions":["read"]}`), 200) + require(t, request(f.handler, "GET", "/api/v1/projects", token, "", "", ""), 403) + require(t, request(f.handler, "PUT", path, manager, "stale-permission-guard", "", body), 409) + stale := request(f.handler, "PUT", path, manager, "another-stale-permission-guard", "", body) + if !strings.Contains(stale.Body.String(), "current_permissions") || strings.Contains(stale.Body.String(), hash) { + t.Fatal("stale conflict omitted safe permission detail or leaked credential hash") + } + // Equivalent normalized requests replay without changing the grant or its audit. + require(t, request(f.handler, "PUT", path, manager, "retain-identity-promote", "", `{"expected_permissions":["read","write"],"permissions":["read","write","manage"]}`), 200) + audits := count(t, f.store, "events") + unchanged := require(t, request(f.handler, "PUT", path, manager, "already-same-role", "", `{"expected_permissions":["manage"],"permissions":["read","write","manage"]}`), 200) + if unchanged["outcome"] != "unchanged" || count(t, f.store, "events") != audits { + t.Fatal("equivalent permission set manufactured a change") + } + require(t, request(f.handler, "PUT", path, manager, "retain-identity-promote", "", `{"expected_permissions":["manage"],"permissions":["read"]}`), 409) + require(t, request(f.handler, "PUT", "/api/v1/projects/"+two+"/credentials/"+id, manager, "not-other-project-grant", "", body), 403) + foreign := f.grant(t, two, "synthetic-unrelated-credential", true) + w := request(f.handler, "PUT", "/api/v1/projects/"+one+"/credentials/"+foreign, manager, "not-foreign-target", "", body) + require(t, w, 404) + if strings.Contains(w.Body.String(), "current_permissions") { + t.Fatal("foreign target leaked permissions") + } + var globalID string + if err := f.store.DB().QueryRow(`SELECT id FROM credentials WHERE is_admin=1`).Scan(&globalID); err != nil { + t.Fatal(err) + } + if _, err := f.store.DB().Exec(`INSERT INTO grants(credential_id,project_id,can_read,can_write) VALUES(?,?,1,1)`, globalID, one); err != nil { + t.Fatal(err) + } + require(t, request(f.handler, "PUT", "/api/v1/projects/"+one+"/credentials/"+globalID, manager, "not-global-administrator-target", "", body), 404) + for i, bad := range []string{`{}`, `{"expected_permissions":null,"permissions":["manage"]}`, `{"expected_permissions":["read","read"],"permissions":["manage"]}`, `{"expected_permissions":["read"],"permissions":["admin"]}`, `{"expected_permissions":["read"],"permissions":[]}`, `{"expected_permissions":["read"],"permissions":["write"]}`} { + require(t, request(f.handler, "PUT", path, manager, "bad-role-"+string(rune('a'+i)), "", bad), 400) + } +} + +func TestProjectManagerPermissionEditRollbackAndReplayAuthorization(t *testing.T) { + f := setup(t) + p := f.project(t, "owner/one") + manager := "synthetic-project-manager-token" + ownerID := projectManagerGrant(t, f, p, manager) + id := f.grant(t, p, "synthetic-managed-credential", false) + path := "/api/v1/projects/" + p + "/credentials/" + id + body := `{"expected_permissions":["read"],"permissions":["manage"]}` + if _, err := f.store.DB().Exec(`CREATE TRIGGER fail_management_event BEFORE INSERT ON events WHEN NEW.event_type='credentials.permissions_changed' BEGIN SELECT RAISE(ABORT,'synthetic event failure'); END`); err != nil { + t.Fatal(err) + } + require(t, request(f.handler, "PUT", path, manager, "retry-role-after-rollback", "", body), 500) + var write, manage int + if err := f.store.DB().QueryRow(`SELECT can_write,can_manage FROM grants WHERE credential_id=?`, id).Scan(&write, &manage); err != nil || write != 0 || manage != 0 { + t.Fatal("failed audit left authority changed", err) + } + if _, err := f.store.DB().Exec(`DROP TRIGGER fail_management_event`); err != nil { + t.Fatal(err) + } + require(t, request(f.handler, "PUT", path, manager, "retry-role-after-rollback", "", body), 200) + req := httptest.NewRequest("PUT", path, nil) + req.SetPathValue("project_id", p) + req.Header.Set("Authorization", "Bearer "+manager) + captured, err := f.store.AdminScope(req) + if err != nil { + t.Fatal(err) + } + mutation := core.Mutation{Operation: "test.management-replay", Target: id, Key: "captured-management", Request: map[string]string{"value": "same"}} + calls := 0 + effect := func(context.Context, *sql.Tx) (any, error) { + calls++ + return map[string]string{"outcome": "changed"}, nil + } + first, err := f.store.Mutate(t.Context(), captured, mutation, effect) + if err != nil { + t.Fatal(err) + } + replay, err := f.store.Mutate(t.Context(), captured, mutation, effect) + if err != nil || !bytes.Equal(first, replay) || calls != 1 { + t.Fatal("authorized receipt did not replay", err, calls) + } + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=0 WHERE credential_id=?`, ownerID); err != nil { + t.Fatal(err) + } + require(t, request(f.handler, "PUT", path, manager, "retry-role-after-rollback", "", body), 403) + replay, err = f.store.Mutate(t.Context(), captured, mutation, effect) + var failure *core.Error + if !errors.As(err, &failure) || failure.Code != "forbidden" || len(replay) != 0 || calls != 1 { + t.Fatal("captured manager scope bypassed replay reauthorization", err, string(replay), calls) + } + +} diff --git a/internal/server/server.go b/internal/server/server.go index 2196011cc..ab7c4eaca 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -70,6 +70,9 @@ func New(store *core.Store, options ...Option) *http.ServeMux { mux.HandleFunc("GET /api/v1/projects/{project_id}/message-events", a.messageEvents) mux.HandleFunc("POST /api/v1/projects/{project_id}/credentials", a.grant) mux.HandleFunc("DELETE /api/v1/projects/{project_id}/credentials/{credential_id}", a.revoke) + mux.HandleFunc("PUT /api/v1/projects/{project_id}/credentials/{credential_id}", a.replaceGrant) + mux.HandleFunc("GET /api/v1/projects/{project_id}/workers/{worker_id}/retirement", a.workerRetirement) + mux.HandleFunc("POST /api/v1/projects/{project_id}/workers/{worker_id}/retire", a.retireWorker) if a.browser != nil { mux.Handle("/", a.browser) } else { @@ -111,6 +114,7 @@ type projectValue struct { Repository string `json:"repository"` } type workerValue struct { + Retired bool `json:"retired,omitempty"` ID string `json:"id"` ProjectID string `json:"project_id"` Name string `json:"name"` @@ -299,7 +303,11 @@ func (a *api) listWorkers(w http.ResponseWriter, r *http.Request) { core.WriteError(w, err) return } - query, err := listQuery(r) + if len(r.URL.RawQuery) > 16<<10 { + core.WriteError(w, core.Fail("validation_failed", "Use only one limit, one cursor and one include_retired query parameter.", 400)) + return + } + query, err := core.QueryKeys(r, "validation_failed", "limit", "cursor", "include_retired") if err != nil { core.WriteError(w, err) return @@ -309,13 +317,21 @@ func (a *api) listWorkers(w http.ResponseWriter, r *http.Request) { core.WriteError(w, err) return } + includeRetired := query.Get("include_retired") == "true" + if _, exists := query["include_retired"]; exists && !includeRetired { + core.WriteError(w, core.Fail("validation_failed", "Use include_retired=true to include archived workers.", 400)) + return + } filter := "workers" + if includeRetired { + filter += ":include_retired" + } after, err := a.store.ParseCursor(scope, filter, query.Get("cursor")) if err != nil { core.WriteError(w, err) return } - rows, err := a.store.DB().QueryContext(r.Context(), "SELECT id,project_id,name FROM workers WHERE project_id=? AND id>? ORDER BY id LIMIT ?", scope.ProjectID, after, limit+1) + rows, err := a.store.DB().QueryContext(r.Context(), "SELECT id,project_id,name,EXISTS(SELECT 1 FROM worker_retirements r WHERE r.project_id=w.project_id AND r.worker_id=w.id) FROM workers w WHERE project_id=? AND id>? AND (? OR NOT EXISTS(SELECT 1 FROM worker_retirements r WHERE r.project_id=w.project_id AND r.worker_id=w.id)) ORDER BY id LIMIT ?", scope.ProjectID, after, includeRetired, limit+1) if err != nil { core.WriteError(w, err) return @@ -324,7 +340,7 @@ func (a *api) listWorkers(w http.ResponseWriter, r *http.Request) { values := make([]workerValue, 0, limit+1) for rows.Next() { var value workerValue - if err = rows.Scan(&value.ID, &value.ProjectID, &value.Name); err != nil { + if err = rows.Scan(&value.ID, &value.ProjectID, &value.Name, &value.Retired); err != nil { core.WriteError(w, err) return } @@ -354,7 +370,7 @@ func (a *api) worker(w http.ResponseWriter, r *http.Request) { return } var value workerValue - err = a.store.DB().QueryRowContext(r.Context(), "SELECT id,project_id,name FROM workers WHERE project_id=? AND id=?", scope.ProjectID, r.PathValue("worker_id")).Scan(&value.ID, &value.ProjectID, &value.Name) + err = a.store.DB().QueryRowContext(r.Context(), "SELECT id,project_id,name,EXISTS(SELECT 1 FROM worker_retirements r WHERE r.project_id=w.project_id AND r.worker_id=w.id) FROM workers w WHERE project_id=? AND id=?", scope.ProjectID, r.PathValue("worker_id")).Scan(&value.ID, &value.ProjectID, &value.Name, &value.Retired) if errors.Is(err, sql.ErrNoRows) { err = core.Fail("not_found", "The worker is unavailable in this project.", 404) } diff --git a/internal/server/worker_retirement.go b/internal/server/worker_retirement.go new file mode 100644 index 000000000..8e98bdce8 --- /dev/null +++ b/internal/server/worker_retirement.go @@ -0,0 +1,141 @@ +package server + +import ( + "context" + "database/sql" + "net/http" + "time" + + "github.com/benhook1013/FireController/internal/core" +) + +type workerRetirementItems struct { + Count int64 `json:"count"` + IDs []string `json:"ids"` +} +type workerRetirementBlockers struct { + Jobs workerRetirementItems `json:"jobs"` + Notes workerRetirementItems `json:"notes"` + Messages workerRetirementItems `json:"messages"` +} +type workerRetirementStatus struct { + WorkerID string `json:"worker_id"` + Retired bool `json:"retired"` + CanRetire bool `json:"can_retire"` + Blockers workerRetirementBlockers `json:"blockers"` +} + +// Drive each arm from the target worker's own index range. The jobs-first +// CROSS JOIN keeps the second arm from scanning a project's unrelated notes. +// UNION counts a note that matches both its direct and job target only once. +const workerRetirementPendingNotes = `SELECT id,count(*) OVER() FROM ( + SELECT n.id FROM notes AS n INDEXED BY notes_project_worker_created + WHERE n.project_id=? AND n.worker_id=? AND n.status='pending' + UNION + SELECT n.id FROM jobs AS j INDEXED BY jobs_project_worker_order + CROSS JOIN notes AS n INDEXED BY notes_project_job_created + ON n.project_id=j.project_id AND n.job_id=j.id + WHERE j.project_id=? AND j.worker_id=? AND n.status='pending' +)` + +func retirementItems(ctx context.Context, tx *sql.Tx, query string, args ...any) (workerRetirementItems, error) { + items := workerRetirementItems{IDs: []string{}} + rows, err := tx.QueryContext(ctx, query+` ORDER BY id LIMIT 20`, args...) + if err != nil { + return items, err + } + defer rows.Close() + for rows.Next() { + var id string + if err := rows.Scan(&id, &items.Count); err != nil { + return items, err + } + items.IDs = append(items.IDs, id) + } + return items, rows.Err() +} + +func readWorkerRetirement(ctx context.Context, tx *sql.Tx, project, worker string) (workerRetirementStatus, error) { + status := workerRetirementStatus{WorkerID: worker} + if err := core.CheckWorker(ctx, tx, project, worker); err != nil { + return status, err + } + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM worker_retirements WHERE project_id=? AND worker_id=?)`, project, worker).Scan(&status.Retired); err != nil { + return status, err + } + var err error + status.Blockers.Jobs, err = retirementItems(ctx, tx, `SELECT id,count(*) OVER() FROM jobs WHERE project_id=? AND worker_id=? AND status<>'completed'`, project, worker) + if err != nil { + return status, err + } + status.Blockers.Notes, err = retirementItems(ctx, tx, workerRetirementPendingNotes, project, worker, project, worker) + if err != nil { + return status, err + } + status.Blockers.Messages, err = retirementItems(ctx, tx, `SELECT m.id,count(*) OVER() FROM inbox_messages m LEFT JOIN inbox_recipient_state r ON r.project_id=m.project_id AND r.message_id=m.id AND r.worker_id=m.recipient_worker_id WHERE m.project_id=? AND m.recipient_worker_id=? AND COALESCE(r.acknowledged,0)=0`, project, worker) + status.CanRetire = !status.Retired && status.Blockers.Jobs.Count == 0 && status.Blockers.Notes.Count == 0 && status.Blockers.Messages.Count == 0 + return status, err +} + +func (a *api) workerRetirement(w http.ResponseWriter, r *http.Request) { + scope, err := a.store.Scope(r, "read") + if err != nil { + core.WriteError(w, err) + return + } + if _, err := core.QueryKeys(r, "validation_failed"); err != nil { + core.WriteError(w, err) + return + } + var status workerRetirementStatus + err = a.store.Read(r.Context(), scope, func(ctx context.Context, tx *sql.Tx) error { + var err error + status, err = readWorkerRetirement(ctx, tx, scope.ProjectID, r.PathValue("worker_id")) + return err + }) + complete(w, status, err) +} + +func (a *api) retireWorker(w http.ResponseWriter, r *http.Request) { + scope, err := a.store.Scope(r, "write") + if err != nil { + core.WriteError(w, err) + return + } + if _, err := core.QueryKeys(r, "validation_failed"); err != nil { + core.WriteError(w, err) + return + } + var request struct{} + if err := core.ReadJSON(w, r, &request); err != nil { + core.WriteError(w, err) + return + } + k, err := key(r) + if err != nil { + core.WriteError(w, err) + return + } + id := r.PathValue("worker_id") + result, err := a.store.Mutate(r.Context(), scope, core.Mutation{Operation: "workers.retire", Target: id, Key: k, Request: request}, func(ctx context.Context, tx *sql.Tx) (any, error) { + status, err := readWorkerRetirement(ctx, tx, scope.ProjectID, id) + if err != nil { + return nil, err + } + outcome := "unchanged" + if !status.Retired { + if !status.CanRetire { + return nil, &core.Error{Code: "worker_retirement_blocked", Message: "Finish, reassign or consume the listed jobs and notes, and explicitly acknowledge incoming messages before retiring this worker.", Status: 409, Details: status.Blockers} + } + if _, err := tx.ExecContext(ctx, `INSERT INTO worker_retirements(project_id,worker_id,retired_at,actor_id) VALUES(?,?,?,?)`, scope.ProjectID, id, time.Now().UTC().Format(time.RFC3339Nano), scope.PrincipalID); err != nil { + return nil, err + } + if err := core.AppendEvent(ctx, tx, scope, "workers.retired", id, 2, map[string]string{"worker_id": id}); err != nil { + return nil, err + } + outcome = "retired" + } + return map[string]any{"id": id, "revision": 2, "outcome": outcome}, nil + }) + complete(w, result, err) +} diff --git a/internal/server/worker_retirement_peer_test.go b/internal/server/worker_retirement_peer_test.go new file mode 100644 index 000000000..4b04827c2 --- /dev/null +++ b/internal/server/worker_retirement_peer_test.go @@ -0,0 +1,104 @@ +package server_test + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/benhook1013/FireController/internal/client" + "github.com/benhook1013/FireController/internal/profile" +) + +func TestWorkerRetirementPeerAckFeedKeepsOriginalWireAndAudit(t *testing.T) { + f, project, actor, target := retirementFixture(t) + base := "/api/v1/projects/" + project + live := httptest.NewServer(f.handler) + defer live.Close() + credential := filepath.Join(t.TempDir(), "credential") + if err := os.WriteFile(credential, []byte(f.admin), 0600); err != nil { + t.Fatal(err) + } + recipient, err := client.New(t.Context(), profile.Binding{Context: profile.Context{Profile: "fixture", ServerURL: live.URL, InstanceID: f.store.InstanceID(), ProjectID: project, WorkerID: target}, CredentialFile: credential}) + if err != nil { + t.Fatal(err) + } + defer recipient.Close() + snapshot, err := recipient.InboxSnapshot(t.Context(), client.PageOptions{}, client.InboxFilter{}) + if err != nil { + t.Fatal(err) + } + message := retirementJSON(t, f, "POST", base+"/messages", f.admin, actor, map[string]any{"recipient_worker_id": target, "body": "Synthetic coordination"}, 201)["id"].(string) + retirementJSON(t, f, "POST", base+"/messages/"+message+"/ack", f.admin, actor, map[string]any{"worker_id": target}, 200) + query := url.Values{"cursor": {snapshot.EventCursor}, "limit": {"100"}} + wire := request(f.handler, http.MethodGet, base+"/message-events?"+query.Encode(), f.admin, "", target, "") + require(t, wire, http.StatusOK) + var wireEvents messageEventPage + if err := json.Unmarshal(wire.Body.Bytes(), &wireEvents); err != nil { + t.Fatal("decode raw feed", err) + } + if len(wireEvents.Items) != 2 || wireEvents.Items[1].Type != "message.acknowledged" || wireEvents.Items[1].ResourceID != message { + t.Fatal("exact acknowledgement missing from raw feed", wireEvents) + } + var ackPayload map[string]json.RawMessage + if err := json.Unmarshal(wireEvents.Items[1].Payload, &ackPayload); err != nil || ackPayload == nil { + t.Fatal("decode acknowledgement payload", err) + } + if _, present := ackPayload["actor_worker_id"]; present { + t.Fatal("public acknowledgement exposes durable actor worker") + } + events, err := recipient.MessageEvents(t.Context(), snapshot.EventCursor, 100, 0) + if err != nil { + t.Fatal("actual typed feed rejected on-behalf ACK", err) + } + if len(events.Items) != 2 || events.Items[1].Type != "message.acknowledged" || events.Items[1].Payload.RecipientWorkerID != target || events.Items[1].Payload.ConversationID == "" { + t.Fatal("feed facts changed", events) + } + raw, err := json.Marshal(events) + if err != nil || strings.Contains(string(raw), "actor_worker_id") { + t.Fatal("public feed changed", err) + } + var stored string + if err = f.store.DB().QueryRow(`SELECT payload_json FROM events WHERE project_id=? AND event_type='message.acknowledged' AND resource_id=?`, project, message).Scan(&stored); err != nil || !strings.Contains(stored, `"actor_worker_id":"`+actor+`"`) { + t.Fatal("durable actor attribution was lost", err) + } +} + +func TestWorkerRetirementPeerBrowserOriginalManagementCeiling(t *testing.T) { + f, project, actor, target := retirementFixture(t) + base := "/api/v1/projects/" + project + token := "synthetic-promoted-writer-token-1234567" + f.grant(t, project, token, true) + oldID := strings.Repeat("a", 32) + oldCookie := browserActionsLogin(t, f, project, token, oldID, false) + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=1 WHERE project_id=?`, project); err != nil { + t.Fatal(err) + } + managerID := strings.Repeat("b", 32) + managerCookie := browserActionsLogin(t, f, project, token, managerID, true) + message := retirementJSON(t, f, "POST", base+"/messages", f.admin, actor, map[string]any{"recipient_worker_id": target, "body": "Synthetic pending message"}, 201)["id"].(string) + path := base + "/messages/" + message + "/ack" + body := `{"worker_id":"` + target + `"}` + before := count(t, f.store, "receipts") + require(t, serveBrowserAction(f, browserActionRequest(f, http.MethodPost, path, oldID, oldCookie, actor, "original-key", body)), 403) + if count(t, f.store, "receipts") != before { + t.Fatal("old writer cookie performed management work") + } + first := serveBrowserAction(f, browserActionRequest(f, http.MethodPost, path, managerID, managerCookie, actor, "original-key", body)) + require(t, first, 200) + require(t, serveBrowserAction(f, browserActionRequest(f, http.MethodPost, path, oldID, oldCookie, actor, "original-key", body)), 403) + replay := serveBrowserAction(f, browserActionRequest(f, http.MethodPost, path, managerID, managerCookie, actor, "original-key", body)) + require(t, replay, 200) + if replay.Body.String() != first.Body.String() { + t.Fatal("original manager replay changed") + } + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=0 WHERE project_id=?`, project); err != nil { + t.Fatal(err) + } + require(t, serveBrowserAction(f, browserActionRequest(f, http.MethodPost, path, managerID, managerCookie, actor, "original-key", body)), 403) + require(t, request(f.handler, http.MethodPost, path, f.admin, "bearer-admin", actor, body), 200) +} diff --git a/internal/server/worker_retirement_plan_test.go b/internal/server/worker_retirement_plan_test.go new file mode 100644 index 000000000..4c3444df9 --- /dev/null +++ b/internal/server/worker_retirement_plan_test.go @@ -0,0 +1,52 @@ +package server + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/jobs" +) + +func TestWorkerRetirementNoteBlockersUseSelectivePlan(t *testing.T) { + data := filepath.Join(t.TempDir(), "data") + if err := os.Mkdir(data, 0700); err != nil { + t.Fatal(err) + } + store, err := core.Open(t.Context(), data) + if err != nil { + t.Fatal(err) + } + defer store.Close() + if err := jobs.EnsureSchema(t.Context(), store); err != nil { + t.Fatal(err) + } + rows, err := store.DB().QueryContext(t.Context(), "EXPLAIN QUERY PLAN "+workerRetirementPendingNotes+" ORDER BY id LIMIT 20", "project", "worker", "project", "worker") + if err != nil { + t.Fatal(err) + } + defer rows.Close() + var plan strings.Builder + for rows.Next() { + var id, parent, unused int + var detail string + if err := rows.Scan(&id, &parent, &unused, &detail); err != nil { + t.Fatal(err) + } + plan.WriteString(detail + "\n") + } + if err := rows.Err(); err != nil { + t.Fatal(err) + } + for _, seek := range []string{ + "notes_project_worker_created (project_id=? AND worker_id=?)", + "jobs_project_worker_order (project_id=? AND worker_id=?)", + "notes_project_job_created (project_id=? AND job_id=?)", + } { + if !strings.Contains(plan.String(), seek) { + t.Fatalf("missing worker-scoped seek %s:\n%s", seek, plan.String()) + } + } +} diff --git a/internal/server/worker_retirement_test.go b/internal/server/worker_retirement_test.go new file mode 100644 index 000000000..7b1f5ddf8 --- /dev/null +++ b/internal/server/worker_retirement_test.go @@ -0,0 +1,390 @@ +package server_test + +import ( + "bytes" + "context" + "database/sql" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "runtime" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/benhook1013/FireController/internal/core" + "github.com/benhook1013/FireController/internal/inbox" + "github.com/benhook1013/FireController/internal/jobs" +) + +type retirementPreview struct { + WorkerID string `json:"worker_id"` + Retired bool `json:"retired"` + CanRetire bool `json:"can_retire"` + Blockers struct { + Jobs, Notes, Messages struct { + Count int `json:"count"` + IDs []string `json:"ids"` + } + } `json:"blockers"` +} + +func retirementFixture(t *testing.T) (*fixture, string, string, string) { + t.Helper() + f := setup(t) + for _, ensure := range []func(context.Context, *core.Store) error{jobs.EnsureSchema, inbox.EnsureSchema} { + if err := ensure(t.Context(), f.store); err != nil { + t.Fatal(err) + } + } + mux := http.NewServeMux() + mux.Handle("/", f.handler) + jobs.Register(mux, f.store) + inbox.Register(mux, f.store) + f.handler = mux + project := f.project(t, "owner/one") + return f, project, f.worker(t, project, "Actor"), f.worker(t, project, "Retiring") +} + +func retirementJSON(t *testing.T, f *fixture, method, path, token, actor string, body any, status int) map[string]any { + t.Helper() + text := "" + if body != nil { + data, err := json.Marshal(body) + if err != nil { + t.Fatal(err) + } + text = string(data) + } + return require(t, request(f.handler, method, path, token, core.NewID("test"), actor, text), status) +} + +func retirementStatus(t *testing.T, f *fixture, path, token string) retirementPreview { + t.Helper() + w := request(f.handler, "GET", path, token, "", "", "") + require(t, w, 200) + var result retirementPreview + if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil { + t.Fatal(err) + } + return result +} + +func TestWorkerRetirementBlockersCleanupHistoryAndActiveTargets(t *testing.T) { + f, project, actor, target := retirementFixture(t) + base := "/api/v1/projects/" + project + path := base + "/workers/" + target + writer, manager := "retirement-writer", "retirement-manager" + f.grant(t, project, writer, true) + projectManagerGrant(t, f, project, manager) + replacement := f.worker(t, project, "Replacement") + job := retirementJSON(t, f, "POST", base+"/jobs", writer, actor, map[string]any{"title": "Unfinished", "worker_id": target}, 201)["id"].(string) + completed := retirementJSON(t, f, "POST", base+"/jobs", writer, actor, map[string]any{"title": "Historical", "worker_id": target, "status": "completed"}, 201)["id"].(string) + createNote := func(worker, job string) string { + return retirementJSON(t, f, "POST", base+"/notes", writer, actor, map[string]any{"worker_id": worker, "job_id": job, "phase": "", "kind": "reminder", "body": "Retained reminder"}, 201)["id"].(string) + } + direct, assigned, historical := createNote(target, ""), createNote("", job), createNote("", completed) + message := retirementJSON(t, f, "POST", base+"/messages", writer, actor, map[string]any{"recipient_worker_id": target, "body": "Retained incoming message"}, 201)["id"].(string) + preview := retirementStatus(t, f, path+"/retirement", writer) + if preview.CanRetire || preview.Retired || preview.WorkerID != target || preview.Blockers.Jobs.Count != 1 || preview.Blockers.Notes.Count != 3 || preview.Blockers.Messages.Count != 1 || preview.Blockers.Jobs.IDs[0] != job || preview.Blockers.Messages.IDs[0] != message { + t.Fatal("unfinished applicable work was omitted", preview, assigned) + } + before := count(t, f.store, "events") + blocked := require(t, request(f.handler, "POST", path+"/retire", writer, "retire-target", actor, `{}`), 409) + if blocked["error"].(map[string]any)["code"] != "worker_retirement_blocked" || count(t, f.store, "events") != before || count(t, f.store, "worker_retirements") != 0 { + t.Fatal("blocked retirement changed state", blocked) + } + retirementJSON(t, f, "PATCH", base+"/jobs/"+job, writer, actor, map[string]any{"expected_revision": 1, "worker_id": replacement}, 200) + preview = retirementStatus(t, f, path+"/retirement", writer) + if preview.Blockers.Jobs.Count != 0 || preview.Blockers.Notes.Count != 2 { + t.Fatal("job reassignment did not move its pending note applicability", preview) + } + for _, id := range []string{direct, historical} { + retirementJSON(t, f, "PATCH", base+"/notes/"+id, writer, actor, map[string]any{"expected_revision": 1, "status": "consumed"}, 200) + } + ack := base + "/messages/" + message + "/ack" + body := `{"worker_id":"` + target + `"}` + require(t, request(f.handler, "POST", ack, writer, "not-manager", actor, body), 403) + require(t, request(f.handler, "POST", ack, manager, "manager-ack", actor, body), 200) + var principal, payload string + if err := f.store.DB().QueryRow(`SELECT actor_id,payload_json FROM events WHERE project_id=? AND event_type='message.acknowledged' AND resource_id=?`, project, message).Scan(&principal, &payload); err != nil || principal == "" || !strings.Contains(payload, target) || !strings.Contains(payload, `"actor_worker_id":"`+actor+`"`) { + t.Fatal("on-behalf acknowledgement lost actual actor or recipient", principal, payload, err) + } + preview = retirementStatus(t, f, path+"/retirement", writer) + if !preview.CanRetire || preview.Blockers.Messages.Count != 0 || preview.Blockers.Notes.Count != 0 { + t.Fatal("explicit cleanup did not permit retirement", preview) + } + if _, err := f.store.DB().Exec(`CREATE TRIGGER refuse_retirement_event BEFORE INSERT ON events WHEN NEW.event_type='workers.retired' BEGIN SELECT RAISE(ABORT,'synthetic retirement event failure'); END`); err != nil { + t.Fatal(err) + } + require(t, request(f.handler, "POST", path+"/retire", writer, "retire-target", actor, `{}`), 500) + if count(t, f.store, "worker_retirements") != 0 { + t.Fatal("failed retirement event left a retired identity") + } + if _, err := f.store.DB().Exec(`DROP TRIGGER refuse_retirement_event`); err != nil { + t.Fatal(err) + } + retired := request(f.handler, "POST", path+"/retire", writer, "retire-target", actor, `{}`) + result := require(t, retired, 200) + if result["id"] != target || result["revision"] != float64(2) || result["outcome"] != "retired" { + t.Fatal(result) + } + before = count(t, f.store, "events") + replay := request(f.handler, "POST", path+"/retire", writer, "retire-target", actor, `{}`) + if replay.Code != 200 || !bytes.Equal(retired.Body.Bytes(), replay.Body.Bytes()) || count(t, f.store, "events") != before { + t.Fatal("retirement replay changed original receipt or history", replay.Body.String()) + } + unchanged := require(t, request(f.handler, "POST", path+"/retire", writer, "already-retired", actor, `{}`), 200) + if unchanged["outcome"] != "unchanged" || count(t, f.store, "events") != before { + t.Fatal("repeat retirement created another transition", unchanged) + } + preview = retirementStatus(t, f, path+"/retirement", writer) + if !preview.Retired || preview.CanRetire { + t.Fatal(preview) + } + active := request(f.handler, "GET", base+"/workers", writer, "", "", "") + require(t, active, 200) + if strings.Contains(active.Body.String(), target) || strings.Contains(active.Body.String(), `"retired":false`) { + t.Fatal("retired worker remained an ordinary target", active.Body.String()) + } + archive := request(f.handler, "GET", base+"/workers?include_retired=true", writer, "", "", "") + require(t, archive, 200) + if !strings.Contains(archive.Body.String(), target) || !strings.Contains(archive.Body.String(), `"retired":true`) { + t.Fatal("archived worker disappeared", archive.Body.String()) + } + if direct := require(t, request(f.handler, "GET", path, writer, "", target, ""), 200); direct["retired"] != true { + t.Fatal("historical worker attribution/authentication was revoked", direct) + } + // Historical corrections stay available, while reopening/attaching new + // unfinished work and sending to or from the retired identity are refused. + retirementJSON(t, f, "PATCH", base+"/jobs/"+completed, writer, actor, map[string]any{"expected_revision": 1, "brief": "Historical correction"}, 200) + for _, call := range []struct{ method, route, acting, body string }{ + {"POST", base + "/jobs", actor, `{"title":"New","worker_id":"` + target + `"}`}, + {"PATCH", base + "/jobs/" + completed, actor, `{"expected_revision":2,"status":"active"}`}, + {"PATCH", base + "/notes/" + direct, actor, `{"expected_revision":2,"status":"pending"}`}, + {"POST", base + "/notes", actor, `{"worker_id":"` + target + `","job_id":"","phase":"","kind":"reminder","body":"New"}`}, + {"POST", base + "/notes", actor, `{"worker_id":"","job_id":"` + completed + `","phase":"","kind":"reminder","body":"New"}`}, + {"POST", base + "/messages", actor, `{"recipient_worker_id":"` + target + `","body":"New"}`}, + {"POST", base + "/messages", target, `{"recipient_worker_id":"` + actor + `","body":"New"}`}, + } { + value := require(t, request(f.handler, call.method, call.route, writer, core.NewID("refused"), call.acting, call.body), 409) + if value["error"].(map[string]any)["code"] != "worker_retired" { + t.Fatal("new retired target was not refused", value) + } + } + retirementJSON(t, f, "PATCH", base+"/notes/"+direct, writer, actor, map[string]any{"expected_revision": 2, "body": "Historical note correction"}, 200) + retirementJSON(t, f, "GET", base+"/jobs/"+completed+"/history", writer, target, nil, 200) + var columns int + if err := f.store.DB().QueryRow(`SELECT count(*) FROM pragma_table_info('workers')`).Scan(&columns); err != nil || columns != 3 { + t.Fatal("retirement rewrote base worker history schema", columns, err) + } +} + +// Named callers let the test distinguish the two handlers in the admission +// wait, rather than mistaking an unrelated writer or goroutine for a contender. +func retirementRaceRequest(f *fixture, path, actor string) *httptest.ResponseRecorder { + return request(f.handler, "POST", path+"/retire", f.admin, "race-retire", actor, "{}") +} + +func retirementRaceAssignment(f *fixture, base, actor, target string) *httptest.ResponseRecorder { + return request(f.handler, "POST", base+"/jobs", f.admin, "race-job", actor, `{"title":"Racing assignment","worker_id":"`+target+`"}`) +} + +func TestWorkerRetirementAdmissionRaceAndBoundedBlockers(t *testing.T) { + f, project, actor, target := retirementFixture(t) + base := "/api/v1/projects/" + project + path := base + "/workers/" + target + req := httptest.NewRequest("POST", "/", nil) + req.SetPathValue("project_id", project) + req.Header.Set("Authorization", "Bearer "+f.admin) + scope, err := f.store.Scope(req, "write") + if err != nil { + t.Fatal(err) + } + entered, release, held := make(chan struct{}), make(chan struct{}), make(chan error, 1) + var releaseOnce sync.Once + releaseWriter := func() { releaseOnce.Do(func() { close(release) }) } + var writers sync.WaitGroup + defer func() { + releaseWriter() + allDone := make(chan struct{}) + go func() { writers.Wait(); close(allDone) }() + select { + case <-allDone: + case <-time.After(3 * time.Second): + t.Error("test writers did not exit after admission release") + } + }() + writers.Add(1) + go func() { + defer writers.Done() + _, err := f.store.Mutate(t.Context(), scope, core.Mutation{ + Operation: "proof.retirement_hold", Target: target, Key: "hold-retirement-race", Request: struct{}{}, + }, func(context.Context, *sql.Tx) (any, error) { + close(entered) + <-release + return struct{}{}, nil + }) + held <- err + }() + select { + case <-entered: + case <-time.After(time.Second): + t.Fatal("test writer did not acquire admission") + } + retire, assign := make(chan *httptest.ResponseRecorder, 1), make(chan *httptest.ResponseRecorder, 1) + writers.Add(2) + go func() { defer writers.Done(); retire <- retirementRaceRequest(f, path, actor) }() + go func() { defer writers.Done(); assign <- retirementRaceAssignment(f, base, actor, target) }() + // Go 1.27's runtime.Stack wait labels are test instrumentation only. + // Match two separately owned handlers and Store.Mutate, not file offsets + // or a global goroutine count. Fail closed if the pinned format changes. + stack := make([]byte, 64<<10) + deadline := time.Now().Add(time.Second) + for { + retirementWaiting, assignmentWaiting := false, false + n := runtime.Stack(stack, true) + if n == len(stack) { + stack = make([]byte, 2*len(stack)) + continue + } + for _, trace := range strings.Split(string(stack[:n]), "\n\n") { + firstLine, _, _ := strings.Cut(trace, "\n") + if !strings.Contains(firstLine, "[select]") || !strings.Contains(trace, "internal/core.(*Store).Mutate(") { + continue + } + retirementWaiting = retirementWaiting || strings.Contains(trace, ".retirementRaceRequest(") + assignmentWaiting = assignmentWaiting || strings.Contains(trace, ".retirementRaceAssignment(") + } + if retirementWaiting && assignmentWaiting { + break + } + if time.Now().After(deadline) { + t.Fatalf("did not observe both requests waiting for write admission: retirement=%t assignment=%t", retirementWaiting, assignmentWaiting) + } + time.Sleep(time.Millisecond) + } + releaseWriter() + select { + case err := <-held: + if err != nil { + t.Fatal(err) + } + case <-time.After(3 * time.Second): + t.Fatal("test writer did not return") + } + result := func(name string, response <-chan *httptest.ResponseRecorder) *httptest.ResponseRecorder { + t.Helper() + select { + case got := <-response: + return got + case <-time.After(3 * time.Second): + t.Fatalf("%s did not return after write admission was released", name) + return nil + } + } + r, a := result("retirement", retire), result("assignment", assign) + if !(r.Code == 200 && a.Code == 409 || r.Code == 409 && a.Code == 201) { + t.Fatal("retirement and new assignment both succeeded or lost state", r.Code, r.Body.String(), a.Code, a.Body.String()) + } + bounded := f.worker(t, project, "Many notes") + for i := range 21 { + retirementJSON(t, f, "POST", base+"/notes", f.admin, actor, map[string]any{"worker_id": bounded, "job_id": "", "phase": "", "kind": "reminder", "body": fmt.Sprintf("Pending %d", i)}, 201) + } + preview := retirementStatus(t, f, base+"/workers/"+bounded+"/retirement", f.admin) + if preview.Blockers.Notes.Count != 21 || len(preview.Blockers.Notes.IDs) != 20 || preview.CanRetire { + t.Fatal("blocker response truncated its actual count or exceeded ID bound", preview) + } +} + +func TestWorkerRetirementManagementAckReplayReauthorizesAndIsolates(t *testing.T) { + f, project, actor, target := retirementFixture(t) + base := "/api/v1/projects/" + project + writer, manager := "ack-writer", "ack-manager" + f.grant(t, project, writer, true) + id := projectManagerGrant(t, f, project, manager) + message := retirementJSON(t, f, "POST", base+"/messages", writer, actor, map[string]any{"recipient_worker_id": target, "body": "Incoming"}, 201)["id"].(string) + path := base + "/messages/" + message + "/ack" + body := `{"worker_id":"` + target + `"}` + for _, invalid := range []string{`{"worker_id":null}`, `{"worker_id":""}`} { + require(t, request(f.handler, "POST", path, writer, core.NewID("invalid-ack"), actor, invalid), 400) + } + require(t, request(f.handler, "POST", path, writer, "ordinary-other-ack", actor, body), 403) + original := request(f.handler, "POST", path, manager, "managed-ack", actor, body) + require(t, original, 200) + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=0 WHERE credential_id=? AND project_id=?`, id, project); err != nil { + t.Fatal(err) + } + require(t, request(f.handler, "POST", path, manager, "managed-ack", actor, body), 403) + if _, err := f.store.DB().Exec(`UPDATE grants SET can_manage=1 WHERE credential_id=? AND project_id=?`, id, project); err != nil { + t.Fatal(err) + } + replay := request(f.handler, "POST", path, manager, "managed-ack", actor, body) + if replay.Code != 200 || !bytes.Equal(original.Body.Bytes(), replay.Body.Bytes()) { + t.Fatal("recovery changed the original explicit acknowledgement", replay.Body.String()) + } + // Default and explicit-own acknowledgement preserve ordinary writer access. + for i, ackBody := range []string{`{}`, body} { + message := retirementJSON(t, f, "POST", base+"/messages", writer, actor, map[string]any{"recipient_worker_id": target, "body": "Own incoming"}, 201)["id"].(string) + require(t, request(f.handler, "POST", base+"/messages/"+message+"/ack", writer, fmt.Sprintf("own-%d", i), target, ackBody), 200) + } + other := f.project(t, "owner/two") + foreign := f.worker(t, other, "Foreign") + require(t, request(f.handler, "GET", base+"/workers/"+foreign+"/retirement", writer, "", "", ""), 404) + require(t, request(f.handler, "POST", base+"/workers/"+foreign+"/retire", writer, "foreign-retire", actor, `{}`), 404) + require(t, request(f.handler, "POST", "/api/v1/projects/"+other+"/workers/"+foreign+"/retire", writer, "other-project-retire", "", `{}`), 403) + reader := "retirement-reader" + f.grant(t, project, reader, false) + require(t, request(f.handler, "GET", base+"/workers/"+target+"/retirement", reader, "", "", ""), 200) + require(t, request(f.handler, "POST", base+"/workers/"+target+"/retire", reader, "reader-retire", "", `{}`), 403) +} + +func TestWorkerListRawQueryBound(t *testing.T) { + f := setup(t) + project := f.project(t, "owner/query-bound") + base := "/api/v1/projects/" + project + "/workers?" + // Leading zeroes retain a valid page limit, distinguishing the raw byte + // bound from cursor/value validation. + for _, size := range []int{16 << 10, (16 << 10) + 1} { + query := "limit=" + strings.Repeat("0", size-len("limit=1")) + "1" + status := 200 + if size > 16<<10 { + status = 400 + } + require(t, request(f.handler, "GET", base+query, f.admin, "", "", ""), status) + } +} +func TestWorkerRetirementNoteBlockersDeduplicateAndKeepScope(t *testing.T) { + f, project, actor, target := retirementFixture(t) + base := "/api/v1/projects/" + project + other := f.worker(t, project, "Other") + job := func(worker string) string { + return retirementJSON(t, f, "POST", base+"/jobs", f.admin, actor, map[string]any{"title": "Retained job", "worker_id": worker, "status": "completed"}, 201)["id"].(string) + } + note := func(worker, job string) string { + return retirementJSON(t, f, "POST", base+"/notes", f.admin, actor, map[string]any{"worker_id": worker, "job_id": job, "phase": "", "kind": "reminder", "body": "Retained note"}, 201)["id"].(string) + } + owned, unrelated, unassigned := job(target), job(other), job("") + both := note(target, owned) + direct := note(target, "") + jobOnly := note("", owned) + directOtherJob := note(target, unrelated) + note(other, unrelated) + note("", unassigned) + dismissed := note(target, owned) + retirementJSON(t, f, "PATCH", base+"/notes/"+dismissed, f.admin, actor, map[string]any{"expected_revision": 1, "status": "consumed"}, 200) + + foreign := f.project(t, "owner/two") + foreignWorker := f.worker(t, foreign, "Foreign") + retirementJSON(t, f, "POST", "/api/v1/projects/"+foreign+"/notes", f.admin, foreignWorker, map[string]any{"worker_id": foreignWorker, "job_id": "", "phase": "", "kind": "reminder", "body": "Other project note"}, 201) + + want := []string{both, direct, jobOnly, directOtherJob} + slices.Sort(want) + got := retirementStatus(t, f, base+"/workers/"+target+"/retirement", f.admin).Blockers.Notes + if got.Count != len(want) || !slices.Equal(got.IDs, want) { + t.Fatalf("pending note blockers: got %v, want sorted unique IDs %v", got, want) + } +} diff --git a/internal/webui/assets/assets/index-DOGM3WbL.js b/internal/webui/assets/assets/index-xQH0iA8U.js similarity index 76% rename from internal/webui/assets/assets/index-DOGM3WbL.js rename to internal/webui/assets/assets/index-xQH0iA8U.js index 2cb9f0b2a..a2e694c7c 100644 --- a/internal/webui/assets/assets/index-DOGM3WbL.js +++ b/internal/webui/assets/assets/index-xQH0iA8U.js @@ -7,4 +7,4 @@ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r= Error generating stack: `+e.message+` `+e.stack}}var Be=Object.prototype.hasOwnProperty,Ve=t.unstable_scheduleCallback,He=t.unstable_cancelCallback,Ue=t.unstable_shouldYield,We=t.unstable_requestPaint,Ge=t.unstable_now,Ke=t.unstable_getCurrentPriorityLevel,qe=t.unstable_ImmediatePriority,Je=t.unstable_UserBlockingPriority,Ye=t.unstable_NormalPriority,Xe=t.unstable_LowPriority,Ze=t.unstable_IdlePriority,Qe=t.log,$e=t.unstable_setDisableYieldValue,et=null,tt=null;function nt(e){if(typeof Qe==`function`&&$e(e),tt&&typeof tt.setStrictMode==`function`)try{tt.setStrictMode(et,e)}catch{}}var rt=Math.clz32?Math.clz32:ot,it=Math.log,at=Math.LN2;function ot(e){return e>>>=0,e===0?32:31-(it(e)/at|0)|0}var st=256,ct=262144,lt=4194304;function ut(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&-e;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function dt(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=ut(n))):i=ut(o):i=ut(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=ut(n))):i=ut(o)):i=ut(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function ft(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function pt(e,t){t&8&&(t|=t&32);var n=e.entangledLanes;if(n!==0)for(e=e.entanglements,n&=t;0n;n++)t.push(e);return t}function _t(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function vt(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0=_r),br=` `,xr=!1;function Sr(e,t){switch(e){case`keyup`:return hr.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function Cr(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var wr=!1;function Tr(e,t){switch(e){case`compositionend`:return Cr(t);case`keypress`:return t.which===32?(xr=!0,br):null;case`textInput`:return e=t.data,e===br&&xr?null:e;default:return null}}function Er(e,t){if(wr)return e===`compositionend`||!gr&&Sr(e,t)?(e=Rn(),Ln=In=Fn=null,wr=!1,e):null;switch(e){case`paste`:return null;case`keypress`:if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}a:{for(;n;){if(n.nextSibling){n=n.nextSibling;break a}n=n.parentNode}n=void 0}n=Yr(n)}}function Zr(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Zr(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Qr(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Jr(e.document);t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href==`string`}catch{n=!1}if(n)e=t.contentWindow;else break;t=Jr(e.document)}return t}function $r(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t===`input`&&(e.type===`text`||e.type===`search`||e.type===`tel`||e.type===`url`||e.type===`password`)||t===`textarea`||e.contentEditable===`true`)}var ei=Mn&&`documentMode`in document&&11>=document.documentMode,ti=null,ni=null,ri=null,ii=!1;function ai(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;ii||ti==null||ti!==Jr(r)||(r=ti,`selectionStart`in r&&$r(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),ri&&qr(ri,r)||(ri=r,r=qf(ni,`onSelect`),0>=o,i-=o,I=1<<32-rt(t)+i|n<h?(g=d,d=null):g=d.sibling;var _=p(i,d,s[h],c);if(_===null){d===null&&(d=g);break}e&&d&&_.alternate===null&&t(i,d),a=o(_,a,h),u===null?l=_:u.sibling=_,u=_,d=g}if(h===s.length)return n(i,d),R&&ta(i,h),l;if(d===null){for(;hg?(_=h,h=null):_=h.sibling;var y=p(a,h,v.value,l);if(y===null){h===null&&(h=_);break}e&&h&&y.alternate===null&&t(a,h),s=o(y,s,g),d===null?u=y:d.sibling=y,d=y,h=_}if(v.done)return n(a,h),R&&ta(a,g),u;if(h===null){for(;!v.done;g++,v=c.next())v=f(a,v.value,l),v!==null&&(s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return R&&ta(a,g),u}for(h=r(h);!v.done;g++,v=c.next())v=m(h,a,g,v.value,l),v!==null&&(e&&(_=v.alternate,_!==null&&h.delete(_.key===null?g:_.key)),s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return e&&h.forEach(function(e){return t(a,e)}),R&&ta(a,g),u}function _(e,r,o,c){if(typeof o==`object`&&o&&o.type===te&&o.key===null&&o.props.ref===void 0&&(o=o.props.children),typeof o==`object`&&o){switch(o.$$typeof){case ee:a:{for(var l=o.key;r!==null;){if(r.key===l){if(l=o.type,l===te){if(r.tag===7){n(e,r.sibling),c=a(r,o.props.children),uo(c,o),c.return=e,e=c;break a}}else if(r.elementType===l||typeof l==`object`&&l&&l.$$typeof===ce&&ro(l)===r.type){n(e,r.sibling),c=a(r,o.props),uo(c,o),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}o.type===te?(c=Hi(o.props.children,e.mode,c,o.key),uo(c,o),c.return=e,e=c):(c=Vi(o.type,o.key,o.props,null,e.mode,c),uo(c,o),c.return=e,e=c)}return s(e);case k:a:{for(l=o.key;r!==null;){if(r.key===l){if(r.tag===4&&r.stateNode.containerInfo===o.containerInfo&&r.stateNode.implementation===o.implementation){n(e,r.sibling),c=a(r,o.children||[]),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}c=Wi(o,e.mode,c),c.return=e,e=c}return s(e);case ce:return o=ro(o),_(e,r,o,c)}if(ve(o))return h(e,r,o,c);if(he(o)){if(l=he(o),typeof l!=`function`)throw Error(i(150));return o=l.call(o),g(e,r,o,c)}if(typeof o.then==`function`)return _(e,r,lo(o),c);if(o.$$typeof===ie)return _(e,r,Oa(e,o),c);fo(e,o)}return typeof o==`string`&&o!==``||typeof o==`number`||typeof o==`bigint`?(o=``+o,r!==null&&r.tag===6?(n(e,r.sibling),c=a(r,o),c.return=e,e=c):(n(e,r),c=Ui(o,e.mode,c),c.return=e,e=c),s(e)):n(e,r)}return function(e,t,n,r){try{co=0;var i=_(e,t,n,r);return so=null,i}catch(t){if(t===Za||t===$a)throw t;var a=Li(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var mo=po(!0),ho=po(!1),go=!1;function _o(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function vo(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function yo(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function bo(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,Yu&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=Pi(e),Ni(e,null,n),t}return Ai(e,r,t,n),Pi(e)}function z(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,n&4194048)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,bt(e,n)}}function xo(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var o={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};a===null?i=a=o:a=a.next=o,n=n.next}while(n!==null);a===null?i=a=t:a=a.next=t}else i=a=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:a,shared:r.shared,callbacks:r.callbacks},e.updateQueue=n}else e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}var So=!1;function Co(){if(So){var e=Ha;if(e!==null)throw e}}function wo(e,t,n,r){So=!1;var i=e.updateQueue;go=!1;var a=i.firstBaseUpdate,o=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var c=s,l=c.next;c.next=null,o===null?a=l:o.next=l,o=c;var u=e.alternate;u!==null&&(u=u.updateQueue,s=u.lastBaseUpdate,s!==o&&(s===null?u.firstBaseUpdate=l:s.next=l,u.lastBaseUpdate=c))}if(a!==null){var d=i.baseState;o=0,u=l=c=null,s=a;do{var f=s.lane&-536870913,p=f!==s.lane;if(p?(Q&f)===f:(r&f)===f){f!==0&&f===Va&&(So=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var m=e,h=s;f=t;var g=n;switch(h.tag){case 1:if(m=h.payload,typeof m==`function`){d=m.call(g,d,f);break a}d=m;break a;case 3:m.flags=m.flags&-65537|128;case 0:if(m=h.payload,f=typeof m==`function`?m.call(g,d,f):m,f==null)break a;d=D({},d,f);break a;case 2:go=!0}}f=s.callback,f!==null&&(e.flags|=64,p&&(e.flags|=8192),p=i.callbacks,p===null?i.callbacks=[f]:p.push(f))}else p={lane:f,tag:s.tag,payload:s.payload,callback:s.callback,next:null},u===null?(l=u=p,c=d):u=u.next=p,o|=f;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;p=s,s=p.next,p.next=null,i.lastBaseUpdate=p,i.shared.pending=null}}while(1);u===null&&(c=d),i.baseState=c,i.firstBaseUpdate=l,i.lastBaseUpdate=u,a===null&&(i.shared.lanes=0),id|=o,e.lanes=o,e.memoizedState=d}}function To(e,t){if(typeof e!=`function`)throw Error(i(191,e));e.call(t)}function Eo(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ea?a:8;var o=M.T,s={};s.types=o===null?null:o.types,M.T=s,sc(e,!1,t,n);try{var c=i(),l=M.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?oc(e,t,Ga(c,r),kd(e)):oc(e,t,r,kd(e))}catch(n){oc(e,t,{then:function(){},status:`rejected`,reason:n},kd())}finally{N.p=a,o!==null&&s.types!==null&&(o.types=s.types),M.T=o}}function Xs(){}function Zs(e,t,n,r){if(e.tag!==5)throw Error(i(476));var a=Qs(e).queue;Ys(e,a,t,ye,n===null?Xs:function(){return $s(e),n(r)})}function Qs(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:ye,baseState:ye,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:H,lastRenderedState:ye},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:H,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function $s(e){var t=Qs(e);t.next===null&&(t=e.alternate.memoizedState),oc(e,t.next.queue,{},kd())}function ec(){return Da(sh)}function tc(){return V().memoizedState}function nc(){return V().memoizedState}function rc(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=kd();e=yo(n);var r=bo(t,e,n);r!==null&&(Md(r,t,n),z(r,t,n)),t={cache:Pa()},e.payload=t;return}t=t.return}}function ic(e,t,n){var r=kd();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},cc(e)?lc(t,n):(n=ji(e,t,n,r),n!==null&&(Md(n,e,r),uc(n,t,r)))}function ac(e,t,n){oc(e,t,n,kd())}function oc(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(cc(e))lc(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var o=t.lastRenderedState,s=a(o,n);if(i.hasEagerState=!0,i.eagerState=s,Kr(s,o))return Ai(e,t,i,0),Xu===null&&ki(),!1}catch{}if(n=ji(e,t,i,r),n!==null)return Md(n,e,r),uc(n,t,r),!0}return!1}function sc(e,t,n,r){if(r={lane:2,revertLane:Nf(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},cc(e)){if(t)throw Error(i(479))}else t=ji(e,n,r,2),t!==null&&Md(t,e,2)}function cc(e){var t=e.alternate;return e===B||t!==null&&t===B}function lc(e,t){qo=Ko=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function uc(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,bt(e,n)}}var dc={readContext:Da,use:ds,useCallback:$o,useContext:$o,useEffect:$o,useImperativeHandle:$o,useLayoutEffect:$o,useInsertionEffect:$o,useMemo:$o,useReducer:$o,useRef:$o,useState:$o,useDebugValue:$o,useDeferredValue:$o,useTransition:$o,useSyncExternalStore:$o,useId:$o,useHostTransitionStatus:$o,useFormState:$o,useActionState:$o,useOptimistic:$o,useMemoCache:$o,useCacheRefresh:$o,useEffectEvent:$o},fc={readContext:Da,use:ds,useCallback:function(e,t){return cs().memoizedState=[e,t===void 0?null:t],e},useContext:Da,useEffect:Is,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),Ps(4194308,4,Hs.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Ps(4194308,4,e,t)},useInsertionEffect:function(e,t){Ps(4,2,e,t)},useMemo:function(e,t){var n=cs();t=t===void 0?null:t;var r=e();if(Jo){nt(!0);try{e()}finally{nt(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=cs();if(n!==void 0){var i=n(t);if(Jo){nt(!0);try{n(t)}finally{nt(!1)}}}else i=t;return r.memoizedState=r.baseState=i,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:i},r.queue=e,e=e.dispatch=ic.bind(null,B,e),[r.memoizedState,e]},useRef:function(e){var t=cs();return e={current:e},t.memoizedState=e},useState:function(e){e=bs(e);var t=e.queue,n=ac.bind(null,B,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:Ws,useDeferredValue:function(e,t){return qs(cs(),e,t)},useTransition:function(){var e=bs(!1);return e=Ys.bind(null,B,e.queue,!0,!1),cs().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=B,a=cs();if(R){if(n===void 0)throw Error(i(407));n=n()}else{if(n=t(),Xu===null)throw Error(i(349));Q&127||_s(r,t,n)}a.memoizedState=n;var o={value:n,getSnapshot:t};return a.queue=o,Is(W.bind(null,r,o,e),[e]),r.flags|=2048,Ns(9,{destroy:void 0},U.bind(null,r,o,n,t),null),n},useId:function(){var e=cs(),t=Xu.identifierPrefix;if(R){var n=ea,r=I;n=(r&~(1<<32-rt(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=Yo++,0<\/script>`,o=o.removeChild(o.firstChild);break;case`select`:o=typeof r.is==`string`?s.createElement(`select`,{is:r.is}):s.createElement(`select`),r.multiple?o.multiple=!0:r.size&&(o.size=r.size);break;default:o=typeof r.is==`string`?s.createElement(a,{is:r.is}):s.createElement(a)}}o[Dt]=t,o[Ot]=r;a:for(s=t.child;s!==null;){if(s.tag===5||s.tag===6)o.appendChild(s.stateNode);else if(s.tag!==4&&s.tag!==27&&s.child!==null){s.child.return=s,s=s.child;continue}if(s===t)break a;for(;s.sibling===null;){if(s.return===null||s.return===t)break a;s=s.return}s.sibling.return=s.return,s=s.sibling}t.stateNode=o;a:switch(np(o,a,r),a){case`button`:case`input`:case`select`:case`textarea`:r=!!r.autoFocus;break a;case`img`:r=!0;break a;default:r=!1}r&&sl(t)}}return fl(t),t.subtreeFlags&=-33554433,cl(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&sl(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(i(166));if(e=De.current,pa(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,a=oa,a!==null)switch(a.tag){case 27:case 5:r=a.memoizedProps}e[Dt]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||$f(e.nodeValue,n)),e||ua(t,!0)}else e=lp(e).createTextNode(r),e[Dt]=t,t.stateNode=e}return fl(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=pa(t),n!==null){if(e===null){if(!r)throw Error(i(318));if(e=t.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(i(557));e[Dt]=t}else ma(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;fl(t),e=!1}else n=ha(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(Ro(t),t):(Ro(t),null);if(t.flags&128)throw Error(i(558))}return fl(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(a=pa(t),r!==null&&r.dehydrated!==null){if(e===null){if(!a)throw Error(i(318));if(a=t.memoizedState,a=a===null?null:a.dehydrated,!a)throw Error(i(317));a[Dt]=t}else ma(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;fl(t),a=!1}else a=ha(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=a),a=!0;if(!a)return t.flags&256?(Ro(t),t):(Ro(t),null)}return Ro(t),t.flags&128?(t.lanes=n,t):(n=r!==null,e=e!==null&&e.memoizedState!==null,n&&(r=t.child,a=null,r.alternate!==null&&r.alternate.memoizedState!==null&&r.alternate.memoizedState.cachePool!==null&&(a=r.alternate.memoizedState.cachePool.pool),o=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(o=r.memoizedState.cachePool.pool),o!==a&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),ul(t,t.updateQueue),fl(t),null);case 4:return Ae(),e===null&&Uf(t.stateNode.containerInfo),t.flags|=67108864,fl(t),null;case 10:return xa(t.type),fl(t),null;case 19:if(Vo(t),r=t.memoizedState,r===null)return fl(t),null;if(a=!!(t.flags&128),o=r.rendering,o===null){if(a)dl(r,!1);else{if(rd!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=Ho(e),o!==null){for(t.flags|=128,dl(r,!1),e=o.updateQueue,t.updateQueue=e,ul(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)Bi(n,e),n=n.sibling;return Bo(t,zo.current&1|2),R&&ta(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&Ge()>md&&(t.flags|=128,a=!0,dl(r,!1),t.lanes=4194304)}}else{if(!a){if(e=Ho(o),e!==null){if(t.flags|=128,a=!0,e=e.updateQueue,t.updateQueue=e,ul(t,e),dl(r,!0),r.tail===null&&r.tailMode!==`collapsed`&&r.tailMode!==`visible`&&!o.alternate&&!R)return fl(t),null}else 2*Ge()-r.renderingStartTime>md&&n!==536870912&&(t.flags|=128,a=!0,dl(r,!1),t.lanes=4194304)}r.isBackwards?(o.sibling=t.child,t.child=o):(e=r.last,e===null?t.child=o:e.sibling=o,r.last=o)}if(r.tail!==null){e=r.tail;a:{for(n=e;n!==null;){if(n.alternate!==null){n=!1;break a}n=n.sibling}n=!0}return r.rendering=e,r.tail=e.sibling,r.renderingStartTime=Ge(),e.sibling=null,o=zo.current,o=a?o&1|2:o&1,r.tailMode===`visible`||r.tailMode===`collapsed`||!n||R?Bo(t,o):(n=o,we(Mo,t),we(zo,n),No===null&&(No=t)),R&&ta(t,r.treeForkCount),e}return fl(t),null;case 22:case 23:return Ro(t),jo(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(fl(t),t.subtreeFlags&6&&(t.flags|=8192)):fl(t),n=t.updateQueue,n!==null&&ul(t,n.retryQueue),n=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),r=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),e!==null&&Ce(qa),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),xa(Na),fl(t),null;case 25:return null;case 30:return t.flags|=33554432,fl(t),null}throw Error(i(156,t.tag))}function ml(e,t){switch(ia(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return xa(Na),Ae(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return Me(t),null;case 31:if(t.memoizedState!==null){if(Ro(t),t.alternate===null)throw Error(i(340));ma()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(Ro(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(i(340));ma()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Vo(t),e=t.flags,e&65536?(t.flags=e&-65537|128,e=t.memoizedState,e!==null&&(e.rendering=null,e.tail=null),t.flags|=4,t):null;case 4:return Ae(),null;case 10:return xa(t.type),null;case 22:case 23:return Ro(t),jo(),e!==null&&Ce(qa),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return xa(Na),null;case 25:return null;default:return null}}function hl(e,t){switch(ia(t),t.tag){case 3:xa(Na),Ae();break;case 26:case 27:case 5:Me(t);break;case 4:Ae();break;case 31:t.memoizedState!==null&&Ro(t);break;case 13:Ro(t);break;case 19:Vo(t);break;case 10:xa(t.type);break;case 22:case 23:Ro(t),jo(),e!==null&&Ce(qa);break;case 24:xa(Na)}}function gl(e,t){try{var n=t.updateQueue,r=n===null?null:n.lastEffect;if(r!==null){var i=r.next;n=i;do{if((n.tag&e)===e){r=void 0;var a=n.create,o=n.inst;r=a(),o.destroy=r}n=n.next}while(n!==i)}}catch(e){ff(t,t.return,e)}}function _l(e,t,n){try{var r=t.updateQueue,i=r===null?null:r.lastEffect;if(i!==null){var a=i.next;r=a;do{if((r.tag&e)===e){var o=r.inst,s=o.destroy;if(s!==void 0){o.destroy=void 0,i=t;var c=n,l=s;try{l()}catch(e){ff(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){ff(t,t.return,e)}}function vl(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{Eo(t,n)}catch(t){ff(e,e.return,t)}}}function yl(e,t,n){n.props=yc(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){ff(e,t,n)}}function bl(e,t){try{var n=e.ref;if(n!==null){switch(e.tag){case 26:case 27:case 5:var r=e.stateNode;break;case 30:var i=e.stateNode,a=Si(e.memoizedProps,i);(i.ref===null||i.ref.name!==a)&&(i.ref=Pp(a)),r=i.ref;break;case 7:if(e.stateNode===null){var o=new Fp(e);h(e.child,!1,Qp,o,void 0,void 0),e.stateNode=o}r=e.stateNode;break;default:r=e.stateNode}typeof n==`function`?e.refCleanup=n(r):n.current=r}}catch(n){ff(e,t,n)}}function xl(e,t){var n=e.ref,r=e.refCleanup;if(n!==null){if(typeof r==`function`)try{r()}catch(n){ff(e,t,n)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof n==`function`)try{n(null)}catch(n){ff(e,t,n)}else n.current=null}}function Sl(e,t){if((e.tag===5||e.tag===27||e.tag===6)&&e.alternate===null&&t!==null)for(var n=0;n title`))),np(r,t,n),r[Dt]=e,Vt(r),t=r;break a;case`link`:if(o=Gm(`link`,`href`,a).get(t+(n.href||``))){for(s=0;sg&&(o=g,g=h,h=o);var _=Xr(s,h),v=Xr(s,g);if(_&&v&&(p.rangeCount!==1||p.anchorNode!==_.node||p.anchorOffset!==_.offset||p.focusNode!==v.node||p.focusOffset!==v.offset)){var y=d.createRange();y.setStart(_.node,_.offset),p.removeAllRanges(),h>g?(p.addRange(y),p.extend(v.node,v.offset)):(y.setEnd(v.node,v.offset),p.addRange(y))}}}}for(d=[],p=s;p=p.parentNode;)p.nodeType===1&&d.push({element:p,left:p.scrollLeft,top:p.scrollTop});for(typeof s.focus==`function`&&s.focus(),s=0;sn?32:n,M.T=null,n=Sd,Sd=null;var o=vd,s=bd;if(_d=0,yd=vd=null,bd=0,Yu&6)throw Error(i(331));var c=Yu;if(Yu|=4,Wu(o.current),Iu(o,o.current,s,n),Yu=c,Ef(0,!1),tt&&typeof tt.onPostCommitFiberRoot==`function`)try{tt.onPostCommitFiberRoot(et,o)}catch{}return!0}finally{N.p=a,M.T=r,cf(e,t)}}function df(e,t,n){t=Ki(n,t),t=Tc(e.stateNode,t,2),e=bo(e,t,2),e!==null&&(_t(e,2),Tf(e))}function ff(e,t,n){if(e.tag===3)df(e,e,n);else for(;t!==null;){if(t.tag===3){df(t,e,n);break}if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(gd===null||!gd.has(r))){e=Ki(n,e),n=Ec(2),r=bo(t,n,2),r!==null&&(Dc(n,r,t,e),_t(r,2),Tf(r));break}}t=t.return}}function pf(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new Ju;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(td=!0,i.add(n),e=mf.bind(null,e,t,n),t.then(e,e))}function mf(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,Xu===e&&(Q&n)===n&&(rd===4||rd===3&&(Q&62914560)===Q&&300>Ge()-fd?Yu&2?od|=n:zd(e,0):od|=n,cd===Q&&(cd=0)),Tf(e)}function hf(e,t){t===0&&(t=ht()),e=Mi(e,t),e!==null&&(_t(e,t),Tf(e))}function gf(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),hf(e,n)}function _f(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,a=e.memoizedState;a!==null&&(n=a.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(i(314))}r!==null&&r.delete(t),hf(e,n)}function vf(e,t){return Ve(e,t)}var yf=null,bf=null,xf=!1,Sf=!1,Cf=!1,wf=0;function Tf(e){e!==bf&&e.next===null&&(bf===null?yf=bf=e:bf=bf.next=e),Sf=!0,xf||(xf=!0,Mf())}function Ef(e,t){if(!Cf&&Sf){Cf=!0;do for(var n=!1,r=yf;r!==null;){if(!t){if(e!==0){var i=r.pendingLanes;if(i===0)var a=0;else{var o=r.suspendedLanes,s=r.pingedLanes;a=(1<<31-rt(42|e)+1)-1,a&=i&~(o&~s),a=a&201326741?a&201326741|1:a?a|2:0}a!==0&&(n=!0,jf(r,a))}else a=Q,a=dt(r,r===Xu?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||ft(r,a)||(n=!0,jf(r,a))}r=r.next}while(n);Cf=!1}}function Df(){Of()}function Of(){Sf=xf=!1;var e=0;wf!==0&&hp()&&(e=wf);for(var t=Ge(),n=null,r=yf;r!==null;){var i=r.next,a=kf(r,t);a===0?(r.next=null,n===null?yf=i:n.next=i,i===null&&(bf=n)):(n=r,(e!==0||a&3)&&(Sf=!0)),r=i}_d!==0&&_d!==5||Ef(e,!1),wf!==0&&(wf=0)}function kf(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,i=e.expirationTimes,a=e.pendingLanes&-62914561;0s)break;var u=c.transferSize,d=c.initiatorType;u&&ap(d)&&(c=c.responseEnd,o+=u*(c$m){s.length=o;break}f=new Promise(jp.bind(f)),s.push(f)}}}if(0`u`?null:document;function Tm(e,t,n){var r=wm;if(r&&typeof t==`string`&&t){var i=cn(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),ym.has(i)||(ym.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),np(t,`link`,e),Vt(t),r.head.appendChild(t)))}}function Em(e){xm.D(e),Tm(`dns-prefetch`,e,null)}function Dm(e,t){xm.C(e,t),Tm(`preconnect`,e,t)}function Om(e,t,n){xm.L(e,t,n);var r=wm;if(r&&e&&t){var i=`link[rel="preload"][as="`+cn(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+cn(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+cn(n.imageSizes)+`"]`)):i+=`[href="`+cn(e)+`"]`;var a=i;switch(t){case`style`:a=Pm(e);break;case`script`:a=Rm(e)}if(!(vm.has(a)||(e=D({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),vm.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(Fm(a))||t===`script`&&r.querySelector(zm(a))))){var o=r.createElement(`link`);np(o,`link`,e),t===`style`&&(o[Ft]=!0,o.onload=o.onerror=function(){Ht(o)}),Vt(o),r.head.appendChild(o)}}}function km(e,t){xm.m(e,t);var n=wm;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+cn(r)+`"][href="`+cn(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=Rm(e)}if(!vm.has(a)&&(e=D({rel:`modulepreload`,href:e},t),vm.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(zm(a)))return}r=n.createElement(`link`),np(r,`link`,e),Vt(r),n.head.appendChild(r)}}}function Am(e,t,n){xm.S(e,t,n);var r=wm;if(r&&e){var i=Bt(r).hoistableStyles,a=Pm(e);t||=`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(Fm(a)))s.loading=5;else{e=D({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=vm.get(a))&&Hm(e,n);var c=o=r.createElement(`link`);Vt(c),np(c,`link`,e),c._p=new Promise(function(e,t){c.onload=e,c.onerror=t}),c.addEventListener(`load`,function(){s.loading|=1}),c.addEventListener(`error`,function(){s.loading|=2}),s.loading|=4,Vm(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function jm(e,t){xm.X(e,t);var n=wm;if(n&&e){var r=Bt(n).hoistableScripts,i=Rm(e),a=r.get(i);a||(a=n.querySelector(zm(i)),a||(e=D({src:e,async:!0},t),(t=vm.get(i))&&Um(e,t),a=n.createElement(`script`),Vt(a),np(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Mm(e,t){xm.M(e,t);var n=wm;if(n&&e){var r=Bt(n).hoistableScripts,i=Rm(e),a=r.get(i);a||(a=n.querySelector(zm(i)),a||(e=D({src:e,async:!0,type:`module`},t),(t=vm.get(i))&&Um(e,t),a=n.createElement(`script`),Vt(a),np(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Nm(e,t,n,r){var a=(a=De.current)?bm(a):null;if(!a)throw Error(i(446));switch(e){case`meta`:case`title`:return null;case`style`:return typeof n.precedence==`string`&&typeof n.href==`string`?(n=Pm(n.href),t=Bt(a).hoistableStyles,r=t.get(n),r||(r={type:`style`,instance:null,count:0,state:null},t.set(n,r)),r):{type:`void`,instance:null,count:0,state:null};case`link`:if(n.rel===`stylesheet`&&typeof n.href==`string`&&typeof n.precedence==`string`){e=Pm(n.href);var o=Bt(a).hoistableStyles,s=o.get(e);if(s||(a=a.ownerDocument||a,s={type:`stylesheet`,instance:null,count:0,state:{loading:0,preload:null}},o.set(e,s),(o=a.querySelector(Fm(e)))?o._p||(s.instance=o,s.state.loading=5):(o=vm.get(e),o||(o={rel:`preload`,as:`style`,href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},vm.set(e,o)),Lm(a,e,o,s.state))),t&&r===null)throw Error(i(528,``));return s}if(t&&r!==null)throw Error(i(529,``));return null;case`script`:return t=n.async,n=n.src,typeof n==`string`&&t&&typeof t!=`function`&&typeof t!=`symbol`?(n=Rm(n),t=Bt(a).hoistableScripts,r=t.get(n),r||(r={type:`script`,instance:null,count:0,state:null},t.set(n,r)),r):{type:`void`,instance:null,count:0,state:null};default:throw Error(i(444,e))}}function Pm(e){return`href="`+cn(e)+`"`}function Fm(e){return`link[rel="stylesheet"][`+e+`]`}function Im(e){return D({},e,{"data-precedence":e.precedence,precedence:null})}function Lm(e,t,n,r){if(t=e.querySelector(`link[rel="preload"][as="style"][`+t+`]`)){if(!0!==t[Ft]){r.loading=1;return}}else t=e.createElement(`link`),t[Ft]=!0,t.onload=t.onerror=Ht.bind(null,t),np(t,`link`,n),Vt(t),e.head.appendChild(t);r.preload=t,t.addEventListener(`load`,function(){return r.loading|=1}),t.addEventListener(`error`,function(){return r.loading|=2})}function Rm(e){return`[src="`+cn(e)+`"]`}function zm(e){return`script[async]`+e}function Bm(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+cn(n.href)+`"]`);if(r)return t.instance=r,Vt(r),r;var a=D({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),Vt(r),np(r,`style`,a),Vm(r,n.precedence,e),t.instance=r;case`stylesheet`:a=Pm(n.href);var o=e.querySelector(Fm(a));if(o)return t.state.loading|=4,t.instance=o,Vt(o),o;r=Im(n),(a=vm.get(a))&&Hm(r,a),o=(e.ownerDocument||e).createElement(`link`),Vt(o);var s=o;return s._p=new Promise(function(e,t){s.onload=e,s.onerror=t}),np(o,`link`,r),t.state.loading|=4,Vm(o,n.precedence,e),t.instance=o;case`script`:return o=Rm(n.src),(a=e.querySelector(zm(o)))?(t.instance=a,Vt(a),a):(r=n,(a=vm.get(o))&&(r=D({},n),Um(r,a)),e=e.ownerDocument||e,a=e.createElement(`script`),Vt(a),np(a,`link`,r),e.head.appendChild(a),t.instance=a);case`void`:return null;default:throw Error(i(443,t.type))}else t.type===`stylesheet`&&!(t.state.loading&4)&&(r=t.instance,t.state.loading|=4,Vm(r,n.precedence,e));return t.instance}function Vm(e,t,n){for(var r=n.querySelectorAll(`link[rel="stylesheet"][data-precedence],style[data-precedence]`),i=r.length?r[r.length-1]:null,a=i,o=0;o title`):null)}function qm(e,t,n){if(n===1||t.itemProp!=null)return!1;switch(e){case`meta`:case`title`:return!0;case`style`:if(typeof t.precedence!=`string`||typeof t.href!=`string`||t.href===``)break;return!0;case`link`:if(typeof t.rel!=`string`||typeof t.href!=`string`||t.href===``||t.onLoad||t.onError)break;switch(t.rel){case`stylesheet`:return e=t.disabled,typeof t.precedence==`string`&&e==null;default:return!0}case`script`:if(t.async&&typeof t.async!=`function`&&typeof t.async!=`symbol`&&!t.onLoad&&!t.onError&&t.src&&typeof t.src==`string`)return!0}return!1}function Jm(e,t){return e===`img`&&t.src!=null&&t.src!==``&&t.onLoad==null&&t.loading!==`lazy`}function Ym(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function Xm(e){return(e.width||100)*(e.height||100)*(typeof devicePixelRatio==`number`?devicePixelRatio:1)*.25}function Zm(e,t){typeof t.decode==`function`&&(e.imgCount++,t.complete||(e.imgBytes+=Xm(t),e.suspenseyImages.push(t)),e=rh.bind(e),t.decode().then(e,e))}function Qm(e,t,n,r){if(n.type===`stylesheet`&&(typeof r.media!=`string`||!1!==matchMedia(r.media).matches)&&!(n.state.loading&4)){if(n.instance===null){var i=Pm(r.href),a=t.querySelector(Fm(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=nh.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,Vt(a);return}a=t.ownerDocument||t,r=Im(r),(i=vm.get(i))&&Hm(r,i),a=a.createElement(`link`),Vt(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),np(a,`link`,r),n.instance=a}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(n,t),(t=n.state.preload)&&!(n.state.loading&3)&&(e.count++,n=nh.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var $m=0;function eh(e,t){return e.stylesheets&&e.count===0&&ah(e,e.stylesheets),0$m?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function th(e){if(e.count===0&&(e.imgCount===0||!e.waitingForImages)){if(e.stylesheets)ah(e,e.stylesheets);else if(e.unsuspend){var t=e.unsuspend;e.unsuspend=null,t()}}}function nh(){this.count--,th(this)}function rh(){this.imgCount--,th(this)}var ih=null;function ah(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,ih=new Map,t.forEach(oh,e),ih=null,nh.call(e))}function oh(e,t){if(!(t.state.loading&4)){var n=ih.get(e);if(n)var r=n.get(null);else{n=new Map,ih.set(e,n);for(var i=e.querySelectorAll(`link[data-precedence],style[data-precedence]`),a=0;a{function n(){if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<`u`&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE==`function`)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=h()})),_=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,v=/^[\\/]{2}/;function y(e,t){return t+e.replace(/\\/g,`/`)}var b=`popstate`;function x(e){return typeof e==`object`&&!!e&&`pathname`in e&&`search`in e&&`hash`in e&&`state`in e&&`key`in e}function S(e={}){function t(e,t){let n=t.state?.masked,{pathname:r,search:i,hash:a}=n||e.location;return D(``,{pathname:r,search:i,hash:a},t.state&&t.state.usr||null,t.state&&t.state.key||`default`,n?{pathname:e.location.pathname,search:e.location.search,hash:e.location.hash}:void 0)}function n(e,t){return typeof t==`string`?t:O(t)}return k(t,n,null,e)}function C(e,t){if(e===!1||e==null)throw Error(t)}function w(e,t){if(!e){typeof console<`u`&&console.warn(t);try{throw Error(t)}catch{}}}function T(){return Math.random().toString(36).substring(2,10)}function E(e,t){return{usr:e.state,key:e.key,idx:t,masked:e.mask?{pathname:e.pathname,search:e.search,hash:e.hash}:void 0}}function D(e,t,n=null,r,i){return{pathname:typeof e==`string`?e:e.pathname,search:``,hash:``,...typeof t==`string`?ee(t):t,state:n,key:t&&t.key||r||T(),mask:i}}function O({pathname:e=`/`,search:t=``,hash:n=``}){return t&&t!==`?`&&(e+=t.charAt(0)===`?`?t:`?`+t),n&&n!==`#`&&(e+=n.charAt(0)===`#`?n:`#`+n),e}function ee(e){let t={};if(e){let n=e.indexOf(`#`);n>=0&&(t.hash=e.substring(n),e=e.substring(0,n));let r=e.indexOf(`?`);r>=0&&(t.search=e.substring(r),e=e.substring(0,r)),e&&(t.pathname=e)}return t}function k(e,t,n,r={}){let{window:i=document.defaultView,v5Compat:a=!1}=r,o=i.history,s=`POP`,c=null,l=u();l??(l=0,o.replaceState({...o.state,idx:l},``));function u(){return(o.state||{idx:null}).idx}function d(){s=`POP`;let e=u(),t=e==null?null:e-l;l=e,c&&c({action:s,location:h.location,delta:t})}function f(e,t){s=`PUSH`;let r=x(e)?e:D(h.location,e,t);n&&n(r,e),l=u()+1;let d=E(r,l),f=h.createHref(r.mask||r);try{o.pushState(d,``,f)}catch(e){if(e instanceof DOMException&&e.name===`DataCloneError`)throw e;i.location.assign(f)}a&&c&&c({action:s,location:h.location,delta:1})}function p(e,t){s=`REPLACE`;let r=x(e)?e:D(h.location,e,t);n&&n(r,e),l=u();let i=E(r,l),d=h.createHref(r.mask||r);o.replaceState(i,``,d),a&&c&&c({action:s,location:h.location,delta:0})}function m(e){return te(i,e)}let h={get action(){return s},get location(){return e(i,o)},listen(e){if(c)throw Error(`A history only accepts one active listener`);return i.addEventListener(b,d),c=e,()=>{i.removeEventListener(b,d),c=null}},createHref(e){return t(i,e)},createURL:m,encodeLocation(e){let t=m(e);return{pathname:t.pathname,search:t.search,hash:t.hash}},push:f,replace:p,go(e){return o.go(e)}};return h}function te(e,t,n=!1){let r=`http://localhost`;e&&(r=e.location.origin===`null`?e.location.href:e.location.origin),C(r,`No window.location.(origin|href) available to create URL`);let i=typeof t==`string`?t:O(t);return i=i.replace(/ $/,`%20`),!n&&v.test(i)&&(i=r+i),new URL(i,r)}var ne=new URL(`http://localhost`);function re(e){if(e.createURL)return e.createURL(`/`);try{return new URL(e.createHref(`/`),ne)}catch{return ne}}function A(e,t){return e.origin===t.origin&&(e.origin!==`null`||e.protocol===t.protocol&&e.host===t.host)}function ie(e,t){if(e.startsWith(`//`))return!0;let n=t.protocol.toLowerCase();return e.toLowerCase().startsWith(n)?t.host===``||e.slice(n.length).startsWith(`//`):!1}function ae(e){let t=e.replace(/[\t\n\r]/g,``),n=0;for(;t.charCodeAt(n)<=32;)n++;if(t=t.slice(n),!_.test(t))return;let r;try{r=new URL(e,ne)}catch{return}if(!ie(e,r))throw Error(`External navigation is not allowed`)}function oe(e,t,n,r){let i=null;try{i=e==null?null:new URL(e,n)}catch{}let a=new URL(t,n),o=i!=null&&!A(i,n),s=!A(a,n);if(r===`reject`){if(o||s)throw Error(`External navigation is not allowed`)}else if(s&&(i==null||!ie(e,i)||!A(i,a)))throw Error(`External navigation is not allowed`)}var j=c(u(),1),se=class{#e=new Map;constructor(e){if(e)for(let[t,n]of e)this.set(t,n)}get(e){if(this.#e.has(e))return this.#e.get(e);if(e.defaultValue!==void 0)return e.defaultValue;throw Error(`No value found for context`)}set(e,t){this.#e.set(e,t)}},ce=class extends Error{},le=new Set([`lazy`,`caseSensitive`,`path`,`id`,`index`,`children`,`unstable_validateParams`]);function ue(e){return le.has(e)}var de=new Set([`lazy`,`caseSensitive`,`path`,`id`,`index`,`middleware`,`children`,`unstable_validateParams`]);function fe(e){return de.has(e)}function pe(e){return e.index===!0}function me(e){let t={};return e.Component&&Object.assign(t,{element:j.createElement(e.Component),Component:void 0}),e.HydrateFallback&&Object.assign(t,{hydrateFallbackElement:j.createElement(e.HydrateFallback),HydrateFallback:void 0}),e.ErrorBoundary&&Object.assign(t,{errorElement:j.createElement(e.ErrorBoundary),ErrorBoundary:void 0}),t}function he(e,t=me,n=[],r={},i=!1){return e.map((e,a)=>{let o=[...n,String(a)],s=typeof e.id==`string`?e.id:o.join(`-`);if(C(e.index!==!0||!e.children,`Cannot specify children on an index route`),C(i||!r[s],`Found a route id collision on id "${s}". Route id's must be globally unique within Data Router usages`),pe(e)){let n={...e,id:s};return r[s]=ge(n,t(n)),n}{let n={...e,id:s,children:void 0};return r[s]=ge(n,t(n)),e.children&&(n.children=he(e.children,t,o,r,i)),n}})}function ge(e,t){return Object.assign(e,{...t,...typeof t.lazy==`object`&&t.lazy!=null?{lazy:{...e.lazy,...t.lazy}}:{}})}function _e(e,t,n=`/`){return ve(e,t,n,!1)}function ve(e,t,n,r,i){let a=Re((typeof t==`string`?ee(t):t).pathname||`/`,n);if(a==null)return null;let o=i??N(e),s=null,c=Le(a);for(let e=0;s==null&&e{let c={relativePath:s===void 0?e.path||``:s,caseSensitive:e.caseSensitive===!0,childrenIndex:a,route:e};if(c.relativePath.startsWith(`/`)){if(!c.relativePath.startsWith(r)&&o)return;C(c.relativePath.startsWith(r),`Absolute route path "${c.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),c.relativePath=c.relativePath.slice(r.length)}let l=Je([r,c.relativePath]),u=n.concat(c);e.children&&e.children.length>0&&(C(e.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${l}".`),ye(e.children,t,u,l,o)),(e.path!=null||e.index)&&t.push({path:l,score:je(l,e.index),routesMeta:u.map((e,t)=>{let[n,r]=Ie(e.relativePath,e.caseSensitive,t===u.length-1);return{...e,matcher:n,compiledParams:r}})})};return e.forEach((e,t)=>{if(e.path===``||!e.path?.includes(`?`))a(e,t);else for(let n of be(e.path))a(e,t,!0,n)}),t}function be(e){let t=e.split(`/`);if(t.length===0)return[];let[n,...r]=t,i=n.endsWith(`?`),a=n.replace(/\?$/,``);if(r.length===0)return i?[a,``]:[a];let o=be(r.join(`/`)),s=[];return s.push(...o.map(e=>e===``?a:[a,e].join(`/`))),i&&s.push(...o),s.map(t=>e.startsWith(`/`)&&t===``?`/`:t)}function xe(e){e.sort((e,t)=>e.score===t.score?Me(e.routesMeta.map(e=>e.childrenIndex),t.routesMeta.map(e=>e.childrenIndex)):t.score-e.score)}var Se=/^:[\w-]+$/,Ce=/^:[\w-]+/,we=3.5,Te=3,Ee=2,De=1,Oe=10,ke=-2,Ae=e=>e===`*`;function je(e,t){let n=e.split(`/`),r=n.length;return n.some(Ae)&&(r+=ke),t&&(r+=Ee),n.filter(e=>!Ae(e)).reduce((e,t)=>e+(Se.test(t)?Te:Ce.test(t)?we:t===``?De:Oe),r)}function Me(e,t){return e.length===t.length&&e.slice(0,-1).every((e,n)=>e===t[n])?e[e.length-1]-t[t.length-1]:0}function Ne(e,t,n=!1){let{routesMeta:r}=e,i={},a=`/`,o=[];for(let e=0;e{if(t===`*`){let e=s[r]||``;o=Ye(a.slice(0,a.length-e.length),1)}let i=s[r];return e[t]=n&&!i?void 0:(i||``).replace(/%2F/g,`/`),e},{}),pathname:a,pathnameBase:o,pattern:e}}function Ie(e,t=!1,n=!0){w(e===`*`||!e.endsWith(`*`)||e.endsWith(`/*`),`Route path "${e}" will be treated as if it were "${e.replace(/\*$/,`/*`)}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${e.replace(/\*$/,`/*`)}".`);let r=[],i=`^`+e.replace(/\/*\*?$/,``).replace(/^\/*/,`/`).replace(/[\\.*+^${}|()[\]]/g,`\\$&`).replace(/\/:([\w-]+)(\?)?/g,(e,t,n,i,a)=>{if(r.push({paramName:t,isOptional:n!=null}),n){let t=a.charAt(i+e.length);return t&&t!==`/`?`/([^\\/]*)`:`(?:/([^\\/]*))?`}return`/([^\\/]+)`}).replace(/\/((?:[^/?()[\]*^\\]|\\.)+)\?(?=\/|$|\()/g,`(?:/$1)?`);return e.endsWith(`*`)?(r.push({paramName:`*`}),i+=e===`*`||e===`/*`?`(.*)$`:`(?:\\/(.+)|\\/*)$`):n?i+=`\\/*$`:e!==``&&e!==`/`&&(i+=`(?:(?=\\/|$))`),[new RegExp(i,t?void 0:`i`),r]}function Le(e){try{return e.split(`/`).map(e=>decodeURIComponent(e).replace(/\//g,`%2F`)).join(`/`)}catch(t){return w(!1,`The URL path "${e}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${t}).`),e}}function Re(e,t){if(t===`/`)return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith(`/`)?t.length-1:t.length,r=e.charAt(n);return r&&r!==`/`?null:e.slice(n)||`/`}function ze({basename:e,pathname:t}){return t===`/`?e:Je([e,t])}var Be=e=>_.test(e);function Ve(e,t=`/`){let{pathname:n,search:r=``,hash:i=``}=typeof e==`string`?ee(e):e,a;return n?(n=qe(n),a=n.startsWith(`/`)||n.startsWith(`\\`)?He(n.substring(1),`/`):He(n,t)):a=t,{pathname:a,search:Ze(r),hash:Qe(i)}}function He(e,t){let n=Ye(t).split(`/`);return e.split(`/`).forEach(e=>{e===`..`?n.length>1&&n.pop():e!==`.`&&n.push(e)}),n.length>1?n.join(`/`):`/`}function Ue(e,t,n,r){return`Cannot include a '${e}' character in a manually specified \`to.${t}\` field [${JSON.stringify(r)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in and the router will parse it for you.`}function We(e){return e.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function Ge(e){let t=We(e);return t.map((e,n)=>n===t.length-1?e.pathname:e.pathnameBase)}function Ke(e,t,n,r=!1){let i;typeof e==`string`?i=ee(e):(i={...e},C(!i.pathname||!i.pathname.includes(`?`),Ue(`?`,`pathname`,`search`,i)),C(!i.pathname||!i.pathname.includes(`#`),Ue(`#`,`pathname`,`hash`,i)),C(!i.search||!i.search.includes(`#`),Ue(`#`,`search`,`hash`,i)));let a=e===``||i.pathname===``,o=a?`/`:i.pathname,s;if(o==null)s=n;else{let e=t.length-1;if(!r&&o.startsWith(`..`)){let t=o.split(`/`);for(;t[0]===`..`;)t.shift(),--e;i.pathname=t.join(`/`)}s=e>=0?t[e]:`/`}let c=Ve(i,s),l=o&&o!==`/`&&o.endsWith(`/`),u=(a||o===`.`)&&n.endsWith(`/`);return!c.pathname.endsWith(`/`)&&(l||u)&&(c.pathname+=`/`),c}var qe=e=>e.replace(/[\\/]{2,}/g,`/`),Je=e=>qe(e.join(`/`));function Ye(e,t=0){let n=e.length;for(;n>t&&e.charCodeAt(n-1)===47;)n--;return n===e.length?e:e.slice(0,n)}var Xe=e=>Ye(e).replace(/^\/*/,`/`),Ze=e=>!e||e===`?`?``:e.startsWith(`?`)?e:`?`+e,Qe=e=>!e||e===`#`?``:e.startsWith(`#`)?e:`#`+e,$e=[`EvalError`,`RangeError`,`ReferenceError`,`SyntaxError`,`TypeError`,`URIError`],et=class{status;statusText;data;error;internal;constructor(e,t,n,r=!1){this.status=e,this.statusText=t||``,this.internal=r,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}};function tt(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.internal==`boolean`&&`data`in e}function nt(e){return Je(e.map(e=>e.route.path).filter(Boolean))||`/`}function rt(e,t){let n=new URL(typeof e==`string`||e instanceof URL?e:e.url),r=typeof t==`string`?ee(t):t;if(n.pathname=r.pathname||`/`,r.search){let e=new URLSearchParams(r.search),t=e.getAll(`index`);e.delete(`index`);for(let n of t.filter(Boolean))e.append(`index`,n);let i=e.toString();n.search=i?`?${i}`:``}else n.search=``;return n.hash=r.hash||``,n}var it=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;function at(e,t){let n=e;if(typeof n!=`string`||!_.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,i=!1;if(it)try{let e=new URL(window.location.href),r=v.test(n)?new URL(y(n,e.protocol)):new URL(n),a=Re(r.pathname,t);r.origin===e.origin&&a!=null?n=a+r.search+r.hash:i=!0}catch{w(!1,` contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:r,isExternal:i,to:n}}var ot=Symbol(`Uninstrumented`),st=new WeakMap;function ct(e,t){let n={lazy:[],"lazy.loader":[],"lazy.action":[],"lazy.middleware":[],middleware:[],loader:[],action:[]};e.forEach(e=>e({id:t.id,index:t.index,path:t.path,instrument(e){e.lazy!=null&&n.lazy.push(e.lazy),e[`lazy.loader`]!=null&&n[`lazy.loader`].push(e[`lazy.loader`]),e[`lazy.action`]!=null&&n[`lazy.action`].push(e[`lazy.action`]),e[`lazy.middleware`]!=null&&n[`lazy.middleware`].push(e[`lazy.middleware`]),e.middleware!=null&&n.middleware.push(e.middleware),e.loader!=null&&n.loader.push(e.loader),e.action!=null&&n.action.push(e.action)}}));let r={};if(typeof t.lazy==`function`&&n.lazy.length>0){let e=t.lazy;r.lazy=async(...t)=>mt(await ht(n.lazy,void 0,()=>e(...t),gt))}if(typeof t.lazy==`object`){let e=t.lazy;if(typeof e.middleware==`function`&&n[`lazy.middleware`].length>0){let t=e.middleware;r.lazy=Object.assign(r.lazy||{},{middleware:async(...e)=>mt(await ht(n[`lazy.middleware`],void 0,()=>t(...e),gt))})}if(typeof e.loader==`function`&&n[`lazy.loader`].length>0){let t=e.loader;r.lazy=Object.assign(r.lazy||{},{loader:async(...e)=>mt(await ht(n[`lazy.loader`],void 0,()=>t(...e),gt))})}if(typeof e.action==`function`&&n[`lazy.action`].length>0){let t=e.action;r.lazy=Object.assign(r.lazy||{},{action:async(...e)=>mt(await ht(n[`lazy.action`],void 0,()=>t(...e),gt))})}}if(typeof t.loader==`function`&&n.loader.length>0){let e=ut(t.loader),i=async(...t)=>mt(await ht(n.loader,_t(t[0]),()=>e(...t),gt));e.hydrate===!0&&(i.hydrate=!0),dt(i,e),r.loader=i}if(typeof t.action==`function`&&n.action.length>0){let e=ut(t.action),i=async(...t)=>mt(await ht(n.action,_t(t[0]),()=>e(...t),gt));dt(i,e),r.action=i}return t.middleware&&t.middleware.length>0&&n.middleware.length>0&&(r.middleware=t.middleware.map(e=>{let t=ut(e),r=async(...e)=>mt(await ht(n.middleware,_t(e[0]),()=>t(...e),gt));return dt(r,t),r})),r}function lt(e,t){let n={navigate:[],fetch:[]};if(t.forEach(e=>e({instrument(e){e.navigate!=null&&n.navigate.push(e.navigate),e.fetch!=null&&n.fetch.push(e.fetch)}})),n.navigate.length>0){let t=ut(e.navigate),r=async(...r)=>{let[i,a]=r,o,s={to:typeof i==`number`||typeof i==`string`?i:i?O(i):`.`,...vt(e,a??{})};return mt(await ht(n.navigate,s,async()=>{if(typeof i==`number`)return await t(...r);let n=ft(e,e=>{o=e});try{return await t(...r)}finally{n()}},e=>({...gt(e),meta:o})))};dt(r,t),e.navigate=r}if(n.fetch.length>0){let t=ut(e.fetch),r=async(...r)=>{let[i,a,o,s]=r,c;return mt(await ht(n.fetch,{href:o??`.`,fetcherKey:i,...vt(e,s??{})},async()=>{let n=ft(e,e=>{c=e});try{return await t(...r)}finally{n()}},e=>({...gt(e),meta:c})))};dt(r,t),e.fetch=r}return e}function ut(e){return e[ot]??e}function dt(e,t){e[ot]=t}function ft(e,t){return st.set(e,t),()=>{st.get(e)===t&&st.delete(e)}}function pt(e){let t=st.get(e);return st.delete(e),t}function mt(e){if(e.type===`error`)throw e.value;return e.value}async function ht(e,t,n,r,i={result:null,innerResult:null},a=e.length-1){let o=e[a];if(o){let s,c=async()=>(s?console.error(`You cannot call instrumented handlers more than once`):s=ht(e,t,n,r,i,a-1),await s,C(i.innerResult,`Expected an inner result`),i.innerResult);try{await o(c,t)}catch(e){console.error(`An instrumentation function threw an error:`,e)}s||await c(),await s}else{try{i.result={type:`success`,value:await n()}}catch(e){i.result={type:`error`,value:e}}i.innerResult=r(i.result,t)}return i.result||(i.result={type:`error`,value:Error(`No result assigned in instrumentation chain.`)},i.innerResult=r(i.result,t)),i.result}function gt(e){return e.type===`error`&&e.value instanceof Error?{status:`error`,error:e.value}:{status:`success`,error:void 0}}function _t(e){let{request:t,context:n,params:r}=e;return{...e,request:yt(t),params:{...r},context:bt(n)}}function vt(e,t){return{currentUrl:O(e.state.location),...`formMethod`in t?{formMethod:t.formMethod}:{},...`formEncType`in t?{formEncType:t.formEncType}:{},...`formData`in t?{formData:t.formData}:{},...`body`in t?{body:t.body}:{}}}function yt(e){return{method:e.method,url:e.url,headers:{get:(...t)=>e.headers.get(...t)}}}function bt(e){return{get:t=>e.get(t)}}var xt=class{#e=[];#t=[];#n;#r=0;constructor(e){this.#n=e}update(e){this.#e=e,this.#t=N(e),this.#r=this.#t.reduce((e,t)=>e+t.routesMeta.length,0)}get matchCost(){return this.#r}match(e,t=!1){return ve(this.#e,e,this.#n,t,this.#t)}},St=[`POST`,`PUT`,`PATCH`,`DELETE`],Ct=new Set(St),wt=[`GET`,...St],Tt=new Set(wt),Et=new Set([301,302,303,307,308]),Dt=new Set([307,308]),Ot={state:`idle`,location:void 0,matches:void 0,historyAction:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},kt={state:`idle`,data:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},At={state:`unblocked`,proceed:void 0,reset:void 0,location:void 0},jt=`remix-router-transitions`,Mt=Symbol(`ResetLoaderData`);function Nt(e,t){return e.unstable_routePatternMatching?(C(void 0,`You must call unstable_preloadRoutePattern() from "react-router/route-pattern" before enabling future.unstable_routePatternMatching.`),new(void 0)(t)):new xt(t)}var Pt=class{#e;#t;#n;constructor(e,t){this.#e=e,this.#n=t,this.#n.update(e)}get stableRoutes(){return this.#e}get activeRoutes(){return this.#t??this.#e}get hasHMRRoutes(){return this.#t!=null}setRoutes(e){this.#e=e,this.#t||this.#n.update(e)}setHmrRoutes(e){this.#t=e,this.#n.update(e)}commitHmrRoutes(){this.#t&&(this.#e=this.#t,this.#t=void 0,this.#n.update(this.#e))}},Ft=new WeakMap;function It(e){let t=e.window?e.window:typeof window<`u`?window:void 0,n=t!==void 0&&t.document!==void 0&&t.document.createElement!==void 0;C(e.routes.length>0,`You must provide a non-empty routes array to createRouter`);let r=e.hydrationRouteProperties||[],i=e.mapRouteProperties,a=i||(()=>({}));if(e.instrumentations){let t=e.instrumentations;a=e=>({...i?.(e),...ct(t.map(e=>e.route).filter(Boolean),e)})}let o={...e.future},s=e.basename||`/`;s.startsWith(`/`)||(s=`/${s}`);let c=Nt(o,s),l={},u=new Pt(he(e.routes,a,void 0,l),c),d=e.dataStrategy||Qt,f=null,p=new Set,m=null,h=null,g=null,_=e.hydrationData!=null,y=c.match(e.history.location),b=!1,x=null,S,T;if(y==null&&!e.patchRoutesOnNavigation){let t=Cn(404,{pathname:e.history.location.pathname}),{matches:n,route:r}=Sn(u.activeRoutes);S=!0,T=!S,y=n,x={[r.id]:t}}else if(y&&!e.hydrationData&&vt(y,e.history.location.pathname).active&&(y=null),!y){S=!1,T=!S,y=[];let t=vt(null,e.history.location.pathname);t.active&&t.matches&&(b=!0,y=t.matches)}else if(y.some(e=>e.route.lazy))S=!1,T=!S;else if(!y.some(e=>Vt(e.route)))S=!0,T=!S;else{let t=e.hydrationData?e.hydrationData.loaderData:null,n=e.hydrationData?e.hydrationData.errors:null,r=y;if(n){let e=y.findIndex(e=>n[e.route.id]!==void 0);r=r.slice(0,e+1)}T=!1,S=!0,r.forEach(e=>{let r=Ht(e.route,t,n);T||=r.renderFallback,S&&=!r.shouldLoad})}let E,k={historyAction:e.history.action,location:e.history.location,matches:y,initialized:S,renderFallback:T,navigation:Ot,restoreScrollPosition:e.hydrationData==null&&null,preventScrollReset:!1,revalidation:`idle`,loaderData:e.hydrationData&&e.hydrationData.loaderData||{},actionData:e.hydrationData&&e.hydrationData.actionData||null,errors:e.hydrationData&&e.hydrationData.errors||x,fetchers:new Map,blockers:new Map},ne=`POP`,re=0,A,ie=null,ae=!1,j,le=!1,ue=new Map,de=null,fe=!1,pe=!1,me=new Set,ge=new Map,_e=0,ve=-1,N=new Map,ye=new Set,be=new Map,xe=new Map,Se=new Set,Ce=new Map,we,Te=null;function Ee(){if(f=e.history.listen(({action:t,location:n,delta:r})=>{if(we){we(),we=void 0;return}w(Ce.size===0||r!=null,"You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL.");let i=dt({currentLocation:k.location,nextLocation:n,historyAction:t});if(i&&r!=null){let t=new Promise(e=>{we=e});e.history.go(r*-1),ut(i,{state:`blocked`,location:n,proceed(){ut(i,{state:`proceeding`,proceed:void 0,reset:void 0,location:n}),t.then(()=>e.history.go(r))},reset(){let e=new Map(k.blockers);e.set(i,At),ke({blockers:e})}}),ie?.resolve(),ie=null}else return o.unstable_customRouteDiscovery&&(re+=r||0),Pe(t,n)}),n){Jn(t,ue);let e=()=>Yn(t,ue);t.addEventListener(`pagehide`,e),de=()=>t.removeEventListener(`pagehide`,e)}return k.initialized||Pe(`POP`,k.location,{initialHydration:!0}),E}function De(){f&&f(),de&&de(),p.clear(),j&&j.abort(),k.fetchers.forEach((e,t)=>$e(k.fetchers,t)),k.blockers.forEach((e,t)=>st(t))}function Oe(e){return p.add(e),()=>p.delete(e)}function ke(e,t={}){let n=e.errors??null,r=n?Ft.get(n):void 0;r!==void 0&&(n=r),(e.errors!==void 0||e.initialized)&&(k.errors&&Ft.delete(k.errors),e.errors&&Ft.set(e.errors,n)),e.matches&&=e.matches.map(e=>{let t=l[e.route.id],n=e.route;return n.element!==t.element||n.errorElement!==t.errorElement||n.hydrateFallbackElement!==t.hydrateFallbackElement?{...e,route:t}:e}),k={...k,...e};let i=[],a=[];k.fetchers.forEach((e,t)=>{e.state===`idle`&&(Se.has(t)?i.push(t):a.push(t))}),Se.forEach(e=>{!k.fetchers.has(e)&&!ge.has(e)&&i.push(e)}),[...p].forEach(e=>e(k,{deletedFetchers:i,newErrors:n,viewTransitionOpts:t.viewTransitionOpts,flushSync:t.flushSync===!0})),i.forEach(e=>$e(k.fetchers,e)),a.forEach(e=>k.fetchers.delete(e))}function Ae(t,n,{flushSync:r}={}){let i=k.actionData!=null&&k.navigation.formMethod!=null&&Rn(k.navigation.formMethod)&&k.navigation.state===`loading`&&t.state?._isRedirect!==!0,a;a=n.actionData?Object.keys(n.actionData).length>0?n.actionData:null:i?k.actionData:null;let o=n.loaderData?yn(k.loaderData,n.loaderData,n.matches||[],n.errors):k.loaderData,s=k.blockers;s.size>0&&!fe&&(s=new Map(s),s.forEach((e,t)=>s.set(t,At)));let c=!fe&&_t(t,n.matches||k.matches),l=ae===!0||k.navigation.formMethod!=null&&Rn(k.navigation.formMethod)&&t.state?._isRedirect!==!0;u.commitHmrRoutes(),fe||ne===`POP`||(ne===`PUSH`?e.history.push(t,t.state):ne===`REPLACE`&&e.history.replace(t,t.state));let d;if(ne===`POP`&&!fe&&t!==k.location){let e=ue.get(k.location.pathname);e&&e.has(t.pathname)?d={currentLocation:k.location,nextLocation:t}:ue.has(t.pathname)&&(d={currentLocation:t,nextLocation:k.location})}else if(le){let e=ue.get(k.location.pathname);e?e.add(t.pathname):(e=new Set([t.pathname]),ue.set(k.location.pathname,e)),d={currentLocation:k.location,nextLocation:t}}ke({...n,actionData:a,loaderData:o,historyAction:ne,location:t,initialized:!0,renderFallback:!1,navigation:Ot,revalidation:`idle`,restoreScrollPosition:c,preventScrollReset:l,blockers:s},{viewTransitionOpts:d,flushSync:r===!0}),je(),ie?.resolve(),ie=null,Te?.resolve(),Te=null}function je(){re=0,ne=`POP`,ae=!1,le=!1,fe=!1,pe=N.size>0}async function Me(t,n){if(A&&await A,ie?.resolve(),ie=null,typeof t==`number`){ie||=Xn();let n=ie.promise;return e.history.go(t),n}let r=pt(E),{path:i,submission:a,error:o}=zt(!1,Rt(k.location,k.matches,s,t,n?.fromRouteId,n?.relative),n),c;if(n?.mask){let t=typeof n.mask==`string`?ee(n.mask):{...k.location.mask,...n.mask};if(c={pathname:t.pathname??``,search:t.search??``,hash:t.hash??``},v.test(c.pathname))throw Error(`External navigation is not allowed`);c.pathname.startsWith(`\\`)&&(c.pathname=c.pathname.replace(/^\\+/,`/`)),oe(typeof n.mask==`string`?n.mask:O(n.mask),O(c),e.history.createURL(`/`),`reject`)}let l=k.location,u=D(l,i,n&&n.state,void 0,c);u={...u,...e.history.encodeLocation(u)},oe(t==null?e.history.createHref(k.location):typeof t==`string`?t:O(t),e.history.createHref(u.mask||u),e.history.createURL(`/`),`reject`);let d=n&&n.replace!=null?n.replace:void 0,f=`PUSH`,p=k.location.pathname+k.location.search;d===!0?f=`REPLACE`:d===!1||a!=null&&Rn(a.formMethod)&&(a.formAction===p||u.pathname+u.search===p)&&(f=`REPLACE`);let m=n&&`preventScrollReset`in n?n.preventScrollReset===!0:void 0,h=(n&&n.flushSync)===!0,g=dt({currentLocation:l,nextLocation:u,historyAction:f});g?ut(g,{state:`blocked`,location:u,proceed(){ut(g,{state:`proceeding`,proceed:void 0,reset:void 0,location:u}),Me(t,n)},reset(){let e=new Map(k.blockers);e.set(g,At),ke({blockers:e})}}):await Pe(f,u,{submission:a,pendingError:o,preventScrollReset:m,replace:n&&n.replace,enableViewTransition:n&&n.viewTransition,flushSync:h,callSiteDefaultShouldRevalidate:n&&n.defaultShouldRevalidate,instrumentationNavigateMetaReceiver:r})}function Ne(){if(A)return A.then(Ne);Te||=Xn(),Je(),ke({revalidation:`loading`});let e=Te.promise;return k.navigation.state===`submitting`?e:k.navigation.state===`idle`?(Pe(k.historyAction,k.location,{startUninterruptedRevalidation:!0,dataStrategyInitiator:`revalidation`}),e):(Pe(ne||k.historyAction,k.navigation.location,{overrideNavigation:k.navigation,dataStrategyInitiator:`revalidation`,enableViewTransition:le===!0}),e)}async function Pe(t,n,r){A&&await A,j&&j.abort(),j=null,ne=t,fe=(r&&r.startUninterruptedRevalidation)===!0,gt(k.location,k.matches),ae=(r&&r.preventScrollReset)===!0,le=(r&&r.enableViewTransition)===!0;let i=r?.initialHydration&&k.matches&&k.matches.length>0&&!b?k.matches:c.match(n),a=(r&&r.flushSync)===!0;if(i&&k.initialized&&!pe&&En(k.location,n)&&!(r&&r.submission&&Rn(r.submission.formMethod))){Ae(n,{matches:i},{flushSync:a});return}let o=vt(i,n.pathname);if(o.active&&o.matches&&(i=o.matches),r?.instrumentationNavigateMetaReceiver){let t=Vn(e.history,n,i);r.instrumentationNavigateMetaReceiver(t)}if(!i){let{error:e,notFoundMatches:t,route:r}=ft(n.pathname);Ae(n,{matches:t,loaderData:{},errors:{[r.id]:e}},{flushSync:a});return}let s=r&&r.overrideNavigation?{...r.overrideNavigation,matches:i,historyAction:t}:void 0;j=new AbortController;let l=mn(e.history,n,j.signal,r&&r.submission),u=r?.initialHydration?`initialization`:r?.dataStrategyInitiator??`navigation`,d=e.getContext?await e.getContext():new se,f;if(r&&r.pendingError)f=[xn(i).route.id,{type:`error`,error:r.pendingError}];else if(r&&r.submission&&Rn(r.submission.formMethod)){let c=await Ie(l,u,n,r.submission,i,t,d,o.active,r&&r.initialHydration===!0,{replace:r.replace,flushSync:a});if(c.shortCircuited)return;if(c.pendingActionResult){let[e,t]=c.pendingActionResult;if(jn(t)&&tt(t.error)&&t.error.status===404){j=null,Ae(n,{matches:c.matches,loaderData:{},errors:{[e]:t.error}});return}}i=c.matches||i,f=c.pendingActionResult,t=ne,s=Un(n,i,t,r.submission),a=!1,o.active=!1,l=mn(e.history,l.url,l.signal)}let{shortCircuited:p,matches:m,loaderData:h,errors:g,workingFetchers:_}=await Le(l,u,n,i,t,d,o.active,s,r&&r.submission,r&&r.fetcherSubmission,r&&r.replace,r&&r.initialHydration===!0,a,f,r&&r.callSiteDefaultShouldRevalidate);p||(j=null,Ae(n,{matches:m||i,...bn(f),loaderData:h,errors:g,..._?{fetchers:_}:{}}))}function Fe(){let t=Xn();A=t.promise;let n=re,r=ie;ie=null,j?.abort(),j=null,je(),Te?.resolve(),Te=null;let i=new Map(k.blockers);i.forEach((e,t)=>{e.state===`proceeding`&&i.set(t,At)});let a=new Map(k.fetchers),o=it(a);a.forEach((e,t)=>{e.state===`loading`&&!ge.has(t)&&(a.set(t,qn(e.data)),o=!0)}),me.clear(),ke({navigation:Ot,revalidation:`idle`,blockers:i,...o?{fetchers:a}:{}});function s(){A=void 0,r?.resolve(),t.resolve()}return n?(we=s,e.history.go(-n)):s(),t.promise}async function Ie(t,n,i,c,d,f,p,m,h,g={}){if(o.unstable_customRouteDiscovery||Je(),ke({navigation:Wn(i,d,f,c)},{flushSync:g.flushSync===!0}),m){let e=await yt(d,i.pathname,t.signal);if(o.unstable_customRouteDiscovery&&t.signal.aborted||e.type===`aborted`)return{shortCircuited:!0};if(e.type===`cancelled`)return await Fe(),{shortCircuited:!0};if(e.type===`error`){if(e.partialMatches.length===0){let{matches:t,route:n}=Sn(u.activeRoutes);return{matches:t,pendingActionResult:[n.id,{type:`error`,error:e.error}]}}let t=xn(e.partialMatches).route.id;return{matches:e.partialMatches,pendingActionResult:[t,{type:`error`,error:e.error}]}}if(e.matches)d=e.matches;else{let{notFoundMatches:e,error:t,route:n}=ft(i.pathname);return{matches:e,pendingActionResult:[n.id,{type:`error`,error:t}]}}}o.unstable_customRouteDiscovery&&Je();let _,v=Bn(d,i);if(!v.route.action&&!v.route.lazy)_={type:`error`,error:Cn(405,{method:t.method,pathname:i.pathname,routeId:v.route.id})};else{let e=await Ke(t,i,an(a,l,t,i,d,v,h?[]:r,p),p,null,n,f);if(_=e[v.route.id],!_){for(let t of d)if(e[t.route.id]){_=e[t.route.id];break}}if(t.signal.aborted)return{shortCircuited:!0}}if(Mn(_)){let r;return r=g&&g.replace!=null?g.replace:pn(_.response.headers.get(`Location`),new URL(t.url),s,e.history)===k.location.pathname+k.location.search,await Ge(t,_,!0,n,{submission:c,replace:r}),{shortCircuited:!0}}if(jn(_)){let e=xn(d,v.route.id);return(g&&g.replace)!==!0&&(ne=`PUSH`),{matches:d,pendingActionResult:[e.route.id,_,v.route.id]}}return{matches:d,pendingActionResult:[v.route.id,_]}}async function Le(t,n,i,s,d,f,p,m,h,g,_,v,y,b,x){let S=m||Un(i,s,d,h),C=h||g||Hn(S),w=!fe&&!v;if(p){if(w){let e=ze(b);ke({navigation:S,...e===void 0?{}:{actionData:e}},{flushSync:y})}let e=await yt(s,i.pathname,t.signal);if(o.unstable_customRouteDiscovery&&t.signal.aborted||e.type===`aborted`)return{shortCircuited:!0};if(e.type===`cancelled`)return await Fe(),{shortCircuited:!0};if(e.type===`error`){if(e.partialMatches.length===0){let{matches:t,route:n}=Sn(u.activeRoutes);return{matches:t,loaderData:{},errors:{[n.id]:e.error}}}let t=xn(e.partialMatches).route.id;return{matches:e.partialMatches,loaderData:{},errors:{[t]:e.error}}}if(e.matches)s=e.matches,v&&!t.signal.aborted&&ke({matches:s});else{let{error:e,notFoundMatches:t,route:n}=ft(i.pathname);return{matches:t,loaderData:{},errors:{[n.id]:e}}}}let{dsMatches:T,revalidatingFetchers:E}=Bt(t,f,a,l,e.history,k,s,C,i,v?[]:r,v===!0,pe,me,Se,be,ye,c,b,x);if(ve=++_e,!e.dataStrategy&&!T.some(e=>e.shouldLoad)&&!T.some(e=>e.route.middleware&&e.route.middleware.length>0)&&E.length===0){let e=new Map(k.fetchers),t=it(e);return Ae(i,{matches:s,loaderData:{},errors:b&&jn(b[1])?{[b[0]]:b[1].error}:null,...bn(b),...t?{fetchers:e}:{}},{flushSync:y}),{shortCircuited:!0}}if(w){let e={};if(!p){e.navigation=S;let t=ze(b);t!==void 0&&(e.actionData=t)}E.length>0&&(e.fetchers=Ve(E)),ke(e,{flushSync:y})}E.forEach(e=>{nt(e.key),e.controller&&ge.set(e.key,e.controller)});let D=()=>E.forEach(e=>{ge.get(e.key)===e.controller&&nt(e.key)});j&&j.signal.addEventListener(`abort`,D);let{loaderResults:O,fetcherResults:ee}=await qe(T,E,t,i,f,n,d);if(t.signal.aborted)return{shortCircuited:!0};j&&j.signal.removeEventListener(`abort`,D),E.forEach(e=>{ge.get(e.key)===e.controller&&ge.delete(e.key)});let te=wn(O);if(te)return await Ge(t,te.result,!0,n,{replace:_}),{shortCircuited:!0};if(te=wn(ee),te)return ye.add(te.key),await Ge(t,te.result,!0,n,{replace:_}),{shortCircuited:!0};let ne=new Map(k.fetchers),{loaderData:re,errors:A}=vn(k,s,O,b,E,ee,ne);if(v&&k.errors){let e=A??null;A={...k.errors,...A},Ft.set(A,e)}let ie=it(ne),ae=at(ve,ne),oe=ie||ae||E.length>0;return{matches:s,loaderData:re,errors:A,...oe?{workingFetchers:ne}:{}}}function ze(e){if(e&&!jn(e[1]))return{[e[0]]:e[1].data};if(k.actionData)return Object.keys(k.actionData).length===0?null:k.actionData}function Ve(e){let t=new Map(k.fetchers);return e.forEach(e=>{let n=t.get(e.key),r=Gn(void 0,n?n.data:void 0);t.set(e.key,r)}),t}async function He(t,n,r,i){A&&await A,nt(t);let a=(i&&i.flushSync)===!0,o=pt(E),l=Rt(k.location,k.matches,s,r,n,i?.relative);oe(null,l,e.history.createURL(`/`),`reject`);let u=c.match(l),d=vt(u,l);if(d.active&&d.matches&&(u=d.matches),o&&o(Vn(e.history,l,u)),!u){Xe(t,n,Cn(404,{pathname:l}),{flushSync:a});return}let{path:f,submission:p,error:m}=zt(!0,l,i);if(m){Xe(t,n,m,{flushSync:a});return}let h=e.getContext?await e.getContext():new se,g=(i&&i.preventScrollReset)===!0;if(p&&Rn(p.formMethod)){await Ue(t,n,f,u,h,d.active,a,g,p,i&&i.defaultShouldRevalidate);return}let _={routeId:n,path:f,isDiscovering:d.active};be.set(t,_),await We(t,_,u,h,a,g,p)}async function Ue(t,n,i,s,u,d,f,p,m,h){o.unstable_customRouteDiscovery||Je(),be.delete(t);let g=k.fetchers.get(t);Ye(t,Kn(m,g),{flushSync:f});let _=new AbortController;o.unstable_customRouteDiscovery&&ge.set(t,_);let v=mn(e.history,i,_.signal,m);if(d){let e=await yt(s,new URL(v.url).pathname,v.signal,t);if(o.unstable_customRouteDiscovery&&v.signal.aborted||e.type===`aborted`)return;if(e.type===`cancelled`){ge.delete(t),be.delete(t),Ye(t,qn(g?.data),{flushSync:f});return}if(e.type===`error`){Xe(t,n,e.error,{flushSync:f});return}if(e.matches)s=e.matches;else{Xe(t,n,Cn(404,{pathname:i}),{flushSync:f});return}}let y=Bn(s,i);if(!y.route.action&&!y.route.lazy){Xe(t,n,Cn(405,{method:m.formMethod,pathname:i,routeId:n}),{flushSync:f});return}o.unstable_customRouteDiscovery&&Je(),ge.set(t,_);let b=_e,x=an(a,l,v,i,s,y,r,u),S=await Ke(v,i,x,u,t,`fetcher`),w=S[y.route.id];if(!w){for(let e of x)if(S[e.route.id]){w=S[e.route.id];break}}if(v.signal.aborted){ge.get(t)===_&&ge.delete(t);return}if(Se.has(t)){if(jn(w)){Ye(t,qn(void 0));return}Mn(w)&&(pe=!0,w={type:`data`,data:void 0})}else{if(Mn(w)){if(ve>b)pe=!0,w={type:`data`,data:void 0};else return ge.delete(t),ye.add(t),Ye(t,Gn(m)),Ge(v,w,!1,`fetcher`,{fetcherSubmission:m,preventScrollReset:p})}if(jn(w)){Xe(t,n,w.error);return}}pe=!0;let T=k.navigation.location||k.location,E=mn(e.history,T,_.signal),D=k.navigation.state===`idle`?k.matches:c.match(k.navigation.location);C(D,`Didn't find any matches after fetcher action`);let O=++_e;N.set(t,O);let{dsMatches:ee,revalidatingFetchers:te}=Bt(E,u,a,l,e.history,k,D,m,T,r,!1,pe,me,Se,be,ye,c,[y.route.id,w],h),re=Gn(m,w.data),A=new Map(k.fetchers);A.set(t,re),te.filter(e=>e.key!==t).forEach(e=>{let t=e.key,n=A.get(t),r=Gn(void 0,n?n.data:void 0);A.set(t,r),nt(t),e.controller&&ge.set(t,e.controller)}),ke({fetchers:A});let ie=()=>te.forEach(e=>{ge.get(e.key)===e.controller&&nt(e.key)});_.signal.addEventListener(`abort`,ie);let{loaderResults:ae,fetcherResults:oe}=await qe(ee,te,E,T,u,`fetcher`);if(_.signal.aborted){N.get(t)===O&&N.delete(t);return}_.signal.removeEventListener(`abort`,ie),N.delete(t),ge.delete(t),te.forEach(e=>{ge.get(e.key)===e.controller&&ge.delete(e.key)});let se=k.fetchers.has(t),ce=e=>{if(!se)return e;let n=new Map(e.fetchers);return n.set(t,qn(w.data)),{...e,fetchers:n}},le=wn(ae);if(le)return k=ce(k),Ge(E,le.result,!1,`fetcher`,{preventScrollReset:p});if(le=wn(oe),le)return ye.add(le.key),k=ce(k),Ge(E,le.result,!1,`fetcher`,{preventScrollReset:p});let ue=new Map(k.fetchers);se&&ue.set(t,qn(w.data));let{loaderData:de,errors:fe}=vn(k,D,ae,void 0,te,oe,ue);at(O,ue),k.navigation.state===`loading`&&O>ve?(C(ne,`Expected pending action`),j&&j.abort(),it(ue),Ae(k.navigation.location,{matches:D,loaderData:de,errors:fe,fetchers:ue})):(ke({errors:fe,loaderData:yn(k.loaderData,de,D,fe),fetchers:ue}),pe=N.size>0)}async function We(t,n,i,s,c,u,d){let{routeId:f,path:p}=n,m=k.fetchers.get(t);Ye(t,Gn(d,m?m.data:void 0),{flushSync:c});let h=new AbortController;o.unstable_customRouteDiscovery&&ge.set(t,h);let g=mn(e.history,p,h.signal);if(n.isDiscovering){let e=await yt(i,new URL(g.url).pathname,g.signal,t);if(o.unstable_customRouteDiscovery&&g.signal.aborted||e.type===`aborted`)return;if(e.type===`cancelled`){ge.delete(t),be.delete(t),Ye(t,qn(m?.data),{flushSync:c});return}if(e.type===`error`){Xe(t,f,e.error,{flushSync:c});return}if(e.matches)i=e.matches,n.isDiscovering=!1;else{Xe(t,f,Cn(404,{pathname:p}),{flushSync:c});return}}let _=Bn(i,p);ge.set(t,h);let v=_e,y=await Ke(g,p,an(a,l,g,p,i,_,r,s),s,t,`fetcher`),b=y[_.route.id];if(!b){for(let e of i)if(y[e.route.id]){b=y[e.route.id];break}}if(ge.get(t)===h&&ge.delete(t),!g.signal.aborted){if(Se.has(t))Ye(t,qn(void 0));else{if(Mn(b)){if(ve>v){Ye(t,qn(void 0));return}ye.add(t),await Ge(g,b,!1,`fetcher`,{preventScrollReset:u});return}jn(b)?Xe(t,f,b.error):Ye(t,qn(b.data))}}}async function Ge(r,i,a,o,{submission:c,fetcherSubmission:l,preventScrollReset:u,replace:d}={}){a||(ie?.resolve(),ie=null),i.response.headers.has(`X-Remix-Revalidate`)&&(pe=!0);let f=i.response.headers.get(`Location`);C(f,`Expected a Location header on the redirect Response`);let p=f,m=new URL(r.url);f=pn(f,m,s,e.history),oe(p,f,m,`allow-explicit`);let h=D(k.location,f,{_isRedirect:!0});if(n){let e=!1;if(i.response.headers.has(`X-Remix-Reload-Document`))e=!0;else if(Be(f)){let n=te(t,f,!0);e=n.origin!==t.location.origin||Re(n.pathname,s)==null}if(e){d?t.location.replace(f):t.location.assign(f);return}}j=null;let g=d===!0||i.response.headers.has(`X-Remix-Replace`)?`REPLACE`:`PUSH`,{formMethod:_,formAction:v,formEncType:y}=k.navigation;!c&&!l&&_&&v&&y&&(c=Hn(k.navigation));let b=c||l;Dt.has(i.response.status)&&b&&Rn(b.formMethod)?await Pe(g,h,{submission:{...b,formAction:f},preventScrollReset:u||ae,enableViewTransition:a?le:void 0,dataStrategyInitiator:o}):await Pe(g,h,{overrideNavigation:Un(h,[],g,c),fetcherSubmission:l,preventScrollReset:u||ae,enableViewTransition:a?le:void 0,dataStrategyInitiator:o})}async function Ke(e,t,n,r,i,a,o=null){let c,l={};try{c=await on(d,e,t,n,i,a,r,!1,o)}catch(e){return n.filter(e=>e.shouldLoad).forEach(t=>{l[t.route.id]={type:`error`,error:e}}),l}if(e.signal.aborted)return l;if(!Rn(e.method))for(let e of n){if(c[e.route.id]?.type===`error`)break;c.hasOwnProperty(e.route.id)||k.loaderData.hasOwnProperty(e.route.id)||k.errors&&k.errors.hasOwnProperty(e.route.id)||!e.shouldCallHandler()||(c[e.route.id]={type:`error`,result:Error(`No result returned from dataStrategy for route ${e.route.id}`)})}for(let[t,r]of Object.entries(c))if(An(r)){let i=r.result;l[t]={type:`redirect`,response:un(i,e,t,n,s)}}else l[t]=await ln(r);return l}async function qe(e,t,n,r,i,a,o=null){let s=Ke(n,r,e,i,null,a,o),c=Promise.all(t.map(async e=>{if(e.matches&&e.match&&e.request&&e.controller){let t=(await Ke(e.request,e.path,e.matches,i,e.key,a,o))[e.match.route.id];return{[e.key]:t}}return Promise.resolve({[e.key]:{type:`error`,error:Cn(404,{pathname:e.path})}})}));return{loaderResults:await s,fetcherResults:(await c).reduce((e,t)=>Object.assign(e,t),{})}}function Je(){pe=!0,be.forEach((e,t)=>{o.unstable_customRouteDiscovery&&e.isDiscovering||(ge.has(t)&&me.add(t),nt(t))})}function Ye(e,t,n={}){let r=new Map(k.fetchers);r.set(e,t),ke({fetchers:r},{flushSync:(n&&n.flushSync)===!0})}function Xe(e,t,n,r={}){let i=xn(k.matches,t),a=new Map(k.fetchers);$e(a,e),ke({errors:{[i.route.id]:n},fetchers:a},{flushSync:(r&&r.flushSync)===!0})}function Ze(e){return xe.set(e,(xe.get(e)||0)+1),Se.has(e)&&Se.delete(e),k.fetchers.get(e)||kt}function Qe(e,t){nt(e,t?.reason),be.delete(e),me.delete(e),Ye(e,qn(null))}function $e(e,t){let n=k.fetchers.get(t);ge.has(t)&&!(n&&n.state===`loading`&&N.has(t))&&nt(t),be.delete(t),N.delete(t),ye.delete(t),Se.delete(t),me.delete(t),e.delete(t)}function et(e){let t=(xe.get(e)||0)-1;t<=0?(xe.delete(e),Se.add(e)):xe.set(e,t),ke({fetchers:new Map(k.fetchers)})}function nt(e,t){let n=ge.get(e);n&&(n.abort(t),ge.delete(e))}function rt(e,t){for(let n of e){let e=t.get(n);C(e,`Expected fetcher: ${n}`);let r=qn(e.data);t.set(n,r)}}function it(e){let t=[],n=!1;for(let r of ye){let i=e.get(r);C(i,`Expected fetcher: ${r}`),i.state===`loading`&&(ye.delete(r),t.push(r),n=!0)}return rt(t,e),n}function at(e,t){let n=[];for(let[r,i]of N)if(i0}function ot(e,t){let n=k.blockers.get(e)||At;return Ce.get(e)!==t&&Ce.set(e,t),n}function st(e){k.blockers.delete(e),Ce.delete(e)}function ut(e,t){let n=k.blockers.get(e)||At;C(n.state===`unblocked`&&t.state===`blocked`||n.state===`blocked`&&t.state===`blocked`||n.state===`blocked`&&t.state===`proceeding`||n.state===`blocked`&&t.state===`unblocked`||n.state===`proceeding`&&t.state===`unblocked`,`Invalid blocker state transition: ${n.state} -> ${t.state}`);let r=new Map(k.blockers);r.set(e,t),ke({blockers:r})}function dt({currentLocation:e,nextLocation:t,historyAction:n}){if(Ce.size===0)return;Ce.size>1&&w(!1,`A router only supports one blocker at a time`);let r=Array.from(Ce.entries()),[i,a]=r[r.length-1],o=k.blockers.get(i);if(!(o&&o.state===`proceeding`)&&a({currentLocation:e,nextLocation:t,historyAction:n}))return i}function ft(e){let t=Cn(404,{pathname:e}),n=u.activeRoutes,{matches:r,route:i}=Sn(n);return{notFoundMatches:r,route:i,error:t}}function mt(e,t,n){if(m=e,g=t,h=n||null,!_&&k.navigation===Ot){_=!0;let e=_t(k.location,k.matches);e!=null&&ke({restoreScrollPosition:e})}return()=>{m=null,g=null,h=null}}function ht(e,t){return h&&h(e,t.map(e=>M(e,k.loaderData)))||e.key}function gt(e,t){if(m&&g){let n=ht(e,t);m[n]=g()}}function _t(e,t){if(m){let n=ht(e,t),r=m[n];if(typeof r==`number`)return r}return null}function vt(t,n){if(e.patchRoutesOnNavigation){if(!t)return{active:!0,matches:c.match(n,!0)||[]};if(Object.keys(t[0].params).length>0)return{active:!0,matches:c.match(n,!0)}}return{active:!1,matches:null}}async function yt(t,n,r,i){if(!e.patchRoutesOnNavigation)return{type:`success`,matches:t};let s=t;for(;;){let t=l;try{await e.patchRoutesOnNavigation({signal:r,path:n,matches:s,fetcherKey:i,patch:(e,n)=>{r.aborted||Kt(e,n,u,t,a,!1)}})}catch(e){if(o.unstable_customRouteDiscovery){if(r.aborted)return{type:`aborted`};if(e instanceof ce)return{type:`cancelled`}}return{type:`error`,error:e,partialMatches:s}}if(r.aborted)return{type:`aborted`};let d=c.match(n),f=null;if(d&&(Object.keys(d[0].params).length===0||(f=c.match(n,!0),!(f&&s.lengthe.route.id===t[n].route.id)}function xt(e){l={},u.setHmrRoutes(he(e,a,void 0,l))}function St(e,t,n=!1){Kt(e,t,u,l,a,n),u.hasHMRRoutes||ke({})}return E={get basename(){return s},get future(){return o},get state(){return k},get routes(){return u.stableRoutes},match(e){return c.match(e)},get manifest(){return l},get window(){return t},initialize:Ee,subscribe:Oe,enableScrollRestoration:mt,navigate:Me,fetch:He,revalidate:Ne,createHref:t=>e.history.createHref(t),createURL:t=>e.history.createURL(t),encodeLocation:t=>e.history.encodeLocation(t),getFetcher:Ze,resetFetcher:Qe,deleteFetcher:et,dispose:De,getBlocker:ot,deleteBlocker:st,patchRoutes:St,_internalFetchControllers:ge,_internalSetRoutes:xt,_internalSetStateDoNotUseOrYouWillBreakYourApp(e){ke(e)}},e.instrumentations&&(E=lt(E,e.instrumentations.map(e=>e.router).filter(Boolean))),E}function Lt(e){return e!=null&&(`formData`in e&&e.formData!=null||`body`in e&&e.body!==void 0)}function Rt(e,t,n,r,i,a){let o,s;if(i){o=[];for(let e of t)if(o.push(e),e.route.id===i){s=e;break}}else o=t,s=t[t.length-1];let c=Ke(r||`.`,Ge(o),Re(e.pathname,n)||e.pathname,a===`path`);if(r??(c.search=e.search,c.hash=e.hash),(r==null||r===``||r===`.`)&&s){let e=zn(c.search);if(s.route.index&&!e)c.search=c.search?c.search.replace(/^\?/,`?index&`):`?index`;else if(!s.route.index&&e){let e=new URLSearchParams(c.search),t=e.getAll(`index`);e.delete(`index`),t.filter(e=>e).forEach(t=>e.append(`index`,t));let n=e.toString();c.search=n?`?${n}`:``}}return n!==`/`&&(c.pathname=ze({basename:n,pathname:c.pathname})),O(c)}function zt(e,t,n){if(!n||!Lt(n))return{path:t};if(n.formMethod&&!Ln(n.formMethod))return{path:t,error:Cn(405,{method:n.formMethod})};let r=()=>({path:t,error:Cn(400,{type:`invalid-body`})}),i=(n.formMethod||`get`).toUpperCase(),a=Tn(t);if(n.body!==void 0){if(n.formEncType===`text/plain`){if(!Rn(i))return r();let e=typeof n.body==`string`?n.body:n.body instanceof FormData||n.body instanceof URLSearchParams?Array.from(n.body.entries()).reduce((e,[t,n])=>`${e}${t}=${n}\n`,``):String(n.body);return{path:t,submission:{formMethod:i,formAction:a,formEncType:n.formEncType,formData:void 0,json:void 0,text:e}}}if(n.formEncType===`application/json`){if(!Rn(i))return r();try{let e=typeof n.body==`string`?JSON.parse(n.body):n.body;return{path:t,submission:{formMethod:i,formAction:a,formEncType:n.formEncType,formData:void 0,json:e,text:void 0}}}catch{return r()}}}C(typeof FormData==`function`,`FormData is not available in this environment`);let o,s;if(n.formData)o=hn(n.formData),s=n.formData;else if(n.body instanceof FormData)o=hn(n.body),s=n.body;else if(n.body instanceof URLSearchParams)o=n.body,s=gn(o);else if(n.body==null)o=new URLSearchParams,s=new FormData;else try{o=new URLSearchParams(n.body),s=gn(o)}catch{return r()}let c={formMethod:i,formAction:a,formEncType:n&&n.formEncType||`application/x-www-form-urlencoded`,formData:s,json:void 0,text:void 0};if(Rn(c.formMethod))return{path:t,submission:c};let l=ee(t);return e&&l.search&&zn(l.search)&&o.append(`index`,``),l.search=`?${o}`,{path:O(l),submission:c}}function Bt(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v){let y=_?jn(_[1])?_[1].error:_[1].data:void 0,b=i.createURL(a.location),x=i.createURL(c),S;if(u&&a.errors){let e=Object.keys(a.errors)[0];S=o.findIndex(t=>t.route.id===e)}else if(_&&jn(_[1])){let e=_[0];S=o.findIndex(t=>t.route.id===e)-1}let C=_?_[1].statusCode:void 0,w=C&&C>=400,T={currentUrl:b,currentParams:a.matches[0]?.params||{},nextUrl:x,nextParams:o[0].params,...s,actionResult:y,actionStatus:C},E=nt(o),D=o.map((i,o)=>{let{route:s}=i,f=null;if(S!=null&&o>S)f=!1;else if(s.lazy)f=!0;else if(!Vt(s))f=!1;else if(u){let{shouldLoad:e}=Ht(s,a.loaderData,a.errors);f=e}else Ut(a.loaderData,a.matches[o],i)&&(f=!0);if(f!==null)return rn(n,r,e,c,E,i,l,t,f);let p=!1;typeof v==`boolean`?p=v:w?p=!1:d||b.pathname+b.search===x.pathname+x.search?p=!0:b.search===x.search?Wt(a.matches[o],i)&&(p=!0):p=!0;let m={...T,defaultShouldRevalidate:p};return rn(n,r,e,c,E,i,l,t,Gt(i,m),m,v)}),O=[];return m.forEach((e,s)=>{if(u||!o.some(t=>t.route.id===e.routeId)||p.has(s)||e.isDiscovering)return;let c=a.fetchers.get(s),m=c&&c.state!==`idle`&&c.data===void 0,_=g.match(e.path);if(!_){O.push({key:s,routeId:e.routeId,path:e.path,matches:null,match:null,request:null,controller:null});return}if(h.has(s))return;let y=Bn(_,e.path),b=new AbortController,x=mn(i,e.path,b.signal),S=null;if(f.has(s))f.delete(s),S=an(n,r,x,e.path,_,y,l,t);else if(m)d&&(S=an(n,r,x,e.path,_,y,l,t));else{let i;i=typeof v==`boolean`?v:!w&&d;let a={...T,defaultShouldRevalidate:i};Gt(y,a)&&(S=an(n,r,x,e.path,_,y,l,t,a))}S&&O.push({key:s,routeId:e.routeId,path:e.path,matches:S,match:y,request:x,controller:b})}),{dsMatches:D,revalidatingFetchers:O}}function Vt(e){return e.loader!=null||e.middleware!=null&&e.middleware.length>0}function Ht(e,t,n){if(e.lazy)return{shouldLoad:!0,renderFallback:!0};if(!Vt(e))return{shouldLoad:!1,renderFallback:!1};let r=t!=null&&e.id in t,i=n!=null&&n[e.id]!==void 0;if(!r&&i)return{shouldLoad:!1,renderFallback:!1};if(typeof e.loader==`function`&&e.loader.hydrate===!0)return{shouldLoad:!0,renderFallback:!r};let a=!r&&!i;return{shouldLoad:a,renderFallback:a}}function Ut(e,t,n){let r=!t||n.route.id!==t.route.id,i=!e.hasOwnProperty(n.route.id);return r||i}function Wt(e,t){let n=e.route.path;return e.pathname!==t.pathname||n!=null&&n.endsWith(`*`)&&e.params[`*`]!==t.params[`*`]}function Gt(e,t){if(e.route.shouldRevalidate){let n=e.route.shouldRevalidate(t);if(typeof n==`boolean`)return n}return t.defaultShouldRevalidate}function Kt(e,t,n,r,i,a){let o;if(e){let t=r[e];C(t,`No route found to patch children into: routeId = ${e}`),t.children||=[],o=t.children}else o=n.activeRoutes;let s=[],c=[];if(t.forEach(e=>{let t=o.find(t=>qt(e,t));t?c.push({existingRoute:t,newRoute:e}):s.push(e)}),s.length>0){let t=he(s,i,[e||`_`,`patch`,String(o?.length||`0`)],r);o.push(...t)}if(a&&c.length>0)for(let e=0;et.children?.some(t=>qt(e,t)))??!1}var Jt=new WeakMap,Yt=({key:e,route:t,manifest:n,mapRouteProperties:r})=>{let i=n[t.id];if(C(i,`No route found in manifest`),!i.lazy||typeof i.lazy!=`object`)return;let a=i.lazy[e];if(!a)return;let o=Jt.get(i);o||(o={},Jt.set(i,o));let s=o[e];if(s)return s;let c=(async()=>{let t=ue(e),n=i[e]!==void 0;if(t)w(!t,`Route property `+e+` is not a supported lazy route property. This property will be ignored.`),o[e]=Promise.resolve();else if(n)w(!1,`Route "${i.id}" has a static property "${e}" defined. The lazy property will be ignored.`);else{let t=await a();t!=null&&(Object.assign(i,{[e]:t}),Object.assign(i,r(i)))}typeof i.lazy==`object`&&(i.lazy[e]=void 0,Object.values(i.lazy).every(e=>e===void 0)&&(i.lazy=void 0))})();return o[e]=c,c.catch(()=>{o[e]===c&&delete o[e]}),c},Xt=new WeakMap;function P(e,t,n,r,i){let a=n[e.id];if(C(a,`No route found in manifest`),!e.lazy)return{lazyRoutePromise:void 0,lazyHandlerPromise:void 0};if(typeof e.lazy==`function`){let t=Xt.get(a);if(t)return{lazyRoutePromise:t,lazyHandlerPromise:t};let n=(async()=>{C(typeof e.lazy==`function`,`No lazy route function found`);let t=await e.lazy(),n={};for(let e in t){let r=t[e];if(r===void 0)continue;let i=fe(e),o=a[e]!==void 0;i?w(!i,`Route property `+e+` is not a supported property to be returned from a lazy route function. This property will be ignored.`):o?w(!o,`Route "${a.id}" has a static property "${e}" defined but its lazy function is also returning a value for this property. The lazy route property "${e}" will be ignored.`):n[e]=r}Object.assign(a,n),Object.assign(a,{...r(a),lazy:void 0})})();return Xt.set(a,n),n.catch(()=>{Xt.get(a)===n&&Xt.delete(a)}),{lazyRoutePromise:n,lazyHandlerPromise:n}}let o=Object.keys(e.lazy),s=[],c;for(let a of o){if(i&&i.includes(a))continue;let o=Yt({key:a,route:e,manifest:n,mapRouteProperties:r});o&&(s.push(o),a===t&&(c=o))}let l=s.length>0?Promise.all(s).then(()=>{}):void 0;return l?.catch(()=>{}),c?.catch(()=>{}),{lazyRoutePromise:l,lazyHandlerPromise:c}}async function Zt(e){let t=e.matches.filter(e=>e.shouldLoad),n={};return(await Promise.all(t.map(e=>e.resolve()))).forEach((e,r)=>{n[t[r].route.id]=e}),n}async function Qt(e){return e.matches.some(e=>e.route.middleware)?$t(e,()=>Zt(e)):Zt(e)}function $t(e,t){return en(e,t,e=>{if(In(e))throw e;return e},On,n);async function n(t,n,r){if(r)return Object.assign(r.value,{[n]:{type:`error`,result:t}});{let{matches:r}=e,i=Math.min(Math.max(r.findIndex(e=>e.route.id===n),0),Math.max(r.findIndex(e=>e.shouldCallHandler()),0)),a=r[i].route.id;for(let e of r.slice(0,i+1))try{await e._lazyPromises?.route}catch{a=e.route.id;break}return{[xn(r,a).route.id]:{type:`error`,result:t}}}}}async function en(e,t,n,r,i){let{matches:a,...o}=e;return await tn(o,a.flatMap(e=>e.route.middleware?e.route.middleware.map(t=>[e.route.id,t]):[]),t,n,r,i)}async function tn(e,t,n,r,i,a,o=0){let{request:s}=e;if(s.signal.aborted)throw s.signal.reason??Error(`Request aborted: ${s.method} ${s.url}`);let c=t[o];if(!c)return await n();let[l,u]=c,d,f=async()=>{if(d)throw Error("You may only call `next()` once per middleware");try{return d={value:await tn(e,t,n,r,i,a,o+1)},d.value}catch(e){return d={value:await a(e,l,d)},d.value}};try{let t=await u(e,f),n=t==null?void 0:r(t);return i(n)?n:d?n??d.value:(d={value:await f()},d.value)}catch(e){return await a(e,l,d)}}function nn(e,t,n,r,i){let a=Yt({key:`middleware`,route:r.route,manifest:t,mapRouteProperties:e}),o=P(r.route,Rn(n.method)?`action`:`loader`,t,e,i);return{middleware:a,route:o.lazyRoutePromise,handler:o.lazyHandlerPromise}}function rn(e,t,n,r,i,a,o,s,c,l=null,u){let d=!1,f=nn(e,t,n,a,o);return{...a,_lazyPromises:f,shouldLoad:c,shouldRevalidateArgs:l,shouldCallHandler(e){return d=!0,l?typeof u==`boolean`?Gt(a,{...l,defaultShouldRevalidate:u}):typeof e==`boolean`?Gt(a,{...l,defaultShouldRevalidate:e}):Gt(a,l):c},resolve(e){let{lazy:t,loader:o,middleware:l}=a.route,u=d||c||e&&!Rn(n.method)&&(t||o),p=l&&l.length>0&&!o&&!t;return u&&(Rn(n.method)||!p)?sn({request:n,path:r,pattern:i,match:a,lazyHandlerPromise:f?.handler,lazyRoutePromise:f?.route,handlerOverride:e,scopedContext:s}):Promise.resolve({type:`data`,result:void 0})}}}function an(e,t,n,r,i,a,o,s,c=null){return i.map(l=>l.route.id===a.route.id?rn(e,t,n,r,nt(i),l,o,s,!0,c):{...l,shouldLoad:!1,shouldRevalidateArgs:c,shouldCallHandler:()=>!1,_lazyPromises:nn(e,t,n,l,o),resolve:()=>Promise.resolve({type:`data`,result:void 0})})}async function on(e,t,n,r,i,a,o,s,c=null){r.some(e=>e._lazyPromises?.middleware)&&await Promise.all(r.map(e=>e._lazyPromises?.middleware));let l={request:t,url:rt(t,n),pattern:nt(r),params:r[0].params,context:o,matches:r,unstable_initiator:a,unstable_navigationType:a===`navigation`?c:null},u=s?()=>{throw Error("You cannot call `runClientMiddleware()` from a static handler `dataStrategy`. Middleware is run outside of `dataStrategy` during SSR in order to bubble up the Response. You can enable middleware via the `respond` API in `query`/`queryRoute`")}:e=>{let t=l;return $t(t,()=>e({...t,fetcherKey:i,runClientMiddleware:()=>{throw Error("Cannot call `runClientMiddleware()` from within an `runClientMiddleware` handler")}}))},d=await e({...l,fetcherKey:i,runClientMiddleware:u});try{await Promise.all(r.flatMap(e=>[e._lazyPromises?.handler,e._lazyPromises?.route]))}catch{}return d}async function sn({request:e,path:t,pattern:n,match:r,lazyHandlerPromise:i,lazyRoutePromise:a,handlerOverride:o,scopedContext:s}){let c,l,u=Rn(e.method),d=u?`action`:`loader`,f=i=>{let a,c=new Promise((e,t)=>a=t);l=()=>a(),e.signal.addEventListener(`abort`,l);let u=a=>typeof i==`function`?i({request:e,url:rt(e,t),pattern:n,params:r.params,context:s},...a===void 0?[]:[a]):Promise.reject(Error(`You cannot call the handler for a route which defines a boolean "${d}" [routeId: ${r.route.id}]`)),f=(async()=>{try{return{type:`data`,result:await(o?o(e=>u(e)):u())}}catch(e){return{type:`error`,result:e}}})();return Promise.race([f,c])};try{let t=u?r.route.action:r.route.loader;if(i||a){if(t){let e,[n]=await Promise.all([f(t).catch(t=>{e=t}),i,a]);if(e!==void 0)throw e;c=n}else{await i;let t=u?r.route.action:r.route.loader;if(t)[c]=await Promise.all([f(t),a]);else if(d===`action`){let t=new URL(e.url),n=t.pathname+t.search;throw Cn(405,{method:e.method,pathname:n,routeId:r.route.id})}else return await a,{type:`data`,result:void 0}}}else if(t)c=await f(t);else{let t=new URL(e.url);throw Cn(404,{pathname:t.pathname+t.search})}}catch(e){return{type:`error`,result:e}}finally{l&&e.signal.removeEventListener(`abort`,l)}return c}async function cn(e){let t=e.headers.get(`Content-Type`);return t&&/\bapplication\/json\b/.test(t)?e.body==null?null:e.json():e.text()}async function ln(e){let{result:t,type:n}=e;if(Pn(t)){let e;try{e=await cn(t)}catch(e){return{type:`error`,error:e}}return n===`error`?{type:`error`,error:new et(t.status,t.statusText,e),statusCode:t.status,headers:t.headers}:{type:`data`,data:e,statusCode:t.status,headers:t.headers}}return n===`error`?Nn(t)?t.data instanceof Error?{type:`error`,error:t.data,statusCode:t.init?.status,headers:t.init?.headers?new Headers(t.init.headers):void 0}:{type:`error`,error:Dn(t),statusCode:tt(t)?t.status:void 0,headers:t.init?.headers?new Headers(t.init.headers):void 0}:{type:`error`,error:t,statusCode:tt(t)?t.status:void 0}:Nn(t)?{type:`data`,data:t.data,statusCode:t.init?.status,headers:t.init?.headers?new Headers(t.init.headers):void 0}:{type:`data`,data:t}}function un(e,t,n,r,i){let a=e.headers.get(`Location`);if(C(a,`Redirects returned/thrown from loaders/actions must have a Location header`),oe(a,a,new URL(t.url),`allow-explicit`),!Be(a)){let o=r.slice(0,r.findIndex(e=>e.route.id===n)+1);a=Rt(new URL(t.url),o,i,a),e.headers.set(`Location`,a)}return e}var dn=[`about:`,`blob:`,`chrome:`,`chrome-untrusted:`,`content:`,`data:`,`devtools:`,`file:`,`filesystem:`,`javascript:`];function fn(e){try{return dn.includes(new URL(e).protocol)}catch{return!1}}function pn(e,t,n,r){if(Be(e)){let r=e,i=v.test(r)?new URL(y(r,t.protocol)):new URL(r);if(fn(i.toString()))throw Error(`Invalid redirect location`);let a=Re(i.pathname,n)!=null;if(i.origin===t.origin&&a)return qe(i.pathname)+i.search+i.hash}try{if(fn(r.createURL(e).toString()))throw Error(`Invalid redirect location`)}catch{}return e}function mn(e,t,n,r){let i=e.createURL(Tn(t)).toString(),a={signal:n};if(r&&Rn(r.formMethod)){let{formMethod:e,formEncType:t}=r;a.method=e.toUpperCase(),t===`application/json`?(a.headers=new Headers({"Content-Type":t}),a.body=JSON.stringify(r.json)):a.body=t===`text/plain`?r.text:t===`application/x-www-form-urlencoded`&&r.formData?hn(r.formData):r.formData}return new Request(i,a)}function hn(e){let t=new URLSearchParams;for(let[n,r]of e.entries())t.append(n,typeof r==`string`?r:r.name);return t}function gn(e){let t=new FormData;for(let[n,r]of e.entries())t.append(n,r);return t}function _n(e,t,n,r=!1,i=!1){let a={},o=null,s,c=!1,l={},u=n&&jn(n[1])?n[1].error:void 0;return e.forEach(n=>{if(!(n.route.id in t))return;let d=n.route.id,f=t[d];if(C(!Mn(f),`Cannot handle redirect results in processLoaderData`),jn(f)){let t=f.error;if(u!==void 0&&(t=u,u=void 0),o||={},i)o[d]=t;else{let n=xn(e,d);o[n.route.id]??(o[n.route.id]=t)}r||(a[d]=Mt),c||(c=!0,s=tt(f.error)?f.error.status:500),f.headers&&(l[d]=f.headers)}else a[d]=f.data,f.statusCode&&f.statusCode!==200&&!c&&(s=f.statusCode),f.headers&&(l[d]=f.headers)}),u!==void 0&&n&&(o={[n[0]]:u},n[2]&&(a[n[2]]=void 0)),{loaderData:a,errors:o,statusCode:s||200,loaderHeaders:l}}function vn(e,t,n,r,i,a,o){let{loaderData:s,errors:c}=_n(t,n,r);return i.filter(e=>!e.matches||e.matches.some(e=>e.shouldLoad)).forEach(t=>{let{key:n,routeId:r,controller:i}=t;if(i&&i.signal.aborted)return;let s=a[n];if(C(s,`Did not find corresponding fetcher result`),jn(s)){let t=xn(e.matches,r);c&&c[t.route.id]||(c={...c,[t.route.id]:s.error}),o.delete(n)}else if(Mn(s))C(!1,`Unhandled fetcher revalidation redirect`);else{let e=qn(s.data);o.set(n,e)}}),{loaderData:s,errors:c}}function yn(e,t,n,r){let i=Object.entries(t).filter(([,e])=>e!==Mt).reduce((e,[t,n])=>(e[t]=n,e),{}),a=0;for(let o of n){let n=o.route.id;if(!t.hasOwnProperty(n)&&e.hasOwnProperty(n)&&o.route.loader&&(i[n]=e[n],a++),r&&r.hasOwnProperty(n))break}return Object.keys(t).length===0&&a===Object.keys(e).length?e:i}function bn(e){return e?jn(e[1])?{actionData:{}}:{actionData:{[e[0]]:e[1].data}}:{}}function xn(e,t){return(t?e.slice(0,e.findIndex(e=>e.route.id===t)+1):[...e]).reverse().find(e=>e.route.ErrorBoundary!=null||e.route.errorElement!=null)||e[0]}function Sn(e){let t=e.length===1?e[0]:e.find(e=>e.index||!e.path||e.path===`/`)||{id:`__shim-error-route__`};return{matches:[{params:{},pathname:``,pathnameBase:``,route:t}],route:t}}function Cn(e,{pathname:t,routeId:n,method:r,type:i,message:a}={}){let o=`Unknown Server Error`,s=`Unknown @remix-run/router error`;return e===400?(o=`Bad Request`,r&&t&&n?s=`You made a ${r} request to "${t}" but did not provide a \`loader\` for route "${n}", so there is no way to handle the request.`:i===`invalid-body`&&(s=`Unable to encode submission body`)):e===403?(o=`Forbidden`,s=`Route "${n}" does not match URL "${t}"`):e===404?(o=`Not Found`,s=`No route matches URL "${t}"`):e===405&&(o=`Method Not Allowed`,r&&t&&n?s=`You made a ${r.toUpperCase()} request to "${t}" but did not provide an \`action\` for route "${n}", so there is no way to handle the request.`:r&&(s=`Invalid request method "${r.toUpperCase()}"`)),new et(e||500,o,Error(s),!0)}function wn(e){let t=Object.entries(e);for(let e=t.length-1;e>=0;e--){let[n,r]=t[e];if(Mn(r))return{key:n,result:r}}}function Tn(e){return O({...typeof e==`string`?ee(e):e,hash:``})}function En(e,t){return e.pathname!==t.pathname||e.search!==t.search?!1:e.hash===``?t.hash!==``:e.hash===t.hash||t.hash!==``}function Dn(e){return new et(e.init?.status??500,e.init?.statusText??`Internal Server Error`,e.data)}function On(e){return typeof e==`object`&&!!e&&Object.entries(e).every(([e,t])=>typeof e==`string`&&kn(t))}function kn(e){return typeof e==`object`&&!!e&&`type`in e&&`result`in e&&(e.type===`data`||e.type===`error`)}function An(e){return Pn(e.result)&&Et.has(e.result.status)}function jn(e){return e.type===`error`}function Mn(e){return(e&&e.type)===`redirect`}function Nn(e){return typeof e==`object`&&!!e&&`type`in e&&`data`in e&&`init`in e&&e.type===`DataWithResponseInit`}function Pn(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.headers==`object`&&e.body!==void 0}function Fn(e){return Et.has(e)}function In(e){return Pn(e)&&Fn(e.status)&&e.headers.has(`Location`)}function Ln(e){return Tt.has(e.toUpperCase())}function Rn(e){return Ct.has(e.toUpperCase())}function zn(e){return new URLSearchParams(e).getAll(`index`).some(e=>e===``)}function Bn(e,t){let n=typeof t==`string`?ee(t).search:t.search;if(e[e.length-1].route.index&&zn(n||``))return e[e.length-1];let r=We(e);return r[r.length-1]}function Vn(e,t,n){return{url:rt(e.createURL(t),t),pattern:n?nt(n):``,params:n?.[0]?.params?{...n[0].params}:{}}}function Hn(e){let{formMethod:t,formAction:n,formEncType:r,text:i,formData:a,json:o}=e;if(t&&n&&r){if(i!=null)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:void 0,text:i};if(a!=null)return{formMethod:t,formAction:n,formEncType:r,formData:a,json:void 0,text:void 0};if(o!==void 0)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:o,text:void 0}}}function Un(e,t,n,r){return r?{state:`loading`,location:e,matches:t,historyAction:n,formMethod:r.formMethod,formAction:r.formAction,formEncType:r.formEncType,formData:r.formData,json:r.json,text:r.text}:{state:`loading`,location:e,matches:t,historyAction:n,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0}}function Wn(e,t,n,r){return{state:`submitting`,location:e,matches:t,historyAction:n,formMethod:r.formMethod,formAction:r.formAction,formEncType:r.formEncType,formData:r.formData,json:r.json,text:r.text}}function Gn(e,t){return e?{state:`loading`,formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t}:{state:`loading`,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:t}}function Kn(e,t){return{state:`submitting`,formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t?t.data:void 0}}function qn(e){return{state:`idle`,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:e}}function Jn(e,t){try{let n=e.sessionStorage.getItem(jt);if(n){let e=JSON.parse(n);for(let[n,r]of Object.entries(e||{}))r&&Array.isArray(r)&&t.set(n,new Set(r||[]))}}catch{}}function Yn(e,t){if(t.size>0){let n={};for(let[e,r]of t)n[e]=[...r];try{e.sessionStorage.setItem(jt,JSON.stringify(n))}catch(e){w(!1,`Failed to save applied view transitions in sessionStorage (${e}).`)}}}function Xn(){let e,t,n=new Promise((r,i)=>{e=async e=>{r(e);try{await n}catch{}},t=async e=>{i(e);try{await n}catch{}}});return{promise:n,resolve:e,reject:t}}var Zn=j.createContext(null);Zn.displayName=`DataRouter`;var Qn=j.createContext(null);Qn.displayName=`DataRouterState`;var $n=j.createContext(null);$n.displayName=`DataRouterData`;var er=j.createContext(null);er.displayName=`DataRouterNavigation`;var tr=j.createContext(!1);function nr(){return j.useContext(tr)}var rr=j.createContext({isTransitioning:!1});rr.displayName=`ViewTransition`;var ir=j.createContext(null);ir.displayName=`Fetchers`;var ar=j.createContext(null);ar.displayName=`Await`;var or=j.createContext(null);or.displayName=`Navigation`;var sr=j.createContext(null);sr.displayName=`Location`;var cr=j.createContext({outlet:null,matches:[],isDataRoute:!1});cr.displayName=`Route`;var lr=j.createContext(!1);lr.displayName=`IsDataRoute`;var ur=j.createContext(void 0);ur.displayName=`RouteId`;var dr=j.createContext(null);dr.displayName=`RouteError`;var fr=`REACT_ROUTER_ERROR`,pr=`REDIRECT`,mr=`ROUTE_ERROR_RESPONSE`;function hr(e){if(e.startsWith(`${fr}:${pr}:{`))try{let t=JSON.parse(e.slice(28));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`&&typeof t.location==`string`&&typeof t.reloadDocument==`boolean`&&typeof t.replace==`boolean`)return t}catch{}}function gr(e){if(e.startsWith(`${fr}:${mr}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`)return new et(t.status,t.statusText,t.data)}catch{}}function _r(e,{relative:t}={}){C(vr(),`useHref() may be used only in the context of a component.`);let{basename:n,navigator:r}=j.useContext(or),{hash:i,pathname:a,search:o}=Tr(e,{relative:t}),s=a;return n!==`/`&&(s=a===`/`?n:Je([n,a])),r.createHref({pathname:s,search:o,hash:i})}function vr(){return j.useContext(sr)!=null}function yr(){return C(vr(),`useLocation() may be used only in the context of a component.`),j.useContext(sr).location}function br(e){C(vr(),`useMatch() may be used only in the context of a component.`);let{pathname:t}=yr();return j.useMemo(()=>Pe(e,Le(t)),[t,e])}var xr=`You should call navigate() in a React.useEffect(), not when your component is first rendered.`;function Sr(){return j.useContext(lr)?Ur():Cr()}function Cr(){C(vr(),`useNavigate() may be used only in the context of a component.`);let e=j.useContext(Zn),{basename:t,navigator:n}=j.useContext(or),{matches:r}=j.useContext(cr),{pathname:i}=yr(),a=JSON.stringify(Ge(r)),o=j.useRef(!1);return j.useLayoutEffect(()=>{o.current=!0}),j.useCallback((r,s={})=>{if(w(o.current,xr),!o.current)return;if(typeof r==`number`){n.go(r);return}let c=Ke(r,JSON.parse(a),i,s.relative===`path`);e==null&&t!==`/`&&(c.pathname=c.pathname===`/`?t:Je([t,c.pathname])),oe(typeof r==`string`?r:O(r),n.createHref(c),re(n),`reject`),(s.replace?n.replace:n.push)(c,s.state,s)},[t,n,a,i,e])}j.createContext(null);function wr(){let{matches:e}=j.useContext(cr);return e[e.length-1]?.params??{}}function Tr(e,{relative:t}={}){let{matches:n}=j.useContext(cr),{pathname:r}=yr(),i=JSON.stringify(Ge(n));return j.useMemo(()=>Ke(e,JSON.parse(i),r,t===`path`),[e,i,r,t])}function Er(e,t){return Dr(e,t)}function Dr(e,t,n){C(vr(),`useRoutes() may be used only in the context of a component.`);let{navigator:r}=j.useContext(or),{matches:i}=j.useContext(cr),a=i[i.length-1],o=a?a.params:{};a&&a.pathname;let s=a?a.pathnameBase:`/`;a&&a.route;let c=yr(),l;if(t){let e=typeof t==`string`?ee(t):t;C(s===`/`||e.pathname?.startsWith(s),`When overriding the location using \`\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${s}" but pathname "${e.pathname}" was given in the \`location\` prop.`),l=e}else l=c;let u=l.pathname||`/`,d=u;if(s!==`/`){let e=s.replace(/^\//,``).split(`/`);d=`/`+u.replace(/^\//,``).split(`/`).slice(e.length).join(`/`)}let f;f=n?n.state.matches.length?n.state.matches.map(e=>Object.assign(e,{route:n.manifest[e.route.id]||e.route})):n.router.match(n.state.location):_e(e,{pathname:d});let p=Pr(f&&f.map(e=>Object.assign({},e,{params:Object.assign({},o,e.params),pathname:Je([s,r.encodeLocation?r.encodeLocation(e.pathname.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathname]),pathnameBase:e.pathnameBase===`/`?s:Je([s,r.encodeLocation?r.encodeLocation(e.pathnameBase.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathnameBase])})),i,n);return t&&p?j.createElement(sr.Provider,{value:{location:{pathname:`/`,search:``,hash:``,state:null,key:`default`,mask:void 0,...l},navigationType:`POP`}},p):p}function Or(){let e=Br(),t=tt(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null;return j.createElement(j.Fragment,null,j.createElement(`h2`,null,`Unexpected Application Error!`),j.createElement(`h3`,{style:{fontStyle:`italic`}},t),n?j.createElement(`pre`,{style:{padding:`0.5rem`,backgroundColor:`rgba(200,200,200, 0.5)`}},n):null,null)}var kr=j.createElement(Or,null),Ar=class extends j.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static contextType=tr;static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!==`idle`&&e.revalidation===`idle`?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error===void 0?t.error:e.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error(`React Router caught the following error during render`,e)}render(){let e=this.state.error;if(this.context&&typeof e==`object`&&e&&`digest`in e&&typeof e.digest==`string`){let t=gr(e.digest);t&&(e=t)}let t=e===void 0?this.props.children:j.createElement(cr.Provider,{value:this.props.routeContext},j.createElement(lr.Provider,{value:this.props.routeContext.isDataRoute},j.createElement(ur.Provider,{value:this.props.routeContext.matches[this.props.routeContext.matches.length-1]?.route.id},j.createElement(dr.Provider,{value:e,children:this.props.component}))));return this.context?j.createElement(Mr,{error:e},t):t}},jr=new WeakMap;function Mr({children:e,error:t}){let{basename:n,navigator:r}=j.useContext(or);if(typeof t==`object`&&t&&`digest`in t&&typeof t.digest==`string`){let e=hr(t.digest);if(e){let i=jr.get(t);if(i)throw i;let a=at(e.location,n),o=a.absoluteURL||a.to;if(oe(e.location,o,re(r),`allow-explicit`),fn(o))throw Error(`Invalid redirect location`);if(it&&!jr.get(t)){if(a.isExternal||e.reloadDocument)window.location.href=o;else{let n=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(a.to,{replace:e.replace}));throw jr.set(t,n),n}}return j.createElement(`meta`,{httpEquiv:`refresh`,content:`0;url=${o}`})}}return e}function Nr({routeContext:e,match:t,children:n}){let r=j.useContext(Zn);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),j.createElement(cr.Provider,{value:e},j.createElement(lr.Provider,{value:e.isDataRoute},j.createElement(ur.Provider,{value:t.route.id},n)))}function Pr(e,t=[],n){let r=n?.state;if(e==null){if(!r)return null;if(r.errors)e=r.matches;else if(t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let i=e,a=r?.errors;if(a!=null){let e=i.findIndex(e=>e.route.id&&a?.[e.route.id]!==void 0);C(e>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(a).join(`,`)}`),i=i.slice(0,Math.min(i.length,e+1))}let o=!1,s=-1;if(n&&r){o=r.renderFallback;for(let e=0;e=0?i.slice(0,s+1):[i[0]];break}}}}let c=n?.onError,l=r&&c?(e,t)=>{c(e,{location:r.location,params:r.matches?.[0]?.params??{},pattern:nt(r.matches),errorInfo:t})}:void 0;return i.reduceRight((e,n,c)=>{let u,d=!1,f=null,p=null;r&&(u=a&&n.route.id?a[n.route.id]:void 0,f=n.route.errorElement||kr,o&&(s<0&&c===0?(Gr(`route-fallback`,!1,"No `HydrateFallback` element provided to render during initial hydration"),d=!0,p=null):s===c&&(d=!0,p=n.route.hydrateFallbackElement||null)));let m=t.concat(i.slice(0,c+1)),h=()=>{let t;return t=u?f:d?p:n.route.Component?j.createElement(n.route.Component,null):n.route.element?n.route.element:e,j.createElement(Nr,{match:n,routeContext:{outlet:e,matches:m,isDataRoute:r!=null},children:t})};return r&&(n.route.ErrorBoundary||n.route.errorElement||c===0)?j.createElement(Ar,{location:r.location,revalidation:r.revalidation,component:f,error:u,children:h(),routeContext:{outlet:null,matches:m,isDataRoute:!0},onError:l}):h()},null)}function Fr(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Ir(e){let t=j.useContext(Zn);return C(t,Fr(e)),t}function Lr(e){let t=j.useContext(Qn);return C(t,Fr(e)),t}function Rr(e){let t=j.useContext($n);return C(t,Fr(e)),t}function zr(e){let t=j.useContext(ur);return C(t,`${e} can only be used on routes that contain a unique "id"`),t}function Br(){let e=j.useContext(dr),t=Rr(`useRouteError`),n=zr(`useRouteError`);return e===void 0?t.errors?.[n]:e}var Vr=0;function Hr(e){let{router:t,basename:n}=Ir(`useBlocker`),r=Lr(`useBlocker`),[i,a]=j.useState(``),o=j.useCallback(t=>{if(typeof e!=`function`)return!!e;if(n===`/`)return e(t);let{currentLocation:r,nextLocation:i,historyAction:a}=t;return e({currentLocation:{...r,pathname:Re(r.pathname,n)||r.pathname},nextLocation:{...i,pathname:Re(i.pathname,n)||i.pathname},historyAction:a})},[n,e]),s=j.useRef(``);return j.useEffect(()=>{let e=String(++Vr);return s.current=e,a(e),()=>{s.current=``,t.deleteBlocker(e)}},[t]),j.useEffect(()=>{i!==``&&i===s.current&&t.getBlocker(i,o)},[t,i,o]),i&&r.blockers.has(i)?r.blockers.get(i):At}function Ur(){let{router:e}=Ir(`useNavigate`),t=zr(`useNavigate`),n=j.useRef(!1);return j.useLayoutEffect(()=>{n.current=!0}),j.useCallback(async(r,i={})=>{w(n.current,xr),n.current&&(typeof r==`number`?await e.navigate(r):await e.navigate(r,{fromRouteId:t,...i}))},[e,t])}var Wr={};function Gr(e,t,n){!t&&!Wr[e]&&(Wr[e]=!0,w(!1,n))}function Kr(e,t){if(e===!1||e==null)throw Error(t)}function qr(e,t,n){let r=typeof e==`string`?new URL(e,n??(typeof window>`u`?`server://singlefetch/`:window.location.origin)):new URL(e);return n&&r.origin!==n&&(r=new URL(r.pathname+r.search+r.hash,n)),r.pathname.endsWith(`/`)?r.pathname=`${r.pathname}_.${t}`:r.pathname=`${r.pathname}.${t}`,r}async function Jr(e,t){if(e.id in t)return t[e.id];try{let n=await import(e.module);return t[e.id]=n,n}catch(t){return console.error(`Error loading route module \`${e.module}\`, reloading page...`),console.error(t),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function Yr(e){return e!=null&&typeof e.page==`string`}function Xr(e){return e==null?!1:e.href==null?e.rel===`preload`&&typeof e.imageSrcSet==`string`&&typeof e.imageSizes==`string`:typeof e.rel==`string`&&typeof e.href==`string`}async function Zr(e,t,n){return ni((await Promise.all(e.map(async e=>{let r=t.routes[e.route.id];if(r){let e=await Jr(r,n);return e.links?e.links():[]}return[]}))).flat(1).filter(Xr).filter(e=>e.rel===`stylesheet`||e.rel===`preload`).map(e=>e.rel===`stylesheet`?{...e,rel:`prefetch`,as:`style`}:{...e,rel:`prefetch`}))}function Qr(e,t,n,r,i,a){let o=(e,t)=>!n[t]||e.route.id!==n[t].route.id,s=(e,t)=>n[t].pathname!==e.pathname||n[t].route.path?.endsWith(`*`)&&n[t].params[`*`]!==e.params[`*`];return a===`assets`?t.filter((e,t)=>o(e,t)||s(e,t)):a===`data`?t.filter((t,a)=>{let c=r.routes[t.route.id];if(!c||!c.hasLoader)return!1;if(o(t,a)||s(t,a))return!0;if(t.route.shouldRevalidate){let r=t.route.shouldRevalidate({currentUrl:new URL(i.pathname+i.search+i.hash,window.origin),currentParams:n[0]?.params||{},nextUrl:new URL(e,window.origin),nextParams:t.params,defaultShouldRevalidate:!0});if(typeof r==`boolean`)return r}return!0}):[]}function $r(e,t,{includeHydrateFallback:n}={}){return ei(e.map(e=>{let r=t.routes[e.route.id];if(!r)return[];let i=[r.module];return r.clientActionModule&&(i=i.concat(r.clientActionModule)),r.clientLoaderModule&&(i=i.concat(r.clientLoaderModule)),n&&r.hydrateFallbackModule&&(i=i.concat(r.hydrateFallbackModule)),r.imports&&(i=i.concat(r.imports)),i}).flat(1))}function ei(e){return[...new Set(e)]}function ti(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function ni(e,t){let n=new Set,r=new Set(t);return e.reduce((e,i)=>{if(t&&!Yr(i)&&i.as===`script`&&i.href&&r.has(i.href))return e;let a=JSON.stringify(ti(i));return n.has(a)||(n.add(a),e.push({key:a,link:i})),e},[])}var ri={};function ii(e,t){!e&&!ri[t]&&(ri[t]=!0,console.warn(t))}var ai=j.createContext(void 0);ai.displayName=`FrameworkContext`;function oi(){let e=j.useContext(ai);return Kr(e,`You must render this element inside a element`),e}function si(e,t){let n=j.useContext(ai),[r,i]=j.useState(!1),[a,o]=j.useState(!1),{onFocus:s,onBlur:c,onMouseEnter:l,onMouseLeave:u,onTouchStart:d}=t,f=j.useRef(null);j.useEffect(()=>{if(e===`render`&&o(!0),e===`viewport`){let e=new IntersectionObserver(e=>{e.forEach(e=>{o(e.isIntersecting)})},{threshold:.5});return f.current&&e.observe(f.current),()=>{e.disconnect()}}},[e]),j.useEffect(()=>{if(r){let e=setTimeout(()=>{o(!0)},100);return()=>{clearTimeout(e)}}},[r]);let p=()=>{i(!0)},m=()=>{i(!1),o(!1)};return n?e===`intent`?[a,f,{onFocus:ci(s,p),onBlur:ci(c,m),onMouseEnter:ci(l,p),onMouseLeave:ci(u,m),onTouchStart:ci(d,p)}]:[a,f,{}]:[!1,f,{}]}function ci(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function li({page:e,...t}){let n=nr(),{nonce:r}=oi(),{router:i}=Ir(`PrefetchPageLinks`),a=j.useMemo(()=>i.match(e),[i,i.routes,e]);return a?(t.nonce==null&&r&&(t={...t,nonce:r}),n?j.createElement(di,{page:e,matches:a,...t}):j.createElement(fi,{page:e,matches:a,...t})):null}function ui(e){let{manifest:t,routeModules:n}=oi(),[r,i]=j.useState([]);return j.useEffect(()=>{let r=!1;return Zr(e,t,n).then(e=>{r||i(e)}),()=>{r=!0}},[e,t,n]),r}function di({page:e,matches:t,...n}){let r=yr(),{unstable_apiServerOrigin:i}=oi(),a=j.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=qr(e,`rsc`,i),a=!1,o=[];for(let e of t)typeof e.route.shouldRevalidate==`function`?a=!0:o.push(e.route.id);return a&&o.length>0&&n.searchParams.set(`_routes`,o.join(`,`)),[i?n.toString():n.pathname+n.search]},[e,r,t,i]);return j.createElement(j.Fragment,null,a.map(e=>j.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})))}function fi({page:e,matches:t,...n}){let r=yr(),{manifest:i,routeModules:a,unstable_apiServerOrigin:o}=oi(),{matches:s}=Lr(`PrefetchPageLinks`),{loaderData:c}=Rr(`PrefetchPageLinks`),l=j.useMemo(()=>Qr(e,t,s,i,r,`data`),[e,t,s,i,r]),u=j.useMemo(()=>Qr(e,t,s,i,r,`assets`),[e,t,s,i,r]),d=j.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=new Set,s=!1;if(t.forEach(e=>{let t=i.routes[e.route.id];t&&t.hasLoader&&(!l.some(t=>t.route.id===e.route.id)&&e.route.id in c&&a[e.route.id]?.shouldRevalidate||t.hasClientLoader?s=!0:n.add(e.route.id))}),n.size===0)return[];let u=qr(e,`data`,o);return s&&n.size>0&&u.searchParams.set(`_routes`,t.filter(e=>n.has(e.route.id)).map(e=>e.route.id).join(`,`)),[o?u.toString():u.pathname+u.search]},[c,r,i,l,t,e,a,o]),f=j.useMemo(()=>$r(u,i),[u,i]),p=ui(u);return j.createElement(j.Fragment,null,d.map(e=>j.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})),f.map(e=>j.createElement(`link`,{key:e,rel:`modulepreload`,href:e,...n})),p.map(({key:e,link:t})=>j.createElement(`link`,{key:e,nonce:n.nonce,...t,crossOrigin:t.crossOrigin??n.crossOrigin})))}function pi(...e){return t=>{e.forEach(e=>{typeof e==`function`?e(t):e!=null&&(e.current=t)})}}var mi=[`HydrateFallback`,`hydrateFallbackElement`],hi=class{status=`pending`;promise;resolve;reject;constructor(){this.promise=new Promise((e,t)=>{this.resolve=t=>{this.status===`pending`&&(this.status=`resolved`,e(t))},this.reject=e=>{this.status===`pending`&&(this.status=`rejected`,t(e))}})}};function gi(e,t){e.ready.catch(e=>{if(!(t.visibilityState===`hidden`||typeof e==`object`&&e&&`name`in e&&e.name===`AbortError`))throw e})}function _i({router:e,flushSync:t,onError:n,useTransitions:r}){r=nr()||r;let[i,a]=j.useState(e.state),[o,s]=(0,j.useOptimistic)(i),c=j.useRef(o),[l,u]=j.useState(),[d,f]=j.useState({isTransitioning:!1}),[p,m]=j.useState(),[h,g]=j.useState(),[_,v]=j.useState(),y=j.useRef(new Map),b=j.useRef(new WeakSet),x=j.useCallback((i,{deletedFetchers:o,newErrors:l,flushSync:d,viewTransitionOpts:_})=>{c.current=i,l&&i.errors&&Ft.has(i.errors)&&(b.current.has(i.errors)?l=null:b.current.add(i.errors)),l&&n&&Object.values(l).forEach(e=>n(e,{location:i.location,params:i.matches[0]?.params??{},pattern:nt(i.matches)})),i.fetchers.forEach((e,t)=>{e.data!==void 0&&y.current.set(t,e.data)}),o.forEach(e=>y.current.delete(e)),ii(d===!1||t!=null,'You provided the `flushSync` option to a router update, but you are not using the `` from `react-router/dom` so `ReactDOM.flushSync()` is unavailable. Please update your app to `import { RouterProvider } from "react-router/dom"` and ensure you have `react-dom` installed as a dependency to use the `flushSync` option.');let x=e.window!=null&&e.window.document!=null&&typeof e.window.document.startViewTransition==`function`;if(ii(_==null||x,"You provided the `viewTransition` option to a router update, but you do not appear to be running in a DOM environment as `window.startViewTransition` is not available."),!_||!x)t&&d?t(()=>a(i)):r===!1?a(i):j.startTransition(()=>{r===!0&&s(e=>vi(e,i)),a(i)});else if(t&&d){t(()=>{h&&(p?.resolve(),h.skipTransition()),f({isTransitioning:!0,flushSync:!0,currentLocation:_.currentLocation,nextLocation:_.nextLocation})});let n=e.window.document.startViewTransition(()=>{t(()=>a(i))});gi(n,e.window.document),n.finished.finally(()=>{t(()=>{m(void 0),g(void 0),u(void 0),f({isTransitioning:!1})})}),t(()=>g(n))}else h?(p?.resolve(),h.skipTransition(),v({state:i,currentLocation:_.currentLocation,nextLocation:_.nextLocation})):(u(i),f({isTransitioning:!0,flushSync:!1,currentLocation:_.currentLocation,nextLocation:_.nextLocation}))},[e.window,t,h,p,r,s,n]);j.useLayoutEffect(()=>e.subscribe(x),[e,x]),j.useLayoutEffect(()=>{let t=e.state.errors,n=t?Ft.get(t):null;(c.current!==e.state||t&&n&&!b.current.has(t))&&x(e.state,{deletedFetchers:[],flushSync:!1,newErrors:n??null})},[e,x]),j.useEffect(()=>{d.isTransitioning&&!d.flushSync&&m(new hi)},[d]),j.useEffect(()=>{if(p&&l&&e.window){let t=l,n=p.promise,i=e.window.document.startViewTransition(async()=>{r===!1?a(t):j.startTransition(()=>{r===!0&&s(e=>vi(e,t)),a(t)}),await n});gi(i,e.window.document),i.finished.finally(()=>{m(void 0),g(void 0),u(void 0),f({isTransitioning:!1})}),g(i)}},[l,p,e.window,r,s]),j.useEffect(()=>{p&&l&&o.location.key===l.location.key&&p.resolve()},[p,h,o.location,l]),j.useEffect(()=>{!d.isTransitioning&&_&&(u(_.state),f({isTransitioning:!0,flushSync:!1,currentLocation:_.currentLocation,nextLocation:_.nextLocation}),v(void 0))},[d.isTransitioning,_]);let S=j.useMemo(()=>({createHref:e.createHref,createURL:e.createURL,encodeLocation:e.encodeLocation,go:t=>e.navigate(t),push:(t,n,r)=>e.navigate(t,{state:n,preventScrollReset:r?.preventScrollReset}),replace:(t,n,r)=>e.navigate(t,{replace:!0,state:n,preventScrollReset:r?.preventScrollReset})}),[e]),C=e.basename||`/`,w=j.useMemo(()=>({router:e,navigator:S,static:!1,basename:C,onError:n}),[e,S,C,n]),T=j.useMemo(()=>({historyAction:o.historyAction,location:o.location,matches:o.matches,initialized:o.initialized,renderFallback:o.renderFallback,restoreScrollPosition:o.restoreScrollPosition,preventScrollReset:o.preventScrollReset,blockers:o.blockers}),[o.historyAction,o.location,o.matches,o.initialized,o.renderFallback,o.restoreScrollPosition,o.preventScrollReset,o.blockers]),E=j.useMemo(()=>({navigation:o.navigation,revalidation:o.revalidation}),[o.navigation,o.revalidation]),D=j.useMemo(()=>({loaderData:o.loaderData,actionData:o.actionData,errors:o.errors}),[o.loaderData,o.actionData,o.errors]),O=j.useMemo(()=>({fetchers:o.fetchers,fetcherData:y.current}),[o.fetchers]);return j.createElement(j.Fragment,null,j.createElement(Zn.Provider,{value:w},j.createElement(Qn.Provider,{value:T},j.createElement(er.Provider,{value:E},j.createElement($n.Provider,{value:D},j.createElement(ir.Provider,{value:O},j.createElement(rr.Provider,{value:d},j.createElement(Si,{basename:C,location:o.location,navigationType:o.historyAction,navigator:S,useTransitions:r},j.createElement(yi,{routes:e.routes,manifest:e.manifest,state:o,isStatic:!1,onError:n})))))))),null)}function vi(e,t){return{...e,navigation:t.navigation.state===`idle`?e.navigation:t.navigation,revalidation:t.revalidation===`idle`?e.revalidation:t.revalidation,actionData:t.navigation.state===`submitting`?e.actionData:t.actionData,fetchers:t.fetchers}}var yi=j.memo(bi);function bi({routes:e,manifest:t,state:n,isStatic:r,onError:i}){let a=j.useContext(Zn);C(a,`You must render this element inside a element`);let o=j.useContext(ai)?.routeDiscoveryRuntime;return j.useEffect(()=>{n.initialized&&o?.markReady()},[n.initialized,o]),Dr(e,void 0,{router:a.router,manifest:t,state:n,isStatic:r,onError:i})}function xi(e){C(!1,`A is only ever to be used as the child of element, never rendered directly. Please wrap your in a .`)}function Si({basename:e=`/`,children:t=null,location:n,navigationType:r=`POP`,navigator:i,static:a=!1,useTransitions:o}){C(!vr(),`You cannot render a inside another . You should never have more than one in your app.`);let s=e.replace(/^\/*/,`/`),c=j.useMemo(()=>({basename:s,navigator:i,static:a,useTransitions:o,future:{}}),[s,i,a,o]);typeof n==`string`&&(n=ee(n));let{pathname:l=`/`,search:u=``,hash:d=``,state:f=null,key:p=`default`,mask:m}=n,h=j.useMemo(()=>{let e=Re(l,s);return e==null?null:{location:{pathname:e,search:u,hash:d,state:f,key:p,mask:m},navigationType:r}},[s,l,u,d,f,p,r,m]);return w(h!=null,` is not able to match the URL "${l}${u}${d}" because it does not start with the basename, so the won't render anything.`),h==null?null:j.createElement(or.Provider,{value:c},j.createElement(sr.Provider,{children:t,value:h}))}function Ci({children:e,location:t}){return Er(wi(e),t)}j.Component;function wi(e,t=[]){let n=[];return j.Children.forEach(e,(e,r)=>{if(!j.isValidElement(e))return;let i=[...t,r];if(e.type===j.Fragment){n.push.apply(n,wi(e.props.children,i));return}C(e.type===xi,`[${typeof e.type==`string`?e.type:e.type.name}] is not a component. All component children of must be a or `);let a=e.props;C(!a.index||!a.children,`An index route cannot have child routes.`);let o={id:a.id||i.join(`-`),caseSensitive:a.caseSensitive,element:a.element,Component:a.Component,index:a.index,path:a.path,middleware:a.middleware,loader:a.loader,action:a.action,hydrateFallbackElement:a.hydrateFallbackElement,HydrateFallback:a.HydrateFallback,errorElement:a.errorElement,ErrorBoundary:a.ErrorBoundary,shouldRevalidate:a.shouldRevalidate,handle:a.handle,lazy:a.lazy};a.children&&(o.children=wi(a.children,i)),n.push(o)}),n}var Ti=`application/x-www-form-urlencoded`;function Ei(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}function Di(e){return Ei(e)&&e.tagName.toLowerCase()===`button`}function Oi(e){return Ei(e)&&e.tagName.toLowerCase()===`form`}function ki(e){return Ei(e)&&e.tagName.toLowerCase()===`input`}function Ai(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function ji(e,t){return e.button===0&&(!t||t===`_self`)&&!Ai(e)}function Mi(e=``){return new URLSearchParams(typeof e==`string`||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(e=>[n,e]):[[n,r]])},[]))}function Ni(e,t){let n=Mi(e);return t&&t.forEach((e,r)=>{n.has(r)||t.getAll(r).forEach(e=>{n.append(r,e)})}),n}var Pi=null;function Fi(){if(Pi===null)try{new FormData(document.createElement(`form`),0),Pi=!1}catch{Pi=!0}return Pi}var Ii=new Set([`application/x-www-form-urlencoded`,`multipart/form-data`,`text/plain`]);function Li(e){return e!=null&&!Ii.has(e)?(w(!1,`"${e}" is not a valid \`encType\` for \`
\`/\`\` and will default to "${Ti}"`),null):e}function Ri(e,t){if(t===`/`)return e;let n=ee(e),r=Re(n.pathname||``,t);return r==null?null:O({...n,pathname:r})}function zi(e,t){let n,r,i,a,o;if(Oi(e)){let o=e.getAttribute(`action`);r=o?Ri(o,t):null,n=e.getAttribute(`method`)||`get`,i=Li(e.getAttribute(`enctype`))||Ti,a=new FormData(e)}else if(Di(e)||ki(e)&&(e.type===`submit`||e.type===`image`)){let o=e.form;if(o==null)throw Error(`Cannot submit a