From 2c1cd6a3ffcf8bcf9ea5aee705a9cda5206ec446 Mon Sep 17 00:00:00 2001 From: xblackicex Date: Fri, 6 Nov 2026 16:14:42 +0100 Subject: [PATCH 1/2] feat(nix): add flake package, dev shell, and NixOS module S-022: build, run, and develop syauth through a flake on x86-64 and ARM64 Linux. The package derivation runs the Rust workspace test suite and installs the CLI, daemon, and PAM module. The development shell supplies the pinned fenix toolchain plus the git-hooks checks. S-023: nixosModules.default configures one desktop account, its private store, and a restricted systemd user unit. PAM changes are opt-in per service and support a control override and module arguments. nix/check.nix evaluates the generated configuration. Docs: add the Nix how-to and module option reference, and record both journeys in the roadmap. --- .envrc | 1 + .gitignore | 4 + AGENTS.md | 7 + README.md | 20 +++ docs/how-to/install.md | 94 ++++++++++++ docs/reference/nix-modules.md | 23 +++ flake.lock | 104 ++++++++++++++ flake.nix | 136 ++++++++++++++++++ mkdocs.yml | 1 + nix/check.nix | 93 ++++++++++++ nix/modules/nixos.nix | 131 +++++++++++++++++ nix/package.nix | 89 ++++++++++++ specs/bugs/BUG-20261104-1330.md | 125 ++++++++++++++++ .../journeys/JOURNEY-S-022-nix-flake-linux.md | 37 +++++ specs/journeys/JOURNEY-S-023-nix-modules.md | 42 ++++++ specs/syauth/ROADMAP.md | 34 +++++ 16 files changed, 941 insertions(+) create mode 100644 .envrc create mode 100644 docs/reference/nix-modules.md create mode 100644 flake.lock create mode 100644 flake.nix create mode 100644 nix/check.nix create mode 100644 nix/modules/nixos.nix create mode 100644 nix/package.nix create mode 100644 specs/bugs/BUG-20261104-1330.md create mode 100644 specs/journeys/JOURNEY-S-022-nix-flake-linux.md create mode 100644 specs/journeys/JOURNEY-S-023-nix-modules.md diff --git a/.envrc b/.envrc new file mode 100644 index 0000000..8a73b1b --- /dev/null +++ b/.envrc @@ -0,0 +1 @@ +use flake . --accept-flake-config diff --git a/.gitignore b/.gitignore index 2a9ca10..faf99a2 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,7 @@ .DS_Store __pycache__/ *.pyc +.direnv/ +.pre-commit-config.yaml +result +result-* diff --git a/AGENTS.md b/AGENTS.md index bc90a06..31b4dfd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -410,6 +410,13 @@ make install # Install to ~/.cargo/bin make docker-build # Build Docker image make docker-test # Build and run tests in container +# Nix +nix develop . # Enter the pinned Rust development environment +nix build . # Build the package and run workspace tests +nix flake check . # Check the package and generated NixOS configuration +nix develop . --command make lint +nix develop . --command make test + # Benchmarks make bench # Run benchmarks ``` diff --git a/README.md b/README.md index 4e8c30e..affd825 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,8 @@ Approve Linux authentication on your Android phone with a fresh strong biometric ## Install +For Nix or NixOS, use the [Nix setup below](#nix-and-nixos). + On a supported Linux desktop: ```sh @@ -29,6 +31,21 @@ Release downloads include DEB, RPM, Arch Linux packages, and manual Linux archiv Use Debian 12+, Ubuntu 24.04+, a current Fedora/openSUSE/Arch installation, or a compatible derivative, with glibc 2.36+, PAM, systemd user services, BlueZ, and a BLE adapter capable of advertising. The phone needs Android 13+ with a supported Ed25519 Keystore implementation and an enrolled strong biometric. The APK can install on older Android versions, but that does not establish signing-key support. +### Nix and NixOS + +The flake supports `x86_64-linux` and `aarch64-linux`. With Nix and flakes enabled, install into your user profile without cloning the repository: + +```sh +nix profile install github:dmytrogajewski/syauth +syauth --version +``` + +This installs the CLI, `syauth-presenced` daemon, and PAM module; storage, service activation, and PAM still need configuration. See [profile installation and setup](docs/how-to/install.md#install-with-nix) for details and update/removal commands. + +For NixOS, add `github:dmytrogajewski/syauth` as a flake input and import `syauth.nixosModules.default`. Enable `services.syauth`, set `desktopUser` to your existing desktop account, and select the PAM services through `pam.services` (empty by default). The module manages the package, private bond-store directory, and daemon in that account's systemd user session. Run pairing as that account, without `sudo`. + +Follow the [installation guide](docs/how-to/install.md#configure-nixos) for the complete flake configuration and activation commands. The [NixOS module reference](docs/reference/nix-modules.md) documents all options and PAM policy. + ## Use 1. Install the desktop package and signed Android companion. @@ -48,12 +65,15 @@ Being nearby prepares the connection; each authentication still needs explicit a - [First unlock tutorial](https://dmytrogajewski.github.io/syauth/tutorials/first-unlock/) - [Install](https://dmytrogajewski.github.io/syauth/how-to/install/), [pair and revoke](https://dmytrogajewski.github.io/syauth/how-to/pair-and-revoke/), [troubleshoot](https://dmytrogajewski.github.io/syauth/how-to/troubleshoot/) +- [Nix and NixOS setup](docs/how-to/install.md#install-with-nix), [NixOS module options](docs/reference/nix-modules.md) - [CLI](https://dmytrogajewski.github.io/syauth/reference/cli/), [configuration](https://dmytrogajewski.github.io/syauth/reference/configuration/), [protocol](https://dmytrogajewski.github.io/syauth/reference/protocol/) - [Illustrated mechanics](https://dmytrogajewski.github.io/syauth/explanation/mechanics/) with animated pairing, discovery, and unlock - [Release builds and signing](https://dmytrogajewski.github.io/syauth/contributing/releases/) ## Development and contributing +For a pinned Rust development environment, run `nix develop .`. Entering the shell also installs the repository's pre-commit hooks. Build from a checkout with `nix build .` and try the CLI with `nix run . -- --version`. Run `nix flake check .` to build the package and check the generated NixOS configuration; see [building with Nix](docs/how-to/install.md#with-nix) for details. + The Rust workspace is under `crates/`; the Android app is under `syauth-android/`. Build from source with a toolchain compatible with the committed `Cargo.lock` and development packages for D-Bus, PAM, and Bluetooth: ```sh diff --git a/docs/how-to/install.md b/docs/how-to/install.md index 3068ae7..127aee2 100644 --- a/docs/how-to/install.md +++ b/docs/how-to/install.md @@ -2,6 +2,8 @@ This guide sets up the desktop daemon and Android companion, then explains how to enable one PAM service. It targets a single desktop account using the default `/var/lib/syauth` store. +Choose a desktop installation method: [release package](#install-a-release-package), [Nix profile](#install-with-nix), [NixOS module](#configure-nixos), or [source build](#build-the-desktop-from-source). Then install the Android companion and pair your phone. The NixOS module manages storage, the user service, and selected PAM rules; other installation methods need those setup steps separately. + ## Prerequisites Use Linux with glibc 2.36+, PAM, systemd user services, BlueZ, and a BLE adapter capable of advertising. Release packages target Debian 12+, Ubuntu 24.04+, and current Fedora, openSUSE, and Arch systems. Both x86_64 and ARM64 artifacts are available; the tested distribution/CPU matrix is listed in [release development](../contributing/releases.md#artifact-contract). @@ -53,8 +55,100 @@ For ARM64, use the DEB ending in `_arm64.deb`, or the RPM/Arch filename with `aa Packages install `/usr/bin/syauth`, `/usr/libexec/syauth-presenced`, the distribution's `pam_syauth.so`, and `/usr/lib/systemd/user/syauth-presenced.service`. Continue with storage preparation below. +## Install with Nix + +On x86-64 or ARM64 Linux with flakes enabled: + +```sh +nix profile install github:dmytrogajewski/syauth +syauth --version +``` + +Includes the CLI, daemon, and PAM module. On NixOS, use the +[module below](#configure-nixos). Otherwise, follow [storage and service setup](#prepare-storage-and-the-user-service), +using the profile's `syauth-presenced` as `--from` and +`lib/security/pam_syauth.so` as the PAM module path. + +Update or remove using the entry name from `nix profile list`: + +```sh +nix profile list +nix profile upgrade syauth +nix profile remove syauth +``` + +Remove its PAM rules and disable the user service before uninstalling. + +## Configure NixOS + +Add the input and module to your NixOS `flake.nix`: + +```nix +{ + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; + syauth = { + url = "github:dmytrogajewski/syauth"; + inputs.nixpkgs.follows = "nixpkgs"; + }; + }; + + outputs = { nixpkgs, syauth, ... }: { + nixosConfigurations.my-host = nixpkgs.lib.nixosSystem { + system = "x86_64-linux"; + modules = [ + ./configuration.nix + syauth.nixosModules.default + { + hardware.bluetooth.enable = true; + services.syauth = { + enable = true; + desktopUser = "alice"; + pam.services = [ "sudo" ]; + pam.moduleArgs = [ "socket=/run/user/1000/syauth/auth.sock" ]; + }; + } + ]; + }; + }; +} +``` + +Adjust `my-host`, `system`, and `alice` for your host. The account must +exist in `users.users`; use its UID (`id -u alice`) in the socket path. + +PAM services: `sudo` (also `sudo-i` for [sudo-rs](https://github.com/trifectatechfoundation/sudo-rs)), `kde` (Plasma lock screen), +`plasmalogin` (Plasma Login Manager). See [module options](../reference/nix-modules.md) +for defaults and PAM policy. The daemon requires an active user session. + ## Build the desktop from source +### With Nix + +From a checkout, enter the development shell: + +```sh +nix develop . +make build +make test +make lint +``` + +The shell provides pinned Rust and pre-commit hooks; +[nix-direnv](https://github.com/nix-community/nix-direnv) users can run +`direnv allow` for automatic loading. The flake declares the nix-community +Cachix cache. + +For the Nix package and module checks: + +```sh +nix build . +nix run . -- --version +nix flake check . +``` + +### With Cargo + Source builds additionally require a Rust toolchain compatible with `Cargo.lock`, a C toolchain, `pkg-config`, and development packages for D-Bus, PAM, and Bluetooth (`libdbus-1-dev`, `libpam0g-dev`, and `libbluetooth-dev` on Debian). From a checkout of syauth: diff --git a/docs/reference/nix-modules.md b/docs/reference/nix-modules.md new file mode 100644 index 0000000..04cbc1f --- /dev/null +++ b/docs/reference/nix-modules.md @@ -0,0 +1,23 @@ +# NixOS module options + +Import `nixosModules.default` to configure syauth for one desktop account. +See the [NixOS setup example](../how-to/install.md#configure-nixos). + +| Option under `services.syauth` | Default | Purpose | +| --- | --- | --- | +| `enable` | `false` | Install syauth and declare the user service. | +| `desktopUser` | Required when enabled | Owns `/var/lib/syauth`, runs the daemon, and pairs phones. | +| `package` | Flake's syauth package | Supplies the CLI, daemon and PAM module. | +| `installCli` | `true` | Put syauth on the system PATH. | +| `pam.services` | `[ ]` | PAM services to change. | +| `pam.control` | `"sufficient"` | Control field applied to each injected PAM rule. | +| `pam.moduleArgs` | `[ ]` | Arguments passed to each rule, such as `socket=`. | + +The module inserts its rule before the service's enabled Unix password rule. +For a stack such as `plasmalogin`, it inserts the rule before the first +enabled authentication rule. If you override a service's PAM text directly, +that text must include the syauth authentication rule. + +With the default `sufficient` control, successful phone approval can end +authentication. On failure PAM continues with the service's other rules. +See [PAM policy](configuration.md#pam-policy) before changing the control. diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..d82bf66 --- /dev/null +++ b/flake.lock @@ -0,0 +1,104 @@ +{ + "nodes": { + "fenix": { + "inputs": { + "nixpkgs": [ + "nixpkgs" + ], + "rust-analyzer-src": "rust-analyzer-src" + }, + "locked": { + "lastModified": 1793801102, + "narHash": "sha256-XZz60a37nUaPX0zH8TcD83ChVVyRV9o/H/t1dr4RZpk=", + "owner": "nix-community", + "repo": "fenix", + "rev": "12b7e3178c093a8af075f4a889238a2fffa3d0ef", + "type": "github" + }, + "original": { + "owner": "nix-community", + "repo": "fenix", + "type": "github" + } + }, + "flake-compat": { + "flake": false, + "locked": { + "lastModified": 1767039857, + "narHash": "sha256-vNpUSpF5Nuw8xvDLj2KCwwksIbjua2LZCqhV1LNRDns=", + "owner": "NixOS", + "repo": "flake-compat", + "rev": "5edf11c44bc78a0d334f6334cdaf7d60d732daab", + "type": "github" + }, + "original": { + "owner": "NixOS", + "repo": "flake-compat", + "type": "github" + } + }, + "git-hooks": { + "inputs": { + "flake-compat": "flake-compat", + "nixpkgs": [ + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1793686154, + "narHash": "sha256-Zb/0L3soxrkfcrywpfp0J++0WFLB3tzh0Xtx9up+VNc=", + "owner": "cachix", + "repo": "git-hooks.nix", + "rev": "204b6977e00caac19e2313015a598543ca7be150", + "type": "github" + }, + "original": { + "owner": "cachix", + "repo": "git-hooks.nix", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1793726008, + "narHash": "sha256-jQp1wKvbwWdLBASTXkSi/VYmDJ5AbBi1WvcMt9HWJC8=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "1d060086d60cb76a40cf37109f979d88a5bd6396", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "fenix": "fenix", + "git-hooks": "git-hooks", + "nixpkgs": "nixpkgs" + } + }, + "rust-analyzer-src": { + "flake": false, + "locked": { + "lastModified": 1793735662, + "narHash": "sha256-hUBVevUu17ttsuKYse5Sfswe8NFvCPgjI5CIHd59DO4=", + "owner": "rust-lang", + "repo": "rust-analyzer", + "rev": "5c7b55ffdceacf7c4907c00b6bbc459f6cd1686c", + "type": "github" + }, + "original": { + "owner": "rust-lang", + "ref": "nightly", + "repo": "rust-analyzer", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..1dbaa7d --- /dev/null +++ b/flake.nix @@ -0,0 +1,136 @@ +{ + description = "syauth — phone-as-key unlock for Linux PAM"; + # Nix configuration: allow binary cache from nix-community to speed up builds + + nixConfig = { + extra-substituters = [ "https://nix-community.cachix.org" ]; + extra-trusted-public-keys = [ + "nix-community.cachix.org-1:mB9FSh9qf2dCimDSUo8Zy7bkq5CX+/rkCWyvRCYg3Fs" + ]; + }; + + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; + fenix = { + url = "github:nix-community/fenix"; + inputs.nixpkgs.follows = "nixpkgs"; + }; + git-hooks = { + url = "github:cachix/git-hooks.nix"; + inputs.nixpkgs.follows = "nixpkgs"; + }; + }; + + outputs = + { + self, + nixpkgs, + fenix, + git-hooks, + }: + let + eachSystem = nixpkgs.lib.genAttrs [ + "x86_64-linux" + "aarch64-linux" + ]; + pkgsFor = system: nixpkgs.legacyPackages.${system}; + toolchainFor = system: fenix.packages.${system}.stable.toolchain; + + # `git-hooks.nix` installs the pre-commit configuration when the + # development shell starts. Rust hooks use the flake's pinned toolchain + # so local commits and `make lint` agree. + preCommitFor = + system: + let + toolchain = toolchainFor system; + in + git-hooks.lib.${system}.run { + src = ./.; + hooks = { + check-added-large-files.enable = true; + check-merge-conflicts.enable = true; + deadnix.enable = true; + nixfmt.enable = true; + statix.enable = true; + + clippy = { + enable = true; + packageOverrides = { + cargo = toolchain; + clippy = toolchain; + }; + settings = { + allFeatures = true; + denyWarnings = true; + extraArgs = "--workspace --all-targets"; + }; + }; + + rustfmt = { + enable = true; + packageOverrides = { + cargo = toolchain; + rustfmt = toolchain; + }; + settings.check = true; + }; + }; + }; + in + { + packages = eachSystem (system: rec { + syauth = (pkgsFor system).callPackage ./nix/package.nix { + rustToolchain = toolchainFor system; + }; + default = syauth; + }); + + apps = eachSystem (system: rec { + syauth = { + type = "app"; + program = "${self.packages.${system}.syauth}/bin/syauth"; + meta.description = "Run the syauth command-line tool"; + }; + default = syauth; + }); + + devShells = eachSystem ( + system: + let + pkgs = pkgsFor system; + preCommit = preCommitFor system; + in + { + default = pkgs.mkShell { + packages = [ + (toolchainFor system) + ] + ++ (with pkgs; [ + gnumake + pkg-config + dbus + python3 + git + cargo-audit + cargo-deny + ]) + ++ preCommit.enabledPackages; + inherit (preCommit) shellHook; + }; + } + ); + + nixosModules.default = import ./nix/modules/nixos.nix { inherit self; }; + + checks = eachSystem (system: { + package = self.packages.${system}.syauth; + nixos-module = import ./nix/check.nix { + inherit nixpkgs; + pkgs = pkgsFor system; + module = self.nixosModules.default; + }; + }); + + formatter = eachSystem (system: (pkgsFor system).nixfmt-rfc-style); + }; +} diff --git a/mkdocs.yml b/mkdocs.yml index 3de62da..39b028c 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -59,6 +59,7 @@ nav: - Reference: - CLI: reference/cli.md - Configuration: reference/configuration.md + - NixOS modules: reference/nix-modules.md - Protocol: reference/protocol.md - Glossary: reference/glossary.md - Explanation: diff --git a/nix/check.nix b/nix/check.nix new file mode 100644 index 0000000..4dd388b --- /dev/null +++ b/nix/check.nix @@ -0,0 +1,93 @@ +# Journey: specs/journeys/JOURNEY-S-023-nix-modules.md +{ + nixpkgs, + pkgs, + module, +}: +let + inherit (pkgs) lib; + user = "fixture"; + socket = "socket=/run/user/1000/syauth/auth.sock"; + evaluate = + modules: + (nixpkgs.lib.nixosSystem { + system = pkgs.stdenv.hostPlatform.system; + modules = [ + { + system.stateVersion = "25.11"; + users.users.${user} = { + isNormalUser = true; + uid = 1000; + }; + security.sudo.enable = false; + security.sudo-rs.enable = true; + services.displayManager.plasma-login-manager.enable = true; + services.desktopManager.plasma6.enable = true; + } + ] + ++ modules; + }).config; + baseline = evaluate [ ]; + setup.services.syauth = { + enable = true; + desktopUser = user; + }; + noPam = evaluate [ + module + setup + ]; + services = [ + "sudo" + "sudo-i" + "kde" + "plasmalogin" + ]; + enabled = evaluate [ + module + setup + { + services.syauth.pam = { + inherit services; + moduleArgs = [ socket ]; + }; + } + ]; + override = evaluate [ + module + setup + { + services.syauth.pam = { + services = [ "sudo" ]; + control = "required"; + }; + } + ]; + textOverride = evaluate [ + module + setup + { + services.syauth.pam.services = [ "sudo" ]; + security.pam.services.sudo.text = "# pam_syauth.so\nauth required pam_unix.so\n"; + } + ]; + pamFailures = + config: + builtins.filter (a: !a.assertion && lib.hasInfix "lacks an auth rule" a.message) config.assertions; + pam = config: name: config.security.pam.services.${name}; + unit = enabled.systemd.user.services.syauth-presenced; + hasRule = + name: + let + service = pam enabled name; + anchor = if name == "plasmalogin" then "login" else "unix"; + in + service.rules.auth.syauth.order < service.rules.auth.${anchor}.order + && lib.hasInfix (builtins.unsafeDiscardStringContext "auth sufficient ${enabled.services.syauth.package}/lib/security/pam_syauth.so ${socket}") service.text; +in +assert noPam.security.pam.services.sudo.text == baseline.security.pam.services.sudo.text; +assert unit.unitConfig.ConditionUser == user && builtins.elem "default.target" unit.wantedBy; +assert builtins.elem "d /var/lib/syauth 0700 ${user} users -" enabled.systemd.tmpfiles.rules; +assert lib.all hasRule services; +assert pamFailures enabled == [ ] && builtins.length (pamFailures textOverride) == 1; +assert (pam override "sudo").rules.auth.syauth.control == "required"; +pkgs.runCommand "syauth-nixos-module-check" { } "touch $out" diff --git a/nix/modules/nixos.nix b/nix/modules/nixos.nix new file mode 100644 index 0000000..c2ca5f2 --- /dev/null +++ b/nix/modules/nixos.nix @@ -0,0 +1,131 @@ +{ self }: +{ + config, + lib, + pkgs, + ... +}: +let + cfg = config.services.syauth; + store = "/var/lib/syauth"; + account = config.users.users.${cfg.desktopUser} or { }; + pamModule = "${cfg.package}/lib/security/pam_syauth.so"; + + anchorOrder = + name: + let + # Exclude the injected rule because its order depends on this lookup. + rules = removeAttrs config.security.pam.services.${name}.rules.auth [ "syauth" ]; + orders = lib.mapAttrsToList (_: rule: rule.order) (lib.filterAttrs (_: rule: rule.enable) rules); + in + if rules.unix.enable or false then + rules.unix.order + else if orders != [ ] then + lib.head (lib.sort builtins.lessThan orders) + else + throw "services.syauth.pam.services: ${name} has no enabled auth rule to anchor syauth to."; + + hasSyauthRule = + text: + lib.any ( + line: + builtins.match "[[:blank:]]*auth[[:blank:]]+([[][^]]+[]]|[^[:blank:]]+)[[:blank:]]+([^[:blank:]]*/)?pam_syauth[.]so([[:blank:]].*)?" line + != null + ) (lib.splitString "\n" text); +in +{ + options.services.syauth = { + enable = lib.mkEnableOption "syauth for one desktop account"; + + desktopUser = lib.mkOption { + type = lib.types.str; + example = "alice"; + description = "Account that pairs phones, owns the bond store, and runs the user service."; + }; + + package = lib.mkOption { + type = lib.types.package; + default = self.packages.${pkgs.stdenv.hostPlatform.system}.syauth; + defaultText = lib.literalExpression "self.packages.\${system}.syauth"; + description = "Package providing the CLI, daemon, and PAM module."; + }; + + installCli = lib.mkOption { + type = lib.types.bool; + default = true; + description = "Add the syauth package to the system PATH."; + }; + + pam = { + services = lib.mkOption { + type = lib.types.listOf lib.types.str; + default = [ ]; + example = [ + "sudo" + "sudo-i" + ]; + description = "PAM services to configure for phone authentication."; + }; + + control = lib.mkOption { + type = lib.types.str; + default = "sufficient"; + description = "PAM control field used for the syauth rule in the selected services."; + }; + + moduleArgs = lib.mkOption { + type = lib.types.listOf lib.types.str; + default = [ ]; + example = [ "socket=/run/user/1000/syauth/auth.sock" ]; + description = "Arguments passed to pam_syauth.so in each selected service."; + }; + }; + }; + + config = lib.mkIf cfg.enable { + assertions = [ + { + assertion = config.users.users ? ${cfg.desktopUser}; + message = "services.syauth.desktopUser must name an account declared in users.users."; + } + ] + ++ map (name: { + assertion = hasSyauthRule config.security.pam.services.${name}.text; + message = "PAM service ${name} lacks an auth rule for pam_syauth.so. Check security.pam.services.${name}.text."; + }) cfg.pam.services; + + systemd.tmpfiles.rules = [ "d ${store} 0700 ${cfg.desktopUser} ${account.group or "-"} -" ]; + environment.systemPackages = lib.optional cfg.installCli cfg.package; + + systemd.user.services.syauth-presenced = { + description = "syauth phone-as-key presence daemon"; + wantedBy = [ "default.target" ]; + unitConfig = { + ConditionUser = cfg.desktopUser; + ConditionPathIsDirectory = "%t"; + }; + serviceConfig = { + ExecStart = "${cfg.package}/bin/syauth-presenced"; + Restart = "on-failure"; + RestartSec = 2; + TimeoutStopSec = 5; + NoNewPrivileges = true; + ProtectSystem = "strict"; + ProtectHome = "read-only"; + ReadWritePaths = [ + store + "%t" + ]; + }; + }; + + security.pam.services = lib.genAttrs cfg.pam.services (name: { + rules.auth.syauth = { + inherit (cfg.pam) control; + modulePath = pamModule; + order = anchorOrder name - 10; + args = cfg.pam.moduleArgs; + }; + }); + }; +} diff --git a/nix/package.nix b/nix/package.nix new file mode 100644 index 0000000..2dad322 --- /dev/null +++ b/nix/package.nix @@ -0,0 +1,89 @@ +# One derivation for the whole workspace: the `syauth` CLI, the +# `syauth-presenced` daemon, and the PAM module cdylib. +{ + lib, + stdenv, + makeRustPlatform, + autoPatchelfHook, + pkg-config, + dbus, + python3, + rustToolchain, +}: + +let + rustPlatform = makeRustPlatform { + cargo = rustToolchain; + rustc = rustToolchain; + }; + + # nixpkgs drives cargo with an explicit `--target `, so the release + # artifacts land one directory deeper than a plain `cargo build --release`. + releaseDir = "target/${stdenv.hostPlatform.rust.rustcTarget}/release"; +in +rustPlatform.buildRustPackage { + pname = "syauth"; + version = (lib.importTOML ../Cargo.toml).workspace.package.version; + + src = lib.fileset.toSource { + root = ../.; + fileset = lib.fileset.unions [ + ../Cargo.toml + ../Cargo.lock + ../crates + ../src + ../tests + ../scripts + ../deploy + ../docs/perf-baselines.md + ]; + }; + + cargoLock.lockFile = ../Cargo.lock; + + # BlueZ needs D-Bus and tests/bt_matrix.rs runs a Python test suite. + # Rust binaries also link `libgcc_s.so.1` at runtime; list the compiler + # runtime as an input so `autoPatchelfHook` searches it and puts it in RPATH. + buildInputs = [ + dbus + (lib.getLib stdenv.cc.cc) + ]; + nativeBuildInputs = [ + autoPatchelfHook + pkg-config + python3 + ]; + + # The root manifest is both a package and the workspace root. + cargoBuildFlags = [ "--workspace" ]; + cargoTestFlags = [ "--workspace" ]; + doCheck = true; + + # The upstream integration test expects the daemon directly under target/release. + # + # Test binaries link against `libdbus-1.so.3` but only the installed files + # get an ELF rpath, so the check phase needs the D-Bus library on the loader + # search path for `cargo test` to start the `bluer`-backed tests. + preCheck = '' + export LD_LIBRARY_PATH="${lib.makeLibraryPath [ dbus ]}''${LD_LIBRARY_PATH:+:}''${LD_LIBRARY_PATH:-}" + mkdir -p target/release + ln -sfn ../${stdenv.hostPlatform.rust.rustcTarget}/release/syauth-presenced target/release/syauth-presenced + ''; + + installPhase = '' + runHook preInstall + mkdir -p $out/bin $out/lib/security + install -m755 ${releaseDir}/syauth $out/bin/syauth + install -m755 ${releaseDir}/syauth-presenced $out/bin/syauth-presenced + install -m755 ${releaseDir}/libpam_syauth.so $out/lib/security/pam_syauth.so + runHook postInstall + ''; + + meta = { + description = "Phone-as-key unlock for Linux PAM"; + homepage = "https://github.com/sy/syauth"; + license = lib.licenses.mit; + platforms = lib.platforms.linux; + mainProgram = "syauth"; + }; +} diff --git a/specs/bugs/BUG-20261104-1330.md b/specs/bugs/BUG-20261104-1330.md new file mode 100644 index 0000000..152ed4c --- /dev/null +++ b/specs/bugs/BUG-20261104-1330.md @@ -0,0 +1,125 @@ +# BUG-20261104-1330: Daemon loses the adapter at boot and permanently serves the Challenge stub + +## Summary + +`syauth-presenced` starts about a second after `bluetoothd`, before the +kernel has finished setting up `hci0`, so `Session::default_adapter()` +fails with "the target object was either not present or removed". The +daemon logs one `WARN`, drops the orchestrator for the rest of its +lifetime, and keeps answering `Request::Challenge` from the S-002 stub +(`reason="not-implemented"`). The PAM module maps that unknown reason to +`PAM_AUTH_ERR` and logs `unlock denied reason=unknown-reason`, so every +unlock fails until the unit is restarted by hand. + +Pairing is unaffected because `syauth pair` is a separate process that +opens the adapter itself; a bond can be minted while unlocks are dead. + +## Reproduction + +Manual, captured on the reporter's host (boot `c73ac0295d4f45…`): + +``` +13:42:35.409 bluetoothd: Bluetooth management interface 1.23 initialized +13:42:36.196 syauth-presenced: WARN orchestrator not started; daemon will serve socket only + reason="BlueZ adapter open failed: peripheral backend error: + default adapter selection: the target object was either not present or removed" +13:42:36.323 kernel: Bluetooth: hci0: Device setup in 2624999 usecs +``` + +The daemon queried D-Bus 127 ms before the adapter object existed. + +Wire-level confirmation, before the restart: + +```console +$ printf '' | socat - UNIX-CONNECT:$XDG_RUNTIME_DIR/syauth/auth.sock +a4 64 6b 69 6e 64 69 63 68 61 6c 6c 65 6e 67 65 62 6f 6b f4 … + {"kind": "challenge", "ok": false, "signature": null, "reason": "not-implemented"} +``` + +After `systemctl --user restart syauth-presenced` the same probe returns +`response-timeout` (a real challenge was issued to the phone), and the +daemon log shows the full orchestrator path: + +``` +13:56:25 registering GATT app with pair service peers=0 +13:56:25 GATT app registration accepted by BlueZ +13:56:26 phone subscribed via standard notifications +13:56:28 notify_challenge: writing frame peer_id=5bbd89ad… +13:56:33 tx peer=5bbd89ad… outcome=ok +``` + +The same race is visible on the preceding boot (`12:42:36`, same +message), while a mid-session restart (`12:35:12`) opened the adapter +successfully — the failure is tied to starting before the adapter is +exported, not to the store or the bonds file. + +## Expected Behavior + +The daemon acquires the adapter once BlueZ exposes it (or retries with +backoff), and an unlock attempt while the radio is unavailable is +reported as `adapter-missing` / `offline` so PAM falls through to the +next auth module instead of returning `AUTH_ERR`. + +## Actual Behavior + +`PersistentPeripheral::new_default()` fails, the orchestrator is never +constructed, and every `Request::Challenge` gets the stub answer +`reason="not-implemented"`. `outcome_reason_to_pam` does not know that +token, so it fails closed with `unknown-reason` → `PAM_AUTH_ERR` +(`crates/syauth-pam/src/auth.rs:212`). Because the process stays alive, +`Restart=on-failure` never fires; only a manual restart recovers it. + +## Root Cause Analysis + +1. Startup ordering. The user unit (`crates/syauth-presenced/dist/syauth-presenced.service`) + has `WantedBy=default.target` and no ordering or readiness gate + against `bluetooth.target` / `bluetooth.service`. With autologin the + user manager races `bluetoothd`; the kernel's `hci0` setup finished + 127 ms after the daemon's only probe. +2. No retry. `crates/syauth-presenced/src/runtime.rs:332-337` returns + `(None, None, None)` on any adapter-open error and the `WARN` is the + only signal. There is no watchdog on adapter appearance/reappearance. +3. Wrong degraded reason. `crates/syauth-presenced/src/server.rs:353-357` + answers with `STUB_CHALLENGE_REASON` when `orchestrator == None`, + which is indistinguishable from the not-yet-implemented S-002 stub. + The PAM taxonomy has an `adapter-missing` token but the daemon never + emits it on this path. +4. Diagnostic blind spot. `syauth doctor` reports `doctor=ok` while the + orchestrator is dead, and `syauth status` prints `advertising=false` + from a constant, so neither surface shows the degraded state. + +## Fix + +Workaround applied on the host (survives reboots, no rebuild needed): + +`~/.config/systemd/user/syauth-presenced.service.d/wait-for-adapter.conf` + +```ini +[Service] +ExecStartPre=/bin/sh -c 'i=0; while [ $i -lt 120 ]; do bluetoothctl show 2>/dev/null | grep -q "^Controller " && exit 0; i=$((i+1)); sleep 0.5; done; exit 0' +TimeoutStartSec=90 +``` + +Verified with `systemctl --user daemon-reload && systemctl --user restart +syauth-presenced`: startup log shows `GATT app registration accepted by +BlueZ` and the rotation timer. + +Source-level fix (not yet applied): + +- `runtime.rs`: retry `PersistentPeripheral::new_default()` with bounded + exponential backoff and re-arm on adapter loss, instead of returning + once. +- `server.rs` / `runtime.rs`: when the orchestrator is absent, answer + `adapter-missing` (or `offline`) rather than the S-002 stub token. +- `syauth doctor` / `syauth status`: probe the orchestrator + GATT + registration instead of a constant. + +## Traceability + +- Daemon: `crates/syauth-presenced/src/runtime.rs` (`maybe_spawn_orchestrator`), + `crates/syauth-presenced/src/server.rs` (`dispatch`), + `crates/syauth-transport/src/peripheral.rs` (`new_default`). +- PAM mapping: `crates/syauth-pam/src/auth.rs:198-213`. +- Unit: `crates/syauth-presenced/dist/syauth-presenced.service`. +- Related: BUG-20261104-0332 (pairing on the same host; same daemon, + different failure), BUG-20261103-2227 (store ownership). diff --git a/specs/journeys/JOURNEY-S-022-nix-flake-linux.md b/specs/journeys/JOURNEY-S-022-nix-flake-linux.md new file mode 100644 index 0000000..2c07b00 --- /dev/null +++ b/specs/journeys/JOURNEY-S-022-nix-flake-linux.md @@ -0,0 +1,37 @@ +# JOURNEY-S-022: Build, run and develop with Nix + +## Roadmap Link + +[Step S-022](../syauth/ROADMAP.md#step-s-022-nix-flake) + +## 1. Journey + +A Linux user builds syauth or runs the CLI from a checkout. A contributor can +enter the same pinned Rust environment to work on the code. + +## 2. CJM + +| Phase | User action | Expected result | +| --- | --- | --- | +| Build | `nix build .` | The result includes the CLI, daemon and PAM module. | +| Run | `nix run . -- --version` | The CLI reports its version. | +| Develop | `nix develop .` | Cargo and the lint tools are available. | + +## 3. UX Implementation and Assessment + +The package and shell are available on x86-64 and ARM64 Linux. The default +flake outputs give the common commands a short entry point. + +## 4. Tests + +`nix flake check` covers the package and NixOS module. The package build +runs the Rust workspace suite. + +## Implementation + +`flake.nix`, `flake.lock` (which pins the fenix stable toolchain), +`nix/package.nix` and [the Nix build instructions](../../docs/how-to/install.md#with-nix). + +## Traceability + +[Step S-022](../syauth/ROADMAP.md#step-s-022-nix-flake) diff --git a/specs/journeys/JOURNEY-S-023-nix-modules.md b/specs/journeys/JOURNEY-S-023-nix-modules.md new file mode 100644 index 0000000..7fe1a47 --- /dev/null +++ b/specs/journeys/JOURNEY-S-023-nix-modules.md @@ -0,0 +1,42 @@ +# JOURNEY-S-023: Configure syauth for a NixOS desktop account + +## Roadmap Link + +[Step S-023](../syauth/ROADMAP.md#step-s-023-nixos-module) + +## 1. Journey + +A NixOS user enables syauth for their desktop account and lists the PAM +services where they want phone authentication. They pair from that account +and use the phone or the service's existing authentication path. + +## 2. CJM + +| Phase | User action | Expected result | +| --- | --- | --- | +| Configure | Import the NixOS module and name the desktop account and PAM services. | The configuration owns the CLI, private store and user unit. | +| Pair | Run `syauth pair` from the desktop account. | The daemon can read the resulting bond. | +| Authenticate | Use an enabled service and approve on the phone. | The selected PAM policy handles approval and fallback. | + +## 3. UX Implementation and Assessment + +One account owns the store and runs the user unit. PAM changes are opt-in by +service. The administrator can override the control and specify the daemon +socket for callers outside the user session. + +## 4. Tests + +The flake check evaluates a NixOS configuration and checks the user unit, +directory ownership, inert PAM defaults, and rules for the sudo-rs and Plasma +services. It checks that an explicit PAM control reaches the generated rule. +The Rust workspace still exercises the daemon binary against a fake radio. + +## Implementation + +- `nix/modules/nixos.nix` declares the installation, user service and PAM rules. +- `nix/check.nix` is the NixOS evaluation check. +- The [installation guide](../../docs/how-to/install.md#configure-nixos) documents the flake input, module import, and settings. + +## Traceability + +[Step S-023](../syauth/ROADMAP.md#step-s-023-nixos-module) diff --git a/specs/syauth/ROADMAP.md b/specs/syauth/ROADMAP.md index 917273c..45d4036 100644 --- a/specs/syauth/ROADMAP.md +++ b/specs/syauth/ROADMAP.md @@ -1020,6 +1020,40 @@ The method is a hidden API since API 1 and remains hidden in API 34. `Reflection --- +## Step S-022: Nix flake + +Build and run syauth with Nix on x86-64 and ARM64 Linux. The default +development shell supplies the pinned Rust toolchain. + +- [x] Expose the package, CLI app, development shell and checks for both systems. +- [x] Run the Rust workspace suite in the package build. +- [x] Document [Nix installation](../../docs/how-to/install.md#install-with-nix) + and [build commands](../../docs/how-to/install.md#with-nix). + +[Journey S-022](../journeys/JOURNEY-S-022-nix-flake-linux.md) · +[Flake](../../flake.nix) · [Package](../../nix/package.nix) + +## Step S-023: NixOS module + +Configure one desktop account through `nixosModules.default`. The module +sets up the CLI, private store, systemd user unit, and selected PAM rules. + +- [x] The generated user unit is restricted to the selected account, which also + owns the store. +- [x] PAM is opt-in by service. The rule supports a control override and + socket arguments, including services that use a substack. +- [x] The flake has one NixOS evaluation check covering the generated + configuration. +- [x] The [installation guide](../../docs/how-to/install.md#configure-nixos) + includes the flake input, module import, and settings. + +[Journey S-023](../journeys/JOURNEY-S-023-nix-modules.md) · +[Module](../../nix/modules/nixos.nix) · [Check](../../nix/check.nix) + +Verified by flake checks on x86-64 and by evaluation on ARM64. The module +check covers the generated sudo-rs and Plasma PAM rules, and the rendered +systemd unit uses the configured account's `ConditionUser`. + ## Dependency graph ``` From ce7a87d335c0f96d71972d8a7895887ea686a962 Mon Sep 17 00:00:00 2001 From: Dmitriy Date: Sun, 8 Nov 2026 01:41:01 +0300 Subject: [PATCH 2/2] fix(nix): derive PAM socket and exercise installation in CI --- .github/workflows/ci.yml | 17 +++ AGENTS.md | 2 +- README.md | 2 +- docs/how-to/install.md | 4 + docs/reference/nix-modules.md | 23 +++- flake.nix | 7 +- nix/check.nix | 48 +++++++++ nix/modules/nixos.nix | 10 +- nix/tests/fixture.py | 26 +++++ nix/tests/installation.nix | 74 +++++++++++++ nix/tests/installation.py | 114 ++++++++++++++++++++ specs/bugs/BUG-20261108-nix-pam-socket.md | 52 +++++++++ specs/journeys/JOURNEY-S-023-nix-modules.md | 9 ++ specs/syauth/ROADMAP.md | 4 +- 14 files changed, 386 insertions(+), 6 deletions(-) create mode 100644 nix/tests/fixture.py create mode 100644 nix/tests/installation.nix create mode 100644 nix/tests/installation.py create mode 100644 specs/bugs/BUG-20261108-nix-pam-socket.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6be42a6..829aeb9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,6 +34,23 @@ env: CARGO_INCREMENTAL: "0" jobs: + nix: + name: nix (package + module + VM) + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + - uses: cachix/install-nix-action@v31 + with: + enable_kvm: true + extra_nix_config: | + system-features = nixos-test big-parallel kvm + max-jobs = 2 + cores = 2 + - name: Check Nix formatting + run: nix --accept-flake-config fmt -- --check flake.nix nix/*.nix nix/modules/*.nix nix/tests/*.nix + - name: Build package, evaluate module, and boot the integration VM + run: nix --accept-flake-config flake check --no-write-lock-file --print-build-logs + lint: name: lint (clippy + fmt + deny + scope-discipline) runs-on: ubuntu-latest diff --git a/AGENTS.md b/AGENTS.md index 31b4dfd..e2b2be6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -413,7 +413,7 @@ make docker-test # Build and run tests in container # Nix nix develop . # Enter the pinned Rust development environment nix build . # Build the package and run workspace tests -nix flake check . # Check the package and generated NixOS configuration +nix flake check . # Check package/module and boot integration VM (requires KVM) nix develop . --command make lint nix develop . --command make test diff --git a/README.md b/README.md index 14927e6..31395a1 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,7 @@ Being nearby prepares the connection; each authentication still needs explicit a ## Development and contributing -For a pinned Rust development environment, run `nix develop .`. Entering the shell also installs the repository's pre-commit hooks. Build from a checkout with `nix build .` and try the CLI with `nix run . -- --version`. Run `nix flake check .` to build the package and check the generated NixOS configuration; see [building with Nix](docs/how-to/install.md#with-nix) for details. +For a pinned Rust development environment, run `nix develop .`. Entering the shell also installs the repository's pre-commit hooks. Build from a checkout with `nix build .` and try the CLI with `nix run . -- --version`. Run `nix flake check .` to build the package, check the generated NixOS configuration, and boot the installed-PAM integration VM (requires writable `/dev/kvm`); see [building with Nix](docs/how-to/install.md#with-nix) for details. The Rust workspace is under `crates/`; the Android app is under `syauth-android/`. Build from source with a toolchain compatible with the committed `Cargo.lock` and development packages for D-Bus, PAM, and Bluetooth: diff --git a/docs/how-to/install.md b/docs/how-to/install.md index ab5d003..5a2223f 100644 --- a/docs/how-to/install.md +++ b/docs/how-to/install.md @@ -147,6 +147,10 @@ nix run . -- --version nix flake check . ``` +The flake check also boots a disposable NixOS VM and exercises the installed +PAM library and daemon. Run it on Linux with writable `/dev/kvm`; it uses +synthetic signing fixtures and does not require your phone or Bluetooth adapter. + ### With Cargo Source builds additionally require a Rust toolchain compatible with `Cargo.lock`, a C toolchain, `pkg-config`, and development packages for D-Bus, PAM, and Bluetooth (`libdbus-1-dev`, `libpam0g-dev`, and `libbluetooth-dev` on Debian). diff --git a/docs/reference/nix-modules.md b/docs/reference/nix-modules.md index 5b1713d..171ed40 100644 --- a/docs/reference/nix-modules.md +++ b/docs/reference/nix-modules.md @@ -14,7 +14,15 @@ matching the upstream service's recovery policy when a controller disappears. | `installCli` | `true` | Put syauth on the system PATH. | | `pam.services` | `[ ]` | PAM services to change. | | `pam.control` | `"sufficient"` | Control field applied to each injected PAM rule. | -| `pam.moduleArgs` | `[ ]` | Arguments passed to each rule, such as `socket=`. | +| `pam.moduleArgs` | Socket for the declared desktop UID | Arguments passed to each rule; requires an absolute `socket=` path when PAM is enabled. | + +When `users.users..uid` is explicitly declared, the default argument +is `socket=/run/user//syauth/auth.sock`. This works for root-run PAM callers +without relying on their environment. If NixOS allocates the UID at activation, +set `pam.moduleArgs` explicitly using the account's actual runtime socket path. +An empty argument list with PAM enabled is rejected during configuration checks. +Explicit arguments replace the generated default, so retain `socket=` when +adding other arguments. The module inserts its rule before the service's enabled Unix password rule. For a stack such as `plasmalogin`, it inserts the rule before the first @@ -24,3 +32,16 @@ that text must include the syauth authentication rule. With the default `sufficient` control, successful phone approval can end authentication. On failure PAM continues with the service's other rules. See [PAM policy](configuration.md#pam-policy) before changing the control. + +## Automated validation + +`nix flake check` builds the package, checks generated rules and invalid +configurations, and boots a NixOS integration VM. The VM exercises installed +PAM and the daemon with deterministic public signing fixtures, including +PAM-before-daemon audit ownership, valid and invalid signatures, password +fallback, two-account isolation, sudo and sudo-rs, profile removal, and +disable/rollback preserving bonds. It uses no physical Bluetooth adapter or +Android phone and does not establish radio or biometric behavior. + +Run on a Linux machine with writable `/dev/kvm`. GitHub CI enables KVM through +the Nix installation action and runs the same flake checks with sandboxing. diff --git a/flake.nix b/flake.nix index 7eae1c3..bfb7ccd 100644 --- a/flake.nix +++ b/flake.nix @@ -131,8 +131,13 @@ pkgs = pkgsFor system; module = self.nixosModules.default; }; + nixos-vm = import ./nix/tests/installation.nix { + pkgs = pkgsFor system; + module = self.nixosModules.default; + package = self.packages.${system}.syauth; + }; }); - formatter = eachSystem (system: (pkgsFor system).nixfmt-rfc-style); + formatter = eachSystem (system: (pkgsFor system).nixfmt); }; } diff --git a/nix/check.nix b/nix/check.nix index 130f1e4..ab663f1 100644 --- a/nix/check.nix +++ b/nix/check.nix @@ -70,6 +70,45 @@ let security.pam.services.sudo.text = "# pam_syauth.so\nauth required pam_unix.so\n"; } ]; + unknownUid = evaluate [ + module + setup + { + users.users.${user}.uid = lib.mkForce null; + services.syauth.pam.services = [ "sudo" ]; + } + ]; + explicitSocket = evaluate [ + module + setup + { + users.users.${user}.uid = lib.mkForce null; + services.syauth.pam = { + services = [ "sudo" ]; + moduleArgs = [ socket ]; + }; + } + ]; + emptyArgs = evaluate [ + module + setup + { + services.syauth.pam = { + services = [ "sudo" ]; + moduleArgs = [ ]; + }; + } + ]; + relativeSocket = evaluate [ + module + setup + { + services.syauth.pam = { + services = [ "sudo" ]; + moduleArgs = [ "socket=auth.sock" ]; + }; + } + ]; pamFailures = config: builtins.filter (a: !a.assertion && lib.hasInfix "lacks an auth rule" a.message) config.assertions; @@ -91,4 +130,13 @@ assert builtins.elem "d /var/lib/syauth 0700 ${user} users -" enabled.systemd.tm assert lib.all hasRule services; assert pamFailures enabled == [ ] && builtins.length (pamFailures textOverride) == 1; assert (pam override "sudo").rules.auth.syauth.control == "required"; +assert (pam override "sudo").rules.auth.syauth.args == [ socket ]; +assert lib.any (a: !a.assertion && lib.hasInfix "absolute socket=" a.message) unknownUid.assertions; +assert lib.any (a: !a.assertion && lib.hasInfix "absolute socket=" a.message) emptyArgs.assertions; +assert lib.any ( + a: !a.assertion && lib.hasInfix "absolute socket=" a.message +) relativeSocket.assertions; +assert lib.all ( + a: a.assertion || !(lib.hasInfix "absolute socket=" a.message) +) explicitSocket.assertions; pkgs.runCommand "syauth-nixos-module-check" { } "touch $out" diff --git a/nix/modules/nixos.nix b/nix/modules/nixos.nix index 6725b49..b6861db 100644 --- a/nix/modules/nixos.nix +++ b/nix/modules/nixos.nix @@ -10,6 +10,7 @@ let store = "/var/lib/syauth"; account = config.users.users.${cfg.desktopUser} or { }; pamModule = "${cfg.package}/lib/security/pam_syauth.so"; + desktopUid = account.uid or null; anchorOrder = name: @@ -75,7 +76,10 @@ in moduleArgs = lib.mkOption { type = lib.types.listOf lib.types.str; - default = [ ]; + default = lib.optional ( + desktopUid != null + ) "socket=/run/user/${toString desktopUid}/syauth/auth.sock"; + defaultText = lib.literalExpression ''[ "socket=/run/user//syauth/auth.sock" ] when the UID is declared, otherwise [ ]''; example = [ "socket=/run/user/1000/syauth/auth.sock" ]; description = "Arguments passed to pam_syauth.so in each selected service."; }; @@ -88,6 +92,10 @@ in assertion = config.users.users ? ${cfg.desktopUser}; message = "services.syauth.desktopUser must name an account declared in users.users."; } + { + assertion = cfg.pam.services == [ ] || lib.any (lib.hasPrefix "socket=/") cfg.pam.moduleArgs; + message = "services.syauth.pam.moduleArgs requires an absolute socket= path when PAM is enabled. Declare users.users..uid or set pam.moduleArgs explicitly."; + } ] ++ map (name: { assertion = hasSyauthRule config.security.pam.services.${name}.text; diff --git a/nix/tests/fixture.py b/nix/tests/fixture.py new file mode 100644 index 0000000..918ceda --- /dev/null +++ b/nix/tests/fixture.py @@ -0,0 +1,26 @@ +# Deterministic public signing fixture for the disposable NixOS guest. +import json, os +from pathlib import Path +import blake3 +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +key = Ed25519PrivateKey.from_private_bytes(bytes(range(1, 33))) +pub = key.public_key().public_bytes_raw() +peer = blake3.blake3(pub).digest()[:16].hex() +nonce = bytes.fromhex("a7" * 16) +signature = key.sign(b"\x01" + nonce).hex() +root = Path('/var/lib/syauth') +(root / 'keys').mkdir(exist_ok=True, mode=0o700) +(root / 'bonds.toml').write_text(f'''schema_version = 1 +[[bond]] +peer_id = "{peer}" +pubkey = "{pub.hex()}" +name = "vm-synthetic-phone" +created_at = "1970-01-01T00:00:00Z" +[bond.status] +kind = "Bonded" +''') +(root / 'keys' / (peer + '.bin')).write_bytes(bytes([0xcc]) * 32) +for path in [root / 'keys', root / 'bonds.toml', root / 'keys' / (peer + '.bin')]: + os.chown(path, 1100, 100) + os.chmod(path, 0o700 if path.is_dir() else 0o600) +Path('/root/fixture.json').write_text(json.dumps(dict(peer=peer, nonce=nonce.hex(), signature=signature))) diff --git a/nix/tests/installation.nix b/nix/tests/installation.nix new file mode 100644 index 0000000..6c6e3d8 --- /dev/null +++ b/nix/tests/installation.nix @@ -0,0 +1,74 @@ +# Journey: specs/journeys/JOURNEY-S-023-nix-modules.md +{ + pkgs, + module, + package, +}: +let + python = pkgs.python3.withPackages (p: [ + p.cryptography + p.blake3 + ]); + fixture = pkgs.writeText "syauth-vm-fixture.py" (builtins.readFile ./fixture.py); +in +pkgs.testers.runNixOSTest { + name = "syauth-installation-and-policy"; + nodes.machine = { lib, ... }: { + imports = [ module ]; + system.stateVersion = "25.11"; + virtualisation = { + memorySize = 2048; + cores = 2; + diskSize = 6144; + writableStore = true; + }; + nix.settings.experimental-features = [ + "nix-command" + "flakes" + ]; + hardware.bluetooth.enable = true; + users.users.alice = { + isNormalUser = true; + uid = 1100; + extraGroups = [ "wheel" ]; + password = "vm-alice-test"; + }; + users.users.bob = { + isNormalUser = true; + uid = 1101; + password = "vm-bob-test"; + }; + security.sudo = { + enable = true; + wheelNeedsPassword = true; + }; + security.sudo-rs.enable = false; + environment.systemPackages = [ python ]; + services.syauth = { + enable = true; + desktopUser = "alice"; + inherit package; + pam.services = [ + "sudo" + "sudo-i" + ]; + }; + specialisation = { + noPam.configuration.services.syauth.pam.services = lib.mkForce [ ]; + disabled.configuration.services.syauth.enable = lib.mkForce false; + explicitArgs.configuration.services.syauth.pam.moduleArgs = lib.mkForce [ + "socket=/run/user/1100/syauth/auth.sock" + ]; + required.configuration.services.syauth.pam.control = lib.mkForce "required"; + sudoRs.configuration = { + security.sudo.enable = lib.mkForce false; + security.sudo-rs.enable = lib.mkForce true; + }; + }; + }; + testScript = + builtins.replaceStrings + [ "@syauth@" "@python@" "@fixture@" "@version@" ] + [ "${package}" "${python}" "${fixture}" package.version ] + (builtins.readFile ./installation.py); +} diff --git a/nix/tests/installation.py b/nix/tests/installation.py new file mode 100644 index 0000000..9b0a64c --- /dev/null +++ b/nix/tests/installation.py @@ -0,0 +1,114 @@ +# Regression: test installed PAM and daemon together in a disposable VM. +import json, shlex +start_all() +machine.wait_for_unit("multi-user.target") +base = machine.succeed("readlink -f /run/current-system").strip() +package = "@syauth@" +def alice(command, ok=True): + run = "su - alice -c " + shlex.quote(command) + return (machine.succeed if ok else machine.fail)(run) +def bob(command, ok=True): + run = "su - bob -c " + shlex.quote(command) + return (machine.succeed if ok else machine.fail)(run) +def sudo(password, ok=True): + return alice("printf '%s\\n' " + shlex.quote(password) + " | sudo -k -S -p '' true", ok) +def switch(name=None): + path = base if name is None else base + "/specialisation/" + name + machine.succeed(path + "/bin/switch-to-configuration test") +def userctl(command, ok=True): + return alice("XDG_RUNTIME_DIR=/run/user/1100 systemctl --user " + command, ok) +def ready(): + machine.wait_until_succeeds("su - alice -c 'XDG_RUNTIME_DIR=/run/user/1100 syauth status --json' | grep -q '\"transport_ready\": true'", timeout=60) +with subtest("installed binaries and PAM loader closure"): + assert machine.succeed("syauth --version").strip() == "syauth @version@" + machine.succeed(package + "/bin/syauth-presenced --help | grep -- --socket") + machine.succeed("ldd " + package + "/lib/security/pam_syauth.so | tee /root/pam-loader.txt; ! grep -q 'not found' /root/pam-loader.txt") + machine.succeed("test -f " + package + "/lib/security/pam_syauth.so") + machine.succeed("grep -F 'auth sufficient " + package + "/lib/security/pam_syauth.so socket=/run/user/1100/syauth/auth.sock' /etc/pam.d/sudo") +with subtest("private storage and per-user service isolation"): + assert machine.succeed("stat -c '%a %U %G' /var/lib/syauth").strip() == "700 alice users" + machine.succeed("loginctl enable-linger alice; loginctl enable-linger bob") + machine.wait_for_unit("user@1100.service") + machine.wait_for_unit("user@1101.service") + assert userctl("show syauth-presenced -p StartLimitIntervalUSec --value").strip() == "0" + machine.wait_until_succeeds("test $(su - alice -c 'XDG_RUNTIME_DIR=/run/user/1100 systemctl --user show syauth-presenced -p NRestarts --value') -ge 3", timeout=60) + machine.succeed("journalctl _UID=1100 --no-pager | grep -q 'Bluetooth transport unavailable'") + assert bob("XDG_RUNTIME_DIR=/run/user/1101 systemctl --user show syauth-presenced -p ConditionResult --value").strip() == "no" + assert bob("XDG_RUNTIME_DIR=/run/user/1101 systemctl --user show syauth-presenced -p MainPID --value").strip() == "0" + bob("test -r /var/lib/syauth/bonds.toml", False) +with subtest("missing phone still requires a valid Unix password"): + sudo("wrong-password", False) + sudo("vm-alice-test") + assert machine.succeed("stat -c '%a %U %G' /var/lib/syauth/last.log").strip() == "600 alice users" +with subtest("synthetic signed response traverses real daemon and installed PAM"): + userctl("stop syauth-presenced") + machine.succeed("@python@/bin/python @fixture@") + data = json.loads(machine.succeed("cat /root/fixture.json")) + daemon = package + "/bin/syauth-presenced --peripheral fake --test-fixed-nonce " + data["nonce"] + " --inject-response " + data["peer"] + ":" + data["signature"] + def inject(command): + unit = "[Service]\\nExecStart=\\nExecStart=" + command + "\\n" + alice("mkdir -p ~/.config/systemd/user/syauth-presenced.service.d; printf '%b' " + shlex.quote(unit) + " > ~/.config/systemd/user/syauth-presenced.service.d/vm-fixture.conf") + userctl("daemon-reload") + userctl("restart syauth-presenced") + ready() + inject(daemon) + sudo("wrong-password") + machine.succeed("grep -q ',ok,' /var/lib/syauth/last.log") + assert machine.succeed("stat -c '%a %U %G' /var/lib/syauth/last.log").strip() == "600 alice users" + machine.fail("journalctl _UID=1100 --no-pager | grep -q 'audit log open failed'") + assert json.loads(alice("XDG_RUNTIME_DIR=/run/user/1100 syauth status --json"))["daemon"]["transport_ready"] is True + bob("cat /var/lib/syauth/bonds.toml", False) + bob("cat /var/lib/syauth/keys/" + data["peer"] + ".bin", False) +with subtest("bad signature is rejected before password fallback"): + inject(package + "/bin/syauth-presenced --peripheral fake --test-fixed-nonce " + data["nonce"] + " --inject-response " + data["peer"] + ":" + "00" * 64) + sudo("wrong-password", False) + machine.succeed("grep -q 'bad-signature' /var/lib/syauth/last.log") + sudo("vm-alice-test") +with subtest("explicit socket override and automatic default both authenticate"): + inject(daemon) + switch("explicitArgs") + ready() + sudo("wrong-password") + switch() + userctl("restart syauth-presenced") + ready() + sudo("wrong-password") +with subtest("required control retains failure despite a correct password"): + userctl("stop syauth-presenced") + switch("required") + userctl("stop syauth-presenced") + machine.succeed("grep -F 'auth required ' /etc/pam.d/sudo | grep pam_syauth") + sudo("vm-alice-test", False) + switch() +with subtest("sudo-rs consumes the generated PAM rules"): + switch("sudoRs") + userctl("stop syauth-presenced") + sudo("wrong-password", False) + sudo("vm-alice-test") + switch() +with subtest("profile install and removal is independent of module activation"): + bob("nix profile install " + package) + assert bob("~/.nix-profile/bin/syauth --version").strip() == "syauth @version@" + bob("test -f ~/.nix-profile/lib/security/pam_syauth.so") + profile = json.loads(bob("nix profile list --json")) + entry = next(iter(profile["elements"])) + bob("nix profile remove " + shlex.quote(entry)) + bob("test -e ~/.nix-profile/bin/syauth", False) +with subtest("disable and rollback preserve the existing bond store"): + alice("rm ~/.config/systemd/user/syauth-presenced.service.d/vm-fixture.conf") + userctl("daemon-reload") + before = machine.succeed("find /var/lib/syauth -type f -exec sha256sum {} + | sort") + switch("noPam") + machine.fail("grep -q pam_syauth /etc/pam.d/sudo") + sudo("vm-alice-test") + switch("disabled") + machine.fail("command -v syauth") + machine.fail("grep -q pam_syauth /etc/pam.d/sudo") + assert machine.succeed("find /var/lib/syauth -type f -exec sha256sum {} + | sort") == before + switch() + machine.succeed("command -v syauth") + assert machine.succeed("stat -c '%a %U %G' /var/lib/syauth").strip() == "700 alice users" + assert machine.succeed("find /var/lib/syauth -type f -exec sha256sum {} + | sort") == before +machine.succeed("journalctl --no-pager > /root/syauth-vm-journal.txt") + +print("SYAUTH_NIXOS_VM_CHECKS_PASSED") diff --git a/specs/bugs/BUG-20261108-nix-pam-socket.md b/specs/bugs/BUG-20261108-nix-pam-socket.md new file mode 100644 index 0000000..4910867 --- /dev/null +++ b/specs/bugs/BUG-20261108-nix-pam-socket.md @@ -0,0 +1,52 @@ +# BUG-20261108-nix-pam-socket: PAM rules do not infer the desktop socket + +## Summary + +Enabling a NixOS PAM service without module arguments cannot reach the daemon +selected by `desktopUser` when root-run sudo has no desktop runtime environment. + +## Reproduction + +- Isolated NixOS KVM guest, PR #7 head `41c262e`, desktop account UID 1100. +- Start the real installed daemon with a valid synthetic signature queued. +- Enable sudo with empty `pam.moduleArgs`: PAM reports `reason=transport-error`. +- Restore `socket=/run/user/1100/syauth/auth.sock`: authentication succeeds. +- Evaluation regression: default rule arguments were `[]`, not the expected + desktop user's socket argument (`nix/check.nix`). + +## Expected Behavior + +Selecting a desktop user with a declared UID and enabling PAM generates a +working socket argument. Without a declared UID, configuration requires an +explicit absolute socket. Explicit overrides remain available. + +## Actual Behavior + +The default argument list is empty. PAM's environment/EUID-based resolver does +not infer the module's selected desktop account and silently falls back to the +service's other authentication rules. + +## Root Cause Analysis + +The NixOS adapter knows `desktopUser` but does not communicate its runtime +socket to PAM. A root caller's effective UID points at `/run/user/0`, independent +of the account running the desktop daemon. + +## Fix + +Generate the socket from the configured UID and assert an absolute socket +argument when any PAM service is selected. Keep opt-in services and the existing +control policy. Add a booted installation regression to flake checks and CI. + +## Stressors + +Non-default UID; auto-allocated UID; missing desktop environment; root caller; +explicit socket override; empty override; no PAM services; required control; +daemon starts after PAM; invalid signature; second account; disable/rollback. + +## Traceability + +- Evaluation: `nix/check.nix`. +- Integrated runtime: `nix/tests/installation.nix`, `installation.py`, `fixture.py`. +- Implementation: `nix/modules/nixos.nix`. +- CI: `.github/workflows/ci.yml`. diff --git a/specs/journeys/JOURNEY-S-023-nix-modules.md b/specs/journeys/JOURNEY-S-023-nix-modules.md index 7fe1a47..29d7e7c 100644 --- a/specs/journeys/JOURNEY-S-023-nix-modules.md +++ b/specs/journeys/JOURNEY-S-023-nix-modules.md @@ -31,6 +31,15 @@ directory ownership, inert PAM defaults, and rules for the sudo-rs and Plasma services. It checks that an explicit PAM control reaches the generated rule. The Rust workspace still exercises the daemon binary against a fake radio. +The booted `nix/tests/installation.nix` check additionally loads the installed +PAM library through sudo and exercises the real daemon/socket with public +synthetic Ed25519 responses. It verifies PAM-first audit ownership without a +manual repair, generated socket arguments for UID 1100, explicit overrides, +signature rejection, password fallback, account isolation, sudo-rs, profile +installation/removal, and data preservation across disable/rollback. CI runs +this VM alongside the package and module checks. Evaluation checks reject +unknown UIDs without an explicit socket and reject an explicitly empty list. + ## Implementation - `nix/modules/nixos.nix` declares the installation, user service and PAM rules. diff --git a/specs/syauth/ROADMAP.md b/specs/syauth/ROADMAP.md index 057b97d..562b5a3 100644 --- a/specs/syauth/ROADMAP.md +++ b/specs/syauth/ROADMAP.md @@ -1048,7 +1048,9 @@ sets up the CLI, private store, systemd user unit, and selected PAM rules. includes the flake input, module import, and settings. [Journey S-023](../journeys/JOURNEY-S-023-nix-modules.md) · -[Module](../../nix/modules/nixos.nix) · [Check](../../nix/check.nix) +[Module](../../nix/modules/nixos.nix) · [Check](../../nix/check.nix) · +[Socket regression](../bugs/BUG-20261108-nix-pam-socket.md) · +[Installed-PAM VM](../../nix/tests/installation.nix) Verified by flake checks on x86-64 and by evaluation on ARM64. The module check covers the generated sudo-rs and Plasma PAM rules, and the rendered