Skip to content
16 changes: 16 additions & 0 deletions acceleration/internal/api/channels_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
23 changes: 23 additions & 0 deletions acceleration/internal/api/custom_models_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"})
Expand Down
28 changes: 28 additions & 0 deletions acceleration/internal/auth/secret.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down Expand Up @@ -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
}
54 changes: 54 additions & 0 deletions acceleration/internal/auth/secret_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"crypto/sha256"
"testing"

"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/stretchr/testify/suite"
)

Expand Down Expand Up @@ -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)
Expand Down
193 changes: 193 additions & 0 deletions acceleration/internal/channels/secrets_integration_test.go
Original file line number Diff line number Diff line change
@@ -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"))
}
21 changes: 17 additions & 4 deletions acceleration/internal/channels/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand All @@ -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")

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

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

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

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

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

if err != nil {
return account, err
}
Expand All @@ -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)
Expand Down
Loading
Loading