store

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: MIT Imports: 24 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFound       = errors.New("store: not found")
	ErrDenied         = errors.New("store: denied")
	ErrSessionExpired = errors.New("store: session expired")
	ErrSessionRevoked = errors.New("store: session revoked")
	// ErrOrgKeyMissing means the org has no org_keys row — a provisioning or
	// ops failure, distinct from a missing item so callers do not 404 a secret
	// that exists but cannot be decrypted.
	ErrOrgKeyMissing = errors.New("store: org has no key")
	// ErrOrgKeyMismatch means EnsureOrgKey was handed a master that does not
	// match the committed org_keys row — the asserted key is wrong.
	ErrOrgKeyMismatch = errors.New("store: org key mismatch")
	// ErrRequestResolved means an approval request was already resolved,
	// expired, or its grant died before the resolution landed — nothing was
	// written.
	ErrRequestResolved = errors.New("store: request already resolved")
	// ErrGrantNotLive means the grant's edge is dead — expired grant,
	// revoked agent, or archived item — so an approval minted on it could
	// never be used.
	ErrGrantNotLive = errors.New("store: grant no longer live")
	// ErrUnsupported means the store backend has no such surface — e.g.
	// key-rotation verbs on a single-key store.
	ErrUnsupported = errors.New("store: unsupported")
)
View Source
var ErrRotationConflict = errors.New("store: concurrent key rotation")

ErrRotationConflict is a concurrent rotation detected by the key_version guard: another RotateOrgKey bumped the version first. Retry to converge.

Functions

func AuditExportCursor

func AuditExportCursor(ctx context.Context, pool *pgxpool.Pool) (int64, error)

AuditExportCursor returns the highest audit id already exported.

func DetachAuditPartitionsBefore

func DetachAuditPartitionsBefore(ctx context.Context, pool *pgxpool.Pool, cutoff time.Time) ([]string, error)

DetachAuditPartitionsBefore detaches every monthly audit partition whose range ends before cutoff, returning the detached table names. Detached partitions become ordinary tables — archive or drop is an ops call (e.g. pg_dump -t then DROP), never an implicit data loss inside the verb. audit_default is never detached: it is the catch-all, not a month.

func EnsureAuditExport

func EnsureAuditExport(ctx context.Context, pool *pgxpool.Pool) error

EnsureAuditExport creates the cursor table and seeds the zero row. Idempotent.

func EnsureAuditPartitions

func EnsureAuditPartitions(ctx context.Context, pool *pgxpool.Pool, ahead int) error

EnsureAuditPartitions creates monthly partitions of audit covering this month and ahead-1 following months. Idempotent — reruns create only the missing range. Boot calls it with ahead=2; `veil sweep` calls it with a wider horizon so a never-restarting origin still partitions ahead.

func EnsureOpsHeartbeat

func EnsureOpsHeartbeat(ctx context.Context, pool *pgxpool.Pool) error

EnsureOpsHeartbeat creates the beat table. Idempotent.

func EnsurePostgresSchema

func EnsurePostgresSchema(ctx context.Context, pool *pgxpool.Pool) error

EnsurePostgresSchema creates the vault tables/indexes if missing. It is the same DDL OpenPostgres runs at boot, exposed so the sqlite→postgres migrator can prepare an empty database without a master key.

func EnsureSQLiteSchema

func EnsureSQLiteSchema(db *sql.DB) error

EnsureSQLiteSchema creates any missing tables and applies the sqlite schema migrations. It touches no secrets, so maintenance commands can call it on a raw handle without a master key.

func HeartbeatAge

func HeartbeatAge(ctx context.Context, pool *pgxpool.Pool, name string) (age time.Duration, ok bool, err error)

HeartbeatAge returns the age of name's last beat. ok is false when the job has never reported — a missing beat is itself a finding.

func MarkHeartbeat

func MarkHeartbeat(ctx context.Context, pool *pgxpool.Pool, name string) error

MarkHeartbeat upserts name's beat to now.

func OutboxLag

func OutboxLag(ctx context.Context, pool *pgxpool.Pool) (depth int, oldest time.Duration, err error)

OutboxLag reports audit relay backlog: queued rows and the age of the oldest one, measured in server time. Zero depth returns oldest=0.

func PushDevicesFromPool

func PushDevicesFromPool(ctx context.Context, pool *pgxpool.Pool, orgID string) ([]protocol.PushDevice, error)

PushDevicesFromPool lists registered phone endpoints for an org — the monitor runs at pool level (no full Store) but still needs the same device list to send ops pages.

func SetAuditExportCursor

func SetAuditExportCursor(ctx context.Context, pool *pgxpool.Pool, lastID int64) error

SetAuditExportCursor advances the watermark after a batch lands offsite. Moving backwards is refused — a regressed cursor re-exports history.

func SystemIdentifier

func SystemIdentifier(ctx context.Context, pool *pgxpool.Pool) (string, error)

SystemIdentifier is the cluster's stable identity (pg_control) — the arc-<sysid>/ namespace prefix every offsite archive object lives under.

func UsageReportLag

func UsageReportLag(ctx context.Context, pool *pgxpool.Pool, currentWindow time.Time) (pending, stale int64, units int64, err error)

UsageReportLag reports billing-flusher backlog: pending rows are org-windows with unreported deltas, stale is the subset from closed windows (before currentWindow) — those have survived at least one full tick plus a window boundary, so they are stuck rather than merely queued. units is the total unreported usage.

func WalSlotStatus

func WalSlotStatus(ctx context.Context, pool *pgxpool.Pool, name string) (active bool, status string, ok bool, err error)

WalSlotStatus reads the archive slot's liveness from the server's side. The wal-archive heartbeat proves the shipper loop is alive; this proves a pg_receivewal is actually attached — a dead receiver with a live shipper otherwise pages nothing while WAL silently stops flowing. ok=false means the slot is missing entirely; status='lost' means max_slot_wal_keep_size fired and retained WAL was dropped.

Types

type AuditExportRow

type AuditExportRow struct {
	ID         int64     `json:"id"`
	At         time.Time `json:"at"`
	OrgID      string    `json:"org_id"`
	AgentID    string    `json:"agent_id"`
	ItemID     string    `json:"item_id"`
	Action     string    `json:"action"`
	Decision   string    `json:"decision"`
	Reason     string    `json:"reason"`
	ApprovalID string    `json:"approval_id"`
}

AuditExportRow is one audit event on the export wire — the full row plus its sequence id so the archive is independently ordered and dedup-able.

func ExportableAudits

func ExportableAudits(ctx context.Context, pool *pgxpool.Pool, afterID int64, limit int) ([]AuditExportRow, error)

ExportableAudits returns up to limit audit rows with id > afterID in sequence order — the archive's read cursor. id is a shared sequence, so strictly increasing across partitions; the scan fans out over monthly partitions, bounded by limit.

type FileOutcome

type FileOutcome struct {
	Request   protocol.ApprovalRequest
	Created   bool
	ExpiredID string
}

FileOutcome is what one FileRequest did: the live ask, whether this call created it (a deduped refile returns Created=false and must not re-notify owners), and the stale open ask it expired on the way in, if any.

type Memory

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

func NewMemory

func NewMemory() *Memory

func (*Memory) AddGroupMember

func (m *Memory) AddGroupMember(groupID string, mb protocol.GroupMember, events ...protocol.AuditEvent) error

func (*Memory) Agent

func (m *Memory) Agent(id string) (protocol.Principal, error)

func (*Memory) AppendAudit

func (m *Memory) AppendAudit(e protocol.AuditEvent) error

func (*Memory) AppendAudits

func (m *Memory) AppendAudits(events []protocol.AuditEvent) error

func (*Memory) ApproveGrant

func (m *Memory) ApproveGrant(grantID string, appr protocol.Approval, at time.Time) ([]protocol.ApprovalRequest, error)

