From d51d4b67dc3a4cece9201e05246684f30c2dd65e Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 3 Nov 2026 10:35:14 -0500 Subject: [PATCH 1/2] refactor(telemetry): add trace-context identity and signed envelope contract Implement the PR 1 foundation of ADR 0154 (AISDLC-576): a pure internal/telemetry/tracecontext package with the versioned immutable work-item identity and deterministic fallback derivation (D01), and the v1 Ed25519-signed fixed-layout envelope with strict bounded parsing and pure admission (wire D02). Both design gates were resolved with maintainer agreement; docs/reference/trace-context.md documents the contract and the tests freeze golden wire vectors for all later PRs. Thread the immutable database IDs through the forge and tracker models: forge.Issue.ID, forge.ChangeProposal.ID, tracker.Issue.ID, and the Jira project reference, populated by the GitHub adapter (REST id and GraphQL databaseId), the GitLab adapter (database id, not the IID), and the tracker clients, with fakes synthesizing IDs in a distinct space. Normalized events are unchanged in this slice; runtime admission wiring follows in PR 3. Admission never returns dispatch permission, sampling flags, tracestate, or baggage; pending markers grant neither context nor links. Signed-off-by: Dharit Shah --- docs/.vitepress/config.ts | 1 + .../infrastructure/distributed-tracing.md | 8 + docs/reference/trace-context.md | 198 ++++++ internal/forge/fake.go | 7 + internal/forge/forge.go | 19 +- internal/forge/github/github.go | 21 +- internal/forge/github/trace_identity_test.go | 97 +++ internal/forge/gitlab/issue.go | 6 + internal/forge/gitlab/mr.go | 4 + internal/forge/gitlab/trace_identity_test.go | 161 +++++ internal/forge/jira/client_test.go | 26 + internal/forge/jira/types.go | 10 + internal/telemetry/tracecontext/envelope.go | 529 ++++++++++++++ .../telemetry/tracecontext/envelope_test.go | 662 ++++++++++++++++++ internal/telemetry/tracecontext/identity.go | 148 ++++ .../telemetry/tracecontext/identity_test.go | 287 ++++++++ internal/tracker/fake_jira.go | 1 + internal/tracker/forge_client.go | 2 + internal/tracker/jira_client.go | 16 + internal/tracker/trace_identity_test.go | 102 +++ internal/tracker/tracker.go | 9 + 21 files changed, 2308 insertions(+), 6 deletions(-) create mode 100644 docs/reference/trace-context.md create mode 100644 internal/forge/github/trace_identity_test.go create mode 100644 internal/forge/gitlab/trace_identity_test.go create mode 100644 internal/telemetry/tracecontext/envelope.go create mode 100644 internal/telemetry/tracecontext/envelope_test.go create mode 100644 internal/telemetry/tracecontext/identity.go create mode 100644 internal/telemetry/tracecontext/identity_test.go create mode 100644 internal/tracker/trace_identity_test.go 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/guides/infrastructure/distributed-tracing.md b/docs/guides/infrastructure/distributed-tracing.md index 5e3a511add..b6d6dbf527 100644 --- a/docs/guides/infrastructure/distributed-tracing.md +++ b/docs/guides/infrastructure/distributed-tracing.md @@ -664,6 +664,14 @@ 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. +Durable work-item continuity across independent launches — signed, +entity-bound context published as metadata on the work item, with a +deterministic fallback derived from immutable entity identity — is a +separate mechanism specified in +[ADR 0154](../../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md) +and documented in 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/reference/trace-context.md b/docs/reference/trace-context.md new file mode 100644 index 0000000000..7bb87ff0c7 --- /dev/null +++ b/docs/reference/trace-context.md @@ -0,0 +1,198 @@ +# Trace Context Reference + +Version 1 of the work-item trace-context identity and signed-envelope +protocol from [ADR 0154](../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md). +This page documents the implemented contract surfaces: the immutable +identity tuple, the deterministic fallback derivation, the v1 wire format, +and the pure admission operation. Carrier publication (hidden body +metadata, Jira properties), key provisioning, and runtime admission wiring +are separate delivery slices; this page marks them where they are not yet +implemented. + +The Go implementation is +[`internal/telemetry/tracecontext`](https://github.com/fullsend-ai/fullsend/blob/main/internal/telemetry/tracecontext). +It is pure: no network I/O, no configuration reads, and it never grants +dispatch permission. + +## Identity + +Every forge entity is addressed by an immutable five-part tuple. Display +names, 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 | issue or PR REST `id` | issue or MR database `id` (not the IID) | issue `id` | + +The instance string is the normalized base URL: lowercase +`scheme://host`, no path, no trailing slash. `NormalizeInstance` builds it +and rejects URLs that carry a path, query, fragment, or user info. + +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: every component is a database ID. +- 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. + +### 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 length-prefixed canonical encoding of the domain + string `fullsend.tracecontext.identity.v1`, the instance string, the + container `int64`, the kind byte, and the entity `int64`. +- 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) + substitutes a documented nonzero value, so derived IDs are always 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: the OpenTelemetry SDK assigns +random span IDs, so no exported span ever carries the anchor ID, the +anchor is never repointed, and operation spans keep distinct +SDK-generated IDs. + +## 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 9 bytes | +| · | 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 | `crypto/rand`, nonzero, unique per creation intent | +| 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. + +### 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 carrier bytes, 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. It + grants nothing; bounded rereads are caller policy. +- **Fallback**: nothing was admissible. The caller uses the + entity-derived fallback. + +Fallback reason codes are redacted diagnostics — `absent`, `malformed`, +`oversized`, `unknown-version`, `unknown-key`, `bad-signature`, +`binding-mismatch`, `conflicting-carrier`, `provenance` — never key +material or raw bytes. A plain W3C `traceparent` is never an envelope. + +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 (missing instance, container, kind, or entity) is +explicit: callers must postpone dispatch with diagnostics rather than +derive a fallback or guess. + +## Go API + +| Symbol | Purpose | +|--------|---------| +| `Identity` | The immutable binding tuple | +| `Identity.Resolved` | Whether forge-side identity components are present | +| `DeriveFallback` | The v1 deterministic fallback context | +| `NormalizeInstance` | Canonical `scheme://host` instance form | +| `Envelope` | A decoded v1 envelope or pending marker | +| `Envelope.Sign` | Validate and sign with an Ed25519 private key (host-side only) | +| `Envelope.Marshal` | Canonical wire bytes | +| `Parse` | Strict bounded decode | +| `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 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. + +## Compatibility + +The golden test vectors in +[`envelope_test.go`](https://github.com/fullsend-ai/fullsend/blob/main/internal/telemetry/tracecontext/envelope_test.go) +pin the exact signed bytes of one envelope per domain and provenance +kind. Any change to the wire layout, derivation, or key-selector rules is +a compatibility break that requires a new version byte and a reviewed +migration path. Unknown versions already reject cleanly. diff --git a/internal/forge/fake.go b/internal/forge/fake.go index 014a89e450..e2b535b272 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, @@ -1602,7 +1605,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/forge.go b/internal/forge/forge.go index 46568f54e1..bd6d40370e 100644 --- a/internal/forge/forge.go +++ b/internal/forge/forge.go @@ -495,10 +495,16 @@ 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. + 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 +579,14 @@ 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. + ID int64 Title string Body string URL string diff --git a/internal/forge/github/github.go b/internal/forge/github/github.go index ee614fcec2..5348757371 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 { + databaseId 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"` + DatabaseID int64 `json:"databaseId"` + Number int `json:"number"` + Title string `json:"title"` + URL string `json:"url"` } `json:"pullRequest"` } `json:"createPullRequest"` } `json:"data"` @@ -2595,6 +2599,9 @@ func (c *LiveClient) CreateCrossRepoChangeProposal(ctx context.Context, baseOwne pr := gqlResult.Data.CreatePullRequest.PullRequest return &forge.ChangeProposal{ + // databaseId is the GraphQL name for the REST numeric id, so + // both creation paths expose the same immutable identity. + ID: pr.DatabaseID, URL: pr.URL, Title: pr.Title, Number: pr.Number, @@ -2612,6 +2619,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 +2642,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 +3308,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 +3321,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 +3364,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 +3379,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 +3430,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 +3450,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/trace_identity_test.go b/internal/forge/github/trace_identity_test.go new file mode 100644 index 0000000000..4ff9b3cc4b --- /dev/null +++ b/internal/forge/github/trace_identity_test.go @@ -0,0 +1,97 @@ +package github + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The tests in this file are V03 for AISDLC-576: the immutable database IDs +// required by the D01 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) +} + +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..c299c365f6 --- /dev/null +++ b/internal/forge/gitlab/trace_identity_test.go @@ -0,0 +1,161 @@ +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 are V03 for AISDLC-576: the immutable database IDs +// required by the D01 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() + + mux.HandleFunc("/api/v4/projects/owner%2Frepo/issues", func(w http.ResponseWriter, r *http.Request) { + 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") + 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() + + mux.HandleFunc("/api/v4/projects/owner%2Frepo/merge_requests", func(w http.ResponseWriter, r *http.Request) { + 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") + 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() + + mux.HandleFunc("/api/v4/projects/owner%2Frepo/merge_requests", func(w http.ResponseWriter, r *http.Request) { + 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") + 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() + + mux.HandleFunc("/api/v4/projects/owner%2Frepo/issues", func(w http.ResponseWriter, r *http.Request) { + 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") + 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_test.go b/internal/forge/jira/client_test.go index 1d49890591..8fe6e2d899 100644 --- a/internal/forge/jira/client_test.go +++ b/internal/forge/jira/client_test.go @@ -781,6 +781,32 @@ func TestGetIssue(t *testing.T) { assert.Equal(t, "new", issue.Fields.Status.StatusCategory.Key) } +// TestGetIssue_CapturesProjectRef is V03 for AISDLC-576: the immutable +// project database ID (the D01 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() + + mux.HandleFunc("/rest/api/3/issue/PROJ-42", func(w http.ResponseWriter, r *http.Request) { + 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") + 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 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..b8d78a22b0 --- /dev/null +++ b/internal/telemetry/tracecontext/envelope.go @@ -0,0 +1,529 @@ +package tracecontext + +import ( + "bytes" + "crypto/ed25519" + "crypto/sha256" + "encoding/base64" + "encoding/binary" + "errors" + "fmt" + "strings" + "unicode/utf8" + + "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. The wire layout, +// exact sizes, and strict limits are frozen in +// docs/reference/trace-context.md; 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 frozen 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 smallest legal envelope: pending domain, no +// provenance, 1-byte instance. +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 n := len(e.Instance); n < 1 || n > 253 { + return fmt.Errorf("%w: instance length %d", errMalformed, n) + } + if !utf8.ValidString(e.Instance) || strings.ContainsRune(e.Instance, 0) { + 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, ok := key.Public().(ed25519.PublicKey) + if !ok { + return errors.New("tracecontext: signing key has no Ed25519 public half") + } + 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 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. 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 := 6 + 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} + p, err := grab(8) + if err != nil { + return nil, err + } + copy(e.KeyID[:], p) + p, err = grab(16) + if err != nil { + return nil, err + } + copy(e.Installation[:], p) + p, err = grab(2) + if err != nil { + return nil, err + } + instLen := int(binary.BigEndian.Uint16(p)) + 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 ( + // OutcomeAdmitted means a verified bound envelope matched the + // expected binding; the admitted IDs are available. + OutcomeAdmitted Outcome = iota + // OutcomePending means a verified pending marker matched the expected + // scope. It grants neither context nor links; bounded rereads are + // caller policy. + OutcomePending + // OutcomeFallback means no carrier was admissible; the caller uses + // the deterministic entity-derived fallback. + OutcomeFallback +) + +// 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" + 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). +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 carrier wire bytes 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. +func Admit(expected Identity, keys map[[8]byte]ed25519.PublicKey, candidates ...[]byte) Result { + 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 { + 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, + } + } + 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..4bb4bcbaf3 --- /dev/null +++ b/internal/telemetry/tracecontext/envelope_test.go @@ -0,0 +1,662 @@ +package tracecontext + +import ( + "bytes" + "crypto/ed25519" + "encoding/base64" + "encoding/binary" + "encoding/hex" + "reflect" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.opentelemetry.io/otel/trace" +) + +// The tests in this file are V02/V04 for AISDLC-576: 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 frozen v1 wire format for +// every later PR. + +// 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 signs and marshals a golden envelope. +func signedGolden(t *testing.T, domain Domain, prov ProvenanceKind) ([]byte, map[[8]byte]ed25519.PublicKey) { + t.Helper() + key, keys := goldenKeys(t) + env := goldenEnvelope(domain, prov) + require.NoError(t, env.Sign(key)) + return env.Marshal(), keys +} + +// specLayout mirrors the frozen v1 wire layout from +// docs/reference/trace-context.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: frozen from the first green run; any later change +// to the wire format is a compatibility break. +var ( + goldenBoundNoneHex = "46535443010165b60673d6ed884ba0a1a2a3a4a5a6a7a8a9aaabacadaeaf001268747470733a2f2f6769746875622e636f6d00000000105add9f01000000009328a1a24f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6da1b2c3d4e5f6071800101112131415161718191a1b1c1d1e1fe337c39001d56da6ba8862e01893f5d63d41fee3cab1d35f925aacd2e4a7165b30cf38403fcd2f809f50df67a62ebe705eb25a16e028df6345d8924b01bd2c0e" + goldenBoundSourceLinkHex = "46535443010165b60673d6ed884ba0a1a2a3a4a5a6a7a8a9aaabacadaeaf001268747470733a2f2f6769746875622e636f6d00000000105add9f01000000009328a1a24f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6da1b2c3d4e5f60718015c4b3a29180f6e5d4c3b2a1908f7e6d50f1e2d3c4b5a6978101112131415161718191a1b1c1d1e1f96451fbecf439bee72e636691b09f313df7b94bb017a63b7cdc0ea57775f3ca5a240c6f592f59bf33a25f463049e389345cf4d1354bd929198dc18803163a604" + goldenBoundScenarioHex = "46535443010165b60673d6ed884ba0a1a2a3a4a5a6a7a8a9aaabacadaeaf001268747470733a2f2f6769746875622e636f6d00000000105add9f01000000009328a1a24f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6da1b2c3d4e5f60718024f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6df0f1f2f3f4f5f6f7f8f9fafbfcfdfeff101112131415161718191a1b1c1d1e1fa59c45c20117895374e9ea5631083900ea081913ec21aa7d4604a23a75f2dd0f2ace2c01dda59c399f24bbdb409bc64081d898ba1ee73c292ca3d716e0860001" + goldenPendingNoneHex = "46535443010265b60673d6ed884ba0a1a2a3a4a5a6a7a8a9aaabacadaeaf001268747470733a2f2f6769746875622e636f6d00000000105add9f014f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6da1b2c3d4e5f6071800101112131415161718191a1b1c1d1e1f51fcd462f5bf6dd75e28f906fe0f4cf72d2c9fe9d3f66f95e1e650588442fdf2167890b17bc34775e27a74cc58ec22603df915fbe5396239d3f2b1ebf965c703" +) + +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}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + raw, keys := signedGolden(t, tc.dom, tc.prov) + want := mustHex(t, *tc.hex) + if !bytes.Equal(raw, want) { + t.Fatalf("golden wire bytes changed or not yet frozen:\n got %x\nwant %x", raw, want) + } + + // Layout is exactly the frozen 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(raw) + require.NoError(t, err) + env := goldenEnvelope(tc.dom, tc.prov) + env.Sign(goldenKey()) + assert.Equal(t, env, parsed) + + // Admission admits exactly the bound context. + res := Admit(goldenIdentity(), keys, raw) + 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, OutcomePending, res.Outcome) + } + }) + } +} + +// 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 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) +} + +// 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") +} + +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) { + env := goldenEnvelope(tc.domain, tc.prov) + require.NoError(t, env.Sign(key)) + raw := tc.mutate(env.Marshal()) + 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_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. + env := goldenEnvelope(DomainBound, ProvenanceSourceLink) + require.NoError(t, env.Sign(key)) + raw := env.Marshal() + 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. + env = goldenEnvelope(DomainBound, ProvenanceScenario) + require.NoError(t, env.Sign(key)) + raw = env.Marshal() + 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") +} + +// TestParse_Truncations walks every truncation of a maximal envelope: no +// prefix may parse, and none may panic. +func TestParse_Truncations(t *testing.T) { + raw, _ := signedGolden(t, DomainBound, ProvenanceScenario) + for n := 0; n < len(raw); n++ { + _, err := Parse(raw[:n]) + require.Error(t, err, "truncation to %d bytes must not parse", n) + } +} + +// TestParse_ShortTails exercises mid-structure bounds failures: buffers +// that pass the minimum-length and header checks but end inside a later +// fixed-size field. The instance length is chosen per buffer so each +// truncation point lands in a different grab. +func TestParse_ShortTails(t *testing.T) { + build := func(instLen, total int) []byte { + b := make([]byte, total) + copy(b, magic[:]) + b[4] = versionV1 + b[5] = byte(DomainBound) + binary.BigEndian.PutUint16(b[30:32], uint16(instLen)) + for i := 32; i < 32+instLen && i < total; i++ { + b[i] = 'x' + } + return b + } + // Instance field overruns the buffer. + _, err := Parse(build(253, 150)) + assert.Error(t, err) + // Container field overruns. + _, err = Parse(build(100, 135)) + assert.Error(t, err) + // Entity field overruns. + _, err = Parse(build(100, 143)) + assert.Error(t, err) + // Trace field overruns. + _, err = Parse(build(100, 151)) + assert.Error(t, err) + // Span field overruns. + _, err = Parse(build(100, 159)) + assert.Error(t, err) + // Provenance kind byte overruns. + _, err = Parse(build(100, 167)) + assert.Error(t, err) + // Signature region overruns (nonce fits, 64-byte signature does not). + _, err = Parse(build(100, 183)) + assert.Error(t, err) +} + +func FuzzParse(f *testing.F) { + // The frozen golden vectors, their truncations, and oversized inputs + // seed the corpus; CI fuzzing grows it from there. + for _, h := range []string{goldenBoundNoneHex, goldenBoundSourceLinkHex, goldenBoundScenarioHex, goldenPendingNoneHex} { + 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..586bd850fc --- /dev/null +++ b/internal/telemetry/tracecontext/identity.go @@ -0,0 +1,148 @@ +// 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/url" + "strings" + + "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, URLs, GitHub numbers, GitLab IIDs, and Jira +// keys are not identity components; docs/reference/trace-context.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 no path and no trailing slash. Use + // NormalizeInstance to build it. + 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 non-empty 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 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. The OpenTelemetry SDK assigns random span +// IDs, so no exported span ever carries the anchor ID; the anchor exists +// only as a parent reference 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]) + // Deterministic nonzero guarantee: SHA-256 output is all-zero with + // probability 2^-128 (trace) / 2^-64 (span); substitute a documented + // nonzero value so callers never see an invalid ID. + if fb.TraceID == (trace.TraceID{}) { + fb.TraceID[15] = 0x01 + } + if fb.AnchorSpanID == (trace.SpanID{}) { + fb.AnchorSpanID[7] = 0x01 + } + return fb, true +} + +// NormalizeInstance canonicalizes a forge web base URL to the D01 instance +// form: lowercase scheme://host with no path, query, fragment, or user +// info. Only http and https are accepted; a bare "/" path is tolerated and +// stripped. All identity and envelope construction must use the normalized +// form so independent launches converge. +func NormalizeInstance(raw string) (string, error) { + u, err := url.Parse(raw) + if err != nil { + return "", fmt.Errorf("tracecontext: parse instance URL: %w", err) + } + if u.Scheme == "" || u.Host == "" { + return "", errors.New("tracecontext: instance URL needs a scheme and host") + } + if u.User != nil || u.RawQuery != "" || u.Fragment != "" { + return "", errors.New("tracecontext: instance URL must be a bare scheme://host") + } + if u.Path != "" && u.Path != "/" { + return "", errors.New("tracecontext: instance URL must not carry a path") + } + scheme := strings.ToLower(u.Scheme) + if scheme != "http" && scheme != "https" { + return "", fmt.Errorf("tracecontext: unsupported instance scheme %q", u.Scheme) + } + return scheme + "://" + strings.ToLower(u.Host), nil +} diff --git a/internal/telemetry/tracecontext/identity_test.go b/internal/telemetry/tracecontext/identity_test.go new file mode 100644 index 0000000000..c4f70849c1 --- /dev/null +++ b/internal/telemetry/tracecontext/identity_test.go @@ -0,0 +1,287 @@ +package tracecontext + +import ( + "bytes" + "fmt" + "os" + "os/exec" + "strings" + "sync" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// 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 installations, +// 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_RenameStable documents the D01 rename rule: display +// names never enter the tuple, so a rename cannot change the binding. Two +// identities built from different display names for the same database IDs +// are the same identity. +func TestDeriveFallback_RenameStable(t *testing.T) { + before, ok := DeriveFallback(v01Identity()) + require.True(t, ok) + + renamed := v01Identity() // same database IDs; only display names changed + after, ok := DeriveFallback(renamed) + require.True(t, ok) + assert.Equal(t, before, after, "a rename must not change trace identity") +} + +// 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 + moved.Instance = "https://acme.atlassian.net" + 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_TRACONTEXT_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_TRACONTEXT_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") + + 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, no path, 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"}, + {"trailing slash", "https://github.com/", "https://github.com"}, + } + 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) + }) + } +} + +func TestNormalizeInstance_Rejects(t *testing.T) { + for _, raw := range []string{ + "", + "://missing-scheme", + "https://github.com/owner/repo", + "https://user:passgithub.com", + "https://github.com?query=1", + "https://github.com#fragment", + } { + _, err := NormalizeInstance(raw) + assert.Error(t, err, "input %q must be rejected", raw) + } +} + +// 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[:])) +} diff --git a/internal/tracker/fake_jira.go b/internal/tracker/fake_jira.go index 53f9d13fd8..dd854469ed 100644 --- a/internal/tracker/fake_jira.go +++ b/internal/tracker/fake_jira.go @@ -129,6 +129,7 @@ func (f *FakeJiraClient) CreateIssue(_ context.Context, in jira.CreateIssueInput issueType.Name = in.IssueType } f.Issues[key] = &jira.Issue{ + ID: fmt.Sprintf("%d", 10000+len(f.CreatedIssues)), Key: key, Fields: jira.IssueFields{Summary: in.Summary, Description: description, IssueType: issueType}, } 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 6a17446095..89f2d7a7fb 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" @@ -125,6 +126,7 @@ func (c *JiraClient) GetIssue(ctx context.Context, project string, number int) ( canonicalKey = key } return &Issue{ + ID: parseJiraIssueID(issue.ID), Number: number, Title: issue.Fields.Summary, Body: Body(jira.ADFToMarkdown(issue.Fields.Description)), @@ -161,6 +163,7 @@ func (c *JiraClient) CreateIssue(ctx context.Context, project, title string, bod return nil, err } return &Issue{ + ID: parseJiraIssueID(created.ID), Number: number, Title: title, Body: body, @@ -169,6 +172,19 @@ func (c *JiraClient) CreateIssue(ctx context.Context, project, title string, bod }, nil } +// parseJiraIssueID converts a Jira issue ID string to the immutable int64 +// identity. Jira always returns numeric ID strings; an unparseable value +// yields 0, which callers must treat as an unresolved identity rather than +// guessing (FR-002), matching jirapoll's parseIssueID behavior. +func parseJiraIssueID(id string) int64 { + n, err := strconv.ParseInt(id, 10, 64) + if err != nil { + log.Printf("WARNING: unparseable Jira issue id %q, using 0: %v", id, err) + 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..3a966f2bad --- /dev/null +++ b/internal/tracker/trace_identity_test.go @@ -0,0 +1,102 @@ +package tracker + +import ( + "context" + "testing" + + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/forge/jira" +) + +// The tests in this file are V03 for AISDLC-576: the immutable database IDs +// required by the D01 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) + if err != nil { + t.Fatalf("GetIssue returned error: %v", err) + } + if issue.ID != 2468913570 { + t.Errorf("issue.ID = %d, want 2468913570 (immutable forge issue id)", issue.ID) + } + if issue.Number != 42 { + t.Errorf("issue.Number = %d, want 42 (display number)", issue.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{}) + if err != nil { + t.Fatalf("CreateIssue returned error: %v", err) + } + if issue.ID == 0 { + t.Errorf("issue.ID = 0, want the fake's synthesized immutable issue id") + } + if issue.Number == 0 { + t.Errorf("issue.Number = 0, want a display number") + } + if issue.ID == int64(issue.Number) { + t.Errorf("issue.ID (%d) must be a distinct id space from the display number (%d)", issue.ID, issue.Number) + } +} + +// 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) + if err != nil { + t.Fatalf("GetIssue returned error: %v", err) + } + if issue.ID != 10100 { + t.Errorf("issue.ID = %d, want 10100 (immutable Jira issue id)", issue.ID) + } + if issue.Key != "PROJ-42" { + t.Errorf("issue.Key = %q, want %q (display key)", issue.Key, "PROJ-42") + } + if issue.Number != 42 { + t.Errorf("issue.Number = %d, want 42 (numeric key suffix)", issue.Number) + } +} + +func TestJiraClient_CreateIssue_MapsImmutableID(t *testing.T) { + fc := &FakeJiraClient{} + c := newTestJiraClient(t, fc, "https://acme.atlassian.net") + + issue, err := c.CreateIssue(context.Background(), "PROJ", "New work", "body", CreateIssueOptions{IssueType: "Task"}) + if err != nil { + t.Fatalf("CreateIssue returned error: %v", err) + } + if issue.ID == 0 { + t.Errorf("issue.ID = 0, want the immutable id of the created issue") + } + if issue.Key == "" { + t.Errorf("issue.Key is empty, want the display key of the created issue") + } +} diff --git a/internal/tracker/tracker.go b/internal/tracker/tracker.go index df7548bd0e..6dbf23fd3a 100644 --- a/internal/tracker/tracker.go +++ b/internal/tracker/tracker.go @@ -58,7 +58,16 @@ 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 + // 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. + ID int64 Title string Body Body URL string From 86f631d613960469f4150846f173d4847ebcad73 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 3 Nov 2026 11:42:57 -0500 Subject: [PATCH 2/2] fix(#9060): harden trace identity and signed admission Preserve full-width GitHub IDs and Jira project identity through adapter and tracker boundaries. Reject malformed verification keys and noncanonical signed instances without granting trace context. Add independent wire and fallback vectors, stable-anchor exporter checks, and regression coverage for the review findings. Correct the protocol reference and retain the explicit pending and unresolved states. Signed-off-by: Dharit Shah --- docs/reference/trace-context.md | 55 +++++++-- internal/forge/fake.go | 1 + internal/forge/fake_test.go | 4 + internal/forge/github/github.go | 22 ++-- internal/forge/github/github_test.go | 57 +++++++++- internal/forge/gitlab/trace_identity_test.go | 12 ++ internal/forge/jira/client.go | 2 +- internal/forge/jira/client_test.go | 28 +++++ internal/telemetry/tracecontext/envelope.go | 12 +- .../telemetry/tracecontext/envelope_test.go | 105 +++++++++++++----- internal/telemetry/tracecontext/identity.go | 28 +++-- .../telemetry/tracecontext/identity_test.go | 67 ++++++++++- internal/tracker/fake_jira.go | 11 +- internal/tracker/jira_client.go | 19 ++-- internal/tracker/trace_identity_test.go | 22 +++- internal/tracker/tracker.go | 14 ++- 16 files changed, 375 insertions(+), 84 deletions(-) diff --git a/docs/reference/trace-context.md b/docs/reference/trace-context.md index 7bb87ff0c7..24931e4851 100644 --- a/docs/reference/trace-context.md +++ b/docs/reference/trace-context.md @@ -26,11 +26,23 @@ components. | 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 | issue or PR REST `id` | issue or MR database `id` (not the IID) | issue `id` | +| Entity | issue or PR REST `id`; PR GraphQL `fullDatabaseId` (`BigInt`) | issue or MR database `id` (not the IID) | issue `id` | The instance string is the normalized base URL: lowercase -`scheme://host`, no path, no trailing slash. `NormalizeInstance` builds it -and rejects URLs that carry a path, query, fragment, or user info. +`scheme://host`, using `http` or `https`, at most 253 UTF-8 bytes, no path or +trailing slash. `NormalizeInstance` builds it (accepting and removing a bare +`/`) and rejects URLs with a longer path, query, fragment, user info, or +missing host. Identity resolution, signing, and parsing require the already +canonical value; they never silently rewrite an authenticated field. + +Jira issue reads expose the project ID as `tracker.Issue.ContainerID`; search +requests 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 reads resolve their repository separately through `forge.Client`. +GitHub cross-repository PR creation decodes `fullDatabaseId` directly into +an `int64`, accepting numeric or string JSON without floating-point rounding; +the deprecated 32-bit GraphQL `databaseId` is not used. The installation ID is generated during key provisioning and identifies one install's key set. It is authenticated inside every envelope and must @@ -57,19 +69,36 @@ deterministically: - Input: the forge instance, container, kind, and entity — never the installation. -- SHA-256 over the length-prefixed canonical encoding of the domain - string `fullsend.tracecontext.identity.v1`, the instance string, the - container `int64`, the kind byte, and the entity `int64`. +- 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) - substitutes a documented nonzero value, so derived IDs are always valid. + 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: the OpenTelemetry SDK assigns -random span IDs, so no exported span ever carries the anchor ID, the -anchor is never repointed, and operation spans keep distinct -SDK-generated IDs. +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 in `identity_test.go`; runtime integration remains a later slice. ## Signed envelope (wire format v1) @@ -88,7 +117,7 @@ the magic through the nonce — there are no unsigned fields. | 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 9 bytes | +| 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 | @@ -127,6 +156,8 @@ 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 diff --git a/internal/forge/fake.go b/internal/forge/fake.go index e2b535b272..36ecabf0a0 100644 --- a/internal/forge/fake.go +++ b/internal/forge/fake.go @@ -1243,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, 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/github/github.go b/internal/forge/github/github.go index 5348757371..d88972e7f0 100644 --- a/internal/forge/github/github.go +++ b/internal/forge/github/github.go @@ -2537,7 +2537,7 @@ func (c *LiveClient) CreateCrossRepoChangeProposal(ctx context.Context, baseOwne query := `mutation($input: CreatePullRequestInput!) { createPullRequest(input: $input) { pullRequest { - databaseId + fullDatabaseId number title url @@ -2568,10 +2568,10 @@ func (c *LiveClient) CreateCrossRepoChangeProposal(ctx context.Context, baseOwne Data struct { CreatePullRequest struct { PullRequest struct { - DatabaseID int64 `json:"databaseId"` - Number int `json:"number"` - Title string `json:"title"` - URL string `json:"url"` + FullDatabaseID json.Number `json:"fullDatabaseId"` + Number int `json:"number"` + Title string `json:"title"` + URL string `json:"url"` } `json:"pullRequest"` } `json:"createPullRequest"` } `json:"data"` @@ -2598,10 +2598,16 @@ func (c *LiveClient) CreateCrossRepoChangeProposal(ctx context.Context, baseOwne } pr := gqlResult.Data.CreatePullRequest.PullRequest + var id int64 + if pr.FullDatabaseID != "" { + id, err = pr.FullDatabaseID.Int64() + if err != nil || id < 1 { + return nil, fmt.Errorf("decode cross-repo pull request response: invalid fullDatabaseId %q", pr.FullDatabaseID) + } + } return &forge.ChangeProposal{ - // databaseId is the GraphQL name for the REST numeric id, so - // both creation paths expose the same immutable identity. - ID: pr.DatabaseID, + // BigInt may be a JSON number or string; never round through float64. + ID: id, URL: pr.URL, Title: pr.Title, Number: pr.Number, diff --git a/internal/forge/github/github_test.go b/internal/forge/github/github_test.go index 649cb7a329..724146927d 100644 --- a/internal/forge/github/github_test.go +++ b/internal/forge/github/github_test.go @@ -1056,6 +1056,53 @@ func TestCreateChangeProposal_Forbidden(t *testing.T) { assert.True(t, forge.IsForbidden(err), "CreateChangeProposal 403 should wrap ErrForbidden") } +func TestCreateCrossRepoChangeProposal_FullWidthID(t *testing.T) { + for _, tc := range []struct { + name, jsonID string + want int64 + wantErr bool + }{ + {"number", "9007199254740993", 9007199254740993, false}, + {"string", `"9007199254740993"`, 9007199254740993, false}, + {"max int64", `"9223372036854775807"`, 9223372036854775807, false}, + {"null unresolved", "null", 0, false}, + {"missing unresolved", "", 0, false}, + {"overflow", `"9223372036854775808"`, 0, true}, + {"negative", "-1", 0, true}, + {"zero", "0", 0, true}, + {"fractional", "1.5", 0, true}, + {"nonnumeric", `"bad"`, 0, true}, + } { + t.Run(tc.name, func(t *testing.T) { + calls := 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/"): + 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}}}}`, 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, 1, calls) + if tc.wantErr { + assert.Error(t, err) + return + } + require.NoError(t, err) + assert.Equal(t, tc.want, cp.ID) + }) + } +} + func TestCreateCrossRepoChangeProposal(t *testing.T) { t.Run("same-org fork uses GraphQL", func(t *testing.T) { var getRepoCalls []string @@ -1075,6 +1122,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 +1137,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 +1161,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/gitlab/trace_identity_test.go b/internal/forge/gitlab/trace_identity_test.go index c299c365f6..c7dd80e107 100644 --- a/internal/forge/gitlab/trace_identity_test.go +++ b/internal/forge/gitlab/trace_identity_test.go @@ -43,8 +43,10 @@ func TestGetIssue_CapturesDatabaseID(t *testing.T) { 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, @@ -55,6 +57,7 @@ func TestCreateIssue_CapturesDatabaseID(t *testing.T) { }) 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) @@ -89,8 +92,10 @@ func TestGetIssue_NestedNamespace(t *testing.T) { 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, @@ -102,6 +107,7 @@ func TestCreateChangeProposal_CapturesDatabaseID(t *testing.T) { }) 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) @@ -110,8 +116,10 @@ func TestCreateChangeProposal_CapturesDatabaseID(t *testing.T) { 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, @@ -124,6 +132,7 @@ func TestListRepoPullRequests_CapturesDatabaseID(t *testing.T) { }) 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") @@ -135,8 +144,10 @@ func TestListRepoPullRequests_CapturesDatabaseID(t *testing.T) { 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, @@ -147,6 +158,7 @@ func TestListOpenIssues_CapturesDatabaseID(t *testing.T) { }) 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) 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 8fe6e2d899..f282c31162 100644 --- a/internal/forge/jira/client_test.go +++ b/internal/forge/jira/client_test.go @@ -788,8 +788,10 @@ 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", @@ -801,12 +803,38 @@ func TestGetIssue_CapturesProjectRef(t *testing.T) { }) 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) { + 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/telemetry/tracecontext/envelope.go b/internal/telemetry/tracecontext/envelope.go index b8d78a22b0..8b649a1108 100644 --- a/internal/telemetry/tracecontext/envelope.go +++ b/internal/telemetry/tracecontext/envelope.go @@ -9,7 +9,6 @@ import ( "errors" "fmt" "strings" - "unicode/utf8" "go.opentelemetry.io/otel/trace" ) @@ -107,8 +106,8 @@ var ( errMalformed = errors.New("tracecontext: malformed envelope") ) -// minEnvelopeLen is the smallest legal envelope: pending domain, no -// provenance, 1-byte instance. +// 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 @@ -131,10 +130,7 @@ func (e *Envelope) validate() error { if e.Installation == ([16]byte{}) { return fmt.Errorf("%w: zero installation", errMalformed) } - if n := len(e.Instance); n < 1 || n > 253 { - return fmt.Errorf("%w: instance length %d", errMalformed, n) - } - if !utf8.ValidString(e.Instance) || strings.ContainsRune(e.Instance, 0) { + if !validInstance(e.Instance) { return fmt.Errorf("%w: invalid instance", errMalformed) } if e.Container < 1 { @@ -498,7 +494,7 @@ func Admit(expected Identity, keys map[[8]byte]ed25519.PublicKey, candidates ... env := parsed[0] pub, ok := keys[env.KeyID] - if !ok { + if !ok || len(pub) != ed25519.PublicKeySize { return fallback(ReasonUnknownKey) } payload := candidates[0][:len(candidates[0])-64] diff --git a/internal/telemetry/tracecontext/envelope_test.go b/internal/telemetry/tracecontext/envelope_test.go index 4bb4bcbaf3..518a05f4af 100644 --- a/internal/telemetry/tracecontext/envelope_test.go +++ b/internal/telemetry/tracecontext/envelope_test.go @@ -102,13 +102,18 @@ func goldenEnvelope(domain Domain, prov ProvenanceKind) *Envelope { return env } -// signedGolden signs and marshals a golden envelope. +// 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() - key, keys := goldenKeys(t) - env := goldenEnvelope(domain, prov) - require.NoError(t, env.Sign(key)) - return env.Marshal(), keys + _, 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 frozen v1 wire layout from @@ -167,12 +172,16 @@ func mustHex(t *testing.T, s string) []byte { } // Golden hex constants: frozen from the first green run; any later change -// to the wire format is a compatibility break. +// to the wire format is a compatibility break. 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" + goldenBoundNoneHex = "46535443010165b60673d6ed884ba0a1a2a3a4a5a6a7a8a9aaabacadaeaf001268747470733a2f2f6769746875622e636f6d00000000105add9f01000000009328a1a24f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6da1b2c3d4e5f6071800101112131415161718191a1b1c1d1e1fe337c39001d56da6ba8862e01893f5d63d41fee3cab1d35f925aacd2e4a7165b30cf38403fcd2f809f50df67a62ebe705eb25a16e028df6345d8924b01bd2c0e" + goldenBoundSourceLinkHex = "46535443010165b60673d6ed884ba0a1a2a3a4a5a6a7a8a9aaabacadaeaf001268747470733a2f2f6769746875622e636f6d00000000105add9f01000000009328a1a24f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6da1b2c3d4e5f60718015c4b3a29180f6e5d4c3b2a1908f7e6d50f1e2d3c4b5a6978101112131415161718191a1b1c1d1e1f96451fbecf439bee72e636691b09f313df7b94bb017a63b7cdc0ea57775f3ca5a240c6f592f59bf33a25f463049e389345cf4d1354bd929198dc18803163a604" + goldenBoundScenarioHex = "46535443010165b60673d6ed884ba0a1a2a3a4a5a6a7a8a9aaabacadaeaf001268747470733a2f2f6769746875622e636f6d00000000105add9f01000000009328a1a24f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6da1b2c3d4e5f60718024f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6df0f1f2f3f4f5f6f7f8f9fafbfcfdfeff101112131415161718191a1b1c1d1e1fa59c45c20117895374e9ea5631083900ea081913ec21aa7d4604a23a75f2dd0f2ace2c01dda59c399f24bbdb409bc64081d898ba1ee73c292ca3d716e0860001" + goldenPendingNoneHex = "46535443010265b60673d6ed884ba0a1a2a3a4a5a6a7a8a9aaabacadaeaf001268747470733a2f2f6769746875622e636f6d00000000105add9f014f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6da1b2c3d4e5f6071800101112131415161718191a1b1c1d1e1f51fcd462f5bf6dd75e28f906fe0f4cf72d2c9fe9d3f66f95e1e650588442fdf2167890b17bc34775e27a74cc58ec22603df915fbe5396239d3f2b1ebf965c703" + goldenPendingSourceLinkHex = "46535443010265b60673d6ed884ba0a1a2a3a4a5a6a7a8a9aaabacadaeaf001268747470733a2f2f6769746875622e636f6d00000000105add9f014f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6da1b2c3d4e5f60718015c4b3a29180f6e5d4c3b2a1908f7e6d50f1e2d3c4b5a6978101112131415161718191a1b1c1d1e1fa35099c98587f7dc2ba94734f2afe542cd1581bcd0dc9320e436de8ca57c0a3dcd61bcdfad9a933e3baec5a324659286eb164aa745c3f62079ea466513aa6703" + goldenPendingScenarioHex = "46535443010265b60673d6ed884ba0a1a2a3a4a5a6a7a8a9aaabacadaeaf001268747470733a2f2f6769746875622e636f6d00000000105add9f014f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6da1b2c3d4e5f60718024f3a9c1b2d8e4a7c9f0b1e2d3c4a5b6df0f1f2f3f4f5f6f7f8f9fafbfcfdfeff101112131415161718191a1b1c1d1e1f0bb31c983e5206e3592f6e437117cbdc06a6991213ee65c57ff3cff4cdd35a26f571fa350d2046117c695892521bf393df228718b96cb5fdbb65c244b3de820c" ) func TestGoldenVectors(t *testing.T) { @@ -186,10 +195,15 @@ func TestGoldenVectors(t *testing.T) { {"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) { - raw, keys := signedGolden(t, tc.dom, tc.prov) + _, 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 changed or not yet frozen:\n got %x\nwant %x", raw, want) @@ -199,21 +213,19 @@ func TestGoldenVectors(t *testing.T) { assert.Equal(t, layout(tc.dom, tc.prov, len(goldenIdentity().Instance)).total, len(raw)) // Parse round-trips byte-for-byte. - parsed, err := Parse(raw) + parsed, err := Parse(want) require.NoError(t, err) - env := goldenEnvelope(tc.dom, tc.prov) - env.Sign(goldenKey()) assert.Equal(t, env, parsed) // Admission admits exactly the bound context. - res := Admit(goldenIdentity(), keys, raw) + 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, OutcomePending, res.Outcome) + assert.Equal(t, Result{Outcome: OutcomePending, Reason: ReasonPending}, res) } }) } @@ -274,6 +286,52 @@ func TestAdmit_UnknownKey(t *testing.T) { 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{ + "not-a-url", "https://GitHub.com", "HTTPS://github.com", "https://github.com/", + "https://github.com/api", "https://github.com?", "https://github.com#", + "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) + assert.Equal(t, Result{Outcome: OutcomeFallback, Reason: ReasonMalformed}, Admit(id, keys, mutated)) + }) + } +} + // 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) { @@ -387,9 +445,8 @@ func TestParse_ZeroAndInvalidFields(t *testing.T) { } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - env := goldenEnvelope(tc.domain, tc.prov) - require.NoError(t, env.Sign(key)) - raw := tc.mutate(env.Marshal()) + raw, _ := signedGolden(t, tc.domain, tc.prov) + raw = tc.mutate(raw) raw = resign(t, key, raw) _, err := Parse(raw) @@ -449,9 +506,7 @@ func TestAdmit_ProvenanceConsistency(t *testing.T) { // Source link whose destination trace equals the source trace: the // traces would merge, which ordinary provenance forbids. - env := goldenEnvelope(DomainBound, ProvenanceSourceLink) - require.NoError(t, env.Sign(key)) - raw := env.Marshal() + 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)) @@ -459,9 +514,7 @@ func TestAdmit_ProvenanceConsistency(t *testing.T) { assert.Equal(t, ReasonProvenance, res.Reason) // Scenario provenance whose trace differs from the scenario trace. - env = goldenEnvelope(DomainBound, ProvenanceScenario) - require.NoError(t, env.Sign(key)) - raw = env.Marshal() + raw = mustHex(t, goldenBoundScenarioHex) lay = layout(DomainBound, ProvenanceScenario, len(goldenIdentity().Instance)) raw[lay.trace] ^= 0x01 res = Admit(goldenIdentity(), keys, resign(t, key, raw)) @@ -636,7 +689,7 @@ func TestParse_ShortTails(t *testing.T) { func FuzzParse(f *testing.F) { // The frozen golden vectors, their truncations, and oversized inputs // seed the corpus; CI fuzzing grows it from there. - for _, h := range []string{goldenBoundNoneHex, goldenBoundSourceLinkHex, goldenBoundScenarioHex, goldenPendingNoneHex} { + for _, h := range []string{goldenBoundNoneHex, goldenBoundSourceLinkHex, goldenBoundScenarioHex, goldenPendingNoneHex, goldenPendingSourceLinkHex, goldenPendingScenarioHex} { b, err := hex.DecodeString(h) if err != nil { f.Fatal(err) diff --git a/internal/telemetry/tracecontext/identity.go b/internal/telemetry/tracecontext/identity.go index 586bd850fc..a8f69631ae 100644 --- a/internal/telemetry/tracecontext/identity.go +++ b/internal/telemetry/tracecontext/identity.go @@ -14,6 +14,7 @@ import ( "fmt" "net/url" "strings" + "unicode/utf8" "go.opentelemetry.io/otel/trace" ) @@ -59,19 +60,18 @@ type Identity struct { } // Resolved reports whether the forge-side identity components are present -// and valid: a non-empty instance, a container ID >= 1, a valid kind, and +// 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 id.Instance != "" && id.Container >= 1 && id.Kind.Valid() && id.Entity >= 1 + 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. The OpenTelemetry SDK assigns random span -// IDs, so no exported span ever carries the anchor ID; the anchor exists -// only as a parent reference and is never repointed. +// 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 @@ -127,14 +127,17 @@ func DeriveFallback(id Identity) (fb Fallback, ok bool) { // stripped. 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.Host == "" { + if u.Scheme == "" || u.Hostname() == "" { return "", errors.New("tracecontext: instance URL needs a scheme and host") } - if u.User != nil || u.RawQuery != "" || u.Fragment != "" { + if u.User != nil || strings.ContainsAny(raw, "?#") { return "", errors.New("tracecontext: instance URL must be a bare scheme://host") } if u.Path != "" && u.Path != "/" { @@ -144,5 +147,14 @@ func NormalizeInstance(raw string) (string, error) { if scheme != "http" && scheme != "https" { return "", fmt.Errorf("tracecontext: unsupported instance scheme %q", u.Scheme) } - return scheme + "://" + strings.ToLower(u.Host), nil + normalized := scheme + "://" + strings.ToLower(u.Host) + 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 index c4f70849c1..421e9a3479 100644 --- a/internal/telemetry/tracecontext/identity_test.go +++ b/internal/telemetry/tracecontext/identity_test.go @@ -2,6 +2,8 @@ package tracecontext import ( "bytes" + "context" + "crypto/sha256" "fmt" "os" "os/exec" @@ -11,6 +13,9 @@ import ( "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 @@ -42,7 +47,7 @@ func TestDeriveFallback_ResolvedAndNonzero(t *testing.T) { } // TestDeriveFallback_ComponentSensitivity is V01: changing any binding -// component changes the derived identity, so distinct installations, +// component changes the derived identity, so distinct // instances, containers, kinds, or entities cannot alias. func TestDeriveFallback_ComponentSensitivity(t *testing.T) { base, ok := DeriveFallback(v01Identity()) @@ -139,7 +144,6 @@ func TestDeriveFallback_MoveIsNewBinding(t *testing.T) { // Jira project move: same issue id, new project container. moved := v01Identity() moved.Container = 999888777 - moved.Instance = "https://acme.atlassian.net" after, ok := DeriveFallback(moved) require.True(t, ok) assert.NotEqual(t, base, after, "a moved entity has a new binding") @@ -225,6 +229,7 @@ func TestDeriveFallback_IdenticalAcrossProcesses(t *testing.T) { 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) @@ -267,12 +272,70 @@ func TestNormalizeInstance_Rejects(t *testing.T) { "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://\xff.example", } { _, 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"}, + } { + 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 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) { diff --git a/internal/tracker/fake_jira.go b/internal/tracker/fake_jira.go index dd854469ed..651b0193bd 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 @@ -129,9 +131,12 @@ func (f *FakeJiraClient) CreateIssue(_ context.Context, in jira.CreateIssueInput issueType.Name = in.IssueType } f.Issues[key] = &jira.Issue{ - ID: fmt.Sprintf("%d", 10000+len(f.CreatedIssues)), - 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/jira_client.go b/internal/tracker/jira_client.go index 89f2d7a7fb..dcadb88531 100644 --- a/internal/tracker/jira_client.go +++ b/internal/tracker/jira_client.go @@ -121,12 +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: parseJiraIssueID(issue.ID), + ID: parseJiraID(issue.ID), + ContainerID: containerID, Number: number, Title: issue.Fields.Summary, Body: Body(jira.ADFToMarkdown(issue.Fields.Description)), @@ -163,7 +168,7 @@ func (c *JiraClient) CreateIssue(ctx context.Context, project, title string, bod return nil, err } return &Issue{ - ID: parseJiraIssueID(created.ID), + ID: parseJiraID(created.ID), Number: number, Title: title, Body: body, @@ -172,14 +177,14 @@ func (c *JiraClient) CreateIssue(ctx context.Context, project, title string, bod }, nil } -// parseJiraIssueID converts a Jira issue ID string to the immutable int64 -// identity. Jira always returns numeric ID strings; an unparseable value +// 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 parseJiraIssueID(id string) int64 { +func parseJiraID(id string) int64 { n, err := strconv.ParseInt(id, 10, 64) - if err != nil { - log.Printf("WARNING: unparseable Jira issue id %q, using 0: %v", id, err) + if err != nil || n < 1 { + log.Printf("WARNING: invalid Jira id %q, using 0", id) return 0 } return n diff --git a/internal/tracker/trace_identity_test.go b/internal/tracker/trace_identity_test.go index 3a966f2bad..1033dbac68 100644 --- a/internal/tracker/trace_identity_test.go +++ b/internal/tracker/trace_identity_test.go @@ -6,6 +6,8 @@ import ( "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 are V03 for AISDLC-576: the immutable database IDs @@ -83,10 +85,11 @@ func TestJiraClient_GetIssue_IDAndKeyDistinct(t *testing.T) { if issue.Number != 42 { t.Errorf("issue.Number = %d, want 42 (numeric key suffix)", issue.Number) } + assert.Equal(t, int64(10000), issue.ContainerID) } func TestJiraClient_CreateIssue_MapsImmutableID(t *testing.T) { - fc := &FakeJiraClient{} + 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"}) @@ -99,4 +102,21 @@ func TestJiraClient_CreateIssue_MapsImmutableID(t *testing.T) { if issue.Key == "" { t.Errorf("issue.Key is empty, want the 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 6dbf23fd3a..b025bd8f90 100644 --- a/internal/tracker/tracker.go +++ b/internal/tracker/tracker.go @@ -67,11 +67,15 @@ type Issue struct { // 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. - ID int64 - Title string - Body Body - URL string - Labels []string + 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