tracecontext

package
v0.57.0-rc.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 20, 2026 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Overview

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.

Index

Constants

View Source
const (
	ReasonAbsent             = "absent"
	ReasonMalformed          = "malformed"
	ReasonOversized          = "oversized"
	ReasonUnknownVersion     = "unknown-version"
	ReasonUnknownKey         = "unknown-key"
	ReasonBadSignature       = "bad-signature"
	ReasonBindingMismatch    = "binding-mismatch"
	ReasonConflictingCarrier = "conflicting-carrier"
	ReasonProvenance         = "provenance"
	ReasonUnresolved         = "unresolved"
	ReasonPending            = "pending"
)

Reason codes for non-admitted outcomes. They are redacted diagnostics: no key material, no raw bytes.

View Source
const MaxCarrierLen = 588

MaxCarrierLen is the maximum legal base64 carrier length in characters: base64.StdEncoding of MaxEnvelopeLen bytes without line breaks.

View Source
const MaxEnvelopeLen = 439

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.

Variables

View Source
var (
	ErrInvalidInstallationID  = errors.New("tracecontext: invalid installation ID")
	ErrInvalidVerificationKey = errors.New("tracecontext: invalid verification key")
	ErrInvalidSigningSeed     = errors.New("tracecontext: invalid signing seed")
	ErrInvalidKeyID           = errors.New("tracecontext: invalid key ID")
	ErrDuplicateKeyID         = errors.New("tracecontext: duplicate verification key ID")
)

Errors for invalid installation IDs, keys and key IDs. Their text is fixed: they never wrap or quote the input, which may be key material.

Functions

func DecodeCarrier

func DecodeCarrier(s string) ([]byte, error)

DecodeCarrier strictly decodes a base64 carrier string to raw envelope bytes. It rejects line breaks, non-canonical encodings, and carriers longer than MaxCarrierLen.

func FormatInstallationID added in v0.56.0

func FormatInstallationID(id [16]byte) string

FormatInstallationID returns id as 32 lowercase hex characters.

func FormatKeyID added in v0.56.0

func FormatKeyID(id [8]byte) string

FormatKeyID returns id as 16 lowercase hex characters.

func FormatVerificationKey added in v0.56.0

func FormatVerificationKey(pub ed25519.PublicKey) string

FormatVerificationKey returns pub as standard base64 with padding.

func KeyID

func KeyID(pub ed25519.PublicKey) [8]byte

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 KeySet added in v0.56.0

func KeySet(active ed25519.PublicKey, retained []ed25519.PublicKey) (map[[8]byte]ed25519.PublicKey, error)

KeySet builds the admission key map from the active and retained keys, keyed by KeyID. It rejects a key that is not 32 bytes (ErrInvalidVerificationKey) and duplicate key IDs (ErrDuplicateKeyID); a key that is both active and retained is a duplicate. The map holds copies, so later changes to the arguments cannot put a key under another key's ID.

func NewInstallationID added in v0.56.0

func NewInstallationID(r io.Reader) ([16]byte, error)

NewInstallationID reads 16 bytes from r (crypto/rand.Reader when r is nil). An all-zero result is an error.

func NormalizeInstance

func NormalizeInstance(raw string) (string, error)

NormalizeInstance canonicalizes a forge web base URL to the D01 instance form: lowercase scheme://host with an escaped, case-sensitive deployment prefix and no trailing slashes, query, fragment, or user info. Only http and https are accepted. Ports lose leading zeros (an all-zero port stays :0) and must fit 16 bits; empty and default ports are then removed. Trailing DNS root dots are stripped, hosts must be ASCII (punycode for IDNs), and IPv6 hosts take their RFC 5952 section 4 form, with IPv4-mapped addresses in mixed notation, and no zone identifier. Path segments and escape spelling are preserved so distinct deployments cannot alias; a path mixing percent-escapes with characters that still need escaping rejects. All identity and envelope construction must use the normalized form so independent launches converge.

func ParseInstallationID added in v0.56.0

func ParseInstallationID(s string) ([16]byte, error)

ParseInstallationID accepts exactly 32 lowercase hex characters that are not all zero, and returns ErrInvalidInstallationID otherwise.

func ParseKeyID added in v0.56.0

func ParseKeyID(s string) ([8]byte, error)

