Skip to content

[AI-3632] Open line and model secrets bound to their row, keep sealing them customer-only - #2573

Merged
kanat merged 8 commits into
mainfrom
ai-3632-channel-model-aad
Nov 26, 2026
Merged

kanat merged 8 commits into
mainfrom
ai-3632-channel-model-aad

Conversation

@kanat

@kanat kanat commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

Why

A channel line's sealed credentials and a custom model's sealed API key are bound only to the customer (AAD []byte(customerID): internal/api/channels.go sealChannelSecrets, internal/api/custom_models.go fillCustomModel). Other sealed secrets also name their row (credentialsAAD in pgsealed, providerkeys.AAD). The decision for credential encryption binds every sealed blob to its row. It is defence in depth.

A blob sealed with the row's AAD does not open on a release that opens with the customer only. So the binding ships in three releases (see «Rollout»). This PR is step 1: the router learns to open the bound form and writes nothing new.

How it works

record written with (unchanged) also opens
channel line (channel_accounts.secrets_sealed) customer_id accelerate:channel-secrets:v1: + length-prefixed customer_id, kind, e164
custom model (custom_models.api_key_sealed) customer_id accelerate:custom-model-key:v1: + length-prefixed customer_id, id
connect a line / create or update a model
└─ SealWithAAD(secret, customer_id)   (as before)

channels.Open (inbound webhook, outbound notice) / CustomModels.CustomModel (session naming custom/<name>)
└─ Sealer.OpenWithLegacyAAD(blob, row AAD, customer_id, stored kek_version, record)
   ├─ opens under the row AAD      -> secret
   ├─ opens only under customer_id -> router_sealed_legacy_opens_total{record} += 1 -> secret
   └─ opens under neither          -> error, as before
   (the row is never written)

Why these keys:

record key why not the row id / name
channel line customer + kind + number the live-line unique key (channel_accounts_line_idx). Upsert conflicts on it and never changes it. On a reconnect the row id is only known once Upsert returns it, so it cannot go into the seal
custom model customer + model id a model can be renamed

record is channel_account or custom_model.

Rollout

Step Release does Starts when Rollback to the release before
1 (this PR) Opens bound, then customer-only; counts customer-only opens; seals customer-only now Safe: nothing bound is written
2 Connect and model create/update seal bound; a customer-only row is sealed again bound when it is read step 1 runs on every environment Safe: step 1 opens bound rows
3 Deletes the customer-only fallback the unbound rows are counted and none is left Safe: rows are bound

The step 2 code (bound writes, reseal on read, its tests) is kept on branch ai-3632-step2.

Changes

  • auth.Sealer.OpenWithLegacyAAD and the router_sealed_legacy_opens_total{record} counter.
  • channels.Open opens with secretsAAD first, then the customer only.
  • CustomModels.CustomModel opens with customModelKeyAAD first, then the customer only.
  • No migration, no operation change, no openapi change. Connect and model create/update write what they wrote before.

Validation

