From febd7223fc3e35f30218e735a99817c64fb831a2 Mon Sep 17 00:00:00 2001 From: "Tom D. Snyder" Date: Sat, 3 Oct 2026 10:18:43 -0400 Subject: [PATCH 1/3] Handoff: a hand-back keeps its attempt, only the reaper expires, no path around the packet gate Three of the sealing, claims and masking review's findings, closed with a test each and each test seen failing with its fix reverted: - Queue.HandBack ends a lease without an attempt and returns the attempt the claim counted. Two hand-backs with max_attempts=2 used to strand a never-attempted row as ready-but-exhausted (finding F10). ReleaseLease(ready) still keeps the attempt, because that is how a failed attempt goes back. - Dispose refuses 'expired'; the claim-timeout reaper is its only writer (finding F13). - Queue.PacketPath is unexported. ReadPacket and WritePacket were gated, but an exported map from any fingerprint to its packet file was a read around the gate. The lease holder still gets its own path on the Handle. --- internal/handoff/claim.go | 66 ++++++++++++++++++++-- internal/handoff/handoff_test.go | 92 +++++++++++++++++++++++++++++-- internal/handoff/reaper.go | 2 +- internal/handoff/state_machine.go | 8 ++- internal/scanctl/handoff_test.go | 19 +++---- 5 files changed, 162 insertions(+), 25 deletions(-) diff --git a/internal/handoff/claim.go b/internal/handoff/claim.go index efe8019..da41ff4 100644 --- a/internal/handoff/claim.go +++ b/internal/handoff/claim.go @@ -425,7 +425,7 @@ func (q *Queue) handleFor(ctx context.Context, handoffID int64, leaseToken strin IdempotencyKey: idemKey.String, leaseToken: leaseToken, } - if path, err := q.PacketPath(r.Fingerprint); err == nil { + if path, err := q.packetPath(r.Fingerprint); err == nil { h.PacketPath = path } return h, nil @@ -530,6 +530,11 @@ func (q *Queue) RenewLeaseContext(ctx context.Context, h Handle) (Handle, error) // work is untouched. That is the mechanism by which reclaiming and // re-processing is idempotent: not a lock, a compare-and-swap on the exact // lease. +// +// Releasing to 'ready' here KEEPS the attempt spent: it is how an attempt that +// ran and failed goes back to the ready set (scanctl's ConsumeOne does exactly +// that), and `attempts` counts attempts started. A holder that is giving the +// finding back WITHOUT having attempted it calls HandBack instead. func (q *Queue) ReleaseLease(h Handle, to record.HandoffState) error { return q.ReleaseLeaseContext(context.Background(), h, to) } @@ -574,6 +579,50 @@ func (q *Queue) ReleaseLeaseContext(ctx context.Context, h Handle, to record.Han return nil } +// HandBack ends a lease WITHOUT an attempt: the holder gives the finding back to +// the ready set and the attempt its claim counted is returned. +// +// `attempts` counts attempts STARTED, so the claim increments it, and a crash +// or a failed attempt keeps it spent. A holder that declines the work before +// attempting it (it is shutting down, it is the wrong worker for this finding) +// has not started an attempt. Before HandBack existed the only way out was +// ReleaseLease(ready), which kept the attempt, so two hand-backs with +// max_attempts=2 stranded a row that had never been attempted as +// ready-but-exhausted, forever (the sealing, claims and masking review's +// finding F10). +// +// The cost is stated rather than hidden: a holder that hands back on every +// lease never exhausts the row. A consumer that cannot make progress on a +// finding must release it with a disposition, not hand it back. +func (q *Queue) HandBack(h Handle) error { + return q.HandBackContext(context.Background(), h) +} + +// HandBackContext is HandBack with a caller-supplied context. +func (q *Queue) HandBackContext(ctx context.Context, h Handle) error { + if err := q.checkRecordVersion(ctx, h); err != nil { + return err + } + res, err := q.db.ExecContext(ctx, + `UPDATE handoff + SET state = ?, claimed_by = NULL, lease_expires_at = NULL, updated_at = ?, + attempts = CASE WHEN attempts > 0 THEN attempts - 1 ELSE 0 END + WHERE handoff_id = ? AND state = ? AND claimed_by = ? AND lease_expires_at = ?`, + string(record.HandoffStateReady), formatTime(q.Now()), + h.HandoffID, string(record.HandoffStateLeased), h.WorkerID, h.leaseToken) + if err != nil { + return fmt.Errorf("handoff: handing back row %d: %w", h.HandoffID, err) + } + n, err := res.RowsAffected() + if err != nil { + return fmt.Errorf("handoff: handing back row %d: %w", h.HandoffID, err) + } + if n == 0 { + return q.explainLeaseLost(ctx, h) + } + return nil +} + // HasDynamicEvidence reports whether a DAST half that ended in this state can // have produced a reproduction of a finding. // @@ -695,10 +744,15 @@ func (q *Queue) explainLeaseLost(ctx context.Context, h Handle) error { // directory at all. var ErrNoPacketDir = errors.New("handoff: no PacketDir is configured") -// PacketPath returns where a fingerprint's packet lives. The fingerprint is +// packetPath returns where a fingerprint's packet lives. The fingerprint is // validated as 64 hex first, which is also what stops a crafted value from // escaping PacketDir. -func (q *Queue) PacketPath(fingerprint string) (string, error) { +// +// It is unexported on purpose. Exported, it handed any caller the file for any +// fingerprint, and the file is the payload: a path is a read around +// packetGate. The lease holder still gets its own packet's path on +// Handle.PacketPath, which is the one caller entitled to it. +func (q *Queue) packetPath(fingerprint string) (string, error) { if err := ValidateFingerprint(fingerprint); err != nil { return "", err } @@ -813,7 +867,7 @@ func (q *Queue) WritePacketContext(ctx context.Context, h Handle, data []byte) ( return "", err } fingerprint := h.Fingerprint - final, err := q.PacketPath(fingerprint) + final, err := q.packetPath(fingerprint) if err != nil { return "", err } @@ -874,7 +928,7 @@ func (q *Queue) ReadPacketContext(ctx context.Context, h Handle) ([]byte, error) if err := q.packetGate(ctx, h); err != nil { return nil, err } - path, err := q.PacketPath(h.Fingerprint) + path, err := q.packetPath(h.Fingerprint) if err != nil { return nil, err } @@ -900,7 +954,7 @@ func (q *Queue) ReadPacketContext(ctx context.Context, h Handle) ([]byte, error) // Dropping a packet that is not there is success, because the packet is a // cache and its absence is the desired state. func (q *Queue) DropPacket(fingerprint string) error { - path, err := q.PacketPath(fingerprint) + path, err := q.packetPath(fingerprint) if errors.Is(err, ErrNoPacketDir) { return nil } diff --git a/internal/handoff/handoff_test.go b/internal/handoff/handoff_test.go index 6d69d90..4e7e918 100644 --- a/internal/handoff/handoff_test.go +++ b/internal/handoff/handoff_test.go @@ -10,6 +10,7 @@ import ( "go/token" "os" "path/filepath" + "reflect" "strings" "sync" "testing" @@ -247,9 +248,9 @@ func (f *fixture) state(handoffID int64) record.HandoffState { // would test the gate instead of the sweep. func (f *fixture) packetExists(fingerprint string) bool { f.t.Helper() - path, err := f.q.PacketPath(fingerprint) + path, err := f.q.packetPath(fingerprint) if err != nil { - f.t.Fatalf("PacketPath: %v", err) + f.t.Fatalf("packetPath: %v", err) } _, err = os.Stat(path) if err != nil && !errors.Is(err, os.ErrNotExist) { @@ -1264,8 +1265,8 @@ func TestPacketPathRejectsTraversal(t *testing.T) { "", strings.Repeat("z", 64), } { - if _, err := f.q.PacketPath(bad); err == nil { - t.Errorf("PacketPath(%q) was accepted", bad) + if _, err := f.q.packetPath(bad); err == nil { + t.Errorf("packetPath(%q) was accepted", bad) } } } @@ -1278,8 +1279,8 @@ func TestPacketDirIsOptional(t *testing.T) { if err != nil { t.Fatalf("New: %v", err) } - if _, err := q.PacketPath(fp(16)); !errors.Is(err, ErrNoPacketDir) { - t.Errorf("PacketPath without a dir: err = %v, want ErrNoPacketDir", err) + if _, err := q.packetPath(fp(16)); !errors.Is(err, ErrNoPacketDir) { + t.Errorf("packetPath without a dir: err = %v, want ErrNoPacketDir", err) } if err := q.DropPacket(fp(16)); err != nil { t.Errorf("DropPacket without a dir: %v", err) @@ -1995,3 +1996,82 @@ func TestHasDynamicEvidenceClassifiesEveryDastStatus(t *testing.T) { len(want), len(record.DastStatusValues())) } } + +// TestAVoluntaryHandBackReturnsItsAttempt is the sealing, claims and masking +// review's finding F10. With max_attempts=2, two hand-backs used to leave the +// row ready with attempts=2/2, so the third claim was ErrExhausted although +// nothing had been attempted. HandBack returns the attempt; ReleaseLease(ready), +// which is how a FAILED attempt goes back, keeps it spent. +func TestAVoluntaryHandBackReturnsItsAttempt(t *testing.T) { + f := newFixture(t, Options{MaxAttempts: 2}) + audit := f.sealedAudit() + fingerprint, row := f.enqueue(40, record.ConsumptionClassStaticOnly, audit) + + for i := 1; i <= 3; i++ { + h, err := f.q.Claim(fingerprint, "worker-a") + if err != nil { + t.Fatalf("claim %d after %d hand-backs: %v", i, i-1, err) + } + if h.Attempt != 1 { + t.Errorf("claim %d: Attempt = %d, want 1 (hand-backs must not count)", i, h.Attempt) + } + if err := f.q.HandBack(h); err != nil { + t.Fatalf("hand-back %d: %v", i, err) + } + } + got, err := f.q.Get(row.HandoffID) + if err != nil { + t.Fatal(err) + } + if got.Attempts != 0 || got.State != record.HandoffStateReady || got.ClaimedBy != "" { + t.Fatalf("after three hand-backs: state=%q attempts=%d claimed_by=%q, want ready, 0, none", + got.State, got.Attempts, got.ClaimedBy) + } + + // A failed attempt released to 'ready' keeps the attempt it used. + h, err := f.q.Claim(fingerprint, "worker-b") + if err != nil { + t.Fatal(err) + } + if err := f.q.ReleaseLease(h, record.HandoffStateReady); err != nil { + t.Fatal(err) + } + if got, _ := f.q.Get(row.HandoffID); got.Attempts != 1 { + t.Errorf("ReleaseLease(ready) returned the attempt: attempts=%d, want 1", got.Attempts) + } + + // A hand-back from a lease that was reclaimed is refused, like any stale holder. + if err := f.q.HandBack(h); !errors.Is(err, ErrLeaseLost) { + t.Errorf("HandBack on a released lease: err = %v, want ErrLeaseLost", err) + } +} + +// TestDisposeRefusesExpired is the sealing, claims and masking review's +// finding F13: 'expired' belongs to the claim-timeout reaper, and Dispose used +// to let any caller set it on a row whose deadline had not passed. +func TestDisposeRefusesExpired(t *testing.T) { + f := newFixture(t, Options{}) + audit := f.sealedAudit() + _, row := f.enqueue(41, record.ConsumptionClassStaticOnly, audit) + if err := f.q.Dispose(row.HandoffID, record.HandoffStateExpired); !errors.Is(err, ErrIllegalTransition) { + t.Fatalf("Dispose(expired): err = %v, want ErrIllegalTransition", err) + } + if got := f.state(row.HandoffID); got != record.HandoffStateReady { + t.Errorf("state = %q after a refused Dispose, want ready", got) + } +} + +// TestNoExportedPathToAnArbitraryPacket: an exported function that maps any +// fingerprint to its packet file is a read around packetGate, because the file +// is the payload. Only the lease holder's Handle carries a path. +func TestNoExportedPathToAnArbitraryPacket(t *testing.T) { + typ := reflect.TypeOf(&Queue{}) + for i := 0; i < typ.NumMethod(); i++ { + m := typ.Method(i) + if m.Type.NumIn() == 2 && m.Type.In(1).Kind() == reflect.String && + m.Type.NumOut() == 2 && m.Type.Out(0).Kind() == reflect.String { + t.Errorf("(*Queue).%s maps a string to a string; if that string is a packet path, it "+ + "bypasses packetGate", m.Name) + } + } +} diff --git a/internal/handoff/reaper.go b/internal/handoff/reaper.go index bdb5b9a..89dd459 100644 --- a/internal/handoff/reaper.go +++ b/internal/handoff/reaper.go @@ -345,7 +345,7 @@ func (q *Queue) ExpireClaimTimeoutsContext(ctx context.Context) (ReapReport, err // dropPacketIfPresent unlinks a packet and reports whether one was there. A // Queue with no PacketDir has nothing to drop, which is not an error. func (q *Queue) dropPacketIfPresent(fingerprint string) (bool, error) { - path, err := q.PacketPath(fingerprint) + path, err := q.packetPath(fingerprint) if errors.Is(err, ErrNoPacketDir) { return false, nil } diff --git a/internal/handoff/state_machine.go b/internal/handoff/state_machine.go index 3d1c042..5c3279c 100644 --- a/internal/handoff/state_machine.go +++ b/internal/handoff/state_machine.go @@ -629,6 +629,12 @@ func (q *Queue) EnqueueContext(ctx context.Context, req EnqueueRequest) (Row, er // A leased row is not disposable this way — ReleaseLease is the only exit from // 'leased', because only the lease holder may decide the outcome of its own // attempt. +// +// 'expired' is not disposable this way either. It is the claim-timeout +// terminal state, and the reaper that owns that clock (ExpireClaimTimeouts) is +// its only writer. Through Dispose any caller could expire a finding whose +// deadline had not passed (the sealing, claims and masking review's finding +// F13). func (q *Queue) Dispose(handoffID int64, to record.HandoffState) error { return q.DisposeContext(context.Background(), handoffID, to) } @@ -638,7 +644,7 @@ func (q *Queue) DisposeContext(ctx context.Context, handoffID int64, to record.H if err := CheckTransition(record.HandoffStateReady, to); err != nil { return err } - if to == record.HandoffStateLeased { + if to == record.HandoffStateLeased || to == record.HandoffStateExpired { return &TransitionError{From: record.HandoffStateReady, To: to} } res, err := q.db.ExecContext(ctx, diff --git a/internal/scanctl/handoff_test.go b/internal/scanctl/handoff_test.go index 11ec558..c980300 100644 --- a/internal/scanctl/handoff_test.go +++ b/internal/scanctl/handoff_test.go @@ -1232,10 +1232,11 @@ func sneakyReadable(s record.State, h record.HalfStatus) bool { } // The adapter must not be the only thing standing between a caller and the -// queue: Queue() is the documented escape hatch, and the packet path it -// returns is the same one the Task carries. If those two ever disagree, a -// caller reaching around the adapter reads a different file from one going -// through it. +// queue: Queue() is the documented escape hatch. It no longer maps an +// arbitrary fingerprint to a packet path (that was a read around the packet +// gate; see handoff's TestNoExportedPathToAnArbitraryPacket), so the Task's +// path is checked against the one file it may name, and the bytes written +// through the adapter must read back through it. func TestTheEscapeHatchAgreesWithTheAdapter(t *testing.T) { f := newHFFixture(t, handoff.Options{}) audit := f.sealedAudit() @@ -1245,12 +1246,8 @@ func TestTheEscapeHatchAgreesWithTheAdapter(t *testing.T) { if err != nil { t.Fatalf("Claim: %v", err) } - direct, err := f.c.Queue().PacketPath(fingerprint) - if err != nil { - t.Fatalf("PacketPath: %v", err) - } - if task.PacketPath != direct { - t.Fatalf("Task.PacketPath = %q, Queue().PacketPath = %q", task.PacketPath, direct) + if filepath.Base(task.PacketPath) != fingerprint+".sarif" { + t.Fatalf("Task.PacketPath = %q does not name this finding's packet", task.PacketPath) } body := []byte(`{"version":"2.1.0","runs":[]}`) @@ -1269,7 +1266,7 @@ func TestTheEscapeHatchAgreesWithTheAdapter(t *testing.T) { if err := f.c.ReleaseLease(task, record.HandoffStateValidated); err != nil { t.Fatalf("ReleaseLease: %v", err) } - if _, err := os.Stat(direct); !errors.Is(err, os.ErrNotExist) { + if _, err := os.Stat(task.PacketPath); !errors.Is(err, os.ErrNotExist) { t.Fatalf("stat packet after a terminal disposition = %v, want os.ErrNotExist", err) } } From 566f234abf7e7efb4a83d078a3dd91c08d40f984 Mon Sep 17 00:00:00 2001 From: "Tom D. Snyder" Date: Sat, 3 Oct 2026 10:18:43 -0400 Subject: [PATCH 2/3] Record: name the trust validation step, and carry the licence note inside the record anvil/trust.validationStep names the validation behind every 'verified' label in a result. It is required, non-blank, exactly when a label is 'verified' and refused otherwise, in ValidateResultTrust and in the wire schema (for the default, checked with jsonschema 4.26.0). Record emission used to carry the step and the licence manual-override note out of band on Emission; both now travel in the record, and Emission keeps only the feed SLO the contract has no field for. Emission names the step only when a verified string travels in the result, which the new check caught. --- internal/record/CONTRACT.md | 18 ++++++ internal/record/contract.go | 57 +++++++++++++++++++ internal/record/contract_test.go | 66 ++++++++++++++++++++++ internal/record/lanea/emit.go | 86 ++++++++++++----------------- internal/record/lanea/emit_test.go | 27 ++++----- internal/record/readpath_test.go | 6 +- schemas/anvil-record-v1.schema.json | 11 +++- 7 files changed, 202 insertions(+), 69 deletions(-) diff --git a/internal/record/CONTRACT.md b/internal/record/CONTRACT.md index 80fca7f..83fc27f 100644 --- a/internal/record/CONTRACT.md +++ b/internal/record/CONTRACT.md @@ -658,3 +658,21 @@ skipped: `SpecHarvest{Outcome: SpecHarvestSkipped}` marshals `files` as `null`, the schema refused while the Go validator accepted. The `harvest_skipped` branch now admits `null` and `[]` alike (they mean the same thing when there is no list to have been written down), and the `harvest_ran` branch narrows back to an array, which is where the distinction is load-bearing. + +--- + +## Amendment 2026-10-03 — the contract gaps closed before the freeze (plan node contractgaps) + +Six open items were carried into Phase 4. Each now either lands with a test or is stated here as a +deliberate limit. + +| Item | Outcome | Where it is held | +|---|---|---| +| No slot for the licence manual-override note | **Closed.** The slot (`anvil/advisory.licenseManualNote`) was added on 2026-08-23, but record emission still carried the note out of band on `Emission`. Emission now writes it into the record, beside the excerpt it licenses, and `Emission` no longer has the field. | `internal/record/lanea/emit_test.go` (the seven Lane A fields, read from the serialised record) | +| No trust-validation step | **Closed.** `anvil/trust.validationStep` names the validation behind every `verified` label in a result — `default`, any `fields` entry, and the inline trust of an advisory excerpt, a licence note or a reproduction span. It is required, non-blank, exactly when some label is `verified`, and refused when none is. Emission fills it only when a `verified` string travels in the result. | `ValidateResultTrust`; `TestVerifiedNamesItsValidationStep`; the wire schema's `trustAssertion` (`if default is verified then validationStep is required`, checked with `jsonschema` 4.26.0 on 2026-10-03) | +| An unpinned payload codec | **Closed.** `audit_record.payload` is zstd from `github.com/klauspost/compress` v1.20.1 (pure Go, BSD-3-Clause), pinned in `go.sum`; its three applicable licence bodies are archived and re-hashed (`third_party/klauspost-compress/PIN.md`). `payload_sha256` is the SHA-256 of the **canonical JSON**, not of the compressed bytes, so it identifies the record whatever the encoder. Decoding refuses a payload over 256 MiB decompressed, a corrupt frame, and bytes whose hash is not the row's. | `internal/store/payload.go`, `payload_test.go` | +| A voluntary lease hand-back burned an attempt | **Closed.** `Queue.HandBack` ends a lease without an attempt and returns the one the claim counted. `ReleaseLease(ready)` still keeps it, because that is how a failed attempt goes back (scanctl's `ConsumeOne`). Stated limit: a holder that hands back on every lease never exhausts the row. | `TestAVoluntaryHandBackReturnsItsAttempt` | +| `expired` settable outside the reaper | **Closed.** `Dispose` refuses `expired`; `ExpireClaimTimeouts` is its only writer. | `TestDisposeRefusesExpired` | +| An exported, ungated packet path | **Closed.** `ReadPacket` and `WritePacket` were already gated; `Queue.PacketPath(fingerprint)` still mapped any fingerprint to its file, which is a read around the gate. It is unexported. A lease holder still receives its own packet's path on the `Handle`. `DropPacket` stays exported: it only removes a regenerable cache. | `TestNoExportedPathToAnArbitraryPacket` | + +Every new check was seen failing with its fix reverted before it was trusted. diff --git a/internal/record/contract.go b/internal/record/contract.go index 1ad9cae..19e0b0d 100644 --- a/internal/record/contract.go +++ b/internal/record/contract.go @@ -51,6 +51,7 @@ package record import ( "fmt" + "sort" "strconv" "strings" "time" @@ -1804,6 +1805,51 @@ type TrustAssertion struct { // returned by Result.ExternalStringPointers must appear here or be // covered by an untrusted Default. Fields map[string]Trust `json:"fields,omitempty"` + + // ValidationStep NAMES the explicit validation step behind every + // `verified` label in this result — Default, any entry in Fields, and the + // inline trust of an advisory excerpt, a licence note or a reproduction's + // evidence span. TrustVerified means "originated outside Anvil AND passed + // an explicit validation step that is named in the record"; without this + // slot the record had nowhere to name it, so a `verified` label published + // the claim without the thing that makes it mean anything (record + // emission's deviation 4, closed by plan node contractgaps). + // + // Required, and non-blank, exactly when some label in the result is + // `verified`; refused otherwise, because a step named for bytes nobody + // claims were validated is a statement about nothing. One result names one + // step: every producer today takes a result's external text from one + // source, and a result that needs two steps is refused rather than given a + // second slot nobody has designed. + ValidationStep string `json:"validationStep,omitempty"` +} + +// verifiedLabels lists where a result claims `verified`, as JSON Pointers +// relative to the result, for ValidateResultTrust's error messages. +func (r *Result) verifiedLabels() []string { + var at []string + if r.Properties.Trust.Default == TrustVerified { + at = append(at, "/properties/anvil~1trust/default") + } + for ptr, t := range r.Properties.Trust.Fields { + if t == TrustVerified { + at = append(at, "/properties/anvil~1trust/fields/"+strings.ReplaceAll(strings.ReplaceAll(ptr, "~", "~0"), "/", "~1")) + } + } + inline := func(ptr string, s *TrustedString) { + if s != nil && s.Trust == TrustVerified { + at = append(at, ptr) + } + } + if a := r.Properties.Advisory; a != nil { + inline("/properties/anvil~1advisory/excerpt/trust", a.Excerpt) + inline("/properties/anvil~1advisory/licenseManualNote/trust", a.LicenseManualNote) + } + if rp := r.Properties.Repro; rp != nil { + inline("/properties/anvil~1repro/observedSignal/match/trust", rp.ObservedSignal.Match) + } + sort.Strings(at) + return at } // DetectorRef identifies the model and prompt behind a finding. @@ -2331,6 +2377,17 @@ func ValidateResultTrust(r *Result) error { if err := ValidateTrust(string(r.Properties.Trust.Default)); err != nil { return err } + verified := r.verifiedLabels() + step := r.Properties.Trust.ValidationStep + switch { + case len(verified) > 0 && strings.TrimSpace(step) == "": + return fmt.Errorf("record: %v claim %q but anvil/trust.validationStep names no validation step; "+ + "%q means the bytes passed an explicit validation step that is NAMED IN THE RECORD", + verified, TrustVerified, TrustVerified) + case len(verified) == 0 && step != "": + return fmt.Errorf("record: anvil/trust.validationStep is %q but nothing in the result is %q; "+ + "a step named for bytes nobody claims were validated states nothing", step, TrustVerified) + } for ptr, t := range r.Properties.Trust.Fields { if err := ValidateTrust(string(t)); err != nil { return fmt.Errorf("anvil/trust.fields[%q]: %w", ptr, err) diff --git a/internal/record/contract_test.go b/internal/record/contract_test.go index 6424412..1b801b4 100644 --- a/internal/record/contract_test.go +++ b/internal/record/contract_test.go @@ -752,6 +752,9 @@ func TestLicenseManualNoteRefusesTheAbsentValueInLegitimateClothes(t *testing.T) r.Properties.Advisory.LicenseManualNote = &TrustedString{ Text: "Redistribution permitted with attribution.", Trust: trust, } + if trust == TrustVerified { + r.Properties.Trust.ValidationStep = "signature-checked feed snapshot" + } if err := r.validate(HalfSast); err != nil { t.Errorf("a note classified %q was refused: %v", trust, err) } @@ -767,3 +770,66 @@ func TestLicenseManualNoteRefusesTheAbsentValueInLegitimateClothes(t *testing.T) } }) } + +// TestVerifiedNamesItsValidationStep is plan node contractgaps' trust-validation +// slot. TrustVerified means "passed an explicit validation step that is named +// in the record", so every `verified` label — default, per-field or inline — +// needs anvil/trust.validationStep, and a step with nothing verified is refused. +func TestVerifiedNamesItsValidationStep(t *testing.T) { + const step = "signature-checked feed snapshot" + cases := []struct { + name string + mutate func(r *Result) + wantErr bool + }{ + {"nothing verified, no step", func(r *Result) {}, false}, + {"nothing verified, a step anyway", func(r *Result) { r.Properties.Trust.ValidationStep = step }, true}, + {"verified excerpt, no step", func(r *Result) { + r.Properties.Advisory.Excerpt = &TrustedString{Text: "x", Trust: TrustVerified} + }, true}, + {"verified excerpt, blank step", func(r *Result) { + r.Properties.Advisory.Excerpt = &TrustedString{Text: "x", Trust: TrustVerified} + r.Properties.Trust.ValidationStep = " " + }, true}, + {"verified excerpt, named step", func(r *Result) { + r.Properties.Advisory.Excerpt = &TrustedString{Text: "x", Trust: TrustVerified} + r.Properties.Trust.ValidationStep = step + }, false}, + {"verified licence note, no step", func(r *Result) { + r.Properties.Advisory.LicenseManualNote = &TrustedString{Text: "x", Trust: TrustVerified} + }, true}, + {"verified default, no step", func(r *Result) { r.Properties.Trust.Default = TrustVerified }, true}, + {"verified field, no step", func(r *Result) { + r.Properties.Trust.Fields = map[string]Trust{"/message/text": TrustVerified} + }, true}, + {"verified field, named step", func(r *Result) { + r.Properties.Trust.Fields = map[string]Trust{"/message/text": TrustVerified} + r.Properties.Trust.ValidationStep = step + }, false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + r := chAdvisoryResult() + c.mutate(r) + err := ValidateResultTrust(r) + if c.wantErr && err == nil { + t.Error("accepted") + } + if !c.wantErr && err != nil { + t.Errorf("refused: %v", err) + } + }) + } + + // The step reaches the wire. + r := chAdvisoryResult() + r.Properties.Trust.Default = TrustVerified + r.Properties.Trust.ValidationStep = step + raw, err := json.Marshal(r) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(raw), `"validationStep":"`+step+`"`) { + t.Errorf("validationStep did not reach the serialised bytes: %s", raw) + } +} diff --git a/internal/record/lanea/emit.go b/internal/record/lanea/emit.go index 3dab995..e6475d0 100644 --- a/internal/record/lanea/emit.go +++ b/internal/record/lanea/emit.go @@ -39,7 +39,7 @@ // parse_degraded -> Result.Properties.Advisory.ParseDegraded // anvil/trust -> Result.Properties.Trust (+ the excerpt's own) // license_spdx -> Result.Properties.Advisory.LicenseSpdx -// license_manual_note -> Emission.LicenseManualNote ** see DEVIATION 1 ** +// license_manual_note -> Result.Properties.Advisory.LicenseManualNote // // =========================================================================== // 1. remediable_by_agent IS FALSE FOR EVERY HOST FINDING. ALWAYS. @@ -154,18 +154,11 @@ // FOUR DEVIATIONS FROM THE PACKET, REPORTED RATHER THAN APPLIED QUIETLY // =========================================================================== // -// 1. license_manual_note HAS NO SLOT IN THE FROZEN RECORD. record's -// AdvisoryContext carries LicenseSpdx and nothing else; run-level -// AdvisorySnapshot carries no licence field either. The spine's -// compliance mechanics require the manual-override field carrying the -// quoted operative sentence — precisely for the sources whose SPDX id is -// NONE, NOASSERTION or a LicenseRef-, which is where the SPDX id alone -// establishes nothing. Every slot it could be smuggled into is worse than -// no slot: LicenseSpdx is an identifier field and prose corrupts it, and -// Reasoning is anvil_generated while the note is a QUOTATION from a -// publisher's LICENSE file. So it travels on Emission, typed as a -// record.TrustedString, and the gap is reported to the orchestrator. -// Dropping it silently would lose a compliance obligation. +// 1. CLOSED. license_manual_note had no slot in the frozen record, so it +// travelled out of band on Emission. The 2026-08-23 contract amendment +// added AdvisoryContext.LicenseManualNote, and plan node contractgaps +// moved the note into it: it now travels inside the record, beside the +// excerpt it licenses, as a record.TrustedString. // // 2. Result.Level IS LEFT UNSET. Severity mapping (advisory severity or CVSS // -> SARIF level) is a vocabulary nobody has been assigned and is not one @@ -181,16 +174,12 @@ // the same record drift handling says the parser did not fully understand. The // finding is still emitted, as report-only. // -// 4. `verified` HAS NO SLOT TO NAME ITS VALIDATION STEP IN. record.Trust -// defines TrustVerified as "the bytes originated outside Anvil AND passed -// an explicit validation step THAT IS NAMED IN THE RECORD ... Never a -// default", and the frozen AdvisoryContext has nowhere to put the step's -// name. Passing `verified` through unaccompanied would publish the label -// without the thing that makes it mean anything. So a row asserting -// `verified` without naming its step is REFUSED here -// (RefusalTrustValidationStep), and the named step travels on -// Emission.TrustValidationStep — the same treatment, and the same reported -// record-contract gap, as license_manual_note in deviation 1. +// 4. CLOSED. `verified` had no slot to name its validation step in, so the +// step travelled on Emission. Plan node contractgaps added +// record.TrustAssertion.ValidationStep, and the step now goes there. A +// row asserting `verified` without naming its step is still REFUSED here +// (RefusalTrustValidationStep) before the record's own validator, which +// now refuses the same shape, ever sees it. package lanea @@ -445,7 +434,8 @@ type AdvisoryRow struct { // that value as "passed an explicit validation step that is named in the // record ... Never a default", so the label without the name is not the // value the contract describes. It must be EMPTY when Trust is - // untrusted. There is no cache column for it today; see deviation 4. + // untrusted. It is written to record.TrustAssertion.ValidationStep; the + // cache has no column for it yet, so a caller fills it from its own source. TrustValidationStep string // AsOf is `advisory.as_of`: THE CACHE WATERMARK. It is when this data @@ -538,39 +528,23 @@ type Emitter struct { // Output // --------------------------------------------------------------------------- -// Emission is one emitted finding: the canonical record.Result, plus the two -// Lane-A-owned facts the frozen record contract has no slot for. +// Emission is one emitted finding: the canonical record.Result, plus the one +// Lane-A-owned fact the record contract has no slot for. // // IT IS NOT A PARALLEL FINDING STRUCT. It carries no fingerprint, no package // identity, no advisory identity and no copy of any field Result already -// holds. Everything about the finding is read from Result; these two exist -// because the contract has nowhere to put them and dropping them would lose, -// respectively, a compliance obligation and the only machine-readable -// statement that a feed missed its SLO. Both are reported to the orchestrator -// as record-contract gaps rather than fixed here — this step must not write to -// the record schema. +// holds. The licence note and the trust validation step used to travel here +// too; both now have slots in the record (deviations 1 and 4). The SLO stays +// because it is the only machine-readable statement that a feed missed its +// SLO, and the contract has no field for a feed's SLO. type Emission struct { // Result is the canonical record. Everything about the finding is here. Result record.Result `json:"result"` - // LicenseManualNote is the spine's manual-override field: the - // quoted operative sentence from the publisher's own licence text, - // required whenever the SPDX id is NONE, NOASSERTION or a LicenseRef-. - // It is a QUOTATION FROM OUTSIDE ANVIL and carries its own trust inline. - // Nil when the row states none. - LicenseManualNote *record.TrustedString `json:"licenseManualNote,omitempty"` - // FreshnessSLOSeconds is the feed's SLO, carried so a consumer can // evaluate BeyondFreshnessSLO without holding the feed table. Zero when // the caller stated none. FreshnessSLOSeconds int `json:"freshnessSloSeconds"` - - // TrustValidationStep names the explicit validation step the advisory - // row's bytes passed, and is non-empty exactly when the excerpt and the - // licence note are classified `verified`. See deviation 4: the frozen - // record has no slot for it, and `verified` without it is not the value - // record.Trust defines. - TrustValidationStep string `json:"trustValidationStep,omitempty"` } // RemediableByAgent is the CLAMPED answer, never a copy. @@ -1108,6 +1082,8 @@ func (e Emitter) Emit(m match.MatchResult, a AdvisoryRow) (Emission, error) { Fields: map[string]record.Trust{ reasoningPointer: record.TrustAnvilGenerated, }, + // Set below, and only when a `verified` string travels + // in this result; see deviation 4. }, Advisory: &record.AdvisoryContext{ IDs: []string{advisoryID}, @@ -1120,10 +1096,11 @@ func (e Emitter) Emit(m match.MatchResult, a AdvisoryRow) (Emission, error) { // caller's assembly instant minus that watermark — and NOT // the row's publisher-lag column, which measures something // else. See the package header, section 3. - AsOf: a.AsOf.UTC(), - StalenessSeconds: staleness, - ParseDegraded: a.ParseDegraded, - Excerpt: excerpt(a), + AsOf: a.AsOf.UTC(), + StalenessSeconds: staleness, + ParseDegraded: a.ParseDegraded, + Excerpt: excerpt(a), + LicenseManualNote: manualNote(a), }, Risk: riskOf(a), }, @@ -1131,6 +1108,13 @@ func (e Emitter) Emit(m match.MatchResult, a AdvisoryRow) (Emission, error) { if loc := manifestLocation(m); loc != nil { res.Locations = []record.Location{*loc} } + // The step names the validation the row's bytes passed, so it goes into + // the record only when some of those bytes do: an excerpt or a licence + // note. A verified row with neither carries no verified string here, and + // the record refuses a step that names nothing. + if adv := res.Properties.Advisory; adv.Excerpt != nil || adv.LicenseManualNote != nil { + res.Properties.Trust.ValidationStep = step + } // The contract's own validator, applied before this leaves the function. // It re-checks the host rule from the other side (it refuses a remediable @@ -1144,9 +1128,7 @@ func (e Emitter) Emit(m match.MatchResult, a AdvisoryRow) (Emission, error) { return Emission{ Result: res, - LicenseManualNote: manualNote(a), FreshnessSLOSeconds: a.FreshnessSLOSeconds, - TrustValidationStep: step, }, nil } diff --git a/internal/record/lanea/emit_test.go b/internal/record/lanea/emit_test.go index b3b558e..e8e53c0 100644 --- a/internal/record/lanea/emit_test.go +++ b/internal/record/lanea/emit_test.go @@ -1175,16 +1175,17 @@ func TestEveryRecordFromTheComparatorCarriesTheSevenLaneAFields(t *testing.T) { if _, err := jsonAt(raw, "properties/anvil~1advisory/licenseSpdx"); err != nil { t.Errorf("result %d: %v", i, err) } - // 7. license_manual_note, on the crossing artifact. + // 7. license_manual_note, inside the record beside the excerpt. + note := em.Result.Properties.Advisory.LicenseManualNote if src.LicenseManualNote != "" { - if em.LicenseManualNote == nil || em.LicenseManualNote.Text != src.LicenseManualNote { - t.Errorf("result %d lost the licence manual note", i) + if note == nil || note.Text != src.LicenseManualNote { + t.Fatalf("result %d lost the licence manual note", i) } - if em.LicenseManualNote.Trust == record.TrustAnvilGenerated { + if note.Trust == record.TrustAnvilGenerated { t.Errorf("result %d labels a quoted licence sentence as Anvil's own", i) } - assertJSONString(t, em, "licenseManualNote/text", src.LicenseManualNote) - } else if em.LicenseManualNote != nil { + assertJSONString(t, em.Result, "properties/anvil~1advisory/licenseManualNote/text", src.LicenseManualNote) + } else if note != nil { t.Errorf("result %d invented a licence manual note", i) } @@ -1602,10 +1603,10 @@ func TestVerifiedTrustMustNameItsValidationStep(t *testing.T) { named.Trust = record.TrustVerified named.TrustValidationStep = fixtureValidationStep em := mustEmit(t, hostMatch(), named) - if em.TrustValidationStep != fixtureValidationStep { - t.Fatalf("the validation step was lost: %q", em.TrustValidationStep) + if got := em.Result.Properties.Trust.ValidationStep; got != fixtureValidationStep { + t.Fatalf("the validation step was lost: %q", got) } - assertJSONString(t, em, "trustValidationStep", fixtureValidationStep) + assertJSONString(t, em.Result, "properties/anvil~1trust/validationStep", fixtureValidationStep) if em.Result.Properties.Advisory.Excerpt.Trust != record.TrustVerified { t.Fatalf("the excerpt is %q, not the row's own trust", em.Result.Properties.Advisory.Excerpt.Trust) @@ -1614,11 +1615,11 @@ func TestVerifiedTrustMustNameItsValidationStep(t *testing.T) { // An untrusted row names nothing, and the key is absent from the bytes // rather than present and empty. plain := mustEmit(t, hostMatch(), hostRow()) - if plain.TrustValidationStep != "" { - t.Errorf("an untrusted row produced the validation step %q", plain.TrustValidationStep) + if got := plain.Result.Properties.Trust.ValidationStep; got != "" { + t.Errorf("an untrusted row produced the validation step %q", got) } - if _, err := jsonAt(marshal(t, plain), "trustValidationStep"); err == nil { - t.Error("an untrusted emission carries a trustValidationStep key") + if _, err := jsonAt(marshal(t, plain.Result), "properties/anvil~1trust/validationStep"); err == nil { + t.Error("an untrusted emission carries a validationStep key") } } diff --git a/internal/record/readpath_test.go b/internal/record/readpath_test.go index 8d280fd..03ee0a7 100644 --- a/internal/record/readpath_test.go +++ b/internal/record/readpath_test.go @@ -2916,8 +2916,10 @@ func gateUngatedAllowlist() map[string]gateExemption { "Result.ExternalStringPointers": {body: "b598635db55a205e", reason: "a pure accessor on a Result the caller already holds. " + "It cannot obtain one: whoever calls it got the Result from somewhere, and that " + "somewhere is what the gate covers."}, - "ValidateResultTrust": {body: "45d470da65ff8018", reason: "a validator over one caller-held Result, returning only an error. " + - "Re-read 2026-09-29: the body changed only in the wording of one error message."}, + "ValidateResultTrust": {body: "bbff534e61dffe8b", reason: "a validator over one caller-held Result, returning only an error. " + + "Re-read 2026-10-03 after plan node contractgaps added the validation-step check: the new " + + "branch reads the caller's own Result through verifiedLabels and puts JSON Pointers and the " + + "step name in its error, never a result's contents."}, "IsHostFinding": {body: "eaf63949394f43ee", reason: "a pure predicate over one caller-held Result. It reads two enum fields " + "and returns a bool."}, "Correlate": {body: "2f5772b9f31ae65b", reason: "the correlation engine. It is handed two []Result by the PRODUCER, " + diff --git a/schemas/anvil-record-v1.schema.json b/schemas/anvil-record-v1.schema.json index 65c8f4a..ca0149a 100644 --- a/schemas/anvil-record-v1.schema.json +++ b/schemas/anvil-record-v1.schema.json @@ -615,8 +615,15 @@ "required": ["default"], "properties": { "default": { "$ref": "#/$defs/trust" }, - "fields": { "type": "object", "additionalProperties": { "$ref": "#/$defs/trust" } } - } + "fields": { "type": "object", "additionalProperties": { "$ref": "#/$defs/trust" } }, + "validationStep": { + "description": "Names the explicit validation step behind every `verified` label in this result (default, fields, and the inline trust of an advisory excerpt, licence note or reproduction span). Required exactly when some label in the result is `verified`; the Go validator enforces that across the whole result, and this schema enforces it for `default`.", + "type": "string", + "pattern": "\\S" + } + }, + "if": { "properties": { "default": { "const": "verified" } }, "required": ["default"] }, + "then": { "required": ["validationStep"] } }, "advisoryContext": { From 4705de6d3ed6d49d71960cdaaa85982a481fe57a Mon Sep 17 00:00:00 2001 From: "Tom D. Snyder" Date: Sat, 3 Oct 2026 10:18:51 -0400 Subject: [PATCH 3/3] Store: a pinned pure-Go zstd codec for the audit payload audit_record.payload has been specified as zstd(canonical SARIF JSON) since the store schema was written, but nothing wrote it and no library was chosen. EncodePayload and DecodePayload use github.com/klauspost/compress v1.20.1 (pure Go, BSD-3-Clause), added on 2026-10-03 with the owner's approval. payload_sha256 is the SHA-256 of the canonical JSON, not of the compressed bytes, so it identifies the record whatever the encoder. Decoding refuses a corrupt frame, a hash mismatch and anything over 256 MiB decompressed; the bomb test builds a real 300 MiB payload that compresses to 33 KB. Encoding is deterministic. The three licence bodies that apply to the linked packages are archived in third_party/klauspost-compress/ with PIN.md, and tests re-hash them and fail if go.mod or go.sum moves the pin. Gate 3 classifies the zstd import as inert: its dependency graph holds no network package. --- THIRD-PARTY-LICENSES.md | 9 +- go.mod | 5 +- go.sum | 2 + internal/dast/authz/egress_chokepoint_test.go | 4 + internal/store/payload.go | 108 +++++++ internal/store/payload_test.go | 149 +++++++++ third_party/klauspost-compress/LICENSE | 304 ++++++++++++++++++ third_party/klauspost-compress/PIN.md | 41 +++ .../internal-snapref-LICENSE | 27 ++ .../zstd-internal-xxhash-LICENSE.txt | 22 ++ 10 files changed, 667 insertions(+), 4 deletions(-) create mode 100644 internal/store/payload.go create mode 100644 internal/store/payload_test.go create mode 100644 third_party/klauspost-compress/LICENSE create mode 100644 third_party/klauspost-compress/PIN.md create mode 100644 third_party/klauspost-compress/internal-snapref-LICENSE create mode 100644 third_party/klauspost-compress/zstd-internal-xxhash-LICENSE.txt diff --git a/THIRD-PARTY-LICENSES.md b/THIRD-PARTY-LICENSES.md index caf8f90..b29b06a 100644 --- a/THIRD-PARTY-LICENSES.md +++ b/THIRD-PARTY-LICENSES.md @@ -22,7 +22,7 @@ go list -m -f '{{.Dir}}' modernc.org/sqlite | xargs -I{} sha256sum {}/LICENSE ## Go module dependencies — compiled into `anvil` and `anvil-dast` -All ten are BSD-3-Clause or MIT. **No copyleft, no unclear licence, no `NOASSERTION` in the set.** All +All eleven are BSD-3-Clause or MIT. **No copyleft, no unclear licence, no `NOASSERTION` in the set.** All are Apache-2.0 compatible in the inbound direction. | Module | Version | SPDX | Copyright holder | LICENSE file SHA-256 | @@ -37,9 +37,12 @@ are Apache-2.0 compatible in the inbound direction. | `github.com/dustin/go-humanize` | v1.0.1 | MIT | Dustin Sallings (2005–2008) | `a973b4498c13eb74baa2a8e5c351426a6826f2fcdd909916dbe53ee2e755fd71` | | `github.com/mattn/go-isatty` | v0.0.24 | MIT | Yasuhiro Matsumoto | `08eab1118c80885fa1fa6a6dd7303f65a379fcb3733e063d20d1bbc2c76e6fa1` | | `github.com/ncruces/go-strftime` | v1.0.0 | MIT | Nuno Cruces (2022) | `38ae43959daf953a393a585b2988672cb65a5a541aca0d0be5e72595a0a16883` | +| `github.com/klauspost/compress` | v1.20.1 | BSD-3-Clause; MIT for `zstd/internal/xxhash` | The Go Authors (2012), Klaus Post (2019); Caleb Spare (2016) for xxhash; The Snappy-Go Authors (2011) for `internal/snapref` | `0d9e582ee4bff57bf1189c9e514e6da7ce277f9cd3bc2d488b22fbb39a6d87cf` (all three bodies in `third_party/klauspost-compress/`) | -Only `modernc.org/sqlite` is a direct requirement; the other nine arrive through it. All nine are -therefore pinned by `go.sum` and move only when the sqlite pin moves. +`modernc.org/sqlite` and `github.com/klauspost/compress` are the direct requirements; the other nine +arrive through sqlite, are pinned by `go.sum`, and move only when the sqlite pin moves. The compress module +is the audit payload's zstd codec, added 2026-10-03; `third_party/klauspost-compress/PIN.md` records the +three licence bodies that apply to the packages it links, and a test re-hashes them. ### BSD-3-Clause — required notice diff --git a/go.mod b/go.mod index daba57d..e60c929 100644 --- a/go.mod +++ b/go.mod @@ -2,7 +2,10 @@ module github.com/Susquehanna-Syntax/Anvil go 1.26.5 -require modernc.org/sqlite v1.56.0 +require ( + github.com/klauspost/compress v1.20.1 + modernc.org/sqlite v1.56.0 +) require ( github.com/dustin/go-humanize v1.0.1 // indirect diff --git a/go.sum b/go.sum index 1932692..eff1c75 100644 --- a/go.sum +++ b/go.sum @@ -6,6 +6,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ= +github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= diff --git a/internal/dast/authz/egress_chokepoint_test.go b/internal/dast/authz/egress_chokepoint_test.go index a8f26e7..24a51b1 100644 --- a/internal/dast/authz/egress_chokepoint_test.go +++ b/internal/dast/authz/egress_chokepoint_test.go @@ -199,6 +199,10 @@ var inertImports = map[string]string{ "unicode/utf8": "rune encoding", "modernc.org/sqlite": "the pure-Go, file-backed SQLite driver the spine's Go control-plane decision mandates; no network protocol", "golang.org/x/sys/cpu": "CPU feature detection", + // Checked 2026-10-03: `go list -deps` of this package names no net, + // net/*, crypto/tls or os/exec package; it compresses byte slices it is + // handed (internal/store's audit payload codec). + "github.com/klauspost/compress/zstd": "the pinned pure-Go zstd codec for audit_record.payload; byte slices in, byte slices out", } // inertSymbols is the single, narrow escape hatch: a package that is NOT inert diff --git a/internal/store/payload.go b/internal/store/payload.go new file mode 100644 index 0000000..49ba4d4 --- /dev/null +++ b/internal/store/payload.go @@ -0,0 +1,108 @@ +// This file is the audit payload codec: what `audit_record.payload` and +// `audit_record.payload_sha256` hold, and the one way to produce and read them. +// +// THE CODEC IS zstd, FROM github.com/klauspost/compress v1.20.1 (pure Go, no +// cgo, BSD-3-Clause; third_party/klauspost-compress/PIN.md records the licence +// bodies read and their hashes). The schema has said "zstd(canonical SARIF +// JSON)" since the store schema was written; no writer existed until plan node +// contractgaps, so the library was never chosen. It is pinned in go.sum, and +// TestThePayloadCodecIsThePinnedModule fails if the build links another +// version. +// +// WHAT THE HASH COVERS. payload_sha256 is the SHA-256 of the CANONICAL JSON, +// not of the compressed bytes. It is "proof of what was handed over" and it +// outlives the payload (the reaper NULLs payload at deadline_at and keeps the +// hash), so it has to identify the record itself: a hash of the compressed +// bytes would change with the encoder level or the library version while the +// record stayed the same. The canonical JSON is encoding/json's output for the +// record, which is deterministic for a struct (fixed field order, sorted map +// keys); the caller marshals, this file never re-marshals. +// +// WHAT DECODING REFUSES. A payload that does not decompress, decompresses to +// more than MaxPayloadBytes, or decompresses to bytes whose hash is not the +// stored one. The size bound is the decompression-bomb guard: a few kilobytes +// of zstd can claim gigabytes. + +package store + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + + "github.com/klauspost/compress/zstd" +) + +// MaxPayloadBytes bounds one decompressed audit payload: 256 MiB. GitHub's own +// SARIF upload limit is 10 MB compressed, and a record over this bound is a +// defect upstream of the store, not a payload to admit. +const MaxPayloadBytes = 256 << 20 + +// ErrPayloadDigest means the decompressed payload is not the record its row's +// payload_sha256 names. +var ErrPayloadDigest = errors.New("store: payload does not match payload_sha256") + +// The encoder and decoder are stateless for EncodeAll/DecodeAll and safe for +// concurrent use; one of each serves the process. Concurrency 1 keeps the +// encoder's output a function of its input alone. +var ( + payloadEncoder = mustEncoder() + payloadDecoder = mustDecoder() +) + +func mustEncoder() *zstd.Encoder { + enc, err := zstd.NewWriter(nil, + zstd.WithEncoderLevel(zstd.SpeedDefault), + zstd.WithEncoderConcurrency(1), + zstd.WithEncoderCRC(true)) + if err != nil { + panic(fmt.Sprintf("store: building the payload encoder: %v", err)) + } + return enc +} + +func mustDecoder() *zstd.Decoder { + dec, err := zstd.NewReader(nil, + zstd.WithDecoderConcurrency(1), + zstd.WithDecoderMaxMemory(MaxPayloadBytes), + zstd.WithDecoderMaxWindow(MaxPayloadBytes)) + if err != nil { + panic(fmt.Sprintf("store: building the payload decoder: %v", err)) + } + return dec +} + +// EncodePayload compresses a record's canonical JSON for audit_record.payload +// and returns it with the payload_sha256 of the canonical JSON. +func EncodePayload(canonicalJSON []byte) (payload []byte, sha256Hex string, err error) { + if len(canonicalJSON) == 0 { + return nil, "", errors.New("store: refusing to encode an empty payload") + } + if len(canonicalJSON) > MaxPayloadBytes { + return nil, "", fmt.Errorf("store: payload is %d bytes, over MaxPayloadBytes (%d)", + len(canonicalJSON), MaxPayloadBytes) + } + sum := sha256.Sum256(canonicalJSON) + return payloadEncoder.EncodeAll(canonicalJSON, nil), hex.EncodeToString(sum[:]), nil +} + +// DecodePayload decompresses audit_record.payload and checks it against the +// row's payload_sha256. It returns the canonical JSON or an error, never +// bytes that failed either check. +func DecodePayload(payload []byte, wantSHA256Hex string) ([]byte, error) { + out, err := payloadDecoder.DecodeAll(payload, nil) + if err != nil { + return nil, fmt.Errorf("store: decompressing the audit payload: %w", err) + } + if len(out) > MaxPayloadBytes { + return nil, fmt.Errorf("store: payload decompresses to %d bytes, over MaxPayloadBytes", len(out)) + } + sum := sha256.Sum256(out) + want, err := hex.DecodeString(wantSHA256Hex) + if err != nil || len(want) != sha256.Size || !bytes.Equal(sum[:], want) { + return nil, ErrPayloadDigest + } + return out, nil +} diff --git a/internal/store/payload_test.go b/internal/store/payload_test.go new file mode 100644 index 0000000..3a18d01 --- /dev/null +++ b/internal/store/payload_test.go @@ -0,0 +1,149 @@ +package store + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "errors" + "os" + "path/filepath" + "strings" + "testing" +) + +const sampleRecord = `{"version":"2.1.0","runs":[{"results":[{"ruleId":"anvil.sca/v1","message":{"text":"x"}}]}]}` + +func TestPayloadRoundTripsAndHashesTheCanonicalJSON(t *testing.T) { + in := []byte(strings.Repeat(sampleRecord, 50)) + payload, sum, err := EncodePayload(in) + if err != nil { + t.Fatal(err) + } + want := sha256.Sum256(in) + if sum != hex.EncodeToString(want[:]) { + t.Fatalf("payload_sha256 = %s, want the SHA-256 of the canonical JSON", sum) + } + // zstd's frame magic, little-endian 0xFD2FB528: the column holds zstd and + // nothing else. + if !bytes.HasPrefix(payload, []byte{0x28, 0xb5, 0x2f, 0xfd}) { + t.Fatalf("payload does not start with the zstd frame magic: % x", payload[:4]) + } + if len(payload) >= len(in) { + t.Errorf("a repetitive %d-byte record compressed to %d bytes", len(in), len(payload)) + } + out, err := DecodePayload(payload, sum) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(out, in) { + t.Fatal("round trip changed the bytes") + } +} + +// The same record must always produce the same column bytes, or two writers +// of one record disagree about what was stored. +func TestPayloadEncodingIsDeterministic(t *testing.T) { + in := []byte(strings.Repeat(sampleRecord, 200)) + first, _, err := EncodePayload(in) + if err != nil { + t.Fatal(err) + } + for i := 0; i < 20; i++ { + again, _, err := EncodePayload(in) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(first, again) { + t.Fatalf("encoding %d differs from the first", i+2) + } + } +} + +func TestPayloadDecodeRefuses(t *testing.T) { + payload, sum, err := EncodePayload([]byte(sampleRecord)) + if err != nil { + t.Fatal(err) + } + other := sha256.Sum256([]byte("another record")) + + if _, err := DecodePayload(payload, hex.EncodeToString(other[:])); !errors.Is(err, ErrPayloadDigest) { + t.Errorf("a payload under the wrong hash: err = %v, want ErrPayloadDigest", err) + } + if _, err := DecodePayload(payload, "not-hex"); !errors.Is(err, ErrPayloadDigest) { + t.Errorf("a malformed hash: err = %v, want ErrPayloadDigest", err) + } + corrupt := append([]byte(nil), payload...) + corrupt[len(corrupt)/2] ^= 0xff + if _, err := DecodePayload(corrupt, sum); err == nil { + t.Error("a corrupted payload decoded") + } + if _, err := DecodePayload([]byte(sampleRecord), sum); err == nil { + t.Error("uncompressed JSON in the payload column decoded as if it were zstd") + } + if _, _, err := EncodePayload(nil); err == nil { + t.Error("an empty payload was encoded") + } +} + +// A payload that decompresses past MaxPayloadBytes is refused, however small +// it is on disk. This builds a real bomb: 300 MiB of zeros compresses to a +// few kilobytes. +func TestPayloadDecodeRefusesABomb(t *testing.T) { + big := make([]byte, MaxPayloadBytes+44<<20) + bomb := payloadEncoder.EncodeAll(big, nil) + t.Logf("%d bytes of zeros compress to %d", len(big), len(bomb)) + sum := sha256.Sum256(big) + if _, err := DecodePayload(bomb, hex.EncodeToString(sum[:])); err == nil { + t.Fatal("a payload over MaxPayloadBytes decoded") + } +} + +// TestThePayloadCodecIsThePinnedModule: the codec is pinned at the version +// whose licence bodies third_party/klauspost-compress/PIN.md records, by the +// module hash go.sum carries for it. A different version or hash is a +// dependency change nobody re-read. +func TestThePayloadCodecIsThePinnedModule(t *testing.T) { + const ( + require = "github.com/klauspost/compress v1.20.1" + sum = "github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ=" + ) + mod, err := os.ReadFile(filepath.Join("..", "..", "go.mod")) + if err != nil { + t.Fatalf("reading go.mod, so the pin is UNCHECKED: %v", err) + } + gosum, err := os.ReadFile(filepath.Join("..", "..", "go.sum")) + if err != nil { + t.Fatalf("reading go.sum, so the pin is UNCHECKED: %v", err) + } + if !strings.Contains(string(mod), "\t"+require+"\n") { + t.Errorf("go.mod does not require %q; the codec moved without its licence being re-read", require) + } + if !strings.Contains(string(gosum), sum+"\n") { + t.Errorf("go.sum does not carry %q", sum) + } + if strings.Contains(string(mod), "replace github.com/klauspost/compress") { + t.Error("go.mod replaces the codec module") + } +} + +// TestTheCodecLicenceBodiesAreArchived re-hashes the licence bodies +// third_party/klauspost-compress/PIN.md records. A body that changed is a +// determination nobody re-made. +func TestTheCodecLicenceBodiesAreArchived(t *testing.T) { + dir := filepath.Join("..", "..", "third_party", "klauspost-compress") + for name, want := range map[string]string{ + "LICENSE": "0d9e582ee4bff57bf1189c9e514e6da7ce277f9cd3bc2d488b22fbb39a6d87cf", + "zstd-internal-xxhash-LICENSE.txt": "f566a9f97bacdaf00d9f21dd991e81dc11201c4e016c86b470799429a1c9a79c", + "internal-snapref-LICENSE": "f69f157b0be75da373605dbc8bbf142e8924ee82d8f44f11bcaf351335bf98cf", + } { + body, err := os.ReadFile(filepath.Join(dir, name)) + if err != nil { + t.Errorf("%s: %v", name, err) + continue + } + sum := sha256.Sum256(body) + if got := hex.EncodeToString(sum[:]); got != want { + t.Errorf("%s hashes to %s, but PIN.md records %s", name, got, want) + } + } +} diff --git a/third_party/klauspost-compress/LICENSE b/third_party/klauspost-compress/LICENSE new file mode 100644 index 0000000..87d5574 --- /dev/null +++ b/third_party/klauspost-compress/LICENSE @@ -0,0 +1,304 @@ +Copyright (c) 2012 The Go Authors. All rights reserved. +Copyright (c) 2019 Klaus Post. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------ + +Files: gzhttp/* + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2016-2017 The New York Times Company + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +------------------ + +Files: s2/cmd/internal/readahead/* + +The MIT License (MIT) + +Copyright (c) 2015 Klaus Post + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--------------------- +Files: snappy/* +Files: internal/snapref/* + +Copyright (c) 2011 The Snappy-Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +----------------- + +Files: s2/cmd/internal/filepathx/* + +Copyright 2016 The filepathx Authors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/third_party/klauspost-compress/PIN.md b/third_party/klauspost-compress/PIN.md new file mode 100644 index 0000000..f4c5ead --- /dev/null +++ b/third_party/klauspost-compress/PIN.md @@ -0,0 +1,41 @@ +# `klauspost/compress` — pin and licence determination for the audit payload codec + +`internal/store/payload.go` compresses `audit_record.payload` with this module's `zstd` package (plan node +contractgaps). This directory holds the licence bodies that apply to the code that build links, copied +verbatim from the Go module cache at the pinned version, and hashed so the determination is reproducible. +`internal/store/payload_test.go` re-reads all three files on every `go test ./...` and fails if any of +them drifts from the hashes below, and it fails if `go.mod` or `go.sum` moves the pin. + +## The pin + +Read on **2026-10-03** on the Debian development machine. The owner approved the download that day. + +| Field | Value | +|---|---| +| Go module | `github.com/klauspost/compress` | +| Version | `v1.20.1` (published 2026-09-25 per `proxy.golang.org/.../@latest`) | +| Upstream commit for the tag (proxy's `Origin.Hash`) | `5d880f230c38a0fc806b9ca1613103a44feff0ac` | +| `go.sum` module hash | `h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ=` | +| Packages linked (`go list -deps ./zstd` in the module) | `zstd`, `zstd/internal/xxhash`, `huff0`, `fse`, `internal/cpuinfo`, `internal/le`, `internal/snapref`, and the module root | + +Reproduce: + +```bash +go list -m -f '{{.Dir}}' github.com/klauspost/compress +sha256sum "$(go list -m -f '{{.Dir}}' github.com/klauspost/compress)"/LICENSE +``` + +## The licence bodies, read in full + +| File here | Copied from | SPDX | Applies to | SHA-256 | +|---|---|---|---|---| +| `LICENSE` | `LICENSE` at the module root | BSD-3-Clause for the module (Copyright 2012 The Go Authors, 2019 Klaus Post), followed by sections naming other licences for specific directories | `zstd`, `huff0`, `fse`, `internal/*` | `0d9e582ee4bff57bf1189c9e514e6da7ce277f9cd3bc2d488b22fbb39a6d87cf` | +| `zstd-internal-xxhash-LICENSE.txt` | `zstd/internal/xxhash/LICENSE.txt` | MIT (Copyright 2016 Caleb Spare) | `zstd/internal/xxhash` | `f566a9f97bacdaf00d9f21dd991e81dc11201c4e016c86b470799429a1c9a79c` | +| `internal-snapref-LICENSE` | `internal/snapref/LICENSE` | BSD-3-Clause (Copyright 2011 The Snappy-Go Authors) | `internal/snapref` | `f69f157b0be75da373605dbc8bbf142e8924ee82d8f44f11bcaf351335bf98cf` | + +The root `LICENSE` also carries an Apache-2.0 section for `gzhttp/*` and MIT sections for +`s2/cmd/internal/readahead/*` and `s2/cmd/internal/filepathx/*`. None of those directories is linked by +`zstd`, so neither applies to Anvil's binaries today; they are recorded because they are in the file. + +No copyleft, no `NOASSERTION`, and nothing beyond the BSD-3-Clause and MIT notice duties +`THIRD-PARTY-LICENSES.md` already describes. BSD clause 3 (no endorsement) is a conduct duty. diff --git a/third_party/klauspost-compress/internal-snapref-LICENSE b/third_party/klauspost-compress/internal-snapref-LICENSE new file mode 100644 index 0000000..6050c10 --- /dev/null +++ b/third_party/klauspost-compress/internal-snapref-LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2011 The Snappy-Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/third_party/klauspost-compress/zstd-internal-xxhash-LICENSE.txt b/third_party/klauspost-compress/zstd-internal-xxhash-LICENSE.txt new file mode 100644 index 0000000..24b5306 --- /dev/null +++ b/third_party/klauspost-compress/zstd-internal-xxhash-LICENSE.txt @@ -0,0 +1,22 @@ +Copyright (c) 2016 Caleb Spare + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.