Every service connected to PostgreSQL as the database owner, which is a superuser, so anything that compromised an app process owned the cluster, and every connection reached the server with an empty application_name, so pg_stat_activity could not say which service a session belonged to. Split the DB credential into two login roles and name every pool: - archie_migrator owns public and its objects and runs goose. Migrations run on a short-lived pool opened from the new migration_database_url, before the serving pool opens. It is not a superuser. - archie_runtime serves requests with SELECT, INSERT, UPDATE, DELETE, sequence USAGE/SELECT and function EXECUTE only. It has no CREATE privilege, so it cannot change the schema. - Every pool sets application_name: archie-state-store, archie-gateway, and a -migrate / -recovery / -schema / -provision suffix on the transient administrative connections. Existing one-URL installs keep working: an absent migration_database_url falls back to database_url and the migration runs on the serving pool exactly as before. Provisioning is a new idempotent `archie-state-store provision` subcommand: it needs an admin URL the services never hold (database owner or superuser), creates or reconciles both roles, hands every public-schema object to the migration role, revokes PUBLIC's CREATE on public, sets row-level grants, and sets the migration role's default privileges so tables future migrations create are usable without a hand-run grant. It stores SCRAM verifiers, refuses superuser roles, and verifies the boundary before committing. install.sh now provisions the bundled path and separates the credentials: the superuser password the Compose database is created with lives only in a compose-only postgres.env, while the env file the units load holds the non-superuser PGPASSWORD. A bundled install that predates the split is upgraded in place: the roles are created, the superuser password is rotated out of the env file, and config.toml is moved to the runtime and migration URLs. External databases keep their operator-managed credential; the deployments README documents the one-shot provision command. setup writes both bundled URLs, dev:postgres provisions the dev database, the e2e stack provisions its throwaway server, and the deployment templates point at the two roles.
134 lines
4.7 KiB
Go
134 lines
4.7 KiB
Go
package statestore
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
|
)
|
|
|
|
// runPostgresRecovery performs one recovery operation on the PostgreSQL
|
|
// database the configuration names. It connects as the migration role
|
|
// (migration_database_url, falling back to database_url): restoring and
|
|
// rolling back replace schema objects, which only the schema's owner may do.
|
|
// There is no automatic schema rollback: goose Down drops tables, so the way
|
|
// back from a migration is restoring the snapshot taken before it, which loses
|
|
// every write made after that snapshot.
|
|
func runPostgresRecovery(ctx context.Context, options RecoveryOptions) (string, error) {
|
|
cfg, err := bootConfig(ctx, options)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
url := cfg.MigrationURL()
|
|
if url == "" {
|
|
return "", errors.New("database_url is required: the configuration names no PostgreSQL database")
|
|
}
|
|
switch options.Operation {
|
|
case RecoveryBackup:
|
|
if options.Out == "" {
|
|
return "", errors.New("backup requires -out")
|
|
}
|
|
if err := postgres.Backup(ctx, url, options.Out); err != nil {
|
|
return "", err
|
|
}
|
|
return "backed up the whole database to " + options.Out, nil
|
|
case RecoveryRestore:
|
|
if options.From == "" {
|
|
return "", errors.New("restore requires -from")
|
|
}
|
|
if err := postgres.Restore(ctx, url, options.From); err != nil {
|
|
return "", err
|
|
}
|
|
return fmt.Sprintf("restored the whole database from %s; every write made after the snapshot is gone; start the archie services again", options.From), nil
|
|
case RecoveryValidate:
|
|
return validatePostgres(ctx, url, options)
|
|
case RecoveryRollback:
|
|
if options.Kind == "" {
|
|
return "", errors.New("rollback requires -kind")
|
|
}
|
|
return rollbackPostgres(ctx, url, options)
|
|
default:
|
|
return "", fmt.Errorf("unknown recovery command %q", options.Operation)
|
|
}
|
|
}
|
|
|
|
// openRecoveryPool opens the database without migrating it: recovery inspects
|
|
// or repairs the schema it finds, and refuses one newer than this binary.
|
|
func openRecoveryPool(ctx context.Context, url string) (*pgxpool.Pool, int64, error) {
|
|
pool, err := postgres.Open(ctx, url, postgres.AppStateStore+"-recovery")
|
|
if err != nil {
|
|
return nil, 0, err
|
|
}
|
|
version, err := postgres.SchemaVersion(ctx, pool)
|
|
if err == nil {
|
|
err = postgres.CheckSchemaVersion(version)
|
|
}
|
|
if err != nil {
|
|
pool.Close()
|
|
return nil, 0, err
|
|
}
|
|
return pool, version, nil
|
|
}
|
|
|
|
// validatePostgres answers whether archied would start against the database:
|
|
// the stored resources pass the writer's validation and boot's gate. An
|
|
// unmigrated database holds nothing to check; the State Store migrates and
|
|
// seeds it on its next start, so only boot's config gate applies.
|
|
func validatePostgres(ctx context.Context, url string, options RecoveryOptions) (string, error) {
|
|
pool, version, err := openRecoveryPool(ctx, url)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer pool.Close()
|
|
server, err := openStateStoreControlPlane(postgres.NewResources(pool))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
checked, err := checkBootGate(ctx, server, version > 0, options)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return fmt.Sprintf("the database is valid at schema version %d; %d stored resources validate", version, checked), nil
|
|
}
|
|
|
|
// rollbackPostgres replays an earlier revision holding the State Store's
|
|
// ownership claim, so it refuses while a State Store serves and none can
|
|
// start until it finishes.
|
|
func rollbackPostgres(ctx context.Context, url string, options RecoveryOptions) (string, error) {
|
|
pool, _, err := openRecoveryPool(ctx, url)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer pool.Close()
|
|
claim, err := postgres.AcquireOwnership(ctx, pool, postgres.OwnerStateStore)
|
|
if err != nil {
|
|
return "", fmt.Errorf("rollback refused, stop the State Store first: %w", err)
|
|
}
|
|
defer func() { _ = claim.Release(context.WithoutCancel(ctx)) }()
|
|
return replayRevision(ctx, postgres.NewResources(pool), options)
|
|
}
|
|
|
|
// SchemaVersion reads the database's applied migration without migrating or
|
|
// refusing a schema newer than this binary, so an older binary can tell that
|
|
// a newer one migrated it.
|
|
func SchemaVersion(ctx context.Context, options RecoveryOptions) (int64, error) {
|
|
cfg, err := bootConfig(ctx, options)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if cfg.DatabaseURL == "" {
|
|
return 0, errors.New("database_url is required: the configuration names no PostgreSQL database")
|
|
}
|
|
// The updater asks this while the services serve, so it reads the version
|
|
// through the runtime role: SELECT on goose's table is all it needs.
|
|
pool, err := postgres.Open(ctx, cfg.DatabaseURL, postgres.AppStateStore+"-schema")
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
defer pool.Close()
|
|
return postgres.SchemaVersion(ctx, pool)
|
|
}
|