defect test
connect, model create or update writes a blob the previous release cannot open ChannelsSuite.TestTheCredentialsOpenAsThePreviousReleaseOpensThem, CustomModelsSuite.TestTheKeyOpensAsThePreviousReleaseOpensIt (open with the base's OpenWithAADVersion(sealed, customerID, v))
a bound blob from another line, or from the same number on another channel or app, opens LineSecretsSuite.TestCredentialsMovedFromAnotherLineDoNotOpen, ...SameNumberOnAnotherChannelOrAppDoNotOpen
a bound key from another model, or from another customer's model with the same id, opens CustomModelKeySuite.TestAKeyMovedFromAnotherModelDoesNotOpen, ...AnotherCustomersModelOfTheSameIdDoesNotOpen
a bound row (what step 2 writes) does not open ...TestALineSealedBoundToItselfOpens, ...TestAKeySealedBoundToItsModelOpens
a customer-only row stops working, is written on a read, or is counted under the wrong record ...TestALineSealedBoundOnlyToItsCustomerOpensIsLeftAsItIsAndIsCounted, ...TestAKeySealedBoundOnlyToItsCustomerOpensIsLeftAsItIsAndIsCounted, SentSuite.TestANoticeCountsTheUserItReachedAsReached (outbound)
KEK rotation: a customer-only row opens under the current version, not the stored one ...TestALegacyLineUnderAnOlderKeyOpensWithItsStoredVersion, ...TestALegacyKeyUnderAnOlderKeyOpensWithItsStoredVersion, KeyringSuite.TestALegacyRecordSealedUnderAnOlderKeyOpensWithItsStoredVersion
the AAD parts run together ...TestTheLinesAADPartsDoNotRunTogether, ...TestTheKeysAADPartsDoNotRunTogether
a bound open is counted, or a failed open is KeyringSuite.TestARecordSealed*, ...OpeningUnderNeither...
  • Suites on the branch merged with main: ./internal/auth, ./internal/channels and ./internal/llmrouter (integration), and the api channel, custom model, scheduled task, billing and streams suites. go vet ./... and go vet -tags integration ./... clean.
  • Mutation run: each of these fails a test above: connect or model writes sealing bound; no customer-only fallback (line, model); no bound open (line, model); the line counted as custom_model and the model as channel_account; the line AAD without the kind or the number; the model AAD without the id; either AAD without its length prefixes; opening under the current KEK version; counting before the bound open.

Follow-ups

  • Step 2: bound writes and reseal on read (branch ai-3632-step2).
  • Step 3: count the unbound rows, then delete the fallback.

🤖 Generated with Claude Code

kanat and others added 5 commits November 26, 2026 14:52
…ir row

A line's sealed credentials now name customer, channel and number in their
AAD, and a custom model's sealed key names customer and model id, as
credentialsAAD and providerkeys.AAD already do. A row still sealed in the
old customer-only form opens through auth.Sealer.OpenWithLegacyAAD, is
counted in router_sealed_legacy_opens_total{record}, and is sealed again in
the new form by a conditional update on the bytes read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
# Conflicts:
#	acceleration/internal/llmrouter/custom_integration_test.go
#	acceleration/internal/store/custom_model.go
Main now writes cached rows through detachedWrite (#2209), so Reseal does
too, and it forgets the name the row has rather than the one it was read
under: a rename in between no longer leaves the old key cached. The
CustomModelsSuite fixture seals as the API now does, bound to the model.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Delete empties secrets_sealed, so a disconnected line never matches the
bytes a reseal read; the deleted_at filter added nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

VERDICT: NO-GO

[security R1] Security review of the row binding for sealed channel line credentials and custom model keys, head 0cc6cd5 merged onto current main.

What I checked and found fine:

  • The new AAD forms name the customer, and the row: kind + number for a line, id for a model. Their purpose labels differ from every other sealed column. Blobs of another customer, in the legacy form or the new one, do not open and are not sealed again.
  • The legacy fallback opens only what the base already opened. It takes its additional data from the stored row, never from the caller.
  • The line reseal is guarded on the row id and the old bytes. It cannot bring back a disconnected line, and it cannot overwrite a reconnect, including a reconnect of the same number after a disconnect (new row id).
  • The model reseal writes nothing for a model that was deleted or whose key changed.
  • The new warn lines and the counter carry no number and no secret: the warn has the customer, the channel kind and the store error; the counter label is a fixed record name.
  • The diff adds no internal error text to any response.
  • Mutations: 12 checked against the PR's tests, 1 survived (S1.1).

Findings:

  • [Should fix] S1.1 internal/store/custom_model.go:179: no test pins the customer_id guard of CustomModels.Reseal. Remove it and every test still passes. Add a store-suite test where a reseal naming another customer leaves the model's key and version unchanged. The alternative is to drop the guard as redundant with the id and bytes guards, as the line reseal does.
  • [Question] S1.2 Rollback: the previous build opens these columns with the customer-only AAD. So every line and model connected, changed or sealed again since the deploy stops opening on a rollback. This fails closed, so nothing is widened. But it is an availability cost to decide before the staging deploy, because the live test reseals the test line on its first use. Either accept it and say so in the PR body, or keep reseal-on-read behind a later step.

Set("api_key_sealed = ?", sealed).
Set("kek_version = ?", version).
Where("id = ?", model.ID).
Where("customer_id = ?", model.CustomerID).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Should fix] S1.1 This guard is untested: removing it leaves every test green. Add a store-suite test where Reseal is given the model with another customer's id. It must return no error and leave api_key_sealed and kek_version unchanged. Or drop the guard as redundant with the id and old-bytes guards, as ChannelAccounts.Reseal does.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Moot here after 82bdc3e: CustomModels.Reseal is no longer in this PR. It moves to step 2; the test StoreSuite.TestAResealLeavesAModelOfAnotherCustomer (Reseal with CustomerID "another-app" leaves api_key_sealed and kek_version as they were) is on branch ai-3632-step2 (1f5f5cc) and fails when the customer_id filter is removed.

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

VERDICT: NO-GO

[main R1] Reviewed 0cc6cd5cc merged onto current main (c351776db, clean). Build, go vet (with and without -tags integration) and the touched suites pass on the merged tree: auth, channels, llmrouter; the store CustomModel|Reseal|ChannelAccount|GivenAnId subset; and the api suites Channels, CustomModels, PrivateCustomModels, ScheduledTasks, TelephonyBilling, TelephonySandboxBilling, Streams, plus the Linq, Telnyx, WhatsApp, Slack and Transcript channel suites, which drive inbound deliveries through Service.open. CI: this is a draft, so the go and integration jobs are skipped; they run at ready.

[Blocker] R1.1: the previous release cannot open what this one writes (see the inline comment on channels/service.go:413). This is the expand/contract decision already taken for this pair of PRs: this PR becomes step 1, which opens both forms and counts old-form opens. Step 1 writes only the customer-only form and does no reseal. Bound writes and reseal-on-read move to a follow-up release.

[Should fix] R1.2 (moves to step 2 with the reseal) and [Should fix] R1.3: see the inline comments.

[Question] R1.4 (outside this PR, ticket): the sibling sweep (grep -rn "SealWithAAD(" acceleration/) finds no other secret bound only to its customer. Every other sealed record names its row. One sealed record has no AAD at all: the API key secret, sealed with Sealer.Seal (cmd/router/keys.go:89) and opened with nil AAD (internal/store/api_key.go:188). It is a separate ticket, not this PR.

Checked and sound:

  • The line key (customer, kind, number) is the live-line unique index, and nothing changes it on a row. A reconnect seals again under the same key. A disconnect empties the blob, and a re-bought number gets a new row. The agent a line answers for lives in configs, not in the row, so no two rows can share a blob.
  • A custom model's id is set before the seal on create, and the update path reads the row by id first.
  • Both reseals are conditional on the bytes read, so two routers racing write once. The model reseal forgets the name the row returns, on every replica.
  • The stored KEK version opens the blob and the reseal writes the current one.
  • OpenWithLegacyAAD has only the two callers, both with AAD built from the stored row. Its counter fires only on the legacy path: moving the Inc before the legacy check is caught.
  • No secret goes into the new log lines, and nothing changes without a keyring.

sealed, err := Seal(s.secrets, stored.CustomerID, stored.Kind, stored.E164,
Secrets{Token: line.Token, Signing: line.Signing, Challenge: line.Challenge})
if err == nil {
err = s.store.ChannelAccounts.Reseal(ctx, stored.ID, stored.SecretsSealed, sealed, s.secrets.CurrentVersion())

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Blocker] R1.1 A blob sealed in the new form does not open on the previous release. I checked this on the base sha: a line sealed with this PR's secretsAAD, given to the base channels.Open, fails with cipher: message authentication failed. The base answers that line errUnopened, which is a 410 Gone (base internal/channels/service.go:413-414). Its own comment says a 410 stops the provider delivering. The base llmrouter/custom.go:60 opens with the customer only, so a custom model read since the deploy fails with ErrCustomModelKey.

The new form is written in four places: this reseal, the connect (api/channels.go:77), model create and update (api/custom_models.go:182), and the model reseal (llmrouter/custom.go:78-81). After a rollback, or on an old pod that still serves during an overlap deploy, every line connected or read since the deploy answers 410, and every custom model read since then fails. The PR body has no rollback note.

Fix (expand/contract): this PR opens the bound form first, then the customer-only form, and counts old-form opens. It writes nothing new: connect and model create/update keep the customer-only AAD, with no reseal on read. Add a test that a row written by this PR's code opens with the base's open call. Bound writes and reseal-on-read ship in the next release, once this one runs everywhere.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 82bdc3e: this PR now only learns to open the bound form. Line connect and model create/update seal with the customer-only AAD, as main does, and nothing is sealed again on a read; ChannelAccounts.Reseal and CustomModels.Reseal are gone from this PR. Tests: ChannelsSuite.TestTheCredentialsOpenAsThePreviousReleaseOpensThem and CustomModelsSuite.TestTheKeyOpensAsThePreviousReleaseOpensIt open what connect / create / PUT stored with the base's OpenWithAADVersion(sealed, customerID, v); each fails when that write seals bound. Bound writes and the reseal move to step 2 (branch ai-3632-step2); see «Rollout» in the description.

if err == nil {
err = s.store.ChannelAccounts.Reseal(ctx, stored.ID, stored.SecretsSealed, sealed, s.secrets.CurrentVersion())
}
if err != nil {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Should fix] R1.2 (moves to step 2 with the reseal, under R1.1) Nothing tests the rule that a failed write-back is logged and the line is still used. Mutant: add return line, err inside this if err != nil. Every suite stays green.

Test row, checked to fail under the mutant and pass on head, for LineSecretsSuite: store a legacy line and read it back. Build closed, _ := store.Open(testenv.Database(dsn, "channels_secrets")); closed.Close() (the closed-store gate from the go-testing skill). Then (&Service{store: closed, secrets: s.sealer, logger: ...}).open(ctx, account) must return no error and Token == "telnyx-key".

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Moot here after 82bdc3e: this PR has no write-back. The rule moves to step 2 with the reseal; its test LineSecretsSuite.TestALegacyLineWhoseWriteBackFailsIsStillUsed is on branch ai-3632-step2 (1f5f5cc) and fails when Service.open returns the write-back error.

[]byte(stored.CustomerID), stored.SecretsKEKVersion)
raw, legacy, err := secrets.OpenWithLegacyAAD(stored.SecretsSealed,
secretsAAD(stored.CustomerID, stored.Kind, stored.E164), []byte(stored.CustomerID),
stored.SecretsKEKVersion, "channel_account")

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Should fix] R1.3 No test checks the record label at either caller, and the follow-up deletes each fallback by this label. Two mutants keep every suite green: this line counting under "custom_model", and llmrouter/custom.go:63 counting under "channel_account".