ParseKeyID accepts exactly 16 lowercase hex characters, and returns ErrInvalidKeyID otherwise. FormatKeyID is its inverse.

func ParseVerificationKey added in v0.56.0

func ParseVerificationKey(s string) (ed25519.PublicKey, error)

ParseVerificationKey accepts strict standard base64 (with padding) of exactly 32 bytes, and returns ErrInvalidVerificationKey otherwise.

Types

type Domain

type Domain byte

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.

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
)

func (Domain) Valid

func (d Domain) Valid() bool

Valid reports whether d is a defined message domain.

type EntityKind

type EntityKind byte

EntityKind distinguishes the entity kinds that can share a forge container. GitLab issue and merge-request database IDs, and GitHub issue and Discussion database IDs, come from independent spaces, so the kind is part of every identity.

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
	// KindConversation is a GitHub Discussion. GitLab and Jira have no
	// conversation entity in this contract. The package cannot tell
	// forges apart, so callers must not construct this kind for them.
	KindConversation EntityKind = 0x03
)

func (EntityKind) Valid

func (k EntityKind) Valid() bool

Valid reports whether k is a defined entity kind.

type Envelope

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
}

Envelope is a decoded v1 envelope or pending marker. Its fields are unauthenticated: Parse checks structure only, so TraceID, ParentSpanID, and Provenance must not be consumed unless Admit returns OutcomeAdmitted. The wire layout, exact sizes, and strict limits are specified in docs/normative/trace-context/v1/README.md, provisional until the first carrier-publishing PR merges; Marshal is its only legal encoder.

func Parse

func Parse(b []byte) (*Envelope, error)

Parse strictly decodes and structurally validates wire bytes. It accepts only the exact structural length for the parsed domain and provenance kind; duplicate and unknown fields are structurally impossible in the fixed layout. Parse does not verify the signature or binding, so its result is unauthenticated: Admit is the only authenticated path and the only safe source of trace context. Provenance cross-field consistency is checked at admission, not here.

func (*Envelope) Marshal

func (e *Envelope) Marshal() []byte

Marshal returns the canonical wire bytes including the signature. Sign must have completed; marshalling an unsigned envelope yields bytes no verifier accepts.

func (*Envelope) Sign

func (e *Envelope) Sign(key ed25519.PrivateKey) error

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.

type Fallback

type Fallback struct {
	TraceID      trace.TraceID
	AnchorSpanID trace.SpanID
}

Fallback is the deterministic entity-derived context: a stable TraceID and a synthetic anchor SpanID. By contract, the anchor exists only as a parent reference, is never exported as a span, and is never repointed.

func DeriveFallback

func DeriveFallback(id Identity) (fb Fallback, ok bool)

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.

type Identity

type Identity struct {
	// Installation is the 128-bit installation identifier provisioned
	// with the signing key pair. It is authenticated in envelopes but
	// deliberately excluded from fallback derivation, per ADR 0154.
	Installation [16]byte
	// Instance is the normalized forge web base URL: lowercase scheme://host
	// with its escaped, case-sensitive deployment prefix and no trailing slash.
	// Use NormalizeInstance to build it from trusted configuration.
	Instance string
	// Container is the immutable repository or project database ID.
	Container int64
	// Kind is the entity kind within the container.
	Kind EntityKind
	// Entity is the immutable entity database ID.
	Entity int64
}

Identity is the immutable binding of a forge entity (ADR 0154, D01): installation, forge instance, container, entity kind, and entity database ID. Display names, entity URLs, GitHub numbers, GitLab IIDs, and Jira keys are not identity components; docs/normative/trace-context/v1/README.md holds the per-forge field mapping.

func (Identity) Resolved

func (id Identity) Resolved() bool

Resolved reports whether the forge-side identity components are present and valid: a canonical instance, a container ID >= 1, a valid kind, and an entity ID >= 1. Installation is local configuration rather than event identity, so it is not part of resolution; admission checks it against the envelope separately. An unresolved identity must postpone dispatch (FR-002); it never derives a fallback.

type Outcome

type Outcome int

Outcome is the admission outcome. It never encodes dispatch permission.

