diff --git a/Dockerfile b/Dockerfile index 4aeebddf0..761a86a09 100644 --- a/Dockerfile +++ b/Dockerfile @@ -37,10 +37,12 @@ ENV PLATFORM_BACKEND_SERVER=platform-backend-service:8080 \ JUPYTER_SERVER=jupyterhub:8000 \ JUPYTER_CONTEXT=notebook \ GUIDE_COVARIATE=Sex \ - GUIDE_VARIABLE=Age + GUIDE_VARIABLE=Age \ + KEYCLOAK_ORIGIN=https://iam.ebrains.eu COPY docker-entrypoint.sh /docker-entrypoint.sh RUN chmod +x /docker-entrypoint.sh COPY nginx-websocket-map.conf /etc/nginx/conf.d/00-websocket-map.conf +COPY nginx-security-headers.conf /etc/nginx/security-headers.conf COPY nginx.conf.template /etc/nginx/templates/default.conf.template RUN rm -rf /usr/share/nginx/html/* COPY --from=build /app/dist/fl-platform/browser /usr/share/nginx/html diff --git a/README.md b/README.md index 2c5235c24..48a3b08be 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ See `src/app/core/algorithm-result-enum-mapper.md` for detailed mapping behavior ## Auth Flow - Routes are guarded (`AuthGuard` in `src/app/guards/auth.guard.ts`). - Login redirects to `/services/oauth2/authorization/keycloak?frontend_redirect=`. -- Logout calls `/services/logout` then returns to dashboard. +- Logout is a full-page `POST /services/logout` carrying the `XSRF-TOKEN` cookie value as `_csrf`. Without that cookie the session is already gone, and it goes to login instead. ## Project Structure - `src/main.ts` – bootstraps app with router, HTTP client, credentials interceptor, ECharts. @@ -56,7 +56,7 @@ See `src/app/core/algorithm-result-enum-mapper.md` for detailed mapping behavior - `src/app/pages/account-page/` – basic profile view. - `src/app/pages/shared/` – header/footer/spinner utilities. - `src/styles.css` – global styles; assets in `src/assets/`. -- `Dockerfile` / `nginx.conf.template` – container build and runtime proxy (`PLATFORM_BACKEND_SERVER`, `PLATFORM_BACKEND_CONTEXT` envs). +- `Dockerfile` / `nginx.conf.template` – container build and runtime proxy (`PLATFORM_BACKEND_SERVER`, `PLATFORM_BACKEND_CONTEXT`, `KEYCLOAK_ORIGIN` envs). @@ -71,6 +71,8 @@ docker run \ ``` Nginx always proxies `/${PLATFORM_BACKEND_CONTEXT}/` to the backend. +`KEYCLOAK_ORIGIN` (default `https://iam.ebrains.eu`) is the Keycloak origin the Content-Security-Policy allows. It must equal the origin of the issuer returned by `GET /services/auth-config`. If they differ, the browser blocks the account page's token request and any Keycloak redirect inside the notebook iframe. Nothing warns at startup; the violation only shows in the browser console. + ## Testing - Unit: `npm test` (Vitest, headless Chromium). - Manual: run `npm start`, authenticate, and exercise Experiment Studio and Dashboard against a running backend. diff --git a/angular.json b/angular.json index eaee9348f..b432de15a 100644 --- a/angular.json +++ b/angular.json @@ -43,7 +43,7 @@ "production": { "optimization": { "scripts": true, - "styles": true, + "styles": { "minify": true, "inlineCritical": false }, "fonts": false }, "budgets": [ diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh index 163bee0e5..40532cb1a 100644 --- a/docker-entrypoint.sh +++ b/docker-entrypoint.sh @@ -12,7 +12,7 @@ JUPYTER_CONTEXT_ESCAPED=$(escape_js "${JUPYTER_CONTEXT:-notebook}") GUIDE_COVARIATE_ESCAPED=$(escape_js "${GUIDE_COVARIATE:-Sex}") GUIDE_VARIABLE_ESCAPED=$(escape_js "${GUIDE_VARIABLE:-Age}") -envsubst '$PLATFORM_BACKEND_SERVER $PLATFORM_BACKEND_CONTEXT $NOTEBOOK_ENABLED $JUPYTER_SERVER $JUPYTER_CONTEXT' \ +envsubst '$PLATFORM_BACKEND_SERVER $PLATFORM_BACKEND_CONTEXT $NOTEBOOK_ENABLED $JUPYTER_SERVER $JUPYTER_CONTEXT $KEYCLOAK_ORIGIN' \ < /etc/nginx/templates/default.conf.template \ > /etc/nginx/conf.d/default.conf diff --git a/docs/context/architecture.md b/docs/context/architecture.md index a866b9309..26f4be5da 100644 --- a/docs/context/architecture.md +++ b/docs/context/architecture.md @@ -51,7 +51,7 @@ flowchart TD ## Authentication and Terms - `AuthService` checks the current session with `GET /services/activeUser`. - Login redirects to `/services/oauth2/authorization/keycloak?frontend_redirect=...`. -- Logout hard-redirects to `/services/logout`. +- Logout is a full-page `POST /services/logout` carrying the `XSRF-TOKEN` cookie value as `_csrf`. Without that cookie it goes to login. - Auth redirect state is stored in localStorage with `redirect_url`. - `TermsGuard` routes users to `/terms` when `user.agreeNDA` is false. - `TermsService` stores the intended terms destination in localStorage with `tos_redirect_url`. diff --git a/docs/context/commands.md b/docs/context/commands.md index 710ba070f..24dd5f521 100644 --- a/docs/context/commands.md +++ b/docs/context/commands.md @@ -60,7 +60,7 @@ Run: docker run -e PLATFORM_BACKEND_SERVER=platform-backend-service:8080 -e PLATFORM_BACKEND_CONTEXT=services -p 80:80 fl-platform ``` -Runtime env values are written to `assets/env.js` by `docker-entrypoint.sh`. +Runtime env values are written to `assets/env.js` by `docker-entrypoint.sh`. For `KEYCLOAK_ORIGIN`, which goes into the nginx Content-Security-Policy instead, see the README's Docker section. ## Output and Runtime Budget Guardrails diff --git a/docs/context/testing.md b/docs/context/testing.md index 3e6111599..618f9af80 100644 --- a/docs/context/testing.md +++ b/docs/context/testing.md @@ -52,6 +52,7 @@ There is no separate QA checklist file; the list below is it. Walk the affected - Visualization registries/renderers. - Histogram and descriptive statistics rendering. - Dashboard detail or compare views. +- Anything loading a new resource type or origin: the Content-Security-Policy exists only in the nginx image, so `ng serve` and the e2e flows never see it. Check the console on the built image. ## Backend Tests Not applicable in this frontend repository. Backend behavior must be validated in the backend repository or against a deployed/local backend. diff --git a/docs/llm-wiki/08-auth-and-terms-flow.md b/docs/llm-wiki/08-auth-and-terms-flow.md index c9b383ba9..270ae2698 100644 --- a/docs/llm-wiki/08-auth-and-terms-flow.md +++ b/docs/llm-wiki/08-auth-and-terms-flow.md @@ -14,7 +14,7 @@ Use for login, logout, active user, route protection, terms, and onboarding. - `GET /services/activeUser` - `/services/oauth2/authorization/keycloak?frontend_redirect=` -- `/services/logout` +- `POST /services/logout` (full-page form with `_csrf`) ## Guard Matrix diff --git a/docs/llm-wiki/indexes/backend-endpoints.md b/docs/llm-wiki/indexes/backend-endpoints.md index 12241bdd1..76c0c1cd5 100644 --- a/docs/llm-wiki/indexes/backend-endpoints.md +++ b/docs/llm-wiki/indexes/backend-endpoints.md @@ -11,7 +11,7 @@ side and `hub-http.ts` carries the Hub XSRF header. |---|---|---|---| | auth | GET | `/services/activeUser` | session check behind `AuthGuard` | | auth | GET | `/services/oauth2/authorization/keycloak` | full-page login redirect, `frontend_redirect` | -| auth | GET | `/services/logout` | full-page logout redirect | +| auth | POST | `/services/logout` | full-page sign-out form with `_csrf` | | terms | POST | `/services/activeUser/agreeNDA` | acceptance from `/terms`; the text itself is the static `assets/tos.md` | | catalog | GET | `/services/data-models` | models, datasets, variables | | specifications | GET | `/services/specifications/inputdata` | input DTO | diff --git a/nginx-security-headers.conf b/nginx-security-headers.conf new file mode 100644 index 000000000..011a093f6 --- /dev/null +++ b/nginx-security-headers.conf @@ -0,0 +1,7 @@ +# Security headers for the pages this nginx serves itself. Included per location: add_header at server level would +# also reach /services and JupyterHub, which set their own, and a location with its own add_header drops inherited ones. +add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; +add_header X-Content-Type-Options "nosniff" always; +add_header X-Frame-Options "SAMEORIGIN" always; +add_header Referrer-Policy "strict-origin-when-cross-origin" always; +add_header Content-Security-Policy $content_security_policy always; diff --git a/nginx.conf.template b/nginx.conf.template index 5da14453c..113273d61 100644 --- a/nginx.conf.template +++ b/nginx.conf.template @@ -1,5 +1,8 @@ server { listen 80; + server_tokens off; + + set $content_security_policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' data: https://fonts.gstatic.com; img-src 'self' data: blob:; connect-src 'self' ${KEYCLOAK_ORIGIN}; frame-src 'self' ${KEYCLOAK_ORIGIN}; frame-ancestors 'self'; object-src 'none'; base-uri 'self'"; # Serve Angular app root /usr/share/nginx/html; @@ -22,6 +25,7 @@ server { if ($uri != "/notebook") { return 302 /notebook; } + include /etc/nginx/security-headers.conf; try_files /index.html =404; } @@ -35,6 +39,7 @@ server { if ($uri != "/notebook/") { return 302 /notebook; } + include /etc/nginx/security-headers.conf; try_files /index.html =404; } @@ -108,6 +113,7 @@ server { # Fallback to index.html for Angular routing location / { + include /etc/nginx/security-headers.conf; try_files $uri /index.html; } } diff --git a/src/app/pages/shared/header/header.component.ts b/src/app/pages/shared/header/header.component.ts index ab049190a..a6e3ee298 100644 --- a/src/app/pages/shared/header/header.component.ts +++ b/src/app/pages/shared/header/header.component.ts @@ -115,7 +115,7 @@ export class HeaderComponent { } signOut(): void { - // The menu goes first: logout is a hard redirect, so the surface should not sit open + // The menu goes first: logout is a full-page navigation, so the surface should not sit open // through the unload — and it stays closed if logout ever stops being one. this.closeAccountMenu({ restoreFocus: false }); this.authService.logout(); diff --git a/src/app/services/auth.service.spec.ts b/src/app/services/auth.service.spec.ts new file mode 100644 index 000000000..4a7c3e6f5 --- /dev/null +++ b/src/app/services/auth.service.spec.ts @@ -0,0 +1,56 @@ +import { HttpXsrfTokenExtractor, provideHttpClient } from '@angular/common/http'; +import { TestBed } from '@angular/core/testing'; +import { provideRouter } from '@angular/router'; +import { AuthService, buildSignOutForm } from './auth.service'; + +describe('buildSignOutForm', () => { + it('posts the token to the backend', () => { + const form = buildSignOutForm('a-token'); + + expect(form.method.toUpperCase()).toBe('POST'); + expect(form.getAttribute('action')).toBe('/services/logout'); + expect((form.elements.namedItem('_csrf') as HTMLInputElement).value).toBe('a-token'); + }); +}); + +describe('AuthService.logout', () => { + function setup(token: string | null) { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideRouter([]), + { provide: HttpXsrfTokenExtractor, useValue: { getToken: () => token } }, + ], + }); + const service = TestBed.inject(AuthService); + return { + service, + login: vi.spyOn(service, 'login').mockReturnValue(undefined), + submit: vi.spyOn(HTMLFormElement.prototype, 'submit').mockReturnValue(undefined), + }; + } + + afterEach(() => { + vi.restoreAllMocks(); + document.querySelectorAll('form[action="/services/logout"]').forEach((form) => form.remove()); + }); + + it('submits the sign-out form when the token exists', () => { + const { service, login, submit } = setup('a-token'); + + service.logout(); + + expect(submit).toHaveBeenCalledTimes(1); + expect(login).not.toHaveBeenCalled(); + expect(service.authState().status).toBe('unauthenticated'); + }); + + it('goes to login instead of posting when the token is missing', () => { + const { service, login, submit } = setup(null); + + service.logout(); + + expect(submit).not.toHaveBeenCalled(); + expect(login).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/app/services/auth.service.ts b/src/app/services/auth.service.ts index 25a54dac5..4c2ecf352 100644 --- a/src/app/services/auth.service.ts +++ b/src/app/services/auth.service.ts @@ -1,7 +1,7 @@ import { inject, Injectable, signal } from '@angular/core'; import { toObservable } from '@angular/core/rxjs-interop'; import { Router } from '@angular/router'; -import { HttpClient } from '@angular/common/http'; +import { HttpClient, HttpXsrfTokenExtractor } from '@angular/common/http'; import { Observable, of } from 'rxjs'; import { catchError, tap, filter } from 'rxjs/operators'; import { User } from '../models/user.interface'; @@ -13,12 +13,27 @@ interface AuthState { user?: User | null; } +/** The sign-out POST, carrying the backend's CSRF token. */ +export function buildSignOutForm(csrfToken: string): HTMLFormElement { + const form = document.createElement('form'); + form.method = 'POST'; + form.action = '/services/logout'; + form.style.display = 'none'; + const token = document.createElement('input'); + token.type = 'hidden'; + token.name = '_csrf'; + token.value = csrfToken; + form.appendChild(token); + return form; +} + @Injectable({ providedIn: 'root' }) export class AuthService { private http = inject(HttpClient); private router = inject(Router); + private xsrfTokens = inject(HttpXsrfTokenExtractor); private readonly redirectUrlKey = 'redirect_url'; private readonly authStateSignal = signal({ status: 'checking' }); @@ -77,8 +92,17 @@ export class AuthService { localStorage.removeItem(this.redirectUrlKey); this.authStateSignal.set({ status: 'unauthenticated' }); - // Use a full-page redirect so the backend/IdP can clear SSO cookies. - window.location.href = '/services/logout'; + // No cookie means the session is already gone (e.g. signed out in another tab). The POST would only get a 403 page. + const csrfToken = this.xsrfTokens.getToken(); + if (!csrfToken) { + this.login(); + return; + } + + // A full-page POST so the backend/IdP can clear SSO cookies. The backend wants its CSRF token on sign-out. + const form = buildSignOutForm(csrfToken); + document.body.appendChild(form); + form.submit(); } isLoggedIn(): boolean {