Test rows, checked to fail under their mutant and pass on head:

  • LineSecretsSuite: connect a legacy line, then call service.line. router_sealed_legacy_opens_total{record="channel_account"}, read through prometheus.DefaultGatherer as in internal/vendorevent/vendorevent_test.go:110, must be >= before+1.
  • CustomModelKeySuite: create a legacy model, then call CustomModel. {record="custom_model"} must be >= before+1.

Use >=, not ==: the label is fixed, so other tests in the package can move it. The mutant moves the count to the other label, so >= still catches it.

The counter stays in step 1, so this applies under R1.1 too.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 062041e: LineSecretsSuite.TestALineSealedBoundOnlyToItsCustomerOpensIsLeftAsItIsAndIsCounted reads router_sealed_legacy_opens_total{record="channel_account"} and CustomModelKeySuite.TestAKeySealedBoundOnlyToItsCustomerOpensIsLeftAsItIsAndIsCounted reads {record="custom_model"}, each >= before+1. Swapping the two labels fails each test.

kanat and others added 3 commits November 26, 2026 15:40
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ling the old one

R1.1: a blob sealed bound to its row does not open on the previous
release, which breaks a rollback and the old pods of an overlap deploy.
This release only learns to open both forms: line connect and custom
model create/update seal bound to the customer, as before, and nothing
is sealed again on a read. Bound writes and the reseal move to step 2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
R1.3: a line opened in the customer-only form counts as channel_account,
a model key as custom_model.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@kanat kanat changed the title [AI-3632] Bind sealed line and model secrets to their row [AI-3632] Open line and model secrets bound to their row, keep sealing them customer-only Nov 26, 2026

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

