Skip to content

[AI-3550] Retry saving a rotated Slack configuration token - #2340

Merged
kanat merged 9 commits into
mainfrom
fix/ai-3550-config-token-save-retry
Nov 25, 2026
Merged

kanat merged 9 commits into
mainfrom
fix/ai-3550-config-token-save-retry

Conversation

@kanat

@kanat kanat commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Why

A Slack app configuration token rotates: Server.configToken calls Rotate, and Slack then treats the refresh token it just got as spent. The new pair was saved with one Upsert. When that one save failed (a dropped connection, a short database outage), the new pair was gone and the stored one was dead, so the customer had to send a new config_refresh_token. Same pattern as the credential refresh fixed in #2192, found in its sibling sweep (AI-3504).

How it works

configToken
├─ Rotate (Slack spends the old refresh token)
└─ saveConfigToken
   ├─ Upsert           ok -> done
   ├─ failed, store.Unwritable? -> stop (a retry fails the same way)
   ├─ wait 100 ms, Upsert again
   ├─ wait 200 ms, Upsert again
   └─ still failing -> one error log (customer, connector, attempts; no token), error returned as before
  • Bound: 3 saves, 300 ms of pauses, each save at most the store's 2 s (credentialDetachedTimeout), so under 6.3 s, inside the provider app lock the caller already holds.
  • The save is an upsert, so one whose answer was lost and landed is safe to repeat.
  • Reused: store.Unwritable (the rule behind the resolver's retryable). Not reused: the resolver's saveAttempts, saveAgain and wait are unexported and tied to its credential store, and the 10DLC service repeats the same numbers; a shared helper would need a package of its own, so the three constants stay local with the reason in the comment.
  • API answers are unchanged: a failed save is the same 500 as before.

Changes

  • connector_provider_apps.go: saveConfigToken with its two constants; configToken logs the last failure.
  • Tests: RouterSuite.failFirstQueries (fail only the first n queries that name a value, on the suite's existing query-hook seam); four tests in ConnectorProviderAppsSuite: TestARotatedConfigTokenWhoseFirstSaveFailsIsSavedByTheNextAndUsedWithoutAnotherRotation, TestARotatedConfigTokenWhoseEverySaveFailsIsLoggedOnceWithoutItsWordsAndAnsweredAsAnyFailure, TestARotatedConfigTokenThatPostgresRefusesIsNotSavedAgain, TestARotatedConfigTokenWhoseSaveLosesItsConnectionIsSavedByTheNextAndUsedWithoutAnotherRotation.
  • Second commit, unrelated to AI-3550: TelnyxUnpaidSuite.callOn assigned the package-level scheduledPhoneWindow and scheduledCallLimit, which [AI-3655] Keep scheduled-delivery timings per router in tests #2293 made constants, so the api package's integration tests did not compile on main (go vet -tags integration ./internal/api at dc88f2f). It sets them on the router as the other scheduled tests do. The same change is [AI-3712] Fix the api integration tests' compile on main #2341 (AI-3712); whichever merges first, the other's copy merges clean.

Validation

Defect Test Mutant that fails it
One failed save loses the pair TestARotatedConfigTokenWhoseFirstSaveFailsIsSavedByTheNextAndUsedWithoutAnotherRotation: the next call uses the stored pair, no second rotation no retry; seam-always-fails
Retries without end, or without waiting ...WhoseEverySaveFailsIsLoggedOnce...: 3 attempts, at least 300 ms, 500 unbounded; 2 attempts; no pause; constant pause
A row Postgres refuses is saved again ...ThatPostgresRefusesIsNotSavedAgain (customer id past the index limit, SQLSTATE 54000): attempts=1 retry on Unwritable
A token or its words in the log, no customer or connector in it the all-fail test reads the one error line token, refresh token, stored refresh in the line; no customer; no connector; warn level; no log
The failure swallowed all-fail test: status 500 return nil
A dropped connection (SQLSTATE 57P01) is not retried ...WhoseSaveLosesItsConnectionIsSavedByTheNext...: the next call uses the stored pair retry only on context deadline; never retry a Postgres-reported error
A refused row's log names the sent token ...ThatPostgresRefusesIsNotSavedAgain: the log line holds no sent token log sent
The every-save-fails log line has extra or missing fields ...WhoseEverySaveFailsIsLoggedOnce...: the line has exactly time, level, msg, customer, connector, attempts, error sealed pair as an extra field
The first-save test passes without a failed save ...WhoseFirstSaveFailsIs...: the seam fails exactly one save (two saves ran) seam off by one
The all-fail call waits on every save ...WhoseEverySaveFailsIsLogged...: the call ends under 2 s 1 s sleep after every save
  • Tests run against real Postgres and the suite's fake Slack; the failing save is the suite's per-suite query hook, no DDL and no store mock.
  • Run: go test -tags integration ./internal/api -run TestConnectorProviderAppsSuite passes, and the suites that use failQueries (authorizations, agent teams, channels, data move, knowledge urls, 10DLC, guests) pass on the tests that call it. The full integration run is CI's.
  • go vet -tags integration ./internal/api, gofmt -l, go build ./... are clean.
  • Not checked: Slack's real behavior on a spent refresh token (the fake takes the strict reading, as its comment says); whether credentialDetachedTimeout is the real worst case on a stalled network. The 3 x 100/200 ms bound is a choice, not measured, as in the resolver.

Review rounds

Round 1: main review NO-GO (no test of a dropped connection; two time and count gaps), security review GO with one log-field test gap. Round 2: all fixed in tests only; delta review GO, 24 mutants, none survived. Round 3: one comment word.

🤖 Generated with Claude Code

kanat and others added 2 commits November 24, 2026 09:05
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 <noreply@anthropic.com>
…idSuite

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 <noreply@anthropic.com>

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[security R1] VERDICT: GO

Reviewed the PR merged onto current main, against the repo's security skill (go.md rules 4, 7 and 9).

  • Route: the provider-app PUT and DELETE stay server-side only. Customer comes from the auth context. The lock and upsert are keyed by (customer, connector). No new route, and the failing-query seam exists only in tests.
  • Token in log or answer: the new error line and the returned error carry only the store's message and stack. A pgdriver error prints severity, message and SQLSTATE, never the row or the query. The API answer is still the generic 500. A probe covered the plain, redacted and refresh-token forms in the answer, the error and every line logged.
  • Bound: one call is at most 3 saves, 2 s each (store timeout), plus 300 ms of pauses. A probe that stalled every save measured one call and 8 parallel calls at about 6.3 s each. Saves are retried only on failures a caller cannot cause; rows Postgres refuses are not retried.
  • Tenancy: a probe retried one customer's save while another customer had a row for the same connector. The other row stayed byte-for-byte the same, and the saved row opens only with its own customer's AAD.
  • Mutations: no retry, retry on a refused row, unbounded retry, and a raw token in the log were all caught. One survived; see S1.1.

One Should fix (test only), inline.

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")

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Should fix] S1.1 The no-token check covers the plain form (xoxe, the sent refresh token) and the redacted form ([redacted]). It misses an attribute that carries the sealed pair. A mutation that adds the sealed blob (hex) to this error line passes the whole suite, so this test does not pin "sealed or plain, never in the log". Fix: also assert the line's attributes are exactly time, level, msg, customer, connector, attempts, error. Parse the keys of the text-handler line, or check that no other key= appears, so any added attribute fails the test.

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 597913b: the every-save-fails test now asserts the line's keys are exactly time, level, msg, customer, connector, attempts, error. Mutant adding the sealed pair in hex as a field now fails it.

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

VERDICT: NO-GO

Reviewed at b884dcd3a merged onto main 6d3cb55b1. CI: CodeQL and GitGuardian pass. go and integration skip on a draft, so CI runs at gh pr ready.

The merged tree passes TestConnectorProviderAppsSuite (23/23) and all 31 tests that call failQueries, across 19 suites, so the seam behaves as before. scheduled_unpaid_test.go is the same as #2341's change.

Verdict: request changes, for R1.1. Its fix is tests only: the code keeps a rotated pair through a real dropped connection. With pg_terminate_backend on the waiting save, the error is SQLSTATE 57P01, not store.Unwritable, and the retry saved the pair (5 of 5 runs). No test pins that.

Checked and sound:

  • The retry rule matches the resolver's retryable, minus the resolver's own sentinels.
  • Each save is bounded to 2 s by the store's own timeout, and pgdriver dials and reads under that deadline. In total that is about 6.3 s, held under the provider app lock. The lock's only holders are this PUT and DELETE, and a waiter waits on its own context.
  • A failed save answers the same 500 as before, on PUT and on DELETE.
  • Nothing changes when connectors are not configured. There is no migration.

Author questions:

  • Keep the compile fix. It matches #2341, and main still lacks it.
  • The sibling sweep is right: slackApps.Rotate has one call site.
  • Naming the connector id in the log is fine.

s.False(strings.Contains(s.logged.String(), given), "nor the refresh token the call sent")
}

