diff --git a/.gitignore b/.gitignore index fb97674..faa86f9 100644 --- a/.gitignore +++ b/.gitignore @@ -52,3 +52,4 @@ mutants/ # Local Bootstrap & Operational Scripts scripts/bootstrap_lldap_users.py scripts/bootstrap_*.py +!scripts/bootstrap_token.py diff --git a/docs/appctl.md b/docs/appctl.md index 73fce4e..8264beb 100644 --- a/docs/appctl.md +++ b/docs/appctl.md @@ -47,6 +47,98 @@ Under Milestone P4, `appctl` operates as a centralized operational control plane └────────────────────────────────────────────────┘ ``` +### Operator Admin Token Bootstrapping & Rotation + +`appctl` implements zero-trust authorization across three roles: `homelab-admin`, `homelab-operator`, and `homelab-viewer`. Local Unix domain socket (`/run/homelab/appctl.sock`) callers without a token are granted `homelab-viewer` privileges via `SO_PEERCRED` for non-sensitive read-only commands (e.g., `appctl list`, `appctl status`, `appctl ssl`). + +Sensitive inspection (e.g., `appctl config ` which renders secrets in Compose definitions) and all mutating operations (e.g., `appctl up`, `appctl restart`, `appctl update`) require an authenticated Bearer token. + +#### Role of `~/.config/homelab/token` +The thin CLI client resolves Bearer tokens in the following order of precedence: +1. Direct CLI flag: `--token ` +2. Environment variable: `APPCTL_TOKEN` +3. Local operator token file: `~/.config/homelab/token` (mode `0600`) +4. System service token file: `/run/secrets/appctl/token` + +The standard operator setup stores a 256-bit hex Bearer token with mode `0600` in `~/.config/homelab/token`. + +#### Generating a Token (`scripts/bootstrap_token.py`) +To generate an operator token and its matching SHA-256 descriptor: + +```bash +python3 scripts/bootstrap_token.py +``` + +This utility: +1. Generates a cryptographically secure 256-bit token (`secrets.token_hex(32)`). +2. Computes the SHA-256 digest: `hashlib.sha256(raw_token.encode("utf-8")).hexdigest()`. +3. Ensures `~/.config/homelab` exists with mode `0700`. +4. Writes the raw Bearer token to `~/.config/homelab/token` with mode `0600`. +5. Outputs the JSON descriptor matching `TokenDescriptor` in `scripts/appctl_auth.py`: + +```json +{ + "token_id": "operator-admin", + "identity": "operator", + "role": "homelab-admin", + "sha256": "4a12...<64-hex-sha256>" +} +``` + +> [!NOTE] +> The raw secret is **never** printed to stdout or stderr. Only the descriptor snippet (containing the SHA-256 digest) is output. To print only the JSON snippet for automation or piping, pass `--print-json`. + +#### Registering the Descriptor in SOPS +Insert the generated JSON descriptor into your encrypted SOPS secrets store (`nixos/secrets.yaml`): + +```bash +sops nixos/secrets.yaml +``` + +Under `appctl.tokens_json`, add the entry to the JSON list: +```yaml +appctl: + tokens_json: | + [ + { + "token_id": "operator-admin", + "identity": "operator", + "role": "homelab-admin", + "sha256": "<64-hex-sha256>" + } + ] +``` + +Save and exit your editor (SOPS will re-encrypt the file), then project the updated secrets: +```bash +sudo nixos-rebuild switch --flake ~/Core#server +``` +This updates `/run/secrets/appctl/tokens.json` (owned by `homelab-appctl:homelab-operators`, mode `0400`), which `homelab-appctl.service` consumes. + +#### Verifying Token Authentication +Verify permissions using both unauthenticated and authenticated queries: + +1. **Viewer Inspection** (succeeds without token via `SO_PEERCRED`): + ```bash + appctl health + # Output: OK (homelab-appctl.service operational) + ``` + +2. **Admin-Gated Operation** (requires `homelab-admin` Bearer token): + ```bash + appctl config docs + # Renders the resolved Compose YAML with injected secrets + ``` + If the token is missing or mismatched, `appctl` returns `401 Unauthorized` or `403 Forbidden` with `ERR_PERMISSION_DENIED`. + +#### Token Rotation Workflow +To rotate an operator token: +1. Run `python3 scripts/bootstrap_token.py --force --token-id "operator-admin-$(date +%Y%m%d)"`. +2. Open `sops nixos/secrets.yaml` and add the new descriptor to `appctl.tokens_json`. Keep the old entry temporarily if multiple sessions share it, or replace it immediately. +3. Run `sudo nixos-rebuild switch --flake ~/Core#server` to apply the updated token store. +4. Verify CLI operations (`appctl config docs`). +5. Remove the deprecated token descriptor from `nixos/secrets.yaml` and re-run `nixos-rebuild switch`. + --- ## 2. CLI Command Reference diff --git a/docs/plans/p4-refactor-and-decoupling-plan.md b/docs/plans/p4-refactor-and-decoupling-plan.md index b360ed6..a204fc5 100644 --- a/docs/plans/p4-refactor-and-decoupling-plan.md +++ b/docs/plans/p4-refactor-and-decoupling-plan.md @@ -59,11 +59,11 @@ This plan establishes the concrete implementation work packages to resolve these - [x] **Task 1.5**: Update `systemd.tmpfiles.rules` in `nixos/modules/homeserver.nix` from `a+` to recursive `A+` on `sitesDir`. ### Phase 2: CLI Hardening & Status Parity -- [ ] **Task 2.1**: Update `scripts/appctl` to fail closed when `[ ! -S "$SOCKET_PATH" ]`, removing the silent fallback to legacy Bash. -- [ ] **Task 2.2**: Update `_op_workload_list` in `scripts/appctl_router.py` to query live container health (`get_docker_status()`). -- [ ] **Task 2.3**: Update `_format_workload_table` in `scripts/appctl_cli.py` to render the `STATUS` column (`🟢 Running (1)` / `🔴 Stopped`). -- [ ] **Task 2.4**: Bootstrap operator admin token documentation and setup instructions in `docs/appctl.md` and `docs/secrets-and-state.md`. -- [ ] **Task 2.5**: Wire `--build` and `--no-cache` in `scripts/appctl_cli.py`, pass `--pull` during `compose_build` in `scripts/appctl_router.py`, and document source-built action policy in `docs/appctl.md`. +- [x] **Task 2.1**: Update `scripts/appctl` to fail closed when `[ ! -S "$SOCKET_PATH" ]`, removing the silent fallback to legacy Bash. +- [x] **Task 2.2**: Update `_op_workload_list` in `scripts/appctl_router.py` to query live container health (`get_docker_status()`). +- [x] **Task 2.3**: Update `_format_workload_table` in `scripts/appctl_cli.py` to render the `STATUS` column (`🟢 Running (1)` / `🔴 Stopped`). +- [x] **Task 2.4**: Bootstrap operator admin token documentation and setup instructions in `docs/appctl.md` and `docs/secrets-and-state.md`. +- [x] **Task 2.5**: Wire `--build` and `--no-cache` in `scripts/appctl_cli.py`, pass `--pull` during `compose_build` in `scripts/appctl_router.py`, and document source-built action policy in `docs/appctl.md`. ### Phase 3: Architectural Records & Roadmap Synchronization - [x] **Task 3.1**: Update `ROADMAP.md` (P6 redefined as Homelab MCP Gateway; on-server AI compiler deprecated). diff --git a/docs/secrets-and-state.md b/docs/secrets-and-state.md index 28448c0..a17eb49 100644 --- a/docs/secrets-and-state.md +++ b/docs/secrets-and-state.md @@ -64,9 +64,9 @@ Generated by `nixos/modules/traefik-deployments.nix`. Projects shared infrastruc ### C. Control Plane Token Store (`/run/secrets/appctl/tokens.json` & `/run/secrets/gitops/appctl_token`) Provisioned from `nixos/secrets.yaml` (`appctl/tokens_json` and `gitops/appctl_token`): -* `/run/secrets/appctl/tokens.json`: Owned by `homelab-appctl:homelab-operators` with strict mode `0400` (enforced fail-closed by `TokenStore._verify_permissions()`). Stores SHA-256 hex digests of Bearer secrets mapped to `token_id`, `identity`, and `role` (`homelab-admin`, `homelab-operator`, `homelab-viewer`). +* `/run/secrets/appctl/tokens.json`: Owned by `homelab-appctl:homelab-operators` with strict mode `0400` (enforced fail-closed by `TokenStore._verify_permissions()`, rejecting any write bit or group/world readability). Stores a JSON array of SHA-256 token descriptors (`token_id`, `identity`, `role`, and 64-hex `sha256`) defined under `appctl/tokens_json` in `nixos/secrets.yaml`. * `/run/secrets/gitops/appctl_token`: Owned by `config.homelab.operatorUser` (mode `0400`). Supplies the `homelab-operator` Bearer secret to `homelab-gitops.service` when delegating `workload.update` to `homelab-appctl.service`. -* `~/.config/homelab/token`: Local operator Bearer token (mode `0600`) read by `appctl_cli.py` for interactive CLI mutations. +* `~/.config/homelab/token`: Local operator Bearer token written with strict mode `0600` (in a mode `0700` directory) by `scripts/bootstrap_token.py`. Automatically discovered and resolved by `appctl_cli.py` for authenticated operator interactions without needing `--token` flags or environment variables. --- diff --git a/scripts/bootstrap_token.py b/scripts/bootstrap_token.py new file mode 100755 index 0000000..abc3b01 --- /dev/null +++ b/scripts/bootstrap_token.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +""" +bootstrap_token.py — Operator Admin Token Bootstrap & Rotation Helper (WP4) + +Generates a 256-bit cryptographically secure Bearer token, saves it locally +with strict mode 0600 permissions (~/.config/homelab/token), and prints the +corresponding JSON descriptor for insertion into the SOPS tokens store +(nixos/secrets.yaml -> appctl/tokens_json). +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import secrets +import stat +import sys +from pathlib import Path +from typing import Any + +# Ensure scripts directory is in sys.path when executed directly +_scripts_dir = Path(__file__).resolve().parent +if str(_scripts_dir) not in sys.path: + sys.path.insert(0, str(_scripts_dir)) + +from appctl_auth import Role, TokenDescriptor + +DEFAULT_TOKEN_PATH = Path.home() / ".config/homelab/token" +DEFAULT_TOKEN_ID = "operator-admin" +DEFAULT_IDENTITY = "operator" +DEFAULT_ROLE = Role.ADMIN.value + + +def generate_token() -> tuple[str, str]: + """Generate a 256-bit cryptographically secure Bearer token and its SHA-256 digest.""" + raw_token = secrets.token_hex(32) + digest = hashlib.sha256(raw_token.encode()).hexdigest() + return raw_token, digest + + +def write_token_file(path: Path, raw_token: str, force: bool = False) -> None: + """ + Write raw Bearer token to path with mode 0600. + Ensures parent directory exists with mode 0700. + Fails closed if the destination exists and force is False. + """ + path = path.expanduser().resolve() + if path.exists() and not force: + raise FileExistsError( + f"Token file '{path}' already exists. Use --force / -f to overwrite." + ) + + parent = path.parent + if not parent.exists(): + parent.mkdir(mode=0o700, parents=True, exist_ok=True) + try: + parent.chmod(0o700) + except OSError: + pass + elif stat.S_IMODE(parent.stat().st_mode) != 0o700: + try: + parent.chmod(0o700) + except OSError: + pass + + fd = os.open(str(path), os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o600) + try: + content = f"{raw_token}\n".encode() + os.write(fd, content) + finally: + os.close(fd) + + path.chmod(0o600) + + +def bootstrap_token( + output_path: Path | str = DEFAULT_TOKEN_PATH, + token_id: str = DEFAULT_TOKEN_ID, + identity: str = DEFAULT_IDENTITY, + role: str = DEFAULT_ROLE, + force: bool = False, +) -> dict[str, Any]: + """ + Generate Bearer token, persist to file with strict permissions, + and return the validated TokenDescriptor dictionary. + """ + path = Path(output_path).expanduser().resolve() + raw_token, digest = generate_token() + + write_token_file(path, raw_token, force=force) + + # Validate against TokenDescriptor model + validated = TokenDescriptor( + token_id=token_id, + identity=identity, + role=Role(role), + sha256=digest, + ) + return validated.model_dump(mode="json") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description="Bootstrap or rotate an operator Bearer token for appctl." + ) + parser.add_argument( + "-o", + "--output", + default=str(DEFAULT_TOKEN_PATH), + help=f"Destination token file path (default: {DEFAULT_TOKEN_PATH})", + ) + parser.add_argument( + "--token-id", + default=DEFAULT_TOKEN_ID, + help=f"Token descriptor ID (default: {DEFAULT_TOKEN_ID})", + ) + parser.add_argument( + "--identity", + default=DEFAULT_IDENTITY, + help=f"Caller identity (default: {DEFAULT_IDENTITY})", + ) + parser.add_argument( + "--role", + default=DEFAULT_ROLE, + choices=[r.value for r in Role], + help=f"Role assignment (default: {DEFAULT_ROLE})", + ) + parser.add_argument( + "-f", + "--force", + action="store_true", + help="Overwrite existing token file if present", + ) + parser.add_argument( + "--print-json", + action="store_true", + help="Output only the JSON descriptor snippet for piping/automation", + ) + + args = parser.parse_args(argv) + + try: + descriptor = bootstrap_token( + output_path=args.output, + token_id=args.token_id, + identity=args.identity, + role=args.role, + force=args.force, + ) + except FileExistsError as err: + sys.stderr.write(f"Error: {err}\n") + return 1 + + json_snippet = json.dumps(descriptor, indent=2) + + if args.print_json: + sys.stdout.write(f"{json_snippet}\n") + else: + sys.stdout.write( + f"Generated Bearer token and saved to {args.output} (mode 0600).\n\n" + f"Add the following descriptor to your SOPS tokens store (nixos/secrets.yaml -> appctl/tokens_json):\n\n" + f"{json_snippet}\n\n" + f"After updating nixos/secrets.yaml with `sops nixos/secrets.yaml`, apply changes with:\n" + f" sudo nixos-rebuild switch --flake ~/Core#server\n" + ) + + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/unit/test_bootstrap_token.py b/tests/unit/test_bootstrap_token.py new file mode 100644 index 0000000..7993c59 --- /dev/null +++ b/tests/unit/test_bootstrap_token.py @@ -0,0 +1,175 @@ +""" +tests/unit/test_bootstrap_token.py — Unit Tests for Operator Admin Token Bootstrap Helper (WP4) + +Verifies: +- 256-bit secure token generation (64 hex characters) and matching SHA-256 digest +- Strict 0600 file mode and 0700 parent directory creation +- TokenDescriptor Pydantic validation (scripts/appctl_auth.py) +- Refusal to overwrite existing token file without --force +- Overwriting existing token file when --force is supplied +- Secrets leakage prevention: raw Bearer token never appears in stdout/stderr +- Machine-readable JSON output via --print-json +""" + +from __future__ import annotations + +import hashlib +import json +import stat +import string +from pathlib import Path +from typing import Any + +import pytest +from appctl_auth import Role, TokenDescriptor +from bootstrap_token import ( + bootstrap_token, + generate_token, + main, + write_token_file, +) + + +def test_generate_token_produces_64_hex_token_and_valid_sha256() -> None: + raw_token, digest = generate_token() + assert len(raw_token) == 64 + assert all(c in string.hexdigits for c in raw_token) + assert len(digest) == 64 + assert all(c in string.hexdigits for c in digest) + expected_digest = hashlib.sha256(raw_token.encode("utf-8")).hexdigest() + assert digest == expected_digest + + +def test_write_token_file_creates_file_and_enforces_0600(tmp_path: Path) -> None: + token_file = tmp_path / "subdir" / "token" + write_token_file(token_file, "secret-token-12345") + assert token_file.is_file() + assert stat.S_IMODE(token_file.stat().st_mode) == 0o600 + assert stat.S_IMODE(token_file.parent.stat().st_mode) == 0o700 + assert token_file.read_text(encoding="utf-8") == "secret-token-12345\n" + + +def test_bootstrap_token_generates_file_with_strict_mode_0600(tmp_path: Path) -> None: + nested_dir = tmp_path / "nested" / "homelab" + token_file = nested_dir / "token" + + descriptor = bootstrap_token(output_path=token_file) + + assert token_file.is_file() + # Check parent directory mode is 0700 + parent_mode = stat.S_IMODE(nested_dir.stat().st_mode) + assert parent_mode == 0o700, f"Expected parent mode 0700, got {oct(parent_mode)}" + + # Check token file mode is 0600 + file_mode = stat.S_IMODE(token_file.stat().st_mode) + assert file_mode == 0o600, f"Expected file mode 0600, got {oct(file_mode)}" + + raw_token = token_file.read_text(encoding="utf-8").strip() + assert len(raw_token) == 64 + assert hashlib.sha256(raw_token.encode("utf-8")).hexdigest() == descriptor["sha256"] + + +def test_bootstrap_token_descriptor_validates_against_token_descriptor(tmp_path: Path) -> None: + token_file = tmp_path / "custom_token" + descriptor = bootstrap_token( + output_path=token_file, + token_id="custom-admin", + identity="operator", + role="homelab-admin", + ) + + validated = TokenDescriptor.model_validate(descriptor) + assert validated.token_id == "custom-admin" + assert validated.identity == "operator" + assert validated.role == Role.ADMIN + assert len(validated.sha256) == 64 + + +def test_bootstrap_token_refuses_overwrite_without_force(tmp_path: Path) -> None: + token_file = tmp_path / "token" + bootstrap_token(output_path=token_file) + original_token = token_file.read_text(encoding="utf-8") + + with pytest.raises(FileExistsError, match="already exists"): + bootstrap_token(output_path=token_file, force=False) + + assert token_file.read_text(encoding="utf-8") == original_token + + +def test_bootstrap_token_overwrites_with_force(tmp_path: Path) -> None: + token_file = tmp_path / "token" + descriptor1 = bootstrap_token(output_path=token_file) + first_token = token_file.read_text(encoding="utf-8").strip() + + descriptor2 = bootstrap_token(output_path=token_file, force=True) + second_token = token_file.read_text(encoding="utf-8").strip() + + assert first_token != second_token + assert descriptor1["sha256"] != descriptor2["sha256"] + assert descriptor2["sha256"] == hashlib.sha256(second_token.encode("utf-8")).hexdigest() + + +def test_bootstrap_cli_never_prints_raw_secret_to_stdout_or_stderr( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + token_file = tmp_path / "token" + ret = main(["--output", str(token_file)]) + assert ret == 0 + + raw_token = token_file.read_text(encoding="utf-8").strip() + captured = capsys.readouterr() + + # RAW SECRET MUST NEVER APPEAR IN STDOUT OR STDERR + assert raw_token not in captured.out, "Leak: raw token found in stdout!" + assert raw_token not in captured.err, "Leak: raw token found in stderr!" + + # Ensure stdout provides helpful human guidance + assert "operator-admin" in captured.out + assert "sops nixos/secrets.yaml" in captured.out + + +def test_bootstrap_cli_print_json_outputs_valid_json_descriptor( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + token_file = tmp_path / "token" + ret = main(["--output", str(token_file), "--print-json"]) + assert ret == 0 + + raw_token = token_file.read_text(encoding="utf-8").strip() + captured = capsys.readouterr() + + assert raw_token not in captured.out + assert captured.err == "" + + # Must be cleanly parseable as pure JSON + data: dict[str, Any] = json.loads(captured.out.strip()) + validated = TokenDescriptor.model_validate(data) + assert validated.token_id == "operator-admin" + assert validated.identity == "operator" + assert validated.role == Role.ADMIN + assert validated.sha256 == hashlib.sha256(raw_token.encode("utf-8")).hexdigest() + + +def test_bootstrap_cli_refuses_overwrite_and_exits_nonzero( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + token_file = tmp_path / "token" + assert main(["--output", str(token_file)]) == 0 + + ret = main(["--output", str(token_file)]) + assert ret != 0 + captured = capsys.readouterr() + assert "already exists" in captured.err + + +def test_bootstrap_cli_force_overwrites( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + token_file = tmp_path / "token" + assert main(["--output", str(token_file)]) == 0 + tok1 = token_file.read_text(encoding="utf-8").strip() + + assert main(["--output", str(token_file), "--force"]) == 0 + tok2 = token_file.read_text(encoding="utf-8").strip() + + assert tok1 != tok2 diff --git a/todo.txt b/todo.txt index cc6659f..9f2df63 100644 --- a/todo.txt +++ b/todo.txt @@ -41,6 +41,6 @@ x 2026-10-23 (A) Change systemd.tmpfiles.rules to recursive A+ ACLs for Sites an x 2026-10-23 (A) Declare global Git safe.directory for /home/operator/Sites/* in nixos/configuration.nix +nixos @git x 2026-10-30 (B) Enforce fail-closed check on daemon socket availability and remove silent Bash fallback in scripts/appctl +cli @security x 2026-10-30 (B) Restore live container status inspection in workload.list and format STATUS column in scripts/appctl_cli.py +cli @ux -(B) Bootstrap operator admin token provisioning helper and documentation in docs/appctl.md and docs/secrets-and-state.md +docs @auth +x 2026-10-30 (B) Bootstrap operator admin token provisioning helper and documentation in docs/appctl.md and docs/secrets-and-state.md +docs @auth x 2026-10-30 (B) Wire --build/--no-cache and pass --pull during compose_build in scripts/appctl_router.py and scripts/appctl_cli.py +build @p4 (C) Deprecate P6 on-server AI authoring compiler in favor of external Homelab MCP Gateway in ROADMAP.md and ADR 0002 +docs @roadmap