From 541eb32b0138f065fb71ffc630788bb95e931dc0 Mon Sep 17 00:00:00 2001 From: betegon Date: Mon, 20 Jul 2026 17:50:10 +0200 Subject: [PATCH] fix(init): retry transient auth validation once --- src/lib/init/init-service-auth.ts | 43 +++++++++++-- test/lib/init/init-service-auth.test.ts | 83 +++++++++++++++++++++++++ 2 files changed, 122 insertions(+), 4 deletions(-) create mode 100644 test/lib/init/init-service-auth.test.ts diff --git a/src/lib/init/init-service-auth.ts b/src/lib/init/init-service-auth.ts index 751bc1728d..493b10fe18 100644 --- a/src/lib/init/init-service-auth.ts +++ b/src/lib/init/init-service-auth.ts @@ -1,3 +1,4 @@ +import { MastraClientError } from "@mastra/client-js"; import { enrich401Detail } from "../api/infrastructure.js"; import { ApiError, HostScopeError } from "../errors.js"; import { isSaaSTrustOrigin, normalizeOrigin } from "../sentry-urls.js"; @@ -15,6 +16,10 @@ export const WORKFLOW_CREATE_RUN_ENDPOINT = `${WORKFLOW_ENDPOINT}/create-run`; export const WORKFLOW_RESUME_ASYNC_ENDPOINT = `${WORKFLOW_ENDPOINT}/resume-async`; export const WORKFLOW_START_ASYNC_ENDPOINT = `${WORKFLOW_ENDPOINT}/start-async`; const MASTRA_HTTP_401_RE = /HTTP error!\s*status:\s*401\b/i; +const RETRYABLE_AUTH_FAILURE_CODES = new Set([ + "AUTH_UPSTREAM_TIMEOUT", + "AUTH_UPSTREAM_UNAVAILABLE", +]); function classifyInitServiceAuthFailure( err: unknown, @@ -32,14 +37,44 @@ function classifyInitServiceAuthFailure( ); } +function isRetryableInitServiceAuthFailure(err: unknown): boolean { + if ( + !(err instanceof MastraClientError) || + err.status !== 503 || + typeof err.body !== "object" || + err.body === null + ) { + return false; + } + + const body = err.body as Record; + return ( + body.safeToRetry === true && + typeof body.code === "string" && + RETRYABLE_AUTH_FAILURE_CODES.has(body.code) + ); +} + export async function withInitServiceAuthClassification( operation: () => Promise, endpoint: string ): Promise { - try { - return await operation(); - } catch (err) { - throw classifyInitServiceAuthFailure(err, endpoint) ?? err; + let retried = false; + + while (true) { + try { + return await operation(); + } catch (err) { + const classified = classifyInitServiceAuthFailure(err, endpoint); + if (classified) { + throw classified; + } + if (!retried && isRetryableInitServiceAuthFailure(err)) { + retried = true; + continue; + } + throw err; + } } } diff --git a/test/lib/init/init-service-auth.test.ts b/test/lib/init/init-service-auth.test.ts new file mode 100644 index 0000000000..d7af0d44e5 --- /dev/null +++ b/test/lib/init/init-service-auth.test.ts @@ -0,0 +1,83 @@ +import { MastraClientError } from "@mastra/client-js"; +import { describe, expect, test, vi } from "vitest"; +import { ApiError } from "../../../src/lib/errors.js"; +import { withInitServiceAuthClassification } from "../../../src/lib/init/init-service-auth.js"; + +const ENDPOINT = "/api/workflows/sentry-wizard/resume-async"; + +function authFailure( + code: string, + safeToRetry = true, + status = 503 +): MastraClientError { + return new MastraClientError(status, "Service Unavailable", "auth failed", { + code, + safeToRetry, + }); +} + +describe("withInitServiceAuthClassification", () => { + test.each([ + "AUTH_UPSTREAM_TIMEOUT", + "AUTH_UPSTREAM_UNAVAILABLE", + ])("retries %s once", async (code) => { + const failure = authFailure(code); + const operation = vi + .fn<() => Promise>() + .mockRejectedValueOnce(failure) + .mockResolvedValueOnce("ok"); + + await expect( + withInitServiceAuthClassification(operation, ENDPOINT) + ).resolves.toBe("ok"); + expect(operation).toHaveBeenCalledTimes(2); + }); + + test("stops after one retry when the auth service remains unavailable", async () => { + const failure = authFailure("AUTH_UPSTREAM_TIMEOUT"); + const operation = vi.fn<() => Promise>().mockRejectedValue(failure); + + await expect( + withInitServiceAuthClassification(operation, ENDPOINT) + ).rejects.toBe(failure); + expect(operation).toHaveBeenCalledTimes(2); + }); + + test("classifies a 401 returned by the second attempt", async () => { + const operation = vi + .fn<() => Promise>() + .mockRejectedValueOnce(authFailure("AUTH_UPSTREAM_TIMEOUT")) + .mockRejectedValueOnce( + new Error( + 'HTTP error! status: 401 - {"error":"Unauthorized: invalid token"}' + ) + ); + + const error = await withInitServiceAuthClassification( + operation, + ENDPOINT + ).catch((caught) => caught); + + expect(error).toBeInstanceOf(ApiError); + expect(error).toMatchObject({ status: 401, endpoint: ENDPOINT }); + expect(operation).toHaveBeenCalledTimes(2); + }); + + test.each([ + authFailure("AUTH_UPSTREAM_RATE_LIMITED", false), + authFailure("UNKNOWN_CODE"), + authFailure("AUTH_UPSTREAM_TIMEOUT", true, 502), + new TypeError("fetch failed"), + Object.assign(new Error("auth failed"), { + status: 503, + body: { code: "AUTH_UPSTREAM_TIMEOUT", safeToRetry: true }, + }), + ])("does not retry an unauthorized failure contract", async (failure) => { + const operation = vi.fn<() => Promise>().mockRejectedValue(failure); + + await expect( + withInitServiceAuthClassification(operation, ENDPOINT) + ).rejects.toBe(failure); + expect(operation).toHaveBeenCalledTimes(1); + }); +});