Skip to content

fix(bot): store chat-platform workspace credentials encrypted at rest - #1320

Merged
scttfrdmn merged 3 commits into
mainfrom
fix/868-bot-secret-at-rest
Nov 8, 2026
Merged

scttfrdmn merged 3 commits into
mainfrom
fix/868-bot-secret-at-rest

Conversation

@scttfrdmn

@scttfrdmn scttfrdmn commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Store chat-platform workspace credentials encrypted at rest with the existing KMS helpers, and resolve the remaining uncalled pkg/security helpers. This is the code half of #868. The bot half is spore-host/spore-host#611 (PR spore-host/spore-host#656).

Fixes #868

Rebased, not superseded (2026-11-08)

This branch was CONFLICTING with main since 2026-10-31. I rebased it rather than opening a new PR, so the owner's 2026-10-26 hold decision and the review history stay here. The old head was 0af87fd. Its three commits are squashed into 1fff515, with conflicts resolved against:

Two commits follow the squash:

  • e95a9e8 makes the change safe to deploy in either order relative to spore-bot, and adds the migration schedule;
  • 124101b is wording only.

The owner's hold condition ("hold until #611 is ready") is now met by spore-host/spore-host#656. The either-order design below means this PR no longer has to deploy after it, only before the flip.

What changed

  • pkg/botsecret is the only code that reads or writes the four credential attributes of spore-bot-workspaces. Each attribute is a botsecret.Field with its own encryption-context purpose:

    attribute purpose
    signing_secret spore-bot-signing-secret
    bot_token spore-bot-bot-token
    refresh_token spore-bot-refresh-token
    incoming_webhook_url spore-bot-incoming-webhook-url
    • Field.Put/Seal encrypt with security.EncryptSecret under alias/spore-bot-secrets (or SPORE_BOT_SECRETS_KMS_KEY), with context {purpose, workspace_key}.
    • Field.Open decrypts when security.IsEncrypted says so, and passes legacy plaintext through without a KMS call.
    • RotatedTokens builds the sealed write-back of a token refresh.
  • The rollout switch (new). The KMS key alias decides the format:

    • Until alias/spore-bot-secrets exists, Seal stores the plaintext, the format every deployed reader handles, and logs once per process: botsecret: KMS key … does not exist yet ….
    • Once it exists, every write is sealed.
    • Only NotFoundException for the default alias means "not provisioned". AccessDenied, a disabled or pending-deletion key, or a missing key named explicitly with SPORE_BOT_SECRETS_KMS_KEY still fail the write, with a message naming the key.
    • spore-bot implements the identical rule. So no writer in either repo ever writes ciphertext before every reader can decrypt it, and the key is created last (spore-host's var.seal_workspace_credentials).
  • Readers accept both formats. A legacy plaintext read is logged once per field per process and never re-written by the read.

  • Migration, no manual step:

  • pkg/bot:

    • all four credential fields of Workspace are dynamodbav:"-", inputs to PutWorkspace only;
    • Client.Credential decrypts on demand;
    • HasCredential checks presence without a KMS call;
    • UpdateWorkspaceTokens writes the rotated pair sealed.
  • cmd/bot.go:

    • freshBotToken opens the bot and refresh tokens and writes the new pair back sealed. A failed write-back is now a warning; before, it was silently ignored.
    • notify workspace list --json and workspace add --json print (redacted) for every credential a workspace holds.
  • Dashboard (lambda/dashboard-api):

    • the Slack OAuth install seals all four fields. When it preserves a legacy-keyed signing secret, it opens it and re-seals it for the new key;
    • getFreshBotToken writes back sealed;
    • rotateTokenByCurrentToken pages the table and compares opened tokens in constant time (ciphertexts aren't deterministic, so a bot_token = :t filter can't match).
  • pkg/security: the remaining helpers are resolved (Encrypt the bot signing secret at rest, and resolve the remaining pkg/security helpers #868's table, Dead-code inventory: ~3,980 unreachable non-test lines, plus two stranded-deployment inverses #811's last item):

    • EncryptSecret/DecryptSecret/IsEncrypted are wired in. The first two take a KMSAPI interface and an encryption-context map.
    • ValidateMountPath and ValidateCommand are removed. Both were uncalled and both are unsafe to start calling: the first rejects spawn launch's own /efs//fsx defaults, and the second is a denylist that would reject legitimate --pre-stop hooks.
    • MaskSecret, MaskURL, SanitizeForLog and SanitizePath are kept, each documented with why it has no caller.

IAM / KMS changes (all provisioned by spore.host; nothing for users to add)

The owner verifies each one with real calls; see the plan below.

  1. SpawnDashboardLambdaRole: a new inline policy, SporeBotCredentialsKMS, written by lambda/dashboard-api/scripts/setup-dashboard-lambda-role.sh with an idempotent aws iam put-role-policy:

    • SporeBotCredentialsEncrypt: kms:Encrypt on arn:aws:kms:*:966362334030:key/*, with StringEquals kms:EncryptionContext:purpose ∈ {all four} and ForAnyValue:StringEquals kms:ResourceAliases = alias/spore-bot-secrets;
    • SporeBotCredentialsDecrypt: kms:Decrypt, the same resource and alias condition, with purposes {signing secret, bot token, refresh token}. No webhook-URL decrypt: the dashboard never reads it.
    • The account comes from the script's ACCOUNT_ID, which is asserted to be 966362334030. There are no IAM policy variables in any Resource. The region wildcard is a literal *, not a variable.
  2. Self-host template deployment/cloudformation/spore-bot.yaml, deployed in the self-hoster's own account:

    • BotSecretsKey: rotation on, 7-day window, key policy delegating to that account's root only;
    • BotSecretsKeyAlias alias/spore-bot-secrets;
    • on the function: kms:Encrypt for all four purposes and kms:Decrypt for signing secret, bot token and webhook URL, on !GetAtt BotSecretsKey.Arn, conditioned on the purpose;
    • new: the SealLegacyCredentials Schedule event. SAM creates an AWS::Events::Rule and an AWS::Lambda::Permission for events.amazonaws.com with SourceArn = that rule. Both are deleted with the stack.
  3. CLI operator (docs/reference/cli-iam-actions.md, regenerated):

    • notify workspace add now needs kms:Encrypt;
    • notify register (email lookup and refresh) needs kms:Encrypt and kms:Decrypt.

    These run with the operator's own admin credentials, in the account that holds the table.

No grant names any other account. Nothing touches 942542972736.

Deploy order (both repos)

Phase A: code, in either order. Nothing is sealed until Phase B.

  • A1, this PR:
    1. Merge, then release.
    2. The release's Lambda deploy checklist marks dashboard-api manual, because its role script changed. The owner runs lambda/dashboard-api/scripts/setup-dashboard-lambda-role.sh spore-host-infra.
    3. The owner dispatches and approves the dashboard-api deploy, snapshotting stack/function config before and after and checking for zero drift.
    4. The owner upgrades their CLI: an older CLI can't use a sealed bot token.
  • A2, fix(spore-bot): store workspace credentials encrypted at rest; decrypt on use; migrate in place (#611) spore-host#656:
    1. make deploy spore-bot.
    2. tofu apply in infra/tofu/spore-bot. This creates the key and the spore-bot-role grants only, with no alias.

Phase B, the flip (after A1 and A2 are both live): a one-line spore-host PR setting seal_workspace_credentials = true, then tofu apply. This creates the alias and the hourly sweep. From then on every write is sealed, and the sweep seals the existing plaintext within the hour.

Phase C, from #868: re-key the four live signing secrets in Slack. Encrypting the column doesn't un-expose values already written. GHSA-xqx8-pcpv-cx2h stays private until then.

Self-hosters:

  1. Upload the new spore-bot zip under a new LambdaCodeKey.
  2. Update the stack. This creates the key and schedule in the same update as the code.
  3. Upgrade the CLI.

The template header says so.

Live-verification plan (owner)

  1. The dashboard role, simulated allow and deny (alias context as a stringList):
    R=arn:aws:iam::966362334030:role/SpawnDashboardLambdaRole; K=<key arn from spore-host tofu output secrets_key_arn>
    for p in spore-bot-signing-secret spore-bot-bot-token spore-bot-refresh-token spore-bot-incoming-webhook-url; do
      aws iam simulate-principal-policy --policy-source-arn $R --action-names kms:Encrypt kms:Decrypt --resource-arns $K \
        --context-entries ContextKeyName=kms:EncryptionContext:purpose,ContextKeyValues=$p,ContextKeyType=string \
                          ContextKeyName=kms:ResourceAliases,ContextKeyValues=alias/spore-bot-secrets,ContextKeyType=stringList \
        --query 'EvaluationResults[].[EvalActionName,EvalDecision]' --output text --profile spore-host-infra
    done   # Encrypt allowed x4; Decrypt allowed x3, implicitDeny for incoming-webhook-url
    Repeat without the kms:ResourceAliases entry: expect implicitDeny for both. The script's put-role-policy is itself the PutRolePolicy proof.
  2. Before the flip: a dashboard Slack install still succeeds. The dashboard log shows botsecret: KMS key alias/spore-bot-secrets does not exist yet … once, and the item's signing_secret/bot_token lengths are unchanged (projection scan, lengths only; command in fix(reaper): read the live stack before deploying, so unspecified params are kept #656).
  3. After the flip:
    • a dashboard Slack install writes all four fields at length ≥ 100;
    • spawn notify workspace list --json shows (redacted);
    • spawn notify register --user <email> resolves the user, which decrypts the bot token;
    • a token-rotation webhook to the dashboard succeeds and writes back sealed;
    • CloudTrail shows Encrypt/Decrypt by SpawnDashboardLambdaRole with encryptionContext.purpose.
  4. The binding: decrypting with the wrong purpose fails with InvalidCiphertextException. Use --query KeyId, so no plaintext is printed.

Gates (each watched failing against a revert that compiles)

  • pkg/botsecret (fake KMS):
    • every field's write stores ciphertext bound to {purpose, workspace_key}, and fails closed without KMS;
    • legacy plaintext opens with zero Decrypt calls;
    • a value sealed under one key or field won't open as another;
    • new: with the default alias not found, every field stores the legacy plaintext and one notice is logged;
    • new: an explicit missing key, AccessDenied, a disabled key or a pending-deletion key refuses the write and logs nothing;
    • new: legacy reads log once per field over repeated reads, never the value.
  • pkg/bot and cmd (Substrate DynamoDB+KMS), lambda/dashboard-api (Substrate): unchanged from the original PR (see the commit). The rotate lookup still finds a late or legacy match and writes back sealed.
  • Root gates:
    • TestCredentialAttributesOnlyInBotsecret: no other Go code names the attributes;
    • TestSporeBotTemplateGrantsOnlyTheCredentialKMSUse and TestDashboardRoleScriptGrantsTheCredentialKMSUse: the exact action-to-purpose table, resource, alias scope, a root-only key policy, and a real put-role-policy.
    • The TestPrintedPathsExist gate caught a cross-repo path in an error hint; the hint was reworded.

Checks

  • make check (GOTOOLCHAIN=go1.27.3): fmt, vet, every-GOOS vet, staticcheck, golangci-lint (all modules), hermetic short tests, nested modules, tidy.
    • One local-only failure: lambda/dashboard-api TestSetupAllRunsEveryStepFromAnyDirectory fails identically on a clean origin/main worktree. The scratch path contains a space (/Volumes/External HD/…), which the script word-splits.
    • check-build-tags passes from the physical path. It's the known symlink artifact.
  • semgrep scan --config=auto --error .: 0 findings.
  • No help text changed.

@codecov

codecov Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 84.93151% with 22 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
cmd/bot.go 65.71% 12 Missing ⚠️
pkg/bot/bot.go 86.84% 5 Missing ⚠️
pkg/botsecret/botsecret.go 95.31% 3 Missing ⚠️
pkg/security/secrets.go 77.77% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

@scttfrdmn

Copy link
Copy Markdown
Contributor Author

Decision (owner, 2026-10-26): this PR stays unmerged until spore-host/spore-host#611 is deployed, and v0.147.0 ships without it. The order is #611 deploys, then this merges and deploys, then the live re-keying.

Scope widens before merge: the other credential fields on a workspace item (bot_token, refresh_token, incoming_webhook_url) are sealed through pkg/botsecret as the signing secret is, and spawn bot workspace list --json redacts every credential field.

Rebased onto main: #1320's three commits (24e861f, 0deddbb, 0af87fd),
squashed, with conflicts resolved against #1376 (dashboard role script owns
its inline policies), #1421 (dashboard paging; scanFirst is now unused and
removed, the rotate lookup pages through the whole table) and the go.mod
bumps since 2026-10-26.
…er (#868)

The KMS key behind alias/spore-bot-secrets is now the switch between the two
formats. Until it exists, botsecret.Field.Seal stores the legacy plaintext
(the format every deployed reader handles) and logs that once; once it
exists every write is sealed. Only NotFoundException for the default alias
counts as not provisioned: a missing key named with SPORE_BOT_SECRETS_KMS_KEY,
AccessDenied, a disabled key or a pending-deletion key still fail the write.

Readers log a legacy plaintext value once per field per process.

The self-host template schedules spore-bot's hourly migration sweep
(spore-host/spore-host#611), which re-seals legacy values in place with a
conditional update, and its header gives the upgrade order.
@scttfrdmn
scttfrdmn force-pushed the fix/868-bot-secret-at-rest branch from 0af87fd to e95a9e8 Compare November 8, 2026 23:01
@scttfrdmn scttfrdmn modified the milestones: v0.153.0, Hardening Nov 8, 2026
@scttfrdmn
scttfrdmn merged commit 066892f into main Nov 8, 2026
9 checks passed
@scttfrdmn
scttfrdmn deleted the fix/868-bot-secret-at-rest branch November 8, 2026 23:44
@scttfrdmn scttfrdmn mentioned this pull request Nov 9, 2026
@scttfrdmn

Copy link
Copy Markdown
Contributor Author

Deploy record: Phase A1 role step, 2026-11-09, account 966362334030

Ran lambda/dashboard-api/scripts/setup-dashboard-lambda-role.sh spore-host-infra from main. I read it first: its cleanup branches had nothing to delete (no legacy managed policy SpawnDashboardLambdaPolicy, and none of the three hand-added inline names were present).

  • Diff against the snapshot: trust unchanged; SpawnDashboardLambdaPolicy, …Slack and …WebSocket unchanged; attached AWSLambdaBasicExecutionRole unchanged; new SporeBotCredentialsKMS, the only change. The real PutRolePolicy was accepted. The only account it names is 966362334030, with no ${…} variables.
  • simulate-principal-policy (key a8d9cbdb-…, with kms:ResourceAliases=alias/spore-bot-secrets):
    • Encrypt allowed for all 4 purposes;
    • Decrypt allowed for signing-secret, bot-token and refresh-token; implicitDeny for incoming-webhook-url;
    • without the alias context, Decrypt is implicitDeny, so the grant is alias-scoped as designed.

Remaining for A1: the v0.162.0 release, the dashboard-api deploy (owner dispatch and approval), and the owner's CLI upgrade. Then Phase B.

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.

Encrypt the bot signing secret at rest, and resolve the remaining pkg/security helpers

1 participant