Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(gitops): fail fast when the token exchange or access token is rejected (#21691)
boojackcf67192d00fb
diff --git a/action/command/api.go b/action/command/api.goindex 14719ca178..b452ad1981 100644--- a/action/command/api.go+++ b/action/command/api.go@@ -373,6 +373,7 @@ func (ui *unifiedInterceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFunreturn func(ctx context.Context, req connect.AnyRequest) (connect.AnyResponse, error) {var lastErr errorinterval := ui.initialInterval+ reauthenticated := falsefor attempt := 0; attempt < ui.maxAttempts; attempt++ {if attempt > 0 {@@ -412,8 +413,14 @@ func (ui *unifiedInterceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFunlastErr = errcode := connect.CodeOf(err)- // Handle authentication errors+ // Handle authentication errors. A token the server rejects right after+ // a refresh will keep being rejected, such as a static access token, so+ // refresh at most once per request.if code == connect.CodeUnauthenticated && ui.tokenRefresher != nil {+ if reauthenticated {+ return nil, err+ }+ reauthenticated = truerefreshErr := ui.reauthenticateOnce(ctx)if refreshErr != nil {return nil, errors.Wrap(refreshErr, "failed to login")diff --git a/action/command/api_test.go b/action/command/api_test.goindex 95a128b879..f86cba66b5 100644--- a/action/command/api_test.go+++ b/action/command/api_test.go@@ -1,13 +1,16 @@package commandimport (+ "context""io""net/http""net/http/httptest""strings"+ "sync/atomic""testing""time"+ "connectrpc.com/connect""github.com/stretchr/testify/require""github.com/bytebase/bytebase/action/world"@@ -213,6 +216,36 @@ func TestNewClientWithAccessTokenUsesAccessTokenAuth(t *testing.T) {require.Equal(t, 120*time.Second, client.httpClient.Timeout)}+func TestRejectedAccessTokenFailsAfterOneReauthentication(t *testing.T) {+ t.Parallel()++ var requests atomic.Int32+ transport := roundTripFunc(func(req *http.Request) (*http.Response, error) {+ requests.Add(1)+ return &http.Response{+ StatusCode: http.StatusUnauthorized,+ Header: make(http.Header),+ Body: io.NopCloser(strings.NewReader("unauthorized")),+ Request: req,+ }, nil+ })++ opts := defaultClientOptions()+ opts.httpClient = &http.Client{Transport: transport}+ opts.retryConfig = &retryConfig{maxAttempts: 3, initialInterval: time.Millisecond, maxInterval: time.Millisecond}+ client, err := newClient("https://example.com", "null", "", "", opts)+ require.NoError(t, err)+ t.Cleanup(client.close)++ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)+ defer cancel()+ _, err = client.getActuatorInfo(ctx)+ require.Equal(t, connect.CodeUnauthenticated, connect.CodeOf(err))+ require.NoError(t, ctx.Err())+ // The first request carries no token; the refresh loads it, and the retry is rejected.+ require.Equal(t, int32(2), requests.Load())+}+func TestNewClientFromWorldPrefersAccessToken(t *testing.T) {t.Parallel()diff --git a/frontend/src/routes/project/gitopsWorkflowYaml.test.ts b/frontend/src/routes/project/gitopsWorkflowYaml.test.tsindex 5acfbe6edc..095cbd444f 100644--- a/frontend/src/routes/project/gitopsWorkflowYaml.test.ts+++ b/frontend/src/routes/project/gitopsWorkflowYaml.test.ts@@ -51,11 +51,18 @@ describe("generated workflows", () => {["GitHub SQL review", generateGithubSqlReviewYaml, 1],["GitHub release", generateGithubReleaseYaml, 3],["GitLab CI", generateGitlabCiYaml, 4],- ])("%s uses the action image for every job", (_, generate, jobCount) => {- const images = generate(params).match(/image: .+/g);- expect(images).toEqual(+ ])("%s configures every job", (_, generate, jobCount) => {+ const yaml = generate(params);+ expect(yaml.match(/image: .+/g)).toEqual(Array(jobCount).fill("image: bytebase/bytebase-action:cloud"));+ // A failed exchange returns no accessToken, so the job must stop there.+ expect(yaml.match(/jq -r '\.accessToken \/\/ empty'/g)).toHaveLength(+ jobCount+ );+ expect(yaml.match(/if \[ -z "\$ACCESS_TOKEN" \]; then/g)).toHaveLength(+ jobCount+ );});test("GitLab deploy jobs receive the rollout metadata artifact", () => {diff --git a/frontend/src/routes/project/gitopsWorkflowYaml.ts b/frontend/src/routes/project/gitopsWorkflowYaml.tsindex 3ec492d7b7..0dc719f653 100644--- a/frontend/src/routes/project/gitopsWorkflowYaml.ts+++ b/frontend/src/routes/project/gitopsWorkflowYaml.ts@@ -29,11 +29,19 @@ const exchangeTokenStep = (indent: string) =>${indent} id: bytebase-auth${indent} run: |${indent} OIDC_TOKEN=$(curl -s -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \\-${indent} "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=${GENERATED_WORKFLOW_AUDIENCE}" | jq -r '.value')-${indent} ACCESS_TOKEN=$(curl -s -X POST "$BYTEBASE_URL/v1/auth:exchangeToken" \\+${indent} "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=${GENERATED_WORKFLOW_AUDIENCE}" | jq -r '.value // empty' 2>/dev/null || true)+${indent} if [ -z "$OIDC_TOKEN" ]; then+${indent} echo "::error::Failed to get a GitHub OIDC token. Check that the job has the id-token: write permission."+${indent} exit 1+${indent} fi+${indent} RESPONSE=$(curl -s -X POST "$BYTEBASE_URL/v1/auth:exchangeToken" \\${indent} -H "Content-Type: application/json" \\-${indent} -d "{\\"token\\":\\"$OIDC_TOKEN\\",\\"email\\":\\"$BYTEBASE_WORKLOAD_IDENTITY\\"}" \\-${indent} | jq -r '.accessToken')+${indent} -d "{\\"token\\":\\"$OIDC_TOKEN\\",\\"email\\":\\"$BYTEBASE_WORKLOAD_IDENTITY\\"}")+${indent} ACCESS_TOKEN=$(echo "$RESPONSE" | jq -r '.accessToken // empty' 2>/dev/null || true)+${indent} if [ -z "$ACCESS_TOKEN" ]; then+${indent} echo "::error::Failed to exchange the OIDC token for a Bytebase access token: $RESPONSE"+${indent} exit 1+${indent} fi${indent} echo "access-token=$ACCESS_TOKEN" >> $GITHUB_OUTPUT`;const accessTokenFlag =@@ -155,10 +163,14 @@ ${exchangeTokenStep(" ")}}const gitlabExchangeScript = ` - |- ACCESS_TOKEN=$(curl -s -X POST "$BYTEBASE_URL/v1/auth:exchangeToken" \\+ RESPONSE=$(curl -s -X POST "$BYTEBASE_URL/v1/auth:exchangeToken" \\-H "Content-Type: application/json" \\- -d "{\\"token\\":\\"$GITLAB_OIDC_TOKEN\\",\\"email\\":\\"$BYTEBASE_WORKLOAD_IDENTITY\\"}" \\- | jq -r '.accessToken')+ -d "{\\"token\\":\\"$GITLAB_OIDC_TOKEN\\",\\"email\\":\\"$BYTEBASE_WORKLOAD_IDENTITY\\"}")+ ACCESS_TOKEN=$(echo "$RESPONSE" | jq -r '.accessToken // empty' 2>/dev/null || true)+ if [ -z "$ACCESS_TOKEN" ]; then+ echo "Failed to exchange the GitLab OIDC token for a Bytebase access token: $RESPONSE"+ exit 1+ fiexport BYTEBASE_ACCESS_TOKEN=$ACCESS_TOKEN`;export function generateGitlabCiYaml(p: YamlParams): string {