audit

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: 14 Imported by: 0

Documentation

Overview

Package audit is the audit-model ADR's event vocabulary: the envelope, the closed category.action registry, retention classes, outcome licensing, and the free-text hygiene applied to every attacker-influencable string before it lands in a durable surveillance record. It is a leaf package (imports only internal/domain) so the authorization package, the store and the service layer can all speak it without cycles.

The package validates; it does not persist. Persistence is the store's audit repositories (tenant trail, instance trail), and the denial writer in the authorization package's enumerated surface — both of which refuse an event this package's Validate rejects (fail-closed: an operation without its durable audit record does not complete).

Index

Constants

View Source
const FreeTextBound = freetext.FreeTextBound

FreeTextBound is the shared free-text byte bound.

View Source
const RedactionMarker = freetext.RedactionMarker

RedactionMarker replaces Hikyo bearer tokens in free text.

View Source
const RefusalSampleLimit = 32
View Source
const RefusalStateBytes = 16384
View Source
const TimeFormat = "2006-01-02T15:04:05.000000Z07:00"

TimeFormat is the fixed-width UTC microsecond text form audit timestamps take on sqlite: unlike RFC3339Nano's trailing-zero truncation, every value is the same width, so lexicographic order is time order and range predicates compare correctly. Postgres stores timestamptz natively.

Variables

View Source
var (
	TransitAlgorithmValues = []string{"xchacha20-poly1305", "ed25519", "hmac-sha256"}
	TransitOperationValues = []string{
		"encrypt", "decrypt", "rewrap", "datakey", "datakey-plaintext",
		"sign", "verify", "hmac", "hmac-verify",
	}
	TransitKeyStates        = []string{"active", "retired", "disabled", "pending-deletion", "destroyed"}
	TransitLifecycleActions = []string{"disable", "enable", "retire", "compromise", "schedule-deletion", "cancel-deletion"}
	// TransitRefusalCauses: the key's state forbids the operation; the version
	// is outside the key's window; the version is compromised; the per-key
	// caller entries exclude the caller; the key does not allow the operation;
	// the custody provider is unavailable; the input was malformed or failed
	// verification is NOT a refusal (verify answers valid=false).
	TransitRefusalCauses = []string{"state", "version", "compromised", "caller", "operation", "custody-unavailable", "invalid-input"}
)

