Files
darmanandClaude Opus 5.5 7a68716c1c feat(matrix): Synapse + MAS on jupiter, published by neptun
Homeserver for mgaction.town (@user:mgaction.town). Synapse and the
Matrix Authentication Service share jupiter's postgres; logins are
OIDC-only through Authentik via MAS, since Element X can't use
Synapse's own SSO. neptun serves the apex .well-known delegation plus
matrix. and account. vhosts; the admin API stays tailnet-only.

Synapse's signing key is a sops secret so the federation identity
survives losing the RAID0 array. Covered by checks.matrix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 13:04:52 +02:00

194 lines
7.8 KiB
Nix

{ config, pkgs, lib, ... }:
# Matrix homeserver for mgaction.town: Synapse + Matrix Authentication Service (MAS),
# both on jupiter's postgres. Published by neptun (services/comms/matrix-proxy.nix).
#
# Login is OIDC only: MAS owns every login and delegates to Authentik (app slug
# `matrix`, client id below). Element X only supports SSO through MAS, not through
# Synapse's own oidc_providers, and adding MAS later is a one-way migration.
# Admin: `sudo -u matrix-authentication-service mas manage promote-admin <user>`.
let
cfg = config.homelab.matrix;
mas = pkgs.matrix-authentication-service;
synapseUser = config.users.users.matrix-synapse.name;
masUser = "matrix-authentication-service";
mediaDir = "/mnt/data/AppData/matrix-synapse";
# Only file paths in here, the config itself is world-readable in the store.
masConfig = (pkgs.formats.yaml { }).generate "mas-config.yaml" {
http = {
public_base = "https://account.mgaction.town/";
# neptun proxies over the tailnet, outside MAS's default private ranges.
trusted_proxies = [ "127.0.0.0/8" "::1/128" "100.64.0.0/10" "fd7a:115c:a1e0::/48" ];
listeners = [{
name = "web";
resources = map (name: { inherit name; })
[ "discovery" "human" "oauth" "compat" "graphql" "assets" ];
binds = [{ address = "[::]:8080"; }];
}];
};
database = {
socket = "/run/postgresql";
username = masUser;
database = masUser;
};
matrix = {
kind = "synapse";
homeserver = "mgaction.town";
endpoint = "http://localhost:8008";
secret_file = cfg.masSecretFile;
};
secrets = {
encryption_file = cfg.masEncryptionFile;
keys = [{ key_file = cfg.masSigningKeyFile; }];
};
passwords.enabled = false;
upstream_oauth2.providers = [{
id = "01M5EYGX82FRWPDQDB8EY79JYW"; # stable, part of the Authentik redirect URI
human_name = "Authentik";
issuer = "https://auth.mgaction.town/application/o/matrix/";
client_id = cfg.oidcClientId;
client_secret_file = cfg.oidcClientSecretFile;
token_endpoint_auth_method = "client_secret_basic";
scope = "openid profile email";
claims_imports = {
# Matrix localparts must be lowercase; fixed at first login.
localpart = { action = "require"; template = "{{ user.preferred_username | lower }}"; };
displayname = { action = "force"; template = "{{ user.name }}"; };
email = { action = "force"; template = "{{ user.email }}"; };
};
# Otherwise "sign out" bounces straight back in through Authentik's session.
additional_authorization_parameters.prompt = "{% if logged_out %}login{% endif %}";
}];
};
masCli = pkgs.writeShellScriptBin "mas" ''
MAS_CONFIG=${masConfig} exec ${mas}/bin/mas-cli "$@"
'';
in
{
options.homelab.matrix = {
signingKeyFile = lib.mkOption { type = lib.types.str; description = "Synapse federation signing key; losing it breaks federation under mgaction.town."; };
macaroonSecretFile = lib.mkOption { type = lib.types.str; };
formSecretFile = lib.mkOption { type = lib.types.str; };
masSecretFile = lib.mkOption { type = lib.types.str; description = "Shared Synapse<->MAS secret, readable by group matrix-synapse."; };
masEncryptionFile = lib.mkOption { type = lib.types.str; description = "64 hex chars; never change after first start."; };
masSigningKeyFile = lib.mkOption { type = lib.types.str; description = "RSA private key (PEM)."; };
oidcClientId = lib.mkOption { type = lib.types.str; default = "matrix"; };
oidcClientSecretFile = lib.mkOption { type = lib.types.str; };
};
config = {
services.matrix-synapse = {
enable = true;
settings = {
server_name = "mgaction.town";
public_baseurl = "https://matrix.mgaction.town/";
listeners = [
{
# Not in allowedTCPPorts: only neptun reaches it, via trusted tailscale0.
port = 8008;
bind_addresses = [ "::" ]; # dual-stack, covers IPv4 too
type = "http";
tls = false;
x_forwarded = true;
resources = [{ names = [ "client" "federation" ]; compress = false; }];
}
{
port = 9001;
bind_addresses = [ "127.0.0.1" ];
type = "metrics";
tls = false;
resources = [ ];
}
];
enable_metrics = true;
report_stats = false;
signing_key_path = cfg.signingKeyFile;
macaroon_secret_key_path = cfg.macaroonSecretFile;
form_secret_path = cfg.formSecretFile;
matrix_authentication_service = {
enabled = true;
endpoint = "http://localhost:8080/";
secret_path = cfg.masSecretFile;
};
password_config.enabled = false; # MAS refuses to start alongside it
media_store_path = mediaDir;
max_upload_size = "100M";
# Federated rooms cache every remote image forever otherwise.
media_retention.remote_media_lifetime = "90d";
# Federation is open, so keep members' profiles to people they share rooms with.
require_auth_for_profile_requests = true;
limit_profile_requests_to_users_who_share_rooms = true;
# No public room directory on a friends & family server.
room_list_publication_rules = [{ action = "deny"; }];
};
};
users.users.matrix-synapse.extraGroups = [ "users" ]; # traverse /mnt/data/AppData
systemd.services.matrix-synapse.unitConfig.RequiresMountsFor = [ mediaDir ];
users.users.${masUser} = {
isSystemUser = true;
group = masUser;
extraGroups = [ synapseUser ]; # read cfg.masSecretFile
};
users.groups.${masUser} = { };
systemd.services.matrix-authentication-service = {
description = "Matrix Authentication Service";
after = [ "postgresql.target" "network-online.target" ];
requires = [ "postgresql.target" ];
wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ];
environment.MAS_CONFIG = masConfig;
serviceConfig = {
User = masUser;
Group = masUser;
ExecStart = "${mas}/bin/mas-cli server";
Restart = "on-failure";
NoNewPrivileges = true;
PrivateTmp = true;
PrivateDevices = true;
ProtectSystem = "strict";
ProtectHome = true;
ProtectKernelTunables = true;
ProtectKernelModules = true;
ProtectControlGroups = true;
RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_UNIX" ];
};
};
environment.systemPackages = [ masCli ];
# Synapse requires C collation, so its DB can't come from ensureDatabases (cluster
# default locale); immich's existing cluster also means initialScript never runs.
services.postgresql = {
enable = true;
ensureDatabases = [ masUser ];
ensureUsers = [
{ name = synapseUser; }
{ name = masUser; ensureDBOwnership = true; }
];
};
systemd.services.postgresql-setup.serviceConfig.ExecStartPost =
let
sqlFile = pkgs.writeText "matrix-synapse-db.sql" ''
SELECT format('CREATE DATABASE %I OWNER %I TEMPLATE template0 ENCODING %L LC_COLLATE %L LC_CTYPE %L',
'${synapseUser}', '${synapseUser}', 'UTF8', 'C', 'C')
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = '${synapseUser}') \gexec
'';
in
[ "${lib.getExe' config.services.postgresql.package "psql"} -d postgres -f ${sqlFile}" ];
# A missing ReadWritePaths entry fails synapse's namespace setup. One level only:
# tmpfiles skips anything nested under a dir owned by another non-root user
# ("unsafe path transition"), and AppData is darman's.
systemd.tmpfiles.rules = [ "d ${mediaDir} 0700 matrix-synapse matrix-synapse -" ];
};
}