From 48cc7d1333927a1467b52be4bff3aea2df47d37d Mon Sep 17 00:00:00 2001 From: eshulman2 Date: Mon, 30 Nov 2026 13:15:01 +0200 Subject: [PATCH 1/5] feat(journal): add protected repository-owned recovery primitives Extract the generic journal engine, GitLab conditional-file backend, protected host binding and explicit CLI operations from the contributor's reference implementation. Preserve fenced ownership, persistent budgets, parent-record predicates and immutable receipts across conservative retries. Require an independently credentialed custom journal writer, rejecting reuse of built-in assessment credentials. Keep workflow admission, dispatch, reconciliation schedules and domain semantics outside this change. Refs #9253 Signed-off-by: eshulman2 --- docs/.vitepress/config.ts | 1 + docs/cli/README.md | 1 + docs/cli/journal.md | 136 ++++++ docs/contributing/forge-abstraction.md | 18 + docs/guides/dev/cli-internals.md | 6 + docs/guides/getting-started/operations.md | 21 + internal/cli/journal.go | 172 +++++++ internal/cli/journal_retry_test.go | 292 ++++++++++++ internal/cli/journal_test.go | 163 +++++++ internal/cli/root.go | 1 + internal/forge/fake.go | 3 + internal/forge/fake_test.go | 4 + internal/forge/fake_versioned_file.go | 51 +++ internal/forge/fake_versioned_file_test.go | 40 ++ internal/forge/forge.go | 12 + internal/forge/github/versioned_file.go | 15 + internal/forge/github/versioned_file_test.go | 16 + internal/forge/gitlab/versioned_file.go | 81 ++++ internal/forge/gitlab/versioned_file_test.go | 133 ++++++ internal/journal/forge.go | 145 ++++++ internal/journal/forge_checkpoint_test.go | 231 ++++++++++ internal/journal/forge_test.go | 79 ++++ internal/journal/journal.go | 454 +++++++++++++++++++ internal/journal/journal_test.go | 234 ++++++++++ internal/journal/json.go | 63 +++ internal/journal/requirements.go | 52 +++ internal/journal/requirements_test.go | 142 ++++++ internal/journalhost/profile.go | 146 ++++++ internal/journalhost/profile_test.go | 155 +++++++ 29 files changed, 2867 insertions(+) create mode 100644 docs/cli/journal.md create mode 100644 internal/cli/journal.go create mode 100644 internal/cli/journal_retry_test.go create mode 100644 internal/cli/journal_test.go create mode 100644 internal/forge/fake_versioned_file.go create mode 100644 internal/forge/fake_versioned_file_test.go create mode 100644 internal/forge/github/versioned_file.go create mode 100644 internal/forge/github/versioned_file_test.go create mode 100644 internal/forge/gitlab/versioned_file.go create mode 100644 internal/forge/gitlab/versioned_file_test.go create mode 100644 internal/journal/forge.go create mode 100644 internal/journal/forge_checkpoint_test.go create mode 100644 internal/journal/forge_test.go create mode 100644 internal/journal/journal.go create mode 100644 internal/journal/journal_test.go create mode 100644 internal/journal/json.go create mode 100644 internal/journal/requirements.go create mode 100644 internal/journal/requirements_test.go create mode 100644 internal/journalhost/profile.go create mode 100644 internal/journalhost/profile_test.go diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index 2e45987978..d5be3c0efd 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -237,6 +237,7 @@ export default defineConfig({ { text: "fullsend prepare", link: "/cli/prepare" }, { text: "fullsend repos", link: "/cli/repos" }, { text: "fullsend run", link: "/cli/run" }, + { text: "fullsend journal", link: "/cli/journal" }, { text: "fullsend self-update", link: "/cli/self-update" }, ], }, diff --git a/docs/cli/README.md b/docs/cli/README.md index a0f32c2a2d..8c5a714930 100644 --- a/docs/cli/README.md +++ b/docs/cli/README.md @@ -31,6 +31,7 @@ To update an installed binary later, run [`fullsend self-update`](self-update.md | [`fullsend prepare`](prepare.md) | Resolve an agent's sandbox image as `fullsend run` does, pre-pull a private image with the CI job's registry credential (`ghcr.io` on GitHub Actions, `CI_REGISTRY` on GitLab CI) as `run` does, and create and delete a restrictive preflight sandbox, which makes the gateway pull the image. Run it once before many parallel runs. `--json` prints the resolved image, architecture, and result. | | `fullsend poll` | Discover forge events and dispatch agent pipelines. `--forge gitlab` runs the cron poller ([ADR 0067](../ADRs/0067-gitlab-cron-polling-event-dispatch.md)); events-mode polling also recovers issue opens whose webhook delivery was missed. `--input-driver jira-poll` polls Jira (see [Jira integration](../guides/user/jira-integration.md)). It reads the Jira site, API gateway, projects, and query only from the effective entity-source configuration: the source translated from `tracker.jira` (`base_url` and `project` required) or an explicit Jira `entity_sources` entry bound in an enabled agent's `entities.source` (the removed `--jira-url`, `--jira-project`, and `--jql` flags are rejected). It authenticates with `FULLSEND_JIRA_TOKEN` (plus `FULLSEND_JIRA_EMAIL` for a bot user) or with OAuth 2.0 client credentials via `FULLSEND_JIRA_CLIENT_ID` and `FULLSEND_JIRA_CLIENT_SECRET`. Those credentials are reused only for the connection translated from `tracker.jira`; a source on an explicit Jira connection is refused until a separately provisioned credential binding exists, and explicit sources are refused when enabled agents bind different `entities.source` lists. It skips the cycle unless a selected source permits discovery (`tracker.jira.poll.enabled` is `true` for the translated source); by default it writes dispatch records (`--output`) for a GitHub repository (`--target-repo`, an `owner/repo` slug; one that contains `..` is refused), and with `--target-forge gitlab` it starts the protected agent pipelines of the GitLab project named by `--project` (full path, nested groups allowed; default `CI_PROJECT_PATH`) on the https `--gitlab-url` instance, through the same signed, typed-input dispatch route and Poller credential as the GitLab poller, advancing a Jira issue's checkpoint only once its pipelines are created ([GitLab runtime](../guides/user/jira-integration.md#gitlab-runtime)). `--input-driver gitlab-webhook` is the GitLab dispatcher job's webhook fast-path ([ADR 0125](../ADRs/0125-gitlab-hybrid-webhook-poller-dispatch.md)). It reads the native webhook body from the file-type `TRIGGER_PAYLOAD` variable, re-validates it against the GitLab API, and creates each routed stage's pipeline (typed inputs, `FULLSEND_DISPATCH_SECRET` HMAC) with the poller-role credential (the `api` route, the default). Scheduled cron polling and the webhook fast path run as the trigger-only service account: once its dispatch activation is recorded, the managed webhook carries the account's pipeline trigger token ([#8509](https://github.com/fullsend-ai/fullsend/issues/8509)), the scaffold sets `FULLSEND_GITLAB_DISPATCH_ROUTE=child-pipeline`, and the command instead starts each pipeline with the job's own `CI_JOB_TOKEN` through the pipeline trigger API (`source=pipeline`); an unknown route, or `child-pipeline` without `CI_JOB_TOKEN`, fails closed. `fullsend poll --forge gitlab --print-dispatch-routes` prints the routes the CLI supports (`api` and `child-pipeline`) and exits; the scaffold runs it before selecting `child-pipeline`, and a CLI that predates the route rejects the flag, so the job stops before any dispatch. It requires `--project`, which has no `CI_PROJECT_PATH` fallback. It deduplicates against the poller's per-mode state on the `fullsend-poll-state-slash` and `fullsend-poll-state-events` branches, so an event the webhook dispatched is not dispatched again by the poller, and the reverse. Shared poller state is occurrence-aware (label additions are keyed on the resource label event ID, dispatched keys are retained for the webhook freshness window, and a failed label dispatch is handed back to the poller as a pending retry); legacy persisted keys keep working. Older pollers do not recognise the new label keys, so before a rollback or mixed-version run, follow the [ADR 0132](../ADRs/0132-occurrence-aware-shared-poller-state.md) guidance to drain in-flight poll jobs or pin every poller to one version. Both GitLab drivers dispatch the fix stage only for a changes-requested marker note authored by the registered Analyst, whose numeric user ID the scaffold exports as the job-local `FULLSEND_GITLAB_ANALYST_USER_ID`. | | `fullsend dispatch` | Evaluate harness CEL triggers for one forge event and print the dispatch matrix (`--output-driver gha-matrix` or `json`); used by the dispatch workflow's `Harness dispatch` job. `--route ` (`review`, `retro`, `triage` or `prioritize`) instead decides routing for that built-in agent and prints one JSON line, `{"agent":"","decision":"run\|skip\|bash","reason":"…","harness":"config:\|agents@"}` (`harness` is optional: it is omitted when the harness cannot be resolved or the decision did not need it, as for `bash`): `run` or `skip` when the repository set `agents[].trigger` on the agent's entry ([Choosing when review runs](../guides/user/customizing-agents.md#choosing-when-review-runs), [Choosing when retro runs](../guides/user/customizing-agents.md#choosing-when-retro-runs), [Choosing when triage and prioritize run](../guides/user/customizing-agents.md#choosing-when-triage-and-prioritize-run)), `bash` to leave the decision to the workflow's built-in rules. Built-in agents resolve from a configured Forgejo instance when `FULLSEND_FORGEJO_URL` is set, as in [`fullsend run`](run.md#agent-definitions-from-a-forgejo-instance). The dispatch workflow's `Route` job runs it. With `--input-driver gha-event`, a GitHub bot actor's registered fullsend role is looked up first through the mint (a layered `mint_url`, else `FULLSEND_MINT_URL`) with the job's Actions OIDC token, so the job needs `id-token: write` ([ADR 0107](../ADRs/0107-bot-identity-resolution-for-dispatch-authorization.md)); label-added events skip the lookup, and an unregistered bot or a failed lookup is denied (an empty matrix, or a `skip` decision) rather than failing the command. An absent config falls back to `FULLSEND_MINT_URL`, but a config that fails to load or parse is a failed lookup, not a fallback. `--input-driver forgejo-event` maps a Forgejo Actions event payload (`FORGEJO_EVENT_PATH`, bound to `FORGEJO_SERVER_URL` and the repository); it is the default when `FORGEJO_ACTIONS` or `GITEA_ACTIONS` is `true`, even when `GITHUB_EVENT_PATH` is also set. This changes the default for pipelines on Forgejo or Gitea runners that relied on the implicit `gha-event` driver; pass `--input-driver gha-event` to restore the previous behavior. No Forgejo permission lookup is wired yet, so its events are denied by the authorization gate ([Forgejo adapter notes](../normative/normalized-event/v1/README.md#forgejo-adapter-notes)). | +| [`fullsend journal`](journal.md) | Explicit protected-host recovery journal operations; no automatic agent dispatch or external-effect replay. | | `fullsend lock [agent-name]` | Pin remote dependencies to `lock.yaml`. If `lock.yaml` exists but cannot be parsed or declares an unsupported version, the command exits without writing and leaves the file unchanged. An entry is stale when the harness file or the `harness:` block of the agent's `agents:` entry has changed. When it composes a harness (a new or stale entry, or `--update`), it also prints the harness diagnostics, including [reserved `env.sandbox` keys](run.md#reserved-envsandbox-keys). A current entry is not composed, so its keys are not checked, and `lock` composes without event context, so keys from event-guarded overlays are reported only by `fullsend run`. A harness whose runtime fetch service can start (`allow_runtime_fetch: true`, URL-sourced skill or plugin directories, or a bare, deprecated `allowed_remote_resources` declaration) must have every harness-level `allowed_remote_resources` prefix covered by the config-level allowlist — `config.yaml`'s `allowed_remote_resources` plus the built-in default prefixes (the defaults are included when the list is omitted or non-empty; an explicit `allowed_remote_resources: []` stays deny-all and excludes them); `lock` fails naming an uncovered prefix, and fails closed when no repository config (`config.yaml` or `config.base.yaml`) exists. With a `harness:` block on the agent's entry, the prefixes checked are the ones the block sets. | | `fullsend lint` | Lint `config.yaml` and agent harness definitions — deprecations, misconfigurations, and file checks, with diagnostics for each enabled agent, or for one agent with `fullsend lint `. See [`fullsend lint`](lint.md), and [Checking a trigger before you merge](../guides/user/cel-triggers-reference.md#checking-a-trigger-before-you-merge) for a walkthrough. | | `fullsend scan` | Run security scanners on agent input/output | diff --git a/docs/cli/journal.md b/docs/cli/journal.md new file mode 100644 index 0000000000..15be4d293b --- /dev/null +++ b/docs/cli/journal.md @@ -0,0 +1,136 @@ +--- +title: fullsend journal +--- + +# fullsend journal + +Read and conditionally update the saga journal in the GitLab control repository. +It provides the storage and host-operation primitives described in +[ADR 0165](../ADRs/0165-recover-work-through-repository-owned-operation-journals.md). +It performs no inference. The JSON output is durable state only after the remote +checkpoint is accepted; a failed or ambiguous call is not permission to repeat +an external action. + +## Protected host profile + +Set `FULLSEND_JOURNAL_PROFILE` in trusted host installation state. Its strict JSON +fields are `forge` (`gitlab`), `base_url` (HTTPS site origin), `owner` (namespace), +`repo`, `branch`, `path` (relative JSON file), and `role`. Source checkouts, tracker +properties and model output cannot supply this profile. The journal branch must +already exist and be protected. The profile selects its exact scope; there are +no command flags to redirect writes elsewhere. + +Register `role` as a custom identity through the existing protected +`FULLSEND_GITLAB_ROLE_REGISTRY`, with `write_repository` capability and its own +secret reference. The built-in Analyst, Poller and Coder roles are refused for +this journal command. Journal credentials stay on trusted hosts. The client +rechecks scope, current profile, authenticating credential and branch protection +on access. Neither ambient `GITLAB_TOKEN` nor a local database is a fallback. + +## Operations + +```sh +fullsend journal initialize +printf '%s' '{"phase":"admitted"}' | fullsend journal admit \ + --id case-001 --binding "reviewed-input-digest" +fullsend journal claim --id case-001 --owner controller-001 --ttl 5m +fullsend journal read --id case-001 +``` + +`initialize` creates the journal on the pre-provisioned branch and refuses an +occupied path. Missing or corrupt existing state requires operator recovery; +ordinary commands never initialize or reset it. + +After admission and claim, leased mutations require `--id`, `--owner` and the +`--generation` returned by `claim`. `admit` and `claim` use the flags in the table: + +| Operation | Other flags / standard input | +| --- | --- | +| `admit` | `--binding`; bounded JSON data on stdin | +| `claim` | `--owner`, optional `--ttl` (default 5m, maximum 24h) | +| `renew` | Optional `--ttl` | +| `release` | Releases the current lease | +| `update` | Bounded replacement domain data on stdin; retains budgets/effects | +| `rebind` | `--binding` plus new reviewed domain data on stdin; preserves consumed bounds and effects | +| `intent` | `--effect-id`, `--kind`, `--binding` | +| `effect` | `--effect-id`, `--status`; confirmed receipt JSON on stdin | +| `spend` | `--counter`, `--limit`; consumption survives later attempts | +| `read` | No mutation flags or stdin | + +The effect states are `intended`, `in_flight`, `ambiguous` and `confirmed`. +Transition checks and immutable receipts prevent a stale owner or repeated +in-flight admission from authorizing another external write. The CLI retries a +mutation at most three times only when the conditional write was definitively +rejected. It reloads state and rechecks all predicates on each attempt, with short +cancellation-aware backoff. It reads stdin once. Initialization and reads are not +replayed. Exhausted conflicts still require caller recovery; do not force-push or +merge competing JSON claims. These retries do not invoke an agent or repeat an +external action. + +GitLab can report a branch-reference race as HTTP 400 with the exact message +`9:reference update: reference does not point to expected object.` The versioned +file adapter classifies this rejected reference update as a revision conflict, +so the same bounded fresh-transaction retry applies. Recognition of this +additional response is exact; similar messages or other HTTP statuses do not +gain retry authority from this rule. + +A lost acknowledgement or failed checkpoint verification returns +`journal checkpoint outcome uncertain` and is never automatically retried. Mixed +conflict/unknown errors, invalid readback, and changes to the target record stay +uncertain. Ownership, binding, integrity and budget failures do not retry either. +The backend keeps all authority in one bounded document, using GitLab's file +revision precondition for the complete transition. After an acknowledged Engine +write, it validates the readback document and its exact intended record; unrelated +records may advance. Direct backend callers retain whole-document verification. + +A checksum detects accidental corruption; it does not authenticate an actor. +Protected storage and current host authorization remain required. No delivery +or publication guarantee is described as exactly once. + +### Bind child mutations to current parent admission + +Promotion controllers can pass all three flags on journal commands: + +```text +--require-record CASE_ID --require-binding MANIFEST_DIGEST --require-data-digest PARENT_DATA_SHA256 +``` + +The data digest is SHA256 of the exact parent record's `data` bytes, as observed +by a trusted context exporter. Every mutation checks all parent requirements on +its fresh loaded snapshot, including idempotent no-op paths, and again in the +whole-document conditional write. A changed parent rejects the mutation. A +concurrent revision conflict can trigger the bounded transaction retry above; +a newly stale parent then fails its fresh check. This does not retry a model call +or external publication. +Reads remain available for recovery even after a parent changes. Requirements +cannot refer to the mutated record itself. They supplement the child operation's +own ownership generation and do not replace source, Jira or human-approval gates. + +## Integration and acceptance boundary + +Installing fullsend does not activate a journal, add schedules, or journal ordinary +agent runs. A workflow must install a protected host profile, explicitly admit +work, supply authorized host adapters and reconcile its external effects. The +journal records intent and receipts; it never performs those external actions. +Assessment sandboxes and their pre/post scripts must not inherit the journal +writer credential merely because they participate in a workflow. + +The storage backend is initially GitLab only. GitHub and Forgejo source targets +remain independent of the journal location; their control-journal backends stay +unsupported pending conformance. No journal access to source repositories is +needed. Hosted cross-machine conformance and end-to-end workflow migration are +tracked in [#9253](https://github.com/fullsend-ai/fullsend/issues/9253); local +fake-backend and HTTP-adapter tests do not establish that acceptance. + +Store only bounded identities, digests and receipts. Checksums detect corruption, +not a writer's identity. Protected storage and host authorization supply that +boundary. Run artifact-level filters do not remove data from journal commits. +Use a separately authorized immutable evidence store when recovery evidence +cannot be retained in run artifacts. Retention, reader access and compaction are +installation responsibilities; exhaustion holds work rather than discarding +unresolved operations. + +This initial command does not create journal-operation trace spans or capture +journal payloads into telemetry. Journal/run trace correlation and metadata-only +instrumentation remain implementation work in #9253. A journal receipt is not a +replacement for the run's detailed telemetry or proof of a domain outcome. diff --git a/docs/contributing/forge-abstraction.md b/docs/contributing/forge-abstraction.md index 2598a6e992..56adbf86e6 100644 --- a/docs/contributing/forge-abstraction.md +++ b/docs/contributing/forge-abstraction.md @@ -53,3 +53,21 @@ When the resource can be reached from more than one repo (for example fork-based - an ownership check whose result does not actually gate every subsequent related operation on that resource (check computed but not enforced) - a predictable-name occupancy check that matches by branch name and author without comparing repo identity (`owner/repo`) - a fail-closed skip that returns success (nil error) to a caller that treats nil as "delivered" + +## Conditional journal files + +`forge.Client.ReadVersionedFile` reads the complete file and its last-modifying +revision. `WriteFileIfRevision` replaces that file once only if the supplied +revision still matches. An empty revision permits creation only when the file +is absent. GitLab implements the pair using its file `last_commit_id` guard; +GitHub control-journal storage returns `ErrNotSupported` until conformance is +implemented. This does not restrict source repositories to GitLab. + +The journal keeps all ownership, budgets and effect receipts in one JSON file, +so its conditional replacement is the complete transaction. A branch-tip read +followed by an unconditional write is not equivalent. Callers authorize the +control repository, branch and path before reading or writing; forge methods +remain transport adapters. Journal checksums detect corruption, not writer +authenticity; protected control storage and host authorization supply that +boundary. A failed or ambiguous write must not be retried +blindly by the transport. diff --git a/docs/guides/dev/cli-internals.md b/docs/guides/dev/cli-internals.md index 90948d84e0..ff6490e66e 100644 --- a/docs/guides/dev/cli-internals.md +++ b/docs/guides/dev/cli-internals.md @@ -29,6 +29,11 @@ fullsend │ ├── --level # Privilege level (read or write; default: write) │ ├── --mint-url # Mint service URL ($FULLSEND_MINT_URL) │ └── --audience # OIDC audience (default: fullsend-mint) +├── journal # Explicit protected-host recovery journal +│ ├── initialize # Create only on a pre-provisioned protected branch +│ ├── read | admit | claim # Inspect or admit work and acquire ownership +│ ├── renew | release | update | rebind # Fenced lease and state transitions +│ └── intent | effect | spend # Record effects and persistent budget consumption ├── inference # Inference credentials (GCP Vertex, OpenAI) │ ├── provision # Create WIF pool/provider for Agent Platform │ │ ├── --forge # Forge whose CI identities the provider trusts (default: github) @@ -1016,6 +1021,7 @@ var executableFiles = map[string]struct{}{ | `internal/cli/github_client.go` | ~130 | GitHub token resolution and authenticated client construction | | `internal/cli/issues.go` | ~971 | Issue read/write commands (`fullsend issues get`, `create`, `post-comment`, `link`, `transition`; transitions are in `issues_transition.go`) | | `internal/cli/tracker_client.go` | ~122 | Tracker client factory (GitHub/GitLab/Jira) | +| `internal/cli/journal.go` | ~170 | Explicit protected-host journal operations and conservative conflict recovery | | `internal/cli/run.go` | ~1923 | Agent execution lifecycle | | `internal/mint/main.go` | ~95 | GCF token mint entry point (wiring only) | | `cmd/mint/` | ~285 | Standalone mint server (no GCP dependency) | diff --git a/docs/guides/getting-started/operations.md b/docs/guides/getting-started/operations.md index b5ae24a30e..045d3d1903 100644 --- a/docs/guides/getting-started/operations.md +++ b/docs/guides/getting-started/operations.md @@ -233,6 +233,27 @@ marker needs adoption and is left untouched (install skips that repository before any write, reports it as failed and exits non-zero, and converges the others). +## Opt in to a recovery journal + +```sh +fullsend journal initialize +fullsend journal read --id OPERATION_ID +``` + +These commands require an administrator-provisioned protected journal branch, +a trusted `FULLSEND_JOURNAL_PROFILE`, and a separately registered GitLab role +with its own `write_repository` credential. Follow the +[journal command reference](../../cli/journal.md#protected-host-profile) before +running them. Initialize only a new journal; never recreate or reset missing +state to release budgets or unresolved effects. + +Workflow integration is explicit. The command neither adds a schedule nor +changes normal poll/webhook dispatch. Keep writer credentials outside assessment +runs, including their pre/post scripts. Trusted adapters remain responsible for +fresh authorization, source binding, evidence retention and reconciliation. +[ADR 0165](../../ADRs/0165-recover-work-through-repository-owned-operation-journals.md) +defines that boundary. + ## Uninstalling ### Per-repo teardown diff --git a/internal/cli/journal.go b/internal/cli/journal.go new file mode 100644 index 0000000000..925f24b1c9 --- /dev/null +++ b/internal/cli/journal.go @@ -0,0 +1,172 @@ +package cli + +import ( + "context" + "encoding/json" + "errors" + "io" + "os" + "time" + + "github.com/fullsend-ai/fullsend/internal/journal" + "github.com/fullsend-ai/fullsend/internal/journalhost" + "github.com/spf13/cobra" +) + +var openJournalHost = journalhost.Open + +func newJournalCmd() *cobra.Command { + var id, binding, owner, kind, effectID, status, counter string + var generation, limit uint64 + var ttl time.Duration + var required journal.Requirement + cmd := &cobra.Command{Use: "journal ", Short: "Checkpoint a saga in the protected GitLab control repository", Args: cobra.ExactArgs(1)} + cmd.Long = "Read and conditionally update the journal selected by protected FULLSEND_JOURNAL_PROFILE installation state. JSON payloads and leases use standard input/output; journal credentials remain host-side. No model is invoked." + cmd.Flags().StringVar(&id, "id", "", "stable admitted operation identity") + cmd.Flags().StringVar(&binding, "binding", "", "immutable input digest for admission or effect") + cmd.Flags().StringVar(&owner, "owner", "", "lease owner identity") + cmd.Flags().Uint64Var(&generation, "generation", 0, "ownership generation returned by claim") + cmd.Flags().DurationVar(&ttl, "ttl", 5*time.Minute, "lease lifetime (maximum 24h)") + cmd.Flags().StringVar(&kind, "kind", "", "effect kind") + cmd.Flags().StringVar(&effectID, "effect-id", "", "stable external operation identity") + cmd.Flags().StringVar(&status, "status", "", "effect state: in_flight, ambiguous or confirmed") + cmd.Flags().StringVar(&counter, "counter", "", "durable budget counter") + cmd.Flags().Uint64Var(&limit, "limit", 0, "maximum budget consumption") + cmd.Flags().StringVar(&required.ID, "require-record", "", "parent record required in the same conditional journal write") + cmd.Flags().StringVar(&required.Binding, "require-binding", "", "required parent input binding") + cmd.Flags().StringVar(&required.DataDigest, "require-data-digest", "", "SHA256 of exact observed parent data bytes") + cmd.RunE = func(cmd *cobra.Command, args []string) error { + action := args[0] + allowed := map[string]bool{"initialize": true, "read": true, "admit": true, "claim": true, "renew": true, "release": true, "update": true, "rebind": true, "intent": true, "effect": true, "spend": true} + if !allowed[action] { + return errors.New("unknown journal operation") + } + if action != "initialize" && id == "" { + return errors.New("--id required") + } + engine, backend, err := openJournalHost(os.Getenv) + if err != nil { + return sanitizeJournalError(err) + } + if required.ID != "" || required.Binding != "" || required.DataDigest != "" { + if action == "initialize" || required.ID == id { + return journal.ErrBinding + } + engine, err = engine.RequireRecord(required) + if err != nil { + return sanitizeJournalError(err) + } + } + lease := journal.Lease{Owner: owner, Generation: generation} + ctx := cmd.Context() + var data json.RawMessage + if action == "admit" || action == "update" || action == "rebind" || (action == "effect" && status == "confirmed") { + data, err = readJournalJSON(cmd.InOrStdin()) + if err != nil { + return sanitizeJournalError(err) + } + } + operation := func() (any, error) { + // Invoke the engine afresh: each transaction reloads and rechecks + // parent predicates, lease ownership, transitions and budgets. + switch action { + case "initialize": + err := backend.Initialize(ctx) + return map[string]bool{"initialized": err == nil}, err + case "read": + return engine.Read(ctx, id) + case "admit": + return engine.Admit(ctx, id, binding, data) + case "claim": + return engine.Claim(ctx, id, owner, ttl) + case "renew": + return engine.Renew(ctx, id, lease, ttl) + case "release": + err := engine.Release(ctx, id, lease) + return map[string]bool{"released": err == nil}, err + case "update": + return engine.Update(ctx, id, lease, func(r *journal.Record) error { r.Data = data; return nil }) + case "rebind": + return engine.Rebind(ctx, id, lease, binding, data) + case "intent": + return engine.Intent(ctx, id, lease, journal.Effect{ID: effectID, Kind: kind, Binding: binding, Status: "intended"}) + case "effect": + return engine.Effect(ctx, id, lease, effectID, status, data) + case "spend": + return engine.Spend(ctx, id, lease, counter, limit) + } + return nil, journal.ErrIntegrity + } + var result any + if action == "initialize" || action == "read" { + result, err = operation() + } else { + result, err = retryJournalTransaction(ctx, operation) + } + if err != nil { + return sanitizeJournalError(err) + } + return json.NewEncoder(cmd.OutOrStdout()).Encode(result) + } + return cmd +} +func readJournalJSON(r io.Reader) (json.RawMessage, error) { + data, err := io.ReadAll(io.LimitReader(r, journal.MaxDocumentBytes+1)) + if err != nil || len(data) > journal.MaxDocumentBytes || !json.Valid(data) { + return nil, errors.New("bounded JSON input required") + } + return json.RawMessage(data), nil +} +func sanitizeJournalError(err error) error { + for _, known := range []error{journal.ErrUncertain, journal.ErrConflict, journal.ErrIntegrity, journal.ErrOwnership, journal.ErrBinding, journal.ErrNotFound, journal.ErrTransition, journal.ErrBudget, context.Canceled, context.DeadlineExceeded} { + if errors.Is(err, known) { + return known + } + } + return errors.New("journal operation failed; inspect control repository and connection permissions") +} + +// retryJournalTransaction replays only definitively rejected writes. Never +// replay a saved document: the operation must execute a fresh engine transaction. +func retryJournalTransaction(ctx context.Context, operation func() (any, error)) (any, error) { + for attempt := 0; ; attempt++ { + if err := ctx.Err(); err != nil { + return nil, err + } + result, err := operation() + if err == nil || attempt == 2 || !journalConflictOnly(err) { + return result, err + } + timer := time.NewTimer(time.Duration(20*(attempt+1)) * time.Millisecond) + select { + case <-ctx.Done(): + timer.Stop() + return nil, ctx.Err() + case <-timer.C: + } + } +} + +// A joined unknown failure can indicate an uncertain outcome even when another +// branch is a conflict. Require every leaf to be the definite-conflict sentinel. +func journalConflictOnly(err error) bool { + if !errors.Is(err, journal.ErrConflict) || errors.Is(err, journal.ErrUncertain) { + return false + } + if joined, ok := err.(interface{ Unwrap() []error }); ok { + children := joined.Unwrap() + if len(children) == 0 { + return false + } + for _, child := range children { + if !journalConflictOnly(child) { + return false + } + } + return true + } + if wrapped, ok := err.(interface{ Unwrap() error }); ok { + return journalConflictOnly(wrapped.Unwrap()) + } + return err == journal.ErrConflict +} diff --git a/internal/cli/journal_retry_test.go b/internal/cli/journal_retry_test.go new file mode 100644 index 0000000000..0e452e8f03 --- /dev/null +++ b/internal/cli/journal_retry_test.go @@ -0,0 +1,292 @@ +package cli + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "testing" + "time" + + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/journal" + "github.com/stretchr/testify/require" +) + +func TestJournalTransactionRetriesOnlyDefiniteConflicts(t *testing.T) { + unknown := errors.New("secret storage failure") + for _, tc := range []struct { + name string + err error + calls int + }{ + {"conflict", fmt.Errorf("wrapped: %w", journal.ErrConflict), 3}, + {"joined conflicts", errors.Join(journal.ErrConflict, journal.ErrConflict), 3}, + {"unknown", unknown, 1}, + {"uncertain", journal.ErrUncertain, 1}, + {"uncertain conflict", errors.Join(journal.ErrConflict, journal.ErrUncertain), 1}, + {"unknown conflict", errors.Join(journal.ErrConflict, unknown), 1}, + {"budget conflict", errors.Join(journal.ErrConflict, journal.ErrBudget), 1}, + {"ownership conflict", errors.Join(journal.ErrConflict, journal.ErrOwnership), 1}, + {"binding conflict", errors.Join(journal.ErrConflict, journal.ErrBinding), 1}, + {"integrity conflict", errors.Join(journal.ErrConflict, journal.ErrIntegrity), 1}, + {"transition conflict", errors.Join(journal.ErrConflict, journal.ErrTransition), 1}, + {"not found conflict", errors.Join(journal.ErrConflict, journal.ErrNotFound), 1}, + {"canceled conflict", errors.Join(journal.ErrConflict, context.Canceled), 1}, + {"timeout conflict", errors.Join(journal.ErrConflict, context.DeadlineExceeded), 1}, + } { + t.Run(tc.name, func(t *testing.T) { + calls := 0 + _, err := retryJournalTransaction(context.Background(), func() (any, error) { calls++; return nil, tc.err }) + require.ErrorIs(t, err, tc.err) + require.Equal(t, tc.calls, calls) + }) + } + calls := 0 + result, err := retryJournalTransaction(context.Background(), func() (any, error) { + calls++ + if calls == 1 { + return nil, journal.ErrConflict + } + return "ok", nil + }) + require.NoError(t, err) + require.Equal(t, "ok", result) + require.Equal(t, 2, calls) + ctx, cancel := context.WithCancel(context.Background()) + calls = 0 + _, err = retryJournalTransaction(ctx, func() (any, error) { calls++; cancel(); return nil, journal.ErrConflict }) + require.ErrorIs(t, err, context.Canceled) + require.Equal(t, 1, calls) + require.Equal(t, "journal checkpoint outcome uncertain", sanitizeJournalError(errors.Join(journal.ErrConflict, fmt.Errorf("secret: %w", journal.ErrUncertain))).Error()) +} + +type retryJournalBackend struct { + doc journal.Document + uncertain bool + loads, writes int + concurrent func(*journal.Document) +} + +func (b *retryJournalBackend) Load(context.Context) (journal.Document, string, error) { + b.loads++ + raw, err := journal.Encode(b.doc) + if err != nil { + return journal.Document{}, "", err + } + d, err := journal.Decode(raw) + return d, "revision", err +} +func (b *retryJournalBackend) CompareAndSwap(_ context.Context, _ string, d journal.Document) (string, error) { + b.writes++ + if b.uncertain { + b.doc = d + return "", errors.Join(journal.ErrConflict, fmt.Errorf("secret: %w", journal.ErrUncertain)) + } + if b.writes == 1 { + if b.concurrent != nil { + b.concurrent(&b.doc) + } + return "", journal.ErrConflict + } + b.doc = d + return "next", nil +} +func TestJournalCLIConflictReloadsAuthorityAndReusesInput(t *testing.T) { + for _, change := range []string{"unrelated", "budget", "ownership", "binding", "parent"} { + t.Run(change, func(t *testing.T) { + lease := journal.Lease{Owner: "worker", Generation: 1, ExpiresAt: time.Now().Add(time.Hour)} + record := journal.Record{ID: "case", Binding: "sha", Generation: 1, Lease: lease, Data: json.RawMessage(`{}`), Counters: map[string]uint64{}, Effects: map[string]journal.Effect{}} + parent := record + parent.ID = "parent" + parent.Binding = "parent-sha" + b := &retryJournalBackend{doc: journal.Empty()} + b.doc.Records["case"] = record + b.doc.Records["parent"] = parent + b.concurrent = func(d *journal.Document) { + r := d.Records["case"] + switch change { + case "budget": + r.Counters["attempts"] = 1 + case "ownership": + r.Lease.Owner = "other" + case "binding": + r.Binding = "changed" + case "parent": + p := d.Records["parent"] + p.Binding = "changed" + d.Records["parent"] = p + case "unrelated": + p := d.Records["parent"] + p.Data = json.RawMessage(`{"concurrent":true}`) + d.Records["parent"] = p + } + d.Records["case"] = r + } + old := openJournalHost + openJournalHost = func(func(string) string) (*journal.Engine, *journal.ForgeBackend, error) { + return journal.New(b, nil), nil, nil + } + t.Cleanup(func() { openJournalHost = old }) + args := []string{"update", "--id", "case", "--owner", "worker", "--generation", "1"} + var want error + switch change { + case "budget": + args[0] = "spend" + args = append(args, "--counter", "attempts", "--limit", "1") + want = journal.ErrBudget + case "ownership": + want = journal.ErrOwnership + case "binding": + args = []string{"admit", "--id", "case", "--binding", "sha"} + want = journal.ErrBinding + case "parent": + sum := sha256.Sum256(parent.Data) + args = append(args, "--require-record", "parent", "--require-binding", "parent-sha", "--require-data-digest", hex.EncodeToString(sum[:])) + want = journal.ErrBinding + } + // Admit needs an absent record to write before the concurrent binding change. + if change == "binding" { + delete(b.doc.Records, "case") + b.concurrent = func(d *journal.Document) { r := record; r.Binding = "changed"; d.Records["case"] = r } + } + output, err := runJournal(t, `{"payload":"read once"}`, args...) + if want != nil { + require.ErrorIs(t, err, want) + require.NotContains(t, output, `"payload":"read once"`) + require.Equal(t, 1, b.writes) + } else { + require.NoError(t, err) + require.Contains(t, output, `"payload":"read once"`) + require.JSONEq(t, `{"concurrent":true}`, string(b.doc.Records["parent"].Data)) + require.Equal(t, 2, b.writes) + } + require.Equal(t, 2, b.loads) + }) + } +} + +func TestJournalCLILostAcknowledgementDoesNotRepeatSpendOrClaim(t *testing.T) { + for _, action := range []string{"spend", "claim"} { + t.Run(action, func(t *testing.T) { + lease := journal.Lease{Owner: "worker", Generation: 1, ExpiresAt: time.Now().Add(time.Hour)} + r := journal.Record{ID: "case", Binding: "sha", Generation: 1, Lease: lease, Data: json.RawMessage(`{}`), Counters: map[string]uint64{}, Effects: map[string]journal.Effect{}} + if action == "claim" { + r.Lease = journal.Lease{} + } + b := &retryJournalBackend{doc: journal.Empty(), uncertain: true} + b.doc.Records["case"] = r + old := openJournalHost + openJournalHost = func(func(string) string) (*journal.Engine, *journal.ForgeBackend, error) { + return journal.New(b, nil), nil, nil + } + t.Cleanup(func() { openJournalHost = old }) + args := []string{action, "--id", "case", "--owner", "worker"} + if action == "spend" { + args = append(args, "--generation", "1", "--counter", "attempts", "--limit", "3") + } + _, err := runJournal(t, "", args...) + require.Equal(t, journal.ErrUncertain, err) + require.Equal(t, 1, b.loads) + require.Equal(t, 1, b.writes) + if action == "spend" { + require.Equal(t, uint64(1), b.doc.Records["case"].Counters["attempts"]) + } else { + require.Equal(t, uint64(2), b.doc.Records["case"].Generation) + } + }) + } +} + +func TestJournalCLIInitializeDoesNotRetryConflict(t *testing.T) { + calls := 0 + backend, err := journal.NewForgeBackend(forge.NewFakeClient(), journal.Location{Owner: "o", Repo: "r", Branch: "journal", Path: "state.json"}, func(context.Context, journal.Location, string) error { calls++; return journal.ErrConflict }) + require.NoError(t, err) + old := openJournalHost + openJournalHost = func(func(string) string) (*journal.Engine, *journal.ForgeBackend, error) { + return journal.New(backend, nil), backend, nil + } + t.Cleanup(func() { openJournalHost = old }) + _, err = runJournal(t, "", "initialize") + require.ErrorIs(t, err, journal.ErrConflict) + require.Equal(t, 1, calls) +} + +func TestJournalTransactionCanceledBeforeAttempt(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + calls := 0 + _, err := retryJournalTransaction(ctx, func() (any, error) { calls++; return nil, nil }) + require.ErrorIs(t, err, context.Canceled) + require.Zero(t, calls) +} + +func TestJournalCLIRetryRejectsStaleParentEvenWhenMutationBecomesNoop(t *testing.T) { + for _, action := range []string{"admit", "update", "intent"} { + t.Run(action, func(t *testing.T) { + lease := journal.Lease{Owner: "worker", Generation: 1, ExpiresAt: time.Now().Add(time.Hour)} + child := journal.Record{ID: "case", Binding: "sha", Generation: 1, Lease: lease, Data: json.RawMessage(`{}`), Counters: map[string]uint64{}, Effects: map[string]journal.Effect{}} + parent := child + parent.ID = "parent" + parent.Binding = "parent-sha" + b := &retryJournalBackend{doc: journal.Empty()} + b.doc.Records["parent"] = parent + if action != "admit" { + b.doc.Records["case"] = child + } + b.concurrent = func(d *journal.Document) { + p := d.Records["parent"] + p.Data = json.RawMessage(`{"revoked":true}`) + d.Records["parent"] = p + switch action { + case "admit", "update": + child.Data = json.RawMessage(`{"desired":true}`) + case "intent": + child.Effects = map[string]journal.Effect{"publish": {ID: "publish", Kind: "pr", Binding: "approved", Status: journal.EffectIntended}} + } + d.Records["case"] = child + } + old := openJournalHost + openJournalHost = func(func(string) string) (*journal.Engine, *journal.ForgeBackend, error) { + return journal.New(b, nil), nil, nil + } + t.Cleanup(func() { openJournalHost = old }) + sum := sha256.Sum256(parent.Data) + args := []string{action, "--id", "case", "--require-record", "parent", "--require-binding", "parent-sha", "--require-data-digest", hex.EncodeToString(sum[:])} + if action == "admit" { + args = append(args, "--binding", "sha") + } else { + args = append(args, "--owner", "worker", "--generation", "1") + } + if action == "intent" { + args = append(args, "--effect-id", "publish", "--kind", "pr", "--binding", "approved") + } + output, err := runJournal(t, `{"desired":true}`, args...) + require.ErrorIs(t, err, journal.ErrBinding) + require.NotContains(t, output, `"desired":true`) + require.Equal(t, 2, b.loads) + require.Equal(t, 1, b.writes) + }) + } +} + +func TestJournalCLIReadAuthorizationConflictIsNotRetried(t *testing.T) { + calls := 0 + backend, err := journal.NewForgeBackend(forge.NewFakeClient(), journal.Location{Owner: "o", Repo: "r", Branch: "journal", Path: "state.json"}, func(context.Context, journal.Location, string) error { + calls++ + return fmt.Errorf("secret authorization failure: %w", journal.ErrConflict) + }) + require.NoError(t, err) + old := openJournalHost + openJournalHost = func(func(string) string) (*journal.Engine, *journal.ForgeBackend, error) { + return journal.New(backend, nil), backend, nil + } + t.Cleanup(func() { openJournalHost = old }) + _, err = runJournal(t, "", "spend", "--id", "case", "--owner", "worker", "--generation", "1", "--counter", "attempts", "--limit", "1") + require.Error(t, err) + require.NotContains(t, err.Error(), "secret") + require.NotErrorIs(t, err, journal.ErrConflict) + require.Equal(t, 1, calls) +} diff --git a/internal/cli/journal_test.go b/internal/cli/journal_test.go new file mode 100644 index 0000000000..584ac560e5 --- /dev/null +++ b/internal/cli/journal_test.go @@ -0,0 +1,163 @@ +package cli + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "strings" + "testing" + "time" + + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/journal" + "github.com/stretchr/testify/require" +) + +func journalCommandFixture(t *testing.T) (*journal.Engine, *journal.ForgeBackend) { + t.Helper() + fc := forge.NewFakeClient() + fc.BranchRefs["o/r/journal"] = "head" + backend, err := journal.NewForgeBackend(fc, journal.Location{Owner: "o", Repo: "r", Branch: "journal", Path: "state.json"}, func(context.Context, journal.Location, string) error { return nil }) + require.NoError(t, err) + engine := journal.New(backend, nil) + old := openJournalHost + openJournalHost = func(func(string) string) (*journal.Engine, *journal.ForgeBackend, error) { return engine, backend, nil } + t.Cleanup(func() { openJournalHost = old }) + return engine, backend +} +func runJournal(t *testing.T, input string, args ...string) (string, error) { + t.Helper() + cmd := newJournalCmd() + var output bytes.Buffer + cmd.SetOut(&output) + cmd.SetErr(io.Discard) + cmd.SetIn(strings.NewReader(input)) + cmd.SetArgs(args) + err := cmd.Execute() + return output.String(), err +} +func TestJournalCLIDurableLifecycle(t *testing.T) { + engine, _ := journalCommandFixture(t) + output, err := runJournal(t, "", "initialize") + require.NoError(t, err) + require.Contains(t, output, `"initialized":true`) + _, err = runJournal(t, `{"targets":["main","release"]}`, "admit", "--id", "case", "--binding", "source-sha") + require.NoError(t, err) + output, err = runJournal(t, "", "claim", "--id", "case", "--owner", "host") + require.NoError(t, err) + var lease journal.Lease + require.NoError(t, json.Unmarshal([]byte(output), &lease)) + require.Equal(t, "host", lease.Owner) + flags := []string{"--id", "case", "--owner", lease.Owner, "--generation", fmt.Sprint(lease.Generation)} + call := func(input, action string, extra ...string) (string, error) { + args := append([]string{action}, flags...) + return runJournal(t, input, append(args, extra...)...) + } + _, err = call("", "intent", "--effect-id", "dispatch-1", "--kind", "dispatch", "--binding", "request-sha") + require.NoError(t, err) + _, err = call("", "effect", "--effect-id", "dispatch-1", "--status", "in_flight") + require.NoError(t, err) + _, err = call("", "effect", "--effect-id", "dispatch-1", "--status", "ambiguous") + require.NoError(t, err) + _, err = call(`{"run":"run-1"}`, "effect", "--effect-id", "dispatch-1", "--status", "confirmed") + require.NoError(t, err) + _, err = call("", "spend", "--counter", "attempts", "--limit", "1") + require.NoError(t, err) + _, err = call("", "spend", "--counter", "attempts", "--limit", "1") + require.ErrorIs(t, err, journal.ErrBudget) + _, err = call(`{"targets":["main","release"],"checked":true}`, "update") + require.NoError(t, err) + _, err = call(`{"targets":["main","release"],"checked":true}`, "rebind", "--binding", "source-sha-2") + require.NoError(t, err) + _, err = call("", "renew", "--ttl", "10m") + require.NoError(t, err) + output, err = runJournal(t, "", "read", "--id", "case") + require.NoError(t, err) + require.Contains(t, output, `"confirmed"`) + require.Contains(t, output, `"checked":true`) + _, err = call("", "release") + require.NoError(t, err) + record, err := engine.Read(context.Background(), "case") + require.NoError(t, err) + require.Empty(t, record.Lease.Owner) + require.Equal(t, uint64(1), record.Counters["attempts"]) + require.Equal(t, "source-sha-2", record.Binding) + require.Equal(t, "confirmed", record.Effects["dispatch-1"].Status) +} +func TestJournalCLIRejectsMalformedAndUnownedOperations(t *testing.T) { + _, backend := journalCommandFixture(t) + require.NoError(t, backend.Initialize(context.Background())) + for _, args := range [][]string{{"unknown"}, {"read"}, {"rebind", "--id", "case", "--binding", "sha-2"}, {"admit", "--id", "case", "--binding", "sha"}, {"effect", "--id", "case", "--status", "confirmed"}} { + _, err := runJournal(t, "bad json", args...) + require.Error(t, err) + } + _, err := runJournal(t, `{}`, "admit", "--id", "case", "--binding", "sha") + require.NoError(t, err) + _, err = runJournal(t, "", "spend", "--id", "case", "--owner", "wrong", "--generation", "1", "--counter", "attempts", "--limit", "1") + require.ErrorIs(t, err, journal.ErrOwnership) + old := openJournalHost + openJournalHost = func(func(string) string) (*journal.Engine, *journal.ForgeBackend, error) { + return nil, nil, errors.New("transport leaked token-secret") + } + t.Cleanup(func() { openJournalHost = old }) + _, err = runJournal(t, "", "read", "--id", "case") + require.Error(t, err) + require.NotContains(t, err.Error(), "token-secret") +} + +type journalBrokenReader struct{} + +func (journalBrokenReader) Read([]byte) (int, error) { return 0, errors.New("read failed") } +func TestJournalJSONBoundsAndSanitizedErrors(t *testing.T) { + for _, r := range []io.Reader{strings.NewReader("{"), strings.NewReader(strings.Repeat("x", journal.MaxDocumentBytes+1)), journalBrokenReader{}} { + _, err := readJournalJSON(r) + require.Error(t, err) + } + valid, err := readJournalJSON(strings.NewReader(`{"a":1}`)) + require.NoError(t, err) + require.JSONEq(t, `{"a":1}`, string(valid)) + for _, sentinel := range []error{journal.ErrConflict, journal.ErrIntegrity, journal.ErrOwnership, journal.ErrBinding, journal.ErrNotFound, journal.ErrTransition, journal.ErrBudget, context.Canceled, context.DeadlineExceeded} { + require.ErrorIs(t, sanitizeJournalError(fmt.Errorf("token-secret: %w", sentinel)), sentinel) + } + require.NotContains(t, sanitizeJournalError(errors.New("token-secret")).Error(), "token-secret") +} + +func TestJournalCLIParentPredicatesRejectStaleEffect(t *testing.T) { + e, b := journalCommandFixture(t) + ctx := context.Background() + require.NoError(t, b.Initialize(ctx)) + parent, err := e.Admit(ctx, "parent", "manifest", json.RawMessage(`{"state":"admitted"}`)) + require.NoError(t, err) + parent, err = e.Read(ctx, "parent") + require.NoError(t, err) + sum := sha256.Sum256(parent.Data) + flags := []string{"--require-record", "parent", "--require-binding", "manifest", "--require-data-digest", hex.EncodeToString(sum[:])} + _, err = runJournal(t, `{}`, append([]string{"admit", "--id", "child", "--binding", "plan"}, flags...)...) + require.NoError(t, err) + lease, err := e.Claim(ctx, "child", "worker", time.Minute) + require.NoError(t, err) + args := append([]string{"intent", "--id", "child", "--owner", "worker", "--generation", fmt.Sprint(lease.Generation), "--effect-id", "publish", "--kind", "pr", "--binding", "approved"}, flags...) + _, err = runJournal(t, "", args...) + require.NoError(t, err) + parentLease, err := e.Claim(ctx, "parent", "controller", time.Minute) + require.NoError(t, err) + _, err = e.Update(ctx, "parent", parentLease, func(r *journal.Record) error { r.Data = json.RawMessage(`{"state":"revoked"}`); return nil }) + require.NoError(t, err) + _, err = runJournal(t, "", append([]string{"effect", "--id", "child", "--owner", "worker", "--generation", fmt.Sprint(lease.Generation), "--effect-id", "publish", "--status", "in_flight"}, flags...)...) + require.ErrorIs(t, err, journal.ErrBinding) + child, err := e.Read(ctx, "child") + require.NoError(t, err) + require.Equal(t, "intended", child.Effects["publish"].Status) + // Read remains available, while malformed/partial/self requirements fail closed. + _, err = runJournal(t, "", append([]string{"read", "--id", "child"}, flags...)...) + require.NoError(t, err) + for _, a := range [][]string{{"initialize", "--require-record", "parent"}, {"read", "--id", "parent", "--require-record", "parent"}, {"read", "--id", "child", "--require-binding", "manifest"}} { + _, err = runJournal(t, "", a...) + require.ErrorIs(t, err, journal.ErrBinding) + } +} diff --git a/internal/cli/root.go b/internal/cli/root.go index 3dfd329688..67bc9449cc 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -82,6 +82,7 @@ func newRootCmd() *cobra.Command { cmd.AddCommand(newGitHubCmd()) cmd.AddCommand(newInferenceCmd()) cmd.AddCommand(newLockCmd()) + cmd.AddCommand(newJournalCmd()) cmd.AddCommand(newMintCmd()) cmd.AddCommand(newFetchSkillCmd()) cmd.AddCommand(newDispatchCmd()) diff --git a/internal/forge/fake.go b/internal/forge/fake.go index 1a16ee4edb..9f267b766c 100644 --- a/internal/forge/fake.go +++ b/internal/forge/fake.go @@ -212,6 +212,9 @@ const ForceCommitFixedBaseSHA = "0000000000000000000000000000000000000001" // Pre-populate its fields to control return values, and inspect // recorder slices after the test to verify which calls were made. type FakeClient struct { + versionedFileRevisions map[string]string + versionedFileSequence uint64 + mu sync.Mutex // Pre-populated data diff --git a/internal/forge/fake_test.go b/internal/forge/fake_test.go index ef66645511..d0b750f71d 100644 --- a/internal/forge/fake_test.go +++ b/internal/forge/fake_test.go @@ -879,6 +879,10 @@ func fakeClientCalls(ctx context.Context) map[string]func(fc *FakeClient) []any return pack(fc.ListDirectoryContents(ctx, "o", "r", "p", "main", false)) }, "ListRepositoryFiles": func(fc *FakeClient) []any { return pack(fc.ListRepositoryFiles(ctx, "o", "r")) }, + "ReadVersionedFile": func(fc *FakeClient) []any { return pack(fc.ReadVersionedFile(ctx, "o", "r", "b", "p")) }, + "WriteFileIfRevision": func(fc *FakeClient) []any { + return pack(fc.WriteFileIfRevision(ctx, "o", "r", "b", "p", "", "m", []byte("c"))) + }, "GetFileContentAtRef": func(fc *FakeClient) []any { return pack(fc.GetFileContentAtRef(ctx, "o", "r", "p", "main")) }, "CommitFiles": func(fc *FakeClient) []any { return pack(fc.CommitFiles(ctx, "o", "r", "m", []TreeFile{{Path: "p", Content: []byte("c"), Mode: "100644"}})) diff --git a/internal/forge/fake_versioned_file.go b/internal/forge/fake_versioned_file.go new file mode 100644 index 0000000000..b89db44796 --- /dev/null +++ b/internal/forge/fake_versioned_file.go @@ -0,0 +1,51 @@ +package forge + +import ( + "context" + "fmt" + "slices" +) + +// Fake revisions bind the complete stored file. Only tests use this backend. +func (f *FakeClient) ReadVersionedFile(_ context.Context, owner, repo, branch, path string) ([]byte, string, error) { + f.mu.Lock() + defer f.mu.Unlock() + if err := f.err("ReadVersionedFile"); err != nil { + return nil, "", err + } + key := fmt.Sprintf("%s/%s/%s@%s", owner, repo, path, branch) + content, ok := f.FileContentsRef[key] + if !ok { + return nil, "", ErrNotFound + } + if f.versionedFileRevisions == nil { + f.versionedFileRevisions = map[string]string{} + } + if f.versionedFileRevisions[key] == "" { + f.versionedFileSequence++ + f.versionedFileRevisions[key] = fmt.Sprintf("versioned-%d", f.versionedFileSequence) + } + return slices.Clone(content), f.versionedFileRevisions[key], nil +} +func (f *FakeClient) WriteFileIfRevision(_ context.Context, owner, repo, branch, path, revision, message string, content []byte) error { + f.mu.Lock() + defer f.mu.Unlock() + if err := f.err("WriteFileIfRevision"); err != nil { + return err + } + key := fmt.Sprintf("%s/%s/%s@%s", owner, repo, path, branch) + _, exists := f.FileContentsRef[key] + if revision == "" && exists || revision != "" && (!exists || revision != f.versionedFileRevisions[key]) { + return ErrConflict + } + if f.FileContentsRef == nil { + f.FileContentsRef = map[string][]byte{} + } + if f.versionedFileRevisions == nil { + f.versionedFileRevisions = map[string]string{} + } + f.versionedFileSequence++ + f.versionedFileRevisions[key] = fmt.Sprintf("versioned-%d", f.versionedFileSequence) + f.FileContentsRef[key] = slices.Clone(content) + return nil +} diff --git a/internal/forge/fake_versioned_file_test.go b/internal/forge/fake_versioned_file_test.go new file mode 100644 index 0000000000..1f5ed33481 --- /dev/null +++ b/internal/forge/fake_versioned_file_test.go @@ -0,0 +1,40 @@ +package forge + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestFakeVersionedFileCASAndABA(t *testing.T) { + ctx := context.Background() + f := NewFakeClient() + require.NoError(t, f.WriteFileIfRevision(ctx, "o", "r", "state", "j.json", "", "create", []byte("a"))) + content, old, err := f.ReadVersionedFile(ctx, "o", "r", "state", "j.json") + require.NoError(t, err) + content[0] = 'z' + _, unchanged, err := f.ReadVersionedFile(ctx, "o", "r", "state", "j.json") + require.NoError(t, err) + require.Equal(t, old, unchanged) + require.NoError(t, f.WriteFileIfRevision(ctx, "o", "r", "state", "j.json", old, "to b", []byte("b"))) + _, next, err := f.ReadVersionedFile(ctx, "o", "r", "state", "j.json") + require.NoError(t, err) + require.NoError(t, f.WriteFileIfRevision(ctx, "o", "r", "state", "j.json", next, "back to a", []byte("a"))) + require.ErrorIs(t, f.WriteFileIfRevision(ctx, "o", "r", "state", "j.json", old, "stale", []byte("c")), ErrConflict) + require.ErrorIs(t, f.WriteFileIfRevision(ctx, "o", "r", "state", "j.json", "", "create", []byte("x")), ErrConflict) +} + +func TestFakeVersionedFileSeededRevisionAndCopies(t *testing.T) { + ctx := context.Background() + f := &FakeClient{FileContentsRef: map[string][]byte{"o/r/j.json@b": []byte("seed")}} + data, revision, err := f.ReadVersionedFile(ctx, "o", "r", "b", "j.json") + require.NoError(t, err) + require.NotEmpty(t, revision) + data[0] = 'x' + again, _, err := f.ReadVersionedFile(ctx, "o", "r", "b", "j.json") + require.NoError(t, err) + require.Equal(t, "seed", string(again)) + empty := &FakeClient{} + require.NoError(t, empty.WriteFileIfRevision(ctx, "o", "r", "b", "j.json", "", "create", []byte("content"))) +} diff --git a/internal/forge/forge.go b/internal/forge/forge.go index 5e98b197d0..ccea673d34 100644 --- a/internal/forge/forge.go +++ b/internal/forge/forge.go @@ -1196,6 +1196,18 @@ type Client interface { // Returns forge.ErrNotFound if the file or ref does not exist. GetFileContentAtRef(ctx context.Context, owner, repo, path, ref string) ([]byte, error) + // ReadVersionedFile reads a file and the revision of its last modification. + // The revision binds the complete file, not the repository's current head. + // GitLab supports this contract; other backends may return ErrNotSupported. + ReadVersionedFile(ctx context.Context, owner, repo, branch, path string) (content []byte, revision string, err error) + + // WriteFileIfRevision performs one conditional whole-file replacement. + // An empty revision creates only if absent; otherwise the revision must + // match the file's last modification. Conflicts wrap ErrConflict. The + // request is never retried after an ambiguous result. Callers authorize + // the control repository and path before invoking this operation. + WriteFileIfRevision(ctx context.Context, owner, repo, branch, path, revision, message string, content []byte) error + // CommitFiles atomically commits multiple files to the repository's // default branch in a single commit. It is idempotent: if all files // already have the expected content and mode, no commit is created diff --git a/internal/forge/github/versioned_file.go b/internal/forge/github/versioned_file.go new file mode 100644 index 0000000000..bb3dfb8d6c --- /dev/null +++ b/internal/forge/github/versioned_file.go @@ -0,0 +1,15 @@ +package github + +import ( + "context" + + "github.com/fullsend-ai/fullsend/internal/forge" +) + +// GitHub control-journal storage is not enabled before backend conformance. +func (c *LiveClient) ReadVersionedFile(context.Context, string, string, string, string) ([]byte, string, error) { + return nil, "", forge.ErrNotSupported +} +func (c *LiveClient) WriteFileIfRevision(context.Context, string, string, string, string, string, string, []byte) error { + return forge.ErrNotSupported +} diff --git a/internal/forge/github/versioned_file_test.go b/internal/forge/github/versioned_file_test.go new file mode 100644 index 0000000000..dc46a96a33 --- /dev/null +++ b/internal/forge/github/versioned_file_test.go @@ -0,0 +1,16 @@ +package github + +import ( + "context" + "testing" + + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/stretchr/testify/require" +) + +func TestJournalFileStorageNotEnabled(t *testing.T) { + c := &LiveClient{} + _, _, err := c.ReadVersionedFile(context.Background(), "o", "r", "b", "p") + require.ErrorIs(t, err, forge.ErrNotSupported) + require.ErrorIs(t, c.WriteFileIfRevision(context.Background(), "o", "r", "b", "p", "r", "m", nil), forge.ErrNotSupported) +} diff --git a/internal/forge/gitlab/versioned_file.go b/internal/forge/gitlab/versioned_file.go new file mode 100644 index 0000000000..89310a4721 --- /dev/null +++ b/internal/forge/gitlab/versioned_file.go @@ -0,0 +1,81 @@ +package gitlab + +import ( + "context" + "encoding/base64" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/fullsend-ai/fullsend/internal/forge" +) + +// ReadVersionedFile returns GitLab's last_commit_id, which is the precondition +// its file update API actually enforces. A branch tip is not equivalent. +func (c *LiveClient) ReadVersionedFile(ctx context.Context, owner, repo, branch, path string) ([]byte, string, error) { + apiPath := fmt.Sprintf("/projects/%s/repository/files/%s?ref=%s", projectPath(owner, repo), url.PathEscape(path), url.QueryEscape(branch)) + resp, err := c.get(ctx, apiPath) + if err != nil { + return nil, "", err + } + var f struct { + Content string `json:"content"` + Encoding string `json:"encoding"` + Revision string `json:"last_commit_id"` + } + if err = decodeJSON(resp, &f); err != nil { + return nil, "", err + } + if f.Revision == "" || f.Encoding != "base64" { + return nil, "", fmt.Errorf("versioned file metadata unavailable") + } + data, err := base64.StdEncoding.DecodeString(f.Content) + if err != nil { + return nil, "", fmt.Errorf("decode versioned file: %w", err) + } + return data, f.Revision, nil +} + +// WriteFileIfRevision never downgrades or retries a conditional write. +func (c *LiveClient) WriteFileIfRevision(ctx context.Context, owner, repo, branch, path, revision, message string, content []byte) error { + payload := map[string]string{"branch": branch, "content": base64.StdEncoding.EncodeToString(content), "encoding": "base64", "commit_message": message} + method := http.MethodPost + if revision != "" { + method = http.MethodPut + payload["last_commit_id"] = revision + } + apiPath := fmt.Sprintf("/projects/%s/repository/files/%s", projectPath(owner, repo), url.PathEscape(path)) + resp, err := c.doOnceNoRedirect(ctx, method, apiPath, payload) + if err == nil { + err = checkStatus(resp, http.StatusOK, http.StatusCreated) + if err == nil { + resp.Body.Close() + return nil + } + } + var apiErr *APIError + if errors.As(err, &apiErr) { + msg := strings.ToLower(apiErr.Message) + // Gitaly can reject the branch-reference CAS after the file revision + // check passed. This exact failed-precondition response proves that + // the reference update was rejected, rather than its ACK being lost. + referenceCASRejected := apiErr.StatusCode == http.StatusBadRequest && + apiErr.Message == "9:reference update: reference does not point to expected object." + if referenceCASRejected || apiErr.StatusCode == http.StatusConflict || apiErr.StatusCode == http.StatusNotFound || (apiErr.StatusCode == http.StatusBadRequest && (strings.Contains(msg, "already exists") || strings.Contains(msg, "changed") || strings.Contains(msg, "last_commit") || strings.Contains(msg, "empty"))) { + return fmt.Errorf("%w: versioned file changed or missing", forge.ErrConflict) + } + } + return err +} + +// doOnceNoRedirect prevents HTTP redirects from silently replaying a journal or +// scheduler write, even when the destination is on the same server. +func (c *LiveClient) doOnceNoRedirect(ctx context.Context, method, path string, body any) (*http.Response, error) { + single := *c + client := *c.http + client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + single.http = &client + return single.doAttempts(ctx, method, path, body, 1) +} diff --git a/internal/forge/gitlab/versioned_file_test.go b/internal/forge/gitlab/versioned_file_test.go new file mode 100644 index 0000000000..5e998e25da --- /dev/null +++ b/internal/forge/gitlab/versioned_file_test.go @@ -0,0 +1,133 @@ +package gitlab + +import ( + "context" + "encoding/base64" + "encoding/json" + "fmt" + "net/http" + "sync/atomic" + "testing" + + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/stretchr/testify/require" +) + +func TestReadVersionedFileRequiresLastCommit(t *testing.T) { + for _, body := range []string{`{"encoding":"base64","content":"eA==","last_commit_id":"file-revision"}`, `{"encoding":"base64","content":"eA=="}`, `{"encoding":"text","content":"x","last_commit_id":"r"}`, `{"encoding":"base64","content":"!","last_commit_id":"r"}`, `bad`} { + t.Run(body, func(t *testing.T) { + c, mux := setupTest(t) + mux.HandleFunc("GET /api/v4/projects/o%2Fr/repository/files/journal.json", func(w http.ResponseWriter, r *http.Request) { + require.Equal(t, "state", r.URL.Query().Get("ref")) + fmt.Fprint(w, body) + }) + data, rev, err := c.ReadVersionedFile(context.Background(), "o", "r", "state", "journal.json") + if body == `{"encoding":"base64","content":"eA==","last_commit_id":"file-revision"}` { + require.NoError(t, err) + require.Equal(t, "x", string(data)) + require.Equal(t, "file-revision", rev) + } else { + require.Error(t, err) + } + }) + } +} +func TestWriteVersionedFileUsesAtomicLastCommitGuard(t *testing.T) { + c, mux := setupTest(t) + var put atomic.Int32 + mux.HandleFunc("PUT /api/v4/projects/o%2Fr/repository/files/journal.json", func(w http.ResponseWriter, r *http.Request) { + put.Add(1) + var payload map[string]string + require.NoError(t, json.NewDecoder(r.Body).Decode(&payload)) + require.Equal(t, "file-revision", payload["last_commit_id"]) + require.Equal(t, "state", payload["branch"]) + require.Equal(t, base64.StdEncoding.EncodeToString([]byte("next")), payload["content"]) + fmt.Fprint(w, `{"file_path":"journal.json"}`) + }) + require.NoError(t, c.WriteFileIfRevision(context.Background(), "o", "r", "state", "journal.json", "file-revision", "checkpoint [skip ci]", []byte("next"))) + require.Equal(t, int32(1), put.Load()) +} +func TestVersionedWriteConflictAndNoRetry(t *testing.T) { + for _, status := range []int{http.StatusBadRequest, http.StatusConflict, http.StatusNotFound, http.StatusInternalServerError, http.StatusTooManyRequests, http.StatusForbidden} { + t.Run(fmt.Sprint(status), func(t *testing.T) { + c, mux := setupTest(t) + var calls atomic.Int32 + mux.HandleFunc("PUT /api/v4/projects/o%2Fr/repository/files/journal.json", func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + w.WriteHeader(status) + fmt.Fprint(w, `{"message":"file has changed"}`) + }) + err := c.WriteFileIfRevision(context.Background(), "o", "r", "state", "journal.json", "old", "checkpoint", []byte("x")) + require.Error(t, err) + if status == 400 || status == 404 || status == 409 { + require.ErrorIs(t, err, forge.ErrConflict) + } + require.Equal(t, int32(1), calls.Load()) + }) + } +} +func TestVersionedCreateNeverUpserts(t *testing.T) { + c, mux := setupTest(t) + mux.HandleFunc("POST /api/v4/projects/o%2Fr/repository/files/journal.json", func(w http.ResponseWriter, r *http.Request) { + var payload map[string]string + require.NoError(t, json.NewDecoder(r.Body).Decode(&payload)) + require.NotContains(t, payload, "last_commit_id") + w.WriteHeader(http.StatusBadRequest) + fmt.Fprint(w, `{"message":"A file with this name already exists"}`) + }) + require.ErrorIs(t, c.WriteFileIfRevision(context.Background(), "o", "r", "state", "journal.json", "", "initialize", []byte("x")), forge.ErrConflict) +} + +func TestVersionedWriteRecognizesOnlyExactReferenceRaceRejection(t *testing.T) { + const rejection = "9:reference update: reference does not point to expected object." + for _, tc := range []struct { + name string + status int + message string + conflict bool + }{ + {"reference CAS rejected", http.StatusBadRequest, rejection, true}, + {"unknown bad request", http.StatusBadRequest, "reference update failed", false}, + {"same text in server failure", http.StatusInternalServerError, rejection, false}, + {"same text in permission failure", http.StatusForbidden, rejection, false}, + {"same text in rate limit", http.StatusTooManyRequests, rejection, false}, + {"extra suffix is not proof", http.StatusBadRequest, rejection + " Response acknowledgement lost.", false}, + {"extra prefix is not proof", http.StatusBadRequest, "Unknown failure: " + rejection, false}, + } { + t.Run(tc.name, func(t *testing.T) { + c, mux := setupTest(t) + var calls atomic.Int32 + mux.HandleFunc("PUT /api/v4/projects/o%2Fr/repository/files/journal.json", func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + w.WriteHeader(tc.status) + require.NoError(t, json.NewEncoder(w).Encode(map[string]string{"message": tc.message})) + }) + err := c.WriteFileIfRevision(context.Background(), "o", "r", "state", "journal.json", "old", "checkpoint", []byte("next")) + require.Error(t, err) + if tc.conflict { + require.ErrorIs(t, err, forge.ErrConflict) + } else { + require.NotErrorIs(t, err, forge.ErrConflict) + } + require.Equal(t, int32(1), calls.Load(), "the transport must never replay a conditional write") + }) + } +} + +func TestJournalWriteNeverFollowsRedirect(t *testing.T) { + c, mux := setupTest(t) + var calls, redirects atomic.Int32 + mux.HandleFunc("PUT /api/v4/projects/o%2Fr/repository/files/journal.json", func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + w.Header().Set("Location", "/unexpected") + w.WriteHeader(http.StatusTemporaryRedirect) + }) + mux.HandleFunc("/unexpected", func(w http.ResponseWriter, r *http.Request) { + redirects.Add(1) + w.WriteHeader(http.StatusCreated) + }) + err := c.WriteFileIfRevision(context.Background(), "o", "r", "state", "journal.json", "old", "checkpoint", []byte(`{}`)) + require.Error(t, err) + require.EqualValues(t, 1, calls.Load()) + require.Zero(t, redirects.Load()) +} diff --git a/internal/journal/forge.go b/internal/journal/forge.go new file mode 100644 index 0000000000..c5448a422c --- /dev/null +++ b/internal/journal/forge.go @@ -0,0 +1,145 @@ +package journal + +import ( + "bytes" + "context" + "errors" + "fmt" + "path" + "strings" + + "github.com/fullsend-ai/fullsend/internal/forge" +) + +type Location struct{ Owner, Repo, Branch, Path string } + +// AuthorizeFunc checks independently configured trusted host identity and scope. +// Journal contents are never proof of authorization. Assessment sandboxes do not receive this capability. +type AuthorizeFunc func(context.Context, Location, string) error + +type ForgeBackend struct { + client forge.Client + location Location + authorize AuthorizeFunc +} + +func NewForgeBackend(client forge.Client, location Location, authorize AuthorizeFunc) (*ForgeBackend, error) { + if client == nil || authorize == nil || location.Owner == "" || location.Repo == "" || location.Branch == "" || location.Path == "" || strings.HasPrefix(location.Path, "/") || path.Clean(location.Path) != location.Path || strings.HasPrefix(location.Path, "../") || !strings.HasSuffix(location.Path, ".json") { + return nil, ErrIntegrity + } + return &ForgeBackend{client: client, location: location, authorize: authorize}, nil +} +func (b *ForgeBackend) Initialize(ctx context.Context) error { + if err := b.authorize(ctx, b.location, "initialize"); err != nil { + return err + } + // Requiring an existing branch avoids silently constructing a control boundary. + if _, err := b.client.GetBranchRef(ctx, b.location.Owner, b.location.Repo, b.location.Branch); err != nil { + return err + } + content, err := Encode(Empty()) + if err != nil { + return err + } + err = b.client.WriteFileIfRevision(ctx, b.location.Owner, b.location.Repo, b.location.Branch, b.location.Path, "", "Initialize Fullsend journal [skip ci]", content) + if errors.Is(err, forge.ErrConflict) { + return ErrConflict + } + return conflict(err) +} +func (b *ForgeBackend) Load(ctx context.Context) (Document, string, error) { + if err := b.authorize(ctx, b.location, "read"); err != nil { + return Document{}, "", nonretryableReadError(err) + } + data, rev, err := b.client.ReadVersionedFile(ctx, b.location.Owner, b.location.Repo, b.location.Branch, b.location.Path) + if err != nil { + return Document{}, "", conflict(nonretryableReadError(err)) + } + if rev == "" { + return Document{}, "", ErrIntegrity + } + d, err := Decode(data) + return d, rev, err +} +func (b *ForgeBackend) CompareAndSwap(ctx context.Context, rev string, d Document) (string, error) { + if rev == "" { + return "", ErrConflict + } + if err := b.authorize(ctx, b.location, "write"); err != nil { + // Only the conditional write may supply a retryable revision conflict. + if errors.Is(err, ErrConflict) { + return "", fmt.Errorf("journal write authorization rejected: %v", err) + } + return "", err + } + data, err := Encode(d) + if err != nil { + return "", err + } + err = b.client.WriteFileIfRevision(ctx, b.location.Owner, b.location.Repo, b.location.Branch, b.location.Path, rev, "Checkpoint Fullsend journal [skip ci]", data) + if definitiveWriteConflict(err) { + return "", ErrConflict + } + if err != nil { + return "", fmt.Errorf("%w: write acknowledgement failed: %v", ErrUncertain, err) + } + // Verification failure is deliberately an uncertain write, never a blind retry. + current, newRev, err := b.client.ReadVersionedFile(ctx, b.location.Owner, b.location.Repo, b.location.Branch, b.location.Path) + if err != nil { + // Do not wrap the underlying error: even a read-side conflict cannot + // make this possibly committed write safe to retry. + return "", fmt.Errorf("%w: readback failed: %v", ErrUncertain, err) + } + observed, err := Decode(current) + if err != nil || newRev == "" { + return "", fmt.Errorf("%w: invalid checkpoint readback", ErrUncertain) + } + if id, ok := ctx.Value(checkpointRecordKey{}).(string); ok { + intended, exists := d.Records[id] + actual, found := observed.Records[id] + // The full parent revision still guards the write above. Only the + // subsequent proof is record-specific. Any target change, including + // lease renewal or release, remains uncertain; it cannot grant authority. + if !exists || !found || !sameJSON(intended, actual) { + return "", fmt.Errorf("%w: checkpoint record changed before verification", ErrUncertain) + } + } else if !bytes.Equal(current, data) { + // Direct backend users supply no single-record transaction proof. + return "", fmt.Errorf("%w: checkpoint changed before verification", ErrUncertain) + } + return newRev, nil +} + +// definitiveWriteConflict requires every leaf to be the forge's conditional +// rejection sentinel. errors.Is alone also accepts mixed lost-ACK/conflict joins. +// Unknown wrappers with custom Is methods cannot prove non-commitment. +func definitiveWriteConflict(err error) bool { + if err == forge.ErrConflict { + return true + } + switch wrapped := err.(type) { + case interface{ Unwrap() []error }: + children := wrapped.Unwrap() + if len(children) == 0 { + return false + } + for _, child := range children { + if !definitiveWriteConflict(child) { + return false + } + } + return true + case interface{ Unwrap() error }: + return definitiveWriteConflict(wrapped.Unwrap()) + default: + return false + } +} + +// A read or authorization failure says nothing about conditional-write rejection. +func nonretryableReadError(err error) error { + if errors.Is(err, ErrConflict) { + return fmt.Errorf("journal pre-write failure: %v", err) + } + return err +} diff --git a/internal/journal/forge_checkpoint_test.go b/internal/journal/forge_checkpoint_test.go new file mode 100644 index 0000000000..d7cffdda36 --- /dev/null +++ b/internal/journal/forge_checkpoint_test.go @@ -0,0 +1,231 @@ +package journal + +import ( + "bytes" + "context" + "errors" + "fmt" + "testing" + "time" + + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/stretchr/testify/require" +) + +// checkpointClient injects a second writer strictly after the conditional write. +type checkpointClient struct { + forge.Client + afterWrite func() + writeError error + readError error + emptyRevision bool +} + +func (c *checkpointClient) WriteFileIfRevision(ctx context.Context, owner, repo, branch, path, revision, message string, content []byte) error { + if err := c.Client.WriteFileIfRevision(ctx, owner, repo, branch, path, revision, message, content); err != nil { + return err + } + if c.afterWrite != nil { + c.afterWrite() + } + return c.writeError +} +func (c *checkpointClient) ReadVersionedFile(ctx context.Context, owner, repo, branch, path string) ([]byte, string, error) { + data, rev, err := c.Client.ReadVersionedFile(ctx, owner, repo, branch, path) + if c.readError != nil { + return nil, "", c.readError + } + if c.emptyRevision { + rev = "" + } + return data, rev, err +} +func checkpointFixture(t *testing.T) (*Engine, *ForgeBackend, *checkpointClient, *forge.FakeClient) { + t.Helper() + fc := forge.NewFakeClient() + fc.BranchRefs["o/r/state"] = "tip" + client := &checkpointClient{Client: fc} + b, err := NewForgeBackend(client, Location{"o", "r", "state", "journal.json"}, func(context.Context, Location, string) error { return nil }) + require.NoError(t, err) + require.NoError(t, b.Initialize(context.Background())) + return New(b, nil), b, client, fc +} +func mutateCheckpoint(t *testing.T, fc *forge.FakeClient, mutate func(*Document)) { + t.Helper() + raw, rev, err := fc.ReadVersionedFile(context.Background(), "o", "r", "state", "journal.json") + require.NoError(t, err) + d, err := Decode(raw) + require.NoError(t, err) + mutate(&d) + data, err := Encode(d) + require.NoError(t, err) + require.NoError(t, fc.WriteFileIfRevision(context.Background(), "o", "r", "state", "journal.json", rev, "concurrent checkpoint", data)) +} +func TestCheckpointUnrelatedRecordAdvance(t *testing.T) { + e, _, client, fc := checkpointFixture(t) + client.afterWrite = func() { + mutateCheckpoint(t, fc, func(d *Document) { + d.Records["other"] = Record{ID: "other", Binding: "other-binding", Data: []byte(`{}`), Counters: map[string]uint64{}, Effects: map[string]Effect{}} + }) + } + _, err := e.Admit(context.Background(), "target", "binding", []byte(`{}`)) + require.NoError(t, err) +} +func TestCheckpointUncertainOutcomes(t *testing.T) { + for _, scenario := range []string{"lost-ack", "read-error", "read-conflict", "empty-revision", "checksum", "removed", "owner", "binding", "counter", "effect", "data", "renewal"} { + t.Run(scenario, func(t *testing.T) { + e, _, client, fc := checkpointFixture(t) + switch scenario { + case "lost-ack": + client.writeError = errors.New("response lost") + case "read-error": + client.afterWrite = func() { client.readError = errors.New("response lost") } + case "read-conflict": + client.afterWrite = func() { client.readError = forge.ErrConflict } + case "empty-revision": + client.afterWrite = func() { client.emptyRevision = true } + case "checksum": + client.afterWrite = func() { + fc.FileContentsRef["o/r/journal.json@state"] = bytes.Replace(fc.FileContentsRef["o/r/journal.json@state"], []byte(`"binding": "binding"`), []byte(`"binding": "tampered"`), 1) + } + default: + client.afterWrite = func() { + mutateCheckpoint(t, fc, func(d *Document) { + r := d.Records["target"] + switch scenario { + case "removed": + delete(d.Records, "target") + return + case "owner": + r.Generation++ + r.Lease = Lease{Owner: "other", Generation: r.Generation} + case "binding": + r.Binding = "different" + case "counter": + r.Counters["writes"]++ + case "effect": + r.Effects["effect"] = Effect{ID: "effect", Kind: "tracker", Binding: "x", Status: EffectIntended} + case "data": + r.Data = []byte(`{"changed":true}`) + case "renewal": + r.Lease.ExpiresAt = r.Lease.ExpiresAt.Add(1) + } + d.Records["target"] = r + }) + } + } + _, err := e.Admit(context.Background(), "target", "binding", []byte(`{}`)) + require.ErrorIs(t, err, ErrUncertain) + require.NotErrorIs(t, err, ErrConflict) + }) + } +} +func TestCheckpointDirectBackendRequiresExactDocument(t *testing.T) { + _, b, client, fc := checkpointFixture(t) + d, rev, err := b.Load(context.Background()) + require.NoError(t, err) + client.afterWrite = func() { + mutateCheckpoint(t, fc, func(d *Document) { + d.Records["other"] = Record{ID: "other", Binding: "b", Data: []byte(`{}`), Counters: map[string]uint64{}, Effects: map[string]Effect{}} + }) + } + _, err = b.CompareAndSwap(context.Background(), rev, d) + require.ErrorIs(t, err, ErrUncertain) + require.NotErrorIs(t, err, ErrConflict) +} + +func TestCheckpointAllEngineTransactionsTolerateUnrelatedAdvance(t *testing.T) { + for _, operation := range []string{"claim", "update", "rebind", "renew", "release"} { + t.Run(operation, func(t *testing.T) { + ctx := context.Background() + e, _, client, fc := checkpointFixture(t) + _, err := e.Admit(ctx, "target", "binding", []byte(`{}`)) + require.NoError(t, err) + var lease Lease + if operation != "claim" { + lease, err = e.Claim(ctx, "target", "owner", time.Hour) + require.NoError(t, err) + } + client.afterWrite = func() { + mutateCheckpoint(t, fc, func(d *Document) { + d.Records["other"] = Record{ID: "other", Binding: "b", Data: []byte(`{}`), Counters: map[string]uint64{}, Effects: map[string]Effect{}} + }) + } + switch operation { + case "claim": + _, err = e.Claim(ctx, "target", "owner", time.Hour) + case "update": + _, err = e.Spend(ctx, "target", lease, "writes", 1) + case "rebind": + _, err = e.Rebind(ctx, "target", lease, "new-binding", []byte(`{"new":true}`)) + case "renew": + _, err = e.Renew(ctx, "target", lease, 2*time.Hour) + case "release": + err = e.Release(ctx, "target", lease) + } + require.NoError(t, err) + }) + } +} + +func TestCheckpointDefinitiveRejectionIsOnlyConflict(t *testing.T) { + _, b, client, _ := checkpointFixture(t) + client.afterWrite = func() { t.Fatal("stale revision must not write") } + _, err := b.CompareAndSwap(context.Background(), "stale", Empty()) + require.ErrorIs(t, err, ErrConflict) + require.NotErrorIs(t, err, ErrUncertain) +} + +func TestCheckpointMixedWriteConflictIsUncertain(t *testing.T) { + e, _, client, _ := checkpointFixture(t) + client.writeError = errors.Join(forge.ErrConflict, errors.New("lost acknowledgement")) + _, err := e.Admit(context.Background(), "target", "binding", []byte(`{}`)) + require.ErrorIs(t, err, ErrUncertain) + require.NotErrorIs(t, err, ErrConflict) +} + +func TestCheckpointAuthorizationCannotSupplyRetryableConflict(t *testing.T) { + _, b, _, _ := checkpointFixture(t) + b.authorize = func(context.Context, Location, string) error { return ErrConflict } + _, err := b.CompareAndSwap(context.Background(), "revision", Empty()) + require.Error(t, err) + require.NotErrorIs(t, err, ErrConflict) +} + +func TestDefinitiveWriteConflict(t *testing.T) { + for _, tc := range []struct { + name string + err error + definite bool + }{ + {"nil", nil, false}, + {"plain", forge.ErrConflict, true}, + {"wrapped", fmt.Errorf("write: %w", forge.ErrConflict), true}, + {"joined-conflicts", errors.Join(forge.ErrConflict, fmt.Errorf("write: %w", forge.ErrConflict)), true}, + {"mixed", errors.Join(forge.ErrConflict, errors.New("unknown")), false}, + {"empty-join", emptyConflictJoin{}, false}, + } { + t.Run(tc.name, func(t *testing.T) { require.Equal(t, tc.definite, definitiveWriteConflict(tc.err)) }) + } +} + +type emptyConflictJoin struct{} + +func (emptyConflictJoin) Error() string { return "empty" } +func (emptyConflictJoin) Unwrap() []error { return nil } + +func TestCheckpointLoadCannotSupplyRetryableConflict(t *testing.T) { + for _, source := range []string{"authorization", "storage"} { + t.Run(source, func(t *testing.T) { + _, b, client, _ := checkpointFixture(t) + if source == "authorization" { + b.authorize = func(context.Context, Location, string) error { return ErrConflict } + } else { + client.readError = fmt.Errorf("read: %w", ErrConflict) + } + _, _, err := b.Load(context.Background()) + require.Error(t, err) + require.NotErrorIs(t, err, ErrConflict) + }) + } +} diff --git a/internal/journal/forge_test.go b/internal/journal/forge_test.go new file mode 100644 index 0000000000..63c6af68b2 --- /dev/null +++ b/internal/journal/forge_test.go @@ -0,0 +1,79 @@ +package journal + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/stretchr/testify/require" +) + +func TestForgeBackendAuthorityAndInitialization(t *testing.T) { + ctx := context.Background() + fc := forge.NewFakeClient() + location := Location{"o", "r", "state", "journal.json"} + denied := errors.New("denied") + _, err := NewForgeBackend(fc, location, nil) + require.Error(t, err) + for _, path := range []string{"", "../journal.json", "/journal.json", "dir/../journal.json", "file.txt"} { + bad := location + bad.Path = path + _, err = NewForgeBackend(fc, bad, func(context.Context, Location, string) error { return nil }) + require.Error(t, err) + } + b, err := NewForgeBackend(fc, location, func(context.Context, Location, string) error { return denied }) + require.NoError(t, err) + require.ErrorIs(t, b.Initialize(ctx), denied) + _, _, err = b.Load(ctx) + require.ErrorIs(t, err, denied) + _, err = b.CompareAndSwap(ctx, "rev", Empty()) + require.ErrorIs(t, err, denied) + b.authorize = func(context.Context, Location, string) error { return nil } + require.ErrorIs(t, b.Initialize(ctx), forge.ErrNotFound) + fc.BranchRefs["o/r/state"] = "tip" + require.NoError(t, b.Initialize(ctx)) + require.ErrorIs(t, b.Initialize(ctx), ErrConflict) + d, rev, err := b.Load(ctx) + require.NoError(t, err) + require.Equal(t, 1, d.SchemaVersion) + require.NotEmpty(t, rev) + _, err = b.CompareAndSwap(ctx, "stale", d) + require.ErrorIs(t, err, ErrConflict) + _, err = b.CompareAndSwap(ctx, "", d) + require.ErrorIs(t, err, ErrConflict) + fc.FileContentsRef["o/r/journal.json@state"] = []byte(`bad`) + _, _, err = b.Load(ctx) + require.ErrorIs(t, err, ErrIntegrity) +} + +type lostAck struct { + Backend + failed bool +} + +func (b *lostAck) CompareAndSwap(ctx context.Context, rev string, d Document) (string, error) { + newRev, err := b.Backend.CompareAndSwap(ctx, rev, d) + if err != nil { + return newRev, err + } + if b.failed { + return newRev, nil + } + b.failed = true + return "", errors.New("response lost") +} +func TestLostCheckpointAcknowledgementRetainsIntent(t *testing.T) { + ctx := context.Background() + e, b, _, now := fixture(t) + l := admitted(t, e) + _, err := e.Intent(ctx, "case-1", l, Effect{ID: "create", Kind: "tracker", Binding: "sha"}) + require.NoError(t, err) + broken := New(&lostAck{Backend: b}, func() time.Time { return *now }) + _, err = broken.Effect(ctx, "case-1", l, "create", EffectInFlight, nil) + require.Error(t, err) + r, err := New(b, nil).Read(ctx, "case-1") + require.NoError(t, err) + require.Equal(t, EffectInFlight, r.Effects["create"].Status) +} diff --git a/internal/journal/journal.go b/internal/journal/journal.go new file mode 100644 index 0000000000..eaa9d93427 --- /dev/null +++ b/internal/journal/journal.go @@ -0,0 +1,454 @@ +// Package journal records recoverable host operations in one conditionally written document. +package journal + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "reflect" + "regexp" + "time" +) + +var ( + ErrConflict = errors.New("journal revision conflict") + // ErrUncertain means a checkpoint may have committed and must not be blindly retried. + ErrUncertain = errors.New("journal checkpoint outcome uncertain") + ErrIntegrity = errors.New("journal integrity failure") + ErrOwnership = errors.New("journal ownership rejected") + ErrBinding = errors.New("journal input binding changed") + ErrNotFound = errors.New("journal operation not found") + ErrTransition = errors.New("journal transition rejected") + ErrBudget = errors.New("journal budget exhausted") +) + +const MaxDocumentBytes = 4 << 20 +const ( + EffectIntended = "intended" + EffectInFlight = "in_flight" + EffectAmbiguous = "ambiguous" + EffectConfirmed = "confirmed" +) + +var identity = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_.:-]{0,255}$`) + +type Lease struct { + Owner string `json:"owner"` + Generation uint64 `json:"generation"` + ExpiresAt time.Time `json:"expires_at"` +} +type Effect struct { + ID string `json:"id"` + Kind string `json:"kind"` + Binding string `json:"binding"` + Status string `json:"status"` + Receipt json.RawMessage `json:"receipt,omitempty"` +} +type Record struct { + ID string `json:"id"` + Binding string `json:"binding"` + Generation uint64 `json:"generation"` + Lease Lease `json:"lease"` + Data json.RawMessage `json:"data"` + Counters map[string]uint64 `json:"counters"` + Effects map[string]Effect `json:"effects"` +} +type Document struct { + SchemaVersion int `json:"schema_version"` + Records map[string]Record `json:"records"` + Checksum string `json:"checksum"` +} + +// Backend must atomically replace the entire document only at the supplied revision. +// There is no retry after an ambiguous write. All effect authority lives in this one file. +type Backend interface { + Load(context.Context) (Document, string, error) + CompareAndSwap(context.Context, string, Document) (string, error) +} +type Engine struct { + backend Backend + clock func() time.Time +} + +func New(backend Backend, clock func() time.Time) *Engine { + if clock == nil { + clock = time.Now + } + return &Engine{backend: backend, clock: clock} +} +func Empty() Document { return Document{SchemaVersion: 1, Records: map[string]Record{}} } +func clone[T any](v T) T { + b, _ := json.Marshal(v) + var result T + _ = json.Unmarshal(b, &result) + return result +} +func (e *Engine) load(ctx context.Context) (Document, string, error) { + if e.backend == nil { + return Document{}, "", ErrIntegrity + } + d, r, err := e.backend.Load(ctx) + if err != nil { + return d, r, err + } + if err = validateDocument(d); err != nil { + return d, r, err + } + return d, r, nil +} + +// loadMutation fences even idempotent mutations against every required parent. +// Reads intentionally bypass this guard so changed admissions remain recoverable. +func (e *Engine) loadMutation(ctx context.Context) (Document, string, error) { + d, rev, err := e.load(ctx) + if err != nil { + return d, rev, err + } + if guard, ok := e.backend.(interface{ validateMutation(Document) error }); ok { + if err := guard.validateMutation(d); err != nil { + return d, rev, err + } + } + return d, rev, nil +} + +func (e *Engine) Read(ctx context.Context, id string) (*Record, error) { + d, _, err := e.load(ctx) + if err != nil { + return nil, err + } + r, ok := d.Records[id] + if !ok { + return nil, ErrNotFound + } + return &r, nil +} + +// checkpointRecordKey is private: only Engine transactions identify the one record +// whose exact readback can prove their outcome after unrelated records advance. +type checkpointRecordKey struct{} + +func (e *Engine) save(ctx context.Context, d Document, rev, id string) error { + if err := validateDocument(d); err != nil { + return err + } + _, err := e.backend.CompareAndSwap(context.WithValue(ctx, checkpointRecordKey{}, id), rev, d) + return err +} +func (e *Engine) Admit(ctx context.Context, id, binding string, data json.RawMessage) (*Record, error) { + if !identity.MatchString(id) || binding == "" || !json.Valid(data) { + return nil, ErrIntegrity + } + d, rev, err := e.loadMutation(ctx) + if err != nil { + return nil, err + } + if old, ok := d.Records[id]; ok { + if old.Binding != binding { + return nil, ErrBinding + } + return &old, nil + } + r := Record{ID: id, Binding: binding, Data: clone(data), Counters: map[string]uint64{}, Effects: map[string]Effect{}} + d.Records[id] = r + if err = e.save(ctx, d, rev, id); err != nil { + return nil, err + } + return &r, nil +} +func (e *Engine) Claim(ctx context.Context, id, owner string, ttl time.Duration) (Lease, error) { + if !identity.MatchString(owner) || ttl <= 0 || ttl > 24*time.Hour { + return Lease{}, ErrOwnership + } + d, rev, err := e.loadMutation(ctx) + if err != nil { + return Lease{}, err + } + r, ok := d.Records[id] + if !ok { + return Lease{}, ErrNotFound + } + if r.Lease.Owner != "" && r.Lease.ExpiresAt.After(e.clock()) { + return Lease{}, ErrOwnership + } + if r.Generation == ^uint64(0) { + return Lease{}, ErrOwnership + } + r.Generation++ + r.Lease = Lease{Owner: owner, Generation: r.Generation, ExpiresAt: e.clock().UTC().Add(ttl)} + d.Records[id] = r + if err = e.save(ctx, d, rev, id); err != nil { + return Lease{}, err + } + return r.Lease, nil +} +func (e *Engine) owns(r Record, l Lease) bool { + return l.Owner != "" && r.Lease.Owner == l.Owner && r.Generation == l.Generation && r.Lease.Generation == l.Generation && r.Lease.ExpiresAt.After(e.clock()) +} + +// Update is a single CAS transaction. A conflict requires caller re-evaluation. +// Identity/lease fields are immutable; counters cannot fall and effects cannot be erased. +func (e *Engine) Update(ctx context.Context, id string, l Lease, update func(*Record) error) (*Record, error) { + d, rev, err := e.loadMutation(ctx) + if err != nil { + return nil, err + } + old, ok := d.Records[id] + if !ok { + return nil, ErrNotFound + } + if !e.owns(old, l) { + return nil, ErrOwnership + } + next := clone(old) + if update == nil { + return nil, ErrTransition + } + if err = update(&next); err != nil { + return nil, err + } + if err = validateTransition(old, next); err != nil { + return nil, err + } + if !e.owns(old, l) { + return nil, ErrOwnership + } + if sameJSON(old, next) { + return &next, nil + } + d.Records[id] = next + if err = e.save(ctx, d, rev, id); err != nil { + return nil, err + } + return &next, nil +} +func (e *Engine) Rebind(ctx context.Context, id string, l Lease, binding string, data json.RawMessage) (*Record, error) { + if binding == "" || !json.Valid(data) { + return nil, ErrBinding + } + d, rev, err := e.loadMutation(ctx) + if err != nil { + return nil, err + } + r, ok := d.Records[id] + if !ok { + return nil, ErrNotFound + } + if !e.owns(r, l) { + return nil, ErrOwnership + } + r.Binding = binding + r.Data = clone(data) + d.Records[id] = r + if err = e.save(ctx, d, rev, id); err != nil { + return nil, err + } + return &r, nil +} +func (e *Engine) Renew(ctx context.Context, id string, l Lease, ttl time.Duration) (Lease, error) { + if ttl <= 0 || ttl > 24*time.Hour { + return Lease{}, ErrOwnership + } + d, rev, err := e.loadMutation(ctx) + if err != nil { + return Lease{}, err + } + r, ok := d.Records[id] + if !ok { + return Lease{}, ErrNotFound + } + if !e.owns(r, l) { + return Lease{}, ErrOwnership + } + r.Lease.ExpiresAt = e.clock().UTC().Add(ttl) + d.Records[id] = r + if err = e.save(ctx, d, rev, id); err != nil { + return Lease{}, err + } + return r.Lease, nil +} +func (e *Engine) Release(ctx context.Context, id string, l Lease) error { + d, rev, err := e.loadMutation(ctx) + if err != nil { + return err + } + r, ok := d.Records[id] + if !ok { + return ErrNotFound + } + if !e.owns(r, l) { + return ErrOwnership + } + r.Lease.Owner = "" + r.Lease.ExpiresAt = time.Time{} + d.Records[id] = r + return e.save(ctx, d, rev, id) +} +func (e *Engine) Spend(ctx context.Context, id string, l Lease, counter string, limit uint64) (*Record, error) { + return e.Update(ctx, id, l, func(r *Record) error { + if !identity.MatchString(counter) { + return ErrIntegrity + } + if r.Counters[counter] >= limit { + return ErrBudget + } + r.Counters[counter]++ + return nil + }) +} +func (e *Engine) Intent(ctx context.Context, id string, l Lease, effect Effect) (*Record, error) { + return e.Update(ctx, id, l, func(r *Record) error { + if old, ok := r.Effects[effect.ID]; ok { + if old.Kind != effect.Kind || old.Binding != effect.Binding { + return ErrBinding + } + return nil + } + effect.Status = "intended" + effect.Receipt = nil + r.Effects[effect.ID] = effect + return nil + }) +} +func (e *Engine) Effect(ctx context.Context, id string, l Lease, effectID, status string, receipt json.RawMessage) (*Record, error) { + return e.Update(ctx, id, l, func(r *Record) error { + effect, ok := r.Effects[effectID] + if !ok { + return ErrNotFound + } + if effect.Status == EffectInFlight && status == EffectInFlight { + return ErrTransition + } + effect.Status = status + effect.Receipt = append(json.RawMessage(nil), receipt...) + r.Effects[effectID] = effect + return nil + }) +} +func validateTransition(old, next Record) error { + if old.ID != next.ID || old.Binding != next.Binding || old.Generation != next.Generation || !reflect.DeepEqual(old.Lease, next.Lease) { + return ErrTransition + } + for key, value := range old.Counters { + if next.Counters[key] < value { + return ErrBudget + } + } + for key, before := range old.Effects { + after, ok := next.Effects[key] + if !ok || before.ID != after.ID || before.Kind != after.Kind || before.Binding != after.Binding { + return ErrTransition + } + allowed := map[string]map[string]bool{"intended": {"in_flight": true, "confirmed": true}, "in_flight": {"ambiguous": true, "confirmed": true}, "ambiguous": {"confirmed": true}, "confirmed": {}} + if before.Status != after.Status && !allowed[before.Status][after.Status] { + return ErrTransition + } + if before.Status == "confirmed" && !sameJSON(before.Receipt, after.Receipt) { + return ErrTransition + } + } + for key, after := range next.Effects { + if _, exists := old.Effects[key]; !exists && after.Status != "intended" { + return ErrTransition + } + } + return nil +} +func validateDocument(d Document) error { + if d.SchemaVersion != 1 || d.Records == nil || len(d.Records) > 1000 { + return ErrIntegrity + } + for key, r := range d.Records { + if !identity.MatchString(key) || r.ID != key || r.Binding == "" || len(r.Binding) > 1024 || strictDecode(r.Data, new(any)) != nil || r.Counters == nil || r.Effects == nil || len(r.Counters) > 256 || len(r.Effects) > 1000 { + return ErrIntegrity + } + if r.Lease.Generation != r.Generation && r.Lease.Owner != "" { + return ErrIntegrity + } + for counter := range r.Counters { + if !identity.MatchString(counter) { + return ErrIntegrity + } + } + for key, effect := range r.Effects { + if key != effect.ID || !identity.MatchString(key) || !identity.MatchString(effect.Kind) || effect.Binding == "" || len(effect.Binding) > 1024 { + return ErrIntegrity + } + switch effect.Status { + case "intended", "in_flight", "ambiguous": + if len(effect.Receipt) > 0 { + return ErrIntegrity + } + case "confirmed": + if strictDecode(effect.Receipt, new(any)) != nil || bytes.Equal(bytes.TrimSpace(effect.Receipt), []byte("null")) { + return ErrIntegrity + } + default: + return ErrIntegrity + } + } + } + return nil +} +func checksum(d Document) (string, error) { + d.Checksum = "" + data, err := json.Marshal(d) + if err != nil { + return "", ErrIntegrity + } + sum := sha256.Sum256(data) + return hex.EncodeToString(sum[:]), nil +} +func Encode(d Document) ([]byte, error) { + if err := validateDocument(d); err != nil { + return nil, err + } + sum, err := checksum(d) + if err != nil { + return nil, err + } + d.Checksum = sum + b, err := json.MarshalIndent(d, "", " ") + if err != nil || len(b) > MaxDocumentBytes { + return nil, ErrIntegrity + } + return b, nil +} +func Decode(data []byte) (Document, error) { + var d Document + if len(data) > MaxDocumentBytes { + return d, ErrIntegrity + } + if err := strictDecode(data, &d); err != nil { + return d, ErrIntegrity + } + if err := validateDocument(d); err != nil { + return d, err + } + sum, err := checksum(d) + if err != nil || sum != d.Checksum { + return d, ErrIntegrity + } + return d, nil +} +func conflict(err error) error { + if err == nil { + return nil + } + return fmt.Errorf("journal storage: %w", err) +} + +// JSON transport may reindent RawMessage fields. Preserve receipt meaning while +// ignoring representation-only whitespace introduced by durable encoding. +func sameJSON(left, right any) bool { + a, err := json.Marshal(left) + if err != nil { + return false + } + b, err := json.Marshal(right) + return err == nil && bytes.Equal(a, b) +} diff --git a/internal/journal/journal_test.go b/internal/journal/journal_test.go new file mode 100644 index 0000000000..b82af1d424 --- /dev/null +++ b/internal/journal/journal_test.go @@ -0,0 +1,234 @@ +package journal + +import ( + "context" + "encoding/json" + "errors" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/stretchr/testify/require" +) + +func fixture(t *testing.T) (*Engine, *ForgeBackend, *forge.FakeClient, *time.Time) { + t.Helper() + fc := forge.NewFakeClient() + fc.BranchRefs["o/r/state"] = "head" + b, err := NewForgeBackend(fc, Location{"o", "r", "state", "journal.json"}, func(context.Context, Location, string) error { return nil }) + require.NoError(t, err) + require.NoError(t, b.Initialize(context.Background())) + now := time.Date(2026, 11, 12, 12, 0, 0, 0, time.UTC) + return New(b, func() time.Time { return now }), b, fc, &now +} +func admitted(t *testing.T, e *Engine) Lease { + t.Helper() + _, err := e.Admit(context.Background(), "case-1", "binding-1", json.RawMessage(`{"required":["a","b"]}`)) + require.NoError(t, err) + l, err := e.Claim(context.Background(), "case-1", "host-1", time.Minute) + require.NoError(t, err) + return l +} + +func TestAdmissionOwnershipAndRestart(t *testing.T) { + ctx := context.Background() + e, b, _, now := fixture(t) + l := admitted(t, e) + r, err := e.Admit(ctx, "case-1", "binding-1", json.RawMessage(`{}`)) + require.NoError(t, err) + require.Contains(t, string(r.Data), "required") + _, err = e.Admit(ctx, "case-1", "different", json.RawMessage(`{}`)) + require.ErrorIs(t, err, ErrBinding) + _, err = e.Claim(ctx, "case-1", "host-2", time.Minute) + require.ErrorIs(t, err, ErrOwnership) + _, err = e.Spend(ctx, "case-1", l, "attempts-a", 2) + require.NoError(t, err) + *now = now.Add(2 * time.Minute) + replacement := New(b, func() time.Time { return *now }) + l2, err := replacement.Claim(ctx, "case-1", "host-2", time.Minute) + require.NoError(t, err) + require.Greater(t, l2.Generation, l.Generation) + _, err = e.Spend(ctx, "case-1", l, "attempts-a", 2) + require.ErrorIs(t, err, ErrOwnership) + r, err = replacement.Rebind(ctx, "case-1", l2, "binding-2", json.RawMessage(`{"required":["a","b","c"]}`)) + require.NoError(t, err) + require.Equal(t, uint64(1), r.Counters["attempts-a"]) + _, err = replacement.Spend(ctx, "case-1", l2, "attempts-a", 2) + require.NoError(t, err) + _, err = replacement.Spend(ctx, "case-1", l2, "attempts-a", 2) + require.ErrorIs(t, err, ErrBudget) + renewed, err := replacement.Renew(ctx, "case-1", l2, time.Hour) + require.NoError(t, err) + require.True(t, renewed.ExpiresAt.After(l2.ExpiresAt)) + require.NoError(t, replacement.Release(ctx, "case-1", renewed)) + require.ErrorIs(t, replacement.Release(ctx, "case-1", renewed), ErrOwnership) + l3, err := replacement.Claim(ctx, "case-1", "host-3", time.Minute) + require.NoError(t, err) + require.Greater(t, l3.Generation, l2.Generation) +} +func TestEffectRecoveryAndImmutableReceipts(t *testing.T) { + ctx := context.Background() + e, b, _, _ := fixture(t) + l := admitted(t, e) + effect := Effect{ID: "create-a", Kind: "jira-create", Binding: "request-sha"} + _, err := e.Intent(ctx, "case-1", l, effect) + require.NoError(t, err) + _, err = e.Intent(ctx, "case-1", l, effect) + require.NoError(t, err) + _, err = e.Intent(ctx, "case-1", l, Effect{ID: effect.ID, Kind: effect.Kind, Binding: "other"}) + require.ErrorIs(t, err, ErrBinding) + _, err = e.Effect(ctx, "case-1", l, effect.ID, EffectInFlight, nil) + require.NoError(t, err) + _, err = e.Effect(ctx, "case-1", l, effect.ID, EffectInFlight, nil) + require.ErrorIs(t, err, ErrTransition) + // New host process reads the durable pre-write checkpoint even without cleanup. + restarted := New(b, nil) + r, err := restarted.Read(ctx, "case-1") + require.NoError(t, err) + require.Equal(t, EffectInFlight, r.Effects[effect.ID].Status) + _, err = e.Effect(ctx, "case-1", l, effect.ID, EffectAmbiguous, nil) + require.NoError(t, err) + _, err = e.Effect(ctx, "case-1", l, effect.ID, EffectIntended, nil) + require.ErrorIs(t, err, ErrTransition) + _, err = e.Effect(ctx, "case-1", l, effect.ID, EffectConfirmed, json.RawMessage(`{"issue":"TEST-1"}`)) + require.NoError(t, err) + _, err = e.Effect(ctx, "case-1", l, effect.ID, EffectConfirmed, json.RawMessage(`{"issue":"TEST-2"}`)) + require.ErrorIs(t, err, ErrTransition) + _, err = e.Rebind(ctx, "case-1", l, "binding-2", json.RawMessage(`{}`)) + require.NoError(t, err) + r, err = e.Read(ctx, "case-1") + require.NoError(t, err) + require.Equal(t, EffectConfirmed, r.Effects[effect.ID].Status) +} +func TestVerifiedReuseMayConfirmWithoutPost(t *testing.T) { + ctx := context.Background() + e, _, _, _ := fixture(t) + l := admitted(t, e) + _, err := e.Intent(ctx, "case-1", l, Effect{ID: "reuse", Kind: "tracker", Binding: "sha"}) + require.NoError(t, err) + _, err = e.Effect(ctx, "case-1", l, "reuse", EffectConfirmed, json.RawMessage(`{"issue":"TEST-1"}`)) + require.NoError(t, err) +} +func TestIllegalTransactions(t *testing.T) { + ctx := context.Background() + e, _, _, now := fixture(t) + l := admitted(t, e) + _, err := e.Spend(ctx, "case-1", l, "attempts", 1) + require.NoError(t, err) + tests := []func(*Record) error{ + func(r *Record) error { r.ID = "other"; return nil }, func(r *Record) error { r.Binding = "other"; return nil }, func(r *Record) error { r.Generation++; return nil }, func(r *Record) error { r.Lease.Owner = "other"; return nil }, func(r *Record) error { r.Counters["attempts"] = 0; return nil }, func(r *Record) error { + r.Effects["x"] = Effect{ID: "x", Kind: "create", Binding: "sha", Status: EffectConfirmed, Receipt: json.RawMessage(`{}`)} + return nil + }, func(r *Record) error { r.Data = json.RawMessage(`bad`); return nil }, + } + for _, change := range tests { + _, err = e.Update(ctx, "case-1", l, change) + require.Error(t, err) + } + _, err = e.Update(ctx, "case-1", l, nil) + require.ErrorIs(t, err, ErrTransition) + _, err = e.Update(ctx, "case-1", l, func(*Record) error { return ErrBudget }) + require.ErrorIs(t, err, ErrBudget) + _, err = e.Update(ctx, "case-1", l, func(*Record) error { *now = now.Add(time.Hour); return nil }) + require.ErrorIs(t, err, ErrOwnership) +} +func TestCASOnlyOneConcurrentTransitionWins(t *testing.T) { + ctx := context.Background() + e, _, _, _ := fixture(t) + l := admitted(t, e) + var arrived atomic.Int32 + ready := make(chan struct{}) + results := make(chan error, 2) + var wg sync.WaitGroup + for range 2 { + wg.Go(func() { + _, err := e.Update(ctx, "case-1", l, func(r *Record) error { + if arrived.Add(1) == 2 { + close(ready) + } + <-ready + r.Counters["attempts"]++ + return nil + }) + results <- err + }) + } + wg.Wait() + close(results) + successes, conflicts := 0, 0 + for err := range results { + if err == nil { + successes++ + } else if errors.Is(err, ErrConflict) { + conflicts++ + } else { + t.Fatal(err) + } + } + require.Equal(t, 1, successes) + require.Equal(t, 1, conflicts) + r, err := e.Read(ctx, "case-1") + require.NoError(t, err) + require.Equal(t, uint64(1), r.Counters["attempts"]) +} +func TestStrictDocumentIntegrity(t *testing.T) { + original, err := Encode(Empty()) + require.NoError(t, err) + _, err = Decode(original) + require.NoError(t, err) + for _, raw := range [][]byte{[]byte(`{}`), []byte(`null`), []byte(`{"schema_version":1,"schema_version":1,"records":{},"checksum":"x"}`), append(append([]byte{}, original...), []byte(` {}`)...), []byte(strings.Replace(string(original), `"schema_version": 1`, `"schema_version": 2`, 1)), []byte(strings.Replace(string(original), `"records": {}`, `"unknown":{},"records": {}`, 1)), []byte(strings.Repeat("x", MaxDocumentBytes+1))} { + _, err = Decode(raw) + require.ErrorIs(t, err, ErrIntegrity) + } + _, err = Encode(Document{SchemaVersion: 1}) + require.ErrorIs(t, err, ErrIntegrity) + d := Empty() + d.Records["a"] = Record{ID: "a", Binding: "x", Data: json.RawMessage(`{}`), Counters: map[string]uint64{}, Effects: map[string]Effect{"e": {ID: "e", Kind: "k", Binding: "x", Status: EffectConfirmed}}} + _, err = Encode(d) + require.ErrorIs(t, err, ErrIntegrity) +} +func TestInvalidArgumentsAndMissingRecords(t *testing.T) { + ctx := context.Background() + e, _, _, _ := fixture(t) + _, err := e.Read(ctx, "missing") + require.ErrorIs(t, err, ErrNotFound) + for _, id := range []string{"", "../x"} { + _, err = e.Admit(ctx, id, "b", json.RawMessage(`{}`)) + require.Error(t, err) + } + _, err = e.Admit(ctx, "case", "", json.RawMessage(`{}`)) + require.Error(t, err) + _, err = e.Claim(ctx, "missing", "host", time.Minute) + require.ErrorIs(t, err, ErrNotFound) + for _, ttl := range []time.Duration{0, 25 * time.Hour} { + _, err = e.Claim(ctx, "missing", "host", ttl) + require.ErrorIs(t, err, ErrOwnership) + _, err = e.Renew(ctx, "missing", Lease{}, ttl) + require.ErrorIs(t, err, ErrOwnership) + } + _, err = e.Update(ctx, "missing", Lease{}, func(*Record) error { return nil }) + require.ErrorIs(t, err, ErrNotFound) + _, err = e.Rebind(ctx, "missing", Lease{}, "new", json.RawMessage(`{}`)) + require.ErrorIs(t, err, ErrNotFound) + _, err = e.Rebind(ctx, "missing", Lease{}, "", nil) + require.ErrorIs(t, err, ErrBinding) + require.ErrorIs(t, e.Release(ctx, "missing", Lease{}), ErrNotFound) + _, err = e.Renew(ctx, "missing", Lease{}, time.Minute) + require.ErrorIs(t, err, ErrNotFound) + _, err = New(nil, nil).Read(ctx, "missing") + require.ErrorIs(t, err, ErrIntegrity) +} + +func TestDuplicatePayloadKeysRejectedBeforeWriting(t *testing.T) { + ctx := context.Background() + engine, _, _, _ := fixture(t) + _, err := engine.Admit(ctx, "bad", "binding", json.RawMessage(`{"owner":"a","owner":"b"}`)) + require.ErrorIs(t, err, ErrIntegrity) + _, err = engine.Admit(ctx, "good", "binding", json.RawMessage(`{"nested":{"a":1}}`)) + require.NoError(t, err) + _, err = engine.Read(ctx, "good") + require.NoError(t, err) +} diff --git a/internal/journal/json.go b/internal/journal/json.go new file mode 100644 index 0000000000..bbaeedb336 --- /dev/null +++ b/internal/journal/json.go @@ -0,0 +1,63 @@ +package journal + +import ( + "bytes" + "encoding/json" + "fmt" + "io" +) + +// Reject duplicate object keys before decoding typed state. Last-wins JSON is +// inappropriate for lease and effect authority. +func strictDecode(data []byte, out any) error { + dec := json.NewDecoder(bytes.NewReader(data)) + dec.UseNumber() + var value func() error + value = func() error { + token, err := dec.Token() + if err != nil { + return err + } + delim, ok := token.(json.Delim) + if !ok { + return nil + } + switch delim { + case '{': + seen := map[string]bool{} + for dec.More() { + key, err := dec.Token() + if err != nil { + return err + } + name, ok := key.(string) + if !ok || seen[name] { + return fmt.Errorf("duplicate key") + } + seen[name] = true + if err = value(); err != nil { + return err + } + } + case '[': + for dec.More() { + if err = value(); err != nil { + return err + } + } + default: + return fmt.Errorf("unexpected delimiter") + } + _, err = dec.Token() + return err + } + if err := value(); err != nil { + return err + } + if _, err := dec.Token(); err != io.EOF { + return fmt.Errorf("trailing value") + } + typed := json.NewDecoder(bytes.NewReader(data)) + typed.DisallowUnknownFields() + return typed.Decode(out) +} diff --git a/internal/journal/requirements.go b/internal/journal/requirements.go new file mode 100644 index 0000000000..a018c7872a --- /dev/null +++ b/internal/journal/requirements.go @@ -0,0 +1,52 @@ +package journal + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "regexp" +) + +// Requirement binds a mutation to another record's currently admitted inputs +// and exact state. The same document CAS protects both records against races. +type Requirement struct { + ID string + Binding string + DataDigest string +} + +type requiredBackend struct { + Backend + requirement Requirement +} + +// RequireRecord returns an engine whose mutations require the observed parent +// admission. Reads remain available for recovery when the parent has changed. +func (e *Engine) RequireRecord(r Requirement) (*Engine, error) { + if e == nil || e.backend == nil || !identity.MatchString(r.ID) || r.Binding == "" || !regexp.MustCompile(`^[a-f0-9]{64}$`).MatchString(r.DataDigest) { + return nil, ErrBinding + } + return New(&requiredBackend{Backend: e.backend, requirement: r}, e.clock), nil +} + +func (b *requiredBackend) CompareAndSwap(ctx context.Context, rev string, d Document) (string, error) { + if err := b.validateMutation(d); err != nil { + return "", err + } + return b.Backend.CompareAndSwap(ctx, rev, d) +} + +func (b *requiredBackend) validateMutation(d Document) error { + r, ok := d.Records[b.requirement.ID] + if !ok || r.Binding != b.requirement.Binding { + return ErrBinding + } + sum := sha256.Sum256(r.Data) + if hex.EncodeToString(sum[:]) != b.requirement.DataDigest { + return ErrBinding + } + if parent, ok := b.Backend.(interface{ validateMutation(Document) error }); ok { + return parent.validateMutation(d) + } + return nil +} diff --git a/internal/journal/requirements_test.go b/internal/journal/requirements_test.go new file mode 100644 index 0000000000..bb670c9783 --- /dev/null +++ b/internal/journal/requirements_test.go @@ -0,0 +1,142 @@ +package journal + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +type hookCAS struct { + Backend + hook func() +} + +func (b *hookCAS) CompareAndSwap(ctx context.Context, rev string, d Document) (string, error) { + if b.hook != nil { + f := b.hook + b.hook = nil + f() + } + return b.Backend.CompareAndSwap(ctx, rev, d) +} +func dataHash(raw json.RawMessage) string { s := sha256.Sum256(raw); return hex.EncodeToString(s[:]) } + +func TestRequiredParentStateFencesChildEffects(t *testing.T) { + ctx := context.Background() + e, b, _, _ := fixture(t) + parentLease := admitted(t, e) + parent, err := e.Read(ctx, "case-1") + require.NoError(t, err) + _, err = e.Admit(ctx, "child", "code-inputs", json.RawMessage(`{}`)) + require.NoError(t, err) + req := Requirement{ID: parent.ID, Binding: parent.Binding, DataDigest: dataHash(parent.Data)} + guarded, err := e.RequireRecord(req) + require.NoError(t, err) + lease, err := guarded.Claim(ctx, "child", "code-host", time.Minute) + require.NoError(t, err) + _, err = guarded.Intent(ctx, "child", lease, Effect{ID: "first", Kind: "code", Binding: "approved-plan"}) + require.NoError(t, err) + // Parent changes after a child read but before its conditional write. + racing, err := New(&hookCAS{Backend: b, hook: func() { + _, updateErr := e.Update(ctx, parent.ID, parentLease, func(r *Record) error { r.Data = json.RawMessage(`{"revoked":true}`); return nil }) + require.NoError(t, updateErr) + }}, e.clock).RequireRecord(req) + require.NoError(t, err) + _, err = racing.Intent(ctx, "child", lease, Effect{ID: "stale", Kind: "publish", Binding: "approved-plan"}) + require.ErrorIs(t, err, ErrConflict) + // Reload cannot silently accept the stale admission either. + _, err = guarded.Intent(ctx, "child", lease, Effect{ID: "stale", Kind: "publish", Binding: "approved-plan"}) + require.ErrorIs(t, err, ErrBinding) + child, err := guarded.Read(ctx, "child") + require.NoError(t, err) + require.NotContains(t, child.Effects, "stale") + require.Contains(t, child.Effects, "first") + fresh, err := e.Read(ctx, parent.ID) + require.NoError(t, err) + req.DataDigest = dataHash(fresh.Data) + guarded, err = e.RequireRecord(req) + require.NoError(t, err) + _, err = guarded.Spend(ctx, "child", lease, "code-attempts", 1) + require.NoError(t, err) + req.Binding = "superseded" + guarded, err = e.RequireRecord(req) + require.NoError(t, err) + _, err = guarded.Spend(ctx, "child", lease, "code-attempts", 2) + require.ErrorIs(t, err, ErrBinding) + req.ID = "missing" + guarded, err = e.RequireRecord(req) + require.NoError(t, err) + _, err = guarded.Spend(ctx, "child", lease, "code-attempts", 2) + require.ErrorIs(t, err, ErrBinding) + for _, invalid := range []Requirement{{}, {ID: "parent", Binding: "binding", DataDigest: "bad"}, {ID: "bad space", Binding: "binding", DataDigest: req.DataDigest}, {ID: "parent", DataDigest: req.DataDigest}} { + _, err = e.RequireRecord(invalid) + require.ErrorIs(t, err, ErrBinding) + } + var nilEngine *Engine + _, err = nilEngine.RequireRecord(req) + require.ErrorIs(t, err, ErrBinding) + _, err = New(nil, nil).RequireRecord(req) + require.ErrorIs(t, err, ErrBinding) +} + +func TestRequiredParentFencesNoOpMutationsAndNestedRequirements(t *testing.T) { + ctx := context.Background() + e, _, _, _ := fixture(t) + parentLease := admitted(t, e) + parent, err := e.Read(ctx, "case-1") + require.NoError(t, err) + _, err = e.Admit(ctx, "child", "child-binding", json.RawMessage(`{}`)) + require.NoError(t, err) + lease, err := e.Claim(ctx, "child", "worker", time.Minute) + require.NoError(t, err) + effect := Effect{ID: "publish", Kind: "tracker", Binding: "inputs"} + _, err = e.Intent(ctx, "child", lease, effect) + require.NoError(t, err) + stale := Requirement{ID: parent.ID, Binding: parent.Binding, DataDigest: dataHash(parent.Data)} + guarded, err := e.RequireRecord(stale) + require.NoError(t, err) + _, err = e.Update(ctx, parent.ID, parentLease, func(r *Record) error { r.Data = json.RawMessage(`{"changed":true}`); return nil }) + require.NoError(t, err) + child, err := e.Read(ctx, "child") + require.NoError(t, err) + nested, err := guarded.RequireRecord(Requirement{ID: child.ID, Binding: child.Binding, DataDigest: dataHash(child.Data)}) + require.NoError(t, err) + for _, g := range []*Engine{guarded, nested} { + _, err = g.Admit(ctx, "child", "child-binding", json.RawMessage(`{}`)) + require.ErrorIs(t, err, ErrBinding) + _, err = g.Update(ctx, "child", lease, func(*Record) error { return nil }) + require.ErrorIs(t, err, ErrBinding) + _, err = g.Intent(ctx, "child", lease, effect) + require.ErrorIs(t, err, ErrBinding) + _, err = g.Effect(ctx, "child", lease, "publish", EffectIntended, nil) + require.ErrorIs(t, err, ErrBinding) + _, err = g.Claim(ctx, "child", "new-worker", time.Minute) + require.ErrorIs(t, err, ErrBinding) + _, err = g.Rebind(ctx, "child", lease, "new-binding", json.RawMessage(`{}`)) + require.ErrorIs(t, err, ErrBinding) + _, err = g.Renew(ctx, "child", lease, time.Minute) + require.ErrorIs(t, err, ErrBinding) + require.ErrorIs(t, g.Release(ctx, "child", lease), ErrBinding) + _, err = g.Read(ctx, "child") + require.NoError(t, err) + } +} + +func TestRequiredParentStillChecksFinalCAS(t *testing.T) { + ctx := context.Background() + e, _, _, _ := fixture(t) + admitted(t, e) + guarded, err := e.RequireRecord(Requirement{ID: "case-1", Binding: "superseded", DataDigest: dataHash(json.RawMessage(`{}`))}) + require.NoError(t, err) + d, rev, err := guarded.backend.Load(ctx) + require.NoError(t, err) + _, err = guarded.backend.CompareAndSwap(ctx, rev, d) + require.ErrorIs(t, err, ErrBinding) + _, err = New(nil, nil).Admit(ctx, "child", "binding", json.RawMessage(`{}`)) + require.ErrorIs(t, err, ErrIntegrity) +} diff --git a/internal/journalhost/profile.go b/internal/journalhost/profile.go new file mode 100644 index 0000000000..d38346ee64 --- /dev/null +++ b/internal/journalhost/profile.go @@ -0,0 +1,146 @@ +// Package journalhost binds storage to administrator-controlled host policy. +package journalhost + +import ( + "context" + "crypto/subtle" + "encoding/json" + "errors" + "io" + "net/url" + "os" + "path" + "strings" + + "github.com/fullsend-ai/fullsend/internal/forge" + gl "github.com/fullsend-ai/fullsend/internal/forge/gitlab" + "github.com/fullsend-ai/fullsend/internal/gitlabroles" + "github.com/fullsend-ai/fullsend/internal/journal" +) + +const ProfileEnv = "FULLSEND_JOURNAL_PROFILE" + +// Profile is protected host installation state, never source or tracker content. +type Profile struct { + Forge string `json:"forge"` + BaseURL string `json:"base_url"` + Owner string `json:"owner"` + Repo string `json:"repo"` + Branch string `json:"branch"` + Path string `json:"path"` + Role string `json:"role"` +} + +func Load(getenv func(string) string) (Profile, error) { + var p Profile + if getenv == nil { + getenv = os.Getenv + } + raw := getenv(ProfileEnv) + if len(raw) == 0 || len(raw) > 16384 { + return p, errors.New("protected journal profile required") + } + // All profile members are scalars. Reject duplicate keys before typed + // decoding, rather than silently accepting the last security scope. + keys := json.NewDecoder(strings.NewReader(raw)) + token, err := keys.Token() + if err != nil || token != json.Delim('{') { + return p, errors.New("invalid protected journal profile") + } + seen := map[string]bool{} + for keys.More() { + key, err := keys.Token() + name, ok := key.(string) + if err != nil || !ok || seen[name] { + return p, errors.New("invalid protected journal profile") + } + seen[name] = true + var value json.RawMessage + if err = keys.Decode(&value); err != nil { + return p, errors.New("invalid protected journal profile") + } + } + dec := json.NewDecoder(strings.NewReader(raw)) + dec.DisallowUnknownFields() + if err := dec.Decode(&p); err != nil { + return Profile{}, errors.New("invalid protected journal profile") + } + if err := dec.Decode(new(any)); !errors.Is(err, io.EOF) { + return Profile{}, errors.New("invalid protected journal profile") + } + u, err := url.Parse(p.BaseURL) + if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") || p.Forge != "gitlab" || p.Owner == "" || p.Repo == "" || p.Branch == "" || p.Path == "" || p.Role == "" { + return Profile{}, errors.New("invalid protected journal profile") + } + if strings.Contains(p.Repo, "/") || path.Clean(p.Path) != p.Path || strings.HasPrefix(p.Path, "/") || strings.HasPrefix(p.Path, "../") || !strings.HasSuffix(p.Path, ".json") || strings.ContainsAny(p.Path, "\\%?#\r\n") || strings.ContainsAny(p.Branch, " \\%?#\r\n~^:*") || strings.Contains(p.Branch, "..") || strings.HasPrefix(p.Branch, "/") || strings.HasSuffix(p.Branch, "/") || strings.Contains(p.Branch, "@{") { + return Profile{}, errors.New("invalid protected journal scope") + } + for _, part := range strings.Split(p.Owner+"/"+p.Repo, "/") { + if part == "" || part == "." || part == ".." || strings.ContainsAny(part, "\\%?#\r\n") { + return Profile{}, errors.New("invalid protected journal scope") + } + } + return p, nil +} +func (p Profile) Location() journal.Location { + return journal.Location{Owner: p.Owner, Repo: p.Repo, Branch: p.Branch, Path: p.Path} +} + +// Credential refuses built-in roles: journal writes do not widen Analyst or Poller. +func (p Profile) Credential(getenv func(string) string) (string, error) { + sel, err := gitlabroles.SelectAgent(p.Role, p.Role, getenv) + if err != nil { + return "", err + } + if string(sel.Registration.Name) != p.Role || sel.Registration.Kind != gitlabroles.RoleKindCustom || sel.Registration.Credential.Kind != gitlabroles.CredentialOwn || !sel.Registration.Has(gitlabroles.CapWriteRepository) { + return "", errors.New("registered journal writer role required") + } + return sel.Token(getenv) +} +func (p Profile) Authorizer(client forge.Client, getenv func(string) string, authenticatingToken string) journal.AuthorizeFunc { + return func(ctx context.Context, loc journal.Location, action string) error { + if loc != p.Location() || (action != "read" && action != "write" && action != "initialize") { + return errors.New("journal scope denied") + } + currentProfile, err := Load(getenv) + if err != nil || currentProfile != p { + return errors.New("journal host profile changed") + } + current, err := p.Credential(getenv) + if err != nil { + return err + } + if client == nil || authenticatingToken == "" || subtle.ConstantTimeCompare([]byte(current), []byte(authenticatingToken)) != 1 { + return gitlabroles.ErrIdentityMismatch + } + protected, err := client.IsProtectedBranch(ctx, p.Owner, p.Repo, p.Branch) + if err != nil { + return errors.New("journal branch protection could not be verified") + } + if !protected { + return errors.New("journal requires protected control branch") + } + return nil + } +} + +// Open never falls back to an ambient GITLAB_TOKEN or local-only backend. +func Open(getenv func(string) string) (*journal.Engine, *journal.ForgeBackend, error) { + p, err := Load(getenv) + if err != nil { + return nil, nil, err + } + token, err := p.Credential(getenv) + if err != nil { + return nil, nil, err + } + client, err := gl.New(token, gl.WithBaseURL(p.BaseURL)) + if err != nil { + return nil, nil, errors.New("journal connection unavailable") + } + backend, err := journal.NewForgeBackend(client, p.Location(), p.Authorizer(client, getenv, token)) + if err != nil { + return nil, nil, errors.New("journal profile rejected") + } + return journal.New(backend, nil), backend, nil +} diff --git a/internal/journalhost/profile_test.go b/internal/journalhost/profile_test.go new file mode 100644 index 0000000000..61bbce01dc --- /dev/null +++ b/internal/journalhost/profile_test.go @@ -0,0 +1,155 @@ +package journalhost + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" + + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/gitlabroles" + "github.com/fullsend-ai/fullsend/internal/journal" + "github.com/stretchr/testify/require" +) + +func trustedEnv(t *testing.T) map[string]string { + t.Helper() + p := Profile{Forge: "gitlab", BaseURL: "https://gitlab.example.com", Owner: "group/control", Repo: "fullsend", Branch: "fullsend-journal", Path: "state/journal.json", Role: "journal"} + raw, err := json.Marshal(p) + require.NoError(t, err) + return map[string]string{ProfileEnv: string(raw), forge.VarGitLabRoleRegistry: `{"roles":[{"name":"journal","credential":"own","capabilities":["write_repository"],"agents":["journal"]}]}`, gitlabroles.CustomSecretName("journal"): "journal-private-token"} +} +func getenv(env map[string]string) func(string) string { + return func(key string) string { return env[key] } +} +func TestLoadStrictTrustedProfile(t *testing.T) { + env := trustedEnv(t) + p, err := Load(getenv(env)) + require.NoError(t, err) + require.Equal(t, journal.Location{Owner: "group/control", Repo: "fullsend", Branch: "fullsend-journal", Path: "state/journal.json"}, p.Location()) + for _, raw := range []string{"", strings.Repeat("x", 16385), "null", "[]", "{", `{"forge":`, env[ProfileEnv] + ` {}`, strings.Replace(env[ProfileEnv], `"forge":"gitlab"`, `"forge":"gitlab","forge":"github"`, 1), strings.Replace(env[ProfileEnv], `"forge":"gitlab"`, `"forge":"gitlab","token":"must-not-appear"`, 1), strings.Replace(env[ProfileEnv], `"forge":"gitlab"`, `"forge":1`, 1)} { + env[ProfileEnv] = raw + _, err = Load(getenv(env)) + require.Error(t, err) + require.NotContains(t, err.Error(), "must-not-appear") + } +} +func TestLoadRejectsUnsafeScope(t *testing.T) { + env := trustedEnv(t) + base, err := Load(getenv(env)) + require.NoError(t, err) + mutations := []func(*Profile){func(p *Profile) { p.Forge = "github" }, func(p *Profile) { p.BaseURL = "http://gitlab.example.com" }, func(p *Profile) { p.BaseURL = "https://user:secret@gitlab.example.com" }, func(p *Profile) { p.BaseURL = "https://gitlab.example.com?token=secret" }, func(p *Profile) { p.BaseURL = "https://gitlab.example.com/path" }, func(p *Profile) { p.Owner = "group/../other" }, func(p *Profile) { p.Repo = "another/repo" }, func(p *Profile) { p.Branch = "../main" }, func(p *Profile) { p.Path = "../journal.json" }, func(p *Profile) { p.Path = "/journal.json" }, func(p *Profile) { p.Path = "journal.txt" }, func(p *Profile) { p.Role = "" }, func(p *Profile) { p.Owner = "" }} + for _, mutate := range mutations { + p := base + mutate(&p) + data, err := json.Marshal(p) + require.NoError(t, err) + env[ProfileEnv] = string(data) + _, err = Load(getenv(env)) + require.Error(t, err) + require.NotContains(t, err.Error(), "coder-secret") + require.NotContains(t, err.Error(), "analyst-secret") + require.NotContains(t, err.Error(), "ambient-secret") + } + t.Setenv(ProfileEnv, trustedEnv(t)[ProfileEnv]) + _, err = Load(nil) + require.NoError(t, err) +} +func TestCredentialRequiresRegisteredCustomWriter(t *testing.T) { + env := trustedEnv(t) + p, err := Load(getenv(env)) + require.NoError(t, err) + token, err := p.Credential(getenv(env)) + require.NoError(t, err) + require.Equal(t, "journal-private-token", token) + env[forge.SecretGitLabCoderToken] = "coder-secret" + env[forge.SecretGitLabAnalystToken] = "analyst-secret" + env[forge.SecretForgeToken] = "ambient-secret" + env["GITLAB_TOKEN"] = "ambient-secret" + for _, role := range []string{"coder", "analyst", "poller", "unregistered"} { + bad := p + bad.Role = role + _, err = bad.Credential(getenv(env)) + require.Error(t, err) + require.NotContains(t, err.Error(), "coder-secret") + require.NotContains(t, err.Error(), "analyst-secret") + require.NotContains(t, err.Error(), "ambient-secret") + } + env[forge.VarGitLabRoleRegistry] = `{"roles":[{"name":"journal","capabilities":["read_issues"]}]}` + _, err = p.Credential(getenv(env)) + require.Error(t, err) + env = trustedEnv(t) + delete(env, gitlabroles.CustomSecretName("journal")) + env["GITLAB_TOKEN"] = "ambient-secret" + env[forge.SecretForgeToken] = "ambient-secret" + _, err = p.Credential(getenv(env)) + require.Error(t, err) +} +func TestAuthorizerBindsCredentialScopeAndProtectedBranch(t *testing.T) { + ctx := context.Background() + env := trustedEnv(t) + p, err := Load(getenv(env)) + require.NoError(t, err) + fc := forge.NewFakeClient() + fc.ProtectedBranches[p.Owner+"/"+p.Repo+"/"+p.Branch] = true + authorize := p.Authorizer(fc, getenv(env), "journal-private-token") + for _, action := range []string{"initialize", "read", "write"} { + require.NoError(t, authorize(ctx, p.Location(), action)) + } + wrong := p.Location() + wrong.Repo = "unapproved" + require.Error(t, authorize(ctx, wrong, "write")) + require.Error(t, authorize(ctx, p.Location(), "delete")) + env[gitlabroles.CustomSecretName("journal")] = "rotated-token" + require.ErrorIs(t, authorize(ctx, p.Location(), "write"), gitlabroles.ErrIdentityMismatch) + env[gitlabroles.CustomSecretName("journal")] = "journal-private-token" + fc.ProtectedBranches[p.Owner+"/"+p.Repo+"/"+p.Branch] = false + require.Error(t, authorize(ctx, p.Location(), "write")) + fc.Errors["IsProtectedBranch"] = errors.New("server says journal-private-token") + err = authorize(ctx, p.Location(), "write") + require.Error(t, err) + require.NotContains(t, err.Error(), "journal-private-token") + delete(env, gitlabroles.CustomSecretName("journal")) + require.Error(t, authorize(ctx, p.Location(), "write")) +} +func TestOpenHasNoAmbientBackendFallback(t *testing.T) { + env := trustedEnv(t) + engine, backend, err := Open(getenv(env)) + require.NoError(t, err) + require.NotNil(t, engine) + require.NotNil(t, backend) + delete(env, ProfileEnv) + _, _, err = Open(getenv(env)) + require.Error(t, err) + env = trustedEnv(t) + delete(env, gitlabroles.CustomSecretName("journal")) + env["GITLAB_TOKEN"] = "ambient" + _, _, err = Open(getenv(env)) + require.Error(t, err) +} + +func TestAuthorizerStopsWhenProtectedProfileChanges(t *testing.T) { + env := trustedEnv(t) + p, err := Load(getenv(env)) + require.NoError(t, err) + fc := forge.NewFakeClient() + fc.ProtectedBranches[p.Owner+"/"+p.Repo+"/"+p.Branch] = true + authorize := p.Authorizer(fc, getenv(env), "journal-private-token") + require.NoError(t, authorize(context.Background(), p.Location(), "write")) + delete(env, ProfileEnv) + require.Error(t, authorize(context.Background(), p.Location(), "write")) +} + +func TestJournalCredentialCannotReuseAssessmentRole(t *testing.T) { + env := trustedEnv(t) + p, err := Load(getenv(env)) + require.NoError(t, err) + delete(env, gitlabroles.CustomSecretName("journal")) + env[forge.SecretGitLabAnalystToken] = "assessment-only-secret" + env[forge.VarGitLabRoleRegistry] = `{"roles":[{"name":"journal","credential":"reuse","reuse":"analyst","capabilities":["write_repository"],"agents":["journal"]}]}` + token, err := p.Credential(getenv(env)) + require.Error(t, err) + require.Empty(t, token) + require.NotContains(t, err.Error(), "assessment-only-secret") +} From db7ba9b31d417a0c6ee6b956cb9a317cbc52be20 Mon Sep 17 00:00:00 2001 From: eshulman2 Date: Mon, 30 Nov 2026 14:11:15 +0200 Subject: [PATCH 2/5] fix(journal): address isolation and recovery review findings Signed-off-by: eshulman2 --- docs/cli/journal.md | 47 ++++++++---- docs/guides/getting-started/operations.md | 38 +++++++--- internal/cli/journal.go | 2 +- internal/cli/journal_test.go | 6 +- internal/forge/gitlab/versioned_file.go | 8 +-- internal/forge/gitlab/versioned_file_test.go | 11 ++- internal/journal/requirements.go | 14 +++- internal/journal/requirements_test.go | 11 ++- internal/journalhost/profile.go | 61 +++++++++++++++- internal/journalhost/profile_test.go | 76 +++++++++++++++++++- 10 files changed, 235 insertions(+), 39 deletions(-) diff --git a/docs/cli/journal.md b/docs/cli/journal.md index 15be4d293b..f18e200844 100644 --- a/docs/cli/journal.md +++ b/docs/cli/journal.md @@ -17,8 +17,17 @@ Set `FULLSEND_JOURNAL_PROFILE` in trusted host installation state. Its strict JS fields are `forge` (`gitlab`), `base_url` (HTTPS site origin), `owner` (namespace), `repo`, `branch`, `path` (relative JSON file), and `role`. Source checkouts, tracker properties and model output cannot supply this profile. The journal branch must -already exist and be protected. The profile selects its exact scope; there are -no command flags to redirect writes elsewhere. +already exist and be protected. Every exact or wildcard rule matching the +branch must allow push and merge only to the journal writer's numeric user ID +(or nobody), with at least one push grant for the writer. Role-level, group +and deploy-key grants are refused, including +Maintainer grants; an overlapping permissive rule also blocks access. The +credential must be able to list protection rules and identify its user. +Named-user protection grants require +[GitLab Premium or Ultimate](https://docs.gitlab.com/user/project/repository/branches/protected/#in-a-project). +Instances without these grants cannot host this journal backend. +The profile selects its exact scope; there are no command flags to redirect +writes elsewhere. Register `role` as a custom identity through the existing protected `FULLSEND_GITLAB_ROLE_REGISTRY`, with `write_repository` capability and its own @@ -60,9 +69,9 @@ After admission and claim, leased mutations require `--id`, `--owner` and the The effect states are `intended`, `in_flight`, `ambiguous` and `confirmed`. Transition checks and immutable receipts prevent a stale owner or repeated in-flight admission from authorizing another external write. The CLI retries a -mutation at most three times only when the conditional write was definitively -rejected. It reloads state and rechecks all predicates on each attempt, with short -cancellation-aware backoff. It reads stdin once. Initialization and reads are not +mutation at most twice (three attempts total), only when the conditional write +was definitively rejected. It reloads state and rechecks all predicates on each +attempt, with short cancellation-aware backoff. It reads stdin once. Initialization and reads are not replayed. Exhausted conflicts still require caller recovery; do not force-push or merge competing JSON claims. These retries do not invoke an agent or repeat an external action. @@ -95,9 +104,14 @@ Promotion controllers can pass all three flags on journal commands: --require-record CASE_ID --require-binding MANIFEST_DIGEST --require-data-digest PARENT_DATA_SHA256 ``` -The data digest is SHA256 of the exact parent record's `data` bytes, as observed -by a trusted context exporter. Every mutation checks all parent requirements on -its fresh loaded snapshot, including idempotent no-op paths, and again in the +The data digest is SHA256 of the compact JSON bytes of the parent record's +`data` value as emitted by `fullsend journal read`, excluding surrounding +whitespace or a trailing newline. This uses Go's `encoding/json` HTML escaping +(for example, `<` becomes `\u003c`) and preserves object key order and number +spellings. Extract the raw value without parsing and reserializing it through a +serializer that changes those bytes. Go callers can use `json.Marshal(record.Data)` +to obtain the same representation. Storage indentation does not affect the digest. +Every mutation checks all parent requirements on its fresh loaded snapshot, including idempotent no-op paths, and again in the whole-document conditional write. A changed parent rejects the mutation. A concurrent revision conflict can trigger the bounded transaction retry above; a newly stale parent then fails its fresh check. This does not retry a model call @@ -118,9 +132,11 @@ writer credential merely because they participate in a workflow. The storage backend is initially GitLab only. GitHub and Forgejo source targets remain independent of the journal location; their control-journal backends stay unsupported pending conformance. No journal access to source repositories is -needed. Hosted cross-machine conformance and end-to-end workflow migration are -tracked in [#9253](https://github.com/fullsend-ai/fullsend/issues/9253); local -fake-backend and HTTP-adapter tests do not establish that acceptance. +needed. Local fake-backend and HTTP-adapter tests do not establish hosted +acceptance. + +> **Planned:** Hosted cross-machine conformance and end-to-end workflow migration +> remain tracked in [#9253](https://github.com/fullsend-ai/fullsend/issues/9253). Store only bounded identities, digests and receipts. Checksums detect corruption, not a writer's identity. Protected storage and host authorization supply that @@ -131,6 +147,9 @@ installation responsibilities; exhaustion holds work rather than discarding unresolved operations. This initial command does not create journal-operation trace spans or capture -journal payloads into telemetry. Journal/run trace correlation and metadata-only -instrumentation remain implementation work in #9253. A journal receipt is not a -replacement for the run's detailed telemetry or proof of a domain outcome. +journal payloads into telemetry. A journal receipt is not a replacement for the +run's detailed telemetry or proof of a domain outcome. + +> **Planned:** Journal-operation trace spans, journal/run trace correlation and +> metadata-only instrumentation remain implementation work in +> [#9253](https://github.com/fullsend-ai/fullsend/issues/9253). diff --git a/docs/guides/getting-started/operations.md b/docs/guides/getting-started/operations.md index 045d3d1903..d2a8897be0 100644 --- a/docs/guides/getting-started/operations.md +++ b/docs/guides/getting-started/operations.md @@ -235,17 +235,35 @@ others). ## Opt in to a recovery journal -```sh -fullsend journal initialize -fullsend journal read --id OPERATION_ID -``` +A recovery journal is a protected, conditionally updated record of operations +that lets a workflow resume after interruption. + +### Prerequisites + +Provision a protected journal branch, a trusted `FULLSEND_JOURNAL_PROFILE`, +and a separately registered GitLab role with its own `write_repository` +credential. Restrict every matching branch rule's push and merge grants to the +journal writer's user ID (or no access). Role-level, group and deploy-key grants +are refused. Follow the +[journal command reference](../../cli/journal.md#protected-host-profile) to +configure these prerequisites. + +### Initialize and inspect + +1. Initialize a new journal: -These commands require an administrator-provisioned protected journal branch, -a trusted `FULLSEND_JOURNAL_PROFILE`, and a separately registered GitLab role -with its own `write_repository` credential. Follow the -[journal command reference](../../cli/journal.md#protected-host-profile) before -running them. Initialize only a new journal; never recreate or reset missing -state to release budgets or unresolved effects. + ```sh + fullsend journal initialize + ``` + + Initialize only a new journal; never recreate or reset missing state to + release budgets or unresolved effects. + +2. Read an admitted operation: + + ```sh + fullsend journal read --id OPERATION_ID + ``` Workflow integration is explicit. The command neither adds a schedule nor changes normal poll/webhook dispatch. Keep writer credentials outside assessment diff --git a/internal/cli/journal.go b/internal/cli/journal.go index 925f24b1c9..f0019d3853 100644 --- a/internal/cli/journal.go +++ b/internal/cli/journal.go @@ -34,7 +34,7 @@ func newJournalCmd() *cobra.Command { cmd.Flags().Uint64Var(&limit, "limit", 0, "maximum budget consumption") cmd.Flags().StringVar(&required.ID, "require-record", "", "parent record required in the same conditional journal write") cmd.Flags().StringVar(&required.Binding, "require-binding", "", "required parent input binding") - cmd.Flags().StringVar(&required.DataDigest, "require-data-digest", "", "SHA256 of exact observed parent data bytes") + cmd.Flags().StringVar(&required.DataDigest, "require-data-digest", "", "SHA256 of compact parent data JSON emitted by read") cmd.RunE = func(cmd *cobra.Command, args []string) error { action := args[0] allowed := map[string]bool{"initialize": true, "read": true, "admit": true, "claim": true, "renew": true, "release": true, "update": true, "rebind": true, "intent": true, "effect": true, "spend": true} diff --git a/internal/cli/journal_test.go b/internal/cli/journal_test.go index 584ac560e5..45bdbb9cf5 100644 --- a/internal/cli/journal_test.go +++ b/internal/cli/journal_test.go @@ -131,10 +131,12 @@ func TestJournalCLIParentPredicatesRejectStaleEffect(t *testing.T) { e, b := journalCommandFixture(t) ctx := context.Background() require.NoError(t, b.Initialize(ctx)) - parent, err := e.Admit(ctx, "parent", "manifest", json.RawMessage(`{"state":"admitted"}`)) + _, err := e.Admit(ctx, "parent", "manifest", json.RawMessage(`{ "state": "admitted", "html": "<&>" }`)) require.NoError(t, err) - parent, err = e.Read(ctx, "parent") + output, err := runJournal(t, "", "read", "--id", "parent") require.NoError(t, err) + var parent journal.Record + require.NoError(t, json.Unmarshal([]byte(output), &parent)) sum := sha256.Sum256(parent.Data) flags := []string{"--require-record", "parent", "--require-binding", "manifest", "--require-data-digest", hex.EncodeToString(sum[:])} _, err = runJournal(t, `{}`, append([]string{"admit", "--id", "child", "--binding", "plan"}, flags...)...) diff --git a/internal/forge/gitlab/versioned_file.go b/internal/forge/gitlab/versioned_file.go index 89310a4721..447d019896 100644 --- a/internal/forge/gitlab/versioned_file.go +++ b/internal/forge/gitlab/versioned_file.go @@ -7,7 +7,6 @@ import ( "fmt" "net/http" "net/url" - "strings" "github.com/fullsend-ai/fullsend/internal/forge" ) @@ -57,14 +56,15 @@ func (c *LiveClient) WriteFileIfRevision(ctx context.Context, owner, repo, branc } var apiErr *APIError if errors.As(err, &apiErr) { - msg := strings.ToLower(apiErr.Message) // Gitaly can reject the branch-reference CAS after the file revision // check passed. This exact failed-precondition response proves that // the reference update was rejected, rather than its ACK being lost. referenceCASRejected := apiErr.StatusCode == http.StatusBadRequest && apiErr.Message == "9:reference update: reference does not point to expected object." - if referenceCASRejected || apiErr.StatusCode == http.StatusConflict || apiErr.StatusCode == http.StatusNotFound || (apiErr.StatusCode == http.StatusBadRequest && (strings.Contains(msg, "already exists") || strings.Contains(msg, "changed") || strings.Contains(msg, "last_commit") || strings.Contains(msg, "empty"))) { - return fmt.Errorf("%w: versioned file changed or missing", forge.ErrConflict) + fileRejected := apiErr.StatusCode == http.StatusBadRequest && ((method == http.MethodPost && apiErr.Message == "A file with this name already exists") || + (method == http.MethodPut && apiErr.Message == "You are attempting to update a file that has changed since you started editing it.")) + if referenceCASRejected || fileRejected || apiErr.StatusCode == http.StatusConflict { + return fmt.Errorf("%w: conditional file write rejected", forge.ErrConflict) } } return err diff --git a/internal/forge/gitlab/versioned_file_test.go b/internal/forge/gitlab/versioned_file_test.go index 5e998e25da..aacbf8888a 100644 --- a/internal/forge/gitlab/versioned_file_test.go +++ b/internal/forge/gitlab/versioned_file_test.go @@ -59,8 +59,10 @@ func TestVersionedWriteConflictAndNoRetry(t *testing.T) { }) err := c.WriteFileIfRevision(context.Background(), "o", "r", "state", "journal.json", "old", "checkpoint", []byte("x")) require.Error(t, err) - if status == 400 || status == 404 || status == 409 { + if status == 409 { require.ErrorIs(t, err, forge.ErrConflict) + } else { + require.NotErrorIs(t, err, forge.ErrConflict) } require.Equal(t, int32(1), calls.Load()) }) @@ -86,6 +88,13 @@ func TestVersionedWriteRecognizesOnlyExactReferenceRaceRejection(t *testing.T) { message string conflict bool }{ + {"missing project", http.StatusNotFound, "404 Project Not Found", false}, + {"missing branch", http.StatusNotFound, "404 Branch Not Found", false}, + {"empty commit message", http.StatusBadRequest, "commit_message is empty", false}, + {"invalid last commit", http.StatusBadRequest, "last_commit_id is invalid", false}, + {"unrelated changed setting", http.StatusBadRequest, "setting changed by administrator", false}, + {"unrelated existing branch", http.StatusBadRequest, "Branch already exists", false}, + {"file revision mismatch", http.StatusBadRequest, "You are attempting to update a file that has changed since you started editing it.", true}, {"reference CAS rejected", http.StatusBadRequest, rejection, true}, {"unknown bad request", http.StatusBadRequest, "reference update failed", false}, {"same text in server failure", http.StatusInternalServerError, rejection, false}, diff --git a/internal/journal/requirements.go b/internal/journal/requirements.go index a018c7872a..bed4c09771 100644 --- a/internal/journal/requirements.go +++ b/internal/journal/requirements.go @@ -4,14 +4,16 @@ import ( "context" "crypto/sha256" "encoding/hex" + "encoding/json" "regexp" ) // Requirement binds a mutation to another record's currently admitted inputs // and exact state. The same document CAS protects both records against races. type Requirement struct { - ID string - Binding string + ID string + Binding string + // DataDigest hashes json.Marshal(record.Data), matching CLI JSON output. DataDigest string } @@ -41,7 +43,13 @@ func (b *requiredBackend) validateMutation(d Document) error { if !ok || r.Binding != b.requirement.Binding { return ErrBinding } - sum := sha256.Sum256(r.Data) + // Match the compact, HTML-escaped RawMessage representation emitted by + // encoding/json (including the CLI), independent of document indentation. + data, err := json.Marshal(r.Data) + if err != nil { + return ErrBinding + } + sum := sha256.Sum256(data) if hex.EncodeToString(sum[:]) != b.requirement.DataDigest { return ErrBinding } diff --git a/internal/journal/requirements_test.go b/internal/journal/requirements_test.go index bb670c9783..97773fbfa7 100644 --- a/internal/journal/requirements_test.go +++ b/internal/journal/requirements_test.go @@ -24,7 +24,11 @@ func (b *hookCAS) CompareAndSwap(ctx context.Context, rev string, d Document) (s } return b.Backend.CompareAndSwap(ctx, rev, d) } -func dataHash(raw json.RawMessage) string { s := sha256.Sum256(raw); return hex.EncodeToString(s[:]) } +func dataHash(raw json.RawMessage) string { + data, _ := json.Marshal(raw) + s := sha256.Sum256(data) + return hex.EncodeToString(s[:]) +} func TestRequiredParentStateFencesChildEffects(t *testing.T) { ctx := context.Background() @@ -140,3 +144,8 @@ func TestRequiredParentStillChecksFinalCAS(t *testing.T) { _, err = New(nil, nil).Admit(ctx, "child", "binding", json.RawMessage(`{}`)) require.ErrorIs(t, err, ErrIntegrity) } + +func TestRequiredParentRejectsInvalidJSON(t *testing.T) { + b := &requiredBackend{requirement: Requirement{ID: "parent", Binding: "binding", DataDigest: dataHash(json.RawMessage(`{}`))}} + require.ErrorIs(t, b.validateMutation(Document{Records: map[string]Record{"parent": {ID: "parent", Binding: "binding", Data: json.RawMessage(`{`)}}}), ErrBinding) +} diff --git a/internal/journalhost/profile.go b/internal/journalhost/profile.go index d38346ee64..52ba23ea5e 100644 --- a/internal/journalhost/profile.go +++ b/internal/journalhost/profile.go @@ -10,6 +10,7 @@ import ( "net/url" "os" "path" + "regexp" "strings" "github.com/fullsend-ai/fullsend/internal/forge" @@ -120,7 +121,7 @@ func (p Profile) Authorizer(client forge.Client, getenv func(string) string, aut if !protected { return errors.New("journal requires protected control branch") } - return nil + return p.verifyWriterIsolation(ctx, client) } } @@ -144,3 +145,61 @@ func Open(getenv func(string) string) (*journal.Engine, *journal.ForgeBackend, e } return journal.New(backend, nil), backend, nil } + +// verifyWriterIsolation checks every matching rule: GitLab combines overlapping +// protections permissively, so an exact rule cannot neutralize a broad wildcard. +func (p Profile) verifyWriterIsolation(ctx context.Context, client forge.Client) error { + denied := errors.New("journal requires writer-only branch push and merge grants") + identity, ok := client.(interface { + GetAuthenticatedUserID(context.Context) (int, error) + }) + if !ok { + return denied + } + writer, err := identity.GetAuthenticatedUserID(ctx) + if err != nil || writer <= 0 { + return denied + } + rules, err := client.ListProtectedBranches(ctx, p.Owner, p.Repo) + if err != nil { + return denied + } + matched, canPush := false, false + for _, rule := range rules { + if rule.Name == "" || strings.ContainsAny(rule.Name, "\\?[] \t\r\n") { + return denied + } + // GitLab protected-branch patterns support '*' across path separators. + pattern := "^" + strings.ReplaceAll(regexp.QuoteMeta(rule.Name), `\*`, ".*") + "$" + if !regexp.MustCompile(pattern).MatchString(p.Branch) { + continue + } + matched = true + // Missing grant metadata cannot establish isolation. + if len(rule.PushAccessLevels) == 0 || len(rule.MergeAccessLevels) == 0 { + return denied + } + for _, grants := range [][]forge.ProtectedBranchAccess{rule.PushAccessLevels, rule.MergeAccessLevels} { + for _, grant := range grants { + if grant.GroupID != 0 || grant.DeployKeyID != 0 || grant.UserID < 0 || grant.AccessLevel < 0 { + return denied + } + if grant.UserID == writer { + continue + } + if grant.UserID != 0 || grant.AccessLevel != 0 { + return denied + } + } + } + for _, grant := range rule.PushAccessLevels { + if grant.UserID == writer { + canPush = true + } + } + } + if !matched || !canPush { + return denied + } + return nil +} diff --git a/internal/journalhost/profile_test.go b/internal/journalhost/profile_test.go index 61bbce01dc..a421d9f658 100644 --- a/internal/journalhost/profile_test.go +++ b/internal/journalhost/profile_test.go @@ -93,7 +93,8 @@ func TestAuthorizerBindsCredentialScopeAndProtectedBranch(t *testing.T) { require.NoError(t, err) fc := forge.NewFakeClient() fc.ProtectedBranches[p.Owner+"/"+p.Repo+"/"+p.Branch] = true - authorize := p.Authorizer(fc, getenv(env), "journal-private-token") + fc.ProtectedBranchRules[p.Owner+"/"+p.Repo+"/"+p.Branch] = &forge.ProtectedBranchRule{Name: p.Branch, PushAccessLevels: []forge.ProtectedBranchAccess{{UserID: 42}}, MergeAccessLevels: []forge.ProtectedBranchAccess{{AccessLevel: 0}}} + authorize := p.Authorizer(writerClient{FakeClient: fc, id: 42}, getenv(env), "journal-private-token") for _, action := range []string{"initialize", "read", "write"} { require.NoError(t, authorize(ctx, p.Location(), action)) } @@ -105,6 +106,7 @@ func TestAuthorizerBindsCredentialScopeAndProtectedBranch(t *testing.T) { require.ErrorIs(t, authorize(ctx, p.Location(), "write"), gitlabroles.ErrIdentityMismatch) env[gitlabroles.CustomSecretName("journal")] = "journal-private-token" fc.ProtectedBranches[p.Owner+"/"+p.Repo+"/"+p.Branch] = false + delete(fc.ProtectedBranchRules, p.Owner+"/"+p.Repo+"/"+p.Branch) require.Error(t, authorize(ctx, p.Location(), "write")) fc.Errors["IsProtectedBranch"] = errors.New("server says journal-private-token") err = authorize(ctx, p.Location(), "write") @@ -135,7 +137,8 @@ func TestAuthorizerStopsWhenProtectedProfileChanges(t *testing.T) { require.NoError(t, err) fc := forge.NewFakeClient() fc.ProtectedBranches[p.Owner+"/"+p.Repo+"/"+p.Branch] = true - authorize := p.Authorizer(fc, getenv(env), "journal-private-token") + fc.ProtectedBranchRules[p.Owner+"/"+p.Repo+"/"+p.Branch] = &forge.ProtectedBranchRule{Name: p.Branch, PushAccessLevels: []forge.ProtectedBranchAccess{{UserID: 42}}, MergeAccessLevels: []forge.ProtectedBranchAccess{{AccessLevel: 0}}} + authorize := p.Authorizer(writerClient{FakeClient: fc, id: 42}, getenv(env), "journal-private-token") require.NoError(t, authorize(context.Background(), p.Location(), "write")) delete(env, ProfileEnv) require.Error(t, authorize(context.Background(), p.Location(), "write")) @@ -153,3 +156,72 @@ func TestJournalCredentialCannotReuseAssessmentRole(t *testing.T) { require.Empty(t, token) require.NotContains(t, err.Error(), "assessment-only-secret") } + +type writerClient struct { + *forge.FakeClient + id int + identityErr error +} + +func (c writerClient) GetAuthenticatedUserID(context.Context) (int, error) { + return c.id, c.identityErr +} + +func TestAuthorizerRequiresWriterOnlyEffectiveGrants(t *testing.T) { + for _, tc := range []struct { + name string + push, merge []forge.ProtectedBranchAccess + pattern string + denied bool + }{ + {"writer", []forge.ProtectedBranchAccess{{UserID: 42}}, []forge.ProtectedBranchAccess{{UserID: 42}}, "fullsend-*", false}, + {"developer push", []forge.ProtectedBranchAccess{{AccessLevel: 30}}, []forge.ProtectedBranchAccess{{}}, "*", true}, + {"maintainer merge", []forge.ProtectedBranchAccess{{UserID: 42}}, []forge.ProtectedBranchAccess{{AccessLevel: 40}}, "*", true}, + {"other user", []forge.ProtectedBranchAccess{{UserID: 43}}, []forge.ProtectedBranchAccess{{}}, "*", true}, + {"group", []forge.ProtectedBranchAccess{{GroupID: 3}}, []forge.ProtectedBranchAccess{{}}, "*", true}, + {"key", []forge.ProtectedBranchAccess{{DeployKeyID: 3, AccessLevel: 40}}, []forge.ProtectedBranchAccess{{}}, "*", true}, + {"missing push", nil, []forge.ProtectedBranchAccess{{}}, "*", true}, + {"missing merge", []forge.ProtectedBranchAccess{{UserID: 42}}, nil, "*", true}, + {"unknown pattern", []forge.ProtectedBranchAccess{{UserID: 42}}, []forge.ProtectedBranchAccess{{}}, "fullsend-?", true}, + {"unrelated broad rule", []forge.ProtectedBranchAccess{{AccessLevel: 30}}, []forge.ProtectedBranchAccess{{AccessLevel: 30}}, "other*", false}, + } { + t.Run(tc.name, func(t *testing.T) { + env := trustedEnv(t) + p, err := Load(getenv(env)) + require.NoError(t, err) + fc := forge.NewFakeClient() + key := p.Owner + "/" + p.Repo + "/" + fc.ProtectedBranches[key+p.Branch] = true + fc.ProtectedBranchRules[key+p.Branch] = &forge.ProtectedBranchRule{Name: p.Branch, PushAccessLevels: []forge.ProtectedBranchAccess{{UserID: 42}}, MergeAccessLevels: []forge.ProtectedBranchAccess{{}}} + fc.ProtectedBranchRules[key+tc.pattern] = &forge.ProtectedBranchRule{Name: tc.pattern, PushAccessLevels: tc.push, MergeAccessLevels: tc.merge} + err = p.Authorizer(writerClient{FakeClient: fc, id: 42}, getenv(env), "journal-private-token")(context.Background(), p.Location(), "write") + if tc.denied { + require.Error(t, err) + } else { + require.NoError(t, err) + } + }) + } +} + +func TestWriterIsolationFailsClosed(t *testing.T) { + env := trustedEnv(t) + p, err := Load(getenv(env)) + require.NoError(t, err) + fc := forge.NewFakeClient() + require.Error(t, p.verifyWriterIsolation(context.Background(), fc)) + require.Error(t, p.verifyWriterIsolation(context.Background(), writerClient{FakeClient: fc, id: 0})) + require.Error(t, p.verifyWriterIsolation(context.Background(), writerClient{FakeClient: fc, id: 42, identityErr: errors.New("denied")})) + client := writerClient{FakeClient: fc, id: 42} + require.Error(t, p.verifyWriterIsolation(context.Background(), client)) + fc.Errors["ListProtectedBranches"] = errors.New("denied") + require.Error(t, p.verifyWriterIsolation(context.Background(), client)) + delete(fc.Errors, "ListProtectedBranches") + key := p.Owner + "/" + p.Repo + "/" + for _, grants := range [][]forge.ProtectedBranchAccess{{{}}, {{UserID: -1}}, {{AccessLevel: -1}}} { + fc.ProtectedBranchRules[key+p.Branch] = &forge.ProtectedBranchRule{Name: p.Branch, PushAccessLevels: grants, MergeAccessLevels: []forge.ProtectedBranchAccess{{}}} + require.Error(t, p.verifyWriterIsolation(context.Background(), client)) + } + fc.ProtectedBranchRules[key+p.Branch] = &forge.ProtectedBranchRule{Name: "", PushAccessLevels: []forge.ProtectedBranchAccess{{UserID: 42}}} + require.Error(t, p.verifyWriterIsolation(context.Background(), client)) +} From 9498f5a3f1ee15e2c99f0a27a6795e52d1f28c52 Mon Sep 17 00:00:00 2001 From: eshulman2 Date: Mon, 30 Nov 2026 15:10:15 +0200 Subject: [PATCH 3/5] fix(journal): address recovery journal review findings Signed-off-by: eshulman2 --- internal/cli/journal.go | 42 ++-- internal/cli/journal_retry_test.go | 38 ++-- internal/cli/journal_test.go | 52 +++-- internal/forge/gitlab/versioned_file_test.go | 45 ++++- internal/journal/forge.go | 17 +- internal/journal/forge_checkpoint_test.go | 21 +- internal/journal/journal.go | 53 +++-- internal/journal/journal_test.go | 186 ++++++++++++++---- internal/journal/requirements_test.go | 84 ++++---- internal/journalhost/profile.go | 30 +-- .../{journal/json.go => strictjson/decode.go} | 8 +- internal/strictjson/decode_test.go | 28 +++ 12 files changed, 392 insertions(+), 212 deletions(-) rename internal/{journal/json.go => strictjson/decode.go} (83%) create mode 100644 internal/strictjson/decode_test.go diff --git a/internal/cli/journal.go b/internal/cli/journal.go index f0019d3853..c713a8dda5 100644 --- a/internal/cli/journal.go +++ b/internal/cli/journal.go @@ -8,14 +8,19 @@ import ( "os" "time" + "github.com/spf13/cobra" + "github.com/fullsend-ai/fullsend/internal/journal" "github.com/fullsend-ai/fullsend/internal/journalhost" - "github.com/spf13/cobra" ) -var openJournalHost = journalhost.Open +type journalHostOpener func(func(string) string) (*journal.Engine, *journal.ForgeBackend, error) func newJournalCmd() *cobra.Command { + return newJournalCmdWithHost(journalhost.Open) +} + +func newJournalCmdWithHost(openHost journalHostOpener) *cobra.Command { var id, binding, owner, kind, effectID, status, counter string var generation, limit uint64 var ttl time.Duration @@ -44,7 +49,7 @@ func newJournalCmd() *cobra.Command { if action != "initialize" && id == "" { return errors.New("--id required") } - engine, backend, err := openJournalHost(os.Getenv) + engine, backend, err := openHost(os.Getenv) if err != nil { return sanitizeJournalError(err) } @@ -118,11 +123,14 @@ func readJournalJSON(r io.Reader) (json.RawMessage, error) { return json.RawMessage(data), nil } func sanitizeJournalError(err error) error { - for _, known := range []error{journal.ErrUncertain, journal.ErrConflict, journal.ErrIntegrity, journal.ErrOwnership, journal.ErrBinding, journal.ErrNotFound, journal.ErrTransition, journal.ErrBudget, context.Canceled, context.DeadlineExceeded} { + for _, known := range []error{journal.ErrUncertain, journal.ErrIntegrity, journal.ErrOwnership, journal.ErrBinding, journal.ErrNotFound, journal.ErrTransition, journal.ErrBudget, context.Canceled, context.DeadlineExceeded} { if errors.Is(err, known) { return known } } + if journal.IsDefiniteConflict(err) { + return journal.ErrConflict + } return errors.New("journal operation failed; inspect control repository and connection permissions") } @@ -134,7 +142,7 @@ func retryJournalTransaction(ctx context.Context, operation func() (any, error)) return nil, err } result, err := operation() - if err == nil || attempt == 2 || !journalConflictOnly(err) { + if err == nil || attempt == 2 || !journal.IsDefiniteConflict(err) { return result, err } timer := time.NewTimer(time.Duration(20*(attempt+1)) * time.Millisecond) @@ -146,27 +154,3 @@ func retryJournalTransaction(ctx context.Context, operation func() (any, error)) } } } - -// A joined unknown failure can indicate an uncertain outcome even when another -// branch is a conflict. Require every leaf to be the definite-conflict sentinel. -func journalConflictOnly(err error) bool { - if !errors.Is(err, journal.ErrConflict) || errors.Is(err, journal.ErrUncertain) { - return false - } - if joined, ok := err.(interface{ Unwrap() []error }); ok { - children := joined.Unwrap() - if len(children) == 0 { - return false - } - for _, child := range children { - if !journalConflictOnly(child) { - return false - } - } - return true - } - if wrapped, ok := err.(interface{ Unwrap() error }); ok { - return journalConflictOnly(wrapped.Unwrap()) - } - return err == journal.ErrConflict -} diff --git a/internal/cli/journal_retry_test.go b/internal/cli/journal_retry_test.go index 0e452e8f03..8562a55e38 100644 --- a/internal/cli/journal_retry_test.go +++ b/internal/cli/journal_retry_test.go @@ -42,6 +42,9 @@ func TestJournalTransactionRetriesOnlyDefiniteConflicts(t *testing.T) { _, err := retryJournalTransaction(context.Background(), func() (any, error) { calls++; return nil, tc.err }) require.ErrorIs(t, err, tc.err) require.Equal(t, tc.calls, calls) + sanitized := sanitizeJournalError(err) + require.Equal(t, tc.calls > 1, errors.Is(sanitized, journal.ErrConflict)) + require.NotContains(t, sanitized.Error(), "secret") }) } calls := 0 @@ -125,11 +128,10 @@ func TestJournalCLIConflictReloadsAuthorityAndReusesInput(t *testing.T) { } d.Records["case"] = r } - old := openJournalHost - openJournalHost = func(func(string) string) (*journal.Engine, *journal.ForgeBackend, error) { + opener := func(func(string) string) (*journal.Engine, *journal.ForgeBackend, error) { return journal.New(b, nil), nil, nil } - t.Cleanup(func() { openJournalHost = old }) + args := []string{"update", "--id", "case", "--owner", "worker", "--generation", "1"} var want error switch change { @@ -152,7 +154,7 @@ func TestJournalCLIConflictReloadsAuthorityAndReusesInput(t *testing.T) { delete(b.doc.Records, "case") b.concurrent = func(d *journal.Document) { r := record; r.Binding = "changed"; d.Records["case"] = r } } - output, err := runJournal(t, `{"payload":"read once"}`, args...) + output, err := runJournal(t, opener, `{"payload":"read once"}`, args...) if want != nil { require.ErrorIs(t, err, want) require.NotContains(t, output, `"payload":"read once"`) @@ -178,16 +180,15 @@ func TestJournalCLILostAcknowledgementDoesNotRepeatSpendOrClaim(t *testing.T) { } b := &retryJournalBackend{doc: journal.Empty(), uncertain: true} b.doc.Records["case"] = r - old := openJournalHost - openJournalHost = func(func(string) string) (*journal.Engine, *journal.ForgeBackend, error) { + opener := func(func(string) string) (*journal.Engine, *journal.ForgeBackend, error) { return journal.New(b, nil), nil, nil } - t.Cleanup(func() { openJournalHost = old }) + args := []string{action, "--id", "case", "--owner", "worker"} if action == "spend" { args = append(args, "--generation", "1", "--counter", "attempts", "--limit", "3") } - _, err := runJournal(t, "", args...) + _, err := runJournal(t, opener, "", args...) require.Equal(t, journal.ErrUncertain, err) require.Equal(t, 1, b.loads) require.Equal(t, 1, b.writes) @@ -204,12 +205,11 @@ func TestJournalCLIInitializeDoesNotRetryConflict(t *testing.T) { calls := 0 backend, err := journal.NewForgeBackend(forge.NewFakeClient(), journal.Location{Owner: "o", Repo: "r", Branch: "journal", Path: "state.json"}, func(context.Context, journal.Location, string) error { calls++; return journal.ErrConflict }) require.NoError(t, err) - old := openJournalHost - openJournalHost = func(func(string) string) (*journal.Engine, *journal.ForgeBackend, error) { + opener := func(func(string) string) (*journal.Engine, *journal.ForgeBackend, error) { return journal.New(backend, nil), backend, nil } - t.Cleanup(func() { openJournalHost = old }) - _, err = runJournal(t, "", "initialize") + + _, err = runJournal(t, opener, "", "initialize") require.ErrorIs(t, err, journal.ErrConflict) require.Equal(t, 1, calls) } @@ -248,11 +248,10 @@ func TestJournalCLIRetryRejectsStaleParentEvenWhenMutationBecomesNoop(t *testing } d.Records["case"] = child } - old := openJournalHost - openJournalHost = func(func(string) string) (*journal.Engine, *journal.ForgeBackend, error) { + opener := func(func(string) string) (*journal.Engine, *journal.ForgeBackend, error) { return journal.New(b, nil), nil, nil } - t.Cleanup(func() { openJournalHost = old }) + sum := sha256.Sum256(parent.Data) args := []string{action, "--id", "case", "--require-record", "parent", "--require-binding", "parent-sha", "--require-data-digest", hex.EncodeToString(sum[:])} if action == "admit" { @@ -263,7 +262,7 @@ func TestJournalCLIRetryRejectsStaleParentEvenWhenMutationBecomesNoop(t *testing if action == "intent" { args = append(args, "--effect-id", "publish", "--kind", "pr", "--binding", "approved") } - output, err := runJournal(t, `{"desired":true}`, args...) + output, err := runJournal(t, opener, `{"desired":true}`, args...) require.ErrorIs(t, err, journal.ErrBinding) require.NotContains(t, output, `"desired":true`) require.Equal(t, 2, b.loads) @@ -279,12 +278,11 @@ func TestJournalCLIReadAuthorizationConflictIsNotRetried(t *testing.T) { return fmt.Errorf("secret authorization failure: %w", journal.ErrConflict) }) require.NoError(t, err) - old := openJournalHost - openJournalHost = func(func(string) string) (*journal.Engine, *journal.ForgeBackend, error) { + opener := func(func(string) string) (*journal.Engine, *journal.ForgeBackend, error) { return journal.New(backend, nil), backend, nil } - t.Cleanup(func() { openJournalHost = old }) - _, err = runJournal(t, "", "spend", "--id", "case", "--owner", "worker", "--generation", "1", "--counter", "attempts", "--limit", "1") + + _, err = runJournal(t, opener, "", "spend", "--id", "case", "--owner", "worker", "--generation", "1", "--counter", "attempts", "--limit", "1") require.Error(t, err) require.NotContains(t, err.Error(), "secret") require.NotErrorIs(t, err, journal.ErrConflict) diff --git a/internal/cli/journal_test.go b/internal/cli/journal_test.go index 45bdbb9cf5..7c53e64df4 100644 --- a/internal/cli/journal_test.go +++ b/internal/cli/journal_test.go @@ -18,21 +18,19 @@ import ( "github.com/stretchr/testify/require" ) -func journalCommandFixture(t *testing.T) (*journal.Engine, *journal.ForgeBackend) { +func journalCommandFixture(t *testing.T) (*journal.Engine, *journal.ForgeBackend, journalHostOpener) { t.Helper() fc := forge.NewFakeClient() fc.BranchRefs["o/r/journal"] = "head" backend, err := journal.NewForgeBackend(fc, journal.Location{Owner: "o", Repo: "r", Branch: "journal", Path: "state.json"}, func(context.Context, journal.Location, string) error { return nil }) require.NoError(t, err) engine := journal.New(backend, nil) - old := openJournalHost - openJournalHost = func(func(string) string) (*journal.Engine, *journal.ForgeBackend, error) { return engine, backend, nil } - t.Cleanup(func() { openJournalHost = old }) - return engine, backend + opener := func(func(string) string) (*journal.Engine, *journal.ForgeBackend, error) { return engine, backend, nil } + return engine, backend, opener } -func runJournal(t *testing.T, input string, args ...string) (string, error) { +func runJournal(t *testing.T, opener journalHostOpener, input string, args ...string) (string, error) { t.Helper() - cmd := newJournalCmd() + cmd := newJournalCmdWithHost(opener) var output bytes.Buffer cmd.SetOut(&output) cmd.SetErr(io.Discard) @@ -42,13 +40,13 @@ func runJournal(t *testing.T, input string, args ...string) (string, error) { return output.String(), err } func TestJournalCLIDurableLifecycle(t *testing.T) { - engine, _ := journalCommandFixture(t) - output, err := runJournal(t, "", "initialize") + engine, _, opener := journalCommandFixture(t) + output, err := runJournal(t, opener, "", "initialize") require.NoError(t, err) require.Contains(t, output, `"initialized":true`) - _, err = runJournal(t, `{"targets":["main","release"]}`, "admit", "--id", "case", "--binding", "source-sha") + _, err = runJournal(t, opener, `{"targets":["main","release"]}`, "admit", "--id", "case", "--binding", "source-sha") require.NoError(t, err) - output, err = runJournal(t, "", "claim", "--id", "case", "--owner", "host") + output, err = runJournal(t, opener, "", "claim", "--id", "case", "--owner", "host") require.NoError(t, err) var lease journal.Lease require.NoError(t, json.Unmarshal([]byte(output), &lease)) @@ -56,7 +54,7 @@ func TestJournalCLIDurableLifecycle(t *testing.T) { flags := []string{"--id", "case", "--owner", lease.Owner, "--generation", fmt.Sprint(lease.Generation)} call := func(input, action string, extra ...string) (string, error) { args := append([]string{action}, flags...) - return runJournal(t, input, append(args, extra...)...) + return runJournal(t, opener, input, append(args, extra...)...) } _, err = call("", "intent", "--effect-id", "dispatch-1", "--kind", "dispatch", "--binding", "request-sha") require.NoError(t, err) @@ -76,7 +74,7 @@ func TestJournalCLIDurableLifecycle(t *testing.T) { require.NoError(t, err) _, err = call("", "renew", "--ttl", "10m") require.NoError(t, err) - output, err = runJournal(t, "", "read", "--id", "case") + output, err = runJournal(t, opener, "", "read", "--id", "case") require.NoError(t, err) require.Contains(t, output, `"confirmed"`) require.Contains(t, output, `"checked":true`) @@ -90,22 +88,20 @@ func TestJournalCLIDurableLifecycle(t *testing.T) { require.Equal(t, "confirmed", record.Effects["dispatch-1"].Status) } func TestJournalCLIRejectsMalformedAndUnownedOperations(t *testing.T) { - _, backend := journalCommandFixture(t) + _, backend, opener := journalCommandFixture(t) require.NoError(t, backend.Initialize(context.Background())) for _, args := range [][]string{{"unknown"}, {"read"}, {"rebind", "--id", "case", "--binding", "sha-2"}, {"admit", "--id", "case", "--binding", "sha"}, {"effect", "--id", "case", "--status", "confirmed"}} { - _, err := runJournal(t, "bad json", args...) + _, err := runJournal(t, opener, "bad json", args...) require.Error(t, err) } - _, err := runJournal(t, `{}`, "admit", "--id", "case", "--binding", "sha") + _, err := runJournal(t, opener, `{}`, "admit", "--id", "case", "--binding", "sha") require.NoError(t, err) - _, err = runJournal(t, "", "spend", "--id", "case", "--owner", "wrong", "--generation", "1", "--counter", "attempts", "--limit", "1") + _, err = runJournal(t, opener, "", "spend", "--id", "case", "--owner", "wrong", "--generation", "1", "--counter", "attempts", "--limit", "1") require.ErrorIs(t, err, journal.ErrOwnership) - old := openJournalHost - openJournalHost = func(func(string) string) (*journal.Engine, *journal.ForgeBackend, error) { + opener = func(func(string) string) (*journal.Engine, *journal.ForgeBackend, error) { return nil, nil, errors.New("transport leaked token-secret") } - t.Cleanup(func() { openJournalHost = old }) - _, err = runJournal(t, "", "read", "--id", "case") + _, err = runJournal(t, opener, "", "read", "--id", "case") require.Error(t, err) require.NotContains(t, err.Error(), "token-secret") } @@ -128,38 +124,38 @@ func TestJournalJSONBoundsAndSanitizedErrors(t *testing.T) { } func TestJournalCLIParentPredicatesRejectStaleEffect(t *testing.T) { - e, b := journalCommandFixture(t) + e, b, opener := journalCommandFixture(t) ctx := context.Background() require.NoError(t, b.Initialize(ctx)) _, err := e.Admit(ctx, "parent", "manifest", json.RawMessage(`{ "state": "admitted", "html": "<&>" }`)) require.NoError(t, err) - output, err := runJournal(t, "", "read", "--id", "parent") + output, err := runJournal(t, opener, "", "read", "--id", "parent") require.NoError(t, err) var parent journal.Record require.NoError(t, json.Unmarshal([]byte(output), &parent)) sum := sha256.Sum256(parent.Data) flags := []string{"--require-record", "parent", "--require-binding", "manifest", "--require-data-digest", hex.EncodeToString(sum[:])} - _, err = runJournal(t, `{}`, append([]string{"admit", "--id", "child", "--binding", "plan"}, flags...)...) + _, err = runJournal(t, opener, `{}`, append([]string{"admit", "--id", "child", "--binding", "plan"}, flags...)...) require.NoError(t, err) lease, err := e.Claim(ctx, "child", "worker", time.Minute) require.NoError(t, err) args := append([]string{"intent", "--id", "child", "--owner", "worker", "--generation", fmt.Sprint(lease.Generation), "--effect-id", "publish", "--kind", "pr", "--binding", "approved"}, flags...) - _, err = runJournal(t, "", args...) + _, err = runJournal(t, opener, "", args...) require.NoError(t, err) parentLease, err := e.Claim(ctx, "parent", "controller", time.Minute) require.NoError(t, err) _, err = e.Update(ctx, "parent", parentLease, func(r *journal.Record) error { r.Data = json.RawMessage(`{"state":"revoked"}`); return nil }) require.NoError(t, err) - _, err = runJournal(t, "", append([]string{"effect", "--id", "child", "--owner", "worker", "--generation", fmt.Sprint(lease.Generation), "--effect-id", "publish", "--status", "in_flight"}, flags...)...) + _, err = runJournal(t, opener, "", append([]string{"effect", "--id", "child", "--owner", "worker", "--generation", fmt.Sprint(lease.Generation), "--effect-id", "publish", "--status", "in_flight"}, flags...)...) require.ErrorIs(t, err, journal.ErrBinding) child, err := e.Read(ctx, "child") require.NoError(t, err) require.Equal(t, "intended", child.Effects["publish"].Status) // Read remains available, while malformed/partial/self requirements fail closed. - _, err = runJournal(t, "", append([]string{"read", "--id", "child"}, flags...)...) + _, err = runJournal(t, opener, "", append([]string{"read", "--id", "child"}, flags...)...) require.NoError(t, err) for _, a := range [][]string{{"initialize", "--require-record", "parent"}, {"read", "--id", "parent", "--require-record", "parent"}, {"read", "--id", "child", "--require-binding", "manifest"}} { - _, err = runJournal(t, "", a...) + _, err = runJournal(t, opener, "", a...) require.ErrorIs(t, err, journal.ErrBinding) } } diff --git a/internal/forge/gitlab/versioned_file_test.go b/internal/forge/gitlab/versioned_file_test.go index aacbf8888a..772136a1d1 100644 --- a/internal/forge/gitlab/versioned_file_test.go +++ b/internal/forge/gitlab/versioned_file_test.go @@ -9,8 +9,10 @@ import ( "sync/atomic" "testing" - "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/forge" ) func TestReadVersionedFileRequiresLastCommit(t *testing.T) { @@ -18,7 +20,7 @@ func TestReadVersionedFileRequiresLastCommit(t *testing.T) { t.Run(body, func(t *testing.T) { c, mux := setupTest(t) mux.HandleFunc("GET /api/v4/projects/o%2Fr/repository/files/journal.json", func(w http.ResponseWriter, r *http.Request) { - require.Equal(t, "state", r.URL.Query().Get("ref")) + assert.Equal(t, "state", r.URL.Query().Get("ref")) fmt.Fprint(w, body) }) data, rev, err := c.ReadVersionedFile(context.Background(), "o", "r", "state", "journal.json") @@ -38,10 +40,10 @@ func TestWriteVersionedFileUsesAtomicLastCommitGuard(t *testing.T) { mux.HandleFunc("PUT /api/v4/projects/o%2Fr/repository/files/journal.json", func(w http.ResponseWriter, r *http.Request) { put.Add(1) var payload map[string]string - require.NoError(t, json.NewDecoder(r.Body).Decode(&payload)) - require.Equal(t, "file-revision", payload["last_commit_id"]) - require.Equal(t, "state", payload["branch"]) - require.Equal(t, base64.StdEncoding.EncodeToString([]byte("next")), payload["content"]) + assert.NoError(t, json.NewDecoder(r.Body).Decode(&payload)) + assert.Equal(t, "file-revision", payload["last_commit_id"]) + assert.Equal(t, "state", payload["branch"]) + assert.Equal(t, base64.StdEncoding.EncodeToString([]byte("next")), payload["content"]) fmt.Fprint(w, `{"file_path":"journal.json"}`) }) require.NoError(t, c.WriteFileIfRevision(context.Background(), "o", "r", "state", "journal.json", "file-revision", "checkpoint [skip ci]", []byte("next"))) @@ -72,8 +74,8 @@ func TestVersionedCreateNeverUpserts(t *testing.T) { c, mux := setupTest(t) mux.HandleFunc("POST /api/v4/projects/o%2Fr/repository/files/journal.json", func(w http.ResponseWriter, r *http.Request) { var payload map[string]string - require.NoError(t, json.NewDecoder(r.Body).Decode(&payload)) - require.NotContains(t, payload, "last_commit_id") + assert.NoError(t, json.NewDecoder(r.Body).Decode(&payload)) + assert.NotContains(t, payload, "last_commit_id") w.WriteHeader(http.StatusBadRequest) fmt.Fprint(w, `{"message":"A file with this name already exists"}`) }) @@ -109,7 +111,7 @@ func TestVersionedWriteRecognizesOnlyExactReferenceRaceRejection(t *testing.T) { mux.HandleFunc("PUT /api/v4/projects/o%2Fr/repository/files/journal.json", func(w http.ResponseWriter, r *http.Request) { calls.Add(1) w.WriteHeader(tc.status) - require.NoError(t, json.NewEncoder(w).Encode(map[string]string{"message": tc.message})) + assert.NoError(t, json.NewEncoder(w).Encode(map[string]string{"message": tc.message})) }) err := c.WriteFileIfRevision(context.Background(), "o", "r", "state", "journal.json", "old", "checkpoint", []byte("next")) require.Error(t, err) @@ -140,3 +142,28 @@ func TestJournalWriteNeverFollowsRedirect(t *testing.T) { require.EqualValues(t, 1, calls.Load()) require.Zero(t, redirects.Load()) } + +func TestVersionedCreateAcceptsCreated(t *testing.T) { + c, mux := setupTest(t) + var calls atomic.Int32 + mux.HandleFunc("POST /api/v4/projects/o%2Fr/repository/files/journal.json", func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + var payload map[string]string + if err := json.NewDecoder(r.Body).Decode(&payload); err != nil { + t.Errorf("decode create payload: %v", err) + w.WriteHeader(http.StatusBadRequest) + return + } + if _, exists := payload["last_commit_id"]; exists { + t.Error("create sent last_commit_id") + } + w.WriteHeader(http.StatusCreated) + fmt.Fprint(w, `{"file_path":"journal.json","branch":"state"}`) + }) + if err := c.WriteFileIfRevision(context.Background(), "o", "r", "state", "journal.json", "", "initialize", []byte("x")); err != nil { + t.Fatalf("create versioned file: %v", err) + } + if got := calls.Load(); got != 1 { + t.Errorf("create calls = %d, want 1", got) + } +} diff --git a/internal/journal/forge.go b/internal/journal/forge.go index c5448a422c..99bc7952e7 100644 --- a/internal/journal/forge.go +++ b/internal/journal/forge.go @@ -77,7 +77,7 @@ func (b *ForgeBackend) CompareAndSwap(ctx context.Context, rev string, d Documen return "", err } err = b.client.WriteFileIfRevision(ctx, b.location.Owner, b.location.Repo, b.location.Branch, b.location.Path, rev, "Checkpoint Fullsend journal [skip ci]", data) - if definitiveWriteConflict(err) { + if onlyConflict(err, forge.ErrConflict) { return "", ErrConflict } if err != nil { @@ -110,11 +110,16 @@ func (b *ForgeBackend) CompareAndSwap(ctx context.Context, rev string, d Documen return newRev, nil } -// definitiveWriteConflict requires every leaf to be the forge's conditional +// IsDefiniteConflict reports whether a journal transaction can be retried. +func IsDefiniteConflict(err error) bool { + return errors.Is(err, ErrConflict) && !errors.Is(err, ErrUncertain) && onlyConflict(err, ErrConflict) +} + +// onlyConflict requires every leaf to be the forge's conditional // rejection sentinel. errors.Is alone also accepts mixed lost-ACK/conflict joins. // Unknown wrappers with custom Is methods cannot prove non-commitment. -func definitiveWriteConflict(err error) bool { - if err == forge.ErrConflict { +func onlyConflict(err, sentinel error) bool { + if err == sentinel { return true } switch wrapped := err.(type) { @@ -124,13 +129,13 @@ func definitiveWriteConflict(err error) bool { return false } for _, child := range children { - if !definitiveWriteConflict(child) { + if !onlyConflict(child, sentinel) { return false } } return true case interface{ Unwrap() error }: - return definitiveWriteConflict(wrapped.Unwrap()) + return onlyConflict(wrapped.Unwrap(), sentinel) default: return false } diff --git a/internal/journal/forge_checkpoint_test.go b/internal/journal/forge_checkpoint_test.go index d7cffdda36..55c7a9792f 100644 --- a/internal/journal/forge_checkpoint_test.go +++ b/internal/journal/forge_checkpoint_test.go @@ -205,7 +205,7 @@ func TestDefinitiveWriteConflict(t *testing.T) { {"mixed", errors.Join(forge.ErrConflict, errors.New("unknown")), false}, {"empty-join", emptyConflictJoin{}, false}, } { - t.Run(tc.name, func(t *testing.T) { require.Equal(t, tc.definite, definitiveWriteConflict(tc.err)) }) + t.Run(tc.name, func(t *testing.T) { require.Equal(t, tc.definite, onlyConflict(tc.err, forge.ErrConflict)) }) } } @@ -229,3 +229,22 @@ func TestCheckpointLoadCannotSupplyRetryableConflict(t *testing.T) { }) } } + +func TestIsDefiniteConflict(t *testing.T) { + for _, tc := range []struct { + name string + err error + want bool + }{ + {"journal conflict", fmt.Errorf("wrapped: %w", ErrConflict), true}, + {"forge conflict", forge.ErrConflict, false}, + {"uncertain journal conflict", errors.Join(ErrConflict, ErrUncertain), false}, + {"unknown journal conflict", errors.Join(ErrConflict, errors.New("unknown")), false}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := IsDefiniteConflict(tc.err); got != tc.want { + t.Errorf("IsDefiniteConflict(%v) = %t, want %t", tc.err, got, tc.want) + } + }) + } +} diff --git a/internal/journal/journal.go b/internal/journal/journal.go index eaa9d93427..d68aba3914 100644 --- a/internal/journal/journal.go +++ b/internal/journal/journal.go @@ -12,6 +12,8 @@ import ( "reflect" "regexp" "time" + + "github.com/fullsend-ai/fullsend/internal/strictjson" ) var ( @@ -26,21 +28,29 @@ var ( ErrBudget = errors.New("journal budget exhausted") ) +// MaxDocumentBytes bounds the encoded journal size. const MaxDocumentBytes = 4 << 20 const ( - EffectIntended = "intended" - EffectInFlight = "in_flight" + // EffectIntended records an effect before execution. + EffectIntended = "intended" + // EffectInFlight marks an effect whose execution has begun. + EffectInFlight = "in_flight" + // EffectAmbiguous marks an effect with an unknown outcome. EffectAmbiguous = "ambiguous" + // EffectConfirmed marks an effect with a durable receipt. EffectConfirmed = "confirmed" ) var identity = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_.:-]{0,255}$`) +// Lease identifies the current owner and its fencing generation. type Lease struct { Owner string `json:"owner"` Generation uint64 `json:"generation"` ExpiresAt time.Time `json:"expires_at"` } + +// Effect tracks an external operation and any confirmation receipt. type Effect struct { ID string `json:"id"` Kind string `json:"kind"` @@ -48,6 +58,8 @@ type Effect struct { Status string `json:"status"` Receipt json.RawMessage `json:"receipt,omitempty"` } + +// Record holds a recoverable operation and its durable state. type Record struct { ID string `json:"id"` Binding string `json:"binding"` @@ -57,6 +69,8 @@ type Record struct { Counters map[string]uint64 `json:"counters"` Effects map[string]Effect `json:"effects"` } + +// Document is the complete checksummed journal. type Document struct { SchemaVersion int `json:"schema_version"` Records map[string]Record `json:"records"` @@ -81,11 +95,16 @@ func New(backend Backend, clock func() time.Time) *Engine { return &Engine{backend: backend, clock: clock} } func Empty() Document { return Document{SchemaVersion: 1, Records: map[string]Record{}} } -func clone[T any](v T) T { - b, _ := json.Marshal(v) +func clone[T any](v T) (T, error) { var result T - _ = json.Unmarshal(b, &result) - return result + b, err := json.Marshal(v) + if err != nil { + return result, ErrIntegrity + } + if err := json.Unmarshal(b, &result); err != nil { + return result, ErrIntegrity + } + return result, nil } func (e *Engine) load(ctx context.Context) (Document, string, error) { if e.backend == nil { @@ -153,7 +172,11 @@ func (e *Engine) Admit(ctx context.Context, id, binding string, data json.RawMes } return &old, nil } - r := Record{ID: id, Binding: binding, Data: clone(data), Counters: map[string]uint64{}, Effects: map[string]Effect{}} + copiedData, err := clone(data) + if err != nil { + return nil, err + } + r := Record{ID: id, Binding: binding, Data: copiedData, Counters: map[string]uint64{}, Effects: map[string]Effect{}} d.Records[id] = r if err = e.save(ctx, d, rev, id); err != nil { return nil, err @@ -204,7 +227,10 @@ func (e *Engine) Update(ctx context.Context, id string, l Lease, update func(*Re if !e.owns(old, l) { return nil, ErrOwnership } - next := clone(old) + next, err := clone(old) + if err != nil { + return nil, err + } if update == nil { return nil, ErrTransition } @@ -242,7 +268,10 @@ func (e *Engine) Rebind(ctx context.Context, id string, l Lease, binding string, return nil, ErrOwnership } r.Binding = binding - r.Data = clone(data) + r.Data, err = clone(data) + if err != nil { + return nil, err + } d.Records[id] = r if err = e.save(ctx, d, rev, id); err != nil { return nil, err @@ -363,7 +392,7 @@ func validateDocument(d Document) error { return ErrIntegrity } for key, r := range d.Records { - if !identity.MatchString(key) || r.ID != key || r.Binding == "" || len(r.Binding) > 1024 || strictDecode(r.Data, new(any)) != nil || r.Counters == nil || r.Effects == nil || len(r.Counters) > 256 || len(r.Effects) > 1000 { + if !identity.MatchString(key) || r.ID != key || r.Binding == "" || len(r.Binding) > 1024 || strictjson.Decode(r.Data, new(any)) != nil || r.Counters == nil || r.Effects == nil || len(r.Counters) > 256 || len(r.Effects) > 1000 { return ErrIntegrity } if r.Lease.Generation != r.Generation && r.Lease.Owner != "" { @@ -384,7 +413,7 @@ func validateDocument(d Document) error { return ErrIntegrity } case "confirmed": - if strictDecode(effect.Receipt, new(any)) != nil || bytes.Equal(bytes.TrimSpace(effect.Receipt), []byte("null")) { + if strictjson.Decode(effect.Receipt, new(any)) != nil || bytes.Equal(bytes.TrimSpace(effect.Receipt), []byte("null")) { return ErrIntegrity } default: @@ -423,7 +452,7 @@ func Decode(data []byte) (Document, error) { if len(data) > MaxDocumentBytes { return d, ErrIntegrity } - if err := strictDecode(data, &d); err != nil { + if err := strictjson.Decode(data, &d); err != nil { return d, ErrIntegrity } if err := validateDocument(d); err != nil { diff --git a/internal/journal/journal_test.go b/internal/journal/journal_test.go index b82af1d424..738cc43e5b 100644 --- a/internal/journal/journal_test.go +++ b/internal/journal/journal_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "fmt" "strings" "sync" "sync/atomic" @@ -37,14 +38,16 @@ func TestAdmissionOwnershipAndRestart(t *testing.T) { ctx := context.Background() e, b, _, now := fixture(t) l := admitted(t, e) - r, err := e.Admit(ctx, "case-1", "binding-1", json.RawMessage(`{}`)) - require.NoError(t, err) - require.Contains(t, string(r.Data), "required") - _, err = e.Admit(ctx, "case-1", "different", json.RawMessage(`{}`)) - require.ErrorIs(t, err, ErrBinding) - _, err = e.Claim(ctx, "case-1", "host-2", time.Minute) - require.ErrorIs(t, err, ErrOwnership) - _, err = e.Spend(ctx, "case-1", l, "attempts-a", 2) + t.Run("idempotent admission and exclusive claim", func(t *testing.T) { + r, err := e.Admit(ctx, "case-1", "binding-1", json.RawMessage(`{}`)) + require.NoError(t, err) + require.Contains(t, string(r.Data), "required") + _, err = e.Admit(ctx, "case-1", "different", json.RawMessage(`{}`)) + require.ErrorIs(t, err, ErrBinding) + _, err = e.Claim(ctx, "case-1", "host-2", time.Minute) + require.ErrorIs(t, err, ErrOwnership) + }) + _, err := e.Spend(ctx, "case-1", l, "attempts-a", 2) require.NoError(t, err) *now = now.Add(2 * time.Minute) replacement := New(b, func() time.Time { return *now }) @@ -53,7 +56,7 @@ func TestAdmissionOwnershipAndRestart(t *testing.T) { require.Greater(t, l2.Generation, l.Generation) _, err = e.Spend(ctx, "case-1", l, "attempts-a", 2) require.ErrorIs(t, err, ErrOwnership) - r, err = replacement.Rebind(ctx, "case-1", l2, "binding-2", json.RawMessage(`{"required":["a","b","c"]}`)) + r, err := replacement.Rebind(ctx, "case-1", l2, "binding-2", json.RawMessage(`{"required":["a","b","c"]}`)) require.NoError(t, err) require.Equal(t, uint64(1), r.Counters["attempts-a"]) _, err = replacement.Spend(ctx, "case-1", l2, "attempts-a", 2) @@ -193,33 +196,45 @@ func TestStrictDocumentIntegrity(t *testing.T) { func TestInvalidArgumentsAndMissingRecords(t *testing.T) { ctx := context.Background() e, _, _, _ := fixture(t) - _, err := e.Read(ctx, "missing") - require.ErrorIs(t, err, ErrNotFound) - for _, id := range []string{"", "../x"} { - _, err = e.Admit(ctx, id, "b", json.RawMessage(`{}`)) + t.Run("read missing record", func(t *testing.T) { + _, err := e.Read(ctx, "missing") + require.ErrorIs(t, err, ErrNotFound) + }) + t.Run("invalid admission", func(t *testing.T) { + for _, id := range []string{"", "../x"} { + _, err := e.Admit(ctx, id, "b", json.RawMessage(`{}`)) + require.Error(t, err) + } + _, err := e.Admit(ctx, "case", "", json.RawMessage(`{}`)) require.Error(t, err) - } - _, err = e.Admit(ctx, "case", "", json.RawMessage(`{}`)) - require.Error(t, err) - _, err = e.Claim(ctx, "missing", "host", time.Minute) - require.ErrorIs(t, err, ErrNotFound) - for _, ttl := range []time.Duration{0, 25 * time.Hour} { - _, err = e.Claim(ctx, "missing", "host", ttl) - require.ErrorIs(t, err, ErrOwnership) - _, err = e.Renew(ctx, "missing", Lease{}, ttl) - require.ErrorIs(t, err, ErrOwnership) - } - _, err = e.Update(ctx, "missing", Lease{}, func(*Record) error { return nil }) - require.ErrorIs(t, err, ErrNotFound) - _, err = e.Rebind(ctx, "missing", Lease{}, "new", json.RawMessage(`{}`)) - require.ErrorIs(t, err, ErrNotFound) - _, err = e.Rebind(ctx, "missing", Lease{}, "", nil) - require.ErrorIs(t, err, ErrBinding) - require.ErrorIs(t, e.Release(ctx, "missing", Lease{}), ErrNotFound) - _, err = e.Renew(ctx, "missing", Lease{}, time.Minute) - require.ErrorIs(t, err, ErrNotFound) - _, err = New(nil, nil).Read(ctx, "missing") - require.ErrorIs(t, err, ErrIntegrity) + }) + t.Run("claim missing record", func(t *testing.T) { + _, err := e.Claim(ctx, "missing", "host", time.Minute) + require.ErrorIs(t, err, ErrNotFound) + }) + t.Run("invalid TTL", func(t *testing.T) { + for _, ttl := range []time.Duration{0, 25 * time.Hour} { + _, err := e.Claim(ctx, "missing", "host", ttl) + require.ErrorIs(t, err, ErrOwnership) + _, err = e.Renew(ctx, "missing", Lease{}, ttl) + require.ErrorIs(t, err, ErrOwnership) + } + }) + t.Run("missing record mutations", func(t *testing.T) { + _, err := e.Update(ctx, "missing", Lease{}, func(*Record) error { return nil }) + require.ErrorIs(t, err, ErrNotFound) + _, err = e.Rebind(ctx, "missing", Lease{}, "new", json.RawMessage(`{}`)) + require.ErrorIs(t, err, ErrNotFound) + _, err = e.Rebind(ctx, "missing", Lease{}, "", nil) + require.ErrorIs(t, err, ErrBinding) + require.ErrorIs(t, e.Release(ctx, "missing", Lease{}), ErrNotFound) + _, err = e.Renew(ctx, "missing", Lease{}, time.Minute) + require.ErrorIs(t, err, ErrNotFound) + }) + t.Run("missing backend", func(t *testing.T) { + _, err := New(nil, nil).Read(ctx, "missing") + require.ErrorIs(t, err, ErrIntegrity) + }) } func TestDuplicatePayloadKeysRejectedBeforeWriting(t *testing.T) { @@ -232,3 +247,104 @@ func TestDuplicatePayloadKeysRejectedBeforeWriting(t *testing.T) { _, err = engine.Read(ctx, "good") require.NoError(t, err) } + +func TestConfirmedEffectRequiresReceiptBeforeWrite(t *testing.T) { + for _, tc := range []struct { + name string + receipt json.RawMessage + }{ + {name: "missing"}, + {name: "null", receipt: json.RawMessage("null")}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + e, backend, _, _ := fixture(t) + lease := admitted(t, e) + _, err := e.Intent(ctx, "case-1", lease, Effect{ID: "publish", Kind: "pr", Binding: "approved", Status: EffectIntended}) + require.NoError(t, err) + + attempted := false + guarded := New(&hookCAS{Backend: backend, hook: func() { attempted = true }}, e.clock) + _, err = guarded.Effect(ctx, "case-1", lease, "publish", EffectConfirmed, tc.receipt) + if !errors.Is(err, ErrIntegrity) || attempted { + t.Fatalf("invalid receipt returned %v, write attempted: %t", err, attempted) + } + }) + } +} + +func TestClaimRejectsGenerationOverflow(t *testing.T) { + ctx := context.Background() + e, backend, _, _ := fixture(t) + d, rev, err := backend.Load(ctx) + require.NoError(t, err) + d.Records["max"] = Record{ + ID: "max", Binding: "binding", Generation: ^uint64(0), + Data: json.RawMessage(`{}`), Counters: map[string]uint64{}, Effects: map[string]Effect{}, + } + _, err = backend.CompareAndSwap(ctx, rev, d) + require.NoError(t, err) + _, err = e.Claim(ctx, "max", "worker", time.Minute) + require.ErrorIs(t, err, ErrOwnership) +} + +func TestJournalDocumentCardinality(t *testing.T) { + for _, tc := range []struct { + name string + limit int + add func(Document, Record, string) + }{ + {"records", 1000, func(d Document, r Record, id string) { r.ID = id; d.Records[id] = r }}, + {"counters", 256, func(_ Document, r Record, id string) { r.Counters[id] = 1 }}, + {"effects", 1000, func(_ Document, r Record, id string) { + r.Effects[id] = Effect{ID: id, Kind: "publish", Binding: "approved", Status: EffectIntended} + }}, + } { + t.Run(tc.name, func(t *testing.T) { + d := Empty() + r := Record{ID: "base", Binding: "binding", Data: json.RawMessage(`{}`), Counters: map[string]uint64{}, Effects: map[string]Effect{}} + d.Records[r.ID] = r + count := tc.limit + if tc.name == "records" { + count-- + } + for i := range count { + tc.add(d, r, fmt.Sprint(i)) + } + require.NoError(t, validateDocument(d)) + tc.add(d, r, "extra") + require.ErrorIs(t, validateDocument(d), ErrIntegrity) + }) + } +} + +func TestEffectRejectsUnknownIDAndPrematureReceipt(t *testing.T) { + ctx := context.Background() + e, _, _, _ := fixture(t) + lease := admitted(t, e) + t.Run("unknown effect", func(t *testing.T) { + _, err := e.Effect(ctx, "case-1", lease, "missing", EffectInFlight, nil) + require.ErrorIs(t, err, ErrNotFound) + }) + t.Run("receipt before confirmation", func(t *testing.T) { + _, err := e.Intent(ctx, "case-1", lease, Effect{ID: "publish", Kind: "pr", Binding: "approved"}) + require.NoError(t, err) + _, err = e.Effect(ctx, "case-1", lease, "publish", EffectInFlight, json.RawMessage(`{}`)) + require.ErrorIs(t, err, ErrIntegrity) + }) +} + +func TestCloneReturnsIntegrityError(t *testing.T) { + if _, err := clone(json.RawMessage("invalid")); !errors.Is(err, ErrIntegrity) { + t.Errorf("clone invalid JSON returned %v, want ErrIntegrity", err) + } + if _, err := clone(rejectCloneDecode{}); !errors.Is(err, ErrIntegrity) { + t.Errorf("clone with decode failure returned %v, want ErrIntegrity", err) + } +} + +type rejectCloneDecode struct{} + +func (*rejectCloneDecode) UnmarshalJSON([]byte) error { + return errors.New("decode rejected") +} diff --git a/internal/journal/requirements_test.go b/internal/journal/requirements_test.go index 97773fbfa7..ccd084f95e 100644 --- a/internal/journal/requirements_test.go +++ b/internal/journal/requirements_test.go @@ -45,47 +45,51 @@ func TestRequiredParentStateFencesChildEffects(t *testing.T) { require.NoError(t, err) _, err = guarded.Intent(ctx, "child", lease, Effect{ID: "first", Kind: "code", Binding: "approved-plan"}) require.NoError(t, err) - // Parent changes after a child read but before its conditional write. - racing, err := New(&hookCAS{Backend: b, hook: func() { - _, updateErr := e.Update(ctx, parent.ID, parentLease, func(r *Record) error { r.Data = json.RawMessage(`{"revoked":true}`); return nil }) - require.NoError(t, updateErr) - }}, e.clock).RequireRecord(req) - require.NoError(t, err) - _, err = racing.Intent(ctx, "child", lease, Effect{ID: "stale", Kind: "publish", Binding: "approved-plan"}) - require.ErrorIs(t, err, ErrConflict) - // Reload cannot silently accept the stale admission either. - _, err = guarded.Intent(ctx, "child", lease, Effect{ID: "stale", Kind: "publish", Binding: "approved-plan"}) - require.ErrorIs(t, err, ErrBinding) - child, err := guarded.Read(ctx, "child") - require.NoError(t, err) - require.NotContains(t, child.Effects, "stale") - require.Contains(t, child.Effects, "first") - fresh, err := e.Read(ctx, parent.ID) - require.NoError(t, err) - req.DataDigest = dataHash(fresh.Data) - guarded, err = e.RequireRecord(req) - require.NoError(t, err) - _, err = guarded.Spend(ctx, "child", lease, "code-attempts", 1) - require.NoError(t, err) - req.Binding = "superseded" - guarded, err = e.RequireRecord(req) - require.NoError(t, err) - _, err = guarded.Spend(ctx, "child", lease, "code-attempts", 2) - require.ErrorIs(t, err, ErrBinding) - req.ID = "missing" - guarded, err = e.RequireRecord(req) - require.NoError(t, err) - _, err = guarded.Spend(ctx, "child", lease, "code-attempts", 2) - require.ErrorIs(t, err, ErrBinding) - for _, invalid := range []Requirement{{}, {ID: "parent", Binding: "binding", DataDigest: "bad"}, {ID: "bad space", Binding: "binding", DataDigest: req.DataDigest}, {ID: "parent", DataDigest: req.DataDigest}} { - _, err = e.RequireRecord(invalid) + t.Run("concurrent parent change fences stale child", func(t *testing.T) { + // Parent changes after a child read but before its conditional write. + racing, err := New(&hookCAS{Backend: b, hook: func() { + _, updateErr := e.Update(ctx, parent.ID, parentLease, func(r *Record) error { r.Data = json.RawMessage(`{"revoked":true}`); return nil }) + require.NoError(t, updateErr) + }}, e.clock).RequireRecord(req) + require.NoError(t, err) + _, err = racing.Intent(ctx, "child", lease, Effect{ID: "stale", Kind: "publish", Binding: "approved-plan"}) + require.ErrorIs(t, err, ErrConflict) + // Reload cannot silently accept the stale admission either. + _, err = guarded.Intent(ctx, "child", lease, Effect{ID: "stale", Kind: "publish", Binding: "approved-plan"}) require.ErrorIs(t, err, ErrBinding) - } - var nilEngine *Engine - _, err = nilEngine.RequireRecord(req) - require.ErrorIs(t, err, ErrBinding) - _, err = New(nil, nil).RequireRecord(req) - require.ErrorIs(t, err, ErrBinding) + child, err := guarded.Read(ctx, "child") + require.NoError(t, err) + require.NotContains(t, child.Effects, "stale") + require.Contains(t, child.Effects, "first") + fresh, err := e.Read(ctx, parent.ID) + require.NoError(t, err) + req.DataDigest = dataHash(fresh.Data) + guarded, err = e.RequireRecord(req) + require.NoError(t, err) + _, err = guarded.Spend(ctx, "child", lease, "code-attempts", 1) + require.NoError(t, err) + req.Binding = "superseded" + guarded, err = e.RequireRecord(req) + require.NoError(t, err) + _, err = guarded.Spend(ctx, "child", lease, "code-attempts", 2) + require.ErrorIs(t, err, ErrBinding) + req.ID = "missing" + guarded, err = e.RequireRecord(req) + require.NoError(t, err) + _, err = guarded.Spend(ctx, "child", lease, "code-attempts", 2) + require.ErrorIs(t, err, ErrBinding) + }) + t.Run("invalid requirements", func(t *testing.T) { + for _, invalid := range []Requirement{{}, {ID: "parent", Binding: "binding", DataDigest: "bad"}, {ID: "bad space", Binding: "binding", DataDigest: req.DataDigest}, {ID: "parent", DataDigest: req.DataDigest}} { + _, err := e.RequireRecord(invalid) + require.ErrorIs(t, err, ErrBinding) + } + var nilEngine *Engine + _, err := nilEngine.RequireRecord(req) + require.ErrorIs(t, err, ErrBinding) + _, err = New(nil, nil).RequireRecord(req) + require.ErrorIs(t, err, ErrBinding) + }) } func TestRequiredParentFencesNoOpMutationsAndNestedRequirements(t *testing.T) { diff --git a/internal/journalhost/profile.go b/internal/journalhost/profile.go index 52ba23ea5e..9832c6b7ac 100644 --- a/internal/journalhost/profile.go +++ b/internal/journalhost/profile.go @@ -4,9 +4,7 @@ package journalhost import ( "context" "crypto/subtle" - "encoding/json" "errors" - "io" "net/url" "os" "path" @@ -17,6 +15,7 @@ import ( gl "github.com/fullsend-ai/fullsend/internal/forge/gitlab" "github.com/fullsend-ai/fullsend/internal/gitlabroles" "github.com/fullsend-ai/fullsend/internal/journal" + "github.com/fullsend-ai/fullsend/internal/strictjson" ) const ProfileEnv = "FULLSEND_JOURNAL_PROFILE" @@ -41,32 +40,7 @@ func Load(getenv func(string) string) (Profile, error) { if len(raw) == 0 || len(raw) > 16384 { return p, errors.New("protected journal profile required") } - // All profile members are scalars. Reject duplicate keys before typed - // decoding, rather than silently accepting the last security scope. - keys := json.NewDecoder(strings.NewReader(raw)) - token, err := keys.Token() - if err != nil || token != json.Delim('{') { - return p, errors.New("invalid protected journal profile") - } - seen := map[string]bool{} - for keys.More() { - key, err := keys.Token() - name, ok := key.(string) - if err != nil || !ok || seen[name] { - return p, errors.New("invalid protected journal profile") - } - seen[name] = true - var value json.RawMessage - if err = keys.Decode(&value); err != nil { - return p, errors.New("invalid protected journal profile") - } - } - dec := json.NewDecoder(strings.NewReader(raw)) - dec.DisallowUnknownFields() - if err := dec.Decode(&p); err != nil { - return Profile{}, errors.New("invalid protected journal profile") - } - if err := dec.Decode(new(any)); !errors.Is(err, io.EOF) { + if err := strictjson.Decode([]byte(raw), &p); err != nil { return Profile{}, errors.New("invalid protected journal profile") } u, err := url.Parse(p.BaseURL) diff --git a/internal/journal/json.go b/internal/strictjson/decode.go similarity index 83% rename from internal/journal/json.go rename to internal/strictjson/decode.go index bbaeedb336..caa27d36f9 100644 --- a/internal/journal/json.go +++ b/internal/strictjson/decode.go @@ -1,4 +1,5 @@ -package journal +// Package strictjson decodes JSON with unambiguous object keys. +package strictjson import ( "bytes" @@ -7,9 +8,8 @@ import ( "io" ) -// Reject duplicate object keys before decoding typed state. Last-wins JSON is -// inappropriate for lease and effect authority. -func strictDecode(data []byte, out any) error { +// Decode rejects duplicate keys, unknown struct fields, and trailing values. +func Decode(data []byte, out any) error { dec := json.NewDecoder(bytes.NewReader(data)) dec.UseNumber() var value func() error diff --git a/internal/strictjson/decode_test.go b/internal/strictjson/decode_test.go new file mode 100644 index 0000000000..8944b6804d --- /dev/null +++ b/internal/strictjson/decode_test.go @@ -0,0 +1,28 @@ +package strictjson + +import "testing" + +func TestDecode(t *testing.T) { + for _, tc := range []struct { + name, input string + valid bool + }{ + {"nested object", `{"items":[{"name":"one"},{"name":"two"}]}`, true}, + {"root duplicate", `{"items":[],"items":[]}`, false}, + {"nested duplicate", `{"items":[{"name":"one","name":"two"}]}`, false}, + {"unknown field", `{"other":[]}`, false}, + {"trailing value", `{"items":[]} {}`, false}, + {"malformed array", `{"items":[,]}`, false}, + {"malformed object", `{"items":}`, false}, + } { + t.Run(tc.name, func(t *testing.T) { + var dst struct { + Items []struct{ Name string } + } + err := Decode([]byte(tc.input), &dst) + if (err == nil) != tc.valid { + t.Fatalf("Decode returned %v, want valid %t", err, tc.valid) + } + }) + } +} From 4657e1a56798c617bdeac30535c2279d8cb51681 Mon Sep 17 00:00:00 2001 From: eshulman2 Date: Tue, 1 Dec 2026 09:44:28 +0200 Subject: [PATCH 4/5] fix(journal): gate experimental GitLab storage Signed-off-by: eshulman2 --- docs/cli/journal.md | 32 ++++++++---- docs/contributing/forge-abstraction.md | 5 +- docs/guides/getting-started/operations.md | 8 +-- internal/forge/fake.go | 3 ++ internal/forge/forge.go | 18 ++++--- internal/forge/gitlab/ci.go | 29 ++++++----- internal/forge/gitlab/methods_test.go | 10 ++-- internal/forge/gitlab/versioned_file.go | 3 +- internal/forge/gitlab/versioned_file_test.go | 5 +- internal/journalhost/profile.go | 29 +++++++---- internal/journalhost/profile_test.go | 53 +++++++++++++++++--- 11 files changed, 139 insertions(+), 56 deletions(-) diff --git a/docs/cli/journal.md b/docs/cli/journal.md index f18e200844..a4bd665ad6 100644 --- a/docs/cli/journal.md +++ b/docs/cli/journal.md @@ -4,7 +4,7 @@ title: fullsend journal # fullsend journal -Read and conditionally update the saga journal in the GitLab control repository. +Experimentally read and conditionally update the saga journal in the GitLab control repository. It provides the storage and host-operation primitives described in [ADR 0165](../ADRs/0165-recover-work-through-repository-owned-operation-journals.md). It performs no inference. The JSON output is durable state only after the remote @@ -15,17 +15,27 @@ an external action. Set `FULLSEND_JOURNAL_PROFILE` in trusted host installation state. Its strict JSON fields are `forge` (`gitlab`), `base_url` (HTTPS site origin), `owner` (namespace), -`repo`, `branch`, `path` (relative JSON file), and `role`. Source checkouts, tracker +`repo`, `branch`, `path` (relative JSON file), `role`, and +`experimental_gitlab` (boolean, defaults to false). Source checkouts, tracker properties and model output cannot supply this profile. The journal branch must already exist and be protected. Every exact or wildcard rule matching the branch must allow push and merge only to the journal writer's numeric user ID (or nobody), with at least one push grant for the writer. Role-level, group and deploy-key grants are refused, including -Maintainer grants; an overlapping permissive rule also blocks access. The +Maintainer grants. Every matching rule must explicitly grant unprotect access +only to that writer. GitLab treats an empty unprotect list as its default +policy, so the journal refuses missing or empty lists. It also refuses custom +member-role grants. An overlapping permissive rule blocks access. The credential must be able to list protection rules and identify its user. Named-user protection grants require [GitLab Premium or Ultimate](https://docs.gitlab.com/user/project/repository/branches/protected/#in-a-project). Instances without these grants cannot host this journal backend. +Set `experimental_gitlab` to `true` only for a controlled trial. Serialize all +journal mutations externally under one shared lock per journal, for example a +single GitLab CI resource group when all writers run in the same project. The +Files API checks `last_commit_id` separately from the branch update, so +concurrent writers can lose updates. Hosted conformance remains pending. + The profile selects its exact scope; there are no command flags to redirect writes elsewhere. @@ -76,19 +86,21 @@ replayed. Exhausted conflicts still require caller recovery; do not force-push o merge competing JSON claims. These retries do not invoke an agent or repeat an external action. -GitLab can report a branch-reference race as HTTP 400 with the exact message -`9:reference update: reference does not point to expected object.` The versioned -file adapter classifies this rejected reference update as a revision conflict, -so the same bounded fresh-transaction retry applies. Recognition of this -additional response is exact; similar messages or other HTTP statuses do not -gain retry authority from this rule. +The GitLab Files API adapter recognizes HTTP 409 and exact HTTP 400 rejection +messages. The recognized reference-update messages are +`9:reference update: reference does not point to expected object.` and +`Could not update refs/heads/. Please refresh and try again.` for the +requested branch. File-revision and file-exists recognition also depends on +exact English text. Localized or unrecognized HTTP 400 responses are treated +as uncertain. Use an English response locale for trials that require these +automatic retries. Hosted verification across GitLab versions is pending. A lost acknowledgement or failed checkpoint verification returns `journal checkpoint outcome uncertain` and is never automatically retried. Mixed conflict/unknown errors, invalid readback, and changes to the target record stay uncertain. Ownership, binding, integrity and budget failures do not retry either. The backend keeps all authority in one bounded document, using GitLab's file -revision precondition for the complete transition. After an acknowledged Engine +revision guard in deployments that serialize writers. After an acknowledged Engine write, it validates the readback document and its exact intended record; unrelated records may advance. Direct backend callers retain whole-document verification. diff --git a/docs/contributing/forge-abstraction.md b/docs/contributing/forge-abstraction.md index 56adbf86e6..890ad2cddc 100644 --- a/docs/contributing/forge-abstraction.md +++ b/docs/contributing/forge-abstraction.md @@ -59,8 +59,9 @@ When the resource can be reached from more than one repo (for example fork-based `forge.Client.ReadVersionedFile` reads the complete file and its last-modifying revision. `WriteFileIfRevision` replaces that file once only if the supplied revision still matches. An empty revision permits creation only when the file -is absent. GitLab implements the pair using its file `last_commit_id` guard; -GitHub control-journal storage returns `ErrNotSupported` until conformance is +is absent. The experimental GitLab adapter sends the file `last_commit_id` guard, +which alone does not establish atomic replacement under concurrency. Trials +require explicit opt-in and external single-writer serialization. GitHub control-journal storage returns `ErrNotSupported` until conformance is implemented. This does not restrict source repositories to GitLab. The journal keeps all ownership, budgets and effect receipts in one JSON file, diff --git a/docs/guides/getting-started/operations.md b/docs/guides/getting-started/operations.md index d2a8897be0..f7445b3079 100644 --- a/docs/guides/getting-started/operations.md +++ b/docs/guides/getting-started/operations.md @@ -240,11 +240,13 @@ that lets a workflow resume after interruption. ### Prerequisites -Provision a protected journal branch, a trusted `FULLSEND_JOURNAL_PROFILE`, +Provision a protected journal branch, a trusted `FULLSEND_JOURNAL_PROFILE` with +`experimental_gitlab` set to `true`, and a separately registered GitLab role with its own `write_repository` credential. Restrict every matching branch rule's push and merge grants to the -journal writer's user ID (or no access). Role-level, group and deploy-key grants -are refused. Follow the +journal writer's user ID (or no access), and grant unprotect permission only +to that user. Role-level, group and deploy-key grants are refused. Limit use to +a controlled trial and serialize all mutations with a shared lock per journal. Follow the [journal command reference](../../cli/journal.md#protected-host-profile) to configure these prerequisites. diff --git a/internal/forge/fake.go b/internal/forge/fake.go index 9f267b766c..8f174acd83 100644 --- a/internal/forge/fake.go +++ b/internal/forge/fake.go @@ -2694,6 +2694,9 @@ func cloneProtectedBranchRule(rule *ProtectedBranchRule) *ProtectedBranchRule { if rule.MergeAccessLevels != nil { out.MergeAccessLevels = append([]ProtectedBranchAccess(nil), rule.MergeAccessLevels...) } + if rule.UnprotectAccessLevels != nil { + out.UnprotectAccessLevels = append([]ProtectedBranchAccess(nil), rule.UnprotectAccessLevels...) + } return &out } diff --git a/internal/forge/forge.go b/internal/forge/forge.go index ccea673d34..c8c0690ea0 100644 --- a/internal/forge/forge.go +++ b/internal/forge/forge.go @@ -1800,19 +1800,21 @@ func (v PipelineInputValue) MarshalJSON() ([]byte, error) { // GitLab access levels: 0 (No one), 30 (Developer), 40 (Maintainer), // 60 (Admin). A role-based grant of N allows identities at N or above. type ProtectedBranchAccess struct { - ID int - AccessLevel int - UserID int - GroupID int - DeployKeyID int + ID int + AccessLevel int + UserID int + GroupID int + DeployKeyID int + MemberRoleID int } // ProtectedBranchRule is the protection configuration for a branch. // A nil value from GetProtectedBranch means the branch is not protected. type ProtectedBranchRule struct { - Name string - PushAccessLevels []ProtectedBranchAccess - MergeAccessLevels []ProtectedBranchAccess + Name string + PushAccessLevels []ProtectedBranchAccess + MergeAccessLevels []ProtectedBranchAccess + UnprotectAccessLevels []ProtectedBranchAccess } // PipelineSchedule represents a scheduled pipeline trigger. diff --git a/internal/forge/gitlab/ci.go b/internal/forge/gitlab/ci.go index fa0a608bb8..8bc52f527a 100644 --- a/internal/forge/gitlab/ci.go +++ b/internal/forge/gitlab/ci.go @@ -1566,17 +1566,18 @@ func (c *LiveClient) IsProtectedBranch(ctx context.Context, owner, repo, branch } type gitlabProtectedAccess struct { - ID int `json:"id"` - AccessLevel int `json:"access_level"` - UserID *int `json:"user_id"` - GroupID *int `json:"group_id"` - DeployKeyID *int `json:"deploy_key_id"` + ID int `json:"id"` + AccessLevel int `json:"access_level"` + UserID *int `json:"user_id"` + GroupID *int `json:"group_id"` + DeployKeyID *int `json:"deploy_key_id"` + MemberRoleID int `json:"member_role_id"` } func convertProtectedAccess(levels []gitlabProtectedAccess) []forge.ProtectedBranchAccess { out := make([]forge.ProtectedBranchAccess, 0, len(levels)) for _, l := range levels { - a := forge.ProtectedBranchAccess{ID: l.ID, AccessLevel: l.AccessLevel} + a := forge.ProtectedBranchAccess{ID: l.ID, AccessLevel: l.AccessLevel, MemberRoleID: l.MemberRoleID} if l.UserID != nil { a.UserID = *l.UserID } @@ -1606,16 +1607,18 @@ func userHasProtectedBranchAccess(rule *forge.ProtectedBranchRule, userID int) b } type gitlabProtectedBranchRaw struct { - Name string `json:"name"` - PushAccessLevels []gitlabProtectedAccess `json:"push_access_levels"` - MergeAccessLevels []gitlabProtectedAccess `json:"merge_access_levels"` + Name string `json:"name"` + PushAccessLevels []gitlabProtectedAccess `json:"push_access_levels"` + MergeAccessLevels []gitlabProtectedAccess `json:"merge_access_levels"` + UnprotectAccessLevels []gitlabProtectedAccess `json:"unprotect_access_levels"` } func (raw gitlabProtectedBranchRaw) toRule() *forge.ProtectedBranchRule { return &forge.ProtectedBranchRule{ - Name: raw.Name, - PushAccessLevels: convertProtectedAccess(raw.PushAccessLevels), - MergeAccessLevels: convertProtectedAccess(raw.MergeAccessLevels), + Name: raw.Name, + PushAccessLevels: convertProtectedAccess(raw.PushAccessLevels), + MergeAccessLevels: convertProtectedAccess(raw.MergeAccessLevels), + UnprotectAccessLevels: convertProtectedAccess(raw.UnprotectAccessLevels), } } @@ -1664,10 +1667,12 @@ func mergeProtectedBranchRules(branch string, exact *forge.ProtectedBranchRule, if exact != nil { merged.PushAccessLevels = append(merged.PushAccessLevels, exact.PushAccessLevels...) merged.MergeAccessLevels = append(merged.MergeAccessLevels, exact.MergeAccessLevels...) + merged.UnprotectAccessLevels = append(merged.UnprotectAccessLevels, exact.UnprotectAccessLevels...) } for _, w := range wildcards { merged.PushAccessLevels = append(merged.PushAccessLevels, w.PushAccessLevels...) merged.MergeAccessLevels = append(merged.MergeAccessLevels, w.MergeAccessLevels...) + merged.UnprotectAccessLevels = append(merged.UnprotectAccessLevels, w.UnprotectAccessLevels...) } return merged } diff --git a/internal/forge/gitlab/methods_test.go b/internal/forge/gitlab/methods_test.go index 1141c95732..0d35063b3f 100644 --- a/internal/forge/gitlab/methods_test.go +++ b/internal/forge/gitlab/methods_test.go @@ -3008,7 +3008,8 @@ func TestGetProtectedBranch_UnionAcrossExactAndWildcard(t *testing.T) { mux.HandleFunc("/api/v4/projects/myorg%2Fmyrepo/protected_branches/main", func(w http.ResponseWriter, r *http.Request) { writeJSON(t, w, http.StatusOK, map[string]any{ - "name": "main", + "name": "main", + "unprotect_access_levels": []map[string]any{{"user_id": 42}}, "merge_access_levels": []map[string]any{ {"access_level": 40}, }, @@ -3020,7 +3021,8 @@ func TestGetProtectedBranch_UnionAcrossExactAndWildcard(t *testing.T) { mux.HandleFunc("/api/v4/projects/myorg%2Fmyrepo/protected_branches", func(w http.ResponseWriter, r *http.Request) { writeJSON(t, w, http.StatusOK, []map[string]any{ { - "name": "*", + "name": "*", + "unprotect_access_levels": []map[string]any{{"member_role_id": 17}}, "merge_access_levels": []map[string]any{ {"access_level": 30}, }, @@ -3037,6 +3039,7 @@ func TestGetProtectedBranch_UnionAcrossExactAndWildcard(t *testing.T) { assert.Equal(t, "main", rule.Name, "the exact-name rule is present, so the PATCH target must remain the branch itself") require.Len(t, rule.MergeAccessLevels, 2, "must include both the exact rule's and the wildcard rule's access levels") require.Len(t, rule.PushAccessLevels, 2, "must include both the exact rule's and the wildcard rule's access levels") + require.Equal(t, []forge.ProtectedBranchAccess{{UserID: 42}, {MemberRoleID: 17}}, rule.UnprotectAccessLevels) hasDeveloperMerge := false for _, l := range rule.MergeAccessLevels { if l.AccessLevel == 30 { @@ -5881,7 +5884,7 @@ func TestListProtectedBranches_IncludesWildcardRules(t *testing.T) { assert.Equal(t, http.MethodGet, r.Method) writeJSON(t, w, http.StatusOK, []map[string]any{ {"name": "main", "push_access_levels": []map[string]int{{"access_level": 40}}, "merge_access_levels": []map[string]int{{"access_level": 30}}}, - {"name": "release/*", "push_access_levels": []map[string]int{{"access_level": 0}}, "merge_access_levels": []map[string]int{{"access_level": 40}}}, + {"name": "release/*", "unprotect_access_levels": []map[string]int{{"access_level": 40}}, "push_access_levels": []map[string]int{{"access_level": 0}}, "merge_access_levels": []map[string]int{{"access_level": 40}}}, }) }) @@ -5892,6 +5895,7 @@ func TestListProtectedBranches_IncludesWildcardRules(t *testing.T) { assert.Equal(t, "main", rules[0].Name) assert.Equal(t, "release/*", rules[1].Name) assert.Equal(t, 40, rules[1].MergeAccessLevels[0].AccessLevel) + assert.Equal(t, []forge.ProtectedBranchAccess{{AccessLevel: 40}}, rules[1].UnprotectAccessLevels) } func TestListProtectedBranches_ErrorStatus(t *testing.T) { diff --git a/internal/forge/gitlab/versioned_file.go b/internal/forge/gitlab/versioned_file.go index 447d019896..032c9de6b5 100644 --- a/internal/forge/gitlab/versioned_file.go +++ b/internal/forge/gitlab/versioned_file.go @@ -60,7 +60,8 @@ func (c *LiveClient) WriteFileIfRevision(ctx context.Context, owner, repo, branc // check passed. This exact failed-precondition response proves that // the reference update was rejected, rather than its ACK being lost. referenceCASRejected := apiErr.StatusCode == http.StatusBadRequest && - apiErr.Message == "9:reference update: reference does not point to expected object." + (apiErr.Message == "9:reference update: reference does not point to expected object." || + apiErr.Message == fmt.Sprintf("Could not update refs/heads/%s. Please refresh and try again.", branch)) fileRejected := apiErr.StatusCode == http.StatusBadRequest && ((method == http.MethodPost && apiErr.Message == "A file with this name already exists") || (method == http.MethodPut && apiErr.Message == "You are attempting to update a file that has changed since you started editing it.")) if referenceCASRejected || fileRejected || apiErr.StatusCode == http.StatusConflict { diff --git a/internal/forge/gitlab/versioned_file_test.go b/internal/forge/gitlab/versioned_file_test.go index 772136a1d1..c43f013ad0 100644 --- a/internal/forge/gitlab/versioned_file_test.go +++ b/internal/forge/gitlab/versioned_file_test.go @@ -34,7 +34,7 @@ func TestReadVersionedFileRequiresLastCommit(t *testing.T) { }) } } -func TestWriteVersionedFileUsesAtomicLastCommitGuard(t *testing.T) { +func TestWriteVersionedFileSendsLastCommitGuard(t *testing.T) { c, mux := setupTest(t) var put atomic.Int32 mux.HandleFunc("PUT /api/v4/projects/o%2Fr/repository/files/journal.json", func(w http.ResponseWriter, r *http.Request) { @@ -98,6 +98,9 @@ func TestVersionedWriteRecognizesOnlyExactReferenceRaceRejection(t *testing.T) { {"unrelated existing branch", http.StatusBadRequest, "Branch already exists", false}, {"file revision mismatch", http.StatusBadRequest, "You are attempting to update a file that has changed since you started editing it.", true}, {"reference CAS rejected", http.StatusBadRequest, rejection, true}, + {"named reference rejected", http.StatusBadRequest, "Could not update refs/heads/state. Please refresh and try again.", true}, + {"different reference", http.StatusBadRequest, "Could not update refs/heads/other. Please refresh and try again.", false}, + {"localized rejection", http.StatusBadRequest, "Der Branch konnte nicht aktualisiert werden.", false}, {"unknown bad request", http.StatusBadRequest, "reference update failed", false}, {"same text in server failure", http.StatusInternalServerError, rejection, false}, {"same text in permission failure", http.StatusForbidden, rejection, false}, diff --git a/internal/journalhost/profile.go b/internal/journalhost/profile.go index 9832c6b7ac..882a880e62 100644 --- a/internal/journalhost/profile.go +++ b/internal/journalhost/profile.go @@ -22,13 +22,14 @@ const ProfileEnv = "FULLSEND_JOURNAL_PROFILE" // Profile is protected host installation state, never source or tracker content. type Profile struct { - Forge string `json:"forge"` - BaseURL string `json:"base_url"` - Owner string `json:"owner"` - Repo string `json:"repo"` - Branch string `json:"branch"` - Path string `json:"path"` - Role string `json:"role"` + Forge string `json:"forge"` + BaseURL string `json:"base_url"` + Owner string `json:"owner"` + Repo string `json:"repo"` + Branch string `json:"branch"` + Path string `json:"path"` + Role string `json:"role"` + ExperimentalGitLab bool `json:"experimental_gitlab"` } func Load(getenv func(string) string) (Profile, error) { @@ -105,6 +106,9 @@ func Open(getenv func(string) string) (*journal.Engine, *journal.ForgeBackend, e if err != nil { return nil, nil, err } + if !p.ExperimentalGitLab { + return nil, nil, errors.New("journal requires experimental_gitlab opt-in") + } token, err := p.Credential(getenv) if err != nil { return nil, nil, err @@ -123,7 +127,7 @@ func Open(getenv func(string) string) (*journal.Engine, *journal.ForgeBackend, e // verifyWriterIsolation checks every matching rule: GitLab combines overlapping // protections permissively, so an exact rule cannot neutralize a broad wildcard. func (p Profile) verifyWriterIsolation(ctx context.Context, client forge.Client) error { - denied := errors.New("journal requires writer-only branch push and merge grants") + denied := errors.New("journal requires writer-only branch push, merge and unprotect grants") identity, ok := client.(interface { GetAuthenticatedUserID(context.Context) (int, error) }) @@ -150,12 +154,12 @@ func (p Profile) verifyWriterIsolation(ctx context.Context, client forge.Client) } matched = true // Missing grant metadata cannot establish isolation. - if len(rule.PushAccessLevels) == 0 || len(rule.MergeAccessLevels) == 0 { + if len(rule.PushAccessLevels) == 0 || len(rule.MergeAccessLevels) == 0 || len(rule.UnprotectAccessLevels) == 0 { return denied } for _, grants := range [][]forge.ProtectedBranchAccess{rule.PushAccessLevels, rule.MergeAccessLevels} { for _, grant := range grants { - if grant.GroupID != 0 || grant.DeployKeyID != 0 || grant.UserID < 0 || grant.AccessLevel < 0 { + if grant.GroupID != 0 || grant.DeployKeyID != 0 || grant.MemberRoleID != 0 || grant.UserID < 0 || grant.AccessLevel < 0 { return denied } if grant.UserID == writer { @@ -166,6 +170,11 @@ func (p Profile) verifyWriterIsolation(ctx context.Context, client forge.Client) } } } + for _, grant := range rule.UnprotectAccessLevels { + if grant.UserID != writer || grant.GroupID != 0 || grant.DeployKeyID != 0 || grant.MemberRoleID != 0 || grant.AccessLevel < 0 { + return denied + } + } for _, grant := range rule.PushAccessLevels { if grant.UserID == writer { canPush = true diff --git a/internal/journalhost/profile_test.go b/internal/journalhost/profile_test.go index a421d9f658..08de286623 100644 --- a/internal/journalhost/profile_test.go +++ b/internal/journalhost/profile_test.go @@ -15,7 +15,7 @@ import ( func trustedEnv(t *testing.T) map[string]string { t.Helper() - p := Profile{Forge: "gitlab", BaseURL: "https://gitlab.example.com", Owner: "group/control", Repo: "fullsend", Branch: "fullsend-journal", Path: "state/journal.json", Role: "journal"} + p := Profile{Forge: "gitlab", BaseURL: "https://gitlab.example.com", Owner: "group/control", Repo: "fullsend", Branch: "fullsend-journal", Path: "state/journal.json", Role: "journal", ExperimentalGitLab: true} raw, err := json.Marshal(p) require.NoError(t, err) return map[string]string{ProfileEnv: string(raw), forge.VarGitLabRoleRegistry: `{"roles":[{"name":"journal","credential":"own","capabilities":["write_repository"],"agents":["journal"]}]}`, gitlabroles.CustomSecretName("journal"): "journal-private-token"} @@ -93,7 +93,7 @@ func TestAuthorizerBindsCredentialScopeAndProtectedBranch(t *testing.T) { require.NoError(t, err) fc := forge.NewFakeClient() fc.ProtectedBranches[p.Owner+"/"+p.Repo+"/"+p.Branch] = true - fc.ProtectedBranchRules[p.Owner+"/"+p.Repo+"/"+p.Branch] = &forge.ProtectedBranchRule{Name: p.Branch, PushAccessLevels: []forge.ProtectedBranchAccess{{UserID: 42}}, MergeAccessLevels: []forge.ProtectedBranchAccess{{AccessLevel: 0}}} + fc.ProtectedBranchRules[p.Owner+"/"+p.Repo+"/"+p.Branch] = &forge.ProtectedBranchRule{Name: p.Branch, PushAccessLevels: []forge.ProtectedBranchAccess{{UserID: 42}}, UnprotectAccessLevels: []forge.ProtectedBranchAccess{{UserID: 42}}, MergeAccessLevels: []forge.ProtectedBranchAccess{{AccessLevel: 0}}} authorize := p.Authorizer(writerClient{FakeClient: fc, id: 42}, getenv(env), "journal-private-token") for _, action := range []string{"initialize", "read", "write"} { require.NoError(t, authorize(ctx, p.Location(), action)) @@ -137,7 +137,7 @@ func TestAuthorizerStopsWhenProtectedProfileChanges(t *testing.T) { require.NoError(t, err) fc := forge.NewFakeClient() fc.ProtectedBranches[p.Owner+"/"+p.Repo+"/"+p.Branch] = true - fc.ProtectedBranchRules[p.Owner+"/"+p.Repo+"/"+p.Branch] = &forge.ProtectedBranchRule{Name: p.Branch, PushAccessLevels: []forge.ProtectedBranchAccess{{UserID: 42}}, MergeAccessLevels: []forge.ProtectedBranchAccess{{AccessLevel: 0}}} + fc.ProtectedBranchRules[p.Owner+"/"+p.Repo+"/"+p.Branch] = &forge.ProtectedBranchRule{Name: p.Branch, PushAccessLevels: []forge.ProtectedBranchAccess{{UserID: 42}}, UnprotectAccessLevels: []forge.ProtectedBranchAccess{{UserID: 42}}, MergeAccessLevels: []forge.ProtectedBranchAccess{{AccessLevel: 0}}} authorize := p.Authorizer(writerClient{FakeClient: fc, id: 42}, getenv(env), "journal-private-token") require.NoError(t, authorize(context.Background(), p.Location(), "write")) delete(env, ProfileEnv) @@ -192,8 +192,8 @@ func TestAuthorizerRequiresWriterOnlyEffectiveGrants(t *testing.T) { fc := forge.NewFakeClient() key := p.Owner + "/" + p.Repo + "/" fc.ProtectedBranches[key+p.Branch] = true - fc.ProtectedBranchRules[key+p.Branch] = &forge.ProtectedBranchRule{Name: p.Branch, PushAccessLevels: []forge.ProtectedBranchAccess{{UserID: 42}}, MergeAccessLevels: []forge.ProtectedBranchAccess{{}}} - fc.ProtectedBranchRules[key+tc.pattern] = &forge.ProtectedBranchRule{Name: tc.pattern, PushAccessLevels: tc.push, MergeAccessLevels: tc.merge} + fc.ProtectedBranchRules[key+p.Branch] = &forge.ProtectedBranchRule{Name: p.Branch, PushAccessLevels: []forge.ProtectedBranchAccess{{UserID: 42}}, UnprotectAccessLevels: []forge.ProtectedBranchAccess{{UserID: 42}}, MergeAccessLevels: []forge.ProtectedBranchAccess{{}}} + fc.ProtectedBranchRules[key+tc.pattern] = &forge.ProtectedBranchRule{Name: tc.pattern, PushAccessLevels: tc.push, UnprotectAccessLevels: []forge.ProtectedBranchAccess{{UserID: 42}}, MergeAccessLevels: tc.merge} err = p.Authorizer(writerClient{FakeClient: fc, id: 42}, getenv(env), "journal-private-token")(context.Background(), p.Location(), "write") if tc.denied { require.Error(t, err) @@ -219,9 +219,50 @@ func TestWriterIsolationFailsClosed(t *testing.T) { delete(fc.Errors, "ListProtectedBranches") key := p.Owner + "/" + p.Repo + "/" for _, grants := range [][]forge.ProtectedBranchAccess{{{}}, {{UserID: -1}}, {{AccessLevel: -1}}} { - fc.ProtectedBranchRules[key+p.Branch] = &forge.ProtectedBranchRule{Name: p.Branch, PushAccessLevels: grants, MergeAccessLevels: []forge.ProtectedBranchAccess{{}}} + fc.ProtectedBranchRules[key+p.Branch] = &forge.ProtectedBranchRule{Name: p.Branch, PushAccessLevels: grants, UnprotectAccessLevels: []forge.ProtectedBranchAccess{{UserID: 42}}, MergeAccessLevels: []forge.ProtectedBranchAccess{{}}} require.Error(t, p.verifyWriterIsolation(context.Background(), client)) } fc.ProtectedBranchRules[key+p.Branch] = &forge.ProtectedBranchRule{Name: "", PushAccessLevels: []forge.ProtectedBranchAccess{{UserID: 42}}} require.Error(t, p.verifyWriterIsolation(context.Background(), client)) } + +func TestOpenRequiresExperimentalOptIn(t *testing.T) { + for _, suffix := range []string{"", `,"experimental_gitlab":false`} { + env := trustedEnv(t) + raw := strings.Replace(env[ProfileEnv], `,"experimental_gitlab":true`, "", 1) + env[ProfileEnv] = strings.TrimSuffix(raw, "}") + suffix + "}" + engine, backend, err := Open(getenv(env)) + require.ErrorContains(t, err, "experimental_gitlab") + require.Nil(t, engine) + require.Nil(t, backend) + } +} + +func TestWriterIsolationRequiresExplicitUnprotectGrants(t *testing.T) { + for _, tc := range []struct { + name string + grants []forge.ProtectedBranchAccess + }{ + {"missing", nil}, + {"empty", []forge.ProtectedBranchAccess{}}, + {"maintainer", []forge.ProtectedBranchAccess{{AccessLevel: 40}}}, + {"other user", []forge.ProtectedBranchAccess{{UserID: 43}}}, + {"group", []forge.ProtectedBranchAccess{{GroupID: 3}}}, + {"custom role", []forge.ProtectedBranchAccess{{MemberRoleID: 3}}}, + } { + t.Run(tc.name, func(t *testing.T) { + p, err := Load(getenv(trustedEnv(t))) + require.NoError(t, err) + fc := forge.NewFakeClient() + key := p.Owner + "/" + p.Repo + "/" + writer := []forge.ProtectedBranchAccess{{UserID: 42}} + fc.ProtectedBranchRules[key+p.Branch] = &forge.ProtectedBranchRule{ + PushAccessLevels: writer, MergeAccessLevels: writer, UnprotectAccessLevels: writer, + } + fc.ProtectedBranchRules[key+"fullsend-*"] = &forge.ProtectedBranchRule{ + PushAccessLevels: writer, MergeAccessLevels: writer, UnprotectAccessLevels: tc.grants, + } + require.Error(t, p.verifyWriterIsolation(context.Background(), writerClient{FakeClient: fc, id: 42})) + }) + } +} From e9863133c15e3bf9426afd1a22ff2cdf989dca85 Mon Sep 17 00:00:00 2001 From: eshulman2 Date: Tue, 1 Dec 2026 15:30:52 +0200 Subject: [PATCH 5/5] fix(journal): pin branch reads and preserve safe guidance Signed-off-by: eshulman2 --- docs/cli/journal.md | 10 +++-- internal/cli/journal.go | 10 ++++- internal/cli/journal_test.go | 18 ++++++++ internal/forge/gitlab/versioned_file.go | 16 +++++-- internal/forge/gitlab/versioned_file_test.go | 37 ++++++++++----- internal/journal/forge.go | 7 ++- internal/journal/forge_checkpoint_test.go | 12 +++++ internal/journalhost/errors.go | 30 +++++++++++++ internal/journalhost/errors_test.go | 24 ++++++++++ internal/journalhost/profile.go | 47 +++++++++++--------- 10 files changed, 168 insertions(+), 43 deletions(-) create mode 100644 internal/journalhost/errors.go create mode 100644 internal/journalhost/errors_test.go diff --git a/docs/cli/journal.md b/docs/cli/journal.md index a4bd665ad6..7e985eb804 100644 --- a/docs/cli/journal.md +++ b/docs/cli/journal.md @@ -86,19 +86,23 @@ replayed. Exhausted conflicts still require caller recovery; do not force-push o merge competing JSON claims. These retries do not invoke an agent or repeat an external action. -The GitLab Files API adapter recognizes HTTP 409 and exact HTTP 400 rejection +The GitLab Files API adapter recognizes exact HTTP 400 rejection messages. The recognized reference-update messages are `9:reference update: reference does not point to expected object.` and `Could not update refs/heads/. Please refresh and try again.` for the requested branch. File-revision and file-exists recognition also depends on -exact English text. Localized or unrecognized HTTP 400 responses are treated -as uncertain. Use an English response locale for trials that require these +exact English text. Generic HTTP 409, localized HTTP 400, and other unrecognized rejection +responses are treated as uncertain. Use an English response locale for trials that require these automatic retries. Hosted verification across GitLab versions is pending. A lost acknowledgement or failed checkpoint verification returns `journal checkpoint outcome uncertain` and is never automatically retried. Mixed conflict/unknown errors, invalid readback, and changes to the target record stay uncertain. Ownership, binding, integrity and budget failures do not retry either. +Reads and write verification resolve the configured branch through GitLab’s +branch API and read the file at the reported commit. This avoids ambiguity +when a tag has the same name. + The backend keeps all authority in one bounded document, using GitLab's file revision guard in deployments that serialize writers. After an acknowledged Engine write, it validates the readback document and its exact intended record; unrelated diff --git a/internal/cli/journal.go b/internal/cli/journal.go index c713a8dda5..8173248565 100644 --- a/internal/cli/journal.go +++ b/internal/cli/journal.go @@ -115,15 +115,18 @@ func newJournalCmdWithHost(openHost journalHostOpener) *cobra.Command { } return cmd } + +var errJournalJSONInput = errors.New("bounded JSON input required") + func readJournalJSON(r io.Reader) (json.RawMessage, error) { data, err := io.ReadAll(io.LimitReader(r, journal.MaxDocumentBytes+1)) if err != nil || len(data) > journal.MaxDocumentBytes || !json.Valid(data) { - return nil, errors.New("bounded JSON input required") + return nil, errJournalJSONInput } return json.RawMessage(data), nil } func sanitizeJournalError(err error) error { - for _, known := range []error{journal.ErrUncertain, journal.ErrIntegrity, journal.ErrOwnership, journal.ErrBinding, journal.ErrNotFound, journal.ErrTransition, journal.ErrBudget, context.Canceled, context.DeadlineExceeded} { + for _, known := range []error{journal.ErrUncertain, journal.ErrIntegrity, journal.ErrOwnership, journal.ErrBinding, journal.ErrNotFound, journal.ErrTransition, journal.ErrBudget, errJournalJSONInput, context.Canceled, context.DeadlineExceeded} { if errors.Is(err, known) { return known } @@ -131,6 +134,9 @@ func sanitizeJournalError(err error) error { if journal.IsDefiniteConflict(err) { return journal.ErrConflict } + if guidance := journalhost.OperatorError(err); guidance != nil { + return guidance + } return errors.New("journal operation failed; inspect control repository and connection permissions") } diff --git a/internal/cli/journal_test.go b/internal/cli/journal_test.go index 7c53e64df4..e1b240b650 100644 --- a/internal/cli/journal_test.go +++ b/internal/cli/journal_test.go @@ -15,6 +15,7 @@ import ( "github.com/fullsend-ai/fullsend/internal/forge" "github.com/fullsend-ai/fullsend/internal/journal" + "github.com/fullsend-ai/fullsend/internal/journalhost" "github.com/stretchr/testify/require" ) @@ -98,6 +99,8 @@ func TestJournalCLIRejectsMalformedAndUnownedOperations(t *testing.T) { require.NoError(t, err) _, err = runJournal(t, opener, "", "spend", "--id", "case", "--owner", "wrong", "--generation", "1", "--counter", "attempts", "--limit", "1") require.ErrorIs(t, err, journal.ErrOwnership) + _, err = runJournal(t, opener, "{", "admit", "--id", "case", "--binding", "sha") + require.EqualError(t, err, "bounded JSON input required") opener = func(func(string) string) (*journal.Engine, *journal.ForgeBackend, error) { return nil, nil, errors.New("transport leaked token-secret") } @@ -159,3 +162,18 @@ func TestJournalCLIParentPredicatesRejectStaleEffect(t *testing.T) { require.ErrorIs(t, err, journal.ErrBinding) } } + +func TestJournalCLISafeOperatorGuidance(t *testing.T) { + opener := func(func(string) string) (*journal.Engine, *journal.ForgeBackend, error) { + _, err := journalhost.Load(func(string) string { return "" }) + return nil, nil, fmt.Errorf("sensitive context: %w", err) + } + _, err := runJournal(t, opener, "", "initialize") + require.EqualError(t, err, "protected journal profile required") + + opener = func(func(string) string) (*journal.Engine, *journal.ForgeBackend, error) { + return nil, nil, errors.New("protected journal profile required: sensitive context") + } + _, err = runJournal(t, opener, "", "initialize") + require.EqualError(t, err, "journal operation failed; inspect control repository and connection permissions") +} diff --git a/internal/forge/gitlab/versioned_file.go b/internal/forge/gitlab/versioned_file.go index 032c9de6b5..bb019370c6 100644 --- a/internal/forge/gitlab/versioned_file.go +++ b/internal/forge/gitlab/versioned_file.go @@ -14,7 +14,16 @@ import ( // ReadVersionedFile returns GitLab's last_commit_id, which is the precondition // its file update API actually enforces. A branch tip is not equivalent. func (c *LiveClient) ReadVersionedFile(ctx context.Context, owner, repo, branch, path string) ([]byte, string, error) { - apiPath := fmt.Sprintf("/projects/%s/repository/files/%s?ref=%s", projectPath(owner, repo), url.PathEscape(path), url.QueryEscape(branch)) + // Resolve the branch through the branch endpoint, then read its immutable + // commit. The Files API also accepts tag names for ref. + tip, err := c.GetBranchRef(ctx, owner, repo, branch) + if err != nil { + return nil, "", err + } + if tip == "" { + return nil, "", fmt.Errorf("versioned file branch tip unavailable") + } + apiPath := fmt.Sprintf("/projects/%s/repository/files/%s?ref=%s", projectPath(owner, repo), url.PathEscape(path), url.QueryEscape(tip)) resp, err := c.get(ctx, apiPath) if err != nil { return nil, "", err @@ -23,11 +32,12 @@ func (c *LiveClient) ReadVersionedFile(ctx context.Context, owner, repo, branch, Content string `json:"content"` Encoding string `json:"encoding"` Revision string `json:"last_commit_id"` + CommitID string `json:"commit_id"` } if err = decodeJSON(resp, &f); err != nil { return nil, "", err } - if f.Revision == "" || f.Encoding != "base64" { + if f.CommitID != tip || f.Revision == "" || f.Encoding != "base64" { return nil, "", fmt.Errorf("versioned file metadata unavailable") } data, err := base64.StdEncoding.DecodeString(f.Content) @@ -64,7 +74,7 @@ func (c *LiveClient) WriteFileIfRevision(ctx context.Context, owner, repo, branc apiErr.Message == fmt.Sprintf("Could not update refs/heads/%s. Please refresh and try again.", branch)) fileRejected := apiErr.StatusCode == http.StatusBadRequest && ((method == http.MethodPost && apiErr.Message == "A file with this name already exists") || (method == http.MethodPut && apiErr.Message == "You are attempting to update a file that has changed since you started editing it.")) - if referenceCASRejected || fileRejected || apiErr.StatusCode == http.StatusConflict { + if referenceCASRejected || fileRejected { return fmt.Errorf("%w: conditional file write rejected", forge.ErrConflict) } } diff --git a/internal/forge/gitlab/versioned_file_test.go b/internal/forge/gitlab/versioned_file_test.go index c43f013ad0..8fcffb04c8 100644 --- a/internal/forge/gitlab/versioned_file_test.go +++ b/internal/forge/gitlab/versioned_file_test.go @@ -15,16 +15,35 @@ import ( "github.com/fullsend-ai/fullsend/internal/forge" ) -func TestReadVersionedFileRequiresLastCommit(t *testing.T) { - for _, body := range []string{`{"encoding":"base64","content":"eA==","last_commit_id":"file-revision"}`, `{"encoding":"base64","content":"eA=="}`, `{"encoding":"text","content":"x","last_commit_id":"r"}`, `{"encoding":"base64","content":"!","last_commit_id":"r"}`, `bad`} { - t.Run(body, func(t *testing.T) { +func TestReadVersionedFilePinsBranchCommit(t *testing.T) { + const tip = "1234567890123456789012345678901234567890" + const valid = `{"encoding":"base64","content":"eA==","last_commit_id":"file-revision","commit_id":"` + tip + `"}` + for _, tc := range []struct{ name, branchBody, fileBody string }{ + {"same-named tag", `{"commit":{"id":"` + tip + `"}}`, valid}, + {"missing branch tip", `{}`, valid}, + {"branch decode error", `bad`, valid}, + {"wrong commit", `{"commit":{"id":"` + tip + `"}}`, `{"encoding":"base64","content":"eA==","last_commit_id":"r","commit_id":"tag-tip"}`}, + {"missing revision", `{"commit":{"id":"` + tip + `"}}`, `{"encoding":"base64","content":"eA==","commit_id":"` + tip + `"}`}, + {"wrong encoding", `{"commit":{"id":"` + tip + `"}}`, `{"encoding":"text","content":"x","last_commit_id":"r","commit_id":"` + tip + `"}`}, + {"bad content", `{"commit":{"id":"` + tip + `"}}`, `{"encoding":"base64","content":"!","last_commit_id":"r","commit_id":"` + tip + `"}`}, + {"file decode error", `{"commit":{"id":"` + tip + `"}}`, `bad`}, + } { + t.Run(tc.name, func(t *testing.T) { c, mux := setupTest(t) + mux.HandleFunc("GET /api/v4/projects/o%2Fr/repository/branches/state", func(w http.ResponseWriter, _ *http.Request) { + fmt.Fprint(w, tc.branchBody) + }) mux.HandleFunc("GET /api/v4/projects/o%2Fr/repository/files/journal.json", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "state", r.URL.Query().Get("ref")) - fmt.Fprint(w, body) + ref := r.URL.Query().Get("ref") + if ref == "state" { + fmt.Fprint(w, `{"encoding":"base64","content":"dGFn","last_commit_id":"tag-revision","commit_id":"tag-tip"}`) + return + } + assert.Equal(t, tip, ref) + fmt.Fprint(w, tc.fileBody) }) data, rev, err := c.ReadVersionedFile(context.Background(), "o", "r", "state", "journal.json") - if body == `{"encoding":"base64","content":"eA==","last_commit_id":"file-revision"}` { + if tc.name == "same-named tag" { require.NoError(t, err) require.Equal(t, "x", string(data)) require.Equal(t, "file-revision", rev) @@ -61,11 +80,7 @@ func TestVersionedWriteConflictAndNoRetry(t *testing.T) { }) err := c.WriteFileIfRevision(context.Background(), "o", "r", "state", "journal.json", "old", "checkpoint", []byte("x")) require.Error(t, err) - if status == 409 { - require.ErrorIs(t, err, forge.ErrConflict) - } else { - require.NotErrorIs(t, err, forge.ErrConflict) - } + require.NotErrorIs(t, err, forge.ErrConflict) require.Equal(t, int32(1), calls.Load()) }) } diff --git a/internal/journal/forge.go b/internal/journal/forge.go index 99bc7952e7..85ecb86e5c 100644 --- a/internal/journal/forge.go +++ b/internal/journal/forge.go @@ -42,10 +42,13 @@ func (b *ForgeBackend) Initialize(ctx context.Context) error { return err } err = b.client.WriteFileIfRevision(ctx, b.location.Owner, b.location.Repo, b.location.Branch, b.location.Path, "", "Initialize Fullsend journal [skip ci]", content) - if errors.Is(err, forge.ErrConflict) { + if onlyConflict(err, forge.ErrConflict) { return ErrConflict } - return conflict(err) + if err != nil { + return fmt.Errorf("%w: create acknowledgement failed: %v", ErrUncertain, err) + } + return nil } func (b *ForgeBackend) Load(ctx context.Context) (Document, string, error) { if err := b.authorize(ctx, b.location, "read"); err != nil { diff --git a/internal/journal/forge_checkpoint_test.go b/internal/journal/forge_checkpoint_test.go index 55c7a9792f..11328695cb 100644 --- a/internal/journal/forge_checkpoint_test.go +++ b/internal/journal/forge_checkpoint_test.go @@ -248,3 +248,15 @@ func TestIsDefiniteConflict(t *testing.T) { }) } } + +func TestJournalInitializeUncertainAfterCreate(t *testing.T) { + ctx := context.Background() + fc := forge.NewFakeClient() + fc.BranchRefs["o/r/state"] = "tip" + client := &checkpointClient{Client: fc, writeError: errors.New("HTTP 409")} + backend, err := NewForgeBackend(client, Location{"o", "r", "state", "journal.json"}, func(context.Context, Location, string) error { return nil }) + require.NoError(t, err) + require.ErrorIs(t, backend.Initialize(ctx), ErrUncertain) + _, _, err = backend.Load(ctx) + require.NoError(t, err) +} diff --git a/internal/journalhost/errors.go b/internal/journalhost/errors.go new file mode 100644 index 0000000000..a3d85d83d4 --- /dev/null +++ b/internal/journalhost/errors.go @@ -0,0 +1,30 @@ +package journalhost + +import "errors" + +var ( + errProfileRequired = errors.New("protected journal profile required") + errInvalidProfile = errors.New("invalid protected journal profile") + errInvalidScope = errors.New("invalid protected journal scope") + errWriterRole = errors.New("registered journal writer role required") + errWriterCredential = errors.New("journal writer credential unavailable") + errProfileChanged = errors.New("journal host profile changed") + errProtectionUnverified = errors.New("journal branch protection could not be verified") + errProtectedBranch = errors.New("journal requires protected control branch") + errExperimentalOptIn = errors.New("journal requires experimental_gitlab opt-in") + errWriterGrants = errors.New("journal requires writer-only branch push, merge and unprotect grants") +) + +// OperatorError returns fixed, non-sensitive guidance for recognized host errors. +func OperatorError(err error) error { + for _, known := range []error{ + errProfileRequired, errInvalidProfile, errInvalidScope, errWriterRole, + errWriterCredential, errProfileChanged, errProtectionUnverified, + errProtectedBranch, errExperimentalOptIn, errWriterGrants, + } { + if errors.Is(err, known) { + return known + } + } + return nil +} diff --git a/internal/journalhost/errors_test.go b/internal/journalhost/errors_test.go new file mode 100644 index 0000000000..5e15164163 --- /dev/null +++ b/internal/journalhost/errors_test.go @@ -0,0 +1,24 @@ +package journalhost + +import ( + "errors" + "fmt" + "testing" +) + +func TestOperatorErrorReturnsOnlyFixedGuidance(t *testing.T) { + for _, known := range []error{ + errProfileRequired, errInvalidProfile, errInvalidScope, errWriterRole, + errWriterCredential, errProfileChanged, errProtectionUnverified, + errProtectedBranch, errExperimentalOptIn, errWriterGrants, + } { + t.Run(known.Error(), func(t *testing.T) { + if got := OperatorError(fmt.Errorf("private context: %w", known)); got != known { + t.Errorf("OperatorError = %v, want %v", got, known) + } + }) + } + if got := OperatorError(errors.New(errProfileRequired.Error())); got != nil { + t.Errorf("OperatorError recognized a coincidental message: %v", got) + } +} diff --git a/internal/journalhost/profile.go b/internal/journalhost/profile.go index 882a880e62..028bccc91e 100644 --- a/internal/journalhost/profile.go +++ b/internal/journalhost/profile.go @@ -39,21 +39,21 @@ func Load(getenv func(string) string) (Profile, error) { } raw := getenv(ProfileEnv) if len(raw) == 0 || len(raw) > 16384 { - return p, errors.New("protected journal profile required") + return p, errProfileRequired } if err := strictjson.Decode([]byte(raw), &p); err != nil { - return Profile{}, errors.New("invalid protected journal profile") + return Profile{}, errInvalidProfile } u, err := url.Parse(p.BaseURL) if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") || p.Forge != "gitlab" || p.Owner == "" || p.Repo == "" || p.Branch == "" || p.Path == "" || p.Role == "" { - return Profile{}, errors.New("invalid protected journal profile") + return Profile{}, errInvalidProfile } if strings.Contains(p.Repo, "/") || path.Clean(p.Path) != p.Path || strings.HasPrefix(p.Path, "/") || strings.HasPrefix(p.Path, "../") || !strings.HasSuffix(p.Path, ".json") || strings.ContainsAny(p.Path, "\\%?#\r\n") || strings.ContainsAny(p.Branch, " \\%?#\r\n~^:*") || strings.Contains(p.Branch, "..") || strings.HasPrefix(p.Branch, "/") || strings.HasSuffix(p.Branch, "/") || strings.Contains(p.Branch, "@{") { - return Profile{}, errors.New("invalid protected journal scope") + return Profile{}, errInvalidScope } for _, part := range strings.Split(p.Owner+"/"+p.Repo, "/") { if part == "" || part == "." || part == ".." || strings.ContainsAny(part, "\\%?#\r\n") { - return Profile{}, errors.New("invalid protected journal scope") + return Profile{}, errInvalidScope } } return p, nil @@ -66,12 +66,16 @@ func (p Profile) Location() journal.Location { func (p Profile) Credential(getenv func(string) string) (string, error) { sel, err := gitlabroles.SelectAgent(p.Role, p.Role, getenv) if err != nil { - return "", err + return "", errWriterRole } if string(sel.Registration.Name) != p.Role || sel.Registration.Kind != gitlabroles.RoleKindCustom || sel.Registration.Credential.Kind != gitlabroles.CredentialOwn || !sel.Registration.Has(gitlabroles.CapWriteRepository) { - return "", errors.New("registered journal writer role required") + return "", errWriterRole } - return sel.Token(getenv) + token, err := sel.Token(getenv) + if err != nil { + return "", errWriterCredential + } + return token, nil } func (p Profile) Authorizer(client forge.Client, getenv func(string) string, authenticatingToken string) journal.AuthorizeFunc { return func(ctx context.Context, loc journal.Location, action string) error { @@ -80,7 +84,7 @@ func (p Profile) Authorizer(client forge.Client, getenv func(string) string, aut } currentProfile, err := Load(getenv) if err != nil || currentProfile != p { - return errors.New("journal host profile changed") + return errProfileChanged } current, err := p.Credential(getenv) if err != nil { @@ -91,10 +95,10 @@ func (p Profile) Authorizer(client forge.Client, getenv func(string) string, aut } protected, err := client.IsProtectedBranch(ctx, p.Owner, p.Repo, p.Branch) if err != nil { - return errors.New("journal branch protection could not be verified") + return errProtectionUnverified } if !protected { - return errors.New("journal requires protected control branch") + return errProtectedBranch } return p.verifyWriterIsolation(ctx, client) } @@ -107,7 +111,7 @@ func Open(getenv func(string) string) (*journal.Engine, *journal.ForgeBackend, e return nil, nil, err } if !p.ExperimentalGitLab { - return nil, nil, errors.New("journal requires experimental_gitlab opt-in") + return nil, nil, errExperimentalOptIn } token, err := p.Credential(getenv) if err != nil { @@ -127,25 +131,24 @@ func Open(getenv func(string) string) (*journal.Engine, *journal.ForgeBackend, e // verifyWriterIsolation checks every matching rule: GitLab combines overlapping // protections permissively, so an exact rule cannot neutralize a broad wildcard. func (p Profile) verifyWriterIsolation(ctx context.Context, client forge.Client) error { - denied := errors.New("journal requires writer-only branch push, merge and unprotect grants") identity, ok := client.(interface { GetAuthenticatedUserID(context.Context) (int, error) }) if !ok { - return denied + return errWriterGrants } writer, err := identity.GetAuthenticatedUserID(ctx) if err != nil || writer <= 0 { - return denied + return errWriterGrants } rules, err := client.ListProtectedBranches(ctx, p.Owner, p.Repo) if err != nil { - return denied + return errWriterGrants } matched, canPush := false, false for _, rule := range rules { if rule.Name == "" || strings.ContainsAny(rule.Name, "\\?[] \t\r\n") { - return denied + return errWriterGrants } // GitLab protected-branch patterns support '*' across path separators. pattern := "^" + strings.ReplaceAll(regexp.QuoteMeta(rule.Name), `\*`, ".*") + "$" @@ -155,24 +158,24 @@ func (p Profile) verifyWriterIsolation(ctx context.Context, client forge.Client) matched = true // Missing grant metadata cannot establish isolation. if len(rule.PushAccessLevels) == 0 || len(rule.MergeAccessLevels) == 0 || len(rule.UnprotectAccessLevels) == 0 { - return denied + return errWriterGrants } for _, grants := range [][]forge.ProtectedBranchAccess{rule.PushAccessLevels, rule.MergeAccessLevels} { for _, grant := range grants { if grant.GroupID != 0 || grant.DeployKeyID != 0 || grant.MemberRoleID != 0 || grant.UserID < 0 || grant.AccessLevel < 0 { - return denied + return errWriterGrants } if grant.UserID == writer { continue } if grant.UserID != 0 || grant.AccessLevel != 0 { - return denied + return errWriterGrants } } } for _, grant := range rule.UnprotectAccessLevels { if grant.UserID != writer || grant.GroupID != 0 || grant.DeployKeyID != 0 || grant.MemberRoleID != 0 || grant.AccessLevel < 0 { - return denied + return errWriterGrants } } for _, grant := range rule.PushAccessLevels { @@ -182,7 +185,7 @@ func (p Profile) verifyWriterIsolation(ctx context.Context, client forge.Client) } } if !matched || !canPush { - return denied + return errWriterGrants } return nil }