func (*Memory) ApproveRequest

func (m *Memory) ApproveRequest(id string, appr protocol.Approval, at time.Time) ([]protocol.ApprovalRequest, bool, error)

func (*Memory) ArchiveItem

func (m *Memory) ArchiveItem(id string, events ...protocol.AuditEvent) error

func (*Memory) Audit

func (m *Memory) Audit() ([]protocol.AuditEvent, error)

func (*Memory) AuditFeed

func (m *Memory) AuditFeed(orgID string, afterID int64, limit int) ([]protocol.AuditFeedEvent, error)

AuditFeed ids are 1-based append positions — the memory store's append order is the same monotonic sequence Postgres assigns from its id column.

func (*Memory) Billing

func (m *Memory) Billing(orgID string) (OrgBilling, error)

func (*Memory) CancelRequestsForAgent

func (m *Memory) CancelRequestsForAgent(agentID string, at time.Time) error

func (*Memory) CancelRequestsForItem

func (m *Memory) CancelRequestsForItem(itemID string, at time.Time) error

func (*Memory) Close

func (m *Memory) Close() error

func (*Memory) ConsumeSession

func (m *Memory) ConsumeSession(sessionHash []byte, now time.Time) (protocol.Principal, error)

func (*Memory) ConsumeSessionAudited

func (m *Memory) ConsumeSessionAudited(sessionHash []byte, now time.Time, e protocol.AuditEvent) (protocol.Principal, error)

func (*Memory) ConsumeUse

func (m *Memory) ConsumeUse(orgID string, window time.Time, cap int64) (int64, bool, error)

func (*Memory) DeleteItem

func (m *Memory) DeleteItem(id string, events ...protocol.AuditEvent) error

func (*Memory) DeletePushDevice

func (m *Memory) DeletePushDevice(orgID, token string) error

func (*Memory) DeleteWorkload

func (m *Memory) DeleteWorkload(issuer, subject string, events ...protocol.AuditEvent) error

func (*Memory) EnsureOrgKey

func (m *Memory) EnsureOrgKey(context.Context, string, []byte) error

Memory holds plaintext and has no key hierarchy — org keys are provisioned.

func (*Memory) ExpireStaleRequests

func (m *Memory) ExpireStaleRequests(now time.Time) ([]protocol.ApprovalRequest, error)

func (*Memory) FileRequest

func (m *Memory) FileRequest(req protocol.ApprovalRequest) (FileOutcome, error)

func (*Memory) FlushAuditOutbox

func (m *Memory) FlushAuditOutbox(int) (int, error)

FlushAuditOutbox: memory has no outbox.

func (*Memory) Grant

func (m *Memory) Grant(id string) (*protocol.Grant, error)

func (*Memory) GrantFor

func (m *Memory) GrantFor(agentID, itemID string) (*protocol.Grant, error)

func (*Memory) Group

func (m *Memory) Group(id string) (protocol.Group, error)

func (*Memory) GroupIDsFor

func (m *Memory) GroupIDsFor(members []protocol.GroupMember) ([]string, error)

func (*Memory) GroupMembers

func (m *Memory) GroupMembers(groupID string) ([]protocol.GroupMember, error)

func (*Memory) HasOrgKey

func (m *Memory) HasOrgKey(context.Context, string) (bool, error)

func (*Memory) HeartbeatAt

func (m *Memory) HeartbeatAt(name string) (time.Time, bool)

HeartbeatAt reports when name last beat. Test surface, not Store.

func (*Memory) Human

func (m *Memory) Human(id string) (protocol.Principal, error)

func (*Memory) Item

func (m *Memory) Item(id string) (protocol.Item, error)

func (*Memory) ItemByName

func (m *Memory) ItemByName(orgID, name string) (protocol.Item, error)

func (*Memory) ListAgents

func (m *Memory) ListAgents() ([]protocol.Principal, error)

func (*Memory) ListGrants

func (m *Memory) ListGrants() ([]protocol.Grant, error)

func (*Memory) ListGroups

func (m *Memory) ListGroups() ([]protocol.Group, error)

func (*Memory) ListHumans

func (m *Memory) ListHumans() ([]protocol.Principal, error)

func (*Memory) ListItems

func (m *Memory) ListItems() ([]protocol.Item, error)

func (*Memory) ListRequests

func (m *Memory) ListRequests(orgID string, status protocol.RequestStatus, now time.Time) ([]protocol.ApprovalRequest, error)

func (*Memory) ListSessions

func (m *Memory) ListSessions() ([]protocol.Session, error)

func (*Memory) LiveApproval

func (m *Memory) LiveApproval(grantID string, now time.Time) (*protocol.Approval, error)

func (*Memory) MarkHeartbeat

func (m *Memory) MarkHeartbeat(name string) error

MarkHeartbeat records the beat — tests read it back via HeartbeatAt.

func (*Memory) MarkUsageReported

func (m *Memory) MarkUsageReported(orgID string, window time.Time, amount int64) error

func (*Memory) OpenRecoveryWrap

func (m *Memory) OpenRecoveryWrap(context.Context, string, protocol.Owner, []byte) ([]byte, error)

func (*Memory) OrgByBillingCustomer

func (m *Memory) OrgByBillingCustomer(customerID string) (string, error)

func (*Memory) PlantHuman

func (m *Memory) PlantHuman(p protocol.Principal) (bool, error)

func (*Memory) PushDevices

func (m *Memory) PushDevices(orgID string) ([]protocol.PushDevice, error)

func (*Memory) PutAgent

func (m *Memory) PutAgent(p protocol.Principal, events ...protocol.AuditEvent) error

func (*Memory) PutApproval

func (m *Memory) PutApproval(a protocol.Approval) error

func (*Memory) PutGrant

func (m *Memory) PutGrant(g protocol.Grant, events ...protocol.AuditEvent) error

func (*Memory) PutGroup

func (m *Memory) PutGroup(g protocol.Group, events ...protocol.AuditEvent) error

func (*Memory) PutHuman

func (m *Memory) PutHuman(p protocol.Principal) error

func (*Memory) PutItem

func (m *Memory) PutItem(item protocol.Item, secret Secret, events ...protocol.AuditEvent) error

func (*Memory) PutPushDevice

func (m *Memory) PutPushDevice(d protocol.PushDevice) error

Push devices — in-memory rows for tests and the embedded store.

func (*Memory) PutSession

func (m *Memory) PutSession(s protocol.Session, secretHash []byte, events ...protocol.AuditEvent) error

func (*Memory) PutWorkload

func (m *Memory) PutWorkload(w protocol.Workload, events ...protocol.AuditEvent) error

func (*Memory) RecoverOrgKey

func (m *Memory) RecoverOrgKey(context.Context, string, protocol.Owner, []byte) error

func (*Memory) RemoveGroupMember

func (m *Memory) RemoveGroupMember(groupID string, mb protocol.GroupMember, events ...protocol.AuditEvent) error

func (*Memory) RenewSession

func (m *Memory) RenewSession(id string, at time.Time, events ...protocol.AuditEvent) (protocol.Session, error)

func (*Memory) Request

func (m *Memory) Request(id string) (protocol.ApprovalRequest, error)

func (*Memory) ReseedOrgKey

func (m *Memory) ReseedOrgKey(context.Context, string, []byte) error

func (*Memory) ResolveRequest

func (m *Memory) ResolveRequest(id string, status protocol.RequestStatus, humanID, approvalID string, at time.Time) (protocol.ApprovalRequest, bool, error)

func (*Memory) RestoreVersion

func (m *Memory) RestoreVersion(itemID string, versionID int64) error

func (*Memory) RevokeAgent

func (m *Memory) RevokeAgent(id string, at time.Time, audit ...protocol.AuditEvent) error

func (*Memory) RevokeSession

