middleman: Replace nginx-sso with Pocket ID SSO
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:
1 parent
a3950b9bb3
commit
eeb1f2d15c
14 files changed
+514
-325
No files matched your search
@@ -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;
|
||||
|
||||
@@ -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}''
|
||||
];
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -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" ];
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user