G: G4 Drift guard and docs commit the spec and fail tests on drift

This commit is contained in:
ari committed 2026-10-20 15:54:13 -04:00
1 parent 869b6818e9
commit 34a1e1644c
5 files changed
+1986

No files matched your search

+2
View File
@@ -89,6 +89,8 @@ curl -N -H "Authorization: Bearer $TOKEN" 'http://127.0.0.1:1984/api/v1/journal/
Full route table with parameters: [docs/api.md](docs/api.md).
The whole surface is also a generated OpenAPI 3.1 document, [`docs/openapi.json`](docs/openapi.json): `GET /api/v1/openapi.json` serves it (same bearer token), `slinuxm openapi [--peers]` prints it offline without reading any config or token, and `x-mcp-tools` in it lists every MCP tool with its JSON Schema. Regenerate with `cargo run -- openapi --peers > docs/openapi.json`; a test fails if the file is stale.
## MCP
Endpoint: `http://127.0.0.1:1984/mcp` (Streamable HTTP, same bearer token). Eight tools (`list_systemd_units`, `get_systemd_unit`, `list_systemd_timers`, `get_journal_logs`, `tail_journal`, `list_containers`, `get_container`, `get_container_logs`), two prompts, two resources and two resource templates. A [consolidator](#peers-consolidator) adds `list_peers` and `get_peer` and a `peer` argument on every tool, for ten tools. Log content is untrusted data and is labelled as such.
+13
View File
@@ -2,6 +2,18 @@
Full endpoint and MCP client reference. The short version is in the [README](../README.md); the design is in [ARCHITECTURE.md](../ARCHITECTURE.md#rest-api).
## Generated reference (OpenAPI)
[`openapi.json`](openapi.json) is a committed OpenAPI 3.1 description of everything this binary serves: every REST route with its parameters and response schemas, the error shape, `POST /mcp`, and an `x-mcp-tools` extension listing each MCP tool with the description and input JSON Schema the tool router reports (eight tools, or ten with `[peers] enabled = true`). `tests/openapi.rs` keeps it true: it fails if a route of the real router is undocumented, if a tool is missing from `x-mcp-tools`, or if the file is stale.
- `GET /api/v1/openapi.json` returns the document for the running instance, behind the same bearer token as the rest of `/api/v1`. Peer routes appear only when peers are enabled.
- `slinuxm openapi [--peers]` prints the same document offline: no config file, no token, no server, no port. `--peers` describes a consolidator; without it you get the peer-less instance.
- Regenerate after changing a route, a tool, a response type or the crate version:
```sh
cargo run -- openapi --peers > docs/openapi.json
```
## REST
Base: `http://127.0.0.1:1984`. Errors are `{"error":{"code","message"}}`.
@@ -20,6 +32,7 @@ Base: `http://127.0.0.1:1984`. Errors are `{"error":{"code","message"}}`.
| `GET /api/v1/peers` | consolidator only; sorted status list; absent when peers are disabled |
| `GET /api/v1/peers/{peer}` | one peer's status object; unknown name is 404 |
| `GET /api/v1/peers/{peer}/...` | GET-only pass-through of that peer's documented routes |
| `GET /api/v1/openapi.json` | this document, OpenAPI 3.1 (see [Generated reference](#generated-reference-openapi)) |
```sh
TOKEN=slinuxm_...
+1899
View File
File diff suppressed because it is too large. Load diff
+6
View File
@@ -37,3 +37,9 @@ Reuse existing DTOs, do not duplicate types for the doc. Read-only, no secrets i
- 2026-10-20: **G3 Serving and CLI.** `document(peers)` now returns a cached `Arc<OpenApi>` (one `OnceLock` per mode; generation walks every DTO and the whole tool router, and the result cannot change while the process runs), with `build`/`to_pretty_json` behind it so one function is shared by every consumer. `GET /api/v1/openapi.json` is mounted in `api::router`, i.e. under `/api/v1` and therefore behind the existing auth layer; no new public route, no change to `server::build_router` or `/healthz`. It serves the mode of the running instance (`state.peers.is_some()`), so a peer-less instance advertises no peer paths. New `slinuxm openapi [--peers]` (`src/cli.rs`, `Command::Openapi`) prints the pretty document; `main` returns before `Config::load`, so it needs no config file, no token file and no socket and cannot start a server or bind a port. `--print-config` still wins if combined. The `peers::cli` import in `main.rs` is now aliased to `peer_cli` because `cli` is the new module.
Tests: `render_is_valid_json_for_both_modes`, `generation_is_deterministic` (bytes, not just values, because the committed file is compared) in the unit tests; `openapi_route_is_authenticated_and_serves_the_document` (401 without a token, 200 with one, body equals the generated peers-on document, `application/json`) and `cli_prints_the_same_document_offline` (real binary, `--config /nonexistent/...`, both modes, output equals the generated document) in `tests/openapi.rs`.
- 2026-10-20: **G4 Drift guard and docs.** `docs/openapi.json` is committed (peers on, pretty-printed by `slinuxm openapi --peers`, 15 paths and 10 tools). `tests/openapi.rs` now holds the guards: `committed_spec_matches_the_code` compares the file byte for byte with `cli::render(true)` and prints the regeneration command (`cargo run -- openapi --peers > docs/openapi.json`) on failure; `every_router_route_is_documented` scans every `.route(...)` literal in `src/api/**` and `src/server.rs` plus the `/mcp` mount and requires each path in the document (verified by adding a throwaway route: the test failed with `/api/v1/ping/extra is routed but missing from the OpenAPI document`); `every_documented_path_is_routed` sends one request per documented path through the assembled router and fails if it hits the fallback's `no such route`; `mcp_tools_match_the_tool_router` requires every tool of the router in `x-mcp-tools` with the same description and input schema (a new or gated-off tool changes the spec and then fails the staleness check); `every_operation_is_read_only` keeps every operation a GET except `POST /mcp`; `operation_ids_and_tags_are_declared` catches duplicate ids and undeclared tags. A crate version bump changes `info.version`, so it also needs the regeneration in the same commit; that is deliberate (the file is the artifact that is published).
Docs: `docs/api.md` gains a "Generated reference (OpenAPI)" section (what the file contains, `GET /api/v1/openapi.json`, `slinuxm openapi [--peers]`, regeneration, what the tests guard) and a route-table row; `README.md` gets a short paragraph in the REST section. `config.example.toml` needs nothing (no new key). `docs/README.md` does not list `docs/openapi.json` yet; it is outside this workstream's owned files, so the merger should add the row.
Verification: `cargo fmt --check`, `cargo clippy --all-targets -- -D warnings`, `cargo test` green (10 tests in `tests/openapi.rs`, 12 unit tests in `src/openapi.rs`/`src/cli.rs`); `cargo tree -i openssl` empty; the committed spec contains no token, token-file path or URL other than the documented default server. No nix build was run; no VM test is involved in this workstream.
+66
View File
@@ -202,6 +202,72 @@ fn mcp_tool_count_follows_the_peers_flag() {
assert!(on.iter().any(|name| name == "get_peer"));
}
/// The committed document is the one the code generates. Regenerate it (and
/// commit the result) whenever a route, a tool, a DTO or the crate version
/// changes.
#[test]
fn committed_spec_matches_the_code() {
let path = Path::new(MANIFEST).join("docs/openapi.json");
let committed = fs::read_to_string(&path).unwrap_or_default();
let generated = skyg_linux_tracker::cli::render(true).unwrap();
assert_eq!(
committed, generated,
"docs/openapi.json is stale; regenerate it with\n \
cargo run -- openapi --peers > docs/openapi.json"
);
}
/// Read-only by construction: every operation is a GET, except the MCP
/// endpoint, which is POST by protocol.
#[test]
fn every_operation_is_read_only() {
let doc = document(true);
for (path, item) in &doc.paths.paths {
for (method, present) in [
("post", item.post.is_some()),
("put", item.put.is_some()),
("delete", item.delete.is_some()),
("patch", item.patch.is_some()),
] {
if present {
assert_eq!(
(method, path.as_str()),
("post", "/mcp"),
"{method} {path} is a write path"
);
}
}
}
}
/// Operation ids are unique and every tag is declared, so client generators
/// and UI tools do not have to guess.
#[test]
fn operation_ids_and_tags_are_declared() {
let doc = document(true);
let declared: Vec<String> = doc
.tags
.clone()
.unwrap_or_default()
.into_iter()
.map(|tag| tag.name)
.collect();
let mut ids = Vec::new();
for (path, item) in &doc.paths.paths {
for operation in [&item.get, &item.post].into_iter().flatten() {
let id = operation.operation_id.clone().expect("operationId");
assert!(!ids.contains(&id), "duplicate operationId {id} ({path})");
ids.push(id);
for tag in operation.tags.iter().flatten() {
assert!(
declared.iter().any(|declared| declared == tag),
"tag {tag} of {path} is not declared"
);
}
}
}
}
#[test]
fn the_spec_is_valid_json_with_the_expected_shape() {
let doc = document(true);