Skip to content
35 changes: 33 additions & 2 deletions acceleration/internal/api/connector_provider_apps.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
148 changes: 148 additions & 0 deletions acceleration/internal/api/connector_provider_apps_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,17 @@ package api
import (
"bytes"
"context"
"crypto/rand"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"regexp"
"strings"
"sync"
"testing"
"time"

"github.com/GetStream/Vision-Agents/acceleration/internal/connectors/core"
"github.com/GetStream/Vision-Agents/acceleration/internal/connectors/fakeprovider"
Expand All @@ -38,6 +41,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) {
Expand Down Expand Up @@ -71,6 +76,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)
Expand Down Expand Up @@ -170,6 +177,124 @@ 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)

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.


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

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

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.

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() {

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.

// 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))
sent := 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() {
s.create("Acme")
rotations := s.slack.ConfigTokenRotations()
Expand Down Expand Up @@ -345,6 +470,29 @@ 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
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 {
Expand Down
20 changes: 16 additions & 4 deletions acceleration/internal/api/router_suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"io"
"log/slog"
"maps"
"math"
"math/rand/v2"
"net"
"net/http"
Expand Down Expand Up @@ -1012,17 +1013,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{})
Expand Down
Loading