middleman: Replace nginx-sso with Pocket ID SSO
CI / Check, build and cache nixfiles (push) Canceled after 25m17s
Update docs / update (push) Failing after 1m53s

Gate the vhosts without their own sign-in with oauth2-proxy, which
signs in with Pocket ID and allows members of the `admins` group.
Each gated vhost serves its own `/oauth2/` endpoints with a host-only
session cookie, so other `.nul.ie` sites never receive it. Sessions
last a week, and a refresh token lets oauth2-proxy check back with
Pocket ID every hour without a passkey.

Add `my.pocket-id`, which declares Pocket ID groups and OIDC clients
in Nix; `pocket-id-sync` applies them through the API with a static
API key that nginx keeps from outside requests. This lets apps move
to Pocket ID with their client defined next to them, with secrets
from `slop secret generate`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit was merged in pull request #12.
This commit is contained in:
jackos1998andClaude Opus 5.5 authored and Jack O'Sullivan committed 2026-11-27 00:15:06 +00:00
1 parent a3950b9bb3
commit eeb1f2d15c
14 files changed
+514 -325

No files matched your search

+1 -1
View File
@@ -42,7 +42,7 @@ Physical host and public-infrastructure hub — see [`sites/colony/README.md`](s
```
colony (physical VM host, ams1)
├── estuary ── edge router: WAN, firewall/NAT, DNS, BGP (AS211024), WireGuard
├── shill ──── NixOS container host ──┬── middleman (reverse proxy, ACME, nginx-sso, librespeed)
├── shill ──── NixOS container host ──┬── middleman (reverse proxy, ACME, Pocket ID, librespeed)
│ ├── vaultwarden (password manager)
│ ├── colony-psql (shared PostgreSQL)
│ ├── chatterbox (Matrix Synapse + bridges)
+1 -1
View File
@@ -187,7 +187,7 @@ descriptions) see [`reference/nixos-options.md`](reference/nixos-options.md).
| `vms` | `my.vms.instances` — QEMU/KVM VMs as systemd units: TAP/bridge networking, LVM-backed disks, VFIO host-device passthrough (with udev tagging), UEFI, SPICE/TTY/QMP unix sockets under `/run/vms/`, clean shutdown via QMP `system_powerdown`. |
| `network` | Baseline networking: networkd only (`useDHCP = false`), IPv6 on, resolved domain/negative-cache settings; dev VMs get DHCP on `eth0` and an SSH port forward. |
| `pdns` | `my.pdns` — PowerDNS: authoritative server driven by BIND-style zone files (with templating and serial management) and recursor extra-settings wiring. |
| `nginx-sso` | `my.nginx-sso` — runs `nginx-sso` (instead of the stock NixOS module) and generates per-instance nginx `auth_request` include files. |
| `pocket-id` | `my.pocket-id` — Pocket ID with user groups and OIDC clients declared in Nix; `pocket-id-sync` applies them through the API with a static API key. |
| `gui` | `my.gui.enable` (default on) — desktop baseline: graphics, polkit, swaylock PAM entry, Android udev rules, screenshot tmpdir. |
| `l2mesh` | Consumes `nixos.vpns.l2` — builds the VXLAN + IPsec layer-2 meshes between edge routers; see [networking.md](networking.md). |
| `borgthin` | `my.borgthin.jobs` — borg backups of thin-LVM snapshots to local or SSH repos on a systemd timer, with pruning. |
+1 -1
View File
@@ -48,7 +48,7 @@ their current addresses. Each container has its own page:
| Container | Role |
|---|---|
| [`middleman`](containers/middleman.md) | Reverse proxy, ACME, nginx-sso, librespeed, Paseo relay |
| [`middleman`](containers/middleman.md) | Reverse proxy, ACME, Pocket ID and SSO, librespeed, Paseo relay |
| [`vaultwarden`](containers/vaultwarden.md) | Password manager |
| [`colony-psql`](containers/colony-psql.md) | Shared PostgreSQL (14) |
| [`chatterbox`](containers/chatterbox.md) | Matrix Synapse + bridges |
+44 -17
View File
@@ -2,11 +2,11 @@
The front-end reverse proxy for the colony's public web services — the single ingress that
`estuary` DNATs HTTP/HTTPS (and Matrix federation on `:8448`) to. Terminates TLS with wildcard
certificates it issues itself, provides nginx-sso for gated vhosts, and runs the Pocket ID
identity provider, a librespeed backend and a Paseo relay.
certificates it issues itself, runs the Pocket ID identity provider with oauth2-proxy in front of
gated vhosts, and runs a librespeed backend and a Paseo relay.
- **Source:** [`shill/containers/middleman/`](../../../../../nixos/boxes/colony/vms/shill/containers/middleman)
(`default.nix`, `vhosts.nix`)
(`default.nix`, `auth.nix`, `vhosts.nix`)
- **Host:** NixOS container on [`shill`](../README.md) (`my.containers` ephemeral nspawn on the
`ctrs` bridge; bind-mounts `/mnt/media` read-only for the static file vhosts)
- **nixpkgs:** `mine`
@@ -32,24 +32,51 @@ also waits for `colony-psql` through `systemdAwaitPostgres`, avoiding an early-b
`mailcow-ssl-reload` there.
- Renewal reloads nginx; the `acme` group owns the secret files and includes the nginx user.
### nginx-sso
The `generic` SSO instance at `sso.nul.ie` uses Google OAuth by default and also offers a simple
username/password provider. Its cookie domain is `.nul.ie`; gated vhosts include the generated
`server-generic.conf` / `location-generic.conf` snippets from `/etc/nginx/includes/sso/`.
### Pocket ID
[Pocket ID](https://pocket-id.org) (`services.pocket-id`) is a passkey-only OpenID Connect
provider at `id.nul.ie`, for apps that sign in with OIDC (first the `slop-broker` approvals web
app, see [`slop-broker.md`](../../../../slop-broker.md#approvals-web-app)). It is meant to replace nginx-sso's
Google sign-in later, with oauth2-proxy in front of apps that lack OIDC.
provider at `id.nul.ie`. Apps with OIDC support sign in with it directly (such as the
[`slop-broker` approvals web app](../../../../slop-broker.md#approvals-web-app)); the rest go
through [oauth2-proxy](#sso).
- Listens on `127.0.0.1:1411` behind nginx and keeps its SQLite database in `/var/lib/pocket-id`
(persisted by `my.tmproot`). The `middleman/pocket-id-encryption-key` secret encrypts it.
- The first admin is created at `/setup`; nginx only allows that page and its API from
internal networks (`lib.my.c.internalNets`). Further users are added from the admin UI.
**Declared groups and clients.** `my.pocket-id` (in
[`auth.nix`](../../../../../nixos/boxes/colony/vms/shill/containers/middleman/auth.nix)) declares
user groups and OIDC clients; `pocket-id-sync` creates and updates them through the API on every
switch.
- It authenticates with the static API key `middleman/pocket-id-api-key`. nginx strips
`X-API-Key` from outside requests, so API keys only work from inside the container.
- Clients and groups that aren't declared are left alone, as is group membership: add users to
groups in the admin UI.
- A client's secret is an age file shared with the box that runs the app (or a key of an env
file). Generate it with `slop secret generate`; after rotating one, restart `pocket-id-sync`.
### SSO
[oauth2-proxy](https://oauth2-proxy.github.io/oauth2-proxy/) signs users in with Pocket ID (client
`sso`) for vhosts with no sign-in of their own.
- `ssoServer [ <groups> ]` in `vhosts.nix` gates a vhost with nginx `auth_request`, allowing
members of any of the given Pocket ID groups. The gated vhosts currently allow `admins`.
- Each gated vhost serves oauth2-proxy's `/oauth2/` endpoints itself. Its session cookie is
host-only, so other `.nul.ie` sites (including `*.slop.nul.ie` previews) never receive it.
Pocket ID's own session turns signing in to another gated vhost into a redirect.
- The `sso` client's callback URLs are derived from the gated vhosts.
- Sessions last a week. Every hour, oauth2-proxy uses a refresh token to check back with Pocket
ID without a passkey, and picks up the user's current groups. A disabled user is signed out at
the next check; someone removed from a group loses access once their access token expires (an
hour at most, Pocket ID's default).
- A location in a gated vhost with its own `add_header` would drop the refreshed session cookie
that `ssoServer` passes on.
- Its client secret and cookie secret are in the env file `middleman/oauth2-proxy.env`.
- `id.nul.ie` resolves to the container itself, so oauth2-proxy reaches Pocket ID through the
local nginx.
### librespeed
The frontend and backend are published as `speed.nul.ie` and `librespeed.ams1.int.nul.ie`, both
@@ -80,14 +107,13 @@ rewrites outbound IPv6 to the container's own address on `host0`.
## Published vhosts
Everything is under `*.nul.ie` with the public wildcard cert unless noted; defaults applied to
all vhosts are `onlySSL`, kTLS and HTTP/2. "SSO" = gated behind nginx-sso (`generic` instance).
all vhosts are `onlySSL`, kTLS and HTTP/2. "SSO" = gated behind [oauth2-proxy](#sso).
| Host | Upstream | Notes |
| --- | --- | --- |
| `nul.ie` (`_`, default) | static | landing page (`index.html`, CV PDF, SSH pubkey); serves Matrix `.well-known`s and redirects `webfinger`/`nodeinfo`/`host-meta` → `toot.nul.ie`, `atproto-did` → `pds.nul.ie`; `forceSSL` (plain HTTP redirects to HTTPS) |
| `localhost` | — | loopback-only VTS status page at `/status` (scraped by netdata); plain HTTP |
| `sso.nul.ie` | `localhost:8082` | nginx-sso endpoint |
| `id.nul.ie` | `localhost:1411` | Pocket ID; `/setup` only from internal networks |
| `id.nul.ie` | `localhost:1411` | Pocket ID; `/setup` only from internal networks; `X-API-Key` stripped |
| `netdata-colony.nul.ie` | `<host>.ams1.int.nul.ie:19999` | netdata fan-out over `vm`, `fw`, `ctr`, `oci`, `http`, `jackflix-ctr`, `chatterbox-ctr`, `colony-psql-ctr`; **SSO** |
| `pass.nul.ie` | `vaultwarden-ctr:8080` | [vaultwarden](vaultwarden.md); `/notifications/hub` proxied with websockets |
| `matrix.nul.ie` | `chatterbox-ctr:8008` | [chatterbox](chatterbox.md) Synapse client + federation; also listens on `:8448` as federation `default_server`; `= /` redirects to Element; serves Matrix `.well-known`s |
@@ -122,6 +148,7 @@ all vhosts are `onlySSL`, kTLS and HTTP/2. "SSO" = gated behind nginx-sso (`gene
## Notable config files
- [`nixos/boxes/colony/vms/shill/containers/middleman/default.nix`](../../../../../nixos/boxes/colony/vms/shill/containers/middleman/default.nix) — container definition: nginx, ACME, nginx-sso, Pocket ID, librespeed, Paseo relay, secrets
- [`nixos/boxes/colony/vms/shill/containers/middleman/vhosts.nix`](../../../../../nixos/boxes/colony/vms/shill/containers/middleman/vhosts.nix) — all virtual hosts, the SSO include helpers, and the `.well-known` tree
- [`nixos/boxes/colony/vms/shill/containers/middleman/default.nix`](../../../../../nixos/boxes/colony/vms/shill/containers/middleman/default.nix) — container definition: nginx, ACME, librespeed, Paseo relay, secrets
- [`nixos/boxes/colony/vms/shill/containers/middleman/auth.nix`](../../../../../nixos/boxes/colony/vms/shill/containers/middleman/auth.nix) — Pocket ID, its declared groups and clients, oauth2-proxy
- [`nixos/boxes/colony/vms/shill/containers/middleman/vhosts.nix`](../../../../../nixos/boxes/colony/vms/shill/containers/middleman/vhosts.nix) — all virtual hosts, the `ssoServer` helper, and the `.well-known` tree
- [`nixos/boxes/colony/vms/shill/containers/middleman/default.html`](../../../../../nixos/boxes/colony/vms/shill/containers/middleman/default.html) — default vhost landing page
@@ -0,0 +1,105 @@
{ lib, config, ... }:
let
inherit (lib) attrNames filterAttrs;
inherit (lib.my.c) pubDomain;
# Vhosts gated by `ssoServer` in `vhosts.nix`, each with its own `/oauth2/` endpoints
ssoVhosts = attrNames (filterAttrs (_: v: v.locations ? "= /oauth2/auth") config.services.nginx.virtualHosts);
in
{
my = {
secrets.files = {
# Pocket ID's database encryption key; it reads it through `LoadCredential`
"middleman/pocket-id-encryption-key" = { };
# Admin key for `pocket-id-sync`, which only works from inside (`vhosts.nix` strips it)
"middleman/pocket-id-api-key" = { };
# `OAUTH2_PROXY_CLIENT_SECRET` and `OAUTH2_PROXY_COOKIE_SECRET`
"middleman/oauth2-proxy.env" = { };
};
pocket-id = {
enable = true;
apiKeyFile = config.age.secrets."middleman/pocket-id-api-key".path;
groups = {
admins.friendlyName = "Admins";
};
clients = {
# oauth2-proxy, which gates vhosts that have no sign-in of their own (`ssoServer`)
sso = {
name = "nul.ie SSO";
callbackURLs = map (h: "https://${h}/oauth2/callback") ssoVhosts;
pkce = true;
allowedGroups = [ "admins" ];
extraSettings.skipConsent = true;
secret = {
file = config.age.secrets."middleman/oauth2-proxy.env".path;
key = "OAUTH2_PROXY_CLIENT_SECRET";
};
};
};
};
};
# oauth2-proxy talks to Pocket ID through the local nginx rather than out and back in
networking.hosts = {
"127.0.0.1" = [ "id.${pubDomain}" ];
"::1" = [ "id.${pubDomain}" ];
};
services = {
# Passkey-only OpenID Connect provider at `id.nul.ie`, published by nginx
pocket-id = {
settings = {
APP_URL = "https://id.${pubDomain}";
HOST = "127.0.0.1";
PORT = 1411;
TRUST_PROXY = true;
ANALYTICS_DISABLED = true;
};
credentials.ENCRYPTION_KEY = config.age.secrets."middleman/pocket-id-encryption-key".path;
};
# Single sign-on for every `.nul.ie` vhost behind `ssoServer` in `vhosts.nix`
oauth2-proxy = {
enable = true;
provider = "oidc";
oidcIssuerUrl = "https://id.${pubDomain}";
clientID = "sso";
# On the vhost being signed in to
redirectURL = "/oauth2/callback";
keyFile = config.age.secrets."middleman/oauth2-proxy.env".path;
# `offline_access` for a refresh token, so sessions can be checked again without a passkey
scope = "openid email profile groups offline_access";
approvalPrompt = "auto";
# Access is decided by Pocket ID group (`allowed_groups` in `ssoServer`)
email.domains = [ "*" ];
httpAddress = "http://127.0.0.1:4180";
reverseProxy = true;
trustedProxyIP = [ "127.0.0.1" ];
setXauthrequest = true;
cookie = {
# Host-only, so the cookie is only sent to the vhost it was issued for
secure = true;
# Sessions last a week, but Pocket ID checks the user (and their groups) every hour
expire = "168h";
refresh = "1h";
};
extraConfig = {
code-challenge-method = "S256";
skip-provider-button = true;
# Pocket ID doesn't verify email addresses, and they aren't used for access here
insecure-oidc-allow-unverified-email = true;
};
};
};
systemd.services.oauth2-proxy = {
wants = [ "pocket-id-sync.service" ];
after = [ "pocket-id-sync.service" "nginx.service" ];
};
}
@@ -29,7 +29,7 @@ in
inherit (lib.my) networkdAssignment;
in
{
imports = [ ./vhosts.nix ];
imports = [ ./auth.nix ./vhosts.nix ];
config = mkMerge [
{
@@ -54,17 +54,11 @@ in
group = "acme";
mode = "400";
};
"middleman/nginx-sso.yaml" = {
owner = "nginx-sso";
group = "nginx-sso";
};
"middleman/htpasswd" = {
owner = "nginx";
group = "nginx";
};
"librespeed.toml" = { };
# Pocket ID's database encryption key; it reads it through `LoadCredential`
"middleman/pocket-id-encryption-key" = { };
};
};
@@ -79,56 +73,6 @@ in
'';
};
nginx-sso = {
enable = true;
extraConfigFile = config.age.secrets."middleman/nginx-sso.yaml".path;
configuration = {
listen = {
addr = "[::]";
port = 8082;
};
login = {
title = "${pubDomain} login";
default_redirect = "https://${pubDomain}";
default_method = "google_oauth";
names = {
google_oauth = "Google account";
simple = "Username / password";
};
};
cookie = {
domain = ".${pubDomain}";
secure = true;
};
audit_log = {
targets = [ "fd://stdout" ];
events = [
"access_denied"
"login_success"
"login_failure"
"logout"
#"validate"
];
};
providers = {
simple = {
groups = {
admin = [ "dev" ];
};
};
google_oauth = {
client_id = "545475967061-cag4g1qf0pk33g3pdbom4v69562vboc8.apps.googleusercontent.com";
redirect_url = "https://sso.${pubDomain}/login";
user_id_method = "user-id";
};
};
};
includes = {
endpoint = "http://localhost:8082";
baseURL = "https://sso.${pubDomain}";
};
};
librespeed = {
frontend.servers = [
{
@@ -227,19 +171,6 @@ in
};
services = {
# Passkey-only OpenID Connect provider at `id.nul.ie`, published by nginx
pocket-id = {
enable = true;
settings = {
APP_URL = "https://id.${pubDomain}";
HOST = "127.0.0.1";
PORT = 1411;
TRUST_PROXY = true;
ANALYTICS_DISABLED = true;
};
credentials.ENCRYPTION_KEY = config.age.secrets."middleman/pocket-id-encryption-key".path;
};
netdata = {
enable = true;
configDir = {
@@ -9,14 +9,40 @@ let
dualStackListen' = l: map (addr: l // { inherit addr; }) [ "0.0.0.0" "[::]" ];
dualStackListen = ll: flatten (map dualStackListen' ll);
ssoServer = i: {
# Gate a vhost behind oauth2-proxy, for members of any of the given Pocket ID groups. The
# session cookie is host-only, so other `.nul.ie` sites never see it; Pocket ID's own session
# makes signing in to the next gated vhost a redirect.
oauth2Proxy = config.services.oauth2-proxy.httpAddress;
ssoServer = groups: {
locations = {
"^~ /oauth2/" = {
proxyPass = oauth2Proxy;
extraConfig = ''
auth_request off;
${proxyHeaders}
# Where to return after signing in; on a 401 this is still the original request
proxy_set_header X-Auth-Request-Redirect $request_uri;
'';
};
# A literal `proxy_pass`: `proxyPass` sets `$nix_proxy_target`, which this subrequest would
# overwrite for the main request too
"= /oauth2/auth".extraConfig = ''
proxy_pass ${oauth2Proxy}/oauth2/auth?allowed_groups=${concatStringsSep "," groups};
internal;
auth_request off;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
${proxyHeaders}
'';
};
# A location with its own `add_header` would drop the refreshed cookie
extraConfig = ''
include /etc/nginx/includes/sso/server-${i}.conf;
'';
};
ssoLoc = i: {
extraConfig = ''
include /etc/nginx/includes/sso/location-${i}.conf;
auth_request /oauth2/auth;
error_page 401 = /oauth2/start;
# Pass on the session cookie when a check refreshes it
auth_request_set $sso_cookie $upstream_http_set_cookie;
add_header Set-Cookie $sso_cookie;
'';
};
@@ -58,12 +84,6 @@ let
};
in
{
my = {
nginx-sso.includes.instances = {
generic = {};
};
};
services.nginx.virtualHosts =
let
hosts = {
@@ -111,11 +131,6 @@ in
};
};
"sso.${pubDomain}" = {
locations."/".proxyPass = config.my.nginx-sso.includes.endpoint;
useACMEHost = pubDomain;
};
"netdata-colony.${pubDomain}" =
let
hosts = [
@@ -130,26 +145,23 @@ in
locations = {
"= /".return = "301 https://$host/vm/";
"~ /(?<behost>${matchHosts})$".return = "301 https://$host/$behost/";
"~ /(?<behost>${matchHosts})/(?<ndpath>.*)" = mkMerge [
{
proxyPass = "http://$behost.${domain}:19999/$ndpath$is_args$args";
extraConfig = ''
proxy_pass_request_headers on;
${proxyHeaders}
proxy_set_header Connection "keep-alive";
proxy_store off;
"~ /(?<behost>${matchHosts})/(?<ndpath>.*)" = {
proxyPass = "http://$behost.${domain}:19999/$ndpath$is_args$args";
extraConfig = ''
proxy_pass_request_headers on;
${proxyHeaders}
proxy_set_header Connection "keep-alive";
proxy_store off;
gzip on;
gzip_proxied any;
gzip_types *;
'';
}
(ssoLoc "generic")
];
gzip on;
gzip_proxied any;
gzip_types *;
'';
};
};
useACMEHost = pubDomain;
}
(ssoServer "generic")
(ssoServer [ "admins" ])
];
"pass.${pubDomain}" =
@@ -242,56 +254,40 @@ in
"torrents.${pubDomain}" = mkMerge [
{
locations."/" = mkMerge [
{
proxyPass = "http://jackflix-ctr.${domain}:9091";
}
(ssoLoc "generic")
];
locations."/".proxyPass = "http://jackflix-ctr.${domain}:9091";
useACMEHost = pubDomain;
}
(ssoServer "generic")
(ssoServer [ "admins" ])
];
"jackett.${pubDomain}" = mkMerge [
{
locations."/" = mkMerge [
{
proxyPass = "http://jackflix-ctr.${domain}:9117";
}
(ssoLoc "generic")
];
locations."/".proxyPass = "http://jackflix-ctr.${domain}:9117";
useACMEHost = pubDomain;
}
(ssoServer "generic")
(ssoServer [ "admins" ])
];
"radarr.${pubDomain}" = mkMerge [
{
locations."/" = mkMerge [
{
proxyPass = "http://jackflix-ctr.${domain}:7878";
proxyWebsockets = true;
extraConfig = proxyHeaders;
}
(ssoLoc "generic")
];
locations."/" = {
proxyPass = "http://jackflix-ctr.${domain}:7878";
proxyWebsockets = true;
extraConfig = proxyHeaders;
};
useACMEHost = pubDomain;
}
(ssoServer "generic")
(ssoServer [ "admins" ])
];
"sonarr.${pubDomain}" = mkMerge [
{
locations."/" = mkMerge [
{
proxyPass = "http://jackflix-ctr.${domain}:8989";
proxyWebsockets = true;
extraConfig = proxyHeaders;
}
(ssoLoc "generic")
];
locations."/" = {
proxyPass = "http://jackflix-ctr.${domain}:8989";
proxyWebsockets = true;
extraConfig = proxyHeaders;
};
useACMEHost = pubDomain;
}
(ssoServer "generic")
(ssoServer [ "admins" ])
];
"gib.${pubDomain}" = {
locations."/".proxyPass = "http://jackflix-ctr.${domain}:5055";
@@ -427,9 +423,14 @@ in
"id.${pubDomain}" =
let
# API keys (including `pocket-id-sync`'s admin key) only work from inside
pocketIdHeaders = ''
${proxyHeaders}
proxy_set_header X-API-Key "";
'';
pocketId = {
proxyPass = "http://127.0.0.1:${toString config.services.pocket-id.settings.PORT}";
extraConfig = proxyHeaders;
extraConfig = pocketIdHeaders;
};
in
{
@@ -440,7 +441,7 @@ in
extraConfig = ''
${concatStringsSep "\n" (map (n: "allow ${n};") (with lib.my.c.internalNets; v4 ++ v6))}
deny all;
${proxyHeaders}
${pocketIdHeaders}
'';
};
};
@@ -470,24 +471,18 @@ in
"pront.${pubDomain}" = mkMerge [
{
locations."/" = mkMerge [
{
proxyPass = "http://stream-hi.${home.domain}:5000";
proxyWebsockets = true;
extraConfig = proxyHeaders;
}
(ssoLoc "generic")
];
locations."~* ^/webcam/(.*)" = mkMerge [
{
proxyPass = "http://stream-hi.${home.domain}:5050/$1$is_args$args";
extraConfig = proxyHeaders;
}
(ssoLoc "generic")
];
locations."/" = {
proxyPass = "http://stream-hi.${home.domain}:5000";
proxyWebsockets = true;
extraConfig = proxyHeaders;
};
locations."~* ^/webcam/(.*)" = {
proxyPass = "http://stream-hi.${home.domain}:5050/$1$is_args$args";
extraConfig = proxyHeaders;
};
useACMEHost = pubDomain;
}
(ssoServer "generic")
(ssoServer [ "admins" ])
];
"hass.${pubDomain}" = {
locations."/" = {
+1 -1
View File
@@ -13,7 +13,7 @@
vms = ./vms.nix;
network = ./network.nix;
pdns = ./pdns.nix;
nginx-sso = ./nginx-sso.nix;
pocket-id = ./pocket-id;
gui = ./gui;
l2mesh = ./l2mesh.nix;
borgthin = ./borgthin.nix;
-127
View File
@@ -1,127 +0,0 @@
{ lib, pkgs, config, ... }:
let
inherit (lib) mkIf mkMerge getBin mapAttrsToList;
inherit (lib.my) mkOpt' mkBoolOpt';
includeOpts = { ... }: {
options = with lib.types; {
auth = {
path = mkOpt' str "/sso-auth" "HTTP path for SSO auth.";
redirect = mkOpt' str "$scheme://$http_host$request_uri" "URL to redirect to upon successful login.";
};
logout = {
path = mkOpt' str "/sso-logout" "HTTP path for SSO logout.";
redirect = mkOpt' str "$scheme://$http_host/" "URL to redirect to upon successful logout.";
};
};
};
cfg = config.my.nginx-sso;
pkg = getBin cfg.package;
baseConfig = pkgs.writeText "nginx-sso.yaml" (builtins.toJSON cfg.configuration);
runCfg = "/run/nginx-sso/config.yaml";
in
{
options.my.nginx-sso = with lib.types; {
enable = mkBoolOpt' false "Whether to enable custom nginx-sso.";
package = mkOpt' package pkgs.nginx-sso "nginx-sso package to use.";
configuration = mkOpt' (attrsOf unspecified) { } "nginx-sso configuration.";
extraConfigFile = mkOpt' (nullOr str) null "Path to configuration (e.g. for secrets).";
includes = {
endpoint = mkOpt' str "http://localhost:8082" "Upstream for proxied auth requests.";
baseURL = mkOpt' str null "Base URL for redirects.";
instances = mkOpt' (attrsOf (submodule includeOpts)) { } "nginx includes instances.";
};
};
config = mkIf cfg.enable {
assertions = [
{
assertion = !config.services.nginx.sso.enable;
message = "Stock nginx-sso cannot be used with this module.";
}
];
environment.etc = with cfg.includes; mkMerge (mapAttrsToList (n: i: {
"nginx/includes/sso/server-${n}.conf".text = ''
location ${i.auth.path} {
# Do not allow requests from outside
internal;
# Access /auth endpoint to query login state
proxy_pass ${endpoint}/auth;
# Do not forward the request body (nginx-sso does not care about it)
proxy_pass_request_body off;
proxy_set_header Content-Length "";
# Set custom information for ACL matching: Each one is available as
# a field for matching: X-Host = x-host, ...
proxy_set_header X-Origin-URI $request_uri;
proxy_set_header X-Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# Define where to send the user to login and specify how to get back
location @error401 {
return 302 ${baseURL}/login?go=${i.auth.redirect};
}
# If the user is lead to /logout redirect them to the logout endpoint
# of ngninx-sso which then will redirect the user to / on the current host
location ${i.logout.path} {
return 302 ${baseURL}/logout?go=${i.logout.redirect};
}
'';
"nginx/includes/sso/location-${n}.conf".text = ''
# Protect this location using the auth_request
auth_request ${i.auth.path};
# Redirect the user to the login page when they are not logged in
error_page 401 = @error401;
# Automatically renew SSO cookie on request
auth_request_set $cookie $upstream_http_set_cookie;
add_header Set-Cookie $cookie;
'';
}) instances);
users = {
groups.nginx-sso = {};
users.nginx-sso = {
group = "nginx-sso";
isSystemUser = true;
};
};
systemd.services.nginx-sso = {
description = "Nginx SSO Backend";
after = [ "network.target" ];
wantedBy = [ "multi-user.target" ];
preStart = ''
umask 066
${if (cfg.extraConfigFile != null) then ''
${pkgs.yq-go}/bin/yq -P '. *= load("${cfg.extraConfigFile}")' "${baseConfig}" > ${runCfg}
'' else ''
${pkgs.yq-go}/bin/yq -P "${baseConfig}" > ${runCfg}
''}
'';
serviceConfig = {
RuntimeDirectory = "nginx-sso";
User = "nginx-sso";
Group = "nginx-sso";
ExecStart = [
# Specify twice to clear original value
""
''${pkg}/bin/nginx-sso --frontend-dir ${pkg}/share/frontend --config ${runCfg}''
];
};
};
};
}
+102
View File
@@ -0,0 +1,102 @@
{ lib, pkgs, config, ... }:
let
inherit (lib) mkIf mapAttrsToList filterAttrs;
inherit (lib.my) mkOpt' mkBoolOpt';
cfg = config.my.pocket-id;
pocketId = config.services.pocket-id;
groupOpts = { name, ... }: {
options = with lib.types; {
friendlyName = mkOpt' str name "Name shown in Pocket ID's UI.";
};
};
clientOpts = { name, ... }: {
options = with lib.types; {
name = mkOpt' str name "Name shown to users when they sign in.";
callbackURLs = mkOpt' (listOf str) [ ] "Allowed redirect URLs after sign-in.";
logoutCallbackURLs = mkOpt' (listOf str) [ ] "Allowed redirect URLs after sign-out.";
launchURL = mkOpt' (nullOr str) null "URL that Pocket ID's app list links to.";
public = mkBoolOpt' false "Whether this is a public client (no secret).";
pkce = mkBoolOpt' false "Whether to require PKCE.";
allowedGroups = mkOpt' (listOf str) [ ]
"Pocket ID groups (by name) whose members may sign in; any user may when empty.";
secret = {
file = mkOpt' (nullOr path) null "File holding the client secret.";
key = mkOpt' (nullOr str) null
"Read the secret from this key of an env file instead of the whole file.";
};
extraSettings = mkOpt' (attrsOf unspecified) { }
"Extra fields of Pocket ID's client API object (e.g. `skipConsent`).";
};
};
spec = pkgs.writeText "pocket-id-sync.json" (builtins.toJSON {
groups = mapAttrsToList (n: g: { name = n; inherit (g) friendlyName; }) cfg.groups;
clients = mapAttrsToList (id: c: {
inherit id;
groups = c.allowedGroups;
secret = c.secret.file != null;
secretKey = c.secret.key;
settings = {
inherit (c) name callbackURLs logoutCallbackURLs launchURL;
isPublic = c.public;
pkceEnabled = c.pkce;
isGroupRestricted = c.allowedGroups != [ ];
} // c.extraSettings;
}) cfg.clients;
});
sync = pkgs.writers.writePython3 "pocket-id-sync" {
flakeIgnore = [ "E501" ];
} (builtins.readFile ./sync.py);
in
{
options.my.pocket-id = with lib.types; {
enable = mkBoolOpt' false "Whether to manage Pocket ID groups and OIDC clients declaratively.";
apiKeyFile = mkOpt' path null "File holding Pocket ID's static API key (at least 16 characters).";
groups = mkOpt' (attrsOf (submodule groupOpts)) { }
"User groups to create; membership is managed in Pocket ID.";
clients = mkOpt' (attrsOf (submodule clientOpts)) { } "OIDC clients, by client ID.";
};
config = mkIf cfg.enable {
assertions = mapAttrsToList (id: c: {
assertion = c.public == (c.secret.file == null);
message = "my.pocket-id.clients.${id}: a client needs a secret unless it is public.";
}) cfg.clients;
services.pocket-id = {
enable = true;
credentials.STATIC_API_KEY = cfg.apiKeyFile;
};
systemd.services.pocket-id-sync = {
description = "Pocket ID groups and OIDC clients";
requires = [ "pocket-id.service" ];
after = [ "pocket-id.service" ];
wantedBy = [ "multi-user.target" ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
ExecStart = "${sync} ${spec} http://127.0.0.1:${toString pocketId.settings.PORT}";
DynamicUser = true;
RuntimeDirectory = "pocket-id-sync";
StateDirectory = "pocket-id-sync";
LoadCredential = [ "api-key:${cfg.apiKeyFile}" ]
++ mapAttrsToList (id: c: "client-${id}:${c.secret.file}")
(filterAttrs (_: c: c.secret.file != null) cfg.clients);
CapabilityBoundingSet = "";
NoNewPrivileges = true;
PrivateDevices = true;
PrivateTmp = true;
ProtectHome = true;
ProtectSystem = "strict";
RestrictAddressFamilies = [ "AF_INET" "AF_INET6" ];
};
};
};
}
+151
View File
@@ -0,0 +1,151 @@
"""Create and update Pocket ID user groups and OIDC clients from a JSON spec.
Usage: pocket-id-sync <spec.json> <base URL>
Credentials come from systemd's $CREDENTIALS_DIRECTORY: `api-key` (the static API key) and
`client-<id>` (each confidential client's secret). Hashes of the secrets that were set are
kept in $STATE_DIRECTORY, since Pocket ID only shows a secret's first few characters.
"""
import hashlib
import json
import os
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path
# Fields of a client that the update endpoint accepts
CLIENT_FIELDS = [
'name', 'description', 'callbackURLs', 'logoutCallbackURLs', 'backchannelLogoutURL',
'isPublic', 'pkceEnabled', 'requiresReauthentication', 'requiresPushedAuthorizationRequests',
'skipConsent', 'credentials', 'launchURL', 'hasLogo', 'hasDarkLogo', 'isGroupRestricted',
'accessTokenDurationMinutes', 'refreshTokenDurationMinutes',
]
SECRET_PREFIX_LENGTH = 4
class NotFound(Exception):
pass
class API:
def __init__(self, base, key):
self.base = base
self.key = key
def request(self, method, path, body=None):
data = None if body is None else json.dumps(body).encode()
req = urllib.request.Request(
f'{self.base}/api{path}', data=data, method=method,
headers={'X-API-Key': self.key, 'Content-Type': 'application/json'})
try:
with urllib.request.urlopen(req) as res:
content = res.read()
except urllib.error.HTTPError as e:
if e.code == 404:
raise NotFound(path) from e
raise RuntimeError(f'{method} {path}: HTTP {e.code}: {e.read().decode()}') from e
return json.loads(content) if content else None
def wait(self, timeout=60):
for _ in range(timeout):
try:
with urllib.request.urlopen(f'{self.base}/healthz'):
return
except OSError:
time.sleep(1)
raise RuntimeError('Pocket ID did not become healthy')
def read_secret(path, key):
text = path.read_text()
if key is None:
return text.rstrip('\n')
# A plain env file, as `slop secret` writes it
value = None
for line in text.splitlines():
name, sep, v = line.removeprefix('export ').partition('=')
if sep and name == key:
value = v
if value is None:
raise RuntimeError(f'{path} has no {key}')
if len(value) >= 2 and value[0] == value[-1] == '"':
value = value[1:-1]
return value
def sync_groups(api, groups):
existing = {g['name']: g for g in api.request('GET', '/user-groups?pagination[limit]=1000')['data']}
for group in groups:
current = existing.get(group['name'])
if current is None:
print(f"Creating group {group['name']}")
api.request('POST', '/user-groups', group)
elif current['friendlyName'] != group['friendlyName']:
print(f"Updating group {group['name']}")
api.request('PUT', f"/user-groups/{current['id']}", group)
return {g['name']: g['id'] for g in api.request('GET', '/user-groups?pagination[limit]=1000')['data']}
def sync_secret(api, client_id, value, state_dir):
digest = hashlib.sha256(f'{client_id}\n{value}'.encode()).hexdigest()
state = state_dir / f'{client_id}.sha256'
secrets = api.request('GET', f'/oidc/clients/{client_id}/secrets')
installed = any(s['isActive'] and s['prefix'] == value[:SECRET_PREFIX_LENGTH] for s in secrets)
if installed and state.exists() and state.read_text() == digest:
return
print(f'Setting the secret of client {client_id}')
new = api.request('POST', f'/oidc/clients/{client_id}/secrets', {'secret': value})
for s in secrets:
if s['id'] != new['id']:
api.request('DELETE', f"/oidc/clients/{client_id}/secrets/{s['id']}")
state.write_text(digest)
def sync_client(api, client, group_ids, creds, state_dir):
client_id = client['id']
settings = client['settings']
# Update on top of the current client, so fields managed in the UI (like logos) stay
try:
current = api.request('GET', f'/oidc/clients/{client_id}')
except NotFound:
print(f'Creating client {client_id}')
api.request('POST', '/oidc/clients', {**settings, 'id': client_id})
else:
merged = {**current, **settings}
api.request('PUT', f'/oidc/clients/{client_id}', {f: merged.get(f) for f in CLIENT_FIELDS})
unknown = [g for g in client['groups'] if g not in group_ids]
if unknown:
raise RuntimeError(f'Client {client_id}: unknown groups {unknown}')
api.request('PUT', f'/oidc/clients/{client_id}/allowed-user-groups',
{'userGroupIds': [group_ids[g] for g in client['groups']]})
if client['secret']:
value = read_secret(creds / f'client-{client_id}', client['secretKey'])
sync_secret(api, client_id, value, state_dir)
def main():
spec = json.loads(Path(sys.argv[1]).read_text())
creds = Path(os.environ['CREDENTIALS_DIRECTORY'])
state_dir = Path(os.environ['STATE_DIRECTORY'])
api = API(sys.argv[2], (creds / 'api-key').read_text().strip())
api.wait()
group_ids = sync_groups(api, spec['groups'])
for client in spec['clients']:
sync_client(api, client, group_ids, creds, state_dir)
if __name__ == '__main__':
main()
-23
View File
@@ -1,23 +0,0 @@
-----BEGIN AGE ENCRYPTED FILE-----
YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IHNzaC1lZDI1NTE5IFZGY3c1ZyBjYUdx
QkdtWUFpWTNiSUljaVRtQnRETktCZVYxQkkyQzRTWVhUanJKZDM0CnlhRXFML01Y
ZWVNVDBiS3I1S1NnMDFGUzh4ZUx6eFFuQjlKSTYrWmNDTjAKLT4gWDI1NTE5IHRk
OGNCMTFsN09ua0FHY3JkUjEzREZScCtDVDEwOEZPdzFWa3UvUW5mWEEKVXhubUd3
b2dWMTByUm5IRGZlSmhnU3luNU1RemU0ZElsZy9kOWE2eHNYUQotPiBYMjU1MTkg
b28vSU1RdTB1NG5TRHFZZkREc2l0cWVoOEZJdmhRTWJLS2VEOFN4NVBCZwpGcFFz
U24rTEJhZGdVY3Nla1FkSmZwNStENElLS1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