Repository navigation
[AI-3550] Retry saving a rotated Slack configuration token - #2340
Conversation
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>
kanat
left a comment
There was a problem hiding this comment.
[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") |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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
mainstill lacks it. - The sibling sweep is right:
slackApps.Rotatehas 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() { |
There was a problem hiding this comment.
[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:
-
Add a test for a save that loses its connection:
s.create("Acme")ands.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 waitingINSERT INTO "connector_config_tokens"inpg_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.
-
Here, keep
sent := s.slack.NewConfigToken()and assert that the line holds neither[redacted]norsent.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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") |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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.
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
left a comment
There was a problem hiding this comment.
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;
sentnot 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>
Why
A Slack app configuration token rotates:
Server.configTokencallsRotate, and Slack then treats the refresh token it just got as spent. The new pair was saved with oneUpsert. 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 newconfig_refresh_token. Same pattern as the credential refresh fixed in #2192, found in its sibling sweep (AI-3504).How it works
credentialDetachedTimeout), so under 6.3 s, inside the provider app lock the caller already holds.store.Unwritable(the rule behind the resolver'sretryable). Not reused: the resolver'ssaveAttempts,saveAgainandwaitare 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.Changes
connector_provider_apps.go:saveConfigTokenwith its two constants;configTokenlogs the last failure.RouterSuite.failFirstQueries(fail only the first n queries that name a value, on the suite's existing query-hook seam); four tests inConnectorProviderAppsSuite:TestARotatedConfigTokenWhoseFirstSaveFailsIsSavedByTheNextAndUsedWithoutAnotherRotation,TestARotatedConfigTokenWhoseEverySaveFailsIsLoggedOnceWithoutItsWordsAndAnsweredAsAnyFailure,TestARotatedConfigTokenThatPostgresRefusesIsNotSavedAgain,TestARotatedConfigTokenWhoseSaveLosesItsConnectionIsSavedByTheNextAndUsedWithoutAnotherRotation.TelnyxUnpaidSuite.callOnassigned the package-levelscheduledPhoneWindowandscheduledCallLimit, which [AI-3655] Keep scheduled-delivery timings per router in tests #2293 made constants, so the api package's integration tests did not compile onmain(go vet -tags integration ./internal/apiat 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
TestARotatedConfigTokenWhoseFirstSaveFailsIsSavedByTheNextAndUsedWithoutAnotherRotation: the next call uses the stored pair, no second rotationseam-always-fails...WhoseEverySaveFailsIsLoggedOnce...: 3 attempts, at least 300 ms, 500...ThatPostgresRefusesIsNotSavedAgain(customer id past the index limit, SQLSTATE 54000):attempts=1Unwritable...WhoseSaveLosesItsConnectionIsSavedByTheNext...: the next call uses the stored pair...ThatPostgresRefusesIsNotSavedAgain: the log line holds no sent tokensent...WhoseEverySaveFailsIsLoggedOnce...: the line has exactly time, level, msg, customer, connector, attempts, error...WhoseFirstSaveFailsIs...: the seam fails exactly one save (two saves ran)...WhoseEverySaveFailsIsLogged...: the call ends under 2 sgo test -tags integration ./internal/api -run TestConnectorProviderAppsSuitepasses, and the suites that usefailQueries(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.credentialDetachedTimeoutis 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