From 6d24afba1ce773ac935f4acc1c35d6521725ac26 Mon Sep 17 00:00:00 2001 From: Kristoffer Dalby Date: Tue, 11 Nov 2025 13:35:23 -0600 Subject: [PATCH 001/148] add pre-commit hooks, move claude to agents. (#2877) --- .../agents/headscale-integration-tester.md | 20 +- .golangci-lint-hook.sh | 27 + .mcp.json | 24 +- .pre-commit-config.yaml | 75 ++ AGENTS.md | 699 ++++++++++++++++++ CLAUDE.md | 532 +------------ Makefile | 4 +- README.md | 2 + derp-example.yaml | 2 +- docs/logo/headscale3-dots.svg | 2 +- docs/logo/headscale3_header_stacked_left.svg | 2 +- flake.nix | 427 +++++------ integration/auth_key_test.go | 1 - 13 files changed, 1041 insertions(+), 776 deletions(-) create mode 100755 .golangci-lint-hook.sh create mode 100644 .pre-commit-config.yaml create mode 100644 AGENTS.md diff --git a/.claude/agents/headscale-integration-tester.md b/.claude/agents/headscale-integration-tester.md index 2b25977d..54474ce9 100644 --- a/.claude/agents/headscale-integration-tester.md +++ b/.claude/agents/headscale-integration-tester.md @@ -52,7 +52,7 @@ go test ./integration -timeout 45m **Timeout Guidelines by Test Type**: - **Basic functionality tests**: `--timeout=900s` (15 minutes minimum) - **Route/ACL tests**: `--timeout=1200s` (20 minutes) -- **HA/failover tests**: `--timeout=1800s` (30 minutes) +- **HA/failover tests**: `--timeout=1800s` (30 minutes) - **Long-running tests**: `--timeout=2100s` (35 minutes) - **Full test suite**: `-timeout 45m` (45 minutes) @@ -433,7 +433,7 @@ When you understand a test's purpose through debugging, always add comprehensive // // The test verifies: // - Route announcements are received and tracked -// - ACL policies control route approval correctly +// - ACL policies control route approval correctly // - Only approved routes appear in peer network maps // - Route state persists correctly in the database func TestSubnetRoutes(t *testing.T) { @@ -535,7 +535,7 @@ var nodeKey key.NodePublic assert.EventuallyWithT(t, func(c *assert.CollectT) { nodes, err := headscale.ListNodes() assert.NoError(c, err) - + for _, node := range nodes { if node.GetName() == "router" { routeNode = node @@ -550,7 +550,7 @@ assert.EventuallyWithT(t, func(c *assert.CollectT) { assert.EventuallyWithT(t, func(c *assert.CollectT) { status, err := client.Status() assert.NoError(c, err) - + peerStatus, ok := status.Peer[nodeKey] assert.True(c, ok, "peer should exist in status") requirePeerSubnetRoutesWithCollect(c, peerStatus, expectedPrefixes) @@ -566,7 +566,7 @@ assert.EventuallyWithT(t, func(c *assert.CollectT) { nodes, err := headscale.ListNodes() assert.NoError(c, err) assert.Len(c, nodes, 2) - + // Second unrelated external call - WRONG! status, err := client.Status() assert.NoError(c, err) @@ -577,7 +577,7 @@ assert.EventuallyWithT(t, func(c *assert.CollectT) { assert.EventuallyWithT(t, func(c *assert.CollectT) { nodes, err := headscale.ListNodes() assert.NoError(c, err) - + // NEVER do this! assert.EventuallyWithT(t, func(c2 *assert.CollectT) { status, _ := client.Status() @@ -666,11 +666,11 @@ When working within EventuallyWithT blocks where you need to prevent panics: assert.EventuallyWithT(t, func(c *assert.CollectT) { nodes, err := headscale.ListNodes() assert.NoError(c, err) - + // For array bounds - use require with t to prevent panic assert.Len(c, nodes, 6) // Test expectation require.GreaterOrEqual(t, len(nodes), 3, "need at least 3 nodes to avoid panic") - + // For nil pointer access - use require with t before dereferencing assert.NotNil(c, srs1PeerStatus.PrimaryRoutes) // Test expectation require.NotNil(t, srs1PeerStatus.PrimaryRoutes, "primary routes must be set to avoid panic") @@ -681,7 +681,7 @@ assert.EventuallyWithT(t, func(c *assert.CollectT) { }, 5*time.Second, 200*time.Millisecond, "checking route state") ``` -**Key Principle**: +**Key Principle**: - Use `assert` with `c` (*assert.CollectT) for test expectations that can be retried - Use `require` with `t` (*testing.T) for MUST conditions that prevent panics - Within EventuallyWithT, both are available - choose based on whether failure would cause a panic @@ -704,7 +704,7 @@ assert.EventuallyWithT(t, func(c *assert.CollectT) { assert.EventuallyWithT(t, func(c *assert.CollectT) { status, err := client.Status() assert.NoError(c, err) - + // Check all peers have expected routes for _, peerKey := range status.Peers() { peerStatus := status.Peer[peerKey] diff --git a/.golangci-lint-hook.sh b/.golangci-lint-hook.sh new file mode 100755 index 00000000..ba62e432 --- /dev/null +++ b/.golangci-lint-hook.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# Wrapper script for golangci-lint pre-commit hook +# Finds where the current branch diverged from the main branch + +set -euo pipefail + +# Try to find the main branch reference in order of preference: +# 1. upstream/main (common in forks) +# 2. origin/main (common in direct clones) +# 3. main (local branch) +for ref in upstream/main origin/main main; do + if git rev-parse --verify "$ref" >/dev/null 2>&1; then + MAIN_REF="$ref" + break + fi +done + +# If we couldn't find any main branch, just check the last commit +if [ -z "${MAIN_REF:-}" ]; then + MAIN_REF="HEAD~1" +fi + +# Find where current branch diverged from main +MERGE_BASE=$(git merge-base HEAD "$MAIN_REF" 2>/dev/null || echo "HEAD~1") + +# Run golangci-lint only on changes since branch point +exec golangci-lint run --new-from-rev="$MERGE_BASE" --timeout=5m --fix diff --git a/.mcp.json b/.mcp.json index 1303afda..71554002 100644 --- a/.mcp.json +++ b/.mcp.json @@ -3,45 +3,31 @@ "claude-code-mcp": { "type": "stdio", "command": "npx", - "args": [ - "-y", - "@steipete/claude-code-mcp@latest" - ], + "args": ["-y", "@steipete/claude-code-mcp@latest"], "env": {} }, "sequential-thinking": { "type": "stdio", "command": "npx", - "args": [ - "-y", - "@modelcontextprotocol/server-sequential-thinking" - ], + "args": ["-y", "@modelcontextprotocol/server-sequential-thinking"], "env": {} }, "nixos": { "type": "stdio", "command": "uvx", - "args": [ - "mcp-nixos" - ], + "args": ["mcp-nixos"], "env": {} }, "context7": { "type": "stdio", "command": "npx", - "args": [ - "-y", - "@upstash/context7-mcp" - ], + "args": ["-y", "@upstash/context7-mcp"], "env": {} }, "git": { "type": "stdio", "command": "npx", - "args": [ - "-y", - "@cyanheads/git-mcp-server" - ], + "args": ["-y", "@cyanheads/git-mcp-server"], "env": {} } } diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 00000000..4d98d4d3 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,75 @@ +# prek/pre-commit configuration for headscale +# See: https://prek.j178.dev/quickstart/ +# See: https://prek.j178.dev/builtin/ + +# Global exclusions - ignore docs and generated code +exclude: ^(docs/|gen/) + +repos: + # Built-in hooks from pre-commit/pre-commit-hooks + # prek will use fast-path optimized versions automatically + # See: https://prek.j178.dev/builtin/ + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v5.0.0 + hooks: + - id: check-added-large-files + - id: check-case-conflict + - id: check-executables-have-shebangs + - id: check-json + - id: check-merge-conflict + - id: check-symlinks + - id: check-toml + - id: check-xml + - id: check-yaml + - id: detect-private-key + - id: end-of-file-fixer + - id: fix-byte-order-marker + - id: mixed-line-ending + - id: trailing-whitespace + + # Local hooks for project-specific tooling + - repo: local + hooks: + # nixpkgs-fmt for Nix files + - id: nixpkgs-fmt + name: nixpkgs-fmt + entry: nixpkgs-fmt + language: system + files: \.nix$ + + # Prettier for formatting + - id: prettier + name: prettier + entry: prettier --write --list-different + language: system + types_or: + [ + javascript, + jsx, + ts, + tsx, + yaml, + json, + toml, + html, + css, + scss, + sass, + markdown, + ] + exclude: ^CHANGELOG\.md$ + + # Prettier for CHANGELOG.md with special formatting + - id: prettier-changelog + name: prettier-changelog + entry: prettier --write --print-width 80 --prose-wrap always + language: system + files: ^CHANGELOG\.md$ + + # golangci-lint for Go code quality + - id: golangci-lint + name: golangci-lint + entry: .golangci-lint-hook.sh + language: system + types: [go] + pass_filenames: false diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..e5dd1b01 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,699 @@ +# AGENTS.md + +This file provides guidance to AI agents when working with code in this repository. + +## Overview + +Headscale is an open-source implementation of the Tailscale control server written in Go. It provides self-hosted coordination for Tailscale networks (tailnets), managing node registration, IP allocation, policy enforcement, and DERP routing. + +## Development Commands + +### Quick Setup + +```bash +# Recommended: Use Nix for dependency management +nix develop + +# Full development workflow +make dev # runs fmt + lint + test + build +``` + +### Essential Commands + +```bash +# Build headscale binary +make build + +# Run tests +make test +go test ./... # All unit tests +go test -race ./... # With race detection + +# Run specific integration test +go run ./cmd/hi run "TestName" --postgres + +# Code formatting and linting +make fmt # Format all code (Go, docs, proto) +make lint # Lint all code (Go, proto) +make fmt-go # Format Go code only +make lint-go # Lint Go code only + +# Protocol buffer generation (after modifying proto/) +make generate + +# Clean build artifacts +make clean +``` + +### Integration Testing + +```bash +# Use the hi (Headscale Integration) test runner +go run ./cmd/hi doctor # Check system requirements +go run ./cmd/hi run "TestPattern" # Run specific test +go run ./cmd/hi run "TestPattern" --postgres # With PostgreSQL backend + +# Test artifacts are saved to control_logs/ with logs and debug data +``` + +## Pre-Commit Quality Checks + +### **MANDATORY: Automated Pre-Commit Hooks with prek** + +**CRITICAL REQUIREMENT**: This repository uses [prek](https://prek.j178.dev/) for automated pre-commit hooks. All commits are automatically validated for code quality, formatting, and common issues. + +### Initial Setup + +When you first clone the repository or enter the nix shell, install the git hooks: + +```bash +# Enter nix development environment +nix develop + +# Install prek git hooks (one-time setup) +prek install +``` + +This installs the pre-commit hook at `.git/hooks/pre-commit` which automatically runs all configured checks before each commit. + +### Configured Hooks + +The repository uses `.pre-commit-config.yaml` with the following hooks: + +**Built-in Checks** (optimized fast-path execution): + +- `check-added-large-files` - Prevents accidentally committing large files +- `check-case-conflict` - Checks for files that would conflict in case-insensitive filesystems +- `check-executables-have-shebangs` - Ensures executables have proper shebangs +- `check-json` - Validates JSON syntax +- `check-merge-conflict` - Prevents committing files with merge conflict markers +- `check-symlinks` - Checks for broken symlinks +- `check-toml` - Validates TOML syntax +- `check-xml` - Validates XML syntax +- `check-yaml` - Validates YAML syntax +- `detect-private-key` - Detects accidentally committed private keys +- `end-of-file-fixer` - Ensures files end with a newline +- `fix-byte-order-marker` - Removes UTF-8 byte order markers +- `mixed-line-ending` - Prevents mixed line endings +- `trailing-whitespace` - Removes trailing whitespace + +**Project-Specific Hooks**: + +- `nixpkgs-fmt` - Formats Nix files +- `prettier` - Formats markdown, YAML, JSON, and TOML files +- `golangci-lint` - Runs Go linter with auto-fix on changed files only + +### Manual Hook Execution + +Run hooks manually without making a commit: + +```bash +# Run hooks on staged files only +prek run + +# Run hooks on all files in the repository +prek run --all-files + +# Run a specific hook +prek run golangci-lint + +# Run hooks on specific files +prek run --files path/to/file1.go path/to/file2.go +``` + +### Workflow Pattern + +With prek installed, your normal workflow becomes: + +```bash +# 1. Make your code changes +vim hscontrol/state/state.go + +# 2. Stage your changes +git add . + +# 3. Commit - hooks run automatically +git commit -m "feat: add new feature" + +# If hooks fail, they will show which checks failed +# Fix the issues and try committing again +``` + +### Manual golangci-lint (Optional) + +While golangci-lint runs automatically via prek, you can also run it manually: + +```bash +# Use the same logic as the pre-commit hook (recommended) +./.golangci-lint-hook.sh + +# Or manually specify a base reference +golangci-lint run --new-from-rev=upstream/main --timeout=5m --fix +``` + +The `.golangci-lint-hook.sh` script automatically finds where your branch diverged from the main branch by checking `upstream/main`, `origin/main`, or `main` in that order. + +### Skipping Hooks (Not Recommended) + +In rare cases where you need to skip hooks (e.g., work-in-progress commits), use: + +```bash +git commit --no-verify -m "WIP: work in progress" +``` + +**WARNING**: Only use `--no-verify` for temporary WIP commits on feature branches. All commits to main must pass all hooks. + +### Troubleshooting + +**Hook installation issues**: + +```bash +# Check if hooks are installed +ls -la .git/hooks/pre-commit + +# Reinstall hooks +prek install +``` + +**Hooks running slow**: + +```bash +# prek uses optimized fast-path for built-in hooks +# If running slow, check which hook is taking time with verbose output +prek run -v +``` + +**Update hook configuration**: + +```bash +# After modifying .pre-commit-config.yaml, hooks will automatically use new config +# No reinstallation needed +``` + +## Project Structure & Architecture + +### Top-Level Organization + +``` +headscale/ +├── cmd/ # Command-line applications +│ ├── headscale/ # Main headscale server binary +│ └── hi/ # Headscale Integration test runner +├── hscontrol/ # Core control plane logic +├── integration/ # End-to-end Docker-based tests +├── proto/ # Protocol buffer definitions +├── gen/ # Generated code (protobuf) +├── docs/ # Documentation +└── packaging/ # Distribution packaging +``` + +### Core Packages (`hscontrol/`) + +**Main Server (`hscontrol/`)** + +- `app.go`: Application setup, dependency injection, server lifecycle +- `handlers.go`: HTTP/gRPC API endpoints for management operations +- `grpcv1.go`: gRPC service implementation for headscale API +- `poll.go`: **Critical** - Handles Tailscale MapRequest/MapResponse protocol +- `noise.go`: Noise protocol implementation for secure client communication +- `auth.go`: Authentication flows (web, OIDC, command-line) +- `oidc.go`: OpenID Connect integration for user authentication + +**State Management (`hscontrol/state/`)** + +- `state.go`: Central coordinator for all subsystems (database, policy, IP allocation, DERP) +- `node_store.go`: **Performance-critical** - In-memory cache with copy-on-write semantics +- Thread-safe operations with deadlock detection +- Coordinates between database persistence and real-time operations + +**Database Layer (`hscontrol/db/`)** + +- `db.go`: Database abstraction, GORM setup, migration management +- `node.go`: Node lifecycle, registration, expiration, IP assignment +- `users.go`: User management, namespace isolation +- `api_key.go`: API authentication tokens +- `preauth_keys.go`: Pre-authentication keys for automated node registration +- `ip.go`: IP address allocation and management +- `policy.go`: Policy storage and retrieval +- Schema migrations in `schema.sql` with extensive test data coverage + +**Policy Engine (`hscontrol/policy/`)** + +- `policy.go`: Core ACL evaluation logic, HuJSON parsing +- `v2/`: Next-generation policy system with improved filtering +- `matcher/`: ACL rule matching and evaluation engine +- Determines peer visibility, route approval, and network access rules +- Supports both file-based and database-stored policies + +**Network Management (`hscontrol/`)** + +- `derp/`: DERP (Designated Encrypted Relay for Packets) server implementation + - NAT traversal when direct connections fail + - Fallback relay for firewall-restricted environments +- `mapper/`: Converts internal Headscale state to Tailscale's wire protocol format + - `tail.go`: Tailscale-specific data structure generation +- `routes/`: Subnet route management and primary route selection +- `dns/`: DNS record management and MagicDNS implementation + +**Utilities & Support (`hscontrol/`)** + +- `types/`: Core data structures, configuration, validation +- `util/`: Helper functions for networking, DNS, key management +- `templates/`: Client configuration templates (Apple, Windows, etc.) +- `notifier/`: Event notification system for real-time updates +- `metrics.go`: Prometheus metrics collection +- `capver/`: Tailscale capability version management + +### Key Subsystem Interactions + +**Node Registration Flow** + +1. **Client Connection**: `noise.go` handles secure protocol handshake +2. **Authentication**: `auth.go` validates credentials (web/OIDC/preauth) +3. **State Creation**: `state.go` coordinates IP allocation via `db/ip.go` +4. **Storage**: `db/node.go` persists node, `NodeStore` caches in memory +5. **Network Setup**: `mapper/` generates initial Tailscale network map + +**Ongoing Operations** + +1. **Poll Requests**: `poll.go` receives periodic client updates +2. **State Updates**: `NodeStore` maintains real-time node information +3. **Policy Application**: `policy/` evaluates ACL rules for peer relationships +4. **Map Distribution**: `mapper/` sends network topology to all affected clients + +**Route Management** + +1. **Advertisement**: Clients announce routes via `poll.go` Hostinfo updates +2. **Storage**: `db/` persists routes, `NodeStore` caches for performance +3. **Approval**: `policy/` auto-approves routes based on ACL rules +4. **Distribution**: `routes/` selects primary routes, `mapper/` distributes to peers + +### Command-Line Tools (`cmd/`) + +**Main Server (`cmd/headscale/`)** + +- `headscale.go`: CLI parsing, configuration loading, server startup +- Supports daemon mode, CLI operations (user/node management), database operations + +**Integration Test Runner (`cmd/hi/`)** + +- `main.go`: Test execution framework with Docker orchestration +- `run.go`: Individual test execution with artifact collection +- `doctor.go`: System requirements validation +- `docker.go`: Container lifecycle management +- Essential for validating changes against real Tailscale clients + +### Generated & External Code + +**Protocol Buffers (`proto/` → `gen/`)** + +- Defines gRPC API for headscale management operations +- Client libraries can generate from these definitions +- Run `make generate` after modifying `.proto` files + +**Integration Testing (`integration/`)** + +- `scenario.go`: Docker test environment setup +- `tailscale.go`: Tailscale client container management +- Individual test files for specific functionality areas +- Real end-to-end validation with network isolation + +### Critical Performance Paths + +**High-Frequency Operations** + +1. **MapRequest Processing** (`poll.go`): Every 15-60 seconds per client +2. **NodeStore Reads** (`node_store.go`): Every operation requiring node data +3. **Policy Evaluation** (`policy/`): On every peer relationship calculation +4. **Route Lookups** (`routes/`): During network map generation + +**Database Write Patterns** + +- **Frequent**: Node heartbeats, endpoint updates, route changes +- **Moderate**: User operations, policy updates, API key management +- **Rare**: Schema migrations, bulk operations + +### Configuration & Deployment + +**Configuration** (`hscontrol/types/config.go`)\*\* + +- Database connection settings (SQLite/PostgreSQL) +- Network configuration (IP ranges, DNS settings) +- Policy mode (file vs database) +- DERP relay configuration +- OIDC provider settings + +**Key Dependencies** + +- **GORM**: Database ORM with migration support +- **Tailscale Libraries**: Core networking and protocol code +- **Zerolog**: Structured logging throughout the application +- **Buf**: Protocol buffer toolchain for code generation + +### Development Workflow Integration + +The architecture supports incremental development: + +- **Unit Tests**: Focus on individual packages (`*_test.go` files) +- **Integration Tests**: Validate cross-component interactions +- **Database Tests**: Extensive migration and data integrity validation +- **Policy Tests**: ACL rule evaluation and edge cases +- **Performance Tests**: NodeStore and high-frequency operation validation + +## Integration Testing System + +### Overview + +Headscale uses Docker-based integration tests with real Tailscale clients to validate end-to-end functionality. The integration test system is complex and requires specialized knowledge for effective execution and debugging. + +### **MANDATORY: Use the headscale-integration-tester Agent** + +**CRITICAL REQUIREMENT**: For ANY integration test execution, analysis, troubleshooting, or validation, you MUST use the `headscale-integration-tester` agent. This agent contains specialized knowledge about: + +- Test execution strategies and timing requirements +- Infrastructure vs code issue distinction (99% vs 1% failure patterns) +- Security-critical debugging rules and forbidden practices +- Comprehensive artifact analysis workflows +- Real-world failure patterns from HA debugging experiences + +### Quick Reference Commands + +```bash +# Check system requirements (always run first) +go run ./cmd/hi doctor + +# Run single test (recommended for development) +go run ./cmd/hi run "TestName" + +# Use PostgreSQL for database-heavy tests +go run ./cmd/hi run "TestName" --postgres + +# Pattern matching for related tests +go run ./cmd/hi run "TestPattern*" +``` + +**Critical Notes**: + +- Only ONE test can run at a time (Docker port conflicts) +- Tests generate ~100MB of logs per run in `control_logs/` +- Clean environment before each test: `rm -rf control_logs/202507* && docker system prune -f` + +### Test Artifacts Location + +All test runs save comprehensive debugging artifacts to `control_logs/TIMESTAMP-ID/` including server logs, client logs, database dumps, MapResponse protocol data, and Prometheus metrics. + +**For all integration test work, use the headscale-integration-tester agent - it contains the complete knowledge needed for effective testing and debugging.** + +## NodeStore Implementation Details + +**Key Insight from Recent Work**: The NodeStore is a critical performance optimization that caches node data in memory while ensuring consistency with the database. When working with route advertisements or node state changes: + +1. **Timing Considerations**: Route advertisements need time to propagate from clients to server. Use `require.EventuallyWithT()` patterns in tests instead of immediate assertions. + +2. **Synchronization Points**: NodeStore updates happen at specific points like `poll.go:420` after Hostinfo changes. Ensure these are maintained when modifying the polling logic. + +3. **Peer Visibility**: The NodeStore's `peersFunc` determines which nodes are visible to each other. Policy-based filtering is separate from monitoring visibility - expired nodes should remain visible for debugging but marked as expired. + +## Testing Guidelines + +### Integration Test Patterns + +#### **CRITICAL: EventuallyWithT Pattern for External Calls** + +**All external calls in integration tests MUST be wrapped in EventuallyWithT blocks** to handle eventual consistency in distributed systems. External calls include: + +- `client.Status()` - Getting Tailscale client status +- `client.Curl()` - Making HTTP requests through clients +- `client.Traceroute()` - Running network diagnostics +- `headscale.ListNodes()` - Querying headscale server state +- Any other calls that interact with external systems or network operations + +**Key Rules**: + +1. **Never use bare `require.NoError(t, err)` with external calls** - Always wrap in EventuallyWithT +2. **Keep related assertions together** - If multiple assertions depend on the same external call, keep them in the same EventuallyWithT block +3. **Split unrelated external calls** - Different external calls should be in separate EventuallyWithT blocks +4. **Never nest EventuallyWithT calls** - Each EventuallyWithT should be at the same level +5. **Declare shared variables at function scope** - Variables used across multiple EventuallyWithT blocks must be declared before first use + +**Examples**: + +```go +// CORRECT: External call wrapped in EventuallyWithT +assert.EventuallyWithT(t, func(c *assert.CollectT) { + status, err := client.Status() + assert.NoError(c, err) + + // Related assertions using the same status call + for _, peerKey := range status.Peers() { + peerStatus := status.Peer[peerKey] + assert.NotNil(c, peerStatus.PrimaryRoutes) + requirePeerSubnetRoutesWithCollect(c, peerStatus, expectedRoutes) + } +}, 5*time.Second, 200*time.Millisecond, "Verifying client status and routes") + +// INCORRECT: Bare external call without EventuallyWithT +status, err := client.Status() // ❌ Will fail intermittently +require.NoError(t, err) + +// CORRECT: Separate EventuallyWithT for different external calls +// First external call - headscale.ListNodes() +assert.EventuallyWithT(t, func(c *assert.CollectT) { + nodes, err := headscale.ListNodes() + assert.NoError(c, err) + assert.Len(c, nodes, 2) + requireNodeRouteCountWithCollect(c, nodes[0], 2, 2, 2) +}, 10*time.Second, 500*time.Millisecond, "route state changes should propagate to nodes") + +// Second external call - client.Status() +assert.EventuallyWithT(t, func(c *assert.CollectT) { + status, err := client.Status() + assert.NoError(c, err) + + for _, peerKey := range status.Peers() { + peerStatus := status.Peer[peerKey] + requirePeerSubnetRoutesWithCollect(c, peerStatus, []netip.Prefix{tsaddr.AllIPv4(), tsaddr.AllIPv6()}) + } +}, 10*time.Second, 500*time.Millisecond, "routes should be visible to client") + +// INCORRECT: Multiple unrelated external calls in same EventuallyWithT +assert.EventuallyWithT(t, func(c *assert.CollectT) { + nodes, err := headscale.ListNodes() // ❌ First external call + assert.NoError(c, err) + + status, err := client.Status() // ❌ Different external call - should be separate + assert.NoError(c, err) +}, 10*time.Second, 500*time.Millisecond, "mixed calls") + +// CORRECT: Variable scoping for shared data +var ( + srs1, srs2, srs3 *ipnstate.Status + clientStatus *ipnstate.Status + srs1PeerStatus *ipnstate.PeerStatus +) + +assert.EventuallyWithT(t, func(c *assert.CollectT) { + srs1 = subRouter1.MustStatus() // = not := + srs2 = subRouter2.MustStatus() + clientStatus = client.MustStatus() + + srs1PeerStatus = clientStatus.Peer[srs1.Self.PublicKey] + // assertions... +}, 5*time.Second, 200*time.Millisecond, "checking router status") + +// CORRECT: Wrapping client operations +assert.EventuallyWithT(t, func(c *assert.CollectT) { + result, err := client.Curl(weburl) + assert.NoError(c, err) + assert.Len(c, result, 13) +}, 5*time.Second, 200*time.Millisecond, "Verifying HTTP connectivity") + +assert.EventuallyWithT(t, func(c *assert.CollectT) { + tr, err := client.Traceroute(webip) + assert.NoError(c, err) + assertTracerouteViaIPWithCollect(c, tr, expectedRouter.MustIPv4()) +}, 5*time.Second, 200*time.Millisecond, "Verifying network path") +``` + +**Helper Functions**: + +- Use `requirePeerSubnetRoutesWithCollect` instead of `requirePeerSubnetRoutes` inside EventuallyWithT +- Use `requireNodeRouteCountWithCollect` instead of `requireNodeRouteCount` inside EventuallyWithT +- Use `assertTracerouteViaIPWithCollect` instead of `assertTracerouteViaIP` inside EventuallyWithT + +```go +// Node route checking by actual node properties, not array position +var routeNode *v1.Node +for _, node := range nodes { + if nodeIDStr := fmt.Sprintf("%d", node.GetId()); expectedRoutes[nodeIDStr] != "" { + routeNode = node + break + } +} +``` + +### Running Problematic Tests + +- Some tests require significant time (e.g., `TestNodeOnlineStatus` runs for 12 minutes) +- Infrastructure issues like disk space can cause test failures unrelated to code changes +- Use `--postgres` flag when testing database-heavy scenarios + +## Quality Assurance and Testing Requirements + +### **MANDATORY: Always Use Specialized Testing Agents** + +**CRITICAL REQUIREMENT**: For ANY task involving testing, quality assurance, review, or validation, you MUST use the appropriate specialized agent at the END of your task list. This ensures comprehensive quality validation and prevents regressions. + +**Required Agents for Different Task Types**: + +1. **Integration Testing**: Use `headscale-integration-tester` agent for: + - Running integration tests with `cmd/hi` + - Analyzing test failures and artifacts + - Troubleshooting Docker-based test infrastructure + - Validating end-to-end functionality changes + +2. **Quality Control**: Use `quality-control-enforcer` agent for: + - Code review and validation + - Ensuring best practices compliance + - Preventing common pitfalls and anti-patterns + - Validating architectural decisions + +**Agent Usage Pattern**: Always add the appropriate agent as the FINAL step in any task list to ensure quality validation occurs after all work is complete. + +### Integration Test Debugging Reference + +Test artifacts are preserved in `control_logs/TIMESTAMP-ID/` including: + +- Headscale server logs (stderr/stdout) +- Tailscale client logs and status +- Database dumps and network captures +- MapResponse JSON files for protocol debugging + +**For integration test issues, ALWAYS use the headscale-integration-tester agent - do not attempt manual debugging.** + +## EventuallyWithT Pattern for Integration Tests + +### Overview + +EventuallyWithT is a testing pattern used to handle eventual consistency in distributed systems. In Headscale integration tests, many operations are asynchronous - clients advertise routes, the server processes them, updates propagate through the network. EventuallyWithT allows tests to wait for these operations to complete while making assertions. + +### External Calls That Must Be Wrapped + +The following operations are **external calls** that interact with the headscale server or tailscale clients and MUST be wrapped in EventuallyWithT: + +- `headscale.ListNodes()` - Queries server state +- `client.Status()` - Gets client network status +- `client.Curl()` - Makes HTTP requests through the network +- `client.Traceroute()` - Performs network diagnostics +- `client.Execute()` when running commands that query state +- Any operation that reads from the headscale server or tailscale client + +### Operations That Must NOT Be Wrapped + +The following are **blocking operations** that modify state and should NOT be wrapped in EventuallyWithT: + +- `tailscale set` commands (e.g., `--advertise-routes`, `--exit-node`) +- Any command that changes configuration or state +- Use `client.MustStatus()` instead of `client.Status()` when you just need the ID for a blocking operation + +### Five Key Rules for EventuallyWithT + +1. **One External Call Per EventuallyWithT Block** + - Each EventuallyWithT should make ONE external call (e.g., ListNodes OR Status) + - Related assertions based on that single call can be grouped together + - Unrelated external calls must be in separate EventuallyWithT blocks + +2. **Variable Scoping** + - Declare variables that need to be shared across EventuallyWithT blocks at function scope + - Use `=` for assignment inside EventuallyWithT, not `:=` (unless the variable is only used within that block) + - Variables declared with `:=` inside EventuallyWithT are not accessible outside + +3. **No Nested EventuallyWithT** + - NEVER put an EventuallyWithT inside another EventuallyWithT + - This is a critical anti-pattern that must be avoided + +4. **Use CollectT for Assertions** + - Inside EventuallyWithT, use `assert` methods with the CollectT parameter + - Helper functions called within EventuallyWithT must accept `*assert.CollectT` + +5. **Descriptive Messages** + - Always provide a descriptive message as the last parameter + - Message should explain what condition is being waited for + +### Correct Pattern Examples + +```go +// CORRECT: Blocking operation NOT wrapped +for _, client := range allClients { + status := client.MustStatus() + command := []string{ + "tailscale", + "set", + "--advertise-routes=" + expectedRoutes[string(status.Self.ID)], + } + _, _, err = client.Execute(command) + require.NoErrorf(t, err, "failed to advertise route: %s", err) +} + +// CORRECT: Single external call with related assertions +var nodes []*v1.Node +assert.EventuallyWithT(t, func(c *assert.CollectT) { + nodes, err = headscale.ListNodes() + assert.NoError(c, err) + assert.Len(c, nodes, 2) + requireNodeRouteCountWithCollect(c, nodes[0], 2, 2, 2) +}, 10*time.Second, 500*time.Millisecond, "nodes should have expected route counts") + +// CORRECT: Separate EventuallyWithT for different external call +assert.EventuallyWithT(t, func(c *assert.CollectT) { + status, err := client.Status() + assert.NoError(c, err) + for _, peerKey := range status.Peers() { + peerStatus := status.Peer[peerKey] + requirePeerSubnetRoutesWithCollect(c, peerStatus, expectedPrefixes) + } +}, 10*time.Second, 500*time.Millisecond, "client should see expected routes") +``` + +### Incorrect Patterns to Avoid + +```go +// INCORRECT: Blocking operation wrapped in EventuallyWithT +assert.EventuallyWithT(t, func(c *assert.CollectT) { + status, err := client.Status() + assert.NoError(c, err) + + // This is a blocking operation - should NOT be in EventuallyWithT! + command := []string{ + "tailscale", + "set", + "--advertise-routes=" + expectedRoutes[string(status.Self.ID)], + } + _, _, err = client.Execute(command) + assert.NoError(c, err) +}, 5*time.Second, 200*time.Millisecond, "wrong pattern") + +// INCORRECT: Multiple unrelated external calls in same EventuallyWithT +assert.EventuallyWithT(t, func(c *assert.CollectT) { + // First external call + nodes, err := headscale.ListNodes() + assert.NoError(c, err) + assert.Len(c, nodes, 2) + + // Second unrelated external call - WRONG! + status, err := client.Status() + assert.NoError(c, err) + assert.NotNil(c, status) +}, 10*time.Second, 500*time.Millisecond, "mixed operations") +``` + +## Important Notes + +- **Dependencies**: Use `nix develop` for consistent toolchain (Go, buf, protobuf tools, linting) +- **Protocol Buffers**: Changes to `proto/` require `make generate` and should be committed separately +- **Code Style**: Enforced via golangci-lint with golines (width 88) and gofumpt formatting +- **Linting**: ALL code must pass `golangci-lint run --new-from-rev=upstream/main --timeout=5m --fix` before commit +- **Database**: Supports both SQLite (development) and PostgreSQL (production/testing) +- **Integration Tests**: Require Docker and can consume significant disk space - use headscale-integration-tester agent +- **Performance**: NodeStore optimizations are critical for scale - be careful with changes to state management +- **Quality Assurance**: Always use appropriate specialized agents for testing and validation tasks diff --git a/CLAUDE.md b/CLAUDE.md index d4034367..43c994c2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,531 +1 @@ -# CLAUDE.md - -This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. - -## Overview - -Headscale is an open-source implementation of the Tailscale control server written in Go. It provides self-hosted coordination for Tailscale networks (tailnets), managing node registration, IP allocation, policy enforcement, and DERP routing. - -## Development Commands - -### Quick Setup -```bash -# Recommended: Use Nix for dependency management -nix develop - -# Full development workflow -make dev # runs fmt + lint + test + build -``` - -### Essential Commands -```bash -# Build headscale binary -make build - -# Run tests -make test -go test ./... # All unit tests -go test -race ./... # With race detection - -# Run specific integration test -go run ./cmd/hi run "TestName" --postgres - -# Code formatting and linting -make fmt # Format all code (Go, docs, proto) -make lint # Lint all code (Go, proto) -make fmt-go # Format Go code only -make lint-go # Lint Go code only - -# Protocol buffer generation (after modifying proto/) -make generate - -# Clean build artifacts -make clean -``` - -### Integration Testing -```bash -# Use the hi (Headscale Integration) test runner -go run ./cmd/hi doctor # Check system requirements -go run ./cmd/hi run "TestPattern" # Run specific test -go run ./cmd/hi run "TestPattern" --postgres # With PostgreSQL backend - -# Test artifacts are saved to control_logs/ with logs and debug data -``` - -## Project Structure & Architecture - -### Top-Level Organization - -``` -headscale/ -├── cmd/ # Command-line applications -│ ├── headscale/ # Main headscale server binary -│ └── hi/ # Headscale Integration test runner -├── hscontrol/ # Core control plane logic -├── integration/ # End-to-end Docker-based tests -├── proto/ # Protocol buffer definitions -├── gen/ # Generated code (protobuf) -├── docs/ # Documentation -└── packaging/ # Distribution packaging -``` - -### Core Packages (`hscontrol/`) - -**Main Server (`hscontrol/`)** -- `app.go`: Application setup, dependency injection, server lifecycle -- `handlers.go`: HTTP/gRPC API endpoints for management operations -- `grpcv1.go`: gRPC service implementation for headscale API -- `poll.go`: **Critical** - Handles Tailscale MapRequest/MapResponse protocol -- `noise.go`: Noise protocol implementation for secure client communication -- `auth.go`: Authentication flows (web, OIDC, command-line) -- `oidc.go`: OpenID Connect integration for user authentication - -**State Management (`hscontrol/state/`)** -- `state.go`: Central coordinator for all subsystems (database, policy, IP allocation, DERP) -- `node_store.go`: **Performance-critical** - In-memory cache with copy-on-write semantics -- Thread-safe operations with deadlock detection -- Coordinates between database persistence and real-time operations - -**Database Layer (`hscontrol/db/`)** -- `db.go`: Database abstraction, GORM setup, migration management -- `node.go`: Node lifecycle, registration, expiration, IP assignment -- `users.go`: User management, namespace isolation -- `api_key.go`: API authentication tokens -- `preauth_keys.go`: Pre-authentication keys for automated node registration -- `ip.go`: IP address allocation and management -- `policy.go`: Policy storage and retrieval -- Schema migrations in `schema.sql` with extensive test data coverage - -**Policy Engine (`hscontrol/policy/`)** -- `policy.go`: Core ACL evaluation logic, HuJSON parsing -- `v2/`: Next-generation policy system with improved filtering -- `matcher/`: ACL rule matching and evaluation engine -- Determines peer visibility, route approval, and network access rules -- Supports both file-based and database-stored policies - -**Network Management (`hscontrol/`)** -- `derp/`: DERP (Designated Encrypted Relay for Packets) server implementation - - NAT traversal when direct connections fail - - Fallback relay for firewall-restricted environments -- `mapper/`: Converts internal Headscale state to Tailscale's wire protocol format - - `tail.go`: Tailscale-specific data structure generation -- `routes/`: Subnet route management and primary route selection -- `dns/`: DNS record management and MagicDNS implementation - -**Utilities & Support (`hscontrol/`)** -- `types/`: Core data structures, configuration, validation -- `util/`: Helper functions for networking, DNS, key management -- `templates/`: Client configuration templates (Apple, Windows, etc.) -- `notifier/`: Event notification system for real-time updates -- `metrics.go`: Prometheus metrics collection -- `capver/`: Tailscale capability version management - -### Key Subsystem Interactions - -**Node Registration Flow** -1. **Client Connection**: `noise.go` handles secure protocol handshake -2. **Authentication**: `auth.go` validates credentials (web/OIDC/preauth) -3. **State Creation**: `state.go` coordinates IP allocation via `db/ip.go` -4. **Storage**: `db/node.go` persists node, `NodeStore` caches in memory -5. **Network Setup**: `mapper/` generates initial Tailscale network map - -**Ongoing Operations** -1. **Poll Requests**: `poll.go` receives periodic client updates -2. **State Updates**: `NodeStore` maintains real-time node information -3. **Policy Application**: `policy/` evaluates ACL rules for peer relationships -4. **Map Distribution**: `mapper/` sends network topology to all affected clients - -**Route Management** -1. **Advertisement**: Clients announce routes via `poll.go` Hostinfo updates -2. **Storage**: `db/` persists routes, `NodeStore` caches for performance -3. **Approval**: `policy/` auto-approves routes based on ACL rules -4. **Distribution**: `routes/` selects primary routes, `mapper/` distributes to peers - -### Command-Line Tools (`cmd/`) - -**Main Server (`cmd/headscale/`)** -- `headscale.go`: CLI parsing, configuration loading, server startup -- Supports daemon mode, CLI operations (user/node management), database operations - -**Integration Test Runner (`cmd/hi/`)** -- `main.go`: Test execution framework with Docker orchestration -- `run.go`: Individual test execution with artifact collection -- `doctor.go`: System requirements validation -- `docker.go`: Container lifecycle management -- Essential for validating changes against real Tailscale clients - -### Generated & External Code - -**Protocol Buffers (`proto/` → `gen/`)** -- Defines gRPC API for headscale management operations -- Client libraries can generate from these definitions -- Run `make generate` after modifying `.proto` files - -**Integration Testing (`integration/`)** -- `scenario.go`: Docker test environment setup -- `tailscale.go`: Tailscale client container management -- Individual test files for specific functionality areas -- Real end-to-end validation with network isolation - -### Critical Performance Paths - -**High-Frequency Operations** -1. **MapRequest Processing** (`poll.go`): Every 15-60 seconds per client -2. **NodeStore Reads** (`node_store.go`): Every operation requiring node data -3. **Policy Evaluation** (`policy/`): On every peer relationship calculation -4. **Route Lookups** (`routes/`): During network map generation - -**Database Write Patterns** -- **Frequent**: Node heartbeats, endpoint updates, route changes -- **Moderate**: User operations, policy updates, API key management -- **Rare**: Schema migrations, bulk operations - -### Configuration & Deployment - -**Configuration** (`hscontrol/types/config.go`)** -- Database connection settings (SQLite/PostgreSQL) -- Network configuration (IP ranges, DNS settings) -- Policy mode (file vs database) -- DERP relay configuration -- OIDC provider settings - -**Key Dependencies** -- **GORM**: Database ORM with migration support -- **Tailscale Libraries**: Core networking and protocol code -- **Zerolog**: Structured logging throughout the application -- **Buf**: Protocol buffer toolchain for code generation - -### Development Workflow Integration - -The architecture supports incremental development: -- **Unit Tests**: Focus on individual packages (`*_test.go` files) -- **Integration Tests**: Validate cross-component interactions -- **Database Tests**: Extensive migration and data integrity validation -- **Policy Tests**: ACL rule evaluation and edge cases -- **Performance Tests**: NodeStore and high-frequency operation validation - -## Integration Testing System - -### Overview -Headscale uses Docker-based integration tests with real Tailscale clients to validate end-to-end functionality. The integration test system is complex and requires specialized knowledge for effective execution and debugging. - -### **MANDATORY: Use the headscale-integration-tester Agent** - -**CRITICAL REQUIREMENT**: For ANY integration test execution, analysis, troubleshooting, or validation, you MUST use the `headscale-integration-tester` agent. This agent contains specialized knowledge about: - -- Test execution strategies and timing requirements -- Infrastructure vs code issue distinction (99% vs 1% failure patterns) -- Security-critical debugging rules and forbidden practices -- Comprehensive artifact analysis workflows -- Real-world failure patterns from HA debugging experiences - -### Quick Reference Commands - -```bash -# Check system requirements (always run first) -go run ./cmd/hi doctor - -# Run single test (recommended for development) -go run ./cmd/hi run "TestName" - -# Use PostgreSQL for database-heavy tests -go run ./cmd/hi run "TestName" --postgres - -# Pattern matching for related tests -go run ./cmd/hi run "TestPattern*" -``` - -**Critical Notes**: -- Only ONE test can run at a time (Docker port conflicts) -- Tests generate ~100MB of logs per run in `control_logs/` -- Clean environment before each test: `rm -rf control_logs/202507* && docker system prune -f` - -### Test Artifacts Location -All test runs save comprehensive debugging artifacts to `control_logs/TIMESTAMP-ID/` including server logs, client logs, database dumps, MapResponse protocol data, and Prometheus metrics. - -**For all integration test work, use the headscale-integration-tester agent - it contains the complete knowledge needed for effective testing and debugging.** - -## NodeStore Implementation Details - -**Key Insight from Recent Work**: The NodeStore is a critical performance optimization that caches node data in memory while ensuring consistency with the database. When working with route advertisements or node state changes: - -1. **Timing Considerations**: Route advertisements need time to propagate from clients to server. Use `require.EventuallyWithT()` patterns in tests instead of immediate assertions. - -2. **Synchronization Points**: NodeStore updates happen at specific points like `poll.go:420` after Hostinfo changes. Ensure these are maintained when modifying the polling logic. - -3. **Peer Visibility**: The NodeStore's `peersFunc` determines which nodes are visible to each other. Policy-based filtering is separate from monitoring visibility - expired nodes should remain visible for debugging but marked as expired. - -## Testing Guidelines - -### Integration Test Patterns - -#### **CRITICAL: EventuallyWithT Pattern for External Calls** - -**All external calls in integration tests MUST be wrapped in EventuallyWithT blocks** to handle eventual consistency in distributed systems. External calls include: -- `client.Status()` - Getting Tailscale client status -- `client.Curl()` - Making HTTP requests through clients -- `client.Traceroute()` - Running network diagnostics -- `headscale.ListNodes()` - Querying headscale server state -- Any other calls that interact with external systems or network operations - -**Key Rules**: -1. **Never use bare `require.NoError(t, err)` with external calls** - Always wrap in EventuallyWithT -2. **Keep related assertions together** - If multiple assertions depend on the same external call, keep them in the same EventuallyWithT block -3. **Split unrelated external calls** - Different external calls should be in separate EventuallyWithT blocks -4. **Never nest EventuallyWithT calls** - Each EventuallyWithT should be at the same level -5. **Declare shared variables at function scope** - Variables used across multiple EventuallyWithT blocks must be declared before first use - -**Examples**: - -```go -// CORRECT: External call wrapped in EventuallyWithT -assert.EventuallyWithT(t, func(c *assert.CollectT) { - status, err := client.Status() - assert.NoError(c, err) - - // Related assertions using the same status call - for _, peerKey := range status.Peers() { - peerStatus := status.Peer[peerKey] - assert.NotNil(c, peerStatus.PrimaryRoutes) - requirePeerSubnetRoutesWithCollect(c, peerStatus, expectedRoutes) - } -}, 5*time.Second, 200*time.Millisecond, "Verifying client status and routes") - -// INCORRECT: Bare external call without EventuallyWithT -status, err := client.Status() // ❌ Will fail intermittently -require.NoError(t, err) - -// CORRECT: Separate EventuallyWithT for different external calls -// First external call - headscale.ListNodes() -assert.EventuallyWithT(t, func(c *assert.CollectT) { - nodes, err := headscale.ListNodes() - assert.NoError(c, err) - assert.Len(c, nodes, 2) - requireNodeRouteCountWithCollect(c, nodes[0], 2, 2, 2) -}, 10*time.Second, 500*time.Millisecond, "route state changes should propagate to nodes") - -// Second external call - client.Status() -assert.EventuallyWithT(t, func(c *assert.CollectT) { - status, err := client.Status() - assert.NoError(c, err) - - for _, peerKey := range status.Peers() { - peerStatus := status.Peer[peerKey] - requirePeerSubnetRoutesWithCollect(c, peerStatus, []netip.Prefix{tsaddr.AllIPv4(), tsaddr.AllIPv6()}) - } -}, 10*time.Second, 500*time.Millisecond, "routes should be visible to client") - -// INCORRECT: Multiple unrelated external calls in same EventuallyWithT -assert.EventuallyWithT(t, func(c *assert.CollectT) { - nodes, err := headscale.ListNodes() // ❌ First external call - assert.NoError(c, err) - - status, err := client.Status() // ❌ Different external call - should be separate - assert.NoError(c, err) -}, 10*time.Second, 500*time.Millisecond, "mixed calls") - -// CORRECT: Variable scoping for shared data -var ( - srs1, srs2, srs3 *ipnstate.Status - clientStatus *ipnstate.Status - srs1PeerStatus *ipnstate.PeerStatus -) - -assert.EventuallyWithT(t, func(c *assert.CollectT) { - srs1 = subRouter1.MustStatus() // = not := - srs2 = subRouter2.MustStatus() - clientStatus = client.MustStatus() - - srs1PeerStatus = clientStatus.Peer[srs1.Self.PublicKey] - // assertions... -}, 5*time.Second, 200*time.Millisecond, "checking router status") - -// CORRECT: Wrapping client operations -assert.EventuallyWithT(t, func(c *assert.CollectT) { - result, err := client.Curl(weburl) - assert.NoError(c, err) - assert.Len(c, result, 13) -}, 5*time.Second, 200*time.Millisecond, "Verifying HTTP connectivity") - -assert.EventuallyWithT(t, func(c *assert.CollectT) { - tr, err := client.Traceroute(webip) - assert.NoError(c, err) - assertTracerouteViaIPWithCollect(c, tr, expectedRouter.MustIPv4()) -}, 5*time.Second, 200*time.Millisecond, "Verifying network path") -``` - -**Helper Functions**: -- Use `requirePeerSubnetRoutesWithCollect` instead of `requirePeerSubnetRoutes` inside EventuallyWithT -- Use `requireNodeRouteCountWithCollect` instead of `requireNodeRouteCount` inside EventuallyWithT -- Use `assertTracerouteViaIPWithCollect` instead of `assertTracerouteViaIP` inside EventuallyWithT - -```go -// Node route checking by actual node properties, not array position -var routeNode *v1.Node -for _, node := range nodes { - if nodeIDStr := fmt.Sprintf("%d", node.GetId()); expectedRoutes[nodeIDStr] != "" { - routeNode = node - break - } -} -``` - -### Running Problematic Tests -- Some tests require significant time (e.g., `TestNodeOnlineStatus` runs for 12 minutes) -- Infrastructure issues like disk space can cause test failures unrelated to code changes -- Use `--postgres` flag when testing database-heavy scenarios - -## Quality Assurance and Testing Requirements - -### **MANDATORY: Always Use Specialized Testing Agents** - -**CRITICAL REQUIREMENT**: For ANY task involving testing, quality assurance, review, or validation, you MUST use the appropriate specialized agent at the END of your task list. This ensures comprehensive quality validation and prevents regressions. - -**Required Agents for Different Task Types**: - -1. **Integration Testing**: Use `headscale-integration-tester` agent for: - - Running integration tests with `cmd/hi` - - Analyzing test failures and artifacts - - Troubleshooting Docker-based test infrastructure - - Validating end-to-end functionality changes - -2. **Quality Control**: Use `quality-control-enforcer` agent for: - - Code review and validation - - Ensuring best practices compliance - - Preventing common pitfalls and anti-patterns - - Validating architectural decisions - -**Agent Usage Pattern**: Always add the appropriate agent as the FINAL step in any task list to ensure quality validation occurs after all work is complete. - -### Integration Test Debugging Reference - -Test artifacts are preserved in `control_logs/TIMESTAMP-ID/` including: -- Headscale server logs (stderr/stdout) -- Tailscale client logs and status -- Database dumps and network captures -- MapResponse JSON files for protocol debugging - -**For integration test issues, ALWAYS use the headscale-integration-tester agent - do not attempt manual debugging.** - -## EventuallyWithT Pattern for Integration Tests - -### Overview -EventuallyWithT is a testing pattern used to handle eventual consistency in distributed systems. In Headscale integration tests, many operations are asynchronous - clients advertise routes, the server processes them, updates propagate through the network. EventuallyWithT allows tests to wait for these operations to complete while making assertions. - -### External Calls That Must Be Wrapped -The following operations are **external calls** that interact with the headscale server or tailscale clients and MUST be wrapped in EventuallyWithT: -- `headscale.ListNodes()` - Queries server state -- `client.Status()` - Gets client network status -- `client.Curl()` - Makes HTTP requests through the network -- `client.Traceroute()` - Performs network diagnostics -- `client.Execute()` when running commands that query state -- Any operation that reads from the headscale server or tailscale client - -### Operations That Must NOT Be Wrapped -The following are **blocking operations** that modify state and should NOT be wrapped in EventuallyWithT: -- `tailscale set` commands (e.g., `--advertise-routes`, `--exit-node`) -- Any command that changes configuration or state -- Use `client.MustStatus()` instead of `client.Status()` when you just need the ID for a blocking operation - -### Five Key Rules for EventuallyWithT - -1. **One External Call Per EventuallyWithT Block** - - Each EventuallyWithT should make ONE external call (e.g., ListNodes OR Status) - - Related assertions based on that single call can be grouped together - - Unrelated external calls must be in separate EventuallyWithT blocks - -2. **Variable Scoping** - - Declare variables that need to be shared across EventuallyWithT blocks at function scope - - Use `=` for assignment inside EventuallyWithT, not `:=` (unless the variable is only used within that block) - - Variables declared with `:=` inside EventuallyWithT are not accessible outside - -3. **No Nested EventuallyWithT** - - NEVER put an EventuallyWithT inside another EventuallyWithT - - This is a critical anti-pattern that must be avoided - -4. **Use CollectT for Assertions** - - Inside EventuallyWithT, use `assert` methods with the CollectT parameter - - Helper functions called within EventuallyWithT must accept `*assert.CollectT` - -5. **Descriptive Messages** - - Always provide a descriptive message as the last parameter - - Message should explain what condition is being waited for - -### Correct Pattern Examples - -```go -// CORRECT: Blocking operation NOT wrapped -for _, client := range allClients { - status := client.MustStatus() - command := []string{ - "tailscale", - "set", - "--advertise-routes=" + expectedRoutes[string(status.Self.ID)], - } - _, _, err = client.Execute(command) - require.NoErrorf(t, err, "failed to advertise route: %s", err) -} - -// CORRECT: Single external call with related assertions -var nodes []*v1.Node -assert.EventuallyWithT(t, func(c *assert.CollectT) { - nodes, err = headscale.ListNodes() - assert.NoError(c, err) - assert.Len(c, nodes, 2) - requireNodeRouteCountWithCollect(c, nodes[0], 2, 2, 2) -}, 10*time.Second, 500*time.Millisecond, "nodes should have expected route counts") - -// CORRECT: Separate EventuallyWithT for different external call -assert.EventuallyWithT(t, func(c *assert.CollectT) { - status, err := client.Status() - assert.NoError(c, err) - for _, peerKey := range status.Peers() { - peerStatus := status.Peer[peerKey] - requirePeerSubnetRoutesWithCollect(c, peerStatus, expectedPrefixes) - } -}, 10*time.Second, 500*time.Millisecond, "client should see expected routes") -``` - -### Incorrect Patterns to Avoid - -```go -// INCORRECT: Blocking operation wrapped in EventuallyWithT -assert.EventuallyWithT(t, func(c *assert.CollectT) { - status, err := client.Status() - assert.NoError(c, err) - - // This is a blocking operation - should NOT be in EventuallyWithT! - command := []string{ - "tailscale", - "set", - "--advertise-routes=" + expectedRoutes[string(status.Self.ID)], - } - _, _, err = client.Execute(command) - assert.NoError(c, err) -}, 5*time.Second, 200*time.Millisecond, "wrong pattern") - -// INCORRECT: Multiple unrelated external calls in same EventuallyWithT -assert.EventuallyWithT(t, func(c *assert.CollectT) { - // First external call - nodes, err := headscale.ListNodes() - assert.NoError(c, err) - assert.Len(c, nodes, 2) - - // Second unrelated external call - WRONG! - status, err := client.Status() - assert.NoError(c, err) - assert.NotNil(c, status) -}, 10*time.Second, 500*time.Millisecond, "mixed operations") -``` - -## Important Notes - -- **Dependencies**: Use `nix develop` for consistent toolchain (Go, buf, protobuf tools, linting) -- **Protocol Buffers**: Changes to `proto/` require `make generate` and should be committed separately -- **Code Style**: Enforced via golangci-lint with golines (width 88) and gofumpt formatting -- **Database**: Supports both SQLite (development) and PostgreSQL (production/testing) -- **Integration Tests**: Require Docker and can consume significant disk space - use headscale-integration-tester agent -- **Performance**: NodeStore optimizations are critical for scale - be careful with changes to state management -- **Quality Assurance**: Always use appropriate specialized agents for testing and validation tasks -- **NEVER create gists in the user's name**: Do not use the `create_gist` tool - present information directly in the response instead +@AGENTS.md diff --git a/Makefile b/Makefile index d9b2c76b..9a5b8dfa 100644 --- a/Makefile +++ b/Makefile @@ -117,7 +117,7 @@ help: @echo "" @echo "Specific targets:" @echo " fmt-go - Format Go code only" - @echo " fmt-prettier - Format documentation only" + @echo " fmt-prettier - Format documentation only" @echo " fmt-proto - Format Protocol Buffer files only" @echo " lint-go - Lint Go code only" @echo " lint-proto - Lint Protocol Buffer files only" @@ -126,4 +126,4 @@ help: @echo " check-deps - Verify required tools are available" @echo "" @echo "Note: If not running in a nix shell, ensure dependencies are available:" - @echo " nix develop" \ No newline at end of file + @echo " nix develop" diff --git a/README.md b/README.md index 61a2c92c..dbde74d9 100644 --- a/README.md +++ b/README.md @@ -147,6 +147,7 @@ make build We recommend using Nix for dependency management to ensure you have all required tools. If you prefer to manage dependencies yourself, you can use Make directly: **With Nix (recommended):** + ```shell nix develop make test @@ -154,6 +155,7 @@ make build ``` **With your own dependencies:** + ```shell make test make build diff --git a/derp-example.yaml b/derp-example.yaml index 532475ef..ea93427c 100644 --- a/derp-example.yaml +++ b/derp-example.yaml @@ -1,6 +1,6 @@ # If you plan to somehow use headscale, please deploy your own DERP infra: https://tailscale.com/kb/1118/custom-derp-servers/ regions: - 1: null # Disable DERP region with ID 1 + 1: null # Disable DERP region with ID 1 900: regionid: 900 regioncode: custom diff --git a/docs/logo/headscale3-dots.svg b/docs/logo/headscale3-dots.svg index 6a20973c..f7120395 100644 --- a/docs/logo/headscale3-dots.svg +++ b/docs/logo/headscale3-dots.svg @@ -1 +1 @@ - \ No newline at end of file + diff --git a/docs/logo/headscale3_header_stacked_left.svg b/docs/logo/headscale3_header_stacked_left.svg index d00af00e..0c3702c6 100644 --- a/docs/logo/headscale3_header_stacked_left.svg +++ b/docs/logo/headscale3_header_stacked_left.svg @@ -1 +1 @@ - \ No newline at end of file + diff --git a/flake.nix b/flake.nix index f8eb6dd1..86f8b005 100644 --- a/flake.nix +++ b/flake.nix @@ -6,239 +6,246 @@ flake-utils.url = "github:numtide/flake-utils"; }; - outputs = { - self, - nixpkgs, - flake-utils, - ... - }: let - headscaleVersion = self.shortRev or self.dirtyShortRev; - commitHash = self.rev or self.dirtyRev; - in + outputs = + { self + , nixpkgs + , flake-utils + , ... + }: + let + headscaleVersion = self.shortRev or self.dirtyShortRev; + commitHash = self.rev or self.dirtyRev; + in { - overlay = _: prev: let - pkgs = nixpkgs.legacyPackages.${prev.system}; - buildGo = pkgs.buildGo125Module; - vendorHash = "sha256-VOi4PGZ8I+2MiwtzxpKc/4smsL5KcH/pHVkjJfAFPJ0="; - in { - headscale = buildGo { - pname = "headscale"; - version = headscaleVersion; - src = pkgs.lib.cleanSource self; + overlay = _: prev: + let + pkgs = nixpkgs.legacyPackages.${prev.system}; + buildGo = pkgs.buildGo125Module; + vendorHash = "sha256-VOi4PGZ8I+2MiwtzxpKc/4smsL5KcH/pHVkjJfAFPJ0="; + in + { + headscale = buildGo { + pname = "headscale"; + version = headscaleVersion; + src = pkgs.lib.cleanSource self; - # Only run unit tests when testing a build - checkFlags = ["-short"]; + # Only run unit tests when testing a build + checkFlags = [ "-short" ]; - # When updating go.mod or go.sum, a new sha will need to be calculated, - # update this if you have a mismatch after doing a change to those files. - inherit vendorHash; + # When updating go.mod or go.sum, a new sha will need to be calculated, + # update this if you have a mismatch after doing a change to those files. + inherit vendorHash; - subPackages = ["cmd/headscale"]; + subPackages = [ "cmd/headscale" ]; - ldflags = [ - "-s" - "-w" - "-X github.com/juanfont/headscale/hscontrol/types.Version=${headscaleVersion}" - "-X github.com/juanfont/headscale/hscontrol/types.GitCommitHash=${commitHash}" - ]; - }; - - hi = buildGo { - pname = "hi"; - version = headscaleVersion; - src = pkgs.lib.cleanSource self; - - checkFlags = ["-short"]; - inherit vendorHash; - - subPackages = ["cmd/hi"]; - }; - - protoc-gen-grpc-gateway = buildGo rec { - pname = "grpc-gateway"; - version = "2.24.0"; - - src = pkgs.fetchFromGitHub { - owner = "grpc-ecosystem"; - repo = "grpc-gateway"; - rev = "v${version}"; - sha256 = "sha256-lUEoqXJF1k4/il9bdDTinkUV5L869njZNYqObG/mHyA="; + ldflags = [ + "-s" + "-w" + "-X github.com/juanfont/headscale/hscontrol/types.Version=${headscaleVersion}" + "-X github.com/juanfont/headscale/hscontrol/types.GitCommitHash=${commitHash}" + ]; }; - vendorHash = "sha256-Ttt7bPKU+TMKRg5550BS6fsPwYp0QJqcZ7NLrhttSdw="; + hi = buildGo { + pname = "hi"; + version = headscaleVersion; + src = pkgs.lib.cleanSource self; - nativeBuildInputs = [pkgs.installShellFiles]; + checkFlags = [ "-short" ]; + inherit vendorHash; - subPackages = ["protoc-gen-grpc-gateway" "protoc-gen-openapiv2"]; - }; - - protobuf-language-server = buildGo rec { - pname = "protobuf-language-server"; - version = "2546944"; - - src = pkgs.fetchFromGitHub { - owner = "lasorda"; - repo = "protobuf-language-server"; - rev = "${version}"; - sha256 = "sha256-Cbr3ktT86RnwUntOiDKRpNTClhdyrKLTQG2ZEd6fKDc="; + subPackages = [ "cmd/hi" ]; }; - vendorHash = "sha256-PfT90dhfzJZabzLTb1D69JCO+kOh2khrlpF5mCDeypk="; + protoc-gen-grpc-gateway = buildGo rec { + pname = "grpc-gateway"; + version = "2.24.0"; - subPackages = ["."]; + src = pkgs.fetchFromGitHub { + owner = "grpc-ecosystem"; + repo = "grpc-gateway"; + rev = "v${version}"; + sha256 = "sha256-lUEoqXJF1k4/il9bdDTinkUV5L869njZNYqObG/mHyA="; + }; + + vendorHash = "sha256-Ttt7bPKU+TMKRg5550BS6fsPwYp0QJqcZ7NLrhttSdw="; + + nativeBuildInputs = [ pkgs.installShellFiles ]; + + subPackages = [ "protoc-gen-grpc-gateway" "protoc-gen-openapiv2" ]; + }; + + protobuf-language-server = buildGo rec { + pname = "protobuf-language-server"; + version = "2546944"; + + src = pkgs.fetchFromGitHub { + owner = "lasorda"; + repo = "protobuf-language-server"; + rev = "${version}"; + sha256 = "sha256-Cbr3ktT86RnwUntOiDKRpNTClhdyrKLTQG2ZEd6fKDc="; + }; + + vendorHash = "sha256-PfT90dhfzJZabzLTb1D69JCO+kOh2khrlpF5mCDeypk="; + + subPackages = [ "." ]; + }; + + # Upstream does not override buildGoModule properly, + # importing a specific module, so comment out for now. + # golangci-lint = prev.golangci-lint.override { + # buildGoModule = buildGo; + # }; + # golangci-lint-langserver = prev.golangci-lint.override { + # buildGoModule = buildGo; + # }; + + # The package uses buildGo125Module, not the convention. + # goreleaser = prev.goreleaser.override { + # buildGoModule = buildGo; + # }; + + gotestsum = prev.gotestsum.override { + buildGoModule = buildGo; + }; + + gotests = prev.gotests.override { + buildGoModule = buildGo; + }; + + gofumpt = prev.gofumpt.override { + buildGoModule = buildGo; + }; + + # gopls = prev.gopls.override { + # buildGoModule = buildGo; + # }; }; - - # Upstream does not override buildGoModule properly, - # importing a specific module, so comment out for now. - # golangci-lint = prev.golangci-lint.override { - # buildGoModule = buildGo; - # }; - # golangci-lint-langserver = prev.golangci-lint.override { - # buildGoModule = buildGo; - # }; - - # The package uses buildGo125Module, not the convention. - # goreleaser = prev.goreleaser.override { - # buildGoModule = buildGo; - # }; - - gotestsum = prev.gotestsum.override { - buildGoModule = buildGo; - }; - - gotests = prev.gotests.override { - buildGoModule = buildGo; - }; - - gofumpt = prev.gofumpt.override { - buildGoModule = buildGo; - }; - - # gopls = prev.gopls.override { - # buildGoModule = buildGo; - # }; - }; } // flake-utils.lib.eachDefaultSystem - (system: let - pkgs = import nixpkgs { - overlays = [self.overlay]; - inherit system; - }; - buildDeps = with pkgs; [git go_1_25 gnumake]; - devDeps = with pkgs; - buildDeps - ++ [ - golangci-lint - golangci-lint-langserver - golines - nodePackages.prettier - goreleaser - nfpm - gotestsum - gotests - gofumpt - gopls - ksh - ko - yq-go - ripgrep - postgresql - - # 'dot' is needed for pprof graphs - # go tool pprof -http=: - graphviz - - # Protobuf dependencies - protobuf - protoc-gen-go - protoc-gen-go-grpc - protoc-gen-grpc-gateway - buf - clang-tools # clang-format - protobuf-language-server - - # Add hi to make it even easier to use ci runner. - hi - ] - ++ lib.optional pkgs.stdenv.isLinux [traceroute]; - - # Add entry to build a docker image with headscale - # caveat: only works on Linux - # - # Usage: - # nix build .#headscale-docker - # docker load < result - headscale-docker = pkgs.dockerTools.buildLayeredImage { - name = "headscale"; - tag = headscaleVersion; - contents = [pkgs.headscale]; - config.Entrypoint = [(pkgs.headscale + "/bin/headscale")]; - }; - in rec { - # `nix develop` - devShell = pkgs.mkShell { - buildInputs = - devDeps + (system: + let + pkgs = import nixpkgs { + overlays = [ self.overlay ]; + inherit system; + }; + buildDeps = with pkgs; [ git go_1_25 gnumake ]; + devDeps = with pkgs; + buildDeps ++ [ - (pkgs.writeShellScriptBin - "nix-vendor-sri" - '' - set -eu + golangci-lint + golangci-lint-langserver + golines + nodePackages.prettier + nixpkgs-fmt + goreleaser + nfpm + gotestsum + gotests + gofumpt + gopls + ksh + ko + yq-go + ripgrep + postgresql + prek - OUT=$(mktemp -d -t nar-hash-XXXXXX) - rm -rf "$OUT" + # 'dot' is needed for pprof graphs + # go tool pprof -http=: + graphviz - go mod vendor -o "$OUT" - go run tailscale.com/cmd/nardump --sri "$OUT" - rm -rf "$OUT" - '') + # Protobuf dependencies + protobuf + protoc-gen-go + protoc-gen-go-grpc + protoc-gen-grpc-gateway + buf + clang-tools # clang-format + protobuf-language-server - (pkgs.writeShellScriptBin - "go-mod-update-all" - '' - cat go.mod | ${pkgs.silver-searcher}/bin/ag "\t" | ${pkgs.silver-searcher}/bin/ag -v indirect | ${pkgs.gawk}/bin/awk '{print $1}' | ${pkgs.findutils}/bin/xargs go get -u - go mod tidy - '') - ]; + # Add hi to make it even easier to use ci runner. + hi + ] + ++ lib.optional pkgs.stdenv.isLinux [ traceroute ]; - shellHook = '' - export PATH="$PWD/result/bin:$PATH" - ''; - }; + # Add entry to build a docker image with headscale + # caveat: only works on Linux + # + # Usage: + # nix build .#headscale-docker + # docker load < result + headscale-docker = pkgs.dockerTools.buildLayeredImage { + name = "headscale"; + tag = headscaleVersion; + contents = [ pkgs.headscale ]; + config.Entrypoint = [ (pkgs.headscale + "/bin/headscale") ]; + }; + in + rec { + # `nix develop` + devShell = pkgs.mkShell { + buildInputs = + devDeps + ++ [ + (pkgs.writeShellScriptBin + "nix-vendor-sri" + '' + set -eu - # `nix build` - packages = with pkgs; { - inherit headscale; - inherit headscale-docker; - }; - defaultPackage = pkgs.headscale; + OUT=$(mktemp -d -t nar-hash-XXXXXX) + rm -rf "$OUT" - # `nix run` - apps.headscale = flake-utils.lib.mkApp { - drv = packages.headscale; - }; - apps.default = apps.headscale; + go mod vendor -o "$OUT" + go run tailscale.com/cmd/nardump --sri "$OUT" + rm -rf "$OUT" + '') - checks = { - format = - pkgs.runCommand "check-format" - { - buildInputs = with pkgs; [ - gnumake - nixpkgs-fmt - golangci-lint - nodePackages.prettier - golines - clang-tools + (pkgs.writeShellScriptBin + "go-mod-update-all" + '' + cat go.mod | ${pkgs.silver-searcher}/bin/ag "\t" | ${pkgs.silver-searcher}/bin/ag -v indirect | ${pkgs.gawk}/bin/awk '{print $1}' | ${pkgs.findutils}/bin/xargs go get -u + go mod tidy + '') ]; - } '' - ${pkgs.nixpkgs-fmt}/bin/nixpkgs-fmt ${./.} - ${pkgs.golangci-lint}/bin/golangci-lint run --fix --timeout 10m - ${pkgs.nodePackages.prettier}/bin/prettier --write '**/**.{ts,js,md,yaml,yml,sass,css,scss,html}' - ${pkgs.golines}/bin/golines --max-len=88 --base-formatter=gofumpt -w ${./.} - ${pkgs.clang-tools}/bin/clang-format -i ${./.} + + shellHook = '' + export PATH="$PWD/result/bin:$PATH" ''; - }; - }); + }; + + # `nix build` + packages = with pkgs; { + inherit headscale; + inherit headscale-docker; + }; + defaultPackage = pkgs.headscale; + + # `nix run` + apps.headscale = flake-utils.lib.mkApp { + drv = packages.headscale; + }; + apps.default = apps.headscale; + + checks = { + format = + pkgs.runCommand "check-format" + { + buildInputs = with pkgs; [ + gnumake + nixpkgs-fmt + golangci-lint + nodePackages.prettier + golines + clang-tools + ]; + } '' + ${pkgs.nixpkgs-fmt}/bin/nixpkgs-fmt ${./.} + ${pkgs.golangci-lint}/bin/golangci-lint run --fix --timeout 10m + ${pkgs.nodePackages.prettier}/bin/prettier --write '**/**.{ts,js,md,yaml,yml,sass,css,scss,html}' + ${pkgs.golines}/bin/golines --max-len=88 --base-formatter=gofumpt -w ${./.} + ${pkgs.clang-tools}/bin/clang-format -i ${./.} + ''; + }; + }); } diff --git a/integration/auth_key_test.go b/integration/auth_key_test.go index 75106dc5..12a5bf67 100644 --- a/integration/auth_key_test.go +++ b/integration/auth_key_test.go @@ -455,4 +455,3 @@ func TestAuthKeyLogoutAndReloginSameUserExpiredKey(t *testing.T) { }) } } - From 299cef4e996fbaced5408883b63a794133112e49 Mon Sep 17 00:00:00 2001 From: Andrey Bobelev Date: Tue, 28 Oct 2025 11:19:14 +0200 Subject: [PATCH 002/148] fix: free ips from usedIps ipset on DeleteNode --- hscontrol/db/ip.go | 9 +++++++++ hscontrol/state/state.go | 2 ++ 2 files changed, 11 insertions(+) diff --git a/hscontrol/db/ip.go b/hscontrol/db/ip.go index 244bb3db..972d8e72 100644 --- a/hscontrol/db/ip.go +++ b/hscontrol/db/ip.go @@ -341,3 +341,12 @@ func (db *HSDatabase) BackfillNodeIPs(i *IPAllocator) ([]string, error) { return ret, err } + +func (i *IPAllocator) FreeIPs(ips []netip.Addr) { + i.mu.Lock() + defer i.mu.Unlock() + + for _, ip := range ips { + i.usedIPs.Remove(ip) + } +} diff --git a/hscontrol/state/state.go b/hscontrol/state/state.go index 297004fc..6ef11f54 100644 --- a/hscontrol/state/state.go +++ b/hscontrol/state/state.go @@ -429,6 +429,8 @@ func (s *State) DeleteNode(node types.NodeView) (change.ChangeSet, error) { return change.EmptySet, err } + s.ipAlloc.FreeIPs(node.IPs()) + c := change.NodeRemoved(node.ID()) // Check if policy manager needs updating after node deletion From 1dcb04ce9b2f98f5aaa8fd361d4e3d9abd682027 Mon Sep 17 00:00:00 2001 From: Kristoffer Dalby Date: Tue, 11 Nov 2025 22:00:39 +0100 Subject: [PATCH 003/148] changelog: add changelog entry Signed-off-by: Kristoffer Dalby --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7669dfcb..b25c80ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ ### Changes +- Reclaim IPs from the IP allocator when nodes are deleted + [#2831](https://github.com/juanfont/headscale/pull/2831) + ## 0.27.1 (2025-11-11) **Minimum supported Tailscale client version: v1.64.0** From 218a8db1b901cc6c7b777c5855c01b15154d932e Mon Sep 17 00:00:00 2001 From: Teej <107083710+TeejMcSteez@users.noreply.github.com> Date: Tue, 11 Nov 2025 22:46:57 -0500 Subject: [PATCH 004/148] add favicon to webpages (#2858) Co-authored-by: TeejMcSteez Co-authored-by: Kristoffer Dalby --- CHANGELOG.md | 3 ++- hscontrol/app.go | 4 ++-- hscontrol/assets/favicon.png | Bin 0 -> 22340 bytes hscontrol/handlers.go | 33 ++++++++++++++++++++++++++++++--- hscontrol/templates/general.go | 4 ++++ swagger.go | 5 ++++- 6 files changed, 42 insertions(+), 7 deletions(-) create mode 100644 hscontrol/assets/favicon.png diff --git a/CHANGELOG.md b/CHANGELOG.md index b25c80ee..9129c526 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ ### Changes +- Add favicon to webpages + [#2858](https://github.com/juanfont/headscale/pull/2858) - Reclaim IPs from the IP allocator when nodes are deleted [#2831](https://github.com/juanfont/headscale/pull/2831) @@ -138,7 +140,6 @@ the code base over time and make it more correct and efficient. starting/ending with hyphen are rejected ### Changes - - **Database schema migration improvements for SQLite** [#2617](https://github.com/juanfont/headscale/pull/2617) - **IMPORTANT: Backup your SQLite database before upgrading** diff --git a/hscontrol/app.go b/hscontrol/app.go index eb5528ba..4ce98719 100644 --- a/hscontrol/app.go +++ b/hscontrol/app.go @@ -476,8 +476,8 @@ func (h *Headscale) createRouter(grpcMux *grpcRuntime.ServeMux) *mux.Router { apiRouter := router.PathPrefix("/api").Subrouter() apiRouter.Use(h.httpAuthenticationMiddleware) apiRouter.PathPrefix("/v1/").HandlerFunc(grpcMux.ServeHTTP) - - router.PathPrefix("/").HandlerFunc(notFoundHandler) + router.HandleFunc("/favicon.ico", FaviconHandler) + router.PathPrefix("/").HandlerFunc(BlankHandler) return router } diff --git a/hscontrol/assets/favicon.png b/hscontrol/assets/favicon.png new file mode 100644 index 0000000000000000000000000000000000000000..4989810faa546554d0e8a494ce8b980816c46b54 GIT binary patch literal 22340 zcmdqJWmr{T7$1nHJgy1P4-Zcvaer9)b2B!#=qf9B5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n}n`{)21~0Rb#k*QTU`h+}A|I4zemakvhBj#34E!)Qp4de44M! zetr#_#Jc{GKIT}GB+?&)Q9k43wQ7EGB=qq|r%Df$Y`a`COp0R#6}Q{rpTIL?a&i)Z z84!XeBjeD0=E{%Z&{xTFc-Gnq=X{Bg3o_79W><70Q2BuN#24o^-&P(nlmL!7PX|M9EFk0 zM~Xg-&I-yf=y;~PmJOPR6~bAM{#-=#Ij{xu{o;SWk=EZ&ZedJ}Q8zQC#XcSQ*h{W| z#bytNoJ~@M%i~^}Eotcqdzic2vgv|&;6VKQsVza07hJXm_8Ya_FKh%Bhc&bNgAzuK zqV7C`IAB*19GbE64Zqjpum;@!hp)BG0DAxlpbf4|#q-kQ6AmxL3W+m!{7%UOz5@9w za0fIcTpcaZ(8xPi{>+&&=Y~&wYWMs{RO*Awy#M3y)HSYAq_W!OMk!xNzC|55coa{y H^o;*2r@Ea? literal 0 HcmV?d00001 diff --git a/hscontrol/handlers.go b/hscontrol/handlers.go index 0cc5bd36..d52b4d50 100644 --- a/hscontrol/handlers.go +++ b/hscontrol/handlers.go @@ -1,6 +1,8 @@ package hscontrol import ( + "bytes" + _ "embed" "encoding/json" "errors" "fmt" @@ -8,6 +10,7 @@ import ( "net/http" "strconv" "strings" + "time" "github.com/chasefleming/elem-go/styles" "github.com/gorilla/mux" @@ -98,6 +101,7 @@ func (h *Headscale) handleVerifyRequest( // Check if any node has the requested NodeKey var nodeKeyFound bool + for _, node := range nodes.All() { if node.NodeKey() == derpAdmitClientRequest.NodePublic { nodeKeyFound = true @@ -128,6 +132,7 @@ func (h *Headscale) VerifyHandler( httpError(writer, err) return } + writer.Header().Set("Content-Type", "application/json") } @@ -149,6 +154,7 @@ func (h *Headscale) KeyHandler( resp := tailcfg.OverTLSPublicKeyResponse{ PublicKey: h.noisePrivateKey.Public(), } + writer.Header().Set("Content-Type", "application/json") json.NewEncoder(writer).Encode(resp) @@ -171,13 +177,14 @@ func (h *Headscale) HealthHandler( if err != nil { writer.WriteHeader(http.StatusInternalServerError) + res.Status = "fail" } json.NewEncoder(writer).Encode(res) } - - if err := h.state.PingDB(req.Context()); err != nil { + err := h.state.PingDB(req.Context()) + if err != nil { respond(err) return @@ -192,6 +199,7 @@ func (h *Headscale) RobotsHandler( ) { writer.Header().Set("Content-Type", "text/plain") writer.WriteHeader(http.StatusOK) + _, err := writer.Write([]byte("User-agent: *\nDisallow: /")) if err != nil { log.Error(). @@ -211,7 +219,8 @@ func (h *Headscale) VersionHandler( writer.WriteHeader(http.StatusOK) versionInfo := types.GetVersionInfo() - if err := json.NewEncoder(writer).Encode(versionInfo); err != nil { + err := json.NewEncoder(writer).Encode(versionInfo) + if err != nil { log.Error(). Caller(). Err(err). @@ -268,3 +277,21 @@ func (a *AuthProviderWeb) RegisterHandler( writer.WriteHeader(http.StatusOK) writer.Write([]byte(templates.RegisterWeb(registrationId).Render())) } + +//go:embed assets/favicon.png +var favicon []byte + +func FaviconHandler(writer http.ResponseWriter, req *http.Request) { + writer.Header().Set("Content-Type", "image/png") + http.ServeContent(writer, req, "favicon.ico", time.Unix(0, 0), bytes.NewReader(favicon)) +} + +// Returns a blank page with favicon linked. +func BlankHandler(writer http.ResponseWriter, res *http.Request) { + writer.Header().Set("Content-Type", "text/html; charset=utf-8") + io.WriteString(writer, ` + + + + `) +} diff --git a/hscontrol/templates/general.go b/hscontrol/templates/general.go index 3728b736..6e2af390 100644 --- a/hscontrol/templates/general.go +++ b/hscontrol/templates/general.go @@ -49,6 +49,10 @@ func HtmlStructure(head, body *elem.Element) *elem.Element { attrs.Name: "viewport", attrs.Content: "width=device-width, initial-scale=1.0", }), + elem.Link(attrs.Props{ + attrs.Rel: "icon", + attrs.Href: "/favicon.ico", + }), head, ), body, diff --git a/swagger.go b/swagger.go index 306fc1f6..fa764568 100644 --- a/swagger.go +++ b/swagger.go @@ -20,7 +20,7 @@ func SwaggerUI( - + @@ -57,6 +57,7 @@ func SwaggerUI( writer.Header().Set("Content-Type", "text/plain; charset=utf-8") writer.WriteHeader(http.StatusInternalServerError) + _, err := writer.Write([]byte("Could not render Swagger")) if err != nil { log.Error(). @@ -70,6 +71,7 @@ func SwaggerUI( writer.Header().Set("Content-Type", "text/html; charset=utf-8") writer.WriteHeader(http.StatusOK) + _, err := writer.Write(payload.Bytes()) if err != nil { log.Error(). @@ -85,6 +87,7 @@ func SwaggerAPIv1( ) { writer.Header().Set("Content-Type", "application/json; charset=utf-8") writer.WriteHeader(http.StatusOK) + if _, err := writer.Write(apiV1JSON); err != nil { log.Error(). Caller(). From 000d5c3b0c3f91761c326eddae93c404f2676dd1 Mon Sep 17 00:00:00 2001 From: Kristoffer Dalby Date: Wed, 12 Nov 2025 06:59:43 -0600 Subject: [PATCH 005/148] prettier: use standard config for all files including changelog (#2879) --- .pre-commit-config.yaml | 8 - CHANGELOG.md | 597 ++++++++++++++-------------------------- Makefile | 1 - 3 files changed, 200 insertions(+), 406 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 4d98d4d3..77ffe299 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -57,14 +57,6 @@ repos: sass, markdown, ] - exclude: ^CHANGELOG\.md$ - - # Prettier for CHANGELOG.md with special formatting - - id: prettier-changelog - name: prettier-changelog - entry: prettier --write --print-width 80 --prose-wrap always - language: system - files: ^CHANGELOG\.md$ # golangci-lint for Go code quality - id: golangci-lint diff --git a/CHANGELOG.md b/CHANGELOG.md index 9129c526..1e43192e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ### Changes +- Add NixOS module in repository for faster iteration [#2857](https://github.com/juanfont/headscale/pull/2857) - Add favicon to webpages [#2858](https://github.com/juanfont/headscale/pull/2858) - Reclaim IPs from the IP allocator when nodes are deleted @@ -15,31 +16,18 @@ ### Changes -- Expire nodes with a custom timestamp - [#2828](https://github.com/juanfont/headscale/pull/2828) -- Fix issue where node expiry was reset when tailscaled restarts - [#2875](https://github.com/juanfont/headscale/pull/2875) -- Fix OIDC authentication when multiple login URLs are opened - [#2861](https://github.com/juanfont/headscale/pull/2861) -- Fix node re-registration failing with expired auth keys - [#2859](https://github.com/juanfont/headscale/pull/2859) -- Remove old unused database tables and indices - [#2844](https://github.com/juanfont/headscale/pull/2844) - [#2872](https://github.com/juanfont/headscale/pull/2872) -- Ignore litestream tables during database validation - [#2843](https://github.com/juanfont/headscale/pull/2843) -- Fix exit node visibility to respect ACL rules - [#2855](https://github.com/juanfont/headscale/pull/2855) -- Fix SSH policy becoming empty when unknown user is referenced - [#2874](https://github.com/juanfont/headscale/pull/2874) -- Fix policy validation when using bypass-grpc mode - [#2854](https://github.com/juanfont/headscale/pull/2854) -- Fix autogroup:self interaction with other ACL rules - [#2842](https://github.com/juanfont/headscale/pull/2842) -- Fix flaky DERP map shuffle test - [#2848](https://github.com/juanfont/headscale/pull/2848) -- Use current stable base images for Debian and Alpine containers - [#2827](https://github.com/juanfont/headscale/pull/2827) +- Expire nodes with a custom timestamp [#2828](https://github.com/juanfont/headscale/pull/2828) +- Fix issue where node expiry was reset when tailscaled restarts [#2875](https://github.com/juanfont/headscale/pull/2875) +- Fix OIDC authentication when multiple login URLs are opened [#2861](https://github.com/juanfont/headscale/pull/2861) +- Fix node re-registration failing with expired auth keys [#2859](https://github.com/juanfont/headscale/pull/2859) +- Remove old unused database tables and indices [#2844](https://github.com/juanfont/headscale/pull/2844) [#2872](https://github.com/juanfont/headscale/pull/2872) +- Ignore litestream tables during database validation [#2843](https://github.com/juanfont/headscale/pull/2843) +- Fix exit node visibility to respect ACL rules [#2855](https://github.com/juanfont/headscale/pull/2855) +- Fix SSH policy becoming empty when unknown user is referenced [#2874](https://github.com/juanfont/headscale/pull/2874) +- Fix policy validation when using bypass-grpc mode [#2854](https://github.com/juanfont/headscale/pull/2854) +- Fix autogroup:self interaction with other ACL rules [#2842](https://github.com/juanfont/headscale/pull/2842) +- Fix flaky DERP map shuffle test [#2848](https://github.com/juanfont/headscale/pull/2848) +- Use current stable base images for Debian and Alpine containers [#2827](https://github.com/juanfont/headscale/pull/2827) ## 0.27.0 (2025-10-27) @@ -119,12 +107,9 @@ the code base over time and make it more correct and efficient. ### BREAKING -- Remove support for 32-bit binaries - [#2692](https://github.com/juanfont/headscale/pull/2692) -- Policy: Zero or empty destination port is no longer allowed - [#2606](https://github.com/juanfont/headscale/pull/2606) -- Stricter hostname validation - [#2383](https://github.com/juanfont/headscale/pull/2383) +- Remove support for 32-bit binaries [#2692](https://github.com/juanfont/headscale/pull/2692) +- Policy: Zero or empty destination port is no longer allowed [#2606](https://github.com/juanfont/headscale/pull/2606) +- Stricter hostname validation [#2383](https://github.com/juanfont/headscale/pull/2383) - Hostnames must be valid DNS labels (2-63 characters, alphanumeric and hyphens only, cannot start/end with hyphen) - **Client Registration (New Nodes)**: Invalid hostnames are automatically @@ -140,53 +125,39 @@ the code base over time and make it more correct and efficient. starting/ending with hyphen are rejected ### Changes -- **Database schema migration improvements for SQLite** - [#2617](https://github.com/juanfont/headscale/pull/2617) + +- **Database schema migration improvements for SQLite** [#2617](https://github.com/juanfont/headscale/pull/2617) - **IMPORTANT: Backup your SQLite database before upgrading** - Introduces safer table renaming migration strategy - Addresses longstanding database integrity issues -- Add flag to directly manipulate the policy in the database - [#2765](https://github.com/juanfont/headscale/pull/2765) -- DERPmap update frequency default changed from 24h to 3h - [#2741](https://github.com/juanfont/headscale/pull/2741) +- Add flag to directly manipulate the policy in the database [#2765](https://github.com/juanfont/headscale/pull/2765) +- DERPmap update frequency default changed from 24h to 3h [#2741](https://github.com/juanfont/headscale/pull/2741) - DERPmap update mechanism has been improved with retry, and is now failing conservatively, preserving the old map upon failure. [#2741](https://github.com/juanfont/headscale/pull/2741) -- Add support for `autogroup:member`, `autogroup:tagged` - [#2572](https://github.com/juanfont/headscale/pull/2572) -- Fix bug where return routes were being removed by policy - [#2767](https://github.com/juanfont/headscale/pull/2767) +- Add support for `autogroup:member`, `autogroup:tagged` [#2572](https://github.com/juanfont/headscale/pull/2572) +- Fix bug where return routes were being removed by policy [#2767](https://github.com/juanfont/headscale/pull/2767) - Remove policy v1 code [#2600](https://github.com/juanfont/headscale/pull/2600) -- Refactor Debian/Ubuntu packaging and drop support for Ubuntu 20.04. - [#2614](https://github.com/juanfont/headscale/pull/2614) -- Remove redundant check regarding `noise` config - [#2658](https://github.com/juanfont/headscale/pull/2658) -- Refactor OpenID Connect documentation - [#2625](https://github.com/juanfont/headscale/pull/2625) -- Don't crash if config file is missing - [#2656](https://github.com/juanfont/headscale/pull/2656) -- Adds `/robots.txt` endpoint to avoid crawlers - [#2643](https://github.com/juanfont/headscale/pull/2643) -- OIDC: Use group claim from UserInfo - [#2663](https://github.com/juanfont/headscale/pull/2663) +- Refactor Debian/Ubuntu packaging and drop support for Ubuntu 20.04. [#2614](https://github.com/juanfont/headscale/pull/2614) +- Remove redundant check regarding `noise` config [#2658](https://github.com/juanfont/headscale/pull/2658) +- Refactor OpenID Connect documentation [#2625](https://github.com/juanfont/headscale/pull/2625) +- Don't crash if config file is missing [#2656](https://github.com/juanfont/headscale/pull/2656) +- Adds `/robots.txt` endpoint to avoid crawlers [#2643](https://github.com/juanfont/headscale/pull/2643) +- OIDC: Use group claim from UserInfo [#2663](https://github.com/juanfont/headscale/pull/2663) - OIDC: Update user with claims from UserInfo _before_ comparing with allowed groups, email and domain [#2663](https://github.com/juanfont/headscale/pull/2663) - Policy will now reject invalid fields, making it easier to spot spelling errors [#2764](https://github.com/juanfont/headscale/pull/2764) -- Add FAQ entry on how to recover from an invalid policy in the database - [#2776](https://github.com/juanfont/headscale/pull/2776) -- EXPERIMENTAL: Add support for `autogroup:self` - [#2789](https://github.com/juanfont/headscale/pull/2789) -- Add healthcheck command - [#2659](https://github.com/juanfont/headscale/pull/2659) +- Add FAQ entry on how to recover from an invalid policy in the database [#2776](https://github.com/juanfont/headscale/pull/2776) +- EXPERIMENTAL: Add support for `autogroup:self` [#2789](https://github.com/juanfont/headscale/pull/2789) +- Add healthcheck command [#2659](https://github.com/juanfont/headscale/pull/2659) ## 0.26.1 (2025-06-06) ### Changes -- Ensure nodes are matching both node key and machine key when connecting. - [#2642](https://github.com/juanfont/headscale/pull/2642) +- Ensure nodes are matching both node key and machine key when connecting. [#2642](https://github.com/juanfont/headscale/pull/2642) ## 0.26.0 (2025-05-14) @@ -220,12 +191,9 @@ ID | Hostname | Approved | Available | Serving (Primary) Note that if an exit route is approved (0.0.0.0/0 or ::/0), both IPv4 and IPv6 will be approved. -- Route API and CLI has been removed - [#2422](https://github.com/juanfont/headscale/pull/2422) -- Routes are now managed via the Node API - [#2422](https://github.com/juanfont/headscale/pull/2422) -- Only routes accessible to the node will be sent to the node - [#2561](https://github.com/juanfont/headscale/pull/2561) +- Route API and CLI has been removed [#2422](https://github.com/juanfont/headscale/pull/2422) +- Routes are now managed via the Node API [#2422](https://github.com/juanfont/headscale/pull/2422) +- Only routes accessible to the node will be sent to the node [#2561](https://github.com/juanfont/headscale/pull/2561) #### Policy v2 @@ -297,12 +265,9 @@ working in v1 and not tested might be broken in v2 (and vice versa). #### Other breaking changes -- Disallow `server_url` and `base_domain` to be equal - [#2544](https://github.com/juanfont/headscale/pull/2544) -- Return full user in API for pre auth keys instead of string - [#2542](https://github.com/juanfont/headscale/pull/2542) -- Pre auth key API/CLI now uses ID over username - [#2542](https://github.com/juanfont/headscale/pull/2542) +- Disallow `server_url` and `base_domain` to be equal [#2544](https://github.com/juanfont/headscale/pull/2544) +- Return full user in API for pre auth keys instead of string [#2542](https://github.com/juanfont/headscale/pull/2542) +- Pre auth key API/CLI now uses ID over username [#2542](https://github.com/juanfont/headscale/pull/2542) - A non-empty list of global nameservers needs to be specified via `dns.nameservers.global` if the configuration option `dns.override_local_dns` is enabled or is not specified in the configuration file. This aligns with @@ -312,48 +277,37 @@ working in v1 and not tested might be broken in v2 (and vice versa). ### Changes - Use Go 1.24 [#2427](https://github.com/juanfont/headscale/pull/2427) -- Add `headscale policy check` command to check policy - [#2553](https://github.com/juanfont/headscale/pull/2553) -- `oidc.map_legacy_users` and `oidc.strip_email_domain` has been removed - [#2411](https://github.com/juanfont/headscale/pull/2411) -- Add more information to `/debug` endpoint - [#2420](https://github.com/juanfont/headscale/pull/2420) +- Add `headscale policy check` command to check policy [#2553](https://github.com/juanfont/headscale/pull/2553) +- `oidc.map_legacy_users` and `oidc.strip_email_domain` has been removed [#2411](https://github.com/juanfont/headscale/pull/2411) +- Add more information to `/debug` endpoint [#2420](https://github.com/juanfont/headscale/pull/2420) - It is now possible to inspect running goroutines and take profiles - View of config, policy, filter, ssh policy per node, connected nodes and DERPmap -- OIDC: Fetch UserInfo to get EmailVerified if necessary - [#2493](https://github.com/juanfont/headscale/pull/2493) +- OIDC: Fetch UserInfo to get EmailVerified if necessary [#2493](https://github.com/juanfont/headscale/pull/2493) - If a OIDC provider doesn't include the `email_verified` claim in its ID tokens, Headscale will attempt to get it from the UserInfo endpoint. -- OIDC: Try to populate name, email and username from UserInfo - [#2545](https://github.com/juanfont/headscale/pull/2545) +- OIDC: Try to populate name, email and username from UserInfo [#2545](https://github.com/juanfont/headscale/pull/2545) - Improve performance by only querying relevant nodes from the database for node updates [#2509](https://github.com/juanfont/headscale/pull/2509) - node FQDNs in the netmap will now contain a dot (".") at the end. This aligns with behaviour of tailscale.com [#2503](https://github.com/juanfont/headscale/pull/2503) -- Restore support for "Override local DNS" - [#2438](https://github.com/juanfont/headscale/pull/2438) -- Add documentation for routes - [#2496](https://github.com/juanfont/headscale/pull/2496) +- Restore support for "Override local DNS" [#2438](https://github.com/juanfont/headscale/pull/2438) +- Add documentation for routes [#2496](https://github.com/juanfont/headscale/pull/2496) ## 0.25.1 (2025-02-25) ### Changes -- Fix issue where registration errors are sent correctly - [#2435](https://github.com/juanfont/headscale/pull/2435) -- Fix issue where routes passed on registration were not saved - [#2444](https://github.com/juanfont/headscale/pull/2444) -- Fix issue where registration page was displayed twice - [#2445](https://github.com/juanfont/headscale/pull/2445) +- Fix issue where registration errors are sent correctly [#2435](https://github.com/juanfont/headscale/pull/2435) +- Fix issue where routes passed on registration were not saved [#2444](https://github.com/juanfont/headscale/pull/2444) +- Fix issue where registration page was displayed twice [#2445](https://github.com/juanfont/headscale/pull/2445) ## 0.25.0 (2025-02-11) ### BREAKING -- Authentication flow has been rewritten - [#2374](https://github.com/juanfont/headscale/pull/2374) This change should be +- Authentication flow has been rewritten [#2374](https://github.com/juanfont/headscale/pull/2374) This change should be transparent to users with the exception of some buxfixes that has been discovered and was fixed as part of the rewrite. - When a node is registered with _a new user_, it will be registered as a new @@ -361,62 +315,44 @@ working in v1 and not tested might be broken in v2 (and vice versa). [#1310](https://github.com/juanfont/headscale/issues/1310)). - A logged out node logging in with the same user will replace the existing node. -- Remove support for Tailscale clients older than 1.62 (Capability version 87) - [#2405](https://github.com/juanfont/headscale/pull/2405) +- Remove support for Tailscale clients older than 1.62 (Capability version 87) [#2405](https://github.com/juanfont/headscale/pull/2405) ### Changes -- `oidc.map_legacy_users` is now `false` by default - [#2350](https://github.com/juanfont/headscale/pull/2350) -- Print Tailscale version instead of capability versions for outdated nodes - [#2391](https://github.com/juanfont/headscale/pull/2391) -- Do not allow renaming of users from OIDC - [#2393](https://github.com/juanfont/headscale/pull/2393) -- Change minimum hostname length to 2 - [#2393](https://github.com/juanfont/headscale/pull/2393) -- Fix migration error caused by nodes having invalid auth keys - [#2412](https://github.com/juanfont/headscale/pull/2412) -- Pre auth keys belonging to a user are no longer deleted with the user - [#2396](https://github.com/juanfont/headscale/pull/2396) -- Pre auth keys that are used by a node can no longer be deleted - [#2396](https://github.com/juanfont/headscale/pull/2396) -- Rehaul HTTP errors, return better status code and errors to users - [#2398](https://github.com/juanfont/headscale/pull/2398) -- Print headscale version and commit on server startup - [#2415](https://github.com/juanfont/headscale/pull/2415) +- `oidc.map_legacy_users` is now `false` by default [#2350](https://github.com/juanfont/headscale/pull/2350) +- Print Tailscale version instead of capability versions for outdated nodes [#2391](https://github.com/juanfont/headscale/pull/2391) +- Do not allow renaming of users from OIDC [#2393](https://github.com/juanfont/headscale/pull/2393) +- Change minimum hostname length to 2 [#2393](https://github.com/juanfont/headscale/pull/2393) +- Fix migration error caused by nodes having invalid auth keys [#2412](https://github.com/juanfont/headscale/pull/2412) +- Pre auth keys belonging to a user are no longer deleted with the user [#2396](https://github.com/juanfont/headscale/pull/2396) +- Pre auth keys that are used by a node can no longer be deleted [#2396](https://github.com/juanfont/headscale/pull/2396) +- Rehaul HTTP errors, return better status code and errors to users [#2398](https://github.com/juanfont/headscale/pull/2398) +- Print headscale version and commit on server startup [#2415](https://github.com/juanfont/headscale/pull/2415) ## 0.24.3 (2025-02-07) ### Changes -- Fix migration error caused by nodes having invalid auth keys - [#2412](https://github.com/juanfont/headscale/pull/2412) -- Pre auth keys belonging to a user are no longer deleted with the user - [#2396](https://github.com/juanfont/headscale/pull/2396) -- Pre auth keys that are used by a node can no longer be deleted - [#2396](https://github.com/juanfont/headscale/pull/2396) +- Fix migration error caused by nodes having invalid auth keys [#2412](https://github.com/juanfont/headscale/pull/2412) +- Pre auth keys belonging to a user are no longer deleted with the user [#2396](https://github.com/juanfont/headscale/pull/2396) +- Pre auth keys that are used by a node can no longer be deleted [#2396](https://github.com/juanfont/headscale/pull/2396) ## 0.24.2 (2025-01-30) ### Changes -- Fix issue where email and username being equal fails to match in Policy - [#2388](https://github.com/juanfont/headscale/pull/2388) -- Delete invalid routes before adding a NOT NULL constraint on node_id - [#2386](https://github.com/juanfont/headscale/pull/2386) +- Fix issue where email and username being equal fails to match in Policy [#2388](https://github.com/juanfont/headscale/pull/2388) +- Delete invalid routes before adding a NOT NULL constraint on node_id [#2386](https://github.com/juanfont/headscale/pull/2386) ## 0.24.1 (2025-01-23) ### Changes -- Fix migration issue with user table for PostgreSQL - [#2367](https://github.com/juanfont/headscale/pull/2367) -- Relax username validation to allow emails - [#2364](https://github.com/juanfont/headscale/pull/2364) +- Fix migration issue with user table for PostgreSQL [#2367](https://github.com/juanfont/headscale/pull/2367) +- Relax username validation to allow emails [#2364](https://github.com/juanfont/headscale/pull/2364) - Remove invalid routes and add stronger constraints for routes to avoid API panic [#2371](https://github.com/juanfont/headscale/pull/2371) -- Fix panic when `derp.update_frequency` is 0 - [#2368](https://github.com/juanfont/headscale/pull/2368) +- Fix panic when `derp.update_frequency` is 0 [#2368](https://github.com/juanfont/headscale/pull/2368) ## 0.24.0 (2025-01-17) @@ -553,12 +489,10 @@ This will also affect the way you ### BREAKING -- Remove `dns.use_username_in_magic_dns` configuration option - [#2020](https://github.com/juanfont/headscale/pull/2020), +- Remove `dns.use_username_in_magic_dns` configuration option [#2020](https://github.com/juanfont/headscale/pull/2020), [#2279](https://github.com/juanfont/headscale/pull/2279) - Having usernames in magic DNS is no longer possible. -- Remove versions older than 1.56 - [#2149](https://github.com/juanfont/headscale/pull/2149) +- Remove versions older than 1.56 [#2149](https://github.com/juanfont/headscale/pull/2149) - Clean up old code required by old versions - User gRPC/API [#2261](https://github.com/juanfont/headscale/pull/2261): - If you depend on a Headscale Web UI, you should wait with this update until @@ -571,27 +505,20 @@ This will also affect the way you - Improved compatibility of built-in DERP server with clients connecting over WebSocket [#2132](https://github.com/juanfont/headscale/pull/2132) -- Allow nodes to use SSH agent forwarding - [#2145](https://github.com/juanfont/headscale/pull/2145) -- Fixed processing of fields in post request in MoveNode rpc - [#2179](https://github.com/juanfont/headscale/pull/2179) +- Allow nodes to use SSH agent forwarding [#2145](https://github.com/juanfont/headscale/pull/2145) +- Fixed processing of fields in post request in MoveNode rpc [#2179](https://github.com/juanfont/headscale/pull/2179) - Added conversion of 'Hostname' to 'givenName' in a node with FQDN rules applied [#2198](https://github.com/juanfont/headscale/pull/2198) -- Fixed updating of hostname and givenName when it is updated in HostInfo - [#2199](https://github.com/juanfont/headscale/pull/2199) -- Fixed missing `stable-debug` container tag - [#2232](https://github.com/juanfont/headscale/pull/2232) +- Fixed updating of hostname and givenName when it is updated in HostInfo [#2199](https://github.com/juanfont/headscale/pull/2199) +- Fixed missing `stable-debug` container tag [#2232](https://github.com/juanfont/headscale/pull/2232) - Loosened up `server_url` and `base_domain` check. It was overly strict in some cases. [#2248](https://github.com/juanfont/headscale/pull/2248) - CLI for managing users now accepts `--identifier` in addition to `--name`, usage of `--identifier` is recommended [#2261](https://github.com/juanfont/headscale/pull/2261) -- Add `dns.extra_records_path` configuration option - [#2262](https://github.com/juanfont/headscale/issues/2262) -- Support client verify for DERP - [#2046](https://github.com/juanfont/headscale/pull/2046) -- Add PKCE Verifier for OIDC - [#2314](https://github.com/juanfont/headscale/pull/2314) +- Add `dns.extra_records_path` configuration option [#2262](https://github.com/juanfont/headscale/issues/2262) +- Support client verify for DERP [#2046](https://github.com/juanfont/headscale/pull/2046) +- Add PKCE Verifier for OIDC [#2314](https://github.com/juanfont/headscale/pull/2314) ## 0.23.0 (2024-09-18) @@ -655,28 +582,22 @@ part of adopting [#1460](https://github.com/juanfont/headscale/pull/1460). - Old structure has been remove and the configuration _must_ be converted. - Adds additional configuration for PostgreSQL for setting max open, idle connection and idle connection lifetime. -- API: Machine is now Node - [#1553](https://github.com/juanfont/headscale/pull/1553) -- Remove support for older Tailscale clients - [#1611](https://github.com/juanfont/headscale/pull/1611) +- API: Machine is now Node [#1553](https://github.com/juanfont/headscale/pull/1553) +- Remove support for older Tailscale clients [#1611](https://github.com/juanfont/headscale/pull/1611) - The oldest supported client is 1.42 -- Headscale checks that _at least_ one DERP is defined at start - [#1564](https://github.com/juanfont/headscale/pull/1564) +- Headscale checks that _at least_ one DERP is defined at start [#1564](https://github.com/juanfont/headscale/pull/1564) - If no DERP is configured, the server will fail to start, this can be because it cannot load the DERPMap from file or url. -- Embedded DERP server requires a private key - [#1611](https://github.com/juanfont/headscale/pull/1611) +- Embedded DERP server requires a private key [#1611](https://github.com/juanfont/headscale/pull/1611) - Add a filepath entry to [`derp.server.private_key_path`](https://github.com/juanfont/headscale/blob/b35993981297e18393706b2c963d6db882bba6aa/config-example.yaml#L95) -- Docker images are now built with goreleaser (ko) - [#1716](https://github.com/juanfont/headscale/pull/1716) +- Docker images are now built with goreleaser (ko) [#1716](https://github.com/juanfont/headscale/pull/1716) [#1763](https://github.com/juanfont/headscale/pull/1763) - Entrypoint of container image has changed from shell to headscale, require change from `headscale serve` to `serve` - `/var/lib/headscale` and `/var/run/headscale` is no longer created automatically, see [container docs](./docs/setup/install/container.md) -- Prefixes are now defined per v4 and v6 range. - [#1756](https://github.com/juanfont/headscale/pull/1756) +- Prefixes are now defined per v4 and v6 range. [#1756](https://github.com/juanfont/headscale/pull/1756) - `ip_prefixes` option is now `prefixes.v4` and `prefixes.v6` - `prefixes.allocation` can be set to assign IPs at `sequential` or `random`. [#1869](https://github.com/juanfont/headscale/pull/1869) @@ -691,30 +612,23 @@ part of adopting [#1460](https://github.com/juanfont/headscale/pull/1460). note that this option _will be removed_ when tags are fixed. - dns.base_domain can no longer be the same as (or part of) server_url. - This option brings Headscales behaviour in line with Tailscale. -- YAML files are no longer supported for headscale policy. - [#1792](https://github.com/juanfont/headscale/pull/1792) +- YAML files are no longer supported for headscale policy. [#1792](https://github.com/juanfont/headscale/pull/1792) - HuJSON is now the only supported format for policy. -- DNS configuration has been restructured - [#2034](https://github.com/juanfont/headscale/pull/2034) +- DNS configuration has been restructured [#2034](https://github.com/juanfont/headscale/pull/2034) - Please review the new [config-example.yaml](./config-example.yaml) for the new structure. ### Changes -- Use versioned migrations - [#1644](https://github.com/juanfont/headscale/pull/1644) -- Make the OIDC callback page better - [#1484](https://github.com/juanfont/headscale/pull/1484) +- Use versioned migrations [#1644](https://github.com/juanfont/headscale/pull/1644) +- Make the OIDC callback page better [#1484](https://github.com/juanfont/headscale/pull/1484) - SSH support [#1487](https://github.com/juanfont/headscale/pull/1487) -- State management has been improved - [#1492](https://github.com/juanfont/headscale/pull/1492) -- Use error group handling to ensure tests actually pass - [#1535](https://github.com/juanfont/headscale/pull/1535) based on +- State management has been improved [#1492](https://github.com/juanfont/headscale/pull/1492) +- Use error group handling to ensure tests actually pass [#1535](https://github.com/juanfont/headscale/pull/1535) based on [#1460](https://github.com/juanfont/headscale/pull/1460) - Fix hang on SIGTERM [#1492](https://github.com/juanfont/headscale/pull/1492) taken from [#1480](https://github.com/juanfont/headscale/pull/1480) -- Send logs to stderr by default - [#1524](https://github.com/juanfont/headscale/pull/1524) +- Send logs to stderr by default [#1524](https://github.com/juanfont/headscale/pull/1524) - Fix [TS-2023-006](https://tailscale.com/security-bulletins/#ts-2023-006) security UPnP issue [#1563](https://github.com/juanfont/headscale/pull/1563) - Turn off gRPC logging [#1640](https://github.com/juanfont/headscale/pull/1640) @@ -722,21 +636,15 @@ part of adopting [#1460](https://github.com/juanfont/headscale/pull/1460). - Added the possibility to manually create a DERP-map entry which can be customized, instead of automatically creating it. [#1565](https://github.com/juanfont/headscale/pull/1565) -- Add support for deleting api keys - [#1702](https://github.com/juanfont/headscale/pull/1702) +- Add support for deleting api keys [#1702](https://github.com/juanfont/headscale/pull/1702) - Add command to backfill IP addresses for nodes missing IPs from configured prefixes. [#1869](https://github.com/juanfont/headscale/pull/1869) -- Log available update as warning - [#1877](https://github.com/juanfont/headscale/pull/1877) -- Add `autogroup:internet` to Policy - [#1917](https://github.com/juanfont/headscale/pull/1917) -- Restore foreign keys and add constraints - [#1562](https://github.com/juanfont/headscale/pull/1562) +- Log available update as warning [#1877](https://github.com/juanfont/headscale/pull/1877) +- Add `autogroup:internet` to Policy [#1917](https://github.com/juanfont/headscale/pull/1917) +- Restore foreign keys and add constraints [#1562](https://github.com/juanfont/headscale/pull/1562) - Make registration page easier to use on mobile devices -- Make write-ahead-log default on and configurable for SQLite - [#1985](https://github.com/juanfont/headscale/pull/1985) -- Add APIs for managing headscale policy. - [#1792](https://github.com/juanfont/headscale/pull/1792) +- Make write-ahead-log default on and configurable for SQLite [#1985](https://github.com/juanfont/headscale/pull/1985) +- Add APIs for managing headscale policy. [#1792](https://github.com/juanfont/headscale/pull/1792) - Fix for registering nodes using preauthkeys when running on a postgres database in a non-UTC timezone. [#764](https://github.com/juanfont/headscale/issues/764) @@ -744,33 +652,25 @@ part of adopting [#1460](https://github.com/juanfont/headscale/pull/1460). - CLI commands (all except `serve`) only requires minimal configuration, no more errors or warnings from unset settings [#2109](https://github.com/juanfont/headscale/pull/2109) -- CLI results are now concistently sent to stdout and errors to stderr - [#2109](https://github.com/juanfont/headscale/pull/2109) -- Fix issue where shutting down headscale would hang - [#2113](https://github.com/juanfont/headscale/pull/2113) +- CLI results are now concistently sent to stdout and errors to stderr [#2109](https://github.com/juanfont/headscale/pull/2109) +- Fix issue where shutting down headscale would hang [#2113](https://github.com/juanfont/headscale/pull/2113) ## 0.22.3 (2023-05-12) ### Changes -- Added missing ca-certificates in Docker image - [#1463](https://github.com/juanfont/headscale/pull/1463) +- Added missing ca-certificates in Docker image [#1463](https://github.com/juanfont/headscale/pull/1463) ## 0.22.2 (2023-05-10) ### Changes -- Add environment flags to enable pprof (profiling) - [#1382](https://github.com/juanfont/headscale/pull/1382) +- Add environment flags to enable pprof (profiling) [#1382](https://github.com/juanfont/headscale/pull/1382) - Profiles are continuously generated in our integration tests. -- Fix systemd service file location in `.deb` packages - [#1391](https://github.com/juanfont/headscale/pull/1391) -- Improvements on Noise implementation - [#1379](https://github.com/juanfont/headscale/pull/1379) -- Replace node filter logic, ensuring nodes with access can see each other - [#1381](https://github.com/juanfont/headscale/pull/1381) -- Disable (or delete) both exit routes at the same time - [#1428](https://github.com/juanfont/headscale/pull/1428) +- Fix systemd service file location in `.deb` packages [#1391](https://github.com/juanfont/headscale/pull/1391) +- Improvements on Noise implementation [#1379](https://github.com/juanfont/headscale/pull/1379) +- Replace node filter logic, ensuring nodes with access can see each other [#1381](https://github.com/juanfont/headscale/pull/1381) +- Disable (or delete) both exit routes at the same time [#1428](https://github.com/juanfont/headscale/pull/1428) - Ditch distroless for Docker image, create default socket dir in `/var/run/headscale` [#1450](https://github.com/juanfont/headscale/pull/1450) @@ -778,65 +678,49 @@ part of adopting [#1460](https://github.com/juanfont/headscale/pull/1460). ### Changes -- Fix issue where systemd could not bind to port 80 - [#1365](https://github.com/juanfont/headscale/pull/1365) +- Fix issue where systemd could not bind to port 80 [#1365](https://github.com/juanfont/headscale/pull/1365) ## 0.22.0 (2023-04-20) ### Changes -- Add `.deb` packages to release process - [#1297](https://github.com/juanfont/headscale/pull/1297) -- Update and simplify the documentation to use new `.deb` packages - [#1349](https://github.com/juanfont/headscale/pull/1349) -- Add 32-bit Arm platforms to release process - [#1297](https://github.com/juanfont/headscale/pull/1297) +- Add `.deb` packages to release process [#1297](https://github.com/juanfont/headscale/pull/1297) +- Update and simplify the documentation to use new `.deb` packages [#1349](https://github.com/juanfont/headscale/pull/1349) +- Add 32-bit Arm platforms to release process [#1297](https://github.com/juanfont/headscale/pull/1297) - Fix longstanding bug that would prevent "\*" from working properly in ACLs (issue [#699](https://github.com/juanfont/headscale/issues/699)) [#1279](https://github.com/juanfont/headscale/pull/1279) -- Fix issue where IPv6 could not be used in, or while using ACLs (part of - [#809](https://github.com/juanfont/headscale/issues/809)) +- Fix issue where IPv6 could not be used in, or while using ACLs (part of [#809](https://github.com/juanfont/headscale/issues/809)) [#1339](https://github.com/juanfont/headscale/pull/1339) -- Target Go 1.20 and Tailscale 1.38 for Headscale - [#1323](https://github.com/juanfont/headscale/pull/1323) +- Target Go 1.20 and Tailscale 1.38 for Headscale [#1323](https://github.com/juanfont/headscale/pull/1323) ## 0.21.0 (2023-03-20) ### Changes -- Adding "configtest" CLI command. - [#1230](https://github.com/juanfont/headscale/pull/1230) -- Add documentation on connecting with iOS to `/apple` - [#1261](https://github.com/juanfont/headscale/pull/1261) -- Update iOS compatibility and added documentation for iOS - [#1264](https://github.com/juanfont/headscale/pull/1264) -- Allow to delete routes - [#1244](https://github.com/juanfont/headscale/pull/1244) +- Adding "configtest" CLI command. [#1230](https://github.com/juanfont/headscale/pull/1230) +- Add documentation on connecting with iOS to `/apple` [#1261](https://github.com/juanfont/headscale/pull/1261) +- Update iOS compatibility and added documentation for iOS [#1264](https://github.com/juanfont/headscale/pull/1264) +- Allow to delete routes [#1244](https://github.com/juanfont/headscale/pull/1244) ## 0.20.0 (2023-02-03) ### Changes -- Fix wrong behaviour in exit nodes - [#1159](https://github.com/juanfont/headscale/pull/1159) -- Align behaviour of `dns_config.restricted_nameservers` to tailscale - [#1162](https://github.com/juanfont/headscale/pull/1162) -- Make OpenID Connect authenticated client expiry time configurable - [#1191](https://github.com/juanfont/headscale/pull/1191) +- Fix wrong behaviour in exit nodes [#1159](https://github.com/juanfont/headscale/pull/1159) +- Align behaviour of `dns_config.restricted_nameservers` to tailscale [#1162](https://github.com/juanfont/headscale/pull/1162) +- Make OpenID Connect authenticated client expiry time configurable [#1191](https://github.com/juanfont/headscale/pull/1191) - defaults to 180 days like Tailscale SaaS - adds option to use the expiry time from the OpenID token for the node (see config-example.yaml) -- Set ControlTime in Map info sent to nodes - [#1195](https://github.com/juanfont/headscale/pull/1195) -- Populate Tags field on Node updates sent - [#1195](https://github.com/juanfont/headscale/pull/1195) +- Set ControlTime in Map info sent to nodes [#1195](https://github.com/juanfont/headscale/pull/1195) +- Populate Tags field on Node updates sent [#1195](https://github.com/juanfont/headscale/pull/1195) ## 0.19.0 (2023-01-29) ### BREAKING -- Rename Namespace to User - [#1144](https://github.com/juanfont/headscale/pull/1144) +- Rename Namespace to User [#1144](https://github.com/juanfont/headscale/pull/1144) - **BACKUP your database before upgrading** - Command line flags previously taking `--namespace` or `-n` will now require `--user` or `-u` @@ -845,35 +729,23 @@ part of adopting [#1460](https://github.com/juanfont/headscale/pull/1460). ### Changes -- Reworked routing and added support for subnet router failover - [#1024](https://github.com/juanfont/headscale/pull/1024) -- Added an OIDC AllowGroups Configuration options and authorization check - [#1041](https://github.com/juanfont/headscale/pull/1041) -- Set `db_ssl` to false by default - [#1052](https://github.com/juanfont/headscale/pull/1052) -- Fix duplicate nodes due to incorrect implementation of the protocol - [#1058](https://github.com/juanfont/headscale/pull/1058) -- Report if a machine is online in CLI more accurately - [#1062](https://github.com/juanfont/headscale/pull/1062) -- Added config option for custom DNS records - [#1035](https://github.com/juanfont/headscale/pull/1035) -- Expire nodes based on OIDC token expiry - [#1067](https://github.com/juanfont/headscale/pull/1067) -- Remove ephemeral nodes on logout - [#1098](https://github.com/juanfont/headscale/pull/1098) -- Performance improvements in ACLs - [#1129](https://github.com/juanfont/headscale/pull/1129) -- OIDC client secret can be passed via a file - [#1127](https://github.com/juanfont/headscale/pull/1127) +- Reworked routing and added support for subnet router failover [#1024](https://github.com/juanfont/headscale/pull/1024) +- Added an OIDC AllowGroups Configuration options and authorization check [#1041](https://github.com/juanfont/headscale/pull/1041) +- Set `db_ssl` to false by default [#1052](https://github.com/juanfont/headscale/pull/1052) +- Fix duplicate nodes due to incorrect implementation of the protocol [#1058](https://github.com/juanfont/headscale/pull/1058) +- Report if a machine is online in CLI more accurately [#1062](https://github.com/juanfont/headscale/pull/1062) +- Added config option for custom DNS records [#1035](https://github.com/juanfont/headscale/pull/1035) +- Expire nodes based on OIDC token expiry [#1067](https://github.com/juanfont/headscale/pull/1067) +- Remove ephemeral nodes on logout [#1098](https://github.com/juanfont/headscale/pull/1098) +- Performance improvements in ACLs [#1129](https://github.com/juanfont/headscale/pull/1129) +- OIDC client secret can be passed via a file [#1127](https://github.com/juanfont/headscale/pull/1127) ## 0.17.1 (2022-12-05) ### Changes -- Correct typo on macOS standalone profile link - [#1028](https://github.com/juanfont/headscale/pull/1028) -- Update platform docs with Fast User Switching - [#1016](https://github.com/juanfont/headscale/pull/1016) +- Correct typo on macOS standalone profile link [#1028](https://github.com/juanfont/headscale/pull/1028) +- Update platform docs with Fast User Switching [#1016](https://github.com/juanfont/headscale/pull/1016) ## 0.17.0 (2022-11-26) @@ -883,13 +755,11 @@ part of adopting [#1460](https://github.com/juanfont/headscale/pull/1460). protocol. - Log level option `log_level` was moved to a distinct `log` config section and renamed to `level` [#768](https://github.com/juanfont/headscale/pull/768) -- Removed Alpine Linux container image - [#962](https://github.com/juanfont/headscale/pull/962) +- Removed Alpine Linux container image [#962](https://github.com/juanfont/headscale/pull/962) ### Important Changes -- Added support for Tailscale TS2021 protocol - [#738](https://github.com/juanfont/headscale/pull/738) +- Added support for Tailscale TS2021 protocol [#738](https://github.com/juanfont/headscale/pull/738) - Add experimental support for [SSH ACL](https://tailscale.com/kb/1018/acls/#tailscale-ssh) (see docs for limitations) [#847](https://github.com/juanfont/headscale/pull/847) @@ -909,81 +779,57 @@ part of adopting [#1460](https://github.com/juanfont/headscale/pull/1460). ### Changes -- Add ability to specify config location via env var `HEADSCALE_CONFIG` - [#674](https://github.com/juanfont/headscale/issues/674) -- Target Go 1.19 for Headscale - [#778](https://github.com/juanfont/headscale/pull/778) -- Target Tailscale v1.30.0 to build Headscale - [#780](https://github.com/juanfont/headscale/pull/780) +- Add ability to specify config location via env var `HEADSCALE_CONFIG` [#674](https://github.com/juanfont/headscale/issues/674) +- Target Go 1.19 for Headscale [#778](https://github.com/juanfont/headscale/pull/778) +- Target Tailscale v1.30.0 to build Headscale [#780](https://github.com/juanfont/headscale/pull/780) - Give a warning when running Headscale with reverse proxy improperly configured for WebSockets [#788](https://github.com/juanfont/headscale/pull/788) -- Fix subnet routers with Primary Routes - [#811](https://github.com/juanfont/headscale/pull/811) -- Added support for JSON logs - [#653](https://github.com/juanfont/headscale/issues/653) -- Sanitise the node key passed to registration url - [#823](https://github.com/juanfont/headscale/pull/823) -- Add support for generating pre-auth keys with tags - [#767](https://github.com/juanfont/headscale/pull/767) +- Fix subnet routers with Primary Routes [#811](https://github.com/juanfont/headscale/pull/811) +- Added support for JSON logs [#653](https://github.com/juanfont/headscale/issues/653) +- Sanitise the node key passed to registration url [#823](https://github.com/juanfont/headscale/pull/823) +- Add support for generating pre-auth keys with tags [#767](https://github.com/juanfont/headscale/pull/767) - Add support for evaluating `autoApprovers` ACL entries when a machine is registered [#763](https://github.com/juanfont/headscale/pull/763) -- Add config flag to allow Headscale to start if OIDC provider is down - [#829](https://github.com/juanfont/headscale/pull/829) -- Fix prefix length comparison bug in AutoApprovers route evaluation - [#862](https://github.com/juanfont/headscale/pull/862) -- Random node DNS suffix only applied if names collide in namespace. - [#766](https://github.com/juanfont/headscale/issues/766) -- Remove `ip_prefix` configuration option and warning - [#899](https://github.com/juanfont/headscale/pull/899) -- Add `dns_config.override_local_dns` option - [#905](https://github.com/juanfont/headscale/pull/905) -- Fix some DNS config issues - [#660](https://github.com/juanfont/headscale/issues/660) -- Make it possible to disable TS2019 with build flag - [#928](https://github.com/juanfont/headscale/pull/928) -- Fix OIDC registration issues - [#960](https://github.com/juanfont/headscale/pull/960) and +- Add config flag to allow Headscale to start if OIDC provider is down [#829](https://github.com/juanfont/headscale/pull/829) +- Fix prefix length comparison bug in AutoApprovers route evaluation [#862](https://github.com/juanfont/headscale/pull/862) +- Random node DNS suffix only applied if names collide in namespace. [#766](https://github.com/juanfont/headscale/issues/766) +- Remove `ip_prefix` configuration option and warning [#899](https://github.com/juanfont/headscale/pull/899) +- Add `dns_config.override_local_dns` option [#905](https://github.com/juanfont/headscale/pull/905) +- Fix some DNS config issues [#660](https://github.com/juanfont/headscale/issues/660) +- Make it possible to disable TS2019 with build flag [#928](https://github.com/juanfont/headscale/pull/928) +- Fix OIDC registration issues [#960](https://github.com/juanfont/headscale/pull/960) and [#971](https://github.com/juanfont/headscale/pull/971) -- Add support for specifying NextDNS DNS-over-HTTPS resolver - [#940](https://github.com/juanfont/headscale/pull/940) -- Make more sslmode available for postgresql connection - [#927](https://github.com/juanfont/headscale/pull/927) +- Add support for specifying NextDNS DNS-over-HTTPS resolver [#940](https://github.com/juanfont/headscale/pull/940) +- Make more sslmode available for postgresql connection [#927](https://github.com/juanfont/headscale/pull/927) ## 0.16.4 (2022-08-21) ### Changes -- Add ability to connect to PostgreSQL over TLS/SSL - [#745](https://github.com/juanfont/headscale/pull/745) -- Fix CLI registration of expired machines - [#754](https://github.com/juanfont/headscale/pull/754) +- Add ability to connect to PostgreSQL over TLS/SSL [#745](https://github.com/juanfont/headscale/pull/745) +- Fix CLI registration of expired machines [#754](https://github.com/juanfont/headscale/pull/754) ## 0.16.3 (2022-08-17) ### Changes -- Fix issue with OIDC authentication - [#747](https://github.com/juanfont/headscale/pull/747) +- Fix issue with OIDC authentication [#747](https://github.com/juanfont/headscale/pull/747) ## 0.16.2 (2022-08-14) ### Changes -- Fixed bugs in the client registration process after migration to NodeKey - [#735](https://github.com/juanfont/headscale/pull/735) +- Fixed bugs in the client registration process after migration to NodeKey [#735](https://github.com/juanfont/headscale/pull/735) ## 0.16.1 (2022-08-12) ### Changes -- Updated dependencies (including the library that lacked armhf support) - [#722](https://github.com/juanfont/headscale/pull/722) -- Fix missing group expansion in function `excludeCorrectlyTaggedNodes` - [#563](https://github.com/juanfont/headscale/issues/563) +- Updated dependencies (including the library that lacked armhf support) [#722](https://github.com/juanfont/headscale/pull/722) +- Fix missing group expansion in function `excludeCorrectlyTaggedNodes` [#563](https://github.com/juanfont/headscale/issues/563) - Improve registration protocol implementation and switch to NodeKey as main identifier [#725](https://github.com/juanfont/headscale/pull/725) -- Add ability to connect to PostgreSQL via unix socket - [#734](https://github.com/juanfont/headscale/pull/734) +- Add ability to connect to PostgreSQL via unix socket [#734](https://github.com/juanfont/headscale/pull/734) ## 0.16.0 (2022-07-25) @@ -996,44 +842,30 @@ part of adopting [#1460](https://github.com/juanfont/headscale/pull/1460). ### Changes -- **Drop** armhf (32-bit ARM) support. - [#609](https://github.com/juanfont/headscale/pull/609) -- Headscale fails to serve if the ACL policy file cannot be parsed - [#537](https://github.com/juanfont/headscale/pull/537) -- Fix labels cardinality error when registering unknown pre-auth key - [#519](https://github.com/juanfont/headscale/pull/519) -- Fix send on closed channel crash in polling - [#542](https://github.com/juanfont/headscale/pull/542) -- Fixed spurious calls to setLastStateChangeToNow from ephemeral nodes - [#566](https://github.com/juanfont/headscale/pull/566) -- Add command for moving nodes between namespaces - [#362](https://github.com/juanfont/headscale/issues/362) +- **Drop** armhf (32-bit ARM) support. [#609](https://github.com/juanfont/headscale/pull/609) +- Headscale fails to serve if the ACL policy file cannot be parsed [#537](https://github.com/juanfont/headscale/pull/537) +- Fix labels cardinality error when registering unknown pre-auth key [#519](https://github.com/juanfont/headscale/pull/519) +- Fix send on closed channel crash in polling [#542](https://github.com/juanfont/headscale/pull/542) +- Fixed spurious calls to setLastStateChangeToNow from ephemeral nodes [#566](https://github.com/juanfont/headscale/pull/566) +- Add command for moving nodes between namespaces [#362](https://github.com/juanfont/headscale/issues/362) - Added more configuration parameters for OpenID Connect (scopes, free-form parameters, domain and user allowlist) -- Add command to set tags on a node - [#525](https://github.com/juanfont/headscale/issues/525) -- Add command to view tags of nodes - [#356](https://github.com/juanfont/headscale/issues/356) -- Add --all (-a) flag to enable routes command - [#360](https://github.com/juanfont/headscale/issues/360) -- Fix issue where nodes was not updated across namespaces - [#560](https://github.com/juanfont/headscale/pull/560) -- Add the ability to rename a nodes name - [#560](https://github.com/juanfont/headscale/pull/560) +- Add command to set tags on a node [#525](https://github.com/juanfont/headscale/issues/525) +- Add command to view tags of nodes [#356](https://github.com/juanfont/headscale/issues/356) +- Add --all (-a) flag to enable routes command [#360](https://github.com/juanfont/headscale/issues/360) +- Fix issue where nodes was not updated across namespaces [#560](https://github.com/juanfont/headscale/pull/560) +- Add the ability to rename a nodes name [#560](https://github.com/juanfont/headscale/pull/560) - Node DNS names are now unique, a random suffix will be added when a node joins - This change contains database changes, remember to **backup** your database before upgrading -- Add option to enable/disable logtail (Tailscale's logging infrastructure) - [#596](https://github.com/juanfont/headscale/pull/596) +- Add option to enable/disable logtail (Tailscale's logging infrastructure) [#596](https://github.com/juanfont/headscale/pull/596) - This change disables the logs by default - Use [Prometheus]'s duration parser, supporting days (`d`), weeks (`w`) and years (`y`) [#598](https://github.com/juanfont/headscale/pull/598) -- Add support for reloading ACLs with SIGHUP - [#601](https://github.com/juanfont/headscale/pull/601) +- Add support for reloading ACLs with SIGHUP [#601](https://github.com/juanfont/headscale/pull/601) - Use new ACL syntax [#618](https://github.com/juanfont/headscale/pull/618) -- Add -c option to specify config file from command line - [#285](https://github.com/juanfont/headscale/issues/285) +- Add -c option to specify config file from command line [#285](https://github.com/juanfont/headscale/issues/285) [#612](https://github.com/juanfont/headscale/pull/601) - Add configuration option to allow Tailscale clients to use a random WireGuard port. [kb/1181/firewalls](https://tailscale.com/kb/1181/firewalls) @@ -1041,19 +873,14 @@ part of adopting [#1460](https://github.com/juanfont/headscale/pull/1460). - Improve obtuse UX regarding missing configuration (`ephemeral_node_inactivity_timeout` not set) [#639](https://github.com/juanfont/headscale/pull/639) -- Fix nodes being shown as 'offline' in `tailscale status` - [#648](https://github.com/juanfont/headscale/pull/648) -- Improve shutdown behaviour - [#651](https://github.com/juanfont/headscale/pull/651) +- Fix nodes being shown as 'offline' in `tailscale status` [#648](https://github.com/juanfont/headscale/pull/648) +- Improve shutdown behaviour [#651](https://github.com/juanfont/headscale/pull/651) - Drop Gin as web framework in Headscale [648](https://github.com/juanfont/headscale/pull/648) [677](https://github.com/juanfont/headscale/pull/677) -- Make tailnet node updates check interval configurable - [#675](https://github.com/juanfont/headscale/pull/675) -- Fix regression with HTTP API - [#684](https://github.com/juanfont/headscale/pull/684) -- nodes ls now print both Hostname and Name(Issue - [#647](https://github.com/juanfont/headscale/issues/647) PR +- Make tailnet node updates check interval configurable [#675](https://github.com/juanfont/headscale/pull/675) +- Fix regression with HTTP API [#684](https://github.com/juanfont/headscale/pull/684) +- nodes ls now print both Hostname and Name(Issue [#647](https://github.com/juanfont/headscale/issues/647) PR [#687](https://github.com/juanfont/headscale/pull/687)) ## 0.15.0 (2022-03-20) @@ -1065,8 +892,7 @@ part of adopting [#1460](https://github.com/juanfont/headscale/pull/1460). - Boundaries between Namespaces has been removed and all nodes can communicate by default [#357](https://github.com/juanfont/headscale/pull/357) - To limit access between nodes, use [ACLs](./docs/ref/acls.md). -- `/metrics` is now a configurable host:port endpoint: - [#344](https://github.com/juanfont/headscale/pull/344). You must update your +- `/metrics` is now a configurable host:port endpoint: [#344](https://github.com/juanfont/headscale/pull/344). You must update your `config.yaml` file to include: ```yaml metrics_listen_addr: 127.0.0.1:9090 @@ -1074,23 +900,18 @@ part of adopting [#1460](https://github.com/juanfont/headscale/pull/1460). ### Features -- Add support for writing ACL files with YAML - [#359](https://github.com/juanfont/headscale/pull/359) -- Users can now use emails in ACL's groups - [#372](https://github.com/juanfont/headscale/issues/372) -- Add shorthand aliases for commands and subcommands - [#376](https://github.com/juanfont/headscale/pull/376) +- Add support for writing ACL files with YAML [#359](https://github.com/juanfont/headscale/pull/359) +- Users can now use emails in ACL's groups [#372](https://github.com/juanfont/headscale/issues/372) +- Add shorthand aliases for commands and subcommands [#376](https://github.com/juanfont/headscale/pull/376) - Add `/windows` endpoint for Windows configuration instructions + registry file download [#392](https://github.com/juanfont/headscale/pull/392) -- Added embedded DERP (and STUN) server into Headscale - [#388](https://github.com/juanfont/headscale/pull/388) +- Added embedded DERP (and STUN) server into Headscale [#388](https://github.com/juanfont/headscale/pull/388) ### Changes - Fix a bug were the same IP could be assigned to multiple hosts if joined in quick succession [#346](https://github.com/juanfont/headscale/pull/346) -- Simplify the code behind registration of machines - [#366](https://github.com/juanfont/headscale/pull/366) +- Simplify the code behind registration of machines [#366](https://github.com/juanfont/headscale/pull/366) - Nodes are now only written to database if they are registered successfully - Fix a limitation in the ACLs that prevented users to write rules with `*` as source [#374](https://github.com/juanfont/headscale/issues/374) @@ -1099,8 +920,7 @@ part of adopting [#1460](https://github.com/juanfont/headscale/pull/1460). [#371](https://github.com/juanfont/headscale/pull/371) - Apply normalization function to FQDN on hostnames when hosts registers and retrieve information [#363](https://github.com/juanfont/headscale/issues/363) -- Fix a bug that prevented the use of `tailscale logout` with OIDC - [#508](https://github.com/juanfont/headscale/issues/508) +- Fix a bug that prevented the use of `tailscale logout` with OIDC [#508](https://github.com/juanfont/headscale/issues/508) - Added Tailscale repo HEAD and unstable releases channel to the integration tests targets [#513](https://github.com/juanfont/headscale/pull/513) @@ -1127,13 +947,11 @@ behaviour. ### Features -- Add support for configurable mTLS [docs](./docs/ref/tls.md) - [#297](https://github.com/juanfont/headscale/pull/297) +- Add support for configurable mTLS [docs](./docs/ref/tls.md) [#297](https://github.com/juanfont/headscale/pull/297) ### Changes -- Remove dependency on CGO (switch from CGO SQLite to pure Go) - [#346](https://github.com/juanfont/headscale/pull/346) +- Remove dependency on CGO (switch from CGO SQLite to pure Go) [#346](https://github.com/juanfont/headscale/pull/346) **0.13.0 (2022-02-18):** @@ -1152,25 +970,18 @@ behaviour. ### Changes -- `ip_prefix` is now superseded by `ip_prefixes` in the configuration - [#208](https://github.com/juanfont/headscale/pull/208) -- Upgrade `tailscale` (1.20.4) and other dependencies to latest - [#314](https://github.com/juanfont/headscale/pull/314) -- fix swapped machine<->namespace labels in `/metrics` - [#312](https://github.com/juanfont/headscale/pull/312) -- remove key-value based update mechanism for namespace changes - [#316](https://github.com/juanfont/headscale/pull/316) +- `ip_prefix` is now superseded by `ip_prefixes` in the configuration [#208](https://github.com/juanfont/headscale/pull/208) +- Upgrade `tailscale` (1.20.4) and other dependencies to latest [#314](https://github.com/juanfont/headscale/pull/314) +- fix swapped machine<->namespace labels in `/metrics` [#312](https://github.com/juanfont/headscale/pull/312) +- remove key-value based update mechanism for namespace changes [#316](https://github.com/juanfont/headscale/pull/316) **0.12.4 (2022-01-29):** ### Changes -- Make gRPC Unix Socket permissions configurable - [#292](https://github.com/juanfont/headscale/pull/292) -- Trim whitespace before reading Private Key from file - [#289](https://github.com/juanfont/headscale/pull/289) -- Add new command to generate a private key for `headscale` - [#290](https://github.com/juanfont/headscale/pull/290) +- Make gRPC Unix Socket permissions configurable [#292](https://github.com/juanfont/headscale/pull/292) +- Trim whitespace before reading Private Key from file [#289](https://github.com/juanfont/headscale/pull/289) +- Add new command to generate a private key for `headscale` [#290](https://github.com/juanfont/headscale/pull/290) - Fixed issue where hosts deleted from control server may be written back to the database, as long as they are connected to the control server [#278](https://github.com/juanfont/headscale/pull/278) @@ -1180,8 +991,7 @@ behaviour. ### Changes - Added Alpine container [#270](https://github.com/juanfont/headscale/pull/270) -- Minor updates in dependencies - [#271](https://github.com/juanfont/headscale/pull/271) +- Minor updates in dependencies [#271](https://github.com/juanfont/headscale/pull/271) ## 0.12.2 (2022-01-11) @@ -1200,8 +1010,7 @@ tagging) ### BREAKING -- Upgrade to Tailscale 1.18 - [#229](https://github.com/juanfont/headscale/pull/229) +- Upgrade to Tailscale 1.18 [#229](https://github.com/juanfont/headscale/pull/229) - This change requires a new format for private key, private keys are now generated automatically: 1. Delete your current key @@ -1210,25 +1019,19 @@ tagging) ### Changes -- Unify configuration example - [#197](https://github.com/juanfont/headscale/pull/197) -- Add stricter linting and formatting - [#223](https://github.com/juanfont/headscale/pull/223) +- Unify configuration example [#197](https://github.com/juanfont/headscale/pull/197) +- Add stricter linting and formatting [#223](https://github.com/juanfont/headscale/pull/223) ### Features -- Add gRPC and HTTP API (HTTP API is currently disabled) - [#204](https://github.com/juanfont/headscale/pull/204) -- Use gRPC between the CLI and the server - [#206](https://github.com/juanfont/headscale/pull/206), +- Add gRPC and HTTP API (HTTP API is currently disabled) [#204](https://github.com/juanfont/headscale/pull/204) +- Use gRPC between the CLI and the server [#206](https://github.com/juanfont/headscale/pull/206), [#212](https://github.com/juanfont/headscale/pull/212) -- Beta OpenID Connect support - [#126](https://github.com/juanfont/headscale/pull/126), +- Beta OpenID Connect support [#126](https://github.com/juanfont/headscale/pull/126), [#227](https://github.com/juanfont/headscale/pull/227) ## 0.11.0 (2021-10-25) ### BREAKING -- Make headscale fetch DERP map from URL and file - [#196](https://github.com/juanfont/headscale/pull/196) +- Make headscale fetch DERP map from URL and file [#196](https://github.com/juanfont/headscale/pull/196) diff --git a/Makefile b/Makefile index 9a5b8dfa..1e08cda9 100644 --- a/Makefile +++ b/Makefile @@ -64,7 +64,6 @@ fmt-go: check-deps $(GO_SOURCES) fmt-prettier: check-deps $(DOC_SOURCES) @echo "Formatting documentation and config files..." prettier --write '**/*.{ts,js,md,yaml,yml,sass,css,scss,html}' - prettier --write --print-width 80 --prose-wrap always CHANGELOG.md .PHONY: fmt-proto fmt-proto: check-deps $(PROTO_SOURCES) From d14be8d43b6a07e0218b8daaa0c10e7db9f5b70b Mon Sep 17 00:00:00 2001 From: Kristoffer Dalby Date: Wed, 12 Nov 2025 07:11:38 -0600 Subject: [PATCH 006/148] nix: add NixOS module and tests (#2857) --- .github/workflows/nix-module-test.yml | 56 ++ CHANGELOG.md | 6 +- README.md | 2 + flake.nix | 34 +- nix/README.md | 41 ++ nix/example-configuration.nix | 145 +++++ nix/module.nix | 727 ++++++++++++++++++++++++++ nix/tests/headscale.nix | 102 ++++ 8 files changed, 1085 insertions(+), 28 deletions(-) create mode 100644 .github/workflows/nix-module-test.yml create mode 100644 nix/README.md create mode 100644 nix/example-configuration.nix create mode 100644 nix/module.nix create mode 100644 nix/tests/headscale.nix diff --git a/.github/workflows/nix-module-test.yml b/.github/workflows/nix-module-test.yml new file mode 100644 index 00000000..18f40f91 --- /dev/null +++ b/.github/workflows/nix-module-test.yml @@ -0,0 +1,56 @@ +name: NixOS Module Tests + +on: + push: + branches: + - main + pull_request: + branches: + - main + +concurrency: + group: ${{ github.workflow }}-$${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + nix-module-check: + runs-on: ubuntu-latest + permissions: + contents: read + + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 2 + + - name: Get changed files + id: changed-files + uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2 + with: + filters: | + nix: + - 'nix/**' + - 'flake.nix' + - 'flake.lock' + go: + - 'go.*' + - '**/*.go' + - 'cmd/**' + - 'hscontrol/**' + + - uses: nixbuild/nix-quick-install-action@889f3180bb5f064ee9e3201428d04ae9e41d54ad # v31 + if: steps.changed-files.outputs.nix == 'true' || steps.changed-files.outputs.go == 'true' + + - uses: nix-community/cache-nix-action@135667ec418502fa5a3598af6fb9eb733888ce6a # v6.1.3 + if: steps.changed-files.outputs.nix == 'true' || steps.changed-files.outputs.go == 'true' + with: + primary-key: + nix-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('**/*.nix', + '**/flake.lock') }} + restore-prefixes-first-match: nix-${{ runner.os }}-${{ runner.arch }} + + - name: Run NixOS module tests + if: steps.changed-files.outputs.nix == 'true' || steps.changed-files.outputs.go == 'true' + run: | + echo "Running NixOS module integration test..." + nix build .#checks.x86_64-linux.headscale -L diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e43192e..15467f79 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,10 +5,8 @@ ### Changes - Add NixOS module in repository for faster iteration [#2857](https://github.com/juanfont/headscale/pull/2857) -- Add favicon to webpages - [#2858](https://github.com/juanfont/headscale/pull/2858) -- Reclaim IPs from the IP allocator when nodes are deleted - [#2831](https://github.com/juanfont/headscale/pull/2831) +- Add favicon to webpages [#2858](https://github.com/juanfont/headscale/pull/2858) +- Reclaim IPs from the IP allocator when nodes are deleted [#2831](https://github.com/juanfont/headscale/pull/2831) ## 0.27.1 (2025-11-11) diff --git a/README.md b/README.md index dbde74d9..7381c372 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,8 @@ and container to run Headscale.** Please have a look at the [`documentation`](https://headscale.net/stable/). +For NixOS users, a module is available in [`nix/`](./nix/). + ## Talks - Fosdem 2023 (video): [Headscale: How we are using integration testing to reimplement Tailscale](https://fosdem.org/2023/schedule/event/goheadscale/) diff --git a/flake.nix b/flake.nix index 86f8b005..8d16f609 100644 --- a/flake.nix +++ b/flake.nix @@ -17,6 +17,12 @@ commitHash = self.rev or self.dirtyRev; in { + # NixOS module + nixosModules = rec { + headscale = import ./nix/module.nix; + default = headscale; + }; + overlay = _: prev: let pkgs = nixpkgs.legacyPackages.${prev.system}; @@ -38,12 +44,9 @@ subPackages = [ "cmd/headscale" ]; - ldflags = [ - "-s" - "-w" - "-X github.com/juanfont/headscale/hscontrol/types.Version=${headscaleVersion}" - "-X github.com/juanfont/headscale/hscontrol/types.GitCommitHash=${commitHash}" - ]; + meta = { + mainProgram = "headscale"; + }; }; hi = buildGo { @@ -228,24 +231,7 @@ apps.default = apps.headscale; checks = { - format = - pkgs.runCommand "check-format" - { - buildInputs = with pkgs; [ - gnumake - nixpkgs-fmt - golangci-lint - nodePackages.prettier - golines - clang-tools - ]; - } '' - ${pkgs.nixpkgs-fmt}/bin/nixpkgs-fmt ${./.} - ${pkgs.golangci-lint}/bin/golangci-lint run --fix --timeout 10m - ${pkgs.nodePackages.prettier}/bin/prettier --write '**/**.{ts,js,md,yaml,yml,sass,css,scss,html}' - ${pkgs.golines}/bin/golines --max-len=88 --base-formatter=gofumpt -w ${./.} - ${pkgs.clang-tools}/bin/clang-format -i ${./.} - ''; + headscale = pkgs.nixosTest (import ./nix/tests/headscale.nix); }; }); } diff --git a/nix/README.md b/nix/README.md new file mode 100644 index 00000000..533e4b5e --- /dev/null +++ b/nix/README.md @@ -0,0 +1,41 @@ +# Headscale NixOS Module + +This directory contains the NixOS module for Headscale. + +## Rationale + +The module is maintained in this repository to keep the code and module +synchronized at the same commit. This allows faster iteration and ensures the +module stays compatible with the latest Headscale changes. All changes should +aim to be upstreamed to nixpkgs. + +## Files + +- **[`module.nix`](./module.nix)** - The NixOS module implementation +- **[`example-configuration.nix`](./example-configuration.nix)** - Example + configuration demonstrating all major features +- **[`tests/`](./tests/)** - NixOS integration tests + +## Usage + +Add to your flake inputs: + +```nix +inputs.headscale.url = "github:juanfont/headscale"; +``` + +Then import the module: + +```nix +imports = [ inputs.headscale.nixosModules.default ]; +``` + +See [`example-configuration.nix`](./example-configuration.nix) for configuration +options. + +## Upstream + +- [nixpkgs module](https://github.com/NixOS/nixpkgs/blob/master/nixos/modules/services/networking/headscale.nix) +- [nixpkgs package](https://github.com/NixOS/nixpkgs/blob/master/pkgs/by-name/he/headscale/package.nix) + +The module in this repository may be newer than the nixpkgs version. diff --git a/nix/example-configuration.nix b/nix/example-configuration.nix new file mode 100644 index 00000000..e1f6cec7 --- /dev/null +++ b/nix/example-configuration.nix @@ -0,0 +1,145 @@ +# 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; + + # Optional: Use a specific package (defaults to pkgs.headscale) + # package = pkgs.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"; + # password_file = "/run/secrets/headscale-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_path = "/run/secrets/oidc-client-secret"; + # scope = [ "openid" "profile" "email" ]; + # allowed_domains = [ "example.com" ]; + # }; + + # Optional: Let's Encrypt TLS certificates + # tls_letsencrypt_hostname = "headscale.example.com"; + # tls_letsencrypt_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"; + }; + }; + + # 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; + # }; + # }; + # }; +} diff --git a/nix/module.nix b/nix/module.nix new file mode 100644 index 00000000..a75398fb --- /dev/null +++ b/nix/module.nix @@ -0,0 +1,727 @@ +{ config +, lib +, pkgs +, ... +}: +let + cfg = config.services.headscale; + + dataDir = "/var/lib/headscale"; + runDir = "/run/headscale"; + + cliConfig = { + # Turn off update checks since the origin of our package + # is nixpkgs and not Github. + disable_check_updates = true; + + unix_socket = "${runDir}/headscale.sock"; + }; + + settingsFormat = pkgs.formats.yaml { }; + configFile = settingsFormat.generate "headscale.yaml" cfg.settings; + cliConfigFile = settingsFormat.generate "headscale.yaml" cliConfig; + + assertRemovedOption = option: message: { + assertion = !lib.hasAttrByPath option cfg; + message = + "The option `services.headscale.${lib.options.showOption option}` was removed. " + message; + }; +in +{ + # Disable the upstream NixOS module to prevent conflicts + disabledModules = [ "services/networking/headscale.nix" ]; + + options = { + services.headscale = { + enable = lib.mkEnableOption "headscale, Open Source coordination server for Tailscale"; + + package = lib.mkPackageOption pkgs "headscale" { }; + + 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. + ::: + ''; + }; + + group = lib.mkOption { + 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; + }; + + settings = lib.mkOption { + description = '' + Overrides to {file}`config.yaml` as a Nix attribute set. + Check the [example config](https://github.com/juanfont/headscale/blob/main/config-example.yaml) + for possible options. + ''; + 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. + ''; + }; + }; + + ephemeral_node_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. + + ''; + 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."; + }; + + password_file = lib.mkOption { + type = lib.types.nullOr lib.types.path; + default = null; + example = "/run/keys/headscale-dbpassword"; + description = '' + A file containing the password corresponding to + {option}`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/kb/1081/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 use the local DNS settings of a node or override + the local DNS settings and force the use of Headscale's DNS + configuration. + ''; + example = false; + }; + + nameservers = { + global = lib.mkOption { + type = lib.types.listOf lib.types.str; + default = [ ]; + description = '' + List of nameservers to pass to Tailscale clients. + Required when {option}`override_local_dns` is true. + ''; + }; + }; + + search_domains = lib.mkOption { + type = lib.types.listOf lib.types.str; + default = [ ]; + description = '' + Search domains to inject to Tailscale clients. + ''; + example = [ "mydomain.internal" ]; + }; + }; + + 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. + ''; + }; + + client_secret_path = lib.mkOption { + type = lib.types.nullOr lib.types.str; + default = null; + description = '' + Path to OpenID Connect client secret file. Expands environment variables in format ''${VAR}. + ''; + }; + + 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_letsencrypt_hostname = lib.mkOption { + type = lib.types.nullOr lib.types.str; + default = ""; + description = '' + Domain name to request a TLS certificate for. + ''; + }; + + tls_letsencrypt_challenge_type = lib.mkOption { + type = lib.types.enum [ + "TLS-ALPN-01" + "HTTP-01" + ]; + default = "HTTP-01"; + description = '' + Type of ACME challenge to use, currently supported types: + `HTTP-01` or `TLS-ALPN-01`. + ''; + }; + + tls_letsencrypt_listen = lib.mkOption { + type = lib.types.nullOr lib.types.str; + default = ":http"; + description = '' + When HTTP-01 challenge is chosen, letsencrypt must set up a + verification endpoint, and it will be listening on: + `:http = port 80`. + ''; + }; + + tls_cert_path = lib.mkOption { + type = lib.types.nullOr lib.types.path; + default = null; + description = '' + Path to already created certificate. + ''; + }; + + tls_key_path = lib.mkOption { + type = lib.types.nullOr lib.types.path; + default = null; + description = '' + Path to key for already created certificate. + ''; + }; + + 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. + ''; + }; + }; + }; + }; + }; + }; + }; + + 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" "ephemeral_node_inactivity_timeout" ] + ) + (mkRenamedOptionModule + [ "services" "headscale" "logLevel" ] + [ "services" "headscale" "settings" "log" "level" ] + ) + (mkRenamedOptionModule + [ "services" "headscale" "openIdConnect" "clientId" ] + [ "services" "headscale" "settings" "oidc" "client_id" ] + ) + (mkRenamedOptionModule + [ "services" "headscale" "openIdConnect" "clientSecretFile" ] + [ "services" "headscale" "settings" "oidc" "client_secret_path" ] + ) + (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_letsencrypt_challenge_type" ] + ) + (mkRenamedOptionModule + [ "services" "headscale" "tls" "letsencrypt" "hostname" ] + [ "services" "headscale" "settings" "tls_letsencrypt_hostname" ] + ) + (mkRenamedOptionModule + [ "services" "headscale" "tls" "letsencrypt" "httpListen" ] + [ "services" "headscale" "settings" "tls_letsencrypt_listen" ] + ) + + (mkRemovedOptionModule [ "services" "headscale" "openIdConnect" "domainMap" ] '' + Headscale no longer uses domain_map. If you're using an old version of headscale you can still set this option via services.headscale.settings.oidc.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 dns.override_local_dns is true"; + } + (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.password_file` 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_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") + ]; + + services.headscale.settings = lib.mkMerge [ + cliConfig + { + listen_addr = lib.mkDefault "${cfg.address}:${toString cfg.port}"; + + tls_letsencrypt_cache_dir = "${dataDir}/.cache"; + } + ]; + + 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; + + systemPackages = [ cfg.package ]; + }; + + users.groups.headscale = lib.mkIf (cfg.group == "headscale") { }; + + users.users.headscale = lib.mkIf (cfg.user == "headscale") { + description = "headscale user"; + home = dataDir; + group = cfg.group; + isSystemUser = true; + }; + + systemd.services.headscale = { + description = "headscale coordination server for Tailscale"; + wants = [ "network-online.target" ]; + after = [ "network-online.target" ]; + wantedBy = [ "multi-user.target" ]; + + script = '' + ${lib.optionalString (cfg.settings.database.postgres.password_file != null) '' + export HEADSCALE_DATABASE_POSTGRES_PASS="$(head -n1 ${lib.escapeShellArg cfg.settings.database.postgres.password_file})" + ''} + + exec ${lib.getExe cfg.package} serve --config ${configFile} + ''; + + serviceConfig = + let + capabilityBoundingSet = [ "CAP_CHOWN" ] ++ lib.optional (cfg.port < 1024) "CAP_NET_BIND_SERVICE"; + in + { + Restart = "always"; + RestartSec = "5s"; + Type = "simple"; + User = cfg.user; + Group = cfg.group; + + # Hardening options + RuntimeDirectory = "headscale"; + # Allow headscale group access so users can be added and use the CLI. + RuntimeDirectoryMode = "0750"; + + StateDirectory = "headscale"; + StateDirectoryMode = "0750"; + + ProtectSystem = "strict"; + ProtectHome = true; + PrivateTmp = true; + PrivateDevices = true; + ProtectKernelTunables = true; + ProtectControlGroups = true; + RestrictSUIDSGID = true; + PrivateMounts = true; + ProtectKernelModules = true; + ProtectKernelLogs = true; + ProtectHostname = true; + ProtectClock = true; + ProtectProc = "invisible"; + ProcSubset = "pid"; + RestrictNamespaces = true; + RemoveIPC = true; + UMask = "0077"; + + CapabilityBoundingSet = capabilityBoundingSet; + AmbientCapabilities = capabilityBoundingSet; + NoNewPrivileges = true; + LockPersonality = true; + RestrictRealtime = true; + SystemCallFilter = [ + "@system-service" + "~@privileged" + "@chown" + ]; + SystemCallArchitectures = "native"; + RestrictAddressFamilies = "AF_INET AF_INET6 AF_UNIX"; + }; + }; + }; + + meta.maintainers = with lib.maintainers; [ + kradalby + misterio77 + ]; +} diff --git a/nix/tests/headscale.nix b/nix/tests/headscale.nix new file mode 100644 index 00000000..7dc93870 --- /dev/null +++ b/nix/tests/headscale.nix @@ -0,0 +1,102 @@ +{ pkgs, lib, ... }: +let + tls-cert = pkgs.runCommand "selfSignedCerts" { buildInputs = [ pkgs.openssl ]; } '' + openssl req \ + -x509 -newkey rsa:4096 -sha256 -days 365 \ + -nodes -out cert.pem -keyout key.pem \ + -subj '/CN=headscale' -addext "subjectAltName=DNS:headscale" + + mkdir -p $out + cp key.pem cert.pem $out + ''; +in +{ + name = "headscale"; + meta.maintainers = with lib.maintainers; [ + kradalby + misterio77 + ]; + + nodes = + let + headscalePort = 8080; + stunPort = 3478; + peer = { + services.tailscale.enable = true; + security.pki.certificateFiles = [ "${tls-cert}/cert.pem" ]; + }; + in + { + peer1 = peer; + peer2 = peer; + + headscale = { + services = { + headscale = { + enable = true; + port = headscalePort; + settings = { + server_url = "https://headscale"; + ip_prefixes = [ "100.64.0.0/10" ]; + derp.server = { + enabled = true; + region_id = 999; + stun_listen_addr = "0.0.0.0:${toString stunPort}"; + }; + dns = { + base_domain = "tailnet"; + extra_records = [ + { + name = "foo.bar"; + type = "A"; + value = "100.64.0.2"; + } + ]; + override_local_dns = false; + }; + }; + }; + nginx = { + enable = true; + virtualHosts.headscale = { + addSSL = true; + sslCertificate = "${tls-cert}/cert.pem"; + sslCertificateKey = "${tls-cert}/key.pem"; + locations."/" = { + proxyPass = "http://127.0.0.1:${toString headscalePort}"; + proxyWebsockets = true; + }; + }; + }; + }; + networking.firewall = { + allowedTCPPorts = [ + 80 + 443 + ]; + allowedUDPPorts = [ stunPort ]; + }; + environment.systemPackages = [ pkgs.headscale ]; + }; + }; + + testScript = '' + start_all() + headscale.wait_for_unit("headscale") + headscale.wait_for_open_port(443) + + # Create headscale user and preauth-key + headscale.succeed("headscale users create test") + authkey = headscale.succeed("headscale preauthkeys -u 1 create --reusable") + + # Connect peers + up_cmd = f"tailscale up --login-server 'https://headscale' --auth-key {authkey}" + peer1.execute(up_cmd) + peer2.execute(up_cmd) + + # Check that they are reachable from the tailnet + peer1.wait_until_succeeds("tailscale ping peer2") + peer2.wait_until_succeeds("tailscale ping peer1.tailnet") + assert (res := peer1.wait_until_succeeds("${lib.getExe pkgs.dig} +short foo.bar").strip()) == "100.64.0.2", f"Domain {res} did not match 100.64.0.2" + ''; +} From 89285c317b66b806663c6ce1a78fcf09488d8c6a Mon Sep 17 00:00:00 2001 From: Kristoffer Dalby Date: Fri, 24 Oct 2025 15:43:29 +0200 Subject: [PATCH 007/148] templates: migrate OIDC callback to elem-go Replace html/template with type-safe elem-go templating for OIDC callback page. Improves consistency with other templates and provides compile-time safety. All UI elements and styling preserved. --- hscontrol/assets/oidc_callback_template.html | 307 ------------------- hscontrol/oidc.go | 23 +- hscontrol/oidc_template_test.go | 63 ++++ hscontrol/templates/general.go | 18 +- hscontrol/templates/oidc_callback.go | 223 ++++++++++++++ hscontrol/templates/register_web.go | 8 +- 6 files changed, 304 insertions(+), 338 deletions(-) delete mode 100644 hscontrol/assets/oidc_callback_template.html create mode 100644 hscontrol/oidc_template_test.go create mode 100644 hscontrol/templates/oidc_callback.go diff --git a/hscontrol/assets/oidc_callback_template.html b/hscontrol/assets/oidc_callback_template.html deleted file mode 100644 index 2236f365..00000000 --- a/hscontrol/assets/oidc_callback_template.html +++ /dev/null @@ -1,307 +0,0 @@ - - - - - - Headscale Authentication Succeeded - - - -

-
- -
- -
-
Signed in via your OIDC provider
-

- {{.Verb}} as {{.User}}, you can now close this window. -

-
-
-
-

Not sure how to get started?

-

- Check out beginner and advanced guides on, or read more in the - documentation. -

- - - - - - - View the headscale documentation - - - - - - - - View the tailscale documentation - -
-
- - diff --git a/hscontrol/oidc.go b/hscontrol/oidc.go index 7c7895c6..2164215a 100644 --- a/hscontrol/oidc.go +++ b/hscontrol/oidc.go @@ -4,10 +4,8 @@ import ( "bytes" "cmp" "context" - _ "embed" "errors" "fmt" - "html/template" "net/http" "slices" "strings" @@ -16,6 +14,7 @@ import ( "github.com/coreos/go-oidc/v3/oidc" "github.com/gorilla/mux" "github.com/juanfont/headscale/hscontrol/db" + "github.com/juanfont/headscale/hscontrol/templates" "github.com/juanfont/headscale/hscontrol/types" "github.com/juanfont/headscale/hscontrol/types/change" "github.com/juanfont/headscale/hscontrol/util" @@ -191,13 +190,6 @@ type oidcCallbackTemplateConfig struct { Verb string } -//go:embed assets/oidc_callback_template.html -var oidcCallbackTemplateContent string - -var oidcCallbackTemplate = template.Must( - template.New("oidccallback").Parse(oidcCallbackTemplateContent), -) - // OIDCCallbackHandler handles the callback from the OIDC endpoint // Retrieves the nkey from the state cache and adds the node to the users email user // TODO: A confirmation page for new nodes should be added to avoid phishing vulnerabilities @@ -573,21 +565,12 @@ func (a *AuthProviderOIDC) handleRegistration( return !nodeChange.Empty(), nil } -// TODO(kradalby): -// Rewrite in elem-go. func renderOIDCCallbackTemplate( user *types.User, verb string, ) (*bytes.Buffer, error) { - var content bytes.Buffer - if err := oidcCallbackTemplate.Execute(&content, oidcCallbackTemplateConfig{ - User: user.Display(), - Verb: verb, - }); err != nil { - return nil, fmt.Errorf("rendering OIDC callback template: %w", err) - } - - return &content, nil + html := templates.OIDCCallback(user.Display(), verb).Render() + return bytes.NewBufferString(html), nil } // getCookieName generates a unique cookie name based on a cookie value. diff --git a/hscontrol/oidc_template_test.go b/hscontrol/oidc_template_test.go new file mode 100644 index 00000000..5eb2b9f5 --- /dev/null +++ b/hscontrol/oidc_template_test.go @@ -0,0 +1,63 @@ +package hscontrol + +import ( + "os" + "path/filepath" + "testing" + + "github.com/juanfont/headscale/hscontrol/templates" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestOIDCCallbackTemplate(t *testing.T) { + tests := []struct { + name string + userName string + verb string + }{ + { + name: "logged_in_user", + userName: "test@example.com", + verb: "Logged in", + }, + { + name: "registered_user", + userName: "newuser@example.com", + verb: "Registered", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Render using the elem-go template + html := templates.OIDCCallback(tt.userName, tt.verb).Render() + + // Verify the HTML contains expected elements + assert.Contains(t, html, "") + assert.Contains(t, html, "Headscale Authentication Succeeded") + assert.Contains(t, html, tt.verb) + assert.Contains(t, html, tt.userName) + assert.Contains(t, html, "You can now close this window") + + // Verify Material for MkDocs design system CSS is present + assert.Contains(t, html, "Material for MkDocs") + assert.Contains(t, html, "Roboto") + assert.Contains(t, html, ".md-typeset") + + // Verify SVG elements are present + assert.Contains(t, html, "