chore(config): remove token_env aliases for forge, artifacts and telegram

Each credential is now only a {engine, key} secret reference. A stale
token_env in a file is reported at startup as an unrecognised key.
nats.token_env stays (no secret-ref form), and providers.api_key_env stays:
it is the carrier the resolver writes each resolved key's env name into.
This commit is contained in:
sam committed 2026-09-24 23:58:26 +10:00
1 parent 9da6108617
commit f624d23f3c
36 files changed
+86 -271

No files matched your search

@@ -119,8 +119,6 @@ Do not expose these helper flags as daemon settings.
| `dispatch.labels.*` | Missing keys default independently to `agent:*`. | production-wired |
| `models.<role>` | Workflow stages read requested role then fall back to `builder`; triage judge falls back `triage` to `planner`. | production-wired |
| `providers.<name>.class`, `api_key_env`, `base_url` | Builds ai-sdk catalog. `base_url` rejects parse errors, userinfo, query, and fragment. | production-wired |
| `agent.mode` | Default `nats` when containers enabled, otherwise `inprocess`; validates `inprocess`, `subprocess`, or `nats`. | production-wired |
| `agent.command`, `agent.env` | Command defaults `archie-agent`; env entries must be nonblank names without `=`. | partially-wired |
| `budgets.max_steps`, `max_tokens`, `wall_clock`, `gate_max_failures` | No loader defaults; `Budgets` documents zero as disabling. | production-wired |
| `diff_cap_lines` | Zero replaced by `400` in `finalize`; `StageDiffCap` treats `<= 0` as disabled. TOML zero cannot disable; negative value does. | production-wired |
| `web.listen` | Empty becomes `127.0.0.1:8484`; literal `off` disables. No authentication. | production-wired |
@@ -154,10 +152,6 @@ looking at before reporting one:
from the stored resource, on purpose. Check for that comment before filing a
defect.
The default `agent.command = "archie-agent"` is not verified subprocess
operation. `SubprocessRunner` expects one JSON invocation on stdin and one JSON
response on stdout; `cmd/archie-agent` is a long-running NATS worker.
### Repository settings
| Keys | Effective behavior | Status |
@@ -175,7 +169,6 @@ response on stdout; `cmd/archie-agent` is a long-running NATS worker.
| Key | Effective behavior |
| --- | --- |
| `enabled` | Requires non-empty `image`, `agent.mode = "nats"`, and non-empty `nats.url`. |
| `image` | Required only when enabled. |
| `max_concurrency` | Zero means no limit; used by general task dispatcher and container pool. |
| `max_uptime` | Default `60m` only when enabled; caps container lifetime. |
@@ -188,7 +181,7 @@ response on stdout; `cmd/archie-agent` is a long-running NATS worker.
| Keys | Effective behavior |
| --- | --- |
| `chat.models` | Optional interactive catalog; empty falls back to workflow model references. |
| `chat.telegram.token_env` | Empty disables Telegram; non-empty names env variable; empty value is fatal. |
| `chat.telegram.token` | Unset disables Telegram; otherwise a secret reference resolved at channel start. |
| `chat.telegram.allowed_user_ids` | Empty denies every sender; IDs match Telegram sender IDs, not chat IDs. |
| `chat.telegram.update_check_command`, `update_install_command` | Argv arrays; check enables update status; install further enables approved installation. |
| `chat.email.listen_addr`, `relay_addr` | Empty listen disables SMTP; relay configures outbound replies. |
@@ -225,20 +218,17 @@ diff cap, notification, and forge host. `TaskConfig.ToConfig` reconstructs
only those fields. Forge tokens, provider values, NATS credential references,
repos, and infrastructure settings do not enter `TaskConfig`.
At top-level `[forge]`, prefer `token = {engine = "env", key = "NAME"}`. The
`token_env = "NAME"` form is converted only when structured reference is empty;
structured reference wins when both appear. This compatibility rule exists
because an earlier migration silently dropped deployed `token_env` values and
crash-looped the daemon. `finalize` does not apply that conversion inside each
identity: identity forges require explicit structured `token`.
Every credential except `nats.token_env` is a `{engine, key}` secret
reference; the flat `token_env` aliases for forge, artifacts and Telegram are
removed. A stale alias in a file is reported at startup as an unrecognised key
(`bootstrap.go`), not silently ignored.
| Source | Archied | Subprocess | Agent container / standalone worker |
| --- | --- | --- | --- |
| Forge `token = {engine="env", key="X"}` | Resolves `X`; empty is fatal. | Not forwarded. | Not forwarded; forge ops proxy to daemon. |
| Provider `api_key_env = "X"` | Runtime reads `X`. | Auto-allowlists selected provider's `X`. | Daemon forwards each present provider variable under original name. |
| `nats.token_env = "X"` | Reads `X`; empty fatal when configured. | Not agent subprocess setting. | Daemon maps to fixed `NATS_TOKEN`; worker also reads `NATS_URL`. |
| Telegram `token_env = "X"` | Reads `X`. | Not forwarded. | Not forwarded. |
| `agent.env = ["X"]` | Names validated. | Copies present `X` from daemon env. | Not used by container construction. |
| Telegram `token = {engine="env", key="X"}` | Resolves `X`. | Not forwarded. | Not forwarded. |
`internal/app/archied` creates `secret.NewRegistry`, which registers only the
`env` engine. Non-env `SecretRef` values are not production-wired.
@@ -145,8 +145,6 @@ For environment failures:
launch environment rather than Compose.
- `containerEnv` translates configured NATS token name into `NATS_TOKEN` and
forwards configured provider key variables.
- Top-level `[forge] token_env` is converted to an env `SecretRef` by
`finalize`; explicit `[forge.token]` wins.
Do not print secret values.
@@ -155,7 +155,7 @@ If current behavior differs from chronicle, update the packet.
| Incident and date | Symptom | Root cause | Evidence and status | Settled rule |
|---|---|---|---|---|
| Container network auto-detection, 2026-07-27 | Every container task returns `nats: no responders`. | `selfNetwork` inspected hostnamed container, silently fell back to default bridge. | `37cf089` records incident, adds `containers.network`; `2ac306b` pins `archie-core_default`. **Status:** `conditional`. | Make cross-container network membership explicit in deployment. |
| SecretRef schema crash-loop, 2026-07-27 | Both identities demand `ARCHIE_GITHUB_TOKEN` despite Gitea config. | Removing old `token_env` field let TOML ignore deployed value. `1f8588d` restored precedence-compatible fallback; a later `308c199` removed the `Forge.TokenEnv` declaration while `finalize` still referenced it. | **Status: `settled`** as of 2026-09-18 — `config.Forge.TokenEnv` is declared (`internal/config/config.go`) and `configuration/defaults.go` converts it to an env `SecretRef` when the structured token is empty. | Preserve decoded compatibility until deployed files migrated and rejection of stale keys observable. |
| SecretRef schema crash-loop, 2026-07-27 | Both identities demand `ARCHIE_GITHUB_TOKEN` despite Gitea config. | Removing old `token_env` field let TOML ignore deployed value. `1f8588d` restored precedence-compatible fallback; a later `308c199` removed the `Forge.TokenEnv` declaration while `finalize` still referenced it. | **Status: `retired`** as of 2026-09-24 — the `token_env` alias is removed; a stale key is now reported at startup as unrecognised (`bootstrap.go` UnknownKeys warning), which is the observability this entry waited for. | Never drop a credential key without the unknown-key warning in place. |
| Compose secret omission, 2026-07-27 | Config names valid env var, container sees it empty. | Compose forwards only listed environment entries. | `22fc0ef`, `d0624b7`. **Status:** `conditional`. | Trace every secret from config key to host value to Compose passthrough to process lookup. |
| FullStream/TextStream deadlock, 2026-07-27 | Streamed Telegram reply renders empty cursor, typing never clears. | ai-sdk makes `FullStream` authoritative and backpressured; `TextStream` is best-effort. | `6a0bd27`. **Status:** `settled` with regression-test gap. | Drain authoritative stream through close. |
| MCP Content-Length framing and mirrored fake, 2026-07-26 to 2026-07-27 | Internal MCP tests pass while official-SDK servers do not. | MCP stdio uses newline-delimited JSON. Test subprocess called same helpers, mirroring the same wrong protocol. | Compare `f2768eb:internal/tools/mcp/framing.go` with `dda4cde`. **Status:** `settled`. | For wire contracts, test raw canonical frames and independently implemented peer. |
@@ -192,10 +192,6 @@ It forwards only configured provider-key variables.
Open limitations until code/tests prove otherwise:
- `subprocess` + default `archie-agent` is protocol-incompatible.
- A deployed overlay previously using legacy `token_env` still converts: the
structured `forge.token` secret reference wins when both are present and
`config.Forge.TokenEnv` is otherwise converted by
`internal/infrastructure/configuration/defaults.go`.
- Container RPC uses root forge/worktree for every identity.
- Container orphan recovery lacks daemon-instance label.
- `max_uptime` only bounds `Pool.Acquire` create/start; no lifetime timer.
+3 -6
View File
@@ -166,10 +166,8 @@ class = "ollama"
# shell snippets). The check command must write a releaseupdate.Snapshot JSON
# document to stdout; configure the installer as well to show Approve/Defer.
# [chat.telegram]
# Preferred: resolve the bot token through a configured secret engine.
# The bot token from @BotFather, resolved through a configured secret engine.
# token = { engine = "bws", key = "TELEGRAM_BOT_TOKEN" }
# Legacy compatibility: read the token from this environment variable.
# token_env = "TELEGRAM_BOT_TOKEN" # env var holding the bot token from @BotFather
# Run by archie-messaging, which serves /update, so these commands execute on
# whichever host runs that process.
# update_check_command = ["/usr/local/bin/archie-update-check"]
@@ -236,12 +234,11 @@ class = "ollama"
# parallel_tool_calls = false
# Publish artifacts (review reports, design docs) to the collaborative editor.
# An empty base_url disables publishing entirely. The token is runtime config:
# set WORKSPACE_INGEST_TOKEN in the daemon's environment or use a secret ref.
# An empty base_url disables publishing entirely. token defaults to the
# WORKSPACE_INGEST_TOKEN environment variable.
[artifacts]
# base_url = "https://offloaded.dev"
# token = { engine = "env", key = "WORKSPACE_INGEST_TOKEN" }
# token_env = "WORKSPACE_INGEST_TOKEN"
# archied's own liveness surface, always on. GET /healthz and /health answer
# 200 once the daemon is serving (503 while it is still booting), and
+1 -1
View File
@@ -124,6 +124,6 @@ gate = [
# Every env var named here must be present in the environment of the host
# archied process, normally through its configured supervisor or launch shell.
[chat.telegram]
token_env = "TELEGRAM_BOT_TOKEN"
token = { engine = "env", key = "TELEGRAM_BOT_TOKEN" }
# Empty list denies everyone.
allowed_user_ids = []
+3 -3
View File
@@ -29,9 +29,9 @@ target = "172.17.0.1:9090"
target_token = "change-me-state-store-token"
[models]
triage = "openai/gpt-4o"
planner = "openai/gpt-4o"
builder = "openai/gpt-4o"
triage = "openai/gpt-6-luna"
planner = "openai/gpt-6-luna"
builder = "openai/gpt-6-luna"
[providers.openai]
class = "openai"
+3 -3
View File
@@ -55,9 +55,9 @@ pr = "archie:pr"
parked = "archie:parked"
[models]
triage = "openai/gpt-4o"
planner = "openai/gpt-4o"
builder = "openai/gpt-4o"
triage = "openai/gpt-6-luna"
planner = "openai/gpt-6-luna"
builder = "openai/gpt-6-luna"
[providers.openai]
class = "openai"
+1 -2
View File
@@ -82,8 +82,7 @@ external account MUST NOT change ownership or historical attribution.
Secret-bearing channel bindings remain configuration concerns rather than
identity data. In particular, `[chat.telegram].token` is a
`secret.SecretRef` resolved by the application through the configured secret
registry; the older `token_env` field remains a compatibility fallback. Neither
form changes the identity that owns or performs a chat action.
registry. It does not change the identity that owns or performs a chat action.
## Persistence
+1 -1
View File
@@ -52,7 +52,7 @@
"url": "/dev/architecture/identity/",
"title": "Identity",
"section": "Architecture",
"body": "# Identity\n\n**Status:** Approved foundation; lifecycle details are deferred \n**Date:** 2026-07-28 \n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Purpose\n\nIdentity answers which persistent actor owns or performed an action. It supplies\nstable cross-domain attribution and lifecycle semantics.\n\nIdentity kinds include:\n\n- the Archie system identity, such as `System` or `archied`;\n- agent or bot identities;\n- service-account identities;\n- future user identities.\n\nA user is another kind of identity rather than a separate foundation concept.\n\n## Ownership\n\n`internal/domain/identity` owns:\n\n- immutable canonical `IdentityID` values;\n- identity kind;\n- lifecycle state;\n- ownership and attribution semantics;\n- identity-related commands and events.\n\nDomains may record an identity reference on their own state and events when\nownership or attribution is required. They MUST NOT receive a complete\nper-identity application configuration bundle.\n\nPersona and communication style are separate from identity.\n\nEvery Agent has its own immutable acting `IdentityID`. Agent actions use that\nidentity for ownership and attribution in the same way an organisation records\nwhich user accessed a resource, changed a permission, or performed another\nauditable action.\n\nAgent and Identity remain separate aggregates. Identity supplies the stable\nactor reference; Agent owns assistant behaviour, memory, specialisation,\nconversations, and capability context.\n\nAgent identities MUST NOT be shared between Agents. Automated WorkflowExecutions\nMAY eventually act through a dedicated service-account identity when a specific\nunattended automation requires it. Such use is an explicit execution decision\nand audit principal, not the default for Agents or a substitute for recording\nthe initiating user when one exists.\n\nA Workflow is owned by an IdentityID and executes as its owner by default.\nFuture delegated execution MAY explicitly assign a different `RunAsIdentityID`,\nincluding a user or service-account identity. Ownership, effective execution\nidentity, initiating identity, and delegation provenance remain distinct audit\nfacts.\n\n## Canonical identity\n\nEvery identity has an immutable `IdentityID`. It is the only value used for\ncross-domain ownership, attribution, routing, persistence, commands, and events.\n\nIdentity kind is explicit:\n\n- system;\n- bot;\n- service account;\n- user.\n\nDisplay names are mutable and MUST NOT be used as identifiers. Forge usernames,\nchannel bot names, Git authors, provider account names, and other external\nidentifiers are bindings associated with an identity rather than identity\nitself.\n\n`System` is represented by a real identity and `IdentityID`. The empty string\nMUST NOT retain special meaning as a legacy system identity.\n\nConfiguration refers to identities by `IdentityID` and supplies external\nbindings and capability settings separately. Renaming an identity or changing an\nexternal account MUST NOT change ownership or historical attribution.\n\nSecret-bearing channel bindings remain configuration concerns rather than\nidentity data. In particular, `[chat.telegram].token` is a\n`secret.SecretRef` resolved by the application through the configured secret\nregistry; the older `token_env` field remains a compatibility fallback. Neither\nform changes the identity that owns or performs a chat action.\n\n## Persistence\n\nIdentity records are durable domain state. The Identity domain's repository is\nthe source of truth; infrastructure implements its persistence contract.\n\nConfiguration MAY bootstrap a missing identity through an explicit, audited\ncreation operation and MAY propose runtime capability bindings for an existing\n`IdentityID`. Configuration is not the identity registry.\n\nOmitting an identity from configuration stops assembling the omitted runtime\ncapabilities. It MUST NOT delete the identity record, erase history, or make\nhistorical references unresolvable.\n\nDisabling or retiring an identity requires an explicit Identity-domain command.\nRetired identities remain resolvable for historical attribution. A failed\nexternal binding affects capability availability without destroying or silently\nreplacing the identity.\n\n## Lifecycle\n\nIdentity lifecycle is deliberately small:\n\n- `active`: may participate in runtime composition;\n- `suspended`: deliberately prevented from initiating new work while ownership\n and history remain;\n- `retired`: terminal, unable to initiate work, and permanently retained for\n attribution.\n\nAllowed transitions are:\n\n```text\ncreate -\u003e active\nactive -\u003e suspended\nsuspended -\u003e active\nactive -\u003e retired\nsuspended -\u003e retired\n```\n\n`retired` has no outgoing transition.\n\nCapability health is separate from identity lifecycle. Forge, model, channel,\nworkspace, and other bindings report health independently. An active ideLine truncated
"body": "# Identity\n\n**Status:** Approved foundation; lifecycle details are deferred \n**Date:** 2026-07-28 \n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Purpose\n\nIdentity answers which persistent actor owns or performed an action. It supplies\nstable cross-domain attribution and lifecycle semantics.\n\nIdentity kinds include:\n\n- the Archie system identity, such as `System` or `archied`;\n- agent or bot identities;\n- service-account identities;\n- future user identities.\n\nA user is another kind of identity rather than a separate foundation concept.\n\n## Ownership\n\n`internal/domain/identity` owns:\n\n- immutable canonical `IdentityID` values;\n- identity kind;\n- lifecycle state;\n- ownership and attribution semantics;\n- identity-related commands and events.\n\nDomains may record an identity reference on their own state and events when\nownership or attribution is required. They MUST NOT receive a complete\nper-identity application configuration bundle.\n\nPersona and communication style are separate from identity.\n\nEvery Agent has its own immutable acting `IdentityID`. Agent actions use that\nidentity for ownership and attribution in the same way an organisation records\nwhich user accessed a resource, changed a permission, or performed another\nauditable action.\n\nAgent and Identity remain separate aggregates. Identity supplies the stable\nactor reference; Agent owns assistant behaviour, memory, specialisation,\nconversations, and capability context.\n\nAgent identities MUST NOT be shared between Agents. Automated WorkflowExecutions\nMAY eventually act through a dedicated service-account identity when a specific\nunattended automation requires it. Such use is an explicit execution decision\nand audit principal, not the default for Agents or a substitute for recording\nthe initiating user when one exists.\n\nA Workflow is owned by an IdentityID and executes as its owner by default.\nFuture delegated execution MAY explicitly assign a different `RunAsIdentityID`,\nincluding a user or service-account identity. Ownership, effective execution\nidentity, initiating identity, and delegation provenance remain distinct audit\nfacts.\n\n## Canonical identity\n\nEvery identity has an immutable `IdentityID`. It is the only value used for\ncross-domain ownership, attribution, routing, persistence, commands, and events.\n\nIdentity kind is explicit:\n\n- system;\n- bot;\n- service account;\n- user.\n\nDisplay names are mutable and MUST NOT be used as identifiers. Forge usernames,\nchannel bot names, Git authors, provider account names, and other external\nidentifiers are bindings associated with an identity rather than identity\nitself.\n\n`System` is represented by a real identity and `IdentityID`. The empty string\nMUST NOT retain special meaning as a legacy system identity.\n\nConfiguration refers to identities by `IdentityID` and supplies external\nbindings and capability settings separately. Renaming an identity or changing an\nexternal account MUST NOT change ownership or historical attribution.\n\nSecret-bearing channel bindings remain configuration concerns rather than\nidentity data. In particular, `[chat.telegram].token` is a\n`secret.SecretRef` resolved by the application through the configured secret\nregistry. It does not change the identity that owns or performs a chat action.\n\n## Persistence\n\nIdentity records are durable domain state. The Identity domain's repository is\nthe source of truth; infrastructure implements its persistence contract.\n\nConfiguration MAY bootstrap a missing identity through an explicit, audited\ncreation operation and MAY propose runtime capability bindings for an existing\n`IdentityID`. Configuration is not the identity registry.\n\nOmitting an identity from configuration stops assembling the omitted runtime\ncapabilities. It MUST NOT delete the identity record, erase history, or make\nhistorical references unresolvable.\n\nDisabling or retiring an identity requires an explicit Identity-domain command.\nRetired identities remain resolvable for historical attribution. A failed\nexternal binding affects capability availability without destroying or silently\nreplacing the identity.\n\n## Lifecycle\n\nIdentity lifecycle is deliberately small:\n\n- `active`: may participate in runtime composition;\n- `suspended`: deliberately prevented from initiating new work while ownership\n and history remain;\n- `retired`: terminal, unable to initiate work, and permanently retained for\n attribution.\n\nAllowed transitions are:\n\n```text\ncreate -\u003e active\nactive -\u003e suspended\nsuspended -\u003e active\nactive -\u003e retired\nsuspended -\u003e retired\n```\n\n`retired` has no outgoing transition.\n\nCapability health is separate from identity lifecycle. Forge, model, channel,\nworkspace, and other bindings report health independently. An active identity\nmay be partially degraded without becoming suspended or reLine truncated
},
{
"url": "/dev/architecture/messaging-and-work-intake/",
@@ -27,7 +27,7 @@ func TestPublishedProjectionAgreesWithFrontEndsOnConfiguredChannels(t *testing.T
{
name: "telegram token",
cfg: config.Config{Chat: config.ChatConfig{
Telegram: config.TelegramConfig{TokenEnv: "TELEGRAM_TOKEN"},
Telegram: config.TelegramConfig{Token: config.SecretRef{Engine: "env", Key: "TELEGRAM_TOKEN"}},
}},
},
{
+2 -5
View File
@@ -356,11 +356,8 @@ func (b *boot) artifactSender() artifactsync.Sender {
return nil
}
if token == "" {
token = b.secrets.Getenv(cfg.TokenEnv)
}
if token == "" {
b.log.Warn("artifact publishing disabled: no service token; set the token secret or its environment variable",
"base_url", cfg.BaseURL, "token_env", cfg.TokenEnv)
b.log.Warn("artifact publishing disabled: the service token resolved empty",
"base_url", cfg.BaseURL, "token_engine", cfg.Token.Engine)
return nil
}
return artifactsync.NewClient(cfg.BaseURL, token)
+1 -1
View File
@@ -94,7 +94,7 @@ func reloadLoop(ctx context.Context, ch <-chan os.Signal, c *ReloadController, l
// handlers re-read on every request. MaxRetries is the worked example:
// its only consumer is api_tasks.go:380,383, reading per-request
// s.Cfg.Get(), and nothing in the daemon reads it -- so it reloads.
// Chat.Telegram.TokenEnv is the counter-example: webui reads it per
// Chat.Telegram.Token is the counter-example: webui reads it per
// request AND a telegram bot built at startup consumes it, so it is
// NOT reloadable, and treating "webui reads it" as sufficient would
// display a new token while the bot uses the old one.
@@ -48,7 +48,7 @@ func TestReloadChannelReachesTheChannelsOwnSeam(t *testing.T) {
dir := t.TempDir()
cfgPath := filepath.Join(dir, "config.toml")
write := func(userIDs string) {
content := "bot_user = \"testbot\"\n\n[chat.telegram]\ntoken_env = \"TEST_TG_TOKEN\"\nallowed_user_ids = " + userIDs + "\n"
content := "bot_user = \"testbot\"\n\n[chat.telegram]\ntoken = { engine = \"env\", key = \"TEST_TG_TOKEN\" }\nallowed_user_ids = " + userIDs + "\n"
if err := os.WriteFile(cfgPath, []byte(content), 0o600); err != nil {
t.Fatal(err)
}
@@ -83,7 +83,7 @@ func TestReloadCapabilityAndActionShareOneSource(t *testing.T) {
srv, err := compose(t.Context(), deps{
Config: ResolvedConfig{
TelegramToken: "token-123",
Telegram: config.TelegramConfig{TokenEnv: "TEST_TG_TOKEN", AllowedUserIDs: []int64{1}},
Telegram: config.TelegramConfig{Token: config.SecretRef{Engine: "env", Key: "TEST_TG_TOKEN"}, AllowedUserIDs: []int64{1}},
WebhookAddr: "127.0.0.1:0",
Webhook: config.WebhookRoute{Path: "/smoke"},
},
+2 -3
View File
@@ -122,10 +122,9 @@ func (s *Service) add(name string, ch channels.Channel, cfg map[string]any) erro
}
// telegramValidateConfigMap builds the map Gateway.ValidateConfig expects
// from the typed config, carrying whichever credential source is set
// (token takes precedence, matching resolveTelegramToken).
// from the typed config.
func telegramValidateConfigMap(cfg config.TelegramConfig) map[string]any {
m := map[string]any{"token_env": cfg.TokenEnv}
m := map[string]any{}
if cfg.Token != (secret.SecretRef{}) {
m["token"] = map[string]any{"engine": cfg.Token.Engine, "key": cfg.Token.Key}
}
+5 -9
View File
@@ -150,17 +150,13 @@ func merge(o Options, p projection) Options {
return o
}
// resolveTelegramToken reads whichever credential source is configured. A
// secret ref takes precedence over token_env, so a deployment that moved to
// a secret engine is not silently served by a stale environment variable.
// resolveTelegramToken resolves the configured bot token; an unset
// reference means the channel is off.
func resolveTelegramToken(cfg config.TelegramConfig, secrets *secret.Registry) (string, error) {
if cfg.Token != (secret.SecretRef{}) {
return secrets.Resolve(cfg.Token)
if cfg.Token == (secret.SecretRef{}) {
return "", nil
}
if cfg.TokenEnv != "" {
return os.Getenv(cfg.TokenEnv), nil
}
return "", nil
return secrets.Resolve(cfg.Token)
}
func resolveWebhookSecret(route config.WebhookRoute, secrets *secret.Registry) (string, error) {
+1 -1
View File
@@ -48,7 +48,7 @@ target = "127.0.0.1:8999"
target_token = "tok-123"
[chat.telegram]
token_env = "TEST_TG_TOKEN"
token = { engine = "env", key = "TEST_TG_TOKEN" }
allowed_user_ids = [12345]
`
if err := os.WriteFile(cfgPath, []byte(content), 0o600); err != nil {
+2 -2
View File
@@ -19,7 +19,7 @@ func TestServiceStartsConfiguredChannels(t *testing.T) {
Config: ResolvedConfig{
TelegramToken: "token-123",
Telegram: config.TelegramConfig{
TokenEnv: "TEST_TG_TOKEN",
Token: config.SecretRef{Engine: "env", Key: "TEST_TG_TOKEN"},
AllowedUserIDs: []int64{123},
},
Email: config.EmailConfig{
@@ -79,7 +79,7 @@ func TestComposeRejectsInvalidChannelConfig(t *testing.T) {
_, err = compose(t.Context(), deps{
Config: ResolvedConfig{
TelegramToken: "token-123",
// Neither token_env nor a token ref: telegram.ValidateConfig refuses.
// No token ref: telegram.ValidateConfig refuses.
},
Log: slog.Default(),
Chat: &dummyChatContract{},
@@ -43,7 +43,7 @@ func telegramChannel(t *testing.T, srv *Service) *telegram.Gateway {
func telegramConfig(t *testing.T, cfg ResolvedConfig, chat messaging.ChatContract) *telegram.Gateway {
t.Helper()
cfg.TelegramToken = "token-123"
cfg.Telegram.TokenEnv = "TEST_TG_TOKEN"
cfg.Telegram.Token = config.SecretRef{Engine: "env", Key: "TEST_TG_TOKEN"}
cfg.Telegram.AllowedUserIDs = []int64{7}
srv, err := compose(t.Context(), deps{Config: cfg, Log: slog.New(slog.DiscardHandler), Chat: chat})
if err != nil {
@@ -173,7 +173,7 @@ func TestTelegramReloadRereadsTokenAndAllowlist(t *testing.T) {
dir := t.TempDir()
cfgPath := filepath.Join(dir, "config.toml")
write := func(userIDs string) {
content := "bot_user = \"testbot\"\n\n[chat.telegram]\ntoken_env = \"TEST_TG_TOKEN\"\nallowed_user_ids = " + userIDs + "\n"
content := "bot_user = \"testbot\"\n\n[chat.telegram]\ntoken = { engine = \"env\", key = \"TEST_TG_TOKEN\" }\nallowed_user_ids = " + userIDs + "\n"
if err := os.WriteFile(cfgPath, []byte(content), 0o600); err != nil {
t.Fatal(err)
}
@@ -213,7 +213,7 @@ func TestTelegramReloadRereadsTokenAndAllowlist(t *testing.T) {
func TestTelegramReloadRefusesAnEmptyToken(t *testing.T) {
dir := t.TempDir()
cfgPath := filepath.Join(dir, "config.toml")
content := "bot_user = \"testbot\"\n\n[chat.telegram]\ntoken_env = \"TEST_TG_TOKEN\"\nallowed_user_ids = [1]\n"
content := "bot_user = \"testbot\"\n\n[chat.telegram]\ntoken = { engine = \"env\", key = \"TEST_TG_TOKEN\" }\nallowed_user_ids = [1]\n"
if err := os.WriteFile(cfgPath, []byte(content), 0o600); err != nil {
t.Fatal(err)
}
@@ -18,66 +18,11 @@ func (testSecretEngine) Resolve(key string) (string, error) {
return "", nil
}
func TestResolveTelegramTokenPrefersSecretRef(t *testing.T) {
registry := secret.NewRegistry()
registry.Register(testSecretEngine{})
cfg := config.TelegramConfig{
Token: secret.SecretRef{Engine: "bws", Key: "telegram-token"},
TokenEnv: "TELEGRAM_LEGACY_TOKEN",
}
t.Setenv("TELEGRAM_LEGACY_TOKEN", "token-from-env")
got, err := resolveTelegramToken(cfg, registry)
if err != nil {
t.Fatalf("resolveTelegramToken returned error: %v", err)
}
if got != "token-from-bws" {
t.Fatalf("resolveTelegramToken = %q, want token-from-bws", got)
}
}
func TestResolveTelegramTokenFallsBackToTokenEnv(t *testing.T) {
registry := secret.NewRegistry()
cfg := config.TelegramConfig{TokenEnv: "TELEGRAM_LEGACY_TOKEN"}
t.Setenv("TELEGRAM_LEGACY_TOKEN", "token-from-env")
got, err := resolveTelegramToken(cfg, registry)
if err != nil {
t.Fatalf("resolveTelegramToken returned error: %v", err)
}
if got != "token-from-env" {
t.Fatalf("resolveTelegramToken = %q, want token-from-env", got)
}
}
func TestResolveTelegramTokenDoesNotUseTokenEnvWhenSecretRefIsSet(t *testing.T) {
registry := secret.NewRegistry()
registry.Register(testSecretEngine{})
cfg := config.TelegramConfig{
Token: secret.SecretRef{Engine: "bws", Key: "telegram-token"},
TokenEnv: "TELEGRAM_LEGACY_TOKEN",
}
t.Setenv("TELEGRAM_LEGACY_TOKEN", "token-from-env")
got, err := resolveTelegramToken(cfg, registry)
if err != nil {
t.Fatalf("resolveTelegramToken returned error: %v", err)
}
if got == "token-from-env" {
t.Fatal("resolveTelegramToken used TokenEnv despite Token being configured")
}
}
// TestResolveTelegramTokenAcceptsTokenRefWithoutTokenEnv is the regression
// guard for channels-telegram-5: a deployment configured only via
// chat.telegram.token must resolve, since Token takes precedence over
// TokenEnv and requiring both would reject every secret-engine setup.
func TestResolveTelegramTokenAcceptsTokenRefWithoutTokenEnv(t *testing.T) {
func TestResolveTelegramTokenResolvesSecretRef(t *testing.T) {
registry := secret.NewRegistry()
registry.Register(testSecretEngine{})
cfg := config.TelegramConfig{
Token: secret.SecretRef{Engine: "bws", Key: "telegram-token"},
// TokenEnv deliberately left empty.
}
got, err := resolveTelegramToken(cfg, registry)
@@ -33,7 +33,7 @@ func seedChannels(cfg config.Config) any {
Operator: chat.Operator, Workspace: chat.Workspace, UnrestrictedFilesystem: chat.UnrestrictedFilesystem, ShowToolCalls: chat.ShowToolCalls, MaxSteps: chat.MaxSteps, Models: chat.Models,
Email: emailSettings{ListenAddr: chat.Email.ListenAddr, RelayAddr: chat.Email.RelayAddr},
WebhookAddr: chat.WebhookAddr,
Telegram: telegramSettings{AllowedUserIDs: chat.Telegram.AllowedUserIDs, Token: chat.Telegram.Token, TokenEnv: chat.Telegram.TokenEnv, CredentialConfigured: chat.Telegram.TokenEnv != "" || chat.Telegram.Token != (config.SecretRef{})},
Telegram: telegramSettings{AllowedUserIDs: chat.Telegram.AllowedUserIDs, Token: chat.Telegram.Token, CredentialConfigured: chat.Telegram.Token != (config.SecretRef{})},
Webhook: webhookChannelSettings{Path: chat.Webhook.Path, Secret: chat.Webhook.Secret, CredentialConfigured: chat.Webhook.Secret != (config.SecretRef{}), Template: chat.Webhook.Template, DeliverTo: chat.Webhook.DeliverTo},
RateLimit: rateLimitSettings{Window: channelDuration(chat.RateLimit.Window), MaxRequests: chat.RateLimit.MaxRequests},
}
+7 -21
View File
@@ -892,25 +892,15 @@ func updateThreadID(update *models.Update) int {
}
// ConfigSchema returns the JSON Schema for the Telegram channel config.
// The bot token may be supplied either directly as token_env (an
// environment variable name) or as token (a secret reference object with
// engine/key); token takes precedence when both are set, matching
// resolveTelegramToken's own precedence.
// The bot token is a secret reference object with engine/key.
func (g *Gateway) ConfigSchema() json.RawMessage {
return json.RawMessage(`{
"type": "object",
"anyOf": [
{ "required": ["token_env"] },
{ "required": ["token"] }
],
"required": ["token"],
"properties": {
"token_env": {
"type": "string",
"description": "Environment variable holding the Telegram bot token from @BotFather"
},
"token": {
"type": "object",
"description": "Secret reference for the bot token, resolved through the configured secret engine. Takes precedence over token_env.",
"description": "Secret reference for the Telegram bot token from @BotFather, resolved through the configured secret engine.",
"properties": {
"engine": { "type": "string" },
"key": { "type": "string" }
@@ -925,18 +915,14 @@ func (g *Gateway) ConfigSchema() json.RawMessage {
}`)
}
// ValidateConfig checks the Telegram channel configuration. A token is
// required, supplied either as token (a secret reference) or token_env
// (an environment variable name) -- either credential source is valid,
// matching resolveTelegramToken's precedence in the daemon's boot path.
// ValidateConfig checks the Telegram channel configuration. A token
// secret reference is required.
func (g *Gateway) ValidateConfig(cfg map[string]any) error {
if cfg == nil {
return fmt.Errorf("telegram config is required")
}
tokenEnv, _ := cfg["token_env"].(string)
_, hasTokenRef := cfg["token"]
if tokenEnv == "" && !hasTokenRef {
return fmt.Errorf("telegram.token or telegram.token_env is required")
if _, ok := cfg["token"]; !ok {
return fmt.Errorf("telegram.token is required")
}
return nil
}
+3 -10
View File
@@ -633,23 +633,16 @@ func TestLaunchDropsPendingUpdatesBeforePolling(t *testing.T) {
}
}
func TestValidateConfigAcceptsTokenEnv(t *testing.T) {
g := New("token", nil, slog.Default())
if err := g.ValidateConfig(map[string]any{"token_env": "TELEGRAM_BOT_TOKEN"}); err != nil {
t.Errorf("ValidateConfig with token_env set = %v, want nil", err)
}
}
func TestValidateConfigAcceptsTokenRef(t *testing.T) {
g := New("token", nil, slog.Default())
if err := g.ValidateConfig(map[string]any{"token": map[string]any{"engine": "env", "key": "TELEGRAM_BOT_TOKEN"}}); err != nil {
t.Errorf("ValidateConfig with a token secret ref set = %v, want nil: chat.telegram.token is an equally valid credential source to token_env", err)
t.Errorf("ValidateConfig with a token secret ref set = %v, want nil", err)
}
}
func TestValidateConfigRejectsNeitherCredential(t *testing.T) {
func TestValidateConfigRejectsMissingToken(t *testing.T) {
g := New("token", nil, slog.Default())
if err := g.ValidateConfig(map[string]any{}); err == nil {
t.Error("ValidateConfig with neither token nor token_env set = nil, want an error")
t.Error("ValidateConfig with no token set = nil, want an error")
}
}
+1 -1
View File
@@ -34,7 +34,7 @@ func (c ChatConfig) FrontEnds() []ChatFrontEnd {
{
ID: "telegram",
Name: "Telegram",
Configured: c.Telegram.Token != (SecretRef{}) || strings.TrimSpace(c.Telegram.TokenEnv) != "",
Configured: c.Telegram.Token != (SecretRef{}),
},
{
ID: "email",
+2 -9
View File
@@ -18,11 +18,6 @@ func TestChatConfigFrontEnds(t *testing.T) {
chat: ChatConfig{},
want: map[string]bool{"telegram": false, "email": false, "webhook": false},
},
{
name: "telegram bot token from the environment",
chat: ChatConfig{Telegram: TelegramConfig{TokenEnv: "TELEGRAM_TOKEN"}},
want: map[string]bool{"telegram": true, "email": false, "webhook": false},
},
{
name: "telegram bot token through the secret engine",
chat: ChatConfig{Telegram: TelegramConfig{Token: SecretRef{Engine: "builtin", Key: "telegram"}}},
@@ -41,18 +36,16 @@ func TestChatConfigFrontEnds(t *testing.T) {
{
name: "every front-end at once",
chat: ChatConfig{
Telegram: TelegramConfig{TokenEnv: "TELEGRAM_TOKEN"},
Telegram: TelegramConfig{Token: SecretRef{Engine: "env", Key: "TELEGRAM_TOKEN"}},
Email: EmailConfig{ListenAddr: "127.0.0.1:2525"},
WebhookAddr: "127.0.0.1:9099",
},
want: map[string]bool{"telegram": true, "email": true, "webhook": true},
},
{
// Whitespace is not a value: an env var name of " " resolves
// to nothing and " " cannot be listened on.
// Whitespace is not a value: " " cannot be listened on.
name: "whitespace-only values are not configured",
chat: ChatConfig{
Telegram: TelegramConfig{TokenEnv: " "},
Email: EmailConfig{ListenAddr: " "},
WebhookAddr: "\t",
},
+5 -12
View File
@@ -192,10 +192,9 @@ const (
// Forge configures the code forge integration.
type Forge struct {
Type string `toml:"type" yaml:"type"`
Host string `toml:"host" yaml:"host"`
Token SecretRef `toml:"token" yaml:"token"`
TokenEnv string `toml:"token_env" yaml:"token_env"`
Type string `toml:"type" yaml:"type"`
Host string `toml:"host" yaml:"host"`
Token SecretRef `toml:"token" yaml:"token"`
// Intake selects how forge issues become work: "poll" (default),
// "webhook", or "both". Webhook intake reacts to forge events the moment
// they arrive instead of up to poll_interval later.
@@ -534,9 +533,6 @@ type ArtifactsConfig struct {
BaseURL string `toml:"base_url" yaml:"base_url"`
// Token is the service credential the editor's ingest route requires.
Token SecretRef `toml:"token" yaml:"token"`
// TokenEnv names the environment variable holding the token when Token
// is unset. Defaults to WORKSPACE_INGEST_TOKEN.
TokenEnv string `toml:"token_env" yaml:"token_env"`
}
// IdentityConfig is a per-identity configuration subset. Each identity
@@ -1046,12 +1042,9 @@ type TelegramConfig struct {
// bot to a group does not grant that group's members access. Empty
// denies everyone.
AllowedUserIDs []int64 `toml:"allowed_user_ids" yaml:"allowed_user_ids"`
// Token references the bot token through the configured secret engine.
// It takes precedence over TokenEnv when both are set.
// Token references the bot token from @BotFather through the configured
// secret engine. Empty disables the Telegram channel.
Token SecretRef `toml:"token" yaml:"token"`
// TokenEnv names the env var holding the bot token from @BotFather.
// Empty disables the Telegram channel.
TokenEnv string `toml:"token_env" yaml:"token_env"`
// UpdateCheckCommand writes a releaseupdate.Snapshot JSON document to
// stdout. UpdateInstallCommand applies an already-approved update. Both
// are argv arrays, never shell snippets.
+2 -2
View File
@@ -1960,7 +1960,7 @@ func configWithCanarySecrets() config.Config {
BotEmail: "archie@example.com",
Label: "archie",
Forge: config.Forge{
Type: "gitea", Host: "gitea.example.com", TokenEnv: "GITEA_TOKEN",
Type: "gitea", Host: "gitea.example.com",
Token: secret.SecretRef{Engine: "bws", Key: canaryForgeToken},
WebhookSecret: secret.SecretRef{Engine: "bws", Key: canaryWebhookSecret},
Intake: "webhook",
@@ -1984,7 +1984,7 @@ func configWithCanarySecrets() config.Config {
Notify: config.Notify{Webhook: "https://hooks.example.com/notify"},
Tools: config.ToolsConfig{Policy: config.ToolPolicy{MaxResultChars: 12000, SpillDir: "/tmp/spill"}},
NATS: config.NATSConfig{Mode: "external", URL: "nats://127.0.0.1:4222", TokenEnv: canaryNATSTokenEnv},
Chat: config.ChatConfig{Operator: "sam", Telegram: config.TelegramConfig{TokenEnv: "TELEGRAM_TOKEN", Token: secret.SecretRef{Engine: "bws", Key: canaryTelegramToken}}},
Chat: config.ChatConfig{Operator: "sam", Telegram: config.TelegramConfig{Token: secret.SecretRef{Engine: "bws", Key: canaryTelegramToken}}},
Services: config.Services{config.ServiceNameState: {Target: "127.0.0.1:50051", TargetToken: canaryStateStoreToken}},
ModelLimits: map[string]config.ModelLimits{
"openai/gpt-4": {ContextWindow: 128000, MaxOutputTokens: 4096},
@@ -11,7 +11,7 @@ import (
func TestArtifactsConfigDefaults(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.toml")
contents := "bot_user = \"widget\"\n" +
"[forge]\ntype = \"gitea\"\nhost = \"https://git.example.test\"\ntoken_env = \"T\"\n"
"[forge]\ntype = \"gitea\"\nhost = \"https://git.example.test\"\n"
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
t.Fatal(err)
}
@@ -22,8 +22,8 @@ func TestArtifactsConfigDefaults(t *testing.T) {
if cfg.Artifacts.BaseURL != "" {
t.Errorf("BaseURL = %q, want empty so the sender stays disabled", cfg.Artifacts.BaseURL)
}
if cfg.Artifacts.TokenEnv != "WORKSPACE_INGEST_TOKEN" {
t.Errorf("TokenEnv = %q, want the documented fallback", cfg.Artifacts.TokenEnv)
if want := (config.SecretRef{Engine: "env", Key: "WORKSPACE_INGEST_TOKEN"}); cfg.Artifacts.Token != want {
t.Errorf("Token = %+v, want the documented fallback %+v", cfg.Artifacts.Token, want)
}
}
@@ -31,8 +31,7 @@ func TestArtifactsConfigPreservesExplicitValues(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.toml")
contents := "bot_user = \"widget\"\n" +
"[artifacts]\nbase_url = \"https://offloaded.dev\"\n" +
"token = { engine = \"env\", key = \"ARCHIE_GITHUB_TOKEN\" }\n" +
"token_env = \"OTHER_TOKEN\"\n"
"token = { engine = \"env\", key = \"ARCHIE_GITHUB_TOKEN\" }\n"
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
t.Fatal(err)
}
@@ -46,7 +45,4 @@ func TestArtifactsConfigPreservesExplicitValues(t *testing.T) {
if want := (config.SecretRef{Engine: "env", Key: "ARCHIE_GITHUB_TOKEN"}); cfg.Artifacts.Token != want {
t.Errorf("Token = %+v, want %+v", cfg.Artifacts.Token, want)
}
if cfg.Artifacts.TokenEnv != "OTHER_TOKEN" {
t.Errorf("TokenEnv = %q, want the explicit value", cfg.Artifacts.TokenEnv)
}
}
@@ -281,22 +281,16 @@ func applyForgeDefaults(cfg *config.Config) {
if cfg.Forge.Host == "" {
cfg.Forge.Host = defaultForgeHost
}
if cfg.Forge.Token.Engine == "" && cfg.Forge.Token.Key == "" && cfg.Forge.TokenEnv != "" {
cfg.Forge.Token = config.SecretRef{Engine: "env", Key: cfg.Forge.TokenEnv}
}
if cfg.Forge.Intake == "" {
cfg.Forge.Intake = config.ForgeIntakePoll
}
}
// applyArtifactsDefaults fills the artifacts section, promoting the
// token_env fallback to a secret reference when no explicit one was given.
// applyArtifactsDefaults reads the artifacts token from WORKSPACE_INGEST_TOKEN
// when no secret reference is given.
func applyArtifactsDefaults(cfg *config.Config) {
if cfg.Artifacts.TokenEnv == "" {
cfg.Artifacts.TokenEnv = "WORKSPACE_INGEST_TOKEN"
}
if cfg.Artifacts.Token == (config.SecretRef{}) {
cfg.Artifacts.Token = config.SecretRef{Engine: "env", Key: cfg.Artifacts.TokenEnv}
cfg.Artifacts.Token = config.SecretRef{Engine: "env", Key: "WORKSPACE_INGEST_TOKEN"}
}
}
@@ -171,57 +171,10 @@ func TestResolveSelectsFileFormatsAndDirectories(t *testing.T) {
}
}
// TestLoadForgeTokenEnvBackwardCompat guards against a real production
// incident: the secrets-engine migration replaced [forge]'s flat
// token_env string with a {engine, key} struct, but TOML silently ignores
// unknown fields — so deployed configs still using the old token_env key
// had their token config dropped entirely and finalize() defaulted to
// demanding ARCHIE_GITHUB_TOKEN, crash-looping a gitea-backed daemon.
func TestLoadForgeTokenEnvBackwardCompat(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.toml")
contents := "bot_user = \"widget\"\n" +
"[forge]\ntype = \"gitea\"\nhost = \"https://git.example.test\"\ntoken_env = \"MY_GITEA_TOKEN\"\n" +
"[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
t.Fatal(err)
}
cfg, err := loadFile(path)
if err != nil {
t.Fatal(err)
}
if cfg.Forge.Token != (secret.SecretRef{Engine: "env", Key: "MY_GITEA_TOKEN"}) {
t.Errorf("Forge.Token = %#v, want {env MY_GITEA_TOKEN} (from legacy token_env)", cfg.Forge.Token)
}
}
// TestLoadForgeTokenTakesPrecedenceOverTokenEnv verifies the new-style
// [forge.token] wins when both the legacy token_env and the new token
// struct are present (e.g. mid-migration configs).
func TestLoadForgeTokenTakesPrecedenceOverTokenEnv(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.toml")
contents := "bot_user = \"widget\"\n" +
"[forge]\ntype = \"gitea\"\ntoken_env = \"OLD_TOKEN\"\n" +
"[forge.token]\nengine = \"env\"\nkey = \"NEW_TOKEN\"\n" +
"[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
t.Fatal(err)
}
cfg, err := loadFile(path)
if err != nil {
t.Fatal(err)
}
if cfg.Forge.Token != (secret.SecretRef{Engine: "env", Key: "NEW_TOKEN"}) {
t.Errorf("Forge.Token = %#v, want {env NEW_TOKEN} (new-style token wins)", cfg.Forge.Token)
}
}
func TestLoadTelegramTokenSecretRefAndLegacyFallback(t *testing.T) {
func TestLoadTelegramTokenSecretRef(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.toml")
contents := "bot_user = \"widget\"\n" +
"[chat.telegram]\ntoken = { engine = \"bws\", key = \"TELEGRAM_BOT_TOKEN\" }\n" +
"token_env = \"TELEGRAM_LEGACY_TOKEN\"\n" +
"[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
t.Fatal(err)
@@ -235,9 +188,6 @@ func TestLoadTelegramTokenSecretRefAndLegacyFallback(t *testing.T) {
if cfg.Chat.Telegram.Token != want {
t.Errorf("Telegram.Token = %#v, want %#v", cfg.Chat.Telegram.Token, want)
}
if cfg.Chat.Telegram.TokenEnv != "TELEGRAM_LEGACY_TOKEN" {
t.Errorf("Telegram.TokenEnv = %q, want TELEGRAM_LEGACY_TOKEN", cfg.Chat.Telegram.TokenEnv)
}
}
// TestLoadRejectsInvalidConfigEnumsAndGlobs pins which layer rejects each kind
@@ -910,7 +860,7 @@ ecosystem = "go"
func TestIdentitiesConfigFallsBackToLegacyWhenEmpty(t *testing.T) {
cfg, err := loadBytes([]byte(`
bot_user = "solo"
forge = { type = "github", host = "https://github.test", token_env = "GH_TOKEN" }
forge = { type = "github", host = "https://github.test", token = { engine = "env", key = "GH_TOKEN" } }
[[repos]]
owner = "acme"
@@ -931,7 +881,7 @@ func TestIdentitiesConfigRejectsEmptyName(t *testing.T) {
_, err := loadBytes([]byte(`
[[identities]]
bot_user = "no-name"
forge = { type = "github", token_env = "X" }
forge = { type = "github", token = { engine = "env", key = "X" } }
`))
if err == nil {
t.Error("expected error for identity with empty name")
@@ -314,8 +314,8 @@ func TestRun_TelegramWithAllowedUserIDs(t *testing.T) {
t.Fatalf("Commit: %v", err)
}
cfg := generateAndLoad(t, edits)
if cfg.Chat.Telegram.TokenEnv != "ARCHIE_TELEGRAM_TOKEN" {
t.Errorf("chat.telegram.token_env = %q, want ARCHIE_TELEGRAM_TOKEN", cfg.Chat.Telegram.TokenEnv)
if want := (config.SecretRef{Engine: "env", Key: "ARCHIE_TELEGRAM_TOKEN"}); cfg.Chat.Telegram.Token != want {
t.Errorf("chat.telegram.token = %+v, want %+v", cfg.Chat.Telegram.Token, want)
}
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)
@@ -10,10 +10,8 @@ import (
"github.com/samcharles93/archie-core/internal/infrastructure/configuration/tomlwrite"
)
// telegramTokenEnv is the env var Telegram's bot token is stored under.
// TelegramConfig has no secret.SecretRef field -- unlike the forge and
// provider steps, the config edit is a plain token_env string, not a
// {engine,key} inline table.
// telegramTokenEnv is the env var a prompted Telegram bot token is stored
// under.
const telegramTokenEnv = "ARCHIE_TELEGRAM_TOKEN"
func stepChat(ctx context.Context, p Prompter, secrets SecretSink, params Params) (tableEdits, error) {
@@ -30,14 +28,11 @@ func stepChat(ctx context.Context, p Prompter, secrets SecretSink, params Params
}
// A reference means the value already lives in a secret engine: write the
// reference and ask nothing. A supplied reference may name any engine, which
// the legacy token_env form cannot express, so it writes the preferred
// secret-reference form instead. Otherwise the token comes from a prompt, and
// reference and ask nothing. Otherwise the token comes from a prompt, and
// only from a prompt; see stepForgeWithToken.
tokenForm := "token_env"
tokenValue := tomlwrite.String(telegramTokenEnv)
tokenValue := tomlwrite.Ref("env", telegramTokenEnv)
if ref := params.TelegramTokenRef; ref != (config.SecretRef{}) {
tokenForm, tokenValue = "token", tomlwrite.Ref(ref.Engine, ref.Key)
tokenValue = tomlwrite.Ref(ref.Engine, ref.Key)
} else {
token, err := p.ReadSecret(ctx, "Telegram bot token (from @BotFather): ")
if err != nil {
@@ -72,7 +67,7 @@ func stepChat(ctx context.Context, p Prompter, secrets SecretSink, params Params
return tableEdits{
"chat.telegram": {
tokenForm: tokenValue,
"token": tokenValue,
"allowed_user_ids": intArrayLiteral(ids),
},
}, nil
@@ -95,7 +95,7 @@ func RuntimeChatConfigFrom(ctx context.Context, reader ResourceReader, base conf
Operator: settings.Operator, ShowToolCalls: settings.ShowToolCalls, MaxSteps: settings.MaxSteps,
Models: settings.Models, Email: config.EmailConfig{ListenAddr: settings.Email.ListenAddr, RelayAddr: settings.Email.RelayAddr}, WebhookAddr: settings.WebhookAddr,
Webhook: config.WebhookRoute{Path: settings.Webhook.Path, Secret: settings.Webhook.Secret, Template: settings.Webhook.Template, DeliverTo: settings.Webhook.DeliverTo},
Telegram: config.TelegramConfig{AllowedUserIDs: settings.Telegram.AllowedUserIDs, Token: settings.Telegram.Token, TokenEnv: settings.Telegram.TokenEnv, UpdateCheckCommand: check, UpdateInstallCommand: install},
Telegram: config.TelegramConfig{AllowedUserIDs: settings.Telegram.AllowedUserIDs, Token: settings.Telegram.Token, UpdateCheckCommand: check, UpdateInstallCommand: install},
RateLimit: config.RateLimitConfig{Window: time.Duration(settings.RateLimit.Window), MaxRequests: settings.RateLimit.MaxRequests},
UnrestrictedFilesystem: settings.UnrestrictedFilesystem, Workspace: settings.Workspace,
}
@@ -33,7 +33,6 @@ type ChannelSettings struct {
type TelegramSettings struct {
AllowedUserIDs []int64 `json:"allowed_user_ids"`
Token config.SecretRef `json:"token_ref"`
TokenEnv string `json:"token_env,omitempty"`
CredentialConfigured bool `json:"credential_configured"`
}
+5 -6
View File
@@ -35,10 +35,9 @@ func configWithFakeSecrets() *config.Holder {
BotEmail: "archie@example.com",
Label: "archie",
Forge: config.Forge{
Type: "gitea",
Host: "gitea.example.com",
TokenEnv: "GITEA_TOKEN",
Token: secret.SecretRef{Engine: "env", Key: fakeForgeToken},
Type: "gitea",
Host: "gitea.example.com",
Token: secret.SecretRef{Engine: "env", Key: fakeForgeToken},
},
Models: map[string]string{"builder": "openai/gpt-4"},
Providers: map[string]config.Provider{
@@ -58,7 +57,7 @@ func configWithFakeSecrets() *config.Holder {
},
NATS: config.NATSConfig{URL: "nats://127.0.0.1:4222", TokenEnv: "NATS_TOKEN"},
Chat: config.ChatConfig{
Telegram: config.TelegramConfig{TokenEnv: "TELEGRAM_TOKEN"},
Telegram: config.TelegramConfig{Token: secret.SecretRef{Engine: "env", Key: "TELEGRAM_TOKEN"}},
},
})
}
@@ -109,7 +108,7 @@ func TestBuildConfigViewPublishesPerIdentityForges(t *testing.T) {
},
{
Name: "github-bot",
Forge: config.Forge{Type: "github", Host: "https://github.example", TokenEnv: fakeForgeToken},
Forge: config.Forge{Type: "github", Host: "https://github.example", Token: secret.SecretRef{Engine: "env", Key: fakeForgeToken}},
Repos: []config.Repo{{Owner: "beta", Name: "app"}},
},
},
+2 -2
View File
@@ -37,7 +37,7 @@ func TestSetupChecklistRendersFromTheProjection(t *testing.T) {
Repos: []config.Repo{{Owner: "acme", Name: "widget"}},
Chat: config.ChatConfig{
Operator: "Sam",
Telegram: config.TelegramConfig{TokenEnv: "TELEGRAM_TOKEN"},
Telegram: config.TelegramConfig{Token: config.SecretRef{Engine: "env", Key: "TELEGRAM_TOKEN"}},
},
},
wantOperator: "Sam",
@@ -120,7 +120,7 @@ func TestSetupChecklistChatChannelStepCountsEveryFrontEnd(t *testing.T) {
{
name: "telegram token env",
cfg: config.Config{Chat: config.ChatConfig{
Telegram: config.TelegramConfig{TokenEnv: "TELEGRAM_TOKEN"},
Telegram: config.TelegramConfig{Token: config.SecretRef{Engine: "env", Key: "TELEGRAM_TOKEN"}},
}},
want: true,
},