func (m *Memory) RevokeSession(id string, at time.Time, events ...protocol.AuditEvent) error

func (*Memory) RotateKEK

func (m *Memory) RotateKEK(context.Context, []byte) error

func (*Memory) RotateOrgKey

func (m *Memory) RotateOrgKey(context.Context, string) error

func (*Memory) Secret

func (m *Memory) Secret(id string) (Secret, error)

func (*Memory) SessionByHash

func (m *Memory) SessionByHash(secretHash []byte) (protocol.Session, error)

func (*Memory) SessionByID

func (m *Memory) SessionByID(id string) (protocol.Session, error)

func (*Memory) SetBilling

func (m *Memory) SetBilling(ob OrgBilling) error
func (m *Memory) SetBillingLink(orgID, customerID, billingAccountID string) error

func (*Memory) StoreRecoveryWrap

func (m *Memory) StoreRecoveryWrap(context.Context, string, protocol.Owner, []byte, time.Time) error

func (*Memory) Sweep

func (m *Memory) Sweep(olderThan time.Time) (SweepReport, error)

func (*Memory) Usage

func (m *Memory) Usage(orgID string, window time.Time) (int64, error)

func (*Memory) UsageReportPending

func (m *Memory) UsageReportPending(limit int) ([]UsageReportRow, error)

func (*Memory) UseAuth

func (m *Memory) UseAuth(agentID, itemID string, now time.Time) (UseAuth, error)

func (*Memory) UseAuthSession

func (m *Memory) UseAuthSession(sessionHash []byte, itemID string, now time.Time) (UseAuth, error)

func (*Memory) Versions

func (m *Memory) Versions(itemID string) ([]protocol.ItemVersion, error)

func (*Memory) WatchRequests

func (m *Memory) WatchRequests(ctx context.Context, orgID string) <-chan struct{}

WatchRequests ticks on approval-request changes for orgID — see Store.

func (*Memory) Workload

func (m *Memory) Workload(issuer, subject string) (*protocol.Workload, error)

func (*Memory) WorkloadsForAgent

func (m *Memory) WorkloadsForAgent(agentID string) ([]protocol.Workload, error)

func (*Memory) WorkloadsForIssuer

func (m *Memory) WorkloadsForIssuer(issuer string) ([]protocol.Workload, error)

type MigrateReport

type MigrateReport struct {
	Tables []MigrateTableReport
}

MigrateReport is the per-table outcome of a sqlite→postgres copy.

func MigrateSQLiteToPostgres

func MigrateSQLiteToPostgres(ctx context.Context, sqlitePath, dsn string) (*MigrateReport, error)

MigrateSQLiteToPostgres copies every application row from the sqlite vault at sqlitePath into the postgres database at dsn. Inserts are ON CONFLICT DO NOTHING, so a rerun inserts only rows written since the last pass and never overwrites fresher postgres state (e.g. session use counts).

No master key is needed: secrets, session hashes, and wrapped owner keys are opaque ciphertext copied byte-for-byte.

type MigrateTableReport

type MigrateTableReport struct {
	Table    string
	Read     int
	Inserted int
	Skipped  int
}

type OrgBilling

type OrgBilling struct {
	OrgID      string
	Plan       string
	CustomerID string
	// BillingAccountID is the provider billing account usage events post to.
	BillingAccountID string
	UpdatedAt        time.Time
}

OrgBilling is the org's billing state as last reported by the billing webhook receiver — plan is what the Use gate enforces. An absent row reads as Plan "free".

type OrgLifecycle

type OrgLifecycle interface {
	// DeleteHuman removes a humans row — after this their token resolves to
	// "not provisioned" on every call. Caller removes the Keto tuple.
	DeleteHuman(ctx context.Context, id string) error
	// PurgeOrg deletes every vault row owned by orgID inside one
	// transaction — secrets, grants, sessions, keys, humans. Audit rows are
	// kept deliberately: teardown must not erase the forensic record; the
	// 90-day partition retention still applies.
	PurgeOrg(ctx context.Context, orgID string) (PurgeReport, error)
}

OrgLifecycle is org teardown and membership surgery — Postgres-only ops surface, asserted via interface at the call site so the sqlite/memory stores stay untouched.

type Postgres

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

Postgres is a pgx-backed Store for the origin. Secrets are encrypted with per-owner data keys before they are written, same as the SQLite store. Owner DEKs sit under a per-org master resolved from org_keys; the store holds the deployment KEK, not any org's plaintext master at rest.

func OpenPostgres

func OpenPostgres(connString string, kek []byte) (*Postgres, error)

OpenPostgres opens a Postgres-backed store. The supplied key is the deployment KEK that seals org_keys rows — it never seals item secrets directly. Org masters live wrapped in the org_keys table.

func (*Postgres) AddGroupMember

func (p *Postgres) AddGroupMember(groupID string, m protocol.GroupMember, events ...protocol.AuditEvent) error

func (*Postgres) Agent

func (p *Postgres) Agent(id string) (protocol.Principal, error)

func (*Postgres) AppendAudit

func (p *Postgres) AppendAudit(e protocol.AuditEvent) error

func (*Postgres) AppendAudits

func (p *Postgres) AppendAudits(events []protocol.AuditEvent) error

func (*Postgres) ApproveGrant

func (p *Postgres) ApproveGrant(grantID string, appr protocol.Approval, at time.Time) ([]protocol.ApprovalRequest, error)

func (*Postgres) ApproveRequest

func (p *Postgres) ApproveRequest(id string, appr protocol.Approval, at time.Time) ([]protocol.ApprovalRequest, bool, error)

func (*Postgres) ArchiveItem

func (p *Postgres) ArchiveItem(id string, events ...protocol.AuditEvent) error

func (*Postgres) Audit

func (p *Postgres) Audit() ([]protocol.AuditEvent, error)

func (*Postgres) AuditFeed

func (p *Postgres) AuditFeed(orgID string, afterID int64, limit int) ([]protocol.AuditFeedEvent, error)

func (*Postgres) Billing

func (p *Postgres) Billing(orgID string) (OrgBilling, error)

func (*Postgres) CancelRequestsForAgent

func (p *Postgres) CancelRequestsForAgent(agentID string, at time.Time) error

func (*Postgres) CancelRequestsForItem

func (p *Postgres) CancelRequestsForItem(itemID string, at time.Time) error

CancelRequestsForItem resolves every open ask on an archived/deleted item as cancelled and writes each request_cancelled event in the same commit — an ask must never vanish without an audit line saying why.

func (*Postgres) Close

func (p *Postgres) Close() error

func (*Postgres) ConsumeSession

func (p *Postgres) ConsumeSession(sessionHash []byte, now time.Time) (protocol.Principal, error)

func (*Postgres) ConsumeSessionAudited

func (p *Postgres) ConsumeSessionAudited(sessionHash []byte, now time.Time, e protocol.AuditEvent) (protocol.Principal, error)

func (*Postgres) ConsumeUse

func (p *Postgres) ConsumeUse(orgID string, window time.Time, cap int64) (int64, bool, error)

func (*Postgres) DeleteHuman

func (p *Postgres) DeleteHuman(ctx context.Context, id string) error

func (*Postgres) DeleteItem

func (p *Postgres) DeleteItem(id string, events ...protocol.AuditEvent) error

func (*Postgres) DeletePushDevice

func (p *Postgres) DeletePushDevice(orgID, token string) error

func (*Postgres) DeleteWorkload

func (p *Postgres) DeleteWorkload(issuer, subject string, events ...protocol.AuditEvent) error

func (*Postgres) EnsureOrgKey

func (p *Postgres) EnsureOrgKey(ctx context.Context, orgID string, master []byte) error

