Files
archie/internal/app/statestore/provision.go
T
sam c54d328f0d feat(store): run services as a non-superuser role and name every connection (#1857)
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.
2026-11-11 03:12:54 +11:00

100 lines
4.1 KiB
Go

package statestore
import (
"context"
"errors"
"flag"
"fmt"
"io"
"os"
"strings"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
)
// provisionCommand is the argv[1] token that runs the one-time database role
// setup instead of serving. Provisioning has to happen before the first
// migration and needs a credential the services never hold, so it cannot be a
// migration and is not part of any service's boot.
const provisionCommand = "provision"
// provisionUsage is the whole flag surface of the provisioning command.
const provisionUsage = `usage: archie-state-store provision [flags]
provision reconciles the PostgreSQL roles an install serves from:
- a migration role that owns the schema and runs goose;
- a runtime role with row access only (SELECT, INSERT, UPDATE, DELETE, plus
sequence USAGE and function EXECUTE), which the services connect as.
It creates the two roles when missing, hands every existing public-schema
object to the migration role, and sets the default privileges that keep the
objects future migrations create usable by the runtime role. It is idempotent:
re-running it on a provisioned database reconciles it back to that state.
The admin URL needs a role that may create roles and take ownership of the
schema (the database owner or a superuser). It is a bootstrap credential: it is
not one of the two roles above and the services never read it.
Passwords come from each URL's userinfo, or from PGPASSWORD when the URL does
not carry one.
-admin-url URL role that creates and owns (database owner or superuser)
-runtime-url URL least-privilege role the services connect as
-migration-url URL role that owns the schema and runs migrations
-rotate-admin-password-env NAME
replace the admin role's password with the value of
environment variable NAME once provisioning succeeds
`
// IsProvisionArgs reports whether args selects the role provisioning command.
func IsProvisionArgs(args []string) bool {
return len(args) > 0 && args[0] == provisionCommand
}
// RunProvision performs the role provisioning and returns the process exit
// code: 0 provisioned, 1 the provisioning failed, 2 the command line was
// wrong.
func RunProvision(ctx context.Context, args []string, stdout, stderr io.Writer) int {
flags := flag.NewFlagSet(provisionCommand, flag.ContinueOnError)
flags.SetOutput(stderr)
flags.Usage = func() { fmt.Fprint(stderr, provisionUsage) }
var options postgres.ProvisionOptions
flags.StringVar(&options.AdminURL, "admin-url", "", "PostgreSQL URL of a role allowed to create roles and own the schema (database owner or superuser)")
flags.StringVar(&options.RuntimeURL, "runtime-url", "", "PostgreSQL URL of the least-privilege role the services connect as")
flags.StringVar(&options.MigrationURL, "migration-url", "", "PostgreSQL URL of the role that owns the schema and runs migrations")
rotateEnv := flags.String("rotate-admin-password-env", "", "name of an environment variable holding the admin role's new password")
if err := flags.Parse(args); err != nil {
// A requested help is not a wrong command line: the usage above is the
// answer.
if errors.Is(err, flag.ErrHelp) {
return 0
}
return 2
}
if flags.NArg() > 0 {
fmt.Fprintf(stderr, "provision: unexpected argument %q\n", flags.Arg(0))
return 2
}
if *rotateEnv != "" {
password, ok := os.LookupEnv(*rotateEnv)
if !ok || password == "" {
fmt.Fprintf(stderr, "provision: %s is unset or empty\n", *rotateEnv)
return 2
}
options.NewAdminPassword = password
}
result, err := postgres.Provision(ctx, options)
if err != nil {
fmt.Fprintf(stderr, "provision: %v\n", err)
return 1
}
if len(result.RolesCreated) > 0 {
fmt.Fprintf(stdout, "provision: created %s\n", strings.Join(result.RolesCreated, ", "))
}
fmt.Fprintf(stdout, "provision: %s owns the schema; %s may read and write rows but not change the schema\n", result.MigrationRole, result.RuntimeRole)
fmt.Fprintf(stdout, "provision: reconciled %d tables, %d sequences and %d functions\n", result.Tables, result.Sequences, result.Functions)
return 0
}