diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index b7214f4..ef483e7 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -36,6 +36,7 @@ Rust edition 2021; release profile uses LTO and `strip`. Cargo.lock is committed ``` Cargo.toml, Cargo.lock # bin `slinuxm`, lib `skyg_linux_tracker` +build.rs # stamps SLINUXM_VERSION (YYYY.MM.DD--); logic in src/version.rs devenv.nix # rust toolchain, pkg-config, libsystemd, otelcol; scripts build/run/smoke/token flake.nix, nix/ # package.nix, module.nix (NixOS), tests/vm.nix (VM test) config.example.toml # every key with its default and env name @@ -200,6 +201,7 @@ All accepted. Rationale is kept; the build history is in [`docs/workstreams/`](d | DEC-13 | Outbound peer credentials are external files | Decided 2026-10-19 | | DEC-14 | Consolidator (peers) design | Decided 2026-10-19, implemented 2026-10-20 | | DEC-15 | Generated OpenAPI document | Decided 2026-10-20 | +| DEC-17 | Build-stamped version | Decided 2026-10-21 | - **DEC-1 name.** The plan used three names (repo `linux-system-monitor`, service `skyg-linux-tracker`, CLI `skyg`). The binary, CLI and `[[bin]]` are `slinuxm`; tokens use the `slinuxm_` prefix. Unchanged: product name `skyg-linux-tracker`, unit `skyg-linux-tracker.service`, state dir `/var/lib/skyg-linux-tracker`, config `/etc/skyg-linux-tracker.toml`, env prefix `SKYG_`. - **DEC-2 traits and fakes.** `SystemdSource`, `JournalSource`, `DockerSource` live in `src/sources/mod.rs`, fakes in `src/sources/fake.rs`, `AppState` holds `Arc` (via `async-trait`). Surfaces can be built and tested without systemd or Docker, at the cost of about 100 extra lines. @@ -219,6 +221,7 @@ All accepted. Rationale is kept; the build history is in [`docs/workstreams/`](d - **HTTP client outcome.** `reqwest` 0.13 with `rustls-no-provider`; the ring provider and webpki roots are passed to the client explicitly, so nothing is installed process-wide and `cargo tree -i openssl` stays empty. Redirects are off and the system proxy is ignored. - **SSRF at connect time.** The host is resolved once, every address is checked against `deny_cidrs` after `to_canonical()` (so `::ffff:169.254.169.254` matches the IPv4 range), one denied address refuses the whole name, and the checked set is pinned with `resolve_to_addrs`, which closes DNS rebinding. The same `deny_networks` / `denied` code runs at config validation and at connect time. The default `deny_cidrs` covers both families (`169.254.0.0/16`, `0.0.0.0/8`, `fe80::/10`, `::/128`, `fd00:ec2::254/128`); private LAN ranges stay allowed. - **DEC-15 generated OpenAPI.** The document is generated so it cannot drift from the code. REST paths are declared on the handlers with `#[utoipa::path]` (utoipa 6, OpenAPI 3.1). DTO schemas are reflected from the existing `schemars::JsonSchema` derives through a bridge in `openapi.rs`, so one derive serves MCP and OpenAPI; only payloads that exist as `serde_json` literals (error body, health) are written by hand and compared with real output in tests. MCP is not REST, so the tools go in the `x-mcp-tools` extension, built from the tool router's own schemas. Peer paths and the two peer tools appear only when peers are enabled. `tests/openapi.rs` is the drift guard: every router route must be documented, `x-mcp-tools` must match `tools/list`, and `docs/openapi.json` must equal `slinuxm openapi --peers` (regenerate with `cargo run -- openapi --peers > docs/openapi.json`). The route is authenticated like the rest of `/api/v1`. +- **DEC-17 build-stamped version.** The runtime version is `YYYY.MM.DD--`, computed by `build.rs` and exposed as `skyg_linux_tracker::VERSION` (`SLINUXM_VERSION`); `--version`, `/healthz`, `/api/v1/ping`, MCP server info and OTel `service.version` use it. `Cargo.toml` stays semver because zero-padded CalVer parts (`2026.03.05`) are not valid semver, and `docs/openapi.json` keeps `info.version` from `CARGO_PKG_VERSION`: a stamp that changes per commit would fail the byte-for-byte drift test on every commit. The string logic (`src/version.rs`) is std-only and compiled into both `build.rs` and the library, so one implementation is unit-tested. Every part can come from `SLINUXM_GIT_SHA`, `SLINUXM_GIT_BRANCH` and `SLINUXM_BUILD_DATE`, and `SLINUXM_VERSION` overrides the whole string; the Nix sandbox has no `.git`, so `flake.nix` passes the commit date (`lastModifiedDate`, which keeps the build reproducible) and short rev, with the placeholder branch `nix` because a flake does not expose its branch. `SOURCE_DATE_EPOCH` is ignored because Nix dev shells set it to 1980. A dirty tree appends `-dirty` to the sha, a small extension of the pattern. Because naming any `rerun-if-changed` path turns off cargo's default package-wide watch, `build.rs` also lists `src`, `Cargo.toml`, `Cargo.lock` and `build.rs`, and watches HEAD through `git rev-parse --git-path` so linked worktrees work. A peer's `peer_version` is an opaque string, so a consolidator shows each peer's own stamp. ## Design notes and gotchas diff --git a/README.md b/README.md index 6fc24c6..b0d6667 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,15 @@ cargo build --release # target/release/slinuxm Without devenv you need a Rust toolchain, `pkg-config` and the libsystemd development files. +### Version + +The binary carries a build-stamped version, `YYYY.MM.DD--` (for example `2026.10.21-main-435a54a`). `slinuxm --version`, `GET /healthz`, `GET /api/v1/ping`, the MCP server info and the OTel `service.version` attribute all report it. `Cargo.toml` keeps a semver `version`, which is what the OpenAPI document's `info.version` uses so that `docs/openapi.json` does not change on every commit. + +- The date is the build day in UTC, the branch has every character outside `[A-Za-z0-9._-]` replaced by `-` (`feature/x` becomes `feature-x`, a detached HEAD becomes `detached`), and the sha is 7 characters, with `-dirty` appended when tracked files have uncommitted changes. +- Without git (a source tarball) the missing parts are `unknown`. +- `build.rs` reads `SLINUXM_GIT_SHA`, `SLINUXM_GIT_BRANCH` and `SLINUXM_BUILD_DATE` (`YYYY.MM.DD`) when set, and `SLINUXM_VERSION` replaces the whole string. `SOURCE_DATE_EPOCH` is ignored on purpose, because Nix dev shells export a fixed 1980 value. +- `nix build` has no `.git`, so the flake passes the commit date and short rev, and the branch is the fixed placeholder `nix` (a flake does not know its branch). Override it with `pkgs.callPackage ./nix/package.nix { gitBranch = "main"; … }`. + ## Install ```sh diff --git a/TODO.md b/TODO.md index e16f328..8fd8ac2 100644 --- a/TODO.md +++ b/TODO.md @@ -2,7 +2,7 @@ The single place for work tracking. **Tick boxes here only.** Design lives in [`ARCHITECTURE.md`](ARCHITECTURE.md). Archived workstream design notes and logs are in [`docs/workstreams/`](docs/workstreams/). Plans for the next big thing go in [`plan/`](plan/README.md). -_Last updated: 2026-10-20_ +_Last updated: 2026-10-21_ ## Status @@ -25,6 +25,7 @@ The build is functionally complete and merged to `main`. REST, MCP, OTel, TLS an | — | | Nothing in flight | - [x] **WS-H Gate:** `nix build` and `nix flake check` pass. `ldd` shows no openssl. A fresh NixOS host serves `:1984` and a token can be minted from a login shell. +- [x] **V-1** Build-stamped version `YYYY.MM.DD--` in `--version`, `/healthz`, `/api/v1/ping`, MCP server info and OTel `service.version` (DEC-17). `dev-test lint`, `cargo test`, `nix build` and both VM tests (`vm`, `vm peers`) pass. ## Backlog @@ -46,6 +47,7 @@ Parked, not scheduled. Each has a reason. Nothing here blocks the current work. | **P5-3** | Scoped tokens (per-peer or read-class scopes) | Any valid inbound token may read peer data (DEC-14); scopes need a token schema change and a policy decision | | **P5-4** | Peer health history | State is in memory only by design; history needs storage or an external TSDB, and the OTel gauges already cover it | | **P5-5** | Runtime peer management (add/remove without editing config) | Peers are declarative so no write path or DB table exists (DEC-14); would need a write path against the read-only rule | +| **V-2** | Real branch name in Nix builds (stamp says `nix`) | A flake does not expose its branch; needs CI to pass it to `callPackage` or a release-tag convention | - [ ] **C7** *(nice-to-have)* Smoke test against the Podman socket - [ ] **I6-5** Verification #5 OTel smoke test against a working collector (see the [verification checklist](ARCHITECTURE.md#verification)) @@ -58,6 +60,7 @@ Parked, not scheduled. Each has a reason. Nothing here blocks the current work. - [ ] **P5-3** Scoped tokens - [ ] **P5-4** Peer health history - [ ] **P5-5** Runtime peer management +- [ ] **V-2** Real branch name in Nix builds instead of the `nix` placeholder - [ ] **F-1** Cap concurrent follow streams. Each journal follow, `tail_journal` call or docker follow pins a `spawn_blocking` thread for up to `limits.max_follow_secs`. Add a global semaphore shared by REST and MCP (suggested 16) returning 429/503 when full. A client that stops reading may hold the thread past the deadline (untested); add a write timeout or a hard `tokio::time::timeout` around the producer. - [ ] **F-2** Bound line and message length. Docker `LineSplitter` and journal `MESSAGE` are buffered without limit before the 256 KiB result cap applies. Truncate per line (suggested 64 KiB, with a visible marker) and cap total bytes collected. - [ ] **F-3** Unit hardening: `ProtectKernelLogs`, `ProtectHostname`, `RemoveIPC`, `LimitNOFILE`, `TasksMax`, `MemoryMax`, narrower `RestrictAddressFamilies`, `PrivateUsers` (check journal group access). Test under the hardened unit on a clean host before enabling. Document how the service user gets read access to the TLS key. diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..06e6b50 --- /dev/null +++ b/build.rs @@ -0,0 +1,106 @@ +//! Stamps the binary with `YYYY.MM.DD--` as `SLINUXM_VERSION`. +//! +//! Cargo.toml keeps a semver `version` (CalVer with zero-padded parts is not +//! valid semver). Every part can be supplied through the environment, which +//! is how a build without a `.git` directory (Nix, tarballs) gets them. + +use std::path::Path; +use std::process::Command; +use std::time::{SystemTime, UNIX_EPOCH}; + +#[path = "src/version.rs"] +mod version; + +const ENV_VARS: [&str; 4] = [ + "SLINUXM_VERSION", + "SLINUXM_GIT_SHA", + "SLINUXM_GIT_BRANCH", + "SLINUXM_BUILD_DATE", +]; + +fn env(name: &str) -> Option { + std::env::var(name).ok().filter(|v| !v.trim().is_empty()) +} + +fn git(args: &[&str]) -> Option { + let out = Command::new("git").args(args).output().ok()?; + if !out.status.success() { + return None; + } + let text = String::from_utf8(out.stdout).ok()?; + let text = text.trim(); + (!text.is_empty()).then(|| text.to_owned()) +} + +/// Registers the files that change HEAD. `--git-path` resolves worktrees, +/// where `.git` is a file and the refs live in the main repository. +fn watch_git(branch: Option<&str>) { + let mut paths = vec!["HEAD".to_owned(), "packed-refs".to_owned()]; + if let Some(b) = branch.filter(|b| *b != "HEAD") { + paths.push(format!("refs/heads/{b}")); + } + for p in paths { + if let Some(resolved) = git(&["rev-parse", "--git-path", &p]) { + println!("cargo:rerun-if-changed={resolved}"); + } + } +} + +/// Wall-clock UTC unless `SLINUXM_BUILD_DATE` is set. `SOURCE_DATE_EPOCH` is +/// deliberately ignored: Nix dev shells export it as a fixed 1980 timestamp. +fn build_date() -> String { + if let Some(d) = env("SLINUXM_BUILD_DATE") { + return d; + } + let secs = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_secs()); + version::date_from_epoch(secs) +} + +fn main() { + for name in ENV_VARS { + println!("cargo:rerun-if-env-changed={name}"); + } + // Naming any rerun path switches off cargo's default of watching the whole + // package, so the sources are listed too: the dirty flag must be rechecked + // whenever they change. + for p in ["build.rs", "Cargo.toml", "Cargo.lock", "src"] { + println!("cargo:rerun-if-changed={p}"); + } + + let value = match env("SLINUXM_VERSION") { + Some(v) => { + assert!( + version::is_valid(&v), + "SLINUXM_VERSION {v:?} is not YYYY.MM.DD--" + ); + v + } + None => { + let in_git = Path::new(".git").exists() || git(&["rev-parse", "--git-dir"]).is_some(); + let git_branch = in_git + .then(|| git(&["rev-parse", "--abbrev-ref", "HEAD"])) + .flatten(); + if in_git { + watch_git(git_branch.as_deref()); + } + + let branch = env("SLINUXM_GIT_BRANCH") + .or(git_branch) + .map_or_else(|| "unknown".to_owned(), |b| version::sanitize_branch(&b)); + + let sha = env("SLINUXM_GIT_SHA").or_else(|| { + let sha = git(&["rev-parse", "--short=7", "HEAD"])?; + let dirty = git(&["status", "--porcelain", "--untracked-files=no"]).is_some(); + Some(if dirty { format!("{sha}-dirty") } else { sha }) + }); + let sha = sha.map_or_else(|| "unknown".to_owned(), |s| version::sanitize_sha(&s)); + + let v = version::compose(&build_date(), &branch, &sha); + assert!(version::is_valid(&v), "built an invalid version: {v:?}"); + v + } + }; + println!("cargo:rustc-env=SLINUXM_VERSION={value}"); +} diff --git a/docs/api.md b/docs/api.md index b30f499..d25b42b 100644 --- a/docs/api.md +++ b/docs/api.md @@ -20,7 +20,7 @@ Base: `http://127.0.0.1:1984`. Errors are `{"error":{"code","message"}}`. | Route | Notes | |---|---| -| `GET /healthz` | public, `{"status":"ok","version":...}` | +| `GET /healthz` | public, `{"status":"ok","version":...}`; `version` is the build stamp `YYYY.MM.DD--`, as in `/api/v1/ping` | | `GET /api/v1/systemd/units?state=failed` | `state` is an active state (`failed`, `active`, ...) | | `GET /api/v1/systemd/units/{name}` | one unit with details; read-only, so only units systemd has loaded (unloaded or unknown is 404) | | `GET /api/v1/systemd/timers` | | diff --git a/flake.nix b/flake.nix index 926b515..42e8ee2 100644 --- a/flake.nix +++ b/flake.nix @@ -8,10 +8,22 @@ system = "x86_64-linux"; systems = [ "x86_64-linux" "aarch64-linux" ]; forAll = f: nixpkgs.lib.genAttrs systems (s: f nixpkgs.legacyPackages.${s}); + + # Stamp for `slinuxm --version`: the commit date and short sha, so the + # build is reproducible. A flake does not know its branch; package.nix + # defaults it to "nix". + lastModified = self.lastModifiedDate or "19700101000000"; + stamp = { + buildDate = "${builtins.substring 0 4 lastModified}.${builtins.substring 4 2 lastModified}.${builtins.substring 6 2 lastModified}"; + gitSha = + if self ? shortRev + then builtins.substring 0 7 self.shortRev + else self.dirtyShortRev or "unknown"; + }; in { packages = forAll (pkgs: rec { - skyg-linux-tracker = pkgs.callPackage ./nix/package.nix { }; + skyg-linux-tracker = pkgs.callPackage ./nix/package.nix stamp; default = skyg-linux-tracker; }); diff --git a/nix/package.nix b/nix/package.nix index 199511c..89a7d75 100644 --- a/nix/package.nix +++ b/nix/package.nix @@ -1,14 +1,26 @@ -{ lib, rustPlatform, pkg-config, cmake, systemd }: +{ lib +, rustPlatform +, pkg-config +, cmake +, systemd + # The build sandbox has no .git, so build.rs gets the stamp from here + # (YYYY.MM.DD--). The flake fills these in; a flake has no + # branch name, hence the placeholder. +, gitSha ? "unknown" +, gitBranch ? "nix" +, buildDate ? "1970.01.01" +}: rustPlatform.buildRustPackage { pname = "skyg-linux-tracker"; - version = (lib.importTOML ../Cargo.toml).package.version; + version = "${buildDate}-${gitBranch}-${gitSha}"; src = lib.fileset.toSource { root = ../.; fileset = lib.fileset.unions [ ../Cargo.toml ../Cargo.lock + ../build.rs ../config.example.toml ../migrations ../src @@ -20,6 +32,12 @@ rustPlatform.buildRustPackage { cargoLock.lockFile = ../Cargo.lock; + env = { + SLINUXM_GIT_SHA = gitSha; + SLINUXM_GIT_BRANCH = gitBranch; + SLINUXM_BUILD_DATE = buildDate; + }; + # cmake: aws-lc-sys. Live-journal tests are #[ignore], so the sandbox runs # the rest of the suite. nativeBuildInputs = [ pkg-config cmake ]; diff --git a/src/api/mod.rs b/src/api/mod.rs index 2cf22f4..9fc9f4e 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -67,7 +67,7 @@ pub fn router(state: AppState) -> Router { pub async fn healthz() -> Json { Json(serde_json::json!({ "status": "ok", - "version": env!("CARGO_PKG_VERSION"), + "version": crate::VERSION, })) } diff --git a/src/api/ping.rs b/src/api/ping.rs index be829c2..44d31bf 100644 --- a/src/api/ping.rs +++ b/src/api/ping.rs @@ -31,7 +31,7 @@ pub fn routes() -> Router { pub(crate) async fn ping() -> Json { Json(serde_json::json!({ "status": "ok", - "version": env!("CARGO_PKG_VERSION"), + "version": crate::VERSION, })) } diff --git a/src/api/ping_tests.rs b/src/api/ping_tests.rs index 64bab50..f46d319 100644 --- a/src/api/ping_tests.rs +++ b/src/api/ping_tests.rs @@ -12,5 +12,5 @@ async fn ping_reports_version() { assert_eq!(status, StatusCode::OK); let v = json(&body); assert_eq!(v["status"], "ok"); - assert_eq!(v["version"], env!("CARGO_PKG_VERSION")); + assert_eq!(v["version"], crate::VERSION); } diff --git a/src/api/systemd_tests.rs b/src/api/systemd_tests.rs index 5ac4e18..4aeac64 100644 --- a/src/api/systemd_tests.rs +++ b/src/api/systemd_tests.rs @@ -42,5 +42,5 @@ async fn timers_ok_and_unknown_route() { async fn healthz_shape() { let v = healthz().await.0; assert_eq!(v["status"], "ok"); - assert!(v["version"].is_string()); + assert_eq!(v["version"], crate::VERSION); } diff --git a/src/lib.rs b/src/lib.rs index a808c98..bf1eefb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -17,3 +17,7 @@ pub mod sources; pub mod state; pub mod telemetry; pub mod tls; +pub mod version; + +/// Build-stamped version, `YYYY.MM.DD--`; see `build.rs`. +pub const VERSION: &str = env!("SLINUXM_VERSION"); diff --git a/src/main.rs b/src/main.rs index ce91a75..7843fcb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -18,7 +18,10 @@ use skyg_linux_tracker::state::AppState; use skyg_linux_tracker::{cli, db, server, telemetry, tls}; #[derive(Debug, Parser)] -#[command(name = "slinuxm", version, about = "Read-only Linux system monitor")] +#[command( + name = "slinuxm", + version = skyg_linux_tracker::VERSION, + about = "Read-only Linux system monitor")] struct Cli { /// Config file (default: /etc/skyg-linux-tracker.toml if present). #[arg(long, global = true, env = "SKYG_CONFIG")] diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs index b6032cd..bb226d1 100644 --- a/src/mcp/mod.rs +++ b/src/mcp/mod.rs @@ -461,10 +461,7 @@ impl ServerHandler for TrackerService { .enable_resources() .build(), ) - .with_server_info(Implementation::new( - env!("CARGO_PKG_NAME"), - env!("CARGO_PKG_VERSION"), - )) + .with_server_info(Implementation::new(env!("CARGO_PKG_NAME"), crate::VERSION)) .with_instructions(instructions(self.state.peers.is_some())) } diff --git a/src/telemetry/mod.rs b/src/telemetry/mod.rs index 360fece..3d56c26 100644 --- a/src/telemetry/mod.rs +++ b/src/telemetry/mod.rs @@ -272,10 +272,7 @@ fn hostname() -> String { fn build_resource(otel: &OtelConfig) -> Resource { Resource::builder() .with_service_name(otel.service_name.clone()) - .with_attribute(KeyValue::new( - "service.version", - env!("CARGO_PKG_VERSION").to_owned(), - )) + .with_attribute(KeyValue::new("service.version", crate::VERSION.to_owned())) .with_attribute(KeyValue::new("host.name", hostname())) .build() } diff --git a/src/version.rs b/src/version.rs new file mode 100644 index 0000000..515f903 --- /dev/null +++ b/src/version.rs @@ -0,0 +1,92 @@ +//! Formatting of the build-stamped version, `YYYY.MM.DD--`. +//! +//! `build.rs` compiles this file directly (`#[path]`), so it must stay +//! std-only and must not refer to anything else in the crate. +#![allow(dead_code)] + +/// Joins the three parts. The inputs are expected to be clean already +/// (`date` from [`date_from_epoch`], the others from [`sanitize_branch`] and +/// [`sanitize_sha`]). +pub fn compose(date: &str, branch: &str, sha: &str) -> String { + format!("{date}-{branch}-{sha}") +} + +/// Keeps `[A-Za-z0-9._-]`, turns everything else (notably the `/` in +/// `feature/x`) into `-`, and trims `-` from both ends. A detached HEAD +/// (`HEAD` from `git rev-parse --abbrev-ref`) and an empty result become +/// `detached` and `unknown`. +pub fn sanitize_branch(raw: &str) -> String { + let raw = raw.trim(); + if raw == "HEAD" { + return "detached".to_owned(); + } + let cleaned: String = raw + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') { + c + } else { + '-' + } + }) + .collect(); + let cleaned = cleaned.trim_matches('-'); + if cleaned.is_empty() { + "unknown".to_owned() + } else { + cleaned.to_owned() + } +} + +/// Keeps `[A-Za-z0-9-]` so a `-dirty` suffix survives, lowercased. +pub fn sanitize_sha(raw: &str) -> String { + let cleaned: String = raw + .trim() + .chars() + .filter(|c| c.is_ascii_alphanumeric() || *c == '-') + .map(|c| c.to_ascii_lowercase()) + .collect(); + if cleaned.is_empty() { + "unknown".to_owned() + } else { + cleaned + } +} + +/// UTC `YYYY.MM.DD` for a Unix timestamp. +pub fn date_from_epoch(secs: u64) -> String { + // Days to civil date, after Howard Hinnant's `civil_from_days`. + let z = (secs / 86_400) as i64 + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + format!("{year:04}.{month:02}.{day:02}") +} + +/// Whether `v` has the shape `YYYY.MM.DD--`: a date, then a +/// non-empty remainder of `[A-Za-z0-9._-]` with at least one more `-`. +pub fn is_valid(v: &str) -> bool { + let b = v.as_bytes(); + if b.len() < 13 || b[10] != b'-' { + return false; + } + let digits = |r: std::ops::Range| b[r].iter().all(u8::is_ascii_digit); + let date_ok = digits(0..4) && b[4] == b'.' && digits(5..7) && b[7] == b'.' && digits(8..10); + let rest = &v[11..]; + date_ok + && rest.contains('-') + && !rest.starts_with('-') + && !rest.ends_with('-') + && rest + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')) +} + +#[cfg(test)] +#[path = "version_tests.rs"] +mod tests; diff --git a/src/version_tests.rs b/src/version_tests.rs new file mode 100644 index 0000000..c452f1d --- /dev/null +++ b/src/version_tests.rs @@ -0,0 +1,53 @@ +use crate::version::{compose, date_from_epoch, is_valid, sanitize_branch, sanitize_sha}; + +#[test] +fn compiled_version_has_the_documented_shape() { + assert!(is_valid(crate::VERSION), "VERSION = {}", crate::VERSION); +} + +#[test] +fn compose_joins_date_branch_and_sha() { + assert_eq!( + compose("2026.10.20", "main", "abc1234"), + "2026.10.20-main-abc1234" + ); +} + +#[test] +fn branch_is_sanitised() { + assert_eq!(sanitize_branch("main"), "main"); + assert_eq!(sanitize_branch("feature/x y"), "feature-x-y"); + assert_eq!(sanitize_branch("release/1.2_rc"), "release-1.2_rc"); + assert_eq!(sanitize_branch("//"), "unknown"); + assert_eq!(sanitize_branch(""), "unknown"); + assert_eq!(sanitize_branch("HEAD"), "detached"); +} + +#[test] +fn sha_is_lowercased_and_keeps_the_dirty_suffix() { + assert_eq!(sanitize_sha("ABC1234\n"), "abc1234"); + assert_eq!(sanitize_sha("abc1234-dirty"), "abc1234-dirty"); + assert_eq!(sanitize_sha(""), "unknown"); +} + +#[test] +fn date_is_utc_and_zero_padded() { + assert_eq!(date_from_epoch(0), "1970.01.01"); + assert_eq!(date_from_epoch(951_782_400), "2000.02.29"); + assert_eq!(date_from_epoch(1_772_323_199), "2026.02.28"); + assert_eq!(date_from_epoch(1_772_323_200), "2026.03.01"); + assert_eq!(date_from_epoch(1_792_454_400), "2026.10.20"); +} + +#[test] +fn validator_accepts_and_rejects() { + assert!(is_valid("2026.10.20-main-abc1234")); + assert!(is_valid("2026.10.20-feature-x-abc1234-dirty")); + assert!(is_valid("2026.10.20-unknown-unknown")); + assert!(!is_valid("0.1.0")); + assert!(!is_valid("2026.10.20")); + assert!(!is_valid("2026.10.20-main")); + assert!(!is_valid("2026-10-20-main-abc1234")); + assert!(!is_valid("2026.10.20-feature/x-abc1234")); + assert!(!is_valid("2026.10.20--abc1234")); +} diff --git a/tests/binary_smoke.rs b/tests/binary_smoke.rs index 4453114..9f4859f 100644 --- a/tests/binary_smoke.rs +++ b/tests/binary_smoke.rs @@ -236,6 +236,13 @@ fn binary_end_to_end() { smoke.port = 1; // placeholder; start_server picks a real port smoke.write_config(); + let version = smoke.cli(&["--version"]); + let stamped = version.trim().strip_prefix("slinuxm ").unwrap_or_default(); + assert!( + skyg_linux_tracker::version::is_valid(stamped), + "--version printed {version:?}, want `slinuxm YYYY.MM.DD--`" + ); + let out = smoke.cli(&["token", "create", "smoke"]); let token = out.trim().to_owned(); assert!(