Skip to content

fix(discord): the bot token comes from the environment on every read, and no copy is stored (TASK-124) - #1889

Merged
lilyshen0722 merged 1 commit into
mainfrom
kai/task124-discord-token-env
Sep 25, 2026
Merged

lilyshen0722 merged 1 commit into
mainfrom
kai/task124-discord-token-env

Conversation

@lilyshen0722

@lilyshen0722 lilyshen0722 commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

The defect

DISCORD_BOT_TOKEN is instance-wide, so rotating it has to reach integrations that were connected before the rotation. It did not: every read resolved the token itself, and three of them prefered a copy stored on the integration row (Vera 73344–73346 — all three discord_integrations documents carried a 72-char copy; Wren 73376/73377). A rotated env var reached new connectors and left existing ones authenticating as the old token.

What this changes (step 1 of Wren's split, with Vera 73384)

One definition decides the precedence — backend/utils/discordBotToken.ts, env first, stored copy only as a fallback for rows that predate the copy being retired — and every read calls it:

site was
integrations/providers/discordProvider.ts config → platformIntegration → env (the stored copy won)
services/discordService.ts (3 sites) one doc-first, two with no env fallback at all
routes/agentsRuntime.ts 400ed when the row carried no copy — a rotation would have read as a Discord fault
routes/registry/helpers.ts config.botToken || env — this is what the provisioner puts in moltbot.json
routes/integrations.ts (resolveEffectiveConfig) validation read, config.botToken || env

Writes stop. The create path no longer stores process.env.DISCORD_BOT_TOKEN on DiscordIntegration, and controllers/discordController.ts no longer persists a body-supplied botToken on either create or update. (A caller-supplied botToken in config was already refused as server-owned; this closes the two server-side writers.)

DiscordIntegration.botToken becomes optional. It was required: true, so "stop writing it" and "the row still saves" are one claim. The toJSON delete stays — the three legacy rows still carry a value.

What is deliberately NOT here

The data step. Dropping the write does not touch stored data (toObject/get/lean still return it), and the field has to stay readable until the stored copies are cleared. Clearing the three documents is its own change, after one live Discord post verifies on the deployed build.

Witnesses (17 new, across five files — each site's own)

  • backend/__tests__/unit/utils/discordBotToken.test.js (6) — the precedence: env over a stored copy, env over a 72-char real-looking copy, fallback when env is absent, blank env treated as absent, trim.
  • backend/__tests__/unit/services/discordService.test.js (+3) — the header that leaves the process for a legacy row, the fallback, and fetchMessages.
  • backend/__tests__/unit/routes/integrations.discordTokenCopy.test.js (3) — create path: the row is asserted to exist with its webhook fields before the token is asserted absent (so the absence cannot pass on a row that was never written), the response leaks neither field, and with the env var absent the create is still refused before any row or webhook exists.
  • backend/__tests__/unit/routes/agentsRuntime.integrations.messages.test.js (+3) — a row with a stale copy fetches with the env token; a row with no copy no longer 400s while the env supplies it; both absent still refuses.
  • backend/__tests__/unit/routes/registry.helpers.discordChannelToken.test.js (3) — the channel binding handed to a runtime.

Mutation ledger (five arms, four redden their own witness by name)

mutation result
M1 resolver env-last 6 red — both precedence cases, the wire header, fetchMessages, the channel binding, the messages route
M2 create path stores the copy again 1 red — the create-path witness
M3 botToken required again 2 red — the row no longer saves, and the response test
M4 helpers.ts stored-first 1 red — the channel-binding witness
M5 agentsRuntime uses the row copy 1 red — the messages-route witness

Base and restored runs: 35/35 passed. One disclosed survivor: reverting the validation read (integrations.ts resolveEffectiveConfig) to stored-first reddens nothing — that read only decides whether the manifest's required-field check passes, and its precedence is unobservable whenever the env supplies the token. It is a tripwire, not coverage.

Verification after deploy

One live Discord post on the deployed build (the acceptance Vera's split names), then the separate data step for the three legacy copies. Backend-only ⇒ no package version slot.

Premise, corrected after the copies were probed (connector-ops 74055)

The three stored copies are not a latent shadow. Probed read-only against Discord from inside the backend pod: DISCORD_BOT_TOKEN → 200, the single distinct stored copy → 401. The rotation happened and Discord's reset revoked the old token — so the copy that won every one of the reads above is a dead credential.

Step 1 is therefore a fix, not future-proofing ("so a rotation reaches existing integrations" in the section above understates it):

  • routes/agentsRuntime.ts:3438-3444 reads integration.config?.botToken off an Integration row — a different document from discord_integrations. No 72-char copy was ever written to Integration.config (Vera, live Mongo: absent on all three live rows), so on the base this read is not shadowed, it 400s today; where a copy did exist it sent the stored copy and never consulted env. Two stores, two failure modes, one missing precedence — which is the argument for the single resolver.
  • services/discordService.ts:462 (config.botToken || env, doc-first), :478 getChannels and :511 testConnection — the stored copy; the last two with no env fallback at all.

Acceptance note — what can and cannot verify this

POST /api/integrations/:id/send cannot verify the token change: DiscordService.sendMessage (services/discordService.ts:387-395) posts to platformIntegration.webhookUrl with Content-Type and no Authorization header — a Discord webhook URL authenticates itself — and the agent outbound path uses the module config (config/discord.ts:24 = process.env.DISCORD_BOT_TOKEN, read at :881/:1037), which was already valid. The instruments that discriminate:

  1. after reprovision-all, the channel binding in the ConfigMap — channels.discord.accounts[<integrationId>].token must be the env value, since that is the credential agents authenticate with;
  2. GET /api/agents/runtime/pods/<podId>/integrations/<integrationId>/messages with an agent token — read-only, and it discriminates on live rows today: the base answers 400 "Discord integration missing botToken" (Integration.config carries no copy), the build resolves env and answers 200. (Corrected from an earlier draft of this section: this read did not hand Discord the revoked copy — that copy lives in discord_integrations, which this route never reads.) fetchMessages has no try/catch around its axios call (Vera 74061), so had the copy been present a 401 would have surfaced as a 500 rather than an empty 200 — it discriminates either way.

A webhook send remains a worthwhile connector liveness check; it proves the webhook URL, not the rotation.

Disclosed, neither a hold (vera 74059)

  • The module config freezes process.env.DISCORD_BOT_TOKEN at load while the resolver reads it per call — a second precedence in the file, moot without a restart.
  • This field now has two write-path shapes: integrations.ts:395/:706 400 a supplied botToken via serverOwnedConfigError, while discordController accepts and ignores it. Nothing is persisted either way; the shape ruling is wren's.

…d, and stop storing a copy (TASK-124)

The token is instance-wide, so rotating DISCORD_BOT_TOKEN has to reach
integrations that were connected before the rotation. It did not: every read
resolved the token itself and three of them prefered a copy stored on the
integration row (Vera 73344-73346 — all three `discord_integrations`
documents carried a 72-char copy; Wren 73376/73377).

One definition now decides the precedence — `resolveDiscordBotToken`, env
first, stored copy only as a fallback for rows that predate the copy being
retired — and every read calls it:

  - integrations/providers/discordProvider.ts (was config -> platformIntegration -> env)
  - services/discordService.ts (three sites: the doc copy won at one, two had no env fallback at all)
  - routes/agentsRuntime.ts (400ed when the row had no copy, so a fresh connect would have failed the live check)
  - routes/registry/helpers.ts, routes/integrations.ts's validation read

Writes stop: the create path no longer stores `process.env.DISCORD_BOT_TOKEN`
on `DiscordIntegration`, and `controllers/discordController.ts` no longer
persists a body-supplied one. `DiscordIntegration.botToken` becomes optional —
it was `required: true`, so "stop writing it" and "the row still saves" are one
claim — and the toJSON delete stays, because the three legacy rows still carry
a value until the data step clears them.

The data step (clearing the stored copies) is deliberately NOT here: dropping
the write does not touch stored data, and the field has to stay readable until
that step runs.

Witnesses (17 across five files, each site's own): the precedence itself
(six cases), the header that leaves the process for a legacy row, the create
path — where the row is asserted to exist with its webhook fields before its
token is asserted absent, so the absence cannot pass on a row that was never
written — the channel binding a runtime is handed, and the agent-facing
messages route, which is also the one that used to 400 when a row carried no
copy.
@lilyshen0722
lilyshen0722 added this pull request to the merge queue Sep 25, 2026
Merged via the queue into main with commit cce68b5 Sep 25, 2026
24 checks passed
lilyshen0722 added a commit to thantiklermcirony/commonly that referenced this pull request Oct 9, 2026
…er is live (TASK-124) (Team-Commonly#1891)

The data half of TASK-124, deliberately separate from Team-Commonly#1889 (`cce68b58`), which
stopped reading and writing the copy. This removes it: three live rows carry a
72-char token Discord revoked (401 against GET /users/@me, measured read-only
from inside the backend pod).

Ordering is the reason it is separate: the pre-Team-Commonly#1889 build still read the stored
copy on two paths with no env fallback, so clearing it before that image was
replaced would have broken those paths. Merge -> deploy -> acceptance read ->
this script.

Dry run by default; `--apply` writes. Idempotent. Scope is one collection:
`discord_integrations.botToken`. `Integration.config.botToken` is a different
store, never written, and still the resolver's fallback read, so it is reported
and never touched.
lilyshen0722 added a commit to thantiklermcirony/commonly that referenced this pull request Oct 9, 2026
…an observation (Team-Commonly#1892)

* docs(review): rule 36 — an acceptance instrument's pre-state must be an observation

Two acceptance instruments for Team-Commonly#1889 were recorded, then measured, then
withdrawn in one session: the runtime messages route (404 before and after,
because the agent-access gate sits above the branch the change touched) and the
moltbot.json channel binding (0 accounts, nothing to compare against env).

Neither needed a guess to settle, and neither needed a write — which is the
clause worth keeping: manufacturing a precondition in production to verify a
read is worse than not verifying it.

* docs(review): rule 36 — say the 404 is derived, name the gates above it

wren's gate on Team-Commonly#1892: the Earned note claimed more than was done.

"Measured: 404, before and after" becomes "Derived, not observed" — nobody
called the route. Three gates sit between a caller and the branch the change
touched, and two answer 403 first (the pod match, then the
`integration:messages:read` scope check); below them the row is resolved by a
`findOne` on `config.agentAccessEnabled: true`, which no live row satisfies.

That also fixes a wrong method name in the same sentence: the route calls
`Integration.findOne`, not `Integration.find`, and the discriminating field is
`config.agentAccessEnabled` — the flag the change did not touch.

The rule gets sharper for the correction: a pre-state that varies with the
caller's token is not a pre-state, which is worse than a constant one. The one
call actually taken was the listing route, and its 200 proves only
`integration:read`.

* docs(review): rule 36 — four call sites are witnesses, not seven

wren's second gate edit on Team-Commonly#1892. The Earned note said the test tier "pins
the env-first precedence at all seven call sites across five files". The
resolver's unit test pins the precedence; four call sites have a witness that
pins the call (agentsRuntime:3439, registry/helpers:249, discordService:464
and :480). The remaining three pin nothing: integrations:146 and
discordProvider:56 feed presence checks, through which precedence is not
visible, and discordService.testConnection (:513) has neither a caller nor a
test.

Each of those was checked rather than copied — the resolver's six tests, the
three named route/service witnesses and the absence of any testConnection
caller — because the rule this note documents is that a claim about coverage
is itself an instrument. The closing line carries the lesson: seven call sites
across five files, four witnesses; the length of a list is not the strength of
the evidence for it.
lilyshen0722 added a commit to thantiklermcirony/commonly that referenced this pull request Oct 9, 2026
…mmonly#1895)

backend/controllers/discordController.ts is 187 lines and 7 exported
handlers with zero importers at aeacfd8: a repo-wide search for the
module name outside the file itself returns nothing, tests included, and
the build compiles without it (tsc -p tsconfig.build.json --noEmit exits
0). No test file references it either, so nothing is deleted beside it.

The rationale on the row needs one correction. The file no longer
persists a client-supplied `botToken` — it accepts the field and ignores
it, with a comment naming TASK-124 and the reason (a stored copy would
shadow a later DISCORD_BOT_TOKEN rotation). That write-site claim was
true before Team-Commonly#1889 and is stale now. What remains is worse in a different
place: `createIntegration` and `updateIntegration` write a
caller-supplied `webhookUrl` straight into the row, the one field in this
collection that is a secret in its own right, while the live connect path
derives that value from the Discord API instead of the request body; and
`testWebhook` POSTs to any URL the caller names. Unmounted code that
would do that is one router line away from doing it.

After this, no non-test code writes DiscordIntegration.botToken at all.
webhookUrl keeps two writers — routes/integrations.ts:441 and
services/discordService.ts:322 — which is the surface TASK-124 part 2 has
to encrypt.

No schema, no migration, no runtime path: the file is not mounted.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant