diff --git a/.gitea/workflows/ci.yaml b/.gitea/workflows/ci.yaml index 2aff002..d9c6049 100644 --- a/.gitea/workflows/ci.yaml +++ b/.gitea/workflows/ci.yaml @@ -157,7 +157,7 @@ jobs: # Log dump must precede teardown (which removes the containers). - name: Dump container logs on failure if: failure() - run: docker compose -f infra/docker-compose.yml logs --no-color --tail=100 oz-init openzaak nrc-init nrc-web nrc-celery nrc-beat flowable-db flowable-rest flowable-init keycloak acl bff domain projection-db event-subscriber projection-api self-service 2>&1 || true + run: docker compose -f infra/docker-compose.yml logs --no-color --tail=100 oz-init openzaak nrc-init nrc-web nrc-celery nrc-beat flowable-db flowable-rest flowable-init keycloak acl bff domain projection-db event-subscriber projection-api self-service openbaar behandel 2>&1 || true - name: Tear down if: always() run: make down diff --git a/Makefile b/Makefile index d785565..40b9403 100644 --- a/Makefile +++ b/Makefile @@ -10,7 +10,7 @@ COMPOSE := infra/docker-compose.yml # Long-running services with a healthcheck — the smoke polls these for readiness # (infra/wait-healthy.sh). One-shot init jobs (oz-init, nrc-init, flowable-init) # are not polled; they only need to have run. See docs/runbooks/gitea-actions-gotchas.md. -WAIT_SVCS := openzaak nrc-web acl bff domain event-subscriber projection-api self-service openbaar +WAIT_SVCS := openzaak nrc-web acl bff domain event-subscriber projection-api self-service openbaar behandel # Config files (OpenZaak data.yaml, Keycloak realms, Flowable BPMN) are streamed # into external named volumes via `docker cp` (infra/seed-config.sh) instead of # bind-mounted, because bind mounts don't reach sibling containers on the diff --git a/apps/behandel/Dockerfile b/apps/behandel/Dockerfile new file mode 100644 index 0000000..a25680b --- /dev/null +++ b/apps/behandel/Dockerfile @@ -0,0 +1,23 @@ +# Multi-stage build for the behandel portal (Angular → nginx). +# Build context is the repo root (the app needs the pnpm workspace + libs). See infra/docker-compose.yml. +FROM node:24-slim AS build +WORKDIR /src +RUN corepack enable && corepack prepare pnpm@11.5.2 --activate + +# Restore first (cached unless the manifests change). +COPY package.json pnpm-lock.yaml pnpm-workspace.yaml nx.json tsconfig.base.json eslint.config.mjs ./ +RUN pnpm install --frozen-lockfile + +# Sources (only what the app + its libs need). +COPY apps/behandel apps/behandel +COPY libs libs +RUN pnpm nx build behandel + +FROM nginx:1.27-alpine AS runtime +COPY apps/behandel/nginx.conf /etc/nginx/conf.d/default.conf +COPY --from=build /src/dist/apps/behandel/browser /usr/share/nginx/html +# Compose-time OIDC config: the browser (Playwright, on the compose network) reaches Keycloak by +# service name, so the token issuer matches the BFF's medewerker authority (host-consistent, ADR-0013). +RUN printf '{ "authority": "http://keycloak:8080/realms/medewerker" }\n' > /usr/share/nginx/html/config.json + +EXPOSE 80 diff --git a/apps/behandel/eslint.config.mjs b/apps/behandel/eslint.config.mjs new file mode 100644 index 0000000..af5ff32 --- /dev/null +++ b/apps/behandel/eslint.config.mjs @@ -0,0 +1,34 @@ +import nx from '@nx/eslint-plugin'; +import baseConfig from '../../eslint.config.mjs'; + +export default [ + ...nx.configs['flat/angular'], + ...nx.configs['flat/angular-template'], + ...baseConfig, + { + files: ['**/*.ts'], + rules: { + '@angular-eslint/directive-selector': [ + 'error', + { + type: 'attribute', + prefix: 'app', + style: 'camelCase', + }, + ], + '@angular-eslint/component-selector': [ + 'error', + { + type: 'element', + prefix: 'app', + style: 'kebab-case', + }, + ], + }, + }, + { + files: ['**/*.html'], + // Override or add rules here + rules: {}, + }, +]; diff --git a/apps/behandel/nginx.conf b/apps/behandel/nginx.conf new file mode 100644 index 0000000..3d6a573 --- /dev/null +++ b/apps/behandel/nginx.conf @@ -0,0 +1,24 @@ +server { + listen 80; + server_name _; + root /usr/share/nginx/html; + index index.html; + + # Resolve the BFF via Docker's embedded DNS at request time (variable proxy_pass), so nginx starts + # even before the BFF is up and picks up restarts — instead of failing to load the config. + resolver 127.0.0.11 ipv6=off valid=30s; + + # Same-origin API: proxy the behandel endpoint group to the bff service. The api-client uses + # relative URLs, so the browser calls this origin and nginx forwards to the BFF — no CORS, and the + # medewerker token (same-origin) is attached by the app's interceptor (ADR-0013). + location /behandel/ { + set $bff http://bff:8080; + proxy_pass $bff; + proxy_set_header Host $host; + } + + # SPA fallback — Angular client-side routing. + location / { + try_files $uri $uri/ /index.html; + } +} diff --git a/apps/behandel/project.json b/apps/behandel/project.json new file mode 100644 index 0000000..4c7a5e2 --- /dev/null +++ b/apps/behandel/project.json @@ -0,0 +1,80 @@ +{ + "name": "behandel", + "$schema": "../../node_modules/nx/schemas/project-schema.json", + "projectType": "application", + "prefix": "app", + "sourceRoot": "apps/behandel/src", + "tags": [], + "targets": { + "build": { + "executor": "@angular/build:application", + "outputs": ["{options.outputPath}"], + "defaultConfiguration": "production", + "options": { + "outputPath": "dist/apps/behandel", + "browser": "apps/behandel/src/main.ts", + "tsConfig": "apps/behandel/tsconfig.app.json", + "assets": [ + { + "glob": "**/*", + "input": "apps/behandel/public" + } + ], + "styles": ["apps/behandel/src/styles.css"] + }, + "configurations": { + "production": { + "budgets": [ + { + "type": "initial", + "maximumWarning": "1mb", + "maximumError": "2mb" + }, + { + "type": "anyComponentStyle", + "maximumWarning": "4kb", + "maximumError": "8kb" + } + ], + "outputHashing": "all" + }, + "development": { + "optimization": false, + "extractLicenses": false, + "sourceMap": true + } + } + }, + "serve": { + "continuous": true, + "executor": "@angular/build:dev-server", + "defaultConfiguration": "development", + "configurations": { + "production": { + "buildTarget": "behandel:build:production" + }, + "development": { + "buildTarget": "behandel:build:development" + } + } + }, + "lint": { + "executor": "@nx/eslint:lint" + }, + "test": { + "executor": "@angular/build:unit-test", + "options": { + "watch": false + } + }, + "serve-static": { + "continuous": true, + "executor": "@nx/web:file-server", + "options": { + "buildTarget": "behandel:build", + "staticFilePath": "dist/apps/behandel/browser", + "spa": true + } + } + } +} diff --git a/apps/behandel/public/config.json b/apps/behandel/public/config.json new file mode 100644 index 0000000..71c0f65 --- /dev/null +++ b/apps/behandel/public/config.json @@ -0,0 +1,3 @@ +{ + "authority": "http://localhost:8180/realms/medewerker" +} diff --git a/apps/behandel/public/favicon.ico b/apps/behandel/public/favicon.ico new file mode 100644 index 0000000..317ebcb Binary files /dev/null and b/apps/behandel/public/favicon.ico differ diff --git a/apps/behandel/src/app/app.config.spec.ts b/apps/behandel/src/app/app.config.spec.ts new file mode 100644 index 0000000..ba0dafc --- /dev/null +++ b/apps/behandel/src/app/app.config.spec.ts @@ -0,0 +1,73 @@ +import { provideHttpClient, withInterceptors } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { TestBed } from '@angular/core/testing'; +import { BffApiV1Service } from 'api-client'; +import { authInterceptor } from 'auth'; +import { AbstractSecurityStorage, ConfigurationService } from 'angular-auth-oidc-client'; +import { SECURE_API_ROUTES } from './app.config'; + +// Guards the medewerker token wiring end-to-end. The api-client calls the BFF with RELATIVE URLs, and +// the angular-auth-oidc-client interceptor attaches the token only when `req.url` starts with a +// configured secureRoute. A regression to an absolute origin makes the relative URL never match, so +// the behandel calls go out unauthenticated and the BFF answers 401. This drives the REAL interceptor +// and the REAL api-client against the REAL production route value (SECURE_API_ROUTES); only the config +// source and token storage are faked, so the assertion turns on the actual route-matching. +describe('behandel medewerker token wiring', () => { + let http: HttpTestingController; + let bff: BffApiV1Service; + const token = 'medewerker-access-token'; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(withInterceptors([authInterceptor()])), + provideHttpClientTesting(), + { + provide: ConfigurationService, + useValue: { + hasAtLeastOneConfig: () => true, + getAllConfigurations: () => [{ configId: 'medewerker', secureRoutes: SECURE_API_ROUTES }], + }, + }, + { + // A signed-in session: the storage the interceptor's token lookup reads from. + provide: AbstractSecurityStorage, + useValue: { + read: () => JSON.stringify({ authzData: token, authnResult: { id_token: 'id-token' } }), + write: () => undefined, + remove: () => undefined, + clear: () => undefined, + }, + }, + ], + }); + http = TestBed.inject(HttpTestingController); + bff = TestBed.inject(BffApiV1Service); + }); + + afterEach(() => http.verify()); + + it('attaches the bearer token to the relative werkbak call', () => { + bff.getBehandelWerkbak().subscribe(); + + const req = http.expectOne('/behandel/werkbak'); + expect(req.request.headers.get('Authorization')).toBe(`Bearer ${token}`); + req.flush([]); + }); + + it('attaches the bearer token to the relative decide call', () => { + bff.postBehandelRegistrationsIdDecide('reg-1', { besluit: 'goedkeuren' }).subscribe(); + + const req = http.expectOne('/behandel/registrations/reg-1/decide'); + expect(req.request.headers.get('Authorization')).toBe(`Bearer ${token}`); + req.flush(null); + }); + + it('leaves the anonymous openbaar register call unauthenticated', () => { + bff.getOpenbaarRegister().subscribe(); + + const req = http.expectOne((r) => r.url === '/openbaar/register'); + expect(req.request.headers.has('Authorization')).toBe(false); + req.flush([]); + }); +}); diff --git a/apps/behandel/src/app/app.config.ts b/apps/behandel/src/app/app.config.ts new file mode 100644 index 0000000..e761d4a --- /dev/null +++ b/apps/behandel/src/app/app.config.ts @@ -0,0 +1,39 @@ +import { provideHttpClient, withInterceptors } from '@angular/common/http'; +import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core'; +import { provideRouter } from '@angular/router'; +import { authInterceptor, provideMedewerkerAuth } from 'auth'; +import { appRoutes } from './app.routes'; + +/** Environment-specific settings fetched from /config.json at startup (see main.ts). */ +export interface RuntimeConfig { + /** The Keycloak `medewerker` realm issuer as the browser reaches it (dev: localhost; compose: keycloak:8080). */ + authority: string; +} + +/** + * Route prefixes whose requests carry the medewerker token. These MUST match the **relative** URLs + * the api-client actually calls (same-origin via the nginx proxy) — the interceptor matches on + * `req.url`, which stays relative, so an absolute origin would never match and the token would go + * unattached. Only `/behandel/` is secured; the app calls no other endpoint group. + */ +export const SECURE_API_ROUTES = ['/behandel/']; + +/** + * Build the app providers from runtime config. `redirectUrl` is the app's own origin (where Keycloak + * redirects back). `secureRoutes` uses {@link SECURE_API_ROUTES} — relative prefixes, not the origin. + */ +export function appConfig(runtime: RuntimeConfig): ApplicationConfig { + const origin = typeof window !== 'undefined' ? window.location.origin : '/'; + return { + providers: [ + provideBrowserGlobalErrorListeners(), + provideRouter(appRoutes), + provideHttpClient(withInterceptors([authInterceptor()])), + provideMedewerkerAuth({ + authority: runtime.authority, + redirectUrl: origin, + secureRoutes: SECURE_API_ROUTES, + }), + ], + }; +} diff --git a/apps/behandel/src/app/app.css b/apps/behandel/src/app/app.css new file mode 100644 index 0000000..e69de29 diff --git a/apps/behandel/src/app/app.html b/apps/behandel/src/app/app.html new file mode 100644 index 0000000..0680b43 --- /dev/null +++ b/apps/behandel/src/app/app.html @@ -0,0 +1 @@ + diff --git a/apps/behandel/src/app/app.routes.ts b/apps/behandel/src/app/app.routes.ts new file mode 100644 index 0000000..07b02f9 --- /dev/null +++ b/apps/behandel/src/app/app.routes.ts @@ -0,0 +1,7 @@ +import { Route } from '@angular/router'; +import { authenticatedGuard } from 'auth'; +import { WerkbakPage } from './werkbak/werkbak-page'; + +export const appRoutes: Route[] = [ + { path: '', component: WerkbakPage, canActivate: [authenticatedGuard] }, +]; diff --git a/apps/behandel/src/app/app.spec.ts b/apps/behandel/src/app/app.spec.ts new file mode 100644 index 0000000..d1010c3 --- /dev/null +++ b/apps/behandel/src/app/app.spec.ts @@ -0,0 +1,15 @@ +import { provideRouter } from '@angular/router'; +import { render, screen } from '@testing-library/angular'; +import { App } from './app'; + +describe('App', () => { + it('renders the router outlet shell', async () => { + const { container } = await render(App, { + providers: [provideRouter([])], + }); + + // The shell is a thin host for routed pages (the WerkbakPage owns the heading). + expect(container.querySelector('router-outlet')).toBeTruthy(); + expect(screen).toBeTruthy(); + }); +}); diff --git a/apps/behandel/src/app/app.ts b/apps/behandel/src/app/app.ts new file mode 100644 index 0000000..f16917f --- /dev/null +++ b/apps/behandel/src/app/app.ts @@ -0,0 +1,12 @@ +import { Component } from '@angular/core'; +import { RouterModule } from '@angular/router'; + +@Component({ + imports: [RouterModule], + selector: 'app-root', + templateUrl: './app.html', + styleUrl: './app.css', +}) +export class App { + protected title = 'behandel'; +} diff --git a/apps/behandel/src/app/werkbak/werkbak-page.html b/apps/behandel/src/app/werkbak/werkbak-page.html new file mode 100644 index 0000000..9693dca --- /dev/null +++ b/apps/behandel/src/app/werkbak/werkbak-page.html @@ -0,0 +1,64 @@ +
+ + Werkbak +

+ Registraties die wachten op beoordeling. Keur elke registratie goed of wijs deze af. +

+ + @if (loading()) { +

Bezig met laden…

+ } @else if (failed()) { +

+ Kon de werkbak niet laden. Controleer of je als behandelaar bent ingelogd en probeer het + opnieuw. +

+ } @else if (loaded() && items().length === 0) { +

De werkbak is leeg.

+ } @else if (items().length > 0) { + + + + + + + + + + + + @for (item of items(); track item.registrationId) { + + + + + + + } + +
+ Registraties in behandeling +
ReferentieBSNStatusActie
{{ item.registrationId }}{{ item.bsn }}{{ item.status }} + + +
+ } +
+
diff --git a/apps/behandel/src/app/werkbak/werkbak-page.spec.ts b/apps/behandel/src/app/werkbak/werkbak-page.spec.ts new file mode 100644 index 0000000..9799845 --- /dev/null +++ b/apps/behandel/src/app/werkbak/werkbak-page.spec.ts @@ -0,0 +1,110 @@ +import { signal } from '@angular/core'; +import { fireEvent, render, screen } from '@testing-library/angular'; +import { of, throwError } from 'rxjs'; +import { BffApiV1Service, type WerkbakItem } from 'api-client'; +import { AuthService } from 'auth'; +import { axe } from 'vitest-axe'; +import { WerkbakPage } from './werkbak-page'; + +const sample: WerkbakItem[] = [ + { registrationId: 'reg-1', bsn: '123456782', status: 'InBehandeling' }, + { registrationId: 'reg-2', bsn: '111222333', status: 'InBehandeling' }, +]; + +class FakeAuth extends AuthService { + readonly isAuthenticated = signal(true); + readonly bsn = signal(undefined); + override readonly roles = signal(['behandelaar']); + login(): void { + /* not exercised here */ + } + logout(): void { + /* spied in tests */ + } +} + +function setup( + overrides: { + getBehandelWerkbak?: ReturnType; + postBehandelRegistrationsIdDecide?: ReturnType; + } = {}, +) { + const getBehandelWerkbak = + overrides.getBehandelWerkbak ?? vi.fn().mockReturnValue(of(sample)); + const postBehandelRegistrationsIdDecide = + overrides.postBehandelRegistrationsIdDecide ?? vi.fn().mockReturnValue(of(undefined)); + return { + getBehandelWerkbak, + postBehandelRegistrationsIdDecide, + providers: [ + { + provide: BffApiV1Service, + useValue: { getBehandelWerkbak, postBehandelRegistrationsIdDecide }, + }, + { provide: AuthService, useClass: FakeAuth }, + ], + }; +} + +describe('WerkbakPage', () => { + it('lists the registrations awaiting beoordeling on open', async () => { + const { getBehandelWerkbak, providers } = setup(); + await render(WerkbakPage, { providers }); + + expect(getBehandelWerkbak).toHaveBeenCalled(); + expect(await screen.findByText('reg-1')).toBeTruthy(); + expect(screen.getByText('123456782')).toBeTruthy(); + expect(screen.getByText('reg-2')).toBeTruthy(); + }); + + it('approves a registration (goedkeuren) and refreshes the werkbak', async () => { + const { getBehandelWerkbak, postBehandelRegistrationsIdDecide, providers } = setup(); + await render(WerkbakPage, { providers }); + + fireEvent.click((await screen.findAllByRole('button', { name: /goedkeuren/i }))[0]); + + expect(postBehandelRegistrationsIdDecide).toHaveBeenCalledWith('reg-1', { + besluit: 'goedkeuren', + }); + // Reloaded after the decision: once on open, once after deciding. + expect(getBehandelWerkbak).toHaveBeenCalledTimes(2); + }); + + it('rejects a registration (afwijzen) via the decide endpoint', async () => { + const { postBehandelRegistrationsIdDecide, providers } = setup(); + await render(WerkbakPage, { providers }); + + fireEvent.click((await screen.findAllByRole('button', { name: /afwijzen/i }))[0]); + + expect(postBehandelRegistrationsIdDecide).toHaveBeenCalledWith('reg-1', { + besluit: 'afwijzen', + }); + }); + + it('shows an empty state when the werkbak has no items', async () => { + const { providers } = setup({ getBehandelWerkbak: vi.fn().mockReturnValue(of([])) }); + await render(WerkbakPage, { providers }); + + expect(await screen.findByText(/werkbak is leeg/i)).toBeTruthy(); + }); + + it('surfaces a load failure instead of swallowing it', async () => { + const { providers } = setup({ + getBehandelWerkbak: vi.fn().mockReturnValue(throwError(() => new Error('403'))), + }); + await render(WerkbakPage, { providers }); + + expect(await screen.findByText(/kon de werkbak niet laden/i)).toBeTruthy(); + }); + + it('has no WCAG 2.1 AA violations', async () => { + document.documentElement.lang = 'nl'; + const { container } = await render(WerkbakPage, { providers: setup().providers }); + + const results = await axe(container, { + runOnly: { type: 'tag', values: ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'] }, + }); + + expect(results.violations).toEqual([]); + }); +}); diff --git a/apps/behandel/src/app/werkbak/werkbak-page.ts b/apps/behandel/src/app/werkbak/werkbak-page.ts new file mode 100644 index 0000000..cc5b8e4 --- /dev/null +++ b/apps/behandel/src/app/werkbak/werkbak-page.ts @@ -0,0 +1,65 @@ +import { Component, inject, signal } from '@angular/core'; +import { BffApiV1Service, type WerkbakItem } from 'api-client'; +import { UtrechtComponentsModule } from 'ui'; + +/** The two decisions a behandelaar can make; the BFF validates these exact values (ADR-0013). */ +type Besluit = 'goedkeuren' | 'afwijzen'; + +/** + * The behandel werkbak: a signed-in behandelaar sees the registrations awaiting beoordeling (the open + * Flowable `Beoordelen` tasks, read through the domain) and decides each — goedkeuren or afwijzen. A + * decision posts to the BFF, which applies the domain transition and completes the workflow task + * (ADR-0013; S-12). After a decision the werkbak refreshes so the handled item drops off the list. + */ +@Component({ + selector: 'app-werkbak-page', + imports: [UtrechtComponentsModule], + templateUrl: './werkbak-page.html', +}) +export class WerkbakPage { + private readonly bff = inject(BffApiV1Service); + + protected readonly items = signal([]); + protected readonly loading = signal(false); + protected readonly loaded = signal(false); + protected readonly failed = signal(false); + protected readonly deciding = signal(undefined); + + constructor() { + this.load(); + } + + load(): void { + this.loading.set(true); + this.failed.set(false); + this.bff.getBehandelWerkbak().subscribe({ + next: (rows: WerkbakItem[]) => { + this.items.set(rows); + this.loading.set(false); + this.loaded.set(true); + }, + // Surface the failure (e.g. 403 for a non-behandelaar) instead of swallowing it. + error: () => { + this.items.set([]); + this.loading.set(false); + this.loaded.set(true); + this.failed.set(true); + }, + }); + } + + decide(registrationId: string, besluit: Besluit): void { + this.deciding.set(registrationId); + this.bff.postBehandelRegistrationsIdDecide(registrationId, { besluit }).subscribe({ + // Refresh so the decided registration drops off the werkbak (its task is now completed). + next: () => { + this.deciding.set(undefined); + this.load(); + }, + error: () => { + this.deciding.set(undefined); + this.failed.set(true); + }, + }); + } +} diff --git a/apps/behandel/src/index.html b/apps/behandel/src/index.html new file mode 100644 index 0000000..c524ad4 --- /dev/null +++ b/apps/behandel/src/index.html @@ -0,0 +1,13 @@ + + + + + Behandelportaal BIG-register + + + + + + + + diff --git a/apps/behandel/src/main.ts b/apps/behandel/src/main.ts new file mode 100644 index 0000000..29b0198 --- /dev/null +++ b/apps/behandel/src/main.ts @@ -0,0 +1,10 @@ +import { bootstrapApplication } from '@angular/platform-browser'; +import { App } from './app/app'; +import { appConfig, type RuntimeConfig } from './app/app.config'; + +// Load environment config before bootstrap so the OIDC authority is set per environment +// (dev: localhost; compose: keycloak:8080) from a single build — 12-factor (S-08d). +fetch('config.json') + .then((response) => response.json() as Promise) + .then((config) => bootstrapApplication(App, appConfig(config))) + .catch((err) => console.error(err)); diff --git a/apps/behandel/src/styles.css b/apps/behandel/src/styles.css new file mode 100644 index 0000000..ade77c5 --- /dev/null +++ b/apps/behandel/src/styles.css @@ -0,0 +1,2 @@ +/* NL Design System theme — Utrecht design tokens (docs/frontend-decisions.md). */ +@import '@utrecht/design-tokens/dist/index.css'; diff --git a/apps/behandel/tsconfig.app.json b/apps/behandel/tsconfig.app.json new file mode 100644 index 0000000..a75ddab --- /dev/null +++ b/apps/behandel/tsconfig.app.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "../../dist/out-tsc", + "types": [] + }, + "include": ["src/**/*.ts"], + "exclude": ["src/**/*.spec.ts", "src/**/*.test.ts"] +} diff --git a/apps/behandel/tsconfig.json b/apps/behandel/tsconfig.json new file mode 100644 index 0000000..bb7614f --- /dev/null +++ b/apps/behandel/tsconfig.json @@ -0,0 +1,31 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "strict": true, + "noImplicitOverride": true, + "noPropertyAccessFromIndexSignature": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true, + "isolatedModules": true, + "target": "es2022", + "moduleResolution": "bundler", + "emitDecoratorMetadata": false, + "module": "preserve" + }, + "angularCompilerOptions": { + "enableI18nLegacyMessageIdFormat": false, + "strictInjectionParameters": true, + "strictInputAccessModifiers": true, + "strictTemplates": true + }, + "files": [], + "include": [], + "references": [ + { + "path": "./tsconfig.app.json" + }, + { + "path": "./tsconfig.spec.json" + } + ] +} diff --git a/apps/behandel/tsconfig.spec.json b/apps/behandel/tsconfig.spec.json new file mode 100644 index 0000000..2d36c49 --- /dev/null +++ b/apps/behandel/tsconfig.spec.json @@ -0,0 +1,8 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "../../dist/out-tsc", + "types": ["vitest/globals"] + }, + "include": ["src/**/*.ts", "src/**/*.d.ts"] +} diff --git a/docs/demo-script.md b/docs/demo-script.md index 2426f9e..8a240f3 100644 --- a/docs/demo-script.md +++ b/docs/demo-script.md @@ -248,3 +248,30 @@ curl -fsS "http://localhost:8140/openbaar/register?q=$ref" | jq > The openbaar register's "Referentie" column and its search now use this reference — the exact value > the citizen saw on submit. Asserted end-to-end by the Playwright happy path. + +## S-12 — Behandel portal: werkbak + beoordeling (#13, ADR-0013) + +A behandelaar now works submitted registrations in a real portal instead of the temporary admin +endpoint. After a citizen submits (as above), the workflow parks the registration at the Flowable +`Beoordelen` user task, and it shows up in the **werkbak**. The behandelaar logs in against the +Keycloak `medewerker` realm and decides — **goedkeuren** (→ INGESCHREVEN via the ACL, per ADR-0011) +or **afwijzen** — which also completes the Beoordelen task so the process advances. + +```text +# 1. Open the behandel portal and log in as a behandelaar (medewerker realm): +# http://localhost:8142/ → merel-behandelaar / test123 +# +# 2. The werkbak lists the registrations awaiting beoordeling (referentie / bsn / status). +# Find the reference from the submit confirmation and click "Goedkeuren" on that row. +# +# 3. The row drops off the werkbak (its Beoordelen task is completed) and the openbaar register +# (http://localhost:8141/) now shows that reference as INGESCHREVEN. +``` + +**The path:** behandel portal → BFF `POST /behandel/registrations/{id}/decide` (behandelaar policy, +`medewerker` realm) → domain applies the decision + completes the Flowable `Beoordelen` task → +ACL → NRC → event-subscriber → projection → openbaar register shows INGESCHREVEN. + +> The full round-trip — DigiD submit → public INGEDIEND → behandelaar goedkeurt in the werkbak → +> public INGESCHREVEN — is the Playwright happy path (`tests/e2e/registration.spec.ts`), which now +> drives the behandel portal in place of the old admin endpoint. diff --git a/docs/frontend-decisions.md b/docs/frontend-decisions.md index 19c65e9..e6a7b11 100644 --- a/docs/frontend-decisions.md +++ b/docs/frontend-decisions.md @@ -117,3 +117,37 @@ with the submit form (S-08c, #67); any deviation from NL DS will be recorded her (id + status); `bsn`/`naam` never leave the BFF. The e2e asserts the bsn never renders. - **Loads on open, filters on search.** `RegisterPage` fetches the full register on construction and re-queries `/openbaar/register?q=` on search — no client-side filtering, the BFF owns the query. + +## Behandel portal (S-12, #13) + +The staff portal where a behandelaar works the **werkbak** (registrations awaiting beoordeling) and +decides each — goedkeuren or afwijzen. `apps/behandel` mirrors `apps/self-service`; the net-new +frontend work is the medewerker realm auth and the werkbak/decide page. Wiring rationale is in +**ADR-0013**; this entry records the frontend-specific choices. + +- **Medewerker realm auth, reusing `libs/auth`.** Staff authenticate against the Keycloak + `medewerker` realm (public client `big-portal`), not `digid`. Rather than fork the auth lib, the + abstract `AuthService` grew a **`roles`/`hasRole` surface** (empty for realms without roles, e.g. + `digid`), and a parallel **`MedewerkerAuthService` + `provideMedewerkerAuth`** were added — same + auth-code + PKCE config, bound to the medewerker realm, reading the nested `realm_access.roles` + claim. The library's own `authInterceptor` attaches the token to the relative `/behandel/` calls + (secure route), exactly as self-service does for `/self-service/`. +- **Roles reach the frontend via a realm mapper.** Keycloak emits realm roles in the access token by + default but not the ID token/userinfo the SPA reads, so the medewerker `big-portal` client gets a + **realm-roles protocol mapper** (`realm_access.roles`, added to id + userinfo tokens). The + **BFF remains the security boundary** (`behandelaar` policy, 401/403 on `/behandel/*`, ADR-0013); + the frontend role signal is for display/UX, and the werkbak page surfaces a load failure (e.g. a + 403 for a non-behandelaar) rather than swallowing it. +- **Same-origin via nginx, like the other portals.** The compose `behandel` image serves the built + app and reverse-proxies `/behandel` to the BFF (relative calls, no CORS). Served on `:8142`, + health-checked over IPv4 (`127.0.0.1`), depends on Keycloak for the medewerker realm. +- **Werkbak = decide-and-refresh.** `WerkbakPage` loads `GET /behandel/werkbak` on open and renders a + row per registration (referentie/bsn/status). Goedkeuren/afwijzen `POST /behandel/registrations/ + {id}/decide` and then reload the werkbak, so the handled item drops off (its Flowable `Beoordelen` + task is completed). Per-row decide buttons carry an `aria-label` including the reference, so the + e2e (and screen readers) can target a specific registration in a shared werkbak. +- **Testing.** Component tests use `@testing-library/angular` with `BffApiV1Service`/`AuthService` + mocked and the axe WCAG 2.1 AA check; an `app.config.spec` drives the real interceptor + api-client + to assert the medewerker token attaches to `/behandel/*` (and not to the anonymous openbaar call). + The full DigiD-submit → behandel-decide → public INGESCHREVEN round-trip is the Playwright happy + path. diff --git a/infra/docker-compose.yml b/infra/docker-compose.yml index c107ca0..1142dd5 100644 --- a/infra/docker-compose.yml +++ b/infra/docker-compose.yml @@ -486,6 +486,29 @@ services: condition: service_healthy networks: [cg] + # The behandel portal: nginx serves the Angular app and reverse-proxies /behandel to the BFF. + # Behandelaars log in against the Keycloak medewerker realm (ADR-0013; S-12). + behandel: + build: + context: .. + dockerfile: apps/behandel/Dockerfile + image: register-referentie/behandel:dev + ports: + - "8142:80" + healthcheck: + # 127.0.0.1, not localhost: nginx listens on IPv4 only, but localhost resolves to ::1 first. + test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1/ || exit 1"] + interval: 5s + timeout: 3s + retries: 5 + start_period: 10s + depends_on: + bff: + condition: service_healthy + keycloak: + condition: service_started + networks: [cg] + volumes: oz-db: nrc-db: diff --git a/infra/keycloak/realms/medewerker-realm.json b/infra/keycloak/realms/medewerker-realm.json index 40ab79a..d56b6d7 100644 --- a/infra/keycloak/realms/medewerker-realm.json +++ b/infra/keycloak/realms/medewerker-realm.json @@ -16,7 +16,22 @@ "standardFlowEnabled": true, "directAccessGrantsEnabled": true, "redirectUris": ["*"], - "webOrigins": ["*"] + "webOrigins": ["*"], + "protocolMappers": [ + { + "name": "realm roles", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-realm-role-mapper", + "config": { + "multivalued": "true", + "claim.name": "realm_access.roles", + "jsonType.label": "String", + "id.token.claim": "true", + "access.token.claim": "true", + "userinfo.token.claim": "true" + } + } + ] } ], "users": [ diff --git a/libs/auth/src/index.ts b/libs/auth/src/index.ts index 81eef46..a821e0f 100644 --- a/libs/auth/src/index.ts +++ b/libs/auth/src/index.ts @@ -1,4 +1,6 @@ export * from './lib/auth.service'; export * from './lib/digid-auth.service'; export * from './lib/digid-auth.providers'; +export * from './lib/medewerker-auth.service'; +export * from './lib/medewerker-auth.providers'; export * from './lib/authenticated.guard'; diff --git a/libs/auth/src/lib/auth.service.ts b/libs/auth/src/lib/auth.service.ts index 605608c..e3023ec 100644 --- a/libs/auth/src/lib/auth.service.ts +++ b/libs/auth/src/lib/auth.service.ts @@ -1,16 +1,26 @@ -import { Signal } from '@angular/core'; +import { signal, Signal } from '@angular/core'; /** * The portal's view of the signed-in user. An abstraction over the OIDC library so components and - * guards depend on a small, mockable surface (the real implementation is DigiadAuthService). + * guards depend on a small, mockable surface (the real implementations are DigiadAuthService for + * citizens and MedewerkerAuthService for staff). */ export abstract class AuthService { - /** Whether a DigiD session is active. */ + /** Whether a session is active. */ abstract readonly isAuthenticated: Signal; - /** The citizen-service number from the DigiD token, once authenticated. */ + /** The citizen-service number from the DigiD token, once authenticated (staff have none). */ abstract readonly bsn: Signal; - /** Start the DigiD login (redirects to Keycloak). */ + /** + * The realm roles carried in the token. Empty for realms that don't grant roles (e.g. `digid`); + * the `medewerker` realm carries `behandelaar`/`teamlead`. + */ + readonly roles: Signal = signal([]); + /** Start login (redirects to Keycloak). */ abstract login(): void; /** End the session. */ abstract logout(): void; + /** Whether the signed-in user holds the given realm role. */ + hasRole(role: string): boolean { + return this.roles().includes(role); + } } diff --git a/libs/auth/src/lib/medewerker-auth.providers.ts b/libs/auth/src/lib/medewerker-auth.providers.ts new file mode 100644 index 0000000..ccd0d9c --- /dev/null +++ b/libs/auth/src/lib/medewerker-auth.providers.ts @@ -0,0 +1,49 @@ +import { EnvironmentProviders, makeEnvironmentProviders } from '@angular/core'; +import { LogLevel, provideAuth, withAppInitializerAuthCheck } from 'angular-auth-oidc-client'; +import { AuthService } from './auth.service'; +import { MedewerkerAuthService } from './medewerker-auth.service'; + +export interface MedewerkerAuthOptions { + /** The Keycloak `medewerker` realm issuer, as reachable from the browser. */ + authority: string; + /** Where Keycloak redirects back to after login (usually the app origin). */ + redirectUrl: string; + /** + * Route prefixes whose requests get the bearer token attached. The api-client calls the BFF with + * **relative** URLs (same-origin via the nginx proxy), so these must be relative path prefixes + * (e.g. `/behandel/`) — angular-auth-oidc-client matches `req.url.startsWith(route)`, and a + * relative `req.url` never starts with an absolute origin. + */ + secureRoutes: string[]; +} + +/** + * Configure medewerker login (Keycloak `medewerker` realm, public client `big-portal`, auth-code + + * PKCE) and bind {@link AuthService} to the medewerker-backed implementation. Register + * {@link authInterceptor} (re-exported from digid-auth.providers) in the app's HttpClient so BFF + * calls carry the token. + */ +export function provideMedewerkerAuth(options: MedewerkerAuthOptions): EnvironmentProviders { + return makeEnvironmentProviders([ + provideAuth( + { + config: { + authority: options.authority, + redirectUrl: options.redirectUrl, + postLogoutRedirectUri: options.redirectUrl, + clientId: 'big-portal', + scope: 'openid profile', + responseType: 'code', + silentRenew: true, + useRefreshToken: true, + secureRoutes: options.secureRoutes, + logLevel: LogLevel.Warn, + }, + }, + // Run checkAuth() at startup so the login callback (?code=…) is processed before the router + // and guard run — without it the guard sees "not authenticated" and re-triggers login (loop). + withAppInitializerAuthCheck(), + ), + { provide: AuthService, useClass: MedewerkerAuthService }, + ]); +} diff --git a/libs/auth/src/lib/medewerker-auth.service.spec.ts b/libs/auth/src/lib/medewerker-auth.service.spec.ts new file mode 100644 index 0000000..503a304 --- /dev/null +++ b/libs/auth/src/lib/medewerker-auth.service.spec.ts @@ -0,0 +1,43 @@ +import { TestBed } from '@angular/core/testing'; +import { OidcSecurityService } from 'angular-auth-oidc-client'; +import { of } from 'rxjs'; +import { MedewerkerAuthService } from './medewerker-auth.service'; + +function makeService(userData: unknown, authenticated = true) { + const oidc = { + isAuthenticated$: of({ isAuthenticated: authenticated }), + userData$: of({ userData }), + authorize: vi.fn(), + logoff: vi.fn(() => of(null)), + }; + TestBed.configureTestingModule({ + providers: [MedewerkerAuthService, { provide: OidcSecurityService, useValue: oidc }], + }); + return { svc: TestBed.inject(MedewerkerAuthService), oidc }; +} + +describe('MedewerkerAuthService', () => { + it('exposes the realm roles carried in the token', () => { + const { svc } = makeService({ realm_access: { roles: ['behandelaar', 'teamlead'] } }); + expect(svc.roles()).toEqual(['behandelaar', 'teamlead']); + expect(svc.hasRole('behandelaar')).toBe(true); + expect(svc.hasRole('beheerder')).toBe(false); + }); + + it('has no roles when the token omits realm_access', () => { + const { svc } = makeService({ preferred_username: 'merel-behandelaar' }); + expect(svc.roles()).toEqual([]); + expect(svc.hasRole('behandelaar')).toBe(false); + }); + + it('reflects the OIDC authenticated state', () => { + const { svc } = makeService({}, true); + expect(svc.isAuthenticated()).toBe(true); + }); + + it('starts login by delegating to the OIDC library', () => { + const { svc, oidc } = makeService({}); + svc.login(); + expect(oidc.authorize).toHaveBeenCalledTimes(1); + }); +}); diff --git a/libs/auth/src/lib/medewerker-auth.service.ts b/libs/auth/src/lib/medewerker-auth.service.ts new file mode 100644 index 0000000..5ffab98 --- /dev/null +++ b/libs/auth/src/lib/medewerker-auth.service.ts @@ -0,0 +1,41 @@ +import { inject, Injectable, Signal } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { OidcSecurityService } from 'angular-auth-oidc-client'; +import { map } from 'rxjs'; +import { AuthService } from './auth.service'; + +/** The subset of the medewerker token the portal reads: Keycloak nests realm roles here. */ +interface MedewerkerClaims { + realm_access?: { roles?: string[] }; +} + +/** Medewerker-backed AuthService over angular-auth-oidc-client (Keycloak `medewerker` realm). */ +@Injectable() +export class MedewerkerAuthService extends AuthService { + private readonly oidc = inject(OidcSecurityService); + + readonly isAuthenticated: Signal = toSignal( + this.oidc.isAuthenticated$.pipe(map((result) => result.isAuthenticated)), + { initialValue: false }, + ); + + // Staff have no BSN; the abstract surface keeps this present for the shared guard/interceptor. + readonly bsn: Signal = toSignal(this.oidc.userData$.pipe(map(() => undefined)), { + initialValue: undefined, + }); + + override readonly roles: Signal = toSignal( + this.oidc.userData$.pipe( + map((data) => (data.userData as MedewerkerClaims | null)?.realm_access?.roles ?? []), + ), + { initialValue: [] }, + ); + + override login(): void { + this.oidc.authorize(); + } + + override logout(): void { + this.oidc.logoff().subscribe(); + } +} diff --git a/tests/e2e/playwright.config.ts b/tests/e2e/playwright.config.ts index 6f6a37d..4423a77 100644 --- a/tests/e2e/playwright.config.ts +++ b/tests/e2e/playwright.config.ts @@ -3,6 +3,9 @@ import { defineConfig, devices } from '@playwright/test'; // The e2e runs inside the compose network (infra/run-e2e-check.sh); baseURL defaults to the // self-service service. Keep timeouts generous — the first navigation triggers the DigiD flow. const baseURL = process.env.SELF_SERVICE_URL ?? 'http://self-service'; +// The behandel portal is a second origin the happy path visits (staff approve from the werkbak); +// it needs the same insecure-origin-as-secure treatment as self-service for the PKCE login (below). +const behandelURL = process.env.BEHANDEL_URL ?? 'http://behandel'; export default defineConfig({ testDir: '.', @@ -22,7 +25,9 @@ export default defineConfig({ // the production HTTPS context. This flag is only honoured by the full Chromium build (new // headless), not Playwright's default headless-shell, so pin `channel: 'chromium'`. channel: 'chromium', - launchOptions: { args: [`--unsafely-treat-insecure-origin-as-secure=${baseURL}`] }, + launchOptions: { + args: [`--unsafely-treat-insecure-origin-as-secure=${baseURL},${behandelURL}`], + }, }, projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }], }); diff --git a/tests/e2e/registration.spec.ts b/tests/e2e/registration.spec.ts index 9c678ab..c6395ff 100644 --- a/tests/e2e/registration.spec.ts +++ b/tests/e2e/registration.spec.ts @@ -1,10 +1,11 @@ import { expect, test } from '@playwright/test'; -// Walking-skeleton happy path (S-08d + S-09 + S-09b): a zorgprofessional logs in via mock DigiD and -// submits through the self-service portal → BFF → domain; the entry appears in the openbaar register -// as INGEDIEND; a behandelaar approves it via the temporary admin endpoint; the approval flows via the -// ACL → NRC → event-subscriber → projection, and the openbaar register then shows it as INGESCHREVEN. -test('DigiD login → submit → public INGEDIEND → approve → public INGESCHREVEN', async ({ page, request }) => { +// Walking-skeleton happy path (S-08d + S-09 + S-09b + S-12): a zorgprofessional logs in via mock +// DigiD and submits through the self-service portal → BFF → domain; the entry appears in the openbaar +// register as INGEDIEND; a behandelaar then logs in to the behandel portal, finds the registration in +// the werkbak, and approves it (goedkeuren); the decision completes the Flowable Beoordelen task and +// flows via the ACL → NRC → event-subscriber → projection, and the openbaar register shows INGESCHREVEN. +test('DigiD submit → public INGEDIEND → behandelaar goedkeurt → public INGESCHREVEN', async ({ page }) => { // Visiting the guarded page redirects to the Keycloak (mock DigiD) login. await page.goto('/'); @@ -43,21 +44,42 @@ test('DigiD login → submit → public INGEDIEND → approve → public INGESCH await expect(page.getByRole('row', { name: reference }).getByRole('cell', { name: 'INGEDIEND' })) .toBeVisible(); - // Approve via the temporary admin endpoint (reached directly on the compose network, as a - // behandelaar would until the behandel-portal exists — S-12). The zaak is opened off the request - // path by the worker, so wait for it before approving. + // A behandelaar picks the registration up in the behandel-portal werkbak and approves it + // (goedkeuren) — the S-12 flow that replaces the temporary admin endpoint. Navigating here switches + // to the medewerker realm (a different Keycloak realm than the citizen's digid session). + await page.goto('http://behandel/'); + await page.locator('#username').fill('merel-behandelaar'); + await page.locator('#password').fill('test123'); + await page.locator('#kc-login').click(); + + await expect(page.getByRole('heading', { name: /Werkbak/i })).toBeVisible(); + + // The registration parks at the Beoordelen user task only after the worker has opened its zaak, so + // it appears in the werkbak asynchronously — reload until this reference's row shows up. Target the + // decide button by reference (not a generic "Goedkeuren"): the shared verify stack holds other open + // tasks, so a positional match could act on someone else's registration. + const goedkeuren = page.getByRole('button', { name: `Goedkeuren ${reference}` }); await expect .poll(async () => { - const res = await request.get(`http://domain:8080/registrations/${reference}`); - return res.ok() ? (await res.json()).zaakUrl : null; + await page.reload(); + return goedkeuren.count(); }, { timeout: 30_000, intervals: [1_000, 2_000, 3_000, 5_000] }) - .toBeTruthy(); + .toBeGreaterThan(0); - const approve = await request.post(`http://domain:8080/registrations/${reference}/approve`); - expect(approve.status()).toBe(204); + // Click and wait for the decide POST to finish (204) BEFORE leaving the page. `click()` only + // dispatches the request; navigating away immediately cancels it in flight (nginx logs a 499) and + // the decision never reaches the domain — so the registration would stay INGEDIEND. + const decided = page.waitForResponse( + (r) => + r.url().includes(`/behandel/registrations/${reference}/decide`) && + r.request().method() === 'POST', + ); + await goedkeuren.click(); + expect((await decided).status()).toBe(204); - // The approval flows back to the projection; the openbaar register now shows *our* row (matched by - // its reference) as INGESCHREVEN. + // The approval flows back to the projection; back on the openbaar register *our* row (matched by + // its reference) now shows INGESCHREVEN. + await page.goto('http://openbaar/'); await expect .poll(async () => { await page.reload();