crypto

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MPL-2.0 Imports: 41 Imported by: 0

Documentation

Overview

Package crypto is the envelope package — the sole crypto chokepoint fixed by the encryption-model ADR and placed here by the system-architecture ADR. It owns the keyring (root → master → tier-3 keys), the per-kind AAD schemas with their injective length-prefixed encoding, the versioned ciphertext envelope over XChaCha20-Poly1305, the DEK cache, root-key bootstrap, and process hardening. No cryptographic primitive is imported anywhere else in the module (enforced by internal/boundary).

The package is a leaf: it imports nothing under internal/, and persists wrapped key material through the narrow KeyStore interface that internal/store/keyring implements.

Index

Constants

View Source
const (
	MaxPasswordTime        = 64
	MaxPasswordParallelism = 64
)

Plausible bounds for the remaining parameters, for the same reason.

View Source
const (
	// MaxTransitPlaintextBytes bounds plaintext, signed or MACed messages, and
	// decrypted output.
	MaxTransitPlaintextBytes = 64 << 10
	// MaxTransitContextBytes bounds caller-supplied associated data.
	MaxTransitContextBytes = 1 << 10
	// MaxTransitWireBytes bounds a presented ciphertext, signature or MAC
	// string before any decoding happens.
	MaxTransitWireBytes = 128 << 10
)

Bounds shared by the service's request validation and the parsers below, so a parser can never accept what the service would refuse (transit ADR D9).

View Source
const KeySize = 32

KeySize is the size of every key in the hierarchy: 256-bit, per the encryption-model ADR.

View Source
const MaxPasswordMemoryKiB = 1 << 21 // 2 GiB

MaxPasswordMemoryKiB bounds what a stored parameter set may ask for. Argon2id allocates m KiB up front, so a row carrying a nonsense value — a corrupted write, a restored backup from a differently-configured instance — would otherwise turn one login attempt into a multi-gigabyte allocation. The bound is generous against any plausible configuration and fatal to an implausible one.

View Source
const Redacted = "[REDACTED:hikyo-key-material]"

Redacted is the marker every formatting surface of a sensitive type returns.

View Source
const SaltSize = 16

SaltSize is 16 random bytes per verifier, as the ADR fixes.

View Source
const StampVersion = "v1"

StampVersion is the stamp's version prefix, carried on the emitted value AND inside the canonical encoding. Outside: the stamp flows into a pod-template annotation as a public machine contract, so a scheme change without a prefix would silently invalidate every consumer's comparison. Inside: without it two different encodings of the same content could collide under a scheme change, which an outside prefix cannot prevent (the change-token package makes the same argument for ManifestVersion).

View Source
const (

	// TOTPSkewSteps is how many steps on either side of now a code is accepted
	// for, absorbing clock drift between the server and the authenticator. One
	// step (±30s) is the common choice; single-use consumption per step means
	// a captured code cannot be replayed within the window.
	TOTPSkewSteps = 1
)
View Source
const TokenVersion = "v1"

TokenVersion is the scheme's version prefix, carried on both values.

It is not decoration. A change token is a PUBLIC MACHINE CONTRACT embedded in pod annotations and client caches, so changing the encoding later without a prefix would silently invalidate every consumer's comparison. The cursor carries the same prefix for the duller reason that a value which looks like a token and is not one is worse than either.

View Source
const TransitMaterialSize = KeySize

TransitMaterialSize is the size of one key version's material: 256 bits of fresh randomness, from which every operation key is derived.

Variables

View Source
var (
	ErrNoRootKey = errors.New("crypto: no root key configured: set --root-key-file or HIKYO_ROOT_KEY")
	// ErrRootKeyPerms: a key file readable by group or other is refused.
	ErrRootKeyPerms = errors.New("crypto: root key file is readable by group or other (chmod 600 it)")
	// ErrRootKeyFormat: anything but 256 bits after hex decoding is refused.
	ErrRootKeyFormat = errors.New("crypto: root key must decode to exactly 256 bits (64 hex characters)")
	// ErrRootKeyMismatch: the master key's Poly1305 tag failed to verify.
	ErrRootKeyMismatch = errors.New("crypto: root key does not match this datastore")
)

Startup refusals — each is its own distinct error (CI invariant 6), all hard failures with no override flag.

View Source
var ErrAboveCeiling = errors.New("crypto: Argon2id parameters above the verification safety ceiling")

ErrAboveCeiling prevents new verifiers from being written with parameters the login path must reject for resource safety.

View Source
var ErrBelowFloor = errors.New("crypto: Argon2id parameters below the boot-verified floor")

ErrBelowFloor is the boot refusal. It is a distinct error so the startup path can name the exact parameter that is short.

View Source
var ErrCursorInvalid = errors.New("crypto: invalid cursor")

ErrCursorInvalid is the generic, non-distinguishing failure the sealer returns for a tampered, truncated, or forged token.

View Source
var ErrDecrypt = errors.New("crypto: decryption failed")

ErrDecrypt is the uniform decrypt failure. It deliberately carries no detail: which byte failed is not the caller's business, and error strings reach logs.

View Source
var ErrKeyExists = errors.New("crypto: key already exists for scope")

ErrKeyExists reports a uniqueness conflict on key creation — two writers racing to mint the same scope's key. Callers re-read the winner.

View Source
var ErrMalformedArtifact = errors.New("crypto: malformed bearer artifact")

ErrMalformedArtifact is returned by ParseArtifact for anything that is not a well-formed value of the expected type. It is deliberately one error for every malformation: a caller must not be able to learn which part was wrong, and the server answers all of them identically anyway.

View Source
var ErrMasterRotationBlocked = errors.New("crypto: master rotation blocked; the root key is dual-wrapped, finalize the root rotation first")

ErrMasterRotationBlocked reports that rotate-master-key cannot proceed: the datastore holds no active master (corrupted hierarchy) or more than one (the root is mid dual-wrapped rotation). The two operations are mutually exclusive — dual-wrapping the new master under both roots is the four-way state the ADR refuses — so master rotation waits for `rotate-root-key --finalize`.

View Source
var ErrNoKey = errors.New("crypto: no active key for scope")

ErrNoKey reports that no active key exists for the requested scope.

View Source
var ErrNotDualWrapped = errors.New("crypto: no root rotation in flight; run --prepare first")

ErrNotDualWrapped reports a verify or finalize with no pending root rotation: there is a single active master wrapper, so there is nothing to confirm or retire. Prepare first.

View Source
var ErrRootRotationBlocked = errors.New("crypto: root rotation blocked; a rotation is already in flight, verify and finalize it first")

ErrRootRotationBlocked reports that rotate-root-key --prepare cannot proceed: the datastore is already dual-wrapped (a prepare is in flight) or the hierarchy is missing. The operator verifies and finalizes the pending rotation, or the instance is unbooted.

View Source
var ErrStaleMaster = errors.New("crypto: wrapping master key version is no longer active")

ErrStaleMaster reports a tier-3 key creation carrying a master version that is no longer the active master: the writer sealed under a master a rotation has since retired. Unreachable until the rotations ticket lands; the fence check exists so the race of CI invariant 9 is structurally refused rather than silently committed.

View Source
var ErrTransitFormat = errors.New("crypto: malformed transit value")

ErrTransitFormat is the uniform refusal for a malformed transit value. It names no byte and no field.

View Source
var ErrUnknownFormat = errors.New("crypto: unknown ciphertext format version")

ErrUnknownFormat marks a ciphertext whose format version this build does not know — startup refusal 5 of the encryption-model ADR ("abort rather than guess") depends on it being distinguishable.

View Source
var PasswordFloor = PasswordParams{MemoryKiB: 64 * 1024, Time: 3, Parallelism: 2}

PasswordFloor is the hard floor the human-auth ADR fixes: m=64 MiB, t=3, p=2. Parameters are tunable UPWARD for stronger hardware and explicitly NOT downward: the server refuses to start below this rather than degrading quietly, because a silently weakened KDF is indistinguishable from a strong one until the database leaks.

Functions

func ArtifactVerifier

func ArtifactVerifier(value string) []byte

ArtifactVerifier is the stored form: an unsalted SHA-256 of the whole presented value. Fast hashing is correct here, not a shortcut — the artifact carries >=256 bits of entropy, so brute force is infeasible and authentication stays a single indexed read. A salt would buy nothing and cost the index.

func BurnDummyVerification

func BurnDummyVerification(password []byte, p PasswordParams)

BurnDummyVerification performs the work a real verification would, and discards it. It exists so the caller cannot accidentally skip the work by returning early on a missing account — the expensive step is the observable one, so it has to happen either way.

func CanonicalStringSet

