Files
archie/internal/infrastructure/configuration/setup/setup_test.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

233 lines
6.9 KiB
Go

package setup
import (
"context"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
"github.com/samcharles93/archie-core/internal/infrastructure/configuration/tomlwrite"
)
// fakePrompter answers prompts from maps keyed by the exact prompt text and
// records what it was asked, so a test can pin both the answers and that the
// bundled database was actually offered.
type fakePrompter struct {
selectAnswers map[string]int
lineAnswers map[string]string
confirmAnswer bool
selects []recordedSelect
lines []recordedLine
}
type recordedSelect struct {
prompt string
options []string
}
type recordedLine struct {
prompt string
defaultValue string
}
func (f *fakePrompter) Select(_ context.Context, prompt string, options []string) (int, error) {
f.selects = append(f.selects, recordedSelect{prompt: prompt, options: options})
if ans, ok := f.selectAnswers[prompt]; ok {
return ans, nil
}
return 0, nil
}
func (f *fakePrompter) ReadLine(_ context.Context, prompt, defaultValue string) (string, error) {
f.lines = append(f.lines, recordedLine{prompt: prompt, defaultValue: defaultValue})
if ans, ok := f.lineAnswers[prompt]; ok {
return ans, nil
}
return defaultValue, nil
}
func (f *fakePrompter) ReadSecret(context.Context, string) (string, error) { return "", nil }
func (f *fakePrompter) Confirm(context.Context, string, bool) (bool, error) {
return f.confirmAnswer, nil
}
// fakeSink records Put calls by engine/key.
type fakeSink struct {
puts map[string]string
}
func (s *fakeSink) Put(engine, key, value string) error {
if s.puts == nil {
s.puts = map[string]string{}
}
s.puts[engine+"/"+key] = value
return nil
}
func (s *fakeSink) Commit() error { return nil }
// databasePrompt is the re-run database choice; bundledChoice is the index of
// the bundled database option in that menu.
const (
databasePrompt = "Database:"
bundledChoice = 1
differentURL = 2
)
func bundledURL() string {
return "postgres://archie_runtime@/archie?host=" + configuration.DefaultPostgresSocketDir()
}
func bundledMigrationURL() string {
return "postgres://archie_migrator@/archie?host=" + configuration.DefaultPostgresSocketDir()
}
// TestRunParamsDatabaseChoice pins the re-run database step at the setup API
// level: with an existing database_url the flow must offer the bundled
// database as an explicit choice, switching to it must generate PGPASSWORD
// into the sink, and keeping must leave the existing URL untouched.
func TestRunParamsDatabaseChoice(t *testing.T) {
const existing = "postgres://operator:secret@db.internal:5432/archie"
tests := []struct {
name string
// existing is the prefilled database_url; empty means fresh install.
existing string
// param is Params.DatabaseURL (the -database-url flag).
param string
selectAnswers map[string]int
lineAnswers map[string]string
wantURL string
wantMigrationURL string // empty means the flow must not write one
wantPassword bool
wantChoice bool // a database Select menu must be presented
}{
{
name: "re-run keep existing is the default choice",
existing: existing,
selectAnswers: map[string]int{databasePrompt: 0},
wantURL: existing,
wantChoice: true,
},
{
name: "re-run switch to the bundled database",
existing: existing,
selectAnswers: map[string]int{databasePrompt: bundledChoice},
wantURL: bundledURL(),
wantMigrationURL: bundledMigrationURL(),
wantPassword: true,
wantChoice: true,
},
{
name: "re-run enter a different URL",
existing: existing,
selectAnswers: map[string]int{databasePrompt: differentURL},
lineAnswers: map[string]string{"PostgreSQL 18 URL: ": "postgres://other.internal/archie"},
wantURL: "postgres://other.internal/archie",
wantChoice: true,
},
{
name: "re-run blank answer on the different-URL prompt keeps existing",
existing: existing,
selectAnswers: map[string]int{databasePrompt: differentURL},
lineAnswers: map[string]string{"PostgreSQL 18 URL: ": ""},
wantURL: existing,
wantChoice: true,
},
{
name: "fresh install blank answer means the bundled database",
existing: "",
lineAnswers: map[string]string{"PostgreSQL 18 URL (blank for the bundled database with a generated password): ": ""},
wantURL: bundledURL(),
wantMigrationURL: bundledMigrationURL(),
wantPassword: true,
wantChoice: false,
},
{
name: "database-url flag wins without prompting",
existing: existing,
param: "postgres://flag.internal/archie",
wantURL: "postgres://flag.internal/archie",
wantChoice: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
p := &fakePrompter{
selectAnswers: tt.selectAnswers,
lineAnswers: tt.lineAnswers,
confirmAnswer: false,
}
sink := &fakeSink{}
params := Params{
DatabaseURL: tt.param,
BotUser: "archie-bot",
ForgeType: "none",
Provider: "ollama",
Model: "llama3",
}
edits, err := RunParams(context.Background(), p, nil, sink, ExistingValues{DatabaseURL: tt.existing}, params)
if err != nil {
t.Fatalf("RunParams: %v", err)
}
var gotURL, gotMigrationURL string
for _, e := range edits {
if e.Table != "" {
continue
}
switch e.Key {
case "database_url":
gotURL = e.Value
case "migration_database_url":
gotMigrationURL = e.Value
}
}
if gotURL != tomlwrite.String(tt.wantURL) {
t.Errorf("database_url = %s, want %s", gotURL, tomlwrite.String(tt.wantURL))
}
wantMigrationURL := ""
if tt.wantMigrationURL != "" {
wantMigrationURL = tomlwrite.String(tt.wantMigrationURL)
}
if gotMigrationURL != wantMigrationURL {
t.Errorf("migration_database_url = %q, want %q", gotMigrationURL, wantMigrationURL)
}
password, hasPassword := sink.puts["env/PGPASSWORD"]
if hasPassword != tt.wantPassword {
t.Fatalf("PGPASSWORD stored = %v, want %v", hasPassword, tt.wantPassword)
}
if tt.wantPassword && len(password) != 48 {
t.Errorf("PGPASSWORD = %q, want a 48-character hex password", password)
}
var offered []string
for _, sel := range p.selects {
if sel.prompt == databasePrompt {
offered = sel.options
}
}
if tt.wantChoice {
if offered == nil {
t.Fatalf("no database choice was presented on a re-run; prompts seen: %+v", p.selects)
}
bundled := false
for _, opt := range offered {
if strings.Contains(strings.ToLower(opt), "bundled") {
bundled = true
}
}
if !bundled {
t.Errorf("database choice options %v do not offer the bundled database", offered)
}
} else if offered != nil {
t.Errorf("database choice was presented (%v) where the flow should not ask", offered)
}
})
}
}