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.
265 lines
11 KiB
Go
265 lines
11 KiB
Go
package postgres
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"regexp"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
// testProvisionRoles is the role set the statement tests reconcile.
|
|
func testProvisionRoles() provisionRoles {
|
|
return provisionRoles{
|
|
admin: provisionRole{name: "archie", password: "admin-password"},
|
|
runtime: provisionRole{name: RuntimeRole, password: "runtime-password"},
|
|
migration: provisionRole{name: MigrationRole, password: "migration-password"},
|
|
}
|
|
}
|
|
|
|
// TestParseProvisionURLs pins what the installer may hand the provisioner: a
|
|
// role per URL, a password from the URL or PGPASSWORD, and a refusal for any
|
|
// plan that would leave the runtime role owning schema changes.
|
|
func TestParseProvisionURLs(t *testing.T) {
|
|
const (
|
|
adminURL = "postgres://archie:admin@db.internal/archie"
|
|
runtimeURL = "postgres://archie_runtime:runtime@db.internal/archie"
|
|
migrationURL = "postgres://archie_migrator:migration@db.internal/archie"
|
|
)
|
|
tests := []struct {
|
|
name string
|
|
opts ProvisionOptions
|
|
env map[string]string
|
|
want provisionRoles
|
|
wantErr string
|
|
}{
|
|
{
|
|
name: "passwords come from the URL userinfo",
|
|
opts: ProvisionOptions{AdminURL: adminURL, RuntimeURL: runtimeURL, MigrationURL: migrationURL},
|
|
want: provisionRoles{
|
|
admin: provisionRole{name: "archie", password: "admin"},
|
|
runtime: provisionRole{name: RuntimeRole, password: "runtime"},
|
|
migration: provisionRole{name: MigrationRole, password: "migration"},
|
|
},
|
|
},
|
|
{
|
|
name: "passwordless role URLs take PGPASSWORD",
|
|
opts: ProvisionOptions{
|
|
AdminURL: "postgres://archie@/archie?host=/run/archie/postgres",
|
|
RuntimeURL: "postgres://archie_runtime@/archie?host=/run/archie/postgres",
|
|
MigrationURL: "postgres://archie_migrator@/archie?host=/run/archie/postgres",
|
|
},
|
|
env: map[string]string{databasePasswordEnv: "from-env"},
|
|
want: provisionRoles{
|
|
admin: provisionRole{name: "archie", password: "from-env"},
|
|
runtime: provisionRole{name: RuntimeRole, password: "from-env"},
|
|
migration: provisionRole{name: MigrationRole, password: "from-env"},
|
|
},
|
|
},
|
|
{
|
|
name: "an admin URL needs no password of its own",
|
|
opts: ProvisionOptions{
|
|
AdminURL: "postgres://archie@/archie?host=/run/archie/postgres",
|
|
RuntimeURL: runtimeURL,
|
|
MigrationURL: migrationURL,
|
|
},
|
|
want: provisionRoles{
|
|
admin: provisionRole{name: "archie"},
|
|
runtime: provisionRole{name: RuntimeRole, password: "runtime"},
|
|
migration: provisionRole{name: MigrationRole, password: "migration"},
|
|
},
|
|
},
|
|
{
|
|
name: "a runtime role with no password is refused",
|
|
opts: ProvisionOptions{AdminURL: adminURL, RuntimeURL: "postgres://archie_runtime@db.internal/archie", MigrationURL: migrationURL},
|
|
wantErr: databasePasswordEnv,
|
|
},
|
|
{
|
|
name: "the same role cannot be runtime and migration",
|
|
opts: ProvisionOptions{AdminURL: adminURL, RuntimeURL: runtimeURL, MigrationURL: "postgres://archie_runtime:other@db.internal/archie"},
|
|
wantErr: "same role",
|
|
},
|
|
{
|
|
name: "the admin role cannot be provisioned as runtime",
|
|
opts: ProvisionOptions{AdminURL: adminURL, RuntimeURL: adminURL, MigrationURL: migrationURL},
|
|
wantErr: "admin role",
|
|
},
|
|
{
|
|
name: "a non-PostgreSQL URL is refused",
|
|
opts: ProvisionOptions{AdminURL: "mysql://archie:admin@db.internal/archie", RuntimeURL: runtimeURL, MigrationURL: migrationURL},
|
|
wantErr: "postgres:// URL",
|
|
},
|
|
{
|
|
name: "a URL without a role is refused",
|
|
opts: ProvisionOptions{AdminURL: adminURL, RuntimeURL: "postgres://db.internal/archie", MigrationURL: migrationURL},
|
|
wantErr: "userinfo",
|
|
},
|
|
{
|
|
name: "a key=value connection string is refused, it names no role",
|
|
opts: ProvisionOptions{AdminURL: adminURL, RuntimeURL: "host=db.internal user=archie_runtime", MigrationURL: migrationURL},
|
|
wantErr: "postgres:// URL",
|
|
},
|
|
{
|
|
name: "a missing role URL is named in the error",
|
|
opts: ProvisionOptions{AdminURL: adminURL, RuntimeURL: runtimeURL},
|
|
wantErr: "migration_url is required",
|
|
},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
getenv := func(key string) string { return tt.env[key] }
|
|
got, err := parseProvisionURLs(tt.opts, getenv)
|
|
if tt.wantErr != "" {
|
|
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
|
|
t.Fatalf("parseProvisionURLs error = %v, want one naming %q", err, tt.wantErr)
|
|
}
|
|
return
|
|
}
|
|
if err != nil {
|
|
t.Fatalf("parseProvisionURLs: %v", err)
|
|
}
|
|
if got != tt.want {
|
|
t.Errorf("parseProvisionURLs = %+v, want %+v", got, tt.want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestSchemaStatements pins the privilege boundary: the runtime role reads and
|
|
// writes rows and nothing else, the migration role owns the schema, and the
|
|
// migration role's default privileges cover the objects future migrations
|
|
// create. A regression here is a security regression, not a formatting one.
|
|
func TestSchemaStatements(t *testing.T) {
|
|
roles := testProvisionRoles()
|
|
runtime := quoteIdent(roles.runtime.name)
|
|
migration := quoteIdent(roles.migration.name)
|
|
statements := schemaStatements(roles)
|
|
joined := strings.Join(statements, "\n")
|
|
|
|
required := []string{
|
|
"ALTER SCHEMA public OWNER TO " + migration,
|
|
"REVOKE CREATE ON SCHEMA public FROM PUBLIC",
|
|
"GRANT USAGE ON SCHEMA public TO " + runtime,
|
|
"GRANT USAGE, CREATE ON SCHEMA public TO " + migration,
|
|
"GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO " + runtime,
|
|
"GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO " + runtime,
|
|
"GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO " + runtime,
|
|
"ALTER DEFAULT PRIVILEGES FOR ROLE " + migration + " IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO " + runtime,
|
|
"ALTER DEFAULT PRIVILEGES FOR ROLE " + migration + " IN SCHEMA public GRANT USAGE, SELECT ON SEQUENCES TO " + runtime,
|
|
"ALTER DEFAULT PRIVILEGES FOR ROLE " + migration + " IN SCHEMA public GRANT EXECUTE ON FUNCTIONS TO " + runtime,
|
|
}
|
|
for _, statement := range required {
|
|
if !strings.Contains(joined, statement) {
|
|
t.Errorf("provisioning lacks %q", statement)
|
|
}
|
|
}
|
|
|
|
// Every statement that mentions the runtime role must be a row-level grant
|
|
// or a default privilege: nothing may let it create, own, truncate or
|
|
// elevate.
|
|
forbiddenForRuntime := []string{" CREATE ", " SUPERUSER", " CREATEDB", " CREATEROLE", " OWNER TO ", "TRUNCATE", "ALL PRIVILEGES"}
|
|
for _, statement := range statements {
|
|
if !strings.Contains(statement, runtime) {
|
|
continue
|
|
}
|
|
for _, forbidden := range forbiddenForRuntime {
|
|
if strings.Contains(statement, forbidden) {
|
|
t.Errorf("statement grants the runtime role more than rows: %q", statement)
|
|
}
|
|
}
|
|
}
|
|
|
|
// The default privileges are what make the next migration's tables usable
|
|
// without a hand-run grant; one per object class is the contract.
|
|
var defaults int
|
|
for _, statement := range statements {
|
|
if strings.HasPrefix(statement, "ALTER DEFAULT PRIVILEGES FOR ROLE "+migration) {
|
|
defaults++
|
|
}
|
|
}
|
|
if defaults != 3 {
|
|
t.Errorf("default privileges for %s = %d statements, want tables, sequences and functions", roles.migration.name, defaults)
|
|
}
|
|
}
|
|
|
|
// TestSchemaStatementsQuoteRoleNames pins that role names arriving in URLs are
|
|
// quoted as identifiers, not spliced into SQL.
|
|
func TestSchemaStatementsQuoteRoleNames(t *testing.T) {
|
|
roles := provisionRoles{
|
|
runtime: provisionRole{name: `runtime"; DROP TABLE tasks; --`},
|
|
migration: provisionRole{name: `migration"role`},
|
|
}
|
|
joined := strings.Join(schemaStatements(roles), "\n")
|
|
if !strings.Contains(joined, `"runtime""; DROP TABLE tasks; --"`) {
|
|
t.Errorf("runtime role name is not quoted as one identifier:\n%s", joined)
|
|
}
|
|
if !strings.Contains(joined, `"migration""role"`) {
|
|
t.Errorf("migration role name is not quoted as one identifier:\n%s", joined)
|
|
}
|
|
}
|
|
|
|
// TestOwnerStatement pins the ALTER an object gets when its ownership moves to
|
|
// the migration role, including PostgreSQL's keyword for each object class.
|
|
func TestOwnerStatement(t *testing.T) {
|
|
const role = MigrationRole
|
|
tests := []struct {
|
|
name string
|
|
object schemaObject
|
|
want string
|
|
}{
|
|
{"table", schemaObject{kind: objectTable, reference: "tasks"}, `ALTER TABLE "public"."tasks" OWNER TO "archie_migrator"`},
|
|
{"partitioned table alters as a table", schemaObject{kind: objectPartitionedTable, reference: "events"}, `ALTER TABLE "public"."events" OWNER TO "archie_migrator"`},
|
|
{"sequence", schemaObject{kind: objectSequence, reference: "tasks_id_seq"}, `ALTER SEQUENCE "public"."tasks_id_seq" OWNER TO "archie_migrator"`},
|
|
{"view", schemaObject{kind: objectView, reference: "open_tasks"}, `ALTER VIEW "public"."open_tasks" OWNER TO "archie_migrator"`},
|
|
{"materialized view", schemaObject{kind: objectMaterializedView, reference: "summary"}, `ALTER MATERIALIZED VIEW "public"."summary" OWNER TO "archie_migrator"`},
|
|
{"foreign table", schemaObject{kind: objectForeignTable, reference: "remote"}, `ALTER FOREIGN TABLE "public"."remote" OWNER TO "archie_migrator"`},
|
|
{"function", schemaObject{kind: objectFunction, reference: "audit_json_diff(jsonb,jsonb)"}, `ALTER FUNCTION audit_json_diff(jsonb,jsonb) OWNER TO "archie_migrator"`},
|
|
{"procedure", schemaObject{kind: objectProcedure, reference: "sweep(integer)"}, `ALTER PROCEDURE sweep(integer) OWNER TO "archie_migrator"`},
|
|
{"a quoted relation name stays one identifier", schemaObject{kind: objectTable, reference: `bad"name`}, `ALTER TABLE "public"."bad""name" OWNER TO "archie_migrator"`},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
if got := tt.object.ownerStatement(role); got != tt.want {
|
|
t.Errorf("ownerStatement = %q, want %q", got, tt.want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestSCRAMVerifier pins that the provisioner stores PostgreSQL a SCRAM
|
|
// verifier rather than a plaintext password, and that the verifier has the
|
|
// shape the server accepts.
|
|
func TestSCRAMVerifier(t *testing.T) {
|
|
verifier, err := scramVerifier("correct horse battery staple")
|
|
if err != nil {
|
|
t.Fatalf("scramVerifier: %v", err)
|
|
}
|
|
if strings.Contains(verifier, "correct horse") {
|
|
t.Fatalf("verifier contains the plaintext password: %q", verifier)
|
|
}
|
|
shape := regexp.MustCompile(`^SCRAM-SHA-256\$4096:([A-Za-z0-9+/=]+)\$([A-Za-z0-9+/=]+):([A-Za-z0-9+/=]+)$`)
|
|
match := shape.FindStringSubmatch(verifier)
|
|
if match == nil {
|
|
t.Fatalf("verifier %q is not SCRAM-SHA-256$iterations:salt$stored:server", verifier)
|
|
}
|
|
for i, want := range map[int]int{1: 16, 2: 32, 3: 32} {
|
|
decoded, err := base64.StdEncoding.DecodeString(match[i])
|
|
if err != nil {
|
|
t.Fatalf("part %d of the verifier does not decode: %v", i, err)
|
|
}
|
|
if len(decoded) != want {
|
|
t.Errorf("part %d decodes to %d bytes, want %d", i, len(decoded), want)
|
|
}
|
|
}
|
|
again, err := scramVerifier("correct horse battery staple")
|
|
if err != nil {
|
|
t.Fatalf("scramVerifier: %v", err)
|
|
}
|
|
if again == verifier {
|
|
t.Error("two verifiers of the same password are equal; the salt is not random")
|
|
}
|
|
|
|
if _, err := scramVerifier(""); err == nil {
|
|
t.Error("scramVerifier accepted an empty password")
|
|
}
|
|
}
|