Skip to content

fix(secrets): field encryption binds each value to where it is stored, on the one envelope core (#17981) - #20737

Closed
mrveiss wants to merge 11 commits into
mainfrom
issue-17981-field-encryption-aad
Closed

mrveiss wants to merge 11 commits into
mainfrom
issue-17981-field-encryption-aad

Conversation

@mrveiss

@mrveiss mrveiss commented Nov 3, 2026

Copy link
Copy Markdown
Owner

Thinking Path

autobot_shared/field_encryption.py sealed stored credentials with AES-GCM and no associated data. Its sibling secrets_envelope.py binds every value to where it lives. Both are live, so the same package disagreed on the property that matters: a sealed company token copied into another company's row decrypted cleanly as that company's. The two also used different keys, and AUTOBOT_FIELD_ENCRYPTION_KEY is provisioned by no install path (not Ansible, not generate-secrets.sh, not Docker secrets-init). So on a standard install every field-encrypted write already failed. AUTOBOT_SECRETS_ROOT_KEY is provisioned by all three.

The fix is one AEAD core with one key contract. field_encryption becomes a facade over the envelope core, and every value is bound to a stable name for where it is stored.

What Changed

  • secrets_envelope gains seal_field / open_field (format fe1.), open_unbound_legacy (read-only) and seal_field's binding. The key is HKDF-derived from the root key (vault id field-encryption). The AAD kind is field-value, distinct from the secret-value and wrapped-dek kinds and length-prefixed by the existing _aad.
  • field_encryption is a facade. encrypt_field(plaintext, *, context) and decrypt_field(ciphertext, *, context) make context required, so no caller can forget the binding.
    • Legacy values (no binding, old key) still read while AUTOBOT_FIELD_ENCRYPTION_KEY is set.
    • Any read failure raises FieldDecryptionError, naming the context and never the value.
    • seal_tagged / open_tagged / is_plaintext replace the enc:-prefix helper that Telegram, WhatsApp and the SSO helpers each carried separately.
  • Bindings, each checked to exist at seal time and never change:
Route family Context Why it is stable
Company PM settings (UI/REST companies set and test) and outbound sync (scheduler/event worker) organization:<uuid>:external_pm_config Sealed only after the row's existence check. Both routes go through outbound_sync.seal_pm_config / open_pm_config, and the id is normalised to one UUID spelling.
Telegram bot token and webhook secret (settings API, webhook auth, poller, notifications) redis:<key name> Fixed key constants
WhatsApp access token, app secret and verify token (settings API, webhook verify and receive) redis:<key name> Fixed key constants
SSO config helpers (SLM maintenance script) sso_provider:<id>:<field> Provider primary key
  • Fail closed.
    • The Telegram reads used to swallow a decrypt failure and return None, so the config view showed "not configured", which invites a save over the credential. They now raise.
    • Both webhook auth paths (Telegram, WhatsApp verify and receive) answer an unreadable secret with the same 503 as an unset one.
    • The poller's lease loop logs a failed tick and continues. The notification path already caught and logged.
  • Re-sealing. Existing values are re-sealed only when the product itself next saves them. Nothing rewrites stored credentials on its own (Umbrella: SLM Data hygiene page — detect and safely clean up orphaned data across services #17038). Any bulk re-seal is an approval-queue proposal.
  • Guard. repo_tests/one_aead_core_17981_test.py is AST-based. It fails on a new cipher user in autobot_shared, its pending list (legacy_secret_keys, passphrase_encryption) can only shrink, it has a prose-vs-code contrast fixture, and an instrument check confirms it still sees the canonical core. It declares a reach floor (non-test source must be at least 50% of autobot_shared; measured at 63%), and its scope is recorded in _reach_roots_record.py and reach_scope_claim_17844_test.py.
  • Docs.
    • The env var reference marks the old key legacy and read-only.
    • The Telegram setup no longer asks for a key.
    • The threat model names the facade.
    • The SSO runbook drops the wrong key name; its migration step actually checks SLM_ENCRYPTION_KEY/SLM_SECRET_KEY.
    • The provider sign-in note is corrected: its "optional key" reason is gone, while the "verifier is useless alone" reason still holds.
  • companies.py shrank by 4 lines, and its size ceiling is lowered to 1605.

Verification

Run on Python 3.14 (the CI-parity venv). The default 3.10 cannot import the Telegram module because it needs StrEnum:

autobot_shared/field_encryption_test.py, field_encryption_sso_test.py, secrets_envelope_test.py,
llc/tests/test_pm_config_seal_17981.py, llc/tests/test_outbound_sync.py,
services/whatsapp_service_seal_17981_test.py, services/telegram_bot_service_test.py,
api/whatsapp_test.py, api/webhook_authentication_security_test.py, services/gateway/live_egress_seams_test.py,
repo_tests/one_aead_core_17981_test.py, redaction_concept_census_test.py, slm_frontend_calls_reach_served_routes_test.py
→ all passed (125 + 53 + 25 + 59 across runs; 0 failed)

Per route family:

The Telegram test now uses real encryption with a test root key instead of stubbing encrypt_field.

A code-reviewer pass found no blocking issue. Its findings were applied: the WhatsApp 503, the restored plaintext warning, UUID normalisation in the context, and the guard's instrument check.

Risks

Model Used

Claude Opus 5.5 (claude-opus-5-5)

Issue Link

Refs #17981. These criteria are delivered:

  • one implementation for field_encryption;
  • every sealed value bound, with relocation tests;
  • legacy values read and re-sealed on save, with no automatic bulk re-seal;
  • one key contract for field encryption;
  • the autobot_shared guard.

The wider cipher class is still open on the issue's list, so this PR does not close it.

🤖 Generated with Claude Code

@mrveiss mrveiss added backend security phase:M4.9 One definition per concept labels Nov 3, 2026
@coderabbitai

coderabbitai Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 5 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration
Commits

Reviewing files that changed from the base of the PR and between 8016267 and 2c2d1d7.

Files ignored due to path filters: 1
  • scripts/python_file_size_known_large.py is excluded by !scripts/python_file_size_known_large.py
Files selected for processing: 28
  • autobot-backend/api/provider_auth_flow_state.py
  • autobot-backend/api/telegram_bot.py
  • autobot-backend/api/webhook_authentication_security_test.py
  • autobot-backend/api/whatsapp.py
  • autobot-backend/api/whatsapp_test.py
  • autobot-backend/app_factory.py
  • autobot-backend/initialization/credential_handlers.py
  • autobot-backend/initialization/credential_handlers_17981_test.py
  • autobot-backend/llc/api/companies.py
  • autobot-backend/llc/sync/outbound_sync.py
  • autobot-backend/llc/tests/test_outbound_sync.py
  • autobot-backend/llc/tests/test_pm_config_seal_17981.py
  • autobot-backend/services/telegram_bot_service.py
  • autobot-backend/services/telegram_bot_service_test.py
  • autobot-backend/services/telegram_polling.py
  • autobot-backend/services/whatsapp_service.py
  • autobot-backend/services/whatsapp_service_seal_17981_test.py
  • autobot-slm-backend/scripts/encrypt_sso_secrets.py
  • autobot_shared/field_encryption.py
  • autobot_shared/field_encryption_sso_test.py
  • autobot_shared/field_encryption_test.py
  • autobot_shared/secrets_envelope.py
  • docs/configuration/environment-variables.md
  • docs/developer/THREAT_MODEL.md
  • docs/security/ENTERPRISE_SSO_ADMIN_RUNBOOK.md
  • repo_tests/_reach_roots_record.py
  • repo_tests/one_aead_core_17981_test.py
  • repo_tests/reach_scope_claim_17844_test.py
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

Notice: 29 open PRs — past the runaway threshold (25)

This is not a request to defer this PR. There is no cap on open PRs (#19397) -- nothing blocks opening or pushing a PR.

This notice only means the count is high enough to be worth a glance for a runaway — something opening PRs in a loop, or a merge pipeline that has stalled so nothing is draining.

Currently open:

If the queue is draining normally, ignore this. Otherwise:

  1. Check whether CI is dispatching at all — see the ci-dispatch-watchdog status on these PRs
  2. Approved PRs land through the merge train the coordinator sequences (merge commits, never squash) -- check the open chore(merge-train) PR is moving, not each PR on its own
  3. Look for a loop opening near-identical PRs

Warn-only runaway detector — .github/workflows/pr-queue-gate.yml. It never blocks a merge.

@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

✅ SSOT Configuration Compliance: Passing

🎉 No new hardcoded values of either class — ssot and other both block.

Known backlog in pipeline-scripts/hardcoded_values_baseline.txt is suppressed and tracked in #14371.

@mrveiss mrveiss left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

code-reviewer pass: #20737 (head a61e5fa)

Verdict: CHANGES NEEDED (one Medium to settle before merge; the crypto itself is sound)

Severity file:line Issue Fix
Medium autobot_shared/secrets_envelope.py _field_key (~L270) Root-key rotation (rewrap in envelope_secrets_service) rewraps grants only. Every fe1. value is sealed directly under the root-derived key, so a rotation makes all of them unreadable, and nothing rewraps them. No agent may re-seal (#17038), so the path has to be a product action. Add the rotation path, or file the issue and name the limitation in THREAT_MODEL.md and the rotation runbook before the first fe1. value is written.
Low secrets_envelope.py _FIELD_VAULT_ID / derive_vault_key The field key is the vault KEK for the pseudo-vault field-encryption (info autobot-secrets-vault:field-encryption). It cannot collide with a parsed vault ref, because VaultRef only admits known kinds. But derive_vault_key takes any string, and rewrap_dek derives from grant.grantee as stored. A grant row with that grantee would hold a KEK equal to the field key. AAD kinds differ (field-value vs wrapped-dek), so no cross-open follows, but this is namespace separation, not a distinct label. Derive with its own info prefix (e.g. autobot-field-encryption:v1), or reject the reserved id in VaultRef/derive_vault_key.
Low services/telegram_polling.py poll_once (~L184) TelegramBotService.from_redis() used to return an empty service (token None) on a bad stored token. It now raises FieldDecryptionError into the lease tick. I did not check whether LeaderLease.run catches it. Catch FieldDecryptionError in poll_once, log, return None.
Low llc/sync/outbound_sync.py ~L471-490 An unreadable PM config is swallowed by the outer logger.exception, so the sync silently skips. test_pm_config returns a 500, and the Telegram and WhatsApp webhooks return a 503. Failing closed is right, but the signal differs by route. Emit one structured error naming the context, and surface "credential unreadable" in the company PM status.
Info repo_tests/one_aead_core_17981_test.py _PENDING legacy_secret_keys.py (Fernet) and passphrase_encryption.py (AESGCM, no AAD) remain second cores in autobot_shared. They are explicitly listed, shrink-only and tracked, so (d) is met for this PR's scope, not fully. None; keep the issue open.

Checks:

  • (a) Contexts are stable and exist at seal time. PM config uses organization:<uuid>:external_pm_config (UUID normalized, immutable). Telegram and WhatsApp use redis:<fixed key>. SSO uses sso_provider:<id>:<field>. All four are fixed at seal time.
  • (b) Reads fail closed. decrypt_field maps every failure to FieldDecryptionError, and open_tagged passes through only values with no enc: tag (plaintext that was never encrypted). The Telegram and WhatsApp webhooks turn an unreadable secret into a 503 (not configured). The only None path is "nothing stored".
  • (c) Legacy values still open:
    • The legacy format is byte-compatible with the old code (nonce || ct, no AAD, AUTOBOT_FIELD_ENCRYPTION_KEY).
    • fe1. cannot start a base64url blob, because . is outside that alphabet.
    • PM config (set, test and outbound sync), Telegram and WhatsApp are covered by the new tests.
    • Provider-auth flow: it still stores the PKCE verifier in plaintext, so there is no encryption to open.
    • SSO: decrypt_sso_config has no runtime caller in the tree. Only the one-shot script calls encrypt_sso_config, so SSO legacy reads are tested but not exercised by any route.
  • (e) Derivation is HKDF-SHA256 with an info string, but see the Low row above on label separation.
  • (f) Nonces are 12 random bytes from os.urandom per seal, under one long-lived key. That is fine at this volume. The AAD is length-prefixed with the format version and a field-value kind, so the encoding is injective and distinct from secret-value and wrapped-dek. One fe1. blob moved to another record or field fails to open.

Not checked: I ran no tests. LeaderLease.run exception handling. Whether any agent tool or MCP route reads these stores. I found none by grep, and the routes I did find are listed above.

…eld key gets its own HKDF label; rotation limit documented (#17981)
@mrveiss

mrveiss commented Nov 3, 2026

Copy link
Copy Markdown
Owner Author

Code review on PR #20737 (head 9d255d9): CHANGES NEEDED

Delta a61e5fa..9d255d9. Items (a) and (b) check out; (c) has one route that still turns the error into a 200.

Severity File:line Issue Fix
MEDIUM autobot-backend/api/telegram_bot.py telegram_webhook (except Exception after except HTTPException, ~line 370) FieldDecryptionError is now a PassThroughError, but this handler catches it before the registered 503 handler can. Path: webhook -> process_telegram_update -> send_telegram_response -> TelegramBotService.from_redis() raises on an unreadable bot token -> except Exception logs and returns {"status":"ok"} (200). The inbound update is dropped, Telegram will not retry, and the same unreadable token answers 503 on GET /telegram/config. Same operation, different answer per route. Add except PassThroughError: raise ahead of except Exception (503 makes Telegram retry, which is right for a recoverable key problem). Add a test posting a webhook with an unreadable token and asserting 503 CREDENTIAL_UNREADABLE.
LOW autobot-backend/services/notification_service.py _send_telegram and api/telegram_bot.py send_telegram_response (except Exception: ... raise) They re-raise, so the error is preserved, but the logger.exception stack trace for an expected credential state is noisy, and I did not verify every caller of _send_telegram lets it propagate. Optional: except PassThroughError: raise first so it is not logged as an unexpected failure.
LOW autobot_shared/secrets_envelope.py:262-275 No test pins that the field key differs from derive_vault_key(root, "field-encryption") and from any vault KEK, so the label change is untested. Add a test: _field_key() != derive_vault_key(root, "field-encryption"), and seal/open round-trip.
LOW autobot_shared/secrets_envelope.py:272-273 HKDF import is repeated inside _field_key() on every seal/open, duplicating the body of derive_vault_key. Hoist to a shared _hkdf(info, root) helper used by both.

Verified:

  • (a) Rotation limit is stated in THREAT_MODEL.md (Canonical enforcement paragraph) and on the AUTOBOT_FIELD_ENCRYPTION_KEY row of docs/configuration/environment-variables.md, both linking security(secrets): rotating the secrets root key leaves every field-sealed credential unreadable; no re-seal path #20744. Accurate.
  • (b) Label b"autobot-field-encryption:v1" is disjoint from the vault info (_HKDF_INFO_PREFIX + vault_id). Changing it changes the key, but no sealed value is orphaned: git grep "FIELD_FORMAT_PREFIX\|seal_field" origin/main finds nothing (field sealing does not exist on main), and every fe1./enc:fe1. fixture in this head is either sealed at runtime by the code under test or a deliberately invalid blob (enc:fe1.AAAA, fe1.!!!).
  • (c) The 503 body is the static CREDENTIAL_UNREADABLE dict, with no exception text. The log line carries the exception message, which names the storage location (redis key or organization id), never the value. Acceptable. with_error_handling already re-raises PassThroughError (decorators.py:462, 476), so decorated routes reach the handler. Telegram config GET, test_pm_config (only ValueError caught now), poll_once (one log, idles), and outbound sync (credential unreadable: <context>) behave as described. The WhatsApp routes have no broad except, so they reach the handler.

Not checked: the body of process_telegram_update for further broad excepts; callers of notification_service._send_telegram; the test suite was not run.

@mrveiss

mrveiss commented Nov 3, 2026

Copy link
Copy Markdown
Owner Author

Code review on PR #20737 (head 37ec8ca): APPROVE

Delta 9d255d9..37ec8ca. The prior MEDIUM (webhook returns 200 on an unreadable token) is fixed.

Severity Where Finding
Verified api/telegram_bot.py telegram_webhook except (HTTPException, PassThroughError): raise now precedes the broad except. FieldDecryptionError subclasses PassThroughError, and with_error_handling already passes it through (decorators.py:462/476), so it reaches the registered 503 handler.
Verified webhook to from_redis chain The only paths are process_telegram_update, _route_to_chat_and_reply and send_telegram_response. The first two contain no try/except. send_telegram_response now re-raises PassThroughError before its broad except. gateway_manager's telegram_gateway_response_handler has no except. Nothing between the webhook and from_redis turns this into a 200.
Verified status regression HTTPException was already re-raised first, so no existing webhook status changes. The only new pass-through types are PassThroughError subclasses. configure_telegram_bot gets the same tuple.
Verified derive_vault_key bytes I loaded the old (9d255d9) and new (37ec8ca) secrets_envelope.py and compared KEKs for system, company:42, user:alice, field-encryption and a 64-char id. They are byte-identical. The info bytes are still _HKDF_INFO_PREFIX + vault_id.encode("utf-8"), with the same algorithm, length and salt=None. The prefix and _FIELD_KEY_INFO constants are unchanged. The validation order is also unchanged, since the length checks still run before derivation.
Verified tests The new tests assert the field key differs from derive_vault_key(root, "field-encryption") and from "system". A webhook test asserts 503 with the CREDENTIAL_UNREADABLE body, and a send_telegram_response test asserts the error propagates.
LOW secrets_envelope_test.py No test pins a known-answer vector for derive_vault_key. Existing tests check determinism, inequality and round trips, and a round trip cannot detect a later drift in the info bytes. This PR is identical (checked above), but pinning one vector for a fixed root and "system" would guard the orphaned-grant risk permanently. Suggest as a follow-up.
LOW the webhook test It patches process_telegram_update to raise, so it does not exercise the real chain. The unit test on send_telegram_response covers the other end, and the chain was checked by reading.
NOTE notification_service._send_telegram The claim "keeps catch-and-log" is only partly accurate. It logs and then re-raises (raise at the end of the except). It does not swallow, so an unreadable token surfaces as a log line plus the caller's own handling. Behaviour is unchanged by this PR, so this is not blocking.

Not checked: no test suite was run (read-only review). The 503 mapping was verified from credential_handlers.py, not by a live request.

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Auto-sync: merging main into issue-17981-field-encryption-aad conflicts

The sync aborted the merge and pushed nothing. Conflicts are information, so it never resolves one itself. Below, for each conflicted file, are the commits that touched it on each side since the merge base 8016267979. Merge main in yourself and push; the label clears on the first run that finds this branch 0 behind.

repo_tests/_reach_roots_record.py

side commit subject issue refs
main 90911ee0c Merge main into issue-16333-human-admin-gate (auto-sync) [skip ci] none
main c822582f3 fix(auth): the service key is not an admin; one gate, a named and audited opt-in, a guard (#16333) #16333
this branch 5f92fa470 Merge main into issue-17981-field-encryption-aad (auto-sync) [skip ci] none
this branch 9df294a0f test(secrets): record the one-AEAD-core guard's scope (#17981) #17981

repo_tests/reach_scope_claim_17844_test.py

side commit subject issue refs
main a7b2a06c4 Merge main into the merge train (#20788) #20788
main 90911ee0c Merge main into issue-16333-human-admin-gate (auto-sync) [skip ci] none
main c822582f3 fix(auth): the service key is not an admin; one gate, a named and audited opt-in, a guard (#16333) #16333
this branch 2c2d1d75b Merge main into issue-17981-field-encryption-aad (auto-sync) [skip ci] none
this branch 5f92fa470 Merge main into issue-17981-field-encryption-aad (auto-sync) [skip ci] none
this branch 9df294a0f test(secrets): record the one-AEAD-core guard's scope (#17981) #17981

@mrveiss

mrveiss commented Nov 4, 2026

Copy link
Copy Markdown
Owner Author

Landed in merge train #20789 (merge commit 09b17c2). This PR's reviewed head 5f92fa4 is on main; any later commits on this branch are automatic main merges. Closing as landed.

@mrveiss mrveiss closed this Nov 4, 2026
@github-actions github-actions Bot removed the sync-conflict Set by the branch sync (#19548) label Nov 4, 2026
timothybrush pushed a commit to timothybrush/AutoBot-AI that referenced this pull request Nov 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend phase:M4.9 One definition per concept security

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant