Makes the application say what it is doing and when it fails
U4. Console logging plus Sentry, a same-origin tunnel so ad blockers cannot silence browser errors, Umami on the admin SPA, and six security events that alert rules can actually be built on. The correlation id is the W3C trace id from the ambient Activity, enabled by one line of ActivityTrackingOptions so every entry from every category carries it without touching a call site. It propagates across the master/slave boundary via traceparent, which TraceIdentifier cannot do at all, and it is the same value ProblemDetails already returns to the browser. The security events use source-generated LoggerMessage with constant templates. Sentry groups log events by message, so interpolating an email address would give every address its own issue and "more than 20 failed logins in five minutes" could never fire — the events would arrive, be visible, be tagged, and the alerting would silently be impossible. A test asserts the rendered message is identical across argument values. Scrubbing happens in-process, before transmission, and covers Set-Cookie as well as Cookie: the login response issues the refreshToken there, so scrubbing only the request side would protect nothing. Transactions are scrubbed too, because they carry request data and are the channel nobody thinks of. The tunnel derives its destination from the DSN once at startup and reads nothing from the request, which is what separates a tunnel from a server-side request forgery primitive. Size is capped by a bounded read rather than by trusting Content-Length, and the endpoint is rate limited. Two things found along the way. Zod 4's url() hands the value to the URL constructor, which accepts any scheme — so the existing frontend validation would have accepted the exact "htp://" typo BR-U4-24 names, and the SPA would have called a nonexistent origin. Now constrained to http(s). And the new appsettings comments are verified against the real configuration provider, because the failure mode if it rejected them is both hosts refusing to start after a release switch. One deviation. IAdminTokenValidator was meant to gain a reason-reporting overload; implemented that way, a substitute returning false by default silently inverted the access decision while both methods compiled. Two methods whose difference is invisible at the call site is the defect, so it is now a single Validate returning AdminTokenResult. Touches two files from already-committed units: DatabaseMigrationExtensions (U2) gains a flush before the rethrow, or the one Critical event in the system dies with the process; AdminTokenValidator (U1) classifies why a bypass was refused. Build 0 errors; 366 backend tests pass, up from 315, and 237 frontend tests, up from 213. tsc clean, eslint clean on every changed file. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HHoJpxYXzHACSQguHrC5fw
This commit is contained in:
@@ -183,4 +183,31 @@ describe('ApiClient', () => {
|
||||
const client = makeClient();
|
||||
await expect(client.get('/network-fail')).rejects.toThrow(NetworkError);
|
||||
});
|
||||
|
||||
/**
|
||||
* Same-origin is the production configuration, and the one nobody runs locally — so it is
|
||||
* only ever exercised here. Note the URL must come out as a plain relative path: any code
|
||||
* building it with `new URL(path, base)` or an interpolated slash would break on an empty
|
||||
* base, and would break only in production.
|
||||
*/
|
||||
describe('with an empty base URL (same-origin)', () => {
|
||||
it('issues requests against relative paths', async () => {
|
||||
let seenUrl: string | null = null;
|
||||
server.use(
|
||||
http.get('/api/v1/System/capabilities', ({ request }) => {
|
||||
seenUrl = request.url;
|
||||
return HttpResponse.json({ modules: [] });
|
||||
}),
|
||||
);
|
||||
|
||||
const client = new ApiClient('');
|
||||
const result = await client.get<{ modules: string[] }>(
|
||||
'/api/v1/System/capabilities',
|
||||
);
|
||||
|
||||
expect(result).toEqual({ modules: [] });
|
||||
expect(seenUrl).toContain('/api/v1/System/capabilities');
|
||||
expect(seenUrl).not.toContain('//api/v1');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { getAppConfig, resetAppConfigCache } from '@/lib/config';
|
||||
|
||||
/**
|
||||
* The empty-base case is the production configuration, and the one nobody runs locally — so it is
|
||||
* only ever exercised here. A malformed value must still be rejected: relaxing validation to
|
||||
* permit "" is not the same as removing it.
|
||||
*/
|
||||
describe('getAppConfig', () => {
|
||||
const originalEnv = { ...import.meta.env };
|
||||
|
||||
beforeEach(() => {
|
||||
resetAppConfigCache();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
resetAppConfigCache();
|
||||
Object.assign(import.meta.env, originalEnv);
|
||||
});
|
||||
|
||||
it('resolves an absent API base URL to same-origin', () => {
|
||||
vi.stubEnv('VITE_API_BASE_URL', undefined as unknown as string);
|
||||
|
||||
expect(getAppConfig().apiBaseUrl).toBe('');
|
||||
});
|
||||
|
||||
it('resolves an empty API base URL to same-origin', () => {
|
||||
vi.stubEnv('VITE_API_BASE_URL', '');
|
||||
|
||||
expect(getAppConfig().apiBaseUrl).toBe('');
|
||||
});
|
||||
|
||||
it('keeps an explicit absolute URL, so local master/slave development is unaffected', () => {
|
||||
vi.stubEnv('VITE_API_BASE_URL', 'https://localhost:7221');
|
||||
|
||||
expect(getAppConfig().apiBaseUrl).toBe('https://localhost:7221');
|
||||
});
|
||||
|
||||
it('warns in development about a malformed API base URL rather than accepting it silently', () => {
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
vi.stubEnv('VITE_API_BASE_URL', 'htp://localhost:7221');
|
||||
|
||||
getAppConfig();
|
||||
|
||||
expect(warn).toHaveBeenCalled();
|
||||
warn.mockRestore();
|
||||
});
|
||||
|
||||
it('does not warn about an empty API base URL', () => {
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
vi.stubEnv('VITE_API_BASE_URL', '');
|
||||
|
||||
getAppConfig();
|
||||
|
||||
expect(warn).not.toHaveBeenCalled();
|
||||
warn.mockRestore();
|
||||
});
|
||||
|
||||
it('exposes the observability values', () => {
|
||||
vi.stubEnv('VITE_SENTRY_DSN', 'https://abc@host.sentry.io/42');
|
||||
vi.stubEnv('VITE_APP_ENV', 'test');
|
||||
vi.stubEnv('VITE_UMAMI_SCRIPT_URL', 'https://analytics.example.com/script.js');
|
||||
vi.stubEnv('VITE_UMAMI_WEBSITE_ID', 'site-id');
|
||||
|
||||
const config = getAppConfig();
|
||||
|
||||
expect(config.sentryDsn).toBe('https://abc@host.sentry.io/42');
|
||||
expect(config.appEnv).toBe('test');
|
||||
expect(config.umamiScriptUrl).toBe('https://analytics.example.com/script.js');
|
||||
expect(config.umamiWebsiteId).toBe('site-id');
|
||||
});
|
||||
|
||||
it('leaves the observability values undefined when nothing is configured', () => {
|
||||
vi.stubEnv('VITE_SENTRY_DSN', undefined as unknown as string);
|
||||
vi.stubEnv('VITE_UMAMI_WEBSITE_ID', undefined as unknown as string);
|
||||
|
||||
const config = getAppConfig();
|
||||
|
||||
expect(config.sentryDsn).toBeUndefined();
|
||||
expect(config.umamiWebsiteId).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -6,8 +6,21 @@ import { z } from 'zod';
|
||||
* once and only warns in development — production trusts the build-time env.
|
||||
*/
|
||||
const configSchema = z.object({
|
||||
apiBaseUrl: z.string().url(),
|
||||
// Relaxed by exactly one case, not loosened: the empty string means same-origin, and
|
||||
// everything else must still be a valid absolute http(s) URL. A typo such as
|
||||
// 'htp://localhost:7221' has to stay a failure, or the SPA silently issues requests to a
|
||||
// nonexistent origin — which looks exactly like the API being down.
|
||||
//
|
||||
// The protocol constraint is not decoration. Zod 4's url() validates by handing the value to
|
||||
// the URL constructor, which happily accepts ANY scheme — 'htp://localhost:7221' and
|
||||
// 'ftp://x.nl' both pass a bare .url(). The scheme typo this rule exists to catch was
|
||||
// therefore never actually caught before this constraint was added.
|
||||
apiBaseUrl: z.union([z.literal(''), z.url({ protocol: /^https?$/ })]),
|
||||
appTitle: z.string(),
|
||||
sentryDsn: z.string().optional(),
|
||||
appEnv: z.string().optional(),
|
||||
umamiScriptUrl: z.string().optional(),
|
||||
umamiWebsiteId: z.string().optional(),
|
||||
});
|
||||
|
||||
export type AppConfig = z.infer<typeof configSchema>;
|
||||
@@ -20,8 +33,16 @@ export function getAppConfig(): AppConfig {
|
||||
}
|
||||
|
||||
const raw: AppConfig = {
|
||||
apiBaseUrl: import.meta.env.VITE_API_BASE_URL,
|
||||
// Absent or empty means same-origin: requests use relative paths, which is the intended
|
||||
// production configuration now that the API and this SPA are served by one process. An
|
||||
// explicit absolute URL is still honoured, so local development against
|
||||
// https://localhost:7221 (master) and :7222 (slave) keeps working unchanged.
|
||||
apiBaseUrl: import.meta.env.VITE_API_BASE_URL ?? '',
|
||||
appTitle: import.meta.env.VITE_APP_TITLE ?? 'SlpModularCms',
|
||||
sentryDsn: import.meta.env.VITE_SENTRY_DSN,
|
||||
appEnv: import.meta.env.VITE_APP_ENV,
|
||||
umamiScriptUrl: import.meta.env.VITE_UMAMI_SCRIPT_URL,
|
||||
umamiWebsiteId: import.meta.env.VITE_UMAMI_WEBSITE_ID,
|
||||
};
|
||||
|
||||
if (import.meta.env.DEV) {
|
||||
@@ -35,3 +56,8 @@ export function getAppConfig(): AppConfig {
|
||||
cached = raw;
|
||||
return cached;
|
||||
}
|
||||
|
||||
/** Test-only: clears the memoised configuration so a different env can be observed. */
|
||||
export function resetAppConfigCache(): void {
|
||||
cached = null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import * as Sentry from '@sentry/react';
|
||||
import { SENTRY_TUNNEL_PATH, initSentry } from '@/lib/sentry';
|
||||
import { resetAppConfigCache } from '@/lib/config';
|
||||
|
||||
// ESM namespace objects are not configurable, so Sentry.init cannot be spied on in place.
|
||||
vi.mock('@sentry/react', () => ({ init: vi.fn() }));
|
||||
|
||||
const init = vi.mocked(Sentry.init);
|
||||
|
||||
describe('initSentry', () => {
|
||||
beforeEach(() => {
|
||||
resetAppConfigCache();
|
||||
init.mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
resetAppConfigCache();
|
||||
});
|
||||
|
||||
it('does nothing without a DSN, so local development is unaffected', () => {
|
||||
vi.stubEnv('VITE_SENTRY_DSN', undefined as unknown as string);
|
||||
|
||||
initSentry();
|
||||
|
||||
expect(init).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does nothing when the DSN is an empty string', () => {
|
||||
vi.stubEnv('VITE_SENTRY_DSN', '');
|
||||
|
||||
initSentry();
|
||||
|
||||
expect(init).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
/**
|
||||
* The tunnel is the whole reason browser reporting survives an ad blocker: a direct ingest URL
|
||||
* is blocked with ERR_BLOCKED_BY_CLIENT, losing errors precisely for the users who have one.
|
||||
*/
|
||||
it('routes through the same-origin tunnel rather than a Sentry ingest URL', () => {
|
||||
vi.stubEnv('VITE_SENTRY_DSN', 'https://abc@o1.ingest.de.sentry.io/42');
|
||||
|
||||
initSentry();
|
||||
|
||||
expect(init).toHaveBeenCalledOnce();
|
||||
const options = init.mock.calls[0][0]!;
|
||||
expect(options.tunnel).toBe(SENTRY_TUNNEL_PATH);
|
||||
expect(options.tunnel).not.toContain('sentry.io');
|
||||
});
|
||||
|
||||
it('tags the environment and the release, and keeps PII off', () => {
|
||||
vi.stubEnv('VITE_SENTRY_DSN', 'https://abc@o1.ingest.de.sentry.io/42');
|
||||
vi.stubEnv('VITE_APP_ENV', 'test');
|
||||
|
||||
initSentry();
|
||||
|
||||
const options = init.mock.calls[0][0]!;
|
||||
expect(options.environment).toBe('test');
|
||||
expect(options.release).toBeTruthy();
|
||||
// False on the frontend even though the backend enables it with scrubbing: the browser
|
||||
// offers no equivalent in-process guarantee, and there is nothing here the backend cannot
|
||||
// already report.
|
||||
expect(options.sendDefaultPii).toBe(false);
|
||||
});
|
||||
|
||||
it('uses the same tunnel path the API serves and the dev proxy mirrors', () => {
|
||||
expect(SENTRY_TUNNEL_PATH).toBe('/sentry-tunnel');
|
||||
expect(SENTRY_TUNNEL_PATH).not.toMatch(/^\/api\//);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import * as Sentry from '@sentry/react';
|
||||
import { getAppConfig } from '@/lib/config';
|
||||
|
||||
/** Same-origin path served by the API (see SentryTunnelExtensions). */
|
||||
export const SENTRY_TUNNEL_PATH = '/sentry-tunnel';
|
||||
|
||||
/**
|
||||
* Initialises Sentry, or does nothing when no DSN is configured.
|
||||
*
|
||||
* Called first from main.tsx, before the query client and before render, so an error during
|
||||
* startup is still captured.
|
||||
*/
|
||||
export function initSentry(): void {
|
||||
const { sentryDsn, appEnv } = getAppConfig();
|
||||
|
||||
// Local development and any deployment without Sentry must work unchanged.
|
||||
if (!sentryDsn) {
|
||||
return;
|
||||
}
|
||||
|
||||
Sentry.init({
|
||||
dsn: sentryDsn,
|
||||
environment: appEnv,
|
||||
release: __APP_VERSION__,
|
||||
// Sentry's free plan counts transactions against the same quota as errors, and this
|
||||
// setup's value is in errors rather than performance traces.
|
||||
tracesSampleRate: 0.1,
|
||||
// False here even though the backend enables it with scrubbing: the backend can scrub
|
||||
// in-process before transmission because it controls the send, and in the browser there
|
||||
// is no equivalent guarantee. The frontend has nothing to add that the backend cannot
|
||||
// already report, so there is no reason to accept the risk.
|
||||
sendDefaultPii: false,
|
||||
// Ad blockers block requests to *.ingest.sentry.io outright (ERR_BLOCKED_BY_CLIENT),
|
||||
// because they look like third-party tracking. Without this, errors are lost precisely
|
||||
// for the users who have an ad blocker — a silently biased sample of exactly the group
|
||||
// most likely to have browser oddities. The API forwards the envelope onward; the
|
||||
// destination is derived from its own DSN, so nothing here needs a project id.
|
||||
tunnel: SENTRY_TUNNEL_PATH,
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user