EnsureOrgKey seals master under the KEK and inserts the org_keys row if the org has none. If a row already exists it is never overwritten — instead the committed master is unwrapped and compared: an identical re-seed is a no-op, a different master is ErrOrgKeyMismatch. A boot that asserts the wrong master fails loud rather than stranding the org's ciphertext under a random key. This is the provisioning hook — signup and the one-time VEIL_MASTER_KEY migration both land here.

func (*Postgres) ExpireStaleRequests

func (p *Postgres) ExpireStaleRequests(now time.Time) ([]protocol.ApprovalRequest, error)

func (*Postgres) FileRequest

func (p *Postgres) FileRequest(req protocol.ApprovalRequest) (FileOutcome, error)

FileRequest expires a stale open on (grant, action) then inserts — the dedupe partial index makes a live open swallow the insert, so a missing RETURNING row means "already filed": select and reuse it.

func (*Postgres) FlushAuditOutbox

func (p *Postgres) FlushAuditOutbox(limit int) (int, error)

FlushAuditOutbox claims up to limit queued events and lands them in `audit`, in one transaction: a crash mid-relay leaves the rows queued for retry, and concurrent relays take disjoint rows via FOR UPDATE SKIP LOCKED. Returns the number of events relayed.

func (*Postgres) Grant

func (p *Postgres) Grant(id string) (*protocol.Grant, error)

func (*Postgres) GrantFor

func (p *Postgres) GrantFor(agentID, itemID string) (*protocol.Grant, error)

func (*Postgres) Group

func (p *Postgres) Group(id string) (protocol.Group, error)

func (*Postgres) GroupIDsFor

func (p *Postgres) GroupIDsFor(members []protocol.GroupMember) ([]string, error)

func (*Postgres) GroupMembers

func (p *Postgres) GroupMembers(groupID string) ([]protocol.GroupMember, error)

func (*Postgres) HasOrgKey

func (p *Postgres) HasOrgKey(ctx context.Context, orgID string) (bool, error)

HasOrgKey reports whether an org_keys row exists for orgID.

func (*Postgres) Human

func (p *Postgres) Human(id string) (protocol.Principal, error)

func (*Postgres) Item

func (p *Postgres) Item(id string) (protocol.Item, error)

func (*Postgres) ItemByName

func (p *Postgres) ItemByName(orgID, name string) (protocol.Item, error)

func (*Postgres) ListAgents

func (p *Postgres) ListAgents() ([]protocol.Principal, error)

func (*Postgres) ListGrants

func (p *Postgres) ListGrants() ([]protocol.Grant, error)

func (*Postgres) ListGroups

func (p *Postgres) ListGroups() ([]protocol.Group, error)

func (*Postgres) ListHumans

func (p *Postgres) ListHumans() ([]protocol.Principal, error)

func (*Postgres) ListItems

func (p *Postgres) ListItems() ([]protocol.Item, error)

func (*Postgres) ListRequests

func (p *Postgres) ListRequests(orgID string, status protocol.RequestStatus, now time.Time) ([]protocol.ApprovalRequest, error)

func (*Postgres) ListSessions

func (p *Postgres) ListSessions() ([]protocol.Session, error)

func (*Postgres) LiveApproval

func (p *Postgres) LiveApproval(grantID string, now time.Time) (*protocol.Approval, error)

func (*Postgres) MarkHeartbeat

func (p *Postgres) MarkHeartbeat(name string) error

MarkHeartbeat delegates to the ops_heartbeat writer — the flusher runs inside the app process, so the beat goes through the store interface.

func (*Postgres) MarkUsageReported

func (p *Postgres) MarkUsageReported(orgID string, window time.Time, amount int64) error

func (*Postgres) OpenRecoveryWrap

func (p *Postgres) OpenRecoveryWrap(ctx context.Context, orgID string, o protocol.Owner, recoveryKey []byte) ([]byte, error)

OpenRecoveryWrap verifies recoveryKey against the owner's wrap and returns the org master. Single-use: the first successful open stamps used_at inside the same transaction that locked the row — replays, concurrent opens, and expired wraps all fail closed.

func (*Postgres) OrgByBillingCustomer

func (p *Postgres) OrgByBillingCustomer(customerID string) (string, error)

func (*Postgres) Ping

func (p *Postgres) Ping(ctx context.Context) error

Ping is the readiness probe: the pool can serve a round trip right now.

func (*Postgres) PlantHuman

func (p *Postgres) PlantHuman(h protocol.Principal) (bool, error)

func (*Postgres) PurgeOrg

func (p *Postgres) PurgeOrg(ctx context.Context, orgID string) (PurgeReport, error)

func (*Postgres) PushDevices

func (p *Postgres) PushDevices(orgID string) ([]protocol.PushDevice, error)

func (*Postgres) PutAgent

func (p *Postgres) PutAgent(agent protocol.Principal, events ...protocol.AuditEvent) error

func (*Postgres) PutApproval

func (p *Postgres) PutApproval(a protocol.Approval) error

func (*Postgres) PutGrant

func (p *Postgres) PutGrant(g protocol.Grant, events ...protocol.AuditEvent) error

func (*Postgres) PutGroup

func (p *Postgres) PutGroup(g protocol.Group, events ...protocol.AuditEvent) error

func (*Postgres) PutHuman

func (p *Postgres) PutHuman(h protocol.Principal) error

func (*Postgres) PutItem

func (p *Postgres) PutItem(item protocol.Item, secret Secret, events ...protocol.AuditEvent) error

func (*Postgres) PutPushDevice

func (p *Postgres) PutPushDevice(d protocol.PushDevice) error

PutPushDevice upserts a registered push endpoint — tokens rotate, so re-registration overwrites platform/label/stamp in place.

func (*Postgres) PutSession

func (p *Postgres) PutSession(sess protocol.Session, secretHash []byte, events ...protocol.AuditEvent) error

func (*Postgres) PutWorkload

func (p *Postgres) PutWorkload(w protocol.Workload, events ...protocol.AuditEvent) error

func (*Postgres) RecoverOrgKey

func (p *Postgres) RecoverOrgKey(ctx context.Context, orgID string, o protocol.Owner, recoveryKey []byte) error

RecoverOrgKey is the lost-KEK recovery verb and the only safe way to spend a wrap for reseed: open + consume + re-wrap org_keys under this store's KEK happen in ONE transaction. Composing OpenRecoveryWrap + ReseedOrgKey burns the wrap on the first commit — a failed reseed would leave the org sealed under the lost KEK with the wrap already spent.

func (*Postgres) RemoveGroupMember

func (p *Postgres) RemoveGroupMember(groupID string, m protocol.GroupMember, events ...protocol.AuditEvent) error

func (*Postgres) RenewSession

func (p *Postgres) RenewSession(id string, at time.Time, events ...protocol.AuditEvent) (protocol.Session, error)

func (*Postgres) Request

func (p *Postgres) Request(id string) (protocol.ApprovalRequest, error)

func (*Postgres) ReseedOrgKey

func (p *Postgres) ReseedOrgKey(ctx context.Context, orgID string, master []byte) error

ReseedOrgKey overwrites the org_keys wrap under this store's KEK. It is the lost-KEK recovery verb: EnsureOrgKey refuses to touch an existing row, so after recovery material yields the master this re-anchors it. Fails ErrOrgKeyMissing when the org has no row — provisioning is EnsureOrgKey's job. The master itself is unchanged, so key_version stays — this is a re-wrap under a new KEK, not a rotation.

func (*Postgres) ResolveRequest

func (p *Postgres) ResolveRequest(id string, status protocol.RequestStatus, humanID, approvalID string, at time.Time) (protocol.ApprovalRequest, bool, error)

func (*Postgres) RestoreVersion

func (p *Postgres) RestoreVersion(itemID string, versionID int64) error

func (*Postgres) RevokeAgent

func (p *Postgres) RevokeAgent(id string, at time.Time, audit ...protocol.AuditEvent) error

func (*Postgres) RevokeSession

