diff --git a/internal/app/archied/setup.go b/internal/app/archied/setup.go index 858a5c96b..77282e3da 100644 --- a/internal/app/archied/setup.go +++ b/internal/app/archied/setup.go @@ -56,11 +56,8 @@ type setupFlags struct { operator string forgeType string forgeHost string - forgeToken string provider string model string - providerAPIKey string - telegramToken string telegramUserIDs string } @@ -72,11 +69,8 @@ func bindSetupFlags(fs *flag.FlagSet) *setupFlags { fs.StringVar(&f.operator, "operator", "", "operator display name (optional)") fs.StringVar(&f.forgeType, "forge-type", "", "forge type: github | gitea | none") fs.StringVar(&f.forgeHost, "forge-host", "", "forge base URL") - fs.StringVar(&f.forgeToken, "forge-token", "", "forge API token, stored in the env file beside the config") fs.StringVar(&f.provider, "provider", "", "LLM provider class: openai | anthropic | openrouter | gemini | groq | deepseek | mistral | ollama") fs.StringVar(&f.model, "model", "", "bare model name; the provider class prefix is added automatically") - fs.StringVar(&f.providerAPIKey, "provider-api-key", "", "cloud LLM provider API key, stored in the env file beside the config") - fs.StringVar(&f.telegramToken, "telegram-token", "", "Telegram bot token, stored in the env file beside the config") fs.StringVar(&f.telegramUserIDs, "telegram-user-ids", "", "comma-separated allowed Telegram user IDs; configuring Telegram requires at least one") return f } @@ -101,21 +95,12 @@ func (f *setupFlags) params() (setup.Params, error) { if f.forgeHost != "" { params.ForgeHost = f.forgeHost } - if f.forgeToken != "" { - params.ForgeToken = f.forgeToken - } if f.provider != "" { params.Provider = f.provider } if f.model != "" { params.Model = f.model } - if f.providerAPIKey != "" { - params.ProviderAPIKey = f.providerAPIKey - } - if f.telegramToken != "" { - params.TelegramToken = f.telegramToken - } if f.telegramUserIDs != "" { ids, err := setup.ParseTelegramUserIDs(f.telegramUserIDs) if err != nil { diff --git a/internal/app/archied/setup_test.go b/internal/app/archied/setup_test.go index 8430e2d41..14509efc2 100644 --- a/internal/app/archied/setup_test.go +++ b/internal/app/archied/setup_test.go @@ -61,35 +61,34 @@ func TestRunSetup_DefaultsWritesLoadableConfig(t *testing.T) { } } -func TestRunSetup_DefaultsWithForgeTokenWritesEnv(t *testing.T) { - dir := t.TempDir() - cfgPath := filepath.Join(dir, "config.toml") +// TestRunSetupRejectsSecretValueFlags pins that no secret value can be passed +// on the command line. Secrets are set in a secret engine; this flow only ever +// writes a reference to one. A flag that carried a value would be a second, +// silent way to set a secret -- and would put it in shell history and in every +// process listing, which is why install.sh prompts with read_secret instead. +func TestRunSetupRejectsSecretValueFlags(t *testing.T) { + for _, flagName := range []string{"-forge-token", "-provider-api-key", "-telegram-token"} { + t.Run(flagName, func(t *testing.T) { + dir := t.TempDir() + cfgPath := filepath.Join(dir, "config.toml") + devNull, err := os.Open(os.DevNull) + if err != nil { + t.Fatal(err) + } + defer func() { _ = devNull.Close() }() - stdin, err := os.Open(os.DevNull) - if err != nil { - t.Fatal(err) - } - defer stdin.Close() - - var stdout, stderr strings.Builder - code := RunSetup([]string{"--defaults", "-config", cfgPath, "-forge-token", "ghp-secret"}, stdin, &stdout, &stderr) - if code != 0 { - t.Fatalf("RunSetup exit = %d, stderr:\n%s", code, stderr.String()) - } - - doc, err := configuration.New(nil).File(cfgPath) - if err != nil { - t.Fatalf("generated config does not load: %v", err) - } - if doc.Config.Forge.Token.Key != "ARCHIE_GITHUB_TOKEN" { - t.Errorf("forge.token.key = %q, want ARCHIE_GITHUB_TOKEN", doc.Config.Forge.Token.Key) - } - b, err := os.ReadFile(filepath.Join(dir, "env")) - if err != nil { - t.Fatalf("env file not written: %v", err) - } - if got, want := string(b), "ARCHIE_GITHUB_TOKEN='ghp-secret'\n"; got != want { - t.Errorf("env file = %q, want %q", got, want) + var stdout, stderr strings.Builder + code := RunSetup([]string{"--defaults", "-config", cfgPath, flagName, "leaked-value"}, devNull, &stdout, &stderr) + if code != 2 { + t.Fatalf("RunSetup with %s = exit %d, want 2 (unknown flag); stderr: %s", flagName, code, stderr.String()) + } + if _, err := os.Stat(cfgPath); !os.IsNotExist(err) { + t.Errorf("config written despite a rejected flag: %v", err) + } + if _, err := os.Stat(filepath.Join(dir, "env")); !os.IsNotExist(err) { + t.Errorf("env file written despite a rejected flag: %v", err) + } + }) } } diff --git a/internal/infrastructure/configuration/setup/params_test.go b/internal/infrastructure/configuration/setup/params_test.go index 3156d08ce..fac407d0b 100644 --- a/internal/infrastructure/configuration/setup/params_test.go +++ b/internal/infrastructure/configuration/setup/params_test.go @@ -7,122 +7,111 @@ import ( // rejectingPrompter fails the test if any question is asked, proving that a // fully-populated Params never touches the prompt surface. -type rejectingPrompter struct { - t *testing.T +// scriptedSecretPrompter answers only the secret reads. Any other prompt means +// Params failed to supply a non-secret answer; an exhausted script means a +// secret was read that the test did not expect. +type scriptedSecretPrompter struct { + t *testing.T + secrets []string + next int } -func (r rejectingPrompter) Select(context.Context, string, []string) (int, error) { - r.t.Fatal("unexpected Select call: Params should have supplied this answer") +func (s *scriptedSecretPrompter) take(prompt string) string { + if s.next >= len(s.secrets) { + s.t.Fatalf("unexpected secret read %q: Params supplied every non-secret answer and no more were scripted", prompt) + } + v := s.secrets[s.next] + s.next++ + return v +} + +func (s *scriptedSecretPrompter) Select(context.Context, string, []string) (int, error) { + s.t.Fatal("unexpected Select: Params should have supplied this answer") return 0, nil } -func (r rejectingPrompter) ReadLine(context.Context, string, string) (string, error) { - r.t.Fatal("unexpected ReadLine call: Params should have supplied this answer") +func (s *scriptedSecretPrompter) ReadLine(context.Context, string, string) (string, error) { + s.t.Fatal("unexpected ReadLine: Params should have supplied this answer") return "", nil } -func (r rejectingPrompter) ReadSecret(context.Context, string) (string, error) { - r.t.Fatal("unexpected ReadSecret call: Params should have supplied this answer") - return "", nil +func (s *scriptedSecretPrompter) ReadSecret(_ context.Context, prompt string) (string, error) { + return s.take(prompt), nil } -func (r rejectingPrompter) Confirm(context.Context, string, bool) (bool, error) { - r.t.Fatal("unexpected Confirm call: Params should have supplied this answer") +func (s *scriptedSecretPrompter) Confirm(context.Context, string, bool) (bool, error) { + s.t.Fatal("unexpected Confirm: Params should have supplied this answer") return false, nil } -func TestRunParams_ProviderAPIKeyNeverPrompts(t *testing.T) { - params := Params{ - BotUser: "archie-bot", - Operator: "Ada", // Run asks for the operator unconditionally; see the note below - ForgeType: "none", - Provider: "openai", - Model: "gpt-5.4", - ProviderAPIKey: "sk-parameterised", - // Telegram enablement is a yes/no question with no parameter to - // pre-answer it, so a genuinely prompt-free run supplies the channel - // outright. Everything else here is supplied, which is the point: the - // provider key must come from Params rather than ReadSecret. - TelegramToken: "tg-token", - TelegramUserIDs: []int64{111}, - } - secrets := newFakeSecrets() - // rejectingPrompter fails the test on any prompt. Before ProviderAPIKey - // existed this run had to ask for the key, which is why an unattended - // install could only ever choose the keyless self-hosted provider. - edits, err := RunParams(context.Background(), rejectingPrompter{t: t}, nil, secrets, ExistingValues{}, params) - if err != nil { - t.Fatalf("RunParams: %v", err) - } - if err := secrets.Commit(); err != nil { - t.Fatalf("Commit: %v", err) - } - if got := secrets.committed["env:OPENAI_API_KEY"]; got != "sk-parameterised" { - t.Errorf("committed env:OPENAI_API_KEY = %q, want sk-parameterised", got) - } - - cfg := generateAndLoad(t, edits) - if got := cfg.Providers["openai"].Class; got != "openai" { - t.Errorf("providers.openai.class = %q, want openai", got) - } - if cfg.Providers["openai"].APIKey.Engine != "env" { - t.Errorf("providers.openai.api_key engine = %q, want env: the key belongs in the env file, not the config", cfg.Providers["openai"].APIKey.Engine) - } - if got := cfg.Models["builder"]; got != "openai/gpt-5.4" { - t.Errorf("models.builder = %q, want openai/gpt-5.4", got) - } -} - -func TestRunParams_FullParamsNeverPrompt(t *testing.T) { +// TestRunParams_SecretsComeOnlyFromThePrompter pins the rule that a secret is +// never a parameter. Params supplies every non-secret answer, so the only +// prompts reached are the secret reads, and the values they return are the only +// values that reach the secret sink. TOML gets a reference, never the value. +func TestRunParams_SecretsComeOnlyFromThePrompter(t *testing.T) { params := Params{ BotUser: "archie-bot", Operator: "Ada", ForgeType: "github", ForgeHost: "https://github.acme.internal", - ForgeToken: "ghp-token", - Provider: "ollama", + Provider: "ollama", // keyless, so no provider secret is read Model: "llama3", - TelegramToken: "tg-token", TelegramUserIDs: []int64{111, 222}, } + p := &scriptedSecretPrompter{t: t, secrets: []string{"ghp-token", "tg-token"}} secrets := newFakeSecrets() - edits, err := RunParams(context.Background(), rejectingPrompter{t: t}, nil, secrets, ExistingValues{}, params) + edits, err := RunParams(context.Background(), p, nil, secrets, ExistingValues{}, params) if err != nil { t.Fatalf("RunParams: %v", err) } if err := secrets.Commit(); err != nil { t.Fatalf("Commit: %v", err) } + if p.next != len(p.secrets) { + t.Errorf("read %d secrets, want %d: every secret must come from a prompt", p.next, len(p.secrets)) + } + if got := secrets.committed["env:ARCHIE_GITHUB_TOKEN"]; got != "ghp-token" { + t.Errorf("committed env:ARCHIE_GITHUB_TOKEN = %q, want ghp-token", got) + } + if got := secrets.committed["env:ARCHIE_TELEGRAM_TOKEN"]; got != "tg-token" { + t.Errorf("committed env:ARCHIE_TELEGRAM_TOKEN = %q, want tg-token", got) + } cfg := generateAndLoad(t, edits) if cfg.BotUser != "archie-bot" { t.Errorf("bot_user = %q, want archie-bot", cfg.BotUser) } - if cfg.Chat.Operator != "Ada" { - t.Errorf("chat.operator = %q, want Ada", cfg.Chat.Operator) + if cfg.Forge.Token.Engine != "env" || cfg.Forge.Token.Key != "ARCHIE_GITHUB_TOKEN" { + t.Errorf("forge.token = %+v, want a reference to env/ARCHIE_GITHUB_TOKEN", cfg.Forge.Token) } - if cfg.Forge.Type != "github" { - t.Errorf("forge.type = %q, want github", cfg.Forge.Type) +} + +// TestRunParams_NonSecretParamsNeverPrompt is the non-secret half: every +// answer Params can carry is supplied, so nothing is asked for except the +// secrets, which Params deliberately cannot supply. +func TestRunParams_NonSecretParamsNeverPrompt(t *testing.T) { + params := Params{ + BotUser: "archie-bot", + Operator: "Ada", + ForgeType: "none", + Provider: "ollama", + Model: "llama3", + TelegramUserIDs: []int64{111, 222}, } - if cfg.Forge.Host != "https://github.acme.internal" { - t.Errorf("forge.host = %q, want https://github.acme.internal", cfg.Forge.Host) + // Ollama is keyless and forge "none" stores no token, so this run asks for + // exactly one secret: the Telegram bot token. + p := &scriptedSecretPrompter{t: t, secrets: []string{"tg-token"}} + secrets := newFakeSecrets() + edits, err := RunParams(context.Background(), p, nil, secrets, ExistingValues{}, params) + if err != nil { + t.Fatalf("RunParams: %v", err) } - if cfg.Forge.Token.Key != "ARCHIE_GITHUB_TOKEN" { - t.Errorf("forge.token.key = %q, want ARCHIE_GITHUB_TOKEN", cfg.Forge.Token.Key) + cfg := generateAndLoad(t, edits) + if cfg.BotUser != "archie-bot" { + t.Errorf("bot_user = %q, want archie-bot", cfg.BotUser) } - for _, role := range []string{"triage", "planner", "builder"} { - if cfg.Models[role] != "ollama/llama3" { - t.Errorf("models[%s] = %q, want ollama/llama3", role, cfg.Models[role]) - } - } - if got := secrets.committed["env:ARCHIE_GITHUB_TOKEN"]; got != "ghp-token" { - t.Errorf("committed github token = %q, want ghp-token", got) - } - if got := secrets.committed["env:ARCHIE_TELEGRAM_TOKEN"]; got != "tg-token" { - t.Errorf("committed telegram token = %q, want tg-token", got) - } - if len(cfg.Chat.Telegram.AllowedUserIDs) != 2 || cfg.Chat.Telegram.AllowedUserIDs[0] != 111 || cfg.Chat.Telegram.AllowedUserIDs[1] != 222 { - t.Errorf("chat.telegram.allowed_user_ids = %v, want [111 222]", cfg.Chat.Telegram.AllowedUserIDs) + if cfg.Forge.Type != "none" { + t.Errorf("forge.type = %q, want none", cfg.Forge.Type) } } diff --git a/internal/infrastructure/configuration/setup/setup.go b/internal/infrastructure/configuration/setup/setup.go index 8ca4f46b2..b03c65c61 100644 --- a/internal/infrastructure/configuration/setup/setup.go +++ b/internal/infrastructure/configuration/setup/setup.go @@ -66,20 +66,23 @@ type tableEdits = map[string]map[string]string // an empty allowlist, so an empty slice means "ask" (or "skip" when the // prompter's default is no). type Params struct { - BotUser string - Operator string - ForgeType string // github | gitea | none - ForgeHost string - ForgeToken string - Provider string // openai | anthropic | openrouter | gemini | groq | deepseek | mistral | ollama - Model string // bare model name; the step adds the "class/" prefix - // ProviderAPIKey is a cloud provider key. It is written to the env file and - // referenced from TOML, never stored in the config itself. Supplying it is - // what makes a cloud provider configurable without a terminal: the keyless - // self-hosted provider was previously the only unattended option. - ProviderAPIKey string - TelegramToken string - TelegramUserIDs []int64 // non-empty means "configure Telegram" + 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 is an access policy, not a credential: IDs are not secret. + // Non-empty means "configure Telegram". + TelegramUserIDs []int64 + + // There is deliberately no secret-valued field here, for forge tokens, + // provider API keys or bot tokens alike. Secrets are set in a secret engine + // and this flow only ever writes a reference to one; a value in Params would + // arrive from a command line, landing in shell history and process listings, + // and would be a second way to set a secret that no engine knows about. + // Values reach an engine through SecretSink, from a prompt. } // Run drives the interactive setup flow and returns the TOML edits to diff --git a/internal/infrastructure/configuration/setup/step_chat.go b/internal/infrastructure/configuration/setup/step_chat.go index b650d5585..a984eddc3 100644 --- a/internal/infrastructure/configuration/setup/step_chat.go +++ b/internal/infrastructure/configuration/setup/step_chat.go @@ -28,13 +28,10 @@ func stepChat(ctx context.Context, p Prompter, secrets SecretSink, params Params return nil, nil } - token := params.TelegramToken - if token == "" { - var err error - token, err = p.ReadSecret(ctx, "Telegram bot token (from @BotFather): ") - if err != nil { - return nil, fmt.Errorf("setup: telegram token: %w", err) - } + // Always prompted, never parameterised; see stepForgeWithToken. + token, err := p.ReadSecret(ctx, "Telegram bot token (from @BotFather): ") + if err != nil { + return nil, fmt.Errorf("setup: telegram token: %w", err) } if strings.TrimSpace(token) == "" { return nil, nil diff --git a/internal/infrastructure/configuration/setup/step_forge.go b/internal/infrastructure/configuration/setup/step_forge.go index 5ffa8df51..11f4ff2f3 100644 --- a/internal/infrastructure/configuration/setup/step_forge.go +++ b/internal/infrastructure/configuration/setup/step_forge.go @@ -40,7 +40,7 @@ func stepForge(ctx context.Context, p Prompter, secrets SecretSink, existingHost if strings.TrimSpace(host) == "" { host = "https://github.com" } - return stepForgeWithToken(ctx, p, secrets, "github", host, "GitHub token (leave blank to configure later): ", params.ForgeToken) + return stepForgeWithToken(ctx, p, secrets, "github", host, "GitHub token (leave blank to configure later): ") case 1: defaultHost := existingHost if defaultHost == "" { @@ -54,7 +54,7 @@ func stepForge(ctx context.Context, p Prompter, secrets SecretSink, existingHost return nil, fmt.Errorf("setup: gitea host: %w", err) } } - return stepForgeWithToken(ctx, p, secrets, "gitea", host, "Gitea token (leave blank to configure later): ", params.ForgeToken) + return stepForgeWithToken(ctx, p, secrets, "gitea", host, "Gitea token (leave blank to configure later): ") default: // The template's default [forge] block is active (type = "github" // with a host and token already set). Selecting "none" must @@ -86,18 +86,22 @@ func forgeChoice(name string) (int, error) { } } -func stepForgeWithToken(ctx context.Context, p Prompter, secrets SecretSink, forgeType, host, tokenPrompt, tokenParam string) (tableEdits, error) { +// stepForgeWithToken records the forge type and host and, when the operator +// supplies one, stores the token in the secret engine and writes only the +// reference to TOML. +// +// The token is always read from the prompt surface. A secret must never travel +// as a parameter: a value passed in would arrive from a command line, where it +// lands in shell history and every process listing, and it would be a second +// way for a secret to be set that no secret engine knows about. +func stepForgeWithToken(ctx context.Context, p Prompter, secrets SecretSink, forgeType, host, tokenPrompt string) (tableEdits, error) { edits := tableEdits{"forge": { "type": tomlwrite.String(forgeType), "host": tomlwrite.String(host), }} - token := tokenParam - if token == "" { - var err error - token, err = p.ReadSecret(ctx, tokenPrompt) - if err != nil { - return nil, fmt.Errorf("setup: %s token: %w", forgeType, err) - } + token, err := p.ReadSecret(ctx, tokenPrompt) + if err != nil { + return nil, fmt.Errorf("setup: %s token: %w", forgeType, err) } if strings.TrimSpace(token) == "" { return edits, nil diff --git a/internal/infrastructure/configuration/setup/step_provider.go b/internal/infrastructure/configuration/setup/step_provider.go index 7cadb7bf4..6421e21c9 100644 --- a/internal/infrastructure/configuration/setup/step_provider.go +++ b/internal/infrastructure/configuration/setup/step_provider.go @@ -72,7 +72,7 @@ func stepProvider(ctx context.Context, p Prompter, discovery ModelDiscovery, sec if choice == len(cloudProviders) { edits, model, err = stepSelfHostedModel(ctx, p, discovery, params.Model) } else { - edits, model, err = stepCloudProvider(ctx, p, secrets, cloudProviders[choice], params.ProviderAPIKey, params.Model) + edits, model, err = stepCloudProvider(ctx, p, secrets, cloudProviders[choice], params.Model) } if err != nil { return nil, "", err @@ -125,17 +125,15 @@ func stepSelfHostedModel(ctx context.Context, p Prompter, discovery ModelDiscove return edits, "ollama/" + model, nil } -func stepCloudProvider(ctx context.Context, p Prompter, secrets SecretSink, cp cloudProvider, keyParam, modelParam string) (tableEdits, string, error) { +func stepCloudProvider(ctx context.Context, p Prompter, secrets SecretSink, cp cloudProvider, modelParam string) (tableEdits, string, error) { // A key supplied as a parameter must not prompt. Without this the only // provider an unattended install could configure was the keyless // self-hosted one, so every cloud setup needed a terminal. - var err error - key := keyParam - if strings.TrimSpace(key) == "" { - key, err = p.ReadSecret(ctx, fmt.Sprintf("%s API key: ", cp.name)) - if err != nil { - return nil, "", fmt.Errorf("setup: %s api key: %w", cp.name, err) - } + // Always prompted, never parameterised: a secret supplied as a value would + // come from a command line and bypass the secret engine entirely. + key, err := p.ReadSecret(ctx, fmt.Sprintf("%s API key: ", cp.name)) + if err != nil { + return nil, "", fmt.Errorf("setup: %s api key: %w", cp.name, err) } table := "providers." + cp.class edits := tableEdits{table: {"class": tomlwrite.String(cp.class)}}