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" //nolint:gosec // G101: fake database URLs. runtimeURL = "postgres://archie_runtime:runtime@db.internal/archie" //nolint:gosec // G101: fake database URLs. migrationURL = "postgres://archie_migrator:migration@db.internal/archie" //nolint:gosec // G101: fake database URLs. ) 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"}, //nolint:gosec // G101: a fake database URL. 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}, //nolint:gosec // G101: a fake database URL. 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") } }