func (p *Postgres) RevokeSession(id string, at time.Time, events ...protocol.AuditEvent) error

func (*Postgres) RotateKEK

func (p *Postgres) RotateKEK(ctx context.Context, newKEK []byte) error

RotateKEK rewraps every org master under newKEK. Masters do not change — owner DEKs and item ciphertexts are untouched; only the org_keys wrap moves. cmk-managed rows are skipped (an external CMK owns its own wrap). On commit this store adopts newKEK; every cached master is invalidated so the next resolve re-unwraps under it.

func (*Postgres) RotateOrgKey

func (p *Postgres) RotateOrgKey(ctx context.Context, orgID string) error

RotateOrgKey mints a fresh org master and rewraps every owner DEK under it, in one transaction. Item ciphertexts seal under owner DEKs — the DEK bytes do not change — so rotation never re-seals items. The key_version guard makes concurrent rotations fail one side instead of interleaving rewraps under different masters.

func (*Postgres) Secret

func (p *Postgres) Secret(id string) (Secret, error)

func (*Postgres) SessionByHash

func (p *Postgres) SessionByHash(secretHash []byte) (protocol.Session, error)

func (*Postgres) SessionByID

func (p *Postgres) SessionByID(id string) (protocol.Session, error)

func (*Postgres) SetBilling

func (p *Postgres) SetBilling(ob OrgBilling) error
func (p *Postgres) SetBillingLink(orgID, customerID, billingAccountID string) error

func (*Postgres) StoreRecoveryWrap

func (p *Postgres) StoreRecoveryWrap(ctx context.Context, orgID string, o protocol.Owner, recoveryKey []byte, expiresAt time.Time) error

StoreRecoveryWrap seals the org's committed master under owner-held recovery material and upserts the wrap, in one transaction: the FOR SHARE read of org_keys serializes against RotateOrgKey's FOR UPDATE, so a wrap can never commit a dead master after rotation's delete+commit. The recovery key never persists — losing it strands the wrap, not the vault. Re-minting replaces the row and clears used_at.

func (*Postgres) Sweep

func (p *Postgres) Sweep(olderThan time.Time) (SweepReport, error)

func (*Postgres) Usage

func (p *Postgres) Usage(orgID string, window time.Time) (int64, error)

func (*Postgres) UsageReportPending

func (p *Postgres) UsageReportPending(limit int) ([]UsageReportRow, error)

func (*Postgres) UseAuth

func (p *Postgres) UseAuth(agentID, itemID string, now time.Time) (UseAuth, error)

func (*Postgres) UseAuthSession

func (p *Postgres) UseAuthSession(sessionHash []byte, itemID string, now time.Time) (UseAuth, error)

func (*Postgres) Versions

func (p *Postgres) Versions(itemID string) ([]protocol.ItemVersion, error)

func (*Postgres) WatchRequests

func (p *Postgres) WatchRequests(ctx context.Context, orgID string) <-chan struct{}

WatchRequests ticks on approval-request changes for orgID. The first call starts a dedicated LISTEN connection so a write committed on ANY origin replica wakes the watchers here — the channel closes when ctx ends.

func (*Postgres) Workload

func (p *Postgres) Workload(issuer, subject string) (*protocol.Workload, error)

func (*Postgres) WorkloadsForAgent

func (p *Postgres) WorkloadsForAgent(agentID string) ([]protocol.Workload, error)

func (*Postgres) WorkloadsForIssuer

func (p *Postgres) WorkloadsForIssuer(issuer string) ([]protocol.Workload, error)

type PurgeReport

type PurgeReport struct {
	Items    int64 `json:"items"`
	Grants   int64 `json:"grants"`
	Sessions int64 `json:"sessions"`
	Agents   int64 `json:"agents"`
	Humans   int64 `json:"humans"`
	Keys     int64 `json:"keys"`
}

type SQLite

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

func OpenSQLite

func OpenSQLite(path string, key []byte) (*SQLite, error)

func (*SQLite) AddGroupMember

func (s *SQLite) AddGroupMember(groupID string, mb protocol.GroupMember, events ...protocol.AuditEvent) error

func (*SQLite) Agent

func (s *SQLite) Agent(id string) (protocol.Principal, error)

func (*SQLite) AppendAudit

func (s *SQLite) AppendAudit(e protocol.AuditEvent) error

func (*SQLite) AppendAudits

func (s *SQLite) AppendAudits(events []protocol.AuditEvent) error

func (*SQLite) ApproveGrant

func (s *SQLite) ApproveGrant(grantID string, appr protocol.Approval, at time.Time) ([]protocol.ApprovalRequest, error)

func (*SQLite) ApproveRequest

func (s *SQLite) ApproveRequest(id string, appr protocol.Approval, at time.Time) ([]protocol.ApprovalRequest, bool, error)

func (*SQLite) ArchiveItem

func (s *SQLite) ArchiveItem(id string, events ...protocol.AuditEvent) error

func (*SQLite) Audit

func (s *SQLite) Audit() ([]protocol.AuditEvent, error)

func (*SQLite) AuditFeed

func (s *SQLite) AuditFeed(orgID string, afterID int64, limit int) ([]protocol.AuditFeedEvent, error)

AuditFeed keys the sqlite audit table on rowid — the sqlite schema has no id column, and rowid is the same monotonic append order Postgres uses.

func (*SQLite) Billing

func (s *SQLite) Billing(orgID string) (OrgBilling, error)

func (*SQLite) CancelRequestsForAgent

func (s *SQLite) CancelRequestsForAgent(agentID string, at time.Time) error

func (*SQLite) CancelRequestsForItem

func (s *SQLite) CancelRequestsForItem(itemID string, at time.Time) error

func (*SQLite) Close

func (s *SQLite) Close() error

func (*SQLite) ConsumeSession

func (s *SQLite) ConsumeSession(sessionHash []byte, now time.Time) (protocol.Principal, error)

func (*SQLite) ConsumeSessionAudited

func (s *SQLite) ConsumeSessionAudited(sessionHash []byte, now time.Time, e protocol.AuditEvent) (protocol.Principal, error)

func (*SQLite) ConsumeUse

func (s *SQLite) ConsumeUse(orgID string, window time.Time, cap int64) (int64, bool, error)

func (*SQLite) DeleteHuman

func (s *SQLite) DeleteHuman(_ context.Context, id string) error

DeleteHuman drops the humans row — token resolution fails closed after this.

func (*SQLite) DeleteItem

func (s *SQLite) DeleteItem(id string, events ...protocol.AuditEvent) error

func (*SQLite) DeletePushDevice

func (s *SQLite) DeletePushDevice(orgID, token string) error

func (*SQLite) DeleteWorkload

func (s *SQLite) DeleteWorkload(issuer, subject string, events ...protocol.AuditEvent) error

func (*SQLite) EnsureOrgKey

func (s *SQLite) EnsureOrgKey(context.Context, string, []byte) error

A sqlite vault is one tenant: the single vault key covers every org, so org-key provisioning is a no-op here. Per-org masters are a Postgres shape.

func (*SQLite) ExpireStaleRequests

func (s *SQLite) ExpireStaleRequests(now time.Time) ([]protocol.ApprovalRequest, error)

func (*SQLite) FileRequest

func (s *SQLite) FileRequest(req protocol.ApprovalRequest) (FileOutcome, error)

func (*SQLite) FlushAuditOutbox

func (s *SQLite) FlushAuditOutbox(int) (int, error)

FlushAuditOutbox: sqlite writes audit rows directly — there is no outbox.

func (*SQLite) Grant

func (s *SQLite) Grant(id string) (*protocol.Grant, error)

func (*SQLite) GrantFor

func (s *SQLite) GrantFor(agentID, itemID string) (*protocol.Grant, error)

func (*SQLite) Group

func (s *SQLite) Group(id string) (protocol.Group, error)

