Documentation
¶
Overview ¶
Package store owns datastore access. All generated query code sits behind per-aggregate repository interfaces here — no service code ever sees a pgx or sqlite type. Canonical cross-engine semantics are fixed in this package: timestamps UTC (RFC 3339 text on sqlite, timestamptz on postgres, both truncated to microseconds), booleans as integers on sqlite, JSON as text validated at the boundary.
Index ¶
- Constants
- Variables
- func CanonTime(t time.Time) time.Time
- func GuardPGSingletonLease(ctx context.Context, transaction pggen.DBTX) error
- func GuardSQLiteSingletonLease(ctx context.Context, transaction sqlitegen.DBTX) error
- func ManifestDigest(m Manifest) (releaseidentity.Digest, error)
- func SQLiteDSN(path string) string
- func VerifyEmbeddedUpgradeSource(plan upgradecompat.Plan, engine Engine) error
- func WithSingletonLease(ctx context.Context, name, owner string, fence int64) context.Context
- type AccessPolicy
- type AccessPolicyUpdate
- type AccessReader
- type AccessRepo
- type AccessRequest
- type AccessRequestState
- type AccessResolution
- type AccessVote
- type AdapterActivation
- type AdapterAdoption
- type AdapterAdoptionResult
- type AdapterAuthorizer
- type AdapterConfigureFence
- type AdapterConflictArtifact
- type AdapterConflictEntry
- type AdapterCreate
- type AdapterCredentialMutation
- type AdapterCredentialResult
- type AdapterEnqueueResult
- type AdapterExecution
- type AdapterFinding
- type AdapterHealthCounts
- type AdapterMove
- type AdapterMoveJob
- type AdapterMoveTarget
- type AdapterOriginMoveMutation
- type AdapterPauseResult
- type AdapterPin
- type AdapterPlanMaterial
- type AdapterReader
- type AdapterRecord
- type AdapterRepo
- type AdapterResumeResult
- type AdapterRouteMoveBatch
- type AdapterRouteMoveMutation
- type AdapterRouteMoveResult
- type AdapterRuntime
- func (r *AdapterRuntime) Activate(ctx context.Context, job adapter.Job, connection adapter.Connection, ...) error
- func (r *AdapterRuntime) CheckProviderSwitch(ctx context.Context) error
- func (r *AdapterRuntime) ClaimDue(ctx context.Context, worker string, now, leaseUntil time.Time) (adapter.Job, bool, error)
- func (r *AdapterRuntime) Enqueue(ctx context.Context, job adapter.Job, now time.Time) (adapter.Job, error)
- func (r *AdapterRuntime) Fail(ctx context.Context, job adapter.Job, revision int64, at time.Time, ...) error
- func (r *AdapterRuntime) Journal(job adapter.Job) adapter.Journal
- func (r *AdapterRuntime) LoadActivation(ctx context.Context, job adapter.Job) (AdapterActivation, error)
- func (r *AdapterRuntime) LoadExecution(ctx context.Context, job adapter.Job) (AdapterExecution, error)
- func (r *AdapterRuntime) Retry(ctx context.Context, job adapter.Job, due time.Time, revision int64, ...) error
- func (r *AdapterRuntime) Succeed(ctx context.Context, job adapter.Job, revision int64, warnings []string, ...) error
- type AdapterSnapshotEntry
- type AdapterTarget
- type AdapterTargetAddResult
- type AdapterTargetKey
- type AdapterTargetMutation
- type AdapterTargetUpdate
- type AdapterTargetUpdateResult
- type AdapterTeardownBatch
- type AdapterTeardownResult
- type AdapterTransport
- type ApprovalApprover
- type ApprovalApproverKind
- type ApprovalBypasser
- type ApprovalPolicy
- type ApprovalPolicyUpdate
- type ApprovalRepo
- type ApprovalRequest
- type ApprovalRequestState
- type ApprovalVote
- type ApprovalVoteDecision
- type AuditCommitSeq
- type AuditEvent
- type AuditFilter
- type AuditMatcher
- type AuditPageOrder
- type AuditPrunedRow
- type AuditReader
- type AuditRepo
- type AuditRetentionPolicy
- type BackupDrillRecord
- type BackupState
- type BackupStateReader
- type BackupStateRepo
- type CatalogueGroup
- type CatalogueKey
- type CatalogueReader
- type CatalogueRepo
- type ClaimedLease
- type Config
- type ConnectionPoolLimits
- type Coordination
- func (c *Coordination) AccountFailureState(ctx context.Context, subject string) (failures int64, lastFailure, dbNow time.Time, ok bool, err error)
- func (c *Coordination) AcquireMCP(ctx context.Context, callID, principalID, orgID string, ttl time.Duration) error
- func (c *Coordination) BumpWindow(ctx context.Context, bucket, subject string, windowStart time.Time) (result int64, err error)
- func (c *Coordination) ClaimLease(ctx context.Context, name, owner string, now, expires time.Time) (fence int64, held bool, err error)
- func (c *Coordination) ClearAccount(ctx context.Context, subject string) error
- func (c *Coordination) CountLiveNodes(ctx context.Context, since time.Time) (result int, err error)
- func (c *Coordination) CurrentSelfConfigGeneration(ctx context.Context) (SelfConfigGeneration, error)
- func (c *Coordination) ForSingletonProcess(nodeID, templateStamp string) *Coordination
- func (c *Coordination) ForeignRootKeyFingerprints(ctx context.Context, nodeID, fingerprint string, since time.Time) (result []string, err error)
- func (c *Coordination) LeaseHolder(ctx context.Context, name string, now time.Time) (owner string, acquiredAt time.Time, live bool, err error)
- func (c *Coordination) Now(ctx context.Context) (result time.Time, err error)
- func (c *Coordination) PruneAccountBackoff(ctx context.Context, cutoff time.Time) error
- func (c *Coordination) PruneAdmissionWindows(ctx context.Context, cutoff time.Time) error
- func (c *Coordination) PruneNodes(ctx context.Context, cutoff time.Time) error
- func (c *Coordination) RecordAccountFailure(ctx context.Context, subject string, now time.Time) (result int64, err error)
- func (c *Coordination) RegisterNodeChecked(ctx context.Context, n HANode, since time.Time) error
- func (c *Coordination) ReleaseLease(ctx context.Context, name, owner string, fence int64) error
- func (c *Coordination) ReleaseMCP(ctx context.Context, callID string) error
- func (c *Coordination) RenewLease(ctx context.Context, name, owner string, fence int64, now, expires time.Time) (held bool, err error)
- func (c *Coordination) SelfConfigSeedAttest(ctx context.Context, nodeID string, schemaVersion int64, fingerprint string, ...) error
- func (c *Coordination) UpsertNode(ctx context.Context, n HANode) error
- type DB
- func (d *DB) AuditExportSnapshotTime(ctx context.Context) (time.Time, error)
- func (d *DB) AwaitAuditExportWriters(ctx context.Context) error
- func (d *DB) BeginPostgres(ctx context.Context, options pgx.TxOptions) (*PostgresTransaction, error)
- func (d *DB) BeginPostgresSerialized(ctx context.Context, namespace, key int32) (*PostgresTransaction, error)
- func (d *DB) BeginSQLite(ctx context.Context, readonly bool) (*SQLiteTransaction, error)
- func (d *DB) CheckAdmission(ctx context.Context) error
- func (d *DB) Close() error
- func (d *DB) ConnectionPoolLimits() ConnectionPoolLimits
- func (d *DB) Coordination() *Coordination
- func (d *DB) DurabilityVerified() bool
- func (d *DB) Engine() Engine
- func (db *DB) ExportUpgrade(ctx context.Context, w io.Writer, workDir string, request UpgradeExportRequest) (Manifest, error)
- func (db *DB) InspectUpgradeSource(ctx context.Context, manifest releaseidentity.MigrationManifest) (upgrade.InstalledSource, error)
- func (d *DB) PG() *pgxpool.Pool
- func (d *DB) Ping(ctx context.Context) error
- func (d *DB) PreparePostgresPool(ctx context.Context, maximum int32) (*PreparedPostgresPool, error)
- func (d *DB) RecoveryIdentity() (string, string, error)
- func (d *DB) RuntimeUpgradeState(ctx context.Context) (upgrade.State, error)
- func (d *DB) SQLiteRead() *sql.DB
- func (d *DB) SQLiteWrite() *sql.DB
- func (d *DB) VerifyPostgresSource(ctx context.Context, candidateDSN string) (*VerifiedPostgresSource, error)
- type DataRestoreDestination
- type DefinitionsPlan
- type DefinitionsReader
- type DefinitionsRepo
- type DeliveryTargetKey
- type DeliveryTargetReader
- type DeliveryTargetRepo
- type DeliveryTargetReport
- type DueAccessRequest
- type DynamicLease
- type DynamicLeaseCreate
- type DynamicLeaseFinishMint
- type DynamicLeaseTransition
- type DynamicProviderCreate
- type DynamicProviderCredentialMutation
- type DynamicProviderRecord
- type DynamicReader
- type DynamicRepo
- type DynamicRuntime
- func (r *DynamicRuntime) ClaimDueLease(ctx context.Context, worker string, now, leaseUntil time.Time) (ClaimedLease, bool, error)
- func (r *DynamicRuntime) EnterUnknown(ctx context.Context, lease ClaimedLease, effectID, kind string, ...) error
- func (r *DynamicRuntime) Gauges(ctx context.Context) (activeLeases, unknownEffects int64, err error)
- func (r *DynamicRuntime) LatestEffectKind(ctx context.Context, lease ClaimedLease) (string, error)
- func (r *DynamicRuntime) LoadProviderMaterial(ctx context.Context, lease ClaimedLease) (LeaseProviderMaterial, error)
- func (r *DynamicRuntime) RecordIntent(ctx context.Context, lease ClaimedLease, kind string) (string, error)
- func (r *DynamicRuntime) RecordOutcome(ctx context.Context, lease ClaimedLease, ...) error
- func (r *DynamicRuntime) RecordOutcomeRetry(ctx context.Context, lease ClaimedLease, effectID, kind, keepState string, ...) error
- func (r *DynamicRuntime) Retry(ctx context.Context, lease ClaimedLease, nextAttempt time.Time) error
- type Engine
- type Environment
- type EnvironmentProtection
- type EnvironmentReader
- type EnvironmentRepo
- type EnvironmentSettings
- type EscrowRecord
- type ExpiredApprovalRequest
- type ExpiredDeliveryTargetReport
- type FileTarget
- type FileTargetKey
- type FileTargetReader
- type FileTargetRepo
- type FileTargetReport
- type Folder
- type FolderReader
- type FolderRepo
- type GCEligibleSnapshot
- type HANode
- type KeyDeclaration
- type KeyMetadata
- type KeyPresence
- type KeyReader
- type KeyRepo
- type LeaseProviderMaterial
- type Manifest
- func Export(ctx context.Context, db *DB, w io.Writer, workDir string) (Manifest, error)
- func ExportUpgrade(ctx context.Context, db *DB, w io.Writer, workDir string, ...) (Manifest, error)
- func ReadManifest(archive io.Reader) (Manifest, error)
- func ReadManifestEvidence(archive io.ReadSeeker) (Manifest, releaseidentity.Digest, error)
- func RestoreDataSQLite(ctx context.Context, archive io.Reader, path string, plan upgradecompat.Plan, ...) (Manifest, error)
- func RestoreSQLite(ctx context.Context, archive io.Reader, path string, ...) (Manifest, error)
- func RestoreUpgradeSQLite(ctx context.Context, archive io.Reader, path string, plan upgradecompat.Plan, ...) (Manifest, error)
- type NewAccessPolicy
- type NewAccessRequest
- type NewApprovalApprover
- type NewApprovalBypasser
- type NewApprovalPolicy
- type NewApprovalRequest
- type NewApprovalVote
- type NewCatalogueGroup
- type NewCatalogueKey
- type NewDefinitionsPlan
- type NewDismissal
- type NewEnvironment
- type NewFolder
- type NewPendingChange
- type NewProject
- type NewRemote
- type NewRevisionPin
- type NewSCIMBinding
- type NewSCIMCredential
- type NewSCIMGroup
- type NewSCIMMapping
- type NewSCIMUser
- type NewSnapshot
- type NewSnapshotEntry
- type NewValueEntry
- type OpsMetadata
- type Org
- type OrgReader
- type OrgRepo
- type PKICRLCandidate
- type PKICertificate
- type PKICertificateCreate
- type PKIGauges
- type PKIIssuer
- type PKIIssuerCreate
- type PKIIssuerInstall
- type PKIProfile
- type PKIProfileBinding
- type PKIReader
- type PKIRepo
- type PKIRevokedEntry
- type PKIRuntime
- func (r *PKIRuntime) DueCRLs(ctx context.Context, now time.Time) ([]PKICRLCandidate, error)
- func (r *PKIRuntime) ExpireDue(ctx context.Context, now time.Time, limit int) (int, error)
- func (r *PKIRuntime) Gauges(ctx context.Context, now time.Time) (PKIGauges, error)
- func (r *PKIRuntime) PublishCRL(ctx context.Context, candidate PKICRLCandidate, der []byte, number int64, ...) (bool, error)
- func (r *PKIRuntime) RevokedEntries(ctx context.Context, issuerID string, now time.Time) ([]PKIRevokedEntry, error)
- func (r *PKIRuntime) SignAndPublishCRL(ctx context.Context, candidate PKICRLCandidate, ...) (bool, error)
- func (r *PKIRuntime) SweepStaleIssuing(ctx context.Context, now time.Time, limit int) (int, error)
- type PendingChange
- type PendingMarker
- type PendingOperation
- type PendingReader
- type PendingRepo
- type PendingSource
- type PlanApplyStamp
- type PostgresTransaction
- func (t *PostgresTransaction) Commit(ctx context.Context) error
- func (t *PostgresTransaction) Exec(ctx context.Context, q string, args ...any) (pgconn.CommandTag, error)
- func (t *PostgresTransaction) Query(ctx context.Context, q string, args ...any) (pgx.Rows, error)
- func (t *PostgresTransaction) QueryRow(ctx context.Context, q string, args ...any) pgx.Row
- func (t *PostgresTransaction) Rollback(ctx context.Context) error
- type PreparationDB
- func (p *PreparationDB) Close() error
- func (p *PreparationDB) ExportUpgrade(ctx context.Context, w io.Writer, workDir string, request UpgradeExportRequest) (Manifest, error)
- func (p *PreparationDB) InspectUpgradeSource(ctx context.Context, manifest releaseidentity.MigrationManifest) (upgrade.InstalledSource, error)
- type PreparedPostgresPool
- type Project
- type ProjectCapacity
- type ProjectName
- type ProjectPayloadBytes
- type ProjectReader
- type ProjectRepo
- type ReadRepos
- type RecoveryDB
- func (r *RecoveryDB) BeginPostgres(ctx context.Context, options pgx.TxOptions) (*RecoveryPostgresTransaction, error)
- func (r *RecoveryDB) BeginSQLite(ctx context.Context, readonly bool) (*RecoverySQLiteTransaction, error)
- func (r *RecoveryDB) CheckScratch(ctx context.Context) error
- func (r *RecoveryDB) Close() error
- func (r *RecoveryDB) Engine() Engine
- func (r *RecoveryDB) SourceMigrationVersion() (uint64, error)
- type RecoveryPostgresTransaction
- func (t *RecoveryPostgresTransaction) Commit(ctx context.Context) error
- func (t *RecoveryPostgresTransaction) Exec(ctx context.Context, q string, args ...any) (pgconn.CommandTag, error)
- func (t *RecoveryPostgresTransaction) Query(ctx context.Context, q string, args ...any) (pgx.Rows, error)
- func (t *RecoveryPostgresTransaction) QueryRow(ctx context.Context, q string, args ...any) pgx.Row
- func (t *RecoveryPostgresTransaction) Rollback(ctx context.Context) error
- type RecoverySQLiteTransaction
- func (t *RecoverySQLiteTransaction) Commit() error
- func (t *RecoverySQLiteTransaction) ExecContext(ctx context.Context, q string, args ...any) (sql.Result, error)
- func (t *RecoverySQLiteTransaction) PrepareContext(ctx context.Context, q string) (*sql.Stmt, error)
- func (t *RecoverySQLiteTransaction) QueryContext(ctx context.Context, q string, args ...any) (*sql.Rows, error)
- func (t *RecoverySQLiteTransaction) QueryRowContext(ctx context.Context, q string, args ...any) *sql.Row
- func (t *RecoverySQLiteTransaction) Rollback() error
- type ReencryptFieldRow
- type ReencryptInstanceRow
- type ReencryptRepo
- type ReencryptValueRow
- type Remote
- type RemoteReader
- type RemoteRepo
- type RemoteSnapshot
- type Repos
- type RestoreDestination
- type RetentionConsequence
- type RetentionPolicy
- type RetentionReader
- type RetentionRepo
- type RevisionChange
- type RevisionKeyChange
- type RevisionPin
- type RevisionPinReader
- type RevisionPinRepo
- type SCIMAttentionRow
- type SCIMBinding
- type SCIMCredential
- type SCIMFilterField
- type SCIMGroup
- type SCIMGroupMember
- type SCIMGroupUpdate
- type SCIMListFilter
- type SCIMMapping
- type SCIMReader
- type SCIMRepo
- type SCIMUser
- type SCIMUserUpdate
- type SQLiteTransaction
- func (t *SQLiteTransaction) Commit() error
- func (t *SQLiteTransaction) ExecContext(ctx context.Context, q string, args ...any) (sql.Result, error)
- func (t *SQLiteTransaction) PrepareContext(ctx context.Context, q string) (*sql.Stmt, error)
- func (t *SQLiteTransaction) QueryContext(ctx context.Context, q string, args ...any) (*sql.Rows, error)
- func (t *SQLiteTransaction) QueryRowContext(ctx context.Context, q string, args ...any) *sql.Row
- func (t *SQLiteTransaction) Rollback() error
- type SSHActiveKey
- type SSHCA
- type SSHCACreate
- type SSHCAKey
- type SSHCAKeyCreate
- type SSHCertificate
- type SSHCertificateCreate
- type SSHProfile
- type SSHProfileWrite
- type SSHReader
- type SSHRepo
- type SSHRevokedCertificate
- type SSHRevokedSerial
- type SSHRuntime
- func (r *SSHRuntime) Gauges(ctx context.Context, now time.Time) (active, krlEntries int64, err error)
- func (r *SSHRuntime) ListLiveCertificates(ctx context.Context, now time.Time, afterID string, limit int) ([]SSHSweepCandidate, error)
- func (r *SSHRuntime) RevokeForAuthority(ctx context.Context, c SSHSweepCandidate, at time.Time) (bool, error)
- type SSHSweepCandidate
- type ScanningDismissalRepo
- type SelfConfigBinding
- type SelfConfigGeneration
- type SelfConfigJob
- type SelfConfigNode
- type SelfConfigReader
- type SelfConfigRepo
- type SelfConfigRollout
- type SelfConfigSeedInput
- type SelfConfigSeedReference
- type Snapshot
- type SnapshotCollection
- type SnapshotEntry
- type SnapshotReader
- type SnapshotRepo
- type TransitCaller
- type TransitDueKey
- type TransitGauges
- type TransitKeyConfig
- type TransitKeyCreate
- type TransitKeyRecord
- type TransitReader
- type TransitRepo
- type TransitRuntime
- type TransitStateChange
- type TransitVersionCreate
- type TransitVersionMaterial
- type TransitVersionRecord
- type UpgradeExportRequest
- type ValueEntry
- type ValueReader
- type ValueRepo
- type VerifiedPostgresSource
Constants ¶
const ( PresenceRuleRequired = "required" PresenceRuleForbidden = "forbidden" )
Presence rule values, fixed here because they are a stored enum.
const ( AccountBucket = "account" IPBucket = "ip" MetaBucket = "meta" IssuerBucket = "issuer" // MCP admission is shared across replicas. One token is restored each // second (60/minute), with at most 20 immediately available. In-flight // calls are bounded independently by principal, organization, and instance. MCPRateCapacity = 20 MCPRateRefillInterval = time.Second MCPPrincipalLimit = 4 MCPOrganizationLimit = 8 MCPInstanceLimit = 64 )
AccountBucket, IPBucket, MetaBucket, and IssuerBucket name the admission dimensions stored in admission_counters.
const ArchiveFormat = "hikyo-backup/v1"
ArchiveFormat is the archive's format identifier. A reader that does not recognise it refuses rather than guessing at the layout.
const AuditMaxPageSize = 1000
AuditMaxPageSize is the page-size ceiling (ops-spec § 10 response caps: list endpoints paged, page ≤ 1 000 items; audit pages § 2). A larger requested Limit is CLAMPED here, not refused — a page cap is a response-shape bound like SCIM's count clamp, applied at the single store chokepoint every audit page read routes through.
const MaxSCIMGroupMembers = 1000
MaxSCIMGroupMembers bounds both reconciliation work and resource expansion. The generated member queries fetch at most this ceiling plus one sentinel row, and oversized legacy groups fail closed rather than returning a subset.
const MaxSelfConfigSeedInputBytes = 32 << 20
MaxSelfConfigSeedInputBytes includes all bounded owner and node values, worst-case JSON escaping, metadata and AEAD framing. Final project values still obey their individual 64 KiB limits; this is encrypted transport only. Every owner catalogue key costs up to 6 x 64 KiB here (one escaped byte per input byte), so the bound grows with the catalogue; the seed-envelope test in internal/service pins that it still fits.
const OutcomeOK = "ok"
OutcomeOK is the one snapshot outcome that means "this fetch returned a listing". It is named here rather than spelled inline because both sides of the invariant read it: the success path requires it and the failure path refuses it.
const SelfConfigPreparationTTL = 5 * time.Minute
SelfConfigPreparationTTL bounds preparation and the administrator review window.
const UpgradeArchiveFormat = "hikyo-upgrade-backup/v2"
Variables ¶
var ErrAdapterTargetPaused = fmt.Errorf("%w: adapter target is paused; resume it to push", domain.ErrConflict)
ErrAdapterTargetPaused refuses a push-shaped act on a paused target. Pause is loud: resume is the one path back to pushing.
var ErrArchiveFormat = errors.New("store: unrecognised backup archive")
ErrArchiveFormat reports an archive this build cannot read.
var ErrAuditRetentionChanged = errors.New("audit retention pruned during export; retry the export")
ErrAuditRetentionChanged prevents an export from reporting success after policy expiry removed rows from its fixed snapshot between pages.
var ErrConflict = domain.ErrConflict
ErrConflict is the canonical cross-engine constraint refusal — a duplicate name among live siblings, or a parent still referenced by children.
var ErrEngineMismatch = errors.New("store: backup archive was taken on a different datastore engine")
ErrEngineMismatch reports an archive taken on the other engine. It is its own sentinel because the operator error is specific and the fix is specific: restore it on the engine that produced it.
var ErrMCPAdmissionLimited = errors.New("store: MCP admission limit reached")
ErrMCPAdmissionLimited is the non-distinguishing shared rate/concurrency refusal. The transport translates it to the uniform authenticated 429.
var ErrMixedRootKey = errors.New("store: another live node registered a different root-key fingerprint (mixed root keys)")
ErrMixedRootKey reports that another live node registered a different root-key fingerprint: the installation's nodes must share one root-key authority. RegisterNodeChecked returns it and boot refuses to serve.
var ErrNoProviderCredential = errors.New("store: dynamic provider has no admin credential")
ErrNoProviderCredential reports a lease whose provider has no admin credential (revoked or restored-invalidated): the worker cannot act at the provider, so it leaves the lease for a retry after the operator re-sets it.
var ErrNoSchema = errors.New("store: datastore has no schema (goose version table missing)")
ErrNoSchema reports a datastore with no goose version table at all: a datastore no migration has ever touched. Callers that treat "fresh instance" differently from "the store is broken" (the pre-migration export preflight) branch on this by name; every other failure stays an error.
var ErrNotFound = domain.ErrNotFound
ErrNotFound is the canonical cross-engine "no such row" — aliased from domain so every layer shares one sentinel for the unauthorized ≡ nonexistent rule without importing the store.
var ErrRestoreDurabilityUnconfirmed = errors.New("restored database published but durability unconfirmed")
ErrRestoreDurabilityUnconfirmed means the restored target was published but its directory durability could not be confirmed. The target and its recovery epoch changes are retained; callers must not roll forward or clean it up.
var ErrRetrySerialization = errors.New("store: transient race; retry the transaction")
ErrRetrySerialization marks an error a caller has classified as a TRANSIENT race that the bounded retry loop should re-run the whole transaction for.
It exists because the engine-level classifier cannot tell a race from a real conflict: postgres answers both with 23505. The SCIM provisioning create is the one caller today — §5.2's "the loser retries and attaches" — and the loser cannot simply re-read, because its failed statement has already aborted the transaction.
var ErrRootFinalizationPendingDeployment = errors.New("store: root finalization is blocked by an unresolved configuration deployment")
ErrRootFinalizationPendingDeployment preserves the root needed by rollback until the current deployment has an applied receipt or a repair advances it.
var ErrRotationSuperseded = errors.New("store: key rotation superseded by a concurrent rotation")
ErrRotationSuperseded reports a tier-3 key rotation (token key or DEK) losing the compare-and-swap: the active version moved between prepare and commit because a concurrent rotation committed first. The caller refuses loudly; retrying mints a fresh successor against the new predecessor.
var ErrSCIMGroupMemberLimit = fmt.Errorf("%w: SCIM groups support at most %d distinct members; the identity provider must retire excess provisioned users and reprovision them into smaller groups", domain.ErrInvalid, MaxSCIMGroupMembers)
var ErrSSHLiveCA = fmt.Errorf("%w: the environment still has a live SSH CA; delete it first", ErrConflict)
ErrSSHLiveCA refuses an environment delete while it still holds a live SSH CA: hosts may trust that CA's keys, and deleting the environment would silently drop its revocation list. Delete the CA first (which retires its keys and says so), then the environment.
var ErrSSHNoActiveKey = errors.New("store: ssh CA has no active signing key")
ErrSSHNoActiveKey reports a CA with no signing key (it was deleted).
var ErrSelfConfigSeedDisagreement = errors.New("store: admitted replicas have missing, stale or different self-configuration seeds")
var ErrSingletonLeaseLost = errors.New("store: singleton lease lost")
ErrSingletonLeaseLost refuses work from an expired or superseded leadership term, even if the scheduler has not yet observed its failed heartbeat.
var ErrStaleDEK = errors.New("store: ciphertext sealed under a non-active DEK version; re-fetch the sealer and retry")
ErrStaleDEK reports the writer fence refusing a ciphertext write: the DEK version it was sealed under is no longer active for its scope — a sealer built before a rotate-dek. The caller re-fetches a fresh sealer and retries; the service maps it to a conflict.
var ErrTargetNotEmpty = errors.New("store: restore target is not an empty datastore")
ErrTargetNotEmpty reports a restore aimed at a datastore that already holds state. Restore never merges: it reconstructs an instance, and merging a backup into a live instance is how two identity sets become one.
var ErrTransitVersionLimit = errors.New("store: transit retained version limit exceeded")
ErrTransitVersionLimit means rotation requires trimming retained versions first.
var MigrationsFS embed.FS
MigrationsFS embeds the per-dialect goose migration directories. Roll-forward only: no down-migrations in production paths.
Functions ¶
func CanonTime ¶
CanonTime fixes the canonical cross-engine timestamp semantics: UTC, microsecond precision (postgres timestamptz cannot hold more; sqlite text stores the same so both engines round-trip identically). Callers producing timestamps use it too, so the rule lives in exactly one place.
func GuardPGSingletonLease ¶
GuardPGSingletonLease locks a live matching lease through transaction commit. A takeover cannot pass the lock while admitted work is committing. After a takeover, an old SERIALIZABLE snapshot retries and checks the new fence. clock_timestamp, rather than the transaction's start time, also refuses a term that expired while this transaction waited for the lease row.
func GuardSQLiteSingletonLease ¶
GuardSQLiteSingletonLease is the SQLite counterpart. BEGIN IMMEDIATE holds write admission through commit; SQLite's process clock is authoritative.
func ManifestDigest ¶
func ManifestDigest(m Manifest) (releaseidentity.Digest, error)
ManifestDigest hashes the exact encoding written by writeManifest. A reader must instead hash original member bytes with ReadManifestEvidence below.
func SQLiteDSN ¶
SQLiteDSN builds the canonical WRITE connection string for a database file: _txlock=immediate makes write transactions BEGIN IMMEDIATE, so write intent is acquired before any read.
func VerifyEmbeddedUpgradeSource ¶
func VerifyEmbeddedUpgradeSource(plan upgradecompat.Plan, engine Engine) error
VerifyEmbeddedUpgradeSource checks the actual SQL bytes this operator binary will use for source-version scratch restoration, including the complete prefix.
func WithSingletonLease ¶
WithSingletonLease binds scheduler work to one leadership term. tx.Write checks this identity inside every attempt, using the same transaction as the job's writes. It is infrastructure identity, never tenant authorization. Ordinary requests and single-node jobs do not carry a singleton lease.
Types ¶
type AccessPolicy ¶
type AccessPolicy struct {
ID string
EnvironmentID string
Capabilities []string
MaxDurationSeconds int
MinApprovals int
AllowSelfApproval bool
RequestTTLSeconds int
Enabled bool
Version int64
CreatedBy string
CreatedAt time.Time
UpdatedAt time.Time
}
AccessPolicy is one scoped access policy. EnvironmentID is "" for a project-wide policy.
type AccessPolicyUpdate ¶
type AccessPolicyUpdate struct {
ID string
Capabilities []string
MaxDurationSeconds int
MinApprovals int
AllowSelfApproval bool
RequestTTLSeconds int
Enabled bool
UpdatedAt time.Time
}
AccessPolicyUpdate carries the mutable fields of a policy update. The environment is immutable; version bumps in SQL.
type AccessReader ¶
type AccessReader interface {
OperationalCounts(ctx context.Context, p authz.Proof, now time.Time) (open, active int64, err error)
}
AccessReader exposes only label-free operational counts to read transactions.
type AccessRepo ¶
type AccessRepo interface {
AccessReader
InsertPolicy(ctx context.Context, p authz.Proof, policy NewAccessPolicy) error
GetPolicy(ctx context.Context, p authz.Proof, id string) (AccessPolicy, error)
// CoveringPolicy returns the policy governing requests to envID: the
// exact-environment policy if one exists, else the project-wide one,
// enabled or not. The bool is false when none exists.
CoveringPolicy(ctx context.Context, p authz.Proof, envID string) (AccessPolicy, bool, error)
ListPolicies(ctx context.Context, p authz.Proof) ([]AccessPolicy, error)
UpdatePolicy(ctx context.Context, p authz.Proof, update AccessPolicyUpdate) (bool, error)
DeletePolicy(ctx context.Context, p authz.Proof, id string) (bool, error)
InsertApprover(ctx context.Context, p authz.Proof, approver NewApprovalApprover) error
ListApprovers(ctx context.Context, p authz.Proof, policyID string) ([]ApprovalApprover, error)
ClearApprovers(ctx context.Context, p authz.Proof, policyID string) (int64, error)
InsertBypasser(ctx context.Context, p authz.Proof, bypasser NewApprovalBypasser) error
ListBypassers(ctx context.Context, p authz.Proof, policyID string) ([]ApprovalBypasser, error)
ClearBypassers(ctx context.Context, p authz.Proof, policyID string) (int64, error)
IsBypasser(ctx context.Context, p authz.Proof, policyID, principalID string) (bool, error)
InsertRequest(ctx context.Context, p authz.Proof, request NewAccessRequest) error
GetRequest(ctx context.Context, p authz.Proof, id string) (AccessRequest, error)
ListRequests(ctx context.Context, p authz.Proof) ([]AccessRequest, error)
// GrantRequest moves an open request to granted; false when it was no
// longer open.
GrantRequest(ctx context.Context, p authz.Proof, id string, grantedAt, expiresAt time.Time) (bool, error)
// ResolveRequest applies one guarded terminal transition; false when the
// request had already moved.
ResolveRequest(ctx context.Context, p authz.Proof, res AccessResolution) (bool, error)
InsertVote(ctx context.Context, p authz.Proof, vote AccessVote) error
GetVote(ctx context.Context, p authz.Proof, requestID, principalID string) (AccessVote, error)
ListVotes(ctx context.Context, p authz.Proof, requestID string) ([]AccessVote, error)
// SelectDue returns one bounded installation-wide sweep batch.
SelectDue(ctx context.Context, p authz.Proof, now time.Time) ([]DueAccessRequest, error)
MarkExpired(ctx context.Context, p authz.Proof, id string, from AccessRequestState, now time.Time) (bool, error)
}
AccessRepo is the proof-bound surface of the temporary-access engine. The approver and bypasser rows reuse the #151 row shapes.
type AccessRequest ¶
type AccessRequest struct {
ID string
EnvironmentID string
PolicyID string
PolicyVersion int64
RequesterPrincipalID string
Capabilities []string
DurationSeconds int
Reason string
Bypassed bool
State AccessRequestState
InvalidatedCause string
ResolvedBy string
CreatedAt time.Time
ReviewExpiresAt time.Time
GrantedAt *time.Time
ExpiresAt *time.Time
ResolvedAt *time.Time
}
AccessRequest is one request row. GrantedAt/ExpiresAt are set once granted; ResolvedAt is set for every terminal state.
type AccessRequestState ¶
type AccessRequestState string
AccessRequestState is the closed request lifecycle. open and granted are the two ACTIVE states (resolved_at is NULL for both); the rest are terminal.
const ( AccessStateOpen AccessRequestState = "open" AccessStateGranted AccessRequestState = "granted" AccessStateRejected AccessRequestState = "rejected" AccessStateCancelled AccessRequestState = "cancelled" AccessStateExpired AccessRequestState = "expired" AccessStateInvalidated AccessRequestState = "invalidated" AccessStateRevoked AccessRequestState = "revoked" )
type AccessResolution ¶
type AccessResolution struct {
ID string
From AccessRequestState
To AccessRequestState
Cause string
ResolvedBy string
ResolvedAt time.Time
}
AccessResolution is one terminal transition, guarded by the state the caller read so a racing resolution is detectable.
type AccessVote ¶
type AccessVote struct {
ID string
RequestID string
PrincipalID string
Decision ApprovalVoteDecision
CreatedAt time.Time
}
AccessVote is one approver's decision on one request.
type AdapterActivation ¶
type AdapterActivation struct {
Provider, Origin, CredentialOwnerID string
CredentialCiphertext []byte
Transport AdapterTransport
Target adapter.Target
}
type AdapterAdoption ¶
type AdapterAdoptionResult ¶
type AdapterAuthorizer ¶
type AdapterConfigureFence ¶
type AdapterConflictArtifact ¶
type AdapterConflictEntry ¶
type AdapterCreate ¶
type AdapterCredentialResult ¶
type AdapterEnqueueResult ¶
type AdapterExecution ¶
type AdapterExecution struct {
Provider, Origin, CredentialOwnerID string
CredentialCiphertext []byte
Transport AdapterTransport
Target adapter.Target
Entries []AdapterSnapshotEntry
Ledger []adapter.LedgerEntry
Revision int64
Completed []adapter.Change
}
type AdapterFinding ¶
AdapterFinding is the latest unresolved journal finding for one provider name.
type AdapterHealthCounts ¶
type AdapterHealthCounts struct {
TargetsFailed int64
TargetsPaused int64
TargetsAttention int64
JobsQueued int64
}
AdapterHealthCounts are the instance-wide, label-free operator gauges.
type AdapterMove ¶
type AdapterMove struct {
ID, AdapterID, Kind, State, PendingOrigin, CreatedAt string
KeepRemote bool
Targets []AdapterMoveTarget
PreviousAuthorityPrincipalID string
AuthorityPrincipalID string
}
type AdapterMoveJob ¶
type AdapterMoveJob struct {
ID, TargetID, Kind, State string
}
type AdapterMoveTarget ¶
type AdapterMoveTarget struct {
TargetID, EnvironmentID, DestinationKind, DestinationOwner, DestinationName, DestinationEnvironment, DestinationScope, Visibility, NamePrefix string
DestinationID, RepositoryID int64
SelectedRepositoryIDs []int64
Orphaned []string
Jobs []AdapterMoveJob
}
type AdapterPauseResult ¶
type AdapterPauseResult struct {
TargetID string
SupersededJobID string
Generation int64
AuthorityPrincipalID string
AlreadyPaused bool
}
AdapterPauseResult reports a pause: the job it superseded (if any) and the generation the target now carries, which fences any worker still running.
type AdapterPin ¶
type AdapterPlanMaterial ¶
type AdapterPlanMaterial struct {
Target AdapterTarget
Transport AdapterTransport
CredentialCiphertext []byte
Manifest []adapter.ManifestEntry
Ledger []adapter.LedgerEntry
}
type AdapterReader ¶
type AdapterReader interface {
Get(ctx context.Context, p authz.Proof, adapterID string) (AdapterRecord, error)
Configuration(ctx context.Context, p authz.Proof, adapterID string) (AdapterRecord, []byte, error)
List(ctx context.Context, p authz.Proof) ([]AdapterRecord, error)
ListTargets(ctx context.Context, p authz.Proof, adapterID string) ([]AdapterTarget, error)
TargetKeyIDs(ctx context.Context, p authz.Proof, targetID string) ([]string, error)
TargetKeys(ctx context.Context, p authz.Proof, targetID string) ([]AdapterTargetKey, error)
Target(ctx context.Context, p authz.Proof, targetID string) (AdapterTarget, error)
// HealthCounts is the instance-wide operator read behind the adapter
// gauges and `hikyo doctor`; it carries no tenant chain.
HealthCounts(ctx context.Context, p authz.Proof) (AdapterHealthCounts, error)
Mapping(ctx context.Context, p authz.Proof, targetID string) ([]adapter.ManifestEntry, error)
PlanMaterial(ctx context.Context, p authz.Proof, targetID string) (AdapterPlanMaterial, error)
TargetEnvironments(ctx context.Context, p authz.Proof, targetID string) ([]string, error)
Environments(ctx context.Context, p authz.Proof, adapterID string) ([]string, error)
Conflicts(ctx context.Context, p authz.Proof, targetID string) ([]AdapterConflictArtifact, error)
Move(ctx context.Context, p authz.Proof, moveID string) (AdapterMove, error)
}
type AdapterRecord ¶
type AdapterRecord struct {
ID string
Provider string
Origin string
CredentialPresent bool
CredentialSetAt string
CredentialExpiresAt string
AuthorityPrincipalID string
State string
CreatedAt string
// GitLab egress trust and token policy (#159). Public material only.
SPKIPin string
CABundlePEM string
AllowPersonalToken bool
}
func (AdapterRecord) Transport ¶
func (r AdapterRecord) Transport() AdapterTransport
Transport returns the adapter's stored transport policy.
type AdapterRepo ¶
type AdapterRepo interface {
AdapterReader
ConfigurationForUpdate(ctx context.Context, p authz.Proof, adapterID string) (AdapterRecord, []byte, error)
Create(ctx context.Context, p authz.Proof, mutation AdapterCreate) (AdapterRecord, AdapterTarget, error)
BeginConfigureEffect(ctx context.Context, p authz.Proof, fence AdapterConfigureFence) error
FinishConfigureEffect(ctx context.Context, p authz.Proof, targetID, effectID, outcome string, at time.Time) error
AddTarget(ctx context.Context, p authz.Proof, mutation AdapterTargetUpdate) (AdapterTargetAddResult, error)
RecordCredentialExpiry(ctx context.Context, p authz.Proof, adapterID string, expiresAt time.Time) error
UpdateTarget(ctx context.Context, p authz.Proof, mutation AdapterTargetUpdate) (AdapterTargetUpdateResult, error)
MoveTarget(ctx context.Context, p authz.Proof, mutation AdapterRouteMoveMutation) (AdapterRouteMoveResult, error)
MoveOrigin(ctx context.Context, p authz.Proof, mutation AdapterOriginMoveMutation) (AdapterRouteMoveBatch, error)
CancelMove(ctx context.Context, p authz.Proof, moveID, authorityPrincipalID string, at time.Time) (AdapterMove, error)
ReplaceMoveTarget(ctx context.Context, p authz.Proof, moveID string, target AdapterTargetMutation, authorityPrincipalID string, at time.Time) (AdapterMove, error)
ReplaceMoveOrigin(ctx context.Context, p authz.Proof, moveID, origin string, pendingCredential []byte, authorityPrincipalID string, at time.Time) (AdapterMove, error)
RecordPlan(ctx context.Context, p authz.Proof, targetID, artifactID string, expectedGeneration, expectedRepositoryID, expectedDestinationID int64, entries []AdapterConflictEntry, at time.Time) error
Adopt(ctx context.Context, p authz.Proof, adoption AdapterAdoption) (AdapterAdoptionResult, error)
EnqueuePublished(ctx context.Context, p authz.Proof, at time.Time) ([]AdapterEnqueueResult, error)
TeardownTarget(ctx context.Context, p authz.Proof, targetID string, keepRemote bool, at time.Time) (AdapterTeardownResult, error)
TeardownAdapter(ctx context.Context, p authz.Proof, adapterID string, keepRemote bool, at time.Time) (AdapterTeardownBatch, error)
ReplaceCredential(ctx context.Context, p authz.Proof, mutation AdapterCredentialMutation) (AdapterCredentialResult, error)
RevokeCredential(ctx context.Context, p authz.Proof, adapterID string, at time.Time) (AdapterCredentialResult, error)
EnqueueManual(ctx context.Context, p authz.Proof, targetID, authorityPrincipalID string, at time.Time) (AdapterEnqueueResult, error)
// PauseTarget stops every push for the target without touching its
// ledger: it supersedes the active job, bumps the generation so a running
// worker is fenced at its next Gate, and marks paused_at. Idempotent.
PauseTarget(ctx context.Context, p authz.Proof, targetID string, at time.Time) (AdapterPauseResult, error)
// ResumeTarget clears paused_at and enqueues one converge under the given
// authority, reporting the published revision that converge will reach.
ResumeTarget(ctx context.Context, p authz.Proof, targetID, authorityPrincipalID string, at time.Time) (AdapterResumeResult, error)
// ListAdaptersForReencrypt / ReencryptAdapter and the route-move pair are
// the reencrypt walk's page + in-place re-seal of adapter credential
// ciphertext (project-wide, keyset by id). Both credential columns are
// nullable; empty rows are skipped by the walker. The AAD owner_row_id is the
// adapter id — carried as ReencryptFieldRow.Owner for the route moves, which
// key by their own id but seal under the adapter's.
ListAdaptersForReencrypt(ctx context.Context, p authz.Proof, cursor string, limit int) ([]ReencryptFieldRow, error)
ReencryptAdapter(ctx context.Context, p authz.Proof, id string, newCiphertext, oldCiphertext []byte) (bool, error)
ListRouteMovesForReencrypt(ctx context.Context, p authz.Proof, cursor string, limit int) ([]ReencryptFieldRow, error)
ReencryptRouteMove(ctx context.Context, p authz.Proof, id string, newCiphertext, oldCiphertext []byte) (bool, error)
}
type AdapterResumeResult ¶
type AdapterResumeResult struct {
Enqueue AdapterEnqueueResult
Revision int64
}
AdapterResumeResult is the converge a resume enqueued and the published revision it will converge to (0 when the environment has never published).
type AdapterRouteMoveBatch ¶
type AdapterRouteMoveBatch struct {
MoveID string
Targets []AdapterRouteMoveResult
Orphaned []string
}
type AdapterRouteMoveResult ¶
type AdapterRuntime ¶
type AdapterRuntime struct {
// contains filtered or unexported fields
}
AdapterRuntime is the domain-specific outbox's system boundary. Tenant request paths never receive it; configuration and adoption remain ordinary proof-carrying repositories. Its methods bind every statement to the leased job's immutable chain and re-check generation/authority at every effect.
func NewAdapterRuntime ¶
func NewAdapterRuntime(db *DB, authorize AdapterAuthorizer) *AdapterRuntime
func (*AdapterRuntime) Activate ¶
func (r *AdapterRuntime) Activate(ctx context.Context, job adapter.Job, connection adapter.Connection, at time.Time) error
Activate commits a tested pending target route and installs its first converge goal atomically. Until this transaction commits, target continues to name old route and remains blocked in moving state.
func (*AdapterRuntime) CheckProviderSwitch ¶
func (r *AdapterRuntime) CheckProviderSwitch(ctx context.Context) error
CheckProviderSwitch is a host-runtime safety predicate, not a tenant data read or an authority to mutate adapters. Any retained configuration or configure fence refuses a real/development-provider switch. Target, outbox, ledger, route and effect rows reference these configurations, so even an idle or historical configuration is unsafe to redirect. The application must call this after draining its requests/workers and must reject HA.
func (*AdapterRuntime) Enqueue ¶
func (r *AdapterRuntime) Enqueue(ctx context.Context, job adapter.Job, now time.Time) (adapter.Job, error)
Enqueue fences the previous goal and installs the newest target goal in one transaction. It waits while a provider request is durably marked in flight; a generation bump can therefore never race past an HTTP request already on the wire. The caller controls cancellation of that wait.
func (*AdapterRuntime) LoadActivation ¶
func (r *AdapterRuntime) LoadActivation(ctx context.Context, job adapter.Job) (AdapterActivation, error)
LoadActivation resolves only the pending route and its outbound credential. It never assembles snapshot plaintext. Caller must Gate immediately before this read; Activate later rechecks the exact leased job and move identity.
func (*AdapterRuntime) LoadExecution ¶
func (r *AdapterRuntime) LoadExecution(ctx context.Context, job adapter.Job) (AdapterExecution, error)
LoadExecution reads only the immutable inputs named by a leased job. The caller must Gate immediately before this method; every query repeats the complete job chain and generation fence. Ciphertexts remain sealed here.
type AdapterSnapshotEntry ¶
type AdapterTarget ¶
type AdapterTarget struct {
Findings []AdapterFinding
ID string
AdapterID string
Provider string
EnvironmentID string
Origin string
DestinationKind string
DestinationOwner string
DestinationName string
DestinationEnvironment string
DestinationID int64
RepositoryID int64
Visibility string
SelectedRepositoryIDs []int64
NamePrefix string
// GitLab only: DestinationScope is the environment_scope and the
// Variable* flags are the per-target delivery options (#159).
DestinationScope string
VariableProtected bool
VariableHidden bool
VariableExpand bool
Generation int64
State string
SyncStatus string
ConvergedRevision *int64
FailureNames []string
Warnings []string
AuthorityPrincipalID string
// Multi-target control and health (#157). PausedAt is non-nil while an
// operator has paused the target. LastAttempted* record the most recent
// converge attempt whether or not it succeeded; LastErrorClass is the
// bounded cause of the last failed attempt and empty after a success.
// DriftAttention is set when the destination disagrees with the ledger in
// a way only an operator can settle, and cleared by the next success.
PausedAt *time.Time
LastAttemptedRevision *int64
LastAttemptedAt *time.Time
LastErrorClass adapter.ErrorClass
DriftAttention bool
// ActiveJobState is the outbox state of the target's active job (” when
// none); RetryAt is that job's next attempt when it is queued for a retry.
ActiveJobState string
RetryAt *time.Time
// Keys is the resolved explicit key subset by name, filled by the service
// for every response that echoes membership.
Keys []AdapterTargetKey
}
func (AdapterTarget) Health ¶
func (t AdapterTarget) Health() adapter.TargetHealth
Health derives the closed operator-facing status from the stored outcome, the pause flag, and the active job state.
type AdapterTargetAddResult ¶
type AdapterTargetAddResult struct {
Target AdapterTarget
PreviousAuthorityPrincipalID string
AuthorityPrincipalID string
}
type AdapterTargetKey ¶
AdapterTargetKey is one member of a target's explicit key subset.
type AdapterTargetMutation ¶
type AdapterTargetMutation struct {
ID string
AdapterID string
EnvironmentID string
DestinationKind string
DestinationOwner string
DestinationName string
DestinationEnvironment string
DestinationID int64
RepositoryID int64
Visibility string
SelectedRepositoryIDs []int64
NamePrefix string
KeyIDs []string
DestinationScope string
VariableProtected bool
VariableHidden bool
VariableExpand bool
}
type AdapterTargetUpdate ¶
type AdapterTargetUpdateResult ¶
type AdapterTargetUpdateResult struct {
Target AdapterTarget
Enqueue AdapterEnqueueResult
PreviousAuthorityPrincipalID string
AuthorityPrincipalID string
}
type AdapterTeardownBatch ¶
type AdapterTeardownBatch struct {
AuthorityPrincipalID string
Targets []AdapterTeardownResult
}
type AdapterTeardownResult ¶
type AdapterTransport ¶
AdapterTransport is the stored provider transport policy (GitLab only).
type ApprovalApprover ¶
type ApprovalApprover struct {
ID string
PolicyID string
Kind ApprovalApproverKind
SubjectID string
ScopeBindingID string
}
ApprovalApprover is one approver-set row.
type ApprovalApproverKind ¶
type ApprovalApproverKind string
ApprovalApproverKind is the closed set of approver subject kinds.
const ( // ApprovalApproverPrincipal names one principal directly. ApprovalApproverPrincipal ApprovalApproverKind = "principal" // ApprovalApproverSCIMGroup names a SCIM group whose current active members // are eligible; ScopeBindingID says which binding to resolve them through. ApprovalApproverSCIMGroup ApprovalApproverKind = "scim_group" )
type ApprovalBypasser ¶
ApprovalBypasser is one emergency-bypasser row.
type ApprovalPolicy ¶
type ApprovalPolicy struct {
ID string
EnvironmentID string
MinApprovals int
AllowSelfApproval bool
RequestTTLSeconds int
Enabled bool
Version int64
CreatedBy string
CreatedAt time.Time
UpdatedAt time.Time
}
ApprovalPolicy is one scoped policy row. EnvironmentID is "" for a project-wide policy (covers every environment) and a concrete environment id otherwise. Version increments on every update so a request pinned to an older version fails closed.
type ApprovalPolicyUpdate ¶
type ApprovalPolicyUpdate struct {
ID string
MinApprovals int
AllowSelfApproval bool
RequestTTLSeconds int
Enabled bool
UpdatedAt time.Time
}
ApprovalPolicyUpdate carries the mutable fields of a policy update. Version bumps in SQL; the scope (org, project, env) is immutable once created.
type ApprovalRepo ¶
type ApprovalRepo interface {
InsertPolicy(ctx context.Context, p authz.Proof, policy NewApprovalPolicy) error
GetPolicy(ctx context.Context, p authz.Proof, id string) (ApprovalPolicy, error)
// CoveringPolicy returns the enabled policy governing publishes to envID:
// the exact-environment policy if one exists, else the project-wide policy.
// The bool is false when no policy covers the environment.
CoveringPolicy(ctx context.Context, p authz.Proof, envID string) (ApprovalPolicy, bool, error)
ListPolicies(ctx context.Context, p authz.Proof) ([]ApprovalPolicy, error)
UpdatePolicy(ctx context.Context, p authz.Proof, update ApprovalPolicyUpdate) (bool, error)
DeletePolicy(ctx context.Context, p authz.Proof, id string) (bool, error)
InsertApprover(ctx context.Context, p authz.Proof, approver NewApprovalApprover) error
ListApprovers(ctx context.Context, p authz.Proof, policyID string) ([]ApprovalApprover, error)
ClearApprovers(ctx context.Context, p authz.Proof, policyID string) (int64, error)
InsertBypasser(ctx context.Context, p authz.Proof, bypasser NewApprovalBypasser) error
ListBypassers(ctx context.Context, p authz.Proof, policyID string) ([]ApprovalBypasser, error)
ClearBypassers(ctx context.Context, p authz.Proof, policyID string) (int64, error)
IsBypasser(ctx context.Context, p authz.Proof, policyID, principalID string) (bool, error)
InsertRequest(ctx context.Context, p authz.Proof, request NewApprovalRequest) error
GetRequest(ctx context.Context, p authz.Proof, id string) (ApprovalRequest, error)
ListRequests(ctx context.Context, p authz.Proof) ([]ApprovalRequest, error)
// UpdateRequestState transitions one request. resolvedAt is nil for the
// approved state and set for every terminal state. It reports whether a row
// changed, so a caller can tell a real transition from a race that already
// resolved the request.
UpdateRequestState(ctx context.Context, p authz.Proof, id string, state ApprovalRequestState, cause string, resolvedAt *time.Time) (bool, error)
InsertVote(ctx context.Context, p authz.Proof, vote NewApprovalVote) error
GetVote(ctx context.Context, p authz.Proof, requestID, principalID string) (ApprovalVote, error)
ListVotes(ctx context.Context, p authz.Proof, requestID string) ([]ApprovalVote, error)
// SelectExpired returns one bounded installation-wide expiry batch. Repeated
// scheduler runs commit progress under system authority.
SelectExpired(ctx context.Context, p authz.Proof, now time.Time) ([]ExpiredApprovalRequest, error)
MarkExpired(ctx context.Context, p authz.Proof, id string, now time.Time) (bool, error)
// OperationalCounts returns the installation-wide count of active requests
// (awaiting review) and expired requests, for the label-free /metrics
// gauges. Cross-tenant; runs under scheduler authority.
OperationalCounts(ctx context.Context, p authz.Proof) (active, expired int64, err error)
}
ApprovalRepo is the proof-bound surface of the change-approval engine. It is on the WRITE bundle only: the coverage lookup that admits a publish runs inside the same publish transaction, and the read surfaces run beside their own lifecycle events, so a read-only twin would have no caller.
type ApprovalRequest ¶
type ApprovalRequest struct {
ID string
EnvironmentID string
PolicyID string
PolicyVersion int64
RequesterPrincipalID string
VersionIDs []string
ClosedVersionIDs []string
KeyIDs []string
PreviewTokenDigest string
BaseRevision int64
Purpose string
State ApprovalRequestState
InvalidatedCause string
CreatedAt time.Time
ExpiresAt time.Time
ResolvedAt *time.Time
}
ApprovalRequest is one immutable request pinned to an exact change set. ResolvedAt is nil while the request is active (open or approved).
type ApprovalRequestState ¶
type ApprovalRequestState string
ApprovalRequestState is the closed request lifecycle. open and approved are the two ACTIVE states (resolved_at is NULL for both); the rest are terminal.
const ( ApprovalStateOpen ApprovalRequestState = "open" ApprovalStateApproved ApprovalRequestState = "approved" ApprovalStateMerged ApprovalRequestState = "merged" ApprovalStateRejected ApprovalRequestState = "rejected" ApprovalStateExpired ApprovalRequestState = "expired" ApprovalStateInvalidated ApprovalRequestState = "invalidated" ApprovalStateBypassed ApprovalRequestState = "bypassed" )
type ApprovalVote ¶
type ApprovalVote struct {
ID string
RequestID string
PrincipalID string
Decision ApprovalVoteDecision
CreatedAt time.Time
}
ApprovalVote is one approver's decision on one request.
type ApprovalVoteDecision ¶
type ApprovalVoteDecision string
ApprovalVoteDecision is the closed set of vote decisions.
const ( ApprovalDecisionApprove ApprovalVoteDecision = "approve" ApprovalDecisionReject ApprovalVoteDecision = "reject" )
type AuditCommitSeq ¶
type AuditCommitSeq int64
AuditCommitSeq is postgres's database-owned export position.
type AuditEvent ¶
type AuditEvent struct {
audit.Event
Seq int64
CommitSeq AuditCommitSeq // postgres export cursor; equals Seq on sqlite
RecordedAt time.Time
ScopeClass string
OrgID string
ProjectID string
EnvID string
RawPayload string // schema-versioned JSON as stored; export emits it verbatim
}
AuditEvent is one stored trail row: the envelope plus its storage-assigned seq and recorded_at, and the chain columns as plain strings (read-side output — the analyzer's tenant-typed-parameter rule concerns inputs).
type AuditFilter ¶
type AuditFilter struct {
RetentionSnapshot time.Time // internal export guard; not a client filter
From time.Time
To time.Time
AfterSeq int64
ToSeq int64 // session ceiling: interactive pages never return seq above this
Limit int
Actor string // actor_id (the acting principal), exact
ActorName string // actor display name/username, glob; service-resolved (see below)
Type string // event type (the operation), glob
Outcomes []string // outcomes; empty = any, else set membership
ObjectType string // object type (a supported resource identifier), glob
ObjectID string // object id (a supported resource identifier), glob
CorrelationID string // links INTENT and OUTCOME of one act, exact
Order AuditPageOrder // service-controlled page mode; excluded from Normalized
AfterCommitSeq AuditCommitSeq // service-controlled export cursor; excluded from Normalized
}
AuditFilter is the normalized filter structure for trail reads. Zero From means the epoch; zero To means unbounded (bound to MaxTime at the query). AfterSeq is the public allocation-order lower bound; Limit is the page size and must be positive (the caller's bound — ops spec owns defaults). Export mode adds an internal commit-order cursor without changing AfterSeq.
The time range, AfterSeq lower bound and chain scope are enforced by the store's SQL (chain-confined, analyzer-2-provable). The equality fields below are applied by Matches AFTER the authorized page read — a projection on rows the proof already admitted, never a SQL predicate: analyzer 2 (tenant isolation, invariant 8) accepts only `col OP param` conjuncts, so an optional equality predicate has no provable SQL shape. An empty field is unset.
func (AuditFilter) Compile ¶
func (f AuditFilter) Compile() AuditMatcher
Compile snapshots the filter's row predicates and splits wildcard patterns once.
func (AuditFilter) Matches ¶
func (f AuditFilter) Matches(e AuditEvent) bool
Matches reports whether a scanned row satisfies the filter's row fields. It is pure and engine-independent by construction, so browser and CLI queries over the same filter select the same events regardless of storage engine. The time range, cursor and scope are already applied by the SQL that produced e. The text fields (Type, ObjectType, ObjectID) accept `*` wildcards via matchGlob; Actor and CorrelationID stay exact (opaque ids). ActorName is NOT checked here: it filters on the acting principal's display name, which only the service can resolve (it needs the authorizer), so the service applies it after Matches — see internal/service/audit.go.
func (AuditFilter) MatchesActorName ¶
func (f AuditFilter) MatchesActorName(name string) bool
MatchesActorName reports whether a resolved actor display name satisfies the ActorName glob. The service calls this after resolving e.Actor.ID -> name; Matches cannot, because name resolution needs the authorizer. An empty ActorName matches anything (the filter is unset).
func (AuditFilter) Normalized ¶
func (f AuditFilter) Normalized() audit.Payload
Normalized renders the filter as the audit.query event's payload fields — the parsed, normalized filter structure, never a raw query string.
func (AuditFilter) Selective ¶
func (f AuditFilter) Selective() bool
Selective reports whether any row field is set — i.e. whether the filter can reject a scanned row (by Matches or by the service's ActorName pass). The service uses this to size store reads: an unselective filter returns every scanned row, so one read of the page limit suffices; a selective one may reject most rows, so the service reads full store pages and loops until the caller's page is filled. Kept beside Matches so the field list stays in sync.
type AuditMatcher ¶
type AuditMatcher struct {
// contains filtered or unexported fields
}
AuditMatcher is an immutable snapshot of the row predicates in an AuditFilter. Cursor, normalization and actor-name resolution remain owned by the caller. It is safe to reuse across chunks even when the source filter is later edited.
func (AuditMatcher) Matches ¶
func (m AuditMatcher) Matches(e AuditEvent) bool
Matches applies the compiled row predicates without per-row allocations.
type AuditPageOrder ¶
type AuditPageOrder uint8
AuditPageOrder names the storage order for an audit page.
const ( AuditPageBySeq AuditPageOrder = iota AuditPageByCommit )
type AuditPrunedRow ¶
AuditPrunedRow contains only the facts needed for the pruning receipt.
type AuditReader ¶
type AuditReader interface {
// PageTenant returns one bounded page of the tenant trail addressed by
// the proof's resolved chain (org proofs read the whole org, deeper
// proofs read their refinement), in the filter's validated order.
PageTenant(ctx context.Context, p authz.Proof, f AuditFilter) ([]AuditEvent, error)
// PageInstance returns one bounded page of the instance trail.
PageInstance(ctx context.Context, p authz.Proof, f AuditFilter) ([]AuditEvent, error)
// MaxTenantSeq returns the highest seq in the tenant trail addressed by the
// proof's resolved chain, or 0 when it is empty. It is the interactive
// query's session ceiling: pinned once and carried by the caller so paging
// terminates and never chases the audit.query events its own reads append.
MaxTenantSeq(ctx context.Context, p authz.Proof) (int64, error)
// MaxInstanceSeq is MaxTenantSeq for the instance trail.
MaxInstanceSeq(ctx context.Context, p authz.Proof) (int64, error)
}
AuditReader is the read side of the trails.
type AuditRepo ¶
type AuditRepo interface {
AuditReader
// InsertTenant writes one tenant-trail event. The event's chain is the
// proof's resolved chain; the engine assigns recorded_at at its durable
// insert boundary.
InsertTenant(ctx context.Context, p authz.Proof, e audit.Event) error
// InsertInstance writes one instance-trail event.
InsertInstance(ctx context.Context, p authz.Proof, e audit.Event) error
// ClaimOfflineRecord atomically claims the principal-scoped client record id.
// False means a prior reconciliation already inserted it.
ClaimOfflineRecord(ctx context.Context, p authz.Proof, principalID, recordID string, at time.Time) (bool, error)
}
AuditRepo adds the two insert doors. Insertion validates against the closed registry and fails the surrounding operation on refusal (fail-closed — an operation without its durable audit record does not complete).
type AuditRetentionPolicy ¶
type AuditRetentionPolicy struct{ AccessDays, SecurityDays int }
AuditRetentionPolicy is a bounded instance policy. Zero is only the unconfigured state; it is never accepted by a persisted policy write.
func (AuditRetentionPolicy) Validate ¶
func (p AuditRetentionPolicy) Validate() error
type BackupDrillRecord ¶
type BackupDrillRecord struct {
At time.Time
OK bool
Archive string
Elapsed time.Duration
BinaryVersion string
SchemaVersion int64
}
BackupDrillRecord is what a completed restore drill writes.
type BackupState ¶
type BackupState struct {
LastSuccessAt time.Time
LastArtifactName string
LastArtifactBytes int64
LastArtifactSHA256 string
LastFailureAt time.Time
LastFailureReason string
LastPruneAt time.Time
LastPruneAttemptAt time.Time
LastPruneAttemptID string
PruneFailureReason string
RetainedExpiredArchives int64
LastDrillAt time.Time
LastDrillOK bool
LastDrillArchive string
LastDrillElapsed time.Duration
LastDrillBinaryVersion string
LastDrillSchemaVersion int64
}
BackupState is the single-row disaster-recovery health record (#145): the latest successful export, the latest failure, the latest prune and the latest restore drill. A zero time means "never". Nothing in it is secret material: archive names, byte counts, versions and reasons only.
type BackupStateReader ¶
BackupStateReader exposes the persisted DR health row.
type BackupStateRepo ¶
type BackupStateRepo interface {
BackupStateReader
SetExportSuccess(ctx context.Context, p authz.Proof, at time.Time, artifactName string, artifactBytes int64, digest string) error
SetExportFailure(ctx context.Context, p authz.Proof, at time.Time, reason string) error
SetPruneResult(ctx context.Context, p authz.Proof, at time.Time, attemptID, reason string, expired int64) error
SetDrill(ctx context.Context, p authz.Proof, rec BackupDrillRecord) error
}
BackupStateRepo owns the DR health row's writes. Each write touches only its own columns, so a failed prune cannot erase the last successful export.
type CatalogueGroup ¶
type CatalogueGroup struct {
ID string
OrgID string
ProjectID string
Name string
CreatedAt time.Time
}
CatalogueGroup is a named, project-level key group.
type CatalogueKey ¶
type CatalogueKey struct {
ID string
OrgID string
ProjectID string
Name string
FolderPath string
Classification string
Description string
Deprecated bool
DeprecationNote string
Declaration string
RequiredMode string
ForbiddenMode string
// GroupID is "" when the key belongs to no group. A key belongs to at most
// one, so this is a column rather than a join table.
GroupID string
CreatedAt time.Time
}
CatalogueKey is one declared Key: a tenant-owned aggregate (chain: org, project) whose identity is the immutable id and whose name is a mutable label on it.
Declaration holds the canonical JSON of the value-dependent rules (internal/schema); this package stores and returns it verbatim and does not interpret it — parsing rules is the schema package's authority, and a second interpreter is a second set of semantics.
type CatalogueReader ¶
type CatalogueReader interface {
Get(ctx context.Context, p authz.Proof, id string) (CatalogueKey, error)
List(ctx context.Context, p authz.Proof) ([]CatalogueKey, error)
// ListPage is the bounded keyset read (#629): one page of keys ordered by
// the UNIQUE name column, strictly past afterName ("" for the first page),
// fetching at most limit rows.
ListPage(ctx context.Context, p authz.Proof, afterName string, limit int) ([]CatalogueKey, error)
// GetInProject resolves one key by id under the key.list store authorization
// (StoreCatalogueList), so a page-bounded caller can attach a key's name and
// classification without a whole-catalogue read. ErrNotFound when absent.
GetInProject(ctx context.Context, p authz.Proof, id string) (CatalogueKey, error)
// PresenceForKey returns one key's explicit presence rows, so a bounded page
// resolves presence per page key instead of listing the project's rows.
PresenceForKey(ctx context.Context, p authz.Proof, keyID string) ([]KeyPresence, error)
// Count is the per-project key cap's input, read inside the same
// transaction as the insert it bounds.
Count(ctx context.Context, p authz.Proof) (int64, error)
AdapterPins(ctx context.Context, p authz.Proof, keyID string) ([]AdapterPin, error)
GetGroup(ctx context.Context, p authz.Proof, id string) (CatalogueGroup, error)
ListGroups(ctx context.Context, p authz.Proof) ([]CatalogueGroup, error)
CountGroups(ctx context.Context, p authz.Proof) (int64, error)
// ListPresence returns every explicit presence row in the project. It is
// project-wide rather than per-key because the group conflict check is a
// property of a SET of keys, and one read is both cheaper and impossible
// to get half-right.
ListPresence(ctx context.Context, p authz.Proof) ([]KeyPresence, error)
// SchemaRevision is the project's monotonic key-catalogue revision.
SchemaRevision(ctx context.Context, p authz.Proof) (int64, error)
}
CatalogueReader is the read side of the catalogue.
type CatalogueRepo ¶
type CatalogueRepo interface {
CatalogueReader
Create(ctx context.Context, p authz.Proof, key NewCatalogueKey) error
// Rename touches the mutable label only — identity is the immutable id, so
// a rename never breaks a reference. It IS a content-affecting schema
// change, because it changes the delivered payload's key set.
Rename(ctx context.Context, p authz.Proof, id, name string) error
UpdateMetadata(ctx context.Context, p authz.Proof, id string, m KeyMetadata) error
UpdateDeclaration(ctx context.Context, p authz.Proof, id string, d KeyDeclaration) error
// SetClassification is reached only by the reclassification ceremony; no
// ordinary update path writes this column.
SetClassification(ctx context.Context, p authz.Proof, id, classification string) error
// SetGroup moves a key into a group, or out of every group when groupID is
// "". A key belongs to at most one group, so this is a set, not an append.
SetGroup(ctx context.Context, p authz.Proof, id, groupID string) error
Delete(ctx context.Context, p authz.Proof, id string) error
CreateGroup(ctx context.Context, p authz.Proof, group NewCatalogueGroup) error
RenameGroup(ctx context.Context, p authz.Proof, id, name string) error
DeleteGroup(ctx context.Context, p authz.Proof, id string) error
// ClearGroupMembers takes a group's members out of it. Deleting a group
// dissolves the coupling; it never deletes the keys it coupled.
ClearGroupMembers(ctx context.Context, p authz.Proof, groupID string) error
// ReplacePresence rewrites one key's explicit sets whole, so a partial
// presence set cannot be observed.
ReplacePresence(ctx context.Context, p authz.Proof, keyID string, rows []KeyPresence) error
// DeletePresenceForEnvironment cascades a deleted environment's id out of
// every explicit presence set. It addresses the environment through the
// proof's chain, so it runs in the same transaction as the delete that
// earned it.
DeletePresenceForEnvironment(ctx context.Context, p authz.Proof) error
// BumpSchemaRevision advances the project's key-catalogue revision. It is
// called exactly where a SEMANTIC declaration change commits: metadata
// moves nothing, so it moves no revision.
BumpSchemaRevision(ctx context.Context, p authz.Proof) error
}
CatalogueRepo is the full catalogue aggregate.
type ClaimedLease ¶
type ClaimedLease struct {
ID string
OrgID string
ProjectID string
EnvironmentID string
ProviderID string
ProviderHandle string
PrincipalID string
PrincipalClass string
State string
MaxTTLSeconds int64
IssuedAt time.Time
ExpiresAt time.Time
Attempt int
LeaseOwner string
// ClaimToken is a monotonic per-lease counter stamped by this claim. Every
// settling write asserts it, so a stale term (even one that reacquired under
// the same worker id) cannot overwrite a newer one: the newer claim bumped
// the token, and the stale write's token no longer matches.
ClaimToken int64
}
ClaimedLease is one lease the worker has leased for a transition term.
type Config ¶
type Config struct {
Engine Engine
Path string
DSN string
PostgresPoolMax int32 // zero selects DSN pool_max_conns or the locked default
SQLiteDriver string // optional database/sql driver name for test instrumentation
}
Config selects and locates the datastore. Exactly one of Path (sqlite) or DSN (postgres) is used, per Engine.
type ConnectionPoolLimits ¶
ConnectionPoolLimits reports the effective datastore-owned limits without requiring callers to reach through the raw driver accessors. Primary is the PostgreSQL general pool or SQLite write pool; ReadOnly is the SQLite read pool and zero for PostgreSQL.
type Coordination ¶
type Coordination struct {
// contains filtered or unexported fields
}
Coordination is the installation-wide, proof-free coordination surface for multi-node HA (#146): the fenced singleton lease, the live-node registry, and the shared pre-authentication admission counters. It is infrastructure, not tenant data, so it does not pass through authz.Verify or a TxToken; like the migrator and the adapter outbox worker it runs at the app layer, and its tables carry no tenant chain (scope class instance).
func (*Coordination) AccountFailureState ¶
func (*Coordination) AcquireMCP ¶
func (*Coordination) BumpWindow ¶
func (*Coordination) ClaimLease ¶
func (*Coordination) ClearAccount ¶
func (c *Coordination) ClearAccount(ctx context.Context, subject string) error
func (*Coordination) CountLiveNodes ¶
func (*Coordination) CurrentSelfConfigGeneration ¶
func (c *Coordination) CurrentSelfConfigGeneration(ctx context.Context) (SelfConfigGeneration, error)
func (*Coordination) ForSingletonProcess ¶
func (c *Coordination) ForSingletonProcess(nodeID, templateStamp string) *Coordination
ForSingletonProcess binds a coordinator to the immutable startup identity. This restricts existing host coordination; it does not grant tenant access.
func (*Coordination) ForeignRootKeyFingerprints ¶
func (*Coordination) LeaseHolder ¶
func (*Coordination) PruneAccountBackoff ¶
func (*Coordination) PruneAdmissionWindows ¶
func (*Coordination) PruneNodes ¶
func (*Coordination) RecordAccountFailure ¶
func (*Coordination) RegisterNodeChecked ¶
func (*Coordination) ReleaseLease ¶
func (*Coordination) ReleaseMCP ¶
func (c *Coordination) ReleaseMCP(ctx context.Context, callID string) error
func (*Coordination) RenewLease ¶
func (*Coordination) SelfConfigSeedAttest ¶
func (*Coordination) UpsertNode ¶
func (c *Coordination) UpsertNode(ctx context.Context, n HANode) error
type DB ¶
type DB struct {
// contains filtered or unexported fields
}
DB holds the open datastore. SQLite keeps a single write connection (pool of one) and a separate read pool, per the boot-enforced connection policy; postgres uses one pgx pool.
func Open ¶
Open opens the datastore and, for sqlite, verifies the pragma policy took effect — if any pragma cannot be established, boot refuses (no silent downgrade).
func (*DB) AuditExportSnapshotTime ¶
AuditExportSnapshotTime returns the authoritative upper time bound for an unbounded audit export. Postgres event inserts use the same server clock, so a transaction that inserted before this cutoff remains in the snapshot even when it commits after paging starts. The fixed bound also keeps live writes from turning an export into an endless chase.
func (*DB) AwaitAuditExportWriters ¶
AwaitAuditExportWriters is the final-page barrier for a fixed audit snapshot. Postgres writers acquire the shared side of this lock before INSERT; taking the exclusive side waits until every pre-cutoff writer has committed. The autocommit statement releases the transaction lock after it establishes that barrier. sqlite's single writer needs no extra barrier.
func (*DB) BeginPostgres ¶
func (*DB) BeginPostgresSerialized ¶
func (d *DB) BeginPostgresSerialized(ctx context.Context, namespace, key int32) (*PostgresTransaction, error)
BeginPostgresSerialized takes the existing named session lock before runtime admission. Settlement releases that connection before denial auditing can ask the pool for another connection. Ambiguous unlock discards the owner.
func (*DB) BeginSQLite ¶
BeginSQLite acquires host admission before BEGIN. The write pool retains its BEGIN IMMEDIATE policy; WAL readers retain the shared host guard too.
func (*DB) CheckAdmission ¶
CheckAdmission is a read-only readiness decision under the same transaction fence as tenant work. It never creates goose tables or migrates a schema.
func (*DB) ConnectionPoolLimits ¶
func (d *DB) ConnectionPoolLimits() ConnectionPoolLimits
func (*DB) Coordination ¶
func (d *DB) Coordination() *Coordination
Coordination returns the coordination surface bound to this datastore.
func (*DB) DurabilityVerified ¶
DurabilityVerified reports successful actual boot checks, not configuration defaults. A zero or partially opened datastore cannot claim verification.
func (*DB) Engine ¶
Engine, SQLiteWrite, SQLiteRead, and PG are the doors internal/store/tx and the test harness need; Go has no friend packages, so the "service never sees a pgx or sqlite type" rule is carried by the import-boundary test and review, not the type system.
func (*DB) ExportUpgrade ¶
func (*DB) InspectUpgradeSource ¶
func (db *DB) InspectUpgradeSource(ctx context.Context, manifest releaseidentity.MigrationManifest) (upgrade.InstalledSource, error)
InspectUpgradeSource measures the source inside one read-only transaction. It is a preparation/restore inspection, not an admission or trust decision.
func (*DB) PreparePostgresPool ¶
PreparePostgresPool opens and checks a candidate without changing the current pool or writing database state. Zero restores the original DSN's pool limit, or Hikyo's default when absent. SQLite accepts only zero as a no-op.
func (*DB) RecoveryIdentity ¶
RecoveryIdentity is immutable admitted metadata. The caller's transaction guard pins it against restore before any diagnostic record is read or written.
func (*DB) RuntimeUpgradeState ¶
RuntimeUpgradeState reads only control metadata, including while admission refuses tenant transactions. It must never become a general query escape.
func (*DB) SQLiteRead ¶
func (*DB) SQLiteWrite ¶
func (*DB) VerifyPostgresSource ¶
func (d *DB) VerifyPostgresSource(ctx context.Context, candidateDSN string) (*VerifiedPostgresSource, error)
VerifyPostgresSource proves an alias/credential change for the same live PostgreSQL database. Cloned installation metadata is insufficient: a separate candidate connection must also observe two unpredictable transaction locks held by this DB. Both transactions roll back without durable writes.
type DataRestoreDestination ¶
type DataRestoreDestination struct {
// contains filtered or unexported fields
}
DataRestoreDestination imports ordinary v1 data only. The caller supplies the already decrypted archive; this capability makes no upgrade-receipt claim. Restored serving still requires a new current-incarnation proof at the gate.
func OpenDataRestoreDestination ¶
func OpenDataRestoreDestination(ctx context.Context, cfg Config, authority upgrade.DataRestoreDestinationAdmission, plan upgradecompat.Plan) (*DataRestoreDestination, error)
func (*DataRestoreDestination) Close ¶
func (d *DataRestoreDestination) Close() error
type DefinitionsPlan ¶
type DefinitionsPlan struct {
ID string
OrgID string
ProjectID string
CreatedBy string
CreatedAt time.Time
ExpiresAt time.Time
Bundle string
Digest string
BaseSchemaRevision int64
EnvRevisions string
ProtectedEnvs string
Diff string
Additive bool
// ScanSnapshot is the secret-scanning ruleset SnapshotVersion the plan was
// scanned under (#74 SS3). Apply re-scans iff it differs from the running
// ruleset's; empty means scanning was off at plan time.
ScanSnapshot string
Applied bool
AppliedAt time.Time
AppliedBy string
ProvenanceCommit string
ProvenanceRef string
ProvenanceActor string
}
DefinitionsPlan is a stored plan row (#70). Bundle holds the canonical bundle bytes; EnvRevisions, ProtectedEnvs and Diff hold canonical JSON. Applied is false until a successful apply stamps AppliedAt/AppliedBy and the display-only provenance strings.
type DefinitionsReader ¶
type DefinitionsReader interface {
// GetPlan returns the plan addressed by (proof chain, id). ErrNotFound when
// absent — the uniform outcome, so unauthorized ≡ nonexistent on the wire.
GetPlan(ctx context.Context, p authz.Proof, id string) (DefinitionsPlan, error)
// LatestAppliedPlan returns the project's most recently applied plan, or
// ErrNotFound when none has ever been applied.
LatestAppliedPlan(ctx context.Context, p authz.Proof) (DefinitionsPlan, error)
// CountOpenPlans is the open-plan quota input: unapplied and unexpired at now.
CountOpenPlans(ctx context.Context, p authz.Proof, now time.Time) (int64, error)
}
DefinitionsReader is the read side of the plan ledger.
type DefinitionsRepo ¶
type DefinitionsRepo interface {
DefinitionsReader
CreatePlan(ctx context.Context, p authz.Proof, plan NewDefinitionsPlan) error
// MarkPlanApplied stamps the apply record. It returns false when the plan was
// already applied (the guarded update affected no row), which the service
// maps to the already-applied conflict.
MarkPlanApplied(ctx context.Context, p authz.Proof, id string, stamp PlanApplyStamp) (bool, error)
// PruneExpiredPlans deletes expired, unapplied plans across the instance
// under an instance-scope proof (the hourly GC).
PruneExpiredPlans(ctx context.Context, p authz.Proof, now time.Time) (int64, error)
}
DefinitionsRepo is the full plan ledger.
type DeliveryTargetKey ¶
type DeliveryTargetKey struct {
PrincipalID string
ClusterID string
InstanceUID string
TargetUID string
}
DeliveryTargetKey is the row key under one environment: the reporting principal and the target's three UIDs (ADR D3).
type DeliveryTargetReader ¶
type DeliveryTargetReader interface {
List(ctx context.Context, p authz.Proof) ([]DeliveryTargetReport, error)
// QuotaNotices returns the project's quota-refused notices, keyed by
// principal, with each one's last refusal time.
QuotaNotices(ctx context.Context, p authz.Proof) (map[string]time.Time, error)
// LastFetchAt returns the principal's last identity.delivery_fetched time
// in the proof's environment, if any (ADR D2, observed by the server).
LastFetchAt(ctx context.Context, p authz.Proof, principalID string) (time.Time, bool, error)
}
DeliveryTargetReader is the read side the human list operation uses.
type DeliveryTargetRepo ¶
type DeliveryTargetRepo interface {
DeliveryTargetReader
Get(ctx context.Context, p authz.Proof, key DeliveryTargetKey) (DeliveryTargetReport, error)
CountForPrincipal(ctx context.Context, p authz.Proof, principalID string) (int64, error)
Insert(ctx context.Context, p authz.Proof, row DeliveryTargetReport) error
// Update replaces the accepted state of the row with row.ID and clears
// any recorded refusal.
Update(ctx context.Context, p authz.Proof, row DeliveryTargetReport) (bool, error)
RecordRefusal(ctx context.Context, p authz.Proof, id, cause string, at time.Time) (bool, error)
Delete(ctx context.Context, p authz.Proof, id string) (bool, error)
RecordQuotaRefusal(ctx context.Context, p authz.Proof, principalID string, at time.Time) error
// SelectExpired returns at most limit rows with no accepted report since
// cutoff.
SelectExpired(ctx context.Context, p authz.Proof, cutoff time.Time, limit int) ([]ExpiredDeliveryTargetReport, error)
Purge(ctx context.Context, p authz.Proof, id string, cutoff time.Time) (bool, error)
}
DeliveryTargetRepo is the write bundle's delivery-target surface.
type DeliveryTargetReport ¶
type DeliveryTargetReport struct {
ID string
EnvironmentID string
PrincipalID string
Target deliverytarget.Target
Vocabulary int
Generation int64
ObservedGeneration int64
ReportedAt time.Time
ReceivedAt time.Time
ReportIntervalSeconds int64
Lifecycle string
Conditions []deliverytarget.Condition
Reporter string
ReporterVersion string
// RefusalCause and RefusedAt are set only by a vocabulary refusal after
// the last accepted report; both are empty otherwise.
RefusalCause string
RefusedAt time.Time
CreatedAt time.Time
}
DeliveryTargetReport is one latest-state row.
type DueAccessRequest ¶
type DueAccessRequest struct {
ID string
OrgID string
ProjectID string
EnvironmentID string
PolicyID string
RequesterPrincipalID string
State AccessRequestState
}
DueAccessRequest is one row the installation-wide sweep found: an open request past its review window or a granted request past its expiry.
type DynamicLease ¶
type DynamicLease struct {
ID string
ProviderID string
EnvironmentID string
PrincipalID string
PrincipalClass string
ProviderHandle string
State string
IssuedAt string
ExpiresAt string
MaxTTLSeconds int64
LastTransitionAt string
CreatedAt string
}
DynamicLease is a lease's metadata surface. There is no secret field, ever: the minted password is delivered once at mint and never stored.
type DynamicLeaseCreate ¶
type DynamicLeaseCreate struct {
ID string
ProviderID string
PrincipalID string
PrincipalClass string
ProviderHandle string
MaxTTLSeconds int64
At time.Time
}
DynamicLeaseCreate is a mint's durable intent row (state=minting). The lease row is itself the job: next_attempt_at is stamped now so a crashed synchronous mint is picked up by the worker and settled.
type DynamicLeaseFinishMint ¶
type DynamicLeaseFinishMint struct {
LeaseID string
State string
IssuedAt time.Time
ExpiresAt time.Time
NextAttemptAt time.Time
At time.Time
}
DynamicLeaseFinishMint settles a synchronous mint: active on success, failed on a definite provider failure, unknown on an ambiguous outcome.
type DynamicLeaseTransition ¶
type DynamicLeaseTransition struct {
LeaseID string
State string
MaxTTLSeconds int64
NextAttemptAt time.Time
At time.Time
}
DynamicLeaseTransition enqueues renew/revoke/reconcile: it sets the transient state and stamps next_attempt_at now so the worker claims it. MaxTTLSeconds, when non-zero, tightens the per-period ceiling on a renew. A larger ceiling conflicts atomically with the current row; zero retains its existing ceiling.
type DynamicProviderCreate ¶
type DynamicProviderCreate struct {
ID string
Kind string
Origin string
TLSMode string
GrantRole string
CredentialCiphertext []byte
AuthorityPrincipalID string
At time.Time
}
DynamicProviderCreate is one provider configuration. Credential is already sealed by the service; the store never sees plaintext.
type DynamicProviderCredentialMutation ¶
type DynamicProviderCredentialMutation struct {
ProviderID string
CredentialCiphertext []byte
At time.Time
}
DynamicProviderCredentialMutation replaces a provider's sealed admin credential.
type DynamicProviderRecord ¶
type DynamicProviderRecord struct {
ID string
Kind string
Origin string
TLSMode string
GrantRole string
CredentialPresent bool
CredentialSetAt string
AuthorityPrincipalID string
State string
CreatedAt string
}
DynamicProviderRecord is a provider's metadata surface. There is no credential value field: the admin credential is write-only, and its presence is all a read exposes.
type DynamicReader ¶
type DynamicReader interface {
GetProvider(ctx context.Context, p authz.Proof, providerID string) (DynamicProviderRecord, error)
// ProviderCredentialCiphertext returns the sealed admin credential for the
// mint path to open. It is the ONLY method that
// returns the ciphertext; ordinary reads never do.
ProviderCredentialCiphertext(ctx context.Context, p authz.Proof, providerID string) ([]byte, error)
ListProviders(ctx context.Context, p authz.Proof) ([]DynamicProviderRecord, error)
GetLease(ctx context.Context, p authz.Proof, leaseID string) (DynamicLease, error)
ListLeasesForEnvironment(ctx context.Context, p authz.Proof) ([]DynamicLease, error)
ActiveLeaseIDsForProvider(ctx context.Context, p authz.Proof, providerID string) ([]DynamicLease, error)
ListProvidersForReencrypt(ctx context.Context, p authz.Proof, cursor string, limit int) ([]ReencryptFieldRow, error)
}
DynamicReader is the read side (inspect/list + reencrypt page).
type DynamicRepo ¶
type DynamicRepo interface {
DynamicReader
CreateProvider(ctx context.Context, p authz.Proof, mutation DynamicProviderCreate) (DynamicProviderRecord, error)
ReplaceProviderCredential(ctx context.Context, p authz.Proof, mutation DynamicProviderCredentialMutation) error
RevokeProviderCredential(ctx context.Context, p authz.Proof, providerID string, at time.Time) error
DeleteProvider(ctx context.Context, p authz.Proof, providerID string, at time.Time) error
CreateLease(ctx context.Context, p authz.Proof, mutation DynamicLeaseCreate) (DynamicLease, error)
FinishMint(ctx context.Context, p authz.Proof, mutation DynamicLeaseFinishMint) error
EnqueueTransition(ctx context.Context, p authz.Proof, mutation DynamicLeaseTransition) (DynamicLease, error)
ReencryptProvider(ctx context.Context, p authz.Proof, id string, newCiphertext, oldCiphertext []byte) (bool, error)
}
DynamicRepo is the write side plus the reads.
type DynamicRuntime ¶
type DynamicRuntime struct {
// contains filtered or unexported fields
}
DynamicRuntime is the dynamic-secret lease worker's system boundary, the second domain-specific outbox (#147; the first is AdapterRuntime). Tenant request paths never receive it. Its methods bind every statement to the claimed lease's immutable chain and re-assert the lease's own crash fence (lease_owner + lease_expires_at) on every write, so a worker that lost its lease affects zero rows.
func NewDynamicRuntime ¶
func NewDynamicRuntime(db *DB) *DynamicRuntime
func (*DynamicRuntime) ClaimDueLease ¶
func (r *DynamicRuntime) ClaimDueLease(ctx context.Context, worker string, now, leaseUntil time.Time) (ClaimedLease, bool, error)
ClaimDueLease leases one due lease for a transition term. Due = a transient state past its next_attempt_at, or an active lease past its expiry (a natural expiry the worker completes by dropping the now-dead role). A per-org cap and SKIP LOCKED keep concurrent workers off each other; the claim stamps lease_owner + lease_expires_at, which every settle re-asserts.
func (*DynamicRuntime) EnterUnknown ¶
func (r *DynamicRuntime) EnterUnknown(ctx context.Context, lease ClaimedLease, effectID, kind string, nextAttempt time.Time) error
EnterUnknown records an ambiguous outcome: the OUTCOME effect is `unknown`, the lease moves to `unknown`, and reconcile settles it later.
func (*DynamicRuntime) Gauges ¶
func (r *DynamicRuntime) Gauges(ctx context.Context) (activeLeases, unknownEffects int64, err error)
Gauges returns the two instance-wide dynamic-secret counts for /metrics: the number of currently usable leases and the number of effects stuck unknown. Proof-free like the rest of the runtime; it is a scrape-time system read.
func (*DynamicRuntime) LatestEffectKind ¶
func (r *DynamicRuntime) LatestEffectKind(ctx context.Context, lease ClaimedLease) (string, error)
LatestEffectKind returns the kind of the lease's most recent effect, so reconcile of an `unknown` lease can resume the exact transition that went ambiguous rather than guessing.
func (*DynamicRuntime) LoadProviderMaterial ¶
func (r *DynamicRuntime) LoadProviderMaterial(ctx context.Context, lease ClaimedLease) (LeaseProviderMaterial, error)
LoadProviderMaterial reads the lease's provider row (origin, grant role, TLS mode, sealed admin credential), re-asserting the lease crash fence.
func (*DynamicRuntime) RecordIntent ¶
func (r *DynamicRuntime) RecordIntent(ctx context.Context, lease ClaimedLease, kind string) (string, error)
RecordIntent writes the durable INTENT (effect row + audit event) before the provider call, re-asserting the lease crash fence. It returns the effect id the matching OUTCOME closes.
func (*DynamicRuntime) RecordOutcome ¶
func (r *DynamicRuntime) RecordOutcome(ctx context.Context, lease ClaimedLease, effectID, kind, outcome, newState string, issuedAt, expiresAt time.Time) error
RecordOutcome closes the effect with its terminal OUTCOME and moves the lease to newState, stamping issued/expires when the transition established them. It clears the crash fence so the term ends.
func (*DynamicRuntime) RecordOutcomeRetry ¶
func (r *DynamicRuntime) RecordOutcomeRetry(ctx context.Context, lease ClaimedLease, effectID, kind, keepState string, nextAttempt time.Time) error
RecordOutcomeRetry closes an effect with a `failure` outcome but keeps the lease in a transient state for another attempt: the provider was unreachable (a definite non-event), so the transition simply runs again later.
func (*DynamicRuntime) Retry ¶
func (r *DynamicRuntime) Retry(ctx context.Context, lease ClaimedLease, nextAttempt time.Time) error
Retry releases the lease for another attempt without changing its state: the provider was unreachable, so the transition is simply due again later.
type Environment ¶
type Environment struct {
ID string
OrgID string
ProjectID string
Name string
Note string
DisplayOrder int64
CreatedAt time.Time
}
Environment is a tenant-owned aggregate (chain: org, project).
DisplayOrder is the user-defined display position within the project. There is deliberately no `base` field and no defaults layer of any kind: the flat-model ADR deletes both, and a dormant column would be the structure it forbids.
type EnvironmentProtection ¶
EnvironmentProtection is one environment's identity and protected flag.
type EnvironmentReader ¶
type EnvironmentReader interface {
Parameters(ctx context.Context, p authz.Proof) (string, error)
// Get returns the environment addressed by the proof's resolved chain.
Get(ctx context.Context, p authz.Proof) (Environment, error)
// List returns the project's environments in display order.
List(ctx context.Context, p authz.Proof) ([]Environment, error)
// ListPage is the bounded keyset read (#629): one page of environments in
// List's display-order/name order, strictly past the supplied tuple (-1/""
// for the first page), fetching at most limit rows. It never materializes
// the whole project to slice a limit afterwards.
ListPage(ctx context.Context, p authz.Proof, afterDisplayOrder int64, afterName string, limit int) ([]Environment, error)
// Count is the environment-count cap's input, read inside the same
// transaction as the insert it bounds.
Count(ctx context.Context, p authz.Proof) (int64, error)
// NextOrder is the append position: one past the highest display order in
// use. It is NOT the count — deleting an environment leaves a gap on
// purpose, so a count would hand the next create a position another row
// already holds.
NextOrder(ctx context.Context, p authz.Proof) (int64, error)
// Settings reads the environment's protection state and its own
// reauthentication window (#55). The proof addresses the environment.
Settings(ctx context.Context, p authz.Proof) (EnvironmentSettings, error)
// ListProtection reads every environment's protected flag under a PROJECT
// proof — the definitions plan/apply protected-set pin (#70).
ListProtection(ctx context.Context, p authz.Proof) ([]EnvironmentProtection, error)
}
EnvironmentReader is the read side of the environments aggregate.
type EnvironmentRepo ¶
type EnvironmentRepo interface {
SetParameters(ctx context.Context, p authz.Proof, declarations string) error
EnvironmentReader
// SetSettings writes the protection state and window together: marking
// an environment protected CAPS its window, so the two are one fact and
// must not be writable apart.
SetSettings(ctx context.Context, p authz.Proof, s EnvironmentSettings) error
Create(ctx context.Context, p authz.Proof, env NewEnvironment) error
// UpdateNote mutates the non-chain note column of the environment
// addressed by the proof's chain. Chain columns are immutable —
// re-parenting is a new row (tenant-isolation ADR).
UpdateNote(ctx context.Context, p authz.Proof, note string) error
Rename(ctx context.Context, p authz.Proof, name string) error
// SetOrder writes one environment's display position. The whole ordered
// set is rewritten by one authorized operation in one transaction, so a
// partial reorder cannot be observed.
SetOrder(ctx context.Context, p authz.Proof, id string, order int64) error
Delete(ctx context.Context, p authz.Proof) error
}
EnvironmentRepo is the full environments aggregate.
type EnvironmentSettings ¶
EnvironmentSettings is the per-environment half of `project-settings`. HasWindow false means the environment inherits the instance default: a stored copy of that default would freeze it at creation time.
type EscrowRecord ¶
type ExpiredApprovalRequest ¶
type ExpiredApprovalRequest struct {
ID string
OrgID string
ProjectID string
EnvironmentID string
PolicyID string
RequesterPrincipalID string
ExpiresAt time.Time
}
ExpiredApprovalRequest is one row the installation-wide expiry sweep found. It carries the chain so the scheduler can emit a per-request audit event.
type ExpiredDeliveryTargetReport ¶
type ExpiredDeliveryTargetReport struct {
ID string
OrgID string
ProjectID string
EnvironmentID string
PrincipalID string
ReceivedAt time.Time
}
ExpiredDeliveryTargetReport is one purge candidate, with the chain the scheduler needs to write its tenant-trail purge event.
type FileTarget ¶
type FileTarget struct {
ID string
EnvironmentID string
Name string
ServiceAccountID string
PrincipalID string
Generation int64
AuthorityPrincipalID string
CreatedAt time.Time
UpdatedAt time.Time
// Report is the client's last value-free assertion, nil until the first.
Report *FileTargetReport
// Keys is attached by the service from Keys; the row read leaves it nil.
Keys []FileTargetKey
}
FileTarget is one file-target row.
type FileTargetKey ¶
FileTargetKey is one selected key: its immutable id, current name and classification.
type FileTargetReader ¶
type FileTargetReader interface {
List(ctx context.Context, p authz.Proof) ([]FileTarget, error)
Get(ctx context.Context, p authz.Proof, id string) (FileTarget, error)
Keys(ctx context.Context, p authz.Proof, id string) ([]FileTargetKey, error)
KeysForTargets(ctx context.Context, p authz.Proof, ids []string) (map[string][]FileTargetKey, error)
// ForPrincipal returns the target a workload principal is bound to in the
// proof's project, or ErrNotFound when it is bound to none.
ForPrincipal(ctx context.Context, p authz.Proof, principalID string) (FileTarget, error)
}
FileTargetReader is the read side.
type FileTargetRepo ¶
type FileTargetRepo interface {
FileTargetReader
Create(ctx context.Context, p authz.Proof, target FileTarget, keyIDs []string) error
// ReplaceKeys swaps the key selection under a generation compare-and-swap
// and returns false when the expected generation is stale.
ReplaceKeys(ctx context.Context, p authz.Proof, target FileTarget, expectedGeneration int64, keyIDs []string, authority string, at time.Time) (bool, error)
Delete(ctx context.Context, p authz.Proof, id string) (bool, error)
// RecordReport stores the report iff principalID is the target's bound
// principal and the target lives in the proof's environment.
RecordReport(ctx context.Context, p authz.Proof, id, principalID string, report FileTargetReport) (bool, error)
}
FileTargetRepo is the write bundle's file-target surface.
type FileTargetReport ¶
type FileTargetReport struct {
State string
Revision int64
Stamp string
Generation int64
ReportedAt time.Time
ReceivedAt time.Time
}
FileTargetReport is the client's last accepted report.
type Folder ¶
Folder is a tenant-owned aggregate (chain: org, project), organizational only: namespace + display grouping. No folder-scoped grants exist (permission-model ADR) and no value ever attaches to one (domain-model), so the row carries its path and nothing else.
type FolderReader ¶
type FolderReader interface {
Get(ctx context.Context, p authz.Proof, id string) (Folder, error)
List(ctx context.Context, p authz.Proof) ([]Folder, error)
}
FolderReader is the read side of the folders aggregate. A folder is addressed by (proof chain, id): the scope lattice has no folder level, so the id is an ordinary argument that can only ever resolve inside the project the proof already authorized.
type FolderRepo ¶
type FolderRepo interface {
FolderReader
Create(ctx context.Context, p authz.Proof, folder NewFolder) error
Rename(ctx context.Context, p authz.Proof, id, path string) error
Delete(ctx context.Context, p authz.Proof, id string) error
}
FolderRepo is the full folders aggregate.
type GCEligibleSnapshot ¶
type GCEligibleSnapshot struct {
ID string
OrgID string
ProjectID string
EnvironmentID string
Revision int64
// Eligible rows always carry a bounded policy, so Unlimited is false.
Policy RetentionPolicy
}
GCEligibleSnapshot is one payload candidate with the effective bounded policy that made it eligible. It contains lineage identifiers, never value material.
type HANode ¶
type HANode struct {
NodeID string
BinaryVersion string
SchemaVersion int64
RootKeyFingerprint string
StartedAt time.Time
HeartbeatAt time.Time
}
HANode is one serving node's registry row.
type KeyDeclaration ¶
KeyDeclaration is the semantic half: the value-dependent rules plus the two presence modes, replaced as one unit.
type KeyMetadata ¶
type KeyMetadata struct {
FolderPath string
Description string
Deprecated bool
DeprecationNote string
}
KeyMetadata is exactly the NON-semantic field set: it cannot change what any environment delivers or whether it validates, which is why the schema-model ADR exempts it from per-environment publish authorization. Its own type so a semantic field cannot be smuggled into a metadata write.
type KeyPresence ¶
KeyPresence is one row of an explicit presence set: this key is required (or forbidden) in this environment. `mode: all` and `mode: none` produce no rows at all — `all` is symbolic and must keep covering environments created later, so expanding it into ids here would silently exempt them.
type KeyReader ¶
type KeyReader interface {
// ActiveTokenKeyForReceipt returns only the active instance token row. The
// PostgreSQL shared row lock holds rotation behind this authorized batch;
// SQLite's admitted writer transaction provides the equivalent fence.
ActiveTokenKeyForReceipt(ctx context.Context, pf authz.Proof) (crypto.WrappedKey, error)
// ActiveMasterWrappers returns every active master wrapper (one per
// root epoch; two while a root rotation is dual-wrapped; empty at
// first boot), newest epoch first.
ActiveMasterWrappers(ctx context.Context, pf authz.Proof) ([]crypto.WrappedKey, error)
ActiveTier3(ctx context.Context, pf authz.Proof, p crypto.Purpose, orgID, projectID string) (crypto.WrappedKey, error)
// Tier3Versions returns every still-openable version of one scope's key
// (active + retiring, newest first) so the keyring can open ciphertext a
// reencrypt has not yet moved off a superseded DEK version. Empty when the
// scope has no key yet.
Tier3Versions(ctx context.Context, pf authz.Proof, p crypto.Purpose, orgID, projectID string) ([]crypto.WrappedKey, error)
// AllOpenableTier3 returns every still-openable tier-3 key across every
// scope (active + retiring), for rotate-master-key to re-wrap.
AllOpenableTier3(ctx context.Context, pf authz.Proof) ([]crypto.WrappedKey, error)
// AssertActiveDEKVersion is the writer fence: it confirms (and, on postgres,
// FOR SHARE-locks) that the DEK version a ciphertext was sealed under is
// still active for its scope, refusing with ErrStaleDEK otherwise. Called
// inside a ciphertext write's own transaction so a stale sealer cannot land a
// write under a version reencrypt is about to retire.
AssertActiveDEKVersion(ctx context.Context, pf authz.Proof, p crypto.Purpose, orgID, projectID string, version uint32) error
}
KeyReader is the read side of keyring persistence.
type KeyRepo ¶
type KeyRepo interface {
InsertInitialProjectDEK(ctx context.Context, pf authz.Proof, key crypto.WrappedKey) error
KeyReader
AcquireHierarchyGeneration(ctx context.Context, pf authz.Proof) error
InsertMaster(ctx context.Context, pf authz.Proof, k crypto.WrappedKey) error
InsertTier3(ctx context.Context, pf authz.Proof, k crypto.WrappedKey) error
// RotateTokenKey retires the active root token key and installs its
// successor, both inside the hierarchy-generation fence.
//
// It is ONE store method rather than the three calls it performs, and that
// is a rule, not a convenience: `keys.AcquireHierarchyGeneration` and
// `keys.InsertTier3` are bound to the boot mint site, and a store method is
// grant-evaluated or site-bound, never both (invariant 6). A rotation is
// grant-evaluated -- an operator holding `rotate-dek` asks for it -- so it
// reaches the same rows through a door of its own.
RotateTokenKey(ctx context.Context, pf authz.Proof, key crypto.WrappedKey) error
// RotateScanningKey retires the active scanning-fingerprint key and installs
// its successor, the exact twin of RotateTokenKey for the sixth rotation
// operation (#74). Dropping the dismissal rows is the service's, in the same
// transaction (StoreScanningDismissalsDeleteAll) — this method owns only the
// key swap, so the two concerns stay separately authorized.
RotateScanningKey(ctx context.Context, pf authz.Proof, key crypto.WrappedKey) error
// RotateDEK appends a new DEK version for one project or the instance scope
// and demotes the previous active version to retiring — no longer written,
// still openable until reencrypt walks its ciphertext. It runs inside the
// hierarchy fence (serializing against master rotation) and the scope fence
// (against writers and reencrypt); a concurrent rotation that already moved
// the active version returns ErrRotationSuperseded.
RotateDEK(ctx context.Context, pf authz.Proof, key crypto.WrappedKey) error
// RotateMasterKey installs a new master, re-wraps every tier-3 key under it,
// and retires the old master — all inside the hierarchy fence. It refuses
// (crypto.ErrMasterRotationBlocked) while the root is dual-wrapped, and
// returns ErrRotationSuperseded if a concurrent master rotation already moved
// the active master.
RotateMasterKey(ctx context.Context, pf authz.Proof, newMaster crypto.WrappedKey, rewrapped []crypto.WrappedKey) error
// RetireRetiringTier3 retires every 'retiring' version of one scope, inside
// the scope fence — reencrypt's completion, once the walk has moved every
// ciphertext onto the active version. Returns how many versions retired.
RetireRetiringTier3(ctx context.Context, pf authz.Proof, p crypto.Purpose, orgID, projectID string) (int64, error)
// RootKeyRotatePrepare commits the second master wrapper (same version, new
// epoch) of the dual-wrapped transition, inside the hierarchy fence. It
// refuses (crypto.ErrRootRotationBlocked) unless exactly one active wrapper
// exists — a prepare while one is already pending is the four-way matrix the
// ADR refuses.
RootKeyRotatePrepare(ctx context.Context, pf authz.Proof, newWrapper crypto.WrappedKey) error
AssertRootKeyEpoch(context.Context, authz.Proof, uint32) error
// RootKeyRotateFinalize retires the old-epoch wrapper and returns the new
// active epoch. It refuses (crypto.ErrNotDualWrapped) when the master is not
// dual-wrapped, ErrRotationSuperseded when a concurrent finalize won, and
// ErrRootFinalizationPendingDeployment while rollback still needs both roots.
RootKeyRotateFinalize(ctx context.Context, pf authz.Proof) (uint32, error)
InsertScopeGeneration(ctx context.Context, pf authz.Proof, p crypto.Purpose, orgID, projectID string) error
}
KeyRepo is the transactional keyring repository. InsertTier3 and InsertMaster are always preceded by AcquireHierarchyGeneration in the same transaction — the fence that will serialize key creation against master rotation (encryption-model ADR § Rotation; the rotation operations land later).
type LeaseProviderMaterial ¶
type LeaseProviderMaterial struct {
Kind string
Origin string
TLSMode string
GrantRole string
CredentialOwnerID string
CredentialCiphertext []byte
}
LeaseProviderMaterial is the provider handle a transition needs: its origin, grant role, TLS mode, and the sealed admin credential (opened by the caller).
type Manifest ¶
type Manifest struct {
Upgrade *backupreceipt.Snapshot `json:"upgrade,omitempty"`
Format string `json:"format"`
Engine Engine `json:"engine"`
// SchemaVersion is the highest applied goose migration. Restore refuses
// an archive this binary's migration set does not contain.
SchemaVersion int64 `json:"schema_version"`
CreatedAt time.Time `json:"created_at"`
// Tables is the postgres COPY member order — foreign-key-safe, so the
// restore replays it as-is. Empty for sqlite.
Tables []string `json:"tables,omitempty"`
// Sequences carries each postgres sequence's position, because COPY
// restores rows and not the counters behind them: a restored instance
// whose audit sequence starts at 1 would collide on its next write.
Sequences map[string]int64 `json:"sequences,omitempty"`
}
Manifest describes an archive: what produced it, and what a restore needs to know before it commits anything.
func Export ¶
Export writes a complete archive to w. workDir holds the engine's snapshot while it is being framed; the caller owns it and its cleanup.
Export needs no root key and produces none: every sensitive field in the snapshot is already envelope ciphertext, and the wrapped key hierarchy travels with it. That is what makes a backup readable only by someone holding BOTH the backup identity and the root key.
func ExportUpgrade ¶
func ReadManifest ¶
ReadManifest reads the archive's first member. It is separate from the restore itself because every refusal a restore can make on shape — unrecognised format, wrong engine, unknown schema version — is decidable from the manifest alone, and deciding them before opening a datastore is what "refused before any state is committed" means in practice.
func ReadManifestEvidence ¶
func ReadManifestEvidence(archive io.ReadSeeker) (Manifest, releaseidentity.Digest, error)
ReadManifestEvidence hashes the original bounded decrypted member, without re-encoding it. Full container authentication remains the caller's first step.
func RestoreDataSQLite ¶
func RestoreSQLite ¶
func RestoreSQLite(ctx context.Context, archive io.Reader, path string, mutate func(ctx context.Context, tx *sql.Tx) error) (Manifest, error)
RestoreSQLite writes the archive's snapshot to path, which must not exist. The file is fully written and fsynced under a temporary name and then linked into place, so a crash mid-restore cannot leave a half-written database where a complete one is expected.
mutate runs against the restored file BEFORE it is published, which is where the credential-epoch bump belongs: a restored datastore must never be reachable, even for an instant, in a state where its pre-restore bearer credentials still authenticate.
type NewAccessPolicy ¶
type NewAccessPolicy struct {
ID string
EnvironmentID string
Capabilities []string
MaxDurationSeconds int
MinApprovals int
AllowSelfApproval bool
RequestTTLSeconds int
Enabled bool
CreatedBy string
CreatedAt time.Time
}
NewAccessPolicy carries the caller-suppliable fields of a policy insert.
type NewAccessRequest ¶
type NewAccessRequest struct {
ID string
EnvironmentID string
PolicyID string
PolicyVersion int64
RequesterPrincipalID string
Capabilities []string
DurationSeconds int
Reason string
Bypassed bool
State AccessRequestState
ResolvedBy string
CreatedAt time.Time
ReviewExpiresAt time.Time
GrantedAt *time.Time
ExpiresAt *time.Time
}
NewAccessRequest carries the fields of a request insert. An ordinary request is written open with GrantedAt/ExpiresAt nil; an emergency request is written granted with both set.
type NewApprovalApprover ¶
type NewApprovalApprover struct {
ID string
PolicyID string
Kind ApprovalApproverKind
SubjectID string
ScopeBindingID string
}
NewApprovalApprover carries the caller-suppliable fields of an approver insert.
type NewApprovalBypasser ¶
NewApprovalBypasser carries the caller-suppliable fields of a bypasser insert.
type NewApprovalPolicy ¶
type NewApprovalPolicy struct {
ID string
EnvironmentID string
MinApprovals int
AllowSelfApproval bool
RequestTTLSeconds int
Enabled bool
CreatedBy string
CreatedAt time.Time
}
NewApprovalPolicy carries the caller-suppliable fields of a policy insert; the chain columns are bound from the proof and Version starts at 1.
type NewApprovalRequest ¶
type NewApprovalRequest struct {
ID string
EnvironmentID string
PolicyID string
PolicyVersion int64
RequesterPrincipalID string
VersionIDs []string
ClosedVersionIDs []string
KeyIDs []string
PreviewTokenDigest string
BaseRevision int64
Purpose string
CreatedAt time.Time
ExpiresAt time.Time
}
NewApprovalRequest carries the caller-suppliable fields of a request insert. State is always ApprovalStateOpen at creation and ResolvedAt is NULL.
type NewApprovalVote ¶
type NewApprovalVote struct {
ID string
RequestID string
PrincipalID string
Decision ApprovalVoteDecision
CreatedAt time.Time
}
NewApprovalVote carries the caller-suppliable fields of a vote insert.
type NewCatalogueGroup ¶
NewCatalogueGroup carries the caller-suppliable fields of a group insert.
type NewCatalogueKey ¶
type NewCatalogueKey struct {
ID string
Name string
FolderPath string
Classification string
Description string
Deprecated bool
DeprecationNote string
Declaration string
RequiredMode string
ForbiddenMode string
GroupID string
CreatedAt time.Time
}
NewCatalogueKey carries the caller-suppliable fields of a key insert; chain columns are bound from the proof, as with every other aggregate.
type NewDefinitionsPlan ¶
type NewDefinitionsPlan struct {
ID string
CreatedBy string
CreatedAt time.Time
ExpiresAt time.Time
Bundle string
Digest string
BaseSchemaRevision int64
EnvRevisions string
ProtectedEnvs string
Diff string
Additive bool
ScanSnapshot string
}
NewDefinitionsPlan carries the caller-suppliable fields of a plan insert; chain columns are bound from the proof.
type NewDismissal ¶
type NewDismissal struct {
ID string
KeyID string
RuleDigest string
Fingerprint []byte
CreatedBy string
CreatedAt time.Time
}
NewDismissal is a "keep as config" acknowledgement to persist.
type NewEnvironment ¶
type NewEnvironment struct {
ID string
Name string
Note string
DisplayOrder int64
CreatedAt time.Time
}
NewEnvironment carries the caller-suppliable fields of an environment insert; chain columns are bound from the proof, as with NewProject.
type NewFolder ¶
NewFolder carries the caller-suppliable fields of a folder insert; chain columns are bound from the proof, as with NewProject.
type NewPendingChange ¶
type NewPendingChange struct {
ID string
KeyID string
OwnerID string
Operation PendingOperation
Ciphertext []byte
StagedFromRevision int64
StagedFromEntry string
CreatedAt time.Time
Source PendingSource
Secret bool
MaterialSecret bool
}
NewPendingChange carries the caller-suppliable fields of a draft write; the chain columns and the environment are bound from the proof.
type NewProject ¶
NewProject carries the caller-suppliable fields of a project insert. It deliberately has no chain fields: the org id is bound from the proof by the repository layer, so caller arguments structurally cannot reach the chain columns (tenant-isolation ADR § row shape and lookup discipline).
type NewRemote ¶
type NewRemote struct {
ID string
Name string
URL string
SPKIPin string
CredentialSealed []byte
CreatedAt time.Time
CreatedBy domain.PrincipalID
}
NewRemote is one entry insert. It is the only carrier that names the sealed credential, and it names it once.
type NewRevisionPin ¶
type NewSCIMBinding ¶
type NewSCIMBinding struct {
ID string
ProviderKind string
ProviderID string
ProviderSlug string
ProviderIssuer string
SubjectSource string
NameIDFormat string
NameIDQualifier string
NameIDQualifierPresent bool
NameIDSPQualifier string
NameIDSPQualifierPresent bool
ConnectionPrincipalID string
CreatedAt time.Time
}
NewSCIMBinding is the insert carrier. It deliberately has no OrgID: the chain column is bound from the proof.
type NewSCIMCredential ¶
type NewSCIMCredential struct {
ID string
BindingID string
PrincipalID string
Verifier []byte
CredentialEpoch int64
CreatedAt time.Time
ExpiresAt time.Time
}
NewSCIMCredential is the mint carrier. It has no OrgID: the chain column is bound from the proof.
type NewSCIMGroup ¶
type NewSCIMGroup struct {
ID string
BindingID string
DisplayName string
DisplayNameLower string
ExternalID string
CreatedAt time.Time
UpdatedAt time.Time
}
NewSCIMGroup is the group insert carrier.
type NewSCIMMapping ¶
type NewSCIMMapping struct {
ID string
BindingID string
GroupID string
Template string
ScopeProjectID string
ScopeEnvID string
CreatedAt time.Time
}
NewSCIMMapping is the mapping insert carrier.
type NewSCIMUser ¶
type NewSCIMUser struct {
ID string
BindingID string
AccountID string
UserName string
UserNameLower string
ExternalID string
Subject string
Active bool
Attributes string
CreatedAt time.Time
UpdatedAt time.Time
}
NewSCIMUser is the user insert carrier.
type NewSnapshot ¶
type NewSnapshot struct {
ParameterContract string
ID string
Revision int64
SchemaRevision int64
PublishedBy string
PublishedAt time.Time
}
NewSnapshot carries the caller-suppliable fields of a snapshot insert.
type NewSnapshotEntry ¶
type NewSnapshotEntry struct {
ID string
SnapshotID string
KeyID string
KeyName string
Classification string
Ciphertext []byte
ValueEntryID string
}
NewSnapshotEntry carries the caller-suppliable fields of an entry insert.
type NewValueEntry ¶
type NewValueEntry struct {
ID string
KeyID string
Ciphertext []byte
UpdatedAt time.Time
UpdatedBy string
}
NewValueEntry carries the caller-suppliable fields of a value write. The chain columns and the environment are bound from the proof.
type OpsMetadata ¶
type OpsMetadata struct {
EscrowVerifiedAt time.Time
EscrowInstanceID, EscrowIncarnation string
EscrowRootEpoch, RootEpoch, RootWrappers, RetiringScopes int64
PinsExpired, PinsDay, PinsWeek, PinsMonth int64
LastReencryptSuccess time.Time
}
OpsMetadata contains aggregate public operational state, never key material or tenant identifiers. Instance/incarnation are internal attestation bindings.
type Org ¶
type Org struct {
ID string
Name string
Active bool
Metadata json.RawMessage
CreatedAt time.Time
Retention RetentionPolicy
// Origin is how the org came to exist (#585 d8): `manual` (an operator's
// org.create) or `registration` (a sign-up). Empty on create means manual.
// RegistrationPolicyID is the minting policy's id, a trail pointer with no
// foreign key; empty for a manual org.
Origin string
RegistrationPolicyID string
}
Org is the tenancy boundary. Creation, listing and counting are instance-scoped (cross-tenant by definition: a create has no parent tenant and an enumeration spans all of them). Every BY-ID operation is tenant-owned at org depth — the addressed id comes from the proof's chain like any other tenant address, which is what makes an org the caller may not reach indistinguishable from one that does not exist (#48, mvp-boundary C1).
type OrgReader ¶
type OrgReader interface {
Get(ctx context.Context, p authz.Proof) (Org, error)
List(ctx context.Context, p authz.Proof) ([]Org, error)
Count(ctx context.Context, p authz.Proof) (int64, error)
}
OrgReader is the read side of the orgs aggregate. Get takes no id: the org it returns is the one the proof's chain addresses. List and Count are the instance-scoped enumerations and carry no address at all.
type OrgRepo ¶
type OrgRepo interface {
OrgReader
Create(ctx context.Context, p authz.Proof, org Org) error
// Rename and Delete address the org through the proof's chain. Rename
// touches the mutable name only — identity is the immutable id, so a
// rename never breaks a reference.
Rename(ctx context.Context, p authz.Proof, name string) error
Lock(ctx context.Context, p authz.Proof) error
SetRetention(ctx context.Context, p authz.Proof, policy RetentionPolicy) error
Delete(ctx context.Context, p authz.Proof) error
}
OrgRepo is the full per-aggregate repository interface. Only transaction closures (internal/store/tx) ever hold one.
type PKICRLCandidate ¶
type PKICRLCandidate struct {
IssuerID string
Name string
Version int64
CertificateDER []byte
EncryptedPrivateKey []byte
DEKVersion uint32
CRLNumber int64
RevocationSeq int64
}
PKICRLCandidate is an issuer version whose CRL is due: never published, past half its validity, or behind a committed revocation. RevocationSeq is captured before the entry snapshot and persisted unchanged on publication.
type PKICertificate ¶
type PKICertificate struct {
ID string
EnvironmentID string
ProfileID string
ProfileName string
IssuerID string
Serial string
State string
KeySource string
KeyAlgorithm string
KeyFingerprint string
CommonName string
SANs string
NotBefore time.Time
NotAfter time.Time
CertificateDER []byte
PrincipalID string
PrincipalClass string
RenewedFrom string
RenewedBy string
RevokedAt time.Time
RevocationReason string
IssuingDeadline time.Time
RowVersion int64
CreatedAt time.Time
UpdatedAt time.Time
}
PKICertificate is an issuance record. There is no private-key field, ever.
type PKICertificateCreate ¶
type PKICertificateCreate struct {
ID string
ProfileID string
ProfileName string
IssuerID string
Serial string
KeySource string
KeyAlgorithm string
KeyFingerprint string
CommonName string
SANs string
NotBefore time.Time
NotAfter time.Time
PrincipalID string
PrincipalClass string
RenewedFrom string
IssuingDeadline time.Time
At time.Time
}
PKICertificateCreate reserves a serial in an `issuing` row (the INTENT).
type PKIIssuer ¶
type PKIIssuer struct {
ID string
Name string
Version int64
Kind string
Origin string
ParentID string
State string
KeyAlgorithm string
KeyFingerprint string
KeyPresent bool
CertificateDER []byte
CSRDER []byte
ChainPEM string
SubjectCN string
SubjectOrg string
NotBefore time.Time
NotAfter time.Time
CRLDistributionURL string
RestoreHold bool
IssuedCount int64
CRLDER []byte
CRLNumber int64
RevocationSeq int64
CRLThisUpdate time.Time
CRLNextUpdate time.Time
RowVersion int64
CreatedBy string
CreatedAt time.Time
UpdatedAt time.Time
}
PKIIssuer is one CA key version's public surface. It has no private-key field: the sealed key is read only by IssuerKey, for the in-process signer.
type PKIIssuerCreate ¶
type PKIIssuerCreate struct {
ID string
Name string
Version int64
Kind string
Origin string
ParentID string
State string
KeyAlgorithm string
KeyFingerprint string
EncryptedPrivateKey []byte
DEKVersion uint32
CertificateDER []byte
CSRDER []byte
ChainPEM string
SubjectCN string
SubjectOrg string
NotBefore time.Time
NotAfter time.Time
CRLDistributionURL string
CreatedBy string
At time.Time
}
PKIIssuerCreate is a new issuer version. EncryptedPrivateKey is sealed by the service; the store never sees key plaintext.
type PKIIssuerInstall ¶
type PKIIssuerInstall struct {
ID string
RowVersion int64
CertificateDER []byte
ChainPEM string
NotBefore time.Time
NotAfter time.Time
At time.Time
}
PKIIssuerInstall activates a pending version with its externally signed certificate.
type PKIProfile ¶
type PKIProfile struct {
ID string
Name string
Policy string
RowVersion int64
CreatedBy string
CreatedAt time.Time
UpdatedAt time.Time
}
PKIProfile is a stored profile. Policy is the canonical JSON the service encodes; the store does not interpret it.
type PKIProfileBinding ¶
type PKIProfileBinding struct {
ID string
ProfileID string
OrgID string
ProjectID string
EnvironmentID string
CreatedBy string
CreatedAt time.Time
}
PKIProfileBinding is one explicit reach of a profile into a project, or one environment of it (EnvironmentID empty = the whole project).
type PKIReader ¶
type PKIReader interface {
GetCertificate(ctx context.Context, p authz.Proof, id string) (PKICertificate, error)
ListCertificates(ctx context.Context, p authz.Proof) ([]PKICertificate, error)
BoundProfiles(ctx context.Context, p authz.Proof) ([]PKIProfile, error)
IssuerPublic(ctx context.Context, p authz.Proof, id string) (PKIIssuer, error)
ActiveIssuerPublic(ctx context.Context, p authz.Proof, name string) (PKIIssuer, error)
}
PKIReader is the audit-free read side.
type PKIRepo ¶
type PKIRepo interface {
PKIReader
// Issuers (instance operations).
ListIssuers(ctx context.Context, p authz.Proof) ([]PKIIssuer, error)
GetIssuer(ctx context.Context, p authz.Proof, id string) (PKIIssuer, error)
// IssuerKey returns the sealed private key and its DEK version for the
// in-process signer. It is the ONLY method that returns key ciphertext.
IssuerKey(ctx context.Context, p authz.Proof, id string) ([]byte, uint32, error)
CreateIssuer(ctx context.Context, p authz.Proof, m PKIIssuerCreate) error
InstallIssuerCertificate(ctx context.Context, p authz.Proof, m PKIIssuerInstall) (bool, error)
TransitionIssuer(ctx context.Context, p authz.Proof, id, from, to string, rowVersion int64, at time.Time) (bool, error)
DestroyIssuerKey(ctx context.Context, p authz.Proof, id, from, to string, rowVersion int64, at time.Time) (bool, error)
SetIssuerHold(ctx context.Context, p authz.Proof, id string, hold bool, rowVersion int64, at time.Time) (bool, error)
CountLiveCertificates(ctx context.Context, p authz.Proof, issuerID string, now time.Time) (int64, error)
RevokeLiveCertificates(ctx context.Context, p authz.Proof, issuerID, reason string, at time.Time) (int64, error)
RevokedEntries(ctx context.Context, p authz.Proof, issuerID string, now time.Time) ([]PKIRevokedEntry, error)
PublishCRL(ctx context.Context, p authz.Proof, issuerID string, der []byte, previousNumber, number, revocationSeq int64, thisUpdate, nextUpdate time.Time) (bool, error)
// Profiles and bindings (instance operations).
ListProfiles(ctx context.Context, p authz.Proof) ([]PKIProfile, error)
GetProfile(ctx context.Context, p authz.Proof, name string) (PKIProfile, error)
CreateProfile(ctx context.Context, p authz.Proof, m PKIProfile) error
UpdateProfile(ctx context.Context, p authz.Proof, id, policy string, rowVersion int64, at time.Time) (bool, error)
DeleteProfile(ctx context.Context, p authz.Proof, id string) (bool, error)
ListBindings(ctx context.Context, p authz.Proof, profileID string) ([]PKIProfileBinding, error)
CreateBinding(ctx context.Context, p authz.Proof, m PKIProfileBinding) error
DeleteBinding(ctx context.Context, p authz.Proof, profileID, bindingID string) (bool, error)
// Certificates (environment operations).
BoundProfile(ctx context.Context, p authz.Proof, name string) (PKIProfile, error)
FenceIssuance(ctx context.Context, p authz.Proof, issuerID string) (bool, error)
CreateCertificate(ctx context.Context, p authz.Proof, m PKICertificateCreate) error
FinishCertificate(ctx context.Context, p authz.Proof, id string, der []byte, at time.Time) (bool, error)
FailCertificate(ctx context.Context, p authz.Proof, id string, at time.Time) (bool, error)
ClaimRenewal(ctx context.Context, p authz.Proof, id, successorID string, at time.Time) (bool, error)
CompleteRenewal(ctx context.Context, p authz.Proof, id, successorID string, at time.Time) (bool, error)
ReleaseRenewal(ctx context.Context, p authz.Proof, id, successorID string, at time.Time) (bool, error)
RevokeCertificate(ctx context.Context, p authz.Proof, id, reason string, at time.Time) (bool, error)
IssuerForSigning(ctx context.Context, p authz.Proof, id string) (PKIIssuer, []byte, uint32, error)
}
PKIRepo is the write side plus the reads.
type PKIRevokedEntry ¶
PKIRevokedEntry is one serial a CRL lists.
type PKIRuntime ¶
type PKIRuntime struct {
// contains filtered or unexported fields
}
PKIRuntime is the private-PKI worker's system boundary (#154, pki ADR D6-D8). Tenant request paths never receive it. Every write is a compare-and-swap on the row's current state (or, for a CRL, its prior CRL number), so the worker runs on every #146 node without a singleton scheduler lease: a node that lost a race affects zero rows. It is the DynamicRuntime shape without the claim columns, because no PKI transition calls an external system.
func NewPKIRuntime ¶
func NewPKIRuntime(db *DB) *PKIRuntime
func (*PKIRuntime) DueCRLs ¶
func (r *PKIRuntime) DueCRLs(ctx context.Context, now time.Time) ([]PKICRLCandidate, error)
DueCRLs lists issuer versions whose CRL must be (re)published. Restore-held versions cannot sign until revocations are reconciled and the hold released. Retired and revoked versions have no key and are never candidates. Sequence comparison is independent of clock skew and keeps revocations racing publication due.
func (*PKIRuntime) ExpireDue ¶
ExpireDue moves issued and renewed leaves past not_after to `expired`.
func (*PKIRuntime) Gauges ¶
Gauges is a proof-free scrape-time system read, like DynamicRuntime.Gauges.
func (*PKIRuntime) PublishCRL ¶
func (r *PKIRuntime) PublishCRL(ctx context.Context, candidate PKICRLCandidate, der []byte, number int64, entries int, thisUpdate, nextUpdate time.Time) (bool, error)
PublishCRL stores a freshly signed CRL under a CAS on the prior number and records the instance audit event in the same transaction. A lost race (another node published first) returns false and writes nothing.
func (*PKIRuntime) RevokedEntries ¶
func (r *PKIRuntime) RevokedEntries(ctx context.Context, issuerID string, now time.Time) ([]PKIRevokedEntry, error)
RevokedEntries is the worker's read of one issuer version's CRL entries.
func (*PKIRuntime) SignAndPublishCRL ¶
func (r *PKIRuntime) SignAndPublishCRL(ctx context.Context, candidate PKICRLCandidate, thisUpdate, nextUpdate time.Time, sign func(PKICRLCandidate, []PKIRevokedEntry) ([]byte, int64, error)) (bool, error)
SignAndPublishCRL holds runtime admission throughout one local signing act. Restore maintenance cannot cross the fresh hold check, key read, revocation snapshot, signing callback, and publication. The callback performs only local cryptography; no externally visible effect may precede the transaction commit.
func (*PKIRuntime) SweepStaleIssuing ¶
SweepStaleIssuing moves `issuing` rows whose deadline passed to `unknown`: the process died, or its outcome transaction failed, between reserving the serial and recording the signed leaf. Hikyo cannot prove the leaf never escaped, so the CRL publishes unknown serials as revoked (fail closed), and the audit trail records an `unknown` OUTCOME. A renewal's predecessor is released so it can be renewed again.
type PendingChange ¶
type PendingChange struct {
// ID is the immutable version id a publish names. Editing the cell mints a
// new one; this row is collected rather than mutated.
ID string
OrgID string
ProjectID string
EnvironmentID string
KeyID string
OwnerID string
Operation PendingOperation
// Ciphertext is nil exactly when Operation is PendingUnset.
Ciphertext []byte
// StagedFromRevision is the environment's published revision at staging
// time. Provenance a client shows, never a check.
StagedFromRevision int64
// StagedFromEntry is the published value-entry row id this cell held when
// the draft was staged, "" when the cell was absent. THIS is the freshness
// check: the rule is stated per entry, not per environment.
StagedFromEntry string
CreatedAt time.Time
Source PendingSource
// Secret is sticky occurrence metadata retained with the draft even after
// historical payload collection.
Secret bool
// MaterialSecret classifies the value being staged, independently from a
// secret current-side comparison that may only make the preview sensitive.
MaterialSecret bool
}
PendingChange is one immutable draft version owned by one principal.
type PendingMarker ¶
type PendingMarker struct {
ID string
EnvironmentID string
KeyID string
OwnerID string
Operation PendingOperation
}
PendingMarker is a pending change stripped of its material: what another principal may learn about a draft is write-presence, and this type is that rule in the type system rather than in a review comment.
type PendingOperation ¶
type PendingOperation string
PendingOperation is what a draft does to its cell. Two states, because presence is two states: `set` carries material, `unset` carries none.
const ( PendingSet PendingOperation = "set" PendingUnset PendingOperation = "unset" )
type PendingReader ¶
type PendingReader interface {
// ListForOwner returns one principal's whole working state in the proof's
// project, material included. There is deliberately no statement that
// returns another principal's material.
ListForOwner(ctx context.Context, p authz.Proof, ownerID string) ([]PendingChange, error)
// ListForOwnerInEnvironment is the pending-draft preview read. Owner and
// environment are both bound into its SQL predicate; no post-query filter
// is trusted with another principal's ciphertext.
ListForOwnerInEnvironment(ctx context.Context, p authz.Proof, ownerID string) ([]PendingChange, error)
// ListForOwnerInEnvironmentPage is the bounded keyset read (#629): one page
// of one owner's drafts in the proof's environment, ordered by the UNIQUE
// key_id column, strictly past afterKeyID ("" for the first page). Owner and
// environment are bound into the SQL predicate; no post-query filter is
// trusted with another principal's ciphertext.
ListForOwnerInEnvironmentPage(ctx context.Context, p authz.Proof, ownerID, afterKeyID string, limit int) ([]PendingChange, error)
// ListMarkers returns every principal's drafts in the proof's project,
// without material.
ListMarkers(ctx context.Context, p authz.Proof) ([]PendingMarker, error)
}
PendingReader is the read side of the draft model.
type PendingRepo ¶
type PendingRepo interface {
PendingReader
// Stage collects the owner's superseded version for the cell and writes the
// new one, in that order and in one transaction.
Stage(ctx context.Context, p authz.Proof, change NewPendingChange) error
// Discard removes one version by id from the proof's environment. It
// reports whether a row existed, so a publish can tell "published it" from
// "it was already gone".
Discard(ctx context.Context, p authz.Proof, id string) (bool, error)
// DiscardEnvironment removes the proof's environment's whole draft set, in
// the transaction that deletes the environment.
DiscardEnvironment(ctx context.Context, p authz.Proof) error
// DiscardKey removes every draft referencing one key across the proof's
// project, in the transaction that deletes the key.
DiscardKey(ctx context.Context, p authz.Proof, keyID string) (int64, error)
// CountForProjectExcludingCell counts the project's pending rows other than
// the (env, key, owner) cell about to be staged — under the stage proof,
// since the count is part of admitting a stage. Stage is delete-then-insert,
// so excluding the cell makes the count the size the project would have
// AROUND the new row: the caller refuses when it has reached the per-project
// pending cap.
CountForProjectExcludingCell(ctx context.Context, p authz.Proof, keyID, ownerID string) (int64, error)
// ListForReencrypt / Reencrypt are the reencrypt walk's page + in-place
// re-seal of pending-draft ciphertext (project-wide, keyset by id). Unset
// drafts (NULL ciphertext) are skipped by the query.
ListForReencrypt(ctx context.Context, p authz.Proof, cursor string, limit int) ([]ReencryptFieldRow, error)
Reencrypt(ctx context.Context, p authz.Proof, id string, newCiphertext, oldCiphertext []byte) (bool, error)
}
PendingRepo is the full draft aggregate.
type PendingSource ¶
type PendingSource string
const ( PendingSourceValues PendingSource = "values" PendingSourceRestore PendingSource = "restore" )
type PlanApplyStamp ¶
type PlanApplyStamp struct {
AppliedAt time.Time
AppliedBy string
Commit string
Ref string
Actor string
}
PlanApplyStamp is the one-shot apply record. Commit/Ref/Actor are the length-bounded, sanitized display-only provenance labels.
type PostgresTransaction ¶
type PostgresTransaction struct {
// contains filtered or unexported fields
}
PostgresTransaction exposes transactional statements, never a pooled/native connection that could outlive admission. Its shared control lock is owned by this same SQL transaction and is released only by commit or rollback.
func (*PostgresTransaction) Commit ¶
func (t *PostgresTransaction) Commit(ctx context.Context) error
func (*PostgresTransaction) Exec ¶
func (t *PostgresTransaction) Exec(ctx context.Context, q string, args ...any) (pgconn.CommandTag, error)
type PreparationDB ¶
type PreparationDB struct {
// contains filtered or unexported fields
}
PreparationDB has no runtime repository or driver accessor. Its only data output is the separately authenticated export/inspection protocol.
func OpenPreparation ¶
func OpenPreparation(ctx context.Context, cfg Config, authority upgrade.PreparationAdmission) (*PreparationDB, error)
func (*PreparationDB) Close ¶
func (p *PreparationDB) Close() error
func (*PreparationDB) ExportUpgrade ¶
func (p *PreparationDB) ExportUpgrade(ctx context.Context, w io.Writer, workDir string, request UpgradeExportRequest) (Manifest, error)
func (*PreparationDB) InspectUpgradeSource ¶
func (p *PreparationDB) InspectUpgradeSource(ctx context.Context, manifest releaseidentity.MigrationManifest) (upgrade.InstalledSource, error)
type PreparedPostgresPool ¶
type PreparedPostgresPool struct {
// contains filtered or unexported fields
}
PreparedPostgresPool owns a verified replacement until Activate transfers it to DB, or Close disposes it. It never changes connection credentials, source, schema selection, admission, keyring, or coordination identity.
func (*PreparedPostgresPool) Activate ¶
func (p *PreparedPostgresPool) Activate(ctx context.Context) error
Activate redirects subsequent acquisitions before returning success. Callers drain application work first. Existing coordination transactions may finish on the old pool; retirement waits for them without blocking new transactions. A candidate prepared against an earlier pool generation cannot overwrite a newer replacement. Cancellation or validation failure leaves current intact.
func (*PreparedPostgresPool) Close ¶
func (p *PreparedPostgresPool) Close() error
Close is idempotent. After activation the DB owns the pool and this handle cannot close it. Before activation all candidate connections are released.
type Project ¶
type Project struct {
ID string
OrgID string
Name string
CreatedAt time.Time
RetentionOverride *RetentionPolicy
// DefinitionsSource is `db` or `git` (#70). In `git` the definition-write
// chokepoint refuses every ordinary edit and only definitions apply writes.
DefinitionsSource string
// MachineReveal is the per-project machine-reveal opt-in (source-of-truth
// ADR). False (the default) means no machine principal may be granted
// `reveal` here and no machine fetch delivers secret plaintext, whatever
// grant rows exist.
MachineReveal bool
}
Project is a tenant-owned aggregate (chain: org). OrgID appears on reads only; writes bind it from the proof.
type ProjectCapacity ¶
ProjectCapacity is the persisted project key-limit policy, independent of the instance owner policy that the service resolves.
type ProjectName ¶
ProjectName is the directory listing's project row: the two fields the served listing may carry, and nothing more. A full Project would hand the caller an id and a creation time the directory has no licence to publish.
type ProjectPayloadBytes ¶
ProjectPayloadBytes is one project's stored ciphertext-byte total, from the instance-scoped storage sweep behind the high-water operator surface (#185).
type ProjectReader ¶
type ProjectReader interface {
// GetCapacity reads the project policy addressed by the resolved proof chain.
GetCapacity(ctx context.Context, p authz.Proof) (ProjectCapacity, error)
// Get returns the project addressed by the proof's resolved chain.
Get(ctx context.Context, p authz.Proof) (Project, error)
// List returns every project in the org the proof addresses.
List(ctx context.Context, p authz.Proof) ([]Project, error)
// ListAll returns (org id, name) for every project on the instance,
// under an instance-scope proof addressing no tenant. It exists for the
// multi-instance directory (#71), whose served listing is org/project
// names and counts across org boundaries by design. It is deliberately
// NOT List in a loop: N tenant proofs for one operation would misreport
// the operation in the boundary check.
ListAll(ctx context.Context, p authz.Proof) ([]ProjectName, error)
}
ProjectReader is the read side of the projects aggregate.
type ProjectRepo ¶
type ProjectRepo interface {
ProjectReader
// SetCapacity replaces the nullable override and advances its independent
// revision only if expectedRevision still matches.
SetCapacity(ctx context.Context, p authz.Proof, override *int, expectedRevision int64) error
Create(ctx context.Context, p authz.Proof, proj NewProject) error
Rename(ctx context.Context, p authz.Proof, name string) error
SetRetention(ctx context.Context, p authz.Proof, policy *RetentionPolicy) error
// SetDefinitionsSource writes the git/db definitions mode (#70). It is a
// project-settings write, off the definitions-edit path.
SetDefinitionsSource(ctx context.Context, p authz.Proof, source string) error
// SetMachineReveal writes the per-project machine-reveal opt-in. It is a
// project-settings write, off every machine-reachable path.
SetMachineReveal(ctx context.Context, p authz.Proof, enabled bool) error
Delete(ctx context.Context, p authz.Proof) error
// Lock takes the project row for the rest of the transaction, so every
// mutation of that project's environment SET serializes: the cap check and
// the append position are both read-then-write, and postgres would
// otherwise let two transactions at cap-1 both pass. ErrNotFound when the
// project is gone — the uniform outcome, as everywhere.
Lock(ctx context.Context, p authz.Proof) error
}
ProjectRepo is the full projects aggregate.
type ReadRepos ¶
type ReadRepos interface {
Access() AccessReader
SelfConfig() SelfConfigReader
Orgs() OrgReader
Keys() KeyReader
Catalogue() CatalogueReader
Values() ValueReader
Pending() PendingReader
Snapshots() SnapshotReader
Pins() RevisionPinReader
Retention() RetentionReader
BackupState() BackupStateReader
Projects() ProjectReader
Environments() EnvironmentReader
Folders() FolderReader
Audit() AuditReader
Remotes() RemoteReader
Adapters() AdapterReader
Dynamic() DynamicReader
SSH() SSHReader
// Transit is the managed-key metadata read side (#156).
Transit() TransitReader
PKI() PKIReader
Definitions() DefinitionsReader
DeliveryTargets() DeliveryTargetReader
FileTargets() FileTargetReader
}
ReadRepos bundles the read-only repositories bound to one read transaction. There is no proof-free read path: authorization is evaluated in-transaction, so reads run under internal/store/tx too.
type RecoveryDB ¶
type RecoveryDB struct {
// contains filtered or unexported fields
}
RecoveryDB exposes only the operator scratch transaction boundary. It has no runtime DB, driver, coordination, adapter or export accessor.
func OpenRecovery ¶
func OpenRecovery(ctx context.Context, cfg Config, authority upgrade.RecoveryAdmission) (*RecoveryDB, error)
func (*RecoveryDB) BeginPostgres ¶
func (r *RecoveryDB) BeginPostgres(ctx context.Context, options pgx.TxOptions) (*RecoveryPostgresTransaction, error)
func (*RecoveryDB) BeginSQLite ¶
func (r *RecoveryDB) BeginSQLite(ctx context.Context, readonly bool) (*RecoverySQLiteTransaction, error)
func (*RecoveryDB) CheckScratch ¶
func (r *RecoveryDB) CheckScratch(ctx context.Context) error
CheckScratch authorizes automatic drill behavior only on a currently guarded authenticated scratch restore, never on the operator's live data recovery.
func (*RecoveryDB) Close ¶
func (r *RecoveryDB) Close() error
func (*RecoveryDB) Engine ¶
func (r *RecoveryDB) Engine() Engine
func (*RecoveryDB) SourceMigrationVersion ¶
func (r *RecoveryDB) SourceMigrationVersion() (uint64, error)
SourceMigrationVersion is derived from the verified recovery plan, not from request flags or a best-effort live schema probe.
type RecoveryPostgresTransaction ¶
type RecoveryPostgresTransaction struct {
// contains filtered or unexported fields
}
func (*RecoveryPostgresTransaction) Commit ¶
func (t *RecoveryPostgresTransaction) Commit(ctx context.Context) error
func (*RecoveryPostgresTransaction) Exec ¶
func (t *RecoveryPostgresTransaction) Exec(ctx context.Context, q string, args ...any) (pgconn.CommandTag, error)
type RecoverySQLiteTransaction ¶
type RecoverySQLiteTransaction struct {
// contains filtered or unexported fields
}
Recovery transactions remain distinct from runtime transactions and refuse a commit after either piece of operator custody has expired.
func (*RecoverySQLiteTransaction) Commit ¶
func (t *RecoverySQLiteTransaction) Commit() error
func (*RecoverySQLiteTransaction) ExecContext ¶
func (*RecoverySQLiteTransaction) PrepareContext ¶
func (*RecoverySQLiteTransaction) QueryContext ¶
func (*RecoverySQLiteTransaction) QueryRowContext ¶
func (*RecoverySQLiteTransaction) Rollback ¶
func (t *RecoverySQLiteTransaction) Rollback() error
type ReencryptFieldRow ¶
type ReencryptFieldRow struct {
ID string
EnvironmentID string
KeyID string
SnapshotID string
Owner string
Ciphertext []byte
}
ReencryptFieldRow is one project_field row the reencrypt walk considers. SnapshotID is set for snapshot entries and empty for pending drafts, matching each table's AAD (the snapshot AAD binds it; the pending AAD does not). Owner is the AAD's owner_row_id where it differs from the primary key: an adapter route move is keyed by its own id but its credential AAD binds the ADAPTER's id, so Owner carries the adapter_id while ID (used for the CAS and cursor) stays the move's id. Empty Owner means "same as ID".
type ReencryptInstanceRow ¶
type ReencryptInstanceRow struct {
ID string
Ciphertext []byte
DEKVersion uint32
RowVersion uint32
}
ReencryptInstanceRow is one instance credential row the walk considers: its id (the AAD owner_row and CAS key), the sealed ciphertext, and, for versioned tables, the DEK version it is on and the row version to CAS against. DEKVersion is zero for remotes and must not be interpreted; that table's registry binding reads the authenticated ciphertext-header version instead.
type ReencryptRepo ¶
type ReencryptRepo interface {
ListPairingInvitesForReencrypt(ctx context.Context, p authz.Proof, cursor string, limit int) ([]ReencryptInstanceRow, error)
ReencryptPairingInvites(ctx context.Context, p authz.Proof, id string, newCiphertext, oldCiphertext []byte) (bool, error)
ListPairingExchangesForReencrypt(ctx context.Context, p authz.Proof, cursor string, limit int) ([]ReencryptInstanceRow, error)
ReencryptPairingExchanges(ctx context.Context, p authz.Proof, id string, newCiphertext, oldCiphertext []byte) (bool, error)
ListSelfConfigSeedInputsForReencrypt(ctx context.Context, p authz.Proof, cursor string, limit int) ([]ReencryptInstanceRow, error)
ReencryptSelfConfigSeedInput(ctx context.Context, p authz.Proof, id string, newCiphertext, oldCiphertext []byte, dekVersion, rowVersion uint32) (bool, error)
ListPasswordCredsForReencrypt(ctx context.Context, p authz.Proof, cursor string, limit int) ([]ReencryptInstanceRow, error)
ReencryptPasswordCred(ctx context.Context, p authz.Proof, id string, newCiphertext []byte, dekVersion, rowVersion uint32) (bool, error)
ListTotpCredsForReencrypt(ctx context.Context, p authz.Proof, cursor string, limit int) ([]ReencryptInstanceRow, error)
ReencryptTotpCred(ctx context.Context, p authz.Proof, id string, newCiphertext []byte, dekVersion, rowVersion uint32) (bool, error)
ListRecoveryCodesForReencrypt(ctx context.Context, p authz.Proof, cursor string, limit int) ([]ReencryptInstanceRow, error)
ReencryptRecoveryCodes(ctx context.Context, p authz.Proof, id string, newCiphertext []byte, dekVersion, rowVersion uint32) (bool, error)
ListOidcProvidersForReencrypt(ctx context.Context, p authz.Proof, cursor string, limit int) ([]ReencryptInstanceRow, error)
ReencryptOidcProvider(ctx context.Context, p authz.Proof, id string, newCiphertext []byte, dekVersion, rowVersion uint32) (bool, error)
ListOauth2ProvidersForReencrypt(ctx context.Context, p authz.Proof, cursor string, limit int) ([]ReencryptInstanceRow, error)
ReencryptOauth2Provider(ctx context.Context, p authz.Proof, id string, newCiphertext []byte, dekVersion, rowVersion uint32) (bool, error)
ListSamlKeysForReencrypt(ctx context.Context, p authz.Proof, cursor string, limit int) ([]ReencryptInstanceRow, error)
ReencryptSamlKey(ctx context.Context, p authz.Proof, id string, newCiphertext []byte, dekVersion, rowVersion uint32) (bool, error)
ListRemotesForReencrypt(ctx context.Context, p authz.Proof, cursor string, limit int) ([]ReencryptInstanceRow, error)
ReencryptRemote(ctx context.Context, p authz.Proof, id string, newCiphertext, oldCiphertext []byte) (bool, error)
ListPkiIssuersForReencrypt(ctx context.Context, p authz.Proof, cursor string, limit int) ([]ReencryptInstanceRow, error)
ReencryptPkiIssuer(ctx context.Context, p authz.Proof, id string, newCiphertext []byte, dekVersion, rowVersion uint32) (bool, error)
}
ReencryptRepo is the instance-credential reencrypt surface (#75/#187): the instance-DEK ciphertext columns the `reencrypt --instance` walk moves onto the active version. They live on one repo rather than spread across auth, factors, providers, saml, remotes and PKI issuers because they share one operation (OpReencryptInstance) and one walk shape. class=authn/instance: no tenant chain.
Versioned tables carry dek_version + row_version, so their re-seal is a compare-and-swap on row_version (the anti-resurrection guard) that also stamps the new dek_version. remotes has neither, so its re-seal CASes on the old blob. Temporary self-config inputs also guard the old blob against delete/reinsert.
type ReencryptValueRow ¶
ReencryptValueRow is one value row the reencrypt walk considers: its id, the AAD-reconstruction fields, and the current ciphertext (whose header names the DEK version it is sealed under).
type Remote ¶
type Remote struct {
ID string
Name string
URL string
// SPKIPin is base64(sha256(SubjectPublicKeyInfo)), verified on every
// connection before any request is written.
SPKIPin string
CreatedAt time.Time
CreatedBy domain.PrincipalID
}
Remote is one connection entry: this instance's named pointer at another one (#71, multi-instance ADR § The connection entry).
There is deliberately NO credential field. URL and pin are immutable and the sealed credential is write-only after storage, so the ordinary read cannot hand it out by accident — reaching it is the separate, greppable SealedCredential call, and that call exists so the fetch path can PRESENT the value, never so a surface can display it.
type RemoteReader ¶
type RemoteReader interface {
List(ctx context.Context, p authz.Proof) ([]Remote, error)
Get(ctx context.Context, p authz.Proof, id string) (Remote, error)
// GetByName is the CLI's addressing mode — `remote show <name>`,
// `remote remove <name>` — and the uniqueness the schema already enforces
// is what makes it single-valued.
GetByName(ctx context.Context, p authz.Proof, name string) (Remote, error)
// Count is the RemoteCount cap's input, read inside the same transaction
// as the insert it bounds.
Count(ctx context.Context, p authz.Proof) (int64, error)
Snapshots(ctx context.Context, p authz.Proof) ([]RemoteSnapshot, error)
Snapshot(ctx context.Context, p authz.Proof, remoteID string) (RemoteSnapshot, error)
// SealedCredential is the ONLY reader of the stored credential. It is a
// distinct method rather than a field on Remote so that reaching the
// credential is a greppable act, and it carries its own StoreOp so an
// operation licensed to LIST remotes is not thereby licensed to present
// one. It is on the READ side because the on-view fetch reads it in a read
// transaction — a network fan-out must not hold the write connection.
SealedCredential(ctx context.Context, p authz.Proof, id string) ([]byte, error)
}
RemoteReader is the read side of the remotes aggregate (viewing side). Every method takes an instance-scope proof: remotes address no tenant.
type RemoteRepo ¶
type RemoteRepo interface {
RemoteReader
Create(ctx context.Context, p authz.Proof, r NewRemote) error
// Rename touches the display name, the ADR's one mutable field. There is
// no Repoint: re-pointing a stored credential at a different host is the
// credential-redirect attack, so it is remove + add, which re-runs the
// full ceremony including the human fingerprint confirmation.
Rename(ctx context.Context, p authz.Proof, id, name string) error
Delete(ctx context.Context, p authz.Proof, id string) error
// WriteSnapshot records a SUCCESSFUL fetch, listing and all.
WriteSnapshot(ctx context.Context, p authz.Proof, s RemoteSnapshot) error
// RecordFetchFailure records the attempt and its outcome and PRESERVES the
// last known listing — that preservation is what makes "unreachable 2h,
// last known state shown" possible, and it is why failure is its own
// method rather than WriteSnapshot with empty fields.
RecordFetchFailure(ctx context.Context, p authz.Proof, remoteID string, at time.Time, outcome string) error
}
RemoteRepo is the full remotes aggregate.
type RemoteSnapshot ¶
type RemoteSnapshot struct {
RemoteID string
LastAttemptAt time.Time
LastOutcome string
// ObservedAt is the zero time until the first successful fetch. The
// listing fields are meaningful IFF it is non-zero — the table's CHECK
// makes the pairing total, so a zero-count "listing" cannot be stored.
ObservedAt time.Time
InstanceIdentity string
Version string
OrgCount int64
ProjectCount int64
// Listing is the org/project names as fetched, stored as JSON. It is
// foreign structure at rest and holds nothing value-bearing: the
// credential that produced it may read nothing else.
Listing json.RawMessage
}
RemoteSnapshot is one entry's last-known directory listing.
TWO CLOCKS, deliberately separate. LastAttemptAt/LastOutcome record the most recent FETCH; ObservedAt and the listing fields record the most recent SUCCESS. That split is the whole freshness model: an unreachable remote serves its last-known listing marked stale with its age, never silently as current, and a credential rejection is a distinct loud state because the operator's fix differs.
LastOutcome is a plain string here rather than remotefetch.Outcome: the store must not depend on the outbound client, and the column's own CHECK is what makes the enum total. A value outside it fails loud at the write.
type Repos ¶
type Repos interface {
SelfConfig() SelfConfigRepo
Orgs() OrgRepo
Keys() KeyRepo
Catalogue() CatalogueRepo
Values() ValueRepo
Pending() PendingRepo
Snapshots() SnapshotRepo
Pins() RevisionPinRepo
Retention() RetentionRepo
BackupState() BackupStateRepo
Projects() ProjectRepo
Environments() EnvironmentRepo
Folders() FolderRepo
Audit() AuditRepo
// SCIM is the provisioning surface (#73). It is on the WRITE bundle only:
// every SCIM read the product performs happens inside a transaction that
// also writes — the wire reads emit `scim.directory_read`, and the
// administration reads run beside their own lifecycle events — so a
// read-only twin would be a surface with no caller.
SCIM() SCIMRepo
// Remotes is the multi-instance directory's viewing side (#71).
Remotes() RemoteRepo
Adapters() AdapterRepo
// Dynamic is the dynamic-secret provider + lease surface (#147).
Dynamic() DynamicRepo
// SSH is the SSH user-certificate surface (#155).
SSH() SSHRepo
// PKI is the private-PKI issuer, profile and certificate surface (#154).
PKI() PKIRepo
// Definitions is the plan ledger behind definitions plan/apply (#70).
Definitions() DefinitionsRepo
// ScanningDismissals is the secret-scanning "keep as config" dismissal
// surface (#74). It is on the WRITE bundle only: the sticky-match lookup
// (Exists) runs inside the same value-write transaction that may record a
// dismissal, so a read-only twin would have no caller — the shape SCIM took
// for the same reason.
ScanningDismissals() ScanningDismissalRepo
// Reencrypt is the instance-credential reencrypt surface (#75/#187).
Reencrypt() ReencryptRepo
// Approvals is the policy-bound secret-change approval engine (#151). It is
// on the WRITE bundle only: the coverage lookup that admits a publish runs
// inside the publish transaction, and every read runs beside its own
// lifecycle event, so a read-only twin would have no caller.
Approvals() ApprovalRepo
// Access is the approval-mediated temporary access engine (#152): policies,
// requests and votes. The time-bound grant rows it writes live on the
// resolution surface, not here. Operational counts also have a read-only surface.
Access() AccessRepo
// DeliveryTargets is the delivery-target condition-report surface (#788).
DeliveryTargets() DeliveryTargetRepo
// Transit is the managed-key surface (#156, transit ADR).
Transit() TransitRepo
// FileTargets is the generic file-destination surface (#164).
FileTargets() FileTargetRepo
}
Repos bundles the full repositories bound to one write transaction.
Keys() is the KEYRING (#43, wrapped crypto material); Catalogue() is the KEY CATALOGUE (#49, the project's schema). The two are unrelated senses of the word and the accessors keep them apart, so no caller can reach one meaning to while holding the other.
type RestoreDestination ¶
type RestoreDestination struct {
// contains filtered or unexported fields
}
RestoreDestination cannot serve repositories or expose a runtime database. Its only mutation imports the exact authenticated archive after the importer locks and checks every destination table in the same transaction as COPY.
func OpenRestoreDestination ¶
func OpenRestoreDestination(ctx context.Context, cfg Config, authority upgrade.RestoreDestinationAdmission, archive *backupreceipt.AuthenticatedArchive, plan upgradecompat.Plan) (*RestoreDestination, error)
func (*RestoreDestination) Close ¶
func (d *RestoreDestination) Close() error
type RetentionConsequence ¶
type RetentionConsequence string
RetentionConsequence is transaction-time truth about a released pin's snapshot. A later sweep may move collection_eligible to already_collected.
const ( RetentionRetained RetentionConsequence = "retained" RetentionCollectionEligible RetentionConsequence = "collection_eligible" RetentionAlreadyCollected RetentionConsequence = "already_collected" )
type RetentionPolicy ¶
RetentionPolicy is the stored keep-if-either payload policy. Unlimited is valid only on an organization row; project overrides are always bounded.
type RetentionReader ¶
type RetentionReader interface {
LastPruneSuccess(ctx context.Context, p authz.Proof) (time.Time, bool, error)
Diagnostics(ctx context.Context, p authz.Proof, now time.Time) (OpsMetadata, error)
}
RetentionReader exposes persisted scheduler health.
type RetentionRepo ¶
type RetentionRepo interface {
RetentionReader
AuditPolicy(ctx context.Context, p authz.Proof) (AuditRetentionPolicy, error)
SetAuditPolicy(ctx context.Context, p authz.Proof, policy AuditRetentionPolicy) error
PruneAudit(ctx context.Context, p authz.Proof, accessCutoff, securityCutoff time.Time) ([]AuditPrunedRow, error)
LockSnapshot(ctx context.Context, p authz.Proof, snapshotID string) error
Eligible(ctx context.Context, p authz.Proof, now time.Time, limit int) ([]GCEligibleSnapshot, error)
MarkCollected(ctx context.Context, p authz.Proof, snapshotID, policy string, now time.Time) (bool, error)
DeleteCollectedEntries(ctx context.Context, p authz.Proof, snapshotID string) (int64, error)
SetLastPruneSuccess(ctx context.Context, p authz.Proof, at time.Time) error
RecordEscrow(ctx context.Context, p authz.Proof, record EscrowRecord) error
RecordReencryptSuccess(ctx context.Context, p authz.Proof, at time.Time) error
}
RetentionRepo owns scheduler GC plus the snapshot lock that makes the pin-release decision transaction-time truth.
type RevisionChange ¶
type RevisionChange string
RevisionChange is one lineage row: which key changed how, in which revision. It never holds a value, and that is what makes payload collection real.
const ( RevisionChangeAdded RevisionChange = "added" RevisionChangeEdited RevisionChange = "edited" RevisionChangeRemoved RevisionChange = "removed" )
type RevisionKeyChange ¶
type RevisionKeyChange struct {
EnvironmentID string
Revision int64
KeyID string
KeyName string
Change RevisionChange
}
RevisionKeyChange is one lineage row.
type RevisionPin ¶
type RevisionPin struct {
ID string
OrgID string
ProjectID string
EnvironmentID string
WorkloadPrincipalID string
SnapshotID string
Revision int64
AuthorityPrincipalID string
ExpiresAt time.Time
CreatedAt time.Time
AuthorizedAt time.Time
HistoryAuthorized bool
SchemaOverride bool
}
RevisionPin is one durable delivery route and retention reference.
type RevisionPinReader ¶
type RevisionPinRepo ¶
type RevisionPinRepo interface {
RevisionPinReader
CountProject(ctx context.Context, p authz.Proof) (int64, error)
Insert(ctx context.Context, p authz.Proof, pin NewRevisionPin) error
Delete(ctx context.Context, p authz.Proof, workloadPrincipalID string) (bool, error)
DeleteEnvironment(ctx context.Context, p authz.Proof) error
}
type SCIMAttentionRow ¶
type SCIMAttentionRow struct {
ID string
BindingID string
State string
SubjectRef string
Cause string
EnteredAt time.Time
}
SCIMAttentionRow is one stored attention state (ADR §9). Stored, not derived: each state is audited on entry AND exit, and a state computed at read time cannot emit a transition.
type SCIMBinding ¶
type SCIMBinding struct {
ID string
OrgID string
ProviderKind string
// ProviderID is the provider's immutable ROW id. The slug beside it is a
// mutable address kept for rendering; liveness, the audit trail's
// `provider_ref` and the identity link's recorded provider all resolve by
// THIS, so a provider deleted and recreated under the same slug is a
// different provider — which it is.
ProviderID string
ProviderSlug string
ProviderIssuer string
SubjectSource string
NameIDFormat string
NameIDQualifier string
NameIDQualifierPresent bool
NameIDSPQualifier string
NameIDSPQualifierPresent bool
ConnectionPrincipalID string
LastContactAt time.Time
CreatedAt time.Time
}
SCIMBinding is one stored binding (ADR §1).
type SCIMCredential ¶
type SCIMCredential struct {
ID string
BindingID string
PrincipalID string
// CredentialEpoch is the instance epoch this credential was minted under.
// A row whose epoch is behind the instance's is a credential a RESTORE
// brought back: permanently dead by presentation (§9.1), and the only
// observable trace of the restore this tree has.
CredentialEpoch int64
CreatedAt time.Time
ExpiresAt time.Time
RevokedAt time.Time
LastUsedAt time.Time
}
SCIMCredential is one provisioning credential as the ADMINISTRATION surface sees it. Token material is absent because it was never stored.
type SCIMFilterField ¶
type SCIMFilterField string
SCIMFilterField selects one supported equality predicate.
const ( SCIMFilterAll SCIMFilterField = "" SCIMFilterUserName SCIMFilterField = "user_name" SCIMFilterDisplayName SCIMFilterField = "display_name" SCIMFilterExternalID SCIMFilterField = "external_id" )
type SCIMGroup ¶
type SCIMGroup struct {
ID string
OrgID string
BindingID string
DisplayName string
DisplayNameLower string
ExternalID string
CreatedAt time.Time
UpdatedAt time.Time
}
SCIMGroup is one provisioned group (ADR §6).
type SCIMGroupMember ¶
type SCIMGroupMember struct {
ID string
BindingID string
GroupID string
UserID string
CreatedAt time.Time
}
SCIMGroupMember is one member reference.
type SCIMGroupUpdate ¶
type SCIMGroupUpdate struct {
ID string
BindingID string
DisplayName string
DisplayNameLower string
ExternalID string
UpdatedAt time.Time
}
SCIMGroupUpdate is the mutable half of a group resource.
type SCIMListFilter ¶
type SCIMListFilter struct {
Field SCIMFilterField
Value string
}
SCIMListFilter carries a normalized value; external IDs remain case-sensitive.
type SCIMMapping ¶
type SCIMMapping struct {
ID string
OrgID string
BindingID string
GroupID string
Template string
ScopeProjectID string
ScopeEnvID string
Inert bool
CreatedAt time.Time
}
SCIMMapping is one `(IdP group -> role template @ scope)` row (ADR §3).
type SCIMReader ¶
type SCIMReader interface {
Binding(ctx context.Context, p authz.Proof, id string) (SCIMBinding, error)
Bindings(ctx context.Context, p authz.Proof) ([]SCIMBinding, error)
Mapping(ctx context.Context, p authz.Proof, id string) (SCIMMapping, error)
Mappings(ctx context.Context, p authz.Proof, bindingID string) ([]SCIMMapping, error)
MappingsForGroup(ctx context.Context, p authz.Proof, bindingID, groupID string) ([]SCIMMapping, error)
User(ctx context.Context, p authz.Proof, bindingID, id string) (SCIMUser, error)
UserByUserName(ctx context.Context, p authz.Proof, bindingID, folded string) (SCIMUser, error)
UserBySubject(ctx context.Context, p authz.Proof, bindingID, subject string) (SCIMUser, error)
UserByAccount(ctx context.Context, p authz.Proof, bindingID, accountID string) (SCIMUser, error)
Users(ctx context.Context, p authz.Proof, bindingID string) ([]SCIMUser, error)
// PageUsers and PageGroups are the WIRE's reads: bounded in SQL, with a
// separate count, so resource materialization stays bounded independently
// of directory size (the count itself can still scan matching index entries).
PageUsers(ctx context.Context, p authz.Proof, bindingID string, filter SCIMListFilter, limit, offset int64) ([]SCIMUser, int64, error)
Group(ctx context.Context, p authz.Proof, bindingID, id string) (SCIMGroup, error)
Groups(ctx context.Context, p authz.Proof, bindingID string) ([]SCIMGroup, error)
PageGroups(ctx context.Context, p authz.Proof, bindingID string, filter SCIMListFilter, limit, offset int64) ([]SCIMGroup, int64, error)
// Every membership method carries the bindingID. Without it an org-scoped
// proof for one binding could address group and user ids belonging to
// another binding in the same org: the proof binds the ORG, and the org is
// not the tenancy here — the binding is.
GroupMembers(ctx context.Context, p authz.Proof, bindingID, groupID string) ([]SCIMGroupMember, error)
MembershipsForUser(ctx context.Context, p authz.Proof, bindingID, userID string) ([]SCIMGroupMember, error)
Attention(ctx context.Context, p authz.Proof, bindingID string) ([]SCIMAttentionRow, error)
}
SCIMReader is the read half of the SCIM surface.
type SCIMRepo ¶
type SCIMRepo interface {
SCIMReader
// Credential administration. It lives HERE and not on the proof-free
// resolver — where only the pre-auth verifier lookup belongs — because
// every one of these runs after `manage-members(org)` is proved, and the
// org predicate must come from that proof rather than from a Go check
// beside a caller-controlled id.
CreateCredential(ctx context.Context, p authz.Proof, c NewSCIMCredential) error
Credential(ctx context.Context, p authz.Proof, bindingID, id string) (SCIMCredential, error)
Credentials(ctx context.Context, p authz.Proof, bindingID string) ([]SCIMCredential, error)
RevokeCredential(ctx context.Context, p authz.Proof, bindingID, id string, at time.Time) (bool, error)
RevokeCredentialsForBinding(ctx context.Context, p authz.Proof, bindingID string, at time.Time) (int64, error)
DeleteCredentialsForBinding(ctx context.Context, p authz.Proof, bindingID string) error
// LockBinding is the FIRST statement of every mutation on a binding's
// subtree (ADR §9: per-binding writes serialize). It is a no-op CAS write,
// not a read — a SELECT takes no row lock — following this repo's own
// GuardProviderForMint precedent.
LockBinding(ctx context.Context, p authz.Proof, id string) error
CreateBinding(ctx context.Context, p authz.Proof, b NewSCIMBinding) error
TouchBinding(ctx context.Context, p authz.Proof, id string, at time.Time) error
DeleteBinding(ctx context.Context, p authz.Proof, id string) error
// RetireConnectionPrincipal removes an ORPHANED provisioning connection
// under a proof; a connection any binding still owns is unmatched.
RetireConnectionPrincipal(ctx context.Context, p authz.Proof, principal domain.PrincipalID) (bool, error)
CreateMapping(ctx context.Context, p authz.Proof, m NewSCIMMapping) error
SetMappingInert(ctx context.Context, p authz.Proof, bindingID, groupID string, inert bool) (int64, error)
UpdateMappingTemplate(ctx context.Context, p authz.Proof, id, template string) error
DeleteMapping(ctx context.Context, p authz.Proof, id string) error
DeleteMappingsForBinding(ctx context.Context, p authz.Proof, bindingID string) error
CreateUser(ctx context.Context, p authz.Proof, u NewSCIMUser) error
UpdateUser(ctx context.Context, p authz.Proof, u SCIMUserUpdate) error
DeleteUser(ctx context.Context, p authz.Proof, bindingID, id string) error
DeleteUsersForBinding(ctx context.Context, p authz.Proof, bindingID string) error
CreateGroup(ctx context.Context, p authz.Proof, g NewSCIMGroup) error
UpdateGroup(ctx context.Context, p authz.Proof, g SCIMGroupUpdate) error
DeleteGroup(ctx context.Context, p authz.Proof, bindingID, id string) error
DeleteGroupsForBinding(ctx context.Context, p authz.Proof, bindingID string) error
AddGroupMember(ctx context.Context, p authz.Proof, m SCIMGroupMember) error
RemoveGroupMember(ctx context.Context, p authz.Proof, bindingID, groupID, userID string) error
ClearGroupMembers(ctx context.Context, p authz.Proof, bindingID, groupID string) error
RemoveMembershipsForUser(ctx context.Context, p authz.Proof, bindingID, userID string) error
DeleteGroupMembersForBinding(ctx context.Context, p authz.Proof, bindingID string) error
EnterAttention(ctx context.Context, p authz.Proof, a SCIMAttentionRow) (bool, error)
ClearAttention(ctx context.Context, p authz.Proof, bindingID, state, subjectRef string) (int64, error)
DeleteAttentionForBinding(ctx context.Context, p authz.Proof, bindingID string) error
}
SCIMRepo is the full SCIM surface bound to one write transaction.
type SCIMUser ¶
type SCIMUser struct {
ID string
OrgID string
BindingID string
AccountID string
UserName string
UserNameLower string
ExternalID string
Subject string
Active bool
Attributes string
CreatedAt time.Time
UpdatedAt time.Time
}
SCIMUser is one provisioned directory entry (ADR §5).
type SCIMUserUpdate ¶
type SCIMUserUpdate struct {
ID string
BindingID string
UserName string
UserNameLower string
ExternalID string
Active bool
Attributes string
UpdatedAt time.Time
}
SCIMUserUpdate is the mutable half of a user resource. `Subject` is absent on purpose: it is write-once per resource (ADR §5.1), so there is no statement here that could change it.
type SQLiteTransaction ¶
type SQLiteTransaction struct {
// contains filtered or unexported fields
}
SQLiteTransaction retains host reader/writer exclusion until SQL settles. The native transaction cannot escape through a raw handle getter.
func (*SQLiteTransaction) Commit ¶
func (t *SQLiteTransaction) Commit() error
func (*SQLiteTransaction) ExecContext ¶
func (*SQLiteTransaction) PrepareContext ¶
func (*SQLiteTransaction) QueryContext ¶
func (*SQLiteTransaction) QueryRowContext ¶
func (*SQLiteTransaction) Rollback ¶
func (t *SQLiteTransaction) Rollback() error
type SSHActiveKey ¶
SSHActiveKey is what signing needs: the active key's identity and its sealed private material.
type SSHCA ¶
type SSHCA struct {
ID string
Name string
State string
AuthorityPrincipalID string
CreatedAt string
Keys []SSHCAKey
}
SSHCA is a CA and its keys, newest first.
type SSHCACreate ¶
SSHCACreate is a new CA row.
type SSHCAKey ¶
type SSHCAKey struct {
ID string
CAID string
Algorithm string
PublicKey string
Fingerprint string
Origin string
State string
CreatedAt string
RetiringAt string
RetireAfter string
RetiredAt string
}
SSHCAKey is one CA signing key's public record. There is no private field: the sealed key is reachable only through ActiveCAKeyCiphertext.
type SSHCAKeyCreate ¶
type SSHCAKeyCreate struct {
ID string
CAID string
Algorithm string
PublicKey string
Fingerprint string
Origin string
Ciphertext []byte
At time.Time
}
SSHCAKeyCreate is a new active key. Ciphertext is already sealed.
type SSHCertificate ¶
type SSHCertificate struct {
ID string
CAID string
CAKeyID string
ProfileID string
Serial int64
KeyID string
Principals []string
PublicKeyFingerprint string
KeyAlgorithm string
KeyOrigin string
ValidAfter string
ValidBefore string
RequesterPrincipalID string
RequesterClass string
State string
RevokedAt string
RevocationReason string
CreatedAt string
CAKeyState string
CAKeyRetireAfter string
CAState string
}
SSHCertificate is an issued certificate's public record, joined with the signing key's and CA's current state so reads can derive trust and KRL membership without a second query.
type SSHCertificateCreate ¶
type SSHCertificateCreate struct {
ID string
CAID string
CAKeyID string
ProfileID string
Serial int64
KeyID string
Principals []string
PublicKeyFingerprint string
KeyAlgorithm string
KeyOrigin string
ValidAfter time.Time
ValidBefore time.Time
RequesterPrincipalID string
RequesterClass string
At time.Time
}
SSHCertificateCreate is one issuance's durable record.
type SSHProfile ¶
type SSHProfile struct {
ID string
CAID string
Name string
Principals []string
ForceCommand string
SourceAddresses []string
Extensions []string
KeyAlgorithms []string
DefaultTTLSeconds int64
MaxTTLSeconds int64
State string
Requesters []string
CreatedAt string
UpdatedAt string
}
SSHProfile is a profile's full policy, requesters included.
type SSHProfileWrite ¶
type SSHProfileWrite struct {
ID string
CAID string
Name string
Principals []string
ForceCommand string
SourceAddresses []string
Extensions []string
KeyAlgorithms []string
DefaultTTLSeconds int64
MaxTTLSeconds int64
Enabled bool
Requesters []string
At time.Time
}
SSHProfileWrite creates or replaces a profile (requesters included).
type SSHReader ¶
type SSHReader interface {
GetCA(ctx context.Context, p authz.Proof, caID string) (SSHCA, error)
ListCAs(ctx context.Context, p authz.Proof) ([]SSHCA, error)
GetProfile(ctx context.Context, p authz.Proof, profileID string) (SSHProfile, error)
ListProfiles(ctx context.Context, p authz.Proof) ([]SSHProfile, error)
GetCertificate(ctx context.Context, p authz.Proof, certID string) (SSHCertificate, error)
ListCertificates(ctx context.Context, p authz.Proof, limit int) ([]SSHCertificate, error)
RevokedSerials(ctx context.Context, p authz.Proof, caID string, now time.Time, limit int) ([]SSHRevokedSerial, error)
ListCAKeysForReencrypt(ctx context.Context, p authz.Proof, cursor string, limit int) ([]ReencryptFieldRow, error)
}
SSHReader is the read side.
type SSHRepo ¶
type SSHRepo interface {
SSHReader
CreateCA(ctx context.Context, p authz.Proof, m SSHCACreate) error
InsertCAKey(ctx context.Context, p authz.Proof, m SSHCAKeyCreate) error
ActiveCAKey(ctx context.Context, p authz.Proof, caID string) (SSHActiveKey, error)
RetireActiveCAKey(ctx context.Context, p authz.Proof, caID string, retireAfter, at time.Time) (string, error)
RetireCAKey(ctx context.Context, p authz.Proof, caID, keyID string, at time.Time) error
DeleteCA(ctx context.Context, p authz.Proof, caID string, at time.Time) error
CountLiveProfilesForCA(ctx context.Context, p authz.Proof, caID string) (int, error)
ActiveKeyLastExpiry(ctx context.Context, p authz.Proof, caID string, now time.Time) (*time.Time, error)
CreateProfile(ctx context.Context, p authz.Proof, m SSHProfileWrite) error
UpdateProfile(ctx context.Context, p authz.Proof, m SSHProfileWrite) error
DeleteProfile(ctx context.Context, p authz.Proof, profileID string, at time.Time) error
IsRequester(ctx context.Context, p authz.Proof, profileID, principalID string) (bool, error)
InsertCertificate(ctx context.Context, p authz.Proof, m SSHCertificateCreate) error
RevokeCertificate(ctx context.Context, p authz.Proof, certID, reason string, at time.Time) (bool, error)
RevokeProfileCertificates(ctx context.Context, p authz.Proof, profileID, reason string, keepRequesters []string, all bool, at time.Time) ([]SSHRevokedCertificate, error)
ReencryptCAKey(ctx context.Context, p authz.Proof, id string, newCiphertext, oldCiphertext []byte) (bool, error)
PurgeEnvironment(ctx context.Context, p authz.Proof) error
}
SSHRepo is the write side plus the reads.
type SSHRevokedCertificate ¶
SSHRevokedCertificate names a certificate a bulk revocation changed, for the caller's per-certificate audit rows.
type SSHRevokedSerial ¶
SSHRevokedSerial is one KRL entry: the signing key and the serial.
type SSHRuntime ¶
type SSHRuntime struct {
// contains filtered or unexported fields
}
SSHRuntime is the SSH certificate sweeper's system boundary (#155). Tenant request paths never receive it. The sweeper re-authorizes each live certificate's recorded requester through the ordinary authorizer and, on a definite refusal, revokes the certificate here. The only write is idempotent (`state='issued'` guards it), so every node in a #146 cluster can sweep concurrently without a claim fence: two nodes revoking the same row affect it once, and the second writes no audit row.
func NewSSHRuntime ¶
func NewSSHRuntime(db *DB) *SSHRuntime
func (*SSHRuntime) Gauges ¶
func (r *SSHRuntime) Gauges(ctx context.Context, now time.Time) (active, krlEntries int64, err error)
Gauges returns the instance-wide SSH counts for /metrics: live (issued, unexpired) certificates and published KRL entries (revoked, unexpired, signed by a key hosts still trust).
func (*SSHRuntime) ListLiveCertificates ¶
func (r *SSHRuntime) ListLiveCertificates(ctx context.Context, now time.Time, afterID string, limit int) ([]SSHSweepCandidate, error)
ListLiveCertificates pages through issued, unexpired certificates by id.
func (*SSHRuntime) RevokeForAuthority ¶
func (r *SSHRuntime) RevokeForAuthority(ctx context.Context, c SSHSweepCandidate, at time.Time) (bool, error)
RevokeForAuthority revokes one certificate whose requester no longer holds issuing authority, with its system-actor audit row, in one transaction. It reports whether this call changed the row.
type SSHSweepCandidate ¶
type SSHSweepCandidate struct {
ID string
OrgID string
ProjectID string
EnvironmentID string
ProfileID string
Serial int64
RequesterPrincipalID string
RequesterClass string
// RequesterListed is whether the requester is still on the profile's
// requester list (false when the profile was deleted).
RequesterListed bool
}
SSHSweepCandidate is one live certificate and the facts the sweeper needs to re-decide its requester's authority.
type ScanningDismissalRepo ¶
type ScanningDismissalRepo interface {
// Insert records one "keep as config" acknowledgement. A second insert of
// the identical (org, project, env, key, rule digest, fingerprint) tuple
// hits the UNIQUE constraint and surfaces as ErrConflict — the dismissal is
// already sticky.
Insert(ctx context.Context, p authz.Proof, d NewDismissal) error
// Exists is the sticky-match lookup that suppresses a re-warn on a value
// already accepted for this (key, rule digest, fingerprint) in the proof's
// environment.
Exists(ctx context.Context, p authz.Proof, keyID, ruleDigest string, fingerprint []byte) (bool, error)
// DeleteByKey drops one key's dismissals across every environment
// (reclassification-to-secret and key deletion; ADR section 4 lifecycle).
DeleteByKey(ctx context.Context, p authz.Proof, keyID string) (int64, error)
// DeleteByProject drops a project's dismissals (project deletion; ADR
// section 4 lifecycle).
DeleteByProject(ctx context.Context, p authz.Proof) (int64, error)
// DeleteAll drops every dismissal instance-wide for scanning-key rotation:
// old fingerprints become unrecomputable and must die.
DeleteAll(ctx context.Context, p authz.Proof) (int64, error)
}
ScanningDismissalRepo is the proof-bound dismissal-row surface (#74, secret-scanning ADR section 4). Every method is authorized against its own registered store operation and binds its chain from the proof.
type SelfConfigBinding ¶
type SelfConfigBinding struct {
AdoptionKey, AdoptedBy string
// SeedFingerprint is a keyed, transient adoption attestation; not a second config store.
SeedFingerprint string
SeedNodes []SelfConfigSeedReference
// HostSeedDiscovery preserves closed-host discovery semantics until the final membership-locked check; never persisted.
HostSeedDiscovery bool
OwnerInstanceID, OrgID, ProjectID, EnvironmentID string
SchemaVersion, Generation, DesiredRevision int64
DesiredSnapshotID, PreviousSnapshotID, Incarnation string
Suspended bool
CreatedAt, UpdatedAt time.Time
}
SelfConfigBinding owns one logical instance's runtime configuration. Values live only in ordinary project-encrypted snapshot entries.
type SelfConfigGeneration ¶
type SelfConfigGeneration struct {
TopologyStamp string
OwnerInstanceID, Incarnation string
Generation int64
Topology *domain.SingletonTopologyChange
TopologyRestoring bool
Suspended, Managed, DeploymentRestoring bool
}
SelfConfigGeneration is nonsecret runtime admission metadata. Consumers can fence stale bundles without minting a runtime payload proof on an HTTP stack.
type SelfConfigJob ¶
type SelfConfigJob struct {
ConfirmRestoredCredentials bool
// LocalNodeID is used only when no HA registry exists; it is not persisted as request identity.
LocalNodeID string
ID, IdempotencyKey, PrincipalID, SnapshotID string
Revision, SchemaVersion, ExpectedGeneration, Generation int64
Status, ErrorCode string
CreatedAt, UpdatedAt time.Time
}
type SelfConfigNode ¶
type SelfConfigReader ¶
type SelfConfigReader interface {
PreviousRevision(context.Context, authz.Proof) (int64, error)
Rollout(context.Context, authz.Proof, string) (SelfConfigRollout, error)
SeedInputs(context.Context, authz.Proof, string, time.Time) ([]SelfConfigSeedInput, error)
HostSeedInputs(context.Context, authz.Proof, time.Time) ([]SelfConfigSeedInput, error)
Binding(context.Context, authz.Proof) (SelfConfigBinding, error)
Jobs(context.Context, authz.Proof) ([]SelfConfigJob, error)
Job(context.Context, authz.Proof, string) (SelfConfigJob, error)
JobByIdempotencyKey(context.Context, authz.Proof, string) (SelfConfigJob, error)
Nodes(context.Context, authz.Proof) ([]SelfConfigNode, error)
Retained(context.Context, authz.Proof) ([]string, error)
}
type SelfConfigRepo ¶
type SelfConfigRepo interface {
NextRolloutSequence(context.Context, authz.Proof, string) (int64, error)
PutRollout(context.Context, authz.Proof, SelfConfigRollout) error
PutSeedInput(context.Context, authz.Proof, SelfConfigSeedInput) error
RecoverTarget(context.Context, authz.Proof, int64, int64, string, time.Time) (SelfConfigBinding, error)
SelfConfigReader
CreateBinding(context.Context, authz.Proof, SelfConfigBinding) error
BeginJob(context.Context, authz.Proof, SelfConfigJob) (SelfConfigJob, error)
CommitJob(context.Context, authz.Proof, string, time.Time) (SelfConfigBinding, error)
FinishJob(context.Context, authz.Proof, string, string, string, time.Time) error
PutNode(context.Context, authz.Proof, SelfConfigNode) error
FenceRestored(context.Context, authz.Proof, string, time.Time) error
}
type SelfConfigRollout ¶
type SelfConfigRollout struct {
JobID, EnrollmentID, Incarnation, PlanDigest string
CommandJSON, ResponseJSON, ExternalPhase string
Sequence, RowVersion int64
}
SelfConfigRollout holds only source-alias commands and secret-free receipts. Project values, database locators and key bytes are never valid contents.
type SelfConfigSeedInput ¶
type SelfConfigSeedInput struct {
NodeID, OwnerInstanceID, Incarnation, Fingerprint, OwnerFingerprint string
Ciphertext []byte
DEKVersion, RowVersion, SchemaVersion int64
UpdatedAt time.Time
}
SelfConfigSeedInput exists only before adoption. Ciphertext is instance-DEK sealed with the node ID as AAD; plaintext is never stored on this surface.
type SelfConfigSeedReference ¶
type SelfConfigSeedReference struct {
NodeID, Fingerprint string
}
SelfConfigSeedReference binds the exact node inputs reviewed for adoption. References are transient and are checked under the membership lock.
type Snapshot ¶
type Snapshot struct {
ID string
OrgID string
ProjectID string
EnvironmentID string
Revision int64
SchemaRevision int64
PublishedBy string
PublishedAt time.Time
// Collected is nil while the snapshot payload is live. Collection time and
// policy travel together so callers cannot observe or construct only one
// part of the durable collection state.
Collected *SnapshotCollection
}
Snapshot is the immutable per-(project, environment) materialization's header. It carries the pinned schema revision; it deliberately carries no change token, which is derived from the current root token key at read.
func (Snapshot) CollectionPolicy ¶
CollectionPolicy reports the stamped policy only for a collected payload.
func (Snapshot) PayloadPresent ¶
PayloadPresent reports whether retention has not collected the payload.
type SnapshotCollection ¶
SnapshotCollection is the indivisible marker stamped when retention removes a snapshot's payload.
type SnapshotEntry ¶
type SnapshotEntry struct {
ID string
OrgID string
ProjectID string
EnvironmentID string
SnapshotID string
KeyID string
KeyName string
Classification string
Ciphertext []byte
// ValueEntryID is the pinned value-entry revision this entry materialized
// from. Metadata, not a reference -- the cell is delete-then-insert, and
// the snapshot must keep answering after the cell moves on.
ValueEntryID string
}
SnapshotEntry is one delivered key of one snapshot. Name and classification are the snapshot's own copies: the delivered key set is a property of the pinned schema revision, not of the live catalogue.
type SnapshotReader ¶
type SnapshotReader interface {
ParameterContract(ctx context.Context, p authz.Proof, snapshot Snapshot) (string, error)
// Latest returns the proof's environment's newest snapshot, or ErrNotFound
// when the environment has never been materialized.
Latest(ctx context.Context, p authz.Proof) (Snapshot, error)
// AtRevision returns one named revision, or ErrNotFound.
AtRevision(ctx context.Context, p authz.Proof, revision int64) (Snapshot, error)
// List returns the environment's revision headers, newest first: the pin
// retention-consequence read, which ranks one snapshot against every
// sibling. History surfaces never use it; they page through ListPage.
List(ctx context.Context, p authz.Proof) ([]Snapshot, error)
// ListPage is the bounded keyset read behind revision history (#629): one
// page of revision headers ordered by the UNIQUE revision column
// descending, strictly below beforeRevision (a sentinel above the newest
// for the first page), fetching at most limit rows.
ListPage(ctx context.Context, p authz.Proof, beforeRevision int64, limit int) ([]Snapshot, error)
// Entries returns one snapshot's resolved map, ordered by key name.
Entries(ctx context.Context, p authz.Proof, snapshot Snapshot) ([]SnapshotEntry, error)
// SecretValueOccurrenceIDsIn reports which of the named value entries
// carry the payload-free sticky sensitivity lineage in this environment.
// It answers only for the candidates it is handed; the lifetime occurrence
// history is never enumerated.
SecretValueOccurrenceIDsIn(ctx context.Context, p authz.Proof, valueEntryIDs []string) (map[string]bool, error)
// Changes returns one revision's lineage rows.
Changes(ctx context.Context, p authz.Proof, revision int64) ([]RevisionKeyChange, error)
// ChangesInRange returns the lineage rows of every revision in
// [minRevision, maxRevision], newest revision first then key name: one
// read serves a whole history page.
ChangesInRange(ctx context.Context, p authz.Proof, minRevision, maxRevision int64) ([]RevisionKeyChange, error)
// ProjectRevisions returns the latest published revision per environment
// across the whole project, under a PROJECT proof, the definitions
// plan/apply value-snapshot pin (#70). Environments with no snapshot are
// absent from the map (revision 0). The maximum is aggregated in SQL; only
// one row per environment crosses the wire.
ProjectRevisions(ctx context.Context, p authz.Proof) (map[string]int64, error)
// PayloadBytesForProject sums the ciphertext bytes of the proof's project's
// published snapshot entries across every environment and revision — the
// other half of the per-project storage high-water accounting (#185).
PayloadBytesForProject(ctx context.Context, p authz.Proof) (int64, error)
// InstancePayloadByProject sums published snapshot-entry ciphertext bytes
// grouped by owning project across the whole instance — the operator storage
// surface (doctor warn, metric). Instance-scoped, cross-tenant by definition.
InstancePayloadByProject(ctx context.Context, p authz.Proof) ([]ProjectPayloadBytes, error)
}
SnapshotReader is the read side of the published state.
type SnapshotRepo ¶
type SnapshotRepo interface {
SnapshotReader
Insert(ctx context.Context, p authz.Proof, snapshot NewSnapshot) error
InsertEntry(ctx context.Context, p authz.Proof, entry NewSnapshotEntry) error
RecordSecretValueOccurrence(ctx context.Context, p authz.Proof, valueEntryID string) error
InsertChange(ctx context.Context, p authz.Proof, revision int64, keyID, keyName string, change RevisionChange) error
// DeleteEnvironment removes the environment's snapshots, their entries and
// their lineage, in the transaction that deletes the environment.
DeleteEnvironment(ctx context.Context, p authz.Proof) error
// ListForReencrypt / Reencrypt are the reencrypt walk's page + in-place
// re-seal of snapshot-entry ciphertext (project-wide, keyset by id).
ListForReencrypt(ctx context.Context, p authz.Proof, cursor string, limit int) ([]ReencryptFieldRow, error)
Reencrypt(ctx context.Context, p authz.Proof, id string, newCiphertext, oldCiphertext []byte) (bool, error)
}
SnapshotRepo is the full published-state aggregate. There is no update and no delete-by-revision: a snapshot is immutable, and history is never rewritten. The only removal is the environment cascade, and payload retention (#52) will add its own collection path beside it.
type TransitCaller ¶
TransitCaller is one per-key caller entry. It only ever narrows crypto-use.
type TransitDueKey ¶
type TransitDueKey struct {
OrgID, ProjectID, EnvironmentID string
TransitKeyRecord
LatestCreatedAt time.Time
}
TransitDueKey is one key the scheduler must act on, with its full chain.
type TransitGauges ¶
type TransitGauges struct {
Live, RotationDue, PendingDeletion int64
}
TransitGauges are the label-free transit counts.
type TransitKeyConfig ¶
type TransitKeyConfig struct {
KeyID string
MinEncryptVersion uint32
MinDecryptVersion uint32
RotationPeriodSeconds int64
Callers *[]TransitCaller
At time.Time
}
TransitKeyConfig changes the mutable policy of a key. Callers nil leaves the caller entries untouched; a non-nil empty slice clears them.
type TransitKeyCreate ¶
type TransitKeyCreate struct {
ID string
Name string
Algorithm string
Custody string
AllowedOperations []string
RotationPeriodSeconds int64
CreatedBy string
Callers []TransitCaller
First TransitVersionCreate
At time.Time
}
TransitKeyCreate is a key plus its first version and caller entries.
type TransitKeyRecord ¶
type TransitKeyRecord struct {
ID string
EnvironmentID string
Name string
Algorithm string
Custody string
AllowedOperations []string
State string
LatestVersion uint32
MinEncryptVersion uint32
MinDecryptVersion uint32
// MinAvailableVersion is the trim floor (see TransitRepo.FenceTrim).
MinAvailableVersion uint32
CompromisedThroughVersion uint32
RotationPeriodSeconds int64
DeletionAfter string
CreatedBy string
CreatedAt string
UpdatedAt string
}
TransitKeyRecord is a key's metadata surface. There is no material here and no method on this surface ever returns material: version material is read only through TransitVersion for the operation that needs it.
type TransitReader ¶
type TransitReader interface {
ListKeys(ctx context.Context, p authz.Proof) ([]TransitKeyRecord, error)
GetKey(ctx context.Context, p authz.Proof, name string) (TransitKeyRecord, error)
ListVersions(ctx context.Context, p authz.Proof, keyID string) ([]TransitVersionRecord, error)
ListCallers(ctx context.Context, p authz.Proof, keyID string) ([]TransitCaller, error)
}
TransitReader is the read side.
type TransitRepo ¶
type TransitRepo interface {
TransitReader
// GetKeyForUse is GetKey for the operation path: on postgres it takes a
// shared row lock, so a concurrent disable, compromise or deletion waits
// for the operation's commit or is seen by it, never interleaved.
GetKeyForUse(ctx context.Context, p authz.Proof, name string) (TransitKeyRecord, error)
// VersionMaterial returns one version's material for the operation that
// needs it. It is the ONLY method that returns material.
VersionMaterial(ctx context.Context, p authz.Proof, keyID string, version uint32) (TransitVersionMaterial, error)
CountKeys(ctx context.Context, p authz.Proof) (int, error)
CreateKey(ctx context.Context, p authz.Proof, m TransitKeyCreate) (TransitKeyRecord, error)
// AppendVersion adds version expectLatest+1 under a compare-and-swap on the
// key row: a concurrent rotation that won first makes this ErrConflict.
AppendVersion(ctx context.Context, p authz.Proof, keyID string, expectLatest uint32, maxVersions int, v TransitVersionCreate) error
Configure(ctx context.Context, p authz.Proof, m TransitKeyConfig) error
ChangeState(ctx context.Context, p authz.Proof, m TransitStateChange) error
// Compromise marks every version up to the current latest compromised.
Compromise(ctx context.Context, p authz.Proof, keyID string, at time.Time) (uint32, error)
// FenceTrim raises the trim floor (min_available_version) to the current
// min_decrypt_version and returns it. From then on Configure refuses a
// min_decrypt_version below the floor, so the versions under it can be
// destroyed at an external provider outside any transaction.
FenceTrim(ctx context.Context, p authz.Proof, keyID string, at time.Time) (uint32, error)
// Trim deletes versions below through, bounded by the durable trim floor.
Trim(ctx context.Context, p authz.Proof, keyID string, through uint32) (int64, error)
ListVersionsForReencrypt(ctx context.Context, p authz.Proof, cursor string, limit int) ([]ReencryptFieldRow, error)
ReencryptVersion(ctx context.Context, p authz.Proof, id string, newCiphertext, oldCiphertext []byte) (bool, error)
// SelectDeletionDue and SelectRotationDue are the scheduler's
// installation-wide reads (system authority), keyset-paged by key id: after
// is the last id of the previous page ("" for the first).
SelectDeletionDue(ctx context.Context, p authz.Proof, now time.Time, after string, limit int) ([]TransitDueKey, error)
SelectRotationDue(ctx context.Context, p authz.Proof, after string, limit int) ([]TransitDueKey, error)
// DestroyVersions fences the due purge and lists material to destroy at an external
// provider; Destroy then erases every version's material and tombstones the
// key, guarded by pending-deletion and the elapsed delay.
DestroyVersions(ctx context.Context, p authz.Proof, keyID string, now time.Time) ([]TransitVersionMaterial, error)
Destroy(ctx context.Context, p authz.Proof, keyID string, now time.Time) (int64, error)
}
TransitRepo is the write side plus the reads.
type TransitRuntime ¶
type TransitRuntime struct {
// contains filtered or unexported fields
}
TransitRuntime serves the label-free transit gauges at scrape time. It reads counts only, never a row's content.
func NewTransitRuntime ¶
func NewTransitRuntime(db *DB) *TransitRuntime
NewTransitRuntime creates a gauge reader over db without reading it.
func (*TransitRuntime) Gauges ¶
func (r *TransitRuntime) Gauges(ctx context.Context, now time.Time) (TransitGauges, error)
Gauges counts non-destroyed, rotation-due, and pending-deletion keys across the installation at now. Database and timestamp errors propagate; counts may be partial on error.
type TransitStateChange ¶
type TransitStateChange struct {
KeyID string
From []string
To string
DeletionAfter time.Time // set exactly when To is pending-deletion
At time.Time
}
TransitStateChange moves a key between lifecycle states. The update applies only when the key is in one of From; otherwise it is ErrConflict (or ErrNotFound when the key is gone).
type TransitVersionCreate ¶
type TransitVersionCreate struct {
ID string
Version uint32
Sealed []byte
ExternalRef string
PublicKey []byte
At time.Time
}
TransitVersionCreate is one version row. The service has already sealed the material (software) or obtained the reference (external).
type TransitVersionMaterial ¶
type TransitVersionMaterial struct {
ID string
Version uint32
Sealed []byte
ExternalRef string
PublicKey []byte
}
TransitVersionMaterial is what a custody provider needs for one operation: the sealed material (software) or the opaque reference (external).
type TransitVersionRecord ¶
type TransitVersionRecord struct {
ID string
Version uint32
PublicKey []byte
HasMaterial bool
ExternalHeld bool
CreatedAt string
}
TransitVersionRecord is one version's public metadata.
type UpgradeExportRequest ¶
type UpgradeExportRequest struct {
Plan upgradecompat.Plan
Recipients []string
LegacyProposal *backupreceipt.LegacyProposal
BackupID backupreceipt.Nonce
CreatedAt time.Time
// contains filtered or unexported fields
}
UpgradeExportRequest carries authenticated route authority and public export policy. Its proposed legacy incarnation is explicitly separate from facts that bindSQLite/bindPostgres read inside the actual archived snapshot.
type ValueEntry ¶
type ValueEntry struct {
// ID is bound into the ciphertext's AAD, so it is immutable and never
// reused: a rewrite of the same cell mints a new id.
ID string
OrgID string
ProjectID string
EnvironmentID string
KeyID string
Ciphertext []byte
UpdatedAt time.Time
// UpdatedBy is the principal whose act produced this occurrence — the
// supply record the re-delivery gate reasons about.
UpdatedBy string
}
ValueEntry is a stored value cell.
type ValueReader ¶
type ValueReader interface {
// Get returns one cell of the proof's environment, or ErrNotFound — which
// IS `absent`, the only non-`set` state there is.
Get(ctx context.Context, p authz.Proof, keyID string) (ValueEntry, error)
// List returns the proof's environment's entire set, ordered by key id.
// This is the delivery-shaped read and the diff's per-side read.
List(ctx context.Context, p authz.Proof) ([]ValueEntry, error)
// EnvironmentsWithValue names the environments in the proof's PROJECT that
// hold a value for one key. It spans environments deliberately: deleting a
// key must be able to say which environments still deliver material for
// it, and that answer cannot be assembled one authorized environment at a
// time without becoming a different (and racier) question.
EnvironmentsWithValue(ctx context.Context, p authz.Proof, keyID string) ([]string, error)
// CountEnvironmentValues counts one environment's live occurrences under a
// PROJECT proof — environment_id is an ordinary column, so the
// definitions-apply path (project-scoped) can ask it of an environment it is
// about to delete. Any count above zero is the unconditional
// environment-delete refusal (#70).
CountEnvironmentValues(ctx context.Context, p authz.Proof, environmentID string) (int64, error)
// PayloadBytesForProject sums the ciphertext bytes of the proof's project's
// live value cells across every environment — half of the per-project
// storage high-water accounting refused at publish (#185, ops-spec section 8).
PayloadBytesForProject(ctx context.Context, p authz.Proof) (int64, error)
// InstancePayloadByProject sums live value-cell ciphertext bytes grouped by
// owning project across the whole instance — the operator storage surface
// (doctor warn, metric). Cross-tenant by definition, so its query is
// instance-scoped; the proof licenses the read, not a tenant chain.
InstancePayloadByProject(ctx context.Context, p authz.Proof) ([]ProjectPayloadBytes, error)
// SampleSecretEntry returns one stored `secret` cell across the whole
// instance, ciphertext only, for the restore drill's decrypt proof (#145).
// Cross-tenant by definition, so its query is instance-scoped; the proof
// licenses the read, not a tenant chain. ErrNotFound when no secret is
// stored anywhere.
SampleSecretEntry(ctx context.Context, p authz.Proof) (ValueEntry, error)
}
ValueReader is the read side of the value model.
type ValueRepo ¶
type ValueRepo interface {
ValueReader
// Put writes one cell of the proof's environment. It is delete-then-insert
// rather than an upsert because the row id is bound into the AAD: reusing
// the id of a superseded occurrence is the one thing the encryption-model ADR
// forbids outright.
Put(ctx context.Context, p authz.Proof, entry NewValueEntry) error
// Clear removes one cell — the `set` → `absent` transition, which with no
// inheritance leaves nothing behind to fall back to. Removing a cell that
// is already absent is not an error: absence is the state, not the act. It
// reports whether a row actually existed, so the caller emits the
// value.cleared event only for a transition that really happened.
Clear(ctx context.Context, p authz.Proof, keyID string) (bool, error)
// ClearEnvironment removes the proof's environment's whole set, in the
// transaction that deletes the environment itself.
ClearEnvironment(ctx context.Context, p authz.Proof) error
// ClearKey removes a key's occurrences across every environment under a
// PROJECT proof, in the definitions-apply transaction that deletes the key
// with --allow-delete (#70). Returns the number of occurrences removed.
ClearKey(ctx context.Context, p authz.Proof, keyID string) (int64, error)
// ListForReencrypt pages a project's entire value set by id (keyset cursor,
// "" for the first page), for the reencrypt walk. Project-scoped: spans every
// environment.
ListForReencrypt(ctx context.Context, p authz.Proof, cursor string, limit int) ([]ReencryptValueRow, error)
// Reencrypt re-seals one value row's ciphertext in place (same id, same AAD,
// new DEK version), compare-and-swapping on the old ciphertext. Reports
// whether the row moved (false = a concurrent write already replaced it).
Reencrypt(ctx context.Context, p authz.Proof, id string, newCiphertext, oldCiphertext []byte) (bool, error)
}
ValueRepo is the full value aggregate.
type VerifiedPostgresSource ¶
type VerifiedPostgresSource struct {
// contains filtered or unexported fields
}
VerifiedPostgresSource is a short-lived in-process proof of an alternate connection descriptor for this exact live datastore. It grants no migration or deployment authority and retains no credential or raw locator. Its digest becomes useful only when an authorized coordinator signs the exact rollout.
func (*VerifiedPostgresSource) Digest ¶
func (p *VerifiedPostgresSource) Digest() string
Digest returns opaque evidence, never the raw or unsalted descriptor hash.
func (*VerifiedPostgresSource) ValidateFor ¶
func (p *VerifiedPostgresSource) ValidateFor(ctx context.Context, current *DB, candidateDSN string, now time.Time) error
ValidateFor must run immediately before signing/submitting the exact rollout and after rereading the immutable installed alias. It rechecks the live challenge, not only immutable admission metadata, so changed recovery state or a changed DNS destination cannot reuse earlier evidence. Expiry is never extended by validation. The installed rollout authority owns execution.
Source Files
¶
- access.go
- adapter_adoption_queries.go
- adapter_config_queries.go
- adapter_config_rows.go
- adapter_credential_queries.go
- adapter_lifecycle_queries.go
- adapter_move_queries.go
- adapter_move_rows.go
- adapter_origin_guard.go
- adapter_origin_queries.go
- adapter_runtime.go
- adapter_runtime_queries.go
- adapter_runtime_rows.go
- adapter_store_queries.go
- adapter_store_rows.go
- admission.go
- admission_serialized.go
- approvals.go
- audit_actor_cache.go
- backup.go
- backup_state.go
- backup_upgrade.go
- backup_upgrade_restore.go
- catalogue.go
- coordination.go
- coordination_fence.go
- coordination_self_config.go
- coordination_transactions.go
- dynamic.go
- dynamic_runtime.go
- dynamic_runtime_queries.go
- dynamic_store_queries.go
- keys.go
- keys_mutations.go
- map_rows.go
- migrations.go
- pki.go
- pki_runtime.go
- pki_store_queries.go
- pki_store_rows.go
- preparation.go
- recovery.go
- repos.go
- repos_access.go
- repos_adapters.go
- repos_adapters_config.go
- repos_adapters_move.go
- repos_approvals.go
- repos_audit.go
- repos_audit_retention.go
- repos_catalogue.go
- repos_definitions.go
- repos_delivery_targets.go
- repos_diagnostics.go
- repos_file_targets.go
- repos_mcp_page.go
- repos_parameters.go
- repos_project_capacity.go
- repos_reencrypt.go
- repos_remote.go
- repos_retention.go
- repos_revisions.go
- repos_scanning.go
- repos_self_config.go
- repos_self_config_dialects.go
- repos_self_config_rollout.go
- repos_self_config_rollout_dialects.go
- repos_self_config_seed.go
- repos_self_config_seed_dialects.go
- repos_self_config_topology.go
- repos_values.go
- restore_destination.go
- retention.go
- revisions.go
- runtime_queries.go
- runtime_read.go
- runtime_status.go
- scim.go
- self_config.go
- ssh.go
- ssh_runtime.go
- ssh_runtime_queries.go
- ssh_store_queries.go
- ssh_store_reads.go
- store.go
- stored_bytes.go
- stored_integer.go
- stored_time.go
- transit.go
- transit_store_queries.go
- transit_store_rows.go
- upgrade_source.go
- values.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package auditrow is the single audit Row → engine-parameter mapping, shared by the store's audit repositories and the authorization package's denial writer so the two writers cannot drift (audit-model ADR: one envelope-to-column mapping).
|
Package auditrow is the single audit Row → engine-parameter mapping, shared by the store's audit repositories and the authorization package's denial writer so the two writers cannot drift (audit-model ADR: one envelope-to-column mapping). |
|
Package authn is the authorization package's enumerated resolution surface (tenant-isolation ADR § bootstrap carve-out): authorize() cannot run under a proof, so the reads it needs to mint one — chain resolution and grant lookup — live here, and nowhere else may read chain tables with request-supplied identifiers.
|
Package authn is the authorization package's enumerated resolution surface (tenant-isolation ADR § bootstrap carve-out): authorize() cannot run under a proof, so the reads it needs to mint one — chain resolution and grant lookup — live here, and nowhere else may read chain tables with request-supplied identifiers. |
|
Package keyring implements crypto.KeyStore over the datastore: every access runs through the transactional boundary, with the hierarchy-generation fence acquired in the same transaction as the writes it fences.
|
Package keyring implements crypto.KeyStore over the datastore: every access runs through the transactional boundary, with the hierarchy-generation fence acquired in the same transaction as the writes it fences. |
|
Package migrate applies the embedded goose migrations.
|
Package migrate applies the embedded goose migrations. |
|
Package tx owns the transactional boundary (system-architecture ADR § Transaction boundary).
|
Package tx owns the transactional boundary (system-architecture ADR § Transaction boundary). |
|
Package upgrade stores upgrade state.
|
Package upgrade stores upgrade state. |