kanade_shared/wire/server_settings.rs
1use serde::{Deserialize, Serialize};
2
3use crate::config::MailSection;
4
5/// Upper bound on [`ServerSettings::agent_prune_days`] (100 years). A
6/// value this large already means "effectively never", and it keeps the
7/// cleanup task's `now - Duration::days(n)` subtraction comfortably inside
8/// `chrono::DateTime`'s representable range — `DateTime - Duration` panics
9/// on overflow, and an unbounded `u32` (~11.7 M years) would trip it.
10/// Enforced two ways: the PUT handler rejects a larger value, and
11/// [`ServerSettings::effective_agent_prune_days`] clamps to it so even a
12/// hand-written KV value can never panic the cleanup task.
13pub const MAX_AGENT_PRUNE_DAYS: u32 = 36_500;
14
15/// Built-in retention window (days) for the `collections` Object Store —
16/// the file bundles a `collect:` job uploads (#219). This is the value the
17/// bootstrap creates a fresh bucket with, and the fallback
18/// [`ServerSettings::effective_collect_retention_days`] resolves to when the
19/// operator hasn't overridden it. Kept here (not just in `bootstrap`) so the
20/// wire default and the bucket's initial `max_age` share one source of truth.
21pub const DEFAULT_COLLECT_RETENTION_DAYS: u32 = 30;
22
23/// Upper bound on [`ServerSettings::collect_retention_days`] (10 years).
24/// Bundles are debugging / audit artifacts, so an operator has no reason to
25/// keep them longer than this; the ceiling stops a fat-fingered value from
26/// pushing the `collections` Object Store's `max_age` to something absurd.
27/// (The bucket's `max_bytes` cap still bounds actual disk regardless.)
28/// Enforced by the PUT handler and clamped in
29/// [`ServerSettings::effective_collect_retention_days`] so even a
30/// hand-written KV value stays sane.
31pub const MAX_COLLECT_RETENTION_DAYS: u32 = 3650;
32
33/// Built-in default for [`ServerSettings::session_ttl_hours`] — how long a
34/// freshly-minted SPA/CLI login token stays valid when the operator hasn't
35/// overridden it. 24h balances "don't re-auth mid-workday" against a
36/// bounded window for a leaked token (the DB row is re-checked every
37/// request, so `disable` still takes effect immediately regardless).
38pub const DEFAULT_SESSION_TTL_HOURS: u32 = 24;
39
40/// Upper bound on [`ServerSettings::session_ttl_hours`] (365 days). Keeps
41/// login's `Utc::now() + Duration::hours(n)` comfortably inside `chrono`'s
42/// representable range (its nanosecond `i64` caps out ~292 years, so an
43/// unclamped `u32` of hours could overflow) and stops an operator pinning a
44/// practically-immortal session. Enforced by the PUT handler and clamped in
45/// [`ServerSettings::effective_session_ttl_hours`] so even a hand-written
46/// KV value stays bounded.
47pub const MAX_SESSION_TTL_HOURS: u32 = 8_760;
48
49/// Built-in default for [`ServerSettings::check_status_stale_days`] (#1032②) —
50/// how many days a `check_status` row may go without a fresh result before the
51/// Compliance view treats it as **stale** and hides it (a PC that stopped
52/// running a check: excluded from its target via a dynamic group, decommissioned,
53/// or its schedule removed). 30 days is comfortably longer than a typical daily
54/// / weekly compliance cadence, so an in-scope PC is never mistakenly hidden,
55/// while a genuinely out-of-scope PC's frozen row drops out within the month.
56/// A real default (like `collect_retention_days`) so the feature works out of
57/// the box; the operator shortens it for prompter hiding or sets `0` to disable.
58pub const DEFAULT_CHECK_STATUS_STALE_DAYS: u32 = 30;
59
60/// Upper bound on [`ServerSettings::check_status_stale_days`] (10 years).
61/// Staleness is purely a display cutoff (`now - Duration::days(n)` compared to a
62/// row's `recorded_at`), so the ceiling just keeps that subtraction inside
63/// `chrono::DateTime`'s range and stops an absurd value; enforced by the PUT
64/// handler and clamped in [`ServerSettings::effective_check_status_stale_days`].
65pub const MAX_CHECK_STATUS_STALE_DAYS: u32 = 3650;
66
67/// Built-in default for [`SupportCode::ttl_minutes`] — how long an unlock
68/// grant lasts when the operator hasn't set a per-code window. 15 minutes is
69/// about the length of a helpdesk call: long enough that the desk isn't
70/// re-typing the code mid-troubleshoot, short enough that a machine left
71/// unattended after the call re-locks on its own.
72pub const DEFAULT_SUPPORT_UNLOCK_TTL_MINUTES: u32 = 15;
73
74/// Upper bound on [`SupportCode::ttl_minutes`] (8 hours). An unlock grant is
75/// standing permission for an end user's machine to run privileged jobs, so
76/// it must not outlive a working day even by operator error — a longer window
77/// is a `visible_to` targeting decision, not an unlock one. Enforced by the
78/// support-code endpoint and clamped in [`SupportCode::effective_ttl_minutes`]
79/// so a hand-written KV value stays bounded too.
80pub const MAX_SUPPORT_UNLOCK_TTL_MINUTES: u32 = 480;
81
82/// Per-bucket disk caps (MiB) for the five NATS Object Stores, reconciled
83/// onto each backing `OBJ_*` stream at backend boot and on save (#1247).
84/// `None` (unset) ⇒ the built-in default below, so a blank SPA field
85/// preserves the out-of-box budget and a deployment that never opens the
86/// Settings page is still capped.
87///
88/// Why these exist: `agent_releases` / `app_packages` / `scripts` were
89/// created with no caps at all, and caps added to code AFTER a bucket
90/// existed never reached the live broker (`ensure_object_store` tolerates
91/// the 10058 config-drift error rather than reconciling — which is how
92/// `OBJ_result_output` grew to 6.76 GB against a nominal 1 GiB cap).
93/// The reconcile path (`bootstrap::reconcile_object_store_max_bytes`) makes
94/// the configured value actually land, so these defaults are also the
95/// **fix** for already-drifted buckets, applied on the first boot after
96/// upgrade.
97#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
98#[serde(default)]
99pub struct ObjectStoreCaps {
100 /// `result_output` — overflow stdout/stderr blobs. Transport +
101 /// replay buffer (the projector derefs within seconds into SQLite),
102 /// so this is a runaway-output backstop, not a history budget.
103 #[serde(skip_serializing_if = "Option::is_none")]
104 pub result_output_mib: Option<u32>,
105 /// `agent_releases` — one exe per version (~100 MB each). Sized for
106 /// ~20 recent versions.
107 #[serde(skip_serializing_if = "Option::is_none")]
108 pub agent_releases_mib: Option<u32>,
109 /// `app_packages` — operator-curated installers; the largest bucket
110 /// in practice (1.5 GB at measurement time, uncapped).
111 #[serde(skip_serializing_if = "Option::is_none")]
112 pub app_packages_mib: Option<u32>,
113 /// `scripts` — manifest script bodies; tiny payloads, so the cap is
114 /// a cardinality backstop.
115 #[serde(skip_serializing_if = "Option::is_none")]
116 pub scripts_mib: Option<u32>,
117 /// `collections` — collect-job bundles. Its `max_age` has its own
118 /// knob ([`ServerSettings::collect_retention_days`]); this caps the
119 /// disk regardless of window.
120 #[serde(skip_serializing_if = "Option::is_none")]
121 pub collections_mib: Option<u32>,
122}
123
124/// Built-in per-bucket caps (MiB) — the values fresh buckets are born
125/// with and unset SPA fields resolve to. Total ≈ 13.5 GiB, comfortably
126/// inside the broker-wide `max_file_store: 50GB` once the ~5.3 GiB of
127/// stream reservations (bootstrap.rs) are accounted for.
128pub const DEFAULT_RESULT_OUTPUT_CAP_MIB: u32 = 1024;
129
130/// How long `OBJECT_RESULT_OUTPUT` keeps an overflowed stdout/stderr blob.
131///
132/// Seven days, not the thirty it used to be, because the blob is redundant
133/// almost immediately: the results projector derefs it into the row before
134/// the INSERT, so SQLite holds the text and the SPA reads it from there. What
135/// the window buys is one thing only — a `-WipeDb` re-projection replays
136/// `STREAM_RESULTS` and re-derefs, so an object that has aged out comes back
137/// as empty stdout on the rebuilt row.
138///
139/// Thirty days of copies nobody reads is what pushed the bucket into its cap,
140/// and the cap is a hard wall rather than an eviction trigger (#1321): once
141/// full, every result over the inline threshold became undeliverable
142/// fleet-wide. A week keeps the recovery path useful for any incident anyone
143/// is still investigating while cutting the standing volume by ~4x.
144///
145/// Bounded above by `STREAM_RESULTS`'s own 30-day window in any case: past
146/// that there is no message to replay, so a longer object window buys
147/// nothing.
148pub const DEFAULT_RESULT_OUTPUT_RETENTION_DAYS: u32 = 7;
149
150/// Upper bound accepted from an operator. Matches `STREAM_RESULTS`'s window —
151/// beyond it the messages are gone, so the objects would outlive the only
152/// thing that could ask for them.
153pub const MAX_RESULT_OUTPUT_RETENTION_DAYS: u32 = 30;
154pub const DEFAULT_AGENT_RELEASES_CAP_MIB: u32 = 2048;
155pub const DEFAULT_APP_PACKAGES_CAP_MIB: u32 = 5120;
156pub const DEFAULT_SCRIPTS_CAP_MIB: u32 = 256;
157pub const DEFAULT_COLLECTIONS_CAP_MIB: u32 = 5120;
158
159/// Upper bound per bucket (50 GiB) — the broker-wide `max_file_store`
160/// default, so a single bucket can never be configured to eat the whole
161/// file store by fat-finger. Enforced by the PUT handler and clamped in
162/// the `effective_*` accessors so a hand-written KV value stays bounded.
163pub const MAX_OBJECT_STORE_CAP_MIB: u32 = 51_200;
164
165/// Upper bound on the SUM of the five effective bucket caps (45.2 GiB):
166/// the broker-wide 50 GiB minus the ~4.8 GiB the streams reserve
167/// (INVENTORY 1024 + RESULTS 2048 + EXEC 64 + EVENTS 256 + AUDIT 512 +
168/// OBS_EVENTS 512 + NOTIFICATIONS 512 MiB — bootstrap.rs). Without an
169/// aggregate bound, five individually-legal caps could total 250 GiB and
170/// every `update_stream` would be refused by the broker (10047) — the KV
171/// document claiming caps the streams don't have. Enforced by the PUT
172/// handler on the merged document.
173pub const MAX_OBJECT_STORE_TOTAL_MIB: u32 = 46_272;
174
175impl ObjectStoreCaps {
176 fn effective(v: Option<u32>, default: u32) -> u32 {
177 v.unwrap_or(default).clamp(1, MAX_OBJECT_STORE_CAP_MIB)
178 }
179
180 pub fn effective_result_output_mib(&self) -> u32 {
181 Self::effective(self.result_output_mib, DEFAULT_RESULT_OUTPUT_CAP_MIB)
182 }
183 pub fn effective_agent_releases_mib(&self) -> u32 {
184 Self::effective(self.agent_releases_mib, DEFAULT_AGENT_RELEASES_CAP_MIB)
185 }
186 pub fn effective_app_packages_mib(&self) -> u32 {
187 Self::effective(self.app_packages_mib, DEFAULT_APP_PACKAGES_CAP_MIB)
188 }
189 pub fn effective_scripts_mib(&self) -> u32 {
190 Self::effective(self.scripts_mib, DEFAULT_SCRIPTS_CAP_MIB)
191 }
192 pub fn effective_collections_mib(&self) -> u32 {
193 Self::effective(self.collections_mib, DEFAULT_COLLECTIONS_CAP_MIB)
194 }
195
196 /// `(bucket, effective cap in MiB)` for every object store, in
197 /// bootstrap order — the reconcile loop's input.
198 pub fn effective_all(&self) -> [(&'static str, u32); 5] {
199 [
200 (
201 crate::kv::OBJECT_AGENT_RELEASES,
202 self.effective_agent_releases_mib(),
203 ),
204 (
205 crate::kv::OBJECT_APP_PACKAGES,
206 self.effective_app_packages_mib(),
207 ),
208 (crate::kv::OBJECT_SCRIPTS, self.effective_scripts_mib()),
209 (
210 crate::kv::OBJECT_RESULT_OUTPUT,
211 self.effective_result_output_mib(),
212 ),
213 (
214 crate::kv::OBJECT_COLLECTIONS,
215 self.effective_collections_mib(),
216 ),
217 ]
218 }
219}
220
221/// One operator-issued support code — the "裏コマンド" that reveals
222/// `client.unlock`-scoped jobs in the Client App (see
223/// [`crate::manifest::ClientHint::unlock`]).
224///
225/// **Only the argon2id hash is stored.** Verification needs no plaintext, so
226/// unlike the SMTP password (#884, which must stay in the HKLM registry
227/// because SMTP AUTH needs the real string) a support code can live in KV
228/// safely — an agent reads the hash to verify a typed code locally, which is
229/// what keeps unlocking working while the backend is down, exactly when the
230/// desk needs it most.
231///
232/// The plaintext exists only in transit: the operator types it once into the
233/// SPA, the backend hashes it, and no layer ever stores or returns it. The
234/// API blanks [`hash`](Self::hash) on the way out too — an operator rotating
235/// a code sets a new one, they never read the old one back.
236#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
237#[serde(default)]
238pub struct SupportCode {
239 /// The scope this code opens, matched byte-for-byte against a job's
240 /// `client.unlock`. Unique within the list; a slug (`[A-Za-z0-9._-]`).
241 pub scope: String,
242 /// argon2id PHC-format hash of the code. Empty ⇒ **no code configured**
243 /// for this scope, which fails closed (nothing can be unlocked with it) —
244 /// that's also what an API response looks like, since the hash is blanked
245 /// before it leaves the backend.
246 #[serde(skip_serializing_if = "String::is_empty")]
247 pub hash: String,
248 /// Human label for the code (`"ヘルプデスク一次窓口"`), shown in the
249 /// Client App's support-mode banner so the user can see which desk opened
250 /// their machine. `None` ⇒ the banner falls back to the scope slug.
251 #[serde(skip_serializing_if = "Option::is_none")]
252 pub label: Option<String>,
253 /// How long a grant from this code lasts, in minutes. `None` ⇒
254 /// [`DEFAULT_SUPPORT_UNLOCK_TTL_MINUTES`]. Clamped to
255 /// `1..=`[`MAX_SUPPORT_UNLOCK_TTL_MINUTES`].
256 #[serde(skip_serializing_if = "Option::is_none")]
257 pub ttl_minutes: Option<u32>,
258 /// Temporarily suspend the code without deleting it (and without having
259 /// to re-issue a new secret afterwards) — a disabled code never verifies.
260 /// `false` (the default) ⇒ live.
261 #[serde(skip_serializing_if = "std::ops::Not::not")]
262 pub disabled: bool,
263}
264
265impl SupportCode {
266 /// The grant window this code mints, in minutes: the configured value if
267 /// set, else [`DEFAULT_SUPPORT_UNLOCK_TTL_MINUTES`]. Floored at 1 and
268 /// clamped to [`MAX_SUPPORT_UNLOCK_TTL_MINUTES`] so a `0` (which would
269 /// mint an already-expired grant, i.e. an unlock that silently does
270 /// nothing) or an out-of-band giant value can't reach the grant store.
271 pub fn effective_ttl_minutes(&self) -> u32 {
272 self.ttl_minutes
273 .unwrap_or(DEFAULT_SUPPORT_UNLOCK_TTL_MINUTES)
274 .clamp(1, MAX_SUPPORT_UNLOCK_TTL_MINUTES)
275 }
276
277 /// Whether this entry can ever grant anything: live and carrying a hash.
278 /// Both halves fail closed — a blanked (API-redacted) or hand-cleared
279 /// hash opens nothing, and neither does a disabled code.
280 pub fn is_usable(&self) -> bool {
281 !self.disabled && !self.hash.is_empty()
282 }
283}
284
285/// Self-service agent-installer knobs (`GET /api/agents/installer`) —
286/// what the generated ZIP bakes in for a fresh PC. Kept server-side so the
287/// restricted "download user" (viewer + the `agent-install` feature only)
288/// never chooses — and never sees — these values.
289// PartialEq/Eq beyond the minimal derive list: `ServerSettings` derives
290// them, so every section must too.
291#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
292#[serde(default)]
293pub struct AgentInstallSection {
294 /// NATS URL baked into the installer's agent.toml. None → the backend's
295 /// own configured `[nats] url`.
296 #[serde(skip_serializing_if = "Option::is_none")]
297 pub nats_url: Option<String>,
298 /// NATS token baked into install-agent.ps1. WRITE-ONLY: redacted from
299 /// every GET response (GET /api/server-settings is viewer+).
300 #[serde(skip_serializing_if = "Option::is_none")]
301 pub nats_token: Option<String>,
302 /// Read-only indicator computed by redacted() so the SPA can show
303 /// "configured" without ever seeing the value. Never accepted from PUT.
304 #[serde(skip_deserializing)]
305 pub nats_token_set: bool,
306 /// Ask the generated Windows installer to pass `-RequireSignedCommands`
307 /// to `deploy-agent.ps1`, so a fresh agent starts enforcing signed
308 /// commands from first boot instead of leaving that as a manual
309 /// post-install step (#1155/#1165 day-1 gap).
310 ///
311 /// `None`/`Some(false)` → omitted, matching every other unset knob here.
312 /// `Some(true)` is honored by the installer ONLY when this backend also
313 /// has a command-signing key configured — see
314 /// `agent_installer::resolve_enforcement`. A backend with no key must
315 /// never generate an installer that turns on enforcement with an empty
316 /// keyring; that request is instead surfaced in the installer's
317 /// README.txt rather than silently dropped.
318 #[serde(skip_serializing_if = "Option::is_none")]
319 pub require_signed_commands: Option<bool>,
320}
321
322/// Value stored in the `server_settings` KV bucket under the single key
323/// [`crate::kv::KEY_SERVER_SETTINGS`]. Operator-editable, backend-side
324/// server configuration that isn't per-agent (so it doesn't belong in
325/// `agent_config`'s layered scopes) and isn't a fleet-wide switch every
326/// agent watches (so it doesn't belong in `fleet_config`). Managed via
327/// the SPA Settings page's "server settings" tab.
328///
329/// Every field is `Option<_>`: `None` (the default / the JSON value
330/// `null` / the field simply absent) means **unset — fall back to the
331/// built-in default** ([`ServerSettings::defaults`]), exactly like the
332/// agent layered-config scopes. The SPA renders the built-in default as a
333/// faint placeholder so a blank field shows what it resolves to, and when
334/// a real default is introduced here it appears in the UI (and takes
335/// effect for already-deployed-but-unset fleets) for free.
336///
337/// `#[serde(default)]` on the container keeps the document backward/forward
338/// compatible: a freshly-created or missing key decodes to all-`None`
339/// (pre-feature behaviour), an older backend reading a newer document
340/// ignores unknown fields, and a newer backend reading an older document
341/// fills the missing field with `None`. Keep that invariant — never add a
342/// field whose `None` doesn't mean "behave as before".
343#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
344#[serde(default)]
345pub struct ServerSettings {
346 /// Days a dead agent (one whose heartbeat stopped arriving) may
347 /// linger in the `agents` registry before the backend cleanup task
348 /// prunes its row.
349 ///
350 /// `None` (unset) falls back to the built-in default; with no default
351 /// configured that resolves to pruning **disabled** (see
352 /// [`ServerSettings::effective_agent_prune_days`]). A positive value
353 /// makes the cleanup sweep delete rows whose `last_heartbeat` is older
354 /// than that many days. The `agents` table is a projection of the
355 /// heartbeat stream, so a machine that's merely offline (not gone)
356 /// reappears on its next heartbeat (~30s cadence); only
357 /// genuinely-retired machines stay gone.
358 #[serde(skip_serializing_if = "Option::is_none")]
359 pub agent_prune_days: Option<u32>,
360
361 /// Agent group whose members are the trusted **controller-tier**
362 /// runners. A job with `tier: controller` (e.g. a `feed:` job that
363 /// fetches an external URL) is dispatched ONLY to members of this group;
364 /// `None` (unset) means controller-tier jobs run **nowhere** (fail-safe,
365 /// so an external fetch never lands on an employee endpoint by accident).
366 /// See `crate::manifest::Tier`. `None` ⇒ no controller runners
367 /// configured, which is the safe default for a fresh deployment.
368 #[serde(skip_serializing_if = "Option::is_none")]
369 pub controller_group: Option<String>,
370
371 /// Non-secret SMTP relay settings for outbound email (compliance-alert
372 /// notifications, account setup links, …). Lives here (#884) rather than
373 /// in `backend.toml` so an operator can edit it from the SPA without
374 /// shell access to the host.
375 ///
376 /// `None` (unset) ⇒ no relay configured, email is a no-op — the in-app
377 /// / NATS notification path is unaffected. The SMTP **password is
378 /// deliberately not here** (KV is
379 /// readable over NATS): it stays sourced from the `MailPassword`
380 /// registry secret / `$KANADE_MAIL_PASSWORD` and is combined with these
381 /// settings when the backend builds its `Mailer`. Changes take effect on
382 /// the **next backend restart** (the backend builds the `Mailer` once at
383 /// startup — no live rebuild), which is acceptable per the #884
384 /// discussion.
385 #[serde(skip_serializing_if = "Option::is_none")]
386 pub mail: Option<MailSection>,
387
388 /// Self-service agent-installer knobs — see [`AgentInstallSection`].
389 /// `None` (unset) ⇒ the installer falls back to this backend's own
390 /// `[nats] url` and embeds no token. The `nats_token` inside is
391 /// write-only: [`ServerSettings::redacted`] strips it from every
392 /// response and the PUT merge preserves a stored token across a
393 /// url-only edit (the same support-code trap: a form round-trip must
394 /// never silently clear a secret).
395 #[serde(skip_serializing_if = "Option::is_none")]
396 pub agent_install: Option<AgentInstallSection>,
397
398 /// Retention window (days) for collected file bundles — the `collect:`
399 /// job archives uploaded to the `collections` Object Store (#219).
400 ///
401 /// Unlike the other fields, this one has a **real built-in default**
402 /// ([`DEFAULT_COLLECT_RETENTION_DAYS`], 30 d): `None` (unset) falls back
403 /// to it, so a blank field preserves the historical behaviour rather than
404 /// disabling retention. A positive value tells the backend to reconcile
405 /// the Object Store's `max_age` to that many days (see
406 /// `bootstrap::reconcile_collect_retention`), applied at boot and again
407 /// whenever this document is saved from the SPA. Clamped to
408 /// [`MAX_COLLECT_RETENTION_DAYS`]. The bucket's `max_bytes` cap is
409 /// untouched, so extending the window can't make the store grow unbounded.
410 #[serde(skip_serializing_if = "Option::is_none")]
411 pub collect_retention_days: Option<u32>,
412
413 /// How long `OBJECT_RESULT_OUTPUT` keeps an overflowed stdout/stderr
414 /// blob, in days. Absent / null falls back to
415 /// [`DEFAULT_RESULT_OUTPUT_RETENTION_DAYS`].
416 ///
417 /// Unlike `collect_retention_days`, this window is NOT how long the data
418 /// survives — the results projector derefs each blob into the row before
419 /// the INSERT, so the text lives in SQLite and the SPA reads it from
420 /// there regardless. What it bounds is how long a `-WipeDb`
421 /// re-projection can still recover that text: replay re-derefs, and an
422 /// aged-out object comes back as empty stdout on the rebuilt row.
423 ///
424 /// So this trades recovery window against standing volume, and volume is
425 /// what filled the bucket into its cap (#1321 — a hard wall, not
426 /// eviction) and stopped result delivery fleet-wide. Clamped to
427 /// [`MAX_RESULT_OUTPUT_RETENTION_DAYS`], which is `STREAM_RESULTS`'s own
428 /// window: past it there is no message left to replay.
429 #[serde(skip_serializing_if = "Option::is_none")]
430 pub result_output_retention_days: Option<u32>,
431
432 /// How many hours a freshly-minted login token (SPA / CLI) stays valid
433 /// before the caller must re-authenticate. Read backend-side by the
434 /// login handler when it mints the JWT `exp`; changing it affects
435 /// **tokens minted after the change**, not already-issued ones.
436 ///
437 /// Like [`collect_retention_days`](Self::collect_retention_days) this
438 /// carries a **real built-in default** ([`DEFAULT_SESSION_TTL_HOURS`],
439 /// 24h): `None` (unset) falls back to it, so a blank field resolves to a
440 /// usable window rather than an instantly-expired token. Clamped to
441 /// `1..=`[`MAX_SESSION_TTL_HOURS`]. The SPA renders `24` as a faint
442 /// placeholder on a blank field.
443 #[serde(skip_serializing_if = "Option::is_none")]
444 pub session_ttl_hours: Option<u32>,
445
446 /// Days a `check_status` row may go without a fresh result before the
447 /// Compliance page treats it as **stale** and hides it (#1032②). A PC that
448 /// stops running a check — excluded from its target via a dynamic group,
449 /// decommissioned, or its schedule removed — stops refreshing its row's
450 /// `recorded_at`; once that timestamp is older than this window the row is
451 /// omitted from the default `/api/checks` view and its counts, so a machine
452 /// no longer in scope stops showing as permanently failing a check it never
453 /// runs.
454 ///
455 /// Like [`collect_retention_days`](Self::collect_retention_days) this carries
456 /// a **real built-in default** ([`DEFAULT_CHECK_STATUS_STALE_DAYS`], 30d), so
457 /// the feature works with no configuration. `0` **disables** staleness
458 /// (every row shown, the pre-feature behaviour); a positive value is the
459 /// cutoff, clamped to [`MAX_CHECK_STATUS_STALE_DAYS`]. The row is never
460 /// deleted — hiding is non-destructive so history and the compliance-alert
461 /// prior-status are preserved.
462 #[serde(skip_serializing_if = "Option::is_none")]
463 pub check_status_stale_days: Option<u32>,
464
465 /// Per-bucket disk caps (MiB) for the five NATS Object Stores (#1247)
466 /// — see [`ObjectStoreCaps`]. `None` (unset) ⇒ every bucket resolves
467 /// to its built-in default, so a blank field preserves the out-of-box
468 /// budget. Applied to the backing `OBJ_*` streams at backend boot and
469 /// whenever this document is saved from the SPA
470 /// (`bootstrap::reconcile_object_store_max_bytes`), which is also what
471 /// finally delivers caps to buckets created before the caps existed.
472 #[serde(skip_serializing_if = "Option::is_none")]
473 pub object_store_caps: Option<ObjectStoreCaps>,
474
475 /// Operator-issued support codes — the helpdesk "裏コマンド" that reveals
476 /// `client.unlock`-scoped jobs in the Client App. See [`SupportCode`].
477 ///
478 /// The one non-`Option` field in this document, because a list has an
479 /// honest empty state: `[]` (the default) means **no codes configured**,
480 /// so every `client.unlock` job stays hidden from everyone — the same
481 /// fail-closed "behave as before" the `None`s give the other fields.
482 ///
483 /// Unlike the rest of the document this is read by **agents** as well as
484 /// the backend (each agent verifies a typed code against these hashes
485 /// locally, so an unlock still works during a backend outage), and it is
486 /// **not** editable through the generic `PUT /api/server-settings` merge:
487 /// a secret gets its own set-and-forget endpoint so a redacted document
488 /// round-tripping through the SPA form can never blank a live code.
489 #[serde(skip_serializing_if = "Vec::is_empty")]
490 pub support_codes: Vec<SupportCode>,
491}
492
493impl ServerSettings {
494 /// Built-in defaults applied when a field is unset (`None`) in the
495 /// stored document. Most fields default to `None` (no fleet-meaningful
496 /// default — a blank prune window means "disabled" rather than some
497 /// arbitrary number of days). The exceptions carry real defaults so a
498 /// blank field still resolves to a sensible value:
499 /// [`collect_retention_days`](Self::collect_retention_days)
500 /// ([`DEFAULT_COLLECT_RETENTION_DAYS`], preserving the historical 30-day
501 /// retention), [`result_output_retention_days`](Self::result_output_retention_days)
502 /// ([`DEFAULT_RESULT_OUTPUT_RETENTION_DAYS`], 7 days — deliberately NOT
503 /// the historical 30, see that constant) and
504 /// [`session_ttl_hours`](Self::session_ttl_hours)
505 /// ([`DEFAULT_SESSION_TTL_HOURS`], 24h).
506 ///
507 /// Exposed via `GET /api/server-settings/defaults` so the SPA renders
508 /// these as faint placeholders (mirroring the agent layered-config
509 /// page's built-in floor). Introducing a real default is a one-line
510 /// change here that automatically shows up in the UI and applies to
511 /// every deployment that hasn't overridden the field.
512 pub fn defaults() -> Self {
513 Self {
514 agent_prune_days: None,
515 controller_group: None,
516 mail: None,
517 agent_install: None,
518 collect_retention_days: Some(DEFAULT_COLLECT_RETENTION_DAYS),
519 result_output_retention_days: Some(DEFAULT_RESULT_OUTPUT_RETENTION_DAYS),
520 session_ttl_hours: Some(DEFAULT_SESSION_TTL_HOURS),
521 check_status_stale_days: Some(DEFAULT_CHECK_STATUS_STALE_DAYS),
522 // Real per-bucket defaults, so the SPA renders them as faint
523 // placeholders and unset deployments are capped out of the box.
524 object_store_caps: Some(ObjectStoreCaps {
525 result_output_mib: Some(DEFAULT_RESULT_OUTPUT_CAP_MIB),
526 agent_releases_mib: Some(DEFAULT_AGENT_RELEASES_CAP_MIB),
527 app_packages_mib: Some(DEFAULT_APP_PACKAGES_CAP_MIB),
528 scripts_mib: Some(DEFAULT_SCRIPTS_CAP_MIB),
529 collections_mib: Some(DEFAULT_COLLECTIONS_CAP_MIB),
530 }),
531 // No built-in code: a deployment that configures none has no
532 // unlockable jobs, which is the only safe default for a secret.
533 support_codes: Vec::new(),
534 }
535 }
536
537 /// The caps document with every bucket resolved: stored values where
538 /// set, built-in defaults elsewhere, each clamped to
539 /// `1..=MAX_OBJECT_STORE_CAP_MIB` so an out-of-band KV write can't
540 /// reach the broker unsanitised.
541 pub fn effective_object_store_caps(&self) -> ObjectStoreCaps {
542 let c = self.object_store_caps.clone().unwrap_or_default();
543 ObjectStoreCaps {
544 result_output_mib: Some(c.effective_result_output_mib()),
545 agent_releases_mib: Some(c.effective_agent_releases_mib()),
546 app_packages_mib: Some(c.effective_app_packages_mib()),
547 scripts_mib: Some(c.effective_scripts_mib()),
548 collections_mib: Some(c.effective_collections_mib()),
549 }
550 }
551
552 /// The live code for `scope`, or `None` when the scope has no code, its
553 /// code is disabled, or the hash was blanked (an API-redacted document).
554 /// Every caller of this is a gate, so all three cases fail closed.
555 pub fn support_code(&self, scope: &str) -> Option<&SupportCode> {
556 self.support_codes
557 .iter()
558 .find(|c| c.scope == scope && c.is_usable())
559 }
560
561 /// The same document with every support-code hash blanked — what an HTTP
562 /// response is allowed to contain. Scope / label / TTL stay visible so
563 /// the SPA can list and manage the codes; the secret material never
564 /// leaves the backend, not even to an operator-authenticated caller.
565 /// (`GET /api/server-settings` is viewer+, so an unredacted document
566 /// would hand every read-only account an offline-crackable hash.)
567 ///
568 /// Same treatment for `agent_install.nats_token`: it is a live broker
569 /// credential baked into installer ZIPs, so it never leaves the backend
570 /// either — the response carries only `nats_token_set` (computed HERE,
571 /// never accepted from a client) so the SPA can render "configured".
572 #[must_use]
573 pub fn redacted(mut self) -> Self {
574 for c in &mut self.support_codes {
575 c.hash.clear();
576 }
577 if let Some(ai) = self.agent_install.as_mut() {
578 ai.nats_token_set = ai.nats_token.is_some();
579 ai.nats_token = None;
580 }
581 self
582 }
583
584 /// The configured controller-tier runner group, trimmed, or `None` when
585 /// unset / blank. `None` ⇒ controller-tier jobs run nowhere (fail-safe).
586 pub fn effective_controller_group(&self) -> Option<&str> {
587 self.controller_group
588 .as_deref()
589 .map(str::trim)
590 .filter(|g| !g.is_empty())
591 }
592
593 /// The effective dead-agent prune window in days: the stored value if
594 /// set, else the built-in default, else `0` (= pruning disabled). The
595 /// final `unwrap_or(0)` is the absent-everywhere floor, not a
596 /// user-facing default — the cleanup task treats `0` as "don't prune".
597 ///
598 /// Clamped to [`MAX_AGENT_PRUNE_DAYS`] so the cleanup task's
599 /// `now - Duration::days(n)` can never overflow `DateTime` (and panic
600 /// the task), even if a value larger than the PUT handler allows was
601 /// written to the KV out-of-band.
602 pub fn effective_agent_prune_days(&self) -> u32 {
603 self.agent_prune_days
604 .or(Self::defaults().agent_prune_days)
605 .unwrap_or(0)
606 .min(MAX_AGENT_PRUNE_DAYS)
607 }
608
609 /// The effective collect-bundle retention window in days: the stored
610 /// value if set, else the built-in default ([`DEFAULT_COLLECT_RETENTION_DAYS`]).
611 /// Floored at 1 and clamped to [`MAX_COLLECT_RETENTION_DAYS`] so an
612 /// out-of-band KV write can't reach the Object Store `max_age` unsanitised.
613 /// The floor matters specifically because NATS treats `max_age: 0` as
614 /// **unlimited** retention, not "evict immediately": a stray `0` would
615 /// silently make bundles never expire (defeating the auto-expire intent),
616 /// so we coerce it to the shortest real window (1 day) instead. The PUT
617 /// handler already rejects `0` / over-cap, so this is the belt-and-braces
618 /// path for a hand-edited KV value.
619 pub fn effective_collect_retention_days(&self) -> u32 {
620 self.collect_retention_days
621 .or(Self::defaults().collect_retention_days)
622 .unwrap_or(DEFAULT_COLLECT_RETENTION_DAYS)
623 .clamp(1, MAX_COLLECT_RETENTION_DAYS)
624 }
625
626 /// The effective `result_output` retention window in days: the stored
627 /// value if set, else the built-in default. Floored at 1 and clamped to
628 /// [`MAX_RESULT_OUTPUT_RETENTION_DAYS`] so a hand-written KV value can
629 /// neither disable retention outright nor outlive the stream it exists
630 /// to serve.
631 pub fn effective_result_output_retention_days(&self) -> u32 {
632 self.result_output_retention_days
633 .or(Self::defaults().result_output_retention_days)
634 .unwrap_or(DEFAULT_RESULT_OUTPUT_RETENTION_DAYS)
635 .clamp(1, MAX_RESULT_OUTPUT_RETENTION_DAYS)
636 }
637
638 /// The effective login-token lifetime in hours: the stored value if
639 /// set, else the built-in [`DEFAULT_SESSION_TTL_HOURS`]. Floored at 1
640 /// and clamped to [`MAX_SESSION_TTL_HOURS`] so a zero/absent/out-of-band
641 /// value can never mint an already-expired or overflow-inducing token.
642 /// The PUT handler already rejects `0` / over-cap, so this is the
643 /// belt-and-braces path for a hand-edited KV value.
644 pub fn effective_session_ttl_hours(&self) -> u32 {
645 self.session_ttl_hours
646 .or(Self::defaults().session_ttl_hours)
647 .unwrap_or(DEFAULT_SESSION_TTL_HOURS)
648 .clamp(1, MAX_SESSION_TTL_HOURS)
649 }
650
651 /// The effective check-staleness window in days: the stored value if set,
652 /// else the built-in [`DEFAULT_CHECK_STATUS_STALE_DAYS`]. **`0` means
653 /// disabled** (no row is ever hidden as stale) — deliberately NOT floored to
654 /// 1 (unlike collect/session), because 0 is a meaningful "show everything"
655 /// value here, the same convention as [`agent_prune_days`](Self::agent_prune_days).
656 /// Clamped to [`MAX_CHECK_STATUS_STALE_DAYS`] so an out-of-band KV write
657 /// can't overflow the `now - Duration::days(n)` cutoff math.
658 pub fn effective_check_status_stale_days(&self) -> u32 {
659 self.check_status_stale_days
660 .or(Self::defaults().check_status_stale_days)
661 .unwrap_or(DEFAULT_CHECK_STATUS_STALE_DAYS)
662 .min(MAX_CHECK_STATUS_STALE_DAYS)
663 }
664}
665
666#[cfg(test)]
667mod tests {
668 use super::*;
669
670 #[test]
671 fn default_is_unset() {
672 assert_eq!(ServerSettings::default().agent_prune_days, None);
673 }
674
675 #[test]
676 fn unset_resolves_to_disabled() {
677 // No stored value + no built-in default ⇒ effective 0 (disabled).
678 assert_eq!(ServerSettings::default().effective_agent_prune_days(), 0);
679 }
680
681 #[test]
682 fn stored_value_wins_over_default() {
683 let s = ServerSettings {
684 agent_prune_days: Some(30),
685 ..Default::default()
686 };
687 assert_eq!(s.effective_agent_prune_days(), 30);
688 }
689
690 #[test]
691 fn effective_clamps_to_max() {
692 // An out-of-band KV write larger than the PUT cap must not reach
693 // the cleanup task unclamped (else its DateTime subtraction panics).
694 let s = ServerSettings {
695 agent_prune_days: Some(u32::MAX),
696 ..Default::default()
697 };
698 assert_eq!(s.effective_agent_prune_days(), MAX_AGENT_PRUNE_DAYS);
699 }
700
701 #[test]
702 fn round_trips_through_json() {
703 let s = ServerSettings {
704 agent_prune_days: Some(30),
705 ..Default::default()
706 };
707 let json = serde_json::to_string(&s).unwrap();
708 assert_eq!(json, r#"{"agent_prune_days":30}"#);
709 let back: ServerSettings = serde_json::from_str(&json).unwrap();
710 assert_eq!(back, s);
711 }
712
713 #[test]
714 fn unset_serialises_to_empty_object() {
715 // `skip_serializing_if` keeps an all-unset doc minimal; it must
716 // round-trip back to all-`None`.
717 let s = ServerSettings::default();
718 let json = serde_json::to_string(&s).unwrap();
719 assert_eq!(json, "{}");
720 let back: ServerSettings = serde_json::from_str(&json).unwrap();
721 assert_eq!(back, s);
722 }
723
724 #[test]
725 fn explicit_null_decodes_to_unset() {
726 let s: ServerSettings = serde_json::from_str(r#"{"agent_prune_days":null}"#).unwrap();
727 assert_eq!(s.agent_prune_days, None);
728 }
729
730 #[test]
731 fn empty_object_decodes_to_default() {
732 // A freshly-created key (or one written by an older backend that
733 // didn't know this field) must read back as the pre-feature
734 // behaviour, not fail to decode.
735 let s: ServerSettings = serde_json::from_str("{}").unwrap();
736 assert_eq!(s, ServerSettings::default());
737 }
738
739 #[test]
740 fn controller_group_effective_trims_and_blank_is_unset() {
741 assert_eq!(ServerSettings::default().effective_controller_group(), None);
742 let s = ServerSettings {
743 controller_group: Some(" feed-runners ".into()),
744 ..Default::default()
745 };
746 assert_eq!(s.effective_controller_group(), Some("feed-runners"));
747 // A blank/whitespace value reads as unset (fail-safe: no runner).
748 let blank = ServerSettings {
749 controller_group: Some(" ".into()),
750 ..Default::default()
751 };
752 assert_eq!(blank.effective_controller_group(), None);
753 }
754
755 #[test]
756 fn controller_group_round_trips_and_omits_when_unset() {
757 let s = ServerSettings {
758 controller_group: Some("infra".into()),
759 ..Default::default()
760 };
761 let json = serde_json::to_string(&s).unwrap();
762 assert_eq!(json, r#"{"controller_group":"infra"}"#);
763 assert_eq!(serde_json::from_str::<ServerSettings>(&json).unwrap(), s);
764 // Unset controller_group is omitted (skip_serializing_if).
765 assert_eq!(
766 serde_json::to_string(&ServerSettings::default()).unwrap(),
767 "{}"
768 );
769 }
770
771 #[test]
772 fn mail_round_trips_and_omits_when_unset() {
773 use crate::config::{MailEncryption, MailSection};
774
775 // Unset mail is omitted (skip_serializing_if) — a mail-less doc
776 // stays minimal and decodes back to `None`.
777 assert_eq!(
778 serde_json::to_string(&ServerSettings::default()).unwrap(),
779 "{}"
780 );
781
782 let s = ServerSettings {
783 mail: Some(MailSection {
784 host: "smtp.example.com".into(),
785 port: 587,
786 encryption: MailEncryption::Starttls,
787 from: "kanade-noreply@example.com".into(),
788 username: Some("kanade-noreply".into()),
789 }),
790 ..Default::default()
791 };
792 let json = serde_json::to_string(&s).unwrap();
793 // Encryption serialises lowercase; the password is never present.
794 assert!(json.contains(r#""encryption":"starttls""#), "json: {json}");
795 assert!(!json.contains("password"), "password must never serialise");
796 assert_eq!(serde_json::from_str::<ServerSettings>(&json).unwrap(), s);
797 }
798
799 #[test]
800 fn mail_defaults_to_unset() {
801 assert_eq!(ServerSettings::default().mail, None);
802 // A doc written before this field existed (no `mail` key) decodes
803 // to `None` — email stays a no-op, the pre-feature behaviour.
804 let s: ServerSettings = serde_json::from_str(r#"{"agent_prune_days":7}"#).unwrap();
805 assert_eq!(s.mail, None);
806 assert_eq!(s.agent_prune_days, Some(7));
807 }
808
809 #[test]
810 fn collect_retention_unset_resolves_to_builtin_default() {
811 // Blank (the derived Default) must preserve the historical 30-day
812 // window, not disable retention.
813 assert_eq!(ServerSettings::default().collect_retention_days, None);
814 assert_eq!(
815 ServerSettings::default().effective_collect_retention_days(),
816 DEFAULT_COLLECT_RETENTION_DAYS,
817 );
818 // The defaults() document surfaces the real default so the SPA can
819 // render it as a placeholder.
820 assert_eq!(
821 ServerSettings::defaults().collect_retention_days,
822 Some(DEFAULT_COLLECT_RETENTION_DAYS),
823 );
824 }
825
826 #[test]
827 fn collect_retention_stored_value_wins() {
828 let s = ServerSettings {
829 collect_retention_days: Some(90),
830 ..Default::default()
831 };
832 assert_eq!(s.effective_collect_retention_days(), 90);
833 }
834
835 #[test]
836 fn collect_retention_effective_clamps_out_of_band_writes() {
837 // A hand-written KV value past the PUT cap (or 0) must be clamped so
838 // the reconciled Object Store max_age stays sane.
839 let big = ServerSettings {
840 collect_retention_days: Some(u32::MAX),
841 ..Default::default()
842 };
843 assert_eq!(
844 big.effective_collect_retention_days(),
845 MAX_COLLECT_RETENTION_DAYS,
846 );
847 let zero = ServerSettings {
848 collect_retention_days: Some(0),
849 ..Default::default()
850 };
851 assert_eq!(zero.effective_collect_retention_days(), 1);
852 }
853
854 #[test]
855 fn result_output_retention_defaults_to_a_week_not_the_old_month() {
856 // The built-in default IS the fix: existing buckets were born at 30
857 // days and reconcile down to this. If someone raises it back the
858 // bucket grows again, so the value is pinned rather than left to the
859 // constant's own definition.
860 assert_eq!(DEFAULT_RESULT_OUTPUT_RETENTION_DAYS, 7);
861 assert_eq!(
862 ServerSettings::default().effective_result_output_retention_days(),
863 7
864 );
865 }
866
867 #[test]
868 fn result_output_retention_is_capped_by_the_stream_it_serves() {
869 // Beyond STREAM_RESULTS' own window there is no message left to
870 // replay, so a longer object window keeps blobs nothing can ask for.
871 assert_eq!(MAX_RESULT_OUTPUT_RETENTION_DAYS, 30);
872 let big = ServerSettings {
873 result_output_retention_days: Some(u32::MAX),
874 ..Default::default()
875 };
876 assert_eq!(
877 big.effective_result_output_retention_days(),
878 MAX_RESULT_OUTPUT_RETENTION_DAYS
879 );
880 // …and 0 is floored rather than disabling retention, which would put
881 // the bucket straight back to unbounded growth.
882 let zero = ServerSettings {
883 result_output_retention_days: Some(0),
884 ..Default::default()
885 };
886 assert_eq!(zero.effective_result_output_retention_days(), 1);
887 }
888
889 #[test]
890 fn collect_retention_round_trips_and_omits_when_unset() {
891 let s = ServerSettings {
892 collect_retention_days: Some(90),
893 ..Default::default()
894 };
895 let json = serde_json::to_string(&s).unwrap();
896 assert_eq!(json, r#"{"collect_retention_days":90}"#);
897 assert_eq!(serde_json::from_str::<ServerSettings>(&json).unwrap(), s);
898 // Unset is omitted so a blank doc stays minimal.
899 assert!(
900 !serde_json::to_string(&ServerSettings::default())
901 .unwrap()
902 .contains("collect_retention_days")
903 );
904 }
905
906 #[test]
907 fn session_ttl_unset_resolves_to_builtin_default() {
908 // Blank (the derived Default) must resolve to the 24h default rather
909 // than 0 (which would mint already-expired tokens).
910 assert_eq!(ServerSettings::default().session_ttl_hours, None);
911 assert_eq!(
912 ServerSettings::default().effective_session_ttl_hours(),
913 DEFAULT_SESSION_TTL_HOURS,
914 );
915 // The defaults() document surfaces the real default so the SPA can
916 // render it as a placeholder.
917 assert_eq!(
918 ServerSettings::defaults().session_ttl_hours,
919 Some(DEFAULT_SESSION_TTL_HOURS),
920 );
921 }
922
923 #[test]
924 fn session_ttl_stored_value_wins() {
925 let s = ServerSettings {
926 session_ttl_hours: Some(72),
927 ..Default::default()
928 };
929 assert_eq!(s.effective_session_ttl_hours(), 72);
930 }
931
932 #[test]
933 fn session_ttl_effective_clamps_out_of_band_writes() {
934 // An out-of-band 0 must floor to 1 (else `now + 0h` is an
935 // instantly-expired token); a value past the cap clamps down so
936 // login's date math can't overflow.
937 let zero = ServerSettings {
938 session_ttl_hours: Some(0),
939 ..Default::default()
940 };
941 assert_eq!(zero.effective_session_ttl_hours(), 1);
942 let huge = ServerSettings {
943 session_ttl_hours: Some(u32::MAX),
944 ..Default::default()
945 };
946 assert_eq!(huge.effective_session_ttl_hours(), MAX_SESSION_TTL_HOURS);
947 }
948
949 #[test]
950 fn session_ttl_round_trips_and_omits_when_unset() {
951 let s = ServerSettings {
952 session_ttl_hours: Some(48),
953 ..Default::default()
954 };
955 let json = serde_json::to_string(&s).unwrap();
956 assert_eq!(json, r#"{"session_ttl_hours":48}"#);
957 assert_eq!(serde_json::from_str::<ServerSettings>(&json).unwrap(), s);
958 // Unset is omitted so a blank doc stays minimal.
959 assert!(
960 !serde_json::to_string(&ServerSettings::default())
961 .unwrap()
962 .contains("session_ttl_hours")
963 );
964 }
965
966 #[test]
967 fn check_stale_unset_resolves_to_builtin_default() {
968 // Blank (the derived Default) resolves to the 30-day default — ON out
969 // of the box, so the feature works without configuration.
970 assert_eq!(ServerSettings::default().check_status_stale_days, None);
971 assert_eq!(
972 ServerSettings::default().effective_check_status_stale_days(),
973 DEFAULT_CHECK_STATUS_STALE_DAYS,
974 );
975 // defaults() surfaces the real default for the SPA placeholder.
976 assert_eq!(
977 ServerSettings::defaults().check_status_stale_days,
978 Some(DEFAULT_CHECK_STATUS_STALE_DAYS),
979 );
980 }
981
982 #[test]
983 fn check_stale_zero_disables() {
984 // Explicit 0 means "disable staleness" (show everything) — NOT floored
985 // to 1 like collect/session; same convention as agent_prune_days.
986 let s = ServerSettings {
987 check_status_stale_days: Some(0),
988 ..Default::default()
989 };
990 assert_eq!(s.effective_check_status_stale_days(), 0);
991 }
992
993 #[test]
994 fn check_stale_stored_value_wins_and_clamps() {
995 let s = ServerSettings {
996 check_status_stale_days: Some(7),
997 ..Default::default()
998 };
999 assert_eq!(s.effective_check_status_stale_days(), 7);
1000 let big = ServerSettings {
1001 check_status_stale_days: Some(u32::MAX),
1002 ..Default::default()
1003 };
1004 assert_eq!(
1005 big.effective_check_status_stale_days(),
1006 MAX_CHECK_STATUS_STALE_DAYS,
1007 );
1008 }
1009
1010 #[test]
1011 fn check_stale_round_trips_and_omits_when_unset() {
1012 let s = ServerSettings {
1013 check_status_stale_days: Some(14),
1014 ..Default::default()
1015 };
1016 let json = serde_json::to_string(&s).unwrap();
1017 assert_eq!(json, r#"{"check_status_stale_days":14}"#);
1018 assert_eq!(serde_json::from_str::<ServerSettings>(&json).unwrap(), s);
1019 assert!(
1020 !serde_json::to_string(&ServerSettings::default())
1021 .unwrap()
1022 .contains("check_status_stale_days")
1023 );
1024 }
1025
1026 #[test]
1027 fn support_codes_absent_by_default_and_omitted_from_the_wire() {
1028 // The pre-feature document must round-trip byte-identically: no
1029 // `support_codes` key, so an older backend / agent reading it sees
1030 // exactly what it saw before, and nothing is unlockable.
1031 let s = ServerSettings::default();
1032 assert!(s.support_codes.is_empty());
1033 assert_eq!(serde_json::to_string(&s).unwrap(), "{}");
1034 assert!(s.support_code("support").is_none());
1035 }
1036
1037 #[test]
1038 fn support_code_lookup_fails_closed() {
1039 let s = ServerSettings {
1040 support_codes: vec![
1041 SupportCode {
1042 scope: "support".into(),
1043 hash: "$argon2id$v=19$m=19456,t=2,p=1$c2FsdA$aGFzaA".into(),
1044 label: Some("ヘルプデスク".into()),
1045 ..Default::default()
1046 },
1047 SupportCode {
1048 scope: "admin".into(),
1049 hash: "$argon2id$v=19$m=19456,t=2,p=1$c2FsdA$aGFzaA".into(),
1050 disabled: true,
1051 ..Default::default()
1052 },
1053 SupportCode {
1054 // Hash blanked — what an API-redacted document looks like.
1055 // It must never be treated as a live code.
1056 scope: "blank".into(),
1057 ..Default::default()
1058 },
1059 ],
1060 ..Default::default()
1061 };
1062 assert!(s.support_code("support").is_some());
1063 assert!(s.support_code("admin").is_none(), "disabled must not match");
1064 assert!(
1065 s.support_code("blank").is_none(),
1066 "blank hash must not match"
1067 );
1068 assert!(s.support_code("nope").is_none());
1069 }
1070
1071 #[test]
1072 fn redacted_blanks_hashes_but_keeps_the_roster() {
1073 // The SPA still needs to see WHICH scopes exist (to list / rotate /
1074 // delete them); it must never see the hash.
1075 let s = ServerSettings {
1076 support_codes: vec![SupportCode {
1077 scope: "support".into(),
1078 hash: "$argon2id$secret".into(),
1079 label: Some("ヘルプデスク".into()),
1080 ttl_minutes: Some(30),
1081 disabled: false,
1082 }],
1083 ..Default::default()
1084 };
1085 let json = serde_json::to_string(&s.redacted()).unwrap();
1086 assert!(!json.contains("argon2"), "wire leaked the hash: {json}");
1087 assert!(!json.contains("hash"), "wire leaked the hash key: {json}");
1088 assert!(json.contains("\"scope\":\"support\""), "wire: {json}");
1089 assert!(json.contains("\"ttl_minutes\":30"), "wire: {json}");
1090 }
1091
1092 #[test]
1093 fn support_code_ttl_clamps() {
1094 let unset = SupportCode::default();
1095 assert_eq!(
1096 unset.effective_ttl_minutes(),
1097 DEFAULT_SUPPORT_UNLOCK_TTL_MINUTES
1098 );
1099 // 0 would mint an already-expired grant (an unlock that silently
1100 // does nothing) — floored to the shortest real window instead.
1101 let zero = SupportCode {
1102 ttl_minutes: Some(0),
1103 ..Default::default()
1104 };
1105 assert_eq!(zero.effective_ttl_minutes(), 1);
1106 let huge = SupportCode {
1107 ttl_minutes: Some(u32::MAX),
1108 ..Default::default()
1109 };
1110 assert_eq!(huge.effective_ttl_minutes(), MAX_SUPPORT_UNLOCK_TTL_MINUTES);
1111 }
1112
1113 #[test]
1114 fn accepts_unknown_fields_for_forward_compat() {
1115 // A newer backend may have added knobs this build doesn't know;
1116 // decoding must drop them rather than error.
1117 let json = r#"{"agent_prune_days":7,"some_future_knob":true}"#;
1118 let s: ServerSettings = serde_json::from_str(json).unwrap();
1119 assert_eq!(s.agent_prune_days, Some(7));
1120 }
1121
1122 #[test]
1123 fn object_store_caps_unset_resolves_to_builtin_defaults() {
1124 // Blank doc ⇒ every bucket capped at its built-in default — the
1125 // out-of-box fix for uncapped / drifted buckets (#1247).
1126 let s = ServerSettings::default();
1127 assert_eq!(s.object_store_caps, None);
1128 let c = s.effective_object_store_caps();
1129 assert_eq!(c.result_output_mib, Some(DEFAULT_RESULT_OUTPUT_CAP_MIB));
1130 assert_eq!(c.agent_releases_mib, Some(DEFAULT_AGENT_RELEASES_CAP_MIB));
1131 assert_eq!(c.app_packages_mib, Some(DEFAULT_APP_PACKAGES_CAP_MIB));
1132 assert_eq!(c.scripts_mib, Some(DEFAULT_SCRIPTS_CAP_MIB));
1133 assert_eq!(c.collections_mib, Some(DEFAULT_COLLECTIONS_CAP_MIB));
1134 }
1135
1136 #[test]
1137 fn object_store_caps_partial_override_keeps_other_defaults() {
1138 let s = ServerSettings {
1139 object_store_caps: Some(ObjectStoreCaps {
1140 app_packages_mib: Some(8192),
1141 ..Default::default()
1142 }),
1143 ..Default::default()
1144 };
1145 let c = s.effective_object_store_caps();
1146 assert_eq!(c.app_packages_mib, Some(8192));
1147 assert_eq!(c.scripts_mib, Some(DEFAULT_SCRIPTS_CAP_MIB));
1148 }
1149
1150 #[test]
1151 fn object_store_caps_clamps_out_of_band_writes() {
1152 let s = ServerSettings {
1153 object_store_caps: Some(ObjectStoreCaps {
1154 result_output_mib: Some(0),
1155 app_packages_mib: Some(u32::MAX),
1156 ..Default::default()
1157 }),
1158 ..Default::default()
1159 };
1160 let c = s.effective_object_store_caps();
1161 // 0 floors to 1 MiB — NATS treats max_bytes: 0 as unlimited, the
1162 // exact failure mode this feature exists to remove.
1163 assert_eq!(c.result_output_mib, Some(1));
1164 assert_eq!(c.app_packages_mib, Some(MAX_OBJECT_STORE_CAP_MIB));
1165 }
1166
1167 #[test]
1168 fn object_store_caps_round_trips_and_omits_when_unset() {
1169 let s = ServerSettings {
1170 object_store_caps: Some(ObjectStoreCaps {
1171 scripts_mib: Some(512),
1172 ..Default::default()
1173 }),
1174 ..Default::default()
1175 };
1176 let json = serde_json::to_string(&s).unwrap();
1177 assert_eq!(json, r#"{"object_store_caps":{"scripts_mib":512}}"#);
1178 assert_eq!(serde_json::from_str::<ServerSettings>(&json).unwrap(), s);
1179 assert!(
1180 !serde_json::to_string(&ServerSettings::default())
1181 .unwrap()
1182 .contains("object_store_caps")
1183 );
1184 }
1185
1186 #[test]
1187 fn agent_install_defaults_to_unset_and_omits_when_unset() {
1188 assert_eq!(ServerSettings::default().agent_install, None);
1189 assert_eq!(ServerSettings::defaults().agent_install, None);
1190 // A doc written before this field existed decodes to `None` — the
1191 // installer then falls back to the backend's own [nats] url, the
1192 // pre-feature behaviour.
1193 let s: ServerSettings = serde_json::from_str(r#"{"agent_prune_days":7}"#).unwrap();
1194 assert_eq!(s.agent_install, None);
1195 assert!(
1196 !serde_json::to_string(&ServerSettings::default())
1197 .unwrap()
1198 .contains("agent_install")
1199 );
1200 }
1201
1202 #[test]
1203 fn agent_install_round_trips() {
1204 let s = ServerSettings {
1205 agent_install: Some(AgentInstallSection {
1206 nats_url: Some("nats://broker.corp:4222".into()),
1207 nats_token: Some("s3cret".into()),
1208 nats_token_set: false,
1209 require_signed_commands: None,
1210 }),
1211 ..Default::default()
1212 };
1213 let json = serde_json::to_string(&s).unwrap();
1214 assert_eq!(
1215 json,
1216 r#"{"agent_install":{"nats_url":"nats://broker.corp:4222","nats_token":"s3cret","nats_token_set":false}}"#
1217 );
1218 assert_eq!(serde_json::from_str::<ServerSettings>(&json).unwrap(), s);
1219 }
1220
1221 #[test]
1222 fn agent_install_require_signed_commands_round_trips() {
1223 let s = ServerSettings {
1224 agent_install: Some(AgentInstallSection {
1225 require_signed_commands: Some(true),
1226 ..Default::default()
1227 }),
1228 ..Default::default()
1229 };
1230 let json = serde_json::to_string(&s).unwrap();
1231 assert_eq!(
1232 json,
1233 r#"{"agent_install":{"nats_token_set":false,"require_signed_commands":true}}"#
1234 );
1235 assert_eq!(serde_json::from_str::<ServerSettings>(&json).unwrap(), s);
1236 }
1237
1238 #[test]
1239 fn agent_install_token_set_is_never_accepted_from_the_wire() {
1240 // `skip_deserializing`: a client sending nats_token_set gets it
1241 // dropped, so the indicator can only ever come from redacted()
1242 // looking at the real stored token — never from a claim.
1243 let s: ServerSettings = serde_json::from_str(
1244 r#"{"agent_install":{"nats_url":"nats://b:4222","nats_token_set":true}}"#,
1245 )
1246 .unwrap();
1247 let ai = s.agent_install.unwrap();
1248 assert!(!ai.nats_token_set);
1249 assert_eq!(ai.nats_url.as_deref(), Some("nats://b:4222"));
1250 }
1251
1252 #[test]
1253 fn redacted_strips_the_install_token_but_reports_its_presence() {
1254 // GET /api/server-settings is viewer+, so the stored NATS token must
1255 // never survive redacted() — not even to an operator. The boolean is
1256 // all the SPA gets to render "configured".
1257 let with_token = ServerSettings {
1258 agent_install: Some(AgentInstallSection {
1259 nats_url: Some("nats://broker.corp:4222".into()),
1260 nats_token: Some("s3cret".into()),
1261 nats_token_set: false,
1262 require_signed_commands: None,
1263 }),
1264 ..Default::default()
1265 };
1266 let redacted = with_token.redacted();
1267 let ai = redacted.agent_install.as_ref().unwrap();
1268 assert_eq!(ai.nats_token, None, "token must not survive redacted()");
1269 assert!(ai.nats_token_set);
1270 // The URL is not a secret — it stays.
1271 assert_eq!(ai.nats_url.as_deref(), Some("nats://broker.corp:4222"));
1272 // And on the wire the token key is gone entirely (not null).
1273 let json = serde_json::to_string(&redacted).unwrap();
1274 assert!(!json.contains("s3cret"), "wire leaked the token: {json}");
1275 assert!(!json.contains("nats_token\""), "wire: {json}");
1276 assert!(json.contains(r#""nats_token_set":true"#), "wire: {json}");
1277
1278 // No token configured → indicator false, nothing to strip.
1279 let sans_token = ServerSettings {
1280 agent_install: Some(AgentInstallSection {
1281 nats_url: Some("nats://broker.corp:4222".into()),
1282 ..Default::default()
1283 }),
1284 ..Default::default()
1285 }
1286 .redacted();
1287 let ai = sans_token.agent_install.as_ref().unwrap();
1288 assert!(!ai.nats_token_set);
1289 }
1290}