func CanonicalStringSet(items []string) []string

CanonicalStringSet returns a sorted, deduplicated copy of items. It is the ONE canonicalizer shared between the snapshot AAD's list fields and the compose cursor's projection / target-key-id membership, so "the authorized projection, sorted as the CLI derives it" means exactly the same bytes in both places.

func CredentialFingerprint

func CredentialFingerprint(credential []byte) [32]byte

CredentialFingerprint creates a non-reversible in-process coordination key. Callers can share provider budgets without retaining another credential copy.

func CustodyWrapKey

func CustodyWrapKey(root []byte) ([]byte, error)

CustodyWrapKey derives the secret that wraps the operator upgrade vault from the installation's root key. Everything the vault protects is already reachable by whoever can read that key, so a separate human-held secret added a prompt without adding a boundary. Domain-separated from every other root-key derivation by its label.

func DeriveVerifier

func DeriveVerifier(password, salt []byte, p PasswordParams) ([]byte, error)

DeriveVerifier returns salt ‖ Argon2id(password, salt). The salt travels with the digest because the whole blob is then envelope-encrypted under the instance DEK: the hash stays a hash — a root-key holder still cannot reverse it — and the encryption is an outer layer that denies an attacker holding the database without the root key the ability to mount the offline guessing attack at all, rather than merely mounting it slowly.

func EncodeRootKey

func EncodeRootKey(key []byte) string

EncodeRootKey renders a root key in the fixed on-disk encoding. It exists for key generation (`hikyo init`, dev bootstrap) so the format lives in one place.

func EqualTransitMAC

func EqualTransitMAC(a, b []byte) bool

EqualTransitMAC compares two MACs in constant time.

func FormatTransitValue

func FormatTransitValue(version uint32, payload []byte) string

FormatTransitValue renders a caller-facing transit value: "hikyo:v" ‖ decimal(version) ‖ ":" ‖ base64url(payload), unpadded.

func GenerateRecoveryBatch

func GenerateRecoveryBatch(n int) (codes []string, verifiers [][]byte, err error)

GenerateRecoveryBatch mints n fresh recovery codes and their verifiers. The plaintext codes are returned once, to display exactly once; only the verifiers are persisted.

func GenerateRootKey

func GenerateRootKey() ([]byte, error)

GenerateRootKey mints a fresh 256-bit root key. Randomness failure aborts, as at every other key generation.

func HardenProcess

func HardenProcess() error

HardenProcess applies the key-material hardening the encryption-model ADR fixes for every process mode that loads the keyring: no core dumps anywhere, and on Linux additionally no same-uid ptrace attach or /proc/<pid>/mem read (PR_SET_DUMPABLE=0). Called before any key material enters the process.

func ImportValuesCommitment

func ImportValuesCommitment(key, canonical []byte) ([]byte, error)

ImportValuesCommitment authenticates canonical imported values under a private 256-bit key and a v2-only domain. Callers own canonical encoding; crypto owns this primitive and never returns the private key in the digest.

func InitializeFreshHierarchy

func InitializeFreshHierarchy(ctx context.Context, store KeyStore, root []byte) error

InitializeFreshHierarchy uses the maintained hierarchy generator, then discards all plaintext key material before returning. The supplied store must enforce empty, exclusively owned first-boot state and atomic persistence. No runtime keyring or retained datastore capability escapes this operation.

func MatchRecoveryCode

func MatchRecoveryCode(presented string, verifiers [][]byte) int

MatchRecoveryCode returns the index of the verifier the presented code matches, or -1 for no match. The whole set is scanned in constant time per entry so neither the presence of a match nor its position leaks through timing; a grammatically invalid code still scans the set rather than returning early.

func NewArtifact

func NewArtifact(t ArtifactType) (value string, verifier []byte, err error)

NewArtifact mints a bearer value of the given type and returns it with its verifier. The plaintext is returned exactly once, to exactly one caller; only the verifier is ever persisted.

func NewImportCommitmentKey

func NewImportCommitmentKey() ([]byte, error)

NewImportCommitmentKey returns fresh private blinding material. It belongs only in a protected values artifact, never its committable manifest.

func NewSalt

func NewSalt() ([]byte, error)

NewSalt draws a fresh per-verifier salt. An RNG failure aborts — the same rule every seal in this package follows.

func NewTOTPSeed

func NewTOTPSeed() ([]byte, error)

NewTOTPSeed draws a fresh random seed. The raw bytes are what gets envelope-encrypted; the base32 form is only ever handed to the user's app inside the provisioning URI.

func NewTransitDataKey

func NewTransitDataKey(bits int) ([]byte, error)

NewTransitDataKey draws a data key of bits length. Anything but 128, 256 or 512 is refused.

func NewTransitMaterial

func NewTransitMaterial() ([]byte, error)

NewTransitMaterial draws one key version's material. A failed or short read returns a wrapped randomness error and no material.

func OpenExistingProjectFields

func OpenExistingProjectFields(ctx context.Context, ks ExistingHierarchyStore, root []byte, orgID, projectID string, fields []ExistingProjectField) (map[string]string, error)

OpenExistingProjectFields consumes root and opens a fixed project projection. No keyring or plaintext key escapes; temporary key material is always cleared.

func ParseArtifact

func ParseArtifact(value string, want ArtifactType) error

ParseArtifact checks the grammar and the checksum locally, so a truncated or mistyped value is refused with zero server calls and never reaches the admission budget. It returns the value unchanged on success — the caller still resolves it against the database, because the server trusts nothing inside it.

func ParseStamp

func ParseStamp(s string) error

ParseStamp enforces the anchored stamp grammar. It validates only; it never returns a default.

func ParseTransitCiphertext

func ParseTransitCiphertext(s, keyID string) (uint32, []byte, error)

ParseTransitCiphertext returns the version and decoded record after checking the transit header, algorithm, key ID, and agreement with the textual version. Parse failures and mismatches return ErrTransitFormat. It does not validate nonce length or authenticate the record; the caller must still decrypt it.

func ParseTransitValue

func ParseTransitValue(s string) (uint32, []byte, error)

ParseTransitValue splits a caller-facing transit value into its version and decoded payload. The version is a canonical positive decimal (no sign, no leading zero, fits uint32) and the payload strict unpadded base64url. The whole string is limited to MaxTransitWireBytes before decoding. Empty payloads and all malformed or oversized values return ErrTransitFormat.

func RandomBytes

func RandomBytes(n int) ([]byte, error)

