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.
210 lines
7.3 KiB
Go
210 lines
7.3 KiB
Go
// Package setup runs archied's first-run configuration flow and returns the
|
|
// TOML edits to persist it.
|
|
package setup
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"github.com/samcharles93/archie-core/internal/config"
|
|
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
|
"github.com/samcharles93/archie-core/internal/infrastructure/configuration/tomlwrite"
|
|
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
|
)
|
|
|
|
// SecretSink receives the secret values setup collects. Put buffers; the
|
|
// caller commits once the generated config is proven loadable.
|
|
type SecretSink interface {
|
|
// Put records that key (as looked up through engine) must resolve to
|
|
// value once Commit is called.
|
|
Put(engine, key, value string) error
|
|
// Commit persists everything Put has recorded so far.
|
|
Commit() error
|
|
}
|
|
|
|
// ModelDiscovery finds locally available models for the self-hosted
|
|
// provider path. A nil ModelDiscovery, or one that returns an error,
|
|
// degrades to a free-text model name -- discovery is a convenience, not a
|
|
// requirement.
|
|
type ModelDiscovery interface {
|
|
ListOllamaModels(ctx context.Context) ([]string, error)
|
|
}
|
|
|
|
// ExistingValues prefills prompts on a re-run. The zero value is correct
|
|
// for a fresh install.
|
|
type ExistingValues struct {
|
|
BotUser string
|
|
Operator string
|
|
ForgeHost string
|
|
DatabaseURL string
|
|
}
|
|
|
|
// tableEdits groups pending edits by table before Run flattens them into
|
|
// []tomlwrite.Edit, so a step can build "everything for [forge]" as one
|
|
// value and let Run decide the flattening order.
|
|
type tableEdits = map[string]map[string]string
|
|
|
|
// Params pre-answers setup questions; a step prompts only for unset fields.
|
|
// Provider is a config class; Model is the bare model name.
|
|
type Params struct {
|
|
DatabaseURL string
|
|
BotUser string
|
|
Operator string
|
|
ForgeType string // github | gitea | none
|
|
ForgeHost string
|
|
Provider string // openai | anthropic | openrouter | gemini | groq | deepseek | mistral | ollama
|
|
Model string // bare model name; the step adds the "class/" prefix
|
|
|
|
// TelegramUserIDs non-empty configures Telegram. The reference fields name
|
|
// already-stored secrets as engine:key; when set, the step writes the
|
|
// reference without prompting.
|
|
ForgeTokenRef config.SecretRef
|
|
ProviderAPIKeyRef config.SecretRef
|
|
TelegramTokenRef config.SecretRef
|
|
|
|
TelegramUserIDs []int64
|
|
|
|
// Secret values are never parameters; they come from a prompt through
|
|
// SecretSink.
|
|
}
|
|
|
|
// RunParams drives the setup flow with the question sites pre-answered from params. A zero
|
|
// Params behaves exactly like Run.
|
|
func RunParams(ctx context.Context, p Prompter, discovery ModelDiscovery, secrets SecretSink, existing ExistingValues, params Params) ([]tomlwrite.Edit, error) {
|
|
var edits []tomlwrite.Edit
|
|
add := func(all tableEdits) {
|
|
for table, kv := range all {
|
|
for k, v := range kv {
|
|
edits = append(edits, tomlwrite.Edit{Table: table, Key: k, Value: v})
|
|
}
|
|
}
|
|
}
|
|
|
|
dbURL, migrationURL, err := stepDatabase(ctx, p, secrets, existing.DatabaseURL, params.DatabaseURL)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
dbEdits := tableEdits{"": {"database_url": tomlwrite.String(dbURL)}}
|
|
if migrationURL != "" {
|
|
dbEdits[""]["migration_database_url"] = tomlwrite.String(migrationURL)
|
|
}
|
|
add(dbEdits)
|
|
|
|
botUser := params.BotUser
|
|
if strings.TrimSpace(botUser) == "" {
|
|
var err error
|
|
botUser, err = p.ReadLine(ctx, "Bot user (forge username for archied's commits and API calls): ", existing.BotUser)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("setup: bot user: %w", err)
|
|
}
|
|
}
|
|
if strings.TrimSpace(botUser) == "" {
|
|
return nil, fmt.Errorf("setup: bot user is required")
|
|
}
|
|
add(tableEdits{"": {"bot_user": tomlwrite.String(botUser)}})
|
|
|
|
operator := params.Operator
|
|
if strings.TrimSpace(operator) == "" {
|
|
var err error
|
|
operator, err = p.ReadLine(ctx, "Operator display name (shown to the chat agent; blank to skip): ", existing.Operator)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("setup: operator: %w", err)
|
|
}
|
|
}
|
|
if strings.TrimSpace(operator) != "" {
|
|
add(tableEdits{"chat": {"operator": tomlwrite.String(operator)}})
|
|
}
|
|
|
|
providerEdits, model, err := stepProvider(ctx, p, discovery, secrets, params)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
add(providerEdits)
|
|
add(tableEdits{"models": {config.DefaultModelAlias: tomlwrite.String(model)}})
|
|
|
|
forgeEdits, err := stepForge(ctx, p, secrets, existing.ForgeHost, params)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
add(forgeEdits)
|
|
|
|
chatEdits, err := stepChat(ctx, p, secrets, params)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
add(chatEdits)
|
|
|
|
return edits, nil
|
|
}
|
|
|
|
// stepDatabase returns the PostgreSQL URLs the install serves from: the
|
|
// runtime role's URL and, for the bundled database, the migration role's. A
|
|
// blank answer on a fresh install means the bundled database. On a re-run with
|
|
// an existing URL the bundled database is an explicit choice rather than
|
|
// something reachable only by typing its socket URL; keeping the existing URL
|
|
// is the first option, so the default answer is unchanged.
|
|
func stepDatabase(ctx context.Context, p Prompter, secrets SecretSink, existing, param string) (runtimeURL, migrationURL string, err error) {
|
|
if strings.TrimSpace(param) != "" {
|
|
return param, "", nil
|
|
}
|
|
if strings.TrimSpace(existing) != "" {
|
|
choice, err := p.Select(ctx, "Database:", []string{
|
|
"Keep the existing database URL",
|
|
"Bundled database (Unix socket, generated password in the env file)",
|
|
"Enter a different PostgreSQL 18 URL",
|
|
})
|
|
if err != nil {
|
|
return "", "", fmt.Errorf("setup: database choice: %w", err)
|
|
}
|
|
switch choice {
|
|
case 0:
|
|
return existing, "", nil
|
|
case 1:
|
|
return bundledDatabase(secrets)
|
|
default:
|
|
url, err := p.ReadLine(ctx, "PostgreSQL 18 URL: ", "")
|
|
if err != nil {
|
|
return "", "", fmt.Errorf("setup: database url: %w", err)
|
|
}
|
|
if strings.TrimSpace(url) == "" {
|
|
// A blank answer keeps the existing URL, as it always has.
|
|
return existing, "", nil
|
|
}
|
|
return url, "", nil
|
|
}
|
|
}
|
|
prompt := "PostgreSQL 18 URL (blank for the bundled database with a generated password): "
|
|
url, err := p.ReadLine(ctx, prompt, "")
|
|
if err != nil {
|
|
return "", "", fmt.Errorf("setup: database url: %w", err)
|
|
}
|
|
if strings.TrimSpace(url) != "" {
|
|
return url, "", nil
|
|
}
|
|
return bundledDatabase(secrets)
|
|
}
|
|
|
|
// bundledDatabase switches to the bundled database: no network, reached
|
|
// through its Unix socket. The services connect as the least-privilege runtime
|
|
// role and migrations run as the schema-owning migration role; one generated
|
|
// password goes only to the env file as PGPASSWORD, which pgx reads for both
|
|
// passwordless URLs, so config.toml holds no secret. The superuser credential
|
|
// the bundled server is created with lives in the installer's Compose-only
|
|
// env file, never here.
|
|
func bundledDatabase(secrets SecretSink) (runtimeURL, migrationURL string, err error) {
|
|
pw := make([]byte, 24)
|
|
if _, err := rand.Read(pw); err != nil {
|
|
return "", "", fmt.Errorf("setup: generate database password: %w", err)
|
|
}
|
|
password := hex.EncodeToString(pw)
|
|
if err := secrets.Put("env", "PGPASSWORD", password); err != nil {
|
|
return "", "", fmt.Errorf("setup: store database password: %w", err)
|
|
}
|
|
socket := configuration.DefaultPostgresSocketDir()
|
|
return "postgres://" + postgres.RuntimeRole + "@/archie?host=" + socket,
|
|
"postgres://" + postgres.MigrationRole + "@/archie?host=" + socket, nil
|
|
}
|