func (s *ConnectorProviderAppsSuite) TestARotatedConfigTokenThatPostgresRefusesIsNotSavedAgain() {

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.1 The retry rule !store.Unwritable(err) is tested only with two errors: the seam's deadline error and a 54000. The case this PR is for, a dropped connection, is never tried. Two mutants survive all three tests: retry only on context.DeadlineExceeded, and never retry an error Postgres reported. A third mutant also survives: adding "sent", sent to the error log. This test is the only one that sends a refresh token, and it does not check its log line.

Two fixes, both checked to pass on head and to fail under their mutants:

  1. Add a test for a save that loses its connection:

    • s.create("Acme") and s.expireConfigToken().
    • Open a transaction that runs SELECT 1 FROM connector_config_tokens WHERE customer_id = ? FOR UPDATE.
    • Send the PUT from a goroutine.
    • With Eventually, find the pid of the waiting INSERT INTO "connector_config_tokens" in pg_stat_activity (wait_event_type = 'Lock').
    • Run SELECT pg_terminate_backend(pid), then roll back the transaction.
    • Expect 200 and one rotation, then a second PUT that answers 200 with no new rotation.

    The save fails with SQLSTATE 57P01 and the retry saves the pair. Under either mutant the PUT answers 500.

  2. Here, keep sent := s.slack.NewConfigToken() and assert that the line holds neither [redacted] nor sent.

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 597913b: new TestARotatedConfigTokenWhoseSaveLosesItsConnectionIsSavedByTheNextAndUsedWithoutAnotherRotation (row locked, waiting INSERT's backend terminated, 200 and one rotation, second PUT no new rotation; Eventually with a deadline, passes -count=10). The 54000 test now sends a token and asserts the line holds neither it nor [redacted]. Mutants fail: retry only on DeadlineExceeded, never retry a Postgres-reported error, logging the sent token.

s.expireConfigToken()
rotations := s.slack.ConfigTokenRotations()
logged := len(s.linesWith(configTokenLost))
s.failFirstQueries(configTokenSave, 1)

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.

[Nit] R1.2 This test does not show that a save failed. A seam off by one (f.left.Add(-1) <= 0, which fails no query when n is 1) still passes it. You could assert that the hook's count shows two saves ran. For a follow-up ticket.

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 597913b: the test asserts the seam's count shows two saves ran; the <= 0 off-by-one now fails it.

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")

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.

[Nit] R1.3 Only a lower bound is checked. A 1 s sleep after every save, the successful ones included, passes all three tests. A loose upper bound (for example < 3 s) would pin the total the comment promises. For a follow-up ticket.

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 597913b: upper bound of 2 s (nominal about 0.3 s, a 1 s sleep after each save takes 3.3 s), reason in a comment. That sleep mutant now fails it.

kanat and others added 5 commits November 24, 2026 09:42
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
… log holds no token

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

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

VERDICT: GO

Delta round 2 on 597913b (previous reviewed b884dcd), checked on the head merged with current origin/main (e1cb5e4). The delta touches only connector_provider_apps_test.go; no production code changed.

PRIOR FINDINGS

  • S1.1 (every-save test does not pin the log fields): fixed. A mutant that adds the sealed pair as a log field is killed by the field-list assertion.
  • R1.1 (retry rule untested for a dropped connection; sent not checked): fixed. The new dropped-connection test kills "retry only on DeadlineExceeded" and "never retry a Postgres-reported error"; the refused-row test kills "log sent". The dropped-connection test passes 5/5 and 5/5 with -cpu 1.
  • R1.2 (first-save test does not prove a save failed): fixed. The seam off-by-one (<= 0) is killed by the new left == -1 assertion.
  • R1.3 (all-fail test has only a lower time bound): fixed. The 2 s upper bound kills a 1 s sleep after every save (3.3 s) and a sleep before the retries only (2.3 s). Its reason is stated in the test; the test took 0.33 s in each of 20 runs.

NEW FINDINGS

  • [Nit] acceleration/internal/api/connector_provider_apps_test.go:220 — "2 s is six times that" is 6.7 times 300 ms; "more than six times" is exact. Wording only.

MUTATIONS: 24 checked, 0 survived (the 7 named ones and the 17 from round 1, rerun on this head).

CHECKS: gofmt clean; go vet -tags integration ./internal/api ok; TestConnectorProviderAppsSuite passes on the merged tree. CI: labeler and GitGuardian pass; go and integration are skipped on the draft; the three CodeQL jobs fail on the GetStream org IP allow list (runner refused), not on code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@kanat
kanat marked this pull request as ready for review November 24, 2026 09:19
@kanat
kanat merged commit 8ad53b3 into main Nov 25, 2026
13 checks passed
@kanat
kanat deleted the fix/ai-3550-config-token-save-retry branch November 25, 2026 03:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant