From 4ee36161a0dced60c8427f1bc0d3df64bdecde4f Mon Sep 17 00:00:00 2001 From: cxymds Date: Sat, 14 Nov 2026 07:54:10 +0800 Subject: [PATCH] fix: handle expired sessions without clearing newer logins Scope failure callbacks and client readiness to their STS session so delayed requests cannot erase a replacement login. Unify API and S3 authentication errors, detect idle expiration, and preserve explicit OIDC logout. --- app/(auth)/auth/login/page.tsx | 6 +- contexts/api-context.tsx | 42 ++-- contexts/auth-context.tsx | 79 +++++-- contexts/s3-context.tsx | 156 ++----------- hooks/use-local-storage.ts | 47 ++-- lib/api-client.ts | 59 +---- lib/auth-session.ts | 33 +++ lib/s3-error-middleware.ts | 92 ++++++++ tests/hooks/use-oidc-logout.test.ts | 311 ++++++++++++++++++++++++-- tests/lib/api-client.test.ts | 63 ++++++ tests/lib/auth-session.test.ts | 34 +++ tests/lib/form-interaction.test.ts | 36 ++- tests/lib/s3-error-middleware.test.ts | 135 +++++++++++ 13 files changed, 806 insertions(+), 287 deletions(-) create mode 100644 lib/auth-session.ts create mode 100644 lib/s3-error-middleware.ts create mode 100644 tests/lib/auth-session.test.ts create mode 100644 tests/lib/s3-error-middleware.test.ts diff --git a/app/(auth)/auth/login/page.tsx b/app/(auth)/auth/login/page.tsx index 7cca8282..f88d2168 100644 --- a/app/(auth)/auth/login/page.tsx +++ b/app/(auth)/auth/login/page.tsx @@ -38,6 +38,7 @@ function LoginPageContent() { sessionToken: "", }) const loginPendingRef = useRef(false) + const expirationWarningShownRef = useRef(false) const [submitting, setSubmitting] = useState(false) const [oidcProviders, setOidcProviders] = useState([]) // The pending second-factor exchange. The long-term credentials it needs stay @@ -56,11 +57,12 @@ function LoginPageContent() { }, [isAuthenticated, router]) useEffect(() => { - if (searchParams.get("unauthorized") === "true") { + if (!isAuthenticated && searchParams.get("unauthorized") === "true" && !expirationWarningShownRef.current) { + expirationWarningShownRef.current = true message.warning(t("Your session has expired. Please log in again.")) router.replace("/auth/login") } - }, [searchParams, message, t, router]) + }, [isAuthenticated, searchParams, message, t, router]) // Fetch OIDC providers after the first paint path has had a chance to settle. useEffect(() => { diff --git a/contexts/api-context.tsx b/contexts/api-context.tsx index 5a64e3d8..3c3bea03 100644 --- a/contexts/api-context.tsx +++ b/contexts/api-context.tsx @@ -8,6 +8,7 @@ import { ApiErrorHandler } from "@/lib/api-error-handler" import { useAuth } from "@/contexts/auth-context" import { configManager } from "@/lib/config" import { scheduleMicrotask } from "@/lib/schedule-microtask" +import { isSameSession, type SessionCredentials } from "@/lib/auth-session" interface ApiContextValue { api: ApiClient | null @@ -17,8 +18,8 @@ interface ApiContextValue { const ApiContext = createContext({ api: null, isReady: false }) export function ApiProvider({ children }: { children: React.ReactNode }) { - const { credentials, isAuthenticated, logout, getIsLoggingOut } = useAuth() - const [apiClient, setApiClient] = useState(null) + const { credentials, isAuthenticated, expireSession, isCurrentSession, getIsLoggingOut } = useAuth() + const [apiClient, setApiClient] = useState<{ client: ApiClient; credentials: SessionCredentials } | null>(null) const [isReady, setIsReady] = useState(false) const router = useRouter() const pathname = usePathname() @@ -58,19 +59,10 @@ export function ApiProvider({ children }: { children: React.ReactNode }) { const errorHandler = new ApiErrorHandler({ onUnauthorized: async () => { - if (getIsLoggingOut()) return - logout() - router.replace("/auth/login/") + if (expireSession(credentials)) router.replace("/auth/login/?unauthorized=true") }, - onForbidden: async (url) => { - if (getIsLoggingOut()) return - // If the forbidden error happens on the accountinfo endpoint, it means the session is invalid - // or the user has no permissions at all. In this case, we should log out. - if (url?.includes("/is-admin") || url?.includes("/accountinfo") || url?.includes("/version")) { - logout() - router.replace("/auth/login/") - return - } + onForbidden: async () => { + if (getIsLoggingOut() || !isCurrentSession(credentials)) return if (pathnameRef.current === "/403/") return router.replace("/403/") @@ -83,24 +75,22 @@ export function ApiProvider({ children }: { children: React.ReactNode }) { errorHandler, }) - setApiClient(client) + setApiClient({ client, credentials }) setIsReady(true) }) return () => { cancelled = true } - }, [ - isAuthenticated, - credentials?.AccessKeyId, - credentials?.SecretAccessKey, - credentials?.SessionToken, - logout, - getIsLoggingOut, - router, - ]) - - return {children} + }, [isAuthenticated, credentials, expireSession, isCurrentSession, getIsLoggingOut, router]) + + const currentClient = + isAuthenticated && apiClient && isSameSession(credentials, apiClient.credentials) ? apiClient.client : null + return ( + + {children} + + ) } export function useApi() { diff --git a/contexts/auth-context.tsx b/contexts/auth-context.tsx index 01cc2d6c..e8aa2a14 100644 --- a/contexts/auth-context.tsx +++ b/contexts/auth-context.tsx @@ -15,17 +15,11 @@ import type { SiteConfig } from "@/types/config" import { getLoginRoute } from "@/lib/routes" import { configManager } from "@/lib/config" import { useLocalStorage } from "@/hooks/use-local-storage" +import { isSameSession, isValidCredentials, type SessionCredentials as Credentials } from "@/lib/auth-session" import { buildOidcLogoutUrl, type OidcLogoutSession } from "@/lib/oidc" import { isMfaRequiredError } from "@/lib/mfa" import { fetchMfaChallenge } from "@/lib/mfa-challenge" -interface Credentials { - AccessKeyId?: string - SecretAccessKey?: string - SessionToken?: string - Expiration?: string -} - /** * Result of a first login attempt. * @@ -51,6 +45,8 @@ interface AuthContextValue { logoutAndRedirect: () => void logoutWithOidcRedirect: () => Promise getIsLoggingOut: () => boolean + isCurrentSession: (credentials: Credentials) => boolean + expireSession: (credentials: Credentials) => boolean setIsAdmin: (value: boolean) => void getIsAdmin: () => boolean credentials: Credentials | undefined @@ -60,19 +56,6 @@ interface AuthContextValue { const AuthContext = createContext(null) -function isValidCredentials(credentials: Credentials | undefined): boolean { - if ( - !credentials?.AccessKeyId || - !credentials?.SecretAccessKey || - !credentials?.SessionToken || - !credentials?.Expiration - ) { - return false - } - const isExpired = (exp: string) => (exp ? new Date(exp) < new Date() : false) - return !isExpired(credentials.Expiration) -} - /** * Whether these credentials are a static key pair we can sign a probe with. * @@ -94,7 +77,11 @@ export function AuthProvider({ children }: { children: ReactNode }) { // Old API/S3 callbacks must see this flag before React commits the cleared credentials. const loggingOutRef = useRef(false) const getIsLoggingOut = useCallback(() => loggingOutRef.current, []) - const [store, setStore] = useLocalStorage("auth.credentials", undefined) + const [store, setStore, getStoredCredentials] = useLocalStorage( + "auth.credentials", + undefined, + true, + ) const [isAdminStore, setIsAdminStore] = useLocalStorage("auth.isAdmin", undefined) const [oidcSessionStore, setOidcSessionStore] = useLocalStorage( "auth.oidcSession", @@ -103,8 +90,8 @@ export function AuthProvider({ children }: { children: ReactNode }) { const setCredentials = useCallback( (credentials: Credentials) => { - loggingOutRef.current = false setStore(credentials) + loggingOutRef.current = false }, [setStore], ) @@ -235,6 +222,50 @@ export function AuthProvider({ children }: { children: ReactNode }) { setOidcSessionStore(undefined) }, [setStore, setIsAdminStore, setOidcSessionStore]) + const isCurrentSession = useCallback( + (expected: Credentials) => { + return isSameSession(getStoredCredentials(), expected) + }, + [getStoredCredentials], + ) + + const expireSession = useCallback( + (expected: Credentials) => { + if (loggingOutRef.current || !isCurrentSession(expected)) return false + logout() + return true + }, + [isCurrentSession, logout], + ) + + useEffect(() => { + if (!store?.Expiration) return + const expiration = Date.parse(store.Expiration) + let timer: number | undefined + const checkExpiration = () => { + window.clearTimeout(timer) + if (!isCurrentSession(store) || loggingOutRef.current) return + const remaining = expiration - Date.now() + if (!Number.isFinite(remaining) || remaining <= 0) { + expireSession(store) + return + } + // Browsers clamp larger delays to 1 ms; recheck long-lived sessions in bounded steps. + timer = window.setTimeout(checkExpiration, Math.min(remaining, 2 ** 31 - 1)) + } + const handleVisibility = () => { + if (document.visibilityState === "visible") checkExpiration() + } + checkExpiration() + document.addEventListener("visibilitychange", handleVisibility) + window.addEventListener("pageshow", checkExpiration) + return () => { + window.clearTimeout(timer) + document.removeEventListener("visibilitychange", handleVisibility) + window.removeEventListener("pageshow", checkExpiration) + } + }, [store, isCurrentSession, expireSession]) + useEffect(() => { const handlePageShow = (event: PageTransitionEvent) => { if (!event.persisted || !loggingOutRef.current) return @@ -293,6 +324,8 @@ export function AuthProvider({ children }: { children: ReactNode }) { logoutAndRedirect, logoutWithOidcRedirect, getIsLoggingOut, + isCurrentSession, + expireSession, setIsAdmin, getIsAdmin, credentials, @@ -307,6 +340,8 @@ export function AuthProvider({ children }: { children: ReactNode }) { logoutAndRedirect, logoutWithOidcRedirect, getIsLoggingOut, + isCurrentSession, + expireSession, setIsAdmin, getIsAdmin, credentials, diff --git a/contexts/s3-context.tsx b/contexts/s3-context.tsx index ea0fbff0..6cd6df2d 100644 --- a/contexts/s3-context.tsx +++ b/contexts/s3-context.tsx @@ -7,47 +7,10 @@ import { useAuth } from "@/contexts/auth-context" import { addApiPrefixMiddleware } from "@/lib/api-prefix-middleware" import { addDeleteReplicationMiddleware } from "@/lib/bucket-replication-delete" import { configManager } from "@/lib/config" -import { getServiceErrorMessage, getXmlErrorCode, getXmlErrorMessage } from "@/lib/error-handler" +import { addS3ErrorMiddleware } from "@/lib/s3-error-middleware" import { scheduleMicrotask } from "@/lib/schedule-microtask" import type { SiteConfig } from "@/types/config" - -interface S3Response { - response?: { body?: string } - [key: string]: unknown -} - -type StreamCollector = (streamBody: unknown) => Promise - -const readResponseBodyText = async ( - body: unknown, - streamCollector: StreamCollector | undefined, -): Promise => { - if (typeof body === "string") { - return body - } - - if (body instanceof Uint8Array) { - return new TextDecoder("utf-8").decode(body) - } - - if (!body || !streamCollector) { - return null - } - - const bytes = await streamCollector(body) - return new TextDecoder("utf-8").decode(bytes) -} - -const createS3ServiceError = (message: string, statusCode: number, code?: string | null) => { - const error = new Error(message) as Error & { - Code?: string - $metadata?: { httpStatusCode?: number } - } - error.name = code ?? "S3ServiceError" - if (code) error.Code = code - error.$metadata = { httpStatusCode: statusCode } - return error -} +import { isSameSession, type SessionCredentials } from "@/lib/auth-session" interface S3ContextValue { client: S3Client | null @@ -60,8 +23,8 @@ const S3Context = createContext({ }) export function S3Provider({ children }: { children: React.ReactNode }) { - const { credentials, isAuthenticated, logout, getIsLoggingOut } = useAuth() - const [s3Client, setS3Client] = useState(null) + const { credentials, isAuthenticated, expireSession } = useAuth() + const [s3Client, setS3Client] = useState<{ client: S3Client; credentials: SessionCredentials } | null>(null) const [isReady, setIsReady] = useState(false) const router = useRouter() @@ -97,109 +60,26 @@ export function S3Provider({ children }: { children: React.ReactNode }) { addDeleteReplicationMiddleware(client) - /* eslint-disable @typescript-eslint/no-explicit-any -- AWS SDK middleware types are complex */ - client.middlewareStack.addRelativeTo( - ((next: any) => async (args: any) => { - const result = await next(args) - const response = result?.response - const statusCode = response?.statusCode - - if (typeof statusCode === "number" && statusCode >= 300) { - const streamCollector = client.config.streamCollector as StreamCollector | undefined - const bodyText = await readResponseBodyText(response.body, streamCollector) - const errorCode = bodyText ? getXmlErrorCode(bodyText) : null - const errorMessage = bodyText ? (getXmlErrorMessage(bodyText) ?? bodyText.trim()) : null - - if (errorMessage) { - throw createS3ServiceError(errorMessage, statusCode, errorCode) - } - } - - return result - }) as any, - { - name: "normalizeXmlErrorResponse", - relation: "after", - toMiddleware: "deserializerMiddleware", - override: true, - }, - ) - client.middlewareStack.add( - ((next: any) => async (args: any) => { - try { - const response = (await next(args)) as S3Response - - if (response.response?.body && typeof response.response.body === "string") { - const body = response.response.body.trim() - if (body.match(/^<\?xml[^>]*\?><[^>]*><\/[^>]*>$/)) { - const tagName = body.match(/<([^>]*)><\/\1>/)?.[1] - if (tagName) { - const propertyName = tagName.replace(/(?:^|_)([a-z])/g, (_, letter: string) => letter.toUpperCase()) - return { - response: response.response, - [propertyName]: null, - } - } - } - } - - return response - } catch (error: unknown) { - const err = error as { - $metadata?: { httpStatusCode?: number } - Code?: string - name?: string - message?: string - } - if (err?.$metadata?.httpStatusCode === 401) { - if (!getIsLoggingOut()) { - logout() - router.replace("/auth/login/") - } - return { response: { statusCode: 401, headers: {} } } - } - if (err?.$metadata?.httpStatusCode === 403) { - const codeText = (err?.Code || err?.name || "").toLowerCase() - const isUnauthorizedAccess = codeText === "unauthorizedaccess" - const isInvalidAccessKey = codeText === "invalidaccesskeyid" - if (isUnauthorizedAccess || isInvalidAccessKey) { - if (!getIsLoggingOut()) { - logout() - router.replace("/auth/login/") - } - return { response: { statusCode: 401, headers: {} } } - } - } - - const serviceErrorMessage = getServiceErrorMessage(error) - if (serviceErrorMessage && error instanceof Error) { - error.message = serviceErrorMessage - } - throw error - } - }) as any, - { step: "deserialize", name: "handleXmlResponse" }, - ) - /* eslint-enable @typescript-eslint/no-explicit-any */ - - setS3Client(client) + addS3ErrorMiddleware(client, () => { + if (expireSession(credentials)) router.replace("/auth/login/?unauthorized=true") + }) + + setS3Client({ client, credentials }) setIsReady(true) }) return () => { cancelled = true } - }, [ - isAuthenticated, - credentials?.AccessKeyId, - credentials?.SecretAccessKey, - credentials?.SessionToken, - logout, - getIsLoggingOut, - router, - ]) - - return {children} + }, [isAuthenticated, credentials, expireSession, router]) + + const currentClient = + isAuthenticated && s3Client && isSameSession(credentials, s3Client.credentials) ? s3Client.client : null + return ( + + {children} + + ) } export function useS3() { diff --git a/hooks/use-local-storage.ts b/hooks/use-local-storage.ts index 31972d25..29ac855b 100644 --- a/hooks/use-local-storage.ts +++ b/hooks/use-local-storage.ts @@ -1,46 +1,44 @@ "use client" -import { useCallback, useEffect, useState } from "react" +import { useCallback, useEffect, useRef, useState } from "react" -function getStorageValue(key: string, defaultValue: T): T { +function getStorageValue(key: string, defaultValue: T, fallbackValue = defaultValue): T { if (typeof window === "undefined") return defaultValue try { const item = localStorage.getItem(key) if (item === null) return defaultValue return JSON.parse(item) as T } catch { - return defaultValue + return fallbackValue } } function setStorageValue(key: string, value: T) { - if (typeof window === "undefined") return + if (typeof window === "undefined") return false try { if (value === undefined || value === null) { localStorage.removeItem(key) } else { localStorage.setItem(key, JSON.stringify(value)) } + return true } catch { - // ignore + return false } } -export function useLocalStorage(key: string, defaultValue: T) { +export function useLocalStorage(key: string, defaultValue: T, requirePersistence = false) { const [value, setValue] = useState(() => getStorageValue(key, defaultValue)) + const valueRef = useRef(value) + const getStoredValue = useCallback(() => getStorageValue(key, defaultValue, valueRef.current), [key, defaultValue]) useEffect(() => { const handleStorage = (e: StorageEvent) => { - if (e.key === key) { - if (e.newValue === null) { - setValue(defaultValue) - return - } - try { - setValue(JSON.parse(e.newValue) as T) - } catch { - // ignore - } + if (e.key === key || e.key === null) { + // A queued event may describe a session that has already been replaced. + const next = getStorageValue(key, defaultValue) + valueRef.current = next + setValue(next) } } @@ -50,14 +48,17 @@ export function useLocalStorage(key: string, defaultValue: T) { const setStoredValue = useCallback( (newValue: T | ((prev: T) => T)) => { - setValue((prev) => { - const next = typeof newValue === "function" ? (newValue as (prev: T) => T)(prev) : newValue - setStorageValue(key, next) - return next - }) + const next = typeof newValue === "function" ? (newValue as (prev: T) => T)(valueRef.current) : newValue + // Persist before scheduling React work so a later login cannot be erased by a replayed updater. + const persisted = setStorageValue(key, next) + if (!persisted && requirePersistence && next !== undefined && next !== null) { + throw new Error("Unable to save the session in browser storage") + } + valueRef.current = next + setValue(next) }, - [key], + [key, requirePersistence], ) - return [value, setStoredValue] as const + return [value, setStoredValue, getStoredValue] as const } diff --git a/lib/api-client.ts b/lib/api-client.ts index db3bd54d..7596e964 100644 --- a/lib/api-client.ts +++ b/lib/api-client.ts @@ -2,6 +2,7 @@ import { joinURL } from "ufo" import type { IApiErrorHandler } from "@/types/api" import { redactRequestOptionsForLog } from "./api-request-log" import { parseApiErrorDetails } from "./error-handler" +import { isSessionError } from "./auth-session" import { logger } from "./logger" type ApiRequestInit = RequestInit & { body?: BodyInit | null; aws?: Record } @@ -104,58 +105,14 @@ export class ApiClient { logger.log("[request] response:", response) - if (response.status === 401) { - if (this.errorHandler) { - await this.errorHandler.handle401(url) - } - throw await createHttpError(response) - } - if (response.status === 403) { - // If suppress403Redirect is true, throw error instead of triggering global handler - // This allows components to handle permission errors gracefully - if (requestOptions.suppress403Redirect) { - throw await createHttpError(response) - } - - try { - const cloned = response.clone() - let codeText = "" - try { - const data = (await cloned.json()) as Record - let code: string | undefined = (data?.code as string | undefined) || (data?.Code as string | undefined) - if (data && typeof data === "object" && "error" in data) { - const errObj = (data as { error?: unknown }).error - if (errObj && typeof errObj === "object") { - const e = errObj as { code?: unknown } - if (typeof e.code === "string") code = code ?? e.code - } - } - codeText = typeof code === "string" ? code : "" - } catch { - codeText = "" - } - - const normalizedCode = codeText.toLowerCase() - const isUnauthorizedAccess = normalizedCode === "unauthorizedaccess" - const isInvalidAccessKey = normalizedCode === "invalidaccesskeyid" - - if (this.errorHandler) { - if (isUnauthorizedAccess || isInvalidAccessKey) { - await this.errorHandler.handle401(url) - } else { - await this.errorHandler.handle403(url) - } - } - } catch { - if (this.errorHandler) { - await this.errorHandler.handle403(url) - } - } - throw await createHttpError(response) - } - if (!response.ok) { - throw await createHttpError(response) + const error = await createHttpError(response) + if (response.status === 401 || isSessionError(error.code)) { + await this.errorHandler?.handle401(url) + } else if (response.status === 403 && !requestOptions.suppress403Redirect) { + await this.errorHandler?.handle403(url) + } + throw error } if (response.status === 204 || response.headers.get("content-length") === "0" || !response.body) { diff --git a/lib/auth-session.ts b/lib/auth-session.ts new file mode 100644 index 00000000..f8a9f8c1 --- /dev/null +++ b/lib/auth-session.ts @@ -0,0 +1,33 @@ +export interface SessionCredentials { + AccessKeyId?: string + SecretAccessKey?: string + SessionToken?: string + Expiration?: string +} + +export function isValidCredentials(credentials: SessionCredentials | undefined, now = Date.now()): boolean { + if ( + !credentials?.AccessKeyId || + !credentials.SecretAccessKey || + !credentials.SessionToken || + !credentials.Expiration + ) { + return false + } + const expiration = Date.parse(credentials.Expiration) + return Number.isFinite(expiration) && expiration > now +} + +export function isSameSession(current: SessionCredentials | undefined, expected: SessionCredentials): boolean { + return ( + !!current?.AccessKeyId && + current.AccessKeyId === expected.AccessKeyId && + current.SecretAccessKey === expected.SecretAccessKey && + current.SessionToken === expected.SessionToken && + current.Expiration === expected.Expiration + ) +} + +export function isSessionError(code: string | undefined): boolean { + return ["invalidaccesskeyid", "expiredtoken", "unauthorizedaccess"].includes(code?.toLowerCase() ?? "") +} diff --git a/lib/s3-error-middleware.ts b/lib/s3-error-middleware.ts new file mode 100644 index 00000000..6c35c9f6 --- /dev/null +++ b/lib/s3-error-middleware.ts @@ -0,0 +1,92 @@ +import type { S3Client } from "@aws-sdk/client-s3" +import { getServiceErrorMessage, getXmlErrorCode, getXmlErrorMessage } from "./error-handler" +import { isSessionError } from "./auth-session" + +type StreamCollector = (streamBody: unknown) => Promise + +const readResponseBodyText = async ( + body: unknown, + streamCollector: StreamCollector | undefined, +): Promise => { + if (typeof body === "string") { + return body + } + + if (body instanceof Uint8Array) { + return new TextDecoder("utf-8").decode(body) + } + + if (!body || !streamCollector) { + return null + } + + const bytes = await streamCollector(body) + return new TextDecoder("utf-8").decode(bytes) +} + +const createS3ServiceError = (message: string, statusCode: number, code?: string | null) => { + const error = new Error(message) as Error & { + Code?: string + $metadata?: { httpStatusCode?: number } + } + error.name = code ?? "S3ServiceError" + if (code) error.Code = code + error.$metadata = { httpStatusCode: statusCode } + return error +} + +export function addS3ErrorMiddleware(client: S3Client, onSessionExpired: () => void) { + /* eslint-disable @typescript-eslint/no-explicit-any -- AWS SDK middleware types are complex */ + client.middlewareStack.addRelativeTo( + ((next: any) => async (args: any) => { + const result = await next(args) + const response = result?.response + const statusCode = response?.statusCode + + if (typeof statusCode === "number" && statusCode >= 300) { + const streamCollector = client.config.streamCollector as StreamCollector | undefined + const bodyText = await readResponseBodyText(response.body, streamCollector) + const errorCode = bodyText ? getXmlErrorCode(bodyText) : null + const errorMessage = bodyText ? (getXmlErrorMessage(bodyText) ?? bodyText.trim()) : null + + if (errorMessage) { + throw createS3ServiceError(errorMessage, statusCode, errorCode) + } + } + + return result + }) as any, + { + name: "normalizeXmlErrorResponse", + relation: "after", + toMiddleware: "deserializerMiddleware", + override: true, + }, + ) + client.middlewareStack.addRelativeTo( + ((next: any) => async (args: any) => { + try { + return await next(args) + } catch (error: unknown) { + const err = error as { + $metadata?: { httpStatusCode?: number } + Code?: string + name?: string + message?: string + } + if (err?.$metadata?.httpStatusCode === 401 || isSessionError(err?.Code) || isSessionError(err?.name)) { + onSessionExpired() + throw error + } + + const serviceErrorMessage = getServiceErrorMessage(error) + if (serviceErrorMessage && error instanceof Error) { + error.message = serviceErrorMessage + } + throw error + } + }) as any, + { name: "handleXmlResponse", relation: "before", toMiddleware: "deserializerMiddleware" }, + ) + /* eslint-enable @typescript-eslint/no-explicit-any */ +} diff --git a/tests/hooks/use-oidc-logout.test.ts b/tests/hooks/use-oidc-logout.test.ts index 2a4f530e..6cd05742 100644 --- a/tests/hooks/use-oidc-logout.test.ts +++ b/tests/hooks/use-oidc-logout.test.ts @@ -67,10 +67,12 @@ overrides["@/contexts/s3-context"] = moduleUrl("contexts/s3-context.tsx") const { AuthProvider, useAuth } = (await import( overrides["@/contexts/auth-context"] )) as typeof import("../../contexts/auth-context") -const { ApiProvider } = (await import( +const { ApiProvider, useApiReady } = (await import( overrides["@/contexts/api-context"] )) as typeof import("../../contexts/api-context") -const { S3Provider } = (await import(overrides["@/contexts/s3-context"])) as typeof import("../../contexts/s3-context") +const { S3Provider, useS3Ready } = (await import( + overrides["@/contexts/s3-context"] +)) as typeof import("../../contexts/s3-context") const { DashboardAuthGuard } = (await import( moduleUrl("components/dashboard-auth-guard.tsx") )) as typeof import("../../components/dashboard-auth-guard") @@ -92,7 +94,12 @@ const credentials = { async function mountDashboard( t: TestContext, - options: { token?: string | null; onCredentials?: (auth: Auth) => void } = {}, + options: { + token?: string | null + expiration?: string + expectAuthenticated?: boolean + onCredentials?: (auth: Auth) => void + } = {}, ) { const browser = new Window({ url: "https://console.example.test/browser/" }) const globals = { @@ -105,6 +112,14 @@ async function mountDashboard( for (const [key, value] of Object.entries(globals)) { Object.defineProperty(globalThis, key, { configurable: true, writable: true, value }) } + const timers: { callback: () => void; delay: number; cancelled: boolean }[] = [] + t.mock.method(browser, "setTimeout", (callback: () => void, delay: number) => { + timers.push({ callback, delay, cancelled: false }) + return timers.length + }) + t.mock.method(browser, "clearTimeout", (id: number) => { + if (timers[id - 1]) timers[id - 1].cancelled = true + }) const navigate = t.mock.fn<(url: string) => void>() const replaceDocument = t.mock.fn<(url: string) => void>() Object.defineProperty(browser, "location", { @@ -118,7 +133,10 @@ async function mountDashboard( replace: replaceDocument, }, }) - browser.localStorage.setItem("auth.credentials", JSON.stringify(credentials)) + browser.localStorage.setItem( + "auth.credentials", + JSON.stringify({ ...credentials, Expiration: options.expiration ?? credentials.Expiration }), + ) browser.localStorage.setItem("auth.isAdmin", "true") const token = options.token === undefined ? "test-logout-token" : options.token if (token !== null) browser.localStorage.setItem("auth.oidcSession", JSON.stringify({ logoutToken: token })) @@ -155,14 +173,33 @@ async function mountDashboard( S3Client: class { config = {} middlewareStack = { - addRelativeTo() {}, - add(middleware: Middleware) { - s3Handlers.push(middleware) + addRelativeTo(middleware: Middleware, options: { name: string }) { + if (options.name === "handleXmlResponse") s3Handlers.push(middleware) }, } }, }) let auth: Auth + const clientSnapshots: { + session?: string + apiReady: boolean + s3Ready: boolean + apiExists: boolean + s3Exists: boolean + }[] = [] + function ClientProbe() { + const auth = useAuth() + const api = useApiReady() + const s3 = useS3Ready() + clientSnapshots.push({ + session: auth.credentials?.AccessKeyId, + apiReady: api.isReady, + s3Ready: s3.isReady, + apiExists: !!api.api, + s3Exists: !!s3.client, + }) + return null + } function Probe() { const value = useAuth() auth = value @@ -187,6 +224,7 @@ async function mountDashboard( createElement( S3Provider, null, + createElement(ClientProbe), createElement(DashboardAuthGuard, null, createElement("main", null, "Dashboard")), ), ), @@ -203,11 +241,23 @@ async function mountDashboard( } }) await render() - assert.ok(container.querySelector("main"), "starts with the authenticated dashboard mounted") - assert.equal(apiHandlers.length, 1) - assert.equal(s3Handlers.length, 1) + assert.equal(!!container.querySelector("main"), options.expectAuthenticated ?? true) + assert.equal(apiHandlers.length, options.expectAuthenticated === false ? 0 : 1) + assert.equal(s3Handlers.length, options.expectAuthenticated === false ? 0 : 1) return { browser, + clientSnapshots, + timers, + async fireTimer(index = timers.length - 1) { + await act(async () => timers[index].callback()) + }, + get latestApiHandler() { + return apiHandlers.at(-1)! + }, + latestS3Error: (error: unknown) => + s3Handlers.at(-1)!(async () => { + throw error + })({}), container, router, configManager, @@ -349,14 +399,17 @@ test("permission changes cannot redirect to forbidden while logout config is pen }) const apiFailures = [ - { status: 401, path: "/buckets", target: "/auth/login/" }, - { status: 403, path: "/accountinfo", target: "/auth/login/" }, + { status: 401, path: "/buckets", target: "/auth/login/?unauthorized=true" }, + { status: 403, path: "/accountinfo", target: "/403/" }, + { status: 403, path: "/is-admin", target: "/403/" }, + { status: 403, path: "/version", target: "/403/" }, { status: 403, path: "/buckets", target: "/403/" }, ] const s3Failures = [ { $metadata: { httpStatusCode: 401 } }, { $metadata: { httpStatusCode: 403 }, Code: "UnauthorizedAccess" }, { $metadata: { httpStatusCode: 403 }, Code: "InvalidAccessKeyId" }, + { $metadata: { httpStatusCode: 400 }, Code: "ExpiredToken" }, ] for (const phase of ["config pending", "navigation started"]) { @@ -367,7 +420,7 @@ for (const phase of ["config pending", "navigation started"]) { await act(async () => { for (const { status, path } of apiFailures) await mounted.apiHandler.handleByStatus(status, path) for (const error of s3Failures) { - assert.deepEqual(await mounted.s3Error(error), { response: { statusCode: 401, headers: {} } }) + await assert.rejects(mounted.s3Error(error), (caught) => caught === error) } }) assert.equal(mounted.router.replace.mock.callCount(), 0) @@ -394,8 +447,8 @@ for (const { status, path, target } of apiFailures) { for (const error of s3Failures) { test(`S3 ${error.Code ?? "401"} still logs out outside federated logout`, async (t) => { const mounted = await mountDashboard(t) - await act(async () => mounted.s3Error(error)) - assert.equal(mounted.router.replace.mock.calls[0].arguments[0], "/auth/login/") + await act(async () => assert.rejects(mounted.s3Error(error), (caught) => caught === error)) + assert.equal(mounted.router.replace.mock.calls[0].arguments[0], "/auth/login/?unauthorized=true") assert.equal(mounted.auth.isAuthenticated, false) }) } @@ -443,7 +496,7 @@ test("a session received from another tab can log out with its own OIDC token", }) for (const service of ["API", "S3"]) { - test(`a cross-tab session restores ${service} authentication handling before child effects run`, async (t) => { + test(`old ${service} callbacks cannot erase a cross-tab session before child effects run`, async (t) => { let failure: Promise | undefined const mounted = await mountDashboard(t, { onCredentials: (auth) => { @@ -451,15 +504,15 @@ for (const service of ["API", "S3"]) { failure = service === "API" ? mounted.apiHandler.handle401() - : mounted.s3Error({ $metadata: { httpStatusCode: 403 }, Code: "UnauthorizedAccess" }) + : mounted.s3Error({ $metadata: { httpStatusCode: 403 }, Code: "UnauthorizedAccess" }).catch(() => undefined) }, }) await mounted.logout() await mounted.syncStorage("auth.credentials", JSON.stringify({ ...credentials, AccessKeyId: "other-tab" })) await act(async () => failure) assert.ok(failure, "the new authenticated session runs its child effect") - assert.equal(mounted.router.replace.mock.calls[0]?.arguments[0], "/auth/login/") - assert.equal(mounted.auth.isAuthenticated, false) + assert.equal(mounted.router.replace.mock.callCount(), 0) + assert.equal(mounted.auth.isAuthenticated, true) }) } @@ -522,3 +575,223 @@ test("restoring an old logged-out document preserves a newer session and reloads ) assert.equal(mounted.router.replace.mock.callCount(), 0) }) + +for (const phase of ["before storage event", "after storage event"]) { + test(`old API and S3 callbacks preserve a replacement session ${phase}`, async (t) => { + const mounted = await mountDashboard(t) + const replacement = { ...credentials, AccessKeyId: "replacement", SessionToken: "replacement-token" } + const serialized = JSON.stringify(replacement) + mounted.browser.localStorage.setItem("auth.credentials", serialized) + mounted.browser.localStorage.setItem("auth.isAdmin", "true") + mounted.browser.localStorage.setItem("auth.oidcSession", JSON.stringify({ logoutToken: "replacement-logout" })) + if (phase === "after storage event") await mounted.syncStorage("auth.credentials", serialized) + await act(async () => { + for (const { status, path } of apiFailures) await mounted.apiHandler.handleByStatus(status, path) + for (const error of s3Failures) await assert.rejects(mounted.s3Error(error), (caught) => caught === error) + }) + assert.equal(mounted.router.replace.mock.callCount(), 0) + assert.equal(mounted.browser.localStorage.getItem("auth.credentials"), serialized) + assert.equal(mounted.browser.localStorage.getItem("auth.isAdmin"), "true") + assert.equal( + mounted.browser.localStorage.getItem("auth.oidcSession"), + JSON.stringify({ logoutToken: "replacement-logout" }), + ) + }) +} + +test("reusing an access key with a new session token protects the replacement session", async (t) => { + const mounted = await mountDashboard(t) + const serialized = JSON.stringify({ ...credentials, SessionToken: "replacement-token" }) + mounted.browser.localStorage.setItem("auth.credentials", serialized) + await act(async () => mounted.apiHandler.handle401()) + assert.equal(mounted.browser.localStorage.getItem("auth.credentials"), serialized) + assert.equal(mounted.router.replace.mock.callCount(), 0) +}) + +test("logout followed by login in the same React batch persists the new session immediately", async (t) => { + const mounted = await mountDashboard(t) + const replacement = { ...credentials, AccessKeyId: "replacement" } + await act(async () => { + mounted.auth.logout() + assert.equal(mounted.browser.localStorage.getItem("auth.credentials"), null) + await mounted.auth.loginWithStsCredentials(replacement) + assert.equal(mounted.browser.localStorage.getItem("auth.credentials"), JSON.stringify(replacement)) + }) + await act(async () => mounted.apiHandler.handle401()) + assert.equal(mounted.auth.credentials?.AccessKeyId, "replacement") + assert.equal(mounted.router.replace.mock.callCount(), 0) +}) + +test("a queued old storage event reloads the latest session instead of its obsolete payload", async (t) => { + const mounted = await mountDashboard(t) + const replacement = { ...credentials, AccessKeyId: "replacement" } + mounted.browser.localStorage.setItem("auth.credentials", JSON.stringify(replacement)) + await act(async () => + mounted.browser.dispatchEvent( + new mounted.browser.StorageEvent("storage", { + key: "auth.credentials", + newValue: JSON.stringify(credentials), + }), + ), + ) + assert.equal(mounted.auth.credentials?.AccessKeyId, "replacement") +}) + +for (const service of ["API", "S3"]) { + test(`new ${service} callbacks still expire a replacement session`, async (t) => { + const mounted = await mountDashboard(t) + await mounted.syncStorage("auth.credentials", JSON.stringify({ ...credentials, AccessKeyId: "replacement" })) + await act(async () => { + if (service === "API") await mounted.latestApiHandler.handle401() + else { + const error = { Code: "ExpiredToken", $metadata: { httpStatusCode: 400 } } + await assert.rejects(mounted.latestS3Error(error), (caught) => caught === error) + } + }) + assert.equal(mounted.auth.isAuthenticated, false) + assert.equal(mounted.router.replace.mock.calls[0].arguments[0], "/auth/login/?unauthorized=true") + }) +} + +test("the expiration timer logs out an idle tab exactly at expiration", async (t) => { + const start = Date.parse("2026-11-14T00:00:00Z") + let now = start + t.mock.method(Date, "now", () => now) + const mounted = await mountDashboard(t, { expiration: new Date(start + 60_000).toISOString() }) + assert.equal(mounted.timers[0].delay, 60_000) + now += 60_000 + await mounted.fireTimer(0) + assert.equal(mounted.auth.isAuthenticated, false) + assert.equal(mounted.browser.localStorage.getItem("auth.credentials"), null) + assert.equal(mounted.navigate.mock.callCount(), 0, "automatic expiration does not start IdP logout") + assert.equal(mounted.router.replace.mock.calls[0].arguments[0], "/auth/login/?unauthorized=true") +}) + +test("an early expiration callback reschedules instead of logging out", async (t) => { + const start = Date.parse("2026-11-14T00:00:00Z") + t.mock.method(Date, "now", () => start) + const mounted = await mountDashboard(t, { expiration: new Date(start + 60_000).toISOString() }) + await mounted.fireTimer(0) + assert.equal(mounted.auth.isAuthenticated, true) + assert.equal(mounted.timers.at(-1)?.delay, 60_000) + assert.equal(mounted.router.replace.mock.callCount(), 0) +}) + +test("long-lived sessions use a bounded timeout instead of overflowing browser timers", async (t) => { + const mounted = await mountDashboard(t) + assert.equal(mounted.timers[0].delay, 2 ** 31 - 1) +}) + +for (const phase of ["before storage event", "after storage event"]) { + test(`an old timer preserves a new session ${phase}`, async (t) => { + const start = Date.parse("2026-11-14T00:00:00Z") + let now = start + t.mock.method(Date, "now", () => now) + const mounted = await mountDashboard(t, { expiration: new Date(start + 60_000).toISOString() }) + const replacement = { ...credentials, AccessKeyId: "replacement" } + mounted.browser.localStorage.setItem("auth.credentials", JSON.stringify(replacement)) + if (phase === "after storage event") await mounted.syncStorage("auth.credentials", JSON.stringify(replacement)) + now += 60_000 + await mounted.fireTimer(0) + assert.equal(mounted.browser.localStorage.getItem("auth.credentials"), JSON.stringify(replacement)) + assert.equal(mounted.router.replace.mock.callCount(), 0) + if (phase === "after storage event") assert.equal(mounted.timers[0].cancelled, true) + }) +} + +for (const event of ["visibilitychange", "pageshow"]) { + test(`${event} rechecks expiration after browser suspension`, async (t) => { + const start = Date.parse("2026-11-14T00:00:00Z") + let now = start + t.mock.method(Date, "now", () => now) + const mounted = await mountDashboard(t, { expiration: new Date(start + 60_000).toISOString() }) + now += 90_000 + await act(async () => { + if (event === "visibilitychange") { + Object.defineProperty(mounted.browser.document, "visibilityState", { configurable: true, value: "visible" }) + mounted.browser.document.dispatchEvent(new mounted.browser.Event(event)) + } else mounted.browser.dispatchEvent(new mounted.browser.Event(event)) + }) + assert.equal(mounted.auth.isAuthenticated, false) + assert.equal(mounted.router.replace.mock.calls[0].arguments[0], "/auth/login/?unauthorized=true") + }) +} + +test("a timer cannot interrupt pending federated logout even after local expiration", async (t) => { + const start = Date.parse("2026-11-14T00:00:00Z") + let now = start + t.mock.method(Date, "now", () => now) + const mounted = await mountDashboard(t, { expiration: new Date(start + 60_000).toISOString() }) + const pending = await pendingLogout(mounted) + now += 60_000 + await mounted.fireTimer(0) + assert.equal(mounted.router.replace.mock.callCount(), 0) + assert.notEqual(mounted.browser.localStorage.getItem("auth.credentials"), null) + await pending.finish() + assert.deepEqual( + mounted.navigate.mock.calls.map((call) => call.arguments), + [[logoutUrl]], + ) +}) + +test("replacement credentials never expose old clients while new configuration is pending", async (t) => { + const mounted = await mountDashboard(t) + const pending = Promise.withResolvers() + mounted.configManager.loadConfig.mock.mockImplementation(() => pending.promise) + await mounted.syncStorage("auth.credentials", JSON.stringify({ ...credentials, AccessKeyId: "replacement" })) + const snapshots = mounted.clientSnapshots.filter((snapshot) => snapshot.session === "replacement") + assert.ok(snapshots.length > 0) + assert.ok( + snapshots.every((snapshot) => !snapshot.apiExists && !snapshot.s3Exists && !snapshot.apiReady && !snapshot.s3Ready), + ) + await act(async () => pending.resolve(config)) + const ready = mounted.clientSnapshots.at(-1)! + assert.equal(ready.session, "replacement") + assert.equal(ready.apiReady && ready.s3Ready && ready.apiExists && ready.s3Exists, true) +}) + +test("an existing session still expires when the browser refuses localStorage", async (t) => { + const mounted = await mountDashboard(t) + for (const method of ["getItem", "setItem", "removeItem"] as const) { + t.mock.method(mounted.browser.localStorage, method, () => { + throw new Error("Storage denied") + }) + } + assert.equal(mounted.auth.isAuthenticated, true) + await act(async () => mounted.latestApiHandler.handle401()) + assert.equal(mounted.auth.isAuthenticated, false) + assert.equal(mounted.router.replace.mock.calls[0].arguments[0], "/auth/login/?unauthorized=true") +}) + +test("a quota failure rejects login without creating an untracked in-memory session", async (t) => { + const mounted = await mountDashboard(t) + t.mock.method(mounted.browser.localStorage, "setItem", () => { + throw new Error("Quota exceeded") + }) + await act(async () => + assert.rejects(mounted.auth.loginWithStsCredentials({ ...credentials, AccessKeyId: "replacement" }), { + message: "Unable to save the session in browser storage", + }), + ) + assert.equal(mounted.auth.credentials?.AccessKeyId, credentials.AccessKeyId) + assert.equal(mounted.browser.localStorage.getItem("auth.credentials"), JSON.stringify(credentials)) + await act(async () => mounted.latestApiHandler.handle401()) + assert.equal(mounted.auth.isAuthenticated, false) +}) + +test("a failed login cannot release pending OIDC logout protection", async (t) => { + const mounted = await mountDashboard(t) + const pending = await pendingLogout(mounted) + t.mock.method(mounted.browser.localStorage, "setItem", () => { + throw new Error("Quota exceeded") + }) + await act(async () => + assert.rejects(mounted.auth.loginWithStsCredentials({ ...credentials, AccessKeyId: "replacement" })), + ) + assert.equal(mounted.auth.getIsLoggingOut(), true) + await pending.finish() + assert.deepEqual( + mounted.navigate.mock.calls.map((call) => call.arguments), + [[logoutUrl]], + ) +}) diff --git a/tests/lib/api-client.test.ts b/tests/lib/api-client.test.ts index fafadef6..234e251b 100644 --- a/tests/lib/api-client.test.ts +++ b/tests/lib/api-client.test.ts @@ -110,3 +110,66 @@ test("ApiClient exposes structured service codes without losing the safe message status: 404, }) }) + +for (const format of ["json", "nested-json", "xml"]) { + for (const [status, code] of [ + [403, "InvalidAccessKeyId"], + [403, "ExpiredToken"], + [400, "ExpiredToken"], + ] as const) { + for (const suppress403Redirect of [false, true]) { + test(`ApiClient expires ${format} ${status} ${code} with suppression=${suppress403Redirect}`, async () => { + const { ApiClient } = await loadApiClient() + const handled: string[] = [] + const payload = { Code: code, Message: "Session expired" } + const response = + format === "xml" + ? new Response(`${code}Session expired`, { status }) + : Response.json(format === "nested-json" ? { error: payload } : payload, { status }) + const client = new ApiClient( + { fetch: async () => response }, + { + errorHandler: { + handle401: async () => { + handled.push("session") + }, + handle403: async () => { + handled.push("permission") + }, + handleServerError: async () => {}, + handleByStatus: async () => {}, + }, + }, + ) + await assert.rejects(client.get("https://console.test/access-keys", { suppress403Redirect }), { status, code }) + assert.deepEqual(handled, ["session"]) + }) + } + } +} + +for (const suppress403Redirect of [false, true]) { + test(`ApiClient preserves ordinary permission handling with suppression=${suppress403Redirect}`, async () => { + const { ApiClient } = await loadApiClient() + const handled: string[] = [] + const client = new ApiClient( + { fetch: async () => Response.json({ Code: "AccessDenied" }, { status: 403 }) }, + { + errorHandler: { + handle401: async () => { + handled.push("session") + }, + handle403: async () => { + handled.push("permission") + }, + handleServerError: async () => {}, + handleByStatus: async () => {}, + }, + }, + ) + await assert.rejects(client.get("https://console.test/accountinfo", { suppress403Redirect }), { + code: "AccessDenied", + }) + assert.deepEqual(handled, suppress403Redirect ? [] : ["permission"]) + }) +} diff --git a/tests/lib/auth-session.test.ts b/tests/lib/auth-session.test.ts new file mode 100644 index 00000000..674082d3 --- /dev/null +++ b/tests/lib/auth-session.test.ts @@ -0,0 +1,34 @@ +import test from "node:test" +import assert from "node:assert/strict" +import { isSameSession, isValidCredentials } from "../../lib/auth-session" + +const now = Date.parse("2026-11-14T00:00:00Z") +const credentials = { + AccessKeyId: "test-access", + SecretAccessKey: "test-secret", + SessionToken: "test-token", + Expiration: new Date(now + 60_000).toISOString(), +} + +test("complete unexpired STS credentials are authenticated", () => { + assert.equal(isValidCredentials(credentials, now), true) +}) + +for (const Expiration of [new Date(now).toISOString(), new Date(now - 1).toISOString(), "invalid-date", ""]) { + test(`credentials with expiration ${Expiration || "missing"} are not authenticated`, () => { + assert.equal(isValidCredentials({ ...credentials, Expiration }, now), false) + }) +} + +for (const field of ["AccessKeyId", "SecretAccessKey", "SessionToken", "Expiration"] as const) { + test(`credentials without ${field} are not authenticated`, () => { + assert.equal(isValidCredentials({ ...credentials, [field]: undefined }, now), false) + }) + test(`a replacement ${field} does not belong to an old request's session`, () => { + assert.equal(isSameSession({ ...credentials, [field]: "replacement" }, credentials), false) + }) +} + +test("a removed session does not belong to an old request", () => { + assert.equal(isSameSession(undefined, credentials), false) +}) diff --git a/tests/lib/form-interaction.test.ts b/tests/lib/form-interaction.test.ts index 9d386b98..0377b679 100644 --- a/tests/lib/form-interaction.test.ts +++ b/tests/lib/form-interaction.test.ts @@ -138,16 +138,21 @@ test("recovery codes retain every typed character, support deletion and stay sep assert.equal(inputs.get("login-mfa-code")!.value, "") }) -async function loginPage(t: TestContext) { +async function loginPage( + t: TestContext, + options: { unauthorized?: boolean; isAuthenticated?: boolean; strict?: boolean } = {}, +) { let props: LoginFormProps const deferred = Promise.withResolvers<{ status: "mfa-required"; challenge: string }>() const attempts: unknown[] = [] const verifications: unknown[] = [] const errors: unknown[] = [] - const router = { replace: () => {} } - const params = new URLSearchParams() + const routes: string[] = [] + const warnings: string[] = [] + const router = { replace: (path: string) => routes.push(path) } + const params = new URLSearchParams(options.unauthorized ? "unauthorized=true" : "") const api = { - isAuthenticated: false, + isAuthenticated: options.isAuthenticated ?? false, login: async (credentials: unknown) => { attempts.push(credentials) return deferred.promise @@ -156,8 +161,13 @@ async function loginPage(t: TestContext) { verifications.push(args) }, } - const feedback = { error: (text: string) => errors.push(text), success: () => {}, warning: () => {} } - await mount(t, React.createElement(LoginPage), { + const feedback = { + error: (text: string) => errors.push(text), + success: () => {}, + warning: (text: string) => warnings.push(text), + } + const page = React.createElement(LoginPage) + await mount(t, options.strict ? React.createElement(React.StrictMode, null, page) : page, { LoginForm: (value: LoginFormProps) => { props = value return null @@ -177,9 +187,23 @@ async function loginPage(t: TestContext) { attempts, verifications, errors, + routes, + warnings, } } +test("session expiration warns once even when login effects are replayed", async (t) => { + const ui = await loginPage(t, { unauthorized: true, strict: true }) + assert.deepEqual(ui.warnings, ["Your session has expired. Please log in again."]) + assert.deepEqual(ui.routes, ["/auth/login"]) +}) + +test("a recovered session ignores an obsolete unauthorized query instead of returning to login", async (t) => { + const ui = await loginPage(t, { unauthorized: true, isAuthenticated: true }) + assert.deepEqual(ui.warnings, []) + assert.deepEqual(ui.routes, ["/"]) +}) + const submitEvent = { preventDefault() {} } as React.FormEvent test("login blocks duplicate submissions and binds MFA to the credentials accepted by the first request", async (t) => { diff --git a/tests/lib/s3-error-middleware.test.ts b/tests/lib/s3-error-middleware.test.ts new file mode 100644 index 00000000..2cc33660 --- /dev/null +++ b/tests/lib/s3-error-middleware.test.ts @@ -0,0 +1,135 @@ +import test, { type TestContext } from "node:test" +import assert from "node:assert/strict" +import { S3Client, ListBucketsCommand } from "@aws-sdk/client-s3" +import { addS3ErrorMiddleware } from "../../lib/s3-error-middleware" + +function createClient(t: TestContext, statusCode: number, body: string) { + const onSessionExpired = t.mock.fn<() => void>() + const client = new S3Client({ + region: "us-east-1", + endpoint: "https://console.example.test", + credentials: { + accessKeyId: "test-access", + secretAccessKey: "test-secret", + sessionToken: "test-token", + }, + maxAttempts: 1, + requestHandler: { + async handle() { + return { + response: { + statusCode, + headers: { "content-type": "application/xml" }, + body: new TextEncoder().encode(body), + }, + } + }, + }, + }) + t.after(() => client.destroy()) + addS3ErrorMiddleware(client, onSessionExpired) + return { client, onSessionExpired } +} + +const errorXml = (code: string) => + `${code}Service reported ${code}test-request` + +const matchesServiceError = (statusCode: number, code: string) => (error: unknown) => { + assert.ok(error instanceof Error) + assert.equal(error.name, code) + assert.equal(error.message, `Service reported ${code}`) + assert.equal((error as Error & { $metadata?: { httpStatusCode?: number } }).$metadata?.httpStatusCode, statusCode) + return true +} + +for (const [statusCode, code] of [ + [403, "InvalidAccessKeyId"], + [400, "ExpiredToken"], + [403, "ExpiredToken"], + [403, "UnauthorizedAccess"], + [401, "Unauthorized"], +] as const) { + test(`S3 ${statusCode} ${code} expires the session and still rejects the service error`, async (t) => { + const { client, onSessionExpired } = createClient(t, statusCode, errorXml(code)) + + await assert.rejects(client.send(new ListBucketsCommand({})), matchesServiceError(statusCode, code)) + assert.equal(onSessionExpired.mock.callCount(), 1) + }) +} + +test("an empty S3 401 response expires the session without resolving a fabricated SDK output", async (t) => { + const { client, onSessionExpired } = createClient(t, 401, "") + + await assert.rejects(client.send(new ListBucketsCommand({})), (error: unknown) => { + assert.ok(error instanceof Error) + assert.notEqual(error.name, "TypeError") + return (error as Error & { $metadata?: { httpStatusCode?: number } }).$metadata?.httpStatusCode === 401 + }) + assert.equal(onSessionExpired.mock.callCount(), 1) +}) + +for (const [statusCode, code] of [ + [403, "AccessDenied"], + [403, "SignatureDoesNotMatch"], + [404, "NoSuchBucket"], + [500, "InternalError"], +] as const) { + test(`S3 ${statusCode} ${code} remains rejected without expiring a valid session`, async (t) => { + const { client, onSessionExpired } = createClient(t, statusCode, errorXml(code)) + + await assert.rejects(client.send(new ListBucketsCommand({})), matchesServiceError(statusCode, code)) + assert.equal(onSessionExpired.mock.callCount(), 0) + }) +} + +test("a successful S3 list preserves deserialized buckets and does not expire the session", async (t) => { + const { client, onSessionExpired } = createClient( + t, + 200, + 'ownerOwnerphotos2026-01-01T00:00:00.000Z', + ) + + const result = await client.send(new ListBucketsCommand({})) + + assert.deepEqual( + result.Buckets?.map((bucket) => bucket.Name), + ["photos"], + ) + assert.equal(result.$metadata.httpStatusCode, 200) + assert.equal(onSessionExpired.mock.callCount(), 0) +}) + +test("an empty successful XML response preserves the SDK output without a TypeError", async (t) => { + const { client, onSessionExpired } = createClient( + t, + 200, + '', + ) + + const result = await client.send(new ListBucketsCommand({})) + + assert.equal(result.Buckets, undefined) + assert.equal(result.$metadata.httpStatusCode, 200) + assert.equal(onSessionExpired.mock.callCount(), 0) +}) + +test("a transport failure preserves the original error and does not expire the session", async (t) => { + const networkError = new Error("Network unavailable") + const onSessionExpired = t.mock.fn<() => void>() + const client = new S3Client({ + region: "us-east-1", + endpoint: "https://console.example.test", + credentials: { accessKeyId: "test-access", secretAccessKey: "test-secret" }, + maxAttempts: 1, + requestHandler: { + async handle(): Promise { + throw networkError + }, + }, + }) + t.after(() => client.destroy()) + addS3ErrorMiddleware(client, onSessionExpired) + + await assert.rejects(client.send(new ListBucketsCommand({})), (error) => error === networkError) + assert.equal(onSessionExpired.mock.callCount(), 0) +})