Sessie: een start-refresh zonder oordeel (429/5xx/netwerk) zet de gebruiker niet meer op gast maar toont een retry-scherm; Retry-After wordt gestuurd en gerespecteerd
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,52 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { render, screen, waitFor } from '@testing-library/react';
|
||||||
|
import userEvent from '@testing-library/user-event';
|
||||||
|
import { http, HttpResponse } from 'msw';
|
||||||
|
import { I18nextProvider } from 'react-i18next';
|
||||||
|
import type { ReactNode } from 'react';
|
||||||
|
import { AuthProvider } from '@/features/auth/context/AuthProvider';
|
||||||
|
import { useAuth } from '@/features/auth/context/auth-context';
|
||||||
|
import { SessionUnreachable } from '@/features/auth/components/SessionUnreachable';
|
||||||
|
import { server } from '@/mocks/server';
|
||||||
|
import { API_BASE, makeAuthResponse } from '@/features/auth/mocks/fixtures';
|
||||||
|
import { refreshBackoff } from '@/lib/refreshPolicy';
|
||||||
|
import i18n from '@/i18n/config';
|
||||||
|
|
||||||
|
function Probe() {
|
||||||
|
const { status } = useAuth();
|
||||||
|
return status === 'unreachable' ? <SessionUnreachable /> : <p data-testid="status">{status}</p>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function Wrapper({ children }: { children: ReactNode }) {
|
||||||
|
return (
|
||||||
|
<I18nextProvider i18n={i18n}>
|
||||||
|
<AuthProvider>{children}</AuthProvider>
|
||||||
|
</I18nextProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('SessionUnreachable', () => {
|
||||||
|
it('offers a retry that signs the visitor in once the server answers again', async () => {
|
||||||
|
const original = [...refreshBackoff.delays];
|
||||||
|
refreshBackoff.delays = [5];
|
||||||
|
try {
|
||||||
|
let down = true;
|
||||||
|
server.use(
|
||||||
|
http.post(`${API_BASE}/api/v1/auth/refresh`, () =>
|
||||||
|
down ? HttpResponse.json({ status: 429 }, { status: 429 }) : HttpResponse.json(makeAuthResponse()),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
render(<Probe />, { wrapper: Wrapper });
|
||||||
|
const retry = await screen.findByTestId('session-unreachable-retry');
|
||||||
|
|
||||||
|
await userEvent.click(retry); // still down
|
||||||
|
expect(await screen.findByTestId('session-unreachable-failed')).toBeInTheDocument();
|
||||||
|
|
||||||
|
down = false;
|
||||||
|
await userEvent.click(screen.getByTestId('session-unreachable-retry'));
|
||||||
|
await waitFor(() => expect(screen.getByTestId('status')).toHaveTextContent('authenticated'));
|
||||||
|
} finally {
|
||||||
|
refreshBackoff.delays = original;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
|
import { useAuth } from '@/features/auth/context/auth-context';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shown when the start-up refresh could not get a verdict (rate limit, restart, network). The visitor is not signed
|
||||||
|
* out - the cookie is intact - so this offers a retry instead of the login page.
|
||||||
|
*/
|
||||||
|
export function SessionUnreachable() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { refresh } = useAuth();
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [failedAgain, setFailedAgain] = useState(false);
|
||||||
|
|
||||||
|
const retry = async () => {
|
||||||
|
setBusy(true);
|
||||||
|
setFailedAgain(false);
|
||||||
|
try {
|
||||||
|
await refresh(); // success -> authenticated, a rejected cookie -> guest; this screen then goes away
|
||||||
|
} catch {
|
||||||
|
setFailedAgain(true);
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-svh items-center justify-center bg-secondary/40 p-4" data-testid="session-unreachable">
|
||||||
|
<Card className="w-full max-w-sm">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>{t('session.unreachable.title')}</CardTitle>
|
||||||
|
<CardDescription>{t('session.unreachable.description')}</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-3">
|
||||||
|
{failedAgain && (
|
||||||
|
<p role="alert" className="text-sm text-destructive" data-testid="session-unreachable-failed">
|
||||||
|
{t('session.unreachable.stillFailing')}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<Button onClick={() => void retry()} disabled={busy} data-testid="session-unreachable-retry">
|
||||||
|
{busy ? t('common.loading') : t('session.unreachable.retry')}
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -113,7 +113,7 @@ describe('AuthContext', () => {
|
|||||||
expect(calls).toBe(3);
|
expect(calls).toBe(3);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('falls back to guest (without a verdict on the cookie) after the last retry', async () => {
|
it('ends in the unreachable state (not guest) after the last retry: no verdict on the session', async () => {
|
||||||
let calls = 0;
|
let calls = 0;
|
||||||
server.use(
|
server.use(
|
||||||
http.post(`${API_BASE}/api/v1/auth/refresh`, () => {
|
http.post(`${API_BASE}/api/v1/auth/refresh`, () => {
|
||||||
@@ -124,10 +124,74 @@ describe('AuthContext', () => {
|
|||||||
|
|
||||||
const { result } = renderHook(() => useAuth(), { wrapper });
|
const { result } = renderHook(() => useAuth(), { wrapper });
|
||||||
|
|
||||||
await waitFor(() => expect(result.current.status).toBe('guest'));
|
await waitFor(() => expect(result.current.status).toBe('unreachable'));
|
||||||
|
expect(result.current.isAuthenticated).toBe(false);
|
||||||
expect(calls).toBe(1 + refreshBackoff.delays.length);
|
expect(calls).toBe(1 + refreshBackoff.delays.length);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('respects Retry-After on a 429 (waits at least that long before the next try)', async () => {
|
||||||
|
const stamps: number[] = [];
|
||||||
|
server.use(
|
||||||
|
http.post(`${API_BASE}/api/v1/auth/refresh`, () => {
|
||||||
|
stamps.push(Date.now());
|
||||||
|
if (stamps.length === 1) {
|
||||||
|
return HttpResponse.json({ status: 429 }, { status: 429, headers: { 'Retry-After': '0.3' } });
|
||||||
|
}
|
||||||
|
return HttpResponse.json(makeAuthResponse());
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const { result } = renderHook(() => useAuth(), { wrapper });
|
||||||
|
|
||||||
|
await waitFor(() => expect(result.current.status).toBe('authenticated'), { timeout: 3000 });
|
||||||
|
expect(stamps[1] - stamps[0]).toBeGreaterThanOrEqual(280); // the planned backoff is only 5 ms
|
||||||
|
});
|
||||||
|
|
||||||
|
it('recovers from the unreachable state through refresh(), without ever having been a guest', async () => {
|
||||||
|
let down = true;
|
||||||
|
server.use(
|
||||||
|
http.post(`${API_BASE}/api/v1/auth/refresh`, () =>
|
||||||
|
down ? HttpResponse.json({ status: 503 }, { status: 503 }) : HttpResponse.json(makeAuthResponse()),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const seen: string[] = [];
|
||||||
|
const { result } = renderHook(
|
||||||
|
() => {
|
||||||
|
const a = useAuth();
|
||||||
|
seen.push(a.status);
|
||||||
|
return a;
|
||||||
|
},
|
||||||
|
{ wrapper },
|
||||||
|
);
|
||||||
|
await waitFor(() => expect(result.current.status).toBe('unreachable'));
|
||||||
|
|
||||||
|
down = false;
|
||||||
|
await act(async () => {
|
||||||
|
await result.current.refresh();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.current.status).toBe('authenticated');
|
||||||
|
expect(seen).not.toContain('guest');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a 401 verdict on the retry still ends in guest', async () => {
|
||||||
|
let first = true;
|
||||||
|
server.use(
|
||||||
|
http.post(`${API_BASE}/api/v1/auth/refresh`, () =>
|
||||||
|
first ? HttpResponse.json({ status: 503 }, { status: 503 }) : HttpResponse.json({ status: 401 }, { status: 401 }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const { result } = renderHook(() => useAuth(), { wrapper });
|
||||||
|
await waitFor(() => expect(result.current.status).toBe('unreachable'));
|
||||||
|
|
||||||
|
first = false;
|
||||||
|
await act(async () => {
|
||||||
|
await result.current.refresh();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.current.status).toBe('guest');
|
||||||
|
});
|
||||||
|
|
||||||
it('does not retry when the server rejects the cookie (401)', async () => {
|
it('does not retry when the server rejects the cookie (401)', async () => {
|
||||||
let calls = 0;
|
let calls = 0;
|
||||||
server.use(
|
server.use(
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
||||||
import type { AuthResponse } from '@/features/auth/services/types';
|
import type { AuthResponse } from '@/features/auth/services/types';
|
||||||
import { api } from '@/lib/api-client';
|
import { api } from '@/lib/api-client';
|
||||||
import { isAuthRejection, refreshBackoff } from '@/lib/refreshPolicy';
|
import { isAuthRejection, nextRetryDelay, refreshBackoff } from '@/lib/refreshPolicy';
|
||||||
import { changeLanguage } from '@/i18n/config';
|
import { changeLanguage } from '@/i18n/config';
|
||||||
import { AuthContext, type AuthContextValue, type AuthStatus } from '@/features/auth/context/auth-context';
|
import { AuthContext, type AuthContextValue, type AuthStatus } from '@/features/auth/context/auth-context';
|
||||||
|
|
||||||
@@ -113,8 +113,9 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
|||||||
|
|
||||||
// Silent refresh on app mount (BR-U1-01). This intentionally synchronizes
|
// Silent refresh on app mount (BR-U1-01). This intentionally synchronizes
|
||||||
// React state with the external session (httpOnly cookie) on startup.
|
// React state with the external session (httpOnly cookie) on startup.
|
||||||
// A transient failure (429, 502 during a restart, network) is retried a few times with a backoff; if it
|
// A transient failure (429, 502 during a restart, network) is retried a few times with a backoff (longer when the
|
||||||
// still fails the visitor is a guest for now, and the refresh cookie is untouched so a reload can recover.
|
// server sends Retry-After). If it still fails there is no verdict on the session: the status becomes
|
||||||
|
// 'unreachable' (a retry screen), NOT 'guest', and the refresh cookie is untouched.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
void (async () => {
|
void (async () => {
|
||||||
@@ -123,18 +124,18 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
|||||||
try {
|
try {
|
||||||
await refresh();
|
await refresh();
|
||||||
return;
|
return;
|
||||||
} catch {
|
} catch (err) {
|
||||||
if (cancelled || attempt >= delays.length) break;
|
if (cancelled || attempt >= delays.length) break;
|
||||||
await new Promise((resolve) => setTimeout(resolve, delays[attempt]));
|
await new Promise((resolve) => setTimeout(resolve, nextRetryDelay(err, delays[attempt])));
|
||||||
if (cancelled) return;
|
if (cancelled) return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!cancelled) clearSession();
|
if (!cancelled) setStatus('unreachable');
|
||||||
})();
|
})();
|
||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
};
|
};
|
||||||
}, [refresh, clearSession]);
|
}, [refresh]);
|
||||||
|
|
||||||
const value = useMemo<AuthContextValue>(
|
const value = useMemo<AuthContextValue>(
|
||||||
() => ({
|
() => ({
|
||||||
|
|||||||
@@ -1,7 +1,12 @@
|
|||||||
import { createContext, useContext } from 'react';
|
import { createContext, useContext } from 'react';
|
||||||
import type { User } from '@/features/auth/services/types';
|
import type { User } from '@/features/auth/services/types';
|
||||||
|
|
||||||
export type AuthStatus = 'loading' | 'authenticated' | 'guest';
|
/**
|
||||||
|
* 'unreachable': the start-up refresh could not get a verdict (rate limit, restart, network) after the quiet retries.
|
||||||
|
* The session is neither confirmed nor ended - the refresh cookie is untouched - so the app offers a retry
|
||||||
|
* instead of treating the visitor as signed out.
|
||||||
|
*/
|
||||||
|
export type AuthStatus = 'loading' | 'authenticated' | 'guest' | 'unreachable';
|
||||||
|
|
||||||
export interface AuthContextValue {
|
export interface AuthContextValue {
|
||||||
status: AuthStatus;
|
status: AuthStatus;
|
||||||
|
|||||||
@@ -20,6 +20,14 @@
|
|||||||
"switchToLight": "Switch to light theme",
|
"switchToLight": "Switch to light theme",
|
||||||
"switchToDark": "Switch to dark theme"
|
"switchToDark": "Switch to dark theme"
|
||||||
},
|
},
|
||||||
|
"session": {
|
||||||
|
"unreachable": {
|
||||||
|
"title": "Could not check your session",
|
||||||
|
"description": "The server is briefly unreachable or busy. You have not been signed out. Try again in a few seconds.",
|
||||||
|
"retry": "Try again",
|
||||||
|
"stillFailing": "Still no answer. Wait a moment and try again."
|
||||||
|
}
|
||||||
|
},
|
||||||
"login": {
|
"login": {
|
||||||
"title": "Sign in",
|
"title": "Sign in",
|
||||||
"subtitle": "Sign in to your SlpModularCms account",
|
"subtitle": "Sign in to your SlpModularCms account",
|
||||||
|
|||||||
@@ -20,6 +20,14 @@
|
|||||||
"switchToLight": "Overschakelen naar licht thema",
|
"switchToLight": "Overschakelen naar licht thema",
|
||||||
"switchToDark": "Overschakelen naar donker thema"
|
"switchToDark": "Overschakelen naar donker thema"
|
||||||
},
|
},
|
||||||
|
"session": {
|
||||||
|
"unreachable": {
|
||||||
|
"title": "Sessie kon niet worden gecontroleerd",
|
||||||
|
"description": "De server is even niet bereikbaar of te druk. Je bent niet uitgelogd. Probeer het over een paar seconden opnieuw.",
|
||||||
|
"retry": "Opnieuw proberen",
|
||||||
|
"stillFailing": "Nog steeds geen antwoord. Wacht even en probeer opnieuw."
|
||||||
|
}
|
||||||
|
},
|
||||||
"login": {
|
"login": {
|
||||||
"title": "Inloggen",
|
"title": "Inloggen",
|
||||||
"subtitle": "Log in op je SlpModularCms-account",
|
"subtitle": "Log in op je SlpModularCms-account",
|
||||||
|
|||||||
@@ -22,12 +22,15 @@ export type ApiResult<T> = { ok: true; data: T } | { ok: false; error: ProblemDe
|
|||||||
export class ProblemDetailsError extends Error {
|
export class ProblemDetailsError extends Error {
|
||||||
readonly status: number;
|
readonly status: number;
|
||||||
readonly problem: ProblemDetails;
|
readonly problem: ProblemDetails;
|
||||||
|
/** From the Retry-After header (seconds), in milliseconds; undefined when the server did not say. */
|
||||||
|
readonly retryAfterMs?: number;
|
||||||
|
|
||||||
constructor(status: number, problem: ProblemDetails) {
|
constructor(status: number, problem: ProblemDetails, retryAfterMs?: number) {
|
||||||
super(problem.title ?? problem.detail ?? `Request failed with status ${status}`);
|
super(problem.title ?? problem.detail ?? `Request failed with status ${status}`);
|
||||||
this.name = 'ProblemDetailsError';
|
this.name = 'ProblemDetailsError';
|
||||||
this.status = status;
|
this.status = status;
|
||||||
this.problem = problem;
|
this.problem = problem;
|
||||||
|
this.retryAfterMs = retryAfterMs;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -155,13 +158,20 @@ export class ApiClient {
|
|||||||
const problem: ProblemDetails = isProblemDetails(data)
|
const problem: ProblemDetails = isProblemDetails(data)
|
||||||
? data
|
? data
|
||||||
: { status: response.status, title: response.statusText };
|
: { status: response.status, title: response.statusText };
|
||||||
throw new ProblemDetailsError(response.status, problem);
|
throw new ProblemDetailsError(response.status, problem, parseRetryAfter(response.headers.get('Retry-After')));
|
||||||
}
|
}
|
||||||
|
|
||||||
return data as T;
|
return data as T;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Retry-After as delay-seconds (the only form a rate limiter sends); anything else is ignored. */
|
||||||
|
function parseRetryAfter(value: string | null): number | undefined {
|
||||||
|
if (value === null) return undefined;
|
||||||
|
const seconds = Number(value);
|
||||||
|
return Number.isFinite(seconds) && seconds >= 0 ? Math.round(seconds * 1000) : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
function safeJsonParse(text: string): unknown {
|
function safeJsonParse(text: string): unknown {
|
||||||
try {
|
try {
|
||||||
return JSON.parse(text);
|
return JSON.parse(text);
|
||||||
|
|||||||
@@ -11,3 +11,12 @@ export const refreshBackoff = { delays: [400, 1200, 2500] as number[] };
|
|||||||
export function isAuthRejection(error: unknown): boolean {
|
export function isAuthRejection(error: unknown): boolean {
|
||||||
return error instanceof ProblemDetailsError && (error.status === 400 || error.status === 401 || error.status === 403);
|
return error instanceof ProblemDetailsError && (error.status === 400 || error.status === 401 || error.status === 403);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Longest a server's Retry-After is honoured at start-up; a longer wait is left to the visitor's retry button. */
|
||||||
|
export const maxRetryAfterMs = 15000;
|
||||||
|
|
||||||
|
/** How long to wait before the next quiet start-up retry: the planned backoff, or the server's Retry-After if longer. */
|
||||||
|
export function nextRetryDelay(error: unknown, planned: number): number {
|
||||||
|
const asked = error instanceof ProblemDetailsError ? error.retryAfterMs : undefined;
|
||||||
|
return asked === undefined ? planned : Math.max(planned, Math.min(asked, maxRetryAfterMs));
|
||||||
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import '@theme';
|
|||||||
import './i18n/config';
|
import './i18n/config';
|
||||||
import { AuthProvider } from '@/features/auth/context/AuthProvider';
|
import { AuthProvider } from '@/features/auth/context/AuthProvider';
|
||||||
import { useAuth } from '@/features/auth/context/auth-context';
|
import { useAuth } from '@/features/auth/context/auth-context';
|
||||||
|
import { SessionUnreachable } from '@/features/auth/components/SessionUnreachable';
|
||||||
import { Toaster } from '@/components/ui/sonner';
|
import { Toaster } from '@/components/ui/sonner';
|
||||||
import { router } from '@/router';
|
import { router } from '@/router';
|
||||||
import { getAppConfig } from '@/lib/config';
|
import { getAppConfig } from '@/lib/config';
|
||||||
@@ -44,6 +45,9 @@ function InnerApp() {
|
|||||||
if (auth.status === 'loading') {
|
if (auth.status === 'loading') {
|
||||||
return <BootstrapSplash />;
|
return <BootstrapSplash />;
|
||||||
}
|
}
|
||||||
|
if (auth.status === 'unreachable') {
|
||||||
|
return <SessionUnreachable />;
|
||||||
|
}
|
||||||
return <RouterProvider router={router} context={{ auth }} />;
|
return <RouterProvider router={router} context={{ auth }} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
using System.Net;
|
||||||
|
using FluentAssertions;
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
using Microsoft.AspNetCore.Hosting;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.AspNetCore.RateLimiting;
|
||||||
|
using Microsoft.AspNetCore.TestHost;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
|
using SlpModularCms.Core.Hosting;
|
||||||
|
|
||||||
|
namespace SlpModularCms.Core.Tests.Hosting;
|
||||||
|
|
||||||
|
/// <summary>A rate-limited call says how long to wait (Retry-After), so the admin app's start-up retries do not hammer the same window.</summary>
|
||||||
|
public class RateLimitRetryAfterTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task ARejectedCall_Is429_WithARetryAfterInWholeSeconds()
|
||||||
|
{
|
||||||
|
var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
|
||||||
|
{
|
||||||
|
["RateLimiting:Refresh:PermitLimit"] = "1",
|
||||||
|
["RateLimiting:Refresh:WindowSeconds"] = "60"
|
||||||
|
}).Build();
|
||||||
|
|
||||||
|
using var host = await new HostBuilder().ConfigureWebHost(web =>
|
||||||
|
{
|
||||||
|
web.UseTestServer();
|
||||||
|
web.ConfigureServices(s =>
|
||||||
|
{
|
||||||
|
s.AddLogging();
|
||||||
|
s.AddRouting();
|
||||||
|
s.AddCmsRateLimiting(config);
|
||||||
|
});
|
||||||
|
web.Configure(app =>
|
||||||
|
{
|
||||||
|
app.UseRouting();
|
||||||
|
app.UseRateLimiter();
|
||||||
|
app.UseEndpoints(e => e.MapPost("/refresh", () => "ok").RequireRateLimiting("refresh"));
|
||||||
|
});
|
||||||
|
}).StartAsync();
|
||||||
|
var client = host.GetTestClient();
|
||||||
|
|
||||||
|
(await client.PostAsync("/refresh", null)).StatusCode.Should().Be(HttpStatusCode.OK);
|
||||||
|
var rejected = await client.PostAsync("/refresh", null);
|
||||||
|
|
||||||
|
rejected.StatusCode.Should().Be(HttpStatusCode.TooManyRequests);
|
||||||
|
rejected.Headers.RetryAfter.Should().NotBeNull();
|
||||||
|
rejected.Headers.RetryAfter!.Delta!.Value.TotalSeconds.Should().BeGreaterThanOrEqualTo(1).And.BeLessThanOrEqualTo(60);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -183,6 +183,29 @@ public static class ServiceCollectionExtensions
|
|||||||
.GetMetadata<EnableRateLimitingAttribute>()?.PolicyName ?? "(unknown)",
|
.GetMetadata<EnableRateLimitingAttribute>()?.PolicyName ?? "(unknown)",
|
||||||
context.HttpContext.Request.Path);
|
context.HttpContext.Request.Path);
|
||||||
|
|
||||||
|
// Tells a well-behaved client (the admin app's start-up retries) how long to wait, instead of
|
||||||
|
// having it retry into the same window and stay limited.
|
||||||
|
// A sliding-window lease carries no RetryAfter, so the "refresh" policy falls back to one segment
|
||||||
|
// (a quarter of the window: the earliest moment a permit frees up); other policies to their window.
|
||||||
|
var policyName = context.HttpContext.GetEndpoint()?.Metadata.GetMetadata<EnableRateLimitingAttribute>()?.PolicyName;
|
||||||
|
var section = policyName switch
|
||||||
|
{
|
||||||
|
"login" => "Login",
|
||||||
|
"refresh" => "Refresh",
|
||||||
|
_ => null
|
||||||
|
};
|
||||||
|
double? waitSeconds = null;
|
||||||
|
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
|
||||||
|
waitSeconds = retryAfter.TotalSeconds;
|
||||||
|
else if (section is not null)
|
||||||
|
{
|
||||||
|
var window = configuration.GetValue<int>($"RateLimiting:{section}:WindowSeconds", 60);
|
||||||
|
waitSeconds = policyName == "refresh" ? window / 4.0 : window;
|
||||||
|
}
|
||||||
|
if (waitSeconds is not null)
|
||||||
|
context.HttpContext.Response.Headers.RetryAfter =
|
||||||
|
Math.Max(1, (int)Math.Ceiling(waitSeconds.Value)).ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
return ValueTask.CompletedTask;
|
return ValueTask.CompletedTask;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user