From cab8f6dcad3f9dd30addf09abc4ef02ad3a7bbf4 Mon Sep 17 00:00:00 2001 From: bigben-7 Date: Fri, 20 Nov 2026 07:47:34 +0100 Subject: [PATCH] Cache auth checks, component a11y tests, dispute description limits --- .github/workflows/ci.yml | 2 +- backend/src/common/api-contracts.ts | 2 +- backend/src/contracts/api-contracts.json | 3 +- backend/src/dispute/dto/create-dispute.dto.ts | 9 +- contracts/api-contracts.json | 3 +- .../components/disputes/FileDisputeModal.tsx | 9 ++ frontend/contracts/api-contracts.json | 3 +- frontend/docs/auth-middleware.md | 18 ++++ frontend/lib/__tests__/dispute-schema.test.ts | 21 +++++ frontend/lib/schemas/dispute.ts | 18 ++-- frontend/middleware.ts | 37 +++++++- frontend/package.json | 2 +- frontend/test-utils/component-a11y.test.tsx | 89 +++++++++++++++++++ frontend/test-utils/middleware.test.ts | 35 +++++++- 14 files changed, 235 insertions(+), 16 deletions(-) create mode 100644 frontend/docs/auth-middleware.md create mode 100644 frontend/lib/__tests__/dispute-schema.test.ts create mode 100644 frontend/test-utils/component-a11y.test.tsx diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 75e4fcb0..df6ba645 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -112,7 +112,7 @@ jobs: path: frontend/coverage/ - name: Accessibility tests (jest-axe) - run: npm run test:a11y -- --passWithNoTests + run: npm run test:a11y - name: Install Playwright browsers run: npx playwright install --with-deps chromium firefox webkit diff --git a/backend/src/common/api-contracts.ts b/backend/src/common/api-contracts.ts index e772cb3b..b7dcb5fa 100644 --- a/backend/src/common/api-contracts.ts +++ b/backend/src/common/api-contracts.ts @@ -18,7 +18,7 @@ type ApiContracts = { }; dispute: { documentId: StringContract; - description: { minLength: number }; + description: { minLength: number; maxLength: number }; statuses: string[]; }; documentUpload: { diff --git a/backend/src/contracts/api-contracts.json b/backend/src/contracts/api-contracts.json index 2907b374..97ce34a6 100644 --- a/backend/src/contracts/api-contracts.json +++ b/backend/src/contracts/api-contracts.json @@ -26,7 +26,8 @@ "format": "uuid" }, "description": { - "minLength": 1 + "minLength": 20, + "maxLength": 5000 }, "statuses": [ "open", diff --git a/backend/src/dispute/dto/create-dispute.dto.ts b/backend/src/dispute/dto/create-dispute.dto.ts index aba3aec6..65f97370 100644 --- a/backend/src/dispute/dto/create-dispute.dto.ts +++ b/backend/src/dispute/dto/create-dispute.dto.ts @@ -1,4 +1,10 @@ -import { IsNotEmpty, IsString, IsUUID, MinLength } from 'class-validator'; +import { + IsNotEmpty, + IsString, + IsUUID, + MaxLength, + MinLength, +} from 'class-validator'; import { apiContracts } from '../../common/api-contracts'; export class CreateDisputeDto { @@ -9,5 +15,6 @@ export class CreateDisputeDto { @IsString() @IsNotEmpty() @MinLength(apiContracts.dispute.description.minLength) + @MaxLength(apiContracts.dispute.description.maxLength) description: string; } diff --git a/contracts/api-contracts.json b/contracts/api-contracts.json index 2907b374..97ce34a6 100644 --- a/contracts/api-contracts.json +++ b/contracts/api-contracts.json @@ -26,7 +26,8 @@ "format": "uuid" }, "description": { - "minLength": 1 + "minLength": 20, + "maxLength": 5000 }, "statuses": [ "open", diff --git a/frontend/components/disputes/FileDisputeModal.tsx b/frontend/components/disputes/FileDisputeModal.tsx index 2b491112..d8205fc9 100644 --- a/frontend/components/disputes/FileDisputeModal.tsx +++ b/frontend/components/disputes/FileDisputeModal.tsx @@ -6,6 +6,7 @@ import { apiUrl } from "@/lib/api-config"; import { createDisputeSchema, disputeResponseSchema, + DISPUTE_DESCRIPTION_MAX_LENGTH, DISPUTE_DESCRIPTION_UX_MIN_LENGTH, type DisputeResponse, } from "@/lib/schemas/dispute"; @@ -132,9 +133,17 @@ export function FileDisputeModal({ value={description} onChange={(e) => setDescription(e.target.value)} rows={4} + maxLength={DISPUTE_DESCRIPTION_MAX_LENGTH} + aria-describedby="description-counter" className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm" placeholder={`Please provide a detailed reason for your dispute (min. ${DISPUTE_DESCRIPTION_UX_MIN_LENGTH} characters).`} /> +

+ {description.length} / {DISPUTE_DESCRIPTION_MAX_LENGTH} +

{error &&

{error}

} diff --git a/frontend/contracts/api-contracts.json b/frontend/contracts/api-contracts.json index 2907b374..97ce34a6 100644 --- a/frontend/contracts/api-contracts.json +++ b/frontend/contracts/api-contracts.json @@ -26,7 +26,8 @@ "format": "uuid" }, "description": { - "minLength": 1 + "minLength": 20, + "maxLength": 5000 }, "statuses": [ "open", diff --git a/frontend/docs/auth-middleware.md b/frontend/docs/auth-middleware.md new file mode 100644 index 00000000..fd8598b6 --- /dev/null +++ b/frontend/docs/auth-middleware.md @@ -0,0 +1,18 @@ +# Auth middleware + +## API base URL (#1653) + +`middleware.ts` builds the `/auth/me` URL with `apiUrl("/auth/me")` from `lib/api-config.ts`, +which normalises `NEXT_PUBLIC_API_URL` whether it is the bare origin, ends in `/api`, or ends in +`/api/v1`. It no longer re-derives the base itself, so all three forms resolve to the same +`/api/v1/auth/me`. This was already the case on `main` when the issue was triaged; +`test-utils/api-config.test.ts` covers the three forms. + +## Round-trips and failures (#1654) + +- Positive `/auth/me` results are cached per access token for 30 seconds per edge isolate, so + navigating between protected pages (and prefetches) does not call the API each time. +- If the API is slow or failing, admin routes still return 503 (the role is needed); other + protected pages are let through, because the page's own API calls reject an invalid token. +- Not done: verifying the JWT signature locally with `jose`. That needs a new dependency and a + verification key or shared secret exposed to the edge runtime. diff --git a/frontend/lib/__tests__/dispute-schema.test.ts b/frontend/lib/__tests__/dispute-schema.test.ts new file mode 100644 index 00000000..64db8539 --- /dev/null +++ b/frontend/lib/__tests__/dispute-schema.test.ts @@ -0,0 +1,21 @@ +import { createDisputeSchema } from "@/lib/schemas/dispute"; + +const documentId = "3f2504e0-4f89-41d3-9a0c-0305e82c3301"; + +describe("createDisputeSchema description limits", () => { + it("rejects a one-character description", () => { + expect(createDisputeSchema.safeParse({ documentId, description: "x" }).success).toBe(false); + }); + + it("accepts a description of at least 20 characters", () => { + expect( + createDisputeSchema.safeParse({ documentId, description: "x".repeat(20) }).success, + ).toBe(true); + }); + + it("rejects an oversized description", () => { + expect( + createDisputeSchema.safeParse({ documentId, description: "x".repeat(5001) }).success, + ).toBe(false); + }); +}); diff --git a/frontend/lib/schemas/dispute.ts b/frontend/lib/schemas/dispute.ts index ed78a6e9..88059b9f 100644 --- a/frontend/lib/schemas/dispute.ts +++ b/frontend/lib/schemas/dispute.ts @@ -10,7 +10,9 @@ function contractUuidSchema(format: string, message?: string) { return message ? z.string().uuid({ message }) : z.string().uuid(); } -export const DISPUTE_DESCRIPTION_UX_MIN_LENGTH = 20; +export const DISPUTE_DESCRIPTION_UX_MIN_LENGTH = + disputeContract.description.minLength; +export const DISPUTE_DESCRIPTION_MAX_LENGTH = disputeContract.description.maxLength; export const disputeStatusValues = disputeContract.statuses; export type DisputeStatus = @@ -30,9 +32,14 @@ export const createDisputeSchema = z.object({ disputeContract.documentId.format, "errors.dispute.documentIdUuid", ), - description: z.string().min(disputeContract.description.minLength, { - message: "errors.dispute.descriptionRequired", - }), + description: z + .string() + .min(disputeContract.description.minLength, { + message: "errors.dispute.descriptionRequired", + }) + .max(disputeContract.description.maxLength, { + message: "errors.dispute.descriptionTooLong", + }), }); export const disputeReasonSchema = z.object({ @@ -43,7 +50,8 @@ export const disputeReasonSchema = z.object({ export const disputeResponseSchema = z.object({ id: z.string().uuid(), documentId: contractUuidSchema(disputeContract.documentId.format), - description: z.string().min(disputeContract.description.minLength), + // Responses stay lenient: disputes filed before the limits may be shorter. + description: z.string().min(1), reason: disputeReasonSchema.nullable(), status: disputeStatusSchema, filedBy: z.string().uuid(), diff --git a/frontend/middleware.ts b/frontend/middleware.ts index de833f77..7baf57b0 100644 --- a/frontend/middleware.ts +++ b/frontend/middleware.ts @@ -189,9 +189,39 @@ interface AccessTokenVerification { role?: string; } +// Short-lived, per-isolate cache of positive `/auth/me` results (#1654). Without +// it every protected navigation (prefetches included) costs an API round-trip. +// Only "authenticated" results are cached, so a revoked or expired token is +// re-checked once the entry lapses. +const AUTH_CACHE_TTL_MS = 30_000; +const AUTH_CACHE_MAX_ENTRIES = 500; +const authCache = new Map(); + +/** Test hook: forget every cached verification. */ +export function resetAuthCache(): void { + authCache.clear(); +} + async function verifyAccessToken(token: string): Promise { if (hasControlCharacter(token)) return { check: "unauthenticated" }; + const cached = authCache.get(token); + if (cached && cached.expires > Date.now()) return cached.value; + authCache.delete(token); + const result = await fetchAccessTokenVerification(token); + if (result.check === "authenticated") { + if (authCache.size >= AUTH_CACHE_MAX_ENTRIES) { + const oldest = authCache.keys().next().value; + if (oldest !== undefined) authCache.delete(oldest); + } + authCache.set(token, { value: result, expires: Date.now() + AUTH_CACHE_TTL_MS }); + } + return result; +} + +async function fetchAccessTokenVerification( + token: string, +): Promise { const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), AUTH_CHECK_TIMEOUT_MS); @@ -269,7 +299,12 @@ async function handleRequest(request: NextRequest): Promise { return createLoginRedirect(request, redirectPath); } if (authCheck.check === "unavailable") { - return createAuthenticationUnavailableResponse(); + // Only admin routes need the role from the API. For everything else a slow + // or failing API must not take the whole UI down (#1654): let the request + // through, the page's own API calls reject an invalid token anyway. + if (isAdminPath(pathname)) { + return createAuthenticationUnavailableResponse(); + } } if (isAdminPath(pathname) && authCheck.role !== "admin") { const url = request.nextUrl.clone(); diff --git a/frontend/package.json b/frontend/package.json index fd711c49..f6a03fec 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -14,7 +14,7 @@ "test:watch": "jest --watch", "test:coverage": "jest --coverage", "test:e2e": "playwright test", - "test:a11y": "jest --testPathPattern=accessibility --passWithNoTests" + "test:a11y": "jest --testPathPattern=\"(accessibility|a11y)\"" }, "dependencies": { "@hookform/resolvers": "^5.2.2", diff --git a/frontend/test-utils/component-a11y.test.tsx b/frontend/test-utils/component-a11y.test.tsx new file mode 100644 index 00000000..7bac6888 --- /dev/null +++ b/frontend/test-utils/component-a11y.test.tsx @@ -0,0 +1,89 @@ +import React from "react"; +import { render } from "@testing-library/react"; +import { NextIntlClientProvider } from "next-intl"; +import { axe, toHaveNoViolations } from "jest-axe"; +import messages from "@/messages/en.json"; +import RegisterForm from "@/components/RegisterForm"; +import { LoginForm } from "@/app/[locale]/login/LoginForm"; +import { FileDisputeModal } from "@/components/disputes/FileDisputeModal"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; + +expect.extend(toHaveNoViolations); + +jest.mock("@/i18n/navigation", () => ({ + Link: ({ children, ...props }: React.AnchorHTMLAttributes) => ( + {children} + ), + useRouter: () => ({ replace: jest.fn(), push: jest.fn() }), +})); + +jest.mock("next/navigation", () => ({ + useSearchParams: () => new URLSearchParams(), +})); + +jest.mock("@/lib/auth-session", () => ({ + resolvePostLoginPath: () => "/", + storeSession: jest.fn(), + saveTwoFactorToken: jest.fn(), +})); + +jest.mock("@/lib/api-client", () => ({ + API_V1_BASE: "http://localhost:3001/api/v1", + ApiError: class ApiError extends Error {}, + apiRequest: jest.fn(), + request: jest.fn(), +})); + +function withIntl(ui: React.ReactElement) { + return ( + + {ui} + + ); +} + +// These render the real components (not a fixture), so a regression such as an +// unlabelled input or a dialog without a title fails the accessibility step. +describe("component accessibility (axe)", () => { + it("LoginForm has no violations", async () => { + const { container } = render(withIntl()); + expect(await axe(container)).toHaveNoViolations(); + }); + + it("RegisterForm has no violations", async () => { + const { container } = render(withIntl()); + expect(await axe(container)).toHaveNoViolations(); + }); + + it("Dialog has no violations", async () => { + const { baseElement } = render( + + + + Title + Description + + + + , + ); + expect(await axe(baseElement)).toHaveNoViolations(); + }); + + it("FileDisputeModal has no violations", async () => { + const { baseElement } = render( + , + ); + expect(await axe(baseElement)).toHaveNoViolations(); + }); +}); diff --git a/frontend/test-utils/middleware.test.ts b/frontend/test-utils/middleware.test.ts index 1ab566fa..c54d8de6 100644 --- a/frontend/test-utils/middleware.test.ts +++ b/frontend/test-utils/middleware.test.ts @@ -1,5 +1,9 @@ import { NextRequest } from "next/server"; -import middleware, { getLegacyRedirectPath, isProtectedPath } from "@/middleware"; +import middleware, { + getLegacyRedirectPath, + isProtectedPath, + resetAuthCache, +} from "@/middleware"; // createMiddleware(routing) returns the locale middleware itself, so the mock // must hand back a function rather than a response. @@ -23,6 +27,7 @@ function response(status: number, body: unknown = {}): Response { } beforeEach(() => { + resetAuthCache(); fetchMock = jest.fn(); globalThis.fetch = fetchMock; }); @@ -127,10 +132,10 @@ describe("protected route middleware", () => { expect(new URL(result.headers.get("location")!).pathname).toBe("/login"); }); - it("fails closed without redirecting on verifier failure", async () => { + it("fails closed without redirecting on verifier failure for admin routes", async () => { fetchMock.mockResolvedValue(response(503)); const result = await middleware( - new NextRequest("https://smalda.test/settings", { + new NextRequest("https://smalda.test/admin/users", { headers: { cookie: "access_token=opaque-value" }, }), ); @@ -139,6 +144,30 @@ describe("protected route middleware", () => { expect(result.headers.get("location")).toBeNull(); }); + it("does not turn a verifier failure into a 503 for non-admin pages (#1654)", async () => { + fetchMock.mockResolvedValue(response(503)); + const result = await middleware( + new NextRequest("https://smalda.test/settings", { + headers: { cookie: "access_token=opaque-value" }, + }), + ); + + expect(result.status).toBe(200); + }); + + it("calls /auth/me once for repeated navigations with the same token (#1654)", async () => { + fetchMock.mockResolvedValue(response(200, { role: "user" })); + for (const path of ["/settings", "/documents", "/profile"]) { + await middleware( + new NextRequest(`https://smalda.test${path}`, { + headers: { cookie: "access_token=opaque-value" }, + }), + ); + } + + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + it("does not invoke locale middleware for infrastructure or static assets", async () => { await middleware(new NextRequest("https://smalda.test/api/documents")); await middleware(new NextRequest("https://smalda.test/fr/logo.svg"));