Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion backend/src/common/api-contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ type ApiContracts = {
};
dispute: {
documentId: StringContract;
description: { minLength: number };
description: { minLength: number; maxLength: number };
statuses: string[];
};
documentUpload: {
Expand Down
3 changes: 2 additions & 1 deletion backend/src/contracts/api-contracts.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
"format": "uuid"
},
"description": {
"minLength": 1
"minLength": 20,
"maxLength": 5000
},
"statuses": [
"open",
Expand Down
9 changes: 8 additions & 1 deletion backend/src/dispute/dto/create-dispute.dto.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -9,5 +15,6 @@ export class CreateDisputeDto {
@IsString()
@IsNotEmpty()
@MinLength(apiContracts.dispute.description.minLength)
@MaxLength(apiContracts.dispute.description.maxLength)
description: string;
}
3 changes: 2 additions & 1 deletion contracts/api-contracts.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
"format": "uuid"
},
"description": {
"minLength": 1
"minLength": 20,
"maxLength": 5000
},
"statuses": [
"open",
Expand Down
9 changes: 9 additions & 0 deletions frontend/components/disputes/FileDisputeModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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).`}
/>
<p
id="description-counter"
className="mt-1 text-right text-xs text-gray-500"
>
{description.length} / {DISPUTE_DESCRIPTION_MAX_LENGTH}
</p>
</div>
{error && <p className="text-sm text-red-600" role="alert">{error}</p>}
<DialogFooter>
Expand Down
3 changes: 2 additions & 1 deletion frontend/contracts/api-contracts.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
"format": "uuid"
},
"description": {
"minLength": 1
"minLength": 20,
"maxLength": 5000
},
"statuses": [
"open",
Expand Down
18 changes: 18 additions & 0 deletions frontend/docs/auth-middleware.md
Original file line number Diff line number Diff line change
@@ -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
`<origin>/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.
21 changes: 21 additions & 0 deletions frontend/lib/__tests__/dispute-schema.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
18 changes: 13 additions & 5 deletions frontend/lib/schemas/dispute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand All @@ -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({
Expand All @@ -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(),
Expand Down
37 changes: 36 additions & 1 deletion frontend/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, { value: AccessTokenVerification; expires: number }>();

/** Test hook: forget every cached verification. */
export function resetAuthCache(): void {
authCache.clear();
}

async function verifyAccessToken(token: string): Promise<AccessTokenVerification> {
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<AccessTokenVerification> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), AUTH_CHECK_TIMEOUT_MS);

Expand Down Expand Up @@ -269,7 +299,12 @@ async function handleRequest(request: NextRequest): Promise<NextResponse> {
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();
Expand Down
2 changes: 1 addition & 1 deletion frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
89 changes: 89 additions & 0 deletions frontend/test-utils/component-a11y.test.tsx
Original file line number Diff line number Diff line change
@@ -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<HTMLAnchorElement>) => (
<a {...props}>{children}</a>
),
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 (
<NextIntlClientProvider locale="en" messages={messages}>
{ui}
</NextIntlClientProvider>
);
}

// 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(<LoginForm />));
expect(await axe(container)).toHaveNoViolations();
});

it("RegisterForm has no violations", async () => {
const { container } = render(withIntl(<RegisterForm />));
expect(await axe(container)).toHaveNoViolations();
});

it("Dialog has no violations", async () => {
const { baseElement } = render(
<Dialog open>
<DialogContent>
<DialogHeader>
<DialogTitle>Title</DialogTitle>
<DialogDescription>Description</DialogDescription>
</DialogHeader>
<button type="button">Close</button>
</DialogContent>
</Dialog>,
);
expect(await axe(baseElement)).toHaveNoViolations();
});

it("FileDisputeModal has no violations", async () => {
const { baseElement } = render(
<FileDisputeModal
documents={[{ id: "d1", title: "Deed" }]}
onDisputeFiled={jest.fn()}
onClose={jest.fn()}
/>,
);
expect(await axe(baseElement)).toHaveNoViolations();
});
});
35 changes: 32 additions & 3 deletions frontend/test-utils/middleware.test.ts
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -23,6 +27,7 @@ function response(status: number, body: unknown = {}): Response {
}

beforeEach(() => {
resetAuthCache();
fetchMock = jest.fn();
globalThis.fetch = fetchMock;
});
Expand Down Expand Up @@ -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" },
}),
);
Expand All @@ -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"));
Expand Down
Loading