diff --git a/auth/auth-module.nix b/auth/auth-module.nix new file mode 100644 index 0000000..289c4eb --- /dev/null +++ b/auth/auth-module.nix @@ -0,0 +1,321 @@ +{ config, lib, pkgs, ... }: +let + inherit (lib) + mkOption + types + ; + auth-passthru = config.selfprivacy.passthru.auth; + keys-path = auth-passthru.keys-path; + # TODO consider tmpfiles.d for creating a directory in ${keys-path} + mkKanidmExecStartPreScriptRoot = oauthClientID: group: + pkgs.writeShellScript + "${oauthClientID}-kanidm-ExecStartPre-root-script.sh" + '' + # set-group-ID bit allows kanidm user to create files with another group + mkdir -p -v --mode=u+rwx,g+rs,g-w,o-rwx ${keys-path}/${oauthClientID} + chown kanidm:${group} ${keys-path}/${oauthClientID} + ''; + # generate OAuth2 client secret + mkKanidmExecStartPreScript = oauthClientID: + let + secretFP = auth-passthru.mkOAuth2ClientSecretFP oauthClientID; + in + pkgs.writeShellScript + "${oauthClientID}-kanidm-ExecStartPre-script.sh" '' + [ -f "${secretFP}" ] || \ + "${lib.getExe pkgs.openssl}" rand -base64 -out "${secretFP}" 32 && \ + chmod 640 "${secretFP}" + ''; + mkKanidmExecStartPostScript = oauthClientID: + let + kanidmServiceAccountName = "sp.${oauthClientID}.service-account"; + kanidmServiceAccountTokenName = "${oauthClientID}-service-account-token"; + kanidmServiceAccountTokenFP = + auth-passthru.mkServiceAccountTokenFP oauthClientID; + in + pkgs.writeShellScript + "${oauthClientID}-kanidm-ExecStartPost-script.sh" + '' + export HOME=$RUNTIME_DIRECTORY/client_home + readonly KANIDM="${pkgs.kanidm}/bin/kanidm" + + # try to get existing Kanidm service account + KANIDM_SERVICE_ACCOUNT="$($KANIDM service-account list --name idm_admin | grep -E "^name: ${kanidmServiceAccountName}$")" + echo KANIDM_SERVICE_ACCOUNT: "$KANIDM_SERVICE_ACCOUNT" + if [ -n "$KANIDM_SERVICE_ACCOUNT" ] + then + echo "kanidm service account \"${kanidmServiceAccountName}\" is found" + else + echo "kanidm service account \"${kanidmServiceAccountName}\" is not found" + echo "creating new kanidm service account \"${kanidmServiceAccountName}\"" + if $KANIDM service-account create --name idm_admin "${kanidmServiceAccountName}" "${kanidmServiceAccountName}" idm_admin + then + echo "kanidm service account \"${kanidmServiceAccountName}\" created" + else + echo "error: cannot create kanidm service account \"${kanidmServiceAccountName}\"" + exit 1 + fi + fi + + # add Kanidm service account to `idm_mail_servers` group + $KANIDM group add-members idm_mail_servers "${kanidmServiceAccountName}" + + # create a new read-only token for kanidm + if ! KANIDM_SERVICE_ACCOUNT_TOKEN_JSON="$($KANIDM service-account api-token generate --name idm_admin "${kanidmServiceAccountName}" "${kanidmServiceAccountTokenName}" --output json)" + then + echo "error: kanidm CLI returns an error when trying to generate service-account api-token" + exit 1 + fi + if ! KANIDM_SERVICE_ACCOUNT_TOKEN="$(echo "$KANIDM_SERVICE_ACCOUNT_TOKEN_JSON" | ${lib.getExe pkgs.jq} -r .result)" + then + echo "error: cannot get service-account API token from JSON" + exit 1 + fi + + if ! install --mode=640 \ + <(printf "%s" "$KANIDM_SERVICE_ACCOUNT_TOKEN") \ + ${kanidmServiceAccountTokenFP} + then + echo "error: cannot write token to \"${kanidmServiceAccountTokenFP}\"" + exit 1 + fi + ''; +in +{ + options.selfprivacy.auth = { + clients = mkOption { + description = + "Configurations for OAuth2 & LDAP servers clients services. Corresponding Kanidm provisioning configuration and systemd scripts are generated."; + default = { }; + type = types.attrsOf ( + types.submodule { + options = { + clientID = mkOption { + type = types.nullOr types.str; + description = '' + Name of this client service. Used as OAuth2 client ID and to form Kanidm sp.$\{clientID}.* group names. Defaults to attribute name in virtualHosts; + ''; + default = null; + }; + displayName = mkOption { + type = types.nullOr types.str; + description = "Display name showed in Kanidm Web GUI. Defaults to clientID."; + default = null; + }; + enablePkce = mkOption { + type = lib.types.bool; + description = + "Whether PKCE must be used between client and Kanidm."; + default = false; + }; + adminsGroup = mkOption { + type = + 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."; + default = null; + }; + usersGroup = mkOption { + type = + 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."; + default = null; + }; + originUrl = mkOption { + type = types.nullOr lib.types.str; + description = + "The origin URL of the service for OAuth2 redirects."; + }; + subdomain = lib.mkOption { + type = + lib.types.strMatching "[A-Za-z0-9][A-Za-z0-9\-]{0,61}[A-Za-z0-9]"; + description = "Subdomain of the service."; + }; + # when true, "name" is passed to a service instead of "name@domain" + useShortPreferredUsername = mkOption { + description = + "Use 'name' instead of 'spn' in the preferred_username claim."; + type = types.bool; + default = true; + }; + linuxUserOfClient = mkOption { + type = types.nullOr lib.types.str; + description = + "Name of a Linux OAuth2 client user, under which it should get access through a folder with keys."; + default = null; + }; + linuxGroupOfClient = mkOption { + type = types.nullOr lib.types.str; + description = + "Name of Linux OAuth2 client group, under which it should read an OAuth2 client secret file."; + default = null; + }; + isTokenNeeded = mkOption { + description = + "Whether a read-only needs to be generated for LDAP access."; + type = types.bool; + default = false; + }; + clientSystemdUnits = mkOption { + description = "A list of systemd services, which depend on OAuth service"; + # taken from nixos/lib/systemd-lib.nix: unitNameType + type = types.listOf + (types.strMatching "[a-zA-Z0-9@%:_.\\-]+[.](service|socket|device|mount|automount|swap|target|path|timer|scope|slice)"); + }; + scopeMaps = mkOption { + description = '' + Maps kanidm groups to returned oauth scopes. + See [Scope Relations](https://kanidm.github.io/kanidm/stable/integrations/oauth2.html#scope-relationships) for more information. + ''; + type = types.nullOr (types.attrsOf (types.listOf types.str)); + default = null; + }; + claimMaps = mkOption { + description = '' + Adds additional claims (and values) based on which kanidm groups an authenticating party belongs to. + See [Claim Maps](https://kanidm.github.io/kanidm/master/integrations/oauth2.html#custom-claim-maps) for more information. + ''; + default = { }; + type = types.attrsOf ( + types.submodule { + options = { + joinType = mkOption { + description = '' + Determines how multiple values are joined to create the claim value. + See [Claim Maps](https://kanidm.github.io/kanidm/master/integrations/oauth2.html#custom-claim-maps) for more information. + ''; + type = types.enum [ + "array" + "csv" + "ssv" + ]; + default = "array"; + }; + + valuesByGroup = mkOption { + description = "Maps kanidm groups to values for the claim."; + default = { }; + type = types.attrsOf (types.listOf types.str); + }; + }; + } + ); + }; + }; + } + ); + }; + }; + # (lib.debug.traceValSeq + config = lib.mkIf config.selfprivacy.sso.enable ( + let + clientsAttrsList = lib.attrsets.mapAttrsToList + (name: attrs: attrs // rec { + clientID = + if attrs.clientID == null + then name + else attrs.clientID; + displayName = + if attrs.displayName == null + then clientID + else attrs.displayName; + 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}/${clientID}/kanidm-oauth-client-secret"; + linuxUserOfClient = + if attrs.linuxUserOfClient == null + then clientID + else attrs.linuxUserOfClient; + linuxGroupOfClient = + if attrs.linuxGroupOfClient == null + then clientID + else attrs.linuxGroupOfClient; + scopeMaps = + if attrs.scopeMaps == null + then { "${usersGroup}" = [ "email" "openid" "profile" ]; } + else attrs.scopeMaps; + }) + config.selfprivacy.auth.clients; + in + { + # for each OAuth2 client: member of the `keys` group for directory access + users.groups.keys.members = lib.mkMerge (lib.forEach + clientsAttrsList + ({ linuxUserOfClient, ... }: [ linuxUserOfClient ]) + ); + + # for each OAuth2 client: scripts with Kanidm CLI commands + systemd.services.kanidm = { + before = + lib.lists.concatMap + ({ clientSystemdUnits, ... }: clientSystemdUnits) + clientsAttrsList; + serviceConfig = + lib.mkMerge (lib.forEach + clientsAttrsList + ({ clientID, isTokenNeeded, linuxGroupOfClient, ... }: { + ExecStartPre = [ + # "-" prefix means to ignore exit code of prefixed script + # "+" prefix means to run script with superuser priveleges + ("-+" + mkKanidmExecStartPreScriptRoot clientID linuxGroupOfClient) + ("-" + mkKanidmExecStartPreScript clientID) + ]; + ExecStartPost = lib.mkIf isTokenNeeded + (lib.mkAfter [ ("-" + mkKanidmExecStartPostScript clientID) ]); + })); + }; + + # for each OAuth2 client: Kanidm provisioning options + services.kanidm.provision = lib.mkMerge (lib.forEach + clientsAttrsList + ({ adminsGroup + , basicSecretFile + , claimMaps + , clientID + , displayName + , enablePkce + , originUrl + , scopeMaps + , useShortPreferredUsername + , subdomain + , usersGroup + , ... + }: { + groups = { + "${adminsGroup}".members = + [ auth-passthru.admins-group ]; + "${usersGroup}".members = + [ adminsGroup auth-passthru.full-users-group ]; + }; + systems.oauth2.${clientID} = { + inherit + basicSecretFile + claimMaps + displayName + originUrl + scopeMaps + ; + originLanding = + "https://${subdomain}.${config.selfprivacy.domain}/"; + preferShortUsername = useShortPreferredUsername; + allowInsecureClientDisablePkce = ! enablePkce; + removeOrphanedClaimMaps = true; + + # NOTE https://github.com/oddlama/kanidm-provision/issues/15 + # add more scopes when a user is a member of specific group + # currently not possible due to https://github.com/kanidm/kanidm/issues/2882#issuecomment-2564490144 + # supplementaryScopeMaps."${admins-group}" = + # [ "read:admin" "write:admin" ]; + }; + })); + } + ); +} diff --git a/auth/auth.nix b/auth/auth.nix index 2a44026..246a09d 100644 --- a/auth/auth.nix +++ b/auth/auth.nix @@ -222,6 +222,7 @@ lib.mkIf config.selfprivacy.sso.enable { full-users-group ldap-host ldap-port + keys-path ; oauth2-introspection-url-prefix = client_id: "https://${client_id}:"; oauth2-introspection-url-postfix = @@ -237,5 +238,12 @@ lib.mkIf config.selfprivacy.sso.enable { "," (x: "dc=" + x) (lib.strings.splitString "." domain); + + # TODO consider to pass a value or throw exception if token is not generated + mkServiceAccountTokenFP = oauthClientID: + "${keys-path}/${oauthClientID}/kanidm-service-account-token"; + + mkOAuth2ClientSecretFP = oauthClientID: + "${keys-path}/${oauthClientID}/kanidm-oauth-client-secret"; }; } diff --git a/configuration.nix b/configuration.nix index 6aa93c8..025d3c3 100644 --- a/configuration.nix +++ b/configuration.nix @@ -32,6 +32,7 @@ in { imports = [ ./selfprivacy-module.nix + ./auth/auth-module.nix ./volumes.nix ./users.nix ./letsencrypt/acme.nix diff --git a/sp-modules/gitea/config-paths-needed.json b/sp-modules/gitea/config-paths-needed.json index 08ee684..63ea4fe 100644 --- a/sp-modules/gitea/config-paths-needed.json +++ b/sp-modules/gitea/config-paths-needed.json @@ -2,17 +2,14 @@ [ "selfprivacy", "domain" ], [ "selfprivacy", "modules", "auth", "enable" ], [ "selfprivacy", "modules", "gitea" ], - [ "selfprivacy", "passthru", "auth", "admins-group" ], - [ "selfprivacy", "passthru", "auth", "auth-fqdn" ], - [ "selfprivacy", "passthru", "auth", "full-users-group" ], [ "selfprivacy", "passthru", "auth", "ldap-base-dn" ], [ "selfprivacy", "passthru", "auth", "ldap-host" ], [ "selfprivacy", "passthru", "auth", "ldap-port" ], + [ "selfprivacy", "passthru", "auth", "mkOAuth2ClientSecretFP" ], + [ "selfprivacy", "passthru", "auth", "mkServiceAccountTokenFP" ], [ "selfprivacy", "passthru", "auth", "oauth2-discovery-url" ], [ "selfprivacy", "passthru", "auth", "oauth2-provider-name" ], - [ "selfprivacy", "passthru", "auth", "oauth2-systemd-service" ], [ "selfprivacy", "sso", "enable" ], [ "selfprivacy", "useBinds" ], - [ "services", "forgejo", "group" ], [ "services", "forgejo", "package" ] ] diff --git a/sp-modules/gitea/module.nix b/sp-modules/gitea/module.nix index b8fd07d..1b8a000 100644 --- a/sp-modules/gitea/module.nix +++ b/sp-modules/gitea/module.nix @@ -15,81 +15,23 @@ let "gitea-dark" ]; is-auth-enabled = cfg.enableSso && config.selfprivacy.sso.enable; - oauth-client-id = "forgejo"; + oauthClientID = "forgejo"; auth-passthru = config.selfprivacy.passthru.auth; oauth2-provider-name = auth-passthru.oauth2-provider-name; redirect-uri = "https://${cfg.subdomain}.${sp.domain}/user/oauth2/${oauth2-provider-name}/callback"; - admins-group = "sp.forgejo.admins"; - users-group = "sp.forgejo.users"; + adminsGroup = "sp.forgejo.admins"; + usersGroup = "sp.forgejo.users"; - kanidm-service-account-name = "sp.${oauth-client-id}.service-account"; - kanidm-service-account-token-name = "${oauth-client-id}-service-account-token"; - kanidm-service-account-token-fp = - "/run/keys/${oauth-client-id}/kanidm-service-account-token"; # FIXME sync with auth module - # TODO rewrite to tmpfiles.d - kanidmExecStartPreScriptRoot = pkgs.writeShellScript - "${oauth-client-id}-kanidm-ExecStartPre-root-script.sh" - '' - # set-group-ID bit allows kanidm user to create files with another group - mkdir -p -v --mode=u+rwx,g+rs,g-w,o-rwx /run/keys/${oauth-client-id} - chown kanidm:${config.services.forgejo.group} /run/keys/${oauth-client-id} - ''; - kanidm-oauth-client-secret-fp = - "/run/keys/${oauth-client-id}/kanidm-oauth-client-secret"; - kanidmExecStartPreScript = pkgs.writeShellScript - "${oauth-client-id}-kanidm-ExecStartPre-script.sh" '' - [ -f "${kanidm-oauth-client-secret-fp}" ] || \ - "${lib.getExe pkgs.openssl}" rand -base64 -out "${kanidm-oauth-client-secret-fp}" 32 - ''; - kanidmExecStartPostScript = pkgs.writeShellScript - "${oauth-client-id}-kanidm-ExecStartPost-script.sh" - '' - export HOME=$RUNTIME_DIRECTORY/client_home - readonly KANIDM="${pkgs.kanidm}/bin/kanidm" + linuxUserOfService = "gitea"; + linuxGroupOfService = "gitea"; + forgejoPackage = pkgs.forgejo; - # get Kanidm service account for mailserver - KANIDM_SERVICE_ACCOUNT="$($KANIDM service-account list --name idm_admin | grep -E "^name: ${kanidm-service-account-name}$")" - echo KANIDM_SERVICE_ACCOUNT: "$KANIDM_SERVICE_ACCOUNT" - if [ -n "$KANIDM_SERVICE_ACCOUNT" ] - then - echo "kanidm service account \"${kanidm-service-account-name}\" is found" - else - echo "kanidm service account \"${kanidm-service-account-name}\" is not found" - echo "creating new kanidm service account \"${kanidm-service-account-name}\"" - if $KANIDM service-account create --name idm_admin "${kanidm-service-account-name}" "${kanidm-service-account-name}" idm_admin - then - echo "kanidm service account \"${kanidm-service-account-name}\" created" - else - echo "error: cannot create kanidm service account \"${kanidm-service-account-name}\"" - exit 1 - fi - fi - - # add Kanidm service account to `idm_mail_servers` group - $KANIDM group add-members idm_mail_servers "${kanidm-service-account-name}" - - # create a new read-only token for kanidm - if ! KANIDM_SERVICE_ACCOUNT_TOKEN_JSON="$($KANIDM service-account api-token generate --name idm_admin "${kanidm-service-account-name}" "${kanidm-service-account-token-name}" --output json)" - then - echo "error: kanidm CLI returns an error when trying to generate service-account api-token" - exit 1 - fi - if ! KANIDM_SERVICE_ACCOUNT_TOKEN="$(echo "$KANIDM_SERVICE_ACCOUNT_TOKEN_JSON" | ${lib.getExe pkgs.jq} -r .result)" - then - echo "error: cannot get service-account API token from JSON" - exit 1 - fi - - if ! install --mode=640 \ - <(printf "%s" "$KANIDM_SERVICE_ACCOUNT_TOKEN") \ - ${kanidm-service-account-token-fp} - then - echo "error: cannot write token to \"${kanidm-service-account-token-fp}\"" - exit 1 - fi - ''; + serviceAccountTokenFP = + auth-passthru.mkServiceAccountTokenFP oauthClientID; + oauthClientSecretFP = + auth-passthru.mkOAuth2ClientSecretFP oauthClientID; in { options.selfprivacy.modules.gitea = { @@ -216,15 +158,15 @@ in services.gitea.enable = false; services.forgejo = { enable = true; - package = pkgs.forgejo; + package = forgejoPackage; inherit stateDir; - user = "gitea"; - group = "gitea"; + user = linuxUserOfService; + group = linuxGroupOfService; database = { type = "sqlite3"; host = "127.0.0.1"; name = "gitea"; - user = "gitea"; + user = linuxUserOfService; path = "${stateDir}/data/gitea.db"; createDatabase = true; }; @@ -281,10 +223,10 @@ in users.users.gitea = { home = "${stateDir}"; useDefaultShell = true; - group = "gitea"; + group = linuxGroupOfService; isSystemUser = true; }; - users.groups.gitea = { }; + users.groups.${linuxGroupOfService} = { }; services.nginx.virtualHosts."${cfg.subdomain}.${sp.domain}" = { useACMEHost = sp.domain; forceSSL = true; @@ -315,7 +257,7 @@ in }; }; } - # the following part is active only when "auth" module is enabled + # the following part is active only when enableSso = true (lib.mkIf is-auth-enabled { services.forgejo.settings = { auth.DISABLE_LOGIN_FORM = true; @@ -359,25 +301,25 @@ in --host '${auth-passthru.ldap-host}' \ --port '${toString auth-passthru.ldap-port}' \ --user-search-base '${auth-passthru.ldap-base-dn}' \ - --user-filter '(&(class=person)(memberof=${users-group})(name=%s))' \ - --admin-filter '(&(class=person)(memberof=${admins-group})' \ + --user-filter '(&(class=person)(memberof=${usersGroup})(name=%s))' \ + --admin-filter '(&(class=person)(memberof=${adminsGroup})' \ --username-attribute name \ --firstname-attribute name \ --surname-attribute displayname \ --email-attribute mail \ --public-ssh-key-attribute sshPublicKey \ --bind-dn 'dn=token' \ - --bind-password "$(cat ${kanidm-service-account-token-fp})" \ + --bind-password "$(< ${serviceAccountTokenFP})" \ --synchronize-users ''; oauthConfigArgs = '' --name "${oauth2-provider-name}" \ --provider openidConnect \ --key forgejo \ - --secret "$(<${kanidm-oauth-client-secret-fp})" \ + --secret "$(< ${oauthClientSecretFP})" \ --group-claim-name groups \ --admin-group admins \ - --auto-discover-url '${auth-passthru.oauth2-discovery-url oauth-client-id}' + --auto-discover-url '${auth-passthru.oauth2-discovery-url oauthClientID}' ''; in lib.mkAfter '' @@ -403,21 +345,8 @@ in ${exe} admin auth add-oauth ${oauthConfigArgs} fi ''; - # TODO consider passing oauth consumer service to auth module instead - after = [ auth-passthru.oauth2-systemd-service ]; - requires = [ auth-passthru.oauth2-systemd-service ]; }; - # for ExecStartPost script to have access to /run/keys/* - users.groups.keys.members = [ config.services.forgejo.group ]; - - systemd.services.kanidm.serviceConfig.ExecStartPre = [ - ("-+" + kanidmExecStartPreScriptRoot) - ("-" + kanidmExecStartPreScript) - ]; - systemd.services.kanidm.serviceConfig.ExecStartPost = - lib.mkAfter [ ("-" + kanidmExecStartPostScript) ]; - services.nginx.virtualHosts."${cfg.subdomain}.${sp.domain}" = { extraConfig = lib.mkAfter '' rewrite ^/user/login$ /user/oauth2/${oauth2-provider-name} last; @@ -426,38 +355,15 @@ in ''; }; - services.kanidm.provision = { - groups = { - "${admins-group}".members = [ auth-passthru.admins-group ]; - "${users-group}".members = - [ admins-group auth-passthru.full-users-group ]; - }; - systems.oauth2.forgejo = { - displayName = "Forgejo"; - originUrl = redirect-uri; - originLanding = "https://${cfg.subdomain}.${sp.domain}/"; - basicSecretFile = kanidm-oauth-client-secret-fp; - # when true, name is passed to a service instead of name@domain - preferShortUsername = true; - allowInsecureClientDisablePkce = true; # FIXME is it needed? - scopeMaps = { - "${users-group}" = [ - "email" - "openid" - "profile" - ]; - }; - removeOrphanedClaimMaps = true; - # NOTE https://github.com/oddlama/kanidm-provision/issues/15 - # add more scopes when a user is a member of specific group - # currently not possible due to https://github.com/kanidm/kanidm/issues/2882#issuecomment-2564490144 - # supplementaryScopeMaps."${admins-group}" = - # [ "read:admin" "write:admin" ]; - claimMaps.groups = { - joinType = "array"; - valuesByGroup.${admins-group} = [ "admins" ]; - }; - }; + selfprivacy.auth.clients."${oauthClientID}" = { + inherit adminsGroup usersGroup; + subdomain = cfg.subdomain; + isTokenNeeded = true; + originUrl = redirect-uri; + clientSystemdUnits = [ "forgejo.service" ]; + enablePkce = false; # FIXME maybe Forgejo supports PKCE? + linuxUserOfClient = linuxUserOfService; + linuxGroupOfClient = linuxGroupOfService; }; }) ]);