style: format tree

This commit is contained in:
nhnn
2025-06-18 19:53:44 +03:00
parent ed990906bd
commit 86233cac27
44 changed files with 2523 additions and 2253 deletions

View File

@@ -1,4 +1,9 @@
{ config, lib, pkgs, ... }: {
config,
lib,
pkgs,
...
}:
let let
inherit (lib) inherit (lib)
mkOption mkOption
@@ -7,12 +12,12 @@ let
auth-passthru = config.selfprivacy.passthru.auth; auth-passthru = config.selfprivacy.passthru.auth;
keys-path = auth-passthru.keys-path; keys-path = auth-passthru.keys-path;
# generate OAuth2 client secret # generate OAuth2 client secret
mkKanidmExecStartPreScript = oauthClientID: linuxGroup: mkKanidmExecStartPreScript =
oauthClientID: linuxGroup:
let let
secretFP = auth-passthru.mkOAuth2ClientSecretFP linuxGroup; secretFP = auth-passthru.mkOAuth2ClientSecretFP linuxGroup;
in in
pkgs.writeShellScript pkgs.writeShellScript "${oauthClientID}-kanidm-ExecStartPre-script.sh" ''
"${oauthClientID}-kanidm-ExecStartPre-script.sh" ''
set -o pipefail set -o pipefail
set -o errexit set -o errexit
if ! [ -f "${secretFP}" ] if ! [ -f "${secretFP}" ]
@@ -22,17 +27,16 @@ let
chmod 640 "${secretFP}" chmod 640 "${secretFP}"
fi fi
''; '';
mkKanidmExecStartPostScript = oauthClientID: linuxGroup: isMailserver: mkKanidmExecStartPostScript =
oauthClientID: linuxGroup: isMailserver:
let let
kanidmServiceAccountName = "sp.${oauthClientID}.service-account"; kanidmServiceAccountName = "sp.${oauthClientID}.service-account";
kanidmServiceAccountTokenName = "${oauthClientID}-service-account-token"; kanidmServiceAccountTokenName = "${oauthClientID}-service-account-token";
kanidmServiceAccountTokenFP = kanidmServiceAccountTokenFP = auth-passthru.mkServiceAccountTokenFP linuxGroup;
auth-passthru.mkServiceAccountTokenFP linuxGroup;
isRW = oauthClientID == "selfprivacy-api"; isRW = oauthClientID == "selfprivacy-api";
in in
pkgs.writeShellScript pkgs.writeShellScript "${oauthClientID}-kanidm-ExecStartPost-script.sh" (
"${oauthClientID}-kanidm-ExecStartPost-script.sh" ''
(''
export HOME=$RUNTIME_DIRECTORY/client_home export HOME=$RUNTIME_DIRECTORY/client_home
readonly KANIDM="${pkgs.kanidm}/bin/kanidm" readonly KANIDM="${pkgs.kanidm}/bin/kanidm"
@@ -87,8 +91,7 @@ in
{ {
options.selfprivacy.auth = { options.selfprivacy.auth = {
clients = mkOption { clients = mkOption {
description = description = "Configurations for OAuth2 & LDAP servers clients services. Corresponding Kanidm provisioning configuration and systemd scripts are generated.";
"Configurations for OAuth2 & LDAP servers clients services. Corresponding Kanidm provisioning configuration and systemd scripts are generated.";
default = { }; default = { };
type = types.attrsOf ( type = types.attrsOf (
types.submodule { types.submodule {
@@ -107,69 +110,58 @@ in
}; };
enablePkce = mkOption { enablePkce = mkOption {
type = lib.types.bool; type = lib.types.bool;
description = description = "Whether PKCE must be used between client and Kanidm.";
"Whether PKCE must be used between client and Kanidm.";
default = false; default = false;
}; };
adminsGroup = mkOption { adminsGroup = mkOption {
type = type = types.nullOr (lib.types.strMatching "sp\.[A-Za-z0-9]+\.admins");
types.nullOr (lib.types.strMatching "sp\.[A-Za-z0-9]+\.admins"); description = "Name of admins group in Kanidm, whose members have admin level access to resources (service) associated with OAuth2 client authorization.";
description =
"Name of admins group in Kanidm, whose members have admin level access to resources (service) associated with OAuth2 client authorization.";
default = null; default = null;
}; };
usersGroup = mkOption { usersGroup = mkOption {
type = type = types.nullOr (lib.types.strMatching "sp\.[A-Za-z0-9]+\.users");
types.nullOr (lib.types.strMatching "sp\.[A-Za-z0-9]+\.users"); description = "Name of users group in Kanidm, whose members have user level access to resources (service) associated with OAuth2 client authorization.";
description =
"Name of users group in Kanidm, whose members have user level access to resources (service) associated with OAuth2 client authorization.";
default = null; default = null;
}; };
originLanding = mkOption { originLanding = mkOption {
type = types.nullOr lib.types.str; type = types.nullOr lib.types.str;
description = description = "The origin landing of the service for OAuth2 redirects.";
"The origin landing of the service for OAuth2 redirects.";
}; };
originUrl = mkOption { originUrl = mkOption {
type = types.nullOr lib.types.str; type = types.nullOr lib.types.str;
description = description = "The origin URL of the service for OAuth2 redirects.";
"The origin URL of the service for OAuth2 redirects.";
}; };
subdomain = lib.mkOption { subdomain = lib.mkOption {
type = type = lib.types.strMatching "[A-Za-z0-9][A-Za-z0-9\-]{0,61}[A-Za-z0-9]";
lib.types.strMatching "[A-Za-z0-9][A-Za-z0-9\-]{0,61}[A-Za-z0-9]";
description = "Subdomain of the service."; description = "Subdomain of the service.";
}; };
# when true, "name" is passed to a service instead of "name@domain" # when true, "name" is passed to a service instead of "name@domain"
useShortPreferredUsername = mkOption { useShortPreferredUsername = mkOption {
description = description = "Use 'name' instead of 'spn' in the preferred_username claim.";
"Use 'name' instead of 'spn' in the preferred_username claim.";
type = types.bool; type = types.bool;
default = true; default = true;
}; };
linuxUserOfClient = mkOption { linuxUserOfClient = mkOption {
type = types.nullOr lib.types.str; type = types.nullOr lib.types.str;
description = description = "Name of a Linux OAuth2 client user, under which it should get access through a folder with keys.";
"Name of a Linux OAuth2 client user, under which it should get access through a folder with keys.";
default = null; default = null;
}; };
linuxGroupOfClient = mkOption { linuxGroupOfClient = mkOption {
type = types.nullOr lib.types.str; type = types.nullOr lib.types.str;
description = description = "Name of Linux OAuth2 client group, under which it should read an OAuth2 client secret file.";
"Name of Linux OAuth2 client group, under which it should read an OAuth2 client secret file.";
default = null; default = null;
}; };
isTokenNeeded = mkOption { isTokenNeeded = mkOption {
description = description = "Whether a read-only needs to be generated for LDAP access.";
"Whether a read-only needs to be generated for LDAP access.";
type = types.bool; type = types.bool;
default = false; default = false;
}; };
clientSystemdUnits = mkOption { clientSystemdUnits = mkOption {
description = "A list of systemd services, which depend on OAuth service"; description = "A list of systemd services, which depend on OAuth service";
# taken from nixos/lib/systemd-lib.nix: unitNameType # taken from nixos/lib/systemd-lib.nix: unitNameType
type = types.listOf type = types.listOf (
(types.strMatching "[a-zA-Z0-9@%:_.\\-]+[.](service|socket|device|mount|automount|swap|target|path|timer|scope|slice)"); types.strMatching "[a-zA-Z0-9@%:_.\\-]+[.](service|socket|device|mount|automount|swap|target|path|timer|scope|slice)"
);
}; };
scopeMaps = mkOption { scopeMaps = mkOption {
description = '' description = ''
@@ -231,111 +223,108 @@ in
}; };
config = lib.mkIf config.selfprivacy.sso.enable ( config = lib.mkIf config.selfprivacy.sso.enable (
let let
clientsAttrsList = lib.attrsets.mapAttrsToList clientsAttrsList = lib.attrsets.mapAttrsToList (
(name: attrs: attrs // rec { name: attrs:
clientID = attrs
if attrs.clientID == null // rec {
then name clientID = if attrs.clientID == null then name else attrs.clientID;
else attrs.clientID; displayName = if attrs.displayName == null then clientID else attrs.displayName;
displayName = adminsGroup = if attrs.adminsGroup == null then "sp.${clientID}.admins" else attrs.adminsGroup;
if attrs.displayName == null usersGroup = if attrs.usersGroup == null then "sp.${clientID}.users" else attrs.usersGroup;
then clientID basicSecretFile = "${keys-path}/${linuxGroupOfClient}/kanidm-oauth-client-secret";
else attrs.displayName; linuxUserOfClient = if attrs.linuxUserOfClient == null then clientID else attrs.linuxUserOfClient;
adminsGroup =
if attrs.adminsGroup == null
then "sp.${clientID}.admins"
else attrs.adminsGroup;
usersGroup =
if attrs.usersGroup == null
then "sp.${clientID}.users"
else attrs.usersGroup;
basicSecretFile =
"${keys-path}/${linuxGroupOfClient}/kanidm-oauth-client-secret";
linuxUserOfClient =
if attrs.linuxUserOfClient == null
then clientID
else attrs.linuxUserOfClient;
linuxGroupOfClient = linuxGroupOfClient =
if attrs.linuxGroupOfClient == null if attrs.linuxGroupOfClient == null then clientID else attrs.linuxGroupOfClient;
then clientID
else attrs.linuxGroupOfClient;
originLanding = originLanding =
if attrs.originLanding == null if attrs.originLanding == null then
then "https://${attrs.subdomain}.${config.selfprivacy.domain}/" "https://${attrs.subdomain}.${config.selfprivacy.domain}/"
else attrs.originLanding; else
attrs.originLanding;
scopeMaps = scopeMaps =
if attrs.scopeMaps == null if attrs.scopeMaps == null then
then { "${usersGroup}" = [ "email" "openid" "profile" ]; } {
else attrs.scopeMaps; "${usersGroup}" = [
}) "email"
config.selfprivacy.auth.clients; "openid"
"profile"
];
}
else
attrs.scopeMaps;
}
) config.selfprivacy.auth.clients;
in in
{ {
# for each OAuth2 client: member of the `keys` group for directory access # for each OAuth2 client: member of the `keys` group for directory access
users.groups.keys.members = lib.mkMerge (lib.forEach users.groups.keys.members = lib.mkMerge (
clientsAttrsList lib.forEach clientsAttrsList ({ linuxUserOfClient, ... }: [ linuxUserOfClient ])
({ linuxUserOfClient, ... }: [ linuxUserOfClient ])
); );
systemd.tmpfiles.settings."kanidm-secrets" = lib.mkMerge (lib.forEach systemd.tmpfiles.settings."kanidm-secrets" = lib.mkMerge (
clientsAttrsList lib.forEach clientsAttrsList (
({ linuxGroupOfClient, ... }: { { linuxGroupOfClient, ... }:
{
"${keys-path}/${linuxGroupOfClient}".d = { "${keys-path}/${linuxGroupOfClient}".d = {
user = "kanidm"; user = "kanidm";
group = linuxGroupOfClient; group = linuxGroupOfClient;
mode = "2750"; mode = "2750";
}; };
}) }
)
); );
# for each OAuth2 client: scripts with Kanidm CLI commands # for each OAuth2 client: scripts with Kanidm CLI commands
systemd.services.kanidm = { systemd.services.kanidm = {
before = before = lib.lists.concatMap ({ clientSystemdUnits, ... }: clientSystemdUnits) clientsAttrsList;
lib.lists.concatMap serviceConfig = lib.mkMerge (
({ clientSystemdUnits, ... }: clientSystemdUnits) lib.forEach clientsAttrsList (
clientsAttrsList; {
serviceConfig = clientID,
lib.mkMerge (lib.forEach isTokenNeeded,
clientsAttrsList linuxGroupOfClient,
({ clientID, isTokenNeeded, linuxGroupOfClient, isMailserver, ... }: isMailserver,
...
}:
{ {
ExecStartPre = [ ExecStartPre = [
# "-" prefix means to ignore exit code of prefixed script # "-" prefix means to ignore exit code of prefixed script
("-" + mkKanidmExecStartPreScript clientID linuxGroupOfClient) ("-" + mkKanidmExecStartPreScript clientID linuxGroupOfClient)
]; ];
ExecStartPost = lib.mkIf isTokenNeeded ExecStartPost = lib.mkIf isTokenNeeded (
(lib.mkAfter [ lib.mkAfter [
("-" + ("-" + mkKanidmExecStartPostScript clientID linuxGroupOfClient isMailserver)
mkKanidmExecStartPostScript ]
clientID );
linuxGroupOfClient }
isMailserver) )
]); );
}));
}; };
# for each OAuth2 client: Kanidm provisioning options # for each OAuth2 client: Kanidm provisioning options
services.kanidm.provision = lib.mkMerge (lib.forEach services.kanidm.provision = lib.mkMerge (
clientsAttrsList lib.forEach clientsAttrsList (
({ adminsGroup {
, basicSecretFile adminsGroup,
, claimMaps basicSecretFile,
, clientID claimMaps,
, displayName clientID,
, enablePkce displayName,
, imageFile enablePkce,
, originLanding imageFile,
, originUrl originLanding,
, scopeMaps originUrl,
, useShortPreferredUsername scopeMaps,
, usersGroup useShortPreferredUsername,
, ... usersGroup,
}: { ...
}:
{
groups = lib.mkIf (clientID != "selfprivacy-api") { groups = lib.mkIf (clientID != "selfprivacy-api") {
"${adminsGroup}".members = "${adminsGroup}".members = [ auth-passthru.admins-group ];
[ auth-passthru.admins-group ]; "${usersGroup}".members = [
"${usersGroup}".members = adminsGroup
[ adminsGroup auth-passthru.full-users-group ]; auth-passthru.full-users-group
];
}; };
systems.oauth2.${clientID} = { systems.oauth2.${clientID} = {
inherit inherit
@@ -357,7 +346,9 @@ in
# supplementaryScopeMaps."${admins-group}" = # supplementaryScopeMaps."${admins-group}" =
# [ "read:admin" "write:admin" ]; # [ "read:admin" "write:admin" ];
}; };
})); }
)
);
} }
); );
} }

View File

@@ -1,4 +1,9 @@
{ config, lib, pkgs, ... }: {
config,
lib,
pkgs,
...
}:
let let
domain = config.selfprivacy.domain; domain = config.selfprivacy.domain;
subdomain = "auth"; subdomain = "auth";
@@ -38,7 +43,6 @@ lib.mkIf config.selfprivacy.sso.enable {
"127.0.0.1" = [ auth-fqdn ]; "127.0.0.1" = [ auth-fqdn ];
}; };
# kanidm uses TLS in internal connection with nginx too # kanidm uses TLS in internal connection with nginx too
# FIXME revise this: maybe kanidm must not have access to a public TLS # FIXME revise this: maybe kanidm must not have access to a public TLS
users.groups."acmereceivers".members = [ "kanidm" ]; users.groups."acmereceivers".members = [ "kanidm" ];
@@ -69,16 +73,13 @@ lib.mkIf config.selfprivacy.sso.enable {
origin = "https://" + auth-fqdn; origin = "https://" + auth-fqdn;
# TODO revise this: maybe kanidm must not have access to a public TLS # TODO revise this: maybe kanidm must not have access to a public TLS
tls_chain = tls_chain = "${config.security.acme.certs.${domain}.directory}/fullchain.pem";
"${config.security.acme.certs.${domain}.directory}/fullchain.pem"; tls_key = "${config.security.acme.certs.${domain}.directory}/key.pem";
tls_key =
"${config.security.acme.certs.${domain}.directory}/key.pem";
# nginx should proxy requests to it # nginx should proxy requests to it
bindaddress = kanidm-bind-address; bindaddress = kanidm-bind-address;
ldapbindaddress = ldapbindaddress = "${ldap-host}:${toString ldap-port}";
"${ldap-host}:${toString ldap-port}";
# kanidm is behind a proxy # kanidm is behind a proxy
trust_x_forward_for = true; trust_x_forward_for = true;
@@ -101,8 +102,7 @@ lib.mkIf config.selfprivacy.sso.enable {
services.nginx = { services.nginx = {
enable = true; enable = true;
additionalModules = additionalModules = lib.mkIf config.selfprivacy.sso.debug [ pkgs.nginxModules.lua ];
lib.mkIf config.selfprivacy.sso.debug [ pkgs.nginxModules.lua ];
commonHttpConfig = lib.mkIf config.selfprivacy.sso.debug '' commonHttpConfig = lib.mkIf config.selfprivacy.sso.debug ''
log_format kanidm escape=none '$request $status\n' log_format kanidm escape=none '$request $status\n'
'[Request body]: $request_body\n' '[Request body]: $request_body\n'
@@ -158,8 +158,7 @@ lib.mkIf config.selfprivacy.sso.enable {
systemd.services.kanidm.serviceConfig.ExecStartPre = systemd.services.kanidm.serviceConfig.ExecStartPre =
# idempotent script to run on each startup only for kanidm v1.5.0 # idempotent script to run on each startup only for kanidm v1.5.0
lib.mkIf (pkgs.kanidm.version == "1.5.0") lib.mkIf (pkgs.kanidm.version == "1.5.0") (lib.mkBefore [ kanidmMigrateDbScript ]);
(lib.mkBefore [ kanidmMigrateDbScript ]);
selfprivacy.passthru.auth = { selfprivacy.passthru.auth = {
inherit inherit
@@ -171,25 +170,20 @@ lib.mkIf config.selfprivacy.sso.enable {
keys-path keys-path
; ;
oauth2-introspection-url-prefix = client_id: "https://${client_id}:"; oauth2-introspection-url-prefix = client_id: "https://${client_id}:";
oauth2-introspection-url-postfix = oauth2-introspection-url-postfix = "@${auth-fqdn}/oauth2/token/introspect";
"@${auth-fqdn}/oauth2/token/introspect"; oauth2-discovery-url =
oauth2-discovery-url = client_id: client_id: "https://${auth-fqdn}/oauth2/openid/${client_id}/.well-known/openid-configuration";
"https://${auth-fqdn}/oauth2/openid/${client_id}/.well-known/openid-configuration";
oauth2-provider-name = "Kanidm"; oauth2-provider-name = "Kanidm";
oauth2-systemd-service = "kanidm.service"; oauth2-systemd-service = "kanidm.service";
# e.g. "dc=mydomain,dc=com" # e.g. "dc=mydomain,dc=com"
ldap-base-dn = ldap-base-dn = lib.strings.concatMapStringsSep "," (x: "dc=" + x) (
lib.strings.concatMapStringsSep lib.strings.splitString "." domain
"," );
(x: "dc=" + x)
(lib.strings.splitString "." domain);
# TODO consider to pass a value or throw exception if token is not generated # TODO consider to pass a value or throw exception if token is not generated
mkServiceAccountTokenFP = linuxGroup: mkServiceAccountTokenFP = linuxGroup: "${keys-path}/${linuxGroup}/kanidm-service-account-token";
"${keys-path}/${linuxGroup}/kanidm-service-account-token";
mkOAuth2ClientSecretFP = linuxGroup: mkOAuth2ClientSecretFP = linuxGroup: "${keys-path}/${linuxGroup}/kanidm-oauth-client-secret";
"${keys-path}/${linuxGroup}/kanidm-oauth-client-secret";
}; };
} }

View File

@@ -1,8 +1,9 @@
{ config {
, lib config,
, options lib,
, pkgs options,
, ... pkgs,
...
}: }:
let let
inherit (lib) inherit (lib)
@@ -40,7 +41,9 @@ let
cfg = config.services.kanidm; cfg = config.services.kanidm;
settingsFormat = pkgs.formats.toml { }; settingsFormat = pkgs.formats.toml { };
# Remove null values, so we can document optional values that don't end up in the generated TOML file. # Remove null values, so we can document optional values that don't end up in the generated TOML file.
filterConfig = converge (a: filterAttrsRecursive (_: v: v != null) (builtins.removeAttrs a [ "provision" ])); filterConfig = converge (
a: filterAttrsRecursive (_: v: v != null) (builtins.removeAttrs a [ "provision" ])
);
serverConfigFile = settingsFormat.generate "server.toml" (filterConfig cfg.serverSettings); serverConfigFile = settingsFormat.generate "server.toml" (filterConfig cfg.serverSettings);
clientConfigFile = settingsFormat.generate "kanidm-config.toml" (filterConfig cfg.clientSettings); clientConfigFile = settingsFormat.generate "kanidm-config.toml" (filterConfig cfg.clientSettings);
unixConfigFile = settingsFormat.generate "kanidm-unixd.toml" (filterConfig cfg.unixSettings); unixConfigFile = settingsFormat.generate "kanidm-unixd.toml" (filterConfig cfg.unixSettings);
@@ -54,8 +57,7 @@ let
# paths, no new bind mount is added. Adding subpaths caused problems on ofborg. # paths, no new bind mount is added. Adding subpaths caused problems on ofborg.
hasPrefixInList = hasPrefixInList =
list: newPath: any (path: hasPrefix (builtins.toString path) (builtins.toString newPath)) list; list: newPath: any (path: hasPrefix (builtins.toString path) (builtins.toString newPath)) list;
mergePaths = foldl' mergePaths = foldl' (
(
merged: newPath: merged: newPath:
let let
# If the new path is a prefix to some existing path, we need to filter it out # If the new path is a prefix to some existing path, we need to filter it out
@@ -127,10 +129,12 @@ let
filterPresent = filterAttrs (_: v: v.present); filterPresent = filterAttrs (_: v: v.present);
selfprivacy-admin-groups-regex = "^sp\.([[:alnum:]]+\.|)admins$"; selfprivacy-admin-groups-regex = "^sp\.([[:alnum:]]+\.|)admins$";
is-selfprivacy-admin-group = name: is-selfprivacy-admin-group =
! builtins.isNull (builtins.match selfprivacy-admin-groups-regex name); name: !builtins.isNull (builtins.match selfprivacy-admin-groups-regex name);
isGroupNonOverwritable = g: false isGroupNonOverwritable =
g:
false
|| !g ? members || !g ? members
|| g ? members && g.members == [ ] || g ? members && g.members == [ ]
|| g ? members && builtins.any is-selfprivacy-admin-group g.members; || g ? members && builtins.any is-selfprivacy-admin-group g.members;
@@ -138,8 +142,7 @@ let
provisionStateJson = pkgs.writeText "provision-state.json" ( provisionStateJson = pkgs.writeText "provision-state.json" (
builtins.toJSON { builtins.toJSON {
inherit (cfg.provision) persons systems; inherit (cfg.provision) persons systems;
groups = groups = lib.attrsets.filterAttrs (_n: v: !isGroupNonOverwritable v) cfg.provision.groups;
lib.attrsets.filterAttrs (_n: v: ! isGroupNonOverwritable v) cfg.provision.groups;
} }
); );
@@ -182,8 +185,9 @@ let
fi fi
''; '';
groupsToCreateAndPopulate = groupsToCreateAndPopulate = lib.attrsets.filterAttrs (
lib.attrsets.filterAttrs (_n: isGroupNonOverwritable) cfg.provision.groups; _n: isGroupNonOverwritable
) cfg.provision.groups;
createGroups = '' createGroups = ''
for group_name in ${lib.strings.concatStringsSep " " (builtins.attrNames groupsToCreateAndPopulate)} for group_name in ${lib.strings.concatStringsSep " " (builtins.attrNames groupsToCreateAndPopulate)}
@@ -199,9 +203,9 @@ let
done done
''; '';
createAndPopulateGroups = createAndPopulateGroups = lib.concatLines (
lib.concatLines ([ createGroups ] [ createGroups ] ++ (lib.mapAttrsToList populateGroup groupsToCreateAndPopulate)
++ (lib.mapAttrsToList populateGroup groupsToCreateAndPopulate)); );
postStartScript = pkgs.writeShellScript "post-start" '' postStartScript = pkgs.writeShellScript "post-start" ''
set -euo pipefail set -euo pipefail
@@ -476,11 +480,9 @@ in
config.members = concatLists ( config.members = concatLists (
flip mapAttrsToList cfg.provision.persons ( flip mapAttrsToList cfg.provision.persons (
person: personCfg: person: personCfg:
optional optional (
(
personCfg.present && builtins.elem groupSubmod.config._module.args.name personCfg.groups personCfg.present && builtins.elem groupSubmod.config._module.args.name personCfg.groups
) ) person
person
) )
); );
}) })
@@ -683,12 +685,9 @@ in
++ entityList "oauth2" cfg.provision.systems.oauth2; ++ entityList "oauth2" cfg.provision.systems.oauth2;
# Accumulate entities by name. Track corresponding entity types for later duplicate check. # Accumulate entities by name. Track corresponding entity types for later duplicate check.
entitiesByName = foldl' entitiesByName = foldl' (
(
acc: { type, name }: acc // { ${name} = (acc.${name} or [ ]) ++ [ type ]; } acc: { type, name }: acc // { ${name} = (acc.${name} or [ ]) ++ [ type ]; }
) ) { } entities;
{ }
entities;
assertGroupsKnown = assertGroupsKnown =
opt: groups: opt: groups:

View File

@@ -1,4 +1,9 @@
{ config, pkgs, lib, ... }: {
config,
pkgs,
lib,
...
}:
let let
redis-sp-api-srv-name = "sp-api"; redis-sp-api-srv-name = "sp-api";
sp-print-api-token = pkgs.writeShellApplication { sp-print-api-token = pkgs.writeShellApplication {
@@ -76,7 +81,8 @@ in
}; };
}; };
services.do-agent.enable = if config.selfprivacy.server.provider == "DIGITALOCEAN" then true else false; services.do-agent.enable =
if config.selfprivacy.server.provider == "DIGITALOCEAN" then true else false;
boot.tmp.cleanOnBoot = true; boot.tmp.cleanOnBoot = true;
networking = { networking = {
@@ -84,14 +90,31 @@ in
domain = config.selfprivacy.domain; domain = config.selfprivacy.domain;
usePredictableInterfaceNames = false; usePredictableInterfaceNames = false;
firewall = { firewall = {
allowedTCPPorts = [ 22 25 80 143 443 465 587 993 4443 8443 ]; allowedTCPPorts = [
allowedUDPPorts = [ 8443 10000 ]; 22
25
80
143
443
465
587
993
4443
8443
];
allowedUDPPorts = [
8443
10000
];
extraCommands = '' extraCommands = ''
iptables --table nat --append POSTROUTING --out-interface eth0 -j MASQUERADE iptables --table nat --append POSTROUTING --out-interface eth0 -j MASQUERADE
iptables --append FORWARD --in-interface vpn00 -j ACCEPT iptables --append FORWARD --in-interface vpn00 -j ACCEPT
''; '';
}; };
nameservers = [ "1.1.1.1" "1.0.0.1" ]; nameservers = [
"1.1.1.1"
"1.0.0.1"
];
}; };
time.timeZone = config.selfprivacy.timezone; time.timeZone = config.selfprivacy.timezone;
i18n.defaultLocale = "en_GB.UTF-8"; i18n.defaultLocale = "en_GB.UTF-8";
@@ -107,8 +130,15 @@ in
}; };
services.fail2ban.enable = true; services.fail2ban.enable = true;
programs.ssh = { programs.ssh = {
pubkeyAcceptedKeyTypes = [ "ssh-ed25519" "ssh-rsa" "ecdsa-sha2-nistp256" ]; pubkeyAcceptedKeyTypes = [
hostKeyAlgorithms = [ "ssh-ed25519" "ssh-rsa" ]; "ssh-ed25519"
"ssh-rsa"
"ecdsa-sha2-nistp256"
];
hostKeyAlgorithms = [
"ssh-ed25519"
"ssh-rsa"
];
}; };
environment.systemPackages = with pkgs; [ environment.systemPackages = with pkgs; [
git git
@@ -124,9 +154,9 @@ in
"R! /old-root" "R! /old-root"
"d /etc/selfprivacy/dump 0700 0700 selfprivacy-api selfprivacy-api" "d /etc/selfprivacy/dump 0700 0700 selfprivacy-api selfprivacy-api"
]; ];
system.stateVersion = system.stateVersion = lib.mkIf (
lib.mkIf (config.selfprivacy.stateVersion != null) config.selfprivacy.stateVersion != null
config.selfprivacy.stateVersion; ) config.selfprivacy.stateVersion;
system.autoUpgrade = { system.autoUpgrade = {
enable = config.selfprivacy.autoUpgrade.enable; enable = config.selfprivacy.autoUpgrade.enable;
allowReboot = config.selfprivacy.autoUpgrade.allowReboot; allowReboot = config.selfprivacy.autoUpgrade.allowReboot;
@@ -168,7 +198,11 @@ in
}; };
nix.settings = { nix.settings = {
sandbox = true; sandbox = true;
experimental-features = [ "nix-command" "flakes" "repl-flake" ]; experimental-features = [
"nix-command"
"flakes"
"repl-flake"
];
# auto-optimise-store = true; # auto-optimise-store = true;
# evaluation restrictions: # evaluation restrictions:

138
flake.nix
View File

@@ -2,93 +2,97 @@
description = "SelfPrivacy NixOS configuration flake"; description = "SelfPrivacy NixOS configuration flake";
inputs = { inputs = {
nixpkgs.url = github:nixos/nixpkgs; nixpkgs.url = "github:nixos/nixpkgs";
nixos-unstable.url = github:nixos/nixpkgs/nixos-unstable; nixos-unstable.url = "github:nixos/nixpkgs/nixos-unstable";
selfprivacy-api.url = selfprivacy-api.url = "git+https://git.selfprivacy.org/SelfPrivacy/selfprivacy-rest-api.git";
git+https://git.selfprivacy.org/SelfPrivacy/selfprivacy-rest-api.git;
# make selfprivacy-api use the same shared nixpkgs # make selfprivacy-api use the same shared nixpkgs
selfprivacy-api.inputs.nixpkgs.follows = "nixpkgs"; selfprivacy-api.inputs.nixpkgs.follows = "nixpkgs";
}; };
outputs = { self, nixpkgs, nixos-unstable, selfprivacy-api }: { outputs =
{
self,
nixpkgs,
nixos-unstable,
selfprivacy-api,
}:
{
nixosConfigurations-fun = nixosConfigurations-fun =
{ hardware-configuration {
, deployment hardware-configuration,
, userdata deployment,
, top-level-flake userdata,
, sp-modules top-level-flake,
sp-modules,
}: }:
{ {
default = nixpkgs.lib.nixosSystem { default = nixpkgs.lib.nixosSystem {
modules = [ modules =
[
hardware-configuration hardware-configuration
deployment deployment
./configuration.nix ./configuration.nix
./auth/auth.nix ./auth/auth.nix
{ {
nixpkgs.overlays = [ nixpkgs.overlays = [
( (_final: prev: {
_final: prev:
{
inherit (nixos-unstable.legacyPackages.${prev.system}) inherit (nixos-unstable.legacyPackages.${prev.system})
kanidm kanidm
kanidm-provision kanidm-provision
; ;
} })
)
]; ];
disabledModules = [ "services/security/kanidm.nix" ]; disabledModules = [ "services/security/kanidm.nix" ];
imports = [ ./auth/kanidm.nix ]; imports = [ ./auth/kanidm.nix ];
} }
selfprivacy-api.nixosModules.default selfprivacy-api.nixosModules.default
({ pkgs, lib, ... }: { (
environment.etc = (lib.attrsets.mapAttrs' { pkgs, lib, ... }:
(name: sp-module: { {
environment.etc =
(lib.attrsets.mapAttrs' (name: sp-module: {
name = "sp-modules/${name}"; name = "sp-modules/${name}";
value.text = import ./lib/meta.nix { inherit pkgs sp-module; }; value.text = import ./lib/meta.nix { inherit pkgs sp-module; };
}) }) sp-modules)
sp-modules) // { // {
suggested-sp-modules.text = builtins.toJSON (builtins.attrNames (builtins.readDir ./sp-modules)); suggested-sp-modules.text = builtins.toJSON (builtins.attrNames (builtins.readDir ./sp-modules));
}; };
}) }
)
( (
let let
deepFilter = ref: attrset: deepFilter =
builtins.foldl' ref: attrset:
(acc: key: builtins.foldl' (
acc: key:
if builtins.hasAttr key ref then if builtins.hasAttr key ref then
let let
value = attrset.${key}; value = attrset.${key};
refValue = ref.${key}; refValue = ref.${key};
in in
acc // { acc
// {
${key} = ${key} =
if builtins.isAttrs value && builtins.isAttrs refValue then if builtins.isAttrs value && builtins.isAttrs refValue then deepFilter refValue value else value;
deepFilter refValue value
else
value;
} }
else else
acc acc
) ) { } (builtins.attrNames attrset);
{ }
(builtins.attrNames attrset);
in in
{ options, ... }: { { options, ... }:
{
# pass userdata (parsed from JSON) options to selfprivacy module # pass userdata (parsed from JSON) options to selfprivacy module
selfprivacy = deepFilter options.selfprivacy userdata; selfprivacy = deepFilter options.selfprivacy userdata;
# embed top-level flake source folder into the build # embed top-level flake source folder into the build
environment.etc."selfprivacy/nixos-config-source".source = environment.etc."selfprivacy/nixos-config-source".source = top-level-flake;
top-level-flake;
# for running "nix search nixpkgs", "nix shell nixpkgs#PKG... etc # for running "nix search nixpkgs", "nix shell nixpkgs#PKG... etc
nix.registry.nixpkgs.flake = nixpkgs; nix.registry.nixpkgs.flake = nixpkgs;
# embed commit sha1 for `nixos-version --configuration-revision` # embed commit sha1 for `nixos-version --configuration-revision`
system.configurationRevision = self.rev system.configurationRevision = self.rev or "@${self.lastModifiedDate}"; # for development
or "@${self.lastModifiedDate}"; # for development
# TODO assertion to forbid dirty builds caused by top-level-flake # TODO assertion to forbid dirty builds caused by top-level-flake
# reset contents of /etc/nixos to match running NixOS generation # reset contents of /etc/nixos to match running NixOS generation
@@ -102,46 +106,50 @@
++ ++
# add SP modules, but constrain available config attributes for each # add SP modules, but constrain available config attributes for each
# (TODO revise evaluation performance of the code below) # (TODO revise evaluation performance of the code below)
nixpkgs.lib.attrsets.mapAttrsToList nixpkgs.lib.attrsets.mapAttrsToList (
(name: sp-module: args@{ config, pkgs, ... }: name: sp-module:
args@{ config, pkgs, ... }:
let let
lib = nixpkgs.lib; lib = nixpkgs.lib;
configPathsNeeded = sp-module.configPathsNeeded or configPathsNeeded =
(abort "allowed config paths not set for module \"${name}\""); sp-module.configPathsNeeded or (abort "allowed config paths not set for module \"${name}\"");
constrainConfigArgs = args'@{ pkgs, ... }: args' // { constrainConfigArgs =
args'@{ pkgs, ... }:
args'
// {
config = config =
# TODO use lib.attrsets.mergeAttrsList from nixpkgs 23.05 # TODO use lib.attrsets.mergeAttrsList from nixpkgs 23.05
(builtins.foldl' lib.attrsets.recursiveUpdate { } (
(map builtins.foldl' lib.attrsets.recursiveUpdate { } (
(p: lib.attrsets.setAttrByPath p map (p: lib.attrsets.setAttrByPath p (lib.attrsets.getAttrFromPath p config)) configPathsNeeded
(lib.attrsets.getAttrFromPath p config))
configPathsNeeded
) )
); );
}; };
constrainImportsArgsRecursive = lib.attrsets.mapAttrsRecursive constrainImportsArgsRecursive = lib.attrsets.mapAttrsRecursive (
(p: v: p: v:
# TODO traverse only imports and imports of imports, etc # TODO traverse only imports and imports of imports, etc
# without traversing all attributes # without traversing all attributes
if lib.lists.last p == "imports" if lib.lists.last p == "imports" then
then map (
map m:
(m: (
(args'@{ pkgs, ... }: constrainImportsArgsRecursive args'@{ pkgs, ... }:
(if builtins.isPath m constrainImportsArgsRecursive (
then import m (constrainConfigArgs args') if builtins.isPath m then
import m (constrainConfigArgs args')
else if builtins.isFunction m then
m (constrainConfigArgs args')
else else
if builtins.isFunction m m
then m (constrainConfigArgs args')
else m))
) )
)
) v
else
v v
else v); );
in in
constrainImportsArgsRecursive constrainImportsArgsRecursive (sp-module.nixosModules.default (constrainConfigArgs args))
(sp-module.nixosModules.default (constrainConfigArgs args)) ) sp-modules;
)
sp-modules;
}; };
}; };
formatter.x86_64-linux = nixpkgs.legacyPackages.x86_64-linux.nixpkgs-fmt; formatter.x86_64-linux = nixpkgs.legacyPackages.x86_64-linux.nixpkgs-fmt;

View File

@@ -1,4 +1,9 @@
{ config, lib, pkgs, ... }: {
config,
lib,
pkgs,
...
}:
let let
cfg = config.selfprivacy; cfg = config.selfprivacy;
dnsCredentialsTemplates = { dnsCredentialsTemplates = {
@@ -27,7 +32,11 @@ in
acceptTerms = true; acceptTerms = true;
defaults = { defaults = {
email = "${cfg.username}@${cfg.domain}"; email = "${cfg.username}@${cfg.domain}";
server = if cfg.dns.useStagingACME then "https://acme-staging-v02.api.letsencrypt.org/directory" else "https://acme-v02.api.letsencrypt.org/directory"; server =
if cfg.dns.useStagingACME then
"https://acme-staging-v02.api.letsencrypt.org/directory"
else
"https://acme-v02.api.letsencrypt.org/directory";
reloadServices = [ "nginx" ]; reloadServices = [ "nginx" ];
dnsResolver = "8.8.8.8:53"; dnsResolver = "8.8.8.8:53";
}; };
@@ -38,7 +47,9 @@ in
dnsProvider = lib.strings.toLower cfg.dns.provider; dnsProvider = lib.strings.toLower cfg.dns.provider;
credentialsFile = acme-env-filepath; credentialsFile = acme-env-filepath;
dnsPropagationCheck = dnsPropagationCheck =
! ((lib.elem cfg.dns.provider dnsPropagationCheckExceptions) || cfg.dns.forceDisableDnsPropagationCheck); !(
(lib.elem cfg.dns.provider dnsPropagationCheckExceptions) || cfg.dns.forceDisableDnsPropagationCheck
);
}; };
"root-${cfg.domain}" = { "root-${cfg.domain}" = {
domain = cfg.domain; domain = cfg.domain;
@@ -51,7 +62,10 @@ in
before = [ "acme-${cfg.domain}.service" ]; before = [ "acme-${cfg.domain}.service" ];
requiredBy = [ "acme-${cfg.domain}.service" ]; requiredBy = [ "acme-${cfg.domain}.service" ];
serviceConfig.Type = "oneshot"; serviceConfig.Type = "oneshot";
path = with pkgs; [ coreutils jq ]; path = with pkgs; [
coreutils
jq
];
script = '' script = ''
set -o nounset set -o nounset

View File

@@ -1,18 +1,28 @@
{ sp-module, pkgs }: { sp-module, pkgs }:
let let
lib = pkgs.lib; lib = pkgs.lib;
options = (pkgs.lib.evalModules { modules = [{ _module.check = false; } sp-module.nixosModules.default]; }).options; options =
(pkgs.lib.evalModules {
modules = [
{ _module.check = false; }
sp-module.nixosModules.default
];
}).options;
# Transform a Nix option to a JSON structure with metadata # Transform a Nix option to a JSON structure with metadata
optionToMeta = (name: option: { optionToMeta = (
name: option: {
name = name; name = name;
description = if builtins.hasAttr "description" option then option.description else null; description = if builtins.hasAttr "description" option then option.description else null;
loc = option.loc; loc = option.loc;
meta = if builtins.hasAttr "meta" option then option.meta else null; meta = if builtins.hasAttr "meta" option then option.meta else null;
default = if builtins.hasAttr "default" option then option.default else null; default = if builtins.hasAttr "default" option then option.default else null;
}); }
);
in in
builtins.toJSON ({ builtins.toJSON ({
meta = if builtins.hasAttr "meta" sp-module then sp-module.meta { inherit lib; } else null; meta = if builtins.hasAttr "meta" sp-module then sp-module.meta { inherit lib; } else null;
configPathsNeeded = sp-module.configPathsNeeded; configPathsNeeded = sp-module.configPathsNeeded;
options = pkgs.lib.mapAttrs optionToMeta (builtins.head (lib.mapAttrsToList (name: value: value) options.selfprivacy.modules)); options = pkgs.lib.mapAttrs optionToMeta (
builtins.head (lib.mapAttrsToList (name: value: value) options.selfprivacy.modules)
);
}) })

View File

@@ -1,6 +1,4 @@
system: system: _final: _prev: {
_final: _prev:
{
# Here is a template to bring a specific package from a given nixpkgs commit: # Here is a template to bring a specific package from a given nixpkgs commit:
# PACKAGE_NAME = (builtins.getFlake "github:nixos/nixpkgs/NIXPKGS_COMMIT_SHA1").legacyPackages.${system}.PACKAGE_NAME; # PACKAGE_NAME = (builtins.getFlake "github:nixos/nixpkgs/NIXPKGS_COMMIT_SHA1").legacyPackages.${system}.PACKAGE_NAME;
# Substitute `PACKAGE_NAME` and `NIXPKGS_COMMIT_SHA1` accordingly. # Substitute `PACKAGE_NAME` and `NIXPKGS_COMMIT_SHA1` accordingly.

View File

@@ -1,22 +1,34 @@
{ config, lib, pkgs, ... }: {
config,
lib,
pkgs,
...
}:
let let
sp = config.selfprivacy; sp = config.selfprivacy;
pleroma_location = pleroma_location =
if lib.attrsets.hasAttr "pleroma" sp.modules && lib.attrsets.hasAttr "location" sp.modules.pleroma if
then sp.modules.pleroma.location lib.attrsets.hasAttr "pleroma" sp.modules && lib.attrsets.hasAttr "location" sp.modules.pleroma
else null; then
sp.modules.pleroma.location
else
null;
postgres_location = postgres_location =
if lib.attrsets.hasAttr "postgresql" sp && lib.attrsets.hasAttr "location" sp.postgresql if lib.attrsets.hasAttr "postgresql" sp && lib.attrsets.hasAttr "location" sp.postgresql then
then sp.postgresql.location sp.postgresql.location
else null; else
null;
# Priority: postgresql > pleroma # Priority: postgresql > pleroma
location = if postgres_location != null then postgres_location else pleroma_location; location = if postgres_location != null then postgres_location else pleroma_location;
# Active if there is a location # Active if there is a location
enable = location != null; enable = location != null;
pleroma_enabled = pleroma_enabled =
if lib.attrsets.hasAttr "pleroma" sp.modules && lib.attrsets.hasAttr "enable" sp.modules.pleroma if
then sp.modules.pleroma.enable lib.attrsets.hasAttr "pleroma" sp.modules && lib.attrsets.hasAttr "enable" sp.modules.pleroma
else false; then
sp.modules.pleroma.enable
else
false;
in in
{ {
imports = [ imports = [

View File

@@ -1,4 +1,9 @@
{ config, lib, pkgs, ... }: {
config,
lib,
pkgs,
...
}:
let let
cfg = config.services.postgresqlUpgrade12to16; cfg = config.services.postgresqlUpgrade12to16;
@@ -62,12 +67,12 @@ in
ExecStartPre = ExecStartPre =
# Stop Pleroma only if pleromaEnabled is true # Stop Pleroma only if pleromaEnabled is true
optional cfg.pleromaEnabled "${pkgs.writeShellScript "postgresql-upgrade12to16-pre.sh" '' optional cfg.pleromaEnabled
"${pkgs.writeShellScript "postgresql-upgrade12to16-pre.sh" ''
if [ -d "${cfg.dataDir12}" ] && [ ! -d "${cfg.dataDir16}" ]; then if [ -d "${cfg.dataDir12}" ] && [ ! -d "${cfg.dataDir16}" ]; then
${pkgs.systemd}/bin/systemctl stop pleroma.service ${pkgs.systemd}/bin/systemctl stop pleroma.service
fi fi
'' ''}";
}";
ExecStart = "${pkgs.writeShellScript "postgresql-upgrade12to16.sh" '' ExecStart = "${pkgs.writeShellScript "postgresql-upgrade12to16.sh" ''
set -e set -e
@@ -119,15 +124,13 @@ in
''}"; ''}";
# Start Pleroma only if pleromaEnabled is true # Start Pleroma only if pleromaEnabled is true
ExecStartPost = ExecStartPost = optional cfg.pleromaEnabled "${pkgs.writeShellScript "postgresql-upgrade12to16-post.sh" ''
optional cfg.pleromaEnabled "${pkgs.writeShellScript "postgresql-upgrade12to16-post.sh" ''
if test -e "${cfg.dataDir16}/.sp_migrated"; then if test -e "${cfg.dataDir16}/.sp_migrated"; then
${pkgs.systemd}/bin/systemctl start --no-block pleroma.service ${pkgs.systemd}/bin/systemctl start --no-block pleroma.service
rm -f "${cfg.dataDir16}/.sp_migrated" rm -f "${cfg.dataDir16}/.sp_migrated"
fi fi
'' ''}";
}";
}; };
}; };
}; };

View File

@@ -5,12 +5,7 @@ in
# FIXME do we really want to delete passwords on module deactivation!? # FIXME do we really want to delete passwords on module deactivation!?
{ {
config = lib.mkIf (!sp.modules.bitwarden.enable) { config = lib.mkIf (!sp.modules.bitwarden.enable) {
system.activationScripts.bitwarden = system.activationScripts.bitwarden = lib.trivial.warn ("bitwarden service is disabled, ${bitwarden-env} will be removed!") ''
lib.trivial.warn
(
"bitwarden service is disabled, ${bitwarden-env} will be removed!"
)
''
rm -f -v ${bitwarden-env} rm -f -v ${bitwarden-env}
''; '';
}; };

View File

@@ -1,5 +1,4 @@
config: config: {
{
sp = config.selfprivacy; sp = config.selfprivacy;
bitwarden-env = "/var/lib/bitwarden/.env"; bitwarden-env = "/var/lib/bitwarden/.env";
} }

View File

@@ -1,12 +1,19 @@
{ {
description = "PoC SP module for Bitwarden password management solution"; description = "PoC SP module for Bitwarden password management solution";
outputs = { self }: { outputs =
nixosModules.default = _: { self }:
{ imports = [ ./module.nix ./cleanup-module.nix ]; }; {
configPathsNeeded = nixosModules.default = _: {
builtins.fromJSON (builtins.readFile ./config-paths-needed.json); imports = [
meta = { lib, ... }: { ./module.nix
./cleanup-module.nix
];
};
configPathsNeeded = builtins.fromJSON (builtins.readFile ./config-paths-needed.json);
meta =
{ lib, ... }:
{
spModuleSchemaVersion = 1; spModuleSchemaVersion = 1;
id = "bitwarden"; id = "bitwarden";
name = "Bitwarden"; name = "Bitwarden";

View File

@@ -1,4 +1,9 @@
{ config, lib, pkgs, ... }: {
config,
lib,
pkgs,
...
}:
let let
secrets-filepath = "/etc/selfprivacy/secrets.json"; secrets-filepath = "/etc/selfprivacy/secrets.json";
backup-dir = "/var/lib/bitwarden/backup"; backup-dir = "/var/lib/bitwarden/backup";
@@ -7,28 +12,34 @@ let
in in
{ {
options.selfprivacy.modules.bitwarden = { options.selfprivacy.modules.bitwarden = {
enable = (lib.mkOption { enable =
(lib.mkOption {
default = false; default = false;
type = lib.types.bool; type = lib.types.bool;
description = "Enable Vaultwarden"; description = "Enable Vaultwarden";
}) // { })
// {
meta = { meta = {
type = "enable"; type = "enable";
}; };
}; };
location = (lib.mkOption { location =
(lib.mkOption {
type = lib.types.str; type = lib.types.str;
description = "Vaultwarden location"; description = "Vaultwarden location";
}) // { })
// {
meta = { meta = {
type = "location"; type = "location";
}; };
}; };
subdomain = (lib.mkOption { subdomain =
(lib.mkOption {
default = "password"; default = "password";
type = lib.types.strMatching "[A-Za-z0-9][A-Za-z0-9\-]{0,61}[A-Za-z0-9]"; type = lib.types.strMatching "[A-Za-z0-9][A-Za-z0-9\-]{0,61}[A-Za-z0-9]";
description = "Subdomain"; description = "Subdomain";
}) // { })
// {
meta = { meta = {
widget = "subdomain"; widget = "subdomain";
type = "string"; type = "string";
@@ -36,31 +47,37 @@ in
weight = 0; weight = 0;
}; };
}; };
signupsAllowed = (lib.mkOption { signupsAllowed =
(lib.mkOption {
default = true; default = true;
type = lib.types.bool; type = lib.types.bool;
description = "Allow new user signups"; description = "Allow new user signups";
}) // { })
// {
meta = { meta = {
type = "bool"; type = "bool";
weight = 1; weight = 1;
}; };
}; };
sendsAllowed = (lib.mkOption { sendsAllowed =
(lib.mkOption {
default = true; default = true;
type = lib.types.bool; type = lib.types.bool;
description = "Allow users to use Bitwarden Send"; description = "Allow users to use Bitwarden Send";
}) // { })
// {
meta = { meta = {
type = "bool"; type = "bool";
weight = 2; weight = 2;
}; };
}; };
emergencyAccessAllowed = (lib.mkOption { emergencyAccessAllowed =
(lib.mkOption {
default = true; default = true;
type = lib.types.bool; type = lib.types.bool;
description = "Allow users to enable Emergency Access"; description = "Allow users to enable Emergency Access";
}) // { })
// {
meta = { meta = {
type = "bool"; type = "bool";
weight = 3; weight = 3;
@@ -118,7 +135,10 @@ in
before = [ "vaultwarden.service" ]; before = [ "vaultwarden.service" ];
requiredBy = [ "vaultwarden.service" ]; requiredBy = [ "vaultwarden.service" ];
serviceConfig.Type = "oneshot"; serviceConfig.Type = "oneshot";
path = with pkgs; [ coreutils jq ]; path = with pkgs; [
coreutils
jq
];
script = '' script = ''
set -o nounset set -o nounset

View File

@@ -1,11 +1,14 @@
{ {
description = "PoC SP module for Gitea forge service"; description = "PoC SP module for Gitea forge service";
outputs = { self }: { outputs =
{ self }:
{
nixosModules.default = import ./module.nix; nixosModules.default = import ./module.nix;
configPathsNeeded = configPathsNeeded = builtins.fromJSON (builtins.readFile ./config-paths-needed.json);
builtins.fromJSON (builtins.readFile ./config-paths-needed.json); meta =
meta = { lib, ... }: { { lib, ... }:
{
spModuleSchemaVersion = 1; spModuleSchemaVersion = 1;
id = "gitea"; id = "gitea";
name = "Forgejo"; name = "Forgejo";

View File

@@ -1,10 +1,12 @@
{ config, lib, pkgs, ... }: {
config,
lib,
pkgs,
...
}:
let let
sp = config.selfprivacy; sp = config.selfprivacy;
stateDir = stateDir = if sp.useBinds then "/volumes/${cfg.location}/gitea" else "/var/lib/gitea";
if sp.useBinds
then "/volumes/${cfg.location}/gitea"
else "/var/lib/gitea";
cfg = sp.modules.gitea; cfg = sp.modules.gitea;
themes = [ themes = [
"forgejo-auto" "forgejo-auto"
@@ -18,8 +20,7 @@ let
oauthClientID = "forgejo"; oauthClientID = "forgejo";
auth-passthru = config.selfprivacy.passthru.auth; auth-passthru = config.selfprivacy.passthru.auth;
oauth2-provider-name = auth-passthru.oauth2-provider-name; oauth2-provider-name = auth-passthru.oauth2-provider-name;
redirect-uri = redirect-uri = "https://${cfg.subdomain}.${sp.domain}/user/oauth2/${oauth2-provider-name}/callback";
"https://${cfg.subdomain}.${sp.domain}/user/oauth2/${oauth2-provider-name}/callback";
oauthDiscoveryURL = auth-passthru.oauth2-discovery-url oauthClientID; oauthDiscoveryURL = auth-passthru.oauth2-discovery-url oauthClientID;
# SelfPrivacy uses SP Module ID to identify the group! # SelfPrivacy uses SP Module ID to identify the group!
@@ -30,35 +31,39 @@ let
linuxGroupOfService = "gitea"; linuxGroupOfService = "gitea";
forgejoPackage = pkgs.forgejo; forgejoPackage = pkgs.forgejo;
serviceAccountTokenFP = serviceAccountTokenFP = auth-passthru.mkServiceAccountTokenFP linuxGroupOfService;
auth-passthru.mkServiceAccountTokenFP linuxGroupOfService; oauthClientSecretFP = auth-passthru.mkOAuth2ClientSecretFP linuxGroupOfService;
oauthClientSecretFP =
auth-passthru.mkOAuth2ClientSecretFP linuxGroupOfService;
in in
{ {
options.selfprivacy.modules.gitea = { options.selfprivacy.modules.gitea = {
enable = (lib.mkOption { enable =
(lib.mkOption {
default = false; default = false;
type = lib.types.bool; type = lib.types.bool;
description = "Enable Forgejo"; description = "Enable Forgejo";
}) // { })
// {
meta = { meta = {
type = "enable"; type = "enable";
}; };
}; };
location = (lib.mkOption { location =
(lib.mkOption {
type = lib.types.str; type = lib.types.str;
description = "Forgejo location"; description = "Forgejo location";
}) // { })
// {
meta = { meta = {
type = "location"; type = "location";
}; };
}; };
subdomain = (lib.mkOption { subdomain =
(lib.mkOption {
default = "git"; default = "git";
type = lib.types.strMatching "[A-Za-z0-9][A-Za-z0-9\-]{0,61}[A-Za-z0-9]"; type = lib.types.strMatching "[A-Za-z0-9][A-Za-z0-9\-]{0,61}[A-Za-z0-9]";
description = "Subdomain"; description = "Subdomain";
}) // { })
// {
meta = { meta = {
widget = "subdomain"; widget = "subdomain";
type = "string"; type = "string";
@@ -66,82 +71,98 @@ in
weight = 0; weight = 0;
}; };
}; };
appName = (lib.mkOption { appName =
(lib.mkOption {
default = "SelfPrivacy git Service"; default = "SelfPrivacy git Service";
type = lib.types.str; type = lib.types.str;
description = "The name displayed in the web interface"; description = "The name displayed in the web interface";
}) // { })
// {
meta = { meta = {
type = "string"; type = "string";
weight = 1; weight = 1;
}; };
}; };
enableLfs = (lib.mkOption { enableLfs =
(lib.mkOption {
default = true; default = true;
type = lib.types.bool; type = lib.types.bool;
description = "Enable Git LFS"; description = "Enable Git LFS";
}) // { })
// {
meta = { meta = {
type = "bool"; type = "bool";
weight = 2; weight = 2;
}; };
}; };
forcePrivate = (lib.mkOption { forcePrivate =
(lib.mkOption {
default = false; default = false;
type = lib.types.bool; type = lib.types.bool;
description = "Force all new repositories to be private"; description = "Force all new repositories to be private";
}) // { })
// {
meta = { meta = {
type = "bool"; type = "bool";
weight = 3; weight = 3;
}; };
}; };
disableRegistration = (lib.mkOption { disableRegistration =
(lib.mkOption {
default = false; default = false;
type = lib.types.bool; type = lib.types.bool;
description = "Disable registration of new users"; description = "Disable registration of new users";
}) // { })
// {
meta = { meta = {
type = "bool"; type = "bool";
weight = 4; weight = 4;
}; };
}; };
requireSigninView = (lib.mkOption { requireSigninView =
(lib.mkOption {
default = false; default = false;
type = lib.types.bool; type = lib.types.bool;
description = "Force users to log in to view any page"; description = "Force users to log in to view any page";
}) // { })
// {
meta = { meta = {
type = "bool"; type = "bool";
weight = 5; weight = 5;
}; };
}; };
defaultTheme = (lib.mkOption { defaultTheme =
(lib.mkOption {
default = "forgejo-auto"; default = "forgejo-auto";
type = lib.types.enum themes; type = lib.types.enum themes;
description = "Default theme"; description = "Default theme";
}) // { })
// {
meta = { meta = {
type = "enum"; type = "enum";
options = themes; options = themes;
weight = 6; weight = 6;
}; };
}; };
enableSso = (lib.mkOption { enableSso =
(lib.mkOption {
default = false; default = false;
type = lib.types.bool; type = lib.types.bool;
description = "Enable Single Sign-On"; description = "Enable Single Sign-On";
}) // { })
// {
meta = { meta = {
type = "bool"; type = "bool";
weight = 7; weight = 7;
}; };
}; };
debug = (lib.mkOption { debug =
(lib.mkOption {
default = false; default = false;
type = lib.types.bool; type = lib.types.bool;
description = "Enable debug logging"; description = "Enable debug logging";
}) // { })
// {
meta = { meta = {
type = "bool"; type = "bool";
weight = 8; weight = 8;
@@ -149,13 +170,13 @@ in
}; };
}; };
config = lib.mkIf cfg.enable (lib.mkMerge [ config = lib.mkIf cfg.enable (
lib.mkMerge [
{ {
assertions = [ assertions = [
{ {
assertion = cfg.enableSso -> sp.sso.enable; assertion = cfg.enableSso -> sp.sso.enable;
message = message = "SSO cannot be enabled for Forgejo when SSO is disabled globally.";
"SSO cannot be enabled for Forgejo when SSO is disabled globally.";
} }
]; ];
fileSystems = lib.mkIf sp.useBinds { fileSystems = lib.mkIf sp.useBinds {
@@ -393,8 +414,7 @@ in
displayName = "Forgejo"; displayName = "Forgejo";
subdomain = cfg.subdomain; subdomain = cfg.subdomain;
isTokenNeeded = true; isTokenNeeded = true;
originLanding = originLanding = "https://${cfg.subdomain}.${sp.domain}/user/login?redirect_to=%2f";
"https://${cfg.subdomain}.${sp.domain}/user/login?redirect_to=%2f";
originUrl = redirect-uri; originUrl = redirect-uri;
clientSystemdUnits = [ "forgejo.service" ]; clientSystemdUnits = [ "forgejo.service" ];
enablePkce = lib.versionAtLeast forgejoPackage.version "8.0"; enablePkce = lib.versionAtLeast forgejoPackage.version "8.0";
@@ -406,5 +426,6 @@ in
}; };
}; };
}) })
]); ]
);
} }

View File

@@ -1,11 +1,14 @@
{ {
description = "PoC SP module for Jitsi Meet video conferences server"; description = "PoC SP module for Jitsi Meet video conferences server";
outputs = { self }: { outputs =
{ self }:
{
nixosModules.default = import ./module.nix; nixosModules.default = import ./module.nix;
configPathsNeeded = configPathsNeeded = builtins.fromJSON (builtins.readFile ./config-paths-needed.json);
builtins.fromJSON (builtins.readFile ./config-paths-needed.json); meta =
meta = { lib, ... }: { { lib, ... }:
{
spModuleSchemaVersion = 1; spModuleSchemaVersion = 1;
id = "jitsi-meet"; id = "jitsi-meet";
name = "JitsiMeet"; name = "JitsiMeet";

View File

@@ -5,20 +5,24 @@ let
in in
{ {
options.selfprivacy.modules.jitsi-meet = { options.selfprivacy.modules.jitsi-meet = {
enable = (lib.mkOption { enable =
(lib.mkOption {
default = false; default = false;
type = lib.types.bool; type = lib.types.bool;
description = "Enable JitsiMeet"; description = "Enable JitsiMeet";
}) // { })
// {
meta = { meta = {
type = "enable"; type = "enable";
}; };
}; };
subdomain = (lib.mkOption { subdomain =
(lib.mkOption {
default = "meet"; default = "meet";
type = lib.types.strMatching "[A-Za-z0-9][A-Za-z0-9\-]{0,61}[A-Za-z0-9]"; type = lib.types.strMatching "[A-Za-z0-9][A-Za-z0-9\-]{0,61}[A-Za-z0-9]";
description = "Subdomain"; description = "Subdomain";
}) // { })
// {
meta = { meta = {
widget = "subdomain"; widget = "subdomain";
type = "string"; type = "string";
@@ -26,11 +30,13 @@ in
weight = 0; weight = 0;
}; };
}; };
appName = (lib.mkOption { appName =
(lib.mkOption {
default = "Jitsi Meet"; default = "Jitsi Meet";
type = lib.types.str; type = lib.types.str;
description = "The name displayed in the web interface"; description = "The name displayed in the web interface";
}) // { })
// {
meta = { meta = {
type = "string"; type = "string";
weight = 1; weight = 1;
@@ -43,7 +49,9 @@ in
(_: prev: { (_: prev: {
# We disable E2E for clients below # We disable E2E for clients below
jitsi-meet = prev.jitsi-meet.overrideAttrs (old: { jitsi-meet = prev.jitsi-meet.overrideAttrs (old: {
meta = old.meta // { knownVulnerabilities = [ ]; }; meta = old.meta // {
knownVulnerabilities = [ ];
};
}); });
}) })
]; ];

View File

@@ -1,11 +1,14 @@
{ {
description = "PoC SP module for Prometheus-based monitoring"; description = "PoC SP module for Prometheus-based monitoring";
outputs = { self }: { outputs =
{ self }:
{
nixosModules.default = import ./module.nix; nixosModules.default = import ./module.nix;
configPathsNeeded = configPathsNeeded = builtins.fromJSON (builtins.readFile ./config-paths-needed.json);
builtins.fromJSON (builtins.readFile ./config-paths-needed.json); meta =
meta = { lib, ... }: { { lib, ... }:
{
spModuleSchemaVersion = 1; spModuleSchemaVersion = 1;
id = "monitoring"; id = "monitoring";
name = "Prometheus"; name = "Prometheus";

View File

@@ -4,19 +4,23 @@ let
in in
{ {
options.selfprivacy.modules.monitoring = { options.selfprivacy.modules.monitoring = {
enable = (lib.mkOption { enable =
(lib.mkOption {
default = false; default = false;
type = lib.types.bool; type = lib.types.bool;
description = "Enable monitoring service"; description = "Enable monitoring service";
}) // { })
// {
meta = { meta = {
type = "enable"; type = "enable";
}; };
}; };
location = (lib.mkOption { location =
(lib.mkOption {
type = lib.types.str; type = lib.types.str;
description = "Monitoring data location"; description = "Monitoring data location";
}) // { })
// {
meta = { meta = {
type = "location"; type = "location";
}; };
@@ -54,15 +58,19 @@ in
scrapeConfigs = [ scrapeConfigs = [
{ {
job_name = "node-exporter"; job_name = "node-exporter";
static_configs = [{ static_configs = [
{
targets = [ "127.0.0.1:9002" ]; targets = [ "127.0.0.1:9002" ];
}]; }
];
} }
{ {
job_name = "cadvisor"; job_name = "cadvisor";
static_configs = [{ static_configs = [
{
targets = [ "127.0.0.1:9003" ]; targets = [ "127.0.0.1:9003" ];
}]; }
];
} }
]; ];
}; };

View File

@@ -1,11 +1,14 @@
{ {
description = "PoC SP module for Mumble conferences server"; description = "PoC SP module for Mumble conferences server";
outputs = { self }: { outputs =
{ self }:
{
nixosModules.default = import ./module.nix; nixosModules.default = import ./module.nix;
configPathsNeeded = configPathsNeeded = builtins.fromJSON (builtins.readFile ./config-paths-needed.json);
builtins.fromJSON (builtins.readFile ./config-paths-needed.json); meta =
meta = { lib, ... }: { { lib, ... }:
{
spModuleSchemaVersion = 1; spModuleSchemaVersion = 1;
id = "mumble"; id = "mumble";
name = "Mumble"; name = "Mumble";

View File

@@ -1,4 +1,9 @@
{ config, lib, pkgs, ... }: {
config,
lib,
pkgs,
...
}:
let let
domain = config.selfprivacy.domain; domain = config.selfprivacy.domain;
sp = config.selfprivacy; sp = config.selfprivacy;
@@ -6,20 +11,24 @@ let
in in
{ {
options.selfprivacy.modules.mumble = { options.selfprivacy.modules.mumble = {
enable = (lib.mkOption { enable =
(lib.mkOption {
default = false; default = false;
type = lib.types.bool; type = lib.types.bool;
description = "Enable Mumble"; description = "Enable Mumble";
}) // { })
// {
meta = { meta = {
type = "enable"; type = "enable";
}; };
}; };
subdomain = (lib.mkOption { subdomain =
(lib.mkOption {
default = "mumble"; default = "mumble";
type = lib.types.strMatching "[A-Za-z0-9][A-Za-z0-9\-]{0,61}[A-Za-z0-9]"; type = lib.types.strMatching "[A-Za-z0-9][A-Za-z0-9\-]{0,61}[A-Za-z0-9]";
description = "Subdomain"; description = "Subdomain";
}) // { })
// {
meta = { meta = {
widget = "subdomain"; widget = "subdomain";
type = "string"; type = "string";
@@ -27,29 +36,35 @@ in
weight = 0; weight = 0;
}; };
}; };
location = (lib.mkOption { location =
(lib.mkOption {
type = lib.types.str; type = lib.types.str;
description = "Location"; description = "Location";
}) // { })
// {
meta = { meta = {
type = "location"; type = "location";
}; };
}; };
appName = (lib.mkOption { appName =
(lib.mkOption {
default = "SelfPrivacy Mumble Service"; default = "SelfPrivacy Mumble Service";
type = lib.types.str; type = lib.types.str;
description = "The name of your Mumble server"; description = "The name of your Mumble server";
}) // { })
// {
meta = { meta = {
type = "string"; type = "string";
weight = 1; weight = 1;
}; };
}; };
welcomeText = (lib.mkOption { welcomeText =
(lib.mkOption {
default = "Welcome to my Mumble server!"; default = "Welcome to my Mumble server!";
type = lib.types.str; type = lib.types.str;
description = "Welcome message"; description = "Welcome message";
}) // { })
// {
meta = { meta = {
type = "string"; type = "string";
weight = 2; weight = 2;
@@ -79,7 +94,9 @@ in
}; };
systemd = { systemd = {
services = { services = {
murmur = { serviceConfig.Slice = "mumble.slice"; }; murmur = {
serviceConfig.Slice = "mumble.slice";
};
murmur-ensure-folder-ownership = { murmur-ensure-folder-ownership = {
description = "Ensure murmur folder ownership"; description = "Ensure murmur folder ownership";
before = [ "murmur.service" ]; before = [ "murmur.service" ];

View File

@@ -13,8 +13,8 @@ in
system.activationScripts.nextcloudSecrets = system.activationScripts.nextcloudSecrets =
lib.trivial.warn lib.trivial.warn
( (
"nextcloud service is disabled, " + "nextcloud service is disabled, "
"${override-config-fp}, ${db-pass-filepath} and ${admin-pass-filepath} will be removed!" + "${override-config-fp}, ${db-pass-filepath} and ${admin-pass-filepath} will be removed!"
) )
'' ''
rm -f -v ${db-pass-filepath} rm -f -v ${db-pass-filepath}

View File

@@ -1,12 +1,19 @@
{ {
description = "PoC SP module for nextcloud"; description = "PoC SP module for nextcloud";
outputs = { self }: { outputs =
nixosModules.default = _: { self }:
{ imports = [ ./module.nix ./cleanup-module.nix ]; }; {
configPathsNeeded = nixosModules.default = _: {
builtins.fromJSON (builtins.readFile ./config-paths-needed.json); imports = [
meta = { lib, ... }: { ./module.nix
./cleanup-module.nix
];
};
configPathsNeeded = builtins.fromJSON (builtins.readFile ./config-paths-needed.json);
meta =
{ lib, ... }:
{
spModuleSchemaVersion = 1; spModuleSchemaVersion = 1;
id = "nextcloud"; id = "nextcloud";
name = "Nextcloud"; name = "Nextcloud";

View File

@@ -1,4 +1,9 @@
{ config, lib, pkgs, ... }: {
config,
lib,
pkgs,
...
}:
let let
inherit (import ./common.nix config) inherit (import ./common.nix config)
admin-pass-filepath admin-pass-filepath
@@ -27,40 +32,43 @@ let
usersGroup = "sp.${oauthClientID}.users"; usersGroup = "sp.${oauthClientID}.users";
wildcardGroup = "sp.${oauthClientID}.*"; wildcardGroup = "sp.${oauthClientID}.*";
serviceAccountTokenFP = serviceAccountTokenFP = auth-passthru.mkServiceAccountTokenFP linuxUserOfService;
auth-passthru.mkServiceAccountTokenFP linuxUserOfService; oauthClientSecretFP = auth-passthru.mkOAuth2ClientSecretFP linuxUserOfService;
oauthClientSecretFP =
auth-passthru.mkOAuth2ClientSecretFP linuxUserOfService;
updater-page-substitute = updater-page-substitute = pkgs.runCommandNoCC "nextcloud-updater-page-substitute" { } ''
pkgs.runCommandNoCC "nextcloud-updater-page-substitute" { } ''
install -m644 ${./updater.html} -DT $out/index.html install -m644 ${./updater.html} -DT $out/index.html
''; '';
in in
{ {
options.selfprivacy.modules.nextcloud = with lib; { options.selfprivacy.modules.nextcloud = with lib; {
enable = (lib.mkOption { enable =
(lib.mkOption {
default = false; default = false;
type = lib.types.bool; type = lib.types.bool;
description = "Enable Nextcloud"; description = "Enable Nextcloud";
}) // { })
// {
meta = { meta = {
type = "enable"; type = "enable";
}; };
}; };
location = (lib.mkOption { location =
(lib.mkOption {
type = lib.types.str; type = lib.types.str;
description = "Nextcloud location"; description = "Nextcloud location";
}) // { })
// {
meta = { meta = {
type = "location"; type = "location";
}; };
}; };
subdomain = (lib.mkOption { subdomain =
(lib.mkOption {
default = "cloud"; default = "cloud";
type = lib.types.strMatching "[A-Za-z0-9][A-Za-z0-9\-]{0,61}[A-Za-z0-9]"; type = lib.types.strMatching "[A-Za-z0-9][A-Za-z0-9\-]{0,61}[A-Za-z0-9]";
description = "Subdomain"; description = "Subdomain";
}) // { })
// {
meta = { meta = {
widget = "subdomain"; widget = "subdomain";
type = "string"; type = "string";
@@ -68,51 +76,61 @@ in
weight = 0; weight = 0;
}; };
}; };
enableImagemagick = (lib.mkOption { enableImagemagick =
(lib.mkOption {
type = types.bool; type = types.bool;
default = true; default = true;
description = "Enable ImageMagick"; description = "Enable ImageMagick";
}) // { })
// {
meta = { meta = {
type = "bool"; type = "bool";
weight = 1; weight = 1;
}; };
}; };
enableSso = (lib.mkOption { enableSso =
(lib.mkOption {
default = false; default = false;
type = lib.types.bool; type = lib.types.bool;
description = "Enable Single Sign-On"; description = "Enable Single Sign-On";
}) // { })
// {
meta = { meta = {
type = "bool"; type = "bool";
weight = 2; weight = 2;
}; };
}; };
enableSambaFeatures = (lib.mkOption { enableSambaFeatures =
(lib.mkOption {
type = types.bool; type = types.bool;
default = false; default = false;
description = "Enable support for Samba/CIFS features"; description = "Enable support for Samba/CIFS features";
}) // { })
// {
meta = { meta = {
type = "bool"; type = "bool";
weight = 3; weight = 3;
}; };
}; };
debug = (lib.mkOption { debug =
(lib.mkOption {
default = false; default = false;
type = lib.types.bool; type = lib.types.bool;
description = "Enable debug logging"; description = "Enable debug logging";
}) // { })
// {
meta = { meta = {
type = "bool"; type = "bool";
weight = 4; weight = 4;
}; };
}; };
disableMaintenanceModeAtStart = (lib.mkOption { disableMaintenanceModeAtStart =
(lib.mkOption {
type = types.bool; type = types.bool;
default = false; default = false;
description = "Disable maintenance mode at Nextcloud service startup"; description = "Disable maintenance mode at Nextcloud service startup";
}) // { })
// {
meta = { meta = {
type = "bool"; type = "bool";
weight = 5; weight = 5;
@@ -121,13 +139,13 @@ in
}; };
# config = lib.mkIf sp.modules.nextcloud.enable # config = lib.mkIf sp.modules.nextcloud.enable
config = lib.mkIf sp.modules.nextcloud.enable (lib.mkMerge [ config = lib.mkIf sp.modules.nextcloud.enable (
lib.mkMerge [
{ {
assertions = [ assertions = [
{ {
assertion = cfg.enableSso -> sp.sso.enable; assertion = cfg.enableSso -> sp.sso.enable;
message = message = "SSO cannot be enabled for Nextcloud when SSO is disabled globally.";
"SSO cannot be enabled for Nextcloud when SSO is disabled globally.";
} }
]; ];
fileSystems = lib.mkIf sp.useBinds { fileSystems = lib.mkIf sp.useBinds {
@@ -144,8 +162,7 @@ in
}; };
# for ExecStartPost script to have access to /run/keys/* # for ExecStartPost script to have access to /run/keys/*
users.groups.keys.members = users.groups.keys.members = lib.mkIf is-auth-enabled [ linuxUserOfService ];
lib.mkIf is-auth-enabled [ linuxUserOfService ];
# not needed, due to turnOffCertCheck=1 in used_ldap # not needed, due to turnOffCertCheck=1 in used_ldap
# users.groups.${config.security.acme.certs.${domain}.group}.members = # users.groups.${config.security.acme.certs.${domain}.group}.members =
@@ -165,7 +182,10 @@ in
before = [ "nextcloud-setup.service" ]; before = [ "nextcloud-setup.service" ];
requiredBy = [ "nextcloud-setup.service" ]; requiredBy = [ "nextcloud-setup.service" ];
serviceConfig.Type = "oneshot"; serviceConfig.Type = "oneshot";
path = with pkgs; [ coreutils jq ]; path = with pkgs; [
coreutils
jq
];
script = '' script = ''
databasePassword=$(jq -re '.modules.nextcloud.databasePassword' ${secrets-filepath}) databasePassword=$(jq -re '.modules.nextcloud.databasePassword' ${secrets-filepath})
adminPassword=$(jq -re '.modules.nextcloud.adminPassword' ${secrets-filepath}) adminPassword=$(jq -re '.modules.nextcloud.adminPassword' ${secrets-filepath})
@@ -202,10 +222,12 @@ in
configureRedis = true; configureRedis = true;
settings = { settings =
{
# further forces Nextcloud to use HTTPS # further forces Nextcloud to use HTTPS
overwriteprotocol = "https"; overwriteprotocol = "https";
} // lib.attrsets.optionalAttrs is-auth-enabled { }
// lib.attrsets.optionalAttrs is-auth-enabled {
loglevel = 0; loglevel = 0;
# log_type = "file"; # log_type = "file";
social_login_auto_redirect = false; social_login_auto_redirect = false;
@@ -262,7 +284,10 @@ in
# only apply cifs-utils package to this module # only apply cifs-utils package to this module
services.phpfpm.pools.nextcloud.phpEnv.PATH = services.phpfpm.pools.nextcloud.phpEnv.PATH =
lib.mkForce "${pkgs.samba}/bin:${pkgs.cifs-utils}/bin:/run/wrappers/bin:/nix/var/nix/profiles/default/bin:/run/current-system/sw/bin:/usr/bin:/bin"; lib.mkForce "${pkgs.samba}/bin:${pkgs.cifs-utils}/bin:/run/wrappers/bin:/nix/var/nix/profiles/default/bin:/run/current-system/sw/bin:/usr/bin:/bin";
systemd.services.nextcloud-cron.path = [ pkgs.samba pkgs.cifs-utils ]; systemd.services.nextcloud-cron.path = [
pkgs.samba
pkgs.cifs-utils
];
}) })
# the following part is active only when "auth" module is enabled # the following part is active only when "auth" module is enabled
(lib.mkIf is-auth-enabled { (lib.mkIf is-auth-enabled {
@@ -390,15 +415,20 @@ in
subdomain = cfg.subdomain; subdomain = cfg.subdomain;
isTokenNeeded = true; isTokenNeeded = true;
originUrl = "https://${cfg.subdomain}.${domain}/apps/user_oidc/code"; originUrl = "https://${cfg.subdomain}.${domain}/apps/user_oidc/code";
originLanding = originLanding = "https://${cfg.subdomain}.${domain}/apps/user_oidc/login/1";
"https://${cfg.subdomain}.${domain}/apps/user_oidc/login/1";
useShortPreferredUsername = true; useShortPreferredUsername = true;
clientSystemdUnits = clientSystemdUnits = [
[ "nextcloud-setup.service" "phpfpm-nextcloud.service" ]; "nextcloud-setup.service"
"phpfpm-nextcloud.service"
];
enablePkce = true; enablePkce = true;
linuxUserOfClient = linuxUserOfService; linuxUserOfClient = linuxUserOfService;
linuxGroupOfClient = linuxGroupOfService; linuxGroupOfClient = linuxGroupOfService;
scopeMaps.${usersGroup} = [ "email" "openid" "profile" ]; scopeMaps.${usersGroup} = [
"email"
"openid"
"profile"
];
claimMaps.groups = { claimMaps.groups = {
joinType = "array"; joinType = "array";
valuesByGroup.${adminsGroup} = [ "admin" ]; valuesByGroup.${adminsGroup} = [ "admin" ];
@@ -413,5 +443,6 @@ in
''; '';
}; };
}) })
]); ]
);
} }

View File

@@ -1,11 +1,14 @@
{ {
description = "PoC SP module for OpenConnect VPN server (ocserv)"; description = "PoC SP module for OpenConnect VPN server (ocserv)";
outputs = { self }: { outputs =
{ self }:
{
nixosModules.default = import ./module.nix; nixosModules.default = import ./module.nix;
configPathsNeeded = configPathsNeeded = builtins.fromJSON (builtins.readFile ./config-paths-needed.json);
builtins.fromJSON (builtins.readFile ./config-paths-needed.json); meta =
meta = { lib, ... }: { { lib, ... }:
{
spModuleSchemaVersion = 1; spModuleSchemaVersion = 1;
id = "ocserv"; id = "ocserv";
name = "OpenConnect VPN"; name = "OpenConnect VPN";

View File

@@ -7,11 +7,13 @@ let
in in
{ {
options.selfprivacy.modules.ocserv = { options.selfprivacy.modules.ocserv = {
enable = (lib.mkOption { enable =
(lib.mkOption {
default = false; default = false;
type = lib.types.bool; type = lib.types.bool;
description = "Enable"; description = "Enable";
}) // { })
// {
meta = { meta = {
type = "enable"; type = "enable";
}; };
@@ -66,7 +68,10 @@ in
systemd = { systemd = {
services = { services = {
ocserv = { ocserv = {
unitConfig.ConditionPathExists = [ cert key ]; unitConfig.ConditionPathExists = [
cert
key
];
serviceConfig.Slice = "ocserv.slice"; serviceConfig.Slice = "ocserv.slice";
}; };
}; };

View File

@@ -5,12 +5,7 @@ in
# FIXME do we really want to delete passwords on module deactivation!? # FIXME do we really want to delete passwords on module deactivation!?
{ {
config = lib.mkIf (!sp.modules.pleroma.enable) { config = lib.mkIf (!sp.modules.pleroma.enable) {
system.activationScripts.pleroma = system.activationScripts.pleroma = lib.trivial.warn ("pleroma service is disabled, ${secrets-exs} will be removed!") ''
lib.trivial.warn
(
"pleroma service is disabled, ${secrets-exs} will be removed!"
)
''
rm -f -v ${secrets-exs} rm -f -v ${secrets-exs}
''; '';
}; };

View File

@@ -1,5 +1,4 @@
config: config: {
{
sp = config.selfprivacy; sp = config.selfprivacy;
secrets-exs = "/var/lib/pleroma/secrets.exs"; secrets-exs = "/var/lib/pleroma/secrets.exs";
} }

View File

@@ -1,11 +1,14 @@
{ {
description = "PoC SP module for Pleroma lightweight fediverse server"; description = "PoC SP module for Pleroma lightweight fediverse server";
outputs = { self }: { outputs =
{ self }:
{
nixosModules.default = import ./module.nix; nixosModules.default = import ./module.nix;
configPathsNeeded = configPathsNeeded = builtins.fromJSON (builtins.readFile ./config-paths-needed.json);
builtins.fromJSON (builtins.readFile ./config-paths-needed.json); meta =
meta = { lib, ... }: { { lib, ... }:
{
spModuleSchemaVersion = 1; spModuleSchemaVersion = 1;
id = "pleroma"; id = "pleroma";
name = "Pleroma"; name = "Pleroma";

View File

@@ -1,4 +1,9 @@
{ config, lib, pkgs, ... }: {
config,
lib,
pkgs,
...
}:
let let
secrets-filepath = "/etc/selfprivacy/secrets.json"; secrets-filepath = "/etc/selfprivacy/secrets.json";
cfg = config.selfprivacy.modules.pleroma; cfg = config.selfprivacy.modules.pleroma;
@@ -6,28 +11,34 @@ let
in in
{ {
options.selfprivacy.modules.pleroma = { options.selfprivacy.modules.pleroma = {
enable = (lib.mkOption { enable =
(lib.mkOption {
default = false; default = false;
type = lib.types.bool; type = lib.types.bool;
description = "Enable"; description = "Enable";
}) // { })
// {
meta = { meta = {
type = "enable"; type = "enable";
}; };
}; };
location = (lib.mkOption { location =
(lib.mkOption {
type = lib.types.str; type = lib.types.str;
description = "Location"; description = "Location";
}) // { })
// {
meta = { meta = {
type = "location"; type = "location";
}; };
}; };
subdomain = (lib.mkOption { subdomain =
(lib.mkOption {
default = "social"; default = "social";
type = lib.types.strMatching "[A-Za-z0-9][A-Za-z0-9\-]{0,61}[A-Za-z0-9]"; type = lib.types.strMatching "[A-Za-z0-9][A-Za-z0-9\-]{0,61}[A-Za-z0-9]";
description = "Subdomain"; description = "Subdomain";
}) // { })
// {
meta = { meta = {
widget = "subdomain"; widget = "subdomain";
type = "string"; type = "string";
@@ -55,10 +66,9 @@ in
user = "pleroma"; user = "pleroma";
group = "pleroma"; group = "pleroma";
configs = [ configs = [
(builtins.replaceStrings (builtins.replaceStrings [ "$DOMAIN" "$LUSER" ] [ sp.domain sp.username ] (
[ "$DOMAIN" "$LUSER" ] builtins.readFile ./config.exs.in
[ sp.domain sp.username ] ))
(builtins.readFile ./config.exs.in))
]; ];
}; };
postgresql = { postgresql = {
@@ -94,7 +104,10 @@ in
before = [ "pleroma.service" ]; before = [ "pleroma.service" ];
requiredBy = [ "pleroma.service" ]; requiredBy = [ "pleroma.service" ];
serviceConfig.Type = "oneshot"; serviceConfig.Type = "oneshot";
path = with pkgs; [ coreutils jq ]; path = with pkgs; [
coreutils
jq
];
script = '' script = ''
set -o nounset set -o nounset

View File

@@ -1,11 +1,14 @@
{ {
description = "Roundcube is a web-based email client."; description = "Roundcube is a web-based email client.";
outputs = { self }: { outputs =
{ self }:
{
nixosModules.default = import ./module.nix; nixosModules.default = import ./module.nix;
configPathsNeeded = configPathsNeeded = builtins.fromJSON (builtins.readFile ./config-paths-needed.json);
builtins.fromJSON (builtins.readFile ./config-paths-needed.json); meta =
meta = { lib, ... }: { { lib, ... }:
{
spModuleSchemaVersion = 1; spModuleSchemaVersion = 1;
id = "roundcube"; id = "roundcube";
name = "Roundcube"; name = "Roundcube";

View File

@@ -1,4 +1,9 @@
{ config, lib, pkgs, ... }: {
config,
lib,
pkgs,
...
}:
let let
domain = config.selfprivacy.domain; domain = config.selfprivacy.domain;
cfg = config.selfprivacy.modules.roundcube; cfg = config.selfprivacy.modules.roundcube;
@@ -16,31 +21,32 @@ let
usersGroup = "sp.${sp-module-name}.users"; usersGroup = "sp.${sp-module-name}.users";
oauth-donor = config.selfprivacy.passthru.mailserver; oauth-donor = config.selfprivacy.passthru.mailserver;
oauthClientSecretFP = oauthClientSecretFP = auth-passthru.mkOAuth2ClientSecretFP linuxGroupOfService;
auth-passthru.mkOAuth2ClientSecretFP linuxGroupOfService;
# copy client secret from mailserver # copy client secret from mailserver
kanidmExecStartPreScriptRoot = pkgs.writeShellScript kanidmExecStartPreScriptRoot = pkgs.writeShellScript "${sp-module-name}-kanidm-ExecStartPre-root-script.sh" ''
"${sp-module-name}-kanidm-ExecStartPre-root-script.sh"
''
install -v -m640 -o kanidm -g ${linuxGroupOfService} ${oauth-donor.oauth-client-secret-fp} ${oauthClientSecretFP} install -v -m640 -o kanidm -g ${linuxGroupOfService} ${oauth-donor.oauth-client-secret-fp} ${oauthClientSecretFP}
''; '';
in in
{ {
options.selfprivacy.modules.roundcube = { options.selfprivacy.modules.roundcube = {
enable = (lib.mkOption { enable =
(lib.mkOption {
default = false; default = false;
type = lib.types.bool; type = lib.types.bool;
description = "Enable"; description = "Enable";
}) // { })
// {
meta = { meta = {
type = "enable"; type = "enable";
}; };
}; };
subdomain = (lib.mkOption { subdomain =
(lib.mkOption {
default = "roundcube"; default = "roundcube";
type = lib.types.strMatching "[A-Za-z0-9][A-Za-z0-9\-]{0,61}[A-Za-z0-9]"; type = lib.types.strMatching "[A-Za-z0-9][A-Za-z0-9\-]{0,61}[A-Za-z0-9]";
description = "Subdomain"; description = "Subdomain";
}) // { })
// {
meta = { meta = {
widget = "subdomain"; widget = "subdomain";
type = "string"; type = "string";
@@ -48,11 +54,13 @@ in
weight = 0; weight = 0;
}; };
}; };
enableSso = (lib.mkOption { enableSso =
(lib.mkOption {
default = false; default = false;
type = lib.types.bool; type = lib.types.bool;
description = "Enable Single Sign-On"; description = "Enable Single Sign-On";
}) // { })
// {
meta = { meta = {
type = "bool"; type = "bool";
weight = 1; weight = 1;
@@ -60,13 +68,13 @@ in
}; };
}; };
config = lib.mkIf cfg.enable (lib.mkMerge [ config = lib.mkIf cfg.enable (
lib.mkMerge [
{ {
assertions = [ assertions = [
{ {
assertion = cfg.enableSso -> config.selfprivacy.sso.enable; assertion = cfg.enableSso -> config.selfprivacy.sso.enable;
message = message = "SSO cannot be enabled for Roundcube when SSO is disabled globally.";
"SSO cannot be enabled for Roundcube when SSO is disabled globally.";
} }
]; ];
services.roundcube = { services.roundcube = {
@@ -127,7 +135,10 @@ in
originUrl = "https://${cfg.subdomain}.${domain}/index.php/login/oauth"; originUrl = "https://${cfg.subdomain}.${domain}/index.php/login/oauth";
originLanding = "https://${cfg.subdomain}.${domain}/"; originLanding = "https://${cfg.subdomain}.${domain}/";
useShortPreferredUsername = false; useShortPreferredUsername = false;
clientSystemdUnits = [ "dovecot2.service" "phpfpm-roundcube.service" ]; clientSystemdUnits = [
"dovecot2.service"
"phpfpm-roundcube.service"
];
enablePkce = false; enablePkce = false;
linuxUserOfClient = linuxUserOfService; linuxUserOfClient = linuxUserOfService;
linuxGroupOfClient = linuxGroupOfService; linuxGroupOfClient = linuxGroupOfService;
@@ -140,5 +151,6 @@ in
}; };
}; };
}) })
]); ]
);
} }

View File

@@ -1,8 +1,14 @@
{ mailserver-service-account-name {
, mailserver-service-account-token-name mailserver-service-account-name,
, mailserver-service-account-token-fp mailserver-service-account-token-name,
mailserver-service-account-token-fp,
}: }:
{ config, lib, pkgs, ... }@nixos-args: {
config,
lib,
pkgs,
...
}@nixos-args:
let let
inherit (import ./common.nix nixos-args) inherit (import ./common.nix nixos-args)
appendSetting appendSetting
@@ -17,9 +23,7 @@ let
keysPath = auth-passthru.keys-path; keysPath = auth-passthru.keys-path;
# create service account token, needed for LDAP # create service account token, needed for LDAP
kanidmExecStartPostScript = pkgs.writeShellScript kanidmExecStartPostScript = pkgs.writeShellScript "mailserver-kanidm-ExecStartPost-script.sh" ''
"mailserver-kanidm-ExecStartPost-script.sh"
''
export HOME=$RUNTIME_DIRECTORY/client_home export HOME=$RUNTIME_DIRECTORY/client_home
readonly KANIDM="${pkgs.kanidm}/bin/kanidm" readonly KANIDM="${pkgs.kanidm}/bin/kanidm"
@@ -66,10 +70,15 @@ let
''; '';
ldapConfFile = "/run/${runtime-folder}/dovecot-ldap.conf.ext"; ldapConfFile = "/run/${runtime-folder}/dovecot-ldap.conf.ext";
mkLdapSearchScope = scope: ( mkLdapSearchScope =
if scope == "sub" then "subtree" scope:
else if scope == "one" then "onelevel" (
else scope if scope == "sub" then
"subtree"
else if scope == "one" then
"onelevel"
else
scope
); );
dovecot-ldap-config = pkgs.writeTextFile { dovecot-ldap-config = pkgs.writeTextFile {
name = "dovecot-ldap.conf.ext.template"; name = "dovecot-ldap.conf.ext.template";
@@ -101,10 +110,8 @@ let
destination = ldapConfFile; destination = ldapConfFile;
}; };
oauth-client-id = "mailserver"; oauth-client-id = "mailserver";
oauth-client-secret-fp = oauth-client-secret-fp = "${keysPath}/${group}/kanidm-oauth-client-secret";
"${keysPath}/${group}/kanidm-oauth-client-secret"; oauth-secret-ExecStartPreScript = pkgs.writeShellScript "${oauth-client-id}-kanidm-ExecStartPre-script.sh" ''
oauth-secret-ExecStartPreScript = pkgs.writeShellScript
"${oauth-client-id}-kanidm-ExecStartPre-script.sh" ''
set -o xtrace set -o xtrace
[ -f "${oauth-client-secret-fp}" ] || \ [ -f "${oauth-client-secret-fp}" ] || \
"${lib.getExe pkgs.openssl}" rand -base64 32 | tr "\n:@/+=" "012345" > "${oauth-client-secret-fp}" "${lib.getExe pkgs.openssl}" rand -base64 32 | tr "\n:@/+=" "012345" > "${oauth-client-secret-fp}"
@@ -122,8 +129,8 @@ let
openid_configuration_url = ${auth-passthru.oauth2-discovery-url oauth-client-id} openid_configuration_url = ${auth-passthru.oauth2-discovery-url oauth-client-id}
debug = "no" debug = "no"
''; '';
prefix = ''introspection_url = "'' + prefix =
(auth-passthru.oauth2-introspection-url-prefix oauth-client-id); ''introspection_url = "'' + (auth-passthru.oauth2-introspection-url-prefix oauth-client-id);
suffix = auth-passthru.oauth2-introspection-url-postfix + ''"''; suffix = auth-passthru.oauth2-introspection-url-postfix + ''"'';
passwordFile = oauth-client-secret-fp; passwordFile = oauth-client-secret-fp;
destination = dovecot-oauth2-conf-fp; destination = dovecot-oauth2-conf-fp;

View File

@@ -1,4 +1,9 @@
{ config, lib, pkgs, ... }@nixos-args: {
config,
lib,
pkgs,
...
}@nixos-args:
let let
inherit (import ./common.nix nixos-args) inherit (import ./common.nix nixos-args)
appendSetting appendSetting
@@ -9,8 +14,7 @@ let
cfg = config.mailserver; cfg = config.mailserver;
ldapSenderLoginMapFile = "/run/postfix/ldap-sender-login-map.cf"; ldapSenderLoginMapFile = "/run/postfix/ldap-sender-login-map.cf";
submissionOptions.smtpd_sender_login_maps = submissionOptions.smtpd_sender_login_maps = lib.mkForce "hash:/etc/postfix/vaccounts,ldap:${ldapSenderLoginMapFile}";
lib.mkForce "hash:/etc/postfix/vaccounts,ldap:${ldapSenderLoginMapFile}";
commonLdapConfig = '' commonLdapConfig = ''
server_host = ${lib.concatStringsSep " " cfg.ldap.uris} server_host = ${lib.concatStringsSep " " cfg.ldap.uris}
start_tls = ${if cfg.ldap.startTls then "yes" else "no"} start_tls = ${if cfg.ldap.startTls then "yes" else "no"}
@@ -61,8 +65,10 @@ in
${appendPwdInVirtualMailboxMap} ${appendPwdInVirtualMailboxMap}
${appendPwdInSenderLoginMap} ${appendPwdInSenderLoginMap}
''; '';
restartTriggers = restartTriggers = [
[ appendPwdInVirtualMailboxMap appendPwdInSenderLoginMap ]; appendPwdInVirtualMailboxMap
appendPwdInSenderLoginMap
];
wants = [ auth-passthru.oauth2-systemd-service ]; wants = [ auth-passthru.oauth2-systemd-service ];
after = [ auth-passthru.oauth2-systemd-service ]; after = [ auth-passthru.oauth2-systemd-service ];
}; };

View File

@@ -4,11 +4,17 @@ rec {
domain = config.selfprivacy.domain; domain = config.selfprivacy.domain;
group = "dovecot2"; group = "dovecot2";
is-auth-enabled = is-auth-enabled =
config.selfprivacy.modules.simple-nixos-mailserver.enableSso config.selfprivacy.modules.simple-nixos-mailserver.enableSso && config.selfprivacy.sso.enable;
&& config.selfprivacy.sso.enable;
appendSetting = appendSetting =
{ name, file, prefix, suffix ? "", passwordFile, destination }: {
name,
file,
prefix,
suffix ? "",
passwordFile,
destination,
}:
pkgs.writeScript "append-ldap-bind-pwd-in-${name}" '' pkgs.writeScript "append-ldap-bind-pwd-in-${name}" ''
#!${pkgs.stdenv.shell} #!${pkgs.stdenv.shell}
set -euo pipefail set -euo pipefail

View File

@@ -1,4 +1,9 @@
{ config, lib, pkgs, ... }@nixos-args: {
config,
lib,
pkgs,
...
}@nixos-args:
let let
sp = config.selfprivacy; sp = config.selfprivacy;
@@ -11,26 +16,22 @@ let
mailserver-service-account = { mailserver-service-account = {
mailserver-service-account-name = "sp.mailserver.service-account"; mailserver-service-account-name = "sp.mailserver.service-account";
mailserver-service-account-token-name = "mailserver-service-account-token"; mailserver-service-account-token-name = "mailserver-service-account-token";
mailserver-service-account-token-fp = mailserver-service-account-token-fp = "/run/keys/${group}/kanidm-service-account-token"; # FIXME sync with auth module
"/run/keys/${group}/kanidm-service-account-token"; # FIXME sync with auth module
}; };
in in
lib.mkIf sp.modules.simple-nixos-mailserver.enable (lib.mkMerge [ lib.mkIf sp.modules.simple-nixos-mailserver.enable (
lib.mkMerge [
{ {
assertions = [ assertions = [
{ {
assertion = assertion =
config.selfprivacy.modules.simple-nixos-mailserver.enableSso config.selfprivacy.modules.simple-nixos-mailserver.enableSso -> config.selfprivacy.sso.enable;
-> config.selfprivacy.sso.enable; message = "SSO cannot be enabled for Mailserver when SSO is disabled globally.";
message =
"SSO cannot be enabled for Mailserver when SSO is disabled globally.";
} }
]; ];
fileSystems = lib.mkIf sp.useBinds fileSystems = lib.mkIf sp.useBinds {
{
"/var/vmail" = { "/var/vmail" = {
device = device = "/volumes/${sp.modules.simple-nixos-mailserver.location}/vmail";
"/volumes/${sp.modules.simple-nixos-mailserver.location}/vmail";
options = [ options = [
"bind" "bind"
"x-systemd.required-by=postfix.service" "x-systemd.required-by=postfix.service"
@@ -38,8 +39,7 @@ lib.mkIf sp.modules.simple-nixos-mailserver.enable (lib.mkMerge [
]; ];
}; };
"/var/sieve" = { "/var/sieve" = {
device = device = "/volumes/${sp.modules.simple-nixos-mailserver.location}/sieve";
"/volumes/${sp.modules.simple-nixos-mailserver.location}/sieve";
options = [ options = [
"bind" "bind"
"x-systemd.required-by=dovecot2.service" "x-systemd.required-by=dovecot2.service"
@@ -54,7 +54,11 @@ lib.mkIf sp.modules.simple-nixos-mailserver.enable (lib.mkMerge [
}; };
}; };
users.groups.acmereceivers.members = [ "dovecot2" "postfix" "virtualMail" ]; users.groups.acmereceivers.members = [
"dovecot2"
"postfix"
"virtualMail"
];
mailserver = { mailserver = {
enable = true; enable = true;
@@ -64,7 +68,8 @@ lib.mkIf sp.modules.simple-nixos-mailserver.enable (lib.mkMerge [
# A list of all login accounts. To create the password hashes, use # A list of all login accounts. To create the password hashes, use
# mkpasswd -m sha-512 "super secret password" # mkpasswd -m sha-512 "super secret password"
loginAccounts = ({ loginAccounts = (
{
"${sp.username}@${sp.domain}" = { "${sp.username}@${sp.domain}" = {
hashedPassword = sp.hashedMasterPassword; hashedPassword = sp.hashedMasterPassword;
sieveScript = '' sieveScript = ''
@@ -76,8 +81,9 @@ lib.mkIf sp.modules.simple-nixos-mailserver.enable (lib.mkMerge [
} }
''; '';
}; };
} // builtins.listToAttrs (builtins.map }
(user: { // builtins.listToAttrs (
builtins.map (user: {
name = "${user.username}@${sp.domain}"; name = "${user.username}@${sp.domain}";
value = { value = {
hashedPassword = user.hashedPassword; hashedPassword = user.hashedPassword;
@@ -90,8 +96,9 @@ lib.mkIf sp.modules.simple-nixos-mailserver.enable (lib.mkMerge [
} }
''; '';
}; };
}) }) sp.users
sp.users)); )
);
extraVirtualAliases = { extraVirtualAliases = {
"admin@${sp.domain}" = "${sp.username}@${sp.domain}"; "admin@${sp.domain}" = "${sp.username}@${sp.domain}";
@@ -144,8 +151,7 @@ lib.mkIf sp.modules.simple-nixos-mailserver.enable (lib.mkMerge [
# bind.dn = "uid=mail,ou=persons," + ldap_base_dn; # bind.dn = "uid=mail,ou=persons," + ldap_base_dn;
bind.dn = "dn=token"; bind.dn = "dn=token";
# TODO change in this file should trigger system restart dovecot # TODO change in this file should trigger system restart dovecot
bind.passwordFile = bind.passwordFile = mailserver-service-account.mailserver-service-account-token-fp;
mailserver-service-account.mailserver-service-account-token-fp;
# searchBase = "ou=persons," + ldap_base_dn; # searchBase = "ou=persons," + ldap_base_dn;
searchBase = auth-passthru.ldap-base-dn; # TODO refine this searchBase = auth-passthru.ldap-base-dn; # TODO refine this
@@ -155,7 +161,7 @@ lib.mkIf sp.modules.simple-nixos-mailserver.enable (lib.mkMerge [
}; };
}; };
}) })
(lib.mkIf is-auth-enabled (lib.mkIf is-auth-enabled (import ./auth-dovecot.nix mailserver-service-account nixos-args))
(import ./auth-dovecot.nix mailserver-service-account nixos-args))
(lib.mkIf is-auth-enabled (import ./auth-postfix.nix nixos-args)) (lib.mkIf is-auth-enabled (import ./auth-postfix.nix nixos-args))
]) ]
)

View File

@@ -1,10 +1,11 @@
{ {
description = "PoC SP module for the simple-nixos-mailserver"; description = "PoC SP module for the simple-nixos-mailserver";
inputs.mailserver.url = inputs.mailserver.url = "gitlab:simple-nixos-mailserver/nixos-mailserver";
gitlab:simple-nixos-mailserver/nixos-mailserver;
outputs = { self, mailserver }: { outputs =
{ self, mailserver }:
{
nixosModules.default = _: { nixosModules.default = _: {
imports = [ imports = [
mailserver.nixosModules.default mailserver.nixosModules.default
@@ -12,9 +13,10 @@
./config.nix ./config.nix
]; ];
}; };
configPathsNeeded = configPathsNeeded = builtins.fromJSON (builtins.readFile ./config-paths-needed.json);
builtins.fromJSON (builtins.readFile ./config-paths-needed.json); meta =
meta = { lib, ... }: { { lib, ... }:
{
spModuleSchemaVersion = 1; spModuleSchemaVersion = 1;
id = "simple-nixos-mailserver"; id = "simple-nixos-mailserver";
name = "Mail Server"; name = "Mail Server";

View File

@@ -1,28 +1,34 @@
{ lib, ... }: { lib, ... }:
{ {
options.selfprivacy.modules.simple-nixos-mailserver = { options.selfprivacy.modules.simple-nixos-mailserver = {
enable = (lib.mkOption { enable =
(lib.mkOption {
default = false; default = false;
type = lib.types.bool; type = lib.types.bool;
description = "Enable mail server"; description = "Enable mail server";
}) // { })
// {
meta = { meta = {
type = "enable"; type = "enable";
}; };
}; };
location = (lib.mkOption { location =
(lib.mkOption {
type = lib.types.str; type = lib.types.str;
description = "Location"; description = "Location";
}) // { })
// {
meta = { meta = {
type = "location"; type = "location";
}; };
}; };
enableSso = (lib.mkOption { enableSso =
(lib.mkOption {
default = true; default = true;
type = lib.types.bool; type = lib.types.bool;
description = "Enable SSO for mail server"; description = "Enable SSO for mail server";
}) // { })
// {
meta = { meta = {
type = "enable"; type = "enable";
}; };

View File

@@ -5,11 +5,14 @@
nixpkgs-24-11.url = "github:NixOS/nixpkgs/nixos-24.11"; nixpkgs-24-11.url = "github:NixOS/nixpkgs/nixos-24.11";
}; };
outputs = {nixpkgs-24-11, ...}: { outputs =
{ nixpkgs-24-11, ... }:
{
nixosModules.default = import ./module.nix nixpkgs-24-11.legacyPackages.x86_64-linux; nixosModules.default = import ./module.nix nixpkgs-24-11.legacyPackages.x86_64-linux;
configPathsNeeded = configPathsNeeded = builtins.fromJSON (builtins.readFile ./config-paths-needed.json);
builtins.fromJSON (builtins.readFile ./config-paths-needed.json); meta =
meta = {lib, ...}: { { lib, ... }:
{
spModuleSchemaVersion = 1; spModuleSchemaVersion = 1;
id = "vikunja"; id = "vikunja";
name = "Vikunja"; name = "Vikunja";

View File

@@ -1,8 +1,10 @@
latestPkgs: { latestPkgs:
{
config, config,
lib, lib,
... ...
}: let }:
let
sp = config.selfprivacy; sp = config.selfprivacy;
cfg = sp.modules.vikunja; cfg = sp.modules.vikunja;
oauthClientID = "vikunja"; oauthClientID = "vikunja";
@@ -13,18 +15,16 @@ latestPkgs: {
# SelfPrivacy uses SP Module ID to identify the group! # SelfPrivacy uses SP Module ID to identify the group!
usersGroup = "sp.vikunja.users"; usersGroup = "sp.vikunja.users";
oauthClientSecretFP = oauthClientSecretFP = auth-passthru.mkOAuth2ClientSecretFP oauthClientID;
auth-passthru.mkOAuth2ClientSecretFP oauthClientID;
vikunjaPackage = latestPkgs.vikunja.overrideAttrs (old: { vikunjaPackage = latestPkgs.vikunja.overrideAttrs (old: {
doCheck = false; # Tests are slow. doCheck = false; # Tests are slow.
patches = patches = (old.patches or [ ]) ++ [
(old.patches or [])
++ [
./load-client-secret-from-env.patch ./load-client-secret-from-env.patch
]; ];
}); });
in { in
{
options.selfprivacy.modules.vikunja = { options.selfprivacy.modules.vikunja = {
enable = enable =
(lib.mkOption { (lib.mkOption {
@@ -63,9 +63,7 @@ in {
}; };
}; };
config = config = lib.mkIf cfg.enable {
lib.mkIf cfg.enable
{
assertions = [ assertions = [
{ {
assertion = sp.sso.enable; assertion = sp.sso.enable;
@@ -186,7 +184,11 @@ in {
ProtectSystem = "strict"; ProtectSystem = "strict";
RestrictAddressFamilies = ["AF_UNIX" "AF_INET" "AF_INET6"]; RestrictAddressFamilies = [
"AF_UNIX"
"AF_INET"
"AF_INET6"
];
RestrictNamespaces = true; RestrictNamespaces = true;
RestrictRealtime = true; RestrictRealtime = true;
@@ -195,7 +197,16 @@ in {
RemoveIPC = true; RemoveIPC = true;
SystemCallFilter = ["@system-service" "~@cpu-emulation" "~@debug" "~@keyring" "~@memlock" "~@obsolete" "~@privileged" "~@setuid"]; SystemCallFilter = [
"@system-service"
"~@cpu-emulation"
"~@debug"
"~@keyring"
"~@memlock"
"~@obsolete"
"~@privileged"
"~@setuid"
];
}; };
environment.SP_VIKUNJA_CLIENT_SECRET_PATH = "%d/oauth2-secret"; environment.SP_VIKUNJA_CLIENT_SECRET_PATH = "%d/oauth2-secret";
}; };

View File

@@ -6,21 +6,23 @@ in
users = { users = {
mutableUsers = false; mutableUsers = false;
allowNoPasswordLogin = true; allowNoPasswordLogin = true;
users = { users =
{
"${cfg.username}" = { "${cfg.username}" = {
isNormalUser = true; isNormalUser = true;
hashedPassword = cfg.hashedMasterPassword; hashedPassword = cfg.hashedMasterPassword;
openssh.authorizedKeys.keys = cfg.sshKeys; openssh.authorizedKeys.keys = cfg.sshKeys;
}; };
} // builtins.listToAttrs (builtins.map }
(user: { // builtins.listToAttrs (
builtins.map (user: {
name = "${user.username}"; name = "${user.username}";
value = { value = {
isNormalUser = true; isNormalUser = true;
hashedPassword = user.hashedPassword; hashedPassword = user.hashedPassword;
openssh.authorizedKeys.keys = (if user ? sshKeys then user.sshKeys else [ ]); openssh.authorizedKeys.keys = (if user ? sshKeys then user.sshKeys else [ ]);
}; };
}) }) cfg.users
cfg.users); );
}; };
} }

View File

@@ -3,13 +3,13 @@ let
cfg = config.selfprivacy; cfg = config.selfprivacy;
in in
{ {
fileSystems = builtins.listToAttrs (builtins.map fileSystems = builtins.listToAttrs (
(volume: { builtins.map (volume: {
name = "${volume.mountPoint}"; name = "${volume.mountPoint}";
value = { value = {
device = "${volume.device}"; device = "${volume.device}";
fsType = "${volume.fsType}"; fsType = "${volume.fsType}";
}; };
}) }) cfg.volumes
cfg.volumes); );
} }