postgres

package
v1.6.3 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2026 License: MIT Imports: 74 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.

README

internal/infrastructure/postgres — SQL store

Postgres persistence, replicating the stroppy-cloud / komeet pipeline: pgx v5 + pgtx (tx manager) + bob (query builder) + the sqld codegen toolchain. No ORM. Each record type is one table with envelope columns (id, project_id, created_at, updated_at, secondary keys) plus the domain object in a data jsonb column.

Layout

Path Role
schema.sql Authoritative schema — sqld reads it to generate code + the bootstrap migration.
queries/*.sql Named queries (-- name: X :exec|:one|:many|:execrows, @param).
migrations/ go:embed-ed SQL migrations + migrations.go.
gen/db/ sqld-gen-go output: models.go, queries.go (typed query funcs).
gen/bob/models/ sqld-gen-bob output: bob query builders per table.
sqld.yaml Codegen + migration config.
db.go Connection bundle: pool + tx manager + ctx-aware TxDB + bob pool.
migrate.go Migrate() applies the embedded migrations at startup.
bobexec.go Adapts the tx-aware executor to bob.Executor.
helpers.go JSON marshal/unmarshal, pg error → ErrNotFound/ErrConflict, uuid.
store.go Store façade; typed repos added per domain entity.

Generated code (gen/) and migrations are committed. bin/ (the sqld tools) is git-ignored.

Workflow

make tools             # install sqld, sqld-gen-go, sqld-gen-bob into ./bin
make db-gen            # regenerate gen/db + gen/bob from schema.sql + queries
make migrate-generate name=add_x   # incremental migration by schema diff
make migrate-clear     # rebuild the single bootstrap migration, then db-gen
make test-db           # DB-backed tests (auto-starts the compose postgres :5436)

Transactions

Services open a transaction with tx.Do* (pgtx); repo calls inside it issue SQL through db.q() / db.Bobx(), both bound to the ctx-aware TxDB, so they run in that transaction. Outside one they auto-commit on the pool.

The two seed tables (iam_users, iam_sessions) are representative; real IAM tables and repos are added as the domain is designed.

Documentation

Overview

Package postgres is the Postgres-backed persistence for IAM: a hand-written pgx + pgtx + bob layer following the komeet pattern — a single *pgxpool.Pool, a pgtx transaction manager (tx.Trm) services use to run repo calls inside an ambient transaction, a ctx-aware TxDB executor, and a bob pool for typed query building.

Storage model: each record type maps to a table mirroring the queryable envelope columns (id, project_id, created_at, updated_at, plus any secondary keys) with the full domain object stored as a `data jsonb` column. Reads map pgx.ErrNoRows onto a domain not-found; unique violations onto a conflict.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFound error = domain.ErrNotFound
	ErrConflict       = errors.New("conflict")
)

ErrNotFound / ErrConflict are the storage-level sentinels the service layer translates to its API errors. (IAM has no proto layer; records are stored as plain JSON in the `data` column.)

ErrNotFound aliases domain.ErrNotFound so that an adapter which surfaces a no-rows result (directly or wrapped via translatePgErr) renders as a 404 at the API boundary instead of being masked as a 500 — errors.As in the ogen NewError hook finds the *domain.Error through the wrap. errors.Is checks against this sentinel keep working unchanged since it is the same value.

Functions

func DeliverBackchannelLogout added in v1.6.0

func DeliverBackchannelLogout(
	ctx context.Context, db *DB, client *http.Client, projectID, env, sessionID, subject string,
) error

DeliverBackchannelLogout notifies every relying party holding a grant on the ended session. Delivery is best-effort per RP — one unreachable client must not stop the others — and the caller (the outbox) retries the batch.

func NewAuditingEmitter added in v1.6.0

func NewAuditingEmitter(db *DB, inner Emitter) *auditingEmitter

NewAuditingEmitter wraps inner so privileged mutations are audited.

func NewAuthenticator

func NewAuthenticator(db *DB, masterKey string) *pgAuthenticator

NewAuthenticator builds the Postgres-backed Authenticator. masterKey is the platform operator credential (empty disables the masterKey scheme).

func NewConfigReader added in v1.3.0

func NewConfigReader(db *DB, ttl time.Duration) *configReader

NewConfigReader builds the shared runtime config reader. ttl<=0 defaults to 30s.

func NewOutboundHTTPClient added in v1.6.0

func NewOutboundHTTPClient(timeout time.Duration) *http.Client

newWebhookHTTPClient builds the delivery client with SSRF protection: a dialer Control hook rejects connections whose resolved IP is private, link-local, unique-local, CGNAT, unspecified or multicast — so a webhook URL (or a redirect it returns) cannot be used to reach cloud metadata (169.254.169.254), internal services, or the cluster network. The check runs at connect time on the actually-resolved IP, closing the DNS-rebinding TOCTOU that host-string validation alone leaves open. Loopback stays reachable as the documented http-development escape hatch (see validateWebhookURL). Redirects are capped. NewOutboundHTTPClient exposes the hardened outbound client (SSRF guards, redirect limits, fixed timeout) to other outbound senders in this service, so a second delivery path cannot quietly be less careful than webhooks.

func NewOutboxEmitter

func NewOutboxEmitter(ob *outbox.Outbox) *outboxEmitter

NewOutboxEmitter builds the outbox-backed Emitter over an initialized *outbox.Outbox (constructed with db.TxDB as its enqueue executor).

func NewPgAccountStore

func NewPgAccountStore(db *DB, emitter Emitter) *pgAccountStore

NewPgAccountStore builds the Postgres-backed AccountStore.

func NewPgAdminAPIKeys

func NewPgAdminAPIKeys(db *DB, emitter Emitter) *pgAdminAPIKeys

NewPgAdminAPIKeys constructs the adapter over an open *DB.

func NewPgAdminAccessRequests

func NewPgAdminAccessRequests(db *DB, emitter Emitter) *pgAdminAccessRequests

NewPgAdminAccessRequests builds the Postgres-backed AdminAccessRequests adapter.

func NewPgAdminApps

func NewPgAdminApps(db *DB, emitter Emitter) *pgAdminApps

NewPgAdminApps builds the Postgres-backed AdminApps adapter.

func NewPgAdminConfig

func NewPgAdminConfig(db *DB, emitter Emitter, cfg *configReader) *pgAdminConfig

NewPgAdminConfig builds the Postgres-backed AdminConfig adapter. cfg should be the same reader instance the runtime (flows, invites, platform) reads through; nil disables cache invalidation (changes propagate within the TTL).

func NewPgAdminConnections

func NewPgAdminConnections(db *DB, emitter Emitter) *pgAdminConnections

NewPgAdminConnections builds the Postgres-backed AdminConnections adapter.

func NewPgAdminKeys

func NewPgAdminKeys(db *DB, emitter Emitter) *pgAdminKeys

NewPgAdminKeys builds the Postgres-backed AdminKeys adapter.

func NewPgAdminServiceAccounts

func NewPgAdminServiceAccounts(db *DB, emitter Emitter) *pgAdminServiceAccounts

NewPgAdminServiceAccounts builds the Postgres-backed AdminServiceAccounts adapter.

func NewPgAdminUsers

func NewPgAdminUsers(db *DB, emitter Emitter) *pgAdminUsers

NewPgAdminUsers builds the Postgres-backed AdminUsers adapter.

func NewPgAudit added in v1.6.0

func NewPgAudit(db *DB, emitter Emitter) *pgAudit

NewPgAudit builds the audit adapter.

func NewPgCoreAuth

func NewPgCoreAuth(db *DB, emitter Emitter, cfg *configReader) *pgCoreAuth

NewPgCoreAuth builds the Postgres-backed Core Auth adapter. cfg is the shared runtime config reader used to resolve password_policy / session_policy at request time; a nil cfg falls back to a fresh default-TTL reader so the adapter is usable in isolation (e.g. tests).

func NewPgCoreAuthFlows added in v1.1.0

func NewPgCoreAuthFlows(db *DB, emitter Emitter, accounts api.CoreAuthAccounts, cfg *configReader) *pgCoreAuthFlows

NewPgCoreAuthFlows builds the flow adapter. accounts must be the same pgCoreAuth adapter already registered for the CoreAuth group. cfg is the shared runtime config reader (registration policy lives in the auth doc); a nil cfg falls back to a fresh default-TTL reader.

func NewPgFederationConnections

func NewPgFederationConnections(db *DB, emitter Emitter) *pgFederationConnections

NewPgFederationConnections builds the Postgres-backed FederationConnections adapter.

func NewPgFederationRuntime

func NewPgFederationRuntime(db *DB, emitter Emitter, cfg *configReader) *pgFederationRuntime

NewPgFederationRuntime builds the Postgres-backed FederationRuntime adapter.

func NewPgFederationScim

func NewPgFederationScim(db *DB, emitter Emitter) *pgFederationScim

NewPgFederationScim builds the Postgres-backed FederationScim adapter.

func NewPgHooks added in v1.6.0

func NewPgHooks(db *DB, emitter Emitter) *pgHooks

NewPgHooks builds the hooks adapter with an SSRF-guarded delivery client.

func NewPgInvites added in v1.2.0

func NewPgInvites(db *DB, emitter Emitter, cfg *configReader) *pgInvites

NewPgInvites builds the invite adapter. cfg reads the auth doc for the member-invite default policy; nil falls back to a default-TTL reader.

func NewPgJobs added in v1.6.0

func NewPgJobs(db *DB, emitter Emitter) *pgJobs

NewPgJobs builds the jobs adapter.

func NewPgMFAAccounts

func NewPgMFAAccounts(db *DB, emitter Emitter, cfg *configReader) *pgMFAAccounts

NewPgMFAAccounts builds the MFA aggregate adapter over a *DB. cfg resolves the project's session_policy when minting a verified session; a nil cfg falls back to default TTLs (see NewPgCoreAuth).

func NewPgOAuthSocial

func NewPgOAuthSocial(db *DB, emitter Emitter, cfg *configReader) *pgOAuthSocial

NewPgOAuthSocial builds the OAuthSocial adapter over the connection bundle. cfg resolves the project's session_policy when minting a login session; a nil cfg falls back to default TTLs (see NewPgCoreAuth).

func NewPgOIDCGrants

func NewPgOIDCGrants(db *DB, emitter Emitter, cfg *configReader) *pgOIDCGrants

NewPgOIDCGrants builds the OIDC-provider adapter over db.

func NewPgPasswordlessAccounts

func NewPgPasswordlessAccounts(db *DB, emitter Emitter, cfg *configReader, core *pgCoreAuth) *pgPasswordlessAccounts

NewPgPasswordlessAccounts builds the Passwordless adapter over db. cfg is the runtime config reader used to enforce registration mode and consent gating on auto-provisioned passwordless signups; core mints sessions through the shared path so passwordless logins honor session_policy and get a rotatable refresh token.

func NewPgPlatform

func NewPgPlatform(db *DB) *pgPlatform

NewPgPlatform builds the Postgres-backed PlatformConfig adapter.

func NewPgRateLimits added in v1.3.0

func NewPgRateLimits(db *DB) *pgRateLimits

NewPgRateLimits builds the Postgres-backed RateLimitConfigReader adapter.

func NewPgRisk added in v1.6.0

func NewPgRisk(db *DB, emitter Emitter) *pgRisk

NewPgRisk builds the risk adapter.

func NewPgRoles added in v1.6.0

func NewPgRoles(db *DB, emitter Emitter) *pgRoles

NewPgRoles builds the role-assignment adapter over db.

func NewPgTestMode added in v1.6.0

func NewPgTestMode(db *DB, emitter Emitter) *pgTestMode

NewPgTestMode builds the test-mode adapter.

func NewPgWebAuthnAccounts

func NewPgWebAuthnAccounts(db *DB, emitter Emitter, cfg *configReader) *pgWebAuthnAccounts

NewPgWebAuthnAccounts builds the WebAuthn adapter. cfg resolves the project's session_policy when minting a verified session; a nil cfg falls back to default TTLs (see NewPgCoreAuth).

Types

type BackchannelLogoutTarget added in v1.6.0

type BackchannelLogoutTarget struct {
	ClientID string
	URI      string
}

BackchannelLogoutTarget is one relying party to notify.

type Cipher

type Cipher interface {
	// Encrypt returns the enc:v1 ciphertext of plaintext.
	Encrypt(plaintext string) (string, error)
	// Decrypt returns the plaintext for an enc:v1 value, or the input unchanged
	// when it is legacy plaintext (no enc: prefix).
	Decrypt(value string) (string, error)
}

Cipher encrypts and decrypts reversible secrets at rest.

func NewCipher

func NewCipher(keyB64 string) (Cipher, error)

NewCipher builds an AES-256-GCM Cipher from a base64-encoded 32-byte key. An empty key yields the identity (passthrough) cipher.

func NewIdentityCipher

func NewIdentityCipher() Cipher

NewIdentityCipher returns a passthrough Cipher (no encryption).

type ConnectOption

type ConnectOption func(*connectOptions)

ConnectOption customizes Postgres connection instrumentation.

func WithLogger

func WithLogger(logger *xlog.Logger) ConnectOption

WithLogger routes pgx query logs through xlog.

func WithMetrics

func WithMetrics(enabled bool) ConnectOption

WithMetrics registers OpenTelemetry metrics for the pgx pool.

func WithQueryLogLevel

func WithQueryLogLevel(level string) ConnectOption

WithQueryLogLevel overrides the pgx query log level.

type DB

type DB struct {
	Pool      *pgxpool.Pool
	TxManager pgtxlib.Trm
	TxDB      pgtxlib.DB
	Bob       bobpgx.Pool
	// Cipher encrypts reversible secrets at rest (signing-key PEMs, TOTP secrets).
	// Defaults to a passthrough cipher; cmd installs a real one via UseCipher.
	Cipher Cipher
	// PublicURL is the absolute base URL this deployment is reachable at, with no
	// trailing slash (service.http.public_url). Adapters build the OIDC issuer and
	// every advertised absolute URL from it; cmd installs it via UsePublicURL
	// after config validation, so it is never empty in a running server.
	PublicURL string
}

DB is the Postgres connection bundle: the raw pool, the pgtx transaction manager services run repo calls through, the ctx-aware TxDB executor (picks up the ambient transaction from ctx) and a bob pool over the same pool.

func Connect

func Connect(ctx context.Context, dsn string, opts ...ConnectOption) (*DB, error)

Connect opens a pgx pool against dsn and builds the tx manager / executors.

func (*DB) Bobx

func (db *DB) Bobx() bob.Executor

Bobx returns a bob.Executor over the ctx-aware TxDB (tx-aware).

func (*DB) Close

func (db *DB) Close()

Close releases the underlying pool.

func (*DB) Migrate

func (db *DB) Migrate(ctx context.Context) error

Migrate applies the embedded SQL migrations against the pool. It needs a live Postgres connection.

func (*DB) Ping

func (db *DB) Ping(ctx context.Context) error

Ping verifies connectivity.

func (*DB) RunGarbageCollector added in v1.6.0

func (db *DB) RunGarbageCollector(ctx context.Context, interval time.Duration, log *xlog.Logger)

RunGarbageCollector periodically deletes expired runtime rows. It runs one sweep shortly after start (to trim any backlog a fresh deploy inherits) and then every interval, and blocks until ctx is cancelled. Wire it as a background worker alongside the outbox relay.

func (*DB) RunJobsWorker added in v1.6.0

func (db *DB) RunJobsWorker(ctx context.Context, interval time.Duration, log *xlog.Logger)

RunJobsWorker drains pending async jobs (audit exports, user imports) one at a time and runs them to completion. Blocks until ctx is cancelled. Wire it as a background worker alongside the GC and webhook-retry workers.

func (*DB) Signer

func (db *DB) Signer() *Signer

Signer returns the JWT signer for this connection bundle.

func (*DB) Store

func (db *DB) Store() *Store

Store returns the typed-repo façade over this connection bundle.

func (*DB) Trm

func (db *DB) Trm() pgtxlib.Trm

Trm returns the transaction manager services wire into their tx.Trm field so repo calls inside tx.Do* share one transaction.

func (*DB) UseCipher

func (db *DB) UseCipher(c Cipher)

UseCipher installs the at-rest secret cipher (call once after Connect, before serving). A nil cipher is ignored, keeping the passthrough default.

func (*DB) UsePublicURL added in v1.6.0

func (db *DB) UsePublicURL(u string)

UsePublicURL installs the absolute public base URL (call once after Connect, before serving). The value must already be normalized — absolute http(s), no trailing slash; config.Normalize guarantees that. An empty value is ignored so a mis-wired caller cannot silently strip the issuer origin.

type EffectiveAuthConfig added in v1.3.0

type EffectiveAuthConfig struct {
	Methods          []string
	RegistrationMode string
	PasswordStrategy string
	AppBaseURL       string
	DefaultLocale    string
	SupportedLocales []string
	// MemberInvitesEnabled/ MemberInvitesDefaultCap flatten the member_invites
	// doc: false/0 means users may not invite (effective per-user caps resolve
	// in pgInvites via the user-envelope override).
	MemberInvitesEnabled    bool
	MemberInvitesDefaultCap int
}

EffectiveAuthConfig is the runtime view of the auth doc. RegistrationMode=="" preserves the flowAuthConfig contract: empty means open/default.

type EffectiveMFAPolicy added in v1.3.0

type EffectiveMFAPolicy struct {
	RequiredForAdmins bool
	AllowedFactors    []string
	RememberDevice    bool
}

EffectiveMFAPolicy is the runtime view of mfa_policy.

type EffectivePasswordPolicy added in v1.3.0

type EffectivePasswordPolicy struct {
	MinLength      int  // default 8
	ZxcvbnMinScore int  // default 0
	BreachedCheck  bool // default false (write path rejects true today)
	History        int  // default 0
}

EffectivePasswordPolicy is the runtime view of password_policy.

type EffectiveSessionPolicy added in v1.3.0

type EffectiveSessionPolicy struct {
	AccessTTL       time.Duration // default coreAuthAccessTTL (10m)
	RefreshTTL      time.Duration // default coreAuthRefreshTTL (30d)
	IdleTimeout     time.Duration // default 0 = disabled
	AbsoluteTimeout time.Duration // default 0 = disabled
	ReuseDetection  bool          // default false
}

EffectiveSessionPolicy is the runtime view of session_policy. Defaults equal the legacy package constants so an absent doc yields identical token lifetimes.

type Emitter

type Emitter interface {
	Emit(ctx context.Context, ev domain.Event) error
}

Emitter is the port the Postgres adapters use to publish domain events. It is consumed inside the adapters' transactions; see outboxEmitter for the wiring.

type PgMachineIdentities

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

PgMachineIdentities is the Postgres-backed MachineIdentities adapter.

func NewPgMachineIdentities

func NewPgMachineIdentities(db *DB, emitter Emitter) *PgMachineIdentities

NewPgMachineIdentities builds the adapter over a *DB.

func (*PgMachineIdentities) CreateAPIKey

func (a *PgMachineIdentities) CreateAPIKey(ctx context.Context, cmd domain.APIKeyCmd) (*domain.APIKey, string, error)

CreateAPIKey creates an API key and returns the plaintext secret exactly once.

func (*PgMachineIdentities) CreateServiceAccount

func (a *PgMachineIdentities) CreateServiceAccount(
	ctx context.Context, cmd domain.ServiceAccountCmd,
) (*domain.ServiceAccount, error)

CreateServiceAccount creates a service account in the command's project.

func (*PgMachineIdentities) CreateServiceAccountSecret

func (a *PgMachineIdentities) CreateServiceAccountSecret(
	ctx context.Context, cmd domain.MachineIDSecretCmd,
) (*domain.MachineIDSecret, error)

CreateServiceAccountSecret mints a new client secret for a service account. The plaintext secret is returned once; only its sha256 hash is persisted.

func (*PgMachineIdentities) DeleteServiceAccount

func (a *PgMachineIdentities) DeleteServiceAccount(ctx context.Context, projectID, serviceAccountID string) error

DeleteServiceAccount removes a service account in the given project.

func (*PgMachineIdentities) GetServiceAccount

func (a *PgMachineIdentities) GetServiceAccount(
	ctx context.Context, projectID, serviceAccountID string,
) (*domain.ServiceAccount, error)

GetServiceAccount fetches one service account, enforcing the tenant boundary.

func (*PgMachineIdentities) ListAPIKeys

func (a *PgMachineIdentities) ListAPIKeys(ctx context.Context, projectID string) ([]*domain.APIKey, error)

ListAPIKeys returns every API key in a project (tenant-scoped).

func (*PgMachineIdentities) ListServiceAccounts

ListServiceAccounts returns a cursor page of service accounts in a project. The cursor is the id of the last item; rows are ordered by id ascending and one extra row is fetched to compute HasMore.

func (*PgMachineIdentities) MintToken

func (a *PgMachineIdentities) MintToken(ctx context.Context, projectID, serviceAccountID string) (string, error)

MintToken issues a signed RS256 JWT access token (jwx Signer) for a service account, carrying the SA subject + its scopes.

func (*PgMachineIdentities) RevokeAPIKey

func (a *PgMachineIdentities) RevokeAPIKey(ctx context.Context, projectID, keyID string) error

RevokeAPIKey deletes an API key in the given project.

func (*PgMachineIdentities) RevokeServiceAccountSecret

func (a *PgMachineIdentities) RevokeServiceAccountSecret(
	ctx context.Context, projectID, serviceAccountID, secretID string,
) error

RevokeServiceAccountSecret marks a service-account client secret revoked.

func (*PgMachineIdentities) RotateAPIKey

func (a *PgMachineIdentities) RotateAPIKey(
	ctx context.Context, projectID, keyID string,
) (*domain.APIKey, string, error)

RotateAPIKey mints a fresh secret for an existing key and returns the new plaintext exactly once; the prefix and hash columns are replaced.

func (*PgMachineIdentities) UpdateAPIKey

UpdateAPIKey patches API-key metadata / scopes / disabled state.

func (*PgMachineIdentities) UpdateServiceAccount

UpdateServiceAccount patches scopes / disabled state of a service account.

type PgOperator

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

PgOperator persists the operator/project aggregates.

func NewPgOperator

func NewPgOperator(db *DB, emitter Emitter) *PgOperator

NewPgOperator builds the operator adapter.

func (*PgOperator) ApplyConfig

func (a *PgOperator) ApplyConfig(ctx context.Context, cmd domain.OperatorConfigCmd) (map[string]any, error)

func (*PgOperator) CreateEnvironment

func (a *PgOperator) CreateEnvironment(ctx context.Context, cmd domain.EnvironmentCmd) (*domain.Environment, error)

func (*PgOperator) CreateProject

func (a *PgOperator) CreateProject(ctx context.Context, cmd domain.ProjectCmd) (*domain.Project, error)

func (*PgOperator) DeleteEnvironment

func (a *PgOperator) DeleteEnvironment(ctx context.Context, projectID, env string) error

func (*PgOperator) DeleteProject

func (a *PgOperator) DeleteProject(ctx context.Context, projectID string, _ bool) error

func (*PgOperator) ExportConfig

func (a *PgOperator) ExportConfig(ctx context.Context, projectID string) (map[string]any, error)

func (*PgOperator) GetEnvironment

func (a *PgOperator) GetEnvironment(ctx context.Context, projectID, env string) (*domain.Environment, error)

func (*PgOperator) GetFeatures

func (a *PgOperator) GetFeatures(ctx context.Context, projectID string) (map[string]bool, error)

func (*PgOperator) GetProject

func (a *PgOperator) GetProject(ctx context.Context, projectID string) (*domain.Project, error)

GetProject reads + decodes a project row, mapping no-rows to project-not-found.

func (*PgOperator) ListAdminTokens

func (a *PgOperator) ListAdminTokens(ctx context.Context, projectID string) ([]domain.OperatorAdminToken, error)

func (*PgOperator) ListEnvironments

func (a *PgOperator) ListEnvironments(ctx context.Context, projectID string) ([]domain.Environment, error)

func (*PgOperator) ListProjects

func (a *PgOperator) ListProjects(ctx context.Context) ([]domain.Project, error)

func (*PgOperator) MintAdminToken

func (a *PgOperator) MintAdminToken(ctx context.Context, cmd domain.OperatorAdminTokenCmd) (string, time.Time, error)

func (*PgOperator) PlanConfig

func (a *PgOperator) PlanConfig(ctx context.Context, cmd domain.OperatorConfigCmd) (map[string]any, error)

PlanConfig is a read-only diff: it returns the proposed config without persisting it. The current document is loaded for context; the plan echoes the incoming config plus the prior state under "current".

func (*PgOperator) RevokeAdminToken

func (a *PgOperator) RevokeAdminToken(ctx context.Context, projectID, tokenID string) error

func (*PgOperator) UpdateFeatures

func (a *PgOperator) UpdateFeatures(ctx context.Context, cmd domain.OperatorFeaturesCmd) (map[string]bool, error)

func (*PgOperator) UpdateProject

type PgWebhooks added in v1.4.0

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

PgWebhooks owns webhook configuration, the durable public-event archive and delivery attempts. It is shared by the admin API and the outbox publisher so manual retries use exactly the same signing and HTTP path as normal delivery.

func NewPgWebhooks added in v1.4.0

func NewPgWebhooks(db *DB, client *http.Client) *PgWebhooks

func (*PgWebhooks) Create added in v1.4.0

func (*PgWebhooks) Delete added in v1.4.0

func (a *PgWebhooks) Delete(ctx context.Context, projectID, environment, id string) error

func (*PgWebhooks) Get added in v1.4.0

func (a *PgWebhooks) Get(ctx context.Context, projectID, environment, id string) (*domain.Webhook, error)

func (*PgWebhooks) List added in v1.4.0

func (*PgWebhooks) ListDeliveries added in v1.4.0

func (a *PgWebhooks) ListDeliveries(
	ctx context.Context, cmd domain.WebhookDeliveryListCmd,
) ([]domain.WebhookDelivery, error)

func (*PgWebhooks) ListEvents added in v1.4.0

func (*PgWebhooks) PublishEvent added in v1.4.0

func (a *PgWebhooks) PublishEvent(ctx context.Context, ev domain.Event) error

PublishEvent archives and delivers one safe public event. Returning an error asks pg-outbox to retry with its exponential backoff. Succeeded deliveries are skipped on the retry, avoiding duplicate sends to healthy endpoints.

func (*PgWebhooks) ReplayEvent added in v1.4.0

func (a *PgWebhooks) ReplayEvent(
	ctx context.Context, projectID, environment, eventID, webhookID string,
) ([]domain.WebhookDelivery, error)

func (*PgWebhooks) RetryDelivery added in v1.4.0

func (a *PgWebhooks) RetryDelivery(
	ctx context.Context, projectID, environment, deliveryID string,
) (*domain.WebhookDelivery, error)

func (*PgWebhooks) RotateSecret added in v1.4.0

func (a *PgWebhooks) RotateSecret(ctx context.Context, projectID, environment, id string) (string, error)

func (*PgWebhooks) RunRetryWorker added in v1.6.0

func (a *PgWebhooks) RunRetryWorker(ctx context.Context, interval time.Duration, log *xlog.Logger)

RunRetryWorker periodically re-delivers webhook deliveries whose backoff has elapsed. deliver() already writes next_attempt_at with exponential backoff on each failure and the partial index idx_iam_webhook_deliveries_retry serves the due-scan; previously nothing consumed that column, so a failed delivery was stranded until a manual retry. Blocks until ctx is cancelled.

func (*PgWebhooks) Test added in v1.4.0

func (a *PgWebhooks) Test(
	ctx context.Context, projectID, environment, webhookID, eventType string,
) (*domain.WebhookDelivery, error)

func (*PgWebhooks) Update added in v1.4.0

type Signer

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

Signer is the JWT signer/verifier over a project+environment's signing keys.

func (*Signer) JWKS

func (s *Signer) JWKS(ctx context.Context, projectID, env string) (map[string]any, error)

JWKS returns the public JWK set for project/env as a generic map (the /.well-known/jwks.json body).

func (*Signer) Sign

func (s *Signer) Sign(
	ctx context.Context,
	projectID, env string,
	claims map[string]any,
	ttl time.Duration,
) (string, error)

Sign mints a signed RS256 JWT for project/env with the given claims and TTL. iss/aud/sub should be passed as claims by the caller.

func (*Signer) UnverifiedClaims

func (s *Signer) UnverifiedClaims(token string) map[string]any

UnverifiedClaims decodes a JWT's claims WITHOUT verifying the signature. Use only where the result is non-authoritative — e.g. routing an idempotent revoke by its sid claim. Returns nil on a malformed token.

func (*Signer) Verify

func (s *Signer) Verify(ctx context.Context, projectID, env, token string) (map[string]any, error)

Verify parses and validates a token against the project/env public keys, returning its claims. An invalid/expired token maps to domain.ErrInvalidToken.

type Store

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

Store is the Postgres-backed persistence façade. It exposes typed repos that issue SQL through the sqld-generated query set bound to db.TxDB (the ctx-aware pgtx executor), so a repo call made inside a service's tx.Do* runs in that same transaction; outside one it runs on the pool (auto-commit).

Repos are added per domain entity as the IAM domain is designed; each follows the envelope pattern: marshal the record to JSON, call the generated query, translate pgx errors via translatePgErr / isUniqueViolation.

func New

func New(db *DB) *Store

New wraps a *DB. It does not touch the database.

Directories

Path Synopsis
gen
db

Jump to

Keyboard shortcuts

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