The closed transit vocabularies (#156, transit ADR). They live here, the leaf the service and the audit schemas both import, so an enum in a payload and the service's own vocabulary cannot drift apart.

Functions

func FormatTime

func FormatTime(t time.Time) string

FormatTime renders a timestamp in the audit text form (UTC, microsecond).

func IsDedicatedRefusal

func IsDedicatedRefusal(e Event) bool

IsDedicatedRefusal classifies validated events that own a dedicated refusal. Suppression still requires the transaction owner to confirm durable commit.

func MarkDedicatedRefusal

func MarkDedicatedRefusal(ctx context.Context)

MarkDedicatedRefusal is a COMMIT receipt, never an insert/capture receipt.

func NewEventID

func NewEventID() (string, error)

NewEventID mints the project-pattern UUIDv7 id for an event.

func NoteRefusal

func NoteRefusal(ctx context.Context, stage RefusalStage)

NoteRefusal retains one candidate stage, with admission taking precedence. Incidental artifact probes cannot claim the final authentication outcome.

func ParseTime

func ParseTime(s string) (time.Time, error)

ParseTime reads the audit text form back.

func RedactTokens

func RedactTokens(s string) string

RedactTokens uses the shared token grammar.

func RefusalRequestID

func RefusalRequestID(ctx context.Context) string

RefusalRequestID returns server correlation without copying credential data.

func SanitizeFreeText

func SanitizeFreeText(s string) string

SanitizeFreeText applies the shared free-text hygiene before audit capture.

func ScopeClass

func ScopeClass(trail Trail, s domain.Scope) (string, error)

ScopeClass returns the audit row's declared scope class string for a tenant event ("org" | "project" | "env") or "instance" for the instance trail, matching the per-class row shapes.

func SetRefusalOperation

func SetRefusalOperation(ctx context.Context, operation string)

SetRefusalOperation is called only with a validated registry member. Raw headers, paths, arguments and JSON-RPC ids must never reach this setter.

func Validate

func Validate(e Event, trail Trail, scope domain.Scope) error

Validate checks the event against the closed registry: registered type, licensed outcome, schema-valid payload, trail-consistent scope, and the envelope's own free-text hygiene already applied (bounded, sanitized — Validate refuses rather than silently re-sanitizes: an unsanitized event at the write boundary is a bug in the emitter). A failure here MUST fail the emitting operation (fail-closed, CI invariant 1). scope is the trusted-layer-bound chain: proof-resolved for tenant events, empty for instance events.

func WithContext

func WithContext(ctx context.Context, c Context) context.Context

WithContext attaches sanitized wire metadata to the request context.

func WithRefusalArtifactProbe

func WithRefusalArtifactProbe(ctx context.Context) context.Context

WithRefusalArtifactProbe keeps the shared receipt and admission result, but an incidental dead-cookie liveness check is not the final authentication outcome. The actual handler/chokepoint or CSRF refusal owns that decision.

func WithRefusalReceipt

func WithRefusalReceipt(ctx context.Context, source, requestID string) context.Context

WithRefusalReceipt installs shared request attribution before transport dispatch.

Types

type Actor

type Actor struct {
	ID           string // principal id, "" when structurally absent
	Class        ActorClass
	CredentialID string // authenticating artifact id, "" when absent
}

Actor is the envelope's acting-principal triple. IDs are nullable as structured facts (class ActorUnauthenticated with empty ids), never dummy principals.

type ActorClass

type ActorClass string

ActorClass is the envelope's principal classification. Nullable actor ids are a structured fact — an unknown-account login failure has no principal — never a dummy principal.

const (
	ActorHuman           ActorClass = "human"
	ActorMachine         ActorClass = "machine"
	ActorSystem          ActorClass = "system"
	ActorBreakGlass      ActorClass = "break-glass"
	ActorUnauthenticated ActorClass = "unauthenticated"
)

type Context

type Context struct {
	SourceIP  string
	UserAgent string
	Origin    Origin
	// RequestOrigin is the HTTP `Origin` HEADER the request presented, not the
	// audit Origin enum beside it — the two are different facts with the same
	// English name. It is empty for every non-browser caller, and it exists so
	// the workspace authentication leg can compare a bearer's BOUND origin
	// against the origin actually presenting it: a `ws` bearer issued to
	// origin A must not authenticate from allowlisted origin B.
	RequestOrigin string
}

Context is the per-request wire metadata every event records: recorded on every event, null only where structurally absent (audit-model ADR: absence is a structural fact, never a redaction). The HTTP and CLI layers (#47/#48) attach it via WithContext; free text is sanitized at capture.

func FromContext

func FromContext(ctx context.Context) Context

FromContext returns the attached wire metadata. Absent metadata means an in-process caller with no wire origin: OriginSystem, no addresses — the structural-absence case, not a default that fakes a request.

type Event

type Event struct {
	ID               string // UUIDv7, prefixed — NewEventID
	Type             EventType
	SchemaVersion    int
	OccurredAt       time.Time
	OccurredAsserted bool // client-asserted occurred_at (offline-reconciled)
	Actor            Actor
	AuthorityID      string // recorded authority principal, "" when direct
	Object           Object
	Outcome          Outcome
	CorrelationID    string
	SourceIP         string // "" only where structurally absent
	UserAgent        string
	Origin           Origin
	Payload          Payload
}

Event is the envelope every audit row carries (audit-model ADR § The event envelope). seq and recorded_at are storage-assigned at durable insert and therefore absent here; occurred_at is caller-supplied and flagged when client-asserted (offline reconciliation).

Deliberately ABSENT: the scope chain. The chain a tenant event carries is the proof's resolved chain (or, for the denial writer, the chain authorize() itself resolved) — passed alongside the event by the trusted layer that binds it, never a field a caller could populate. This keeps the proof-signature analyzer's rule intact: no tenant-identifier-typed value travels a store-method parameter.

type EventType

type EventType string

EventType is one closed-registry entry, named category.action. An unregistered type cannot be written; an unvalidated payload cannot be written (CI invariant 1).

const (
	EventPrivacySubjectCorrected  EventType = "privacy.subject_corrected"
	EventPrivacySubjectReleased   EventType = "privacy.subject_released"
	EventPrivacySubjectExported   EventType = "privacy.subject_exported"
	EventPrivacySubjectRestricted EventType = "privacy.subject_restricted"
	EventPrivacySubjectErased     EventType = "privacy.subject_erased"
)
const (
	EventSelfConfigMigrated                   EventType = "self_config.migrated"
	EventSelfConfigResumed                    EventType = "self_config.resumed"
	EventSelfConfigTargetCommitted            EventType = "self_config.target_committed"
	EventSelfConfigRecovered                  EventType = "self_config.recovered"
	EventSelfConfigStatusRead                 EventType = "self_config.status_read"
	EventSelfConfigAdopted                    EventType = "self_config.adopted"
	EventSelfConfigApplyRequested             EventType = "self_config.apply_requested"
	EventSelfConfigDeploymentRestoreRequested EventType = "self_config.deployment_restore_requested"
	EventSelfConfigTestRequested              EventType = "self_config.test_requested"
	EventSelfConfigTestCompleted              EventType = "self_config.test_completed"
	EventSelfConfigProjectPrepared            EventType = "self_config.project_prepared"
	EventSelfConfigApplied                    EventType = "self_config.applied"
	EventSelfConfigRecoveryFenced             EventType = "self_config.recovery_fenced"
	// grant.denied is the per-event authorization denial (#15's per-event
	// obligation; audit-model ADR § Denials). Resolvable denials land in the
	// tenant trail with the truthful resolved chain; unresolvable denials
	// land in the instance trail with the addressed identifiers preserved as
	// caller-asserted claims.
	EventGrantDenied EventType = "grant.denied"

	// audit.* — the trail watching itself (audit-model ADR § Storage and
	// export). One query event per trail query; INTENT/OUTCOME pair per
	// export.
	EventAuditQuery           EventType = "audit.query"
	EventAuditExportStarted   EventType = "audit.export_started"
	EventAuditExportCompleted EventType = "audit.export_completed"

	// auth.* — human authentication (#47, human-auth ADR § Propagations to
	// the audit-model ADR). Failures matter as much as successes, so every type
	// below licenses the failure outcome its path can produce.
	//
	// Note what these payloads deliberately do NOT carry: the presented
	// username. A human who types a password into the username field would
	// otherwise put it in a durable trail, which is the exact accident the
	// no-plaintext rule exists to prevent. Attribution is carried as the
	// resolved account id — definitively not a password, because it resolved
	// — plus a boolean saying whether resolution happened at all. Source IP
	// and user agent ride in the envelope, so incident response keeps the
	// signal it actually needs.
	EventAuthLogin      EventType = "auth.login"
	EventRequestRefused EventType = "auth.request_refused"
	EventAuthLogout     EventType = "auth.logout"
	// auth.artifact_class_refused records a valid authenticated identity whose
	// artifact class the addressed OpenAPI operation does not admit. The wire
	// response remains the uniform nonexistent shape; the named distinction is
	// visible only in the security trail.
	EventAuthArtifactClassRefused EventType = "auth.artifact_class_refused"
	// auth.session_created records the artifact minted and the assurance it
	// carries — the record the chokepoint will consult on every later request.
	EventAuthSessionCreated EventType = "auth.session_created"
	// auth.credential_authority_minted records a credential-establishment
	// authority coming into existence AND how it was delivered, because
	// delivery mode is the security property: a token that reached a log
	// shipper is a different event from one written to a root-owned file.
	EventAuthAuthorityMinted EventType = "auth.credential_authority_minted"
	// auth.credential_established is its consumption: exactly one initial
	// credential, atomically, and nothing more.
	EventAuthCredentialEstablished EventType = "auth.credential_established"
	// auth.credential_authority_refused covers failed presentation, expiry
	// and re-use — the ADR requires the failures, not just the successes.
	EventAuthAuthorityRefused EventType = "auth.credential_authority_refused"
	// auth.throttle_crossed fires when a per-account backoff threshold is
	// crossed, so a distributed attempt is visible rather than merely slowed.
	EventAuthThrottleCrossed EventType = "auth.throttle_crossed"

	// auth.* factor events (#54, human-auth ADR § Factors, § Account-security
	// mutations). A factor beyond a password exists, so the chokepoint enforces
	// the MFA-mandatory rule (assuranceInadequate at the authorize chokepoint).
	//
	// auth.factor_enrolled / auth.factor_removed record a TOTP factor coming
	// into or out of existence, naming the credential class that authorized the
	// account-security mutation.
	EventAuthFactorEnrolled EventType = "auth.factor_enrolled"
	EventAuthFactorRemoved  EventType = "auth.factor_removed"
	// auth.recovery_codes_generated records a display-once batch replacing the
	// previous one.
	EventAuthProfileUpdated         EventType = "auth.profile_updated"
	EventAuthRecoveryCodesGenerated EventType = "auth.recovery_codes_generated"
	// auth.recovery_code_consumed records the pre-auth break-in-glass path,
	// including its failures (the ADR requires the failures, uniform response
	// notwithstanding).
	EventAuthRecoveryCodeConsumed EventType = "auth.recovery_code_consumed"
	// auth.reauthenticated records a step-up: the acting session presented a
	// possession factor and gained a factor class.
	EventAuthReauthenticated EventType = "auth.reauthenticated"
	// auth.cli_reauth_handoff records each phase of the CLI/browser adapter
	// reauthentication transport. The payload carries only the internal row id
	// and public policy shape; front-channel artifacts never enter the trail.
	EventAuthCLIReauthHandoff EventType = "auth.cli_reauth_handoff"
	// auth.passkey_added / auth.passkey_removed record a WebAuthn credential
	// coming into or out of existence, naming the credential class that
	// authorized the account-security mutation (#54). auth.passkey_cloned is the
	// clone-detection security event: a real sign-count regression on a
	// non-backup credential disabled it and swept its sessions (B9).
	EventAuthPasskeyAdded   EventType = "auth.passkey_added"
	EventAuthPasskeyRemoved EventType = "auth.passkey_removed"
	EventAuthPasskeyCloned  EventType = "auth.passkey_cloned"

	// auth.* OIDC events (#54, human-auth ADR - Login methods, Identity
	// linking, The OIDC transaction). auth.oidc_login records a federated login
	// or reauth success with its method and the assurance the provider policy
	// yielded; auth.oidc_refused records every transaction failure BY CAUSE
	// (the ADR requires the failures, uniform response notwithstanding), with a
	// closed cause enum covering mix-up, nonce, purpose, state, issuer,
	// audience, signature, epoch and IdP-error refusals.
	EventAuthPasswordChanged EventType = "auth.password_changed"
	EventCredentialEstablish EventType = "auth.credential_establish"
	EventOAuth2Login         EventType = "auth.oauth2_login"
	EventOAuth2Refused       EventType = "auth.oauth2_refused"
	EventOIDCLogin           EventType = "auth.oidc_login"
	EventOIDCRefused         EventType = "auth.oidc_refused"
	// auth.identity_linked / auth.identity_unlinked record an external identity
	// bound to or removed from an account - account-security mutations both.
	EventIdentityLinked   EventType = "auth.identity_linked"
	EventIdentityUnlinked EventType = "auth.identity_unlinked"
	// auth.provider_changed records a provider configuration change and the
	// count of federated sessions it swept (A3/A4). auth.provider_read records
	// the instance-scoped provider reads (audit-model default-deny refuses
	// audited:none to instance-class operations).
	EventOIDCProviderChanged EventType = "auth.provider_changed"
	EventOIDCProviderRead    EventType = "auth.provider_read"

	// auth.* SAML events (#72, saml-sp ADR). Login and reauth outcomes keep
	// their distinct ceremony semantics; provider, certificate, metadata and
	// SP-key lifecycle events make every trust-root transition attributable.
	EventSAMLLogin                 EventType = "auth.saml_login"
	EventSAMLReauth                EventType = "auth.saml_reauth"
	EventSAMLProviderConfigure     EventType = "auth.saml_provider_configure"
	EventSAMLProviderRefresh       EventType = "auth.saml_provider_refresh"
	EventSAMLProviderRemove        EventType = "auth.saml_provider_remove"
	EventSAMLCertChange            EventType = "auth.saml_cert_change"
	EventSAMLEmailNameIDOptIn      EventType = "auth.saml_nameid_email_optin"
	EventSAMLSPKey                 EventType = "auth.saml_sp_key"
	EventSAMLMetadataExpiryWarning EventType = "auth.saml_metadata_expiry_warning"

	// auth.credential_reset_issued records an administrator-issued or break-glass
	// credential-establishment authority minted for a target (#54, human-auth ADR
	// - Recovery), naming the issuer tier and whether it ran under network
	// (credential-reset) or local host (break-glass) authority.
	EventAuthCredentialResetIssued EventType = "auth.credential_reset_issued"
	// auth.effective_window_lowered records an environment's effective
	// reauthentication window being lowered, the count of windows it invalidated,
	// and the principals the transition strands (reveal holders there without a
	// WebAuthn authenticator), so the trail carries the surfaced list (#54 B6).
	EventAuthEffectiveWindowLowered EventType = "auth.effective_window_lowered"

	// settings.* — the hierarchy's own catalogue rows (#48): Organization,
	// Project, Environment, Folder lifecycle. Every mutation has its own type,
	// because "a project was renamed" and "a project was deleted" are different
	// facts for an investigator and collapsing them into one changed-event
	// would make the trail answer neither question.
	//
	// Reads are NOT here: a tenant-class bare-`read` operation takes the
	// audit-model ADR's audited-none permit, so the only read event is the
	// instance-scoped org enumeration below.
	EventOrgCreated EventType = "settings.org_created"
	EventOrgRenamed EventType = "settings.org_renamed"
	EventOrgDeleted EventType = "settings.org_deleted"
	// settings.org_read covers the instance-scoped org enumeration. The ADR's
	// default-deny rule refuses `audited: none` to instance-class
	// operations, and that is an operator read of cross-tenant metadata —
	// so it is audited, at the access retention class (read volume, not
	// grant history).
	EventOrgRead EventType = "settings.org_read"

	EventProjectCreated EventType = "settings.project_created"
	EventProjectRenamed EventType = "settings.project_renamed"
	EventProjectDeleted EventType = "settings.project_deleted"

	EventEnvCreated          EventType = "settings.environment_created"
	EventEnvParameterChanged EventType = "settings.environment_parameter_changed"
	EventEnvRenamed          EventType = "settings.environment_renamed"
	EventEnvDeleted          EventType = "settings.environment_deleted"
	// settings.environment_reordered records one authorized rewrite of a
	// project's whole display order, naming how many environments it covered.
	// The ids are the object of the operation, not free text, and the count is
	// what an investigator reads first.
	EventEnvReordered   EventType = "settings.environment_reordered"
	EventEnvNoteChanged EventType = "settings.environment_note_changed"

	EventFolderCreated EventType = "settings.folder_created"
	EventFolderRenamed EventType = "settings.folder_renamed"
	EventFolderDeleted EventType = "settings.folder_deleted"

	// grant.* — the permission model's own catalogue rows (#55). The ADR's
	// propagation to this one names created / modified / revoked with
	// self-grants distinguishable; the three map onto the origin model
	// exactly: a row that did not exist is created, a row an additional
	// origin joins is modified, and a row whose LAST origin was released is
	// revoked. `grant.template_applied` records one template expansion as a
	// single fact beside the per-capability rows it created — without it the
	// trail can say ten capabilities appeared but not that one administrator
	// performed one act.
	EventGrantCreated         EventType = "grant.created"
	EventGrantModified        EventType = "grant.modified"
	EventGrantRevoked         EventType = "grant.revoked"
	EventGrantTemplateApplied EventType = "grant.template_applied"
	// Member access rules (member-access-rules ADR). A rule is created and
	// revoked whole (an edit is revoke plus create). rule.revoked also records a
	// deletion path removing a rule whose only-list lost its last item.
	// rule.move_widening_confirmed records the confirmed set of principals a
	// key's folder move admitted through their rules (D9).
	EventRuleCreated               EventType = "rule.created"
	EventRuleRevoked               EventType = "rule.revoked"
	EventRuleMoveWideningConfirmed EventType = "rule.move_widening_confirmed"
	// grant.membership_read is the membership surface's read event. It is not
	// `audited: none`: that permit covers tenant-class bare-`read` operations,
	// and "who can reveal production secrets" is administrative information
	// under `manage-members`, not an object read. Access retention class —
	// read volume, not grant history.
	EventGrantMembershipRead EventType = "grant.membership_read"
	// member.invited records an invitation (#568): a human principal and its
	// account came to exist under a `manage-members` holder's authority, with
	// the optional template named. The minted authority is its own instance
	// event (auth.credential_authority_minted, issued_by=invitation); this one
	// lives on the scope's trail so an org administrator can answer "who
	// invited whom" without instance access.
	EventMemberInvited EventType = "member.invited"
	// registration.* (#606, audit-model banner 2026-09-03). The policy events
	// land on the scope's trail (tenant for an org policy, instance for the
	// instance policy) and carry the authority reassignment every edit makes.
	// registration.signup_expired records a pending local sign-up removed
	// before verification: by the reaper (#608) or, here, by deleting the
	// policy that admitted it.
	EventRegistrationPolicyCreated EventType = "registration.policy_created"
	EventRegistrationPolicyUpdated EventType = "registration.policy_updated"
	EventRegistrationPolicyDeleted EventType = "registration.policy_deleted"
	EventRegistrationSignupExpired EventType = "registration.signup_expired"
	// The sign-up outcomes (#607 federated; #608 local): admitted (the
	// admission predicate passed, written before the account exists, actor
	// unauthenticated), refused by one closed cause (uncharged before the
	// `signup` budget, charged after it), and completed (actor = the new
	// principal). They land on the instance trail, the pre-authentication
	// plane the auth.* refusals share, carrying the policy id and scope. The
	// landing org's own trail records the grants the sign-up received
	// (grant.created / grant.template_applied, origin_kind registration).
	EventRegistrationSignupAdmitted  EventType = "registration.signup_admitted"
	EventRegistrationSignupRefused   EventType = "registration.signup_refused"
	EventRegistrationSignupCompleted EventType = "registration.signup_completed"
	EventRegistrationMailIntent      EventType = "registration.mail_intent"
	EventRegistrationMailOutcome     EventType = "registration.mail_outcome"
	EventRegistrationMailStatusRead  EventType = "registration.mail_status_read"

	// settings.reauthentication_window_changed and
	// settings.protected_flag_changed are the `project-settings` security
	// events the audit catalogue names — a widening and a protected-flag
	// clearing are the two changes an investigator looks for, so widening is
	// a field on the first and the direction is the whole of the second.
	EventReauthWindowChanged EventType = "settings.reauthentication_window_changed"
	EventProtectedFlagChange EventType = "settings.protected_flag_changed"
	// Retention policy changes are distinct at org and project scope. Both are
	// security-class because widening either bound lengthens value-bearing
	// history, while tightening makes payload loss imminent and unrestorable.
	EventOrgRetentionChanged     EventType = "settings.org_retention_changed"
	EventProjectRetentionChanged EventType = "settings.project_retention_changed"
	EventProjectCapacityChanged  EventType = "project.capacity_changed"
	// retention.health_read is the audited instance-level operational read.
	// retention.payload_gc records each irreversible tenant payload collection;
	// retention.prune_run records the scheduler sweep outcome.
	EventAuditRetentionChanged EventType = "retention.audit_policy_changed"
	EventAuditRetentionPruned  EventType = "retention.audit_pruned"
	EventRetentionHealthRead   EventType = "retention.health_read"
	EventRetentionPayloadGC    EventType = "retention.payload_gc"
	EventRetentionPruneRun     EventType = "retention.prune_run"
	EventUpdateStatusRead      EventType = "system.update_status_read"
	EventUpdateRequested       EventType = "system.update_requested"
	EventUpdateOutcome         EventType = "system.update_outcome"

	// recovery.break_glass_grant records a grant issued under local host
	// authority — the one authorization path not evaluated against a grant.
	EventBreakGlassGrant EventType = "recovery.break_glass_grant"

	// approval.* — the secret-change approval engine (#151). All tenant-trail,
	// all SECURITY retention: who may commit a change to a sensitive scope, and
	// under whose review, is exactly the evidence a compliance audit starts
	// from. None carries any value plaintext, length or digest — only the
	// change set's identity and the review outcome. approval.bypassed is the
	// high-signal one (the emergency path), carrying the operator's reason.
	EventApprovalPolicyChanged EventType = "approval.policy_changed"
	EventApprovalPolicyRead    EventType = "approval.policy_read"
	EventApprovalRequested     EventType = "approval.requested"
	EventApprovalVoted         EventType = "approval.voted"
	EventApprovalMerged        EventType = "approval.merged"
	EventApprovalInvalidated   EventType = "approval.invalidated"
	EventApprovalExpired       EventType = "approval.expired"
	EventApprovalBypassed      EventType = "approval.bypassed"

	// access.* - approval-mediated temporary access (#152). All tenant-trail,
	// all SECURITY retention: who held which capability in which environment,
	// from when until when, and on whose approval, is the evidence an access
	// review starts from. access.bypassed is the high-signal one (the
	// emergency path), carrying the requester's reason. None carries value
	// material.
	EventAccessPolicyChanged EventType = "access.policy_changed"
	EventAccessPolicyRead    EventType = "access.policy_read"
	EventAccessRequested     EventType = "access.requested"
	EventAccessVoted         EventType = "access.voted"
	EventAccessGranted       EventType = "access.granted"
	EventAccessCancelled     EventType = "access.cancelled"
	EventAccessInvalidated   EventType = "access.invalidated"
	EventAccessRevoked       EventType = "access.revoked"
	EventAccessExpired       EventType = "access.expired"
	EventAccessBypassed      EventType = "access.bypassed"

	// backup.* / restore.* — the operator lifecycle (#76, encryption-model ADR
	// § Propagations "export and restore are auditable events"; ops spec § 11).
	// All four are instance-trail, local host authority, and all four are
	// SECURITY retention: a backup is a copy of every ciphertext in the
	// instance, and the record of one being taken, skipped, or replayed into a
	// new instance is exactly the evidence an incident starts from.
	//
	// backup.exported records an artifact coming into existence and WHERE it
	// went, because a backup nobody can find is a backup that does not exist.
	// It deliberately records the recipient MODE and count, never a recipient
	// value: the public recipients are not secret, but naming them in every
	// event would put the operator's escrow topology in the trail.
	EventBackupExported EventType = "backup.exported"
	// backup.export_skipped is the loud half of the ops spec's "automatic
	// pre-migration export when public recipients are configured, LOUD SKIP
	// otherwise". A skip that only warned to a log would be invisible the
	// morning after a migration went wrong.
	EventBackupExportSkipped EventType = "backup.export_skipped"
	// restore.completed records an instance being reconstructed from an
	// archive: the credential epoch it advanced to, and therefore the moment
	// every pre-restore artifact in the restored state became inert.
	EventRestoreCompleted EventType = "restore.completed"
	// restore.principal_reconciled records ONE principal's re-activation. One
	// event per principal is the point — the ADR's per-principal assertion has
	// to leave a per-principal record, and a single "reconciliation completed"
	// event would be exactly the bulk accept the surface refuses to offer.
	EventRestorePrincipalReconciled EventType = "restore.principal_reconciled"
	// EventBackupExportFailed is the scheduled export's loud failure (#145):
	// a configured policy that was not honoured, on the instance trail so
	// it survives the morning after. The reason is a bounded class, never a
	// path that could carry a secret.
	EventBackupExportFailed EventType = "backup.export_failed"
	// EventRestoreDrillCompleted records one isolated restore drill (#145):
	// archive identity, versions, elapsed time and the RTO verdict. Never
	// key material, never the decrypted sample.
	EventRestoreDrillCompleted EventType = "restore.drill_completed"
	// settings.key_* — the key catalogue's lifecycle (#49). The catalogue IS
	// the project's schema, so these are schema events; they are named
	// `settings.*` like the rest of the definitions surface because an
	// investigator asks "who changed the project's definitions?", not "which
	// subsystem owned the row".
	//
	// NO PAYLOAD HERE EVER CARRIES A VALUE, A DECLARATION BODY, OR AN
	// INSTANCE-DERIVED PATH. Key NAMES are schema and are recorded; a folder
	// path is recorded as `namespace`, because the #48 convention reserves
	// every *_path spelling for instance-derived JSON pointers into a value.
	EventKeyCreated EventType = "settings.key_created"
	EventKeyRenamed EventType = "settings.key_renamed"
	EventKeyDeleted EventType = "settings.key_deleted"
	// settings.key_declaration_changed records a semantic schema change: the
	// value-dependent rules, the presence rules, or both. It carries the
	// resulting schema revision, because "the validation guarantee moved" is
	// the fact a later snapshot pins.
	EventKeyDeclarationChanged EventType = "settings.key_declaration_changed"
	// settings.key_metadata_changed records the NON-semantic half. It exists
	// separately precisely because it materializes nothing and moves no
	// revision — collapsing it into the declaration event would make the trail
	// unable to answer which changes could have affected delivery.
	EventKeyMetadataChanged EventType = "settings.key_metadata_changed"
	// settings.key_reclassified records the ceremony in both directions,
	// recorded under the STRICTER of the pre- and post-change classification
	// so neither direction lands under the laxer regime.
	EventKeyReclassified EventType = "settings.key_reclassified"
	// settings.key_reveal_gate_attempt is the disclosure-class record of EVERY
	// reveal-gated attempt on a `secret` key — a value-dependent rule change or
	// a declassification — whatever its outcome: allowed (success), refused
	// (denied), or rate-limited (failure). The schema-model ADR's obligation is
	// "every attempt is audited", so the denied and limited cases matter most,
	// and both roll their transaction back; the row therefore rides the
	// rollback-surviving settlement path rather than an in-transaction insert.
	//
	// The before-commit disclosure record the ADR separately requires for
	// declassification is settings.key_reclassified, which IS written inside
	// the committing transaction ahead of the classification write.
	EventKeyRevealGateAttempt EventType = "settings.key_reveal_gate_attempt"

	// Definitions Git flow (#70, source-of-truth ADR § Propagations). plan_created
	// and applied are COMMITTED acts written inside their transaction; the three
	// *_refused events record acts that ROLL THEIR TRANSACTION BACK — a stale-pin
	// apply, a refused deletion, a refused additive modification — so they ride
	// the rollback-surviving settlement path (az.CaptureAudit) and carry only
	// schema vocabulary, never a value or a bundle body.
	EventDefinitionsPlanCreated                 EventType = "definitions.plan_created"
	EventDefinitionsApplied                     EventType = "definitions.applied"
	EventDefinitionsApplyRejectedStale          EventType = "definitions.apply_rejected_stale"
	EventDefinitionsDeletionRefused             EventType = "definitions.deletion_refused"
	EventDefinitionsAdditiveModificationRefused EventType = "definitions.additive_modification_refused"
	// settings.definitions_source_changed is the git/db flip, audited in both
	// directions like the protected-flag flip it sits beside.
	EventSettingsDefinitionsSourceChanged EventType = "settings.definitions_source_changed"
	// settings.machine_reveal_changed is the per-project machine-reveal
	// opt-in flip (source-of-truth ADR), audited in both directions: enabling
	// it admits a standing decryption capability onto machine principals,
	// withdrawing it makes every such grant inert on the next fetch.
	EventSettingsMachineRevealChanged EventType = "settings.machine_reveal_changed"

	// value.* and disclosure.* — the flat value model (#50). Both categories
	// are the audit catalogue's own: `value` holds the acts that change what
	// an environment delivers, `disclosure` holds the acts that move stored
	// material to a principal or to another environment.
	//
	// NO PAYLOAD HERE EVER CARRIES A VALUE, IN ANY FORM — not the plaintext,
	// not a length, not a hash, not a "changed from" marker. A key name and
	// its classification are schema and are recorded; everything derived from
	// the material itself is exactly what the trail must not hold, because the
	// trail is readable under `audit-read` and `audit-read` is not `reveal`.
	//
	// value.set records a cell beginning to deliver material the actor
	// SUPPLIED (typed, piped, or read from a file they named). Material the
	// actor did not supply arrives through disclosure.value_copied instead —
	// the two are different authorization stories (supply needs no `reveal`,
	// duplication does), so they are different events.
	EventValueSet EventType = "value.set"
	// value.cleared records the `set` → `absent` transition. With no
	// inheritance there is nothing underneath, so this event means delivery of
	// that key in that environment STOPPED — which is why it is its own event
	// and not a `value.set` with an empty payload.
	EventValueCleared EventType = "value.cleared"
	// disclosure.value_revealed is one event per key per environment whose
	// current `secret` plaintext was opened under the caller's authority.
	// `surface` says where: `cell` and `diff` are reads rendered to the
	// principal, `copy` and `clone` are the source side of a duplication. The
	// audit-model ADR lists these as separate disclosure entries; they are one type
	// with a field because they disclose exactly the same thing, and an
	// investigator filtering "who read this key" must not have to know four
	// spellings.
	EventValueRevealed EventType = "disclosure.value_revealed"
	// Public export inputs are recorded once per successful parameterized export.
	// Ordinary config exports remain unaudited; per-key export disclosure records
	// remain exclusive to secrets.
	EventValuesExported EventType = "disclosure.values_exported"
	// value.staged records an edit landing in the actor's own WORKING STATE
	// (#51). It is deliberately its own type rather than a `value.set` with a
	// flag: a draft delivers nothing, so an investigator asking "when did this
	// environment start delivering X" must not have to filter staged edits out
	// of the answer. It carries the immutable version id, which is what a
	// later revision.published names, so the two events chain without either
	// carrying material.
	EventValueStaged EventType = "value.staged"
	// value.change_validated records a proposed change being evaluated
	// against the current schema, presence rules, and scanner without being
	// staged (mcp-write ADR § 1). It carries the verdict and counts, never
	// the proposed material or the problem text.
	EventValueChangeValidated EventType = "value.change_validated"
	// revision.published records ONE environment advancing to a new revision.
	// Every materialization emits it -- a selective publish, a declare, a copy,
	// a clone, an environment's creation, and a semantic schema change's
	// fan-out -- with `trigger` saying which act produced it. It records
	// numbers, never keys' values: `changed_keys` is a COUNT, because the names
	// live in the revision lineage, which has its own permanent retention.
	EventRevisionPublished     EventType = "revision.published"
	EventRevisionRestoreStaged EventType = "revision.restore_staged"
	EventPinCreated            EventType = "pin.created"
	EventPinReassigned         EventType = "pin.reassigned"
	EventPinRenewed            EventType = "pin.renewed"
	EventPinReleased           EventType = "pin.released"
	EventPinExpiryRefused      EventType = "pin.expiry_refused"
	// crypto.token_key_rotated records `rotate-token-key`. Instance trail,
	// because the root token key is instance-scoped crypto material; the
	// payload is the new version and nothing else, since a token key is never
	// exported, displayed or compared.
	EventTokenKeyRotated EventType = "crypto.token_key_rotated"
	// crypto.scanning_key_rotated records `rotate-scanning-key` (#74,
	// secret-scanning ADR section 4), exactly parallel to token_key_rotated:
	// instance trail, security retention, the new key version and nothing else,
	// since a scanning key is never exported, displayed or compared. Spelled
	// `key_version` for the same invariant-4 name-shape reason.
	EventScanningKeyRotated EventType = "crypto.scanning_key_rotated"

	// scanning.* (#74, secret-scanning ADR section 5) — the four finding events.
	// Their emitters are wired at the value-write and declaration-ingress
	// chokepoints, so the closure invariant (a registered type must be emittable)
	// holds and the specs live directly in the registry map below.
	EventScanningFindingWarned     EventType = "scanning.finding_warned"
	EventScanningFindingDismissed  EventType = "scanning.finding_dismissed"
	EventScanningFindingBlocked    EventType = "scanning.finding_blocked"
	EventScanningFindingOverridden EventType = "scanning.finding_overridden"
	// crypto.dek_rotated records `rotate-dek` for one project or the instance
	// scope: a new DEK version is active and the previous one is retiring until
	// reencrypt walks its ciphertext. Instance trail — DEKs are instance-scoped
	// crypto material — carrying only the scope and the new version, never key
	// bytes.
	EventDEKRotated EventType = "crypto.dek_rotated"
	// crypto.reencrypt_completed records a finished reencrypt pass over one
	// scope: every ciphertext is on the active DEK version and the superseded
	// versions are retired. rows_moved is the count re-sealed this run. Tenant
	// trail for a project scope, instance trail for the instance scope.
	EventReencryptCompleted EventType = "crypto.reencrypt_completed"
	// crypto.master_key_rotated records `rotate-master-key`: a new master now
	// wraps every tier-3 key and the old master is retired. Instance trail,
	// payload the new master version only.
	EventMasterKeyRotated EventType = "crypto.master_key_rotated"
	// The three crypto.root_key_* events record the crash-safe root rotation
	// protocol — prepare stores the dual wrapper at the new epoch, verify
	// confirms the operator installed the new root at the primary source,
	// finalize retires the old wrapper. Payload the epoch only, never key bytes.
	EventRootEscrowVerified       EventType = "crypto.root_escrow_verified"
	EventRootKeyRotationPrepared  EventType = "crypto.root_key_rotation_prepared"
	EventRootKeyRotationVerified  EventType = "crypto.root_key_rotation_verified"
	EventRootKeyRotationFinalized EventType = "crypto.root_key_rotation_finalized"
	// disclosure.value_copied is one event per key per DESTINATION for every
	// server-side duplication: copy-to, bulk-apply and clone-at-creation. It
	// records the source environment, because "material this environment's
	// publisher did not supply" is the fact the re-delivery gate exists to
	// make auditable.
	EventValueCopied EventType = "disclosure.value_copied"
	// value.imported records one `values import` RUN against one environment
	// (#68). It sits BESIDE the per-key value.set events the run's writes emit,
	// not instead of them: "who set this value" must be answerable without
	// knowing how the value arrived, and "was there a migration, when, from
	// what, against which reviewed state" must be answerable without
	// reconstructing it from a burst of writes. The payload is the run's shape
	// — how many keys landed, how many were skipped, whether a manifest bound
	// the run — and never a key's material.
	EventValueImported EventType = "value.imported"

	EventKeyGroupCreated EventType = "settings.key_group_created"
	EventKeyGroupRenamed EventType = "settings.key_group_renamed"
	EventKeyGroupDeleted EventType = "settings.key_group_deleted"
	// settings.key_group_membership_changed records a key joining or leaving a
	// group. Membership is coupling, and coupling is a schema change.
	EventKeyGroupMembershipChanged EventType = "settings.key_group_membership_changed"

	// identity.* — machine identities (#61, machine-identities ADR §
	// Audit attribution). Every credential-lifecycle transition is here
	// because the forensic question after a leak is "which token", and one
	// service account holds several.
	//
	// identity.service_account_created / _deleted bracket the principal's
	// life; the deletion event carries the blast radius it took with it (the
	// credentials revoked and the grants released in the same transaction).
	EventServiceAccountCreated EventType = "identity.service_account_created"
	EventServiceAccountDeleted EventType = "identity.service_account_deleted"
	// identity.credential_minted records a credential coming into existence
	// AND the environments the authorizing formula ranged over, per authority
	// class — the delivery mode itself is the CLI's to record, since the
	// server never sees where the value went.
	EventCredentialMinted                 EventType = "identity.credential_minted"
	EventDeveloperCredentialMintRefused   EventType = "identity.developer_credential_mint_refused"
	EventDeveloperCredentialMinted        EventType = "identity.developer_credential_minted"
	EventDeveloperCredentialRevoked       EventType = "identity.developer_credential_revoked"
	EventDeveloperCredentialsListed       EventType = "identity.developer_credentials_listed"
	EventDeveloperCredentialPolicyRead    EventType = "identity.developer_credential_policy_read"
	EventDeveloperCredentialPolicyChanged EventType = "identity.developer_credential_policy_changed"

	// identity.credential_revoked is the incident-response half. It is
	// reachable under the PLAIN capability, with no reveal gate, because
	// gating revocation on disclosure rights is a self-inflicted delay.
	EventCredentialRevoked EventType = "identity.credential_revoked"
	// identity.grant_widened records a grant mutation on a MACHINE principal
	// that made plaintext newly reachable. It is a separate event from
	// grant.created because it is a separate fact: a grant landing on a
	// machine principal re-scopes every credential already in circulation,
	// instantly, with nobody re-presenting anything.
	EventMachineGrantWidened EventType = "identity.grant_widened"
	// identity.lifetime_policy_changed records the instance lifetime
	// controls moving, with the credentials the change clamped or stranded —
	// the enumeration the actor was shown before it committed.
	EventCredentialPolicyChanged EventType = "identity.lifetime_policy_changed"
	// identity.credentials_listed is the metadata read. It is audited rather
	// than `audited: none` for the same reason grant.membership_read is:
	// reading which credentials can reach production is not a bare tenant
	// read.
	EventCredentialsListed EventType = "identity.credentials_listed"
	// identity.lifetime_policy_read is the instance-scoped read of the
	// lifetime controls. Instance-class operations cannot be `audited: none`
	// under the audit-model ADR's default-deny permit rule, and this is the
	// same shape auth.provider_read already has for OIDC configuration.
	EventCredentialPolicyRead EventType = "identity.lifetime_policy_read"

	// identity.* — OIDC federation and the machine delivery surface (#62,
	// machine-identities ADR § Federation, § JWKS, § Restore, § Audit
	// attribution).
	//
	// identity.binding_created records a federated binding coming into
	// existence, and — when it replaced one — which. There is deliberately no
	// `binding_modified`: a binding is IMMUTABLE, so every change is a
	// replacement, and an event type for an operation that cannot happen would
	// suggest it can. The predecessor's death is recorded by
	// identity.credential_revoked with `cause: replaced`, at the same
	// cardinality an ordinary revoke has.
	EventBindingCreated EventType = "identity.binding_created"
	// identity.binding_reactivated records a restore-time RE-VALIDATION of one
	// binding. It carries the `reactivated_at` instant and the clock-skew
	// margin, because together they are the permanent predicate every later
	// token is measured against — an investigator asking "why was this token
	// refused" needs both numbers, and only this row has them.
	EventBindingReactivated EventType = "identity.binding_reactivated"
	// identity.federation_issuer_changed records an instance-scoped issuer
	// configuration coming into existence, moving, or going away. The ADR names
	// "federation issuer configuration" in its audit propagation, and the
	// reason is the blast radius: an issuer is an external authority the
	// instance trusts to name principals.
	EventFederationIssuerChanged EventType = "identity.federation_issuer_changed"
	// identity.federation_issuer_read is the instance-scoped read. Not
	// `audited: none`: the audit-model ADR's default-deny permit rule admits
	// only tenant-class bare-`read` operations, and reading which external
	// authorities the instance trusts is neither.
	EventFederationIssuerRead EventType = "identity.federation_issuer_read"
	// identity.federation_refused records a federated presentation failing, BY
	// CAUSE, with a closed enum covering not-a-token, unknown issuer,
	// unavailable and stale keys, signature, token age and span, audience,
	// claim, the CI event rule, the restore predicate, and an unbound identity.
	//
	// It is the one machine authentication-failure event #61 deliberately did
	// NOT register, and what changed is that the asymmetry it would have
	// claimed is now real: a federated refusal has causes a human session
	// refusal does not have — an unreachable issuer, a rotated key, a pinned
	// claim that moved — and an operator debugging a fleet that stopped
	// authenticating has no other way to tell them apart. Aggregation is
	// permitted for failure floods and for nothing else, per #16.
	EventFederationRefused EventType = "identity.federation_refused"
	// identity.jwks_refresh_failed records both halves of the ADR's JWKS
	// obligation: a refresh failure the cache ABSORBED by serving keys inside
	// the staleness window, and the staleness-bound BREACH that fails closed.
	// One type, discriminated by `served_stale` and `staleness_breached`,
	// because they are the same fact about the same object at two severities
	// and splitting them would make a reader join two streams to answer "was
	// this issuer reachable".
	EventJWKSRefreshFailed EventType = "identity.jwks_refresh_failed"
	// identity.delivery_fetched is the machine fetch record. `disposition`
	// distinguishes a full authorized delivery from a "current" answer, and the
	// ADR requires exactly one immutable record per conditional fetch that
	// delivered nothing — never aggregated, never a counter, never a mutable
	// last-seen field.
	EventDeliveryFetched EventType = "identity.delivery_fetched"
	// Delivery-target condition reporting (#788, k8s-condition-reporting ADR
	// D8): a new row, a tombstone, a purge and each refused report. An
	// accepted repeat report emits nothing.
	EventDeliveryTargetCreated    EventType = "identity.delivery_target_created"
	EventDeliveryTargetTombstoned EventType = "identity.delivery_target_tombstoned"
	EventDeliveryTargetPurged     EventType = "identity.delivery_target_purged"
	EventDeliveryTargetRefused    EventType = "identity.delivery_target_refused"
	// identity.offline_records_reconciled is one access-class envelope per
	// reconciliation call; per-key disclosures remain separate immutable events.
	EventOfflineRecordsReconciled EventType = "identity.offline_records_reconciled"

	// identity.disclosure is the per-VALUE disclosure event on a machine fetch
	// (#64, machine-identities ADR § Audit attribution). #15's locked
	// cardinality holds: one immutable event per delivered value, never
	// collapsed, never counted. It fires only for keys whose PLAINTEXT actually
	// crossed — a `config` value under `read`, a `secret` value under
	// `read ∧ reveal` (or `read ∧ reveal-history` for a pinned non-current
	// revision) — so a presence-only key emits nothing, because no value
	// crossed, and a `current` answer emits nothing at all. Each event
	// references the fetch record (identity.delivery_fetched) by correlation
	// id: the fetch is the envelope, the per-value events are its contents
	// (audit-model ADR § envelope).
	EventDisclosure EventType = "identity.disclosure"

	// scim.* — SCIM provisioning (#73, scim-provisioning ADR §10). The set is
	// CLOSED at that ADR's lock, with a versioned v1 payload schema per entry
	// declared here rather than deferred: every field required unless the
	// schema says otherwise, ids are the rows' own ids, IdP-originated strings
	// are sanitized and bounded free text, and the derived subject NEVER
	// appears in plaintext. `subject_digest` is a per-event privately blinded
	// HMAC-SHA256 commitment, not a guessable bare subject hash. Immutable
	// resource/account IDs provide correlation. Historical bare hashes remain
	// sensitive; new commitments retain the same 64-character hex spelling.
	//
	// One entry the ADR table names is deliberately ABSENT: `scim.binding_updated`.
	// See the handoff — the locked administration surface fixes no
	// binding-mutation verb (the subject source and NameID profile are
	// immutable at creation, §5.1, and the provider reference is read-only,
	// §1), so the binding row has no field a human can address. Registering an
	// event with no emitter is exactly what the registry-closure invariant
	// forbids.
	EventSCIMUserProvisioned   EventType = "scim.user_provisioned"
	EventSCIMUserUpdated       EventType = "scim.user_updated"
	EventSCIMUserDeprovisioned EventType = "scim.user_deprovisioned"
	EventSCIMUserDeleted       EventType = "scim.user_deleted"

	EventSCIMGroupCreated    EventType = "scim.group_created"
	EventSCIMGroupUpdated    EventType = "scim.group_updated"
	EventSCIMGroupDeleted    EventType = "scim.group_deleted"
	EventSCIMGroupMembership EventType = "scim.group_membership_changed"

	// The lockout pair (§2.4). Entry names the retained grant and the cause;
	// the cure event is its own registered name, not a flag on the first.
	EventSCIMLockoutRetention         EventType = "scim.lockout_retention"
	EventSCIMLockoutRetentionReleased EventType = "scim.lockout_retention_released"

	EventSCIMBindingCreated EventType = "scim.binding_created"
	EventSCIMBindingDeleted EventType = "scim.binding_deleted"

	EventSCIMMappingCreated EventType = "scim.mapping_created"
	EventSCIMMappingUpdated EventType = "scim.mapping_updated"
	EventSCIMMappingDeleted EventType = "scim.mapping_deleted"

	// `scim.credential_rotated` is not a second verb: overlap rotation IS
	// mint-new-then-revoke-old, so a mint that joins an already-live credential
	// is the rotation and says so, while the first mint of a binding's life is
	// a plain mint.
	EventSCIMCredentialMinted  EventType = "scim.credential_minted"
	EventSCIMCredentialRotated EventType = "scim.credential_rotated"
	EventSCIMCredentialRevoked EventType = "scim.credential_revoked"

	EventSCIMAttentionEntered EventType = "scim.attention_entered"
	EventSCIMAttentionCleared EventType = "scim.attention_cleared"

	// The authenticated read/list/filter stream. `access` class, like the fetch
	// stream: the ADR withdraws by name the earlier claim that every SCIM
	// operation is mutating. The discovery endpoints are the one SCIM surface
	// carrying no tenant data and are annotated as a probe class rather than
	// being silently unaudited.
	EventSCIMDirectoryRead EventType = "scim.directory_read"

	// scim.admin_read is the ADMINISTRATION surface's read stream. It is a
	// separate name rather than a widened `scim.directory_read` because §10
	// closes that event's `resource_type` to `{user, group, discovery}` — the
	// identity provider's own wire — and a binding, mapping or credential
	// listing is a human reading configuration, not the IdP walking a
	// directory. Same `access` retention class.
	EventSCIMAdminRead EventType = "scim.admin_read"

	// scim.credential_refused records an authentication failure on the wire —
	// today, the credential-versus-binding-path mismatch §8 requires to be
	// audited. The RESPONSE is the uniform 401 either way; the trail is where
	// the distinction lives, which is the whole point of auditing it.
	EventSCIMCredentialRefused EventType = "scim.credential_refused"
	// remote.* — multi-instance (#71, multi-instance ADR § Audit). Both sides
	// of the relationship land in the INSTANCE trail: a remote entry, a
	// connection credential and an origin allowlist are all instance
	// configuration, and the directory listing addresses no tenant.
	//
	// Viewing side. remote.added carries the pin digest because the pin IS the
	// trust decision a human made interactively, and an audit trail that
	// recorded the URL but not the key the operator confirmed would record the
	// wrong half.
	EventRemotePairingPrepared      EventType = "remote.pairing_prepared"
	EventRemotePairingInviteCreated EventType = "remote.pairing_invite_created"
	EventRemotePairingInvitesListed EventType = "remote.pairing_invites_listed"
	EventRemotePairingInviteRevoked EventType = "remote.pairing_invite_revoked"
	EventRemotePairingStarted       EventType = "remote.pairing_started"
	EventRemotePairingFinished      EventType = "remote.pairing_finished"
	EventRemotePairingFailed        EventType = "remote.pairing_failed"
	EventRemoteAdded                EventType = "remote.added"
	EventRemoteRemoved              EventType = "remote.removed"
	EventRemoteRenamed              EventType = "remote.renamed"
	// remote.fetch_failed carries the closed outcome enum, never a raw
	// transport error: unreachable / credential-rejected / pin-mismatch /
	// redirect-refused / identity-conflict / self-connected. The operator's fix
	// differs per outcome, which is the whole reason the enum is closed rather
	// than a message.
	EventRemoteFetchFailed EventType = "remote.fetch_failed"
	// remote.directory_viewed is the listing read, audited because it is
	// FOREIGN STRUCTURE and `instance-directory` is a read-is-power grant — the
	// audit-model ADR's own argument applied to this ADR's own data. Successful
	// fetches ride this event: the fetch happens because of the view, so they
	// are not separately per-remote evented.
	EventRemoteDirectoryViewed EventType = "remote.directory_viewed"

	// Serving side.
	EventRemoteCredentialMinted  EventType = "remote.credential_minted"
	EventRemoteCredentialRevoked EventType = "remote.credential_revoked"
	// remote.directory_served is one event per authenticated listing serve,
	// actor = the instance-connection principal, in the ACCESS retention class
	// because it is the machine-fetch stream shape.
	EventRemoteDirectoryServed EventType = "remote.directory_served"
	// remote.origin_allowlist_changed brackets the consent list, and the
	// removal event carries the count of workspace sessions the same
	// transaction killed — de-allowlisting is a kill switch, and a trail that
	// recorded the config change but not its blast radius would understate it.
	EventRemoteOriginAllowlistChanged EventType = "remote.origin_allowlist_changed"
	// Workspace lifecycle. Each carries the normalized requesting origin and
	// the handoff transaction id; the session artifact id is present where a
	// session exists. A FAILED handoff predates any session, so its session
	// field is explicitly nullable and the transaction id is the correlating
	// key.
	EventRemoteWorkspaceSessionIssued  EventType = "remote.workspace_session_issued"
	EventRemoteWorkspaceSessionRevoked EventType = "remote.workspace_session_revoked"
	EventRemoteHandoffFailed           EventType = "remote.handoff_failed"

	// The three read events below are NOT in the multi-instance ADR's § Audit
	// enumeration, and they are here anyway because the AUDIT ADR forces them:
	// its default-deny permit rule admits `audited: none` only for tenant-class
	// bare-`read` operations, and each of these is an instance-class read of
	// custody or ceremony state. Registering them is the same disposition #54
	// took when it added auth.provider_read for exactly this collision, and #61
	// repeated for identity.lifetime_policy_read. Flagged for review as a #71
	// addition rather than smuggled in as if the ADR had named them.
	EventRemoteCredentialsListed   EventType = "remote.credentials_listed"
	EventRemoteOriginAllowlistRead EventType = "remote.origin_allowlist_read"
	// remote.workspace_handoff_read is the approve page reading a live
	// transaction's authoritative purpose and any step-up binding by state. It
	// is an authenticated human read of ceremony state, so it cannot take the
	// silent permit rule — and a caller can read then close the popup, producing
	// neither an approval nor an issuance, so no other event subsumes it.
	EventRemoteWorkspaceHandoffRead EventType = "remote.workspace_handoff_read"

	// adapter.* — deployment-module configuration, provider inspection and
	// durable per-request external-effect linkage (#65).
	EventAdapterConfigure         EventType = "adapter.configure"
	EventAdapterCredentialReplace EventType = "adapter.credential_replace"
	EventAdapterCredentialRevoke  EventType = "adapter.credential_revoke"
	EventAdapterAdopt             EventType = "adapter.adopt"
	EventAdapterInspect           EventType = "adapter.inspect"
	EventAdapterPlan              EventType = "adapter.plan"
	EventAdapterTest              EventType = "adapter.test"
	EventAdapterSyncRequested     EventType = "adapter.sync_requested"
	EventAdapterPushIntent        EventType = "adapter.push_intent"
	EventAdapterPushOutcome       EventType = "adapter.push_outcome"
	EventAdapterKeyDelivered      EventType = "adapter.key_delivered"
	EventAdapterAbort             EventType = "adapter.abort"
	EventAdapterScrub             EventType = "adapter.scrub"
	EventAdapterSuperseded        EventType = "adapter.superseded"

	// Generic file destinations (#164): configuration of a pull-class target,
	// its metadata read, and each change the bound client reports applying.
	// No path, format or value ever appears: the server never learns them.
	EventFileTargetConfigured EventType = "file_target.configured"
	EventFileTargetInspected  EventType = "file_target.inspected"
	EventFileTargetApplied    EventType = "file_target.applied"

	// Dynamic secrets (#147).
	EventDynamicProviderConfigured        EventType = "dynamic.provider_configured"
	EventDynamicProviderCredentialReplace EventType = "dynamic.provider_credential_replace"
	EventDynamicProviderCredentialRevoke  EventType = "dynamic.provider_credential_revoke"
	EventDynamicProviderDeleted           EventType = "dynamic.provider_deleted"
	EventDynamicProviderInspected         EventType = "dynamic.provider_inspected"
	EventDynamicLeaseTransitionIntent     EventType = "dynamic.lease_transition_intent"
	EventDynamicLeaseTransitionOutcome    EventType = "dynamic.lease_transition_outcome"
	EventDynamicLeaseDisclosed            EventType = "dynamic.lease_disclosed"
	EventDynamicLeaseSettleRequested      EventType = "dynamic.lease_settle_requested"
	// SSH user certificates (#155).
	EventSSHCAConfigured       EventType = "ssh.ca_configured"
	EventSSHCARotated          EventType = "ssh.ca_rotated"
	EventSSHCAKeyRetired       EventType = "ssh.ca_key_retired"
	EventSSHCADeleted          EventType = "ssh.ca_deleted"
	EventSSHProfileConfigured  EventType = "ssh.profile_configured"
	EventSSHProfileDeleted     EventType = "ssh.profile_deleted"
	EventSSHCertificateIssued  EventType = "ssh.certificate_issued"
	EventSSHCertificateRevoked EventType = "ssh.certificate_revoked"

	// Transit (#156, transit ADR D8). Every event records a decision about a
	// key: its id, versions, states and policy values. No schema below has a
	// field that can carry plaintext, ciphertext, context, signatures, MACs,
	// digests, data keys or key material.
	EventTransitKeyCreated      EventType = "transit.key_created"
	EventTransitKeyConfigured   EventType = "transit.key_configured"
	EventTransitKeyRotated      EventType = "transit.key_rotated"
	EventTransitKeyStateChanged EventType = "transit.key_state_changed"
	EventTransitKeyTrimmed      EventType = "transit.key_trimmed"
	EventTransitKeyDestroyed    EventType = "transit.key_destroyed"
	EventTransitOperation       EventType = "transit.operation"
	// Private PKI (#154, docs/adr/pki.md).
	EventPKIInventoryRead                EventType = "pki.inventory_read"
	EventPKIIssuer                       EventType = "pki.issuer"
	EventPKIProfile                      EventType = "pki.profile"
	EventPKICertificateTransitionIntent  EventType = "pki.certificate_transition_intent"
	EventPKICertificateTransitionOutcome EventType = "pki.certificate_transition_outcome"
	EventPKICertificateKeyDisclosed      EventType = "pki.certificate_key_disclosed"
	EventPKICRLPublished                 EventType = "pki.crl_published"
)

The registered event types. This slice of the v1 catalogue covers every event today's operations emit: the audit trail's own events, the authorization denial, and scaffolding domain events for the walking skeleton's demonstration operations (their real catalogue rows land with the surfaces that replace them — #47/#48/#54/#55 — under the completeness invariant, which forces every newly registered operation to map here).

func Types

func Types() []EventType

Types returns the registered types sorted, for the invariant tests.

func (EventType) Category

func (t EventType) Category() string

Category returns the category half of a type name; invalid names return "" (the registry well-formedness test refuses them).

type FieldKind

type FieldKind int

FieldKind is the closed set of payload value kinds.

const (
	// KindString is a schema-typed identifier or enum value — trusted
	// vocabulary (operation names, ids, class names), never caller free text.
	KindString FieldKind = iota
	// KindFreeText is attacker-influencable caller text. The emitter MUST
	// pass it through SanitizeFreeText before write; validation refuses a
	// value that is over-bound, non-UTF-8-clean or still matching the token
	// grammar.
	KindFreeText
	// KindInt is an integer count or bound.
	KindInt
	// KindBool is a boolean fact.
	KindBool
	// KindStringList is an ordered or set-like collection of trusted
	// identifiers. Keeping it structured avoids lossy delimiter encoding.
	KindStringList
	// KindObject is a nested, closed-schema object.
	KindObject
	// KindFreeTextMap is a bounded public config map with sanitized keys and values.
	KindFreeTextMap
	// KindObjectList is a bounded list of closed-schema objects.
	KindObjectList
)

type FieldSpec

type FieldSpec struct {
	Kind         FieldKind
	Required     bool
	ObjectSchema Schema
	// Enum closes a KindString field to a fixed value set, validated at WRITE
	// time. A registry that declares a closed enum and then accepts anything is
	// a closed enum in prose only — which is what §10's typing rules are not.
	Enum []string
	// NonNegative bounds a KindInt field below at zero. It is a FLAG, not a
	// `Min int`: the zero value of an int cannot distinguish "bound at 0" from
	// "unbounded", and a silent Min:0 on every field rejects the legitimate -1
	// that `previous_configured_seconds` uses for "inherits".
	NonNegative bool
	// AtLeast bounds a KindInt field below at a stated value; ignored when zero.
	AtLeast int
	// MaxLen bounds a KindStringList's length; MaxBytes bounds each entry.
	// MaxBytes also bounds a KindFreeText or KindString scalar, which is how
	// #73 §10's 256-byte SCIM bound is stated at the write boundary rather than
	// inherited from the trail-wide 512-byte one — a per-surface bound the
	// registry declares is a bound; a comment about it is not.
	MaxLen, MaxBytes int
	// Digest closes a KindString field to lowercase SHA-256 hex. §10 states
	// "the subject never appears in plaintext — `subject digest` is its
	// SHA-256 hex", and a field that accepts any string cannot tell a digest
	// from the subject itself, which is the exact leak the rule prevents.
	Digest bool
}

FieldSpec declares one payload field.

type Object

type Object struct {
	Type string
	ID   string
}

Object is the acted-on type + immutable id; the zero value means the event has no object (an admission-threshold crossing).

type Origin

type Origin string

Origin is the envelope's origin enum.

const (
	OriginWeb           Origin = "web"
	OriginCLI           Origin = "cli"
	OriginAPI           Origin = "api"
	OriginMCP           Origin = "mcp"
	OriginOperatorFetch Origin = "operator-fetch"
	OriginAdapterJob    Origin = "adapter-job"
	OriginOfflineRecon  Origin = "offline-reconciled"
	OriginSystem        Origin = "system"
)

type Outcome

type Outcome string

Outcome is the envelope's single outcome enum — no payload shadow-outcomes. Which values a type may carry is registry data (CI invariant 12).

const (
	OutcomeIntent       Outcome = "intent"
	OutcomeSuccess      Outcome = "success"
	OutcomeDenied       Outcome = "denied"
	OutcomeFailure      Outcome = "failure"
	OutcomeUnknown      Outcome = "unknown"
	OutcomeDisconnected Outcome = "disconnected"
)

type Payload

type Payload map[string]any

Payload carries the per-type fields, validated against the type's registered schema at write time. Values are restricted to the schema kinds below; an unregistered field, a missing required field or a kind-mismatched value fails validation and therefore fails the emitting operation (fail-closed).

type RefusalSample

type RefusalSample struct {
	Stage     RefusalStage `json:"stage"`
	SourceIP  string       `json:"source_ip"`
	RequestID string       `json:"request_id"`
	Operation string       `json:"operation"`
}

RefusalSample carries only transport-derived attribution and closed operation vocabulary. It never carries a credential identity or artifact-state cause.

func PendingRefusal

func PendingRefusal(ctx context.Context) (RefusalSample, bool)

PendingRefusal snapshots the candidate unless a dedicated event committed.

func (RefusalSample) Validate

func (s RefusalSample) Validate() error

Validate checks canonical, bounded metadata. Operation membership is supplied by the transport registry; this validator enforces its safe wire shape.

type RefusalStage

type RefusalStage string
const (
	RefusalArtifact  RefusalStage = "artifact"
	RefusalConflict  RefusalStage = "credential-conflict"
	RefusalProof     RefusalStage = "proof"
	RefusalCSRF      RefusalStage = "csrf"
	RefusalAdmission RefusalStage = "admission"
)

func RefusalStages

func RefusalStages() []RefusalStage

RefusalStages returns the closed stage order used by durable counters.

type RefusalWindow

type RefusalWindow struct {
	Counts  []int64         `json:"counts"`
	Samples []RefusalSample `json:"samples"`
}

RefusalWindow is the singleton's bounded durable staging shape. Only its dedicated writer may mutate it. Counts are exact for committed updates.

func NewRefusalWindow

func NewRefusalWindow() RefusalWindow

NewRefusalWindow initializes every counter and the bounded sample collection.

func (*RefusalWindow) Add

func (w *RefusalWindow) Add(s RefusalSample) error

Add increments an initialized, validated window and retains its first samples. Invalid metadata and counter saturation fail without advancing the counter.

func (RefusalWindow) Empty

func (w RefusalWindow) Empty() bool

Empty reports whether any committed refusal count remains to be sealed.

func (RefusalWindow) RefusalPayload

func (w RefusalWindow) RefusalPayload(stage RefusalStage, start int64) Payload

RefusalPayload produces one stage's closed summary, preserving the sample pairing without parallel arrays or delimiter encoding.

func (RefusalWindow) Validate

func (w RefusalWindow) Validate() error

Validate rejects malformed window bounds and samples not covered by a count.

type RetentionClass

type RetentionClass string

RetentionClass is one of the two classes (audit-model ADR § Retention). Class membership is fixed per event type in the registry, not configurable.

const (
	// RetentionAccess: the unbounded machine-traffic stream — fetch
	// envelopes, per-key delivery, conditional-fetch access records, denial
	// events.
	RetentionAccess RetentionClass = "access"
	// RetentionSecurity: everything else; longer default.
	RetentionSecurity RetentionClass = "security"
)

type Row

type Row struct {
	ID                string
	Type              string
	SchemaVersion     int64
	OccurredAt        time.Time
	OccurredAsserted  bool
	RecordedAt        time.Time
	ActorID           *string
	ActorClass        string
	ActorCredentialID *string
	AuthorityID       *string
	ScopeClass        string // "instance" on the instance trail
	OrgID             string // tenant trail only
	ProjectID         *string
	EnvID             *string
	ObjectType        *string
	ObjectID          *string
	Outcome           string
	CorrelationID     *string
	SourceIP          *string
	UserAgent         *string
	Origin            string
	Payload           string // schema-validated JSON
}

Row is the canonical storage shape of one validated event — the single place envelope-to-column mapping lives, shared by the store's audit repositories and the authorization package's denial writer so the two writers cannot drift. Nullable columns are pointers; times stay time.Time (each engine's binding formats them).

func BuildRow

func BuildRow(e Event, trail Trail, scope domain.Scope, recordedAt time.Time) (Row, error)

BuildRow validates e for the trail and renders it into its storage shape. scope is the trusted-layer-bound chain (see Event). sqlite supplies its durable-insert timestamp as recordedAt; postgres passes zero because its BEFORE INSERT trigger owns recorded_at. A validation failure MUST fail the emitting operation.

type Schema

type Schema map[string]FieldSpec

Schema is one event type's closed payload field set.

type Trail

type Trail string

Trail names one of the two append-only tables. The two trails are two independent seq sequences; no cross-trail order exists (audit-model ADR § Storage).

const (
	// TrailTenant is audit_tenant_events: org-owned, chain-scoped rows.
	TrailTenant Trail = "tenant"
	// TrailInstance is audit_instance_events: instance-, system- and
	// unauthenticated-class events, unresolvable denials included.
	TrailInstance Trail = "instance"
)

type TypeSpec

type TypeSpec struct {
	SchemaVersion int
	Retention     RetentionClass
	Outcomes      map[Outcome]bool
	Trails        map[Trail]bool
	Schema        Schema
}

TypeSpec is one registry row: the payload schema with its version, the retention class (exactly one — CI invariant 10), the licensed outcomes (CI invariant 12) and the trails the type may land in.

func Spec

func Spec(t EventType) (TypeSpec, bool)

Spec returns a type's registry row, reporting whether the type is registered at all.

Jump to

Keyboard shortcuts

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