Repository navigation
fix(bot): store chat-platform workspace credentials encrypted at rest - #1320
Conversation
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
|
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 ( |
2f70ecf to
0af87fd
Compare
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.
0af87fd to
e95a9e8
Compare
Deploy record: Phase A1 role step, 2026-11-09, account 966362334030Ran
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. |
Store chat-platform workspace credentials encrypted at rest with the existing KMS helpers, and resolve the remaining uncalled
pkg/securityhelpers. 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 into1fff515, with conflicts resolved against:setup-dashboard-lambda-role.shnow owns the role's inline policies. The KMS policy is added next to the hand-added-policy cleanup, and both are kept.scanFirstlost its only caller and is removed. The pagination gate's message no longer names it.go.modbumps since then (go mod tidy).Two commits follow the squash:
e95a9e8makes the change safe to deploy in either order relative to spore-bot, and adds the migration schedule;124101bis 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/botsecretis the only code that reads or writes the four credential attributes ofspore-bot-workspaces. Each attribute is abotsecret.Fieldwith its own encryption-context purpose:signing_secretspore-bot-signing-secretbot_tokenspore-bot-bot-tokenrefresh_tokenspore-bot-refresh-tokenincoming_webhook_urlspore-bot-incoming-webhook-urlField.Put/Sealencrypt withsecurity.EncryptSecretunderalias/spore-bot-secrets(orSPORE_BOT_SECRETS_KMS_KEY), with context{purpose, workspace_key}.Field.Opendecrypts whensecurity.IsEncryptedsays so, and passes legacy plaintext through without a KMS call.RotatedTokensbuilds the sealed write-back of a token refresh.The rollout switch (new). The KMS key alias decides the format:
alias/spore-bot-secretsexists,Sealstores the plaintext, the format every deployed reader handles, and logs once per process:botsecret: KMS key … does not exist yet ….NotFoundExceptionfor the default alias means "not provisioned". AccessDenied, a disabled or pending-deletion key, or a missing key named explicitly withSPORE_BOT_SECRETS_KMS_KEYstill fail the write, with a message naming the key.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:
UpdateItemper attribute, so it can't clobber a concurrent refresh.Events.SealLegacyCredentials,rate(1 hour), input{"spore_bot_task":"seal-legacy-credentials"}).pkg/bot:Workspacearedynamodbav:"-", inputs toPutWorkspaceonly;Client.Credentialdecrypts on demand;HasCredentialchecks presence without a KMS call;UpdateWorkspaceTokenswrites the rotated pair sealed.cmd/bot.go:freshBotTokenopens 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 --jsonandworkspace add --jsonprint(redacted)for every credential a workspace holds.Dashboard (
lambda/dashboard-api):getFreshBotTokenwrites back sealed;rotateTokenByCurrentTokenpages the table and compares opened tokens in constant time (ciphertexts aren't deterministic, so abot_token = :tfilter 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/IsEncryptedare wired in. The first two take aKMSAPIinterface and an encryption-context map.ValidateMountPathandValidateCommandare removed. Both were uncalled and both are unsafe to start calling: the first rejectsspawn launch's own/efs//fsxdefaults, and the second is a denylist that would reject legitimate--pre-stophooks.MaskSecret,MaskURL,SanitizeForLogandSanitizePathare 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.
SpawnDashboardLambdaRole: a new inline policy,SporeBotCredentialsKMS, written bylambda/dashboard-api/scripts/setup-dashboard-lambda-role.shwith an idempotentaws iam put-role-policy:SporeBotCredentialsEncrypt:kms:Encryptonarn:aws:kms:*:966362334030:key/*, withStringEquals kms:EncryptionContext:purpose∈ {all four} andForAnyValue: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.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.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;BotSecretsKeyAliasalias/spore-bot-secrets;kms:Encryptfor all four purposes andkms:Decryptfor signing secret, bot token and webhook URL, on!GetAtt BotSecretsKey.Arn, conditioned on the purpose;SealLegacyCredentialsSchedule event. SAM creates anAWS::Events::Ruleand anAWS::Lambda::Permissionforevents.amazonaws.comwithSourceArn= that rule. Both are deleted with the stack.CLI operator (
docs/reference/cli-iam-actions.md, regenerated):notify workspace addnow needskms:Encrypt;notify register(email lookup and refresh) needskms:Encryptandkms: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.
dashboard-apimanual, because its role script changed. The owner runslambda/dashboard-api/scripts/setup-dashboard-lambda-role.sh spore-host-infra.dashboard-apideploy, snapshotting stack/function config before and after and checking for zero drift.make deployspore-bot.tofu applyininfra/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, thentofu 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:
LambdaCodeKey.The template header says so.
Live-verification plan (owner)
stringList):kms:ResourceAliasesentry: expect implicitDeny for both. The script'sput-role-policyis itself the PutRolePolicy proof.botsecret: KMS key alias/spore-bot-secrets does not exist yet …once, and the item'ssigning_secret/bot_tokenlengths are unchanged (projection scan, lengths only; command in fix(reaper): read the live stack before deploying, so unspecified params are kept #656).spawn notify workspace list --jsonshows(redacted);spawn notify register --user <email>resolves the user, which decrypts the bot token;Encrypt/DecryptbySpawnDashboardLambdaRolewithencryptionContext.purpose.purposefails withInvalidCiphertextException. Use--query KeyId, so no plaintext is printed.Gates (each watched failing against a revert that compiles)
pkg/botsecret(fake KMS):{purpose, workspace_key}, and fails closed without KMS;pkg/botandcmd(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.TestCredentialAttributesOnlyInBotsecret: no other Go code names the attributes;TestSporeBotTemplateGrantsOnlyTheCredentialKMSUseandTestDashboardRoleScriptGrantsTheCredentialKMSUse: the exact action-to-purpose table, resource, alias scope, a root-only key policy, and a realput-role-policy.TestPrintedPathsExistgate 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.lambda/dashboard-apiTestSetupAllRunsEveryStepFromAnyDirectoryfails identically on a cleanorigin/mainworktree. The scratch path contains a space (/Volumes/External HD/…), which the script word-splits.check-build-tagspasses from the physical path. It's the known symlink artifact.semgrep scan --config=auto --error .: 0 findings.