func (*SQLite) GroupIDsFor

func (s *SQLite) GroupIDsFor(members []protocol.GroupMember) ([]string, error)

func (*SQLite) GroupMembers

func (s *SQLite) GroupMembers(groupID string) ([]protocol.GroupMember, error)

func (*SQLite) HasOrgKey

func (s *SQLite) HasOrgKey(context.Context, string) (bool, error)

func (*SQLite) Human

func (s *SQLite) Human(id string) (protocol.Principal, error)

func (*SQLite) Item

func (s *SQLite) Item(id string) (protocol.Item, error)

func (*SQLite) ItemByName

func (s *SQLite) ItemByName(orgID, name string) (protocol.Item, error)

func (*SQLite) ListAgents

func (s *SQLite) ListAgents() ([]protocol.Principal, error)

func (*SQLite) ListGrants

func (s *SQLite) ListGrants() ([]protocol.Grant, error)

func (*SQLite) ListGroups

func (s *SQLite) ListGroups() ([]protocol.Group, error)

func (*SQLite) ListHumans

func (s *SQLite) ListHumans() ([]protocol.Principal, error)

func (*SQLite) ListItems

func (s *SQLite) ListItems() ([]protocol.Item, error)

func (*SQLite) ListRequests

func (s *SQLite) ListRequests(orgID string, status protocol.RequestStatus, now time.Time) ([]protocol.ApprovalRequest, error)

func (*SQLite) ListSessions

func (s *SQLite) ListSessions() ([]protocol.Session, error)

func (*SQLite) LiveApproval

func (s *SQLite) LiveApproval(grantID string, now time.Time) (*protocol.Approval, error)

func (*SQLite) MarkHeartbeat

func (s *SQLite) MarkHeartbeat(string) error

MarkHeartbeat: sqlite has no ops_heartbeat table — the monitor is a postgres deployment concern.

func (*SQLite) MarkUsageReported

func (s *SQLite) MarkUsageReported(orgID string, window time.Time, amount int64) error

func (*SQLite) OpenRecoveryWrap

func (s *SQLite) OpenRecoveryWrap(context.Context, string, protocol.Owner, []byte) ([]byte, error)

func (*SQLite) OrgByBillingCustomer

func (s *SQLite) OrgByBillingCustomer(customerID string) (string, error)

func (*SQLite) PlantHuman

func (s *SQLite) PlantHuman(p protocol.Principal) (bool, error)

PlantHuman is the provisioning anchor — insert-if-absent, never overwrite.

func (*SQLite) PurgeOrg

func (s *SQLite) PurgeOrg(ctx context.Context, orgID string) (PurgeReport, error)

PurgeOrg deletes every vault row owned by orgID in one transaction — the sqlite schema has no org_keys/recovery_wraps (encryption is file-local). Audit rows survive deliberately: teardown must not erase the record.

func (*SQLite) PushDevices

func (s *SQLite) PushDevices(orgID string) ([]protocol.PushDevice, error)

func (*SQLite) PutAgent

func (s *SQLite) PutAgent(p protocol.Principal, events ...protocol.AuditEvent) error

func (*SQLite) PutApproval

func (s *SQLite) PutApproval(a protocol.Approval) error

func (*SQLite) PutGrant

func (s *SQLite) PutGrant(g protocol.Grant, events ...protocol.AuditEvent) error

func (*SQLite) PutGroup

func (s *SQLite) PutGroup(g protocol.Group, events ...protocol.AuditEvent) error

func (*SQLite) PutHuman

func (s *SQLite) PutHuman(p protocol.Principal) error

func (*SQLite) PutItem

func (s *SQLite) PutItem(item protocol.Item, secret Secret, events ...protocol.AuditEvent) error

func (*SQLite) PutPushDevice

func (s *SQLite) PutPushDevice(d protocol.PushDevice) error

PutPushDevice upserts a registered push endpoint — tokens rotate, so re-registration overwrites platform/label/stamp in place.

func (*SQLite) PutSession

func (s *SQLite) PutSession(sess protocol.Session, secretHash []byte, events ...protocol.AuditEvent) error

func (*SQLite) PutWorkload

func (s *SQLite) PutWorkload(w protocol.Workload, events ...protocol.AuditEvent) error

func (*SQLite) RecoverOrgKey

func (s *SQLite) RecoverOrgKey(context.Context, string, protocol.Owner, []byte) error

func (*SQLite) RemoveGroupMember

func (s *SQLite) RemoveGroupMember(groupID string, mb protocol.GroupMember, events ...protocol.AuditEvent) error

func (*SQLite) RenewSession

func (s *SQLite) RenewSession(id string, at time.Time, events ...protocol.AuditEvent) (protocol.Session, error)

func (*SQLite) Request

func (s *SQLite) Request(id string) (protocol.ApprovalRequest, error)

func (*SQLite) ReseedOrgKey

func (s *SQLite) ReseedOrgKey(context.Context, string, []byte) error

func (*SQLite) ResolveRequest

func (s *SQLite) ResolveRequest(id string, status protocol.RequestStatus, humanID, approvalID string, at time.Time) (protocol.ApprovalRequest, bool, error)

func (*SQLite) RestoreVersion

func (s *SQLite) RestoreVersion(itemID string, versionID int64) error

func (*SQLite) RevokeAgent

func (s *SQLite) RevokeAgent(id string, at time.Time, audit ...protocol.AuditEvent) error

func (*SQLite) RevokeSession

func (s *SQLite) RevokeSession(id string, at time.Time, events ...protocol.AuditEvent) error

func (*SQLite) RotateKEK

func (s *SQLite) RotateKEK(context.Context, []byte) error

func (*SQLite) RotateOrgKey

func (s *SQLite) RotateOrgKey(context.Context, string) error

func (*SQLite) Secret

func (s *SQLite) Secret(id string) (Secret, error)

func (*SQLite) SessionByHash

func (s *SQLite) SessionByHash(secretHash []byte) (protocol.Session, error)

func (*SQLite) SessionByID

func (s *SQLite) SessionByID(id string) (protocol.Session, error)

func (*SQLite) SetBilling

func (s *SQLite) SetBilling(ob OrgBilling) error
func (s *SQLite) SetBillingLink(orgID, customerID, billingAccountID string) error

func (*SQLite) StoreRecoveryWrap

func (s *SQLite) StoreRecoveryWrap(context.Context, string, protocol.Owner, []byte, time.Time) error

func (*SQLite) Sweep

func (s *SQLite) Sweep(olderThan time.Time) (SweepReport, error)

func (*SQLite) Usage

func (s *SQLite) Usage(orgID string, window time.Time) (int64, error)

func (*SQLite) UsageReportPending

func (s *SQLite) UsageReportPending(limit int) ([]UsageReportRow, error)

func (*SQLite) UseAuth

func (s *SQLite) UseAuth(agentID, itemID string, now time.Time) (UseAuth, error)

func (*SQLite) UseAuthSession

func (s *SQLite) UseAuthSession(sessionHash []byte, itemID string, now time.Time) (UseAuth, error)

func (*SQLite) Versions

func (s *SQLite) Versions(itemID string) ([]protocol.ItemVersion, error)

func (*SQLite) WatchRequests

func (s *SQLite) WatchRequests(ctx context.Context, orgID string) <-chan struct{}

WatchRequests ticks on approval-request changes for orgID — see Store.

func (*SQLite) Workload

func (s *SQLite) Workload(issuer, subject string) (*protocol.Workload, error)

func (*SQLite) WorkloadsForAgent

func (s *SQLite) WorkloadsForAgent(agentID string) ([]protocol.Workload, error)

func (*SQLite) WorkloadsForIssuer

func (s *SQLite) WorkloadsForIssuer(issuer string) ([]protocol.Workload, error)

type Secret

type Secret []byte

