diff --git a/acceleration/internal/api/channels_test.go b/acceleration/internal/api/channels_test.go index 2040ad40e7..345b222400 100644 --- a/acceleration/internal/api/channels_test.go +++ b/acceleration/internal/api/channels_test.go @@ -106,6 +106,22 @@ func (s *ChannelsSuite) TestTheCredentialsAreSealedInTheDatabase() { s.Positive(stored.SecretsKEKVersion) } +// 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) + 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) +} + // 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_test.go b/acceleration/internal/api/custom_models_test.go index 6b90ccb9cb..e348e8b48b 100644 --- a/acceleration/internal/api/custom_models_test.go +++ b/acceleration/internal/api/custom_models_test.go @@ -43,6 +43,29 @@ func (s *CustomModelsSuite) TestAModelIsStoredAndReadBackWithoutItsKey() { s.NotContains(string(stored.APIKeySealed), "sk-secret", "the key is sealed at rest") } +// 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", + }) + 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 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) + key, err := s.sealer.OpenWithAADVersion(stored.APIKeySealed, []byte(s.customerID()), 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/auth/secret.go b/acceleration/internal/auth/secret.go index 17c959706f..f92e35eb27 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. 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 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, nil + } + plain, legacyErr := s.OpenWithAADVersion(sealed, legacy, version) + if legacyErr != nil { + return "", err + } + legacyOpens.WithLabelValues(record).Inc() + return plain, nil +} diff --git a/acceleration/internal/auth/secret_test.go b/acceleration/internal/auth/secret_test.go index 1eee8d4940..25dfb89942 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,59 @@ func (s *KeyringSuite) TestAWrongAADFailsToOpen() { s.Error(err, "a secret bound to a record does not open without it") } +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, err := sealer.OpenWithLegacyAAD(sealed, s.record, []byte("tenant"), 1, "bound-record") + s.Require().NoError(err) + s.Equal("line secret", opened) + s.InDelta(before, testutil.ToFloat64(legacyOpens.WithLabelValues("bound-record")), 0) +} + +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, err := sealer.OpenWithLegacyAAD(sealed, s.record, []byte("tenant"), 1, "legacy-record") + s.Require().NoError(err) + s.Equal("line secret", opened) + 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, err := sealer.OpenWithLegacyAAD(sealed, s.record, []byte("tenant"), 1, "moved-record") + s.ErrorContains(err, "auth: open secret") + s.Empty(opened) + 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, err := rotated.OpenWithLegacyAAD(sealed, s.record, []byte("tenant"), 1, "rotated-record") + s.Require().NoError(err) + s.Equal("line secret", opened) + _, 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..0088a1f68b --- /dev/null +++ b/acceleration/internal/channels/secrets_integration_test.go @@ -0,0 +1,193 @@ +//go:build integration + +package channels + +import ( + "context" + "encoding/json" + "log/slog" + "os" + "testing" + + "github.com/google/uuid" + "github.com/prometheus/client_golang/prometheus" + "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 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 + 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 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) + 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 +} + +// 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 +} + +// 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() { + 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) + + s.ErrorContains(err, "cannot be opened") +} + +// 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()} + + 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 = 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 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() + 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) +} + +// 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) + + s.Require().NoError(err) + 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 +// 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) + 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) + 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 +// 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/channels/service.go b/acceleration/internal/channels/service.go index a312358392..88836c4ef8 100644 --- a/acceleration/internal/channels/service.go +++ b/acceleration/internal/channels/service.go @@ -355,8 +355,10 @@ 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. +// 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 := Account{ Kind: Kind(stored.Kind), @@ -366,8 +368,9 @@ func Open(secrets *auth.Sealer, stored store.ChannelAccount) (Account, error) { if secrets == nil || len(stored.SecretsSealed) == 0 { return account, stack.Wrap(errors.New("channels: this line has no stored credentials")) } - raw, err := secrets.OpenWithAADVersion(stored.SecretsSealed, - []byte(stored.CustomerID), stored.SecretsKEKVersion) + 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, err } @@ -381,6 +384,16 @@ func Open(secrets *auth.Sealer, stored store.ChannelAccount) (Account, error) { return account, 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. func (s *Service) line(ctx context.Context, token string) (Account, store.ChannelAccount, error) { account, err := s.store.ChannelAccounts.GetByToken(ctx, token) diff --git a/acceleration/internal/llmrouter/custom.go b/acceleration/internal/llmrouter/custom.go index 5882682598..cce643a155 100644 --- a/acceleration/internal/llmrouter/custom.go +++ b/acceleration/internal/llmrouter/custom.go @@ -57,7 +57,8 @@ 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)) } - endpoint.APIKey, err = m.secrets.OpenWithAADVersion(stored.APIKeySealed, []byte(customerID), stored.KEKVersion) + 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) } @@ -65,6 +66,16 @@ func (m *CustomModels) CustomModel(ctx context.Context, customerID, name string) return CustomModelConfig(stored), endpoint, nil } +// 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. 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) +} + // 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 index 1f4a09eb6b..9a970b18ea 100644 --- a/acceleration/internal/llmrouter/custom_integration_test.go +++ b/acceleration/internal/llmrouter/custom_integration_test.go @@ -8,12 +8,14 @@ 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" "github.com/GetStream/Vision-Agents/acceleration/internal/routing" "github.com/GetStream/Vision-Agents/acceleration/internal/store" - _ "github.com/GetStream/Vision-Agents/acceleration/internal/testenv" + "github.com/GetStream/Vision-Agents/acceleration/internal/testenv" + "github.com/GetStream/Vision-Agents/acceleration/internal/testenv/redisready" ) // CustomModelsSuite resolves the models customers serve themselves from rows in Postgres. @@ -86,3 +88,158 @@ func (s *CustomModelsSuite) TestAKeyTheDeploymentSealedOpens() { s.Require().NoError(err) s.Equal("sk-endpoint", endpoint.APIKey) } + +// 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 + 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 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) + s.Require().NoError(err) + 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() { + 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) + + s.ErrorContains(err, "auth: open secret") +} + +// Catches another customer's model of the same id opening here: the customer is in the AAD. +func (s *CustomModelKeySuite) TestAKeySealedForAnotherCustomersModelOfTheSameIdDoesNotOpen() { + 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) + + s.ErrorContains(err, "auth: open secret") +} + +// 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) +} + +// 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 +// one it was sealed under. +func (s *CustomModelKeySuite) TestALegacyKeyUnderAnOlderKeyOpensWithItsStoredVersion() { + before, err := auth.NewSealer("old-key") + s.Require().NoError(err) + 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) + + _, endpoint, err := NewCustomModels(s.store, rotated, false).CustomModel(s.ctx, s.customerID, model.Name) + + s.Require().NoError(err) + s.Equal("sk-own", endpoint.APIKey) + 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")) +}