RandomBytes returns n cryptographically random bytes. It is the source for opaque identifiers that are not bearer artifacts — the WebAuthn user handle (#54), an opaque per-account value that must never be a username, email or id.

func ReadEscrowRootKey

func ReadEscrowRootKey(path, serverRootPath string) ([]byte, error)

ReadEscrowRootKey reads one bounded, private regular file through the same descriptor whose identity is compared with the server root source. It proves distinct files, not physical offline custody or distinct failure domains.

func ReadRootKey

func ReadRootKey(file, envValue string) ([]byte, error)

ReadRootKey loads and validates the root key from a file path or an env-delivered value; exactly one source must be present (the config layer refuses ambiguity before this runs). The caller owns the returned bytes and must Zero them when done.

func RecordKeyVersion

func RecordKeyVersion(record []byte) (uint32, error)

RecordKeyVersion reports the wrapping-key version named in a record's authenticated header, without opening it. reencrypt reads it to decide whether a row is already on the active DEK version (skip) or still on a superseded one (re-seal). A malformed or unknown-format header is an error.

func RegistryPasswordHash

func RegistryPasswordHash(password []byte) ([]byte, error)

RegistryPasswordHash produces the bcrypt format required by a distribution registry's htpasswd backend. The disposable native-consumer fixture uses it; Hikyo account passwords continue to use the Argon2id policy in password.go.

func RootKeyFingerprint

func RootKeyFingerprint(root []byte) string

RootKeyFingerprint is a stable, non-reversible identifier for a root key, used by multi-node HA (#146) to name a mixed-root-key misconfiguration in a refusal rather than surfacing it only as an opaque keyring unwrap failure. It is a domain-separated SHA-256 over the key, so it reveals nothing about the key material and never collides with another envelope digest.

func SCIMSubjectDigest

func SCIMSubjectDigest(org, binding, issuer, subject string) (string, error)

SCIMSubjectDigest is a blinded, per-event subject commitment. The private blinding key is never persisted or emitted, so even predictable subjects cannot be guessed from an audit export. Immutable resource/account IDs, not this commitment, provide audit correlation. Its spelling retains the v1 payload's 64 lowercase hexadecimal characters.

func SealAnonymousBox

func SealAnonymousBox(value []byte, publicKey [32]byte) ([]byte, error)

SealAnonymousBox confines the GitHub Actions sealed-box primitive to the repository's crypto chokepoint. The provider adapter receives ciphertext only and never imports cryptographic primitives directly.

func Stamp

func Stamp(stampKey []byte, pairs []StampPair) (string, error)

Stamp computes the target's rollout stamp: `v1:` + hex(first 16 bytes of HMAC-SHA256(stampKey, canonicalEncoding(pairs))). Truncated to 128 bits per the k8s ADR — a rollout trigger, not an authentication tag, and the annotation stays short (the key-name part is capped at 63 chars, hence `target.name` ≤ 63).

The stamp is a PURE FUNCTION of the delivered content, which is what makes the write path idempotent: a crash-and-redo full fetch delivering unchanged content yields the same stamp and moves no workload (ADR § Write ordering).

func StampKey

func StampKey(root []byte, instanceUID, crUID, secretName string) ([]byte, error)

StampKey derives the per-target stamp key via HKDF-SHA256 over the operator's local 256-bit random root, domain-separated by `(HikyoInstance UID, CR UID, managed-Secret name)`. A single flat key would make equal content produce equal stamps across namespaces and projects — a cross-scope equality oracle for any principal who can read workloads in two namespaces but Secrets in neither, which is the exact comparison the revision-model ADR's scoped derivation kills server-side; derivation re-kills it client-side (ADR § Change propagation).

The info string is PIPE-JOINED exactly as § 0.2 fixes it — not the length-prefixed encoding scoped token derivation uses — and it is injective anyway: a Kubernetes UID is a hyphenated hex UUID and a Secret name obeys RFC 1123, so neither component can contain the `|` separator.

func TOTPProvisioningURI

func TOTPProvisioningURI(issuer, account string, seed []byte) string

TOTPProvisioningURI renders the otpauth:// URI an authenticator app scans. The label carries the instance issuer and the account handle; the secret is the base32 seed. It is returned once, at enrolment, and never stored.

func TOTPStep

func TOTPStep(t time.Time) int64

TOTPStep is the time-step index of an instant: the single-use consumption unit. A code is accepted at most once per (account, step).

func ValidateTOTP

func ValidateTOTP(seed []byte, code string, now time.Time, skew int) (step int64, ok bool)

ValidateTOTP checks a presented code against the seed within the skew window and returns the exact step it matched. The whole window is scanned (no early return) so the number of HMAC evaluations does not depend on which step matched, and the comparison is constant-time. ok is false for a code that matches no step in the window.

func VerifyExistingHierarchy

func VerifyExistingHierarchy(ctx context.Context, ks ExistingHierarchyStore, root []byte) error

VerifyExistingHierarchy authenticates the existing master and every openable tier-3 wrapper using separately escrowed root material. It consumes root and zeroes every temporary unwrapped key on success and failure. A hierarchy from before scanning keys existed is valid; missing instance/token keys are not.

func VerifyPassword

func VerifyPassword(password, verifier []byte, p PasswordParams) bool

VerifyPassword re-derives under the verifier's own recorded parameters and compares in constant time. A malformed verifier answers false rather than erroring: at the login path a stored-value defect and a wrong password must look identical from outside.

func VerifyTransitSignature

func VerifyTransitSignature(publicKey, message, signature []byte) bool

VerifyTransitSignature checks a pure Ed25519 signature. Wrong-sized inputs are a plain false, never a panic.

func WithExistingProjectSealer

func WithExistingProjectSealer(ctx context.Context, ks ExistingProjectSealingStore, root []byte, orgID, projectID string, fn func(*ProjectSealer) error) error

WithExistingProjectSealer authenticates only existing project wrappers. It consumes root and clears all temporary keys after fn; fn must not retain the sealer. It never creates or persists key material.

func Zero

func Zero(b []byte)

Zero overwrites b. Best effort only — Go's GC gives no wipe guarantee, and the encryption-model ADR makes no memory-secrecy claim.

Types

type AAD

type AAD interface {
	// contains filtered or unexported methods
}

AAD is implemented by exactly one struct per envelope kind. The interface is sealed (unexported methods): the six schemas below are the closed set the ADR fixes, and a new kind is an ADR amendment, not a new struct.

type ArtifactType

type ArtifactType string

ArtifactType is the `type` field of the token grammar.

const (
	// ArtifactCLISession is a human CLI session — a distinct artifact type
	// with its own storage, lifetime, audit identity and revocation surface.
	ArtifactCLISession          ArtifactType = "cli"
	ArtifactDeveloper           ArtifactType = "dev"
	ArtifactDeveloperCredential ArtifactType = ArtifactDeveloper
	// ArtifactBootstrap is a credential-establishment authority.
	ArtifactBootstrap ArtifactType = "bs"
	// ArtifactBrowserSession is a human browser session, carried in the
	// `__Host-hikyo` cookie — a distinct artifact type with its own lifetime
	// and revocation surface, listed separately from CLI sessions.
	ArtifactBrowserSession ArtifactType = "br"
	// ArtifactRecoveryCode is a single-use recovery code. The grammar buys
	// the audit redaction filter and offline checksum validation; the batch
	// is stored as hashes sealed under the instance DEK.
	ArtifactRecoveryCode ArtifactType = "rc"
	// ArtifactOIDCState is the `state` value of an OIDC transaction; the row
	// it resolves to holds the transaction record, and the value crosses the
	// IdP redirect, so it carries full artifact entropy and redacts like any
	// other bearer value.
	ArtifactOIDCState ArtifactType = "st"
	// ArtifactOIDCBinding is the browser-binding cookie value minted at an
	// anonymous OIDC start — the callback must present it before the
	// transaction is consumed, closing forced-login/fixation.
	ArtifactOIDCBinding ArtifactType = "ob"
	// ArtifactCSRF is the synchronizer token bound to a browser session,
	// required on state-changing cookie-authenticated requests.
	ArtifactCSRF ArtifactType = "cs"
	// ArtifactWorkload and ArtifactAutomation are the two machine bearer
	// credentials (#61): the ADR's `wl` and `au` rows of the closed type
	// list. They are a HINT only — the prefix a scanner and a human read.
	// Which service account a value belongs to, which class it is, what it
	// may reach and when it expires are read from the row the verifier
	// resolves to, so a value carrying `au` against a workload row is a
	// workload credential.
	ArtifactWorkload   ArtifactType = "wl"
	ArtifactAutomation ArtifactType = "au"
	// ArtifactSCIM is a SCIM provisioning connection's credential — the
	// machine-identities ADR's closed type list gaining `scim` by the
	// scim-provisioning amendment (#73 §7). One scanner family is preserved:
	// everything else about it (>=256-bit body, checksum, unsalted SHA-256
	// verifier, overlap rotation, lifetime ceiling, revocation at next request,
	// credential epoch, restored verifiers permanently dead) inherits unchanged
	// from the locked machine-credential mechanics.
	ArtifactSCIM ArtifactType = "scim"
	// ArtifactInstanceConn is the directory credential of an instance
	// connection (#71): the multi-instance ADR's amendment to the closed type
	// list, so the credential scans as what it is. Mechanically an ordinary
	// machine bearer; what makes it different is not the grammar but the
	// artifact-eligibility confinement in internal/authz, which admits it to
	// exactly one operation.
	ArtifactInstanceConn ArtifactType = "ic"
	// ArtifactWorkspaceSession is a workspace session (#71) — a session row in
	// every locked mechanical respect, differing from a browser session only in
	// transport: presented in an Authorization header, never a cookie.
	ArtifactWorkspaceSession ArtifactType = "ws"
	// ArtifactHandoffState and ArtifactHandoffCode are the two front-channel
	// values of the cross-origin UI handoff (#71), the browser edition of the
	// RFC 8252 shape the API/CLI ADR already fixed for the CLI. They carry full
	// artifact entropy for the same reason `st` does: they cross a redirect, so
	// they redact like any other bearer value and a truncated one is refused
	// with zero server calls.
	ArtifactHandoffState ArtifactType = "hs"
	ArtifactHandoffCode  ArtifactType = "hc"
	// ArtifactSignup is the local sign-up verification token (social-signin
	// spec 2.4): mailed in a URL fragment, stored only as its verifier on the
	// pending registration_signups row, single-use. It crosses a mail client and
	// a browser, so it carries full artifact entropy and redacts like `hs`/`hc`.
	ArtifactSignup ArtifactType = "su"
)

type DeliveryTokenSnapshot

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

DeliveryTokenSnapshot holds one transaction's immutable scoped delivery keys. Its caller selects and locks the active wrapped token row inside the SAME authorized transaction as issuance/reconciliation, never through a nested KeyStore refresh. A process-local token handle is not evidence of freshness.

func (*DeliveryTokenSnapshot) ChangeToken

func (s *DeliveryTokenSnapshot) ChangeToken(manifest []byte) string

func (*DeliveryTokenSnapshot) Close

func (s *DeliveryTokenSnapshot) Close()

func (*DeliveryTokenSnapshot) DeliveryCursor

func (s *DeliveryTokenSnapshot) DeliveryCursor(tuple []byte) string

func (*DeliveryTokenSnapshot) Sign

func (s *DeliveryTokenSnapshot) Sign(claims []byte) string

func (*DeliveryTokenSnapshot) Verify

func (s *DeliveryTokenSnapshot) Verify(claims []byte, signature string) bool

type ExistingHierarchyStore

type ExistingHierarchyStore interface {
	ActiveMasterWrappers(context.Context) ([]WrappedKey, error)
	AllOpenableTier3(context.Context) ([]WrappedKey, error)
}

ExistingHierarchyStore exposes only persisted wrappers, with no creation capability. Escrow verification must not initialize an absent hierarchy.

type ExistingProjectField

type ExistingProjectField struct {
	Name       string
	AAD        ProjectFieldAAD
	Ciphertext []byte
	// contains filtered or unexported fields
}

ExistingProjectField is one authenticated persisted field, with no write or key-creation capability. Callers must restrict its source to the fixed owner.

func (ExistingProjectField) GoString

func (ExistingProjectField) GoString() string

func (ExistingProjectField) LogValue

func (ExistingProjectField) LogValue() slog.Value

func (ExistingProjectField) MarshalJSON

func (ExistingProjectField) MarshalJSON() ([]byte, error)

func (ExistingProjectField) MarshalText

func (ExistingProjectField) MarshalText() ([]byte, error)

func (ExistingProjectField) String

func (ExistingProjectField) String() string

type ExistingProjectSealingStore

type ExistingProjectSealingStore interface {
	ExistingHierarchyStore
	ActiveProjectVersion(context.Context, string, string) (uint32, error)
}

ExistingProjectSealingStore additionally identifies the active write version.

type InstanceFieldAAD

type InstanceFieldAAD struct {
	OwnerTable, OwnerRowID, FieldTag string
}

InstanceFieldAAD covers instance-scoped sensitive fields (MFA seeds, recovery codes, instance credentials): fields owner_table, owner_row_id, field_tag.

type InstanceSealer

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

InstanceSealer seals and opens instance-scoped fields under the instance DEK. It accepts only instance_field envelopes — the type system, not a runtime branch, keeps project-owned material out of the instance domain.

Like ProjectSealer, it captures its write-side handle at construction (a point-in-time snapshot of the active version) so Version() and the writer fence agree on the version a row was actually sealed under, even if a rotate-dek adopts a new active between ForInstance and the fenced commit. The old key buffer is never zeroed on instance-DEK adoption (ReloadInstanceDEK / the rotation adopt swap the atomic set and let the GC reclaim it), so a captured handle stays usable — which is exactly the stale write the fence then rejects. Reads (OpenField) resolve every version live and are unaffected.

func (InstanceSealer) GoString

func (InstanceSealer) GoString() string

func (InstanceSealer) LogValue

func (InstanceSealer) LogValue() slog.Value

func (InstanceSealer) MarshalJSON

func (InstanceSealer) MarshalJSON() ([]byte, error)

func (InstanceSealer) MarshalText

func (InstanceSealer) MarshalText() ([]byte, error)

func (*InstanceSealer) OpenField

func (s *InstanceSealer) OpenField(a InstanceFieldAAD, record []byte) ([]byte, error)

func (*InstanceSealer) SealField

func (s *InstanceSealer) SealField(a InstanceFieldAAD, plaintext []byte) ([]byte, error)

func (InstanceSealer) String

func (InstanceSealer) String() string

func (*InstanceSealer) Version

func (s *InstanceSealer) Version() uint32

Version reports the instance DEK version this sealer writes under — the active version captured when the sealer was built. Credential rows record it so `reencrypt` knows which rows it has already moved, and so the writer fence's compare-and-swap has the sealed version, not a live re-read, to check.

type KeyStore

type KeyStore interface {
	// ActiveMasterWrappers returns every active wrapper of the master key —
	// one per root epoch; two during a dual-wrapped root rotation; empty at
	// first boot.
	ActiveMasterWrappers(ctx context.Context) ([]WrappedKey, error)
	ActiveTier3(ctx context.Context, p Purpose, orgID, projectID string) (WrappedKey, error)
	// Tier3Versions returns every still-openable version of one scope's key —
	// the active version plus every retiring version a reencrypt has not yet
	// walked — newest first. Empty (not ErrNoKey) when the scope has no key.
	// The keyring loads all of them so a sealer can open ciphertext written
	// under a superseded DEK version while sealing new writes under the active.
	Tier3Versions(ctx context.Context, p Purpose, orgID, projectID string) ([]WrappedKey, error)
	// AllOpenableTier3 returns every still-openable tier-3 key (active +
	// retiring) across every scope, for rotate-master-key to re-wrap them all
	// under a new master.
	AllOpenableTier3(ctx context.Context) ([]WrappedKey, error)
	// CreateHierarchy persists the first-boot key set (master + tier-3 keys)
	// atomically. A concurrent first boot returns ErrKeyExists.
	CreateHierarchy(ctx context.Context, master WrappedKey, tier3 []WrappedKey) error
	// CreateTier3 persists one new tier-3 key. Same-scope race returns
	// ErrKeyExists; a retired MasterKeyVersion returns ErrStaleMaster.
	CreateTier3(ctx context.Context, key WrappedKey) error
}

KeyStore is the persistence seam. internal/store/keyring implements it; every method that creates keys must run in one transaction, acquire the hierarchy generation (the fence that serializes tier-3 key creation against master rotation — encryption-model ADR § Rotation), and for tier-3 creation verify the key's MasterKeyVersion is still the active master inside that fence (ErrStaleMaster otherwise).

type Keyring

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

Keyring holds the unwrapped key hierarchy for the server process — the only mode that ever constructs one. Master key, instance DEK and root token key live unwrapped for the process lifetime; project DEKs are unwrapped on demand into a bounded LRU.

func LoadKeyring

func LoadKeyring(ctx context.Context, ks KeyStore, root []byte) (*Keyring, error)

LoadKeyring unwraps (or, at first startup, mints) the key hierarchy. It consumes root: the root key is zeroed before returning, success or failure — it is re-read from its source when rotation needs it again.

func (*Keyring) ChangeToken

func (k *Keyring) ChangeToken(orgID, projectID, envID string, manifest []byte) (string, error)

ChangeToken is HMAC-SHA256(scopedTokenKey, manifest), base64url, prefixed.

Keyed, never a bare digest, and the revision-model ADR's reasoning is worth restating because the naive version looks fine: a bare digest over delivered content is a function of secret plaintexts, so a low-entropy secret is brute-forceable offline by anyone holding the digest — and the Kubernetes operator writes this value into a pod-template annotation, readable by every principal who can read Deployments but not Secrets. A keyed token is unforgeable and un-invertible without the key.

The key is derived per (org, project, environment), so a token is meaningful only within the environment that produced it. A single global key would make tokens comparable ACROSS scopes: an attacker who can write values in their own project constructs a candidate payload, reads its token, and compares it against a target environment's pod annotation.

func (*Keyring) ClearRootRotationPending

func (k *Keyring) ClearRootRotationPending()

ClearRootRotationPending records that the pending root rotation has been finalized in this process, so RootRotationPending stops reporting the dual-wrapped state without waiting for a reboot.

func (*Keyring) DeliveryCursor

func (k *Keyring) DeliveryCursor(orgID, projectID, envID string, tuple []byte) (string, error)

DeliveryCursor is HMAC-SHA256(scoped cursor key, tuple), base64url, prefixed.

The caller passes the whole four-tuple encoding — change token, authorized delivery projection, authorization revision, pin generation — and the server answers "current" only when the cursor it recomputes equals the one presented. That makes the cursor OPAQUE by construction rather than by convention: there is nothing inside it to parse, and a caller cannot construct one for a state it has not been served.

It also means there is no cursor-versioning machinery, and none is needed: a mismatch produces a full authorized delivery, so changing what the tuple covers is always safe. When real revisions replace the manifest computation behind this seam, every outstanding cursor mismatches once and every caller re-syncs.

func (*Keyring) DeliveryTokenSnapshot

func (k *Keyring) DeliveryTokenSnapshot(row WrappedKey, orgID, projectID, envID string) (*DeliveryTokenSnapshot, error)

func (*Keyring) EvictProjectDEK

func (k *Keyring) EvictProjectDEK(orgID, projectID string)

EvictProjectDEK drops a project scope from the DEK cache so the next ForProject rebuilds its version set from the store. reencrypt calls it after retiring the scope's retiring versions, so a cached sealer stops offering them. Not zeroed: a concurrent sealer built before the retire may still alias the buffers, and a zeroed-key open would be a silent failure — the Go GC reclaims them.

func (*Keyring) ForInstance

func (k *Keyring) ForInstance() *InstanceSealer

ForInstance returns the sealer for instance-scoped sensitive fields. It snapshots the active write-handle now, so the sealer keeps sealing under the version live at this moment even across a concurrent rotate-dek adoption — the writer fence rejects that stale write at commit.

func (*Keyring) ForProject

func (k *Keyring) ForProject(ctx context.Context, orgID, projectID string) (*ProjectSealer, error)

ForProject returns the sealer for one project's key domain, minting the project DEK on first use. The sealer only accepts value and project_field envelopes whose AAD names exactly this org and project — a project-owned secret can never land under the instance DEK (CI invariant 16).

func (Keyring) GoString

func (Keyring) GoString() string

func (*Keyring) LockHierarchyRotation

func (k *Keyring) LockHierarchyRotation()

LockHierarchyRotation / UnlockHierarchyRotation serialize master and root rotations process-wide (see hierarchyRotationMu). The caller holds the lock across the entire rotation — prepare, the store transaction, and adopt/abort.

func (Keyring) LogValue

func (Keyring) LogValue() slog.Value

func (*Keyring) MCPCursorSealer

func (k *Keyring) MCPCursorSealer() (*MCPCursorSealer, error)

MCPCursorSealer builds the instance-wide sealer that encrypts and authenticates MCP pagination cursors. It derives from the live root token key on each Seal and Open, so rotate-token-key invalidates old cursors atomically instead of a boot-time cached key splitting this process from a restarted replica. The cursor payload binds the tool and exact scope ids, so one instance-wide key suffices and every replica derives the same key from shared key material.

func (Keyring) MarshalJSON

func (Keyring) MarshalJSON() ([]byte, error)

func (Keyring) MarshalText

func (Keyring) MarshalText() ([]byte, error)

func (*Keyring) OccurrenceToken

func (k *Keyring) OccurrenceToken(orgID, projectID, envID string, encoding []byte) (string, error)

OccurrenceToken is HMAC-SHA256(scoped occurrence key, encoding), base64url, prefixed — the server-minted opaque token an import's phase 1 records per (key, environment) and phase 2 verifies inside its own authorized transaction.

Keyed rather than a bare digest, and SCOPED per (org, project, environment), for the reason the change token is: a global key would make tokens comparable across scopes, so an attacker who can write values in their own project could construct a candidate state, read its token, and test it against a target environment's manifest. Scoped and keyed, an edited or fabricated manifest cannot phrase a question about someone else's state that the server will answer — an unrecognized token recomputes to a mismatch exactly like a stale one, which is what makes the two indistinguishable to a caller.

The caller owns the encoding (internal/delivery.EncodeOccurrence); this package receives bytes and returns a token.

func (*Keyring) PrepareInstanceDEKRotation

func (k *Keyring) PrepareInstanceDEKRotation() (WrappedKey, func(), error)

PrepareInstanceDEKRotation mints the next instance DEK version and returns the adopt function that installs it. Unlike a project DEK the instance set is held for the process lifetime, so adoption swaps in a new set carrying the new active version alongside every still-openable retiring version. Monotonic: a late or losing adopt whose version does not advance the live set is a no-op.

func (*Keyring) PrepareMasterKeyRotation

func (k *Keyring) PrepareMasterKeyRotation(ctx context.Context, root []byte) (newRow WrappedKey, rewrapped []WrappedKey, adopt, abort func(), err error)

PrepareMasterKeyRotation generates a new master key, re-wraps every openable tier-3 key under it, and returns the new master row, the re-wrapped tier-3 rows, and the adopt function. root is the current operator root, re-read from its source (the master is wrapped by the root, and the root is zeroed after boot); the caller zeroes it after this returns.

It refuses while the root is dual-wrapped (more than one active master wrapper): the two rotations are mutually exclusive per the ADR, and the store re-checks the count inside the hierarchy fence. Key bytes are unchanged — only the wrapping master and the wrapping AAD move — so cached DEK handles stay valid and adoption swaps only the master, never the DEK caches.

The new master is made RESOLVABLE (but not active) here, before the store transaction, so a tier-3 cache miss in the window between the store commit and adopt() resolves the new master version rather than failing. adopt() switches active forward after the commit; abort() removes and zeroes the new master if the transaction never commits — the caller defers abort and cancels it on success.

func (*Keyring) PrepareNewProject

func (k *Keyring) PrepareNewProject(orgID, projectID string) (WrappedKey, *ProjectSealer, error)

PrepareNewProject creates the encryption material for an atomic project provision. It performs no datastore write and does not populate the keyring cache. The caller persists the returned wrapper in the same transaction as the new project and its initial encrypted values. Existing projects must use ForProject; the datastore's unique active-key constraint refuses replacement.

func (*Keyring) PrepareProjectDEKRotation

func (k *Keyring) PrepareProjectDEKRotation(ctx context.Context, orgID, projectID string) (WrappedKey, func(), error)

PrepareProjectDEKRotation mints the next version of a project DEK and returns its wrapped row plus the adopt function. Like the token rotation, the split exists because the persistence closure runs in a retryable transaction: only the attempt that commits may adopt. Project DEK adoption is a cache eviction — the next ForProject rebuilds the version set from the store, picking up the new active version and the demoted retiring one — so a rolled-back attempt that never adopts leaves nothing behind.

func (*Keyring) PrepareRootKeyRotation

func (k *Keyring) PrepareRootKeyRotation(ctx context.Context, newRoot []byte) (WrappedKey, error)

PrepareRootKeyRotation seals the active master under a new root at the next epoch, producing the second wrapper of the dual-wrapped transition. The master is already unwrapped in memory, so this needs only the NEW root (the operator's new-root source) — no current root, and no data is touched.

It refuses unless there is exactly one active master wrapper: a second prepare while one is pending, or master rotation mid-flight, would build the four-way root×master matrix the ADR refuses.

func (*Keyring) PrepareScanningKeyRotation

func (k *Keyring) PrepareScanningKeyRotation() (WrappedKey, func(), func(), error)

PrepareScanningKeyRotation mints the next scanning-fingerprint key and returns its wrapped row plus mutually exclusive adopt and abort functions, mirroring PrepareTokenKeyRotation: the material never leaves this package, the caller defers abort, persists the row inside its own authorized transaction, and adopt runs only AFTER that transaction commits.

`rotate-scanning-key` is OUTRIGHT REPLACEMENT (secret-scanning ADR §4): there is no version keyring and no reencrypt walk, because a fingerprint is a keyed digest, not a ciphertext to preserve — old fingerprints MUST die, that is the operation's purpose, and every dismissal row is dropped in the same transaction (re-fire, the safe direction). The row still carries a monotonically increasing version for the same reason the token key does: the version is bound into the wrapping AAD and the store retires the predecessor by a compare-and-swap on it, so two concurrent rotations resolve to one winner rather than a torn handle.

The superseded key is NOT zeroed: a concurrent fingerprint may still be holding the buffer, and computing under a zeroed key would be a silent break rather than a loud failure — the same reason the token key and the DEK cache do not zero superseded material.

func (*Keyring) PrepareTokenKeyRotation

func (k *Keyring) PrepareTokenKeyRotation() (WrappedKey, func(), func(), error)

PrepareTokenKeyRotation mints the next root token key and returns its wrapped row plus mutually exclusive adopt and abort functions. The material never leaves this package: the caller defers abort, persists the row inside its own authorized transaction, and calls adopt only AFTER that transaction commits.

The split exists because the persistence closure runs inside a retryable transaction: an attempt that is rolled back and retried mints fresh material each time, and only the attempt that actually committed may become the live key. Adopting inside the closure would leave the process serving tokens under a key version the datastore does not record.

THERE IS NO TOKEN CACHE TO INVALIDATE. The encryption-model ADR's rotation protocol exists because "rotate the key and tokens change" is false when tokens are served from a cache; here a token is derived from the live key on every read and no snapshot stores one, so adopting the new handle IS the whole rotation. Every current published snapshot serves a token under the new key from the next read onward, and no snapshot's content, revision number or pinned input revisions move (encryption-model ADR CI invariant 15, mvp-boundary C4).

The superseded key is NOT zeroed. A concurrent derivation may still be holding the buffer, and deriving under a zeroed key would be a silent confidentiality break rather than a loud failure — the same reason the DEK cache does not zero evicted entries.

func (*Keyring) PublishPreviewToken

func (k *Keyring) PublishPreviewToken(orgID, projectID, envID string, encoding []byte) (string, error)

PublishPreviewToken binds a reviewed publish preview to its exact scoped inputs. It has its own derivation label so a preview token is never usable as a delivery cursor, occurrence token, or change token.

func (*Keyring) ReloadInstanceDEK

func (k *Keyring) ReloadInstanceDEK(ctx context.Context) error

ReloadInstanceDEK rebuilds the instance DEK version set from the store, dropping versions no longer openable. reencrypt --instance calls it after retiring the instance scope's retiring versions, so the held set stops offering them.

func (*Keyring) RootRotationPending

func (k *Keyring) RootRotationPending() bool

RootRotationPending reports whether this instance booted with a root rotation half-done (the master dual-wrapped under two roots). Boot warns on it every start until `rotate-root-key --finalize` — a rotation half-done must be visible, not silent.

func (*Keyring) ScanningFingerprint

func (k *Keyring) ScanningFingerprint(orgID, projectID, envID, keyID string, value []byte) []byte

ScanningFingerprint is the keyed value a dismissal row stores in place of the offending value: HMAC-SHA256 over the domain-separation label, the scope binding (org, project, environment, key identity) and the canonical stored value bytes, each length-prefixed with the same injective encoding the AADs use.

fingerprint = HMAC-SHA256(scanningKey,
    LP(label) ‖ LP(org) ‖ LP(project) ‖ LP(env) ‖ LP(key) ‖ LP(value))

The length-prefixing is load-bearing exactly as it is for the change token: raw concatenation would let ("a","bc") and ("ab","c") — or a value whose leading bytes shift a scope boundary — collide, resurrecting a cross-scope equality oracle. Deterministic for identical inputs (a re-saved value re-fingerprints to the same bytes, so a sticky dismissal recognises it) and distinct across any scope change, including a different key identity for the same value. `value` is the canonical stored bytes (post-trim — exactly what the value write persists), passed in by the caller; this package neither trims nor interprets it.

func (*Keyring) SelfConfigAdoptionToken

func (k *Keyring) SelfConfigAdoptionToken(owner string, encoded []byte) (string, error)

SelfConfigAdoptionToken binds the server's one-time seed to its owning instance. The dedicated derivation label keeps preview and HA comparison tokens separate from delivery, scanning and authentication artifacts.

func (*Keyring) SetHAFreshness

func (k *Keyring) SetHAFreshness(on bool)

SetHAFreshness turns per-fetch project-DEK cache revalidation on. Boot calls it once under HA before serving. See the haFreshness field.

func (Keyring) String

func (Keyring) String() string

func (*Keyring) UnlockHierarchyRotation

func (k *Keyring) UnlockHierarchyRotation()

func (*Keyring) VerifyRootKeyRotation

func (k *Keyring) VerifyRootKeyRotation(ctx context.Context, primaryRoot []byte) (uint32, error)

VerifyRootKeyRotation confirms the operator has installed the new root at the PRIMARY source: primaryRoot (re-read from that source) must unwrap the new-epoch wrapper to the live master. It reads and decides only — the dual wrapper is already committed by prepare — so a failed verify is safe to retry after the operator fixes the source.

type Kind

type Kind byte

Kind is the envelope kind byte. It selects the AAD schema, so identifiers from different tables can never collide into the same context.

const (
	KindValue           Kind = 1
	KindWrappedDEK      Kind = 2
	KindWrappedMaster   Kind = 3
	KindWrappedTokenKey Kind = 4
	KindProjectField    Kind = 5
	KindInstanceField   Kind = 6
	// KindComposeSnapshot is the client-side offline snapshot container added
	// by declared amendment 5 to the encryption-model ADR (compose-integration
	// ADR § Offline behaviour). It is outside the server key hierarchy but uses
	// the same envelope primitive; its AAD schema is SnapshotAAD in client.go.
	KindComposeSnapshot Kind = 7
)
const KindTransit Kind = 8

KindTransit is the caller-facing transit ciphertext envelope. Its AAD schema is TransitAAD. Kind bytes are persisted format: never renumber.

type LocalKeys

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

LocalKeys is the two derived client keys. Callers hold it for the life of a render/fetch and let it go; the underlying local key stays on disk 0600.

func LoadOrCreateLocalKey

func LoadOrCreateLocalKey(dir string) (*LocalKeys, error)

LoadOrCreateLocalKey loads the local key from dir/local.key, creating it (and dir) on first use. The state directory MUST be 0700 and the key file 0600, both owned by the invoking user (system-architecture ADR § Client local state — protection model). Every access goes through directory-relative, no-symlink-follow descriptors (§ *Client local state*): the directory is opened with O_NOFOLLOW and its mode/ownership verified through the descriptor (never a path stat followed by a separate open), and the key is opened relative to that directory. A directory or key that is a symlink, group/other-accessible, or not owned by the euid is REFUSED, not repaired.

func (LocalKeys) GoString

func (LocalKeys) GoString() string

func (LocalKeys) LogValue

func (LocalKeys) LogValue() slog.Value

func (LocalKeys) MarshalJSON

func (LocalKeys) MarshalJSON() ([]byte, error)

func (LocalKeys) MarshalText

func (LocalKeys) MarshalText() ([]byte, error)

func (*LocalKeys) OpenSnapshot

func (k *LocalKeys) OpenSnapshot(headerCanonical, record []byte) ([]byte, error)

OpenSnapshot decrypts a snapshot payload, requiring the associated data to be byte-identical to the header bytes sealed alongside it. Any tampered header/payload byte fails as ErrDecrypt.

func (*LocalKeys) SealSnapshot

func (k *LocalKeys) SealSnapshot(headerCanonical, plaintext []byte) ([]byte, error)

SealSnapshot encrypts plaintext under the snapshot key with headerCanonical as the associated data — reusing the module's XChaCha20-Poly1305 envelope (versioned header, fresh 192-bit nonce). The caller passes the exact canonical header bytes it also stores in the container, so the cleartext header is authenticated by the AEAD.

func (*LocalKeys) Stamp

func (k *LocalKeys) Stamp(content []byte) string

Stamp is "v1-" + hex(HMAC-SHA256(stampKey, stampDomain+content)[:16]) — 128 bits, 32 lowercase hex, version-prefixed. Keyed, never a bare content digest: a bare digest over rendered content is a function of secret plaintexts and so brute-forceable offline by anyone holding it (compose ADR § "The stamp is keyed, never a content digest", inheriting the revision ADR's rule).

func (LocalKeys) String

func (LocalKeys) String() string

type MCPCursorSealer

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

MCPCursorSealer encrypts and authenticates opaque MCP pagination cursors (#629) with XChaCha20-Poly1305 under an instance-wide derived key. Encryption is required because the keyset position can be a tenant-controlled name, which must not appear in the cursor. The crypto chokepoint owns the primitive; the transport holds only the narrow Seal/Open verbs.

func (*MCPCursorSealer) Open

func (s *MCPCursorSealer) Open(ctx context.Context, token string) ([]byte, error)

Open verifies one cursor token and returns its payload. Every malformed or unauthenticated token returns ErrCursorInvalid without distinguishing which.

func (*MCPCursorSealer) Seal

func (s *MCPCursorSealer) Seal(ctx context.Context, payload []byte) (string, error)

Seal authenticates and encodes one cursor payload.

type PasswordParams

type PasswordParams struct {
	MemoryKiB   uint32
	Time        uint32
	Parallelism uint8
}

PasswordParams are the Argon2id cost parameters recorded per verifier. Serving configuration must match live-epoch credentials: changing costs requires deliberate credential re-establishment, not a silent login lockout.

func (PasswordParams) CheckFloor

func (p PasswordParams) CheckFloor() error

CheckFloor is the boot check. Fail fast, fail loud: an installation configured below the floor does not start.

func (PasswordParams) Plausible

func (p PasswordParams) Plausible() bool

Plausible reports whether recorded parameters are within the bounds a verification may be run under. It is deliberately separate from CheckFloor: the floor is policy about NEW verifiers, this is safety about OLD ones.

type ProjectFieldAAD

type ProjectFieldAAD struct {
	OrgID, ProjectID, OwnerTable, OwnerRowID, FieldTag string
	EnvironmentID, KeyID, SnapshotID                   string
}

ProjectFieldAAD covers project-scoped sensitive fields outside the value table: fields org_id, project_id, owner_table, owner_row_id, field_tag.

EnvironmentID, KeyID and SnapshotID are the optional owner coordinates used by value-bearing project-field rows whose identity is wider than their row id. They are appended only when at least one is present, preserving the AAD of every pre-existing project-field record while binding new draft and snapshot rows against same-id metadata relocation.

type ProjectSealer

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

ProjectSealer seals and opens ciphertext in one project's key domain. It holds every still-openable DEK version for the scope: new writes seal under the active version, reads resolve the version named in the record's header, so a sealer opens ciphertext a reencrypt has not yet moved off a superseded version. The set is fixed at construction — a rotation that lands after this sealer is built is picked up by the next ForProject, not by this instance.

func (*ProjectSealer) ActiveVersion

func (s *ProjectSealer) ActiveVersion() uint32

ActiveVersion is the DEK version new writes seal under. reencrypt compares it against a record's header version to decide whether the row is already current and can be skipped.

func (ProjectSealer) GoString

func (ProjectSealer) GoString() string

func (ProjectSealer) LogValue

func (ProjectSealer) LogValue() slog.Value

func (ProjectSealer) MarshalJSON

func (ProjectSealer) MarshalJSON() ([]byte, error)

func (ProjectSealer) MarshalText

func (ProjectSealer) MarshalText() ([]byte, error)

func (*ProjectSealer) Open

func (s *ProjectSealer) Open(a AAD, record []byte) ([]byte, error)

Open and Seal are the AAD-kind-generic forms of OpenValue/OpenField and SealValue/SealField, for reencrypt's table-agnostic walk. They dispatch on the AAD's concrete type to apply the scope check, then resolve the record's version (Open) or seal under the active version (Seal). A sealer built for one project rejects an AAD naming another.

func (*ProjectSealer) OpenField

func (s *ProjectSealer) OpenField(a ProjectFieldAAD, record []byte) ([]byte, error)

func (*ProjectSealer) OpenValue

func (s *ProjectSealer) OpenValue(a ValueAAD, record []byte) ([]byte, error)

func (*ProjectSealer) Seal

func (s *ProjectSealer) Seal(a AAD, plaintext []byte) ([]byte, error)

func (*ProjectSealer) SealField

func (s *ProjectSealer) SealField(a ProjectFieldAAD, plaintext []byte) ([]byte, error)

func (*ProjectSealer) SealValue

func (s *ProjectSealer) SealValue(a ValueAAD, plaintext []byte) ([]byte, error)

func (ProjectSealer) String

func (ProjectSealer) String() string

type Purpose

type Purpose string

Purpose distinguishes the tier-3 keys: one DEK per project, one instance DEK for rows belonging to no project, the root token key (derivation only, never encryption), and the scanning-fingerprint key (secret-scanning amendment — derivation only, one instance-scoped key for dismissal fingerprints).

const (
	PurposeProject  Purpose = "project"
	PurposeInstance Purpose = "instance"
	PurposeToken    Purpose = "token"
	// PurposeScanning is the instance-scoped scanning-fingerprint key
	// (secret-scanning ADR §4, encryption-model amendment): a tier-3 sibling of
	// the instance DEK and token key, used only to compute dismissal-row value
	// fingerprints and for nothing else. Like the token key it is derivation
	// material, never an envelope key, and it wraps under the existing
	// wrapped_dek kind.
	PurposeScanning Purpose = "scanning"
)

type SnapshotAAD

type SnapshotAAD struct {
	InstanceOrigin string `json:"instance_origin"`
	OrgID          string `json:"org_id"`
	ProjectID      string `json:"project_id"`
	EnvironmentID  string `json:"environment_id"`
	// CredentialID is the server-asserted credential id. It is authenticated
	// metadata (bound into the AAD, returned to the caller for the offline
	// records' credential_id) but is not locally knowable: it is a mutable on-disk
	// value the box could rewrite, so it supplies no offline expectation.
	CredentialID string `json:"credential_id"`
	// CredentialFingerprint is the LOCAL, offline-derivable identity of the
	// credential the snapshot was fetched with — hex(sha256(domain ‖ token)). The
	// CLI recomputes it from the PRESENTED token at load and ContextMatches
	// refuses the snapshot by name if it differs, so a rotated token cannot serve
	// the old snapshot even fully offline (nothing mutable on disk supplies the
	// expectation — the presented token does).
	CredentialFingerprint string `json:"credential_fingerprint"`
	ConfigOnly            bool   `json:"config_only"`
	// TargetNames is the render-target id set.
	TargetNames []string `json:"target_names"`
	// PinnedRevision is the resolved historical revision when the snapshot was
	// served from a pin, or 0 when serving current material (unpinned). It
	// replaces the earlier Revision+Pinned pair: a pin is exactly a non-zero
	// resolved revision, so one field is both necessary and sufficient.
	PinnedRevision int64 `json:"pinned_revision"`
	// ChangeToken is the server's keyed delivery-manifest token (`v1:`-prefixed),
	// on the wire on BOTH the delivering and config-only dispositions. It is the
	// resolved-content identity the client actually holds: an unpinned "current"
	// revision is NOT on the wire, so PinnedRevision alone cannot distinguish two
	// current snapshots with the same issuance but different content. Binding the
	// token into the header makes the header — and therefore the HWM digest over
	// it — differ whenever the delivered content differs (compose ADR § Expiry,
	// clocks and rollback). The offline box cannot reconstruct it without the
	// server; ParseSnapshotBinding recovers it from the authenticated header.
	ChangeToken string `json:"change_token"`
	// Projection is the authorized delivery capability list.
	Projection []string `json:"projection"`
	IssuedAt   string   `json:"issued_at"`
	ExpiresAt  string   `json:"expires_at"`
}

SnapshotAAD is the stable serialized form derived from SnapshotBinding. Its field names and declaration order are persisted protocol data for HKS1 containers. Runtime save/load code accepts SnapshotBinding instead, so this mutable serialization DTO cannot bypass binding validation.

The list fields (Projection, TargetNames) are sorted and deduplicated INSIDE Canonical(), so a caller-visible ordering choice or an accidental duplicate cannot change the authenticated bytes: identical sets always canonicalize identically.

IssuedAt and ExpiresAt are the EXACT RFC3339 UTC strings the server returned; they are carried verbatim, never re-formatted through time.Time. InstanceOrigin is the instance identity the client actually holds: the client's trust store is origin-keyed, so the origin is the stable identity it can compare offline.

func ParseSnapshotHeader

func ParseSnapshotHeader(b []byte) (SnapshotAAD, error)

ParseSnapshotHeader decodes canonical header bytes back into a SnapshotAAD.

func (SnapshotAAD) Canonical

func (a SnapshotAAD) Canonical() ([]byte, error)

Canonical is the deterministic header-bytes encoding of the full AAD tuple: the two list fields are sorted and deduplicated, then the struct is marshalled to JSON (Go marshals struct fields in declaration order, so the bytes are stable). These bytes are BOTH the cleartext container header and the AEAD's associated data, so tampering the header fails the open.

type SnapshotBinding

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

SnapshotBinding carries one validated snapshot identity through both live and offline paths. Its scope-only state is valid for locating and checking an offline snapshot. Its delivery-complete state additionally owns every field required to derive the serialized SnapshotAAD.

Fields are private so list canonicalization and issuance-window validation cannot be bypassed by mutation after construction.

func NewSnapshotBinding

func NewSnapshotBinding(scope SnapshotBindingScope) (SnapshotBinding, error)

NewSnapshotBinding validates and owns the locally derivable snapshot scope.

func ParseSnapshotBinding

func ParseSnapshotBinding(storageDir string, header []byte) (SnapshotBinding, error)

ParseSnapshotBinding validates an existing serialized AAD header without changing its field names, ordering, or timestamp spellings.

func (SnapshotBinding) AAD

func (b SnapshotBinding) AAD() (SnapshotAAD, error)

AAD derives a detached serialization value from a complete binding. Slices are copied, so mutating the returned DTO cannot mutate the binding.

func (SnapshotBinding) CanonicalAAD

func (b SnapshotBinding) CanonicalAAD() ([]byte, error)

CanonicalAAD derives the stable serialized AAD bytes from a complete binding.

func (SnapshotBinding) ContextMatches

func (b SnapshotBinding) ContextMatches(expect SnapshotBinding) error

ContextMatches compares the locally knowable scope of two validated bindings. Server-only delivery fields are intentionally not expectations on an offline box.

func (SnapshotBinding) LegacyStorageKey

func (b SnapshotBinding) LegacyStorageKey() (string, error)

LegacyStorageKey identifies the former directory-dependent cache slot. It is used only to retain existing high-water marks during migration.

func (SnapshotBinding) StorageDir

func (b SnapshotBinding) StorageDir() (string, error)

StorageDir returns the validated local storage locator owned by the binding. It is intentionally absent from SnapshotAAD: moving a state directory does not change cryptographic or serialized snapshot identity.

func (SnapshotBinding) StorageKey

func (b SnapshotBinding) StorageKey() (string, error)

StorageKey identifies the complete locally known snapshot scope without exposing any part of it in a filename. Run, render, config-only, credentials, and target sets therefore retain independent offline caches and high-water marks inside the same stack state directory. The directory itself is only a locator and does not affect this identity.

func (SnapshotBinding) ValidateScope

func (b SnapshotBinding) ValidateScope() error

ValidateScope reports whether the binding can safely identify an offline snapshot. Both scope-only and delivery-complete bindings are valid locators.

func (SnapshotBinding) WithDelivery

func (b SnapshotBinding) WithDelivery(delivery SnapshotBindingDelivery) (SnapshotBinding, error)

WithDelivery returns a delivery-complete binding. A binding can be completed once only, preventing accidental reconstruction with a second response.

type SnapshotBindingDelivery

type SnapshotBindingDelivery struct {
	CredentialID   string
	PinnedRevision int64
	ChangeToken    string
	Projection     []string
	IssuedAt       string
	ExpiresAt      string
}

SnapshotBindingDelivery is the server-asserted remainder of a snapshot binding. WithDelivery adds it atomically: callers cannot construct a binding containing only some revision, projection, or issuance fields.

type SnapshotBindingScope

type SnapshotBindingScope struct {
	StorageDir            string
	InstanceOrigin        string
	OrgID                 string
	ProjectID             string
	EnvironmentID         string
	CredentialFingerprint string
	ConfigOnly            bool
	TargetNames           []string
}

SnapshotBindingScope is the locally known identity of one offline snapshot. It is validated and copied by NewSnapshotBinding before it can be used for a filesystem lookup or compared with an authenticated snapshot header.

type StampPair

type StampPair struct {
	SecretKey string
	Value     string
}

StampPair is one delivered `(secretKey, value)` the stamp covers. `secretKey` is the managed Secret's DATA key (the mapping's destination name), not the Hikyo source key — the annotation follows what the workload consumes, and a destination rename is a delivery change the stamp must move on (cursor eligibility § 0.5 binds the same mapping digest).

type TransitAAD

type TransitAAD struct {
	OrgID, ProjectID, EnvID, KeyID string
	Context                        []byte
}

TransitAAD binds a transit ciphertext to one key in one environment and to the caller's context: fields org_id, project_id, env_id, transit_key_id, context. The key version is already in the authenticated header.

type TransitAlgorithm

type TransitAlgorithm string

TransitAlgorithm is the closed algorithm set of transit ADR D2. The algorithm fixes the key's purpose for its whole life.

const (
	TransitXChaCha20Poly1305 TransitAlgorithm = "xchacha20-poly1305"
	TransitEd25519           TransitAlgorithm = "ed25519"
	TransitHMACSHA256        TransitAlgorithm = "hmac-sha256"
)

func ParseTransitAlgorithm

func ParseTransitAlgorithm(s string) (TransitAlgorithm, error)

ParseTransitAlgorithm refuses anything outside the closed set.

func TransitAlgorithms

func TransitAlgorithms() []TransitAlgorithm

TransitAlgorithms returns the closed algorithm set in a stable order.

type TransitBinding

type TransitBinding struct {
	Algorithm                      TransitAlgorithm
	OrgID, ProjectID, EnvID, KeyID string
	Version                        uint32
}

TransitBinding names exactly one key version. Every derived key is bound to all of it, so material copied onto another key, version or environment derives a different operation key.

type TransitKey

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

TransitKey is one version's derived operation key, held only for the span of one operation. It carries no exported field and redacts itself in every formatting surface. Destroy zeroes it.

func OpenTransitKey

func OpenTransitKey(material []byte, b TransitBinding) (*TransitKey, error)

OpenTransitKey derives the operation key for one version from its material. The material is not retained; the caller zeroes it. Invalid bindings, material of the wrong size, and key derivation failures return errors.

func (*TransitKey) Decrypt

func (k *TransitKey) Decrypt(record, context []byte) ([]byte, error)

Decrypt opens a transit envelope record. The header must name this key and this version, and the AAD must match this binding and context. A nil or non-XChaCha20-Poly1305 key returns an algorithm error. Oversized context or plaintext and all record parsing or authentication failures return ErrDecrypt.

func (*TransitKey) Destroy

func (k *TransitKey) Destroy()

Destroy zeroes the derived key. Best effort, like every Zero.

func (*TransitKey) Encrypt

func (k *TransitKey) Encrypt(plaintext, context []byte) ([]byte, error)

Encrypt seals plaintext as a transit envelope record under this version, binding context as associated data. A nil or non-XChaCha20-Poly1305 key is an error. Plaintext over MaxTransitPlaintextBytes or context over MaxTransitContextBytes returns ErrTransitFormat; sealing errors propagate.

func (TransitKey) GoString

func (TransitKey) GoString() string

func (TransitKey) LogValue

func (TransitKey) LogValue() slog.Value

func (*TransitKey) MAC

func (k *TransitKey) MAC(message []byte) ([]byte, error)

MAC is HMAC-SHA256 under the derived key over the message bytes. A nil or non-HMAC key returns an error; messages over MaxTransitPlaintextBytes return ErrTransitFormat.

func (TransitKey) MarshalJSON

func (TransitKey) MarshalJSON() ([]byte, error)

func (TransitKey) MarshalText

func (TransitKey) MarshalText() ([]byte, error)

func (*TransitKey) PublicKey

func (k *TransitKey) PublicKey() ([]byte, error)

PublicKey returns a copy of the Ed25519 public key. It is public metadata: storing and returning it discloses nothing about the private half. A nil key or a non-Ed25519 key returns an error.

func (*TransitKey) Sign

func (k *TransitKey) Sign(message []byte) ([]byte, error)

Sign is pure Ed25519 over the message bytes, so any RFC 8032 verifier holding the public key can check it without Hikyo. A nil or non-Ed25519 key returns an error; messages over MaxTransitPlaintextBytes return ErrTransitFormat.

func (TransitKey) String

func (TransitKey) String() string

type ValueAAD

type ValueAAD struct {
	OrgID, ProjectID, EnvID, KeyID, RowID, FieldTag string
}

ValueAAD binds a stored value ciphertext to exactly one row: kind `value`, fields org_id, project_id, env_id, key_id, row_id, field_tag. (env_id per the flat-model amendment to the encryption-model ADR — every value row has an owning environment.)

type WrappedDEKAAD

type WrappedDEKAAD struct {
	OrgID, ProjectID, DEKID      string
	DEKVersion, MasterKeyVersion uint32
}

WrappedDEKAAD covers tier-3 keys wrapped by the master key: project DEKs, the instance DEK (empty org/project), and — per the secret-scanning amendment — the future scanning-fingerprint key. Fields org_id, project_id, dek_id, dek_version, master_key_version.

type WrappedKey

type WrappedKey struct {
	ID               string  // tier-3 key id; empty for the master key
	Purpose          Purpose // tier-3 only
	OrgID, ProjectID string  // empty for instance-scoped keys and the master
	Version          uint32
	MasterKeyVersion uint32 // tier-3 only: the master version that wraps it
	RootKeyEpoch     uint32 // master only: the root epoch that wraps it
	Blob             []byte
	CreatedAt        time.Time
}

WrappedKey is a stored, wrapped key row. Blob is a versioned ciphertext envelope — the repository layer stores and returns ciphertext only, never unwrapped key material.

type WrappedMasterAAD

type WrappedMasterAAD struct {
	MasterKeyVersion, RootKeyEpoch uint32
}

WrappedMasterAAD covers the master key wrapped by the operator root: fields master_key_version, root_key_epoch.

type WrappedTokenKeyAAD

type WrappedTokenKeyAAD struct {
	TokenKeyVersion, MasterKeyVersion uint32
}

WrappedTokenKeyAAD covers the root token key wrapped by the master key: fields token_key_version, master_key_version.

Directories

Path Synopsis
Package backup owns the age container around an instance export (#76, encryption-model ADR § Backups and exports).
Package backup owns the age container around an instance export (#76, encryption-model ADR § Backups and exports).
Package sealedhook owns every cryptographic operation of the sealed webhook receiver protocol (docs/spec/sealed-webhook.md).
Package sealedhook owns every cryptographic operation of the sealed webhook receiver protocol (docs/spec/sealed-webhook.md).

Jump to

Keyboard shortcuts

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