From 66bb91cb3e3dc5b7e087d38eb5b36bd86f1bc5f3 Mon Sep 17 00:00:00 2001 From: "Dev (Paperclip)" Date: Wed, 25 Nov 2026 09:27:50 +0000 Subject: [PATCH] fix(auth): Review-Findings M1, M2, S1, S2 - M1: Start bricht ab, wenn oidc+naturalcrit aktiv, nicht lokal und Upstream-secret Standard/leer - M2: README.md wieder mit CRLF (Diff nur +4) - S1: /auth/oidc/login zeigt interne Fehlertexte nicht mehr an - S2: http://-Issuer nur bei http://-HB_PUBLIC_URL Co-Authored-By: Claude Sonnet 5.5 --- README.md | 340 +++++++++++++++--------------- docs/auth/README.md | 2 +- server/app.js | 2 +- server/fork/auth/auth.api.spec.js | 8 +- server/fork/auth/config.js | 13 +- server/fork/auth/config.spec.js | 38 +++- server/fork/auth/index.js | 3 +- server/fork/auth/session.spec.js | 2 +- 8 files changed, 224 insertions(+), 184 deletions(-) diff --git a/README.md b/README.md index b5de6791..d22efd40 100644 --- a/README.md +++ b/README.md @@ -1,170 +1,170 @@ -# The Homebrewery - -[![Homebrewery](https://circleci.com/gh/naturalcrit/homebrewery/tree/master.svg?style=svg)](https://app.circleci.com/pipelines/github/naturalcrit/homebrewery?branch=master) - -The Homebrewery is a tool for making authentic looking [D&D content][dnd-content-url] -using [Markdown][markdown-url]. It is distributed under the terms of the [MIT License](./license). - -[dnd-content-url]: https://dnd.wizards.com/products/tabletop-games/rpg-products/rpg_playershandbook -[markdown-url]: https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet - -## Quick Start -The easiest way to get started using The Homebrewery is to use it -[on our website][homebrewery-url]. The code is open source, so feel free to -clone it and tinker with it. If you want to make changes to the code, you can run -your own local version for testing by following the installation instructions -below. - -[homebrewery-url]: https://homebrewery.naturalcrit.com - -### Installation -First, install three programs that The Homebrewery requires to run and retrieve -updates: - -1. install [node](https://nodejs.org/en/), version v16 or higher. -1. install [mongodb](https://www.mongodb.com/try/download/community) (Community version) - - For the easiest installation, follow these steps: - 1. In the installer, uncheck the option to run as a service. - 1. You can install MongoDB Compass if you want a GUI to view your database documents. - 1. If you install any version over 6.0, you will have to install [MongoDB Shell](https://www.mongodb.com/try/download/shell). - 1. Go to the C:\ drive and create a folder called "data". - 1. Inside the "data" folder, create a new folder called "db". - 1. Open a command prompt or other terminal and navigate to your MongoDB install folder (C:\Program Files\Mongo\Server\6.0\bin). - 1. In the command prompt, run "mongod", which will start up your local database server. - 1. While MongoD is running, open a second command prompt and navigate to the MongoDB install folder. - 1. Search in Windows for "Advanced system settings" and open it. - 1. Click "Environment variables", find the "path" variable, and double-click to open it. - 1. Click "New" and paste in the path to the MongoDB "bin" folder. - 1. Click "OK" three times to close all the windows. - 1. In the second command prompt, run "mongo", which allows you to edit the database. - 1. Type `use homebrewery` to create The Homebrewery database. You should see `switched to db homebrewery`. - 1. Type `db.brews.insertOne({"title":"test"})` to create a blank document. You should see `{ -acknowledged: true, -insertedId: ObjectId("63c2fce9e5ac5a94fe2410cf") -}` - -1. install [git](https://git-scm.com/downloads) (select the option that allows Git to run from the command prompt). - -Checkout the repo ([documentation][github-clone-repo-docs-url]): -``` -git clone https://github.com/naturalcrit/homebrewery.git -``` - -[github-clone-repo-docs-url]: https://docs.github.com/en/free-pro-team@latest/github/creating-cloning-and-archiving-repositories/cloning-a-repository - -Second, you will need to add the environment variable `NODE_ENV=local` to allow -the project to run locally. - -You can set this **temporarily** (until you close the terminal) in your shell of choice with admin privileges: -* Windows Powershell: `$env:NODE_ENV="local"` -* Windows CMD: `set NODE_ENV=local` -* Linux / macOS: `export NODE_ENV=local` - -If you want to add this variable **permanently** the steps are as follows: - 1. Search in Windows for "Advanced system settings" and open it. - 1. Click "Environment variables". - 1. In System Variables, click "New" - 1. Click "New" and write `NODE_ENV` as a name and `local` as the value. - 1. Click "OK" three times to close all the windows. - This can be undone at any time if needed. - -Third, you will need to install the Node dependencies, compile the app, and run -it using the two commands: - -1. `npm install` -1. `npm start` - -When the Homebrewery server is started for the first time, it will modify the database to create the indexes required for better Homebrewery performance. This may take a few moments to complete for each index, dependent on how much content is in your local database - a brand new, empty database should be done in seconds. - -On completion, you should be able to go to [http://localhost:8000](http://localhost:8000) in your browser and use The Homebrewery offline. - -If you had any issue at all, here are some links that may be useful: -- [Course](https://learn.mongodb.com/courses/m103-basic-cluster-administration) on cluster administration, useful for beginners -- [Mongo community forums](https://www.mongodb.com/community/forums/) -- Useful Stack Overflow links for your most probable errors: [1](https://stackoverflow.com/questions/44962540/mongod-and-mongo-commands-not-working-on-windows-10), [2](https://stackoverflow.com/questions/15053893/mongo-command-not-recognized-when-trying-to-connect-to-a-mongodb-server/41507803#41507803), [3](https://stackoverflow.com/questions/51224959/mongo-is-not-recognized-as-an-internal-or-external-command-operable-program-o) - -If you still have problems, post in [Our Subreddit](https://www.reddit.com/r/homebrewery/) and we will help you. - -### Running the application via Docker - -Please see the docs here: [README.DOCKER.md](./README.DOCKER.md) - -### Lokal starten / Selbst hosten (Fork homebrewery-oidc) - -```bash -cp .env.example .env # optional, alle Werte haben Entwicklungs-Defaults -docker compose up --build # App + MongoDB -> http://localhost:8000 -``` - -`docker-compose.override.yml` (wird automatisch geladen) und `docker/` enthalten die Fork-Erweiterungen; `docker-compose.yml` bleibt Upstream-identisch. - -| Profil | Start | Ergebnis | -|---|---|---| -| `postgres` | `docker compose --profile postgres up -d postgres` | PostgreSQL 18 auf `127.0.0.1:5432` (ab M2) | -| `keycloak` | `docker compose --profile keycloak up -d` | Keycloak :8080, Realm `homebrewery`, Client `homebrewery`/`dev-only-client-secret`, Nutzer `testuser`/`testuser-dev`, Admin `admin`/`admin-dev`. Discovery: `http://keycloak.localhost:8080/realms/homebrewery/.well-known/openid-configuration` (Start dauert 1–2 Min.) | -| `authentik` | `docker compose --profile authentik up -d` | authentik :9000, Provider/App `homebrewery` per Blueprint, gleicher Client und Nutzer, Admin `akadmin`/`admin-dev`. Discovery: `http://authentik.localhost:9000/application/o/homebrewery/.well-known/openid-configuration` | - -Hinweise: Die IdPs laufen unter `keycloak.localhost:8080` bzw. `authentik.localhost:9000` (Issuer für Browser und App-Container identisch, Bindung nur an 127.0.0.1; `*.localhost` löst moderne Browser/OS automatisch auf, sonst `127.0.0.1 keycloak.localhost authentik.localhost` in `/etc/hosts`). Ports nur ändern, wenn Redirect-/Issuer-Einstellungen mitgezogen werden. Alle Zugangsdaten sind reine Dev-Werte, für den Betrieb in `.env` ersetzen. MongoDB 5+ benötigt eine CPU mit AVX; auf älteren CPUs/VMs `MONGO_TAG=4.4` setzen. Der authentik-Blueprint wird beim Erststart automatisch angewendet (dauert einige Minuten, bis die Discovery-URL 200 liefert). - -#### Login über OIDC (Keycloak, authentik, …) - -Der Fork bringt einen generischen OIDC-Login (Authorization Code + PKCE) mit. Konfiguration nur über Umgebungsvariablen (`HB_OIDC_ISSUER`, `HB_OIDC_CLIENT_ID`, `HB_OIDC_CLIENT_SECRET`, `HB_PUBLIC_URL`, `HB_SESSION_SECRET`, …, Vorlage in `.env.example`). Die bisherigen Logins (`naturalcrit`: Benutzername/Passwort, Google) bleiben Standard und lassen sich über `HB_AUTH_PROVIDERS` abschalten, abgeschaltete Methoden verschwinden aus der UI und ihre Endpunkte sind gesperrt. Einrichtung, Variablen und Kontozuordnung: [docs/auth/README.md](./docs/auth/README.md), [Keycloak](./docs/auth/keycloak.md), [authentik](./docs/auth/authentik.md). Entscheidung: [ADR 0001](./docs/adr/0001-auth-oidc.md). - -### Running the application on FreeBSD or FreeNAS - -Please see the docs here: [README.FreeBSD.md](./README.FREEBSD.md) - -### Standalone PHB Stylesheet -If you just want the stylesheet that is generated to make pages look like they -are from the Player's Handbook, you will find it in the -[phb.standalone.css](./phb.standalone.css) file. - -If you are developing locally and would like to generate your own, follow the -above steps and then run `npm run phb`. - -## Issues, Suggestions, and Bugs -If you run into any issues using The Homebrewery or have suggestions for -improvement, please submit an issue [on GitHub][repo-issues-url]. -You can also get help for issues on the subreddit [r/homebrewery][subreddit-url] - -[repo-issues-url]: https://github.com/naturalcrit/homebrewery/issues -[subreddit-url]: https://www.reddit.com/r/homebrewery - -## Changelog - -You can check out the [changelog](./changelog.md). - -## License - -This project is licensed under the [MIT license](./license), which means you -are free to use The Homebrewery in any way that you want, except for claiming -that you made it yourself. - -If you wish to sell, or in some way gain profit for, what's created on this site, -it's your responsibility to ensure you have the proper licenses/rights for any -images or resources used. - -## Contributing - -You are welcome to contribute to the development and maintenance of the -project! There are several ways of doing that: -- At the moment, we have a huge backlog of [issues][repo-issues-url] and some - of them are outdated, duplicates, or don't contain any useful info. To help, you can [mark duplicates][github-mark-duplicate-url], try to - reproduce some complex or weird issues, try finding a workaround for a - reported bug, or just mention our issue managers team to let them know about - outdated issues via `@naturalcrit/issue-managers`. -- Our [subreddit][subreddit-url] is constantly growing and there are number of - bug reports. Any help with sorting them out is very welcome. -- And of course you can contribute by fixing a bug or implementing a new - feature by yourself, we are waiting for your - [pull requests][github-pr-docs-url]! - -Anyway, if you would like to get in touch with the team and discuss/coordinate -your contribution to the project, please join our [gitter chat][gitter-url]. - -[github-mark-duplicate-url]: https://docs.github.com/en/free-pro-team@latest/github/managing-your-work-on-github/about-duplicate-issues-and-pull-requests -[github-pr-docs-url]: https://docs.github.com/en/free-pro-team@latest/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request -[gitter-url]: https://gitter.im/naturalcrit/Lobby - - +# The Homebrewery + +[![Homebrewery](https://circleci.com/gh/naturalcrit/homebrewery/tree/master.svg?style=svg)](https://app.circleci.com/pipelines/github/naturalcrit/homebrewery?branch=master) + +The Homebrewery is a tool for making authentic looking [D&D content][dnd-content-url] +using [Markdown][markdown-url]. It is distributed under the terms of the [MIT License](./license). + +[dnd-content-url]: https://dnd.wizards.com/products/tabletop-games/rpg-products/rpg_playershandbook +[markdown-url]: https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet + +## Quick Start +The easiest way to get started using The Homebrewery is to use it +[on our website][homebrewery-url]. The code is open source, so feel free to +clone it and tinker with it. If you want to make changes to the code, you can run +your own local version for testing by following the installation instructions +below. + +[homebrewery-url]: https://homebrewery.naturalcrit.com + +### Installation +First, install three programs that The Homebrewery requires to run and retrieve +updates: + +1. install [node](https://nodejs.org/en/), version v16 or higher. +1. install [mongodb](https://www.mongodb.com/try/download/community) (Community version) + + For the easiest installation, follow these steps: + 1. In the installer, uncheck the option to run as a service. + 1. You can install MongoDB Compass if you want a GUI to view your database documents. + 1. If you install any version over 6.0, you will have to install [MongoDB Shell](https://www.mongodb.com/try/download/shell). + 1. Go to the C:\ drive and create a folder called "data". + 1. Inside the "data" folder, create a new folder called "db". + 1. Open a command prompt or other terminal and navigate to your MongoDB install folder (C:\Program Files\Mongo\Server\6.0\bin). + 1. In the command prompt, run "mongod", which will start up your local database server. + 1. While MongoD is running, open a second command prompt and navigate to the MongoDB install folder. + 1. Search in Windows for "Advanced system settings" and open it. + 1. Click "Environment variables", find the "path" variable, and double-click to open it. + 1. Click "New" and paste in the path to the MongoDB "bin" folder. + 1. Click "OK" three times to close all the windows. + 1. In the second command prompt, run "mongo", which allows you to edit the database. + 1. Type `use homebrewery` to create The Homebrewery database. You should see `switched to db homebrewery`. + 1. Type `db.brews.insertOne({"title":"test"})` to create a blank document. You should see `{ +acknowledged: true, +insertedId: ObjectId("63c2fce9e5ac5a94fe2410cf") +}` + +1. install [git](https://git-scm.com/downloads) (select the option that allows Git to run from the command prompt). + +Checkout the repo ([documentation][github-clone-repo-docs-url]): +``` +git clone https://github.com/naturalcrit/homebrewery.git +``` + +[github-clone-repo-docs-url]: https://docs.github.com/en/free-pro-team@latest/github/creating-cloning-and-archiving-repositories/cloning-a-repository + +Second, you will need to add the environment variable `NODE_ENV=local` to allow +the project to run locally. + +You can set this **temporarily** (until you close the terminal) in your shell of choice with admin privileges: +* Windows Powershell: `$env:NODE_ENV="local"` +* Windows CMD: `set NODE_ENV=local` +* Linux / macOS: `export NODE_ENV=local` + +If you want to add this variable **permanently** the steps are as follows: + 1. Search in Windows for "Advanced system settings" and open it. + 1. Click "Environment variables". + 1. In System Variables, click "New" + 1. Click "New" and write `NODE_ENV` as a name and `local` as the value. + 1. Click "OK" three times to close all the windows. + This can be undone at any time if needed. + +Third, you will need to install the Node dependencies, compile the app, and run +it using the two commands: + +1. `npm install` +1. `npm start` + +When the Homebrewery server is started for the first time, it will modify the database to create the indexes required for better Homebrewery performance. This may take a few moments to complete for each index, dependent on how much content is in your local database - a brand new, empty database should be done in seconds. + +On completion, you should be able to go to [http://localhost:8000](http://localhost:8000) in your browser and use The Homebrewery offline. + +If you had any issue at all, here are some links that may be useful: +- [Course](https://learn.mongodb.com/courses/m103-basic-cluster-administration) on cluster administration, useful for beginners +- [Mongo community forums](https://www.mongodb.com/community/forums/) +- Useful Stack Overflow links for your most probable errors: [1](https://stackoverflow.com/questions/44962540/mongod-and-mongo-commands-not-working-on-windows-10), [2](https://stackoverflow.com/questions/15053893/mongo-command-not-recognized-when-trying-to-connect-to-a-mongodb-server/41507803#41507803), [3](https://stackoverflow.com/questions/51224959/mongo-is-not-recognized-as-an-internal-or-external-command-operable-program-o) + +If you still have problems, post in [Our Subreddit](https://www.reddit.com/r/homebrewery/) and we will help you. + +### Running the application via Docker + +Please see the docs here: [README.DOCKER.md](./README.DOCKER.md) + +### Lokal starten / Selbst hosten (Fork homebrewery-oidc) + +```bash +cp .env.example .env # optional, alle Werte haben Entwicklungs-Defaults +docker compose up --build # App + MongoDB -> http://localhost:8000 +``` + +`docker-compose.override.yml` (wird automatisch geladen) und `docker/` enthalten die Fork-Erweiterungen; `docker-compose.yml` bleibt Upstream-identisch. + +| Profil | Start | Ergebnis | +|---|---|---| +| `postgres` | `docker compose --profile postgres up -d postgres` | PostgreSQL 18 auf `127.0.0.1:5432` (ab M2) | +| `keycloak` | `docker compose --profile keycloak up -d` | Keycloak :8080, Realm `homebrewery`, Client `homebrewery`/`dev-only-client-secret`, Nutzer `testuser`/`testuser-dev`, Admin `admin`/`admin-dev`. Discovery: `http://keycloak.localhost:8080/realms/homebrewery/.well-known/openid-configuration` (Start dauert 1–2 Min.) | +| `authentik` | `docker compose --profile authentik up -d` | authentik :9000, Provider/App `homebrewery` per Blueprint, gleicher Client und Nutzer, Admin `akadmin`/`admin-dev`. Discovery: `http://authentik.localhost:9000/application/o/homebrewery/.well-known/openid-configuration` | + +Hinweise: Die IdPs laufen unter `keycloak.localhost:8080` bzw. `authentik.localhost:9000` (Issuer für Browser und App-Container identisch, Bindung nur an 127.0.0.1; `*.localhost` löst moderne Browser/OS automatisch auf, sonst `127.0.0.1 keycloak.localhost authentik.localhost` in `/etc/hosts`). Ports nur ändern, wenn Redirect-/Issuer-Einstellungen mitgezogen werden. Alle Zugangsdaten sind reine Dev-Werte, für den Betrieb in `.env` ersetzen. MongoDB 5+ benötigt eine CPU mit AVX; auf älteren CPUs/VMs `MONGO_TAG=4.4` setzen. Der authentik-Blueprint wird beim Erststart automatisch angewendet (dauert einige Minuten, bis die Discovery-URL 200 liefert). + +#### Login über OIDC (Keycloak, authentik, …) + +Der Fork bringt einen generischen OIDC-Login (Authorization Code + PKCE) mit. Konfiguration nur über Umgebungsvariablen (`HB_OIDC_ISSUER`, `HB_OIDC_CLIENT_ID`, `HB_OIDC_CLIENT_SECRET`, `HB_PUBLIC_URL`, `HB_SESSION_SECRET`, …, Vorlage in `.env.example`). Die bisherigen Logins (`naturalcrit`: Benutzername/Passwort, Google) bleiben Standard und lassen sich über `HB_AUTH_PROVIDERS` abschalten, abgeschaltete Methoden verschwinden aus der UI und ihre Endpunkte sind gesperrt. Einrichtung, Variablen und Kontozuordnung: [docs/auth/README.md](./docs/auth/README.md), [Keycloak](./docs/auth/keycloak.md), [authentik](./docs/auth/authentik.md). Entscheidung: [ADR 0001](./docs/adr/0001-auth-oidc.md). + +### Running the application on FreeBSD or FreeNAS + +Please see the docs here: [README.FreeBSD.md](./README.FREEBSD.md) + +### Standalone PHB Stylesheet +If you just want the stylesheet that is generated to make pages look like they +are from the Player's Handbook, you will find it in the +[phb.standalone.css](./phb.standalone.css) file. + +If you are developing locally and would like to generate your own, follow the +above steps and then run `npm run phb`. + +## Issues, Suggestions, and Bugs +If you run into any issues using The Homebrewery or have suggestions for +improvement, please submit an issue [on GitHub][repo-issues-url]. +You can also get help for issues on the subreddit [r/homebrewery][subreddit-url] + +[repo-issues-url]: https://github.com/naturalcrit/homebrewery/issues +[subreddit-url]: https://www.reddit.com/r/homebrewery + +## Changelog + +You can check out the [changelog](./changelog.md). + +## License + +This project is licensed under the [MIT license](./license), which means you +are free to use The Homebrewery in any way that you want, except for claiming +that you made it yourself. + +If you wish to sell, or in some way gain profit for, what's created on this site, +it's your responsibility to ensure you have the proper licenses/rights for any +images or resources used. + +## Contributing + +You are welcome to contribute to the development and maintenance of the +project! There are several ways of doing that: +- At the moment, we have a huge backlog of [issues][repo-issues-url] and some + of them are outdated, duplicates, or don't contain any useful info. To help, you can [mark duplicates][github-mark-duplicate-url], try to + reproduce some complex or weird issues, try finding a workaround for a + reported bug, or just mention our issue managers team to let them know about + outdated issues via `@naturalcrit/issue-managers`. +- Our [subreddit][subreddit-url] is constantly growing and there are number of + bug reports. Any help with sorting them out is very welcome. +- And of course you can contribute by fixing a bug or implementing a new + feature by yourself, we are waiting for your + [pull requests][github-pr-docs-url]! + +Anyway, if you would like to get in touch with the team and discuss/coordinate +your contribution to the project, please join our [gitter chat][gitter-url]. + +[github-mark-duplicate-url]: https://docs.github.com/en/free-pro-team@latest/github/managing-your-work-on-github/about-duplicate-issues-and-pull-requests +[github-pr-docs-url]: https://docs.github.com/en/free-pro-team@latest/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request +[gitter-url]: https://gitter.im/naturalcrit/Lobby + + diff --git a/docs/auth/README.md b/docs/auth/README.md index 0848bfab..78f1da53 100644 --- a/docs/auth/README.md +++ b/docs/auth/README.md @@ -42,7 +42,7 @@ Der Redirect-URI beim IdP ist `${HB_PUBLIC_URL}/auth/oidc/callback`, der Post-Lo | Einstellung | Wirkung | | --- | --- | | nicht gesetzt, kein Issuer | Upstream-Verhalten: nur `naturalcrit` | -| nicht gesetzt, `HB_OIDC_ISSUER` gesetzt | `oidc,naturalcrit`: Login-Link führt auf die Auswahlseite `/auth/login` | +| nicht gesetzt, `HB_OIDC_ISSUER` gesetzt | `oidc,naturalcrit`: Login-Link führt auf die Auswahlseite `/auth/login`. Außerhalb lokaler Umgebungen bricht der Start ab, solange das Upstream-`secret` (Env `SECRET`) der Standardwert `secret` ist, weil sich sonst `nc_session` fälschen ließe; `SECRET` setzen oder `HB_AUTH_PROVIDERS=oidc` | | `oidc` | nur OIDC. `nc_session` wird ignoriert, `POST /local/login` liefert 404, Google Drive als Speicherort entfällt | | `naturalcrit` | nur Alt-Login (Benutzername/Passwort und Google laufen bei Upstream über naturalcrit.com). `/auth/oidc/*` liefern 404, ein vorhandenes `hb_session` wird ignoriert | diff --git a/server/app.js b/server/app.js index 04993e41..378a4db1 100644 --- a/server/app.js +++ b/server/app.js @@ -116,7 +116,7 @@ export default async function createApp(vite) { }); // Fork: OIDC-Login (ADR 0001); ersetzt req.account nach der Upstream-Middleware - const authConfig = readAuthConfig(); + const authConfig = readAuthConfig(process.env, { upstreamSecret: config.get('secret'), isLocal: isLocalEnvironment }); app.use(accountMiddleware(authConfig)); app.use(createAuthRouter(authConfig, { getUsers : ()=>getStorage().users, diff --git a/server/fork/auth/auth.api.spec.js b/server/fork/auth/auth.api.spec.js index d259bcc2..834e2527 100644 --- a/server/fork/auth/auth.api.spec.js +++ b/server/fork/auth/auth.api.spec.js @@ -19,7 +19,7 @@ const buildApp = (envOverrides = {}, depsOverrides = {})=>{ const config = readAuthConfig({ HB_PUBLIC_URL : appUrl, HB_OIDC_ISSUER : idp.issuer, HB_OIDC_CLIENT_ID : CLIENT.client_id, HB_OIDC_CLIENT_SECRET : CLIENT.client_secret, HB_SESSION_SECRET : SECRET, ...envOverrides - }); + }, { upstreamSecret: 'eigenes-secret' }); const app = express(); app.use(cookieParser()); // Stand-in für die Upstream-Account-Middleware: nc_session-Cookie == Benutzername @@ -203,7 +203,7 @@ describe('OIDC-Login (Authorization Code + PKCE) gegen Mock-IdP', ()=>{ const b = browser(); const start = await b.req('/auth/oidc/login'); const { callbackUrl } = await loginAtIdp(start.headers.get('location'), { login: 'alice' }); - const config = readAuthConfig({ HB_PUBLIC_URL: appUrl, HB_OIDC_ISSUER: idp.issuer, HB_OIDC_CLIENT_ID: 'x', HB_OIDC_CLIENT_SECRET: 'x', HB_SESSION_SECRET: SECRET }); + const config = readAuthConfig({ HB_PUBLIC_URL: appUrl, HB_OIDC_ISSUER: idp.issuer, HB_OIDC_CLIENT_ID: 'x', HB_OIDC_CLIENT_SECRET: 'x', HB_SESSION_SECRET: SECRET }, { upstreamSecret: 'eigenes-secret' }); const tx = openTx(config, b.jar[TX_COOKIE]); b.jar[TX_COOKIE] = sealTx(config, { ...tx, createdAt: Date.now() - 11 * 60 * 1000 }); await expectErrorPage(await b.req(callbackUrl), 400); @@ -222,7 +222,7 @@ describe('OIDC-Login (Authorization Code + PKCE) gegen Mock-IdP', ()=>{ const b = browser(); const start = await b.req('/auth/oidc/login'); const { callbackUrl } = await loginAtIdp(start.headers.get('location'), { login: 'alice' }); - const config = readAuthConfig({ HB_PUBLIC_URL: appUrl, HB_OIDC_ISSUER: idp.issuer, HB_OIDC_CLIENT_ID: 'x', HB_OIDC_CLIENT_SECRET: 'x', HB_SESSION_SECRET: SECRET }); + const config = readAuthConfig({ HB_PUBLIC_URL: appUrl, HB_OIDC_ISSUER: idp.issuer, HB_OIDC_CLIENT_ID: 'x', HB_OIDC_CLIENT_SECRET: 'x', HB_SESSION_SECRET: SECRET }, { upstreamSecret: 'eigenes-secret' }); const tx = openTx(config, b.jar[TX_COOKIE]); b.jar[TX_COOKIE] = sealTx(config, { ...tx, nonce: 'anderer-nonce' }); await expectErrorPage(await b.req(callbackUrl), 400); @@ -234,7 +234,7 @@ describe('OIDC-Login (Authorization Code + PKCE) gegen Mock-IdP', ()=>{ const b = browser(); const start = await b.req('/auth/oidc/login'); const { callbackUrl } = await loginAtIdp(start.headers.get('location'), { login: 'alice' }); - const config = readAuthConfig({ HB_PUBLIC_URL: appUrl, HB_OIDC_ISSUER: idp.issuer, HB_OIDC_CLIENT_ID: 'x', HB_OIDC_CLIENT_SECRET: 'x', HB_SESSION_SECRET: SECRET }); + const config = readAuthConfig({ HB_PUBLIC_URL: appUrl, HB_OIDC_ISSUER: idp.issuer, HB_OIDC_CLIENT_ID: 'x', HB_OIDC_CLIENT_SECRET: 'x', HB_SESSION_SECRET: SECRET }, { upstreamSecret: 'eigenes-secret' }); const tx = openTx(config, b.jar[TX_COOKIE]); b.jar[TX_COOKIE] = sealTx(config, { ...tx, codeVerifier: 'A'.repeat(43) }); await expectErrorPage(await b.req(callbackUrl), 400); diff --git a/server/fork/auth/config.js b/server/fork/auth/config.js index c2f0c274..34764e1c 100644 --- a/server/fork/auth/config.js +++ b/server/fork/auth/config.js @@ -18,7 +18,7 @@ export const parseTtl = (value, def = 7 * 24 * 3600)=>{ return seconds; }; -export const readAuthConfig = (env = process.env)=>{ +export const readAuthConfig = (env = process.env, { upstreamSecret, isLocal = false } = {})=>{ const issuer = env.HB_OIDC_ISSUER || undefined; let providers; @@ -63,7 +63,16 @@ export const readAuthConfig = (env = process.env)=>{ throw new Error(`HB_SESSION_SECRET muss mindestens ${MIN_SECRET_BYTES} Byte lang sein`); } if(!/^https?:\/\//.test(config.publicUrl)) throw new Error('HB_PUBLIC_URL muss mit http:// oder https:// beginnen'); - try { new URL(config.oidc.issuer); } catch { throw new Error('HB_OIDC_ISSUER ist keine gültige URL'); } + let issuerUrl; + try { issuerUrl = new URL(config.oidc.issuer); } catch { throw new Error('HB_OIDC_ISSUER ist keine gültige URL'); } + // http://-Issuer nur im Dev-Setup (HB_PUBLIC_URL selbst http://), sonst läuft Discovery/JWKS/Token unverschlüsselt + if(issuerUrl.protocol === 'http:' && config.publicUrl.startsWith('https://')) { + throw new Error('HB_OIDC_ISSUER muss https:// verwenden, wenn HB_PUBLIC_URL https:// ist'); + } + // Upstream-nc_session wird mit config "secret" signiert; Standardwert => Sitzung fälschbar + if(providers.includes('naturalcrit') && !isLocal && (!upstreamSecret || upstreamSecret === 'secret')) { + throw new Error('Auth: "naturalcrit" ist neben "oidc" aktiv, aber das Upstream-"secret" ist der Standardwert. Entweder SECRET setzen oder HB_AUTH_PROVIDERS=oidc.'); + } } return config; diff --git a/server/fork/auth/config.spec.js b/server/fork/auth/config.spec.js index 6663374d..67103ee5 100644 --- a/server/fork/auth/config.spec.js +++ b/server/fork/auth/config.spec.js @@ -5,6 +5,8 @@ const base = { HB_OIDC_CLIENT_ID : 'id', HB_OIDC_CLIENT_SECRET : 's', HB_SESSION_SECRET : 'x'.repeat(32) }; +const own = { upstreamSecret: 'eigenes-secret' }; + describe('Auth-Konfiguration', ()=>{ test('Standard ohne Angaben: nur naturalcrit (Upstream-Verhalten)', ()=>{ const c = readAuthConfig({}); @@ -13,7 +15,7 @@ describe('Auth-Konfiguration', ()=>{ }); test('Issuer gesetzt, Provider leer: oidc,naturalcrit mit Auswahlseite', ()=>{ - const c = readAuthConfig(base); + const c = readAuthConfig(base, own); expect(c.providers).toEqual(['oidc', 'naturalcrit']); expect(c.publicUrl).toBe('https://brew.example.org'); expect(c.secureCookies).toBe(true); @@ -32,12 +34,12 @@ describe('Auth-Konfiguration', ()=>{ }); test('zu kurzes Session-Secret und unbekannter Provider brechen ab', ()=>{ - expect(()=>readAuthConfig({ ...base, HB_SESSION_SECRET: 'kurz' })).toThrow(/32 Byte/); + expect(()=>readAuthConfig({ ...base, HB_SESSION_SECRET: 'kurz' }, own)).toThrow(/32 Byte/); expect(()=>readAuthConfig({ HB_AUTH_PROVIDERS: 'ldap' })).toThrow(/unbekannte/); }); test('http-URL: Cookies nicht Secure', ()=>{ - expect(readAuthConfig({ ...base, HB_PUBLIC_URL: 'http://localhost:8000' }).secureCookies).toBe(false); + expect(readAuthConfig({ ...base, HB_PUBLIC_URL: 'http://localhost:8000' }, own).secureCookies).toBe(false); }); test('TTL-Formate', ()=>{ @@ -50,6 +52,34 @@ describe('Auth-Konfiguration', ()=>{ }); test('Secret taucht nicht in der Client-Konfiguration auf', ()=>{ - expect(JSON.stringify(clientConfig(readAuthConfig(base)))).not.toMatch(/secret|"s"/i); + expect(JSON.stringify(clientConfig(readAuthConfig(base, own)))).not.toMatch(/secret|"s"/i); + }); + + describe('Upstream-secret (fälschbare nc_session)', ()=>{ + test('Abbruch bei oidc+naturalcrit, Standard-secret, nicht lokal', ()=>{ + expect(()=>readAuthConfig(base, { upstreamSecret: 'secret', isLocal: false })).toThrow(/Upstream-"secret".*HB_AUTH_PROVIDERS=oidc/); + expect(()=>readAuthConfig(base, { upstreamSecret: '', isLocal: false })).toThrow(/Upstream-"secret"/); + expect(()=>readAuthConfig(base)).toThrow(/Upstream-"secret"/); + }); + + test('kein Abbruch: lokal, nur oidc oder eigenes secret', ()=>{ + expect(()=>readAuthConfig(base, { upstreamSecret: 'secret', isLocal: true })).not.toThrow(); + expect(()=>readAuthConfig({ ...base, HB_AUTH_PROVIDERS: 'oidc' }, { upstreamSecret: 'secret', isLocal: false })).not.toThrow(); + expect(()=>readAuthConfig(base, { upstreamSecret: 'eigenes-secret', isLocal: false })).not.toThrow(); + }); + + test('reiner Upstream-Modus bleibt unverändert', ()=>{ + expect(()=>readAuthConfig({}, { upstreamSecret: 'secret', isLocal: false })).not.toThrow(); + }); + }); + + describe('Issuer-Schema', ()=>{ + test('http-Issuer mit https-HB_PUBLIC_URL bricht ab', ()=>{ + expect(()=>readAuthConfig({ ...base, HB_OIDC_ISSUER: 'http://idp.example' }, own)).toThrow(/https:\/\//); + }); + + test('http-Issuer mit http-HB_PUBLIC_URL ist erlaubt (Dev/Compose)', ()=>{ + expect(()=>readAuthConfig({ ...base, HB_OIDC_ISSUER: 'http://idp:8080', HB_PUBLIC_URL: 'http://localhost:8000' }, own)).not.toThrow(); + }); }); }); diff --git a/server/fork/auth/index.js b/server/fork/auth/index.js index ea8dddb9..f1ecee2d 100644 --- a/server/fork/auth/index.js +++ b/server/fork/auth/index.js @@ -98,7 +98,8 @@ export const createAuthRouter = (config, deps = {})=>{ res.redirect(url); } catch (err) { console.error('OIDC login:', err); - errorPage(res, err.status ?? 502, err.message ?? 'Anmeldung nicht möglich.'); + if(err instanceof OidcCallbackError) return errorPage(res, err.status, err.message); + errorPage(res, 500, 'Anmeldung nicht möglich.'); } }); diff --git a/server/fork/auth/session.spec.js b/server/fork/auth/session.spec.js index 1124d7ee..27fee0c0 100644 --- a/server/fork/auth/session.spec.js +++ b/server/fork/auth/session.spec.js @@ -5,7 +5,7 @@ import { readSession, sealTx, openTx, safeRedirect, SESSION_COOKIE } from './ses const config = readAuthConfig({ HB_PUBLIC_URL : 'http://localhost:8000', HB_OIDC_ISSUER : 'http://idp', HB_OIDC_CLIENT_ID : 'id', HB_OIDC_CLIENT_SECRET : 's', HB_SESSION_SECRET : 'a'.repeat(32) -}); +}, { upstreamSecret: 'eigenes-secret' }); const req = (token)=>({ cookies: { [SESSION_COOKIE]: token } }); const payload = { v: 1, uid: 'u', username: 'bob', iss: 'i', sub: 's' };