diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index d60dba8d..35a34ea1 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -34,3 +34,4 @@ jobs: run: | make format make lint + make smoke diff --git a/AGENTS.md b/AGENTS.md index 7e97b59c..1f60b777 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,7 +9,7 @@ This repository holds itsUP, a Docker-based GitOps deployment platform, together ### Rules -- **Runtime-mutating commands run only on the container host** — the machine whose own LAN IP equals `SSH_HOST` in `.env`. The `itsup` CLI enforces this fail-closed: `run`, `apply`, `down`, `dns`, `proxy`, `svc`, `monitor`, and `logs` refuse on any machine whose detected LAN IP does not match `SSH_HOST`, and `make install-runtime` refuses off-host before it touches systemd/launchd. `make uninstall-runtime` is the recovery exception: it may run off-host to remove stale local systemd/launchd integration and local remnants from the current checkout, but it does not invoke the host-only `itsup down` path there. The GitOps, config, secrets, and read commands (`pull`, `commit`, `status`, `create`, `init`, `validate`, `migrate`, `encrypt`, `decrypt`, `diff-secrets`, `edit-secret`, `sops-key`) run anywhere. Off-host a runtime-mutating command would spin up the entire stack locally; the gate is not self-grantable. The command-level contract is in `project/itsup/spec/cli`; operational detail in `project/itsup/spec/runtime-operations`. +- **Runtime-mutating commands run only on the container host** — the machine whose own LAN IP equals `SSH_HOST` in `.env`. The `itsup` CLI enforces this fail-closed: `run`, `apply`, `down`, `dns`, `proxy`, `svc`, and `monitor` refuse on any machine whose detected LAN IP does not match `SSH_HOST`, and `make install-runtime` refuses off-host before it touches systemd/launchd. `make uninstall-runtime` is the recovery exception: it may run off-host to remove stale local systemd/launchd integration and local remnants from the current checkout, but it does not invoke the host-only `itsup down` path there. The GitOps, config, secrets, and read commands (`pull`, `commit`, `status`, `create`, `init`, `validate`, `migrate`, `encrypt`, `decrypt`, `diff-secrets`, `edit-secret`, `sops-key`) run anywhere. Off-host a runtime-mutating command would spin up the entire stack locally; the gate is not self-grantable. The command-level contract is in `project/itsup/spec/cli`; operational detail in `project/itsup/spec/runtime-operations`. - **Operate from the repository root.** Never stay `cd`'d into a subdirectory. For directory-scoped work use `(cd && )` with relative paths. - **Operate from the repository root.** Never stay `cd`'d into a subdirectory. For directory-scoped work use `(cd && )` with relative paths. - **itsUP's own code is not containerized.** The Python CLI (`itsup`), API server, monitoring, DNS honeypot-management, and proxy-config code all run on the host. Only upstream project services are containerized. Never containerize itsUP code. diff --git a/Makefile b/Makefile index e74f8c9f..1c798302 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: help install install-runtime uninstall-runtime restart status lint format clean +.PHONY: help install install-runtime uninstall-runtime restart status lint format smoke clean help: ## Show this help message @echo 'Usage: make [target]' @@ -31,6 +31,9 @@ format: ## Format code lint: ## Run linter @FILES_FROM="$(FILES_FROM)" ./bin/lint.sh +smoke: ## Start the CLI from the installed environment + @.venv/bin/itsup --help + clean: ## Remove generated artifacts and caches find . -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true find . -type f -name '*.pyc' -delete diff --git a/README.md b/README.md index b179f6df..5ef784ad 100644 --- a/README.md +++ b/README.md @@ -238,7 +238,7 @@ itsup svc exec web sh # Execute commands in containers # Container Security Monitor itsup monitor start [--flags] # Start security monitor itsup monitor stop # Stop monitor -instrukt-ai-logs itsup --include monitor # Tail monitor diagnostics +journalctl -u itsup-monitor -f # Follow monitor diagnostics (container host) itsup monitor cleanup # Review blacklist itsup monitor report # Generate threat report @@ -379,8 +379,8 @@ itsup monitor start --report-only --use-opensnitch # Stop monitor itsup monitor stop -# View diagnostics -instrukt-ai-logs itsup --include monitor +# View diagnostics (container host) +journalctl -u itsup-monitor # Generate threat intelligence report itsup monitor report @@ -509,25 +509,38 @@ On Linux hosts, `make install-runtime` (via `bin/install-bringup.sh`) configures ##### Runtime logs -`itsup logs` is the front door for API, monitor, and supervised runtime logs: +itsUP has no log command of its own; each log is read with the tool that owns it. + +**Application logs** — what itsUP's own code writes through the shared InstruktAI logger (the `itsup` CLI and the one-shot jobs) — are read with the InstruktAI logs tool, the same instruction as for every other InstruktAI project: ```bash -itsup logs api -f +instrukt-ai-logs itsup --since 1h # Everything from the last hour, merged by time +instrukt-ai-logs itsup --follow # Print the recent window, then follow ``` -Application logs can also be queried with the InstruktAI logs CLI: +On a systemd host the nightly backup's unit runs as root and writes its own file into the same log directory; a launchd agent runs as the user and is not affected. The logger keeps each file private to the user that wrote it, so the itsUP user cannot read the backup's file, and the unfiltered commands above meet it in one of three ways: + +- The backup's file was written inside the time window: the command stops with a permission error and prints nothing, with or without `--follow`. +- It was written before the window and `--follow` is not given: lines from the other sources print as usual, but when nothing in the window matches and the backup's file holds the most recent write in the directory, the command stops with a permission error. A bare `instrukt-ai-logs itsup` meets that after a backup run that wrote to its file, until the CLI next logs. +- It was written before the window and `--follow` is given: no error, but the backup's new lines are left out and nothing says so. + +`instrukt-ai-logs itsup --include itsup` reads and follows the CLI's file in every case, and the backup's file needs root. + +`instrukt-ai-logs` is the logger project's standalone tool ([InstruktAI/logging](https://github.com/InstruktAI/logging)). The Python package itsUP depends on only writes logs, so `make install` does not provide the tool. Install it once on each machine that reads these logs: ```bash -instrukt-ai-logs -f itsup +curl -LsSf https://github.com/InstruktAI/logging/releases/latest/download/instrukt-ai-logs-installer.sh | sh ``` -Systemd-managed units (bringup, healthcheck, backup) log to stdout/stderr, captured by the journal: `journalctl -u `. On macOS, launchd captures agent output to `~/Library/Logs/itsup..log`. +**Supervised units** — the API server, the security monitor, bringup, apply, backup, and the healthcheck — write to stdout/stderr, captured by the journal: `journalctl -u ` (for example `journalctl -u itsup-api -f`). On macOS, launchd captures agent output to `~/Library/Logs/itsup..log`. + +**The Traefik access log** is Traefik's own JSON file, `logs/access.log`, read with ordinary tools. #### 6. Monitor ```bash # Follow raw Traefik access records -itsup logs access -f +tail -f logs/access.log ``` ### Configure services diff --git a/commands/logs.py b/commands/logs.py deleted file mode 100644 index 6cf5a54b..00000000 --- a/commands/logs.py +++ /dev/null @@ -1,275 +0,0 @@ -"""Route itsUP runtime logs to the backend that owns each target.""" - -import json -import platform -import plistlib -import re -import shutil -import subprocess -from dataclasses import dataclass -from datetime import datetime, timezone -from enum import StrEnum -from pathlib import Path - -import click -from instrukt_ai_logging.cli import iter_follow_lines -from instrukt_ai_logging.logging import parse_since - -from commands.common import fail -from lib.paths import access_log_file, display_path - - -class LogTarget(StrEnum): - """The closed set of runtime logs itsUP exposes.""" - - API = "api" - MONITOR = "monitor" - BRINGUP = "bringup" - APPLY = "apply" - BACKUP = "backup" - HEALTHCHECK = "healthcheck" - ACCESS = "access" - - -@dataclass(frozen=True) -class LogDescriptor: - """Describe one target and the backend identities that can serve it.""" - - description: str - linux_unit: str | None = None - macos_agent: str | None = None - - -@dataclass(frozen=True) -class LogOptions: - """The selection predicates shared by every backend.""" - - follow: bool - cutoff: datetime | None - pattern: re.Pattern[str] | None - - -LOG_TARGETS: dict[LogTarget, LogDescriptor] = { - LogTarget.API: LogDescriptor("API service requests and failures", "itsup-api", "api"), - LogTarget.MONITOR: LogDescriptor("container security monitor lifecycle", "itsup-monitor"), - LogTarget.BRINGUP: LogDescriptor("runtime bringup service", "itsup-bringup", "bringup"), - LogTarget.APPLY: LogDescriptor("configuration apply service", "itsup-apply", "apply"), - LogTarget.BACKUP: LogDescriptor("backup service", "itsup-backup", "backup"), - LogTarget.HEALTHCHECK: LogDescriptor("host healthcheck service", "pi-healthcheck"), - LogTarget.ACCESS: LogDescriptor("Traefik access records"), -} - - -def complete_log_target(ctx: click.Context, param: click.Parameter, incomplete: str) -> list[str]: - """Complete log targets from the router's single target registry.""" - return [target.value for target in LogTarget if target.value.startswith(incomplete)] - - -def _fail(message: str) -> None: - fail(message) - raise SystemExit(1) - - -def _parse_target(value: str) -> LogTarget: - try: - return LogTarget(value) - except ValueError as exc: - valid_targets = ", ".join(target.value for target in LogTarget) - _fail(f"Unknown log target: {value}. Valid targets: {valid_targets}") - raise AssertionError("unreachable") from exc - - -def _parse_options(follow: bool, since: str | None, pattern: str | None) -> LogOptions: - cutoff = None - if since is not None: - try: - cutoff = datetime.now(timezone.utc) - parse_since(since) - except ValueError as exc: - _fail(f"Invalid --since value: {exc}") - raise AssertionError("unreachable") from exc - - compiled_pattern = None - if pattern is not None: - try: - compiled_pattern = re.compile(pattern) - except re.error as exc: - _fail(f"Invalid --grep pattern: {exc}") - raise AssertionError("unreachable") from exc - - return LogOptions(follow=follow, cutoff=cutoff, pattern=compiled_pattern) - - -def _emit_if_selected(line: str, options: LogOptions) -> None: - if options.pattern is None or options.pattern.search(line): - click.echo(line, nl=False) - - -def _load_state(systemctl: str, unit: str) -> str | None: - try: - # systemctl has no project-provided or Python-native binding. - result = subprocess.run( - [systemctl, "show", unit, "--property=LoadState"], - capture_output=True, - check=True, - text=True, - ) - except subprocess.CalledProcessError: - return None - - key, separator, value = result.stdout.strip().partition("=") - return value if key == "LoadState" and separator else None - - -def _journal_tools() -> tuple[str, str]: - journalctl = shutil.which("journalctl") - systemctl = shutil.which("systemctl") - if journalctl is None: - _fail("Cannot read unit logs: journalctl is not available.") - if systemctl is None: - _fail("Cannot inspect unit logs: systemctl is not available.") - - assert journalctl is not None - assert systemctl is not None - return journalctl, systemctl - - -def _require_loaded_unit(systemctl: str, unit: str) -> None: - """Refuse a journal query when its unit is absent or unusable.""" - load_state = _load_state(systemctl, unit) - if load_state == "loaded": - return - - observed = load_state if load_state is not None else "unavailable" - _fail(f"Cannot read {unit}: unit LoadState is {observed}.") - - -def _journal_command(journalctl: str, unit: str, options: LogOptions) -> list[str]: - command = [journalctl, "-u", unit] - if options.cutoff is not None: - command.extend(["--since", options.cutoff.astimezone().strftime("%Y-%m-%d %H:%M:%S")]) - if options.follow: - command.extend(["-n", "0", "-f"]) - return command - - -def _stream_journal(command: list[str], options: LogOptions, unit: str) -> None: - try: - # journalctl has no project-provided or Python-native binding. - with subprocess.Popen(command, stdout=subprocess.PIPE, text=True) as process: - if process.stdout is None: - _fail(f"Cannot read {unit}: journalctl produced no output stream.") - try: - for line in process.stdout: - _emit_if_selected(line, options) - except KeyboardInterrupt: - process.terminate() - return - return_code = process.wait() - except OSError as exc: - _fail(f"Cannot read {unit}: unable to start journalctl ({exc}).") - return - - if return_code != 0: - raise SystemExit(return_code) - - -def _read_journal(unit: str, options: LogOptions) -> None: - journalctl, systemctl = _journal_tools() - _require_loaded_unit(systemctl, unit) - _stream_journal(_journal_command(journalctl, unit, options), options, unit) - - -def _access_line_is_in_window(line: str, cutoff: datetime) -> bool: - """Return whether a raw Traefik record proves it is inside the time window.""" - try: - record = json.loads(line) - if not isinstance(record, dict): - return False - timestamp = record.get("time", record.get("StartUTC")) - if not isinstance(timestamp, str): - return False - parsed = datetime.fromisoformat(timestamp.replace("Z", "+00:00")) - if parsed.tzinfo is None: - return False - return parsed.astimezone(timezone.utc) >= cutoff - except (json.JSONDecodeError, ValueError, TypeError): - return False - - -def _emit_file_line(line: str, options: LogOptions, *, is_access_log: bool) -> None: - if options.cutoff is not None and (not is_access_log or not _access_line_is_in_window(line, options.cutoff)): - return - _emit_if_selected(line, options) - - -def _read_file(path: Path, options: LogOptions, *, is_access_log: bool) -> None: - if not path.exists(): - _fail(f"Cannot read log file: {display_path(path)} does not exist.") - - try: - if options.follow: - for line in iter_follow_lines(path, start_at_end=True): - _emit_file_line(line, options, is_access_log=is_access_log) - return - - with path.open("r", encoding="utf-8", errors="replace", newline="") as log_file: - for line in log_file: - _emit_file_line(line, options, is_access_log=is_access_log) - except KeyboardInterrupt: - return - except OSError as exc: - _fail(f"Cannot read log file {display_path(path)}: {exc}.") - - -def _macos_log_file(agent: str) -> Path: - plist_path = Path.home() / "Library" / "LaunchAgents" / f"ai.itsup.{agent}.plist" - if not plist_path.is_file(): - _fail(f"Cannot read macOS log: {display_path(plist_path)} does not exist.") - - try: - with plist_path.open("rb") as plist_file: - plist = plistlib.load(plist_file) - except (OSError, plistlib.InvalidFileException) as exc: - _fail(f"Cannot read macOS log configuration {display_path(plist_path)}: {exc}.") - raise AssertionError("unreachable") from exc - - stdout_path = plist.get("StandardOutPath") - if not isinstance(stdout_path, str) or not stdout_path: - _fail(f"Cannot read macOS log: {display_path(plist_path)} has no StandardOutPath.") - assert isinstance(stdout_path, str) - return Path(stdout_path) - - -@click.command() -@click.argument("target", required=False, shell_complete=complete_log_target) -@click.option("--follow", "follow", "-f", is_flag=True, help="Print new records as they arrive.") -@click.option("--since", help="Select records from a duration such as 10m or 2h ago.") -@click.option("--grep", "pattern", help="Select records matching this case-sensitive regular expression.") -def logs(target: str | None, follow: bool, since: str | None, pattern: str | None) -> None: - """View TARGET's runtime logs, or list the available targets.""" - if target is None: - for log_target, descriptor in LOG_TARGETS.items(): - click.echo(f"{log_target.value} — {descriptor.description}") - return - - log_target = _parse_target(target) - options = _parse_options(follow, since, pattern) - if log_target is LogTarget.ACCESS: - _read_file(access_log_file(), options, is_access_log=True) - return - - descriptor = LOG_TARGETS[log_target] - operating_system = platform.system() - if operating_system == "Linux" and descriptor.linux_unit is not None: - _read_journal(descriptor.linux_unit, options) - return - - if operating_system == "Darwin": - if descriptor.macos_agent is None: - _fail(f"{log_target.value} logs are available only on Linux.") - if options.cutoff is not None: - _fail("Cannot use --since for macOS unit logs: launchd output has no per-line timestamp.") - _read_file(_macos_log_file(descriptor.macos_agent), options, is_access_log=False) - return - - _fail(f"{log_target.value} logs are unavailable on {operating_system}.") diff --git a/docs/domain/itsup/policy/host-boundary.md b/docs/domain/itsup/policy/host-boundary.md index 7e3281a5..a862a769 100644 --- a/docs/domain/itsup/policy/host-boundary.md +++ b/docs/domain/itsup/policy/host-boundary.md @@ -7,7 +7,7 @@ description: Which itsUP CLI commands may run on which machine — runtime-mutat - **Runtime-mutating commands run only on the container host** — the machine whose own LAN IP equals `SSH_HOST` in `.env`. These deploy or stop containers: `apply`, `run`, `down`, and the - stack-management commands (`dns`, `proxy`, `svc`, `monitor`, `logs`), plus host provisioning + stack-management commands (`dns`, `proxy`, `svc`, `monitor`), plus host provisioning (`make install-runtime`). On the host, the full command set is available. - **GitOps, config, secret, and read commands run anywhere.** `pull`, `commit`, `status`, `create`, `init`, `validate`, `migrate`, `edit-secret`, `encrypt`, `decrypt`, `diff-secrets`, diff --git a/docs/domain/itsup/spec/cli-surface.md b/docs/domain/itsup/spec/cli-surface.md index 9f739689..7348e9d4 100644 --- a/docs/domain/itsup/spec/cli-surface.md +++ b/docs/domain/itsup/spec/cli-surface.md @@ -43,8 +43,8 @@ Container host only — runtime-mutating (see itsUP Host Boundary): - `itsup down` — stop all containers. - `itsup dns` / `itsup proxy` — DNS and proxy stack management. - `itsup svc ` — service operations for a project. -- `itsup monitor` — container security monitor management. Diagnostics are viewed via - `instrukt-ai-logs itsup --include monitor`, not a subcommand. +- `itsup monitor` — container security monitor management. Its diagnostics are in the host + supervisor's journal (`journalctl -u itsup-monitor`), not behind a subcommand. ## Known caveats diff --git a/docs/project/design/logging.md b/docs/project/design/logging.md index 78d19fa2..b76ffd98 100644 --- a/docs/project/design/logging.md +++ b/docs/project/design/logging.md @@ -70,19 +70,22 @@ The library writes a single folder per app, `$XDG_STATE_HOME/instrukt-ai/itsup/` (fallback `~/.local/state/instrukt-ai/itsup/`), and one plain-text logfmt file per producing process, selected by the `source=` argument of `configure_logging` (`configure_logging(app, *, source=None)` → `f"{source or app}.log"`, a single -file-only `WatchedFileHandler` on the root logger — the library has no console -mode, which is why the daemon paths configure their own stdout handler instead): +file-only handler on the root logger — the library has no console mode, which is +why the daemon paths configure their own stdout handler instead): - `instrukt-ai/itsup/itsup.log` — the `itsup` CLI and the ephemeral CLI-family one-shots (`bin/migrate_to_v2.py`, `bin/write_artifacts.py`), via `configure_logging("itsup")` (default source). - `instrukt-ai/itsup/backup.log` — the backup job, via - `configure_logging("itsup", source="backup")`. + `configure_logging("itsup", source="backup")`. The systemd unit runs the job + as root with `HOME` pinned to the itsUP user, so on a systemd host root owns + this file inside that user's folder (Failure modes); the launchd agent runs + it as the user, who then owns the file. -Each producing process declares its own `source`; the empty-source default (one -shared `.log`) is deliberately avoided because multiple independent -processes must not share one `WatchedFileHandler` file. This mirrors TeleClaude's -convention (`configure_logging("teleclaude", source="cron")`). +A producer that runs on its own trigger declares its own `source` and gets its +own file; the CLI and the CLI-family one-shots share the default `itsup.log`. +This mirrors TeleClaude's convention +(`configure_logging("teleclaude", source="cron")`). **Container logs (ephemeral):** every Docker container also writes to Docker's default json-file driver. Read via `docker logs` / `docker compose logs`. These @@ -96,22 +99,20 @@ are not part of the `logs/` directory contract. detection feed. - **`journalctl -u `** (Linux) / the agent's `StandardOutPath` file (macOS) — the daemon diagnostics. -- **`instrukt-ai-logs itsup`** — the logger's shipped viewer (console script - `instrukt_ai_logging.cli:main`) tails the diagnostic folder: folder- and - rotation-aware, with `--since`, `--include `, and `--grep`. itsUP - carries no diagnostic-log viewer of its own. +- **`instrukt-ai-logs itsup`** — the logger project's reader for the + diagnostic folder, and the one instruction for reading what itsUP's own code + logged through the logger: it merges the per-source files by timestamp, + rotated archives included, and narrows with `--since`, `--include `, + `--grep`, and `--follow`. It is the logger project's standalone tool, + released and installed separately from the `instruktai-python-logger` + package itsUP depends on, which is the writer only: neither `make install` + nor syncing itsUP's environment provides it. Each machine that reads these + logs installs it once with the logger project's own installer, whose README + carries the step. - **Operators** via direct `tail`/`zcat` on `logs/access.log`. -- **`itsup logs `** — the itsUP-side front door to these sinks, host-only - like the other runtime commands because every backend it reads exists only on - the container host. It routes each target to whichever backend already holds it: - the supervised units (`api`, `monitor`, `bringup`, `apply`, `backup`, - `healthcheck`) to their journal (`journalctl -u ` on Linux, the launchd - agent's `StandardOutPath` file on macOS), and `access` to `logs/access.log`, - whose lines it emits verbatim. Bare `itsup logs` lists the targets with - descriptions; `--follow`, `--grep`, and `--since` narrow the read, with - `--since` refused for a macOS unit target whose supervisor-less stream carries - no per-line time. No target exists for an upstream project — those stay - `docker`-led via `itsup svc`/`proxy`/`dns` — and none for interactive CLI runs. + +itsUP carries no log reader of its own: every sink above is read with the tool +that owns it. ## Invariants @@ -148,15 +149,10 @@ are not part of the `logs/` directory contract. CrowdSec parses it for threat detection; a second writer in a second format would corrupt the feed. The API's access records go to its own journal. - **The access log is read as-is; itsUP renders no access line.** Every reader — - operator `tail`, `itsup logs access`, CrowdSec — sees Traefik's JSON record - byte-for-byte. itsUP ships no formatter for it, because the record's single - format is the thing that makes it a parseable threat-detection feed, and a - second rendering of the same line is a second format to keep in step. Selecting - which lines to emit is not rendering: `itsup logs access --grep` matches a regex - against the raw line and `--since` reads the record's own timestamp field - (`time`, else `StartUTC` — RFC3339, emitted by default because the generated - static config declares no `accessLog.fields` drop), then emits the line - unchanged. + operator `tail`, CrowdSec — sees Traefik's JSON record byte-for-byte. itsUP + ships no formatter for it, because the record's single format is the thing + that makes it a parseable threat-detection feed, and a second rendering of the + same line is a second format to keep in step. - **The access log rotates in place, so `logs/access.log` is stable across rotation for every reader on it.** The host's daily logrotate run rotates it with `copytruncate`: Traefik holds the file open with `O_APPEND` and takes no @@ -186,13 +182,17 @@ restarts of the unit and rotate under the host's journald retention. On macOS th API's equivalent is `~/Library/Logs/itsup.api.log`. **Viewing CLI and one-shot diagnostics (`instrukt-ai-logs itsup [--include -] [--since W] [--grep RE]`):** the shipped viewer resolves the files -under `instrukt-ai/itsup/` and follows them (rotation-aware). `--include backup` -narrows to `backup.log`; with no filter it merges every source in the folder. +] [--since W] [--grep RE] [--follow]`):** the logger project's reader +resolves the files under `instrukt-ai/itsup/` and prints the requested window +merged by timestamp; `--follow` then keeps printing new lines across rotation. +`--include itsup` narrows to `itsup.log`; with no filter it merges every source +written inside the window, each of which the reading user must be able to open. +On a systemd host the backup's file is one the itsUP user cannot open (Failure +modes). -**Viewing the access log:** `itsup logs access` on the container host, or -`tail`/`zcat` on `logs/access.log` directly. Either way the JSON record is what -the reader sees; nothing reformats it. +**Viewing the access log:** `tail`/`zcat` on `logs/access.log`, or any other +ordinary text tool. The JSON record is what the reader sees; nothing reformats +it. **Threat detection:** Traefik appends each request to `logs/access.log` → the CrowdSec acquisition source (`crowdsec/acquis.yml`) parses it under the `traefik` @@ -217,6 +217,43 @@ and operator banners are unaffected. written — there is no degraded or console-fallback mode. A process that cannot open its file fails fast rather than starting blind. The daemon paths have no such failure: stdout is always available. +- **A root-written file in the itsUP user's diagnostic folder.** On a systemd + host the backup unit runs the job as root with `HOME` pinned to the itsUP + user (`samples/systemd/itsup-backup.service`), so root creates `backup.log` + in that user's folder; a launchd agent runs as the user and is not affected. + At the logger release itsUP locks, the writer keeps every file readable by + its producing user only and re-applies that each time it opens the file, so + the itsUP user cannot read `backup.log` at all. The reader is installed + separately and itsUP pins no release of it. At the release that matches the + lock, an unfiltered `instrukt-ai-logs itsup` from the itsUP user meets that + file in one of three ways: + + - **The file was last written inside the requested window.** The read ends + with a permission error and prints nothing, not even from the sources it + could read, with or without `--follow`. + - **The file was last written before the window, without `--follow`.** Lines + from the readable sources inside the window print as usual. When nothing in + the window matches, the read ends with a permission error if that file + holds the folder's most recent write: that is the state from a backup run + that wrote to its file until an `itsup` command next logs. + - **The file was last written before the window, with `--follow`.** The + window prints from the readable sources and the follow starts without an + error, but the file is left out of it: lines the backup writes from then on + never appear, and nothing reports that they are missing. + + Naming only sources that user owns (`--include itsup`) reads and follows them + in every case; `backup.log` is readable only as root. The same holds for + every further root-run producer routed through the logger, and the container + security monitor's unit also runs as root. +- **Root as the first writer.** The writer creates every missing directory on + the way to the folder owned by the process that asks and closed to everyone + else. When a root-run producer is the first to log on a host where the itsUP + user's state directory does not exist yet, those directories end up owned by + root, and the itsUP user's own processes then fail at `configure_logging`: + the `itsup` CLI does not start. On an installed host the itsUP user has + normally logged first — `make install-runtime` starts bringup, which runs + `itsup` as that user — so the folder exists and is user-owned before the + nightly backup writes into it. - **Journal retention exhausted.** journald caps its own store; once the cap is reached the oldest records are discarded. A host that needs a longer daemon history raises the cap rather than reintroducing a file sink, which would put @@ -225,13 +262,12 @@ and operator banners are unaffected. marker, `monitor/core.py:_get_last_processed_timestamp` returns `None` and the monitor reprocesses the docker-log window from scratch — correct, just less efficient. -- **Access-log line with no readable timestamp.** Nothing parses the record on the - read path, so a malformed line reaches every reader intact and reading never - fails on it. Only a time filter needs the field: under `itsup logs access - --since`, a line whose `time`/`StartUTC` is absent or unparseable is **excluded** - — the reader cannot prove it falls inside the requested window, and admitting it - would silently widen the window the operator asked for. Without `--since` the - same line is emitted like any other. - **Container removal.** Container (Docker json-file) logs are lost when the container is removed; only the `logs/` files, the journal, and the instrukt-ai diagnostic folder persist. + +## See Also + +- https://github.com/InstruktAI/logging — the logger project: its README + carries the `instrukt-ai-logs` install step and the reader's options, and + `docs/contract.md` the file location, format, and permission contract. diff --git a/docs/project/policy/repository-conventions.md b/docs/project/policy/repository-conventions.md index 66d676f4..e6290ed6 100644 --- a/docs/project/policy/repository-conventions.md +++ b/docs/project/policy/repository-conventions.md @@ -7,7 +7,7 @@ visibility: 'internal' ## Rules -- **Runtime-mutating commands run only on the container host** — the machine whose own LAN IP equals `SSH_HOST` in `.env`. The `itsup` CLI enforces this fail-closed: `run`, `apply`, `down`, `dns`, `proxy`, `svc`, `monitor`, and `logs` refuse on any machine whose detected LAN IP does not match `SSH_HOST`, and `make install-runtime` refuses off-host before it touches systemd/launchd. `make uninstall-runtime` is the recovery exception: it may run off-host to remove stale local systemd/launchd integration and local remnants from the current checkout, but it does not invoke the host-only `itsup down` path there. The GitOps, config, secrets, and read commands (`pull`, `commit`, `status`, `create`, `init`, `validate`, `migrate`, `encrypt`, `decrypt`, `diff-secrets`, `edit-secret`, `sops-key`) run anywhere. Off-host a runtime-mutating command would spin up the entire stack locally; the gate is not self-grantable. The command-level contract is in `project/itsup/spec/cli`; operational detail in `project/itsup/spec/runtime-operations`. +- **Runtime-mutating commands run only on the container host** — the machine whose own LAN IP equals `SSH_HOST` in `.env`. The `itsup` CLI enforces this fail-closed: `run`, `apply`, `down`, `dns`, `proxy`, `svc`, and `monitor` refuse on any machine whose detected LAN IP does not match `SSH_HOST`, and `make install-runtime` refuses off-host before it touches systemd/launchd. `make uninstall-runtime` is the recovery exception: it may run off-host to remove stale local systemd/launchd integration and local remnants from the current checkout, but it does not invoke the host-only `itsup down` path there. The GitOps, config, secrets, and read commands (`pull`, `commit`, `status`, `create`, `init`, `validate`, `migrate`, `encrypt`, `decrypt`, `diff-secrets`, `edit-secret`, `sops-key`) run anywhere. Off-host a runtime-mutating command would spin up the entire stack locally; the gate is not self-grantable. The command-level contract is in `project/itsup/spec/cli`; operational detail in `project/itsup/spec/runtime-operations`. - **Operate from the repository root.** Never stay `cd`'d into a subdirectory. For directory-scoped work use `(cd && )` with relative paths. - **Operate from the repository root.** Never stay `cd`'d into a subdirectory. For directory-scoped work use `(cd && )` with relative paths. - **itsUP's own code is not containerized.** The Python CLI (`itsup`), API server, monitoring, DNS honeypot-management, and proxy-config code all run on the host. Only upstream project services are containerized. Never containerize itsUP code. diff --git a/docs/project/spec/cli.md b/docs/project/spec/cli.md index 9683fe8e..c7bc863a 100644 --- a/docs/project/spec/cli.md +++ b/docs/project/spec/cli.md @@ -114,83 +114,6 @@ in `project/itsup/spec/secrets-management`. (`lib/deploy.py:62`, `lib/deploy.py:257`) -### `logs` — the routing front door over fragmented log backends - -`itsup logs [TARGET]` is the single entry point to itsUP's host-side logs. Each -target names a producer, and the command routes it to whichever backend actually -holds that producer's records; the operator never needs to know which. It is -host-only (see the gate below) and read-only. - -**Bare invocation is discovery**: `itsup logs` with no target prints every -routable target with its description, one pair per line, and exits 0. An -unrecognised target exits 1 and prints the routable set. Every rejection the -router owns — unknown target, malformed option value, unavailable backend — exits -1; the CLI declares no exit-2 contract, so parameter failures are translated -rather than left to the parser's own usage exit. - -**Targets and their backends.** Six supervised-unit targets — `api`, `monitor`, -`bringup`, `apply`, `backup`, `healthcheck` — plus the file-backed `access` -(Traefik's JSON access log under `logs/`, emitted verbatim: the router is a raw -passthrough reader of that file and formats nothing, because the record's single -JSON format is what makes it CrowdSec's parseable feed). -The unit targets resolve per platform, following the supervision contract in -`project/itsup/design/logging`: on Linux to `journalctl -u `; on macOS to the -launchd agent's `StandardOutPath`, read from the installed agent's own plist so -the path comes from what launchd actually loaded. `monitor` and `healthcheck` are -Linux-only daemons and have no macOS agent, so on macOS they are refused with -that reason rather than routed to a file that will never exist. - -There is deliberately **no `` target** — container logs stay docker-led -through `itsup svc` / `proxy` / `dns` — and **no `cli` target**: interactive runs -are observed live, and their diagnostic file is read with `instrukt-ai-logs -itsup`. - -**One option surface, translated per backend.** `-f/--follow`, `--since`, and -`--grep` mean the same thing on every target. They **select** which lines are -emitted; none of them changes a line's content, on any backend. Every line the -router prints is the line its backend produced. - -- `--since` takes the duration grammar `{s,m,h,d}`. The journal's own - `--since` rejects a bare duration, so the router parses the duration and hands - the journal an absolute timestamp. The `access` backend has no such grammar to - delegate to, so the router applies the same cutoff itself, reading each JSON - record's own timestamp field (`time`, else `StartUTC`) to decide inclusion and - then emitting the record unchanged. A record whose timestamp field is absent or - unparseable is excluded: the router cannot prove it is inside the window, and - admitting it would silently widen the window that was asked for. -- `--grep` is a case-sensitive Python regular expression, applied by the router - itself to each complete line just before it is printed — on every backend. For - `access` that line is the raw JSON record, so a pattern can match a field name - as readily as a value. The journal's own `-g` is not used: it matches only the - record's message field, while the line the operator sees also carries the - supervisor's timestamp and identity, and its smart-case default would make the - same pattern mean different things on different backends. -- `--follow` is future-only everywhere: it streams what arrives after the - command starts and never replays history first. The journal is asked for - `-n 0` alongside `-f` so it does not emit its recent window, matching the - file backend, which follows from the end of the file. Following `access` - survives the host's `copytruncate` rotation of that file - (`project/itsup/design/logging`). -- An invalid duration or an invalid regex is rejected at the option boundary with - exit 1 before any backend is reached. - -**`--since` has one designed exception: macOS unit targets.** Filtering by time -requires a per-line time, and the supervisor is what supplies it — journald does, -launchd does not. A launchd agent's `StandardOutPath` captures the daemon's -stream verbatim, and that stream deliberately carries no timestamp because the -supervisor is expected to add one. So `--since` against a macOS unit target exits -1 naming that reason, while `--follow` and `--grep` remain available there. The -`access` target is unaffected on either platform: its record carries its own -RFC3339 timestamp field, which is what the router reads. - -**Every unavailability path refuses, never degrades.** A unit target with no -reader on this platform, and a unit target whose unit is not installed, each exit -1 naming the reason. Unit existence is established before the query — a unit is -usable only when its `LoadState` is `loaded`, and any other value is reported -rather than interpreted — because a journal query against an absent unit succeeds -with empty output. - - ### Host-identity gate (runtime-mutating commands are host-only) The CLI group refuses runtime-mutating commands on any machine that is not the @@ -204,8 +127,8 @@ per-command argument parsing, and off-host even `itsup --help` i refused. - **Host-only** (refused off-host, exit 1): `run`, `apply`, `down`, `dns`, - `proxy`, `svc`, `monitor`, `logs`. `make install-runtime` refuses off-host - before it touches systemd/launchd (`bin/install-bringup.sh`). + `proxy`, `svc`, `monitor`. `make install-runtime` refuses off-host before it + touches systemd/launchd (`bin/install-bringup.sh`). - **Available anywhere** (GitOps + config + secrets + read): `pull`, `commit`, `status`, `create`, `init`, `validate`, `migrate`, `encrypt`, `decrypt`, @@ -275,10 +198,8 @@ The CLI emits only these — there is no 2/3/130 contract. running container's `com.docker.compose.config-hash` label (container-label based), not a hash stored on disk. - Runtime-mutating commands (`run`, `apply`, `down`, `dns`, `proxy`, `svc`, - `monitor`) and the read-only `logs` router are **host-only** and refuse - fail-closed off-host (detected LAN IP ≠ `SSH_HOST`); see the host-identity - gate above. `logs` is gated not because it mutates but because every backend - it reads exists only on the container host. + `monitor`) are **host-only** and refuse fail-closed off-host (detected LAN IP + ≠ `SSH_HOST`); see the host-identity gate above. ## See Also diff --git a/docs/third-party/instrukt-ai-logging/log-reading-primitives.md b/docs/third-party/instrukt-ai-logging/log-reading-primitives.md deleted file mode 100644 index d7d1eb57..00000000 --- a/docs/third-party/instrukt-ai-logging/log-reading-primitives.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -description: Verified read-side contracts of the installed instrukt-ai-logging package that itsUP reuses — parse_since duration grammar, the rotation-aware iter_follow_lines follower, and why iter_recent_log_lines_merged cannot window Traefik's JSON access log. ---- - -# instrukt-ai-logging — Read-Side Primitives - -Curated from the installed package -(`.venv/lib/python3.14/site-packages/instrukt_ai_logging/`) for the `itsup logs` -router, which reuses the library's readers rather than re-deriving them. The -write side (`configure_logging`, `get_logger`) is covered by -`project/itsup/design/logging`; only what the router consumes is recorded here. - -## Export surface - -`instrukt_ai_logging.__all__` exports the write side plus `resolve_log_file` / -`resolve_log_files`. The three read primitives below are **not** in `__all__`; -the package's own shipped viewer (`instrukt_ai_logging.cli:main`) imports them -from `instrukt_ai_logging.logging` and `instrukt_ai_logging.cli` directly, which -is the same import path a consumer must use. Treat them as a supported-by-usage -surface, not a declared public API: a package upgrade can move them without a -deprecation cycle. - -## `logging.parse_since(value: str) -> timedelta` - -- Accepts `` where unit is one of `s`, `m`, `h`, `d` - (case-insensitive, surrounding whitespace stripped). The number part is - validated with `str.isdigit()`, so `0s` is accepted and yields a zero window; - a sign or a decimal point is rejected. -- Raises `ValueError` on an empty string, a non-digit number part, or an - unrecognised unit. -- Returns a `timedelta` only — it never formats a timestamp, so a consumer - targeting a backend with its own time grammar does that conversion itself. - -## `cli.iter_follow_lines(log_file, *, poll_interval_s=0.25, start_at_end=True, max_lines=None, max_seconds=None)` - -- Yields lines appended to a file, `tail -f` style, by polling. -- Waits for the file to appear if it does not exist yet. -- Detects **rotation** (inode change — reopens and reads the new file from the - start) and **truncation** (offset beyond size — seeks back to the start). -- `max_lines` / `max_seconds` bound the generator. - -## `logging.iter_recent_log_lines_merged(files, since: timedelta)` - -- Merges multiple files into one chronologically ordered stream, skipping files - whose mtime predates the cutoff. -- Keys entirely on `parse_log_timestamp`, which reads the **first - whitespace-delimited token** of each line and requires the form - `YYYY-MM-DDTHH:MM:SS.mmmZ`. A line without that leading token inherits the - previous parsed timestamp from its own file. -- **Not usable for Traefik's JSON access log**: those lines begin with `{`, carry - their time inside a `time` / `StartUTC` field, and therefore have no leading - token to parse. A consumer windowing that format supplies its own predicate over - the JSON field. - -Verified directly against the installed package source in this repository's -`.venv` — `instrukt_ai_logging/logging.py`, `instrukt_ai_logging/cli.py`, and -`instrukt_ai_logging/__init__.py`. diff --git a/docs/third-party/systemd/journalctl-querying.md b/docs/third-party/systemd/journalctl-querying.md index 492fe0d2..2dd4bb87 100644 --- a/docs/third-party/systemd/journalctl-querying.md +++ b/docs/third-party/systemd/journalctl-querying.md @@ -4,9 +4,10 @@ description: Verified journalctl query semantics itsUP delegates to — the --si # journalctl — Query Semantics -Curated from the `journalctl(1)` manual page for the `itsup logs` router, which -delegates its unit-backed targets to `journalctl` rather than reading the journal -itself. Only the flags the router composes are covered. +Curated from the `journalctl(1)` manual page for the journal reads itsUP +relies on rather than reading the journal itself: an operator's +`journalctl -u ` on a supervised unit, and the failure alert composer's +bounded tail of a failed unit (`lib/alerting.py`). ## Time window — `--since` / `--until` diff --git a/docs/third-party/systemd/systemctl-unit-introspection.md b/docs/third-party/systemd/systemctl-unit-introspection.md index 0dabe618..933a7f2d 100644 --- a/docs/third-party/systemd/systemctl-unit-introspection.md +++ b/docs/third-party/systemd/systemctl-unit-introspection.md @@ -4,9 +4,10 @@ description: 'What systemctl documents — and does not document — for decidin # systemctl — Unit Introspection for an Existence Predicate -Curated for the `itsup logs` router, which must distinguish "this unit is not -installed" from "this unit is installed and quiet" before querying the journal. -Only what bears on that predicate is recorded. +Curated for a caller that must distinguish "this unit is not installed" from +"this unit is installed and quiet", as the runtime installer does when it +checks whether the daemon units are registered (`bin/install-bringup.sh`). Only +what bears on that predicate is recorded. ## What is not documented diff --git a/itsup/cli.py b/itsup/cli.py index a9fdb124..c9f2fb79 100644 --- a/itsup/cli.py +++ b/itsup/cli.py @@ -19,7 +19,6 @@ from commands.edit_secret import edit_secret from commands.encrypt import encrypt from commands.init import init -from commands.logs import logs from commands.migrate import migrate_cmd from commands.monitor import monitor from commands.projects import projects @@ -32,7 +31,7 @@ from commands.validate import validate from lib.host_gate import require_host -HOST_ONLY = frozenset({"run", "apply", "down", "dns", "proxy", "svc", "monitor", "logs"}) +HOST_ONLY = frozenset({"run", "apply", "down", "dns", "proxy", "svc", "monitor"}) @click.group(context_settings={"allow_interspersed_args": False, "help_option_names": ["-h", "--help"]}) @@ -100,7 +99,6 @@ def cli(ctx: click.Context, verbose: int) -> None: cli.add_command(edit_secret) cli.add_command(sops_key) cli.add_command(projects) -cli.add_command(logs) def main() -> None: diff --git a/lib/paths.py b/lib/paths.py index 8828390b..96db9ca6 100644 --- a/lib/paths.py +++ b/lib/paths.py @@ -63,16 +63,6 @@ def projects_dir() -> Path: return root() / "projects" -def logs_dir() -> Path: - """Resolve the runtime logs tree.""" - return root() / "logs" - - -def access_log_file() -> Path: - """Resolve Traefik's JSON access-log file.""" - return logs_dir() / "access.log" - - def project_dir(name: str) -> Path: """Resolve one project's config directory.""" return projects_dir() / name diff --git a/pyproject.toml b/pyproject.toml index 1b76670b..b28033bc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -22,9 +22,7 @@ dependencies = [ "boto3", "click", "fastapi", - # itsup logs imports instrukt_ai_logging.cli, which releases from 0.7.0 no - # longer ship; without the upper bound the CLI fails to start. - "instruktai-python-logger>=0.6.6,<0.11", + "instruktai-python-logger>=0.10", "ipwhois", "jinja2-cli", "netifaces", diff --git a/uv.lock b/uv.lock index 8f586363..ef807ace 100644 --- a/uv.lock +++ b/uv.lock @@ -538,11 +538,11 @@ wheels = [ [[package]] name = "instruktai-python-logger" -version = "0.10.2" +version = "0.10.3" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/51/42/4add0fc4138b6b8615bfc96d09d6f694c5fbcfd4108fe49dc9c6e672bb53/instruktai_python_logger-0.10.2.tar.gz", hash = "sha256:89a21ba1bf6fccf6f3ee7e3f6887b4eed510f33ea533523e0c81c54767c3f608", size = 41430, upload-time = "2026-11-13T07:07:57.692Z" } +sdist = { url = "https://files.pythonhosted.org/packages/10/e8/38e58474e1a8b22519415ea7c4909b6a8d58484f6a23c4922e13589b2ec3/instruktai_python_logger-0.10.3.tar.gz", hash = "sha256:33e103f593bfc96d9c7e97986de455d9e6d340803a006b23e9f8d33300747cbd", size = 42334, upload-time = "2026-11-21T13:49:13.707Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/5c/e5/50e6c201fa706d0a6f8e7ec948ba4d0f8d033614523ceab623866989736e/instruktai_python_logger-0.10.2-py3-none-any.whl", hash = "sha256:47b57e10825e41c79ce9da579f3b649e77e9172be98dba484211d41fe6bb08da", size = 21769, upload-time = "2026-11-13T07:07:56.61Z" }, + { url = "https://files.pythonhosted.org/packages/4d/7f/eb72b0bb6278d39695f36dd6d746ae06307fcb0a9bc3794bd54a3c57516b/instruktai_python_logger-0.10.3-py3-none-any.whl", hash = "sha256:62939f277b1b513677066bee5afc01e434cd8841179a0205f9a9e204c5caa767", size = 22248, upload-time = "2026-11-21T13:49:12.789Z" }, ] [[package]] @@ -603,7 +603,7 @@ requires-dist = [ { name = "boto3" }, { name = "click" }, { name = "fastapi" }, - { name = "instruktai-python-logger", specifier = ">=0.6.6,<0.11" }, + { name = "instruktai-python-logger", specifier = ">=0.10" }, { name = "ipwhois" }, { name = "jinja2-cli" }, { name = "netifaces" },