const (
	// OutcomeFallback means no decoded candidate was admissible; the
	// caller uses the deterministic entity-derived fallback, except for
	// ReasonUnresolved, where it must postpone dispatch. It is the zero
	// value.
	OutcomeFallback Outcome = iota
	// OutcomeAdmitted means a verified bound envelope matched the
	// expected binding; the admitted IDs are available.
	OutcomeAdmitted
	// OutcomePending means a verified pending marker matched the expected
	// scope. It grants neither context nor links; callers bound the reread
	// by a window from the entity's trusted creation metadata, then fall
	// back.
	OutcomePending
)

type Provenance

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
}

Provenance carries the authenticated creation provenance of an envelope. Only the fields selected by Kind are meaningful.

type ProvenanceKind

type ProvenanceKind byte

ProvenanceKind selects the authenticated provenance section.

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
)

func (ProvenanceKind) Valid

func (k ProvenanceKind) Valid() bool

Valid reports whether k is a defined provenance kind.

type Result

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
}

Result is the admission outcome. It carries admitted IDs and authenticated provenance only — never sampling flags, tracestate, baggage, or dispatch permission (FR-007, FR-008). Its zero value selects fallback and carries no admitted context or links.

func Admit

func Admit(expected Identity, keys map[[8]byte]ed25519.PublicKey, candidates ...[]byte) Result

Admit parses, verifies, and binds candidate envelope wire bytes, each decoded from its carrier with DecodeCarrier, against the expected identity and the configured eligible verification keys (active plus retained). Identical duplicate candidates are acceptable; any differing candidates reject. Keys are resolved only from the supplied trusted set. Admission is independent of dispatch authorization: this function never returns permission.

An unresolved expected identity reports ReasonUnresolved before any decoded candidate is inspected: the caller must postpone dispatch (FR-002) and must not read the candidate's own diagnostics as the cause.

type SigningKey added in v0.56.0

type SigningKey struct {
	// contains filtered or unexported fields
}

SigningKey holds an Ed25519 private key expanded from a 32-byte seed. EncodeSeed is the only way the key material leaves the type: String, GoString, Format (every verb), MarshalJSON, MarshalText and LogValue all return "[redacted]". The zero value holds no key.

func NewSigningKey added in v0.56.0

func NewSigningKey(r io.Reader) (SigningKey, error)

NewSigningKey generates a key from r (crypto/rand.Reader when r is nil).

func ParseSigningSeed added in v0.56.0

func ParseSigningSeed(s string) (SigningKey, error)

ParseSigningSeed trims surrounding ASCII whitespace (not Unicode spaces such as U+00A0), then accepts strict standard base64 (no CR or LF anywhere) of exactly 32 bytes and expands it with ed25519.NewKeyFromSeed. Anything else returns ErrInvalidSigningSeed.

func (SigningKey) EncodeSeed added in v0.56.0

func (k SigningKey) EncodeSeed() string

EncodeSeed returns the 32-byte seed as standard base64, for the secret write, or "" for the zero value. It is the only way the key material leaves the type.

func (SigningKey) Format added in v0.56.0

func (k SigningKey) Format(f fmt.State, verb rune)

Format writes "[redacted]" for every verb, ignoring width and flags.

func (SigningKey) GoString added in v0.56.0

func (k SigningKey) GoString() string

GoString returns "[redacted]".

func (SigningKey) IsZero added in v0.56.0

func (k SigningKey) IsZero() bool

IsZero reports whether k holds no key.

func (SigningKey) KeyID added in v0.56.0

func (k SigningKey) KeyID() [8]byte

KeyID returns KeyID(k.Public()).

func (SigningKey) LogValue added in v0.56.0

func (k SigningKey) LogValue() slog.Value

LogValue returns "[redacted]" as a string value.

func (SigningKey) MarshalJSON added in v0.56.0

func (k SigningKey) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON string "[redacted]".

func (SigningKey) MarshalText added in v0.56.0

func (k SigningKey) MarshalText() ([]byte, error)

MarshalText returns "[redacted]".

func (SigningKey) Public added in v0.56.0

func (k SigningKey) Public() ed25519.PublicKey

Public returns the verification key of k, or nil for the zero value.

func (SigningKey) SignEnvelope added in v0.56.0

func (k SigningKey) SignEnvelope(e *Envelope) error

SignEnvelope signs e in place with the expanded key (Envelope.Sign). The zero value returns an error and leaves e unchanged.

func (SigningKey) String added in v0.56.0

func (k SigningKey) String() string

String returns "[redacted]".

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL