From 69cff276924ead5cc9cf6cc363987178f4148fb2 Mon Sep 17 00:00:00 2001 From: Kanat Date: Tue, 24 Nov 2026 09:05:44 +0100 Subject: [PATCH 1/7] [AI-3550] Retry saving a rotated Slack configuration token Slack spends the refresh token a rotation uses, so one failed save of the new pair left the stored one dead and the customer had to send a new config_refresh_token. The save is tried up to three times (100 ms, then 200 ms apart) while its failure is one a retry can fix (store.Unwritable says not), and a last failure is logged once with the customer and connector, never a token. failFirstQueries lets a test fail only the first n queries that name a value. Co-Authored-By: Claude Sonnet 5.5 --- .../internal/api/connector_provider_apps.go | 35 +++++++- .../api/connector_provider_apps_test.go | 87 +++++++++++++++++++ .../internal/api/router_suite_test.go | 20 ++++- 3 files changed, 136 insertions(+), 6 deletions(-) diff --git a/acceleration/internal/api/connector_provider_apps.go b/acceleration/internal/api/connector_provider_apps.go index 5452e45add..4de377274c 100644 --- a/acceleration/internal/api/connector_provider_apps.go +++ b/acceleration/internal/api/connector_provider_apps.go @@ -576,17 +576,48 @@ func (s *Server) configToken(ctx context.Context, customerID, connectorID, sent if err != nil { return "", err } - err = s.store.ConnectorConfigTokens.Upsert(detached, &store.ConnectorConfigToken{ + attempts, err := s.saveConfigToken(detached, &store.ConnectorConfigToken{ CustomerID: customerID, ConnectorID: connectorID, TokensSealed: sealed, KEKVersion: s.connectorSecrets.CurrentVersion(), ExpiresAt: rotated.ExpiresAt, }) - if err != nil { + s.logger.Error("could not save a rotated app configuration token; its customer must send a new config_refresh_token", + "customer", customerID, "connector", connectorID, "attempts", attempts, "error", err) return "", err } return rotated.Token, nil } +// configTokenSaveAttempts and configTokenSaveFirstPause bound how often a rotated configuration +// token is saved: the first save and two more, 100 ms and then 200 ms after the one before, for +// a dropped connection or a failover, the short failures a retry fixes. Slack has spent the +// refresh token the router rotated, so the save is the only way the new pair is kept. Each save +// is bounded by the store (Upsert's credentialDetachedTimeout, 2 s), so the whole is under +// 6.3 s, inside the provider app lock the caller holds. A choice, not measured; a database +// down for longer still loses the pair. The same numbers as the resolver's saveAttempts +// (internal/connectors/resolver) and the 10DLC service's; theirs are unexported, and a shared +// helper would need a package of its own, so only store.Unwritable is shared. +const ( + configTokenSaveAttempts = 3 + configTokenSaveFirstPause = 100 * time.Millisecond +) + +// saveConfigToken saves a rotated configuration token and says how many saves it took. It +// tries again while the failure is one a retry may fix: not a row the store or Postgres refused +// (store.Unwritable). The save is an upsert, so one whose answer was lost and landed is safe to +// repeat. +func (s *Server) saveConfigToken(ctx context.Context, token *store.ConnectorConfigToken) (int, error) { + pause := configTokenSaveFirstPause + attempts, err := 1, s.store.ConnectorConfigTokens.Upsert(ctx, token) + for err != nil && !store.Unwritable(err) && attempts < configTokenSaveAttempts { + // ctx is detached from the caller, so nothing ends this wait early. + time.Sleep(pause) + pause *= 2 + attempts, err = attempts+1, s.store.ConnectorConfigTokens.Upsert(ctx, token) + } + return attempts, err +} + // slackFailure is the answer to a Slack call that failed: its own code when Slack refused, // the error as it is otherwise. func slackFailure(err error) error { diff --git a/acceleration/internal/api/connector_provider_apps_test.go b/acceleration/internal/api/connector_provider_apps_test.go index 0ae03af108..70e2df18c3 100644 --- a/acceleration/internal/api/connector_provider_apps_test.go +++ b/acceleration/internal/api/connector_provider_apps_test.go @@ -5,6 +5,7 @@ package api import ( "bytes" "context" + "crypto/rand" "encoding/json" "fmt" "io" @@ -13,6 +14,7 @@ import ( "strings" "sync" "testing" + "time" "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/core" "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/fakeprovider" @@ -38,6 +40,8 @@ type ConnectorProviderAppsSuite struct { // environment is the router's environment: the operator's own Slack app. environment map[string]string staff *testClient + // logged is what the router logged, for the line a configuration token that was lost leaves. + logged *lockedLog } func TestConnectorProviderAppsSuite(t *testing.T) { @@ -71,6 +75,8 @@ func (s *ConnectorProviderAppsSuite) SetupSuite() { Schemes: map[string]core.Scheme{oauth2code.Name: scheme}, Verifiers: map[string]core.Verifier{verifier.Name(): verifier}, } + s.logged = &lockedLog{} + s.logs = s.logged s.slackApps, err = slackapps.New(slackapps.Config{HTTP: s.slack.Client(), BaseURL: s.slack.URL + fakeprovider.PathSlackAPI}) s.Require().NoError(err) s.operatorApps = ConnectorOperatorApps(getenv) @@ -170,6 +176,76 @@ func (s *ConnectorProviderAppsSuite) TestAnExpiredConfigTokenIsRotatedOnceUnderT s.Equal(rotations+1, s.slack.ConfigTokenRotations()) } +// configTokenSave is what the store's save of a configuration token says in a query, for +// failFirstQueries. +const configTokenSave = `INSERT INTO "connector_config_tokens"` + +// configTokenLost is the message of the error a rotated configuration token that could not be +// saved leaves in the log. +const configTokenLost = "could not save a rotated app configuration token" + +func (s *ConnectorProviderAppsSuite) TestARotatedConfigTokenWhoseFirstSaveFailsIsSavedByTheNextAndUsedWithoutAnotherRotation() { + s.create("Acme") + s.expireConfigToken() + rotations := s.slack.ConfigTokenRotations() + logged := len(s.linesWith(configTokenLost)) + s.failFirstQueries(configTokenSave, 1) + + status, answer := s.serverClient.call(http.MethodPut, providerAppPath("slack_bot"), ConnectorProviderAppRequest{Name: "Acme"}) + + s.Require().Equal(http.StatusOK, status, string(answer)) + s.Equal(rotations+1, s.slack.ConfigTokenRotations()) + status, answer = s.serverClient.call(http.MethodPut, providerAppPath("slack_bot"), ConnectorProviderAppRequest{Name: "Acme"}) + s.Require().Equal(http.StatusOK, status, "the pair the retry saved is the one kept: "+string(answer)) + s.Equal(rotations+1, s.slack.ConfigTokenRotations(), "kept and still good, so not rotated again") + s.Len(s.linesWith(configTokenLost), logged, "a save that landed on its second try is no failure") +} + +func (s *ConnectorProviderAppsSuite) TestARotatedConfigTokenWhoseEverySaveFailsIsLoggedOnceWithoutItsWordsAndAnsweredAsAnyFailure() { + given := s.slack.NewConfigToken() + s.Require().Equal(http.StatusCreated, s.serverClient.do(http.MethodPut, providerAppPath("slack_bot"), + ConnectorProviderAppRequest{Name: "Acme", ConfigRefreshToken: given}, nil)) + s.expireConfigToken() + s.failQueries(configTokenSave) + logged := len(s.linesWith(configTokenLost)) + + started := time.Now() + status, failure := s.serverClient.failure(http.MethodPut, providerAppPath("slack_bot"), ConnectorProviderAppRequest{Name: "Acme"}) + + s.GreaterOrEqual(time.Since(started), 3*configTokenSaveFirstPause, "the saves wait 100 ms and then 200 ms between them") + s.Equal(http.StatusInternalServerError, status) + s.Equal("something went wrong", failure) + lost := s.linesWith(configTokenLost) + s.Require().Len(lost, logged+1, "one error for the pair, not one for each save") + line := lost[len(lost)-1] + s.Contains(line, "level=ERROR") + s.Contains(line, s.customerID()) + s.Contains(line, "slack_bot") + s.Contains(line, "attempts=3") + // The router's logger masks a Slack token as [redacted], so a token the line held would show as that. + s.NotContains(line, "[redacted]", "neither the configuration token nor its refresh token is logged") + s.False(strings.Contains(s.logged.String(), "xoxe"), "nor in the clear") + s.False(strings.Contains(s.logged.String(), given), "nor the refresh token the call sent") +} + +func (s *ConnectorProviderAppsSuite) TestARotatedConfigTokenThatPostgresRefusesIsNotSavedAgain() { + // A customer id too long for the primary key's index is refused by Postgres (SQLSTATE + // 54000): the same row fails the same way. Random, so the index cannot compress it. + var customer strings.Builder + for range 500 { + customer.WriteString(rand.Text()) + } + logged := len(s.linesWith(configTokenLost)) + + _, err := s.router.configToken(context.Background(), customer.String(), "slack_bot", s.slack.NewConfigToken()) + + s.Require().Error(err) + s.True(store.Unwritable(err), "the failure is one a retry cannot fix: %v", err) + lost := s.linesWith(configTokenLost) + s.Require().Len(lost, logged+1) + s.Contains(lost[len(lost)-1], "attempts=1") +} + func (s *ConnectorProviderAppsSuite) TestAConfigTokenStillGoodIsNotRotated() { s.create("Acme") rotations := s.slack.ConfigTokenRotations() @@ -345,6 +421,17 @@ func (s *ConnectorProviderAppsSuite) create(name string) ConnectorProviderApp { return created } +// linesWith is the lines the router logged that hold text. +func (s *ConnectorProviderAppsSuite) linesWith(text string) []string { + var lines []string + for line := range strings.Lines(s.logged.String()) { + if strings.Contains(line, text) { + lines = append(lines, line) + } + } + return lines +} + // withToken is a request naming the app name with the refresh token of a configuration token // the fake Slack's admin just generated. func (s *ConnectorProviderAppsSuite) withToken(name string) ConnectorProviderAppRequest { diff --git a/acceleration/internal/api/router_suite_test.go b/acceleration/internal/api/router_suite_test.go index 450c93acb2..2056619206 100644 --- a/acceleration/internal/api/router_suite_test.go +++ b/acceleration/internal/api/router_suite_test.go @@ -17,6 +17,7 @@ import ( "io" "log/slog" "maps" + "math" "math/rand/v2" "net" "net/http" @@ -1009,17 +1010,28 @@ func (s *RouterSuite) trigger(name, table, op, when, body string) (drop func()) // failQueries makes each query that contains value fail, until the test ends. func (s *RouterSuite) failQueries(value string) { + s.failFirstQueries(value, math.MaxInt64) +} + +// failFirstQueries makes the first n queries that contain value fail, and the ones after them +// pass, until the test ends. +func (s *RouterSuite) failFirstQueries(value string, n int64) { + s.failing.left.Store(n) s.failing.value.Store(&value) s.T().Cleanup(func() { s.failing.value.Store(nil) }) } -// failingQueries makes each query that contains a value fail. The query stops before Postgres -// gets it, with the same error as when the database does not answer in time. -type failingQueries struct{ value atomic.Pointer[string] } +// failingQueries makes each query that contains a value fail, while it has failures left. The +// query stops before Postgres gets it, with the same error as when the database does not answer +// in time. +type failingQueries struct { + value atomic.Pointer[string] + left atomic.Int64 +} func (f *failingQueries) BeforeQuery(ctx context.Context, event *bun.QueryEvent) context.Context { value := f.value.Load() - if value == nil || !strings.Contains(event.Query, *value) { + if value == nil || !strings.Contains(event.Query, *value) || f.left.Add(-1) < 0 { return ctx } expired, cancel := context.WithDeadline(ctx, time.Time{}) From b884dcd3ac41deac8e68aae9dcb7248bd99d98e2 Mon Sep 17 00:00:00 2001 From: Kanat Date: Tue, 24 Nov 2026 09:05:45 +0100 Subject: [PATCH 2/7] test(api): set the scheduled phone window on the router in TelnyxUnpaidSuite The change of #2277 assigned the package-level scheduledPhoneWindow and scheduledCallLimit, which #2293 made constants and moved to the router, so the api integration tests did not compile on main. Co-Authored-By: Claude Sonnet 5.5 --- acceleration/internal/api/scheduled_unpaid_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/acceleration/internal/api/scheduled_unpaid_test.go b/acceleration/internal/api/scheduled_unpaid_test.go index 6c243f4607..4b60c862c7 100644 --- a/acceleration/internal/api/scheduled_unpaid_test.go +++ b/acceleration/internal/api/scheduled_unpaid_test.go @@ -1194,11 +1194,11 @@ func (s *TelnyxUnpaidSuite) ringingOn(model string) ringing { // callOn is ringing, on model, with the call taken on its run and not placed yet. func (s *TelnyxUnpaidSuite) callOn(model string) ringing { - window, longest := scheduledPhoneWindow, scheduledCallLimit + window, longest := s.router.phoneWindow, s.router.callLimit // The limit is longer than the test waits for the call to be let go: a call let go is one // the agent hung up, or the test ended. - scheduledPhoneWindow, scheduledCallLimit = deliveryWait, 2*deliveryWait - s.T().Cleanup(func() { scheduledPhoneWindow, scheduledCallLimit = window, longest }) + s.router.phoneWindow, s.router.callLimit = deliveryWait, 2*deliveryWait + s.T().Cleanup(func() { s.router.phoneWindow, s.router.callLimit = window, longest }) number, writer := "+1555"+digits(s.utils.uuid()), "+1347"+digits(s.utils.uuid()) s.seedSMSLine(number) s.config.Channels.Lines = store.AgentChannels{SMS: &store.ChannelLine{Number: number}} From 92b550587c3471971915259baa51f0d713fb336d Mon Sep 17 00:00:00 2001 From: Kanat Date: Tue, 24 Nov 2026 09:47:04 +0100 Subject: [PATCH 3/7] AI-3550: pin the lost-token log line to its fields Co-Authored-By: Claude Sonnet 5.5 --- .../internal/api/connector_provider_apps_test.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/acceleration/internal/api/connector_provider_apps_test.go b/acceleration/internal/api/connector_provider_apps_test.go index 70e2df18c3..8aa9517fcb 100644 --- a/acceleration/internal/api/connector_provider_apps_test.go +++ b/acceleration/internal/api/connector_provider_apps_test.go @@ -11,6 +11,7 @@ import ( "io" "net/http" "net/url" + "regexp" "strings" "sync" "testing" @@ -222,6 +223,8 @@ func (s *ConnectorProviderAppsSuite) TestARotatedConfigTokenWhoseEverySaveFailsI s.Contains(line, s.customerID()) s.Contains(line, "slack_bot") s.Contains(line, "attempts=3") + s.Equal([]string{"time", "level", "msg", "customer", "connector", "attempts", "error"}, logAttributes(line), + "no field beside these, so none can hold the sealed pair or a token") // The router's logger masks a Slack token as [redacted], so a token the line held would show as that. s.NotContains(line, "[redacted]", "neither the configuration token nor its refresh token is logged") s.False(strings.Contains(s.logged.String(), "xoxe"), "nor in the clear") @@ -421,6 +424,18 @@ func (s *ConnectorProviderAppsSuite) create(name string) ConnectorProviderApp { return created } +// logAttributes is the keys of a text log line, in order; a quoted value is skipped whole, so +// a key= inside a message is not one. +func logAttributes(line string) []string { + var keys []string + for _, found := range logAttribute.FindAllStringSubmatch(line, -1) { + keys = append(keys, found[1]) + } + return keys +} + +var logAttribute = regexp.MustCompile(`(?:^| )([A-Za-z_][\w.]*)=("(?:[^"\\]|\\.)*"|\S*)`) + // linesWith is the lines the router logged that hold text. func (s *ConnectorProviderAppsSuite) linesWith(text string) []string { var lines []string From eaa561ad864edcd08a0286294d983d53d3c84c42 Mon Sep 17 00:00:00 2001 From: Kanat Date: Tue, 24 Nov 2026 09:51:37 +0100 Subject: [PATCH 4/7] AI-3550: prove the first-save test saw a failed save Co-Authored-By: Claude Sonnet 5.5 --- acceleration/internal/api/connector_provider_apps_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/acceleration/internal/api/connector_provider_apps_test.go b/acceleration/internal/api/connector_provider_apps_test.go index 8aa9517fcb..db1d372287 100644 --- a/acceleration/internal/api/connector_provider_apps_test.go +++ b/acceleration/internal/api/connector_provider_apps_test.go @@ -196,6 +196,7 @@ func (s *ConnectorProviderAppsSuite) TestARotatedConfigTokenWhoseFirstSaveFailsI s.Require().Equal(http.StatusOK, status, string(answer)) s.Equal(rotations+1, s.slack.ConfigTokenRotations()) + s.Equal(int64(-1), s.failing.left.Load(), "the seam failed the first save and let the second through: two saves ran") status, answer = s.serverClient.call(http.MethodPut, providerAppPath("slack_bot"), ConnectorProviderAppRequest{Name: "Acme"}) s.Require().Equal(http.StatusOK, status, "the pair the retry saved is the one kept: "+string(answer)) s.Equal(rotations+1, s.slack.ConfigTokenRotations(), "kept and still good, so not rotated again") From 6eb62fc36d2a299b1225b4351ba01c28875929c9 Mon Sep 17 00:00:00 2001 From: Kanat Date: Tue, 24 Nov 2026 09:58:06 +0100 Subject: [PATCH 5/7] AI-3550: bound the time the failing saves take from above Co-Authored-By: Claude Sonnet 5.5 --- acceleration/internal/api/connector_provider_apps_test.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/acceleration/internal/api/connector_provider_apps_test.go b/acceleration/internal/api/connector_provider_apps_test.go index db1d372287..ec7f3bc78d 100644 --- a/acceleration/internal/api/connector_provider_apps_test.go +++ b/acceleration/internal/api/connector_provider_apps_test.go @@ -214,7 +214,12 @@ func (s *ConnectorProviderAppsSuite) TestARotatedConfigTokenWhoseEverySaveFailsI started := time.Now() status, failure := s.serverClient.failure(http.MethodPut, providerAppPath("slack_bot"), ConnectorProviderAppRequest{Name: "Acme"}) - s.GreaterOrEqual(time.Since(started), 3*configTokenSaveFirstPause, "the saves wait 100 ms and then 200 ms between them") + took := time.Since(started) + s.GreaterOrEqual(took, 3*configTokenSaveFirstPause, "the saves wait 100 ms and then 200 ms between them") + // The seam fails each save at once, so the call takes the two pauses (300 ms) and a little + // more. 2 s is six times that, for a CI runner under load, and still under what an added + // 1 s wait after each of the three saves would take (3.3 s), or after the two retries (2.3 s). + s.Less(took, 2*time.Second, "the saves wait for nothing beside the two pauses") s.Equal(http.StatusInternalServerError, status) s.Equal("something went wrong", failure) lost := s.linesWith(configTokenLost) From 597913bf52cea81059adaa554696c6877d23d843 Mon Sep 17 00:00:00 2001 From: Kanat Date: Tue, 24 Nov 2026 09:58:46 +0100 Subject: [PATCH 6/7] AI-3550: test a save whose connection drops, and that the refused-row log holds no token Co-Authored-By: Claude Sonnet 5.5 --- .../api/connector_provider_apps_test.go | 42 ++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/acceleration/internal/api/connector_provider_apps_test.go b/acceleration/internal/api/connector_provider_apps_test.go index ec7f3bc78d..ba9e691b71 100644 --- a/acceleration/internal/api/connector_provider_apps_test.go +++ b/acceleration/internal/api/connector_provider_apps_test.go @@ -245,14 +245,54 @@ func (s *ConnectorProviderAppsSuite) TestARotatedConfigTokenThatPostgresRefusesI customer.WriteString(rand.Text()) } logged := len(s.linesWith(configTokenLost)) + sent := s.slack.NewConfigToken() - _, err := s.router.configToken(context.Background(), customer.String(), "slack_bot", s.slack.NewConfigToken()) + _, err := s.router.configToken(context.Background(), customer.String(), "slack_bot", sent) s.Require().Error(err) s.True(store.Unwritable(err), "the failure is one a retry cannot fix: %v", err) lost := s.linesWith(configTokenLost) s.Require().Len(lost, logged+1) s.Contains(lost[len(lost)-1], "attempts=1") + s.NotContains(lost[len(lost)-1], "[redacted]", "the refresh token the call sent is not logged") + s.NotContains(lost[len(lost)-1], sent) +} + +// A save whose connection Postgres ends (a failover, a dropped connection) is a failure a +// retry fixes: Postgres reports it as an error of its own, which is not a row it refuses. +func (s *ConnectorProviderAppsSuite) TestARotatedConfigTokenWhoseSaveLosesItsConnectionIsSavedByTheNextAndUsedWithoutAnotherRotation() { + s.create("Acme") + s.expireConfigToken() + rotations := s.slack.ConfigTokenRotations() + logged := len(s.linesWith(configTokenLost)) + ctx := context.Background() + db := s.store.GlobalDB() + // Hold the customer's row, so the save waits on it while its backend is ended. + tx, err := db.BeginTx(ctx, nil) + s.Require().NoError(err) + defer func() { _ = tx.Rollback() }() + _, err = tx.ExecContext(ctx, "SELECT 1 FROM connector_config_tokens WHERE customer_id = ? FOR UPDATE", s.customerID()) + s.Require().NoError(err) + + statuses := make(chan int, 1) + go func() { + status, _ := s.put(ConnectorProviderAppRequest{Name: "Acme"}) + statuses <- status + }() + var pid int + s.Require().Eventually(func() bool { + return db.QueryRowContext(ctx, `SELECT pid FROM pg_stat_activity + WHERE datname = current_database() AND wait_event_type = 'Lock' AND query LIKE 'INSERT INTO "connector_config_tokens"%'`).Scan(&pid) == nil + }, 30*time.Second, 5*time.Millisecond, "the save waits for the row") + _, err = db.ExecContext(ctx, "SELECT pg_terminate_backend(?)", pid) + s.Require().NoError(err) + s.Require().NoError(tx.Rollback()) + + s.Equal(http.StatusOK, <-statuses) + s.Equal(rotations+1, s.slack.ConfigTokenRotations()) + s.Equal(http.StatusOK, s.serverClient.do(http.MethodPut, providerAppPath("slack_bot"), ConnectorProviderAppRequest{Name: "Acme"}, nil)) + s.Equal(rotations+1, s.slack.ConfigTokenRotations(), "the pair saved after the dropped connection is the one kept") + s.Len(s.linesWith(configTokenLost), logged, "a save that landed on its second try is no failure") } func (s *ConnectorProviderAppsSuite) TestAConfigTokenStillGoodIsNotRotated() { From 89995ac2dcd16788275860c49ceca61fb841f062 Mon Sep 17 00:00:00 2001 From: Kanat Date: Tue, 24 Nov 2026 10:18:41 +0100 Subject: [PATCH 7/7] AI-3550: say the bound is more than six times the pauses Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/connector_provider_apps_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/acceleration/internal/api/connector_provider_apps_test.go b/acceleration/internal/api/connector_provider_apps_test.go index ba9e691b71..39850393ce 100644 --- a/acceleration/internal/api/connector_provider_apps_test.go +++ b/acceleration/internal/api/connector_provider_apps_test.go @@ -217,7 +217,7 @@ func (s *ConnectorProviderAppsSuite) TestARotatedConfigTokenWhoseEverySaveFailsI took := time.Since(started) s.GreaterOrEqual(took, 3*configTokenSaveFirstPause, "the saves wait 100 ms and then 200 ms between them") // The seam fails each save at once, so the call takes the two pauses (300 ms) and a little - // more. 2 s is six times that, for a CI runner under load, and still under what an added + // more. 2 s is more than six times that, for a CI runner under load, and still under what an added // 1 s wait after each of the three saves would take (3.3 s), or after the two retries (2.3 s). s.Less(took, 2*time.Second, "the saves wait for nothing beside the two pauses") s.Equal(http.StatusInternalServerError, status)