Secret is vault material. It never lives on protocol types.

type Store

type Store interface {
	// Mutators take optional audit events: when passed, the write and its
	// event commit in one transaction — an administration write can never
	// land unaudited (VEIL-86). Callers that omit them get the write only.
	PutAgent(protocol.Principal, ...protocol.AuditEvent) error
	Agent(id string) (protocol.Principal, error)
	ListAgents() ([]protocol.Principal, error)
	// RevokeAgent sets RevokedAt on the agent. It is idempotent and preserves
	// the earliest revocation time. It returns ErrNotFound if the agent does not exist.
	// If one or more audit events are provided, they are appended atomically with
	// the revocation in the same store transaction.
	RevokeAgent(id string, at time.Time, audit ...protocol.AuditEvent) error

	PutHuman(protocol.Principal) error
	// PlantHuman inserts a humans row only if the id is absent — the
	// provisioning anchor that makes signup idempotent. Returns true when
	// this call created the row.
	PlantHuman(protocol.Principal) (bool, error)
	Human(id string) (protocol.Principal, error)
	ListHumans() ([]protocol.Principal, error)

	// EnsureOrgKey seals master as the org's org_keys row if absent; an
	// existing row under a different master fails ErrOrgKeyMismatch.
	// HasOrgKey reports whether the row exists. Single-key stores (sqlite,
	// memory) cover every org by construction.
	EnsureOrgKey(ctx context.Context, orgID string, master []byte) error
	HasOrgKey(ctx context.Context, orgID string) (bool, error)

	// RotateOrgKey mints a fresh org master and rewraps every owner DEK
	// under it (item ciphertexts are untouched). RotateKEK rewraps every
	// org master under newKEK. Single-key stores have no rotation surface
	// and return ErrUnsupported.
	RotateOrgKey(ctx context.Context, orgID string) error
	RotateKEK(ctx context.Context, newKEK []byte) error

	// StoreRecoveryWrap seals the org master under owner-held recoveryKey —
	// KEK-independent escrow for lost devices or a lost deployment KEK.
	// OpenRecoveryWrap verifies recoveryKey and returns the master; it is
	// single-use (used_at stamps on first open) and fails closed on wrong
	// material, expiry, or replay. ReseedOrgKey re-anchors that master under
	// the current KEK after the old KEK is lost. Single-key stores return
	// ErrUnsupported.
	StoreRecoveryWrap(ctx context.Context, orgID string, o protocol.Owner, recoveryKey []byte, expiresAt time.Time) error
	OpenRecoveryWrap(ctx context.Context, orgID string, o protocol.Owner, recoveryKey []byte) ([]byte, error)
	ReseedOrgKey(ctx context.Context, orgID string, master []byte) error
	// RecoverOrgKey opens the owner's recovery wrap, re-wraps the recovered
	// master under this store's KEK, and marks the wrap used — atomically,
	// in one transaction, so a failed reseed cannot burn the wrap. It is the
	// safe composition of OpenRecoveryWrap + ReseedOrgKey; prefer it.
	RecoverOrgKey(ctx context.Context, orgID string, o protocol.Owner, recoveryKey []byte) error

	PutItem(protocol.Item, Secret, ...protocol.AuditEvent) error
	Item(id string) (protocol.Item, error)
	ItemByName(orgID, name string) (protocol.Item, error)
	ListItems() ([]protocol.Item, error)
	ArchiveItem(id string, events ...protocol.AuditEvent) error
	DeleteItem(id string, events ...protocol.AuditEvent) error
	Versions(itemID string) ([]protocol.ItemVersion, error)
	RestoreVersion(itemID string, versionID int64) error
	// Secret is for the broker only. There is no agent-facing reveal.
	Secret(id string) (Secret, error)
	// UseAuth returns the agent, item, grant, and live approval for a Use
	// request in a single round trip. It never returns a secret.
	UseAuth(agentID, itemID string, now time.Time) (UseAuth, error)
	// UseAuthSession is the same as UseAuth but resolves a session by its
	// secret hash first. It read-only validates the session is not expired,
	// revoked, or exhausted and then joins the authorization metadata. It does
	// not consume a use; the broker calls ConsumeSession after the pre-secret
	// authorization gates. If the session is missing, expired, revoked,
	// exhausted, or maps to a missing agent, it returns ErrNotFound,
	// ErrSessionExpired, ErrSessionRevoked, or ErrDenied.
	UseAuthSession(sessionHash []byte, itemID string, now time.Time) (UseAuth, error)

	// ConsumeSession atomically verifies the session is still valid (not
	// expired, revoked, or exhausted), that the bound agent has not been
	// revoked, and increments Uses. It returns the current agent principal on
	// success. It must be called only after all pre-secret authorization
	// checks have passed. It is the final revocation race guard for session
	// token Use calls.
	ConsumeSession(sessionHash []byte, now time.Time) (protocol.Principal, error)

	// ConsumeSessionAudited is ConsumeSession plus the audit event appended in
	// the same transaction: the consume and the audit row commit together or
	// not at all. e's OrgID/AgentID are overwritten with the consumed agent's
	// identity before insert, so callers may leave them unset. The broker uses
	// this on the allow path so an allow can never release a credential
	// without its audit row already durable.
	ConsumeSessionAudited(sessionHash []byte, now time.Time, e protocol.AuditEvent) (protocol.Principal, error)

	SessionByID(id string) (protocol.Session, error)
	RevokeSession(id string, at time.Time, events ...protocol.AuditEvent) error
	RenewSession(id string, at time.Time, events ...protocol.AuditEvent) (protocol.Session, error)

	PutGrant(protocol.Grant, ...protocol.AuditEvent) error
	Grant(id string) (*protocol.Grant, error)
	GrantFor(agentID, itemID string) (*protocol.Grant, error)
	ListGrants() ([]protocol.Grant, error)

	// Groups are vault data (VEIL-20): an org-owned item plus a grant to a
	// group is the shared-vault shape. PutGroup upserts by id; the name is
	// unique per org. Membership is idempotent — adding an existing member
	// is a no-op, removing an absent one succeeds.
	PutGroup(protocol.Group, ...protocol.AuditEvent) error
	Group(id string) (protocol.Group, error)
	ListGroups() ([]protocol.Group, error)
	AddGroupMember(groupID string, m protocol.GroupMember, events ...protocol.AuditEvent) error
	RemoveGroupMember(groupID string, m protocol.GroupMember, events ...protocol.AuditEvent) error
	GroupMembers(groupID string) ([]protocol.GroupMember, error)
	// GroupIDsFor resolves the distinct groups holding any of the passed
	// members — a principal passes its MemberKeys (itself plus, for a
	// user-owned agent, the owning human).
	GroupIDsFor(members []protocol.GroupMember) ([]string, error)

	PutApproval(protocol.Approval) error
	LiveApproval(grantID string, now time.Time) (*protocol.Approval, error)

	// FileRequest records an open approval request for (grant, action) in
	// one transaction: a stale open on the same key is expired first
	// (ExpiredID names it), a live one is returned unchanged — Created=false
	// means the ask was already on file and must not re-notify owners.
	FileRequest(protocol.ApprovalRequest) (FileOutcome, error)
	Request(id string) (protocol.ApprovalRequest, error)
	// ListRequests returns org requests; status open lists only unexpired.
	ListRequests(orgID string, status protocol.RequestStatus, now time.Time) ([]protocol.ApprovalRequest, error)
	// ResolveRequest flips an open, unexpired request to a terminal status —
	// first write wins; won=false means it was already resolved or expired.
	ResolveRequest(id string, status protocol.RequestStatus, humanID, approvalID string, at time.Time) (req protocol.ApprovalRequest, won bool, err error)
	// ApproveRequest resolves ONE open ask by minting its grant's approval:
	// conditional resolve + approval insert + sibling asks resolve, all in
	// one transaction — and only while the ask AND its grant are live.
	// won=false means the ask was resolved, expired, or its grant died —
	// nothing was written, so a lost race leaves no side effects.
	// resolved[0] is the ask named by id; the rest are siblings the same
	// grant-approval answered.
	ApproveRequest(id string, appr protocol.Approval, at time.Time) (resolved []protocol.ApprovalRequest, won bool, err error)
	// ApproveGrant mints a grant-level approval and resolves every open ask
	// on it in one transaction — grant-scoped `veil approve`.
	ApproveGrant(grantID string, appr protocol.Approval, at time.Time) (resolved []protocol.ApprovalRequest, err error)
	CancelRequestsForAgent(agentID string, at time.Time) error
	CancelRequestsForItem(itemID string, at time.Time) error
	// ExpireStaleRequests marks open requests past expiry as expired and
	// returns the rows it marked — the sweep audits request_expired per row.
	ExpireStaleRequests(now time.Time) ([]protocol.ApprovalRequest, error)
	// WatchRequests returns a channel that ticks when approval requests for
	// orgID change — filed, resolved, expired, or cancelled. Ticks carry no
	// data: refetch the list. The channel closes when ctx ends.
	WatchRequests(ctx context.Context, orgID string) <-chan struct{}

	PutWorkload(protocol.Workload, ...protocol.AuditEvent) error
	Workload(issuer, subject string) (*protocol.Workload, error)
	WorkloadsForIssuer(issuer string) ([]protocol.Workload, error)
	WorkloadsForAgent(agentID string) ([]protocol.Workload, error)
	DeleteWorkload(issuer, subject string, events ...protocol.AuditEvent) error

	PutSession(s protocol.Session, secretHash []byte, events ...protocol.AuditEvent) error
	SessionByHash(secretHash []byte) (protocol.Session, error)
	ListSessions() ([]protocol.Session, error)

	AppendAudit(protocol.AuditEvent) error
	AppendAudits([]protocol.AuditEvent) error
	Audit() ([]protocol.AuditEvent, error)
	// AuditFeed returns an org's committed audit events with row id >
	// afterID in id order — the per-org SIEM export cursor. Committed rows
	// only: events still queued in the outbox join the feed on relay with a
	// fresh id, so a consumer that checkpoints on the last returned id never
	// misses and never double-reads.
	AuditFeed(orgID string, afterID int64, limit int) ([]protocol.AuditFeedEvent, error)

	// Billing returns the org's billing state; an absent row is Plan "free".
	Billing(orgID string) (OrgBilling, error)
	// SetBilling upserts the org's billing state — the billing webhook
	// receiver is the writer.
	SetBilling(OrgBilling) error
	// SetBillingLink upserts only the billing link (customer + billing
	// account). Plan and UpdatedAt belong to the webhook receiver — link
	// writes must not disturb the staleness anchor.
	SetBillingLink(orgID, customerID, billingAccountID string) error
	// OrgByBillingCustomer resolves the org that owns a billing customer id
	// (Vortex cus_…), ErrNotFound when unlinked.
	OrgByBillingCustomer(customerID string) (string, error)
	// ConsumeUse atomically increments the org's counter for window and
	// reports whether the claim is within cap (cap <= 0 means unlimited —
	// the counter still accrues). Over-cap claims count too: blocked demand
	// is signal. Every claim lands exactly once, safe under concurrency.
	ConsumeUse(orgID string, window time.Time, cap int64) (used int64, ok bool, err error)
	// UsageReportPending returns the usage deltas the billing flusher has
	// not yet reported: rows where used exceeds the reported watermark.
	UsageReportPending(limit int) ([]UsageReportRow, error)
	// MarkUsageReported advances the reported watermark by amount, clamped
	// to used — over-marks (double flush, racing claims) never push the
	// watermark past the counter.
	MarkUsageReported(orgID string, window time.Time, amount int64) error
	// Usage reads the org's counter for window; absent rows read 0.
	Usage(orgID string, window time.Time) (int64, error)
	// FlushAuditOutbox relays queued audit events into the audit table.
	// Postgres queues events that fail the direct write so a transient
	// outage cannot lose them; stores without an outbox report 0.
	FlushAuditOutbox(limit int) (int, error)
	// MarkHeartbeat stamps the named job's liveness beat in ops_heartbeat —
	// the monitor pages when a beat goes stale. Stores without the ops
	// table no-op.
	MarkHeartbeat(name string) error

	// Push devices — the registered phone endpoints for approval wake-ups
	// and ops pages. Upsert on Put (re-registration is routine; tokens
	// rotate); a send that returns "token dead" prunes via Delete.
	PutPushDevice(d protocol.PushDevice) error
	PushDevices(orgID string) ([]protocol.PushDevice, error)
	DeletePushDevice(orgID, token string) error

	// Sweep deletes terminally-expired rows (sessions past expiry or revoked,
	// grants and approvals past expiry) older than the cutoff. It keeps the
	// hot-path indexes bounded; expiry semantics are unaffected because
	// expired rows are already invisible to authorization queries.
	Sweep(olderThan time.Time) (SweepReport, error)
	Close() error
}

