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}
307
308/// Value stored in the `server_settings` KV bucket under the single key
309/// [`crate::kv::KEY_SERVER_SETTINGS`]. Operator-editable, backend-side
310/// server configuration that isn't per-agent (so it doesn't belong in
311/// `agent_config`'s layered scopes) and isn't a fleet-wide switch every
312/// agent watches (so it doesn't belong in `fleet_config`). Managed via
313/// the SPA Settings page's "server settings" tab.
314///
315/// Every field is `Option<_>`: `None` (the default / the JSON value
316/// `null` / the field simply absent) means **unset — fall back to the
317/// built-in default** ([`ServerSettings::defaults`]), exactly like the
318/// agent layered-config scopes. The SPA renders the built-in default as a
319/// faint placeholder so a blank field shows what it resolves to, and when
320/// a real default is introduced here it appears in the UI (and takes
321/// effect for already-deployed-but-unset fleets) for free.
322///
323/// `#[serde(default)]` on the container keeps the document backward/forward
324/// compatible: a freshly-created or missing key decodes to all-`None`
325/// (pre-feature behaviour), an older backend reading a newer document
326/// ignores unknown fields, and a newer backend reading an older document
327/// fills the missing field with `None`. Keep that invariant — never add a
328/// field whose `None` doesn't mean "behave as before".
329#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
330#[serde(default)]
331pub struct ServerSettings {
332 /// Days a dead agent (one whose heartbeat stopped arriving) may
333 /// linger in the `agents` registry before the backend cleanup task
334 /// prunes its row.
335 ///
336 /// `None` (unset) falls back to the built-in default; with no default
337 /// configured that resolves to pruning **disabled** (see
338 /// [`ServerSettings::effective_agent_prune_days`]). A positive value
339 /// makes the cleanup sweep delete rows whose `last_heartbeat` is older
340 /// than that many days. The `agents` table is a projection of the
341 /// heartbeat stream, so a machine that's merely offline (not gone)
342 /// reappears on its next heartbeat (~30s cadence); only
343 /// genuinely-retired machines stay gone.
344 #[serde(skip_serializing_if = "Option::is_none")]
345 pub agent_prune_days: Option<u32>,
346
347 /// Agent group whose members are the trusted **controller-tier**
348 /// runners. A job with `tier: controller` (e.g. a `feed:` job that
349 /// fetches an external URL) is dispatched ONLY to members of this group;
350 /// `None` (unset) means controller-tier jobs run **nowhere** (fail-safe,
351 /// so an external fetch never lands on an employee endpoint by accident).
352 /// See `crate::manifest::Tier`. `None` ⇒ no controller runners
353 /// configured, which is the safe default for a fresh deployment.
354 #[serde(skip_serializing_if = "Option::is_none")]
355 pub controller_group: Option<String>,
356
357 /// Non-secret SMTP relay settings for outbound email (compliance-alert
358 /// notifications, account setup links, …). Lives here (#884) rather than
359 /// in `backend.toml` so an operator can edit it from the SPA without
360 /// shell access to the host.
361 ///
362 /// `None` (unset) ⇒ no relay configured, email is a no-op — the in-app
363 /// / NATS notification path is unaffected. The SMTP **password is
364 /// deliberately not here** (KV is
365 /// readable over NATS): it stays sourced from the `MailPassword`
366 /// registry secret / `$KANADE_MAIL_PASSWORD` and is combined with these
367 /// settings when the backend builds its `Mailer`. Changes take effect on
368 /// the **next backend restart** (the backend builds the `Mailer` once at
369 /// startup — no live rebuild), which is acceptable per the #884
370 /// discussion.
371 #[serde(skip_serializing_if = "Option::is_none")]
372 pub mail: Option<MailSection>,
373
374 /// Self-service agent-installer knobs — see [`AgentInstallSection`].
375 /// `None` (unset) ⇒ the installer falls back to this backend's own
376 /// `[nats] url` and embeds no token. The `nats_token` inside is
377 /// write-only: [`ServerSettings::redacted`] strips it from every
378 /// response and the PUT merge preserves a stored token across a
379 /// url-only edit (the same support-code trap: a form round-trip must
380 /// never silently clear a secret).
381 #[serde(skip_serializing_if = "Option::is_none")]
382 pub agent_install: Option<AgentInstallSection>,
383
384 /// Retention window (days) for collected file bundles — the `collect:`
385 /// job archives uploaded to the `collections` Object Store (#219).
386 ///
387 /// Unlike the other fields, this one has a **real built-in default**
388 /// ([`DEFAULT_COLLECT_RETENTION_DAYS`], 30 d): `None` (unset) falls back
389 /// to it, so a blank field preserves the historical behaviour rather than
390 /// disabling retention. A positive value tells the backend to reconcile
391 /// the Object Store's `max_age` to that many days (see
392 /// `bootstrap::reconcile_collect_retention`), applied at boot and again
393 /// whenever this document is saved from the SPA. Clamped to
394 /// [`MAX_COLLECT_RETENTION_DAYS`]. The bucket's `max_bytes` cap is
395 /// untouched, so extending the window can't make the store grow unbounded.
396 #[serde(skip_serializing_if = "Option::is_none")]
397 pub collect_retention_days: Option<u32>,
398
399 /// How long `OBJECT_RESULT_OUTPUT` keeps an overflowed stdout/stderr
400 /// blob, in days. Absent / null falls back to
401 /// [`DEFAULT_RESULT_OUTPUT_RETENTION_DAYS`].
402 ///
403 /// Unlike `collect_retention_days`, this window is NOT how long the data
404 /// survives — the results projector derefs each blob into the row before
405 /// the INSERT, so the text lives in SQLite and the SPA reads it from
406 /// there regardless. What it bounds is how long a `-WipeDb`
407 /// re-projection can still recover that text: replay re-derefs, and an
408 /// aged-out object comes back as empty stdout on the rebuilt row.
409 ///
410 /// So this trades recovery window against standing volume, and volume is
411 /// what filled the bucket into its cap (#1321 — a hard wall, not
412 /// eviction) and stopped result delivery fleet-wide. Clamped to
413 /// [`MAX_RESULT_OUTPUT_RETENTION_DAYS`], which is `STREAM_RESULTS`'s own
414 /// window: past it there is no message left to replay.
415 #[serde(skip_serializing_if = "Option::is_none")]
416 pub result_output_retention_days: Option<u32>,
417
418 /// How many hours a freshly-minted login token (SPA / CLI) stays valid
419 /// before the caller must re-authenticate. Read backend-side by the
420 /// login handler when it mints the JWT `exp`; changing it affects
421 /// **tokens minted after the change**, not already-issued ones.
422 ///
423 /// Like [`collect_retention_days`](Self::collect_retention_days) this
424 /// carries a **real built-in default** ([`DEFAULT_SESSION_TTL_HOURS`],
425 /// 24h): `None` (unset) falls back to it, so a blank field resolves to a
426 /// usable window rather than an instantly-expired token. Clamped to
427 /// `1..=`[`MAX_SESSION_TTL_HOURS`]. The SPA renders `24` as a faint
428 /// placeholder on a blank field.
429 #[serde(skip_serializing_if = "Option::is_none")]
430 pub session_ttl_hours: Option<u32>,
431
432 /// Days a `check_status` row may go without a fresh result before the
433 /// Compliance page treats it as **stale** and hides it (#1032②). A PC that
434 /// stops running a check — excluded from its target via a dynamic group,
435 /// decommissioned, or its schedule removed — stops refreshing its row's
436 /// `recorded_at`; once that timestamp is older than this window the row is
437 /// omitted from the default `/api/checks` view and its counts, so a machine
438 /// no longer in scope stops showing as permanently failing a check it never
439 /// runs.
440 ///
441 /// Like [`collect_retention_days`](Self::collect_retention_days) this carries
442 /// a **real built-in default** ([`DEFAULT_CHECK_STATUS_STALE_DAYS`], 30d), so
443 /// the feature works with no configuration. `0` **disables** staleness
444 /// (every row shown, the pre-feature behaviour); a positive value is the
445 /// cutoff, clamped to [`MAX_CHECK_STATUS_STALE_DAYS`]. The row is never
446 /// deleted — hiding is non-destructive so history and the compliance-alert
447 /// prior-status are preserved.
448 #[serde(skip_serializing_if = "Option::is_none")]
449 pub check_status_stale_days: Option<u32>,
450
451 /// Per-bucket disk caps (MiB) for the five NATS Object Stores (#1247)
452 /// — see [`ObjectStoreCaps`]. `None` (unset) ⇒ every bucket resolves
453 /// to its built-in default, so a blank field preserves the out-of-box
454 /// budget. Applied to the backing `OBJ_*` streams at backend boot and
455 /// whenever this document is saved from the SPA
456 /// (`bootstrap::reconcile_object_store_max_bytes`), which is also what
457 /// finally delivers caps to buckets created before the caps existed.
458 #[serde(skip_serializing_if = "Option::is_none")]
459 pub object_store_caps: Option<ObjectStoreCaps>,
460
461 /// Operator-issued support codes — the helpdesk "裏コマンド" that reveals
462 /// `client.unlock`-scoped jobs in the Client App. See [`SupportCode`].
463 ///
464 /// The one non-`Option` field in this document, because a list has an
465 /// honest empty state: `[]` (the default) means **no codes configured**,
466 /// so every `client.unlock` job stays hidden from everyone — the same
467 /// fail-closed "behave as before" the `None`s give the other fields.
468 ///
469 /// Unlike the rest of the document this is read by **agents** as well as
470 /// the backend (each agent verifies a typed code against these hashes
471 /// locally, so an unlock still works during a backend outage), and it is
472 /// **not** editable through the generic `PUT /api/server-settings` merge:
473 /// a secret gets its own set-and-forget endpoint so a redacted document
474 /// round-tripping through the SPA form can never blank a live code.
475 #[serde(skip_serializing_if = "Vec::is_empty")]
476 pub support_codes: Vec<SupportCode>,
477}
478
479impl ServerSettings {
480 /// Built-in defaults applied when a field is unset (`None`) in the
481 /// stored document. Most fields default to `None` (no fleet-meaningful
482 /// default — a blank prune window means "disabled" rather than some
483 /// arbitrary number of days). The exceptions carry real defaults so a
484 /// blank field still resolves to a sensible value:
485 /// [`collect_retention_days`](Self::collect_retention_days)
486 /// ([`DEFAULT_COLLECT_RETENTION_DAYS`], preserving the historical 30-day
487 /// retention), [`result_output_retention_days`](Self::result_output_retention_days)
488 /// ([`DEFAULT_RESULT_OUTPUT_RETENTION_DAYS`], 7 days — deliberately NOT
489 /// the historical 30, see that constant) and
490 /// [`session_ttl_hours`](Self::session_ttl_hours)
491 /// ([`DEFAULT_SESSION_TTL_HOURS`], 24h).
492 ///
493 /// Exposed via `GET /api/server-settings/defaults` so the SPA renders
494 /// these as faint placeholders (mirroring the agent layered-config
495 /// page's built-in floor). Introducing a real default is a one-line
496 /// change here that automatically shows up in the UI and applies to
497 /// every deployment that hasn't overridden the field.
498 pub fn defaults() -> Self {
499 Self {
500 agent_prune_days: None,
501 controller_group: None,
502 mail: None,
503 agent_install: None,
504 collect_retention_days: Some(DEFAULT_COLLECT_RETENTION_DAYS),
505 result_output_retention_days: Some(DEFAULT_RESULT_OUTPUT_RETENTION_DAYS),
506 session_ttl_hours: Some(DEFAULT_SESSION_TTL_HOURS),
507 check_status_stale_days: Some(DEFAULT_CHECK_STATUS_STALE_DAYS),
508 // Real per-bucket defaults, so the SPA renders them as faint
509 // placeholders and unset deployments are capped out of the box.
510 object_store_caps: Some(ObjectStoreCaps {
511 result_output_mib: Some(DEFAULT_RESULT_OUTPUT_CAP_MIB),
512 agent_releases_mib: Some(DEFAULT_AGENT_RELEASES_CAP_MIB),
513 app_packages_mib: Some(DEFAULT_APP_PACKAGES_CAP_MIB),
514 scripts_mib: Some(DEFAULT_SCRIPTS_CAP_MIB),
515 collections_mib: Some(DEFAULT_COLLECTIONS_CAP_MIB),
516 }),
517 // No built-in code: a deployment that configures none has no
518 // unlockable jobs, which is the only safe default for a secret.
519 support_codes: Vec::new(),
520 }
521 }
522
523 /// The caps document with every bucket resolved: stored values where
524 /// set, built-in defaults elsewhere, each clamped to
525 /// `1..=MAX_OBJECT_STORE_CAP_MIB` so an out-of-band KV write can't
526 /// reach the broker unsanitised.
527 pub fn effective_object_store_caps(&self) -> ObjectStoreCaps {
528 let c = self.object_store_caps.clone().unwrap_or_default();
529 ObjectStoreCaps {
530 result_output_mib: Some(c.effective_result_output_mib()),
531 agent_releases_mib: Some(c.effective_agent_releases_mib()),
532 app_packages_mib: Some(c.effective_app_packages_mib()),
533 scripts_mib: Some(c.effective_scripts_mib()),
534 collections_mib: Some(c.effective_collections_mib()),
535 }
536 }
537
538 /// The live code for `scope`, or `None` when the scope has no code, its
539 /// code is disabled, or the hash was blanked (an API-redacted document).
540 /// Every caller of this is a gate, so all three cases fail closed.
541 pub fn support_code(&self, scope: &str) -> Option<&SupportCode> {
542 self.support_codes
543 .iter()
544 .find(|c| c.scope == scope && c.is_usable())
545 }
546
547 /// The same document with every support-code hash blanked — what an HTTP
548 /// response is allowed to contain. Scope / label / TTL stay visible so
549 /// the SPA can list and manage the codes; the secret material never
550 /// leaves the backend, not even to an operator-authenticated caller.
551 /// (`GET /api/server-settings` is viewer+, so an unredacted document
552 /// would hand every read-only account an offline-crackable hash.)
553 ///
554 /// Same treatment for `agent_install.nats_token`: it is a live broker
555 /// credential baked into installer ZIPs, so it never leaves the backend
556 /// either — the response carries only `nats_token_set` (computed HERE,
557 /// never accepted from a client) so the SPA can render "configured".
558 #[must_use]
559 pub fn redacted(mut self) -> Self {
560 for c in &mut self.support_codes {
561 c.hash.clear();
562 }
563 if let Some(ai) = self.agent_install.as_mut() {
564 ai.nats_token_set = ai.nats_token.is_some();
565 ai.nats_token = None;
566 }
567 self
568 }
569
570 /// The configured controller-tier runner group, trimmed, or `None` when
571 /// unset / blank. `None` ⇒ controller-tier jobs run nowhere (fail-safe).
572 pub fn effective_controller_group(&self) -> Option<&str> {
573 self.controller_group
574 .as_deref()
575 .map(str::trim)
576 .filter(|g| !g.is_empty())
577 }
578
579 /// The effective dead-agent prune window in days: the stored value if
580 /// set, else the built-in default, else `0` (= pruning disabled). The
581 /// final `unwrap_or(0)` is the absent-everywhere floor, not a
582 /// user-facing default — the cleanup task treats `0` as "don't prune".
583 ///
584 /// Clamped to [`MAX_AGENT_PRUNE_DAYS`] so the cleanup task's
585 /// `now - Duration::days(n)` can never overflow `DateTime` (and panic
586 /// the task), even if a value larger than the PUT handler allows was
587 /// written to the KV out-of-band.
588 pub fn effective_agent_prune_days(&self) -> u32 {
589 self.agent_prune_days
590 .or(Self::defaults().agent_prune_days)
591 .unwrap_or(0)
592 .min(MAX_AGENT_PRUNE_DAYS)
593 }
594
595 /// The effective collect-bundle retention window in days: the stored
596 /// value if set, else the built-in default ([`DEFAULT_COLLECT_RETENTION_DAYS`]).
597 /// Floored at 1 and clamped to [`MAX_COLLECT_RETENTION_DAYS`] so an
598 /// out-of-band KV write can't reach the Object Store `max_age` unsanitised.
599 /// The floor matters specifically because NATS treats `max_age: 0` as
600 /// **unlimited** retention, not "evict immediately": a stray `0` would
601 /// silently make bundles never expire (defeating the auto-expire intent),
602 /// so we coerce it to the shortest real window (1 day) instead. The PUT
603 /// handler already rejects `0` / over-cap, so this is the belt-and-braces
604 /// path for a hand-edited KV value.
605 pub fn effective_collect_retention_days(&self) -> u32 {
606 self.collect_retention_days
607 .or(Self::defaults().collect_retention_days)
608 .unwrap_or(DEFAULT_COLLECT_RETENTION_DAYS)
609 .clamp(1, MAX_COLLECT_RETENTION_DAYS)
610 }
611
612 /// The effective `result_output` retention window in days: the stored
613 /// value if set, else the built-in default. Floored at 1 and clamped to
614 /// [`MAX_RESULT_OUTPUT_RETENTION_DAYS`] so a hand-written KV value can
615 /// neither disable retention outright nor outlive the stream it exists
616 /// to serve.
617 pub fn effective_result_output_retention_days(&self) -> u32 {
618 self.result_output_retention_days
619 .or(Self::defaults().result_output_retention_days)
620 .unwrap_or(DEFAULT_RESULT_OUTPUT_RETENTION_DAYS)
621 .clamp(1, MAX_RESULT_OUTPUT_RETENTION_DAYS)
622 }
623
624 /// The effective login-token lifetime in hours: the stored value if
625 /// set, else the built-in [`DEFAULT_SESSION_TTL_HOURS`]. Floored at 1
626 /// and clamped to [`MAX_SESSION_TTL_HOURS`] so a zero/absent/out-of-band
627 /// value can never mint an already-expired or overflow-inducing token.
628 /// The PUT handler already rejects `0` / over-cap, so this is the
629 /// belt-and-braces path for a hand-edited KV value.
630 pub fn effective_session_ttl_hours(&self) -> u32 {
631 self.session_ttl_hours
632 .or(Self::defaults().session_ttl_hours)
633 .unwrap_or(DEFAULT_SESSION_TTL_HOURS)
634 .clamp(1, MAX_SESSION_TTL_HOURS)
635 }
636
637 /// The effective check-staleness window in days: the stored value if set,
638 /// else the built-in [`DEFAULT_CHECK_STATUS_STALE_DAYS`]. **`0` means
639 /// disabled** (no row is ever hidden as stale) — deliberately NOT floored to
640 /// 1 (unlike collect/session), because 0 is a meaningful "show everything"
641 /// value here, the same convention as [`agent_prune_days`](Self::agent_prune_days).
642 /// Clamped to [`MAX_CHECK_STATUS_STALE_DAYS`] so an out-of-band KV write
643 /// can't overflow the `now - Duration::days(n)` cutoff math.
644 pub fn effective_check_status_stale_days(&self) -> u32 {
645 self.check_status_stale_days
646 .or(Self::defaults().check_status_stale_days)
647 .unwrap_or(DEFAULT_CHECK_STATUS_STALE_DAYS)
648 .min(MAX_CHECK_STATUS_STALE_DAYS)
649 }
650}
651
652#[cfg(test)]
653mod tests {
654 use super::*;
655
656 #[test]
657 fn default_is_unset() {
658 assert_eq!(ServerSettings::default().agent_prune_days, None);
659 }
660
661 #[test]
662 fn unset_resolves_to_disabled() {
663 // No stored value + no built-in default ⇒ effective 0 (disabled).
664 assert_eq!(ServerSettings::default().effective_agent_prune_days(), 0);
665 }
666
667 #[test]
668 fn stored_value_wins_over_default() {
669 let s = ServerSettings {
670 agent_prune_days: Some(30),
671 ..Default::default()
672 };
673 assert_eq!(s.effective_agent_prune_days(), 30);
674 }
675
676 #[test]
677 fn effective_clamps_to_max() {
678 // An out-of-band KV write larger than the PUT cap must not reach
679 // the cleanup task unclamped (else its DateTime subtraction panics).
680 let s = ServerSettings {
681 agent_prune_days: Some(u32::MAX),
682 ..Default::default()
683 };
684 assert_eq!(s.effective_agent_prune_days(), MAX_AGENT_PRUNE_DAYS);
685 }
686
687 #[test]
688 fn round_trips_through_json() {
689 let s = ServerSettings {
690 agent_prune_days: Some(30),
691 ..Default::default()
692 };
693 let json = serde_json::to_string(&s).unwrap();
694 assert_eq!(json, r#"{"agent_prune_days":30}"#);
695 let back: ServerSettings = serde_json::from_str(&json).unwrap();
696 assert_eq!(back, s);
697 }
698
699 #[test]
700 fn unset_serialises_to_empty_object() {
701 // `skip_serializing_if` keeps an all-unset doc minimal; it must
702 // round-trip back to all-`None`.
703 let s = ServerSettings::default();
704 let json = serde_json::to_string(&s).unwrap();
705 assert_eq!(json, "{}");
706 let back: ServerSettings = serde_json::from_str(&json).unwrap();
707 assert_eq!(back, s);
708 }
709
710 #[test]
711 fn explicit_null_decodes_to_unset() {
712 let s: ServerSettings = serde_json::from_str(r#"{"agent_prune_days":null}"#).unwrap();
713 assert_eq!(s.agent_prune_days, None);
714 }
715
716 #[test]
717 fn empty_object_decodes_to_default() {
718 // A freshly-created key (or one written by an older backend that
719 // didn't know this field) must read back as the pre-feature
720 // behaviour, not fail to decode.
721 let s: ServerSettings = serde_json::from_str("{}").unwrap();
722 assert_eq!(s, ServerSettings::default());
723 }
724
725 #[test]
726 fn controller_group_effective_trims_and_blank_is_unset() {
727 assert_eq!(ServerSettings::default().effective_controller_group(), None);
728 let s = ServerSettings {
729 controller_group: Some(" feed-runners ".into()),
730 ..Default::default()
731 };
732 assert_eq!(s.effective_controller_group(), Some("feed-runners"));
733 // A blank/whitespace value reads as unset (fail-safe: no runner).
734 let blank = ServerSettings {
735 controller_group: Some(" ".into()),
736 ..Default::default()
737 };
738 assert_eq!(blank.effective_controller_group(), None);
739 }
740
741 #[test]
742 fn controller_group_round_trips_and_omits_when_unset() {
743 let s = ServerSettings {
744 controller_group: Some("infra".into()),
745 ..Default::default()
746 };
747 let json = serde_json::to_string(&s).unwrap();
748 assert_eq!(json, r#"{"controller_group":"infra"}"#);
749 assert_eq!(serde_json::from_str::<ServerSettings>(&json).unwrap(), s);
750 // Unset controller_group is omitted (skip_serializing_if).
751 assert_eq!(
752 serde_json::to_string(&ServerSettings::default()).unwrap(),
753 "{}"
754 );
755 }
756
757 #[test]
758 fn mail_round_trips_and_omits_when_unset() {
759 use crate::config::{MailEncryption, MailSection};
760
761 // Unset mail is omitted (skip_serializing_if) — a mail-less doc
762 // stays minimal and decodes back to `None`.
763 assert_eq!(
764 serde_json::to_string(&ServerSettings::default()).unwrap(),
765 "{}"
766 );
767
768 let s = ServerSettings {
769 mail: Some(MailSection {
770 host: "smtp.example.com".into(),
771 port: 587,
772 encryption: MailEncryption::Starttls,
773 from: "kanade-noreply@example.com".into(),
774 username: Some("kanade-noreply".into()),
775 }),
776 ..Default::default()
777 };
778 let json = serde_json::to_string(&s).unwrap();
779 // Encryption serialises lowercase; the password is never present.
780 assert!(json.contains(r#""encryption":"starttls""#), "json: {json}");
781 assert!(!json.contains("password"), "password must never serialise");
782 assert_eq!(serde_json::from_str::<ServerSettings>(&json).unwrap(), s);
783 }
784
785 #[test]
786 fn mail_defaults_to_unset() {
787 assert_eq!(ServerSettings::default().mail, None);
788 // A doc written before this field existed (no `mail` key) decodes
789 // to `None` — email stays a no-op, the pre-feature behaviour.
790 let s: ServerSettings = serde_json::from_str(r#"{"agent_prune_days":7}"#).unwrap();
791 assert_eq!(s.mail, None);
792 assert_eq!(s.agent_prune_days, Some(7));
793 }
794
795 #[test]
796 fn collect_retention_unset_resolves_to_builtin_default() {
797 // Blank (the derived Default) must preserve the historical 30-day
798 // window, not disable retention.
799 assert_eq!(ServerSettings::default().collect_retention_days, None);
800 assert_eq!(
801 ServerSettings::default().effective_collect_retention_days(),
802 DEFAULT_COLLECT_RETENTION_DAYS,
803 );
804 // The defaults() document surfaces the real default so the SPA can
805 // render it as a placeholder.
806 assert_eq!(
807 ServerSettings::defaults().collect_retention_days,
808 Some(DEFAULT_COLLECT_RETENTION_DAYS),
809 );
810 }
811
812 #[test]
813 fn collect_retention_stored_value_wins() {
814 let s = ServerSettings {
815 collect_retention_days: Some(90),
816 ..Default::default()
817 };
818 assert_eq!(s.effective_collect_retention_days(), 90);
819 }
820
821 #[test]
822 fn collect_retention_effective_clamps_out_of_band_writes() {
823 // A hand-written KV value past the PUT cap (or 0) must be clamped so
824 // the reconciled Object Store max_age stays sane.
825 let big = ServerSettings {
826 collect_retention_days: Some(u32::MAX),
827 ..Default::default()
828 };
829 assert_eq!(
830 big.effective_collect_retention_days(),
831 MAX_COLLECT_RETENTION_DAYS,
832 );
833 let zero = ServerSettings {
834 collect_retention_days: Some(0),
835 ..Default::default()
836 };
837 assert_eq!(zero.effective_collect_retention_days(), 1);
838 }
839
840 #[test]
841 fn result_output_retention_defaults_to_a_week_not_the_old_month() {
842 // The built-in default IS the fix: existing buckets were born at 30
843 // days and reconcile down to this. If someone raises it back the
844 // bucket grows again, so the value is pinned rather than left to the
845 // constant's own definition.
846 assert_eq!(DEFAULT_RESULT_OUTPUT_RETENTION_DAYS, 7);
847 assert_eq!(
848 ServerSettings::default().effective_result_output_retention_days(),
849 7
850 );
851 }
852
853 #[test]
854 fn result_output_retention_is_capped_by_the_stream_it_serves() {
855 // Beyond STREAM_RESULTS' own window there is no message left to
856 // replay, so a longer object window keeps blobs nothing can ask for.
857 assert_eq!(MAX_RESULT_OUTPUT_RETENTION_DAYS, 30);
858 let big = ServerSettings {
859 result_output_retention_days: Some(u32::MAX),
860 ..Default::default()
861 };
862 assert_eq!(
863 big.effective_result_output_retention_days(),
864 MAX_RESULT_OUTPUT_RETENTION_DAYS
865 );
866 // …and 0 is floored rather than disabling retention, which would put
867 // the bucket straight back to unbounded growth.
868 let zero = ServerSettings {
869 result_output_retention_days: Some(0),
870 ..Default::default()
871 };
872 assert_eq!(zero.effective_result_output_retention_days(), 1);
873 }
874
875 #[test]
876 fn collect_retention_round_trips_and_omits_when_unset() {
877 let s = ServerSettings {
878 collect_retention_days: Some(90),
879 ..Default::default()
880 };
881 let json = serde_json::to_string(&s).unwrap();
882 assert_eq!(json, r#"{"collect_retention_days":90}"#);
883 assert_eq!(serde_json::from_str::<ServerSettings>(&json).unwrap(), s);
884 // Unset is omitted so a blank doc stays minimal.
885 assert!(
886 !serde_json::to_string(&ServerSettings::default())
887 .unwrap()
888 .contains("collect_retention_days")
889 );
890 }
891
892 #[test]
893 fn session_ttl_unset_resolves_to_builtin_default() {
894 // Blank (the derived Default) must resolve to the 24h default rather
895 // than 0 (which would mint already-expired tokens).
896 assert_eq!(ServerSettings::default().session_ttl_hours, None);
897 assert_eq!(
898 ServerSettings::default().effective_session_ttl_hours(),
899 DEFAULT_SESSION_TTL_HOURS,
900 );
901 // The defaults() document surfaces the real default so the SPA can
902 // render it as a placeholder.
903 assert_eq!(
904 ServerSettings::defaults().session_ttl_hours,
905 Some(DEFAULT_SESSION_TTL_HOURS),
906 );
907 }
908
909 #[test]
910 fn session_ttl_stored_value_wins() {
911 let s = ServerSettings {
912 session_ttl_hours: Some(72),
913 ..Default::default()
914 };
915 assert_eq!(s.effective_session_ttl_hours(), 72);
916 }
917
918 #[test]
919 fn session_ttl_effective_clamps_out_of_band_writes() {
920 // An out-of-band 0 must floor to 1 (else `now + 0h` is an
921 // instantly-expired token); a value past the cap clamps down so
922 // login's date math can't overflow.
923 let zero = ServerSettings {
924 session_ttl_hours: Some(0),
925 ..Default::default()
926 };
927 assert_eq!(zero.effective_session_ttl_hours(), 1);
928 let huge = ServerSettings {
929 session_ttl_hours: Some(u32::MAX),
930 ..Default::default()
931 };
932 assert_eq!(huge.effective_session_ttl_hours(), MAX_SESSION_TTL_HOURS);
933 }
934
935 #[test]
936 fn session_ttl_round_trips_and_omits_when_unset() {
937 let s = ServerSettings {
938 session_ttl_hours: Some(48),
939 ..Default::default()
940 };
941 let json = serde_json::to_string(&s).unwrap();
942 assert_eq!(json, r#"{"session_ttl_hours":48}"#);
943 assert_eq!(serde_json::from_str::<ServerSettings>(&json).unwrap(), s);
944 // Unset is omitted so a blank doc stays minimal.
945 assert!(
946 !serde_json::to_string(&ServerSettings::default())
947 .unwrap()
948 .contains("session_ttl_hours")
949 );
950 }
951
952 #[test]
953 fn check_stale_unset_resolves_to_builtin_default() {
954 // Blank (the derived Default) resolves to the 30-day default — ON out
955 // of the box, so the feature works without configuration.
956 assert_eq!(ServerSettings::default().check_status_stale_days, None);
957 assert_eq!(
958 ServerSettings::default().effective_check_status_stale_days(),
959 DEFAULT_CHECK_STATUS_STALE_DAYS,
960 );
961 // defaults() surfaces the real default for the SPA placeholder.
962 assert_eq!(
963 ServerSettings::defaults().check_status_stale_days,
964 Some(DEFAULT_CHECK_STATUS_STALE_DAYS),
965 );
966 }
967
968 #[test]
969 fn check_stale_zero_disables() {
970 // Explicit 0 means "disable staleness" (show everything) — NOT floored
971 // to 1 like collect/session; same convention as agent_prune_days.
972 let s = ServerSettings {
973 check_status_stale_days: Some(0),
974 ..Default::default()
975 };
976 assert_eq!(s.effective_check_status_stale_days(), 0);
977 }
978
979 #[test]
980 fn check_stale_stored_value_wins_and_clamps() {
981 let s = ServerSettings {
982 check_status_stale_days: Some(7),
983 ..Default::default()
984 };
985 assert_eq!(s.effective_check_status_stale_days(), 7);
986 let big = ServerSettings {
987 check_status_stale_days: Some(u32::MAX),
988 ..Default::default()
989 };
990 assert_eq!(
991 big.effective_check_status_stale_days(),
992 MAX_CHECK_STATUS_STALE_DAYS,
993 );
994 }
995
996 #[test]
997 fn check_stale_round_trips_and_omits_when_unset() {
998 let s = ServerSettings {
999 check_status_stale_days: Some(14),
1000 ..Default::default()
1001 };
1002 let json = serde_json::to_string(&s).unwrap();
1003 assert_eq!(json, r#"{"check_status_stale_days":14}"#);
1004 assert_eq!(serde_json::from_str::<ServerSettings>(&json).unwrap(), s);
1005 assert!(
1006 !serde_json::to_string(&ServerSettings::default())
1007 .unwrap()
1008 .contains("check_status_stale_days")
1009 );
1010 }
1011
1012 #[test]
1013 fn support_codes_absent_by_default_and_omitted_from_the_wire() {
1014 // The pre-feature document must round-trip byte-identically: no
1015 // `support_codes` key, so an older backend / agent reading it sees
1016 // exactly what it saw before, and nothing is unlockable.
1017 let s = ServerSettings::default();
1018 assert!(s.support_codes.is_empty());
1019 assert_eq!(serde_json::to_string(&s).unwrap(), "{}");
1020 assert!(s.support_code("support").is_none());
1021 }
1022
1023 #[test]
1024 fn support_code_lookup_fails_closed() {
1025 let s = ServerSettings {
1026 support_codes: vec![
1027 SupportCode {
1028 scope: "support".into(),
1029 hash: "$argon2id$v=19$m=19456,t=2,p=1$c2FsdA$aGFzaA".into(),
1030 label: Some("ヘルプデスク".into()),
1031 ..Default::default()
1032 },
1033 SupportCode {
1034 scope: "admin".into(),
1035 hash: "$argon2id$v=19$m=19456,t=2,p=1$c2FsdA$aGFzaA".into(),
1036 disabled: true,
1037 ..Default::default()
1038 },
1039 SupportCode {
1040 // Hash blanked — what an API-redacted document looks like.
1041 // It must never be treated as a live code.
1042 scope: "blank".into(),
1043 ..Default::default()
1044 },
1045 ],
1046 ..Default::default()
1047 };
1048 assert!(s.support_code("support").is_some());
1049 assert!(s.support_code("admin").is_none(), "disabled must not match");
1050 assert!(
1051 s.support_code("blank").is_none(),
1052 "blank hash must not match"
1053 );
1054 assert!(s.support_code("nope").is_none());
1055 }
1056
1057 #[test]
1058 fn redacted_blanks_hashes_but_keeps_the_roster() {
1059 // The SPA still needs to see WHICH scopes exist (to list / rotate /
1060 // delete them); it must never see the hash.
1061 let s = ServerSettings {
1062 support_codes: vec![SupportCode {
1063 scope: "support".into(),
1064 hash: "$argon2id$secret".into(),
1065 label: Some("ヘルプデスク".into()),
1066 ttl_minutes: Some(30),
1067 disabled: false,
1068 }],
1069 ..Default::default()
1070 };
1071 let json = serde_json::to_string(&s.redacted()).unwrap();
1072 assert!(!json.contains("argon2"), "wire leaked the hash: {json}");
1073 assert!(!json.contains("hash"), "wire leaked the hash key: {json}");
1074 assert!(json.contains("\"scope\":\"support\""), "wire: {json}");
1075 assert!(json.contains("\"ttl_minutes\":30"), "wire: {json}");
1076 }
1077
1078 #[test]
1079 fn support_code_ttl_clamps() {
1080 let unset = SupportCode::default();
1081 assert_eq!(
1082 unset.effective_ttl_minutes(),
1083 DEFAULT_SUPPORT_UNLOCK_TTL_MINUTES
1084 );
1085 // 0 would mint an already-expired grant (an unlock that silently
1086 // does nothing) — floored to the shortest real window instead.
1087 let zero = SupportCode {
1088 ttl_minutes: Some(0),
1089 ..Default::default()
1090 };
1091 assert_eq!(zero.effective_ttl_minutes(), 1);
1092 let huge = SupportCode {
1093 ttl_minutes: Some(u32::MAX),
1094 ..Default::default()
1095 };
1096 assert_eq!(huge.effective_ttl_minutes(), MAX_SUPPORT_UNLOCK_TTL_MINUTES);
1097 }
1098
1099 #[test]
1100 fn accepts_unknown_fields_for_forward_compat() {
1101 // A newer backend may have added knobs this build doesn't know;
1102 // decoding must drop them rather than error.
1103 let json = r#"{"agent_prune_days":7,"some_future_knob":true}"#;
1104 let s: ServerSettings = serde_json::from_str(json).unwrap();
1105 assert_eq!(s.agent_prune_days, Some(7));
1106 }
1107
1108 #[test]
1109 fn object_store_caps_unset_resolves_to_builtin_defaults() {
1110 // Blank doc ⇒ every bucket capped at its built-in default — the
1111 // out-of-box fix for uncapped / drifted buckets (#1247).
1112 let s = ServerSettings::default();
1113 assert_eq!(s.object_store_caps, None);
1114 let c = s.effective_object_store_caps();
1115 assert_eq!(c.result_output_mib, Some(DEFAULT_RESULT_OUTPUT_CAP_MIB));
1116 assert_eq!(c.agent_releases_mib, Some(DEFAULT_AGENT_RELEASES_CAP_MIB));
1117 assert_eq!(c.app_packages_mib, Some(DEFAULT_APP_PACKAGES_CAP_MIB));
1118 assert_eq!(c.scripts_mib, Some(DEFAULT_SCRIPTS_CAP_MIB));
1119 assert_eq!(c.collections_mib, Some(DEFAULT_COLLECTIONS_CAP_MIB));
1120 }
1121
1122 #[test]
1123 fn object_store_caps_partial_override_keeps_other_defaults() {
1124 let s = ServerSettings {
1125 object_store_caps: Some(ObjectStoreCaps {
1126 app_packages_mib: Some(8192),
1127 ..Default::default()
1128 }),
1129 ..Default::default()
1130 };
1131 let c = s.effective_object_store_caps();
1132 assert_eq!(c.app_packages_mib, Some(8192));
1133 assert_eq!(c.scripts_mib, Some(DEFAULT_SCRIPTS_CAP_MIB));
1134 }
1135
1136 #[test]
1137 fn object_store_caps_clamps_out_of_band_writes() {
1138 let s = ServerSettings {
1139 object_store_caps: Some(ObjectStoreCaps {
1140 result_output_mib: Some(0),
1141 app_packages_mib: Some(u32::MAX),
1142 ..Default::default()
1143 }),
1144 ..Default::default()
1145 };
1146 let c = s.effective_object_store_caps();
1147 // 0 floors to 1 MiB — NATS treats max_bytes: 0 as unlimited, the
1148 // exact failure mode this feature exists to remove.
1149 assert_eq!(c.result_output_mib, Some(1));
1150 assert_eq!(c.app_packages_mib, Some(MAX_OBJECT_STORE_CAP_MIB));
1151 }
1152
1153 #[test]
1154 fn object_store_caps_round_trips_and_omits_when_unset() {
1155 let s = ServerSettings {
1156 object_store_caps: Some(ObjectStoreCaps {
1157 scripts_mib: Some(512),
1158 ..Default::default()
1159 }),
1160 ..Default::default()
1161 };
1162 let json = serde_json::to_string(&s).unwrap();
1163 assert_eq!(json, r#"{"object_store_caps":{"scripts_mib":512}}"#);
1164 assert_eq!(serde_json::from_str::<ServerSettings>(&json).unwrap(), s);
1165 assert!(
1166 !serde_json::to_string(&ServerSettings::default())
1167 .unwrap()
1168 .contains("object_store_caps")
1169 );
1170 }
1171
1172 #[test]
1173 fn agent_install_defaults_to_unset_and_omits_when_unset() {
1174 assert_eq!(ServerSettings::default().agent_install, None);
1175 assert_eq!(ServerSettings::defaults().agent_install, None);
1176 // A doc written before this field existed decodes to `None` — the
1177 // installer then falls back to the backend's own [nats] url, the
1178 // pre-feature behaviour.
1179 let s: ServerSettings = serde_json::from_str(r#"{"agent_prune_days":7}"#).unwrap();
1180 assert_eq!(s.agent_install, None);
1181 assert!(
1182 !serde_json::to_string(&ServerSettings::default())
1183 .unwrap()
1184 .contains("agent_install")
1185 );
1186 }
1187
1188 #[test]
1189 fn agent_install_round_trips() {
1190 let s = ServerSettings {
1191 agent_install: Some(AgentInstallSection {
1192 nats_url: Some("nats://broker.corp:4222".into()),
1193 nats_token: Some("s3cret".into()),
1194 nats_token_set: false,
1195 }),
1196 ..Default::default()
1197 };
1198 let json = serde_json::to_string(&s).unwrap();
1199 assert_eq!(
1200 json,
1201 r#"{"agent_install":{"nats_url":"nats://broker.corp:4222","nats_token":"s3cret","nats_token_set":false}}"#
1202 );
1203 assert_eq!(serde_json::from_str::<ServerSettings>(&json).unwrap(), s);
1204 }
1205
1206 #[test]
1207 fn agent_install_token_set_is_never_accepted_from_the_wire() {
1208 // `skip_deserializing`: a client sending nats_token_set gets it
1209 // dropped, so the indicator can only ever come from redacted()
1210 // looking at the real stored token — never from a claim.
1211 let s: ServerSettings = serde_json::from_str(
1212 r#"{"agent_install":{"nats_url":"nats://b:4222","nats_token_set":true}}"#,
1213 )
1214 .unwrap();
1215 let ai = s.agent_install.unwrap();
1216 assert!(!ai.nats_token_set);
1217 assert_eq!(ai.nats_url.as_deref(), Some("nats://b:4222"));
1218 }
1219
1220 #[test]
1221 fn redacted_strips_the_install_token_but_reports_its_presence() {
1222 // GET /api/server-settings is viewer+, so the stored NATS token must
1223 // never survive redacted() — not even to an operator. The boolean is
1224 // all the SPA gets to render "configured".
1225 let with_token = ServerSettings {
1226 agent_install: Some(AgentInstallSection {
1227 nats_url: Some("nats://broker.corp:4222".into()),
1228 nats_token: Some("s3cret".into()),
1229 nats_token_set: false,
1230 }),
1231 ..Default::default()
1232 };
1233 let redacted = with_token.redacted();
1234 let ai = redacted.agent_install.as_ref().unwrap();
1235 assert_eq!(ai.nats_token, None, "token must not survive redacted()");
1236 assert!(ai.nats_token_set);
1237 // The URL is not a secret — it stays.
1238 assert_eq!(ai.nats_url.as_deref(), Some("nats://broker.corp:4222"));
1239 // And on the wire the token key is gone entirely (not null).
1240 let json = serde_json::to_string(&redacted).unwrap();
1241 assert!(!json.contains("s3cret"), "wire leaked the token: {json}");
1242 assert!(!json.contains("nats_token\""), "wire: {json}");
1243 assert!(json.contains(r#""nats_token_set":true"#), "wire: {json}");
1244
1245 // No token configured → indicator false, nothing to strip.
1246 let sans_token = ServerSettings {
1247 agent_install: Some(AgentInstallSection {
1248 nats_url: Some("nats://broker.corp:4222".into()),
1249 ..Default::default()
1250 }),
1251 ..Default::default()
1252 }
1253 .redacted();
1254 let ai = sans_token.agent_install.as_ref().unwrap();
1255 assert!(!ai.nats_token_set);
1256 }
1257}