diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index 103b44cb98..c7b2e2dd42 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -349,6 +349,7 @@ export default defineConfig({ items: [ { text: "Config Reference", link: "/reference/config-reference" }, { text: "Harness Field Reference", link: "/reference/harness-reference" }, + { text: "Trace Context Reference", link: "/reference/trace-context" }, ], }, { diff --git a/docs/ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md b/docs/ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md index 90d969ef1f..2301036c05 100644 --- a/docs/ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md +++ b/docs/ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md @@ -19,7 +19,11 @@ Date: 2026-10-22 Accepted -This records the chosen topology; implementation is pending. +This records the chosen topology. The identity, fallback, envelope, and +admission foundation is implemented; the +[trace-context v1 specification](../normative/trace-context/v1/README.md) +defines its contract. Carrier publication, key provisioning, and runtime +integration are pending. ## Context diff --git a/docs/guides/infrastructure/distributed-tracing.md b/docs/guides/infrastructure/distributed-tracing.md index 636e053616..15ac5b3607 100644 --- a/docs/guides/infrastructure/distributed-tracing.md +++ b/docs/guides/infrastructure/distributed-tracing.md @@ -715,6 +715,10 @@ GitHub webhooks do not support custom trace headers. Within a single work item, `fullsend.work_item_id` on the root `run` span is the correlation key for filtering related traces in a backend. +For durable work-item continuity, see +[ADR 0154](../../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md) +and the [Trace Context Reference](../../reference/trace-context.md). + ## Operational behavior - **Export timing:** spans are exported live via the batch processor. On diff --git a/docs/normative/trace-context/v1/README.md b/docs/normative/trace-context/v1/README.md new file mode 100644 index 0000000000..13e3a8ff90 --- /dev/null +++ b/docs/normative/trace-context/v1/README.md @@ -0,0 +1,263 @@ +# Trace context v1 + +This normative specification defines the immutable identity, deterministic +fallback, signed-envelope encoding, and admission contract adopted by +[ADR 0154](../../../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md). +See the [Trace Context Reference](../../../reference/trace-context.md) for +Go API guidance and implementation scope. Carrier publication, key +provisioning, and runtime integration are outside this contract. + +## Identity + +Every forge entity is addressed by an immutable five-part tuple. Display +names, entity URLs, GitHub numbers, GitLab IIDs, and Jira keys are not +identity components. + +| Component | GitHub | GitLab | Jira | +|-----------|--------|--------|------| +| Installation | 128-bit ID provisioned with the signing key pair | same | same | +| Forge instance | web base URL (`https://github.com`, or a GHES host) | web base URL (`https://gitlab.com`, or a self-hosted host) | site base URL | +| Container | repository `id` | project `id` | project `id` | +| Entity kind | `work_item` (issue), `change_proposal` (PR) | `work_item` (issue), `change_proposal` (MR) | `work_item` (issue; Jira has no change proposal) | +| Entity | `work_item`: issue REST `id`; `change_proposal`: pull-request REST `id` = GraphQL `fullDatabaseId` (`BigInt`), never the issue-space ID | issue or MR database `id` (not the IID) | issue `id` | + +A GitHub PR has both a pull-request ID and a different issue-space ID. +The `change_proposal` identity must use the pull-request ID from +`/repos/{owner}/{repo}/pulls/{number}`, also exposed as GraphQL +`fullDatabaseId`. A PR's `/issues/{number}` response and the `issue` object +in an `issue_comment` event carry its issue-space ID, which must never be +used for `change_proposal` identity. For a PR event carrying only that issue +object, resolve the pull-request ID through a trusted forge-adapter +`/pulls/{number}` read before declaring the identity resolved. Until that +read succeeds, keep the identity unresolved rather than substituting the +issue-space ID or display number. + +The instance string is the normalized, trusted deployment base URL: lowercase +`scheme://host`, using `http` or `https`, followed by the case-sensitive, +URL-escaped deployment path prefix, with trailing slashes removed. For +example, `https://GitLab.example.com/gitlab/` becomes +`https://gitlab.example.com/gitlab`; it is distinct from both the root +installation and `/GitLab`. Path segments and existing escape spelling are +preserved, never cleaned or decoded into separators. A path that mixes +percent-escapes with characters that still need escaping, such as +`/a%2Fb/c d`, rejects; write the fully escaped prefix (`/a%2Fb/c%20d`). Use +the same configured deployment URL on every launch, rather than an entity or +API URL. + +Strip leading zeros from the port, keeping an all-zero port as `:0` rather +than treating it as the default, and reject ports above `65535`. Then remove +an empty port and the scheme's default port (`443` for HTTPS, `80` for +HTTP). For example, `https://host:` and `https://host:0443` become +`https://host`, and `https://host:08443` becomes `https://host:8443`. +Hosts must be ASCII: use the punycode form for internationalized domain +names, and reject Unicode host spellings instead of converting them. For +example, `https://GitHub.com:443/` becomes `https://github.com`, and +`https://XN--BCHER-KVA.example` becomes `https://xn--bcher-kva.example`. +Bracketed IPv6 hosts follow the same port rules and take their RFC 5952 +form: `https://[2001:DB8:0:0:0:0:0:1]` becomes `https://[2001:db8::1]`. +Zone identifiers reject (`https://[FE80::1%25EN0]`; use a routable +address), so a normalized instance always re-normalizes to itself. +Trailing DNS root dots are stripped: `https://github.com.` and +`https://github.com` are one deployment with one fallback identity. + +`NormalizeInstance` rejects queries, fragments, user info, missing hosts, +invalid UTF-8 or NUL in the decoded path, and normalized URLs over 253 bytes +(including the escaped prefix). Identity resolution, signing, and parsing +require the already canonical value; they never silently rewrite an +authenticated field. Prefixed deployments use the same v1 length-delimited +instance field and fallback derivation with the full normalized instance +bytes. + +The installation ID is generated during key provisioning and identifies +one install's key set. It is authenticated inside every envelope and must +match the verifier's configured installation at admission. It is +deliberately **not** part of fallback derivation, so entities keep stable +traces regardless of key state. + +### Rename and move rules + +- Renames (issue titles, repository names, Jira project keys) never + change identity: the container and entity components are database IDs. +- Repository transfers on GitHub and GitLab preserve the database ID, so + identity survives a transfer. +- An entity moved between containers (a GitHub issue transfer, a Jira + project move) has a **new binding** — a different container or entity + ID — and therefore a new identity. A previously published envelope + fails the binding check and the moved entity falls back. A move is + never treated as a rename. +- Changing the configured deployment URL (a Jira site rename, a GHES + hostname change, a GitLab `external_url` change) is also a new binding: + published envelopes fail the binding check and entities fall back. + +### Fallback derivation (v1) + +When no admissible stored context exists, the entity's context is derived +deterministically: + +- Input: the forge instance, container, kind, and entity — never the + installation. +- SHA-256 over the exact concatenation below. Only strings are + length-prefixed; all integers are big-endian: + `uint16(33) || "fullsend.tracecontext.identity.v1" || uint16(N) || + instance[N] || uint64(container) || byte(kind) || uint64(entity)`. + `N` counts UTF-8 bytes, container/entity are in `[1, 2^63−1]`, and kind + is `0x01` (work item) or `0x02` (change proposal). +- TraceID = the first 16 digest bytes; the anchor SpanID = the next 8. +- An all-zero result (probability 2⁻¹²⁸ for the trace, 2⁻⁶⁴ for the span) + replaces only that ID's final byte with `0x01`, so derived IDs are valid. + +The derivation is pure, so independent launches and concurrent first +events converge on identical nonzero IDs without shared state. The anchor +SpanID is a synthetic parent reference by protocol choice: no exported span +carries the anchor ID, the anchor is never repointed, and operation spans +keep distinct SDK-generated IDs. OpenTelemetry supports custom ID generators +(`WithIDGenerator`); this contract deliberately uses an unexported anchor +rather than creating a real root span with that ID. + +For `https://github.com`, container `274390431`, kind `0x01`, and entity +`2468913570`, the exact input is: + +```text +002166756c6c73656e642e7472616365636f6e746578742e6964656e746974792e7631 +001268747470733a2f2f6769746875622e636f6d00000000105add9f01000000009328a1a2 +``` + +Concatenate those hex lines before hashing. The TraceID is +`c9bdb0e38247ebbe2e0f1039250c32d4`; the anchor is `892a346c55356aca`. +Additional independent GitLab/Jira vectors and an SDK exporter lifecycle +test are linked from the [implementation reference](../../../reference/trace-context.md). + +## Signed envelope (wire format v1) + +One fixed-layout binary encoding serves both message domains; all +integers are big-endian, and the Ed25519 signature covers every byte from +the magic through the nonce — there are no unsigned fields. + +| Offset | Size | Field | Constraints | +|--------|------|-------|-------------| +| 0 | 4 | Magic `FSTC` | exact bytes | +| 4 | 1 | Version | `0x01`; anything else rejects | +| 5 | 1 | Message domain | `0x01` bound envelope, `0x02` pending marker | +| 6 | 8 | Key ID | first 8 bytes of SHA-256(public key) | +| 14 | 16 | Installation ID | nonzero | +| 30 | 2 | Instance length N | `1 ≤ N ≤ 253` | +| 32 | N | Forge instance | normalized form, UTF-8, no NUL | +| 32+N | 8 | Container ID | `int64 ≥ 1` | +| 40+N | 1 | Entity kind | `0x01` work item, `0x02` change proposal | +| 41+N | 8 | Entity ID | `int64 ≥ 1`; bound envelopes only — pending markers omit these 8 bytes, retaining the kind byte | +| · | 16 | Trace ID | nonzero | +| · | 8 | Parent/anchor Span ID | nonzero | +| · | 1 | Provenance kind | `0x00` none, `0x01` source link, `0x02` scenario | +| · | 0/24/32 | Provenance fields | none; source link = 16B source TraceID + 8B source SpanID; scenario = 16B scenario TraceID + 16B invocation ID | +| · | 16 | Nonce | nonzero (checked); signers draw it from `crypto/rand`, unique per creation intent (not checked at admission) | +| end−64 | 64 | Ed25519 signature | over bytes `[0, end−64)` | + +The maximum legal size is 439 bytes (bound envelope, scenario provenance, +253-byte instance); carriers hold the envelope as unwrapped standard +base64 (≤ 588 characters, no line breaks). + +Strict parsing rules: + +- The total length must equal the exact structural length for the parsed + domain and provenance kind; trailing bytes reject. +- Duplicate and unknown fields are structurally impossible in the fixed + layout. +- Every enumerated byte and ID must satisfy its constraint; invalid + values reject rather than degrade. +- Unknown versions reject — never a partial parse. +- Identical duplicate carriers are acceptable (idempotent publication); + any differing carriers reject — never first-match. + +### Domains, keys, and nonces + +The domain byte is covered by the signature, so a pending marker cannot +be replayed as a bound envelope and vice versa. A pending marker carries +the creation's intended context and provenance as signed intent, omits +the entity ID (the destination does not exist yet), and grants neither +context, parent, nor source link. The nonce links a pending marker to +the bound envelope published after creation; admission never depends on +having seen the marker. + +The key selector resolves **only** against the verifier's configured +eligible keys (active plus retained). Envelopes never carry public keys +or key locations, and metadata can never select a signer or a remote key +URL. After rotation, metadata signed by an older retained key remains +verifiable while new metadata uses the active key. +Missing or malformed-length verification keys yield `unknown-key` fallback +without context or provenance; they never reach Ed25519 verification. + +### Provenance consistency + +- Source-link provenance (ordinary created work) requires the envelope + TraceID to differ from the source TraceID: the destination keeps its + own trace and the source context is a link, never a parent. +- Scenario provenance (behaviour-test work) requires the envelope + TraceID to equal the scenario TraceID: descendants inherit the + scenario trace with distinct operation spans. + +## Admission + +`Admit(expected Identity, keys, candidates...)` is the pure decision +operation. It takes the trusted expected binding, the configured eligible +verification keys, and bounded candidate envelope bytes, each decoded from +its carrier with `DecodeCarrier`, and returns exactly one outcome: + +- **Admitted**: a verified bound envelope matched every binding + component. The result carries the admitted TraceID, parent SpanID, and + authenticated provenance. +- **Pending**: a verified pending marker matched the expected scope — + installation, instance, container, and kind, never the entity, because a + pending marker carries no entity binding by design. A marker replayed + onto another entity in the same container still grants nothing beyond a + bounded wait. It grants no context; callers must bound that wait by a + window from the entity's trusted creation metadata (for example + `created_at`) before rereading and falling back, per + [ADR 0154](../../../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md). +- **Fallback**: nothing was admissible. The caller uses the + entity-derived fallback, except for reason `unresolved`, where it + postpones dispatch (see below). + +The zero-value result selects fallback and grants no context or provenance. + +Fallback reason codes are redacted diagnostics — `absent`, `malformed`, +`oversized`, `unknown-version`, `unknown-key`, `bad-signature`, +`binding-mismatch`, `conflicting-carrier`, `provenance`, `unresolved` — +never key material or raw bytes. A plain W3C `traceparent` is never an +envelope. + +Any differing extra candidate, whether junk or a second envelope, +deliberately forces fallback even when one candidate alone would admit; +identical duplicates do not. An actor who can edit the body can deny +continuity by appending junk or deleting the carrier, but can never alter +or inject a context: only an envelope the installation signed for this +entity admits. Admission has no freshness check, so an older valid +envelope for the same entity still admits. Rejection is deliberately +fail-closed so a forged carrier is reported rather than silently ignored. +Publishing a bound envelope must remove the pending marker it replaces; +leaving both present produces conflicting carriers and fallback, never a +pick between them. + +The result structurally cannot carry sampling flags, `tracestate`, +baggage, or dispatch permission. Trace admission and dispatch +authorization are independent decisions; a denied actor never dispatches +regardless of admission, and an admitted envelope never authorizes +anything. + +An unresolved identity (a missing or invalid instance, container, kind, or +entity, including a non-canonical instance) is explicit: admission returns +fallback with reason `unresolved` before inspecting any candidate, and +callers must postpone dispatch with diagnostics rather than derive a +fallback or guess. + +## Compatibility + +The [conformance vectors](../../../reference/trace-context.md#conformance-evidence) +pin the exact signed bytes of one envelope per domain and provenance kind. + +**v1 is provisional** until the first pull request that publishes carriers +merges. No production carrier exists yet, so the wire layout, derivation, +and key-selector rules may still change without a new version byte while +contract gaps surface in review. From the first carrier-publishing pull +request onward, any such change is a compatibility break that requires a +new version byte and a reviewed migration path. Unknown versions must +reject cleanly. diff --git a/docs/reference/trace-context.md b/docs/reference/trace-context.md new file mode 100644 index 0000000000..b9f2e62125 --- /dev/null +++ b/docs/reference/trace-context.md @@ -0,0 +1,81 @@ +# Trace Context Reference + +The [trace-context v1 specification](../normative/trace-context/v1/README.md) +defines the identity, fallback, wire format, admission, and compatibility +contract for [ADR 0154](../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md). +This page covers the Go API and adapter integration. + +## Implementation scope + +The v1 implementation lives in +[`internal/telemetry/tracecontext`](https://github.com/fullsend-ai/fullsend/tree/main/internal/telemetry/tracecontext): +[`identity.go`](https://github.com/fullsend-ai/fullsend/blob/main/internal/telemetry/tracecontext/identity.go) +implements identity resolution and fallback derivation; +[`envelope.go`](https://github.com/fullsend-ai/fullsend/blob/main/internal/telemetry/tracecontext/envelope.go) +implements signing, strict parsing, and admission. The package performs no +network I/O or configuration reads and never grants dispatch permission. +Carrier publication, key provisioning, production creation activation, +runtime admission wiring, and scenario collection remain later delivery +slices. + +The package must stay importable from public behaviour-test code: it must not +depend on `internal/cli`, `internal/repos`, `internal/layers`, or the nested +mintcore module. + +## Adapter integration + +[`JiraClient.GetIssue`](https://github.com/fullsend-ai/fullsend/blob/main/internal/tracker/jira_client.go) +exposes the project ID as `tracker.Issue.ContainerID`; Jira +[search requests](https://github.com/fullsend-ai/fullsend/blob/main/internal/forge/jira/client.go) +include `project`. Missing or invalid project IDs stay zero (unresolved). +Jira's create response contains no project ID, so a subsequent trusted read +must resolve the container before trace admission. Forge-backed tracker +callers must resolve their repository separately through `forge.Client`. + +[`CreateCrossRepoChangeProposal`](https://github.com/fullsend-ai/fullsend/blob/main/internal/forge/github/github.go) +decodes GitHub's `fullDatabaseId` into an `int64`, accepting numeric or string +JSON without floating-point rounding; it does not use the deprecated 32-bit +GraphQL `databaseId`. Missing or invalid IDs leave identity unresolved without +discarding a successful PR creation. + +GitHub `GetIssue` preserves the issue-space ID even for a PR number. Before +constructing a `KindChangeProposal` identity for an `issue_comment` event on +a PR, the runtime integration must resolve the pull-request ID through a +trusted forge read, following the [identity contract](../normative/trace-context/v1/README.md#identity). +`GetPullRequestInfo` currently returns branch/repository context without that +database ID; its result alone cannot resolve trace identity. + +## Go API + +| Symbol | Purpose | +|--------|---------| +| `Identity` | The immutable binding tuple | +| `Identity.Resolved` | Whether the forge-side components are present and valid: a canonical instance, IDs ≥ 1, and a defined kind | +| `DeriveFallback` | The v1 deterministic fallback context | +| `NormalizeInstance` | Canonical deployment base URL, including its path prefix | +| `Envelope` | A decoded, unverified v1 envelope or pending marker; fields are safe only after `Admit` admits | +| `Envelope.Sign` | Validate and sign with an Ed25519 private key (host-side only) | +| `Envelope.Marshal` | Canonical wire bytes | +| `Parse` | Strict bounded structural decode; does not verify the signature or binding | +| `DecodeCarrier` | Strict base64 carrier decode | +| `KeyID` | The 8-byte key selector for a public key | +| `Admit` | The pure admission decision | +| `Result`, `Outcome` | Admission outcome and admitted IDs; the zero value selects fallback | + +## Conformance evidence + +- [`identity_test.go`](https://github.com/fullsend-ai/fullsend/blob/main/internal/telemetry/tracecontext/identity_test.go) + contains independent fallback vectors, deployment-prefix separation checks, + cross-process convergence, root-dot, port, and IPv6 spelling and zone + canonicalization, mixed-escape path rejection, a + normalization fuzz target asserting the canonical form re-normalizes to + itself, and SDK exporter lifecycle assertions. +- [`envelope_test.go`](https://github.com/fullsend-ai/fullsend/blob/main/internal/telemetry/tracecontext/envelope_test.go) + contains independent signed-wire vectors for both domains and all provenance + kinds, binding checks, empty/default/padded-port convergence, zero-value fallback, + pending-scope admission (container-scoped markers, stale markers beside bound + envelopes), unresolved identities suppressing every carrier kind, + malformed-input cases, and parser fuzzing. + +These foundation tests do not establish production runtime integration or +live-adapter trace continuity. diff --git a/internal/forge/fake.go b/internal/forge/fake.go index 014a89e450..36ecabf0a0 100644 --- a/internal/forge/fake.go +++ b/internal/forge/fake.go @@ -1219,6 +1219,9 @@ func (f *FakeClient) CreateChangeProposal(_ context.Context, owner, repo, title, f.proposalCounter++ cp := ChangeProposal{ + // Synthetic immutable database ID in a distinct space from the + // display number, mirroring the real forges. + ID: int64(9100000000 + f.proposalCounter), URL: fmt.Sprintf("https://forge.example.com/%s/%s/pull/%d", owner, repo, f.proposalCounter), Title: title, Number: f.proposalCounter, @@ -1240,6 +1243,7 @@ func (f *FakeClient) CreateCrossRepoChangeProposal(_ context.Context, baseOwner, f.proposalCounter++ cp := ChangeProposal{ URL: fmt.Sprintf("https://forge.example.com/%s/%s/pull/%d", baseOwner, baseRepo, f.proposalCounter), + ID: int64(9100000000 + f.proposalCounter), Title: title, Number: f.proposalCounter, Head: headOwner + ":" + headBranch, @@ -1602,7 +1606,11 @@ func (f *FakeClient) CreateIssue(_ context.Context, owner, repo, title, body str return nil, e } f.issueCounter++ + // The synthetic immutable database ID lives in a distinct space from + // the display number, mirroring the real forges, so identity tests + // can detect conflation. Deterministic: 9000000000 + counter. issue := Issue{ + ID: int64(9000000000 + f.issueCounter), Number: f.issueCounter, Title: title, Body: body, diff --git a/internal/forge/fake_test.go b/internal/forge/fake_test.go index e254b3de51..24d175e948 100644 --- a/internal/forge/fake_test.go +++ b/internal/forge/fake_test.go @@ -338,6 +338,8 @@ func TestFakeClient_CreateCrossRepoChangeProposal(t *testing.T) { assert.Equal(t, "head-owner/head-repo", cp.HeadRepo) assert.Equal(t, "main", cp.Base) assert.Contains(t, cp.URL, "base-owner/base-repo/pull/1") + assert.Positive(t, cp.ID) + assert.NotEqual(t, int64(cp.Number), cp.ID) // Second proposal gets incremented number. cp2, err := fc.CreateCrossRepoChangeProposal(ctx, @@ -347,6 +349,8 @@ func TestFakeClient_CreateCrossRepoChangeProposal(t *testing.T) { require.NoError(t, err) assert.Equal(t, 2, cp2.Number) assert.Len(t, fc.CreatedProposals, 2) + assert.NotEqual(t, cp.ID, cp2.ID) + assert.Equal(t, []ChangeProposal{*cp, *cp2}, fc.CreatedProposals) } func TestFakeClient_CreateChangeProposal(t *testing.T) { diff --git a/internal/forge/forge.go b/internal/forge/forge.go index 46568f54e1..3967ef0e2b 100644 --- a/internal/forge/forge.go +++ b/internal/forge/forge.go @@ -495,10 +495,17 @@ type Repository struct { // ChangeProposal represents a pull request or merge request. type ChangeProposal struct { - URL string - Title string + URL string + Title string + // Number is the display number: GitHub's per-repo PR number or + // GitLab's per-project MR IID. It is not a stable identity. Number int - Head string + // ID is the immutable forge database ID of the change proposal: + // GitHub's REST pull-request id or GitLab's database merge-request + // id (not the IID). It is 0 when the adapter did not capture one. + // A GitHub PR's issue-space id is not its change-proposal identity. + ID int64 + Head string // HeadRepo identifies the repository the head branch lives in, as // "owner/repo" on both GitHub and GitLab (GitLab resolves a fork's // numeric source project ID to its path_with_namespace). Empty when @@ -573,7 +580,17 @@ type Annotation struct { // Issue represents a forge issue. type Issue struct { + // Number is the display number: GitHub's per-repo issue number or + // GitLab's per-project IID. It is not a stable identity. Number int + // ID is the immutable forge database ID of the issue: GitHub's REST + // id or GitLab's database id (not the IID). It is 0 when the adapter + // did not capture one; trace admission treats that as unresolved + // identity rather than guessing. + // For a GitHub PR number, GetIssue returns the issue-space id, not the + // pull-request id. Never use it as KindChangeProposal identity; resolve + // the pull-request id through a trusted pull-request read instead. + ID int64 Title string Body string URL string diff --git a/internal/forge/github/github.go b/internal/forge/github/github.go index ee614fcec2..c22055adbe 100644 --- a/internal/forge/github/github.go +++ b/internal/forge/github/github.go @@ -2483,6 +2483,7 @@ func (c *LiveClient) CreateChangeProposal(ctx context.Context, owner, repo, titl } var pr struct { + ID int64 `json:"id"` HTMLURL string `json:"html_url"` Title string `json:"title"` Number int `json:"number"` @@ -2492,6 +2493,7 @@ func (c *LiveClient) CreateChangeProposal(ctx context.Context, owner, repo, titl } return &forge.ChangeProposal{ + ID: pr.ID, URL: pr.HTMLURL, Title: pr.Title, Number: pr.Number, @@ -2535,6 +2537,7 @@ func (c *LiveClient) CreateCrossRepoChangeProposal(ctx context.Context, baseOwne query := `mutation($input: CreatePullRequestInput!) { createPullRequest(input: $input) { pullRequest { + fullDatabaseId number title url @@ -2565,9 +2568,10 @@ func (c *LiveClient) CreateCrossRepoChangeProposal(ctx context.Context, baseOwne Data struct { CreatePullRequest struct { PullRequest struct { - Number int `json:"number"` - Title string `json:"title"` - URL string `json:"url"` + FullDatabaseID json.RawMessage `json:"fullDatabaseId"` + Number int `json:"number"` + Title string `json:"title"` + URL string `json:"url"` } `json:"pullRequest"` } `json:"createPullRequest"` } `json:"data"` @@ -2594,7 +2598,18 @@ func (c *LiveClient) CreateCrossRepoChangeProposal(ctx context.Context, baseOwne } pr := gqlResult.Data.CreatePullRequest.PullRequest + var id int64 + var number json.Number + // An unusable optional ID must not discard an already-created PR. + if json.Unmarshal(pr.FullDatabaseID, &number) == nil { + id, err = number.Int64() + if err != nil || id < 1 { + id = 0 + } + } return &forge.ChangeProposal{ + // BigInt may be a JSON number or string; never round through float64. + ID: id, URL: pr.URL, Title: pr.Title, Number: pr.Number, @@ -2612,6 +2627,7 @@ func (c *LiveClient) ListRepoPullRequests(ctx context.Context, owner, repo strin } var prs []struct { + ID int64 `json:"id"` HTMLURL string `json:"html_url"` Title string `json:"title"` Number int `json:"number"` @@ -2634,6 +2650,7 @@ func (c *LiveClient) ListRepoPullRequests(ctx context.Context, owner, repo strin for _, pr := range prs { result = append(result, forge.ChangeProposal{ + ID: pr.ID, URL: pr.HTMLURL, Title: pr.Title, Number: pr.Number, @@ -3299,6 +3316,7 @@ func (c *LiveClient) CreateIssue(ctx context.Context, owner, repo, title, body s } } var result struct { + ID int64 `json:"id"` Number int `json:"number"` Title string `json:"title"` Body string `json:"body"` @@ -3311,6 +3329,7 @@ func (c *LiveClient) CreateIssue(ctx context.Context, owner, repo, title, body s return nil, fmt.Errorf("decode issue: %w", err) } return &forge.Issue{ + ID: result.ID, Number: result.Number, Title: result.Title, Body: result.Body, @@ -3353,6 +3372,7 @@ func (c *LiveClient) GetIssue(ctx context.Context, owner, repo string, number in return nil, fmt.Errorf("get issue #%d: %w", number, err) } var result struct { + ID int64 `json:"id"` Number int `json:"number"` Title string `json:"title"` Body string `json:"body"` @@ -3367,6 +3387,7 @@ func (c *LiveClient) GetIssue(ctx context.Context, owner, repo string, number in return nil, fmt.Errorf("decode issue #%d: %w", number, err) } return &forge.Issue{ + ID: result.ID, Number: result.Number, Title: result.Title, Body: result.Body, @@ -3417,6 +3438,7 @@ func (c *LiveClient) ListOpenIssues(ctx context.Context, owner, repo string, lab return nil, fmt.Errorf("list open issues page %d: %w", page, err) } var raw []struct { + ID int64 `json:"id"` Number int `json:"number"` Title string `json:"title"` Body string `json:"body"` @@ -3436,6 +3458,7 @@ func (c *LiveClient) ListOpenIssues(ctx context.Context, owner, repo string, lab continue } result = append(result, forge.Issue{ + ID: item.ID, Number: item.Number, Title: item.Title, Body: item.Body, diff --git a/internal/forge/github/github_test.go b/internal/forge/github/github_test.go index 649cb7a329..a530cba63a 100644 --- a/internal/forge/github/github_test.go +++ b/internal/forge/github/github_test.go @@ -1056,6 +1056,57 @@ func TestCreateChangeProposal_Forbidden(t *testing.T) { assert.True(t, forge.IsForbidden(err), "CreateChangeProposal 403 should wrap ErrForbidden") } +func TestCreateCrossRepoChangeProposal_FullWidthID(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name, jsonID string + want int64 + }{ + {"number", "9007199254740993", 9007199254740993}, + {"string", `"9007199254740993"`, 9007199254740993}, + {"max int64", `"9223372036854775807"`, 9223372036854775807}, + {"null unresolved", "null", 0}, + {"missing unresolved", "", 0}, + {"overflow", `"9223372036854775808"`, 0}, + {"negative", "-1", 0}, + {"zero", "0", 0}, + {"fractional", "1.5", 0}, + {"nonnumeric", `"bad"`, 0}, + {"boolean", "true", 0}, + {"object", `{}`, 0}, + {"array", `[]`, 0}, + } { + t.Run(tc.name, func(t *testing.T) { + getCalls, calls := 0, 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/repos/"): + getCalls++ + json.NewEncoder(w).Encode(map[string]string{"node_id": "NODE_repo"}) + case r.Method == http.MethodPost && r.URL.Path == "/graphql": + calls++ + id := "" + if tc.jsonID != "" { + id = `"fullDatabaseId":` + tc.jsonID + "," + } + fmt.Fprintf(w, `{"data":{"createPullRequest":{"pullRequest":{%s"number":99,"title":"title","url":"https://github.com/org/repo/pull/99"}}}}`, id) + default: + http.NotFound(w, r) + } + })) + defer srv.Close() + cp, err := newTestClient(t, srv).CreateCrossRepoChangeProposal(context.Background(), "org", "repo", "org", "fork", "title", "body", "feature", "main") + assert.Equal(t, 2, getCalls) + assert.Equal(t, 1, calls) + require.NoError(t, err) + assert.Equal(t, tc.want, cp.ID) + assert.Equal(t, 99, cp.Number) + assert.Equal(t, "title", cp.Title) + assert.Equal(t, "https://github.com/org/repo/pull/99", cp.URL) + }) + } +} + func TestCreateCrossRepoChangeProposal(t *testing.T) { t.Run("same-org fork uses GraphQL", func(t *testing.T) { var getRepoCalls []string @@ -1075,6 +1126,8 @@ func TestCreateCrossRepoChangeProposal(t *testing.T) { var body map[string]any json.NewDecoder(r.Body).Decode(&body) + assert.Contains(t, body["query"], "fullDatabaseId") + assert.NotContains(t, body["query"], "\n\t\t\t\tdatabaseId") vars, _ := body["variables"].(map[string]any) input, _ := vars["input"].(map[string]any) assert.Equal(t, "NODE_org_repo", input["repositoryId"]) @@ -1088,9 +1141,10 @@ func TestCreateCrossRepoChangeProposal(t *testing.T) { "data": map[string]any{ "createPullRequest": map[string]any{ "pullRequest": map[string]any{ - "number": 99, - "title": "PR title", - "url": "https://github.com/org/repo/pull/99", + "fullDatabaseId": "9007199254740993", + "number": 99, + "title": "PR title", + "url": "https://github.com/org/repo/pull/99", }, }, }, @@ -1111,6 +1165,7 @@ func TestCreateCrossRepoChangeProposal(t *testing.T) { assert.True(t, graphqlCalled, "should use GraphQL createPullRequest") require.Len(t, getRepoCalls, 2, "should fetch node IDs for both repos") assert.Equal(t, 99, cp.Number) + assert.Equal(t, int64(9007199254740993), cp.ID, "BigInt must survive without float64 rounding") assert.Equal(t, "PR title", cp.Title) assert.Equal(t, "https://github.com/org/repo/pull/99", cp.URL) }) diff --git a/internal/forge/github/trace_identity_test.go b/internal/forge/github/trace_identity_test.go new file mode 100644 index 0000000000..3ed419a9f7 --- /dev/null +++ b/internal/forge/github/trace_identity_test.go @@ -0,0 +1,131 @@ +package github + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/fullsend-ai/fullsend/internal/telemetry/tracecontext" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The tests in this file cover ADR 0154: the immutable database IDs +// required by the identity tuple must survive adapter mapping. GitHub's +// per-repo numbers are display values; the REST `id` is the identity. + +func TestGetIssue_CapturesImmutableID(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, "/repos/org/repo/issues/7", r.URL.Path) + _ = json.NewEncoder(w).Encode(map[string]any{ + "id": 2468913570, + "number": 7, + "title": "Widget is broken", + "body": "details", + "html_url": "https://github.com/org/repo/issues/7", + "state": "open", + "labels": []any{}, + }) + })) + defer srv.Close() + + client := newTestClient(t, srv) + issue, err := client.GetIssue(context.Background(), "org", "repo", 7) + require.NoError(t, err) + assert.Equal(t, int64(2468913570), issue.ID, "GetIssue must capture the immutable REST issue id") + assert.Equal(t, 7, issue.Number, "the display number is still addressed by (owner, repo, number)") +} + +func TestCreateIssue_CapturesImmutableID(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]any{ + "id": 2468913571, + "number": 8, + "title": "New work", + "body": "body", + "html_url": "https://github.com/org/repo/issues/8", + }) + })) + defer srv.Close() + + client := newTestClient(t, srv) + issue, err := client.CreateIssue(context.Background(), "org", "repo", "New work", "body") + require.NoError(t, err) + assert.Equal(t, int64(2468913571), issue.ID, "CreateIssue must capture the immutable REST issue id") + assert.Equal(t, 8, issue.Number) +} + +func TestCreateChangeProposal_CapturesImmutableID(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]any{ + "id": 1357924680, + "number": 12, + "title": "Add widget", + "html_url": "https://github.com/org/repo/pull/12", + }) + })) + defer srv.Close() + + client := newTestClient(t, srv) + cp, err := client.CreateChangeProposal(context.Background(), "org", "repo", "Add widget", "body", "head", "main") + require.NoError(t, err) + assert.Equal(t, int64(1357924680), cp.ID, "CreateChangeProposal must capture the immutable REST pull-request id") + assert.Equal(t, 12, cp.Number) +} + +// TestGetIssue_RenameKeepsIdentity covers the D01 rename rule at the +// adapter boundary: a title change on the same immutable ID must not +// change trace identity. +func TestGetIssue_RenameKeepsIdentity(t *testing.T) { + title := "Widget is broken" + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]any{ + "id": 2468913570, + "number": 7, + "title": title, + "html_url": "https://github.com/org/repo/issues/7", + "state": "open", + "labels": []any{}, + }) + })) + defer srv.Close() + + client := newTestClient(t, srv) + identity := func() tracecontext.Identity { + issue, err := client.GetIssue(context.Background(), "org", "repo", 7) + require.NoError(t, err) + return tracecontext.Identity{ + Instance: "https://github.com", + Container: 274390431, + Kind: tracecontext.KindWorkItem, + Entity: issue.ID, + } + } + before := identity() + title = "Widget is fixed (renamed)" + assert.Equal(t, before, identity(), "a rename must not change trace identity") +} + +func TestListRepoPullRequests_CapturesImmutableID(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode([]map[string]any{{ + "id": 1357924681, + "number": 13, + "title": "Fix widget", + "html_url": "https://github.com/org/repo/pull/13", + "head": map[string]any{"ref": "fix", "repo": map[string]any{"full_name": "org/repo"}}, + "base": map[string]any{"ref": "main"}, + "user": map[string]any{"login": "octocat"}, + }}) + })) + defer srv.Close() + + client := newTestClient(t, srv) + cps, err := client.ListRepoPullRequests(context.Background(), "org", "repo") + require.NoError(t, err) + require.Len(t, cps, 1) + assert.Equal(t, int64(1357924681), cps[0].ID, "ListRepoPullRequests must capture the immutable REST pull-request id") + assert.Equal(t, 13, cps[0].Number) +} diff --git a/internal/forge/gitlab/issue.go b/internal/forge/gitlab/issue.go index a6e45ddec9..c48e5f5a6f 100644 --- a/internal/forge/gitlab/issue.go +++ b/internal/forge/gitlab/issue.go @@ -29,6 +29,7 @@ func (c *LiveClient) CreateIssue(ctx context.Context, owner, repo, title, body s } var result struct { + ID int64 `json:"id"` IID int `json:"iid"` Title string `json:"title"` Desc string `json:"description"` @@ -40,6 +41,7 @@ func (c *LiveClient) CreateIssue(ctx context.Context, owner, repo, title, body s } return &forge.Issue{ + ID: result.ID, Number: result.IID, Title: result.Title, Body: result.Desc, @@ -58,6 +60,7 @@ func (c *LiveClient) GetIssue(ctx context.Context, owner, repo string, number in } var result struct { + ID int64 `json:"id"` IID int `json:"iid"` Title string `json:"title"` Desc string `json:"description"` @@ -76,6 +79,7 @@ func (c *LiveClient) GetIssue(ctx context.Context, owner, repo string, number in state = "open" } return &forge.Issue{ + ID: result.ID, Number: result.IID, Title: result.Title, Body: result.Desc, @@ -107,6 +111,7 @@ func (c *LiveClient) ListOpenIssues(ctx context.Context, owner, repo string, lab } var raw []struct { + ID int64 `json:"id"` IID int `json:"iid"` Title string `json:"title"` Desc string `json:"description"` @@ -119,6 +124,7 @@ func (c *LiveClient) ListOpenIssues(ctx context.Context, owner, repo string, lab for _, item := range raw { result = append(result, forge.Issue{ + ID: item.ID, Number: item.IID, Title: item.Title, Body: item.Desc, diff --git a/internal/forge/gitlab/mr.go b/internal/forge/gitlab/mr.go index bb48e74eca..5619bd592a 100644 --- a/internal/forge/gitlab/mr.go +++ b/internal/forge/gitlab/mr.go @@ -77,6 +77,7 @@ func (c *LiveClient) createMergeRequest(ctx context.Context, projPath string, pa } var mr struct { + ID int64 `json:"id"` IID int `json:"iid"` Title string `json:"title"` WebURL string `json:"web_url"` @@ -88,6 +89,7 @@ func (c *LiveClient) createMergeRequest(ctx context.Context, projPath string, pa } return &forge.ChangeProposal{ + ID: mr.ID, Number: mr.IID, URL: mr.WebURL, Title: mr.Title, @@ -112,6 +114,7 @@ func (c *LiveClient) ListRepoPullRequests(ctx context.Context, owner, repo strin } var mrs []struct { + ID int64 `json:"id"` IID int `json:"iid"` Title string `json:"title"` WebURL string `json:"web_url"` @@ -151,6 +154,7 @@ func (c *LiveClient) ListRepoPullRequests(ctx context.Context, owner, repo strin headRepo = resolved } result = append(result, forge.ChangeProposal{ + ID: mr.ID, Number: mr.IID, URL: mr.WebURL, Title: mr.Title, diff --git a/internal/forge/gitlab/trace_identity_test.go b/internal/forge/gitlab/trace_identity_test.go new file mode 100644 index 0000000000..3286096f36 --- /dev/null +++ b/internal/forge/gitlab/trace_identity_test.go @@ -0,0 +1,173 @@ +package gitlab + +import ( + "context" + "net/http" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/forge" +) + +// The tests in this file cover ADR 0154: the immutable database IDs +// required by the identity tuple must survive adapter mapping. GitLab's +// per-project IIDs are display values; the database `id` is the identity, +// and issue and merge-request id spaces are independent. + +func TestGetIssue_CapturesDatabaseID(t *testing.T) { + client, mux := setupTest(t) + ctx := context.Background() + handlerCalled := false + + mux.HandleFunc("/api/v4/projects/owner%2Frepo/issues/5", func(w http.ResponseWriter, r *http.Request) { + handlerCalled = true + writeJSON(t, w, http.StatusOK, map[string]any{ + "id": 987654321, + "iid": 5, + "title": "Widget is broken", + "description": "details", + "web_url": "https://gitlab.com/owner/repo/-/issues/5", + "state": "opened", + }) + }) + + issue, err := client.GetIssue(ctx, "owner", "repo", 5) + require.NoError(t, err) + assert.True(t, handlerCalled, "handler was not called — URL path mismatch") + assert.Equal(t, int64(987654321), issue.ID, "GetIssue must capture the immutable database id, not the IID") + assert.Equal(t, 5, issue.Number, "the display IID is still addressed by (owner, repo, iid)") +} + +func TestCreateIssue_CapturesDatabaseID(t *testing.T) { + client, mux := setupTest(t) + ctx := context.Background() + handlerCalled := false + + mux.HandleFunc("/api/v4/projects/owner%2Frepo/issues", func(w http.ResponseWriter, r *http.Request) { + handlerCalled = true + writeJSON(t, w, http.StatusCreated, map[string]any{ + "id": 987654322, + "iid": 6, + "title": "New work", + "description": "body", + "web_url": "https://gitlab.com/owner/repo/-/issues/6", + }) + }) + + issue, err := client.CreateIssue(ctx, "owner", "repo", "New work", "body") + assert.True(t, handlerCalled) + require.NoError(t, err) + assert.Equal(t, int64(987654322), issue.ID, "CreateIssue must capture the immutable database id") + assert.Equal(t, 6, issue.Number) +} + +// TestGetIssue_NestedNamespace exercises a project path under nested groups: +// the identity fields must survive the same escaped-path mapping. +func TestGetIssue_NestedNamespace(t *testing.T) { + client, mux := setupTest(t) + ctx := context.Background() + handlerCalled := false + + mux.HandleFunc("/api/v4/projects/group%2Fsubgroup%2Frepo/issues/7", func(w http.ResponseWriter, r *http.Request) { + handlerCalled = true + writeJSON(t, w, http.StatusOK, map[string]any{ + "id": 987654323, + "iid": 7, + "title": "Nested", + "description": "details", + "web_url": "https://gitlab.com/group/subgroup/repo/-/issues/7", + "state": "opened", + }) + }) + + issue, err := client.GetIssue(ctx, "group/subgroup", "repo", 7) + require.NoError(t, err) + assert.True(t, handlerCalled, "handler was not called — URL path mismatch") + assert.Equal(t, int64(987654323), issue.ID) + assert.Equal(t, 7, issue.Number) +} + +func TestCreateChangeProposal_CapturesDatabaseID(t *testing.T) { + client, mux := setupTest(t) + ctx := context.Background() + handlerCalled := false + + mux.HandleFunc("/api/v4/projects/owner%2Frepo/merge_requests", func(w http.ResponseWriter, r *http.Request) { + handlerCalled = true + writeJSON(t, w, http.StatusCreated, map[string]any{ + "id": 555444333, + "iid": 9, + "title": "Add widget", + "web_url": "https://gitlab.com/owner/repo/-/merge_requests/9", + "source_branch": "feature", + "target_branch": "main", + }) + }) + + cp, err := client.CreateChangeProposal(ctx, "owner", "repo", "Add widget", "body", "feature", "main") + assert.True(t, handlerCalled) + require.NoError(t, err) + assert.Equal(t, int64(555444333), cp.ID, "CreateChangeProposal must capture the immutable database MR id, not the IID") + assert.Equal(t, 9, cp.Number) +} + +func TestListRepoPullRequests_CapturesDatabaseID(t *testing.T) { + client, mux := setupTest(t) + ctx := context.Background() + handlerCalled := false + + mux.HandleFunc("/api/v4/projects/owner%2Frepo/merge_requests", func(w http.ResponseWriter, r *http.Request) { + handlerCalled = true + writeJSON(t, w, http.StatusOK, []map[string]any{{ + "id": 555444334, + "iid": 10, + "title": "Fix widget", + "web_url": "https://gitlab.com/owner/repo/-/merge_requests/10", + "source_branch": "fix", + "target_branch": "main", + "author": map[string]any{"username": "octocat"}, + }}) + }) + + cps, err := client.ListRepoPullRequests(ctx, "owner", "repo") + assert.True(t, handlerCalled) + require.NoError(t, err) + require.Len(t, cps, 1) + assert.Equal(t, int64(555444334), cps[0].ID, "ListRepoPullRequests must capture the immutable database MR id") + assert.Equal(t, 10, cps[0].Number) +} + +// TestListOpenIssues_CapturesDatabaseID keeps the display and identity +// fields distinguishable on the listing path used by polling. +func TestListOpenIssues_CapturesDatabaseID(t *testing.T) { + client, mux := setupTest(t) + ctx := context.Background() + handlerCalled := false + + mux.HandleFunc("/api/v4/projects/owner%2Frepo/issues", func(w http.ResponseWriter, r *http.Request) { + handlerCalled = true + writeJSON(t, w, http.StatusOK, []map[string]any{{ + "id": 987654324, + "iid": 11, + "title": "Listed", + "description": "details", + "web_url": "https://gitlab.com/owner/repo/-/issues/11", + }}) + }) + + issues, err := client.ListOpenIssues(ctx, "owner", "repo") + assert.True(t, handlerCalled) + require.NoError(t, err) + require.Len(t, issues, 1) + assert.Equal(t, int64(987654324), issues[0].ID) + assert.Equal(t, 11, issues[0].Number) +} + +// Compile-time guard: the fixture values above must stay forge.Issue / +// forge.ChangeProposal fields. +var ( + _ = forge.Issue{ID: 1} + _ = forge.ChangeProposal{ID: 1} +) diff --git a/internal/forge/jira/client.go b/internal/forge/jira/client.go index 68f956e09d..bd7d916ed9 100644 --- a/internal/forge/jira/client.go +++ b/internal/forge/jira/client.go @@ -351,7 +351,7 @@ type searchRequest struct { // plausibly exceed the client's 10MB decode cap — and since a failed // search aborts the whole cycle with the same data returning every time, // that failure mode would wedge the poller for the entire project. -var searchFields = []string{"summary", "status", "labels", "reporter", "created", "updated"} +var searchFields = []string{"summary", "status", "labels", "reporter", "created", "updated", "project"} // maxSearchPages limits pagination to prevent unbounded memory growth // from overly broad JQL queries. diff --git a/internal/forge/jira/client_test.go b/internal/forge/jira/client_test.go index 1d49890591..ff5ef96950 100644 --- a/internal/forge/jira/client_test.go +++ b/internal/forge/jira/client_test.go @@ -781,6 +781,61 @@ func TestGetIssue(t *testing.T) { assert.Equal(t, "new", issue.Fields.Status.StatusCategory.Key) } +// TestGetIssue_CapturesProjectRef covers ADR 0154: the immutable +// project database ID (the Jira container identity) must survive issue +// reads, distinct from the display project key. +func TestGetIssue_CapturesProjectRef(t *testing.T) { + t.Parallel() + client, mux := setupTest(t) + ctx := context.Background() + handlerCalled := false + + mux.HandleFunc("/rest/api/3/issue/PROJ-42", func(w http.ResponseWriter, r *http.Request) { + handlerCalled = true + writeJSON(t, w, http.StatusOK, map[string]any{ + "id": "10042", + "key": "PROJ-42", + "fields": map[string]any{ + "summary": "Test issue", + "project": map[string]any{"id": "10000", "key": "PROJ"}, + }, + }) + }) + + issue, err := client.GetIssue(ctx, "PROJ-42") + assert.True(t, handlerCalled) + require.NoError(t, err) + require.NotNil(t, issue.Fields.Project, "project ref must be captured") + assert.Equal(t, "10000", issue.Fields.Project.ID, "immutable project database id") + assert.Equal(t, "PROJ", issue.Fields.Project.Key, "display project key") +} + +func TestSearchIssues_CapturesProjectRef(t *testing.T) { + t.Parallel() + client, mux := setupTest(t) + handlerCalled := false + mux.HandleFunc("/rest/api/3/search/jql", func(w http.ResponseWriter, r *http.Request) { + handlerCalled = true + var body searchRequest + if !assert.NoError(t, json.NewDecoder(r.Body).Decode(&body)) { + return + } + assert.Contains(t, body.Fields, "project", "polling must request immutable container identity") + writeJSON(t, w, http.StatusOK, map[string]any{ + "isLast": true, + "issues": []any{map[string]any{"id": "10042", "key": "PROJ-42", "fields": map[string]any{ + "project": map[string]any{"id": "10000", "key": "PROJ"}, + }}}, + }) + }) + issues, err := client.SearchIssues(context.Background(), "project = PROJ", 0) + assert.True(t, handlerCalled) + require.NoError(t, err) + require.Len(t, issues, 1) + require.NotNil(t, issues[0].Fields.Project) + assert.Equal(t, "10000", issues[0].Fields.Project.ID) +} + func TestGetIssue_IssueTypeAndCustomFields(t *testing.T) { t.Parallel() client, mux := setupTest(t) diff --git a/internal/forge/jira/types.go b/internal/forge/jira/types.go index 158e0039c0..46907ed020 100644 --- a/internal/forge/jira/types.go +++ b/internal/forge/jira/types.go @@ -32,6 +32,9 @@ type IssueFields struct { Updated string `json:"updated"` Comment *CommentPage `json:"comment,omitempty"` IssueType *IssueType `json:"issuetype,omitempty"` + // Project is the issue's project. Its ID is the immutable Jira + // container identity for trace binding; the key is display-only. + Project *ProjectRef `json:"project,omitempty"` // CustomFields holds the raw JSON value of every "customfield_*" key // in the fields object, keyed by field ID (e.g. "customfield_10875"). @@ -44,6 +47,13 @@ type IssueFields struct { // customFieldPrefix is the prefix Jira uses for custom field IDs. const customFieldPrefix = "customfield_" +// ProjectRef identifies a Jira project. ID is the immutable project +// database ID (the trace container identity); Key is the display key. +type ProjectRef struct { + ID string `json:"id"` + Key string `json:"key"` +} + // UnmarshalJSON decodes the standard fields and additionally collects // every "customfield_*" key into CustomFields. func (f *IssueFields) UnmarshalJSON(data []byte) error { diff --git a/internal/telemetry/tracecontext/envelope.go b/internal/telemetry/tracecontext/envelope.go new file mode 100644 index 0000000000..6c974e9a72 --- /dev/null +++ b/internal/telemetry/tracecontext/envelope.go @@ -0,0 +1,530 @@ +package tracecontext + +import ( + "bytes" + "crypto/ed25519" + "crypto/sha256" + "encoding/base64" + "encoding/binary" + "errors" + "fmt" + "strings" + + "go.opentelemetry.io/otel/trace" +) + +// Domain distinguishes the two v1 message domains. The domain byte is +// covered by the signature, so a pending marker cannot be replayed as a +// bound envelope. +type Domain byte + +const ( + // DomainBound is a signed envelope bound to a destination entity. + DomainBound Domain = 0x01 + // DomainPending is a signed creation-intent marker. It carries no + // entity ID and grants neither context, parent, nor source link. + DomainPending Domain = 0x02 +) + +// Valid reports whether d is a defined message domain. +func (d Domain) Valid() bool { + return d == DomainBound || d == DomainPending +} + +// ProvenanceKind selects the authenticated provenance section. +type ProvenanceKind byte + +const ( + // ProvenanceNone means the envelope carries no creation provenance. + ProvenanceNone ProvenanceKind = 0x00 + // ProvenanceSourceLink is an ordinary creation relationship: the + // source operation's span context, recorded as a link only. The + // destination keeps its own TraceID. + ProvenanceSourceLink ProvenanceKind = 0x01 + // ProvenanceScenario is behaviour-test scenario ownership: the entity + // inherits the scenario TraceID. + ProvenanceScenario ProvenanceKind = 0x02 +) + +// Valid reports whether k is a defined provenance kind. +func (k ProvenanceKind) Valid() bool { + return k == ProvenanceNone || k == ProvenanceSourceLink || k == ProvenanceScenario +} + +// Provenance carries the authenticated creation provenance of an envelope. +// Only the fields selected by Kind are meaningful. +type Provenance struct { + Kind ProvenanceKind + // SourceTraceID and SourceSpanID identify the creating operation for + // ProvenanceSourceLink. Valid when Kind == ProvenanceSourceLink. + SourceTraceID trace.TraceID + SourceSpanID trace.SpanID + // ScenarioTraceID and ScenarioInvocationID identify the scenario for + // ProvenanceScenario. Valid when Kind == ProvenanceScenario. + ScenarioTraceID trace.TraceID + ScenarioInvocationID [16]byte +} + +// Envelope is a decoded v1 envelope or pending marker. Its fields are +// unauthenticated: Parse checks structure only, so TraceID, ParentSpanID, +// and Provenance must not be consumed unless Admit returns +// OutcomeAdmitted. The wire layout, exact sizes, and strict limits are +// specified in docs/normative/trace-context/v1/README.md, provisional until +// the first carrier-publishing PR merges; Marshal is its only legal encoder. +type Envelope struct { + Domain Domain + KeyID [8]byte + Installation [16]byte + Instance string + Container int64 + Kind EntityKind + // Entity is the immutable destination database ID. It must be 0 in + // pending markers; the destination does not exist yet. + Entity int64 + TraceID trace.TraceID + ParentSpanID trace.SpanID + Provenance Provenance + Nonce [16]byte + Signature [64]byte +} + +// MaxEnvelopeLen is the maximum legal wire size in bytes: a bound envelope +// with scenario provenance and a 253-byte instance (439 bytes). Anything +// longer is definitionally invalid. +const MaxEnvelopeLen = 439 + +// MaxCarrierLen is the maximum legal base64 carrier length in characters: +// base64.StdEncoding of MaxEnvelopeLen bytes without line breaks. +const MaxCarrierLen = 588 + +// Wire constants of the v1 format. +var magic = [4]byte{'F', 'S', 'T', 'C'} + +const versionV1 = 0x01 + +// Parse error sentinels; Admit maps them to reason codes. +var ( + errOversized = errors.New("tracecontext: envelope exceeds maximum length") + errUnknownVersion = errors.New("tracecontext: unknown envelope version") + errMalformed = errors.New("tracecontext: malformed envelope") +) + +// minEnvelopeLen is the structural lower bound: pending domain, no +// provenance, one instance byte. Canonical URL validation is stricter. +const minEnvelopeLen = 147 + +// KeyID returns the v1 key selector for a verification key: the first 8 +// bytes of SHA-256(public key). Envelopes carry only this selector; keys +// are resolved exclusively against trusted configuration. +func KeyID(pub ed25519.PublicKey) [8]byte { + sum := sha256.Sum256(pub) + var id [8]byte + copy(id[:], sum[:8]) + return id +} + +// validate enforces the structural field constraints shared by Sign and +// Parse. Provenance cross-field consistency is separate (checkConsistency) +// because it is an admission-layer rule, not wire validity. +func (e *Envelope) validate() error { + if !e.Domain.Valid() { + return fmt.Errorf("%w: domain %#02x", errMalformed, byte(e.Domain)) + } + if e.Installation == ([16]byte{}) { + return fmt.Errorf("%w: zero installation", errMalformed) + } + if !validInstance(e.Instance) { + return fmt.Errorf("%w: invalid instance", errMalformed) + } + if e.Container < 1 { + return fmt.Errorf("%w: container %d", errMalformed, e.Container) + } + if !e.Kind.Valid() { + return fmt.Errorf("%w: kind %#02x", errMalformed, byte(e.Kind)) + } + if e.Domain == DomainBound { + if e.Entity < 1 { + return fmt.Errorf("%w: entity %d", errMalformed, e.Entity) + } + } else if e.Entity != 0 { + return fmt.Errorf("%w: pending marker carries entity %d", errMalformed, e.Entity) + } + if !e.TraceID.IsValid() { + return fmt.Errorf("%w: zero trace id", errMalformed) + } + if !e.ParentSpanID.IsValid() { + return fmt.Errorf("%w: zero span id", errMalformed) + } + if !e.Provenance.Kind.Valid() { + return fmt.Errorf("%w: provenance kind %#02x", errMalformed, byte(e.Provenance.Kind)) + } + switch e.Provenance.Kind { + case ProvenanceSourceLink: + if !e.Provenance.SourceTraceID.IsValid() || !e.Provenance.SourceSpanID.IsValid() { + return fmt.Errorf("%w: invalid source link", errMalformed) + } + case ProvenanceScenario: + if !e.Provenance.ScenarioTraceID.IsValid() { + return fmt.Errorf("%w: zero scenario trace id", errMalformed) + } + if e.Provenance.ScenarioInvocationID == ([16]byte{}) { + return fmt.Errorf("%w: zero scenario invocation id", errMalformed) + } + } + if e.Nonce == ([16]byte{}) { + return fmt.Errorf("%w: zero nonce", errMalformed) + } + return nil +} + +// checkConsistency enforces the D02 provenance consistency rules: an +// ordinary source link keeps separate traces; scenario provenance inherits +// the scenario trace. +func (e *Envelope) checkConsistency() error { + switch e.Provenance.Kind { + case ProvenanceSourceLink: + if e.TraceID == e.Provenance.SourceTraceID { + return errors.New("tracecontext: source-link provenance must not merge the source and destination traces") + } + case ProvenanceScenario: + if e.TraceID != e.Provenance.ScenarioTraceID { + return errors.New("tracecontext: scenario provenance must inherit the scenario trace") + } + } + return nil +} + +// payload returns the signed prefix of the wire bytes: everything except +// the 64-byte signature. The magic, version, and domain bytes are included, +// so signatures are domain-separated and cannot be replayed across +// message domains. +func (e *Envelope) payload() []byte { + buf := make([]byte, 0, MaxEnvelopeLen) + buf = append(buf, magic[:]...) + buf = append(buf, versionV1, byte(e.Domain)) + buf = append(buf, e.KeyID[:]...) + buf = append(buf, e.Installation[:]...) + var l [2]byte + binary.BigEndian.PutUint16(l[:], uint16(len(e.Instance))) + buf = append(buf, l[:]...) + buf = append(buf, e.Instance...) + var i64 [8]byte + binary.BigEndian.PutUint64(i64[:], uint64(e.Container)) + buf = append(buf, i64[:]...) + buf = append(buf, byte(e.Kind)) + if e.Domain == DomainBound { + binary.BigEndian.PutUint64(i64[:], uint64(e.Entity)) + buf = append(buf, i64[:]...) + } + buf = append(buf, e.TraceID[:]...) + buf = append(buf, e.ParentSpanID[:]...) + buf = append(buf, byte(e.Provenance.Kind)) + switch e.Provenance.Kind { + case ProvenanceSourceLink: + buf = append(buf, e.Provenance.SourceTraceID[:]...) + buf = append(buf, e.Provenance.SourceSpanID[:]...) + case ProvenanceScenario: + buf = append(buf, e.Provenance.ScenarioTraceID[:]...) + buf = append(buf, e.Provenance.ScenarioInvocationID[:]...) + } + buf = append(buf, e.Nonce[:]...) + return buf +} + +// Sign validates the envelope, derives KeyID from the signing key, and +// signs the canonical bytes in place. Signing is a trusted host-side +// operation; keys never enter sandboxes or argv. +func (e *Envelope) Sign(key ed25519.PrivateKey) error { + if len(key) != ed25519.PrivateKeySize { + return errors.New("tracecontext: invalid signing key size") + } + if err := e.validate(); err != nil { + return err + } + if err := e.checkConsistency(); err != nil { + return err + } + pub := key.Public().(ed25519.PublicKey) + e.KeyID = KeyID(pub) + copy(e.Signature[:], ed25519.Sign(key, e.payload())) + return nil +} + +// Marshal returns the canonical wire bytes including the signature. Sign +// must have completed; marshalling an unsigned envelope yields bytes no +// verifier accepts. +func (e *Envelope) Marshal() []byte { + return append(e.payload(), e.Signature[:]...) +} + +// Parse strictly decodes and structurally validates wire bytes. It accepts +// only the exact structural length for the parsed domain and provenance +// kind; duplicate and unknown fields are structurally impossible in the +// fixed layout. Parse does not verify the signature or binding, so its +// result is unauthenticated: Admit is the only authenticated path and the +// only safe source of trace context. Provenance cross-field consistency is +// checked at admission, not here. +func Parse(b []byte) (*Envelope, error) { + if len(b) > MaxEnvelopeLen { + return nil, errOversized + } + if len(b) < minEnvelopeLen { + return nil, fmt.Errorf("%w: %d bytes", errMalformed, len(b)) + } + if !bytes.Equal(b[0:4], magic[:]) { + return nil, fmt.Errorf("%w: bad magic", errMalformed) + } + if b[4] != versionV1 { + return nil, fmt.Errorf("%w: %#02x", errUnknownVersion, b[4]) + } + domain := Domain(b[5]) + if !domain.Valid() { + return nil, fmt.Errorf("%w: domain %#02x", errMalformed, b[5]) + } + + off := 32 + grab := func(n int) ([]byte, error) { + if off+n > len(b) { + return nil, fmt.Errorf("%w: truncated at %d", errMalformed, off) + } + p := b[off : off+n] + off += n + return p, nil + } + + e := &Envelope{Domain: domain} + // The minimum-length check covers the fixed 32-byte header. + copy(e.KeyID[:], b[6:14]) + copy(e.Installation[:], b[14:30]) + instLen := int(binary.BigEndian.Uint16(b[30:32])) + if instLen < 1 || instLen > 253 { + return nil, fmt.Errorf("%w: instance length %d", errMalformed, instLen) + } + p, err := grab(instLen) + if err != nil { + return nil, err + } + e.Instance = string(p) + p, err = grab(8) + if err != nil { + return nil, err + } + e.Container = int64(binary.BigEndian.Uint64(p)) + p, err = grab(1) + if err != nil { + return nil, err + } + e.Kind = EntityKind(p[0]) + if domain == DomainBound { + p, err = grab(8) + if err != nil { + return nil, err + } + e.Entity = int64(binary.BigEndian.Uint64(p)) + } + p, err = grab(16) + if err != nil { + return nil, err + } + copy(e.TraceID[:], p) + p, err = grab(8) + if err != nil { + return nil, err + } + copy(e.ParentSpanID[:], p) + p, err = grab(1) + if err != nil { + return nil, err + } + e.Provenance.Kind = ProvenanceKind(p[0]) + switch e.Provenance.Kind { + case ProvenanceSourceLink: + p, err = grab(16) + if err != nil { + return nil, err + } + copy(e.Provenance.SourceTraceID[:], p) + p, err = grab(8) + if err != nil { + return nil, err + } + copy(e.Provenance.SourceSpanID[:], p) + case ProvenanceScenario: + p, err = grab(16) + if err != nil { + return nil, err + } + copy(e.Provenance.ScenarioTraceID[:], p) + p, err = grab(16) + if err != nil { + return nil, err + } + copy(e.Provenance.ScenarioInvocationID[:], p) + case ProvenanceNone: + default: + return nil, fmt.Errorf("%w: provenance kind %#02x", errMalformed, p[0]) + } + p, err = grab(16) + if err != nil { + return nil, err + } + copy(e.Nonce[:], p) + if off != len(b)-64 { + return nil, fmt.Errorf("%w: %d trailing bytes", errMalformed, len(b)-64-off) + } + copy(e.Signature[:], b[off:]) + + if err := e.validate(); err != nil { + return nil, err + } + return e, nil +} + +// DecodeCarrier strictly decodes a base64 carrier string to raw envelope +// bytes. It rejects line breaks, non-canonical encodings, and carriers +// longer than MaxCarrierLen. +func DecodeCarrier(s string) ([]byte, error) { + if strings.ContainsAny(s, "\r\n") { + return nil, errors.New("tracecontext: carrier contains line breaks") + } + if len(s) > MaxCarrierLen { + return nil, errors.New("tracecontext: carrier exceeds maximum length") + } + b, err := base64.StdEncoding.Strict().DecodeString(s) + if err != nil { + return nil, fmt.Errorf("tracecontext: decode carrier: %w", err) + } + return b, nil +} + +// Outcome is the admission outcome. It never encodes dispatch permission. +type Outcome int + +const ( + // OutcomeFallback means no carrier was admissible; the caller uses + // the deterministic entity-derived fallback, except for + // ReasonUnresolved, where it must postpone dispatch. It is the zero + // value. + OutcomeFallback Outcome = iota + // OutcomeAdmitted means a verified bound envelope matched the + // expected binding; the admitted IDs are available. + OutcomeAdmitted + // OutcomePending means a verified pending marker matched the expected + // scope. It grants neither context nor links; callers bound the reread + // by a window from the entity's trusted creation metadata, then fall + // back. + OutcomePending +) + +// Reason codes for non-admitted outcomes. They are redacted diagnostics: +// no key material, no raw bytes. +const ( + ReasonAbsent = "absent" + ReasonMalformed = "malformed" + ReasonOversized = "oversized" + ReasonUnknownVersion = "unknown-version" + ReasonUnknownKey = "unknown-key" + ReasonBadSignature = "bad-signature" + ReasonBindingMismatch = "binding-mismatch" + ReasonConflictingCarrier = "conflicting-carrier" + ReasonProvenance = "provenance" + ReasonUnresolved = "unresolved" + ReasonPending = "pending" +) + +// Result is the admission outcome. It carries admitted IDs and +// authenticated provenance only — never sampling flags, tracestate, +// baggage, or dispatch permission (FR-007, FR-008). +// Its zero value selects fallback and carries no admitted context or links. +type Result struct { + Outcome Outcome + // Reason is a redacted reason code when the outcome is not admitted. + Reason string + // TraceID and ParentSpanID are the admitted context, valid when + // Outcome == OutcomeAdmitted. + TraceID trace.TraceID + ParentSpanID trace.SpanID + // Provenance is the authenticated provenance, valid when + // Outcome == OutcomeAdmitted. + Provenance Provenance +} + +func fallback(reason string) Result { + return Result{Outcome: OutcomeFallback, Reason: reason} +} + +func reasonForParse(err error) string { + switch { + case errors.Is(err, errOversized): + return ReasonOversized + case errors.Is(err, errUnknownVersion): + return ReasonUnknownVersion + default: + return ReasonMalformed + } +} + +// Admit parses, verifies, and binds candidate envelope wire bytes, each +// decoded from its carrier with DecodeCarrier, against the expected +// identity and the configured eligible verification keys (active plus +// retained). Identical duplicate candidates are acceptable; any differing +// candidates reject. Keys are resolved only from the supplied trusted set. +// Admission is independent of dispatch authorization: this function never +// returns permission. +// +// An unresolved expected identity reports ReasonUnresolved before any +// carrier is inspected: the caller must postpone dispatch (FR-002) and +// must not read the candidate's own diagnostics as the cause. +func Admit(expected Identity, keys map[[8]byte]ed25519.PublicKey, candidates ...[]byte) Result { + if !expected.Resolved() { + return fallback(ReasonUnresolved) + } + if len(candidates) == 0 { + return fallback(ReasonAbsent) + } + parsed := make([]*Envelope, 0, len(candidates)) + for _, c := range candidates { + env, err := Parse(c) + if err != nil { + return fallback(reasonForParse(err)) + } + parsed = append(parsed, env) + } + for i := 1; i < len(parsed); i++ { + if !bytes.Equal(candidates[i], candidates[0]) { + return fallback(ReasonConflictingCarrier) + } + } + + env := parsed[0] + pub, ok := keys[env.KeyID] + if !ok || len(pub) != ed25519.PublicKeySize { + return fallback(ReasonUnknownKey) + } + payload := candidates[0][:len(candidates[0])-64] + if !ed25519.Verify(pub, payload, env.Signature[:]) { + return fallback(ReasonBadSignature) + } + if err := env.checkConsistency(); err != nil { + return fallback(ReasonProvenance) + } + if env.Installation != expected.Installation || + env.Instance != expected.Instance || + env.Container != expected.Container || + env.Kind != expected.Kind { + return fallback(ReasonBindingMismatch) + } + if env.Domain == DomainBound { + if env.Entity != expected.Entity { + return fallback(ReasonBindingMismatch) + } + return Result{ + Outcome: OutcomeAdmitted, + TraceID: env.TraceID, + ParentSpanID: env.ParentSpanID, + Provenance: env.Provenance, + } + } + // A pending marker binds no entity, so a resolved scope is enough. + return Result{Outcome: OutcomePending, Reason: ReasonPending} +} diff --git a/internal/telemetry/tracecontext/envelope_test.go b/internal/telemetry/tracecontext/envelope_test.go new file mode 100644 index 0000000000..df3b366ca7 --- /dev/null +++ b/internal/telemetry/tracecontext/envelope_test.go @@ -0,0 +1,869 @@ +package tracecontext + +import ( + "bytes" + "crypto/ed25519" + "encoding/base64" + "encoding/binary" + "encoding/hex" + "fmt" + "reflect" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.opentelemetry.io/otel/trace" +) + +// The tests in this file cover ADR 0154: exact signed-byte +// fixtures, tamper-every-field, cross-binding replay, strict parser limits, +// duplicate/oversized/zero-ID rejection, retained keys, and pending markers +// granting nothing. Golden hex constants pin the v1 wire format. + +// goldenKey is a deterministic Ed25519 key for reproducible fixtures. +func goldenKey() ed25519.PrivateKey { + seed := make([]byte, ed25519.SeedSize) + for i := range seed { + seed[i] = byte(i + 1) + } + return ed25519.NewKeyFromSeed(seed) +} + +func goldenKeys(t *testing.T) (ed25519.PrivateKey, map[[8]byte]ed25519.PublicKey) { + t.Helper() + key := goldenKey() + pub := key.Public().(ed25519.PublicKey) + return key, map[[8]byte]ed25519.PublicKey{KeyID(pub): pub} +} + +func hexTrace(s string) trace.TraceID { + tid, err := trace.TraceIDFromHex(s) + if err != nil { + panic(err) + } + return tid +} + +func hexSpan(s string) trace.SpanID { + sid, err := trace.SpanIDFromHex(s) + if err != nil { + panic(err) + } + return sid +} + +// goldenIdentity matches the identity bound into every golden envelope. +func goldenIdentity() Identity { + return Identity{ + Installation: [16]byte{0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, + 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf}, + Instance: "https://github.com", + Container: 274390431, + Kind: KindWorkItem, + Entity: 2468913570, + } +} + +// goldenEnvelope builds the fixture envelope for a domain and provenance +// kind. Scenario envelopes keep TraceID == ScenarioTraceID per the +// provenance consistency rule. +func goldenEnvelope(domain Domain, prov ProvenanceKind) *Envelope { + id := goldenIdentity() + env := &Envelope{ + Domain: domain, + Installation: id.Installation, + Instance: id.Instance, + Container: id.Container, + Kind: id.Kind, + TraceID: hexTrace("4f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6d"), + ParentSpanID: hexSpan("a1b2c3d4e5f60718"), + Nonce: [16]byte{0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, + 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f}, + } + if domain == DomainBound { + env.Entity = id.Entity + } + switch prov { + case ProvenanceSourceLink: + env.Provenance = Provenance{ + Kind: ProvenanceSourceLink, + SourceTraceID: hexTrace("5c4b3a29180f6e5d4c3b2a1908f7e6d5"), + SourceSpanID: hexSpan("0f1e2d3c4b5a6978"), + } + case ProvenanceScenario: + env.Provenance = Provenance{ + Kind: ProvenanceScenario, + ScenarioTraceID: env.TraceID, // consistency: inherits scenario trace + ScenarioInvocationID: [16]byte{0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, + 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff}, + } + } + return env +} + +// signedGolden returns precomputed signed bytes so parser/admission tests +// do not depend on Sign or Marshal succeeding during fixture setup. +func signedGolden(t *testing.T, domain Domain, prov ProvenanceKind) ([]byte, map[[8]byte]ed25519.PublicKey) { + t.Helper() + _, keys := goldenKeys(t) + vectors := map[Domain]map[ProvenanceKind]string{ + DomainBound: {ProvenanceNone: goldenBoundNoneHex, ProvenanceSourceLink: goldenBoundSourceLinkHex, ProvenanceScenario: goldenBoundScenarioHex}, + DomainPending: {ProvenanceNone: goldenPendingNoneHex, ProvenanceSourceLink: goldenPendingSourceLinkHex, ProvenanceScenario: goldenPendingScenarioHex}, + } + wire := vectors[domain][prov] + require.NotEmpty(t, wire) + return mustHex(t, wire), keys +} + +// specLayout mirrors the v1 wire layout from +// docs/normative/trace-context/v1/README.md so tests locate fields independently of +// the implementation, pinning the format from the spec side. +type specLayout struct { + instance, container, kind, entity int + trace, span, prov, provFields int + nonce, sig, total int +} + +func layout(domain Domain, prov ProvenanceKind, instanceLen int) specLayout { + var o specLayout + o.instance = 32 + o.container = o.instance + instanceLen + o.kind = o.container + 8 + o.entity = o.kind + 1 + if domain == DomainBound { + o.trace = o.entity + 8 + } else { + o.trace = o.entity // pending markers omit the entity bytes + } + o.span = o.trace + 16 + o.prov = o.span + 8 + o.provFields = o.prov + 1 + fields := 0 + switch prov { + case ProvenanceSourceLink: + fields = 24 + case ProvenanceScenario: + fields = 32 + } + o.nonce = o.provFields + fields + o.sig = o.nonce + 16 + o.total = o.sig + 64 + return o +} + +// resign re-signs mutated wire bytes so field-validity failures are not +// masked by signature failures: the parser must reject the field, not the +// signature. +func resign(t *testing.T, key ed25519.PrivateKey, raw []byte) []byte { + t.Helper() + require.Greater(t, len(raw), 64) + out := bytes.Clone(raw) + sig := ed25519.Sign(key, out[:len(out)-64]) + copy(out[len(out)-64:], sig) + return out +} + +func mustHex(t *testing.T, s string) []byte { + t.Helper() + b, err := hex.DecodeString(s) + require.NoError(t, err) + return b +} + +// Golden hex constants: the v1 conformance vectors. While v1 is provisional +// (README Compatibility), a deliberate wire-format change updates the README +// and these vectors together. Independently reconstructed +// with Python struct + cryptography Ed25519 during corrective review; the +// pending provenance vectors were first generated by that independent code. +var ( + goldenBoundNoneHex = "46535443010165b60673d6ed884ba0a1a2a3a4a5a6a7a8a9aaabacadaeaf001268747470733a2f2f6769746875622e636f6d00000000105add9f01000000009328a1a24f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6da1b2c3d4e5f6071800101112131415161718191a1b1c1d1e1fe337c39001d56da6ba8862e01893f5d63d41fee3cab1d35f925aacd2e4a7165b30cf38403fcd2f809f50df67a62ebe705eb25a16e028df6345d8924b01bd2c0e" + goldenBoundSourceLinkHex = "46535443010165b60673d6ed884ba0a1a2a3a4a5a6a7a8a9aaabacadaeaf001268747470733a2f2f6769746875622e636f6d00000000105add9f01000000009328a1a24f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6da1b2c3d4e5f60718015c4b3a29180f6e5d4c3b2a1908f7e6d50f1e2d3c4b5a6978101112131415161718191a1b1c1d1e1f96451fbecf439bee72e636691b09f313df7b94bb017a63b7cdc0ea57775f3ca5a240c6f592f59bf33a25f463049e389345cf4d1354bd929198dc18803163a604" + goldenBoundScenarioHex = "46535443010165b60673d6ed884ba0a1a2a3a4a5a6a7a8a9aaabacadaeaf001268747470733a2f2f6769746875622e636f6d00000000105add9f01000000009328a1a24f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6da1b2c3d4e5f60718024f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6df0f1f2f3f4f5f6f7f8f9fafbfcfdfeff101112131415161718191a1b1c1d1e1fa59c45c20117895374e9ea5631083900ea081913ec21aa7d4604a23a75f2dd0f2ace2c01dda59c399f24bbdb409bc64081d898ba1ee73c292ca3d716e0860001" + goldenPendingNoneHex = "46535443010265b60673d6ed884ba0a1a2a3a4a5a6a7a8a9aaabacadaeaf001268747470733a2f2f6769746875622e636f6d00000000105add9f014f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6da1b2c3d4e5f6071800101112131415161718191a1b1c1d1e1f51fcd462f5bf6dd75e28f906fe0f4cf72d2c9fe9d3f66f95e1e650588442fdf2167890b17bc34775e27a74cc58ec22603df915fbe5396239d3f2b1ebf965c703" + goldenPendingSourceLinkHex = "46535443010265b60673d6ed884ba0a1a2a3a4a5a6a7a8a9aaabacadaeaf001268747470733a2f2f6769746875622e636f6d00000000105add9f014f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6da1b2c3d4e5f60718015c4b3a29180f6e5d4c3b2a1908f7e6d50f1e2d3c4b5a6978101112131415161718191a1b1c1d1e1fa35099c98587f7dc2ba94734f2afe542cd1581bcd0dc9320e436de8ca57c0a3dcd61bcdfad9a933e3baec5a324659286eb164aa745c3f62079ea466513aa6703" + goldenPendingScenarioHex = "46535443010265b60673d6ed884ba0a1a2a3a4a5a6a7a8a9aaabacadaeaf001268747470733a2f2f6769746875622e636f6d00000000105add9f014f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6da1b2c3d4e5f60718024f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6df0f1f2f3f4f5f6f7f8f9fafbfcfdfeff101112131415161718191a1b1c1d1e1f0bb31c983e5206e3592f6e437117cbdc06a6991213ee65c57ff3cff4cdd35a26f571fa350d2046117c695892521bf393df228718b96cb5fdbb65c244b3de820c" +) + +func TestGoldenVectors(t *testing.T) { + cases := []struct { + name string + dom Domain + prov ProvenanceKind + hex *string + }{ + {"bound none", DomainBound, ProvenanceNone, &goldenBoundNoneHex}, + {"bound source link", DomainBound, ProvenanceSourceLink, &goldenBoundSourceLinkHex}, + {"bound scenario", DomainBound, ProvenanceScenario, &goldenBoundScenarioHex}, + {"pending none", DomainPending, ProvenanceNone, &goldenPendingNoneHex}, + {"pending source link", DomainPending, ProvenanceSourceLink, &goldenPendingSourceLinkHex}, + {"pending scenario", DomainPending, ProvenanceScenario, &goldenPendingScenarioHex}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + _, keys := goldenKeys(t) + env := goldenEnvelope(tc.dom, tc.prov) + require.NoError(t, env.Sign(goldenKey())) + raw := env.Marshal() + want := mustHex(t, *tc.hex) + if !bytes.Equal(raw, want) { + t.Fatalf("golden wire bytes differ from the v1 conformance vector:\n got %x\nwant %x", raw, want) + } + + // Layout is exactly the spec's size. + assert.Equal(t, layout(tc.dom, tc.prov, len(goldenIdentity().Instance)).total, len(raw)) + + // Parse round-trips byte-for-byte. + parsed, err := Parse(want) + require.NoError(t, err) + assert.Equal(t, env, parsed) + + // Admission admits exactly the bound context. + res := Admit(goldenIdentity(), keys, want) + if tc.dom == DomainBound { + assert.Equal(t, OutcomeAdmitted, res.Outcome, "reason: %s", res.Reason) + assert.Equal(t, env.TraceID, res.TraceID) + assert.Equal(t, env.ParentSpanID, res.ParentSpanID) + assert.Equal(t, env.Provenance, res.Provenance) + } else { + assert.Equal(t, Result{Outcome: OutcomePending, Reason: ReasonPending}, res) + } + }) + } +} + +// TestTamperEverySignedByte flips each byte of a maximal envelope — header, +// binding, context, provenance, nonce, and signature — and requires +// rejection every time. +func TestTamperEverySignedByte(t *testing.T) { + raw, keys := signedGolden(t, DomainBound, ProvenanceScenario) + for i := 0; i < len(raw); i++ { + tampered := bytes.Clone(raw) + tampered[i] ^= 0x01 + res := Admit(goldenIdentity(), keys, tampered) + assert.NotEqual(t, OutcomeAdmitted, res.Outcome, "flipping byte %d must not admit", i) + } +} + +// TestCrossBindingReplay signs for one identity and admits against another: +// every binding component mismatch must reject a copied envelope. +func TestCrossBindingReplay(t *testing.T) { + raw, keys := signedGolden(t, DomainBound, ProvenanceNone) + + mutations := map[string]func(*Identity){ + "installation": func(i *Identity) { i.Installation = [16]byte{0xbb} }, + "instance": func(i *Identity) { i.Instance = "https://ghe.example.com" }, + "container": func(i *Identity) { i.Container++ }, + "kind": func(i *Identity) { i.Kind = KindChangeProposal }, + "entity": func(i *Identity) { i.Entity++ }, + } + for name, mutate := range mutations { + t.Run(name, func(t *testing.T) { + expected := goldenIdentity() + mutate(&expected) + res := Admit(expected, keys, raw) + assert.Equal(t, OutcomeFallback, res.Outcome) + assert.Equal(t, ReasonBindingMismatch, res.Reason) + }) + } +} + +func TestResult_ZeroValueFallsBack(t *testing.T) { + t.Parallel() + var result Result + assert.Equal(t, OutcomeFallback, result.Outcome) + assert.False(t, result.TraceID.IsValid()) + assert.False(t, result.ParentSpanID.IsValid()) + assert.Equal(t, Provenance{}, result.Provenance) +} + +func TestAdmit_Absent(t *testing.T) { + _, keys := goldenKeys(t) + res := Admit(goldenIdentity(), keys) + assert.Equal(t, OutcomeFallback, res.Outcome) + assert.Equal(t, ReasonAbsent, res.Reason) +} + +func TestAdmit_UnknownKey(t *testing.T) { + raw, _ := signedGolden(t, DomainBound, ProvenanceNone) + + // A genuinely different key: goldenKey is deterministic, so derive + // from a distinct seed. + other := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{7}, ed25519.SeedSize)) + otherPub := other.Public().(ed25519.PublicKey) + res := Admit(goldenIdentity(), map[[8]byte]ed25519.PublicKey{KeyID(otherPub): otherPub}, raw) + assert.Equal(t, OutcomeFallback, res.Outcome) + assert.Equal(t, ReasonUnknownKey, res.Reason) +} + +func TestAdmit_MalformedVerificationKeys(t *testing.T) { + raw := mustHex(t, goldenBoundSourceLinkHex) + selector := [8]byte{0x65, 0xb6, 0x06, 0x73, 0xd6, 0xed, 0x88, 0x4b} + for _, key := range []ed25519.PublicKey{nil, {}, make([]byte, 31), make([]byte, 33)} { + var result Result + assert.NotPanics(t, func() { + result = Admit(goldenIdentity(), map[[8]byte]ed25519.PublicKey{selector: key}, raw) + }, "key length %d", len(key)) + assert.Equal(t, Result{Outcome: OutcomeFallback, Reason: ReasonUnknownKey}, result) + } +} + +func TestCanonicalInstanceAtEveryBoundary(t *testing.T) { + for _, instance := range []string{ + "https://github.com:443", "https://github.com:0443", "http://github.com:80", + "https://github.com:", "https://[::1]:", "https://github.com:08443", + "https://[::1]:08443", "https://github.com:000", + "https://bücher.example", + "not-a-url", "https://GitHub.com", "HTTPS://github.com", "https://github.com/", + "https://gitlab.example.com/gitlab/", "https://github.com?", "https://github.com#", + "https://gitlab.example.com/café", "https://gitlab.example.com/%00", "https://gitlab.example.com/%ff", + "https://user@github.com", "ftp://github.com", "https://:443", + "https://" + strings.Repeat("a", 246), "https://\xff.example", + } { + t.Run(instance, func(t *testing.T) { + id := goldenIdentity() + id.Instance = instance + assert.False(t, id.Resolved()) + fb, ok := DeriveFallback(id) + assert.False(t, ok) + assert.Equal(t, Fallback{}, fb) + + env := goldenEnvelope(DomainBound, ProvenanceNone) + env.Instance = instance + assert.Error(t, env.Sign(goldenKey())) + + // Replace only the instance in precomputed wire bytes, then sign + // directly so Sign validation cannot mask Parse/Admit failures. + raw := mustHex(t, goldenBoundNoneHex) + mutated := append(bytes.Clone(raw[:32]), []byte(instance)...) + mutated = append(mutated, raw[50:]...) + binary.BigEndian.PutUint16(mutated[30:32], uint16(len(instance))) + mutated = resign(t, goldenKey(), mutated) + _, err := Parse(mutated) + assert.Error(t, err) + _, keys := goldenKeys(t) + // The unresolved identity dominates, but the same malformed + // carrier under a resolved identity still reports malformed. + assert.Equal(t, Result{Outcome: OutcomeFallback, Reason: ReasonUnresolved}, Admit(id, keys, mutated)) + assert.Equal(t, Result{Outcome: OutcomeFallback, Reason: ReasonMalformed}, Admit(goldenIdentity(), keys, mutated)) + }) + } +} + +func TestAdmit_NormalizedPorts(t *testing.T) { + t.Parallel() + key, keys := goldenKeys(t) + for _, tc := range []struct{ raw, canonical string }{ + {"https://GitHub.com:443/", "https://github.com"}, + {"https://github.com:", "https://github.com"}, + {"https://[::1]:", "https://[::1]"}, + {"https://github.com:08443", "https://github.com:8443"}, + {"https://[::1]:08443", "https://[::1]:8443"}, + {"https://github.com:000", "https://github.com:0"}, + } { + t.Run(tc.raw, func(t *testing.T) { + env := goldenEnvelope(DomainBound, ProvenanceNone) + env.Instance = tc.canonical + require.NoError(t, env.Sign(key)) + id := goldenIdentity() + id.Instance = tc.canonical + wantFallback, ok := DeriveFallback(id) + require.True(t, ok) + var err error + id.Instance, err = NormalizeInstance(tc.raw) + require.NoError(t, err) + fb, ok := DeriveFallback(id) + require.True(t, ok) + assert.Equal(t, wantFallback, fb) + assert.Equal(t, OutcomeAdmitted, Admit(id, keys, env.Marshal()).Outcome) + }) + } +} + +func TestEnvelope_DeploymentPrefixBinding(t *testing.T) { + t.Parallel() + key, keys := goldenKeys(t) + for _, domain := range []Domain{DomainBound, DomainPending} { + raw, _ := signedGolden(t, domain, ProvenanceNone) + instance := "https://gitlab.example.com/gitlab" + // Build the prefixed fixture independently of production validation. + raw = append(append(bytes.Clone(raw[:32]), []byte(instance)...), raw[50:]...) + binary.BigEndian.PutUint16(raw[30:32], uint16(len(instance))) + raw = resign(t, key, raw) + env, err := Parse(raw) + require.NoError(t, err) + assert.Equal(t, instance, env.Instance) + require.NoError(t, env.Sign(key)) + assert.Equal(t, raw, env.Marshal()) + + id := goldenIdentity() + id.Instance = instance + want := OutcomeAdmitted + if domain == DomainPending { + want = OutcomePending + } + assert.Equal(t, want, Admit(id, keys, raw).Outcome) + for _, other := range []string{"https://gitlab.example.com", "https://gitlab.example.com/other", "https://gitlab.example.com/GitLab"} { + id.Instance = other + assert.Equal(t, Result{Outcome: OutcomeFallback, Reason: ReasonBindingMismatch}, Admit(id, keys, raw)) + } + } +} + +// TestAdmit_RetainedKey covers rotation: metadata signed by an older +// retained key stays verifiable while the active key signs new metadata. +func TestAdmit_RetainedKey(t *testing.T) { + oldKey, _ := goldenKeys(t) + env := goldenEnvelope(DomainBound, ProvenanceNone) + require.NoError(t, env.Sign(oldKey)) + raw := env.Marshal() + + // Rotation: generate the new active key, keep the old public key. + newSeed := make([]byte, ed25519.SeedSize) + for i := range newSeed { + newSeed[i] = byte(200 - i) + } + newKey := ed25519.NewKeyFromSeed(newSeed) + newPub := newKey.Public().(ed25519.PublicKey) + oldPub := oldKey.Public().(ed25519.PublicKey) + keys := map[[8]byte]ed25519.PublicKey{KeyID(newPub): newPub, KeyID(oldPub): oldPub} + + res := Admit(goldenIdentity(), keys, raw) + assert.Equal(t, OutcomeAdmitted, res.Outcome, "old metadata must verify with a retained key") +} + +// TestAdmit_KeyIDDerivedFromPublicKey pins the selector rule: the key ID is +// the first 8 bytes of SHA-256(public key). +func TestAdmit_KeyIDDerivedFromPublicKey(t *testing.T) { + key, _ := goldenKeys(t) + pub := key.Public().(ed25519.PublicKey) + + env := goldenEnvelope(DomainBound, ProvenanceNone) + require.NoError(t, env.Sign(key)) + raw := env.Marshal() + + // Same public key registered under a wrong key ID: the envelope's + // selector must not resolve, proving lookup uses the derived ID. + wrong := map[[8]byte]ed25519.PublicKey{[8]byte{0x99}: pub} + res := Admit(goldenIdentity(), wrong, raw) + assert.Equal(t, OutcomeFallback, res.Outcome) + assert.Equal(t, ReasonUnknownKey, res.Reason) +} + +func TestAdmit_DuplicateCarriers(t *testing.T) { + raw, keys := signedGolden(t, DomainBound, ProvenanceNone) + + res := Admit(goldenIdentity(), keys, raw, bytes.Clone(raw)) + assert.Equal(t, OutcomeAdmitted, res.Outcome, "identical duplicates are idempotent publication") + + // A differing carrier (different nonce) must conflict, never + // first-match. + key, _ := goldenKeys(t) + otherEnv := goldenEnvelope(DomainBound, ProvenanceNone) + otherEnv.Nonce[0] ^= 0xff + require.NoError(t, otherEnv.Sign(key)) + res = Admit(goldenIdentity(), keys, raw, otherEnv.Marshal()) + assert.Equal(t, OutcomeFallback, res.Outcome) + assert.Equal(t, ReasonConflictingCarrier, res.Reason, "conflicting carriers must reject, never first-match") +} + +// TestAdmit_AppendedJunkForcesFallback documents the accepted +// denial-of-continuity trade-off: an editor can suppress continuity by +// appending an unauthenticated carrier, but cannot inject or select one. +func TestAdmit_AppendedJunkForcesFallback(t *testing.T) { + t.Parallel() + raw, keys := signedGolden(t, DomainBound, ProvenanceNone) + res := Admit(goldenIdentity(), keys, raw, []byte("not-an-envelope")) + assert.Equal(t, Result{Outcome: OutcomeFallback, Reason: ReasonMalformed}, res) +} + +func TestAdmit_Oversized(t *testing.T) { + _, keys := goldenKeys(t) + + // Pad a valid envelope beyond the maximum legal size. + padded := make([]byte, MaxEnvelopeLen+1) + res := Admit(goldenIdentity(), keys, padded) + assert.Equal(t, OutcomeFallback, res.Outcome) + assert.Equal(t, ReasonOversized, res.Reason) + + big := make([]byte, 10*1024) + res = Admit(goldenIdentity(), keys, big) + assert.Equal(t, OutcomeFallback, res.Outcome) + assert.Equal(t, ReasonOversized, res.Reason) +} + +// TestParse_ZeroAndInvalidFields mutates individual fields in otherwise +// valid, correctly signed envelopes: the parser must reject the field +// itself, not merely the signature. +func TestParse_ZeroAndInvalidFields(t *testing.T) { + key, keys := goldenKeys(t) + inst := len(goldenIdentity().Instance) + + cases := []struct { + name string + domain Domain + prov ProvenanceKind + mutate func(raw []byte) []byte + }{ + {"zero installation", DomainBound, ProvenanceNone, func(r []byte) []byte { zeroAt(r, 14, 16); return r }}, + {"zero container", DomainBound, ProvenanceNone, func(r []byte) []byte { zeroAt(r, layout(DomainBound, ProvenanceNone, inst).container, 8); return r }}, + {"zero entity", DomainBound, ProvenanceNone, func(r []byte) []byte { zeroAt(r, layout(DomainBound, ProvenanceNone, inst).entity, 8); return r }}, + {"zero trace", DomainBound, ProvenanceNone, func(r []byte) []byte { zeroAt(r, layout(DomainBound, ProvenanceNone, inst).trace, 16); return r }}, + {"zero span", DomainBound, ProvenanceNone, func(r []byte) []byte { zeroAt(r, layout(DomainBound, ProvenanceNone, inst).span, 8); return r }}, + {"zero nonce", DomainBound, ProvenanceNone, func(r []byte) []byte { zeroAt(r, layout(DomainBound, ProvenanceNone, inst).nonce, 16); return r }}, + {"invalid kind", DomainBound, ProvenanceNone, func(r []byte) []byte { r[layout(DomainBound, ProvenanceNone, inst).kind] = 0x7f; return r }}, + {"invalid provenance kind", DomainBound, ProvenanceNone, func(r []byte) []byte { r[layout(DomainBound, ProvenanceNone, inst).prov] = 0x03; return r }}, + {"zero scenario trace", DomainBound, ProvenanceScenario, func(r []byte) []byte { + zeroAt(r, layout(DomainBound, ProvenanceScenario, inst).provFields, 16) + return r + }}, + {"zero invocation id", DomainBound, ProvenanceScenario, func(r []byte) []byte { + zeroAt(r, layout(DomainBound, ProvenanceScenario, inst).provFields+16, 16) + return r + }}, + {"zero source trace", DomainBound, ProvenanceSourceLink, func(r []byte) []byte { + zeroAt(r, layout(DomainBound, ProvenanceSourceLink, inst).provFields, 16) + return r + }}, + {"unknown version", DomainBound, ProvenanceNone, func(r []byte) []byte { r[4] = 0x02; return r }}, + {"unknown domain", DomainBound, ProvenanceNone, func(r []byte) []byte { r[5] = 0x03; return r }}, + {"bad magic", DomainBound, ProvenanceNone, func(r []byte) []byte { r[0] = 'X'; return r }}, + {"trailing byte", DomainBound, ProvenanceNone, func(r []byte) []byte { return append(r[:len(r):len(r)], 0) }}, + {"truncated", DomainBound, ProvenanceNone, func(r []byte) []byte { return r[:len(r)-1] }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + raw, _ := signedGolden(t, tc.domain, tc.prov) + raw = tc.mutate(raw) + raw = resign(t, key, raw) + + _, err := Parse(raw) + require.Error(t, err, "parser must reject invalid field values") + + res := Admit(goldenIdentity(), keys, raw) + assert.Equal(t, OutcomeFallback, res.Outcome) + if tc.name == "unknown version" { + assert.Equal(t, ReasonUnknownVersion, res.Reason) + } + }) + } +} + +func zeroAt(b []byte, off, n int) { + for i := off; i < off+n; i++ { + b[i] = 0 + } +} + +// TestAdmit_PlainTraceparentIsNotAnEnvelope is V04: a plain W3C +// traceparent never substitutes for a signed envelope. +func TestAdmit_PlainTraceparentIsNotAnEnvelope(t *testing.T) { + _, keys := goldenKeys(t) + res := Admit(goldenIdentity(), keys, []byte("00-4f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6d-a1b2c3d4e5f60718-01")) + assert.Equal(t, OutcomeFallback, res.Outcome) + assert.Equal(t, ReasonMalformed, res.Reason) + assert.Equal(t, trace.TraceID{}, res.TraceID, "no unverified trace may be adopted") + assert.Equal(t, Provenance{}, res.Provenance, "no unverified link may be adopted") +} + +// TestAdmit_PendingGrantsNothing is V04: a verified pending marker matching +// the expected scope yields the pending outcome with no context and no +// links; a scope mismatch is a binding mismatch. +func TestAdmit_PendingGrantsNothing(t *testing.T) { + raw, keys := signedGolden(t, DomainPending, ProvenanceScenario) + + res := Admit(goldenIdentity(), keys, raw) + assert.Equal(t, OutcomePending, res.Outcome) + assert.Equal(t, ReasonPending, res.Reason) + assert.Equal(t, trace.TraceID{}, res.TraceID, "pending must not grant context") + assert.Equal(t, trace.SpanID{}, res.ParentSpanID, "pending must not grant a parent") + assert.Equal(t, Provenance{}, res.Provenance, "pending must not grant links or scenario membership") + + expected := goldenIdentity() + expected.Container++ + res = Admit(expected, keys, raw) + assert.Equal(t, OutcomeFallback, res.Outcome) + assert.Equal(t, ReasonBindingMismatch, res.Reason) +} + +// TestAdmit_PendingRequiresResolvedIdentity pins the README rule: an +// unresolved expected identity never earns the pending outcome; the launch +// must postpone with an explicit fallback reason instead of waiting out +// the pending window on a guessed binding. +func TestAdmit_PendingRequiresResolvedIdentity(t *testing.T) { + t.Parallel() + raw, keys := signedGolden(t, DomainPending, ProvenanceNone) + unresolved := goldenIdentity() + unresolved.Entity = 0 + res := Admit(unresolved, keys, raw) + assert.Equal(t, Result{Outcome: OutcomeFallback, Reason: ReasonUnresolved}, res) +} + +// TestAdmit_UnresolvedIdentityAlwaysReportsUnresolved pins the README +// contract: an unresolved identity must postpone (FR-002) whatever carrier +// is present, so callers never mistake a carrier rejection for the cause. +func TestAdmit_UnresolvedIdentityAlwaysReportsUnresolved(t *testing.T) { + t.Parallel() + bound, keys := signedGolden(t, DomainBound, ProvenanceNone) + pending, _ := signedGolden(t, DomainPending, ProvenanceNone) + + components := []struct { + name string + mutate func(*Identity) + }{ + {"instance", func(id *Identity) { id.Instance = "" }}, + {"container", func(id *Identity) { id.Container = 0 }}, + {"kind", func(id *Identity) { id.Kind = 0 }}, + {"entity", func(id *Identity) { id.Entity = 0 }}, + } + carriers := []struct { + name string + raw [][]byte + }{ + {"absent", nil}, + {"malformed", [][]byte{[]byte("not-an-envelope")}}, + {"bound", [][]byte{bound}}, + {"pending", [][]byte{pending}}, + } + for _, c := range components { + for _, carrier := range carriers { + t.Run(c.name+"/"+carrier.name, func(t *testing.T) { + t.Parallel() + expected := goldenIdentity() + c.mutate(&expected) + res := Admit(expected, keys, carrier.raw...) + assert.Equal(t, Result{Outcome: OutcomeFallback, Reason: ReasonUnresolved}, res) + }) + } + } +} + +// TestAdmit_PendingMarkerIsContainerScoped documents that a pending marker +// deliberately carries no entity binding: one replayed onto another entity +// in the same container still grants nothing beyond a bounded pending +// wait, which callers must cap by a window from trusted creation metadata. +func TestAdmit_PendingMarkerIsContainerScoped(t *testing.T) { + t.Parallel() + raw, keys := signedGolden(t, DomainPending, ProvenanceNone) + replayed := goldenIdentity() + replayed.Entity++ + res := Admit(replayed, keys, raw) + assert.Equal(t, Result{Outcome: OutcomePending, Reason: ReasonPending}, res) +} + +// TestAdmit_BoundEnvelopeWithStalePendingMarker pins the fail-closed rule: +// a publisher that leaves the pending marker beside the bound envelope +// produces conflicting carriers, and admission rejects the conflict rather +// than picking either carrier. +func TestAdmit_BoundEnvelopeWithStalePendingMarker(t *testing.T) { + t.Parallel() + bound, keys := signedGolden(t, DomainBound, ProvenanceNone) + pending, _ := signedGolden(t, DomainPending, ProvenanceNone) + res := Admit(goldenIdentity(), keys, bound, pending) + assert.Equal(t, Result{Outcome: OutcomeFallback, Reason: ReasonConflictingCarrier}, res) +} + +// TestAdmit_ProvenanceConsistency enforces the D02 rules: an ordinary +// source link keeps the destination's own trace; scenario provenance +// inherits the scenario trace. +func TestAdmit_ProvenanceConsistency(t *testing.T) { + key, keys := goldenKeys(t) + + // Source link whose destination trace equals the source trace: the + // traces would merge, which ordinary provenance forbids. + raw := mustHex(t, goldenBoundSourceLinkHex) + lay := layout(DomainBound, ProvenanceSourceLink, len(goldenIdentity().Instance)) + copy(raw[lay.trace:lay.trace+16], raw[lay.provFields:lay.provFields+16]) + res := Admit(goldenIdentity(), keys, resign(t, key, raw)) + assert.Equal(t, OutcomeFallback, res.Outcome) + assert.Equal(t, ReasonProvenance, res.Reason) + + // Scenario provenance whose trace differs from the scenario trace. + raw = mustHex(t, goldenBoundScenarioHex) + lay = layout(DomainBound, ProvenanceScenario, len(goldenIdentity().Instance)) + raw[lay.trace] ^= 0x01 + res = Admit(goldenIdentity(), keys, resign(t, key, raw)) + assert.Equal(t, OutcomeFallback, res.Outcome) + assert.Equal(t, ReasonProvenance, res.Reason) +} + +// TestAdmit_FallbackAdoptsNothing asserts every non-admitted result keeps +// zero context and provenance (FR-005). +func TestAdmit_FallbackAdoptsNothing(t *testing.T) { + raw, keys := signedGolden(t, DomainBound, ProvenanceSourceLink) + + tampered := bytes.Clone(raw) + tampered[len(tampered)-1] ^= 0x01 // break the signature only + res := Admit(goldenIdentity(), keys, tampered) + assert.Equal(t, OutcomeFallback, res.Outcome) + assert.Equal(t, ReasonBadSignature, res.Reason) + assert.Equal(t, trace.TraceID{}, res.TraceID) + assert.Equal(t, trace.SpanID{}, res.ParentSpanID) + assert.Equal(t, Provenance{}, res.Provenance) +} + +// TestResultCarriesNoSamplingStateOrBaggage is FR-007/V02: the admission +// result structurally cannot carry sampling flags, tracestate, or baggage. +func TestResultCarriesNoSamplingStateOrBaggage(t *testing.T) { + rt := reflect.TypeOf(Result{}) + var fields []string + for i := 0; i < rt.NumField(); i++ { + fields = append(fields, rt.Field(i).Name) + } + assert.ElementsMatch(t, + []string{"Outcome", "Reason", "TraceID", "ParentSpanID", "Provenance"}, + fields) +} + +// TestSign_RejectsInvalidEnvelopes keeps malformed envelopes from ever +// being signed: signing validates exactly what the parser validates. +func TestSign_RejectsInvalidEnvelopes(t *testing.T) { + key, _ := goldenKeys(t) + inst := goldenIdentity().Instance + + cases := map[string]func(*Envelope){"zero installation": func(e *Envelope) { e.Installation = [16]byte{} }, + "empty instance": func(e *Envelope) { e.Instance = "" }, + "nul in instance": func(e *Envelope) { e.Instance = "https://git\x00hub.com" }, + "instance too long": func(e *Envelope) { e.Instance = "https://" + strings.Repeat("a", 300) + ".com" }, + "zero container": func(e *Envelope) { e.Container = 0 }, + "zero entity": func(e *Envelope) { e.Entity = 0 }, + "zero trace": func(e *Envelope) { e.TraceID = trace.TraceID{} }, + "zero span": func(e *Envelope) { e.ParentSpanID = trace.SpanID{} }, + "zero nonce": func(e *Envelope) { e.Nonce = [16]byte{} }, + "invalid kind": func(e *Envelope) { e.Kind = EntityKind(0x7f) }, + "invalid domain": func(e *Envelope) { e.Domain = Domain(0x03) }, + "invalid provenance": func(e *Envelope) { e.Provenance = Provenance{Kind: ProvenanceKind(0x03)} }, + "zero source span": func(e *Envelope) { + e.Provenance = Provenance{Kind: ProvenanceSourceLink, SourceTraceID: hexTrace("4f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6d")} + }, + "zero invocation id": func(e *Envelope) { + e.Provenance = Provenance{Kind: ProvenanceScenario, ScenarioTraceID: hexTrace("4f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6d")} + }, + "pending with entity": func(e *Envelope) { + e.Domain = DomainPending + e.Entity = 1 + }, + "bound scenario trace mismatch": func(e *Envelope) { + e.Provenance = Provenance{ + Kind: ProvenanceScenario, + ScenarioTraceID: hexTrace("11111111111111111111111111111111"), + ScenarioInvocationID: [16]byte{1}, + } + }, + } + for name, mutate := range cases { + t.Run(name, func(t *testing.T) { + env := goldenEnvelope(DomainBound, ProvenanceNone) + env.Instance = inst + mutate(env) + err := env.Sign(key) + assert.Error(t, err, "Sign must refuse to sign an invalid envelope") + }) + } +} + +func TestDecodeCarrier(t *testing.T) { + raw, _ := signedGolden(t, DomainBound, ProvenanceNone) + carrier := base64.StdEncoding.EncodeToString(raw) + + got, err := DecodeCarrier(carrier) + require.NoError(t, err) + assert.Equal(t, raw, got) + + _, err = DecodeCarrier("ab\r\ncd") // line break inside + assert.Error(t, err, "line breaks must be rejected") + + _, err = DecodeCarrier(carrier[:len(carrier)-2]) // broken padding + assert.Error(t, err) + + _, err = DecodeCarrier(carrier + "!!!") + assert.Error(t, err, "invalid alphabet must be rejected") + + _, err = DecodeCarrier(strings.Repeat("A", MaxCarrierLen+1)) + assert.Error(t, err, "carriers longer than the maximum must be rejected") +} + +func TestKeyID_Derivation(t *testing.T) { + key := goldenKey() + pub := key.Public().(ed25519.PublicKey) + id := KeyID(pub) + assert.NotEqual(t, [8]byte{}, id, "key ID must be derived, not zero") + + other := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{7}, 32)) + otherPub := other.Public().(ed25519.PublicKey) + assert.NotEqual(t, id, KeyID(otherPub), "distinct keys must have distinct IDs") +} + +// TestSign_RejectsWrongKeySize guards the trust boundary between caller +// and host-side signing: only a well-formed Ed25519 private key may sign. +func TestSign_RejectsWrongKeySize(t *testing.T) { + env := goldenEnvelope(DomainBound, ProvenanceNone) + err := env.Sign(ed25519.PrivateKey(bytes.Repeat([]byte{1}, 10))) + assert.Error(t, err, "Sign must reject a mis-sized private key") +} + +// Long instances let truncations reach every variable-field boundary +// beyond the minimum-length check, including both provenance layouts. +func TestParse_Truncations(t *testing.T) { + for _, domain := range []Domain{DomainBound, DomainPending} { + for _, provenance := range []ProvenanceKind{ProvenanceNone, ProvenanceSourceLink, ProvenanceScenario} { + for _, instance := range []string{goldenIdentity().Instance, "https://" + strings.Repeat("a.", 122) + "a"} { + t.Run(fmt.Sprintf("domain=%d/provenance=%d/instance=%d", domain, provenance, len(instance)), func(t *testing.T) { + raw, keys := signedGolden(t, domain, provenance) + // Change the precomputed fixture's instance and re-sign independently. + extended := append(bytes.Clone(raw[:32]), []byte(instance)...) + extended = append(extended, raw[32+len(goldenIdentity().Instance):]...) + binary.BigEndian.PutUint16(extended[30:32], uint16(len(instance))) + raw = resign(t, goldenKey(), extended) + + parsed, err := Parse(raw) + require.NoError(t, err, "complete envelope must parse") + assert.Equal(t, raw, parsed.Marshal()) + expected := goldenIdentity() + expected.Instance = instance + outcome := OutcomeAdmitted + if domain == DomainPending { + outcome = OutcomePending + } + require.Equal(t, outcome, Admit(expected, keys, raw).Outcome) + + for n := 0; n < len(raw); n++ { + parsed, err := Parse(raw[:n]) + require.ErrorIs(t, err, errMalformed, "truncation to %d bytes", n) + assert.Nil(t, parsed) + assert.Equal(t, Result{Outcome: OutcomeFallback, Reason: ReasonMalformed}, + Admit(expected, keys, raw[:n]), "truncation to %d bytes grants nothing", n) + } + }) + } + } + } +} + +func FuzzParse(f *testing.F) { + // The golden vectors, their truncations, and oversized inputs seed the + // corpus. CI runs only these seeds; go test -fuzz=FuzzParse fuzzes. + for _, h := range []string{goldenBoundNoneHex, goldenBoundSourceLinkHex, goldenBoundScenarioHex, goldenPendingNoneHex, goldenPendingSourceLinkHex, goldenPendingScenarioHex} { + b, err := hex.DecodeString(h) + if err != nil { + f.Fatal(err) + } + f.Add(b) + f.Add(b[:len(b)-1]) + f.Add(b[:len(b)/2]) + } + f.Add([]byte{}) + f.Add(bytes.Repeat([]byte{0x41}, MaxEnvelopeLen)) + f.Add(bytes.Repeat([]byte{0x00}, MaxEnvelopeLen+1)) + f.Fuzz(func(t *testing.T, data []byte) { + env, err := Parse(data) + if err != nil { + return + } + // Any parsed envelope must round-trip byte-for-byte: the wire + // format has exactly one encoding. + if got := env.Marshal(); !bytes.Equal(got, data) { + t.Fatalf("round-trip mismatch:\n got %x\nwant %x", got, data) + } + }) +} diff --git a/internal/telemetry/tracecontext/identity.go b/internal/telemetry/tracecontext/identity.go new file mode 100644 index 0000000000..7502e46bec --- /dev/null +++ b/internal/telemetry/tracecontext/identity.go @@ -0,0 +1,211 @@ +// Package tracecontext implements the versioned immutable work-item +// identity and signed trace-context envelope contract from ADR 0154. +// +// The package is pure: it performs no network I/O, reads no configuration, +// and never grants dispatch permission. It must stay importable from +// pkg/behaviourtest, so it must not depend on internal/cli, internal/repos, +// internal/layers, or the nested mintcore module. +package tracecontext + +import ( + "crypto/sha256" + "encoding/binary" + "errors" + "fmt" + "net/netip" + "net/url" + "strconv" + "strings" + "unicode/utf8" + + "go.opentelemetry.io/otel/trace" +) + +// EntityKind distinguishes the entity kinds that can share a forge +// container. GitLab issue and merge-request database IDs come from +// independent spaces, so the kind is part of every identity. +type EntityKind byte + +const ( + // KindWorkItem is an issue on GitHub, GitLab, or Jira. + KindWorkItem EntityKind = 0x01 + // KindChangeProposal is a GitHub pull request or a GitLab merge + // request. Jira has no change-proposal entity in this contract. + KindChangeProposal EntityKind = 0x02 +) + +// Valid reports whether k is a defined entity kind. +func (k EntityKind) Valid() bool { + return k == KindWorkItem || k == KindChangeProposal +} + +// Identity is the immutable binding of a forge entity (ADR 0154, D01): +// installation, forge instance, container, entity kind, and entity +// database ID. Display names, entity URLs, GitHub numbers, GitLab IIDs, +// and Jira keys are not identity components; docs/normative/trace-context/v1/README.md holds +// the per-forge field mapping. +type Identity struct { + // Installation is the 128-bit installation identifier provisioned + // with the signing key pair. It is authenticated in envelopes but + // deliberately excluded from fallback derivation, per ADR 0154. + Installation [16]byte + // Instance is the normalized forge web base URL: lowercase scheme://host + // with its escaped, case-sensitive deployment prefix and no trailing slash. + // Use NormalizeInstance to build it from trusted configuration. + Instance string + // Container is the immutable repository or project database ID. + Container int64 + // Kind is the entity kind within the container. + Kind EntityKind + // Entity is the immutable entity database ID. + Entity int64 +} + +// Resolved reports whether the forge-side identity components are present +// and valid: a canonical instance, a container ID >= 1, a valid kind, and +// an entity ID >= 1. Installation is local configuration rather than event +// identity, so it is not part of resolution; admission checks it against +// the envelope separately. An unresolved identity must postpone dispatch +// (FR-002); it never derives a fallback. +func (id Identity) Resolved() bool { + return validInstance(id.Instance) && id.Container >= 1 && id.Kind.Valid() && id.Entity >= 1 +} + +// Fallback is the deterministic entity-derived context: a stable TraceID +// and a synthetic anchor SpanID. By contract, the anchor exists only as a +// parent reference, is never exported as a span, and is never repointed. +type Fallback struct { + TraceID trace.TraceID + AnchorSpanID trace.SpanID +} + +// identityDomain separates fallback derivation from every other use of +// SHA-256 in this package and in the envelope format. +const identityDomain = "fullsend.tracecontext.identity.v1" + +// DeriveFallback derives the v1 deterministic fallback context. The +// derivation covers the forge instance, container, kind, and entity — +// never the installation, per ADR 0154. It returns ok=false for an +// unresolved identity. The derivation is pure, so independent and +// concurrent first events converge on identical nonzero IDs. +func DeriveFallback(id Identity) (fb Fallback, ok bool) { + if !id.Resolved() { + return Fallback{}, false + } + h := sha256.New() + writeField := func(b []byte) { + var l [2]byte + binary.BigEndian.PutUint16(l[:], uint16(len(b))) + h.Write(l[:]) + h.Write(b) + } + writeField([]byte(identityDomain)) + writeField([]byte(id.Instance)) + var i64 [8]byte + binary.BigEndian.PutUint64(i64[:], uint64(id.Container)) + h.Write(i64[:]) + h.Write([]byte{byte(id.Kind)}) + binary.BigEndian.PutUint64(i64[:], uint64(id.Entity)) + h.Write(i64[:]) + + sum := h.Sum(nil) + copy(fb.TraceID[:], sum[0:16]) + copy(fb.AnchorSpanID[:], sum[16:24]) + return nonzeroFallback(fb), true +} + +// All-zero digest slices use the documented v1 substitute so IDs stay valid. +func nonzeroFallback(fb Fallback) Fallback { + if fb.TraceID == (trace.TraceID{}) { + fb.TraceID[15] = 0x01 + } + if fb.AnchorSpanID == (trace.SpanID{}) { + fb.AnchorSpanID[7] = 0x01 + } + return fb +} + +// NormalizeInstance canonicalizes a forge web base URL to the D01 instance +// form: lowercase scheme://host with an escaped, case-sensitive deployment +// prefix and no trailing slashes, query, fragment, or user info. Only http +// and https are accepted. Ports lose leading zeros (an all-zero port stays +// :0) and must fit 16 bits; empty and default ports are then removed. +// Trailing DNS root dots are stripped, hosts must be ASCII (punycode for +// IDNs), and IPv6 hosts take their RFC 5952 form without a zone +// identifier. Path segments and escape spelling are preserved so distinct +// deployments cannot alias; a path mixing percent-escapes with characters +// that still need escaping rejects. All identity and envelope construction +// must use the normalized form so independent launches converge. +func NormalizeInstance(raw string) (string, error) { + if !utf8.ValidString(raw) { + return "", errors.New("tracecontext: instance must be valid UTF-8") + } + u, err := url.Parse(raw) + if err != nil { + return "", fmt.Errorf("tracecontext: parse instance URL: %w", err) + } + if u.Scheme == "" || u.Hostname() == "" { + return "", errors.New("tracecontext: instance URL needs a scheme and host") + } + if u.User != nil || strings.ContainsAny(raw, "?#") { + return "", errors.New("tracecontext: instance URL must not carry user info, query, or fragment") + } + if !utf8.ValidString(u.Path) || strings.ContainsRune(u.Path, '\x00') { + return "", errors.New("tracecontext: instance path must be valid UTF-8 without NUL") + } + // net/url keeps the original escapes only when the whole path is validly + // escaped; otherwise EscapedPath re-escapes the decoded path and %2F + // becomes a separator, aliasing two deployments. + if strings.Contains(u.RawPath, "%") && u.EscapedPath() != u.RawPath { + return "", errors.New("tracecontext: instance path mixes percent-escapes with unescaped characters; use the fully escaped prefix") + } + scheme := strings.ToLower(u.Scheme) + if scheme != "http" && scheme != "https" { + return "", fmt.Errorf("tracecontext: unsupported instance scheme %q", u.Scheme) + } + for _, r := range u.Host { + if r >= utf8.RuneSelf { + return "", errors.New("tracecontext: instance host must be ASCII; use punycode for IDNs") + } + } + // Zone identifiers survive parsing in a form the round trip cannot + // re-parse, and lowercasing would corrupt the case-sensitive zone. + if strings.ContainsRune(u.Host, '%') { + return "", errors.New("tracecontext: instance host must not carry an IPv6 zone identifier; use a routable address") + } + rawPort := u.Port() + host := strings.TrimSuffix(strings.ToLower(u.Host), ":"+rawPort) + // The DNS root dot is not a distinct deployment: strip trailing root + // dots so https://host and https://host. share one identity, and the + // strip stays idempotent for multi-dot spellings. + host = strings.TrimRight(host, ".") + if host == "" { + return "", errors.New("tracecontext: instance URL needs a host") + } + // One IPv6 address has one spelling: use its RFC 5952 form. + if addr, err := netip.ParseAddr(u.Hostname()); err == nil && addr.Is6() { + host = "[" + addr.String() + "]" + } + port := strings.TrimLeft(rawPort, "0") + if port == "" && rawPort != "" { + port = "0" + } + if port != "" { + if _, err := strconv.ParseUint(port, 10, 16); err != nil { + return "", fmt.Errorf("tracecontext: instance port %q must be at most 65535", rawPort) + } + if !(scheme == "https" && port == "443" || scheme == "http" && port == "80") { + host += ":" + port + } + } + normalized := scheme + "://" + host + strings.TrimRight(u.EscapedPath(), "/") + if len(normalized) > 253 { + return "", errors.New("tracecontext: instance must be at most 253 bytes") + } + return normalized, nil +} + +func validInstance(instance string) bool { + normalized, err := NormalizeInstance(instance) + return err == nil && instance == normalized +} diff --git a/internal/telemetry/tracecontext/identity_test.go b/internal/telemetry/tracecontext/identity_test.go new file mode 100644 index 0000000000..abbed0786e --- /dev/null +++ b/internal/telemetry/tracecontext/identity_test.go @@ -0,0 +1,475 @@ +package tracecontext + +import ( + "bytes" + "context" + "crypto/sha256" + "fmt" + "os" + "os/exec" + "strings" + "sync" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + sdktrace "go.opentelemetry.io/otel/sdk/trace" + "go.opentelemetry.io/otel/sdk/trace/tracetest" + "go.opentelemetry.io/otel/trace" +) + +// v01Identity is the shared V01 fixture: one resolved identity per forge +// kind, exercised by the derivation, sensitivity, rename, and concurrency +// tests below. +func v01Identity() Identity { + return Identity{ + Installation: [16]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10}, + Instance: "https://github.com", + Container: 274390431, + Kind: KindWorkItem, + Entity: 2468913570, + } +} + +// TestDeriveFallback_ResolvedAndNonzero is V01: the same resolved immutable +// identity derives a nonzero fallback, and repeated derivation in one +// process is deterministic. +func TestDeriveFallback_ResolvedAndNonzero(t *testing.T) { + fb, ok := DeriveFallback(v01Identity()) + require.True(t, ok, "resolved identity must derive a fallback") + assert.True(t, fb.TraceID.IsValid(), "derived TraceID must be nonzero") + assert.True(t, fb.AnchorSpanID.IsValid(), "derived anchor SpanID must be nonzero") + + again, ok := DeriveFallback(v01Identity()) + require.True(t, ok) + assert.Equal(t, fb, again, "derivation must be deterministic") +} + +// TestDeriveFallback_ComponentSensitivity is V01: changing any binding +// component changes the derived identity, so distinct +// instances, containers, kinds, or entities cannot alias. +func TestDeriveFallback_ComponentSensitivity(t *testing.T) { + base, ok := DeriveFallback(v01Identity()) + require.True(t, ok) + + changed := v01Identity() + changed.Instance = "https://ghe.example.com" + other, ok := DeriveFallback(changed) + require.True(t, ok) + assert.NotEqual(t, base, other, "forge instance must change identity") + + changed = v01Identity() + changed.Container = 274390432 + other, ok = DeriveFallback(changed) + require.True(t, ok) + assert.NotEqual(t, base, other, "container must change identity") + + changed = v01Identity() + changed.Kind = KindChangeProposal + other, ok = DeriveFallback(changed) + require.True(t, ok) + assert.NotEqual(t, base, other, "entity kind must change identity: GitLab issue and MR id spaces are independent") + + changed = v01Identity() + changed.Entity = 2468913571 + other, ok = DeriveFallback(changed) + require.True(t, ok) + assert.NotEqual(t, base, other, "entity must change identity") +} + +// TestDeriveFallback_InstallationExcluded pins the ADR 0154 rule: the +// fallback derivation covers forge instance, repository, and entity IDs — +// never the installation. +func TestDeriveFallback_InstallationExcluded(t *testing.T) { + base, ok := DeriveFallback(v01Identity()) + require.True(t, ok) + + other := v01Identity() + other.Installation = [16]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff} + got, ok := DeriveFallback(other) + require.True(t, ok) + assert.Equal(t, base, got, "installation must not participate in fallback derivation") +} + +// TestDeriveFallback_Unresolved is V01/FR-002: missing identity components +// are explicit unresolved outcomes, never a random or zero-context guess. +func TestDeriveFallback_Unresolved(t *testing.T) { + cases := map[string]Identity{ + "empty instance": func() Identity { i := v01Identity(); i.Instance = ""; return i }(), + "zero container": func() Identity { i := v01Identity(); i.Container = 0; return i }(), + "zero entity": func() Identity { i := v01Identity(); i.Entity = 0; return i }(), + "negative entity": func() Identity { i := v01Identity(); i.Entity = -1; return i }(), + "invalid kind": func() Identity { i := v01Identity(); i.Kind = EntityKind(0x00); return i }(), + "unknown kind": func() Identity { i := v01Identity(); i.Kind = EntityKind(0x7f); return i }(), + } + for name, id := range cases { + t.Run(name, func(t *testing.T) { + fb, ok := DeriveFallback(id) + assert.False(t, ok, "unresolved identity must be explicit") + assert.False(t, fb.TraceID.IsValid(), "unresolved identity must not fabricate a TraceID") + assert.False(t, fb.AnchorSpanID.IsValid(), "unresolved identity must not fabricate a SpanID") + assert.False(t, id.Resolved(), "Resolved must agree with DeriveFallback") + }) + } +} + +// TestIdentity_Resolved accepts the V01 fixture. +func TestIdentity_Resolved(t *testing.T) { + assert.True(t, v01Identity().Resolved()) +} + +// TestDeriveFallback_MoveIsNewBinding documents the D01 move rule: moving an +// entity to another bound container changes the binding (container or +// entity database ID), which is a new identity, never a rename. +func TestDeriveFallback_MoveIsNewBinding(t *testing.T) { + base, ok := DeriveFallback(v01Identity()) + require.True(t, ok) + + // Jira project move: same issue id, new project container. + moved := v01Identity() + moved.Container = 999888777 + after, ok := DeriveFallback(moved) + require.True(t, ok) + assert.NotEqual(t, base, after, "a moved entity has a new binding") + + // GitHub issue transfer: new container and new entity id. + transfered := v01Identity() + transfered.Container = 111222333 + transfered.Entity = 987654321 + after, ok = DeriveFallback(transfered) + require.True(t, ok) + assert.NotEqual(t, base, after, "a transferred entity has a new binding") +} + +// TestDeriveFallback_IIDsAreNotIdentity documents the D01 mapping: GitLab +// IIDs (and GitHub numbers, Jira keys) are display values. The same IID in +// two projects, or an issue and MR sharing a database id in different kind +// spaces, must not alias. +func TestDeriveFallback_IIDsAreNotIdentity(t *testing.T) { + a := Identity{Instance: "https://gitlab.com", Container: 101, Kind: KindWorkItem, Entity: 555} + b := Identity{Instance: "https://gitlab.com", Container: 102, Kind: KindWorkItem, Entity: 555} + fa, ok := DeriveFallback(a) + require.True(t, ok) + fb, ok := DeriveFallback(b) + require.True(t, ok) + assert.NotEqual(t, fa, fb, "the same IID in another project is a different entity") +} + +// TestDeriveFallback_ConcurrentFirstEvents is V01: concurrent first events +// converge on the same fallback. Run with -race. +func TestDeriveFallback_ConcurrentFirstEvents(t *testing.T) { + const goroutines = 64 + results := make([]Fallback, goroutines) + var wg sync.WaitGroup + for i := 0; i < goroutines; i++ { + wg.Add(1) + go func(slot int) { + defer wg.Done() + fb, ok := DeriveFallback(v01Identity()) + if !ok { + t.Error("concurrent derivation must resolve") + return + } + results[slot] = fb + }(i) + } + wg.Wait() + for i := 1; i < goroutines; i++ { + assert.Equal(t, results[0], results[i], "all first events must converge") + } + assert.True(t, results[0].TraceID.IsValid()) + assert.True(t, results[0].AnchorSpanID.IsValid()) +} + +// deriveChildEnv re-executes this test binary as a fresh process that +// derives the V01 fixture and prints the result, proving there is no shared +// in-memory state behind convergence. +const deriveChildEnv = "FULLSEND_TRACECONTEXT_DERIVE_CHILD=1" + +// TestDeriveFallback_IdenticalAcrossProcesses is V01: two fresh processes +// derive identical nonzero fallbacks for the same immutable identity. +func TestDeriveFallback_IdenticalAcrossProcesses(t *testing.T) { + if os.Getenv("FULLSEND_TRACECONTEXT_DERIVE_CHILD") == "1" { + fb, ok := DeriveFallback(v01Identity()) + if !ok { + fmt.Println("unresolved") + os.Exit(1) + } + // Print raw byte slices: the otel ID types implement Stringer, + // and %x on a Stringer would hex-encode the hex string. + fmt.Printf("%x %x\n", fb.TraceID[:], fb.AnchorSpanID[:]) + os.Exit(0) + } + + run := func() string { + cmd := exec.Command(os.Args[0], "-test.run", "^TestDeriveFallback_IdenticalAcrossProcesses$") + cmd.Env = append(os.Environ(), deriveChildEnv) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "child process: %s", out) + return strings.TrimSpace(string(out)) + } + first := run() + second := run() + + assert.NotEqual(t, "unresolved", first) + assert.Equal(t, first, second, "two fresh processes must derive identical fallbacks") + assert.Equal(t, "c9bdb0e38247ebbe2e0f1039250c32d4 892a346c55356aca", first) + + parts := strings.Fields(first) + require.Len(t, parts, 2, "child output: %q", first) + assert.Len(t, parts[0], 32, "TraceID must be 16 bytes hex") + assert.Len(t, parts[1], 16, "SpanID must be 8 bytes hex") + assert.NotEqual(t, strings.Repeat("00", 16), parts[0], "TraceID must be nonzero") + assert.NotEqual(t, strings.Repeat("00", 8), parts[1], "SpanID must be nonzero") +} + +// TestNormalizeInstance covers the D01 instance form: lowercase +// scheme://host with a deployment prefix, no query, fragment, or user info. +func TestNormalizeInstance(t *testing.T) { + cases := []struct { + name string + raw string + want string + }{ + {"github default", "https://github.com", "https://github.com"}, + {"gitlab default", "https://gitlab.com", "https://gitlab.com"}, + {"jira site", "https://acme.atlassian.net", "https://acme.atlassian.net"}, + {"GHES host", "https://ghe.example.com", "https://ghe.example.com"}, + {"uppercase host", "https://GitHub.com", "https://github.com"}, + {"uppercase scheme", "HTTPS://github.com", "https://github.com"}, + {"https default port", "https://GitHub.com:443/", "https://github.com"}, + {"https padded default port", "https://github.com:0443", "https://github.com"}, + {"http default port", "http://example.com:80/gitlab/", "http://example.com/gitlab"}, + {"https empty port", "https://GitHub.com:/", "https://github.com"}, + {"http empty port", "http://example.com:/gitlab/", "http://example.com/gitlab"}, + {"nondefault port", "https://example.com:8443/gitlab", "https://example.com:8443/gitlab"}, + {"padded nondefault port", "https://example.com:08443/gitlab", "https://example.com:8443/gitlab"}, + {"http nondefault port", "http://example.com:443", "http://example.com:443"}, + {"zero port", "https://example.com:0", "https://example.com:0"}, + {"padded zero port", "https://example.com:000", "https://example.com:0"}, + {"ipv6 default port", "https://[2001:DB8::1]:443/", "https://[2001:db8::1]"}, + {"ipv6 empty port", "https://[::1]:/gitlab", "https://[::1]/gitlab"}, + {"ipv6 nondefault port", "https://[2001:DB8::1]:8443", "https://[2001:db8::1]:8443"}, + {"ipv6 padded nondefault port", "https://[2001:DB8::1]:08443", "https://[2001:db8::1]:8443"}, + {"ipv6 expanded spelling", "https://[2001:DB8:0:0:0:0:0:1]", "https://[2001:db8::1]"}, + {"ipv6 padded group", "https://[2001:db8::0001]:443", "https://[2001:db8::1]"}, + {"ipv4-mapped ipv6 hex spelling", "https://[::ffff:c000:201]", "https://[::ffff:192.0.2.1]"}, + {"multiple root dots", "https://GitHub.com..", "https://github.com"}, + {"IDN punycode", "https://XN--BCHER-KVA.example", "https://xn--bcher-kva.example"}, + {"trailing slash", "https://github.com/", "https://github.com"}, + {"gitlab prefix", "https://GitLab.example.com/gitlab/", "https://gitlab.example.com/gitlab"}, + {"nested case-sensitive prefix", "https://gitlab.example.com/Services/GitLab///", "https://gitlab.example.com/Services/GitLab"}, + {"escaped prefix", "https://gitlab.example.com/a%2Fb/", "https://gitlab.example.com/a%2Fb"}, + {"unicode prefix", "https://gitlab.example.com/café/", "https://gitlab.example.com/caf%C3%A9"}, + {"fully escaped prefix with separator escape", "https://gitlab.example.com/a%2Fb/c%20d", "https://gitlab.example.com/a%2Fb/c%20d"}, + {"fully escaped unicode prefix with separator escape", "https://gitlab.example.com/caf%C3%A9%2Fx", "https://gitlab.example.com/caf%C3%A9%2Fx"}, + {"maximum prefix", "https://example.com/" + strings.Repeat("a", 233), "https://example.com/" + strings.Repeat("a", 233)}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, err := NormalizeInstance(tc.raw) + require.NoError(t, err) + assert.Equal(t, tc.want, got) + }) + } +} + +// TestNormalizeInstance_RootDotDoesNotForkIdentity pins the DNS root-dot +// rule: `host` and `host.` name the same deployment, so they must converge +// to one instance and one fallback, never two trace IDs. +func TestNormalizeInstance_RootDotDoesNotForkIdentity(t *testing.T) { + t.Parallel() + dotted, err := NormalizeInstance("https://GitHub.com.") + require.NoError(t, err) + plain, err := NormalizeInstance("https://github.com") + require.NoError(t, err) + assert.Equal(t, plain, dotted) + + a := v01Identity() + b := v01Identity() + a.Instance, b.Instance = plain, dotted + fa, ok := DeriveFallback(a) + require.True(t, ok) + fb, ok := DeriveFallback(b) + require.True(t, ok) + assert.Equal(t, fa, fb, "one deployment must not fork into two fallback traces") +} + +// TestNormalizeInstance_PortRangeAndZones pins the port and IPv6-zone +// rules: ports must fit 16 bits, and zone identifiers must reject so +// validInstance(NormalizeInstance(x)) always holds. +func TestNormalizeInstance_PortRangeAndZones(t *testing.T) { + t.Parallel() + for _, raw := range []string{"https://example.com:65535", "https://example.com:065535"} { + _, err := NormalizeInstance(raw) + require.NoError(t, err, raw) + } + for _, raw := range []string{ + "https://example.com:65536", + "https://example.com:99999999999999999999", + "https://[FE80::1%25EN0]", + "https://[fe80::1%en0]", + "https://.", + } { + _, err := NormalizeInstance(raw) + assert.Error(t, err, "input %q must be rejected", raw) + } +} + +// FuzzNormalizeInstance asserts the canonicalization invariant: anything +// NormalizeInstance accepts must re-normalize to itself, so the normalized +// form is always a valid instance. +func FuzzNormalizeInstance(f *testing.F) { + f.Add("https://github.com") + f.Add("https://GitLab.example.com:08443/gitlab/") + f.Add("https://[2001:DB8::1]:443/") + f.Add("https://example.com.") + f.Add("https://example.com:65536") + f.Add("https://[2001:DB8:0:0:0:0:0:1]:08443") + f.Add("https://gitlab.example.com/a%2Fb/c d") + f.Fuzz(func(t *testing.T, raw string) { + normalized, err := NormalizeInstance(raw) + if err != nil { + return + } + again, err := NormalizeInstance(normalized) + if err != nil { + t.Fatalf("normalized instance must re-normalize: %q: %v", normalized, err) + } + if normalized != again { + t.Fatalf("normalization must be idempotent: %q vs %q", normalized, again) + } + }) +} + +func TestNormalizeInstance_Rejects(t *testing.T) { + for _, raw := range []string{ + "", + "://missing-scheme", + "https://github.com/%00", + "https://github.com/%ff", + "https://user:passgithub.com", + "https://github.com?query=1", + "https://github.com#fragment", + "https://github.com?", + "https://github.com#", + "https://:443", + "ftp://github.com", + "https://" + strings.Repeat("a", 246), + "https://example.com/" + strings.Repeat("a", 234), + "https://\xff.example", + "https://bücher.example", + "https://b%C3%BCcher.example", + // Mixed escapes would decode %2F into a separator and alias + // /a/b/c%20d or /caf%C3%A9/x. + "https://gitlab.example.com/a%2Fb/c d", + "https://gitlab.example.com/café%2Fx", + } { + _, err := NormalizeInstance(raw) + assert.Error(t, err, "input %q must be rejected", raw) + } +} + +// These preimages and IDs were computed independently with Python struct +// (>H string lengths, >QBQ IDs/kind) and hashlib.sha256, not DeriveFallback. +func TestDeriveFallback_FixedVectors(t *testing.T) { + for _, tc := range []struct { + id Identity + preimage, traceID, anchor string + }{ + {v01Identity(), "002166756c6c73656e642e7472616365636f6e746578742e6964656e746974792e7631001268747470733a2f2f6769746875622e636f6d00000000105add9f01000000009328a1a2", "c9bdb0e38247ebbe2e0f1039250c32d4", "892a346c55356aca"}, + {Identity{Instance: "https://gitlab.com", Container: 101, Kind: KindChangeProposal, Entity: 555}, "002166756c6c73656e642e7472616365636f6e746578742e6964656e746974792e7631001268747470733a2f2f6769746c61622e636f6d000000000000006502000000000000022b", "407b66d9453075850f3ee7ef31d6ff1e", "a39491edef0440ae"}, + {Identity{Instance: "https://acme.atlassian.net", Container: 10000, Kind: KindWorkItem, Entity: 10100}, "002166756c6c73656e642e7472616365636f6e746578742e6964656e746974792e7631001a68747470733a2f2f61636d652e61746c61737369616e2e6e65740000000000002710010000000000002774", "535e9f2c6d8bd8a814edd68dceb60e9a", "7e00bd92068701ac"}, + {Identity{Instance: "https://gitlab.example.com/gitlab", Container: 101, Kind: KindChangeProposal, Entity: 555}, "002166756c6c73656e642e7472616365636f6e746578742e6964656e746974792e7631002168747470733a2f2f6769746c61622e6578616d706c652e636f6d2f6769746c6162000000000000006502000000000000022b", "71c6f9ad9a13f7244356f839e29687fa", "8f2d2a176bde1f88"}, + } { + t.Run(tc.id.Instance, func(t *testing.T) { + digest := sha256.Sum256(mustHex(t, tc.preimage)) + assert.Equal(t, tc.traceID, fmt.Sprintf("%x", digest[:16])) + assert.Equal(t, tc.anchor, fmt.Sprintf("%x", digest[16:24])) + fb, ok := DeriveFallback(tc.id) + require.True(t, ok) + assert.Equal(t, tc.traceID, fb.TraceID.String()) + assert.Equal(t, tc.anchor, fb.AnchorSpanID.String()) + }) + } +} + +func TestNonzeroFallback(t *testing.T) { + t.Parallel() + traceID := trace.TraceID{0: 0xab, 15: 0xcd} + anchor := trace.SpanID{0: 0xef, 7: 0x42} + for _, tc := range []struct { + name string + in Fallback + want Fallback + }{ + {"both zero", Fallback{}, Fallback{trace.TraceID{15: 1}, trace.SpanID{7: 1}}}, + {"zero trace", Fallback{AnchorSpanID: anchor}, Fallback{trace.TraceID{15: 1}, anchor}}, + {"zero anchor", Fallback{TraceID: traceID}, Fallback{traceID, trace.SpanID{7: 1}}}, + {"nonzero preserved", Fallback{traceID, anchor}, Fallback{traceID, anchor}}, + } { + t.Run(tc.name, func(t *testing.T) { + got := nonzeroFallback(tc.in) + assert.Equal(t, tc.want, got) + assert.True(t, got.TraceID.IsValid()) + assert.True(t, got.AnchorSpanID.IsValid()) + }) + } +} + +func TestFallback_SyntheticAnchorExportLifecycle(t *testing.T) { + seen := map[trace.SpanID]bool{} + for range 2 { + // Each provider models an independent launch with no retained state. + exporter := tracetest.NewInMemoryExporter() + provider := sdktrace.NewTracerProvider(sdktrace.WithSyncer(exporter), sdktrace.WithSampler(sdktrace.AlwaysSample())) + t.Cleanup(func() { assert.NoError(t, provider.Shutdown(context.Background())) }) + fb, ok := DeriveFallback(v01Identity()) + require.True(t, ok) + parent := trace.NewSpanContext(trace.SpanContextConfig{TraceID: fb.TraceID, SpanID: fb.AnchorSpanID}) + ctx := trace.ContextWithRemoteSpanContext(context.Background(), parent) + tracer := provider.Tracer("tracecontext-test") + for range 2 { + _, span := tracer.Start(ctx, "operation") + span.End() + } + spans := exporter.GetSpans() + require.Len(t, spans, 2, "only operation spans are exported") + for _, span := range spans { + assert.Equal(t, "c9bdb0e38247ebbe2e0f1039250c32d4", span.SpanContext.TraceID().String()) + assert.Equal(t, "892a346c55356aca", span.Parent.SpanID().String()) + assert.Equal(t, span.SpanContext.TraceID(), span.Parent.TraceID()) + assert.NotEqual(t, fb.AnchorSpanID, span.SpanContext.SpanID(), "anchor is never exported") + assert.False(t, seen[span.SpanContext.SpanID()], "operations have distinct IDs across launches") + seen[span.SpanContext.SpanID()] = true + } + } +} + +// TestDeriveFallback_InstancesDifferByHost ensures normalization feeds +// derivation distinctly per host. +func TestDeriveFallback_InstancesDifferByHost(t *testing.T) { + a := v01Identity() + b := v01Identity() + b.Instance = "https://ghe.example.com" + fa, ok := DeriveFallback(a) + require.True(t, ok) + fb, ok := DeriveFallback(b) + require.True(t, ok) + assert.False(t, bytes.Equal(fa.TraceID[:], fb.TraceID[:])) +} + +func TestDeriveFallback_DeploymentPrefixesStayDistinct(t *testing.T) { + t.Parallel() + seen := map[Fallback]bool{} + for _, prefix := range []string{"", "/gitlab", "/GitLab", "/other/gitlab", "/a%2Fb", "/a/b"} { + id := v01Identity() + id.Instance = "https://gitlab.example.com" + prefix + fb, ok := DeriveFallback(id) + require.True(t, ok, id.Instance) + assert.False(t, seen[fb], "deployment prefixes must not alias: %s", prefix) + seen[fb] = true + } +} diff --git a/internal/tracker/fake_jira.go b/internal/tracker/fake_jira.go index d7fc7c8331..564c80d8e1 100644 --- a/internal/tracker/fake_jira.go +++ b/internal/tracker/fake_jira.go @@ -22,6 +22,8 @@ import ( type FakeJiraClient struct { Issues map[string]*jira.Issue Comments map[string][]jira.Comment + // ProjectIDs supplies immutable project IDs for created issue reads. + ProjectIDs map[string]string // CommentProperties maps "issueKey/commentID" to a map of // propertyKey -> value, mirroring Jira's per-comment entity @@ -133,8 +135,12 @@ func (f *FakeJiraClient) CreateIssue(_ context.Context, in jira.CreateIssueInput issueType.Name = in.IssueType } f.Issues[key] = &jira.Issue{ - Key: key, - Fields: jira.IssueFields{Summary: in.Summary, Description: description, IssueType: issueType}, + ID: fmt.Sprintf("%d", 10000+len(f.CreatedIssues)), + Key: key, + Fields: jira.IssueFields{ + Summary: in.Summary, Description: description, IssueType: issueType, + Project: &jira.ProjectRef{ID: f.ProjectIDs[in.ProjectKey], Key: in.ProjectKey}, + }, } return &jira.CreatedIssue{ID: fmt.Sprintf("%d", 10000+len(f.CreatedIssues)), Key: key}, nil } diff --git a/internal/tracker/forge_client.go b/internal/tracker/forge_client.go index aac72d1f7a..ad6cc030d5 100644 --- a/internal/tracker/forge_client.go +++ b/internal/tracker/forge_client.go @@ -43,6 +43,7 @@ func (c *ForgeClient) GetIssue(ctx context.Context, project string, number int) return nil, wrapNotFound(err) } return &Issue{ + ID: issue.ID, Number: issue.Number, Title: issue.Title, Body: Body(issue.Body), @@ -72,6 +73,7 @@ func (c *ForgeClient) CreateIssue(ctx context.Context, project, title string, bo return nil, wrapNotFound(err) } return &Issue{ + ID: issue.ID, Number: issue.Number, Title: issue.Title, Body: Body(issue.Body), diff --git a/internal/tracker/jira_client.go b/internal/tracker/jira_client.go index 80794b127d..6b7a2aff65 100644 --- a/internal/tracker/jira_client.go +++ b/internal/tracker/jira_client.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "log" "strconv" "strings" "time" @@ -120,11 +121,17 @@ func (c *JiraClient) GetIssue(ctx context.Context, project string, number int) ( if issue.Fields.IssueType != nil { issueType = issue.Fields.IssueType.Name } + var containerID int64 + if issue.Fields.Project != nil { + containerID = parseJiraID(issue.Fields.Project.ID) + } canonicalKey := issue.Key if canonicalKey == "" { canonicalKey = key } return &Issue{ + ID: parseJiraID(issue.ID), + ContainerID: containerID, Number: number, Title: issue.Fields.Summary, Body: Body(jira.ADFToMarkdown(issue.Fields.Description)), @@ -161,6 +168,7 @@ func (c *JiraClient) CreateIssue(ctx context.Context, project, title string, bod return nil, err } return &Issue{ + ID: parseJiraID(created.ID), Number: number, Title: title, Body: body, @@ -169,6 +177,19 @@ func (c *JiraClient) CreateIssue(ctx context.Context, project, title string, bod }, nil } +// parseJiraID converts a Jira issue or project ID string to the immutable +// int64 identity. Jira returns positive numeric ID strings; an invalid value +// yields 0, which callers must treat as an unresolved identity rather than +// guessing (FR-002), matching jirapoll's parseIssueID behavior. +func parseJiraID(id string) int64 { + n, err := strconv.ParseInt(id, 10, 64) + if err != nil || n < 1 { + log.Printf("WARNING: invalid Jira id %q, using 0", id) + return 0 + } + return n +} + // issueNumberFromKey returns the numeric part of a Jira issue key, e.g. // issueNumberFromKey("PROJ-123") = 123. func issueNumberFromKey(key string) (int, error) { diff --git a/internal/tracker/trace_identity_test.go b/internal/tracker/trace_identity_test.go new file mode 100644 index 0000000000..4b229fab12 --- /dev/null +++ b/internal/tracker/trace_identity_test.go @@ -0,0 +1,94 @@ +package tracker + +import ( + "context" + "testing" + + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/forge/jira" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The tests in this file cover ADR 0154: the immutable database IDs +// required by the identity tuple must survive tracker mapping, and the +// Jira immutable issue ID must stay distinct from the display key. + +func TestForgeClient_GetIssue_MapsImmutableID(t *testing.T) { + fc := forge.NewFakeClient() + fc.OpenIssues = map[string][]forge.Issue{ + "acme/widgets": { + {ID: 2468913570, Number: 42, Title: "Widget is broken", Body: "details", URL: "https://example.com/42"}, + }, + } + + c := NewForgeClient(fc) + issue, err := c.GetIssue(context.Background(), "acme/widgets", 42) + require.NoError(t, err) + assert.Equal(t, int64(2468913570), issue.ID, "immutable forge issue id") + assert.Equal(t, 42, issue.Number, "display number") +} + +func TestForgeClient_CreateIssue_MapsImmutableID(t *testing.T) { + fc := forge.NewFakeClient() + + c := NewForgeClient(fc) + issue, err := c.CreateIssue(context.Background(), "acme/widgets", "New work", "body", CreateIssueOptions{}) + require.NoError(t, err) + assert.NotZero(t, issue.ID, "the fake's synthesized immutable issue id") + assert.NotZero(t, issue.Number, "display number") + assert.NotEqual(t, int64(issue.Number), issue.ID, "identity and display number use distinct id spaces") +} + +// TestJiraClient_GetIssue_IDAndKeyDistinct covers the Jira ID/key +// distinction: the immutable numeric issue id and the display key must both +// survive mapping without being conflated. +func TestJiraClient_GetIssue_IDAndKeyDistinct(t *testing.T) { + fc := &FakeJiraClient{ + Issues: map[string]*jira.Issue{ + "PROJ-42": { + ID: "10100", + Key: "PROJ-42", + Fields: jira.IssueFields{ + Summary: "Widget is broken", + Project: &jira.ProjectRef{ID: "10000", Key: "PROJ"}, + }, + }, + }, + } + + c := newTestJiraClient(t, fc, "https://acme.atlassian.net") + issue, err := c.GetIssue(context.Background(), "PROJ", 42) + require.NoError(t, err) + assert.Equal(t, int64(10100), issue.ID, "immutable Jira issue id") + assert.Equal(t, "PROJ-42", issue.Key, "display key") + assert.Equal(t, 42, issue.Number, "numeric key suffix") + assert.Equal(t, int64(10000), issue.ContainerID) +} + +func TestJiraClient_CreateIssue_MapsImmutableID(t *testing.T) { + fc := &FakeJiraClient{ProjectIDs: map[string]string{"PROJ": "20000"}} + c := newTestJiraClient(t, fc, "https://acme.atlassian.net") + + issue, err := c.CreateIssue(context.Background(), "PROJ", "New work", "body", CreateIssueOptions{IssueType: "Task"}) + require.NoError(t, err) + assert.NotZero(t, issue.ID, "immutable id of the created issue") + assert.NotEmpty(t, issue.Key, "display key of the created issue") + assert.Zero(t, issue.ContainerID, "Jira create response has no project ID") + read, err := c.GetIssue(context.Background(), "PROJ", issue.Number) + require.NoError(t, err) + assert.Equal(t, issue.ID, read.ID) + assert.Equal(t, int64(20000), read.ContainerID, "trusted read resolves the container") +} + +func TestJiraClient_GetIssue_UnresolvedProject(t *testing.T) { + for _, project := range []*jira.ProjectRef{nil, {}, {ID: "bad"}, {ID: "0"}, {ID: "-1"}, {ID: "9223372036854775808"}} { + fc := &FakeJiraClient{Issues: map[string]*jira.Issue{ + "PROJ-42": {ID: "10100", Key: "PROJ-42", Fields: jira.IssueFields{Project: project}}, + }} + c := newTestJiraClient(t, fc, "https://acme.atlassian.net") + issue, err := c.GetIssue(context.Background(), "PROJ", 42) + require.NoError(t, err) + assert.Zero(t, issue.ContainerID, "project %#v must remain unresolved", project) + } +} diff --git a/internal/tracker/tracker.go b/internal/tracker/tracker.go index df7548bd0e..2fbcc5c40a 100644 --- a/internal/tracker/tracker.go +++ b/internal/tracker/tracker.go @@ -58,11 +58,26 @@ type Body string // Issue represents an issue's content, independent of the tracker backend. type Issue struct { + // Number is the display number addressing the issue as (project, + // number): GitHub's per-repo issue number, GitLab's per-project IID, + // or the numeric suffix of a Jira key. It is not a stable identity. Number int - Title string - Body Body - URL string - Labels []string + // ID is the immutable issue database ID: GitHub's REST issue id, + // GitLab's database issue id (not the IID), or Jira's numeric issue + // id string parsed to an integer. It is 0 when the backend did not + // report one; trace admission treats that as unresolved identity + // rather than guessing. For a GitHub PR number, a forge-backed GetIssue + // returns the issue-space id; never use it as KindChangeProposal + // identity (see forge.Issue.ID). + ID int64 + // ContainerID is the immutable Jira project ID supplied by GetIssue. + // Zero means unresolved: create responses and forge-backed reads need + // a separate trusted project/repository lookup before trace admission. + ContainerID int64 + Title string + Body Body + URL string + Labels []string // IssueType is the tracker's issue type name (e.g. "Bug", "Story"). // Set by the Jira client; empty for trackers that don't report one. IssueType string