type SweepReport

type SweepReport struct {
	Sessions  int64
	Grants    int64
	Approvals int64
	Requests  int64
}

SweepReport counts rows deleted by a Sweep — Requests marks, not deletes.

func SweepPostgres

func SweepPostgres(ctx context.Context, db sqlc.DBTX, before time.Time) (SweepReport, error)

SweepPostgres deletes terminally-expired rows older than before: sessions past expiry or revoked, and grants/approvals past expiry. Open asks past their own TTL mark expired and each expiry writes a request_expired audit event. It takes a bare DBTX so callers that never touch ciphertext (e.g. `veil sweep`) do not need the master key.

When db can open a transaction (pool, conn) the whole sweep runs in one: request expirations and their audit rows commit together or not at all — a mid-sweep crash can never strand an expired ask with no audit line. Each audit insert runs under a savepoint so a failed insert falls back to audit_outbox inside the same transaction instead of aborting it. A caller-passed pgx.Tx is already atomic and gets the same treatment; a DBTX that cannot begin a transaction runs autocommitted with the per-row outbox fallback.

func SweepSQLite

func SweepSQLite(db *sql.DB, before time.Time) (SweepReport, error)

SweepSQLite deletes terminally-expired rows older than before: sessions past expiry or revoked, and grants/approvals past expiry. Session expires_at is a unix epoch integer while revoked_at is RFC3339 text — the encodings match the write paths. It takes a bare *sql.DB so callers that never touch ciphertext (e.g. `veil sweep`) do not need the master key.

type UsageReportRow

type UsageReportRow struct {
	OrgID            string
	WindowStart      time.Time
	Used             int64
	Reported         int64
	CustomerID       string
	BillingAccountID string
}

UsageReportRow is one pending usage delta for the billing flusher: the locally metered units not yet reported to the billing provider. The billing link fields are empty when the org has no billing row yet.

type UseAuth

type UseAuth struct {
	Agent    protocol.Principal
	Item     protocol.Item
	Grant    *protocol.Grant
	Approval *protocol.Approval
	Groups   []string
}

UseAuth is the consolidated authorization snapshot for a single Use call. It is returned by Store.UseAuth in one round trip and contains no secret. Groups is the agent's resolved group set — the ids the group-grant leg of the lookup already matched against.

type WalSlot

type WalSlot struct {
	Name   string
	Active bool
	Status string
}

WalSlot is one replication slot's server-side liveness — the multi-slot view for monitor: primary + standby archivers each own a pinned slot.

func WalSlots

func WalSlots(ctx context.Context, pool *pgxpool.Pool) ([]WalSlot, error)

WalSlots lists every archive slot (wal_archive, wal_archive_dr, …). The monitor pages when none is active or any shows wal_status='lost'.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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