VERDICT: GO

Delta round 2, head 062041e merged onto main 25b4f15 (clean). Details: delta-2.md in the ticket ledger.

Prior findings

  • R1.1 (Blocker, previous release cannot open what this PR writes): fixed. Connect, reconnect and model create/update seal customer-only again (api/channels.go, api/custom_models.go and store/* equal main). I made rows with the head (connect + reconnect a line, create + update a model), then opened them with the base sha's channels.Open and base CustomModels.CustomModel on the same database: both open. The head's own open leaves the rows byte-identical (row_to_json before and after).
  • R1.2 and S1.1 are on ai-3632-step2 (1f5f5cc): TestALegacyLineWhoseWriteBackFailsIsStillUsed and TestAResealLeavesAModelOfAnotherCustomer pass there. Returning the write-back error from Service.open fails the first, dropping the customer_id guard at store/custom_model.go:179 fails the second.
  • R1.3 (counter label unpinned): fixed. Mutant R4 (line counted as custom_model) fails TestALineSealedBoundOnlyToItsCustomerOpensIsLeftAsItIsAndIsCounted. Mutant R4b (model counted as channel_account) fails TestAKeySealedBoundOnlyToItsCustomerOpensIsLeftAsItIsAndIsCounted.
  • S1.2, R1.4: closed (settled by D3, sibling PR).

New findings

  • [Nit] auth/secret.go (OpenWithLegacyAAD): when both opens fail it returns the bound-form error, as the comment says. A mutant returning the legacy error survives. Nothing reads the difference, so no test is asked for.

Checks: build, vet (+ integration tag) and gofmt clean on the touched packages. auth unit; channels and llmrouter integration; api Channels, CustomModels, PrivateCustomModels, Telnyx, WhatsApp and Linq suites pass. Extra mutants (no counter Inc, bound/legacy order swapped) are killed. The PR body says nothing about moving a customer-only blob between rows. CI: draft, Go and integration skipped (#2130); the other checks pass.

@kanat
kanat marked this pull request as ready for review November 26, 2026 21:11
@kanat
kanat merged commit 184df63 into main Nov 26, 2026
20 of 21 checks passed
@kanat
kanat deleted the ai-3632-channel-model-aad branch November 26, 2026 22:35
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