From 7b4064a0dc2fade74eb9c514602d56b9c93e34a9 Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 14:52:07 -0500 Subject: [PATCH 1/6] fix(router): bind sealed channel line and custom model secrets to their 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 --- acceleration/internal/api/channels.go | 12 +- acceleration/internal/api/channels_test.go | 15 ++ acceleration/internal/api/custom_models.go | 6 +- .../internal/api/custom_models_test.go | 27 +++ .../internal/api/scheduled_reach_test.go | 2 +- .../internal/api/scheduled_tasks_test.go | 2 +- .../internal/api/telephony_billing_test.go | 2 +- acceleration/internal/auth/secret.go | 28 +++ acceleration/internal/auth/secret_test.go | 58 ++++++ .../channels/secrets_integration_test.go | 168 ++++++++++++++++++ .../channels/sent_integration_test.go | 38 +++- acceleration/internal/channels/service.go | 68 +++++-- acceleration/internal/llmrouter/custom.go | 31 +++- .../llmrouter/custom_integration_test.go | 149 ++++++++++++++++ .../internal/store/channel_account.go | 19 +- .../internal/store/channel_account_test.go | 47 +++++ acceleration/internal/store/custom_model.go | 26 ++- .../internal/store/custom_model_test.go | 45 +++++ 18 files changed, 706 insertions(+), 37 deletions(-) create mode 100644 acceleration/internal/channels/secrets_integration_test.go create mode 100644 acceleration/internal/llmrouter/custom_integration_test.go diff --git a/acceleration/internal/api/channels.go b/acceleration/internal/api/channels.go index b22b8fef1b..43d94739e2 100644 --- a/acceleration/internal/api/channels.go +++ b/acceleration/internal/api/channels.go @@ -73,7 +73,7 @@ func (s *Server) connectChannel(ctx context.Context, request *connectChannelRequ AccountID: strings.TrimSpace(value(body.AccountId)), Token: token, } - sealed, err := s.sealChannelSecrets(customerID, channels.Secrets{ + sealed, err := channels.Seal(s.secrets, customerID, string(kind), number, channels.Secrets{ Token: strings.TrimSpace(value(body.Token)), Signing: strings.TrimSpace(value(body.Signing)), Challenge: strings.TrimSpace(value(body.Challenge)), @@ -277,16 +277,6 @@ func channelCredentialsComplaint(kind channels.Kind, body ConnectChannelRequest) return "", true } -// sealChannelSecrets wraps a line's credentials under this deployment's key, bound to the -// customer so ciphertext moved to another app's row does not open. -func (s *Server) sealChannelSecrets(customerID string, secrets channels.Secrets) ([]byte, error) { - raw, err := json.Marshal(secrets) - if err != nil { - return nil, stack.Wrap(err) - } - return s.secrets.SealWithAAD(string(raw), []byte(customerID)) -} - // channelAccountOf renders a line for the wire, with the URL its provider delivers to. That // URL is the point of connecting: it is what is pasted into Meta's or Linq's setup. func (s *Server) channelAccountOf(account store.ChannelAccount) ChannelAccount { diff --git a/acceleration/internal/api/channels_test.go b/acceleration/internal/api/channels_test.go index af1960b070..885b8fbc46 100644 --- a/acceleration/internal/api/channels_test.go +++ b/acceleration/internal/api/channels_test.go @@ -100,6 +100,21 @@ func (s *ChannelsSuite) TestTheCredentialsAreSealedInTheDatabase() { s.Positive(stored.SecretsKEKVersion) } +// Catches connect sealing a line bound only to its customer, or to anything but the line it +// stored: what it stored opens as that line's and not in the customer-only form. +func (s *ChannelsSuite) TestTheCredentialsAreSealedBoundToTheLine() { + number := s.number() + s.connect(number) + + stored, err := s.store.ChannelAccounts.GetByNumber(context.Background(), s.customerID(), "whatsapp", number) + s.Require().NoError(err) + _, err = s.sealer.OpenWithAADVersion(stored.SecretsSealed, []byte(s.customerID()), stored.SecretsKEKVersion) + s.Error(err, "not in the customer-only form") + line, err := channels.Open(s.sealer, stored) + s.Require().NoError(err) + s.Equal("meta-token", line.Token) +} + // Rotating a token must not mean setting the webhook up with Meta all over again. func (s *ChannelsSuite) TestReconnectingALineKeepsItsWebhookURL() { number := s.number() diff --git a/acceleration/internal/api/custom_models.go b/acceleration/internal/api/custom_models.go index 3d895aa68d..07cdebc9cc 100644 --- a/acceleration/internal/api/custom_models.go +++ b/acceleration/internal/api/custom_models.go @@ -8,6 +8,7 @@ import ( "time" "github.com/GetStream/Vision-Agents/acceleration/internal/egress" + "github.com/GetStream/Vision-Agents/acceleration/internal/llmrouter" "github.com/GetStream/Vision-Agents/acceleration/internal/options" "github.com/GetStream/Vision-Agents/acceleration/internal/routing" "github.com/GetStream/Vision-Agents/acceleration/internal/store" @@ -75,7 +76,8 @@ func (s *Server) createCustomModel(ctx context.Context, request *createCustomMod return nil, errNoCustomModels } - model := store.CustomModel{CustomerID: customerID} + // The id is set before Insert, since the key is sealed bound to it. + model := store.CustomModel{ID: store.NewID(), CustomerID: customerID} if failure := s.fillCustomModel(ctx, &model, request.Body); failure != nil { return nil, failure } @@ -177,7 +179,7 @@ func (s *Server) fillCustomModel(ctx context.Context, model *store.CustomModel, if s.secrets == nil { return errNoModelKeys } - sealed, err := s.secrets.SealWithAAD(*request.ApiKey, []byte(model.CustomerID)) + sealed, err := s.secrets.SealWithAAD(*request.ApiKey, llmrouter.CustomModelKeyAAD(model.CustomerID, model.ID)) if err != nil { return err } diff --git a/acceleration/internal/api/custom_models_test.go b/acceleration/internal/api/custom_models_test.go index dde8af1994..c9cb55de61 100644 --- a/acceleration/internal/api/custom_models_test.go +++ b/acceleration/internal/api/custom_models_test.go @@ -6,6 +6,8 @@ import ( "context" "net/http" "testing" + + "github.com/GetStream/Vision-Agents/acceleration/internal/llmrouter" ) type CustomModelsSuite struct { @@ -42,6 +44,31 @@ func (s *CustomModelsSuite) TestAModelIsStoredAndReadBackWithoutItsKey() { s.NotContains(string(stored.APIKeySealed), "sk-secret", "the key is sealed at rest") } +// Catches a key sealed bound only to the customer, or to an id the model does not end up with: +// the key a model is created or updated with opens bound to the id it is read back under. +func (s *CustomModelsSuite) TestTheKeyIsSealedBoundToTheModelItIsGivenTo() { + created := s.createModel(map[string]any{ + "name": "bound", "base_url": "https://8.8.8.8/v1", "model": "a", "api_key": "sk-first", + }) + s.Equal("sk-first", s.storedKey(created.Id)) + + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPut, "/v1/agents/models/"+created.Id, + map[string]any{"name": "bound", "base_url": "https://8.8.8.8/v1", "model": "a", "api_key": "sk-second"}, nil)) + s.Equal("sk-second", s.storedKey(created.Id)) +} + +// storedKey opens the stored key of the model id bound to that model, and checks it does not +// open bound to the customer only. +func (s *CustomModelsSuite) storedKey(id string) string { + stored, err := s.store.CustomModels.Get(context.Background(), s.customerID(), id) + s.Require().NoError(err) + _, err = s.sealer.OpenWithAADVersion(stored.APIKeySealed, []byte(s.customerID()), stored.KEKVersion) + s.Require().Error(err, "not in the customer-only form") + key, err := s.sealer.OpenWithAADVersion(stored.APIKeySealed, llmrouter.CustomModelKeyAAD(s.customerID(), id), stored.KEKVersion) + s.Require().NoError(err) + return key +} + func (s *CustomModelsSuite) TestModelsAreListedNewestFirstAPageAtATime() { first := s.createModel(map[string]any{"name": "first", "base_url": "https://8.8.8.8/v1", "model": "a"}) second := s.createModel(map[string]any{"name": "second", "base_url": "https://8.8.8.8/v1", "model": "b"}) diff --git a/acceleration/internal/api/scheduled_reach_test.go b/acceleration/internal/api/scheduled_reach_test.go index eef7de6644..d09249033c 100644 --- a/acceleration/internal/api/scheduled_reach_test.go +++ b/acceleration/internal/api/scheduled_reach_test.go @@ -74,7 +74,7 @@ func (s *ScheduledTasksSuite) TestAWhatsAppMessageMoreThanADayAfterThePersonWrot func (s *ScheduledTasksSuite) TestAnIMessageWithNoChatToWriteToIsUnreachable() { number := s.lineNumber() - sealed, err := s.router.sealChannelSecrets(s.customerID(), channels.Secrets{Token: "linq-key", Signing: "linq-secret"}) + sealed, err := channels.Seal(s.sealer, s.customerID(), "imessage", number, channels.Secrets{Token: "linq-key", Signing: "linq-secret"}) s.Require().NoError(err) s.Require().NoError(s.store.ChannelAccounts.Upsert(context.Background(), &store.ChannelAccount{ CustomerID: s.customerID(), Kind: "imessage", E164: number, Token: "line-" + s.utils.uuid(), diff --git a/acceleration/internal/api/scheduled_tasks_test.go b/acceleration/internal/api/scheduled_tasks_test.go index 8aa6c68841..4f814cbf6e 100644 --- a/acceleration/internal/api/scheduled_tasks_test.go +++ b/acceleration/internal/api/scheduled_tasks_test.go @@ -3236,7 +3236,7 @@ func (s *RouterSuite) seedSMSLine(number string) { CustomerID: s.customerID(), E164: number, Vendor: "telnyx", Capabilities: []string{"sms"}, })) - sealed, err := s.router.sealChannelSecrets(s.customerID(), channels.Secrets{ + sealed, err := channels.Seal(s.sealer, s.customerID(), "sms", number, channels.Secrets{ Token: "telnyx-key", Signing: "a-public-key", }) s.Require().NoError(err) diff --git a/acceleration/internal/api/telephony_billing_test.go b/acceleration/internal/api/telephony_billing_test.go index 79066aeedd..633cd19a5b 100644 --- a/acceleration/internal/api/telephony_billing_test.go +++ b/acceleration/internal/api/telephony_billing_test.go @@ -538,7 +538,7 @@ func (s *telephonyBilling) smsLine() string { s.Require().NoError(s.store.PhoneNumbers.Insert(ctx, &store.PhoneNumber{ CustomerID: s.customerID(), E164: number, Vendor: "telnyx", Country: "US", Capabilities: []string{"sms"}, })) - sealed, err := s.router.sealChannelSecrets(s.customerID(), channels.Secrets{Token: "telnyx-key", Signing: s.public}) + sealed, err := channels.Seal(s.sealer, s.customerID(), "sms", number, channels.Secrets{Token: "telnyx-key", Signing: s.public}) s.Require().NoError(err) s.Require().NoError(s.store.ChannelAccounts.Upsert(ctx, &store.ChannelAccount{ CustomerID: s.customerID(), Kind: "sms", E164: number, Token: "line-" + s.utils.uuid(), diff --git a/acceleration/internal/auth/secret.go b/acceleration/internal/auth/secret.go index 17c959706f..ce21a0ea25 100644 --- a/acceleration/internal/auth/secret.go +++ b/acceleration/internal/auth/secret.go @@ -9,6 +9,9 @@ import ( "errors" "fmt" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promauto" + "github.com/GetStream/Vision-Agents/acceleration/internal/stack" ) @@ -142,3 +145,28 @@ func (s *Sealer) OpenWithAADVersion(sealed, additional []byte, version int) (str } return string(plain), nil } + +// legacyOpens counts the records that opened only under the additional data they had before they were bound to +// their row. Their readers seal each one again bound to its row, so the count falls to zero as those records are +// read, and OpenWithLegacyAAD can go once it stays there. record is a fixed name per kind of record. +var legacyOpens = promauto.NewCounterVec(prometheus.CounterOpts{ + Namespace: "router", + Name: "sealed_legacy_opens_total", + Help: "Sealed records that opened only under the additional data they had before they were bound to their row, by kind of record", +}, []string{"record"}) + +// OpenWithLegacyAAD is OpenWithAADVersion for a record that may still be sealed with legacy, the additional data +// it had before it was bound to its row. wasLegacy says it was, counted under record, so the caller can seal it +// again with additional. A record that opens under neither fails with the error of additional. +func (s *Sealer) OpenWithLegacyAAD(sealed, additional, legacy []byte, version int, record string) (plain string, wasLegacy bool, err error) { + plain, err = s.OpenWithAADVersion(sealed, additional, version) + if err == nil { + return plain, false, nil + } + plain, legacyErr := s.OpenWithAADVersion(sealed, legacy, version) + if legacyErr != nil { + return "", false, err + } + legacyOpens.WithLabelValues(record).Inc() + return plain, true, nil +} diff --git a/acceleration/internal/auth/secret_test.go b/acceleration/internal/auth/secret_test.go index 1eee8d4940..81dbbc8b71 100644 --- a/acceleration/internal/auth/secret_test.go +++ b/acceleration/internal/auth/secret_test.go @@ -5,6 +5,7 @@ import ( "crypto/sha256" "testing" + "github.com/prometheus/client_golang/prometheus/testutil" "github.com/stretchr/testify/suite" ) @@ -63,6 +64,63 @@ func (s *KeyringSuite) TestAWrongAADFailsToOpen() { s.Error(err, "a secret bound to a record does not open without it") } +func (s *KeyringSuite) TestARecordSealedBoundToItsRowOpensAsNotLegacy() { + sealer, err := NewSealer("a passphrase") + s.Require().NoError(err) + sealed, err := sealer.SealWithAAD("line secret", s.record) + s.Require().NoError(err) + before := testutil.ToFloat64(legacyOpens.WithLabelValues("bound-record")) + + opened, legacy, err := sealer.OpenWithLegacyAAD(sealed, s.record, []byte("tenant"), 1, "bound-record") + s.Require().NoError(err) + s.Equal("line secret", opened) + s.False(legacy) + s.InDelta(before, testutil.ToFloat64(legacyOpens.WithLabelValues("bound-record")), 0) +} + +func (s *KeyringSuite) TestARecordSealedBoundOnlyToItsCustomerOpensAsLegacyAndIsCounted() { + sealer, err := NewSealer("a passphrase") + s.Require().NoError(err) + sealed, err := sealer.SealWithAAD("line secret", []byte("tenant")) + s.Require().NoError(err) + before := testutil.ToFloat64(legacyOpens.WithLabelValues("legacy-record")) + + opened, legacy, err := sealer.OpenWithLegacyAAD(sealed, s.record, []byte("tenant"), 1, "legacy-record") + s.Require().NoError(err) + s.Equal("line secret", opened) + s.True(legacy) + s.InDelta(before+1, testutil.ToFloat64(legacyOpens.WithLabelValues("legacy-record")), 0) +} + +func (s *KeyringSuite) TestARecordOpeningUnderNeitherFailsWithTheErrorOfTheCurrentForm() { + sealer, err := NewSealer("a passphrase") + s.Require().NoError(err) + sealed, err := sealer.SealWithAAD("line secret", []byte("tenant/another-row")) + s.Require().NoError(err) + + opened, legacy, err := sealer.OpenWithLegacyAAD(sealed, s.record, []byte("tenant"), 1, "moved-record") + s.ErrorContains(err, "auth: open secret") + s.Empty(opened) + s.False(legacy) + s.InDelta(0, testutil.ToFloat64(legacyOpens.WithLabelValues("moved-record")), 0) +} + +func (s *KeyringSuite) TestALegacyRecordSealedUnderAnOlderKeyOpensWithItsStoredVersion() { + before, err := NewSealer("old-key") + s.Require().NoError(err) + sealed, err := before.SealWithAAD("line secret", []byte("tenant")) + s.Require().NoError(err) + rotated, err := NewSealerWithKeyring(2, map[int]string{1: "old-key", 2: "new-key"}) + s.Require().NoError(err) + + opened, legacy, err := rotated.OpenWithLegacyAAD(sealed, s.record, []byte("tenant"), 1, "rotated-record") + s.Require().NoError(err) + s.Equal("line secret", opened) + s.True(legacy) + _, _, err = rotated.OpenWithLegacyAAD(sealed, s.record, []byte("tenant"), 2, "rotated-record") + s.Error(err, "the stored version, not the current one, opens it") +} + func (s *KeyringSuite) TestAVersionNotInTheKeyringFailsToOpen() { sealer, err := NewSealer("a passphrase") s.Require().NoError(err) diff --git a/acceleration/internal/channels/secrets_integration_test.go b/acceleration/internal/channels/secrets_integration_test.go new file mode 100644 index 0000000000..39d0c39d5e --- /dev/null +++ b/acceleration/internal/channels/secrets_integration_test.go @@ -0,0 +1,168 @@ +//go:build integration + +package channels + +import ( + "context" + "log/slog" + "os" + "testing" + + "github.com/google/uuid" + "github.com/stretchr/testify/suite" + + "github.com/GetStream/Vision-Agents/acceleration/internal/auth" + "github.com/GetStream/Vision-Agents/acceleration/internal/store" + "github.com/GetStream/Vision-Agents/acceleration/internal/testenv" +) + +// LineSecretsSuite is how a line's sealed credentials are read back: bound to the line, and +// still readable from a line sealed before they were, which is then sealed again bound to it. +type LineSecretsSuite struct { + suite.Suite + ctx context.Context + store *store.Store + sealer *auth.Sealer + service *Service + customerID string +} + +func TestLineSecretsSuite(t *testing.T) { suite.Run(t, new(LineSecretsSuite)) } + +func (s *LineSecretsSuite) SetupSuite() { + dsn := os.Getenv("ROUTER_POSTGRES_DSN") + if dsn == "" { + s.T().Skip("ROUTER_POSTGRES_DSN not set") + } + s.ctx = context.Background() + opened, err := store.Open(testenv.Database(dsn, "channels_secrets")) + s.Require().NoError(err) + s.Require().NoError(opened.Migrate(s.ctx)) + s.T().Cleanup(func() { s.Require().NoError(opened.Close()) }) + s.store = opened + s.sealer, err = auth.NewSealer("line-secrets-kek") + s.Require().NoError(err) +} + +func (s *LineSecretsSuite) SetupTest() { + s.customerID = "line-secrets-" + uuid.NewString() + s.service = s.serviceSealedBy(s.sealer) +} + +func (s *LineSecretsSuite) serviceSealedBy(sealer *auth.Sealer) *Service { + return &Service{store: s.store, secrets: sealer, logger: slog.New(slog.DiscardHandler)} +} + +// number is a line number no other test connects. +func (s *LineSecretsSuite) number() string { + return "+1555" + uuid.NewString()[:7] +} + +// connected stores the SMS line e164 holding sealed as its credentials and returns the row. +func (s *LineSecretsSuite) connected(e164 string, sealed []byte, version int) store.ChannelAccount { + account := store.ChannelAccount{ + CustomerID: s.customerID, Kind: string(SMS), E164: e164, + Token: "line-" + uuid.NewString(), SecretsSealed: sealed, SecretsKEKVersion: version, + } + s.Require().NoError(s.store.ChannelAccounts.Upsert(s.ctx, &account)) + return account +} + +// legacy is a line's credentials sealed the way lines were before they were bound to the +// line: bound to the customer only. +func (s *LineSecretsSuite) legacy(sealer *auth.Sealer) []byte { + sealed, err := sealer.SealWithAAD(`{"token":"telnyx-key","signing":"a-public-key"}`, []byte(s.customerID)) + s.Require().NoError(err) + return sealed +} + +func (s *LineSecretsSuite) stored(account store.ChannelAccount) store.ChannelAccount { + held, err := s.store.ChannelAccounts.GetByToken(s.ctx, account.Token) + s.Require().NoError(err) + return held +} + +// Catches the line's own AAD naming only the customer, or a fallback that opens any blob of +// the customer's: credentials sealed for one line, put in another line's row, do not open. +func (s *LineSecretsSuite) TestCredentialsMovedFromAnotherLineDoNotOpen() { + sealed, err := Seal(s.sealer, s.customerID, string(SMS), s.number(), Secrets{Token: "telnyx-key"}) + s.Require().NoError(err) + second := s.connected(s.number(), sealed, s.sealer.CurrentVersion()) + + _, _, err = s.service.line(s.ctx, second.Token) + + s.ErrorContains(err, "cannot be opened") + s.Equal(sealed, s.stored(second).SecretsSealed, "nothing was sealed again from a blob that did not open") +} + +// Catches the kind or the customer missing from the line's AAD: the same number on another +// channel, or another app's line on the same number, is another line. +func (s *LineSecretsSuite) TestCredentialsSealedForTheSameNumberOnAnotherChannelOrAppDoNotOpen() { + number := s.number() + line := store.ChannelAccount{CustomerID: s.customerID, Kind: string(SMS), E164: number, + SecretsKEKVersion: s.sealer.CurrentVersion()} + var err error + + line.SecretsSealed, err = Seal(s.sealer, s.customerID, string(WhatsApp), number, Secrets{Token: "meta-token"}) + s.Require().NoError(err) + _, _, err = unseal(s.sealer, line) + s.Error(err, "a WhatsApp line's credentials on the SMS line of the same number") + + line.SecretsSealed, err = Seal(s.sealer, "another-app", string(SMS), number, Secrets{Token: "telnyx-key"}) + s.Require().NoError(err) + _, _, err = unseal(s.sealer, line) + s.Error(err, "another app's line of the same number") +} + +// Catches a line sealed bound to the line not opening, or being sealed again on every read. +func (s *LineSecretsSuite) TestALineSealedBoundToItselfOpensAndIsLeftAsItIs() { + number := s.number() + sealed, err := Seal(s.sealer, s.customerID, string(SMS), number, Secrets{Token: "telnyx-key"}) + s.Require().NoError(err) + account := s.connected(number, sealed, s.sealer.CurrentVersion()) + + line, _, err := s.service.line(s.ctx, account.Token) + + s.Require().NoError(err) + s.Equal("telnyx-key", line.Token) + s.Equal(sealed, s.stored(account).SecretsSealed) +} + +// Catches a line connected before the binding going dark, or staying in the old form: it +// opens, and the row then holds its credentials bound to the line and nothing else. +func (s *LineSecretsSuite) TestALineSealedBoundOnlyToItsCustomerOpensAndIsSealedAgainBoundToTheLine() { + account := s.connected(s.number(), s.legacy(s.sealer), s.sealer.CurrentVersion()) + + line, _, err := s.service.line(s.ctx, account.Token) + + s.Require().NoError(err) + s.Equal("telnyx-key", line.Token) + s.Equal("a-public-key", line.Signing) + held := s.stored(account) + _, err = s.sealer.OpenWithAADVersion(held.SecretsSealed, []byte(s.customerID), held.SecretsKEKVersion) + s.Error(err, "the customer-only form is gone from the row") + opened, legacy, err := unseal(s.sealer, held) + s.Require().NoError(err) + s.False(legacy) + s.Equal(line, opened) +} + +// Catches the old form being opened under the current key rather than the stored one, or +// sealed again under the old one: a rotation and the binding land on the same row. +func (s *LineSecretsSuite) TestALegacyLineUnderAnOlderKeyOpensAndIsSealedAgainUnderTheCurrentOne() { + before, err := auth.NewSealer("old-key") + s.Require().NoError(err) + account := s.connected(s.number(), s.legacy(before), 1) + rotated, err := auth.NewSealerWithKeyring(2, map[int]string{1: "old-key", 2: "new-key"}) + s.Require().NoError(err) + + line, _, err := s.serviceSealedBy(rotated).line(s.ctx, account.Token) + + s.Require().NoError(err) + s.Equal("telnyx-key", line.Token) + held := s.stored(account) + s.Equal(2, held.SecretsKEKVersion) + _, legacy, err := unseal(rotated, held) + s.Require().NoError(err) + s.False(legacy) +} diff --git a/acceleration/internal/channels/sent_integration_test.go b/acceleration/internal/channels/sent_integration_test.go index fc2a0eeda8..7f04445adb 100644 --- a/acceleration/internal/channels/sent_integration_test.go +++ b/acceleration/internal/channels/sent_integration_test.go @@ -89,14 +89,15 @@ func (s *SentSuite) reached() []string { return members } -// Catches Notify counting its recipient as the line or nobody: the second message a day to the -// same person must not take another of the organization's recipients. -func (s *SentSuite) TestANoticeCountsTheUserItReachedAsReached() { - line, writer := "+15550100"+uuid.NewString()[:2], "+13475550101" +// noticeLine connects an SMS line sealed the way lines were before they were bound to the +// line, bound to the customer only, with an agent on it that knows user-1 as writer. It returns +// the line's token and the agent's config. +func (s *SentSuite) noticeLine(writer string) (string, store.AgentConfig) { + line, token := "+15550100"+uuid.NewString()[:2], "line-"+uuid.NewString() sealed, err := s.sealer.SealWithAAD(`{"token":"telnyx-key"}`, []byte(s.owner.CustomerID)) s.Require().NoError(err) s.Require().NoError(s.money.Store.ChannelAccounts.Upsert(s.ctx, &store.ChannelAccount{ - CustomerID: s.owner.CustomerID, Kind: string(SMS), E164: line, Token: "line-" + uuid.NewString(), + CustomerID: s.owner.CustomerID, Kind: string(SMS), E164: line, Token: token, SecretsSealed: sealed, SecretsKEKVersion: s.sealer.CurrentVersion(), })) agentConfig := store.AgentConfig{CustomerID: s.owner.CustomerID, Name: "sent-" + uuid.NewString(), @@ -105,14 +106,39 @@ func (s *SentSuite) TestANoticeCountsTheUserItReachedAsReached() { s.Require().NoError(s.money.Store.ContactMapEntries.Upsert(s.ctx, &store.ContactMapEntry{ CustomerID: s.owner.CustomerID, ConfigID: agentConfig.ID, Kind: string(SMS), Address: writer, UserID: "user-1", })) + return token, agentConfig +} + +// Catches Notify counting its recipient as the line or nobody: the second message a day to the +// same person must not take another of the organization's recipients. +func (s *SentSuite) TestANoticeCountsTheUserItReachedAsReached() { + writer := "+13475550101" + _, agentConfig := s.noticeLine(writer) - err = s.service.Notify(s.ctx, Notice{CustomerID: s.owner.CustomerID, ConfigID: agentConfig.ID, Kind: SMS, + err := s.service.Notify(s.ctx, Notice{CustomerID: s.owner.CustomerID, ConfigID: agentConfig.ID, Kind: SMS, UserID: "user-1", Text: "Your table is ready."}) s.Require().NoError(err) s.Equal([]string{writer}, s.reached(), "the person written to, not the line, the customer or nobody") } +// Catches the outbound path opening a line still bound only to its customer without sealing +// it again bound to the line, which would keep that form alive on lines that only send. +func (s *SentSuite) TestANoticeOnALineSealedBoundOnlyToItsCustomerSealsItAgainBoundToTheLine() { + token, agentConfig := s.noticeLine("+13475550103") + + err := s.service.Notify(s.ctx, Notice{CustomerID: s.owner.CustomerID, ConfigID: agentConfig.ID, Kind: SMS, + UserID: "user-1", Text: "Your table is ready."}) + + s.Require().NoError(err) + s.reached() // deletes the day's counter Notify added to + held, err := s.money.Store.ChannelAccounts.GetByToken(s.ctx, token) + s.Require().NoError(err) + _, legacy, err := unseal(s.sealer, held) + s.Require().NoError(err) + s.False(legacy, "the row holds the credentials bound to the line") +} + // Catches a reply counting nobody, or the line, as the person reached: the reached set is who // the reply went to. func (s *SentSuite) TestAReplyCountsTheSenderItAnsweredAsReached() { diff --git a/acceleration/internal/channels/service.go b/acceleration/internal/channels/service.go index d9fa877a48..4572e1a7a7 100644 --- a/acceleration/internal/channels/service.go +++ b/acceleration/internal/channels/service.go @@ -306,7 +306,7 @@ func (s *Service) reach(ctx context.Context, notice Notice) (Account, string, st if err != nil { return Account{}, "", "", nil, stack.Wrap(err) } - line, err := Open(s.secrets, account) + line, err := s.open(ctx, account) if err != nil { return Account{}, "", "", nil, stack.Wrap(err) } @@ -344,30 +344,78 @@ func (s *Service) reach(ctx context.Context, notice Notice) (Account, string, st return line, thread, identity.Address, provider, nil } -// Open reads back the credentials a line was stored with. The customer is bound into the -// sealing, so ciphertext moved to another app's row does not open. +// Seal wraps a line's credentials under the deployment's key, bound to the line (secretsAAD). +func Seal(secrets *auth.Sealer, customerID, kind, e164 string, credentials Secrets) ([]byte, error) { + raw, err := json.Marshal(credentials) + if err != nil { + return nil, stack.Wrap(err) + } + return secrets.SealWithAAD(string(raw), secretsAAD(customerID, kind, e164)) +} + +// Open reads back the credentials a line was stored with. They are bound to the line, so +// ciphertext moved to another line's row does not open. func Open(secrets *auth.Sealer, stored store.ChannelAccount) (Account, error) { + account, _, err := unseal(secrets, stored) + return account, err +} + +// unseal is Open, saying too whether the line was sealed bound only to its customer, as lines +// were before they were bound to the line. +func unseal(secrets *auth.Sealer, stored store.ChannelAccount) (Account, bool, error) { account := Account{ Kind: Kind(stored.Kind), E164: stored.E164, AccountID: stored.AccountID, } if secrets == nil || len(stored.SecretsSealed) == 0 { - return account, stack.Wrap(errors.New("channels: this line has no stored credentials")) + return account, false, stack.Wrap(errors.New("channels: this line has no stored credentials")) } - raw, err := secrets.OpenWithAADVersion(stored.SecretsSealed, - []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") if err != nil { - return account, err + return account, false, err } var opened Secrets if err := json.Unmarshal([]byte(raw), &opened); err != nil { - return account, stack.Wrap(err) + return account, false, stack.Wrap(err) } account.Token = opened.Token account.Signing = opened.Signing account.Challenge = opened.Challenge - return account, nil + return account, legacy, nil +} + +// open is Open for a line the service is about to use. A line still sealed bound only to its +// customer is sealed again bound to the line, so that form is gone from every line in use. +// Failing to write it back costs nothing but another try on the next use, so it is logged and +// the line is used. +func (s *Service) open(ctx context.Context, stored store.ChannelAccount) (Account, error) { + line, legacy, err := unseal(s.secrets, stored) + if err != nil || !legacy { + return line, err + } + 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()) + } + if err != nil { + s.logger.Warn("could not seal a line's credentials again bound to the line", "customer", stored.CustomerID, + "channel", stored.Kind, "error", err) + } + return line, nil +} + +// secretsAAD binds a line's sealed credentials to the line: its customer, channel and number. +// No two live lines share those (channel_accounts_line_idx), and a reconnect keeps them, where +// the row's id is not known until Upsert returns the one the line already had. Each part is +// length-prefixed, as pgsealed's credentialsAAD is, so no two lines give the same bytes. v1 +// changes with the layout. +func secretsAAD(customerID, kind, e164 string) []byte { + return fmt.Appendf(nil, "accelerate:channel-secrets:v1:%d:%s:%d:%s:%d:%s", + len(customerID), customerID, len(kind), kind, len(e164), e164) } // line opens the credentials of the account a delivery is addressed to. @@ -376,7 +424,7 @@ func (s *Service) line(ctx context.Context, token string) (Account, store.Channe if err != nil { return Account{}, store.ChannelAccount{}, errors.New("no line is connected at this address") } - line, err := Open(s.secrets, account) + line, err := s.open(ctx, account) if err != nil { return Account{}, account, errors.New("this line's credentials cannot be opened: connect it again") } diff --git a/acceleration/internal/llmrouter/custom.go b/acceleration/internal/llmrouter/custom.go index 334d0e1a7f..3ad5f70bdb 100644 --- a/acceleration/internal/llmrouter/custom.go +++ b/acceleration/internal/llmrouter/custom.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "log/slog" "net/http" "github.com/GetStream/Vision-Agents/acceleration/internal/auth" @@ -51,14 +52,42 @@ func (m *CustomModels) CustomModel(ctx context.Context, customerID, name string) return routing.ProviderConfig{}, routing.Endpoint{}, stack.Wrap( errors.New("routing: this deployment has no key to open a model's api key with")) } - endpoint.APIKey, err = m.secrets.OpenWithAADVersion(stored.APIKeySealed, []byte(customerID), stored.KEKVersion) + var legacy bool + endpoint.APIKey, legacy, err = m.secrets.OpenWithLegacyAAD(stored.APIKeySealed, + CustomModelKeyAAD(customerID, stored.ID), []byte(customerID), stored.KEKVersion, "custom_model") if err != nil { return routing.ProviderConfig{}, routing.Endpoint{}, err } + if legacy { + m.reseal(ctx, stored, endpoint.APIKey) + } } return CustomModelConfig(stored), endpoint, nil } +// reseal seals again bound to the model a key sealed bound only to its customer, as keys were +// before they were bound to their model, so that form is gone from every model in use. Failing +// to write it back costs nothing but another try on the next session, so it is logged and the +// session goes on. +func (m *CustomModels) reseal(ctx context.Context, stored store.CustomModel, key string) { + sealed, err := m.secrets.SealWithAAD(key, CustomModelKeyAAD(stored.CustomerID, stored.ID)) + if err == nil { + err = m.store.CustomModels.Reseal(ctx, stored, sealed, m.secrets.CurrentVersion()) + } + if err != nil { + slog.WarnContext(ctx, "could not seal a custom model's key again bound to the model", + "customer", stored.CustomerID, "model", stored.ID, "error", err) + } +} + +// CustomModelKeyAAD binds a model's sealed api key to its customer and id, so a key copied to +// another model's row does not open. The id, not the name: a model can be renamed. Each part is +// length-prefixed, as pgsealed's credentialsAAD is, so no two models give the same bytes. v1 +// changes with the layout. +func CustomModelKeyAAD(customerID, id string) []byte { + return fmt.Appendf(nil, "accelerate:custom-model-key:v1:%d:%s:%d:%s", len(customerID), customerID, len(id), id) +} + // CustomModelConfig is what routing knows about a customer's model: everything but where // it is and how to get in. func CustomModelConfig(stored store.CustomModel) routing.ProviderConfig { diff --git a/acceleration/internal/llmrouter/custom_integration_test.go b/acceleration/internal/llmrouter/custom_integration_test.go new file mode 100644 index 0000000000..847282d553 --- /dev/null +++ b/acceleration/internal/llmrouter/custom_integration_test.go @@ -0,0 +1,149 @@ +//go:build integration + +package llmrouter + +import ( + "context" + "os" + "testing" + + "github.com/google/uuid" + "github.com/stretchr/testify/suite" + + "github.com/GetStream/Vision-Agents/acceleration/internal/auth" + "github.com/GetStream/Vision-Agents/acceleration/internal/store" + "github.com/GetStream/Vision-Agents/acceleration/internal/testenv" + "github.com/GetStream/Vision-Agents/acceleration/internal/testenv/redisready" +) + +// CustomModelKeySuite is how a customer's model's sealed key is read back: bound to the model, +// and still readable from a model stored before it was, which is then sealed again bound to it. +// It reads through the name cache a session reads through. +type CustomModelKeySuite struct { + suite.Suite + ctx context.Context + store *store.Store + sealer *auth.Sealer + customerID string +} + +func TestCustomModelKeySuite(t *testing.T) { + suite.Run(t, new(CustomModelKeySuite)) +} + +func (s *CustomModelKeySuite) SetupSuite() { + dsn, address := os.Getenv("ROUTER_POSTGRES_DSN"), os.Getenv("ROUTER_REDIS_ADDR") + if dsn == "" || address == "" { + s.T().Skip("ROUTER_POSTGRES_DSN and ROUTER_REDIS_ADDR must be set") + } + s.ctx = context.Background() + opened, err := redisready.Retry(address, func() (*store.Store, error) { + return store.OpenShards(store.Options{DSN: testenv.Database(dsn, "llmrouter_custom"), Redis: store.Redis{Address: address}}) + }) + s.Require().NoError(err) + s.Require().NoError(opened.Migrate(s.ctx)) + s.T().Cleanup(func() { s.Require().NoError(opened.Close()) }) + s.store = opened + s.sealer, err = auth.NewSealer("custom-model-key-kek") + s.Require().NoError(err) +} + +func (s *CustomModelKeySuite) SetupTest() { + s.customerID = "custom-key-" + uuid.NewString() +} + +// model stores a model of the customer's under id, its key sealed as sealed under version. +func (s *CustomModelKeySuite) model(id string, sealed []byte, version int) store.CustomModel { + model := store.CustomModel{ID: id, CustomerID: s.customerID, Name: "tuned-" + uuid.NewString()[:8], + BaseURL: "https://8.8.8.8/v1", Model: "acme/tuned", APIKeySealed: sealed, KEKVersion: version} + s.Require().NoError(s.store.CustomModels.Insert(s.ctx, &model)) + return model +} + +// read is the model as a session reads it, through the name cache. +func (s *CustomModelKeySuite) read(model store.CustomModel) store.CustomModel { + read, err := s.store.CustomModels.GetByName(s.ctx, s.customerID, model.Name) + s.Require().NoError(err) + return read +} + +// Catches the key's AAD naming only the customer, or a fallback that opens any of the +// customer's blobs: a key sealed for one model, put in another model's row, does not open. +func (s *CustomModelKeySuite) TestAKeyMovedFromAnotherModelDoesNotOpen() { + sealed, err := s.sealer.SealWithAAD("sk-other", CustomModelKeyAAD(s.customerID, store.NewID())) + s.Require().NoError(err) + model := s.model(store.NewID(), sealed, s.sealer.CurrentVersion()) + + _, _, err = NewCustomModels(s.store, s.sealer, false).CustomModel(s.ctx, s.customerID, model.Name) + + s.ErrorContains(err, "auth: open secret") + s.Equal(sealed, s.read(model).APIKeySealed, "nothing was sealed again from a key that did not open") +} + +// Catches another customer's model of the same id opening here: the customer is in the AAD. +func (s *CustomModelKeySuite) TestAKeySealedForAnotherCustomersModelOfTheSameIdDoesNotOpen() { + id := store.NewID() + sealed, err := s.sealer.SealWithAAD("sk-other", CustomModelKeyAAD("another-app", id)) + s.Require().NoError(err) + model := s.model(id, sealed, s.sealer.CurrentVersion()) + + _, _, err = NewCustomModels(s.store, s.sealer, false).CustomModel(s.ctx, s.customerID, model.Name) + + s.ErrorContains(err, "auth: open secret") +} + +// Catches a key bound to its model not opening, or being sealed again on every session. +func (s *CustomModelKeySuite) TestAKeySealedBoundToItsModelOpensAndIsLeftAsItIs() { + id := store.NewID() + sealed, err := s.sealer.SealWithAAD("sk-own", CustomModelKeyAAD(s.customerID, id)) + s.Require().NoError(err) + model := s.model(id, sealed, s.sealer.CurrentVersion()) + + _, endpoint, err := NewCustomModels(s.store, s.sealer, false).CustomModel(s.ctx, s.customerID, model.Name) + + s.Require().NoError(err) + s.Equal("sk-own", endpoint.APIKey) + s.Equal(sealed, s.read(model).APIKeySealed) +} + +// Catches a model stored before the binding going dark, or staying in the old form, in the +// database or in the name cache a session reads through: it opens, and the next read holds the +// key bound to the model and nothing else. +func (s *CustomModelKeySuite) TestAKeySealedBoundOnlyToItsCustomerOpensAndIsSealedAgainBoundToTheModel() { + sealed, err := s.sealer.SealWithAAD("sk-own", []byte(s.customerID)) + s.Require().NoError(err) + model := s.model(store.NewID(), sealed, s.sealer.CurrentVersion()) + + _, endpoint, err := NewCustomModels(s.store, s.sealer, false).CustomModel(s.ctx, s.customerID, model.Name) + + s.Require().NoError(err) + s.Equal("sk-own", endpoint.APIKey) + read := s.read(model) + _, err = s.sealer.OpenWithAADVersion(read.APIKeySealed, []byte(s.customerID), read.KEKVersion) + s.Error(err, "the customer-only form is gone from what a session reads") + key, err := s.sealer.OpenWithAADVersion(read.APIKeySealed, CustomModelKeyAAD(s.customerID, model.ID), read.KEKVersion) + s.Require().NoError(err) + s.Equal("sk-own", key) +} + +// Catches the old form being opened under the current key rather than the stored one, or +// sealed again under the old one: a rotation and the binding land on the same row. +func (s *CustomModelKeySuite) TestALegacyKeyUnderAnOlderKeyOpensAndIsSealedAgainUnderTheCurrentOne() { + before, err := auth.NewSealer("old-key") + s.Require().NoError(err) + sealed, err := before.SealWithAAD("sk-own", []byte(s.customerID)) + s.Require().NoError(err) + model := s.model(store.NewID(), sealed, 1) + rotated, err := auth.NewSealerWithKeyring(2, map[int]string{1: "old-key", 2: "new-key"}) + s.Require().NoError(err) + + _, endpoint, err := NewCustomModels(s.store, rotated, false).CustomModel(s.ctx, s.customerID, model.Name) + + s.Require().NoError(err) + s.Equal("sk-own", endpoint.APIKey) + read := s.read(model) + s.Equal(2, read.KEKVersion) + key, err := rotated.OpenWithAADVersion(read.APIKeySealed, CustomModelKeyAAD(s.customerID, model.ID), 2) + s.Require().NoError(err) + s.Equal("sk-own", key) +} diff --git a/acceleration/internal/store/channel_account.go b/acceleration/internal/store/channel_account.go index 0de2fd3d67..e3216fa3cd 100644 --- a/acceleration/internal/store/channel_account.go +++ b/acceleration/internal/store/channel_account.go @@ -31,7 +31,7 @@ type ChannelAccount struct { // it apart from anybody who guessed the route. Token string `bun:"token,notnull"` // SecretsSealed is the provider's credentials as JSON, sealed under SecretsKEKVersion - // with the customer and the account's id as additional data. + // with the customer, the kind and the number as additional data. SecretsSealed []byte `bun:"secrets_sealed"` SecretsKEKVersion int `bun:"kek_version,notnull"` CreatedAt time.Time `bun:"created_at,notnull"` @@ -143,6 +143,23 @@ func (r *ChannelAccounts) Upsert(ctx context.Context, account *ChannelAccount) e return nil } +// Reseal replaces a line's sealed credentials with the same credentials sealed again. It +// writes only while the line still holds was, the bytes they were read as, so a reconnect or +// a disconnect since then stands. +func (r *ChannelAccounts) Reseal(ctx context.Context, id string, was, sealed []byte, version int) error { + _, err := r.store.global.NewUpdate().Model((*ChannelAccount)(nil)). + Set("secrets_sealed = ?", sealed). + Set("kek_version = ?", version). + Where("id = ?", id). + Where("secrets_sealed = ?", was). + Where("deleted_at IS NULL"). + Exec(ctx) + if err != nil { + return stack.Wrap(fmt.Errorf("store: reseal channel account: %w", err)) + } + return nil +} + // Delete disconnects a line, so deliveries to it are refused. The credentials go with it: a // line nobody answers on has no use for them. func (r *ChannelAccounts) Delete(ctx context.Context, customerID, kind, e164 string) error { diff --git a/acceleration/internal/store/channel_account_test.go b/acceleration/internal/store/channel_account_test.go index 532e9f3523..a09e419260 100644 --- a/acceleration/internal/store/channel_account_test.go +++ b/acceleration/internal/store/channel_account_test.go @@ -133,3 +133,50 @@ func (s *StoreSuite) TestChannelAccountQueryBudgets() { }), "GetByToken") s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.ChannelAccounts.Delete(s.ctx, customerID, "whatsapp", e164)) }), "Delete") } + +// Catches a reseal writing every line that holds the same bytes rather than the one read. +func (s *StoreSuite) TestAResealReplacesTheCredentialsOfTheLineItWasGiven() { + customerID := newID() + account := s.line(customerID, "+1555"+newID()[:7]) + other := s.line(customerID, "+1555"+newID()[:7]) + + s.Require().NoError(s.store.ChannelAccounts.Reseal(s.ctx, account.ID, []byte("sealed"), []byte("resealed"), 2)) + + held, err := s.store.ChannelAccounts.GetByToken(s.ctx, account.Token) + s.Require().NoError(err) + s.Equal([]byte("resealed"), held.SecretsSealed) + s.Equal(2, held.SecretsKEKVersion) + untouched, err := s.store.ChannelAccounts.GetByToken(s.ctx, other.Token) + s.Require().NoError(err) + s.Equal([]byte("sealed"), untouched.SecretsSealed) +} + +// Catches a reseal of what was read clobbering a reconnect that landed in between. +func (s *StoreSuite) TestAResealLeavesALineReconnectedSinceItWasRead() { + customerID := newID() + account := s.line(customerID, "+1555"+newID()[:7]) + s.Require().NoError(s.store.ChannelAccounts.Upsert(s.ctx, &ChannelAccount{ + CustomerID: customerID, Kind: "whatsapp", E164: account.E164, Token: newID(), + SecretsSealed: []byte("reconnected"), SecretsKEKVersion: 1, + })) + + s.Require().NoError(s.store.ChannelAccounts.Reseal(s.ctx, account.ID, []byte("sealed"), []byte("resealed"), 2)) + + held, err := s.store.ChannelAccounts.GetByToken(s.ctx, account.Token) + s.Require().NoError(err) + s.Equal([]byte("reconnected"), held.SecretsSealed) + s.Equal(1, held.SecretsKEKVersion) +} + +// Catches a reseal bringing the credentials of a disconnected line back. +func (s *StoreSuite) TestAResealLeavesADisconnectedLineWithoutCredentials() { + customerID := newID() + account := s.line(customerID, "+1555"+newID()[:7]) + s.Require().NoError(s.store.ChannelAccounts.Delete(s.ctx, customerID, "whatsapp", account.E164)) + + s.Require().NoError(s.store.ChannelAccounts.Reseal(s.ctx, account.ID, []byte("sealed"), []byte("resealed"), 2)) + + var held ChannelAccount + s.Require().NoError(s.store.global.NewSelect().Model(&held).Where("id = ?", account.ID).Scan(s.ctx)) + s.Nil(held.SecretsSealed) +} diff --git a/acceleration/internal/store/custom_model.go b/acceleration/internal/store/custom_model.go index cdc56076db..e9409d5e39 100644 --- a/acceleration/internal/store/custom_model.go +++ b/acceleration/internal/store/custom_model.go @@ -26,7 +26,7 @@ type CustomModel struct { // Model is the id the endpoint serves the weights under. Model string `bun:"model,notnull"` // APIKeySealed is the key the endpoint wants, sealed under KEKVersion and bound to the - // customer. Nil for an endpoint that takes none. + // customer and the model's id. Nil for an endpoint that takes none. APIKeySealed []byte `bun:"api_key_sealed"` KEKVersion int `bun:"kek_version,notnull"` ContextWindow int64 `bun:"context_window,notnull"` @@ -90,13 +90,15 @@ type CustomModels struct { store *Store } -// Insert stores a new model and fills in its id and timestamps. +// Insert stores a new model and fills in its timestamps, and its id unless it has one. func (r *CustomModels) Insert(ctx context.Context, model *CustomModel) error { if err := model.Validate(); err != nil { return stack.Wrap(err) } - model.ID = newID() + if model.ID == "" { + model.ID = newID() + } if model.InputModalities == nil { model.InputModalities = []string{} } @@ -155,6 +157,24 @@ func (r *CustomModels) Update(ctx context.Context, model *CustomModel) error { return nil } +// Reseal replaces a model's sealed key with the same key sealed again. It writes only while +// the model still holds the bytes it was read with, so a key changed since then stands, and +// it forgets the model's name, so the next read sees the new form. +func (r *CustomModels) Reseal(ctx context.Context, model CustomModel, sealed []byte, version int) error { + _, err := r.store.global.NewUpdate().Model((*CustomModel)(nil)). + Set("api_key_sealed = ?", sealed). + Set("kek_version = ?", version). + Where("id = ?", model.ID). + Where("customer_id = ?", model.CustomerID). + Where("api_key_sealed = ?", model.APIKeySealed). + Exec(ctx) + if err != nil { + return stack.Wrap(fmt.Errorf("store: reseal model key: %w", err)) + } + r.store.forget(ctx, customModelKey(model.CustomerID, model.Name)) + return nil +} + // Delete removes a model. A session that names it afterwards is refused. func (r *CustomModels) Delete(ctx context.Context, customerID, id string) error { if customerID == "" || id == "" { diff --git a/acceleration/internal/store/custom_model_test.go b/acceleration/internal/store/custom_model_test.go index 3ca1ac5567..ce5365d4ff 100644 --- a/acceleration/internal/store/custom_model_test.go +++ b/acceleration/internal/store/custom_model_test.go @@ -99,3 +99,48 @@ func (s *StoreSuite) TestCustomModelQueryBudgets() { s.Equal(1, s.countRedis(func() { s.Require().NoError(s.store.CustomModels.Delete(s.ctx, "app", other.ID)) }), "forgetting a row is one round trip") } + +func (s *StoreSuite) TestAModelGivenAnIdIsInsertedUnderIt() { + id := NewID() + + model := s.customModel("app", "tuned", func(model *CustomModel) { model.ID = id }) + + s.Equal(id, model.ID) + _, err := s.store.CustomModels.Get(s.ctx, "app", id) + s.Require().NoError(err) +} + +// Catches a reseal that leaves the old key in the name cache, which a session reads through, or +// that writes every model holding the same bytes rather than the one read. +func (s *StoreSuite) TestAResealReplacesTheKeyOfTheModelItWasGivenAndForgetsItsName() { + sealed := func(model *CustomModel) { model.APIKeySealed, model.KEKVersion = []byte("sealed"), 1 } + model := s.customModel("app", "tuned", sealed) + other := s.customModel("app", "other", sealed) + _, err := s.store.CustomModels.GetByName(s.ctx, "app", "tuned") + s.Require().NoError(err) + + s.Require().NoError(s.store.CustomModels.Reseal(s.ctx, model, []byte("resealed"), 2)) + + read, err := s.store.CustomModels.GetByName(s.ctx, "app", "tuned") + s.Require().NoError(err) + s.Equal([]byte("resealed"), read.APIKeySealed) + s.Equal(2, read.KEKVersion) + untouched, err := s.store.CustomModels.Get(s.ctx, "app", other.ID) + s.Require().NoError(err) + s.Equal([]byte("sealed"), untouched.APIKeySealed) +} + +// Catches a reseal of what was read clobbering a key the customer changed in between. +func (s *StoreSuite) TestAResealLeavesAKeyChangedSinceItWasRead() { + model := s.customModel("app", "tuned", func(model *CustomModel) { model.APIKeySealed, model.KEKVersion = []byte("sealed"), 1 }) + changed := model + changed.APIKeySealed = []byte("changed") + s.Require().NoError(s.store.CustomModels.Update(s.ctx, &changed)) + + s.Require().NoError(s.store.CustomModels.Reseal(s.ctx, model, []byte("resealed"), 2)) + + read, err := s.store.CustomModels.Get(s.ctx, "app", model.ID) + s.Require().NoError(err) + s.Equal([]byte("changed"), read.APIKeySealed) + s.Equal(1, read.KEKVersion) +} From e60c11b949a6829c9c5fd433771b27ff82c57fc5 Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 14:56:41 -0500 Subject: [PATCH 2/6] fix(store): reseal a custom model's key in a detached write 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 --- .../llmrouter/custom_integration_test.go | 5 +-- acceleration/internal/store/custom_model.go | 31 +++++++++++++------ .../internal/store/custom_model_test.go | 17 ++++++++++ 3 files changed, 42 insertions(+), 11 deletions(-) diff --git a/acceleration/internal/llmrouter/custom_integration_test.go b/acceleration/internal/llmrouter/custom_integration_test.go index 8cbb7d985a..ef6f411e68 100644 --- a/acceleration/internal/llmrouter/custom_integration_test.go +++ b/acceleration/internal/llmrouter/custom_integration_test.go @@ -51,10 +51,11 @@ func (s *CustomModelsSuite) SetupTest() { // keep stores a model whose key is sealed by sealer, as the API stores one. func (s *CustomModelsSuite) keep(name string, sealer *auth.Sealer) { - sealed, err := sealer.SealWithAAD("sk-endpoint", []byte(s.customerID)) + id := store.NewID() + sealed, err := sealer.SealWithAAD("sk-endpoint", CustomModelKeyAAD(s.customerID, id)) s.Require().NoError(err) s.Require().NoError(s.store.CustomModels.Insert(s.ctx, &store.CustomModel{ - CustomerID: s.customerID, Name: name, BaseURL: "https://models.example/v1", Model: "gemma-4", + ID: id, CustomerID: s.customerID, Name: name, BaseURL: "https://models.example/v1", Model: "gemma-4", APIKeySealed: sealed, KEKVersion: sealer.CurrentVersion(), })) } diff --git a/acceleration/internal/store/custom_model.go b/acceleration/internal/store/custom_model.go index 735e9a9313..64aed804d5 100644 --- a/acceleration/internal/store/custom_model.go +++ b/acceleration/internal/store/custom_model.go @@ -168,19 +168,32 @@ func (r *CustomModels) Update(ctx context.Context, model *CustomModel) error { // Reseal replaces a model's sealed key with the same key sealed again. It writes only while // the model still holds the bytes it was read with, so a key changed since then stands, and -// it forgets the model's name, so the next read sees the new form. +// it forgets the name the row has, so the next read sees the new form even after a rename. func (r *CustomModels) Reseal(ctx context.Context, model CustomModel, sealed []byte, version int) error { - _, err := r.store.global.NewUpdate().Model((*CustomModel)(nil)). - Set("api_key_sealed = ?", sealed). - Set("kek_version = ?", version). - Where("id = ?", model.ID). - Where("customer_id = ?", model.CustomerID). - Where("api_key_sealed = ?", model.APIKeySealed). - Exec(ctx) + var name string + err := r.store.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { + err := tx.NewUpdate().Model((*CustomModel)(nil)). + Set("api_key_sealed = ?", sealed). + Set("kek_version = ?", version). + Where("id = ?", model.ID). + Where("customer_id = ?", model.CustomerID). + Where("api_key_sealed = ?", model.APIKeySealed). + Returning("name"). + Scan(ctx, &name) + // No row: the key changed or the model went since it was read, and that write stands. + if errors.Is(err, sql.ErrNoRows) { + return nil + } + return err + }, func() []string { + if name == "" { + return nil + } + return []string{customModelKey(model.CustomerID, name)} + }) if err != nil { return stack.Wrap(fmt.Errorf("store: reseal model key: %w", err)) } - r.store.forget(ctx, customModelKey(model.CustomerID, model.Name)) return nil } diff --git a/acceleration/internal/store/custom_model_test.go b/acceleration/internal/store/custom_model_test.go index de3dd40f04..260971c79c 100644 --- a/acceleration/internal/store/custom_model_test.go +++ b/acceleration/internal/store/custom_model_test.go @@ -144,3 +144,20 @@ func (s *StoreSuite) TestAResealLeavesAKeyChangedSinceItWasRead() { s.Equal([]byte("changed"), read.APIKeySealed) s.Equal(1, read.KEKVersion) } + +// Catches a reseal forgetting only the name the model was read under: a rename in between +// leaves the old key cached under the new name, which the next session reads. +func (s *StoreSuite) TestAResealForgetsTheNameAModelWasRenamedToSinceItWasRead() { + model := s.customModel("app", "tuned", func(model *CustomModel) { model.APIKeySealed, model.KEKVersion = []byte("sealed"), 1 }) + renamed := model + renamed.Name = "renamed" + s.Require().NoError(s.store.CustomModels.Update(s.ctx, &renamed)) + _, err := s.store.CustomModels.GetByName(s.ctx, "app", "renamed") + s.Require().NoError(err) + + s.Require().NoError(s.store.CustomModels.Reseal(s.ctx, model, []byte("resealed"), 2)) + + read, err := s.store.CustomModels.GetByName(s.ctx, "app", "renamed") + s.Require().NoError(err) + s.Equal([]byte("resealed"), read.APIKeySealed) +} From 3530bc9f3d7c93c7cae242df93206bcffdcf7659 Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 15:01:07 -0500 Subject: [PATCH 3/6] test(router): a line's and a model key's AAD parts do not run together Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/channels/secrets_integration_test.go | 7 +++++++ acceleration/internal/llmrouter/custom_integration_test.go | 6 ++++++ 2 files changed, 13 insertions(+) diff --git a/acceleration/internal/channels/secrets_integration_test.go b/acceleration/internal/channels/secrets_integration_test.go index 39d0c39d5e..0ccd5c5a76 100644 --- a/acceleration/internal/channels/secrets_integration_test.go +++ b/acceleration/internal/channels/secrets_integration_test.go @@ -166,3 +166,10 @@ func (s *LineSecretsSuite) TestALegacyLineUnderAnOlderKeyOpensAndIsSealedAgainUn s.Require().NoError(err) s.False(legacy) } + +// Catches the parts of a line's AAD running together: a colon inside one part cannot make two +// lines give the same bytes. +func (s *LineSecretsSuite) TestTheLinesAADPartsDoNotRunTogether() { + s.NotEqual(secretsAAD("app:sms", "whatsapp", "+15550100"), secretsAAD("app", "sms:whatsapp", "+15550100")) + s.NotEqual(secretsAAD("app", "sms:+1555", "0100"), secretsAAD("app", "sms", "+1555:0100")) +} diff --git a/acceleration/internal/llmrouter/custom_integration_test.go b/acceleration/internal/llmrouter/custom_integration_test.go index ef6f411e68..1e1a9df9ae 100644 --- a/acceleration/internal/llmrouter/custom_integration_test.go +++ b/acceleration/internal/llmrouter/custom_integration_test.go @@ -220,3 +220,9 @@ func (s *CustomModelKeySuite) TestALegacyKeyUnderAnOlderKeyOpensAndIsSealedAgain s.Require().NoError(err) s.Equal("sk-own", key) } + +// Catches the parts of a model key's AAD running together: a colon inside one part cannot make +// two models give the same bytes. +func (s *CustomModelKeySuite) TestTheKeysAADPartsDoNotRunTogether() { + s.NotEqual(CustomModelKeyAAD("app:model", "id"), CustomModelKeyAAD("app", "model:id")) +} From 0cc6cd5cc4f407856aebb28e91805c1938548ac4 Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 15:09:13 -0500 Subject: [PATCH 4/6] refactor(store): a line's reseal relies on the bytes check alone 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 --- acceleration/internal/store/channel_account.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/acceleration/internal/store/channel_account.go b/acceleration/internal/store/channel_account.go index e3216fa3cd..51eb9b5998 100644 --- a/acceleration/internal/store/channel_account.go +++ b/acceleration/internal/store/channel_account.go @@ -144,15 +144,14 @@ func (r *ChannelAccounts) Upsert(ctx context.Context, account *ChannelAccount) e } // Reseal replaces a line's sealed credentials with the same credentials sealed again. It -// writes only while the line still holds was, the bytes they were read as, so a reconnect or -// a disconnect since then stands. +// writes only while the line still holds was, the bytes they were read as, so a reconnect +// since then stands, and so does a disconnect, which empties them. func (r *ChannelAccounts) Reseal(ctx context.Context, id string, was, sealed []byte, version int) error { _, err := r.store.global.NewUpdate().Model((*ChannelAccount)(nil)). Set("secrets_sealed = ?", sealed). Set("kek_version = ?", version). Where("id = ?", id). Where("secrets_sealed = ?", was). - Where("deleted_at IS NULL"). Exec(ctx) if err != nil { return stack.Wrap(fmt.Errorf("store: reseal channel account: %w", err)) From 82bdc3e556e7d921cc92d0b02525115963cf067c Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 15:47:05 -0500 Subject: [PATCH 5/6] AI-3632: open both forms of a line's and a model key's seal, keep sealing 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 --- acceleration/internal/api/channels.go | 12 ++- acceleration/internal/api/channels_test.go | 13 +-- acceleration/internal/api/custom_models.go | 6 +- .../internal/api/custom_models_test.go | 16 ++- .../internal/api/scheduled_reach_test.go | 2 +- .../internal/api/scheduled_tasks_test.go | 2 +- .../internal/api/telephony_billing_test.go | 2 +- acceleration/internal/auth/secret.go | 20 ++-- acceleration/internal/auth/secret_test.go | 18 ++-- .../channels/secrets_integration_test.go | 75 +++++++------- .../channels/sent_integration_test.go | 38 ++----- acceleration/internal/channels/service.go | 57 +++-------- acceleration/internal/llmrouter/custom.go | 32 ++---- .../llmrouter/custom_integration_test.go | 98 +++++++++---------- .../internal/store/channel_account.go | 18 +--- .../internal/store/channel_account_test.go | 47 --------- acceleration/internal/store/custom_model.go | 39 +------- .../internal/store/custom_model_test.go | 62 ------------ 18 files changed, 155 insertions(+), 402 deletions(-) diff --git a/acceleration/internal/api/channels.go b/acceleration/internal/api/channels.go index d47cee5261..cf7755feff 100644 --- a/acceleration/internal/api/channels.go +++ b/acceleration/internal/api/channels.go @@ -74,7 +74,7 @@ func (s *Server) connectChannel(ctx context.Context, request *connectChannelRequ AccountID: strings.TrimSpace(value(body.AccountId)), Token: token, } - sealed, err := channels.Seal(s.secrets, customerID, string(kind), number, channels.Secrets{ + sealed, err := s.sealChannelSecrets(customerID, channels.Secrets{ Token: strings.TrimSpace(value(body.Token)), Signing: strings.TrimSpace(value(body.Signing)), Challenge: strings.TrimSpace(value(body.Challenge)), @@ -283,6 +283,16 @@ func channelCredentialsComplaint(kind channels.Kind, body ConnectChannelRequest) return "", true } +// sealChannelSecrets wraps a line's credentials under this deployment's key, bound to the +// customer so ciphertext moved to another app's row does not open. +func (s *Server) sealChannelSecrets(customerID string, secrets channels.Secrets) ([]byte, error) { + raw, err := json.Marshal(secrets) + if err != nil { + return nil, stack.Wrap(err) + } + return s.secrets.SealWithAAD(string(raw), []byte(customerID)) +} + // channelAccountOf renders a line for the wire, with the URL its provider delivers to. That // URL is the point of connecting: it is what is pasted into Meta's or Linq's setup. func (s *Server) channelAccountOf(account store.ChannelAccount) ChannelAccount { diff --git a/acceleration/internal/api/channels_test.go b/acceleration/internal/api/channels_test.go index a187045959..345b222400 100644 --- a/acceleration/internal/api/channels_test.go +++ b/acceleration/internal/api/channels_test.go @@ -106,18 +106,19 @@ func (s *ChannelsSuite) TestTheCredentialsAreSealedInTheDatabase() { s.Positive(stored.SecretsKEKVersion) } -// Catches connect sealing a line bound only to its customer, or to anything but the line it -// stored: what it stored opens as that line's and not in the customer-only form. -func (s *ChannelsSuite) TestTheCredentialsAreSealedBoundToTheLine() { +// Catches connect sealing a line in a form the previous release cannot open, which breaks a +// rollback and the old pods of a rolling deploy: what it stored opens the way that release +// opens a line, bound to the customer only. +func (s *ChannelsSuite) TestTheCredentialsOpenAsThePreviousReleaseOpensThem() { number := s.number() s.connect(number) stored, err := s.store.ChannelAccounts.GetByNumber(context.Background(), s.customerID(), "whatsapp", number) s.Require().NoError(err) - _, err = s.sealer.OpenWithAADVersion(stored.SecretsSealed, []byte(s.customerID()), stored.SecretsKEKVersion) - s.Error(err, "not in the customer-only form") - line, err := channels.Open(s.sealer, stored) + raw, err := s.sealer.OpenWithAADVersion(stored.SecretsSealed, []byte(s.customerID()), stored.SecretsKEKVersion) s.Require().NoError(err) + var line channels.Secrets + s.Require().NoError(json.Unmarshal([]byte(raw), &line)) s.Equal("meta-token", line.Token) } diff --git a/acceleration/internal/api/custom_models.go b/acceleration/internal/api/custom_models.go index b5c265294f..8bb13a1b2b 100644 --- a/acceleration/internal/api/custom_models.go +++ b/acceleration/internal/api/custom_models.go @@ -8,7 +8,6 @@ import ( "time" "github.com/GetStream/Vision-Agents/acceleration/internal/egress" - "github.com/GetStream/Vision-Agents/acceleration/internal/llmrouter" "github.com/GetStream/Vision-Agents/acceleration/internal/options" "github.com/GetStream/Vision-Agents/acceleration/internal/routing" "github.com/GetStream/Vision-Agents/acceleration/internal/store" @@ -76,8 +75,7 @@ func (s *Server) createCustomModel(ctx context.Context, request *createCustomMod return nil, errNoCustomModels } - // The id is set before Insert, since the key is sealed bound to it. - model := store.CustomModel{ID: store.NewID(), CustomerID: customerID} + model := store.CustomModel{CustomerID: customerID} if failure := s.fillCustomModel(ctx, &model, request.Body); failure != nil { return nil, failure } @@ -179,7 +177,7 @@ func (s *Server) fillCustomModel(ctx context.Context, model *store.CustomModel, if s.secrets == nil { return errNoModelKeys } - sealed, err := s.secrets.SealWithAAD(*request.ApiKey, llmrouter.CustomModelKeyAAD(model.CustomerID, model.ID)) + sealed, err := s.secrets.SealWithAAD(*request.ApiKey, []byte(model.CustomerID)) if err != nil { return err } diff --git a/acceleration/internal/api/custom_models_test.go b/acceleration/internal/api/custom_models_test.go index e80c82fa6a..e348e8b48b 100644 --- a/acceleration/internal/api/custom_models_test.go +++ b/acceleration/internal/api/custom_models_test.go @@ -7,8 +7,6 @@ import ( "encoding/json" "net/http" "testing" - - "github.com/GetStream/Vision-Agents/acceleration/internal/llmrouter" ) type CustomModelsSuite struct { @@ -45,9 +43,10 @@ func (s *CustomModelsSuite) TestAModelIsStoredAndReadBackWithoutItsKey() { s.NotContains(string(stored.APIKeySealed), "sk-secret", "the key is sealed at rest") } -// Catches a key sealed bound only to the customer, or to an id the model does not end up with: -// the key a model is created or updated with opens bound to the id it is read back under. -func (s *CustomModelsSuite) TestTheKeyIsSealedBoundToTheModelItIsGivenTo() { +// Catches create or update sealing a key in a form the previous release cannot open, which +// breaks a rollback and the old pods of a rolling deploy: the key a model is created or updated +// with opens the way that release opens one, bound to the customer only. +func (s *CustomModelsSuite) TestTheKeyOpensAsThePreviousReleaseOpensIt() { created := s.createModel(map[string]any{ "name": "bound", "base_url": "https://8.8.8.8/v1", "model": "a", "api_key": "sk-first", }) @@ -58,14 +57,11 @@ func (s *CustomModelsSuite) TestTheKeyIsSealedBoundToTheModelItIsGivenTo() { s.Equal("sk-second", s.storedKey(created.Id)) } -// storedKey opens the stored key of the model id bound to that model, and checks it does not -// open bound to the customer only. +// storedKey opens the stored key of the model id the way the previous release opens it. func (s *CustomModelsSuite) storedKey(id string) string { stored, err := s.store.CustomModels.Get(context.Background(), s.customerID(), id) s.Require().NoError(err) - _, err = s.sealer.OpenWithAADVersion(stored.APIKeySealed, []byte(s.customerID()), stored.KEKVersion) - s.Require().Error(err, "not in the customer-only form") - key, err := s.sealer.OpenWithAADVersion(stored.APIKeySealed, llmrouter.CustomModelKeyAAD(s.customerID(), id), stored.KEKVersion) + key, err := s.sealer.OpenWithAADVersion(stored.APIKeySealed, []byte(s.customerID()), stored.KEKVersion) s.Require().NoError(err) return key } diff --git a/acceleration/internal/api/scheduled_reach_test.go b/acceleration/internal/api/scheduled_reach_test.go index d09249033c..eef7de6644 100644 --- a/acceleration/internal/api/scheduled_reach_test.go +++ b/acceleration/internal/api/scheduled_reach_test.go @@ -74,7 +74,7 @@ func (s *ScheduledTasksSuite) TestAWhatsAppMessageMoreThanADayAfterThePersonWrot func (s *ScheduledTasksSuite) TestAnIMessageWithNoChatToWriteToIsUnreachable() { number := s.lineNumber() - sealed, err := channels.Seal(s.sealer, s.customerID(), "imessage", number, channels.Secrets{Token: "linq-key", Signing: "linq-secret"}) + sealed, err := s.router.sealChannelSecrets(s.customerID(), channels.Secrets{Token: "linq-key", Signing: "linq-secret"}) s.Require().NoError(err) s.Require().NoError(s.store.ChannelAccounts.Upsert(context.Background(), &store.ChannelAccount{ CustomerID: s.customerID(), Kind: "imessage", E164: number, Token: "line-" + s.utils.uuid(), diff --git a/acceleration/internal/api/scheduled_tasks_test.go b/acceleration/internal/api/scheduled_tasks_test.go index da055b10b0..409ff93399 100644 --- a/acceleration/internal/api/scheduled_tasks_test.go +++ b/acceleration/internal/api/scheduled_tasks_test.go @@ -4110,7 +4110,7 @@ func (s *RouterSuite) seedSMSLine(number string) { CustomerID: s.customerID(), E164: number, Vendor: "telnyx", Capabilities: []string{"sms"}, })) - sealed, err := channels.Seal(s.sealer, s.customerID(), "sms", number, channels.Secrets{ + sealed, err := s.router.sealChannelSecrets(s.customerID(), channels.Secrets{ Token: "telnyx-key", Signing: "a-public-key", }) s.Require().NoError(err) diff --git a/acceleration/internal/api/telephony_billing_test.go b/acceleration/internal/api/telephony_billing_test.go index 39c550be2e..0842086119 100644 --- a/acceleration/internal/api/telephony_billing_test.go +++ b/acceleration/internal/api/telephony_billing_test.go @@ -642,7 +642,7 @@ func (s *telephonyBilling) smsLine() string { s.Require().NoError(s.store.PhoneNumbers.Insert(ctx, &store.PhoneNumber{ CustomerID: s.customerID(), E164: number, Vendor: "telnyx", Country: "US", Capabilities: []string{"sms"}, })) - sealed, err := channels.Seal(s.sealer, s.customerID(), "sms", number, channels.Secrets{Token: "telnyx-key", Signing: s.public}) + sealed, err := s.router.sealChannelSecrets(s.customerID(), channels.Secrets{Token: "telnyx-key", Signing: s.public}) s.Require().NoError(err) s.Require().NoError(s.store.ChannelAccounts.Upsert(ctx, &store.ChannelAccount{ CustomerID: s.customerID(), Kind: "sms", E164: number, Token: "line-" + s.utils.uuid(), diff --git a/acceleration/internal/auth/secret.go b/acceleration/internal/auth/secret.go index ce21a0ea25..f92e35eb27 100644 --- a/acceleration/internal/auth/secret.go +++ b/acceleration/internal/auth/secret.go @@ -147,26 +147,26 @@ func (s *Sealer) OpenWithAADVersion(sealed, additional []byte, version int) (str } // legacyOpens counts the records that opened only under the additional data they had before they were bound to -// their row. Their readers seal each one again bound to its row, so the count falls to zero as those records are -// read, and OpenWithLegacyAAD can go once it stays there. record is a fixed name per kind of record. +// their row. Records are still sealed that way; once they are sealed bound to their row and the count stays at +// zero, OpenWithLegacyAAD can go. record is a fixed name per kind of record. var legacyOpens = promauto.NewCounterVec(prometheus.CounterOpts{ Namespace: "router", Name: "sealed_legacy_opens_total", Help: "Sealed records that opened only under the additional data they had before they were bound to their row, by kind of record", }, []string{"record"}) -// OpenWithLegacyAAD is OpenWithAADVersion for a record that may still be sealed with legacy, the additional data -// it had before it was bound to its row. wasLegacy says it was, counted under record, so the caller can seal it -// again with additional. A record that opens under neither fails with the error of additional. -func (s *Sealer) OpenWithLegacyAAD(sealed, additional, legacy []byte, version int, record string) (plain string, wasLegacy bool, err error) { - plain, err = s.OpenWithAADVersion(sealed, additional, version) +// OpenWithLegacyAAD is OpenWithAADVersion for a record that may be sealed with additional, the additional data +// that binds it to its row, or with legacy, the additional data it had before. A record that opens only under +// legacy is counted under record. A record that opens under neither fails with the error of additional. +func (s *Sealer) OpenWithLegacyAAD(sealed, additional, legacy []byte, version int, record string) (string, error) { + plain, err := s.OpenWithAADVersion(sealed, additional, version) if err == nil { - return plain, false, nil + return plain, nil } plain, legacyErr := s.OpenWithAADVersion(sealed, legacy, version) if legacyErr != nil { - return "", false, err + return "", err } legacyOpens.WithLabelValues(record).Inc() - return plain, true, nil + return plain, nil } diff --git a/acceleration/internal/auth/secret_test.go b/acceleration/internal/auth/secret_test.go index 81dbbc8b71..25dfb89942 100644 --- a/acceleration/internal/auth/secret_test.go +++ b/acceleration/internal/auth/secret_test.go @@ -64,31 +64,29 @@ func (s *KeyringSuite) TestAWrongAADFailsToOpen() { s.Error(err, "a secret bound to a record does not open without it") } -func (s *KeyringSuite) TestARecordSealedBoundToItsRowOpensAsNotLegacy() { +func (s *KeyringSuite) TestARecordSealedBoundToItsRowOpensAndIsNotCounted() { sealer, err := NewSealer("a passphrase") s.Require().NoError(err) sealed, err := sealer.SealWithAAD("line secret", s.record) s.Require().NoError(err) before := testutil.ToFloat64(legacyOpens.WithLabelValues("bound-record")) - opened, legacy, err := sealer.OpenWithLegacyAAD(sealed, s.record, []byte("tenant"), 1, "bound-record") + opened, err := sealer.OpenWithLegacyAAD(sealed, s.record, []byte("tenant"), 1, "bound-record") s.Require().NoError(err) s.Equal("line secret", opened) - s.False(legacy) s.InDelta(before, testutil.ToFloat64(legacyOpens.WithLabelValues("bound-record")), 0) } -func (s *KeyringSuite) TestARecordSealedBoundOnlyToItsCustomerOpensAsLegacyAndIsCounted() { +func (s *KeyringSuite) TestARecordSealedBoundOnlyToItsCustomerOpensAndIsCounted() { sealer, err := NewSealer("a passphrase") s.Require().NoError(err) sealed, err := sealer.SealWithAAD("line secret", []byte("tenant")) s.Require().NoError(err) before := testutil.ToFloat64(legacyOpens.WithLabelValues("legacy-record")) - opened, legacy, err := sealer.OpenWithLegacyAAD(sealed, s.record, []byte("tenant"), 1, "legacy-record") + opened, err := sealer.OpenWithLegacyAAD(sealed, s.record, []byte("tenant"), 1, "legacy-record") s.Require().NoError(err) s.Equal("line secret", opened) - s.True(legacy) s.InDelta(before+1, testutil.ToFloat64(legacyOpens.WithLabelValues("legacy-record")), 0) } @@ -98,10 +96,9 @@ func (s *KeyringSuite) TestARecordOpeningUnderNeitherFailsWithTheErrorOfTheCurre sealed, err := sealer.SealWithAAD("line secret", []byte("tenant/another-row")) s.Require().NoError(err) - opened, legacy, err := sealer.OpenWithLegacyAAD(sealed, s.record, []byte("tenant"), 1, "moved-record") + opened, err := sealer.OpenWithLegacyAAD(sealed, s.record, []byte("tenant"), 1, "moved-record") s.ErrorContains(err, "auth: open secret") s.Empty(opened) - s.False(legacy) s.InDelta(0, testutil.ToFloat64(legacyOpens.WithLabelValues("moved-record")), 0) } @@ -113,11 +110,10 @@ func (s *KeyringSuite) TestALegacyRecordSealedUnderAnOlderKeyOpensWithItsStoredV rotated, err := NewSealerWithKeyring(2, map[int]string{1: "old-key", 2: "new-key"}) s.Require().NoError(err) - opened, legacy, err := rotated.OpenWithLegacyAAD(sealed, s.record, []byte("tenant"), 1, "rotated-record") + opened, err := rotated.OpenWithLegacyAAD(sealed, s.record, []byte("tenant"), 1, "rotated-record") s.Require().NoError(err) s.Equal("line secret", opened) - s.True(legacy) - _, _, err = rotated.OpenWithLegacyAAD(sealed, s.record, []byte("tenant"), 2, "rotated-record") + _, err = rotated.OpenWithLegacyAAD(sealed, s.record, []byte("tenant"), 2, "rotated-record") s.Error(err, "the stored version, not the current one, opens it") } diff --git a/acceleration/internal/channels/secrets_integration_test.go b/acceleration/internal/channels/secrets_integration_test.go index 0ccd5c5a76..df274a6653 100644 --- a/acceleration/internal/channels/secrets_integration_test.go +++ b/acceleration/internal/channels/secrets_integration_test.go @@ -4,6 +4,7 @@ package channels import ( "context" + "encoding/json" "log/slog" "os" "testing" @@ -16,8 +17,8 @@ import ( "github.com/GetStream/Vision-Agents/acceleration/internal/testenv" ) -// LineSecretsSuite is how a line's sealed credentials are read back: bound to the line, and -// still readable from a line sealed before they were, which is then sealed again bound to it. +// LineSecretsSuite is how a line's sealed credentials are read back: bound to its customer, as +// lines are sealed, or bound to the line, as a later release seals them. type LineSecretsSuite struct { suite.Suite ctx context.Context @@ -68,8 +69,7 @@ func (s *LineSecretsSuite) connected(e164 string, sealed []byte, version int) st return account } -// legacy is a line's credentials sealed the way lines were before they were bound to the -// line: bound to the customer only. +// legacy is a line's credentials sealed the way connect seals them: bound to the customer only. func (s *LineSecretsSuite) legacy(sealer *auth.Sealer) []byte { sealed, err := sealer.SealWithAAD(`{"token":"telnyx-key","signing":"a-public-key"}`, []byte(s.customerID)) s.Require().NoError(err) @@ -82,17 +82,25 @@ func (s *LineSecretsSuite) stored(account store.ChannelAccount) store.ChannelAcc return held } +// bound is a line's credentials sealed bound to the line of customerID, kind and e164, as the +// release after this one seals them. +func (s *LineSecretsSuite) bound(customerID string, kind Kind, e164 string, credentials Secrets) []byte { + raw, err := json.Marshal(credentials) + s.Require().NoError(err) + sealed, err := s.sealer.SealWithAAD(string(raw), secretsAAD(customerID, string(kind), e164)) + s.Require().NoError(err) + return sealed +} + // Catches the line's own AAD naming only the customer, or a fallback that opens any blob of // the customer's: credentials sealed for one line, put in another line's row, do not open. func (s *LineSecretsSuite) TestCredentialsMovedFromAnotherLineDoNotOpen() { - sealed, err := Seal(s.sealer, s.customerID, string(SMS), s.number(), Secrets{Token: "telnyx-key"}) - s.Require().NoError(err) + sealed := s.bound(s.customerID, SMS, s.number(), Secrets{Token: "telnyx-key"}) second := s.connected(s.number(), sealed, s.sealer.CurrentVersion()) - _, _, err = s.service.line(s.ctx, second.Token) + _, _, err := s.service.line(s.ctx, second.Token) s.ErrorContains(err, "cannot be opened") - s.Equal(sealed, s.stored(second).SecretsSealed, "nothing was sealed again from a blob that did not open") } // Catches the kind or the customer missing from the line's AAD: the same number on another @@ -101,55 +109,46 @@ func (s *LineSecretsSuite) TestCredentialsSealedForTheSameNumberOnAnotherChannel number := s.number() line := store.ChannelAccount{CustomerID: s.customerID, Kind: string(SMS), E164: number, SecretsKEKVersion: s.sealer.CurrentVersion()} - var err error - line.SecretsSealed, err = Seal(s.sealer, s.customerID, string(WhatsApp), number, Secrets{Token: "meta-token"}) - s.Require().NoError(err) - _, _, err = unseal(s.sealer, line) + line.SecretsSealed = s.bound(s.customerID, WhatsApp, number, Secrets{Token: "meta-token"}) + _, err := Open(s.sealer, line) s.Error(err, "a WhatsApp line's credentials on the SMS line of the same number") - line.SecretsSealed, err = Seal(s.sealer, "another-app", string(SMS), number, Secrets{Token: "telnyx-key"}) - s.Require().NoError(err) - _, _, err = unseal(s.sealer, line) + line.SecretsSealed = s.bound("another-app", SMS, number, Secrets{Token: "telnyx-key"}) + _, err = Open(s.sealer, line) s.Error(err, "another app's line of the same number") } -// Catches a line sealed bound to the line not opening, or being sealed again on every read. -func (s *LineSecretsSuite) TestALineSealedBoundToItselfOpensAndIsLeftAsItIs() { +// Catches a line the next release seals bound to itself not opening here, which would make +// that release impossible to roll back. +func (s *LineSecretsSuite) TestALineSealedBoundToItselfOpens() { number := s.number() - sealed, err := Seal(s.sealer, s.customerID, string(SMS), number, Secrets{Token: "telnyx-key"}) - s.Require().NoError(err) - account := s.connected(number, sealed, s.sealer.CurrentVersion()) + account := s.connected(number, s.bound(s.customerID, SMS, number, Secrets{Token: "telnyx-key"}), + s.sealer.CurrentVersion()) line, _, err := s.service.line(s.ctx, account.Token) s.Require().NoError(err) s.Equal("telnyx-key", line.Token) - s.Equal(sealed, s.stored(account).SecretsSealed) } -// Catches a line connected before the binding going dark, or staying in the old form: it -// opens, and the row then holds its credentials bound to the line and nothing else. -func (s *LineSecretsSuite) TestALineSealedBoundOnlyToItsCustomerOpensAndIsSealedAgainBoundToTheLine() { - account := s.connected(s.number(), s.legacy(s.sealer), s.sealer.CurrentVersion()) +// Catches a line sealed bound only to its customer, as every line is, going dark or being +// written back on a read. +func (s *LineSecretsSuite) TestALineSealedBoundOnlyToItsCustomerOpensIsLeftAsItIs() { + sealed := s.legacy(s.sealer) + account := s.connected(s.number(), sealed, s.sealer.CurrentVersion()) line, _, err := s.service.line(s.ctx, account.Token) s.Require().NoError(err) s.Equal("telnyx-key", line.Token) s.Equal("a-public-key", line.Signing) - held := s.stored(account) - _, err = s.sealer.OpenWithAADVersion(held.SecretsSealed, []byte(s.customerID), held.SecretsKEKVersion) - s.Error(err, "the customer-only form is gone from the row") - opened, legacy, err := unseal(s.sealer, held) - s.Require().NoError(err) - s.False(legacy) - s.Equal(line, opened) + s.Equal(sealed, s.stored(account).SecretsSealed, "a read writes nothing") } -// Catches the old form being opened under the current key rather than the stored one, or -// sealed again under the old one: a rotation and the binding land on the same row. -func (s *LineSecretsSuite) TestALegacyLineUnderAnOlderKeyOpensAndIsSealedAgainUnderTheCurrentOne() { +// Catches a line bound only to its customer being opened under the current key rather than +// the one it was sealed under. +func (s *LineSecretsSuite) TestALegacyLineUnderAnOlderKeyOpensWithItsStoredVersion() { before, err := auth.NewSealer("old-key") s.Require().NoError(err) account := s.connected(s.number(), s.legacy(before), 1) @@ -160,11 +159,7 @@ func (s *LineSecretsSuite) TestALegacyLineUnderAnOlderKeyOpensAndIsSealedAgainUn s.Require().NoError(err) s.Equal("telnyx-key", line.Token) - held := s.stored(account) - s.Equal(2, held.SecretsKEKVersion) - _, legacy, err := unseal(rotated, held) - s.Require().NoError(err) - s.False(legacy) + s.Equal(1, s.stored(account).SecretsKEKVersion) } // Catches the parts of a line's AAD running together: a colon inside one part cannot make two diff --git a/acceleration/internal/channels/sent_integration_test.go b/acceleration/internal/channels/sent_integration_test.go index 7e1d70611b..5102735499 100644 --- a/acceleration/internal/channels/sent_integration_test.go +++ b/acceleration/internal/channels/sent_integration_test.go @@ -91,15 +91,14 @@ func (s *SentSuite) reached() []string { return members } -// noticeLine connects an SMS line sealed the way lines were before they were bound to the -// line, bound to the customer only, with an agent on it that knows user-1 as writer. It returns -// the line's token and the agent's config. -func (s *SentSuite) noticeLine(writer string) (string, store.AgentConfig) { - line, token := "+15550100"+uuid.NewString()[:2], "line-"+uuid.NewString() +// Catches Notify counting its recipient as the line or nobody: the second message a day to the +// same person must not take another of the organization's recipients. +func (s *SentSuite) TestANoticeCountsTheUserItReachedAsReached() { + line, writer := "+15550100"+uuid.NewString()[:2], "+13475550101" sealed, err := s.sealer.SealWithAAD(`{"token":"telnyx-key"}`, []byte(s.owner.CustomerID)) s.Require().NoError(err) s.Require().NoError(s.money.Store.ChannelAccounts.Upsert(s.ctx, &store.ChannelAccount{ - CustomerID: s.owner.CustomerID, Kind: string(SMS), E164: line, Token: token, + CustomerID: s.owner.CustomerID, Kind: string(SMS), E164: line, Token: "line-" + uuid.NewString(), SecretsSealed: sealed, SecretsKEKVersion: s.sealer.CurrentVersion(), })) agentConfig := store.AgentConfig{CustomerID: s.owner.CustomerID, Name: "sent-" + uuid.NewString(), @@ -108,39 +107,14 @@ func (s *SentSuite) noticeLine(writer string) (string, store.AgentConfig) { s.Require().NoError(s.money.Store.ContactMapEntries.Upsert(s.ctx, &store.ContactMapEntry{ CustomerID: s.owner.CustomerID, ConfigID: agentConfig.ID, Kind: string(SMS), Address: writer, UserID: "user-1", })) - return token, agentConfig -} - -// Catches Notify counting its recipient as the line or nobody: the second message a day to the -// same person must not take another of the organization's recipients. -func (s *SentSuite) TestANoticeCountsTheUserItReachedAsReached() { - writer := "+13475550101" - _, agentConfig := s.noticeLine(writer) - err := s.service.Notify(s.ctx, Notice{CustomerID: s.owner.CustomerID, ConfigID: agentConfig.ID, Kind: SMS, + err = s.service.Notify(s.ctx, Notice{CustomerID: s.owner.CustomerID, ConfigID: agentConfig.ID, Kind: SMS, UserID: "user-1", Text: "Your table is ready."}) s.Require().NoError(err) s.Equal([]string{writer}, s.reached(), "the person written to, not the line, the customer or nobody") } -// Catches the outbound path opening a line still bound only to its customer without sealing -// it again bound to the line, which would keep that form alive on lines that only send. -func (s *SentSuite) TestANoticeOnALineSealedBoundOnlyToItsCustomerSealsItAgainBoundToTheLine() { - token, agentConfig := s.noticeLine("+13475550103") - - err := s.service.Notify(s.ctx, Notice{CustomerID: s.owner.CustomerID, ConfigID: agentConfig.ID, Kind: SMS, - UserID: "user-1", Text: "Your table is ready."}) - - s.Require().NoError(err) - s.reached() // deletes the day's counter Notify added to - held, err := s.money.Store.ChannelAccounts.GetByToken(s.ctx, token) - s.Require().NoError(err) - _, legacy, err := unseal(s.sealer, held) - s.Require().NoError(err) - s.False(legacy, "the row holds the credentials bound to the line") -} - // Catches a reply counting nobody, or the line, as the person reached: the reached set is who // the reply went to. func (s *SentSuite) TestAReplyCountsTheSenderItAnsweredAsReached() { diff --git a/acceleration/internal/channels/service.go b/acceleration/internal/channels/service.go index 076d074289..88836c4ef8 100644 --- a/acceleration/internal/channels/service.go +++ b/acceleration/internal/channels/service.go @@ -317,7 +317,7 @@ func (s *Service) reach(ctx context.Context, notice Notice) (Account, string, st if err != nil { return Account{}, "", "", nil, stack.Wrap(err) } - line, err := s.open(ctx, account) + line, err := Open(s.secrets, account) if err != nil { return Account{}, "", "", nil, stack.Wrap(err) } @@ -355,68 +355,33 @@ func (s *Service) reach(ctx context.Context, notice Notice) (Account, string, st return line, thread, identity.Address, provider, nil } -// Seal wraps a line's credentials under the deployment's key, bound to the line (secretsAAD). -func Seal(secrets *auth.Sealer, customerID, kind, e164 string, credentials Secrets) ([]byte, error) { - raw, err := json.Marshal(credentials) - if err != nil { - return nil, stack.Wrap(err) - } - return secrets.SealWithAAD(string(raw), secretsAAD(customerID, kind, e164)) -} - -// Open reads back the credentials a line was stored with. They are bound to the line, so -// ciphertext moved to another line's row does not open. +// Open reads back the credentials a line was stored with. Lines are sealed bound to their +// customer, so ciphertext moved to another app's row does not open. Open tries the line's own +// binding (secretsAAD) first, so a later release can seal lines bound to themselves and still +// be rolled back to this one. Each line that opens only bound to its customer is counted. func Open(secrets *auth.Sealer, stored store.ChannelAccount) (Account, error) { - account, _, err := unseal(secrets, stored) - return account, err -} - -// unseal is Open, saying too whether the line was sealed bound only to its customer, as lines -// were before they were bound to the line. -func unseal(secrets *auth.Sealer, stored store.ChannelAccount) (Account, bool, error) { account := Account{ Kind: Kind(stored.Kind), E164: stored.E164, AccountID: stored.AccountID, } if secrets == nil || len(stored.SecretsSealed) == 0 { - return account, false, stack.Wrap(errors.New("channels: this line has no stored credentials")) + return account, stack.Wrap(errors.New("channels: this line has no stored credentials")) } - raw, legacy, err := secrets.OpenWithLegacyAAD(stored.SecretsSealed, + raw, err := secrets.OpenWithLegacyAAD(stored.SecretsSealed, secretsAAD(stored.CustomerID, stored.Kind, stored.E164), []byte(stored.CustomerID), stored.SecretsKEKVersion, "channel_account") if err != nil { - return account, false, err + return account, err } var opened Secrets if err := json.Unmarshal([]byte(raw), &opened); err != nil { - return account, false, stack.Wrap(err) + return account, stack.Wrap(err) } account.Token = opened.Token account.Signing = opened.Signing account.Challenge = opened.Challenge - return account, legacy, nil -} - -// open is Open for a line the service is about to use. A line still sealed bound only to its -// customer is sealed again bound to the line, so that form is gone from every line in use. -// Failing to write it back costs nothing but another try on the next use, so it is logged and -// the line is used. -func (s *Service) open(ctx context.Context, stored store.ChannelAccount) (Account, error) { - line, legacy, err := unseal(s.secrets, stored) - if err != nil || !legacy { - return line, err - } - 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()) - } - if err != nil { - s.logger.Warn("could not seal a line's credentials again bound to the line", "customer", stored.CustomerID, - "channel", stored.Kind, "error", err) - } - return line, nil + return account, nil } // secretsAAD binds a line's sealed credentials to the line: its customer, channel and number. @@ -438,7 +403,7 @@ func (s *Service) line(ctx context.Context, token string) (Account, store.Channe if err != nil { return Account{}, store.ChannelAccount{}, err } - line, err := s.open(ctx, account) + line, err := Open(s.secrets, account) if err != nil { s.logger.Error("could not open a channel line's credentials", "app_id", account.CustomerID, "channel", account.Kind, "error", err) diff --git a/acceleration/internal/llmrouter/custom.go b/acceleration/internal/llmrouter/custom.go index bcf76b7f2e..cce643a155 100644 --- a/acceleration/internal/llmrouter/custom.go +++ b/acceleration/internal/llmrouter/custom.go @@ -4,7 +4,6 @@ import ( "context" "errors" "fmt" - "log/slog" "net/http" "github.com/GetStream/Vision-Agents/acceleration/internal/auth" @@ -58,39 +57,22 @@ func (m *CustomModels) CustomModel(ctx context.Context, customerID, name string) return routing.ProviderConfig{}, routing.Endpoint{}, stack.Wrap( fmt.Errorf("%w: this deployment has no key to open it with", ErrCustomModelKey)) } - var legacy bool - endpoint.APIKey, legacy, err = m.secrets.OpenWithLegacyAAD(stored.APIKeySealed, - CustomModelKeyAAD(customerID, stored.ID), []byte(customerID), stored.KEKVersion, "custom_model") + endpoint.APIKey, err = m.secrets.OpenWithLegacyAAD(stored.APIKeySealed, + customModelKeyAAD(customerID, stored.ID), []byte(customerID), stored.KEKVersion, "custom_model") if err != nil { return routing.ProviderConfig{}, routing.Endpoint{}, fmt.Errorf("%w: %s: %w", ErrCustomModelKey, routing.CustomProvider+"/"+name, err) } - if legacy { - m.reseal(ctx, stored, endpoint.APIKey) - } } return CustomModelConfig(stored), endpoint, nil } -// reseal seals again bound to the model a key sealed bound only to its customer, as keys were -// before they were bound to their model, so that form is gone from every model in use. Failing -// to write it back costs nothing but another try on the next session, so it is logged and the -// session goes on. -func (m *CustomModels) reseal(ctx context.Context, stored store.CustomModel, key string) { - sealed, err := m.secrets.SealWithAAD(key, CustomModelKeyAAD(stored.CustomerID, stored.ID)) - if err == nil { - err = m.store.CustomModels.Reseal(ctx, stored, sealed, m.secrets.CurrentVersion()) - } - if err != nil { - slog.WarnContext(ctx, "could not seal a custom model's key again bound to the model", - "customer", stored.CustomerID, "model", stored.ID, "error", err) - } -} - -// CustomModelKeyAAD binds a model's sealed api key to its customer and id, so a key copied to +// customModelKeyAAD binds a model's sealed api key to its customer and id, so a key copied to // another model's row does not open. The id, not the name: a model can be renamed. Each part is // length-prefixed, as pgsealed's credentialsAAD is, so no two models give the same bytes. v1 -// changes with the layout. -func CustomModelKeyAAD(customerID, id string) []byte { +// changes with the layout. Keys are still sealed bound to the customer only. CustomModel tries +// this binding first, so a later release can seal keys with it and still be rolled back to this +// one. +func customModelKeyAAD(customerID, id string) []byte { return fmt.Appendf(nil, "accelerate:custom-model-key:v1:%d:%s:%d:%s", len(customerID), customerID, len(id), id) } diff --git a/acceleration/internal/llmrouter/custom_integration_test.go b/acceleration/internal/llmrouter/custom_integration_test.go index 1e1a9df9ae..5b2bc78a00 100644 --- a/acceleration/internal/llmrouter/custom_integration_test.go +++ b/acceleration/internal/llmrouter/custom_integration_test.go @@ -51,11 +51,10 @@ func (s *CustomModelsSuite) SetupTest() { // keep stores a model whose key is sealed by sealer, as the API stores one. func (s *CustomModelsSuite) keep(name string, sealer *auth.Sealer) { - id := store.NewID() - sealed, err := sealer.SealWithAAD("sk-endpoint", CustomModelKeyAAD(s.customerID, id)) + sealed, err := sealer.SealWithAAD("sk-endpoint", []byte(s.customerID)) s.Require().NoError(err) s.Require().NoError(s.store.CustomModels.Insert(s.ctx, &store.CustomModel{ - ID: id, CustomerID: s.customerID, Name: name, BaseURL: "https://models.example/v1", Model: "gemma-4", + CustomerID: s.customerID, Name: name, BaseURL: "https://models.example/v1", Model: "gemma-4", APIKeySealed: sealed, KEKVersion: sealer.CurrentVersion(), })) } @@ -89,9 +88,9 @@ func (s *CustomModelsSuite) TestAKeyTheDeploymentSealedOpens() { s.Equal("sk-endpoint", endpoint.APIKey) } -// CustomModelKeySuite is how a customer's model's sealed key is read back: bound to the model, -// and still readable from a model stored before it was, which is then sealed again bound to it. -// It reads through the name cache a session reads through. +// CustomModelKeySuite is how a customer's model's sealed key is read back: bound to its +// customer, as keys are sealed, or bound to the model, as a later release seals them. It reads +// through the name cache a session reads through. type CustomModelKeySuite struct { suite.Suite ctx context.Context @@ -125,14 +124,28 @@ func (s *CustomModelKeySuite) SetupTest() { s.customerID = "custom-key-" + uuid.NewString() } -// model stores a model of the customer's under id, its key sealed as sealed under version. -func (s *CustomModelKeySuite) model(id string, sealed []byte, version int) store.CustomModel { - model := store.CustomModel{ID: id, CustomerID: s.customerID, Name: "tuned-" + uuid.NewString()[:8], - BaseURL: "https://8.8.8.8/v1", Model: "acme/tuned", APIKeySealed: sealed, KEKVersion: version} +// model stores a model of the customer's whose key is sealedFor its id, under version. +func (s *CustomModelKeySuite) model(sealedFor func(id string) []byte, version int) store.CustomModel { + model := store.CustomModel{CustomerID: s.customerID, Name: "tuned-" + uuid.NewString()[:8], + BaseURL: "https://8.8.8.8/v1", Model: "acme/tuned"} s.Require().NoError(s.store.CustomModels.Insert(s.ctx, &model)) + model.APIKeySealed, model.KEKVersion = sealedFor(model.ID), version + s.Require().NoError(s.store.CustomModels.Update(s.ctx, &model)) return model } +// sealed seals key with sealer under additional, whatever the model's id. +func (s *CustomModelKeySuite) sealed(sealer *auth.Sealer, key string, additional func(id string) []byte) func(string) []byte { + return func(id string) []byte { + sealed, err := sealer.SealWithAAD(key, additional(id)) + s.Require().NoError(err) + return sealed + } +} + +// customerOnly is the AAD keys are sealed with: the customer's id, whatever the model. +func (s *CustomModelKeySuite) customerOnly(string) []byte { return []byte(s.customerID) } + // read is the model as a session reads it, through the name cache. func (s *CustomModelKeySuite) read(model store.CustomModel) store.CustomModel { read, err := s.store.CustomModels.GetByName(s.ctx, s.customerID, model.Name) @@ -143,70 +156,55 @@ func (s *CustomModelKeySuite) read(model store.CustomModel) store.CustomModel { // Catches the key's AAD naming only the customer, or a fallback that opens any of the // customer's blobs: a key sealed for one model, put in another model's row, does not open. func (s *CustomModelKeySuite) TestAKeyMovedFromAnotherModelDoesNotOpen() { - sealed, err := s.sealer.SealWithAAD("sk-other", CustomModelKeyAAD(s.customerID, store.NewID())) - s.Require().NoError(err) - model := s.model(store.NewID(), sealed, s.sealer.CurrentVersion()) + other := store.NewID() + model := s.model(s.sealed(s.sealer, "sk-other", func(string) []byte { return customModelKeyAAD(s.customerID, other) }), + s.sealer.CurrentVersion()) - _, _, err = NewCustomModels(s.store, s.sealer, false).CustomModel(s.ctx, s.customerID, model.Name) + _, _, err := NewCustomModels(s.store, s.sealer, false).CustomModel(s.ctx, s.customerID, model.Name) s.ErrorContains(err, "auth: open secret") - s.Equal(sealed, s.read(model).APIKeySealed, "nothing was sealed again from a key that did not open") } // Catches another customer's model of the same id opening here: the customer is in the AAD. func (s *CustomModelKeySuite) TestAKeySealedForAnotherCustomersModelOfTheSameIdDoesNotOpen() { - id := store.NewID() - sealed, err := s.sealer.SealWithAAD("sk-other", CustomModelKeyAAD("another-app", id)) - s.Require().NoError(err) - model := s.model(id, sealed, s.sealer.CurrentVersion()) + model := s.model(s.sealed(s.sealer, "sk-other", func(id string) []byte { return customModelKeyAAD("another-app", id) }), + s.sealer.CurrentVersion()) - _, _, err = NewCustomModels(s.store, s.sealer, false).CustomModel(s.ctx, s.customerID, model.Name) + _, _, err := NewCustomModels(s.store, s.sealer, false).CustomModel(s.ctx, s.customerID, model.Name) s.ErrorContains(err, "auth: open secret") } -// Catches a key bound to its model not opening, or being sealed again on every session. -func (s *CustomModelKeySuite) TestAKeySealedBoundToItsModelOpensAndIsLeftAsItIs() { - id := store.NewID() - sealed, err := s.sealer.SealWithAAD("sk-own", CustomModelKeyAAD(s.customerID, id)) - s.Require().NoError(err) - model := s.model(id, sealed, s.sealer.CurrentVersion()) +// Catches a key the next release seals bound to its model not opening here, which would make +// that release impossible to roll back. +func (s *CustomModelKeySuite) TestAKeySealedBoundToItsModelOpens() { + model := s.model(s.sealed(s.sealer, "sk-own", func(id string) []byte { return customModelKeyAAD(s.customerID, id) }), + s.sealer.CurrentVersion()) _, endpoint, err := NewCustomModels(s.store, s.sealer, false).CustomModel(s.ctx, s.customerID, model.Name) s.Require().NoError(err) s.Equal("sk-own", endpoint.APIKey) - s.Equal(sealed, s.read(model).APIKeySealed) } -// Catches a model stored before the binding going dark, or staying in the old form, in the -// database or in the name cache a session reads through: it opens, and the next read holds the -// key bound to the model and nothing else. -func (s *CustomModelKeySuite) TestAKeySealedBoundOnlyToItsCustomerOpensAndIsSealedAgainBoundToTheModel() { - sealed, err := s.sealer.SealWithAAD("sk-own", []byte(s.customerID)) - s.Require().NoError(err) - model := s.model(store.NewID(), sealed, s.sealer.CurrentVersion()) +// Catches a key sealed bound only to its customer, as every key is, going dark or being +// written back on a read. +func (s *CustomModelKeySuite) TestAKeySealedBoundOnlyToItsCustomerOpensIsLeftAsItIs() { + model := s.model(s.sealed(s.sealer, "sk-own", s.customerOnly), s.sealer.CurrentVersion()) _, endpoint, err := NewCustomModels(s.store, s.sealer, false).CustomModel(s.ctx, s.customerID, model.Name) s.Require().NoError(err) s.Equal("sk-own", endpoint.APIKey) - read := s.read(model) - _, err = s.sealer.OpenWithAADVersion(read.APIKeySealed, []byte(s.customerID), read.KEKVersion) - s.Error(err, "the customer-only form is gone from what a session reads") - key, err := s.sealer.OpenWithAADVersion(read.APIKeySealed, CustomModelKeyAAD(s.customerID, model.ID), read.KEKVersion) - s.Require().NoError(err) - s.Equal("sk-own", key) + s.Equal(model.APIKeySealed, s.read(model).APIKeySealed, "a read writes nothing") } -// Catches the old form being opened under the current key rather than the stored one, or -// sealed again under the old one: a rotation and the binding land on the same row. -func (s *CustomModelKeySuite) TestALegacyKeyUnderAnOlderKeyOpensAndIsSealedAgainUnderTheCurrentOne() { +// Catches a key bound only to its customer being opened under the current key rather than the +// one it was sealed under. +func (s *CustomModelKeySuite) TestALegacyKeyUnderAnOlderKeyOpensWithItsStoredVersion() { before, err := auth.NewSealer("old-key") s.Require().NoError(err) - sealed, err := before.SealWithAAD("sk-own", []byte(s.customerID)) - s.Require().NoError(err) - model := s.model(store.NewID(), sealed, 1) + model := s.model(s.sealed(before, "sk-own", s.customerOnly), 1) rotated, err := auth.NewSealerWithKeyring(2, map[int]string{1: "old-key", 2: "new-key"}) s.Require().NoError(err) @@ -214,15 +212,11 @@ func (s *CustomModelKeySuite) TestALegacyKeyUnderAnOlderKeyOpensAndIsSealedAgain s.Require().NoError(err) s.Equal("sk-own", endpoint.APIKey) - read := s.read(model) - s.Equal(2, read.KEKVersion) - key, err := rotated.OpenWithAADVersion(read.APIKeySealed, CustomModelKeyAAD(s.customerID, model.ID), 2) - s.Require().NoError(err) - s.Equal("sk-own", key) + s.Equal(1, s.read(model).KEKVersion) } // Catches the parts of a model key's AAD running together: a colon inside one part cannot make // two models give the same bytes. func (s *CustomModelKeySuite) TestTheKeysAADPartsDoNotRunTogether() { - s.NotEqual(CustomModelKeyAAD("app:model", "id"), CustomModelKeyAAD("app", "model:id")) + s.NotEqual(customModelKeyAAD("app:model", "id"), customModelKeyAAD("app", "model:id")) } diff --git a/acceleration/internal/store/channel_account.go b/acceleration/internal/store/channel_account.go index 51eb9b5998..0de2fd3d67 100644 --- a/acceleration/internal/store/channel_account.go +++ b/acceleration/internal/store/channel_account.go @@ -31,7 +31,7 @@ type ChannelAccount struct { // it apart from anybody who guessed the route. Token string `bun:"token,notnull"` // SecretsSealed is the provider's credentials as JSON, sealed under SecretsKEKVersion - // with the customer, the kind and the number as additional data. + // with the customer and the account's id as additional data. SecretsSealed []byte `bun:"secrets_sealed"` SecretsKEKVersion int `bun:"kek_version,notnull"` CreatedAt time.Time `bun:"created_at,notnull"` @@ -143,22 +143,6 @@ func (r *ChannelAccounts) Upsert(ctx context.Context, account *ChannelAccount) e return nil } -// Reseal replaces a line's sealed credentials with the same credentials sealed again. It -// writes only while the line still holds was, the bytes they were read as, so a reconnect -// since then stands, and so does a disconnect, which empties them. -func (r *ChannelAccounts) Reseal(ctx context.Context, id string, was, sealed []byte, version int) error { - _, err := r.store.global.NewUpdate().Model((*ChannelAccount)(nil)). - Set("secrets_sealed = ?", sealed). - Set("kek_version = ?", version). - Where("id = ?", id). - Where("secrets_sealed = ?", was). - Exec(ctx) - if err != nil { - return stack.Wrap(fmt.Errorf("store: reseal channel account: %w", err)) - } - return nil -} - // Delete disconnects a line, so deliveries to it are refused. The credentials go with it: a // line nobody answers on has no use for them. func (r *ChannelAccounts) Delete(ctx context.Context, customerID, kind, e164 string) error { diff --git a/acceleration/internal/store/channel_account_test.go b/acceleration/internal/store/channel_account_test.go index a09e419260..532e9f3523 100644 --- a/acceleration/internal/store/channel_account_test.go +++ b/acceleration/internal/store/channel_account_test.go @@ -133,50 +133,3 @@ func (s *StoreSuite) TestChannelAccountQueryBudgets() { }), "GetByToken") s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.ChannelAccounts.Delete(s.ctx, customerID, "whatsapp", e164)) }), "Delete") } - -// Catches a reseal writing every line that holds the same bytes rather than the one read. -func (s *StoreSuite) TestAResealReplacesTheCredentialsOfTheLineItWasGiven() { - customerID := newID() - account := s.line(customerID, "+1555"+newID()[:7]) - other := s.line(customerID, "+1555"+newID()[:7]) - - s.Require().NoError(s.store.ChannelAccounts.Reseal(s.ctx, account.ID, []byte("sealed"), []byte("resealed"), 2)) - - held, err := s.store.ChannelAccounts.GetByToken(s.ctx, account.Token) - s.Require().NoError(err) - s.Equal([]byte("resealed"), held.SecretsSealed) - s.Equal(2, held.SecretsKEKVersion) - untouched, err := s.store.ChannelAccounts.GetByToken(s.ctx, other.Token) - s.Require().NoError(err) - s.Equal([]byte("sealed"), untouched.SecretsSealed) -} - -// Catches a reseal of what was read clobbering a reconnect that landed in between. -func (s *StoreSuite) TestAResealLeavesALineReconnectedSinceItWasRead() { - customerID := newID() - account := s.line(customerID, "+1555"+newID()[:7]) - s.Require().NoError(s.store.ChannelAccounts.Upsert(s.ctx, &ChannelAccount{ - CustomerID: customerID, Kind: "whatsapp", E164: account.E164, Token: newID(), - SecretsSealed: []byte("reconnected"), SecretsKEKVersion: 1, - })) - - s.Require().NoError(s.store.ChannelAccounts.Reseal(s.ctx, account.ID, []byte("sealed"), []byte("resealed"), 2)) - - held, err := s.store.ChannelAccounts.GetByToken(s.ctx, account.Token) - s.Require().NoError(err) - s.Equal([]byte("reconnected"), held.SecretsSealed) - s.Equal(1, held.SecretsKEKVersion) -} - -// Catches a reseal bringing the credentials of a disconnected line back. -func (s *StoreSuite) TestAResealLeavesADisconnectedLineWithoutCredentials() { - customerID := newID() - account := s.line(customerID, "+1555"+newID()[:7]) - s.Require().NoError(s.store.ChannelAccounts.Delete(s.ctx, customerID, "whatsapp", account.E164)) - - s.Require().NoError(s.store.ChannelAccounts.Reseal(s.ctx, account.ID, []byte("sealed"), []byte("resealed"), 2)) - - var held ChannelAccount - s.Require().NoError(s.store.global.NewSelect().Model(&held).Where("id = ?", account.ID).Scan(s.ctx)) - s.Nil(held.SecretsSealed) -} diff --git a/acceleration/internal/store/custom_model.go b/acceleration/internal/store/custom_model.go index 64aed804d5..283fee27f7 100644 --- a/acceleration/internal/store/custom_model.go +++ b/acceleration/internal/store/custom_model.go @@ -26,7 +26,7 @@ type CustomModel struct { // Model is the id the endpoint serves the weights under. Model string `bun:"model,notnull"` // APIKeySealed is the key the endpoint wants, sealed under KEKVersion and bound to the - // customer and the model's id. Nil for an endpoint that takes none. + // customer. Nil for an endpoint that takes none. APIKeySealed []byte `bun:"api_key_sealed"` KEKVersion int `bun:"kek_version,notnull"` ContextWindow int64 `bun:"context_window,notnull"` @@ -90,15 +90,13 @@ type CustomModels struct { store *Store } -// Insert stores a new model and fills in its timestamps, and its id unless it has one. +// Insert stores a new model and fills in its id and timestamps. func (r *CustomModels) Insert(ctx context.Context, model *CustomModel) error { if err := model.Validate(); err != nil { return stack.Wrap(err) } - if model.ID == "" { - model.ID = newID() - } + model.ID = newID() model.InputModalities = orEmpty(model.InputModalities) now := time.Now().UTC() model.CreatedAt = now @@ -166,37 +164,6 @@ func (r *CustomModels) Update(ctx context.Context, model *CustomModel) error { return nil } -// Reseal replaces a model's sealed key with the same key sealed again. It writes only while -// the model still holds the bytes it was read with, so a key changed since then stands, and -// it forgets the name the row has, so the next read sees the new form even after a rename. -func (r *CustomModels) Reseal(ctx context.Context, model CustomModel, sealed []byte, version int) error { - var name string - err := r.store.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { - err := tx.NewUpdate().Model((*CustomModel)(nil)). - Set("api_key_sealed = ?", sealed). - Set("kek_version = ?", version). - Where("id = ?", model.ID). - Where("customer_id = ?", model.CustomerID). - Where("api_key_sealed = ?", model.APIKeySealed). - Returning("name"). - Scan(ctx, &name) - // No row: the key changed or the model went since it was read, and that write stands. - if errors.Is(err, sql.ErrNoRows) { - return nil - } - return err - }, func() []string { - if name == "" { - return nil - } - return []string{customModelKey(model.CustomerID, name)} - }) - if err != nil { - return stack.Wrap(fmt.Errorf("store: reseal model key: %w", err)) - } - return nil -} - // Delete removes a model. A session that names it afterwards is refused. func (r *CustomModels) Delete(ctx context.Context, customerID, id string) error { if customerID == "" || id == "" { diff --git a/acceleration/internal/store/custom_model_test.go b/acceleration/internal/store/custom_model_test.go index 260971c79c..b9c09ba3e8 100644 --- a/acceleration/internal/store/custom_model_test.go +++ b/acceleration/internal/store/custom_model_test.go @@ -99,65 +99,3 @@ func (s *StoreSuite) TestCustomModelQueryBudgets() { s.Equal(1, s.countRedis(func() { s.Require().NoError(s.store.CustomModels.Delete(s.ctx, "app", other.ID)) }), "forgetting a row is one round trip") } - -func (s *StoreSuite) TestAModelGivenAnIdIsInsertedUnderIt() { - id := NewID() - - model := s.customModel("app", "tuned", func(model *CustomModel) { model.ID = id }) - - s.Equal(id, model.ID) - _, err := s.store.CustomModels.Get(s.ctx, "app", id) - s.Require().NoError(err) -} - -// Catches a reseal that leaves the old key in the name cache, which a session reads through, or -// that writes every model holding the same bytes rather than the one read. -func (s *StoreSuite) TestAResealReplacesTheKeyOfTheModelItWasGivenAndForgetsItsName() { - sealed := func(model *CustomModel) { model.APIKeySealed, model.KEKVersion = []byte("sealed"), 1 } - model := s.customModel("app", "tuned", sealed) - other := s.customModel("app", "other", sealed) - _, err := s.store.CustomModels.GetByName(s.ctx, "app", "tuned") - s.Require().NoError(err) - - s.Require().NoError(s.store.CustomModels.Reseal(s.ctx, model, []byte("resealed"), 2)) - - read, err := s.store.CustomModels.GetByName(s.ctx, "app", "tuned") - s.Require().NoError(err) - s.Equal([]byte("resealed"), read.APIKeySealed) - s.Equal(2, read.KEKVersion) - untouched, err := s.store.CustomModels.Get(s.ctx, "app", other.ID) - s.Require().NoError(err) - s.Equal([]byte("sealed"), untouched.APIKeySealed) -} - -// Catches a reseal of what was read clobbering a key the customer changed in between. -func (s *StoreSuite) TestAResealLeavesAKeyChangedSinceItWasRead() { - model := s.customModel("app", "tuned", func(model *CustomModel) { model.APIKeySealed, model.KEKVersion = []byte("sealed"), 1 }) - changed := model - changed.APIKeySealed = []byte("changed") - s.Require().NoError(s.store.CustomModels.Update(s.ctx, &changed)) - - s.Require().NoError(s.store.CustomModels.Reseal(s.ctx, model, []byte("resealed"), 2)) - - read, err := s.store.CustomModels.Get(s.ctx, "app", model.ID) - s.Require().NoError(err) - s.Equal([]byte("changed"), read.APIKeySealed) - s.Equal(1, read.KEKVersion) -} - -// Catches a reseal forgetting only the name the model was read under: a rename in between -// leaves the old key cached under the new name, which the next session reads. -func (s *StoreSuite) TestAResealForgetsTheNameAModelWasRenamedToSinceItWasRead() { - model := s.customModel("app", "tuned", func(model *CustomModel) { model.APIKeySealed, model.KEKVersion = []byte("sealed"), 1 }) - renamed := model - renamed.Name = "renamed" - s.Require().NoError(s.store.CustomModels.Update(s.ctx, &renamed)) - _, err := s.store.CustomModels.GetByName(s.ctx, "app", "renamed") - s.Require().NoError(err) - - s.Require().NoError(s.store.CustomModels.Reseal(s.ctx, model, []byte("resealed"), 2)) - - read, err := s.store.CustomModels.GetByName(s.ctx, "app", "renamed") - s.Require().NoError(err) - s.Equal([]byte("resealed"), read.APIKeySealed) -} From 062041ed32b6d2a036a919c56b67ab8d1032523c Mon Sep 17 00:00:00 2001 From: Kanat Date: Thu, 26 Nov 2026 15:47:24 -0500 Subject: [PATCH 6/6] AI-3632: pin the record label an old-form open is counted under 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 --- .../channels/secrets_integration_test.go | 29 +++++++++++++++++-- .../llmrouter/custom_integration_test.go | 29 +++++++++++++++++-- 2 files changed, 52 insertions(+), 6 deletions(-) diff --git a/acceleration/internal/channels/secrets_integration_test.go b/acceleration/internal/channels/secrets_integration_test.go index df274a6653..0088a1f68b 100644 --- a/acceleration/internal/channels/secrets_integration_test.go +++ b/acceleration/internal/channels/secrets_integration_test.go @@ -10,6 +10,7 @@ import ( "testing" "github.com/google/uuid" + "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/suite" "github.com/GetStream/Vision-Agents/acceleration/internal/auth" @@ -92,6 +93,25 @@ func (s *LineSecretsSuite) bound(customerID string, kind Kind, e164 string, cred return sealed } +// legacyOpensOf reads router_sealed_legacy_opens_total for one kind of record. +func (s *LineSecretsSuite) legacyOpensOf(record string) float64 { + families, err := prometheus.DefaultGatherer.Gather() + s.Require().NoError(err) + for _, family := range families { + if family.GetName() != "router_sealed_legacy_opens_total" { + continue + } + for _, metric := range family.GetMetric() { + for _, pair := range metric.GetLabel() { + if pair.GetName() == "record" && pair.GetValue() == record { + return metric.GetCounter().GetValue() + } + } + } + } + return 0 +} + // Catches the line's own AAD naming only the customer, or a fallback that opens any blob of // the customer's: credentials sealed for one line, put in another line's row, do not open. func (s *LineSecretsSuite) TestCredentialsMovedFromAnotherLineDoNotOpen() { @@ -132,11 +152,13 @@ func (s *LineSecretsSuite) TestALineSealedBoundToItselfOpens() { s.Equal("telnyx-key", line.Token) } -// Catches a line sealed bound only to its customer, as every line is, going dark or being -// written back on a read. -func (s *LineSecretsSuite) TestALineSealedBoundOnlyToItsCustomerOpensIsLeftAsItIs() { +// Catches a line sealed bound only to its customer, as every line is, going dark, being +// written back on a read, or counted under another kind of record than a channel account: the +// count is what says when that form can stop being opened. +func (s *LineSecretsSuite) TestALineSealedBoundOnlyToItsCustomerOpensIsLeftAsItIsAndIsCounted() { sealed := s.legacy(s.sealer) account := s.connected(s.number(), sealed, s.sealer.CurrentVersion()) + before := s.legacyOpensOf("channel_account") line, _, err := s.service.line(s.ctx, account.Token) @@ -144,6 +166,7 @@ func (s *LineSecretsSuite) TestALineSealedBoundOnlyToItsCustomerOpensIsLeftAsItI s.Equal("telnyx-key", line.Token) s.Equal("a-public-key", line.Signing) s.Equal(sealed, s.stored(account).SecretsSealed, "a read writes nothing") + s.GreaterOrEqual(s.legacyOpensOf("channel_account"), before+1) } // Catches a line bound only to its customer being opened under the current key rather than diff --git a/acceleration/internal/llmrouter/custom_integration_test.go b/acceleration/internal/llmrouter/custom_integration_test.go index 5b2bc78a00..9a970b18ea 100644 --- a/acceleration/internal/llmrouter/custom_integration_test.go +++ b/acceleration/internal/llmrouter/custom_integration_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/google/uuid" + "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/suite" "github.com/GetStream/Vision-Agents/acceleration/internal/auth" @@ -153,6 +154,25 @@ func (s *CustomModelKeySuite) read(model store.CustomModel) store.CustomModel { return read } +// legacyOpensOf reads router_sealed_legacy_opens_total for one kind of record. +func (s *CustomModelKeySuite) legacyOpensOf(record string) float64 { + families, err := prometheus.DefaultGatherer.Gather() + s.Require().NoError(err) + for _, family := range families { + if family.GetName() != "router_sealed_legacy_opens_total" { + continue + } + for _, metric := range family.GetMetric() { + for _, pair := range metric.GetLabel() { + if pair.GetName() == "record" && pair.GetValue() == record { + return metric.GetCounter().GetValue() + } + } + } + } + return 0 +} + // Catches the key's AAD naming only the customer, or a fallback that opens any of the // customer's blobs: a key sealed for one model, put in another model's row, does not open. func (s *CustomModelKeySuite) TestAKeyMovedFromAnotherModelDoesNotOpen() { @@ -187,16 +207,19 @@ func (s *CustomModelKeySuite) TestAKeySealedBoundToItsModelOpens() { s.Equal("sk-own", endpoint.APIKey) } -// Catches a key sealed bound only to its customer, as every key is, going dark or being -// written back on a read. -func (s *CustomModelKeySuite) TestAKeySealedBoundOnlyToItsCustomerOpensIsLeftAsItIs() { +// Catches a key sealed bound only to its customer, as every key is, going dark, being written +// back on a read, or counted under another kind of record than a custom model: the count is what says when that form can +// stop being opened. +func (s *CustomModelKeySuite) TestAKeySealedBoundOnlyToItsCustomerOpensIsLeftAsItIsAndIsCounted() { model := s.model(s.sealed(s.sealer, "sk-own", s.customerOnly), s.sealer.CurrentVersion()) + before := s.legacyOpensOf("custom_model") _, endpoint, err := NewCustomModels(s.store, s.sealer, false).CustomModel(s.ctx, s.customerID, model.Name) s.Require().NoError(err) s.Equal("sk-own", endpoint.APIKey) s.Equal(model.APIKeySealed, s.read(model).APIKeySealed, "a read writes nothing") + s.GreaterOrEqual(s.legacyOpensOf("custom_model"), before+1) } // Catches a key bound only to its customer being opened under the current key rather than the