nix: build the module on the generated options

settings mirrors headscale's keys one to one, headscale's checks judge the
rest, and the local CLI gets the socket from a variable instead of a file.

headscale always runs as headscale:headscale, which the module creates;
user and group are read-only, so setting either fails evaluation, and stay
only because nixpkgs' headplane module reads them. A settings.cli key
fails evaluation instead of being dropped with a warning, and the unit no
longer gets CAP_CHOWN.
nix/example-configuration.nix goes: the options carry its examples and
defaults.

Updates #1926
This commit is contained in:
Kristoffer Dalby committed 2026-11-11 12:19:29 +01:00
1 parent bff13ee823
commit 7e0e423fbf
17 files changed
+1175 -949

No files matched your search

+9
View File
@@ -73,3 +73,12 @@ jobs:
- uses: Mic92/hestia@dfed9ced335d28978ba74e513939a10db1f71025 # v3.1.0
- name: nixos-options
run: nix build -L .#checks.x86_64-linux.nixos-options
nixos-module:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: NixOS/nix-installer-action@62c1943b776c509394b550f3f983adc14e9212d6 # main
- uses: Mic92/hestia@dfed9ced335d28978ba74e513939a10db1f71025 # v3.1.0
- name: nixos-module
run: nix build -L .#checks.x86_64-linux.nixos-module
+4
View File
@@ -359,6 +359,10 @@ a broken one.
- **Do not edit `gen/`** — it is regenerated from `proto/` by
`make generate`.
- **Proto changes + code changes should be two commits**, not one.
- **`services.headscale.settings` options come only from
`nix/options.generated.nix`**, generated from `hscontrol/types/config.go`
by `go generate ./hscontrol/types/`. Never declare one in `nix/module.nix`:
the module only sets values, below `lib.mkDefault`.
- **Do not edit the generated config files** —
`hscontrol/types/config_docs_generated.go`, `nix/options.generated.nix`,
`docs/ref/configuration-options.md` and `docs/ref/config-example.yaml`
+3 -3
View File
@@ -484,9 +484,9 @@ func TestLoadConfig(t *testing.T) {
}
}
// TestCLIOnlyConfig: a file with only what client commands read, as the
// NixOS module writes to /etc/headscale/config.yaml, serves them; check
// config reports what the server lacks.
// TestCLIOnlyConfig: a file with only what client commands read, such as
// ~/.config/headscale/config.yaml, serves them; check config reports what
// the server lacks.
func TestCLIOnlyConfig(t *testing.T) {
path := writeFile(t, t.TempDir(), "config.yaml", `cli:
address: headscale.example.com:443
+1
View File
@@ -434,6 +434,7 @@
// {
headscale = pkgs.testers.runNixOSTest (import ./nix/tests/headscale.nix self);
headscale-checks = pkgs.testers.runNixOSTest (import ./nix/tests/checks.nix self);
nixos-module = import ./nix/tests/module.nix self pkgs;
inherit nixos-options;
}
);
+5 -3
View File
@@ -3043,13 +3043,15 @@ func unsetHeadscaleEnv(t *testing.T) {
//
// Sources: example-<tag>.yaml is `git show <tag>:config-example.yaml`;
// example-main.yaml is a frozen copy of main's root config-example.yaml;
// nixos-*.yaml are the files `nix build` writes for the flake module with
// nix/example-configuration.nix
// nixos-*.yaml are the files `nix build` wrote for the flake module with
// the since-deleted nix/example-configuration.nix
// (services.headscale.configFile, environment.etc."headscale/config.yaml") and
// for the nixpkgs module with only server_url, dns.base_domain and
// dns.nameservers.global set; nixos-module-minimal.yaml is the flake module's
// configFile with only those three set, before the module moved to the
// generated options; hsic-* mirror integration/hsic's
// generated options, and nixos-*-options.yaml the same two configFiles after
// it; nixos-module-cli.env is what that module exports for the local CLI;
// hsic-* mirror integration/hsic's
// MinimumConfigYAML and DefaultConfigEnv. <name>-strict is the same source
// as updated for the strict loader, <name>-pruned without the keys removed
// for having no effect.
+191
View File
@@ -0,0 +1,191 @@
{
"config": {
"ServerURL": "https://headscale.example.com",
"Addr": "0.0.0.0:8080",
"MetricsAddr": "",
"TrustedProxies": null,
"Node": {
"Expiry": 0,
"Ephemeral": {
"InactivityTimeout": 1800000000000
},
"Routes": {
"HA": {
"ProbeInterval": 10000000000,
"ProbeTimeout": 5000000000
}
}
},
"PreAuthKeys": {
"RevokedRetention": 604800000000000
},
"PrefixV4": "100.64.0.0/10",
"PrefixV6": "fd7a:115c:a1e0::/48",
"IPAllocation": "sequential",
"NoisePrivateKeyPath": "/var/lib/headscale/noise_private.key",
"BaseDomain": "tailnet.example.com",
"Log": {
"Format": "text",
"Level": "info"
},
"DisableUpdateCheck": true,
"Database": {
"Type": "sqlite3",
"Debug": false,
"Gorm": {
"Debug": false,
"SlowThreshold": 0,
"SkipErrRecordNotFound": false,
"ParameterizedQueries": false
},
"Sqlite": {
"Path": "/var/lib/headscale/db.sqlite",
"WriteAheadLog": true,
"WALAutoCheckPoint": 1000
},
"Postgres": {
"Host": "",
"Port": 0,
"Name": "",
"User": "",
"Ssl": "false",
"MaxOpenConnections": 10,
"MaxIdleConnections": 10,
"ConnMaxIdleTimeSecs": 3600
}
},
"DERP": {
"ServerEnabled": false,
"AutomaticallyAddEmbeddedDerpRegion": true,
"ServerRegionID": 0,
"ServerRegionCode": "",
"ServerRegionName": "",
"ServerPrivateKeyPath": "/var/lib/headscale/derp_server_private.key",
"ServerVerifyClients": true,
"STUNAddr": "",
"URLs": [
{
"Scheme": "https",
"Opaque": "",
"User": null,
"Host": "controlplane.tailscale.com",
"Path": "/derpmap/default",
"Fragment": "",
"RawQuery": "",
"RawPath": "",
"RawFragment": "",
"ForceQuery": false,
"OmitHost": false
}
],
"Paths": [],
"DERPMap": null,
"AutoUpdate": true,
"UpdateFrequency": 86400000000000,
"IPv4": "",
"IPv6": ""
},
"TLS": {
"CertPath": "",
"KeyPath": "",
"ACME": {
"Hostname": "",
"ChallengeType": "HTTP-01",
"HTTPListen": ":http",
"URL": "",
"Email": "",
"CacheDir": "/var/lib/headscale/cache"
}
},
"DNSConfig": {
"MagicDNS": true,
"BaseDomain": "tailnet.example.com",
"OverrideLocalDNS": true,
"Nameservers": {
"Global": [
"1.1.1.1",
"8.8.8.8"
],
"Split": {}
},
"SearchDomains": [],
"ExtraRecords": [],
"ExtraRecordsPath": "",
"Certificates": {
"Enabled": false,
"Zone": "tailnet.example.com"
}
},
"TailcfgDNSConfig": {
"Resolvers": [
{
"Addr": "1.1.1.1"
},
{
"Addr": "8.8.8.8"
}
],
"Domains": [
"tailnet.example.com"
],
"Proxied": true
},
"DNSChallenge": {
"PropagationTimeout": 120000000000,
"Resolvers": [
"1.1.1.1:53",
"8.8.8.8:53"
],
"ProviderName": ""
},
"UnixSocket": "/run/headscale/headscale.sock",
"UnixSocketPermission": 504,
"OIDC": {
"OnlyStartIfOIDCIsAvailable": true,
"Issuer": "",
"ClientID": "",
"Scope": [
"openid",
"profile",
"email"
],
"ExtraParams": {},
"AllowedDomains": [],
"AllowedUsers": [],
"AllowedGroups": [],
"EmailVerifiedRequired": true,
"UseExpiryFromToken": false,
"PKCE": {
"Enabled": false,
"Method": "S256"
}
},
"LogTail": {
"Enabled": false
},
"Taildrop": {
"Enabled": true
},
"AutoUpdate": {
"Enabled": false
},
"CLI": {
"Address": "",
"Timeout": 5000000000,
"Insecure": false
},
"Policy": {
"Path": "/var/lib/headscale/policy.hujson",
"Mode": "file"
},
"Tuning": {
"BatchChangeDelay": 800000000,
"NodeMapSessionBufferedChanSize": 30,
"BatcherWorkers": 0,
"RegisterCacheExpiration": 900000000000,
"RegisterCacheMaxEntries": 1024,
"NodeStoreBatchSize": 100,
"NodeStoreBatchTimeout": 500000000
}
}
}
@@ -0,0 +1,132 @@
%YAML 1.1
---
auto_update:
enabled: false
database:
debug: false
gorm:
parameterized_queries: false
skip_err_record_not_found: false
slow_threshold: 0
postgres:
conn_max_idle_time_secs: 3600
host: ''
max_idle_conns: 10
max_open_conns: 10
name: ''
pass: ''
port: 0
ssl: 'false'
user: ''
sqlite:
path: /var/lib/headscale/db.sqlite
wal_autocheckpoint: 1000
write_ahead_log: true
type: sqlite
derp:
auto_update_enabled: true
paths: []
server:
automatically_add_embedded_derp_region: true
enabled: false
ipv4: ''
ipv6: ''
private_key_path: /var/lib/headscale/derp_server_private.key
region_code: ''
region_id: 0
region_name: ''
stun_listen_addr: ''
verify_clients: true
update_frequency: 24h
urls:
- https://controlplane.tailscale.com/derpmap/default
disable_check_updates: true
dns:
base_domain: tailnet.example.com
certificates:
enabled: false
zone: ''
challenge:
propagation_timeout: 2m
provider: {}
resolvers:
- 1.1.1.1:53
- 8.8.8.8:53
extra_records: []
extra_records_path: ''
magic_dns: true
nameservers:
global:
- 1.1.1.1
- 8.8.8.8
split: {}
override_local_dns: true
search_domains: []
listen_addr: 0.0.0.0:8080
log:
format: text
level: info
logtail:
enabled: false
metrics_listen_addr: ''
node:
ephemeral:
inactivity_timeout: 30m
expiry: 0s
routes:
ha:
probe_interval: 10s
probe_timeout: 5s
noise:
private_key_path: /var/lib/headscale/noise_private.key
oidc:
allowed_domains: []
allowed_groups: []
allowed_users: []
client_id: ''
client_secret: ''
email_verified_required: true
extra_params: {}
issuer: ''
only_start_if_oidc_is_available: true
pkce:
enabled: false
method: S256
scope:
- openid
- profile
- email
use_expiry_from_token: false
policy:
mode: file
path: /var/lib/headscale/policy.hujson
preauth_keys:
revoked_retention: 168h
prefixes:
allocation: sequential
v4: 100.64.0.0/10
v6: fd7a:115c:a1e0::/48
server_url: https://headscale.example.com
taildrop:
enabled: true
tls:
acme:
cache_dir: /var/lib/headscale/cache
challenge_type: HTTP-01
email: ''
hostname: ''
http_listen: :http
url: ''
cert_path: ''
key_path: ''
trusted_proxies: []
tuning:
batch_change_delay: 800ms
batcher_workers: 0
node_mapsession_buffered_chan_size: 30
node_store_batch_size: 100
node_store_batch_timeout: 500ms
register_cache_expiration: 15m
register_cache_max_entries: 1024
unix_socket: /run/headscale/headscale.sock
unix_socket_permission: '0770'
+2
View File
@@ -0,0 +1,2 @@
HEADSCALE_UNIX_SOCKET=/run/headscale/headscale.sock
HEADSCALE_DISABLE_CHECK_UPDATES=true
+154
View File
@@ -0,0 +1,154 @@
{
"config": {
"ServerURL": "",
"Addr": "",
"MetricsAddr": "",
"TrustedProxies": null,
"Node": {
"Expiry": 0,
"Ephemeral": {
"InactivityTimeout": 0
},
"Routes": {
"HA": {
"ProbeInterval": 0,
"ProbeTimeout": 0
}
}
},
"PreAuthKeys": {
"RevokedRetention": 0
},
"PrefixV4": null,
"PrefixV6": null,
"IPAllocation": "",
"NoisePrivateKeyPath": "",
"BaseDomain": "",
"Log": {
"Format": "text",
"Level": "info"
},
"DisableUpdateCheck": true,
"Database": {
"Type": "",
"Debug": false,
"Gorm": {
"Debug": false,
"SlowThreshold": 0,
"SkipErrRecordNotFound": false,
"ParameterizedQueries": false
},
"Sqlite": {
"Path": "",
"WriteAheadLog": false,
"WALAutoCheckPoint": 0
},
"Postgres": {
"Host": "",
"Port": 0,
"Name": "",
"User": "",
"Ssl": "",
"MaxOpenConnections": 0,
"MaxIdleConnections": 0,
"ConnMaxIdleTimeSecs": 0
}
},
"DERP": {
"ServerEnabled": false,
"AutomaticallyAddEmbeddedDerpRegion": false,
"ServerRegionID": 0,
"ServerRegionCode": "",
"ServerRegionName": "",
"ServerPrivateKeyPath": "",
"ServerVerifyClients": false,
"STUNAddr": "",
"URLs": null,
"Paths": null,
"DERPMap": null,
"AutoUpdate": false,
"UpdateFrequency": 0,
"IPv4": "",
"IPv6": ""
},
"TLS": {
"CertPath": "",
"KeyPath": "",
"ACME": {
"Hostname": "",
"ChallengeType": "",
"HTTPListen": "",
"URL": "",
"Email": "",
"CacheDir": ""
}
},
"DNSConfig": {
"MagicDNS": false,
"BaseDomain": "",
"OverrideLocalDNS": false,
"Nameservers": {
"Global": null,
"Split": null
},
"SearchDomains": null,
"ExtraRecords": null,
"ExtraRecordsPath": "",
"Certificates": {
"Enabled": false,
"Zone": ""
}
},
"TailcfgDNSConfig": null,
"DNSChallenge": {
"PropagationTimeout": 0,
"Resolvers": null,
"ProviderName": ""
},
"UnixSocket": "/run/headscale/headscale.sock",
"UnixSocketPermission": 0,
"OIDC": {
"OnlyStartIfOIDCIsAvailable": false,
"Issuer": "",
"ClientID": "",
"Scope": null,
"ExtraParams": null,
"AllowedDomains": null,
"AllowedUsers": null,
"AllowedGroups": null,
"EmailVerifiedRequired": false,
"UseExpiryFromToken": false,
"PKCE": {
"Enabled": false,
"Method": ""
}
},
"LogTail": {
"Enabled": false
},
"Taildrop": {
"Enabled": false
},
"AutoUpdate": {
"Enabled": false
},
"CLI": {
"Address": "",
"Timeout": 5000000000,
"Insecure": false
},
"Policy": {
"Path": "",
"Mode": ""
},
"Tuning": {
"BatchChangeDelay": 0,
"NodeMapSessionBufferedChanSize": 0,
"BatcherWorkers": 0,
"RegisterCacheExpiration": 0,
"RegisterCacheMaxEntries": 0,
"NodeStoreBatchSize": 0,
"NodeStoreBatchTimeout": 0
}
}
}
@@ -0,0 +1,191 @@
{
"config": {
"ServerURL": "https://headscale.example.com",
"Addr": "127.0.0.1:8080",
"MetricsAddr": "",
"TrustedProxies": null,
"Node": {
"Expiry": 0,
"Ephemeral": {
"InactivityTimeout": 1800000000000
},
"Routes": {
"HA": {
"ProbeInterval": 10000000000,
"ProbeTimeout": 5000000000
}
}
},
"PreAuthKeys": {
"RevokedRetention": 604800000000000
},
"PrefixV4": "100.64.0.0/10",
"PrefixV6": "fd7a:115c:a1e0::/48",
"IPAllocation": "sequential",
"NoisePrivateKeyPath": "/var/lib/headscale/noise_private.key",
"BaseDomain": "tailnet.example.com",
"Log": {
"Format": "text",
"Level": "info"
},
"DisableUpdateCheck": true,
"Database": {
"Type": "sqlite3",
"Debug": false,
"Gorm": {
"Debug": false,
"SlowThreshold": 0,
"SkipErrRecordNotFound": false,
"ParameterizedQueries": false
},
"Sqlite": {
"Path": "/var/lib/headscale/db.sqlite",
"WriteAheadLog": true,
"WALAutoCheckPoint": 1000
},
"Postgres": {
"Host": "",
"Port": 0,
"Name": "",
"User": "",
"Ssl": "false",
"MaxOpenConnections": 10,
"MaxIdleConnections": 10,
"ConnMaxIdleTimeSecs": 3600
}
},
"DERP": {
"ServerEnabled": false,
"AutomaticallyAddEmbeddedDerpRegion": true,
"ServerRegionID": 0,
"ServerRegionCode": "",
"ServerRegionName": "",
"ServerPrivateKeyPath": "/var/lib/headscale/derp_server_private.key",
"ServerVerifyClients": true,
"STUNAddr": "",
"URLs": [
{
"Scheme": "https",
"Opaque": "",
"User": null,
"Host": "controlplane.tailscale.com",
"Path": "/derpmap/default",
"Fragment": "",
"RawQuery": "",
"RawPath": "",
"RawFragment": "",
"ForceQuery": false,
"OmitHost": false
}
],
"Paths": [],
"DERPMap": null,
"AutoUpdate": true,
"UpdateFrequency": 86400000000000,
"IPv4": "",
"IPv6": ""
},
"TLS": {
"CertPath": "",
"KeyPath": "",
"ACME": {
"Hostname": "",
"ChallengeType": "HTTP-01",
"HTTPListen": ":http",
"URL": "",
"Email": "",
"CacheDir": "/var/lib/headscale/cache"
}
},
"DNSConfig": {
"MagicDNS": true,
"BaseDomain": "tailnet.example.com",
"OverrideLocalDNS": true,
"Nameservers": {
"Global": [
"1.1.1.1",
"8.8.8.8"
],
"Split": {}
},
"SearchDomains": [],
"ExtraRecords": [],
"ExtraRecordsPath": "",
"Certificates": {
"Enabled": false,
"Zone": "tailnet.example.com"
}
},
"TailcfgDNSConfig": {
"Resolvers": [
{
"Addr": "1.1.1.1"
},
{
"Addr": "8.8.8.8"
}
],
"Domains": [
"tailnet.example.com"
],
"Proxied": true
},
"DNSChallenge": {
"PropagationTimeout": 120000000000,
"Resolvers": [
"1.1.1.1:53",
"8.8.8.8:53"
],
"ProviderName": ""
},
"UnixSocket": "/run/headscale/headscale.sock",
"UnixSocketPermission": 504,
"OIDC": {
"OnlyStartIfOIDCIsAvailable": true,
"Issuer": "",
"ClientID": "",
"Scope": [
"openid",
"profile",
"email"
],
"ExtraParams": {},
"AllowedDomains": [],
"AllowedUsers": [],
"AllowedGroups": [],
"EmailVerifiedRequired": true,
"UseExpiryFromToken": false,
"PKCE": {
"Enabled": false,
"Method": "S256"
}
},
"LogTail": {
"Enabled": false
},
"Taildrop": {
"Enabled": true
},
"AutoUpdate": {
"Enabled": false
},
"CLI": {
"Address": "",
"Timeout": 5000000000,
"Insecure": false
},
"Policy": {
"Path": "",
"Mode": "file"
},
"Tuning": {
"BatchChangeDelay": 800000000,
"NodeMapSessionBufferedChanSize": 30,
"BatcherWorkers": 0,
"RegisterCacheExpiration": 900000000000,
"RegisterCacheMaxEntries": 1024,
"NodeStoreBatchSize": 100,
"NodeStoreBatchTimeout": 500000000
}
}
}
@@ -0,0 +1,132 @@
%YAML 1.1
---
auto_update:
enabled: false
database:
debug: false
gorm:
parameterized_queries: false
skip_err_record_not_found: false
slow_threshold: 0
postgres:
conn_max_idle_time_secs: 3600
host: ''
max_idle_conns: 10
max_open_conns: 10
name: ''
pass: ''
port: 0
ssl: 'false'
user: ''
sqlite:
path: /var/lib/headscale/db.sqlite
wal_autocheckpoint: 1000
write_ahead_log: true
type: sqlite
derp:
auto_update_enabled: true
paths: []
server:
automatically_add_embedded_derp_region: true
enabled: false
ipv4: ''
ipv6: ''
private_key_path: /var/lib/headscale/derp_server_private.key
region_code: ''
region_id: 0
region_name: ''
stun_listen_addr: ''
verify_clients: true
update_frequency: 24h
urls:
- https://controlplane.tailscale.com/derpmap/default
disable_check_updates: true
dns:
base_domain: tailnet.example.com
certificates:
enabled: false
zone: ''
challenge:
propagation_timeout: 2m
provider: {}
resolvers:
- 1.1.1.1:53
- 8.8.8.8:53
extra_records: []
extra_records_path: ''
magic_dns: true
nameservers:
global:
- 1.1.1.1
- 8.8.8.8
split: {}
override_local_dns: true
search_domains: []
listen_addr: 127.0.0.1:8080
log:
format: text
level: info
logtail:
enabled: false
metrics_listen_addr: ''
node:
ephemeral:
inactivity_timeout: 30m
expiry: 0s
routes:
ha:
probe_interval: 10s
probe_timeout: 5s
noise:
private_key_path: /var/lib/headscale/noise_private.key
oidc:
allowed_domains: []
allowed_groups: []
allowed_users: []
client_id: ''
client_secret: ''
email_verified_required: true
extra_params: {}
issuer: ''
only_start_if_oidc_is_available: true
pkce:
enabled: false
method: S256
scope:
- openid
- profile
- email
use_expiry_from_token: false
policy:
mode: file
path: ''
preauth_keys:
revoked_retention: 168h
prefixes:
allocation: sequential
v4: 100.64.0.0/10
v6: fd7a:115c:a1e0::/48
server_url: https://headscale.example.com
taildrop:
enabled: true
tls:
acme:
cache_dir: /var/lib/headscale/cache
challenge_type: HTTP-01
email: ''
hostname: ''
http_listen: :http
url: ''
cert_path: ''
key_path: ''
trusted_proxies: []
tuning:
batch_change_delay: 800ms
batcher_workers: 0
node_mapsession_buffered_chan_size: 30
node_store_batch_size: 100
node_store_batch_timeout: 500ms
register_cache_expiration: 15m
register_cache_max_entries: 1024
unix_socket: /run/headscale/headscale.sock
unix_socket_permission: '0770'
-158
View File
@@ -1,158 +0,0 @@
# Example NixOS configuration using the headscale module
#
# This file demonstrates how to use the headscale NixOS module from this flake.
# To use in your own configuration, add this to your flake.nix inputs:
#
# inputs.headscale.url = "github:juanfont/headscale";
#
# Then import the module:
#
# imports = [ inputs.headscale.nixosModules.default ];
#
{ config, pkgs, ... }:
{
# Import the headscale module
# In a real configuration, this would come from the flake input
# imports = [ inputs.headscale.nixosModules.default ];
services.headscale = {
enable = true;
# Use this flake's headscale. The default, pkgs.headscale from nixpkgs,
# may predate settings this module writes, such as "file:" secrets.
# package = inputs.headscale.packages.${pkgs.stdenv.hostPlatform.system}.headscale;
# Listen on all interfaces (default is 127.0.0.1)
address = "0.0.0.0";
port = 8080;
settings = {
# The URL clients will connect to
server_url = "https://headscale.example.com";
# IP prefixes for the tailnet
# These use the freeform settings - you can set any headscale config option
prefixes = {
v4 = "100.64.0.0/10";
v6 = "fd7a:115c:a1e0::/48";
allocation = "sequential";
};
# DNS configuration with MagicDNS
dns = {
magic_dns = true;
base_domain = "tailnet.example.com";
# Whether to override client's local DNS settings (default: true)
# When true, nameservers.global must be set
override_local_dns = true;
nameservers = {
global = [
"1.1.1.1"
"8.8.8.8"
];
};
};
# DERP (relay) configuration
derp = {
# Use default Tailscale DERP servers
urls = [ "https://controlplane.tailscale.com/derpmap/default" ];
auto_update_enabled = true;
update_frequency = "24h";
# Optional: Run your own DERP server
# server = {
# enabled = true;
# region_id = 999;
# stun_listen_addr = "0.0.0.0:3478";
# };
};
# Database configuration (SQLite is recommended)
database = {
type = "sqlite";
sqlite = {
path = "/var/lib/headscale/db.sqlite";
write_ahead_log = true;
};
# PostgreSQL example (not recommended for new deployments)
# type = "postgres";
# postgres = {
# host = "localhost";
# port = 5432;
# name = "headscale";
# user = "headscale";
# pass = "file:\${CREDENTIALS_DIRECTORY}/db-password";
# };
};
# Logging configuration
log = {
level = "info";
format = "text";
};
# Optional: OIDC authentication
# oidc = {
# issuer = "https://accounts.google.com";
# client_id = "your-client-id";
# client_secret = "file:\${CREDENTIALS_DIRECTORY}/oidc-client-secret";
# scope = [ "openid" "profile" "email" ];
# allowed_domains = [ "example.com" ];
# };
# Optional: Let's Encrypt TLS certificates
# tls.acme = {
# hostname = "headscale.example.com";
# challenge_type = "HTTP-01";
# };
# Optional: Provide your own TLS certificates
# tls.cert_path = "/path/to/cert.pem";
# tls.key_path = "/path/to/key.pem";
# ACL policy configuration
policy = {
mode = "file";
path = "/var/lib/headscale/policy.hujson";
};
# You can add ANY headscale configuration option here thanks to freeform settings
# For example, experimental features or settings not explicitly defined above:
# experimental_feature = true;
# custom_setting = "value";
};
};
# Secrets: systemd copies each file into $CREDENTIALS_DIRECTORY, readable
# only by the service, and the settings above read it with "file:".
# systemd.services.headscale.serviceConfig.LoadCredential = [
# "db-password:/run/secrets/headscale-db-password"
# "oidc-client-secret:/run/secrets/oidc-client-secret"
# ];
# Optional: Open firewall ports
networking.firewall = {
allowedTCPPorts = [ 8080 ];
# If running a DERP server:
# allowedUDPPorts = [ 3478 ];
};
# Optional: Use with nginx reverse proxy for TLS termination
# services.nginx = {
# enable = true;
# virtualHosts."headscale.example.com" = {
# enableACME = true;
# forceSSL = true;
# locations."/" = {
# proxyPass = "http://127.0.0.1:8080";
# proxyWebsockets = true;
# };
# };
# };
}
+94 -757
View File
@@ -10,15 +10,7 @@ let
dataDir = "/var/lib/headscale";
runDir = "/run/headscale";
cliConfig = {
# Nix pins the package, so an update notice cannot be acted on.
disable_check_updates = true;
unix_socket = "${runDir}/headscale.sock";
};
settingsFormat = pkgs.formats.yaml { };
cliConfigFile = settingsFormat.generate "headscale.yaml" cliConfig;
# headscale reads a non-empty variable of the unit over the setting.
effective =
@@ -30,7 +22,7 @@ let
policyMode = effective "HEADSCALE_POLICY_MODE" cfg.settings.policy.mode;
policyPath = effective "HEADSCALE_POLICY_PATH" cfg.settings.policy.path;
# Interpolated as the config and the unit are, so a Nix path is the same store path.
policyFile = if policyMode == "file" && policyPath != null then "${policyPath}" else null;
policyFile = if policyMode == "file" && policyPath != "" then "${policyPath}" else null;
policyFileCheck = cfg.check.policy && policyFile != null;
# The build can read a store path, and must be able to run the binary.
buildTimePolicy =
@@ -47,27 +39,22 @@ let
# Its own script, for shellcheck and runtimeInputs.
preSwitchCheck =
let
user = lib.escapeShellArg cfg.user;
group = lib.escapeShellArg cfg.group;
# systemd gives the unit Group= and the account's /etc/group memberships.
# Activation rewrites a declared account's memberships in the groups
# NixOS declares (members holds extraGroups), so those come from the new
# configuration. It keeps the rest: an undeclared account's, and with
# mutableUsers a hand-made group.
managed = config.users.users ? ${cfg.user};
# Activation rewrites the account's memberships in the groups NixOS
# declares (members holds extraGroups), so those come from the new
# configuration. With mutableUsers it keeps a hand-made group.
groups = [
cfg.group
"headscale"
]
++ lib.optionals managed (
map (g: g.name) (lib.filter (g: lib.elem cfg.user g.members) (lib.attrValues config.users.groups))
++ map (g: g.name) (
lib.filter (g: lib.elem "headscale" g.members) (lib.attrValues config.users.groups)
)
++ lib.filter (g: g != "") (
lib.concatMap (g: lib.splitString " " (toString g)) (
lib.toList (config.systemd.services.headscale.serviceConfig.SupplementaryGroups or [ ])
)
);
keepCurrent = !managed || config.users.mutableUsers;
declared = lib.optionals managed (map (g: g.name) (lib.attrValues config.users.groups));
declared = map (g: g.name) (lib.attrValues config.users.groups);
unitEnv = lib.mapAttrsToList (n: v: "${n}=${toString v}") (
lib.filterAttrs (_: v: v != null) config.systemd.services.headscale.environment
);
@@ -87,23 +74,23 @@ let
exit 0
fi
# Activation creates users and groups after this check runs.
if ! id -u ${user} >/dev/null 2>&1; then
echo "headscale: user" ${user} "does not exist yet, skipping checks"
if ! id -u headscale >/dev/null 2>&1; then
echo "headscale: user headscale does not exist yet, skipping checks"
exit 0
fi
if ! getent group ${group} >/dev/null; then
echo "headscale: group" ${group} "does not exist yet, skipping checks"
if ! getent group headscale >/dev/null; then
echo "headscale: group headscale does not exist yet, skipping checks"
exit 0
fi
trap '[ "$?" = 0 ] || echo "headscale: to skip, set services.headscale.check.config and check.policy to false, or run once with NIXOS_NO_CHECK=1"' EXIT
# A group this switch creates does not exist yet; setpriv would fail on it.
want=(${lib.escapeShellArgs groups})
${lib.optionalString keepCurrent ''
${lib.optionalString config.users.mutableUsers ''
# Not the account's primary group, which the unit does not get, nor a
# group NixOS declares now, or declared before and activation removes.
skip=" $(id -gn ${user} 2>/dev/null || true) "${lib.escapeShellArg (toString declared)}" ${lib.optionalString managed "$(cat /var/lib/nixos/declarative-groups 2>/dev/null || true)"} "
for g in $(id -Gn ${user}); do
skip=" $(id -gn headscale 2>/dev/null || true) "${lib.escapeShellArg (toString declared)}" $(cat /var/lib/nixos/declarative-groups 2>/dev/null || true) "
for g in $(id -Gn headscale); do
[[ $skip == *" $g "* ]] || want+=("$g")
done
''}
@@ -115,7 +102,7 @@ let
# As the unit's user and groups, with the unit's environment rather than the caller's.
hs() {
setpriv --reuid=${user} --regid=${group} --groups="$grouplist" -- \
setpriv --reuid=headscale --regid=headscale --groups="$grouplist" -- \
env -i ${lib.escapeShellArgs unitEnv} ${lib.getExe cfg.package} "$@"
}
@@ -130,11 +117,26 @@ let
'';
};
assertRemovedOption = option: message: {
assertion = !lib.hasAttrByPath option cfg;
message =
"The option `services.headscale.${lib.options.showOption option}` was removed. " + message;
};
# The option's type admits a number or http/https as the port, or an empty
# listen_addr, which grants nothing. Past four digits a port is never
# privileged, and the cap keeps toIntBase10 from throwing on a number too
# long for an integer.
listenPort = lib.last (lib.splitString ":" cfg.settings.listen_addr);
listenDigits = builtins.match "0*([0-9]{1,4})" listenPort;
privilegedPort =
lib.elem listenPort [
"http"
"https"
]
|| (listenDigits != null && lib.toIntBase10 (lib.head listenDigits) < 1024);
# Below lib.mkDefault, so a user's own mkDefault replaces these values
# instead of conflicting with a scalar or merging into a list.
distroDefault = lib.mkOverride 1200;
# Go reads cli, nested or dotted, as the client-only cli.*; written to the
# config, cli.api_key would land in the world-readable store.
cliKeys = lib.filter (n: n == "cli" || lib.hasPrefix "cli." n) (lib.attrNames cfg.settings);
in
{
# Disable the upstream NixOS module to prevent conflicts
@@ -150,9 +152,10 @@ in
type = lib.types.path;
readOnly = true;
default = settingsFormat.generate "headscale.yaml" cfg.settings;
defaultText = lib.literalExpression ''(pkgs.formats.yaml { }).generate "headscale.yaml" config.services.headscale.settings'';
defaultText = lib.literalMD "{option}`services.headscale.settings` as YAML";
description = ''
Path to the configuration file of headscale.
Path to the configuration file of headscale:
{option}`services.headscale.settings` as YAML.
'';
};
@@ -164,8 +167,7 @@ in
`headscale check all` on the new configuration and abort the switch
if it fails. It checks the configuration and every file it names
(policy, DERP maps, extra records, TLS pair, existing noise and DERP
keys) as {option}`services.headscale.user`. Keys are read, never
created.
keys) as the `headscale` user. Keys are read, never created.
It runs outside the unit, and only when headscale's unit changes.
It never reads a `file:` secret, so credentials referenced with
@@ -190,756 +192,89 @@ in
'';
};
# Read-only, kept only because nixpkgs' headplane module reads them.
user = lib.mkOption {
default = "headscale";
type = lib.types.str;
description = ''
User account under which headscale runs.
::: {.note}
If left as the default value this user will automatically be created
on system activation, otherwise you are responsible for
ensuring the user exists before the headscale service starts.
:::
'';
default = "headscale";
readOnly = true;
description = "User account under which headscale runs, created by this module.";
};
group = lib.mkOption {
type = lib.types.str;
default = "headscale";
type = lib.types.str;
description = ''
Group under which headscale runs.
::: {.note}
If left as the default value this group will automatically be created
on system activation, otherwise you are responsible for
ensuring the user exists before the headscale service starts.
:::
'';
};
address = lib.mkOption {
type = lib.types.str;
default = "127.0.0.1";
description = ''
Listening address of headscale.
'';
example = "0.0.0.0";
};
port = lib.mkOption {
type = lib.types.port;
default = 8080;
description = ''
Listening port of headscale.
'';
example = 443;
readOnly = true;
description = "Group under which headscale runs, created by this module.";
};
settings = lib.mkOption {
description = ''
Overrides to {file}`config.yaml` as a Nix attribute set.
See [Configuration options](https://headscale.net/stable/ref/configuration-options/)
for every key.
headscale's configuration, written to
{option}`services.headscale.configFile`. Each option is one key of
[Configuration options](https://headscale.net/stable/ref/configuration-options/).
A key without an option passes through to headscale, which rejects
unknown keys.
'';
type = lib.types.submodule {
freeformType = settingsFormat.type;
options = {
server_url = lib.mkOption {
type = lib.types.str;
default = "http://127.0.0.1:8080";
description = ''
The url clients will connect to.
'';
example = "https://myheadscale.example.com:443";
};
noise.private_key_path = lib.mkOption {
type = lib.types.path;
default = "${dataDir}/noise_private.key";
description = ''
Path to noise private key file, generated automatically if it does not exist.
'';
};
prefixes =
let
prefDesc = ''
Each prefix consists of either an IPv4 or IPv6 address,
and the associated prefix length, delimited by a slash.
It must be within IP ranges supported by the Tailscale
client - i.e., subnets of 100.64.0.0/10 and fd7a:115c:a1e0::/48.
'';
in
{
v4 = lib.mkOption {
type = lib.types.str;
default = "100.64.0.0/10";
description = prefDesc;
};
v6 = lib.mkOption {
type = lib.types.str;
default = "fd7a:115c:a1e0::/48";
description = prefDesc;
};
allocation = lib.mkOption {
type = lib.types.enum [
"sequential"
"random"
];
example = "random";
default = "sequential";
description = ''
Strategy used for allocation of IPs to nodes, available options:
- sequential (default): assigns the next free IP from the previous given IP.
- random: assigns the next free IP from a pseudo-random IP generator (crypto/rand).
'';
};
};
derp = {
urls = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ "https://controlplane.tailscale.com/derpmap/default" ];
description = ''
List of urls containing DERP maps.
See [How Tailscale works](https://tailscale.com/blog/how-tailscale-works/) for more information on DERP maps.
'';
};
paths = lib.mkOption {
type = lib.types.listOf lib.types.path;
default = [ ];
description = ''
List of file paths containing DERP maps.
See [How Tailscale works](https://tailscale.com/blog/how-tailscale-works/) for more information on DERP maps.
'';
};
auto_update_enabled = lib.mkOption {
type = lib.types.bool;
default = true;
description = ''
Whether to automatically update DERP maps on a set frequency.
'';
example = false;
};
update_frequency = lib.mkOption {
type = lib.types.str;
default = "24h";
description = ''
Frequency to update DERP maps.
'';
example = "5m";
};
server.private_key_path = lib.mkOption {
type = lib.types.path;
default = "${dataDir}/derp_server_private.key";
description = ''
Path to derp private key file, generated automatically if it does not exist.
'';
};
};
node = {
expiry = lib.mkOption {
type = lib.types.str;
default = "0";
description = ''
Default key expiry for non-tagged nodes, regardless of
registration method (auth key, CLI, web auth, OIDC).
Tagged nodes are exempt and never expire. Set to "0"
for no default expiry.
'';
example = "90d";
};
ephemeral = {
inactivity_timeout = lib.mkOption {
type = lib.types.str;
default = "30m";
description = ''
Time before an inactive ephemeral node is deleted.
'';
example = "5m";
};
};
};
database = {
type = lib.mkOption {
type = lib.types.enum [
"sqlite"
"sqlite3"
"postgres"
];
example = "postgres";
default = "sqlite";
description = ''
Database engine to use.
Please note that using Postgres is highly discouraged as it is only supported for legacy reasons.
All new development, testing and optimisations are done with SQLite in mind.
'';
};
sqlite = {
path = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = "${dataDir}/db.sqlite";
description = "Path to the sqlite3 database file.";
};
write_ahead_log = lib.mkOption {
type = lib.types.bool;
default = true;
description = ''
Enable WAL mode for SQLite. This is recommended for production environments.
<https://www.sqlite.org/wal.html>
'';
example = true;
};
};
postgres = {
host = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
example = "127.0.0.1";
description = "Database host address.";
};
port = lib.mkOption {
type = lib.types.nullOr lib.types.port;
default = null;
example = 3306;
description = "Database host port.";
};
name = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
example = "headscale";
description = "Database name.";
};
user = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
example = "headscale";
description = "Database user.";
};
};
};
log = {
level = lib.mkOption {
type = lib.types.str;
default = "info";
description = ''
headscale log level.
'';
example = "debug";
};
format = lib.mkOption {
type = lib.types.str;
default = "text";
description = ''
headscale log format.
'';
example = "json";
};
};
dns = {
magic_dns = lib.mkOption {
type = lib.types.bool;
default = true;
description = ''
Whether to use [MagicDNS](https://tailscale.com/docs/features/magicdns).
'';
example = false;
};
base_domain = lib.mkOption {
type = lib.types.str;
default = "";
description = ''
Defines the base domain to create the hostnames for MagicDNS.
This domain must be different from the {option}`server_url`
domain.
{option}`base_domain` must be a FQDN, without the trailing dot.
The FQDN of the hosts will be `hostname.base_domain` (e.g.
`myhost.tailnet.example.com`).
'';
example = "tailnet.example.com";
};
override_local_dns = lib.mkOption {
type = lib.types.bool;
default = true;
description = ''
Whether to [override clients' DNS servers](https://tailscale.com/docs/reference/dns-in-tailscale#override-dns-servers).
'';
example = false;
};
nameservers = {
global = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = ''
List of nameservers to pass to Tailscale clients.
'';
};
split = lib.mkOption {
type = lib.types.attrsOf (lib.types.listOf lib.types.str);
default = { };
description = ''
Split DNS configuration (map of domains and which DNS server to use for each).
See <https://tailscale.com/docs/reference/dns-in-tailscale>.
'';
example = {
"foo.bar.com" = [ "1.1.1.1" ];
};
};
};
extra_records = lib.mkOption {
type = lib.types.nullOr (
lib.types.listOf (
lib.types.submodule {
options = {
name = lib.mkOption {
type = lib.types.str;
description = "DNS record name.";
example = "grafana.tailnet.example.com";
};
type = lib.mkOption {
type = lib.types.enum [
"A"
"AAAA"
];
description = "DNS record type.";
example = "A";
};
value = lib.mkOption {
type = lib.types.str;
description = "DNS record value (IP address).";
example = "100.64.0.3";
};
};
}
)
);
default = null;
description = ''
Extra DNS records to expose to clients.
'';
example = ''
[ {
name = "grafana.tailnet.example.com";
type = "A";
value = "100.64.0.3";
} ]
'';
};
search_domains = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = ''
Search domains to inject to Tailscale clients.
'';
example = [ "mydomain.internal" ];
};
certificates = {
enabled = lib.mkOption {
type = lib.types.bool;
default = false;
description = ''
Whether nodes can get TLS certificates for their MagicDNS name
with `tailscale cert`. Needs a public {option}`base_domain` and
{option}`dns.challenge.provider`.
'';
};
zone = lib.mkOption {
type = lib.types.str;
default = "";
description = ''
DNS zone the challenge records are written to. Empty means
{option}`base_domain`.
'';
example = "example.com";
};
};
challenge.provider = lib.mkOption {
type = lib.types.nullOr (
lib.types.submodule {
freeformType = settingsFormat.type;
options.name = lib.mkOption {
type = lib.types.str;
description = ''
DNS provider that writes ACME DNS-01 challenge records:
acmedns, cloudflare, gigahost, hetzner, powerdns or rfc2136.
'';
};
}
);
default = null;
description = ''
DNS provider for ACME DNS-01 challenges. Every key besides
`name` is a setting of the provider; a text setting can be read
from a file by setting it to `file:<path>`.
'';
example = lib.literalExpression ''
{
name = "cloudflare";
api_token = "file:\''${CREDENTIALS_DIRECTORY}/cloudflare-token";
}
'';
};
};
oidc = {
issuer = lib.mkOption {
type = lib.types.str;
default = "";
description = ''
URL to OpenID issuer.
'';
example = "https://openid.example.com";
};
client_id = lib.mkOption {
type = lib.types.str;
default = "";
description = ''
OpenID Connect client ID.
'';
};
scope = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [
"openid"
"profile"
"email"
];
description = ''
Scopes used in the OIDC flow.
'';
};
extra_params = lib.mkOption {
type = lib.types.attrsOf lib.types.str;
default = { };
description = ''
Custom query parameters to send with the Authorize Endpoint request.
'';
example = {
domain_hint = "example.com";
};
};
allowed_domains = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = ''
Allowed principal domains. if an authenticated user's domain
is not in this list authentication request will be rejected.
'';
example = [ "example.com" ];
};
allowed_users = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = ''
Users allowed to authenticate even if not in allowedDomains.
'';
example = [ "alice@example.com" ];
};
pkce = {
enabled = lib.mkOption {
type = lib.types.bool;
default = false;
description = ''
Enable or disable PKCE (Proof Key for Code Exchange) support.
PKCE adds an additional layer of security to the OAuth 2.0
authorization code flow by preventing authorization code
interception attacks
See https://datatracker.ietf.org/doc/html/rfc7636
'';
example = true;
};
method = lib.mkOption {
type = lib.types.str;
default = "S256";
description = ''
PKCE method to use:
- plain: Use plain code verifier
- S256: Use SHA256 hashed code verifier (default, recommended)
'';
};
};
};
tls = {
cert_path = lib.mkOption {
type = lib.types.nullOr lib.types.path;
default = null;
description = ''
Path to already created certificate.
'';
};
key_path = lib.mkOption {
type = lib.types.nullOr lib.types.path;
default = null;
description = ''
Path to key for already created certificate.
'';
};
acme = {
hostname = lib.mkOption {
type = lib.types.str;
default = "";
description = ''
Domain name to request a TLS certificate for.
'';
};
# Null is written as YAML null, which headscale treats as unset.
challenge_type = lib.mkOption {
type = lib.types.nullOr (
lib.types.enum [
"TLS-ALPN-01"
"HTTP-01"
"DNS-01"
]
);
default = null;
description = ''
Type of ACME challenge to use: `HTTP-01` (default),
`TLS-ALPN-01`, or `DNS-01` through
{option}`dns.challenge.provider`.
'';
};
http_listen = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
description = ''
When HTTP-01 challenge is chosen, letsencrypt must set up a
verification endpoint, and it will be listening on:
`:http = port 80` (default).
'';
};
};
};
policy = {
mode = lib.mkOption {
type = lib.types.enum [
"file"
"database"
];
default = "file";
description = ''
The mode can be "file" or "database" that defines
where the ACL policies are stored and read from.
'';
};
path = lib.mkOption {
type = lib.types.nullOr lib.types.path;
default = null;
description = ''
If the mode is set to "file", the path to a
HuJSON file containing ACL policies.
'';
};
};
};
options = import ./options.generated.nix { inherit lib; };
};
};
};
};
imports = with lib; [
(mkRenamedOptionModule
[ "services" "headscale" "derp" "autoUpdate" ]
[ "services" "headscale" "settings" "derp" "auto_update_enabled" ]
)
(mkRenamedOptionModule
[ "services" "headscale" "derp" "auto_update_enable" ]
[ "services" "headscale" "settings" "derp" "auto_update_enabled" ]
)
(mkRenamedOptionModule
[ "services" "headscale" "derp" "paths" ]
[ "services" "headscale" "settings" "derp" "paths" ]
)
(mkRenamedOptionModule
[ "services" "headscale" "derp" "updateFrequency" ]
[ "services" "headscale" "settings" "derp" "update_frequency" ]
)
(mkRenamedOptionModule
[ "services" "headscale" "derp" "urls" ]
[ "services" "headscale" "settings" "derp" "urls" ]
)
(mkRenamedOptionModule
[ "services" "headscale" "ephemeralNodeInactivityTimeout" ]
[ "services" "headscale" "settings" "node" "ephemeral" "inactivity_timeout" ]
)
(mkRenamedOptionModule
[ "services" "headscale" "logLevel" ]
[ "services" "headscale" "settings" "log" "level" ]
)
(mkRenamedOptionModule
[ "services" "headscale" "openIdConnect" "clientId" ]
[ "services" "headscale" "settings" "oidc" "client_id" ]
)
(mkRemovedOptionModule [ "services" "headscale" "openIdConnect" "clientSecretFile" ] ''
Load the secret with systemd.services.headscale.serviceConfig.LoadCredential and set services.headscale.settings.oidc.client_secret = "file:\''${CREDENTIALS_DIRECTORY}/<name>".
'')
(mkRenamedOptionModule
[ "services" "headscale" "openIdConnect" "issuer" ]
[ "services" "headscale" "settings" "oidc" "issuer" ]
)
(mkRenamedOptionModule
[ "services" "headscale" "serverUrl" ]
[ "services" "headscale" "settings" "server_url" ]
)
(mkRenamedOptionModule
[ "services" "headscale" "tls" "certFile" ]
[ "services" "headscale" "settings" "tls" "cert_path" ]
)
(mkRenamedOptionModule
[ "services" "headscale" "tls" "keyFile" ]
[ "services" "headscale" "settings" "tls" "key_path" ]
)
(mkRenamedOptionModule
[ "services" "headscale" "tls" "letsencrypt" "challengeType" ]
[ "services" "headscale" "settings" "tls" "acme" "challenge_type" ]
)
(mkRenamedOptionModule
[ "services" "headscale" "tls" "letsencrypt" "hostname" ]
[ "services" "headscale" "settings" "tls" "acme" "hostname" ]
)
(mkRenamedOptionModule
[ "services" "headscale" "tls" "letsencrypt" "httpListen" ]
[ "services" "headscale" "settings" "tls" "acme" "http_listen" ]
)
(mkRemovedOptionModule [ "services" "headscale" "openIdConnect" "domainMap" ] ''
Headscale no longer uses domain_map.
'')
];
config = lib.mkIf cfg.enable {
assertions = [
{
assertion = with cfg.settings; dns.magic_dns -> dns.base_domain != "";
message = "dns.base_domain must be set when using MagicDNS";
}
{
assertion = with cfg.settings; dns.override_local_dns -> dns.nameservers.global != [ ];
message = "dns.nameservers.global must be set when overriding local DNS";
}
{
assertion =
with cfg.settings;
dns.certificates.enabled
-> dns.magic_dns && dns.base_domain != "" && dns.challenge.provider != null;
message = "dns.certificates.enabled needs dns.magic_dns, dns.base_domain and dns.challenge.provider";
}
{
assertion =
with cfg.settings.tls.acme;
hostname != "" && challenge_type == "DNS-01" -> cfg.settings.dns.challenge.provider != null;
message = "tls.acme.challenge_type DNS-01 needs dns.challenge.provider";
}
(assertRemovedOption [ "settings" "acl_policy_path" ] "Use `policy.path` instead.")
(assertRemovedOption [ "settings" "db_host" ] "Use `database.postgres.host` instead.")
(assertRemovedOption [ "settings" "db_name" ] "Use `database.postgres.name` instead.")
(assertRemovedOption [
"settings"
"db_password_file"
] "Use `database.postgres.pass = \"file:<path>\"` instead.")
(assertRemovedOption [ "settings" "db_path" ] "Use `database.sqlite.path` instead.")
(assertRemovedOption [ "settings" "db_port" ] "Use `database.postgres.port` instead.")
(assertRemovedOption [ "settings" "db_type" ] "Use `database.type` instead.")
(assertRemovedOption [ "settings" "db_user" ] "Use `database.postgres.user` instead.")
(assertRemovedOption [ "settings" "dns" "split" ] "Use `dns.nameservers.split` instead.")
(assertRemovedOption [ "settings" "dns_config" ] "Use `dns` instead.")
(assertRemovedOption [ "settings" "dns_config" "domains" ] "Use `dns.search_domains` instead.")
(assertRemovedOption [
"settings"
"dns_config"
"nameservers"
] "Use `dns.nameservers.global` instead.")
(assertRemovedOption [
"settings"
"oidc"
"strip_email_domain"
] "The strip_email_domain option got removed upstream")
(assertRemovedOption [
"settings"
"ephemeral_node_inactivity_timeout"
] "Use `node.ephemeral.inactivity_timeout` instead.")
(assertRemovedOption [
"settings"
"database"
"postgres"
"password_file"
] "Use `database.postgres.pass = \"file:<path>\"` instead.")
(assertRemovedOption [
"settings"
"oidc"
"client_secret_path"
] "Use `oidc.client_secret = \"file:<path>\"` instead.")
];
system.checks = lib.optional buildTimePolicy policyCheck;
system.preSwitchChecks.headscale = lib.mkIf (
cfg.check.config || preSwitchPolicy
) ''${lib.getExe preSwitchCheck} "$@"'';
services.headscale.settings = lib.mkMerge [
cliConfig
assertions = [
{
listen_addr = lib.mkDefault "${cfg.address}:${toString cfg.port}";
assertion = cliKeys == [ ];
message = "services.headscale.settings: remove ${lib.concatStringsSep ", " cliKeys}: the server never reads cli.*; headscale's CLI reads ~/.config/headscale/config.yaml or HEADSCALE_CLI_*, and here it would be written to the world-readable Nix store.";
}
];
environment = {
# Headscale CLI needs a minimal config to be able to locate the unix socket
# to talk to the server instance.
etc."headscale/config.yaml".source = cliConfigFile;
services.headscale.settings = lib.mapAttrsRecursive (_: distroDefault) {
# Where this module keeps state and the socket. Nix pins the package, so
# an update notice cannot be acted on.
noise.private_key_path = "${dataDir}/noise_private.key";
derp.server.private_key_path = "${dataDir}/derp_server_private.key";
database.type = "sqlite";
database.sqlite.path = "${dataDir}/db.sqlite";
unix_socket = "${runDir}/headscale.sock";
disable_check_updates = true;
systemPackages = [ cfg.package ];
# Earlier defaults of this module that headscale's own do not match,
# kept so an upgrade does not change a running configuration.
listen_addr = "127.0.0.1:8080";
prefixes.v4 = "100.64.0.0/10";
prefixes.v6 = "fd7a:115c:a1e0::/48";
derp.urls = [ "https://controlplane.tailscale.com/derpmap/default" ];
derp.auto_update_enabled = true;
derp.update_frequency = "24h";
node.ephemeral.inactivity_timeout = "30m";
};
users.groups.headscale = lib.mkIf (cfg.group == "headscale") { };
environment = {
systemPackages = [ cfg.package ];
users.users.headscale = lib.mkIf (cfg.user == "headscale") {
# The local CLI reads no file: these point it at the server's socket and
# update-check setting. Through PAM, so sudo keeps them too.
sessionVariables = {
HEADSCALE_UNIX_SOCKET = cfg.settings.unix_socket;
HEADSCALE_DISABLE_CHECK_UPDATES = lib.boolToString cfg.settings.disable_check_updates;
};
};
users.groups.headscale = { };
users.users.headscale = {
description = "headscale user";
home = dataDir;
group = cfg.group;
group = "headscale";
isSystemUser = true;
};
@@ -955,13 +290,16 @@ in
serviceConfig =
let
capabilityBoundingSet = [ "CAP_CHOWN" ] ++ lib.optional (cfg.port < 1024) "CAP_NET_BIND_SERVICE";
# "" empties the set, and comes first, so the unit gets only the
# capabilities listed after it, here or by another module.
capabilities = lib.mkBefore ([ "" ] ++ lib.optional privilegedPort "CAP_NET_BIND_SERVICE");
in
{
ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID";
Restart = "always";
RestartSec = "5s";
Type = "simple";
# Read here, so setting either read-only option fails evaluation.
User = cfg.user;
Group = cfg.group;
@@ -991,15 +329,14 @@ in
RemoveIPC = true;
UMask = "0077";
CapabilityBoundingSet = capabilityBoundingSet;
AmbientCapabilities = capabilityBoundingSet;
CapabilityBoundingSet = capabilities;
AmbientCapabilities = capabilities;
NoNewPrivileges = true;
LockPersonality = true;
RestrictRealtime = true;
SystemCallFilter = [
"@system-service"
"~@privileged"
"@chown"
];
SystemCallArchitectures = "native";
RestrictAddressFamilies = "AF_INET AF_INET6 AF_UNIX";
+2 -3
View File
@@ -35,10 +35,9 @@ in
services.headscale = {
enable = true;
address = "[::]";
port = 80;
settings = {
server_url = "http://${config.networking.hostName}";
listen_addr = "[::]:80";
dns.base_domain = lib.mkDefault "tailnet";
dns.override_local_dns = lib.mkDefault false;
# Nothing stored allows all, and `headscale policy set` works live.
@@ -60,7 +59,7 @@ in
# for a hostname URL after a recent dial.
systemd.services.headscale = {
environment.HEADSCALE_DEBUG_INSECURE_TLS_LISTEN_ADDR = "[::]:443";
# The module grants this only for a privileged main port.
# The module grants this from listen_addr, which does not name this :443.
serviceConfig.AmbientCapabilities = [ "CAP_NET_BIND_SERVICE" ];
serviceConfig.CapabilityBoundingSet = [ "CAP_NET_BIND_SERVICE" ];
};
+20 -25
View File
@@ -63,8 +63,6 @@ let
# Outside the store, so only the switch can check it.
mutablePolicy = "/var/lib/headscale/policy.json";
# Readable only through the group headscale.
oldGroupPolicy = "/var/lib/hsold/policy.json";
# Readable only through hshand, a group made by hand.
handGroupPolicy = "/var/lib/hshand/policy.json";
# Readable only through the group hsread.
@@ -82,10 +80,6 @@ in
{
specialisation = lib.mapAttrs (_: c: { configuration = c; }) {
unitEnv.systemd.services.headscale.environment.HEADSCALE_SERVER_URL = "ftp://headscale";
newGroup = {
services.headscale.group = "hs3";
users.groups.hs3 = { };
};
# hsnew is created by this switch, so the check leaves it out.
supplementaryGroup = {
services.headscale.settings.policy.path = lib.mkForce groupPolicy;
@@ -106,9 +100,13 @@ in
};
}
];
services.headscale.settings.policy = {
mode = "file";
path = valid;
services.headscale.settings = {
policy = {
mode = "file";
path = valid;
};
# The CLI calls below find it through HEADSCALE_UNIX_SOCKET.
unix_socket = "/run/headscale/moved.sock";
};
users.groups.hsread = { };
specialisation = lib.mapAttrs (_: c: { configuration.services.headscale = c; }) {
@@ -125,16 +123,7 @@ in
policy = false;
};
};
newUser = {
user = "hs2";
group = "hs2";
};
testsPass.settings.policy.path = lib.mkForce testsPass;
# After activation the user is no longer in its old primary group headscale.
newPrimaryGroup = {
group = "hsread";
settings.policy.path = lib.mkForce oldGroupPolicy;
};
# Activation keeps a membership of a group NixOS does not declare.
handGroup.settings.policy.path = lib.mkForce handGroupPolicy;
credential.settings.dns = {
@@ -188,6 +177,9 @@ in
headscale.wait_for_unit("headscale.service")
headscale.wait_until_succeeds("headscale health", timeout=timedelta(seconds=60))
headscale.fail("test -e /etc/headscale/config.yaml")
# sudo resets the environment; PAM sets HEADSCALE_UNIX_SOCKET again.
headscale.succeed("env -u HEADSCALE_UNIX_SOCKET sudo -u headscale headscale health")
with subtest("rejected switches leave the running headscale alone"):
pid = main_pid()
@@ -222,9 +214,6 @@ in
headscale.succeed("install -d -m 750 -g hshand ${builtins.dirOf handGroupPolicy}")
headscale.succeed("install -m 640 -g hshand ${valid} ${handGroupPolicy}")
headscale.succeed(stc("handGroup", "check"))
headscale.succeed("install -d -m 750 -g headscale ${builtins.dirOf oldGroupPolicy}")
headscale.succeed("install -m 640 -g headscale ${valid} ${oldGroupPolicy}")
assert_rejected("newPrimaryGroup", "permission denied")
with subtest("a file: secret is skipped, not read"):
out = headscale.succeed(stc("credential", "check"))
@@ -233,10 +222,6 @@ in
with subtest("skips"):
out = headscale.succeed("${toplevel}/bin/switch-to-configuration check 2>&1")
assert "unit unchanged" in out, out
out = headscale.succeed(stc("newUser", "check"))
assert "does not exist yet" in out, out
out = headscale.succeed(stc("newGroup", "check"))
assert 'group hs3 does not exist yet' in out, out
with subtest("escape hatches"):
headscale.succeed(stc("unchecked", "check"))
@@ -249,5 +234,15 @@ in
assert main_pid() != pid, "headscale was not restarted"
want = headscale.succeed("${jq} -S . ${testsPass}")
assert served_policy() == want, "new policy not served"
# Last: it takes headscale's account away.
with subtest("an account activation has yet to create skips the checks"):
headscale.succeed("systemctl stop headscale.service")
headscale.succeed("groupmod -n hsgone headscale")
out = headscale.succeed(stc("mutable", "check"))
assert "group headscale does not exist yet" in out, out
headscale.succeed("usermod -l hsgone headscale")
out = headscale.succeed(stc("mutable", "check"))
assert "user headscale does not exist yet" in out, out
'';
}
+5
View File
@@ -72,6 +72,11 @@ in
)
headscale.succeed("headscale policy set -f ${policy}")
# The default socket needs neither a config file nor a variable.
headscale.succeed("env -u HEADSCALE_UNIX_SOCKET headscale nodes list")
# sudo resets the environment; PAM sets the module's variables again.
out = headscale.succeed("env -u HEADSCALE_DISABLE_CHECK_UPDATES sudo printenv HEADSCALE_DISABLE_CHECK_UPDATES")
assert out.strip() == "true", out
# The docs tell operators to run this; it needs ExecReload in the unit.
headscale.succeed("systemctl reload headscale.service")
+230
View File
@@ -0,0 +1,230 @@
# What the module writes, grants and exports, without a VM. headscale's own
# check decides what the written config means.
self: pkgs:
let
inherit (pkgs) lib;
required = {
server_url = "https://headscale.example.com";
dns.base_domain = "tailnet.example.com";
dns.nameservers.global = [ "192.0.2.53" ];
};
system =
m:
pkgs.nixos {
imports = [
self.nixosModules.default
m
];
services.headscale = {
enable = true;
settings = required;
};
};
settings = s: system { services.headscale.settings = s; };
policy = pkgs.writeText "policy.json" "{}";
derpMap = pkgs.writeText "derp.yaml" "regions: {}";
ok = settings {
policy = {
mode = "file";
path = policy;
};
derp.paths = [ derpMap ];
unix_socket = "/run/headscale/moved.sock";
dns = {
certificates.enabled = true;
challenge.provider = {
name = "rfc2136";
server = "127.0.0.1:53";
key_name = "headscale.";
key_alg = "hmac-sha256.";
key = "file:\${CREDENTIALS_DIRECTORY}/tsig";
};
};
};
http = settings { listen_addr = ":http"; };
# A user's mkDefault and a plain assignment both replace the module's values.
overrides = settings {
prefixes.v4 = lib.mkDefault "100.96.0.0/11";
derp.urls = lib.mkDefault [ "https://derp.example.com/map.json" ];
derp.update_frequency = "1h";
};
# Both spellings Go reads as cli.*.
clis = settings {
cli.api_key = "not-for-the-store";
"cli.api_key" = "not-for-the-store";
};
# Key errors only: headscale stops at them before it reads any value.
bad = settings {
listen_addr = "[::]:443";
dns.magic_dsn = true;
oidc.client_secret_path = "/run/x";
db_password_file = "/run/x";
tls_cert_path = "/x";
};
badUrl = settings { server_url = lib.mkForce "ftp://headscale"; };
# A record's unknown field is a decoding error, reported without the others.
badRecord = settings {
dns.extra_records = [
{
name = "grafana.tailnet.example.com";
value = "100.64.0.3";
typo = "A";
}
];
};
# A system evaluated inside the build, where the test can read its error.
evalSystem = pkgs.writeText "eval-system.nix" ''
{ case }:
let
inherit
(import ${pkgs.path}/nixos/lib/eval-config.nix {
system = "${pkgs.stdenv.hostPlatform.system}";
modules = [
${self}/nix/module.nix
(builtins.fromJSON (builtins.readFile case))
];
})
config
;
unit = config.systemd.services.headscale.serviceConfig;
in
# What building the system reads: the settings and the unit's account.
builtins.deepSeq [
config.services.headscale.settings
unit.User
unit.Group
] true
'';
evalCase =
name: c:
pkgs.writeText "${name}.json" (
builtins.toJSON (
lib.recursiveUpdate {
services.headscale = {
enable = true;
settings = required;
};
} c
)
);
configFile = s: s.config.services.headscale.configFile;
binds =
s:
lib.elem "CAP_NET_BIND_SERVICE" s.config.systemd.services.headscale.serviceConfig.CapabilityBoundingSet;
inherit (ok.config.environment) sessionVariables;
overridden = overrides.config.services.headscale.settings;
in
assert lib.assertMsg (
sessionVariables.HEADSCALE_UNIX_SOCKET or null == "/run/headscale/moved.sock"
) "ok: HEADSCALE_UNIX_SOCKET is not settings.unix_socket";
assert lib.assertMsg (
sessionVariables.HEADSCALE_DISABLE_CHECK_UPDATES or null == "true"
) "ok: HEADSCALE_DISABLE_CHECK_UPDATES is not true";
assert lib.assertMsg (
overridden.prefixes.v4 == "100.96.0.0/11"
) "overrides: a user's mkDefault does not replace prefixes.v4";
assert lib.assertMsg (
overridden.derp.urls == [
"https://derp.example.com/map.json"
]
) "overrides: a user's mkDefault does not replace derp.urls";
assert lib.assertMsg (
overridden.derp.update_frequency == "1h"
) "overrides: a plain assignment does not replace derp.update_frequency";
assert lib.assertMsg (lib.any (
a: !a.assertion && lib.hasPrefix "services.headscale.settings: remove cli, cli.api_key:" a.message
) clis.config.assertions) "clis: no failed assertion names every spelling of settings.cli";
assert lib.assertMsg (
!(ok.config.environment.etc ? "headscale/config.yaml")
) "ok: /etc/headscale/config.yaml is written";
assert lib.assertMsg (!binds ok) "ok: 127.0.0.1:8080 grants CAP_NET_BIND_SERVICE";
assert lib.assertMsg (binds http) "http: :http does not grant CAP_NET_BIND_SERVICE";
assert lib.assertMsg (binds bad) "bad: [::]:443 does not grant CAP_NET_BIND_SERVICE";
assert lib.assertMsg (
ok.config.systemd.services.headscale.serviceConfig.CapabilityBoundingSet == [ "" ]
) "ok: the unit keeps a capability";
pkgs.runCommand "headscale-nixos-module"
{
nativeBuildInputs = [
ok.config.services.headscale.package
pkgs.yq-go
pkgs.jq
pkgs.nix
];
}
''
want() {
yq -o json "$1" | jq -e "$2" >/dev/null || { echo "$1: want $2"; cat "$1"; exit 1; }
}
rejects() {
local file=$1 out
shift
if out=$(headscale check config -f "$file" 2>&1); then
echo "$file: check config passed"
exit 1
fi
for msg in "$@"; do
grep -qF -- "$msg" <<<"$out" || { echo "$file: no '$msg' in:"; echo "$out"; exit 1; }
done
}
ok=${configFile ok}
want $ok '.policy.path == "${policy}" and .derp.paths == ["${derpMap}"]'
want $ok 'has("cli") | not'
want $ok '.listen_addr == "127.0.0.1:8080" and .disable_check_updates == true'
want $ok '.database.type == "sqlite"'
want $ok '.derp.urls[0] == "https://controlplane.tailscale.com/derpmap/default"'
headscale check config -f $ok
bad=${configFile bad}
want $bad '(.dns | has("magic_dsn")) and (.oidc | has("client_secret_path"))'
want $bad 'has("db_password_file") and has("tls_cert_path")'
rejects $bad 'unknown configuration key dns.magic_dsn' \
'oidc.client_secret_path was removed' \
'db_password_file was removed' \
'tls_cert_path was removed'
rejects ${configFile badUrl} 'missing a scheme'
badRecord=${configFile badRecord}
want $badRecord '.dns.extra_records[0].typo == "A"'
rejects $badRecord 'dns.extra_records has invalid keys: typo'
export HOME=$TMPDIR NIX_STATE_DIR=$TMPDIR/state NIX_CONF_DIR=$TMPDIR/etc NIX_LOG_DIR=$TMPDIR/log
evaluate() {
nix-instantiate --store dummy:// --readonly-mode --eval --strict ${evalSystem} --argstr case "$1" 2>&1
}
evalFails() {
local case=$1 out
shift
if out=$(evaluate "$case"); then
echo "$case: evaluates"
exit 1
fi
for msg in "$@"; do
grep -qF -- "$msg" <<<"$out" || { echo "$case: no '$msg' in:"; echo "$out"; exit 1; }
done
}
# The distro defaults pass their types.
evaluate ${evalCase "defaults" { }} || exit 1
evalFails ${
evalCase "store-key" { services.headscale.settings.noise.private_key_path = "${./module.nix}"; }
} "services.headscale.settings.noise.private_key_path' is not of type"
evalFails ${
evalCase "literal-secret" { services.headscale.settings.oidc.client_secret = "hunter2"; }
} "services.headscale.settings.oidc.client_secret' is not of type"
evalFails ${
evalCase "no-port" { services.headscale.settings.listen_addr = "0.0.0.0"; }
} "services.headscale.settings.listen_addr' is not of type"
evalFails ${
evalCase "user" { services.headscale.user = "hs2"; }
} "services.headscale.user' is read-only"
evalFails ${
evalCase "group" { services.headscale.group = "hs2"; }
} "services.headscale.group' is read-only"
touch $out
''