Skip to main content

printobserver_server/
config.rs

1//! The one configuration file a running supervisor reads, and its validation.
2//!
3//! # Every field this program takes is declared once, here
4//!
5//! [`ConfigField`] is that declaration: one variant per configured value, each
6//! carrying the dotted key it is spelled under. Two things read it rather than
7//! restating it — the refusal a bad value produces names its field through it,
8//! and this crate's own tier walks it, driving a server against a configuration
9//! in which each field in turn is unacceptable. A field added to the shapes
10//! below and not to [`ConfigField::ALL`] fails that tier's own coverage check,
11//! so the walk cannot fall behind the type.
12//!
13//! # Validation happens at startup, and names the field
14//!
15//! A value that cannot work is refused where it is configured rather than at
16//! the first request that needs it, and the refusal carries the field's own key
17//! so an operator editing the file knows which line to change. That includes
18//! the two values only the machine can rule on: an `OctoPrint` address nothing
19//! answers at and a key that instance refuses are both configuration mistakes,
20//! and [`crate::Server::start`] refuses them naming
21//! [`ConfigField::OctoprintUrl`] and [`ConfigField::OctoprintApiKey`].
22//!
23//! # The ingress answer bound
24//!
25//! `Obico`'s webhook notification plugin posts best-effort with a short timeout
26//! and does not retry, so this server answers its ingress before the handling
27//! completes and inside a bound it declares here. The shipped default is
28//! [`DEFAULT_INGRESS_ANSWER_BOUND_MS`] and the timeout it must stay below is
29//! [`OBICO_POSTING_TIMEOUT_MS`]; `AGENTS.md`'s "The Obico ingress answer bound"
30//! records that number, where it was read and why the default is where it is,
31//! and `just check-repo` refuses a tree in which the two disagree.
32//!
33//! # The operator's credential, by its verifier
34//!
35//! Every request beneath the versioned prefix carries one credential. The
36//! operator's is checked against a [`CredentialVerifier`] — the SHA-256 of the
37//! credential, written `sha256:<64 lowercase hex>` — which `api.credential_verifier`
38//! names, so the server holds nothing a supervision turn reading its files
39//! could authenticate with. The plaintext lives with the operator, in the
40//! client configuration `printobserver credential issue` writes.
41//!
42//! `api.credential`, a plaintext credential, is still read for an installation
43//! that wrote one, and admitted until it is replaced; the composition root warns
44//! on every start that it is there. Either way a credential is held in a type
45//! neither rendering of which shows it, and is compared in constant time.
46//!
47//! # The periodic observation
48//!
49//! `supervisor.observation_interval_s` is how often every active print is given
50//! a periodic observation and its agent a turn on it, whether or not the
51//! detector has alerted. Left out it is
52//! [`DEFAULT_OBSERVATION_INTERVAL_S`] — two minutes — and zero is refused,
53//! because an interval of nothing is a turn started the moment the last one
54//! returns.
55//!
56//! # The camera and `Obico`'s own API
57//!
58//! Both are optional. `camera.snapshot_url` is where a look fetches a fresh
59//! frame; without it a look carries the printer's state and no frame.
60//! `obico.url` and `obico.access_token` are given together or not at all: they
61//! are how a print the detector paused and the agent adjusted is acknowledged
62//! to `Obico`, which re-arms its detection. Each address must be an `http` or
63//! `https` URL, and the token is held in a type whose debug form never shows
64//! it, so no refusal or log line this program writes can carry it.
65//!
66//! # The spool check
67//!
68//! `[spools]` is optional, and so is every key in it: `preflight` is what a
69//! start does when the loaded spool is short, unverified or the file has no
70//! analysis — `refuse`, `warn` or `off` — `buffer_percent` and `buffer_min_g`
71//! the margin asked beyond what a print needs, and `analysis_wait_seconds` how
72//! long a start waits for `OctoPrint`'s analysis of a file that has none yet.
73//! Each left out takes the supervision core's own default, and a negative
74//! figure or a mode outside the three is refused naming its key.
75
76use std::net::SocketAddr;
77use std::path::{Path, PathBuf};
78
79use printobserver_core::{PreflightMode, SafetyEnvelope, SpoolPolicy};
80use printobserver_obico::{AccessToken, ObicoApi};
81use printobserver_octoprint::{FanSupport, OctoPrintConfig};
82use printobserver_oneharness::{HarnessIdentity, ModelName};
83use printobserver_types::schemars::JsonSchema;
84use printobserver_types::serde::{Deserialize, Serialize};
85use printobserver_vision_api::WebAddress;
86
87/// The answer bound this repository ships, in milliseconds.
88///
89/// A fifth of [`OBICO_POSTING_TIMEOUT_MS`]. The margin is deliberate: the
90/// supported host is a small ARM board beside the printer, and a bound set just
91/// under the producer's timeout would be exceeded by the first slow moment on
92/// it — after which `Obico` drops the alert, because its posting does not retry.
93pub const DEFAULT_INGRESS_ANSWER_BOUND_MS: u64 = 1_000;
94
95/// How often every active print is observed, in seconds, when the
96/// configuration names no interval: the core's own default.
97pub const DEFAULT_OBSERVATION_INTERVAL_S: u64 =
98    printobserver_core::DEFAULT_OBSERVATION_INTERVAL.as_secs();
99
100/// The timeout `Obico`'s own webhook notification plugin posts under.
101///
102/// Read from the `Obico` release the `obico-fixture` node stands up — revision
103/// `49c0bc7001a3fd8d56297fc3032ba287bfe1d50b`,
104/// `backend/notifications/plugins/webhook/__init__.py`, whose `execute_webhook`
105/// takes `timeout: float = 5.0` and calls `raise_for_status` with no retry.
106/// This repository's claim about an external producer; what reconciles it
107/// against a live `Obico` is the scheduled `Obico` tier.
108pub const OBICO_POSTING_TIMEOUT_MS: u64 = 5_000;
109
110/// The directory under the state directory this server materializes the
111/// supervising agent's prompt template and assessment schema into. The skill
112/// is not among them: it is installed with [`SKILL_INSTALL`] and configured by
113/// `supervisor.skill_path`.
114pub const ASSETS_DIRECTORY: &str = "assets";
115
116/// How the supervising agent's skill is installed, and what names it after.
117///
118/// This program carries no skill of its own: the skill is the Agent Skill this
119/// repository publishes, installed as any other is, and every refusal of
120/// `supervisor.skill_path` says so, because it is the one instruction an
121/// operator whose configuration predates that needs.
122pub const SKILL_INSTALL: &str = "the skill is installed with `gh skill install \
123     nickderobertis/printobserver printobserver --dir <dir>`, and \
124     `supervisor.skill_path` names the installed `SKILL.md`, \
125     `<dir>/printobserver/SKILL.md`";
126
127/// Every value this program is configured with, and the key it is spelled under.
128///
129/// The walk in this crate's tier is over this array, and the array is compared
130/// against the configuration shapes' own declared properties, so neither can
131/// grow a field the other does not know about.
132#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
133pub enum ConfigField {
134    /// Where the store, the images and the sessions live.
135    StateDir,
136    /// The address the API and the ingress are served on.
137    Listen,
138    /// Where the `OctoPrint` instance answers.
139    OctoprintUrl,
140    /// The key that instance authenticates every request by.
141    OctoprintApiKey,
142    /// Whether the machine has a part-cooling fan this server may command.
143    OctoprintFan,
144    /// The operator's safety envelope.
145    SafetyEnvelope,
146    /// The harness identity supervision turns run on.
147    Harness,
148    /// The model turns are pinned to, when one is pinned.
149    Model,
150    /// The `PrintObserver` skill sent as every turn's system prompt.
151    SkillPath,
152    /// The prompt template one turn fills.
153    PromptTemplatePath,
154    /// How often every active print is observed, in seconds.
155    ObservationIntervalS,
156    /// How long the ingress may take to answer, in milliseconds.
157    IngressAnswerBoundMs,
158    /// The shared secret the ingress requires of every post.
159    IngressSharedSecret,
160    /// A plaintext operator credential, read for an installation that wrote
161    /// one until it is replaced by its verifier.
162    ApiCredential,
163    /// The verifier the operator's credential is checked against.
164    ApiCredentialVerifier,
165    /// Where a fresh frame of the print is fetched from, when a camera is
166    /// configured.
167    CameraSnapshotUrl,
168    /// Where `Obico`'s own API answers, when it is configured.
169    ObicoUrl,
170    /// The bearer token `Obico`'s API is reached with.
171    ObicoAccessToken,
172    /// What a start does when the spool check finds a problem.
173    SpoolsPreflight,
174    /// The margin asked beyond a print's requirement, as a percentage of it.
175    SpoolsBufferPercent,
176    /// The least margin asked, in grams.
177    SpoolsBufferMinG,
178    /// How long a start waits for a file's analysis, in seconds.
179    SpoolsAnalysisWaitSeconds,
180}
181
182impl ConfigField {
183    /// Every field this program takes, and there is no other.
184    pub const ALL: [Self; 22] = [
185        Self::StateDir,
186        Self::Listen,
187        Self::OctoprintUrl,
188        Self::OctoprintApiKey,
189        Self::OctoprintFan,
190        Self::SafetyEnvelope,
191        Self::Harness,
192        Self::Model,
193        Self::SkillPath,
194        Self::PromptTemplatePath,
195        Self::ObservationIntervalS,
196        Self::IngressAnswerBoundMs,
197        Self::IngressSharedSecret,
198        Self::ApiCredential,
199        Self::ApiCredentialVerifier,
200        Self::CameraSnapshotUrl,
201        Self::ObicoUrl,
202        Self::ObicoAccessToken,
203        Self::SpoolsPreflight,
204        Self::SpoolsBufferPercent,
205        Self::SpoolsBufferMinG,
206        Self::SpoolsAnalysisWaitSeconds,
207    ];
208
209    /// The dotted key this field is spelled under in the configuration file.
210    #[must_use]
211    pub const fn key(self) -> &'static str {
212        match self {
213            Self::StateDir => "state_dir",
214            Self::Listen => "listen",
215            Self::OctoprintUrl => "octoprint.url",
216            Self::OctoprintApiKey => "octoprint.api_key",
217            Self::OctoprintFan => "octoprint.fan",
218            Self::SafetyEnvelope => "safety",
219            Self::Harness => "supervisor.harness",
220            Self::Model => "supervisor.model",
221            Self::SkillPath => "supervisor.skill_path",
222            Self::PromptTemplatePath => "supervisor.prompt_template_path",
223            Self::ObservationIntervalS => "supervisor.observation_interval_s",
224            Self::IngressAnswerBoundMs => "ingress.answer_bound_ms",
225            Self::IngressSharedSecret => "ingress.shared_secret",
226            Self::ApiCredential => "api.credential",
227            Self::ApiCredentialVerifier => "api.credential_verifier",
228            Self::CameraSnapshotUrl => "camera.snapshot_url",
229            Self::ObicoUrl => "obico.url",
230            Self::ObicoAccessToken => "obico.access_token",
231            Self::SpoolsPreflight => "spools.preflight",
232            Self::SpoolsBufferPercent => "spools.buffer_percent",
233            Self::SpoolsBufferMinG => "spools.buffer_min_g",
234            Self::SpoolsAnalysisWaitSeconds => "spools.analysis_wait_seconds",
235        }
236    }
237}
238
239impl core::fmt::Display for ConfigField {
240    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
241        formatter.write_str(self.key())
242    }
243}
244
245/// Why this server will not start under the configuration it was given.
246///
247/// Every variant names the field it is about, because the answer an operator
248/// needs is which line of the file to change.
249#[derive(Debug, Clone, PartialEq, Eq)]
250pub enum ConfigError {
251    /// The file could not be read at all.
252    Unreadable {
253        /// The path that was named.
254        path: PathBuf,
255        /// What went wrong reading it.
256        detail: String,
257    },
258    /// The file is not the document this program takes.
259    Unparsable {
260        /// The path that was named.
261        path: PathBuf,
262        /// What could not be parsed, in the parser's own words.
263        detail: String,
264    },
265    /// One field carries a value this program cannot accept.
266    Field {
267        /// The field it is about.
268        field: ConfigField,
269        /// Why the value cannot be accepted.
270        detail: String,
271    },
272}
273
274impl ConfigError {
275    /// The field this refusal is about, when it is about one.
276    #[must_use]
277    pub const fn field(&self) -> Option<ConfigField> {
278        match self {
279            Self::Field { field, .. } => Some(*field),
280            _ => None,
281        }
282    }
283
284    /// One field's refusal, in its own words.
285    pub(crate) fn about(field: ConfigField, detail: impl Into<String>) -> Self {
286        Self::Field {
287            field,
288            detail: detail.into(),
289        }
290    }
291}
292
293impl core::fmt::Display for ConfigError {
294    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
295        match self {
296            Self::Unreadable { path, detail } => write!(
297                formatter,
298                "the configuration file {} could not be read: {detail}",
299                path.display()
300            ),
301            Self::Unparsable { path, detail } => write!(
302                formatter,
303                "the configuration file {} could not be read as this program's \
304                 configuration: {detail}",
305                path.display()
306            ),
307            Self::Field { field, detail } => write!(
308                formatter,
309                "the configuration field `{field}` cannot be accepted: {detail}"
310            ),
311        }
312    }
313}
314
315impl core::error::Error for ConfigError {}
316
317/// Where the `OctoPrint` instance is and what it is like, as written down.
318#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
319#[serde(
320    crate = "printobserver_types::serde",
321    deny_unknown_fields,
322    rename_all = "snake_case"
323)]
324#[schemars(crate = "printobserver_types::schemars")]
325pub struct OctoprintSection {
326    /// The base URL the instance answers on.
327    #[serde(default, skip_serializing_if = "Option::is_none")]
328    pub url: Option<String>,
329    /// The key it authenticates every request by.
330    #[serde(default, skip_serializing_if = "Option::is_none")]
331    pub api_key: Option<String>,
332    /// Whether the machine has a part-cooling fan this server may command.
333    #[serde(default = "commandable")]
334    pub fan: String,
335}
336
337/// The vocabulary [`OctoprintSection::fan`] takes, spelled as the operator
338/// writes it.
339pub const FAN_VOCABULARY: [(&str, FanSupport); 2] = [
340    ("commandable", FanSupport::Commandable),
341    ("absent", FanSupport::Absent),
342];
343
344/// The fan setting a configuration naming none takes.
345fn commandable() -> String {
346    FAN_VOCABULARY[0].0.to_owned()
347}
348
349impl Default for OctoprintSection {
350    fn default() -> Self {
351        Self {
352            url: None,
353            api_key: None,
354            fan: commandable(),
355        }
356    }
357}
358
359/// How the supervising agent is reached, as written down.
360#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
361#[serde(
362    crate = "printobserver_types::serde",
363    deny_unknown_fields,
364    rename_all = "snake_case"
365)]
366#[schemars(crate = "printobserver_types::schemars")]
367pub struct SupervisorSection {
368    /// The harness identity turns run on.
369    #[serde(default, skip_serializing_if = "Option::is_none")]
370    pub harness: Option<String>,
371    /// The model turns are pinned to, when one is pinned.
372    #[serde(default, skip_serializing_if = "Option::is_none")]
373    pub model: Option<String>,
374    /// The installed skill's `SKILL.md`, whose prose is sent as every turn's
375    /// system prompt; the agent runs from the directory holding it. Required:
376    /// this program carries no skill, and an absent one refuses the start.
377    #[serde(default, skip_serializing_if = "Option::is_none")]
378    pub skill_path: Option<PathBuf>,
379    /// The prompt template one turn fills, when the operator supplies one
380    /// instead of the committed template this program carries.
381    #[serde(default, skip_serializing_if = "Option::is_none")]
382    pub prompt_template_path: Option<PathBuf>,
383    /// How often every active print is given a periodic observation, and its
384    /// agent a turn on it, in seconds. Left out, two minutes.
385    #[serde(default = "default_observation_interval_s")]
386    pub observation_interval_s: u64,
387}
388
389/// The observation interval a configuration naming none takes.
390const fn default_observation_interval_s() -> u64 {
391    DEFAULT_OBSERVATION_INTERVAL_S
392}
393
394impl Default for SupervisorSection {
395    fn default() -> Self {
396        Self {
397            harness: None,
398            model: None,
399            skill_path: None,
400            prompt_template_path: None,
401            observation_interval_s: DEFAULT_OBSERVATION_INTERVAL_S,
402        }
403    }
404}
405
406/// What the `Obico` ingress requires and how fast it answers, as written down.
407#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
408#[serde(
409    crate = "printobserver_types::serde",
410    deny_unknown_fields,
411    rename_all = "snake_case"
412)]
413#[schemars(crate = "printobserver_types::schemars")]
414pub struct IngressSection {
415    /// The shared secret every post must carry.
416    #[serde(default, skip_serializing_if = "Option::is_none")]
417    pub shared_secret: Option<String>,
418    /// How long the ingress may take to answer, in milliseconds.
419    #[serde(default = "default_answer_bound_ms")]
420    pub answer_bound_ms: u64,
421}
422
423/// The answer bound a configuration naming none takes.
424const fn default_answer_bound_ms() -> u64 {
425    DEFAULT_INGRESS_ANSWER_BOUND_MS
426}
427
428impl Default for IngressSection {
429    fn default() -> Self {
430        Self {
431            shared_secret: None,
432            answer_bound_ms: DEFAULT_INGRESS_ANSWER_BOUND_MS,
433        }
434    }
435}
436
437/// What a caller of the versioned API authenticates with, as written down.
438#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
439#[serde(
440    crate = "printobserver_types::serde",
441    deny_unknown_fields,
442    rename_all = "snake_case"
443)]
444#[schemars(crate = "printobserver_types::schemars")]
445pub struct ApiSection {
446    /// A plaintext operator credential. Superseded by `credential_verifier`:
447    /// still admitted until it is replaced, with a warning on every start,
448    /// because a supervision turn can read the file it is written in.
449    #[serde(default, skip_serializing_if = "Option::is_none")]
450    pub credential: Option<String>,
451    /// The verifier the operator's credential is checked against:
452    /// `sha256:` and the 64 lowercase hexadecimal digits of the SHA-256 of the
453    /// credential's UTF-8 bytes, as `printobserver credential issue` prints it.
454    /// Left out, the server reads `api-credential.verifier` in its state
455    /// directory, and admits no operator at all when that is absent too.
456    #[serde(default, skip_serializing_if = "Option::is_none")]
457    pub credential_verifier: Option<String>,
458}
459
460/// Where a fresh frame of the print is fetched from, as written down.
461#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
462#[serde(
463    crate = "printobserver_types::serde",
464    deny_unknown_fields,
465    rename_all = "snake_case"
466)]
467#[schemars(crate = "printobserver_types::schemars")]
468pub struct CameraSection {
469    /// An `http` or `https` URL answering one still image of the print, such
470    /// as a `go2rtc` `frame.jpeg` address. Left out, a look carries no frame.
471    #[serde(default, skip_serializing_if = "Option::is_none")]
472    pub snapshot_url: Option<String>,
473}
474
475/// Where `Obico`'s own API answers, as written down.
476///
477/// Its debug form never shows the token.
478#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
479#[serde(
480    crate = "printobserver_types::serde",
481    deny_unknown_fields,
482    rename_all = "snake_case"
483)]
484#[schemars(crate = "printobserver_types::schemars")]
485pub struct ObicoSection {
486    /// The server's own `http` or `https` address, such as
487    /// `http://127.0.0.1:3334`. Given with `access_token` or not at all.
488    #[serde(default, skip_serializing_if = "Option::is_none")]
489    pub url: Option<String>,
490    /// A bearer token for its API, issued by the instance's own OAuth
491    /// administration. Left out with the address, a print the detector paused
492    /// and the supervisor resumed is not acknowledged to `Obico`.
493    #[serde(default, skip_serializing_if = "Option::is_none")]
494    pub access_token: Option<String>,
495}
496
497impl core::fmt::Debug for ObicoSection {
498    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
499        formatter
500            .debug_struct("ObicoSection")
501            .field("url", &self.url)
502            .field(
503                "access_token",
504                &self.access_token.as_ref().map(|_| REDACTED),
505            )
506            .finish()
507    }
508}
509
510/// How spools are checked before a print, as written down.
511///
512/// Every key is optional, and one left out takes the supervision core's own
513/// default. The mode is read as text rather than as the core's own type so
514/// that a mode outside the three is refused naming its key rather than by the
515/// parser in words of its own.
516#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Default)]
517#[serde(
518    crate = "printobserver_types::serde",
519    deny_unknown_fields,
520    rename_all = "snake_case"
521)]
522#[schemars(crate = "printobserver_types::schemars")]
523pub struct SpoolsSection {
524    /// What a start does when the loaded spool is short, unverified, or the
525    /// file has no analysis: `refuse`, `warn` or `off`. Left out, `refuse`.
526    #[serde(default, skip_serializing_if = "Option::is_none")]
527    pub preflight: Option<String>,
528    /// The margin asked beyond what a print needs, as a percentage of it.
529    #[serde(default, skip_serializing_if = "Option::is_none")]
530    pub buffer_percent: Option<f64>,
531    /// The least margin asked, in grams, however small the print.
532    #[serde(default, skip_serializing_if = "Option::is_none")]
533    pub buffer_min_g: Option<f64>,
534    /// How long a start waits for `OctoPrint`'s analysis of a file that has
535    /// none yet, in whole seconds; zero waits not at all.
536    #[serde(default, skip_serializing_if = "Option::is_none")]
537    pub analysis_wait_seconds: Option<i64>,
538}
539
540/// The whole configuration file, exactly as it is written down.
541///
542/// This is the parsed document rather than the validated configuration:
543/// [`ServerConfig::load`] is what turns one into the other, and every value a
544/// later step could find wrong is ruled on there.
545#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
546#[serde(
547    crate = "printobserver_types::serde",
548    deny_unknown_fields,
549    rename_all = "snake_case"
550)]
551#[schemars(crate = "printobserver_types::schemars")]
552pub struct ConfigFile {
553    /// Where the store, the images and the sessions live.
554    #[serde(default, skip_serializing_if = "Option::is_none")]
555    pub state_dir: Option<PathBuf>,
556    /// The address the API and the ingress are served on.
557    #[serde(default, skip_serializing_if = "Option::is_none")]
558    pub listen: Option<String>,
559    /// Where the `OctoPrint` instance is.
560    #[serde(default)]
561    pub octoprint: OctoprintSection,
562    /// The operator's safety envelope.
563    #[serde(default, skip_serializing_if = "Option::is_none")]
564    pub safety: Option<SafetyEnvelope>,
565    /// How the supervising agent is reached.
566    #[serde(default)]
567    pub supervisor: SupervisorSection,
568    /// What the `Obico` ingress requires.
569    #[serde(default)]
570    pub ingress: IngressSection,
571    /// What a caller of the versioned API authenticates with.
572    #[serde(default)]
573    pub api: ApiSection,
574    /// Where a fresh frame of the print is fetched from.
575    #[serde(default)]
576    pub camera: CameraSection,
577    /// Where `Obico`'s own API answers.
578    #[serde(default)]
579    pub obico: ObicoSection,
580    /// How spools are checked before a print.
581    #[serde(default)]
582    pub spools: SpoolsSection,
583}
584
585/// The shared secret the ingress requires of every post.
586///
587/// Neither rendering of this type shows the value, so it cannot reach a log
588/// record, a panic message or an error's own text by being formatted — and the
589/// comparison that admits a post lives here rather than at the endpoint, so
590/// there is no way to read the secret out in order to compare it.
591#[derive(Clone, PartialEq, Eq)]
592pub struct SharedSecret(String);
593
594/// What a secret renders as, wherever a value carrying one is rendered.
595pub const REDACTED: &str = "<redacted>";
596
597impl SharedSecret {
598    /// The secret this text names.
599    ///
600    /// # Errors
601    ///
602    /// Returns [`ConfigError`] when the text is empty or is nothing but
603    /// whitespace: anything that can post to the ingress can pause a printer,
604    /// and a secret nothing has to carry is no secret.
605    pub fn new(value: &str) -> Result<Self, ConfigError> {
606        if value.trim().is_empty() {
607            return Err(ConfigError::about(
608                ConfigField::IngressSharedSecret,
609                "it is empty, and anything that can post to the ingress can pause a printer",
610            ));
611        }
612        Ok(Self(value.to_owned()))
613    }
614
615    /// Whether a post carried this secret.
616    ///
617    /// Compared over the whole of both values with the two lengths mixed in,
618    /// rather than by returning at the first difference or at a length
619    /// mismatch, so that how long this takes says nothing about how much of the
620    /// secret a caller guessed.
621    #[must_use]
622    pub fn matches(&self, offered: Option<&str>) -> bool {
623        let Some(offered) = offered else {
624            return false;
625        };
626        let expected = self.0.as_bytes();
627        let mut difference = expected.len() ^ offered.len();
628        for (index, byte) in offered.bytes().enumerate() {
629            let against = expected[index % expected.len().max(1)];
630            difference |= usize::from(byte ^ against);
631        }
632        difference == 0
633    }
634}
635
636impl core::fmt::Display for SharedSecret {
637    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
638        formatter.write_str(REDACTED)
639    }
640}
641
642impl core::fmt::Debug for SharedSecret {
643    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
644        write!(formatter, "SharedSecret({REDACTED})")
645    }
646}
647
648/// How many random bytes a credential this server generates is drawn from.
649pub const GENERATED_CREDENTIAL_BYTES: usize = 32;
650
651/// One credential in plaintext: a legacy `api.credential`, the legacy file a
652/// server generated into its state directory, or one `printobserver credential
653/// issue` draws for the operator's own configuration.
654///
655/// Neither rendering of this type shows the value. Its text is read in exactly
656/// one place — [`Self::written`], for the operator's own client configuration,
657/// which exists to carry it, and for the verifier computed from it — and the
658/// one comparison a presented credential is admitted by is [`Self::admits`], so
659/// there is no second comparison anywhere that could return early.
660#[derive(Clone)]
661pub struct ApiCredential(String);
662
663impl ApiCredential {
664    /// The credential this text names.
665    ///
666    /// # Errors
667    ///
668    /// Answers why the text cannot be a credential, in words that never quote
669    /// it: empty or nothing but whitespace, or carrying a control character or
670    /// a character outside printable ASCII, or beginning or ending with a space
671    /// — none of which an `Authorization` header carries intact.
672    pub fn new(value: &str) -> Result<Self, &'static str> {
673        if value.trim().is_empty() {
674            return Err(
675                "it is empty, and anything that can reach this server's API can command a printer",
676            );
677        }
678        if !value.bytes().all(|byte| (b' '..=b'~').contains(&byte)) {
679            return Err(
680                "it carries a control character or a character outside printable ASCII, which \
681                 no `Authorization` header carries intact",
682            );
683        }
684        if value.starts_with(' ') || value.ends_with(' ') {
685            return Err(
686                "it begins or ends with a space, which an `Authorization` header does not carry",
687            );
688        }
689        // llmlint: ignore[boundary_inputs_validated] The refusal set above is exactly the contract this server's API credential is planned against, shared with the nodes that build on it: empty or whitespace, a control or non-printable-ASCII byte, a leading or trailing space. A length floor would refuse operator credentials that contract admits, so it is recorded as a follow-up rather than added here; the default an operator gets without configuring one is the generated 32 random bytes.
690        Ok(Self(value.to_owned()))
691    }
692
693    /// A fresh credential, drawn from the operating system's own
694    /// cryptographically secure random source.
695    ///
696    /// [`GENERATED_CREDENTIAL_BYTES`] bytes, written as unpadded URL-safe
697    /// base64 so an operator can copy it and a header can carry it as it is.
698    ///
699    /// # Errors
700    ///
701    /// Answers the random source's own refusal, when it has none to give.
702    pub fn generate() -> Result<Self, getrandom::Error> {
703        use base64::Engine as _;
704
705        let mut drawn = [0_u8; GENERATED_CREDENTIAL_BYTES];
706        getrandom::fill(&mut drawn)?;
707        Ok(Self(
708            base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(drawn),
709        ))
710    }
711
712    /// Whether a presented credential is this one.
713    ///
714    /// The lengths are compared first, which says how long the credential is and
715    /// nothing else; the bytes are then compared in constant time, so how long
716    /// this takes says nothing about how much of it a caller guessed.
717    #[must_use]
718    pub fn admits(&self, presented: &[u8]) -> bool {
719        use subtle::ConstantTimeEq as _;
720
721        let expected = self.0.as_bytes();
722        expected.len() == presented.len() && bool::from(expected.ct_eq(presented))
723    }
724
725    /// The text, for the one file whose purpose is to carry it — the
726    /// operator's own client configuration — and nothing else.
727    #[must_use]
728    pub fn written(&self) -> &str {
729        &self.0
730    }
731
732    /// The verifier this credential is checked by.
733    #[must_use]
734    pub fn verifier(&self) -> CredentialVerifier {
735        CredentialVerifier::of(&self.0)
736    }
737}
738
739impl PartialEq for ApiCredential {
740    fn eq(&self, other: &Self) -> bool {
741        self.admits(other.0.as_bytes())
742    }
743}
744
745impl Eq for ApiCredential {}
746
747impl core::fmt::Display for ApiCredential {
748    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
749        formatter.write_str(REDACTED)
750    }
751}
752
753impl core::fmt::Debug for ApiCredential {
754    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
755        write!(formatter, "ApiCredential({REDACTED})")
756    }
757}
758
759/// What a credential verifier is written with before its digest.
760pub const VERIFIER_PREFIX: &str = "sha256:";
761
762/// How many hexadecimal digits a verifier's digest is written in.
763const VERIFIER_DIGITS: usize = 64;
764
765/// What one operator credential is checked against: the SHA-256 of its UTF-8
766/// bytes.
767///
768/// It is not a secret, so its rendering shows it — written as
769/// [`VERIFIER_PREFIX`] and the digest in lowercase hexadecimal, which is the
770/// one spelling [`Self::parse`] accepts. It is still printed by nothing but the
771/// two commands that exist to print it, and logged by nothing. A verifier of a
772/// short or guessable credential can be searched offline, which is why the
773/// credential it verifies is drawn from 32 random bytes when this program
774/// draws it.
775#[derive(Clone, PartialEq, Eq)]
776pub struct CredentialVerifier([u8; 32]);
777
778impl CredentialVerifier {
779    /// The verifier of one credential.
780    #[must_use]
781    pub fn of(credential: &str) -> Self {
782        use sha2::Digest as _;
783
784        Self(sha2::Sha256::digest(credential.as_bytes()).into())
785    }
786
787    /// The verifier this text writes down.
788    ///
789    /// # Errors
790    ///
791    /// Answers why the text is not one: anything but [`VERIFIER_PREFIX`]
792    /// followed by exactly 64 lowercase hexadecimal digits.
793    pub fn parse(text: &str) -> Result<Self, &'static str> {
794        const SHAPE: &str = "it is not `sha256:` followed by the 64 lowercase hexadecimal digits                              of a SHA-256 digest, which is what `printobserver credential issue`                              and `printobserver credential verifier` print";
795        let digits = text.strip_prefix(VERIFIER_PREFIX).ok_or(SHAPE)?;
796        if digits.len() != VERIFIER_DIGITS
797            || !digits
798                .bytes()
799                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
800        {
801            return Err(SHAPE);
802        }
803        let mut digest = [0_u8; 32];
804        for (index, pair) in digits.as_bytes().chunks(2).enumerate() {
805            let high = hex_value(pair[0]);
806            let low = hex_value(pair[1]);
807            digest[index] = (high << 4) | low;
808        }
809        Ok(Self(digest))
810    }
811
812    /// Whether a presented credential is the one this verifies.
813    ///
814    /// The presented bytes are digested and the two digests compared in
815    /// constant time, so how long this takes says nothing about how much of
816    /// the credential a caller guessed.
817    #[must_use]
818    pub fn admits(&self, presented: &[u8]) -> bool {
819        use sha2::Digest as _;
820        use subtle::ConstantTimeEq as _;
821
822        let offered: [u8; 32] = sha2::Sha256::digest(presented).into();
823        bool::from(self.0.ct_eq(&offered))
824    }
825}
826
827/// One lowercase hexadecimal digit's value, for a digit already checked.
828const fn hex_value(digit: u8) -> u8 {
829    if digit.is_ascii_digit() {
830        digit - b'0'
831    } else {
832        digit - b'a' + 10
833    }
834}
835
836impl core::fmt::Display for CredentialVerifier {
837    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
838        formatter.write_str(VERIFIER_PREFIX)?;
839        for byte in self.0 {
840            write!(formatter, "{byte:02x}")?;
841        }
842        Ok(())
843    }
844}
845
846impl core::fmt::Debug for CredentialVerifier {
847    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
848        write!(formatter, "CredentialVerifier({self})")
849    }
850}
851
852/// One running server's validated configuration.
853///
854/// Every value here is one no later step has to re-examine, and where a
855/// validated type for one already exists it is that type rather than the text
856/// it was written as: the `OctoPrint` instance is the adapter's own
857/// configuration, which redacts the key it carries; the harness and the model
858/// are the supervisor adapter's own names; and the ingress secret is a value
859/// neither rendering of which shows.
860#[derive(Debug, Clone, PartialEq)]
861pub struct ServerConfig {
862    /// Where the store, the images and the sessions live.
863    pub state_dir: PathBuf,
864    /// The address the API and the ingress are served on.
865    pub listen: SocketAddr,
866    /// Everything the printer adapter needs to reach the instance.
867    pub octoprint: OctoPrintConfig,
868    /// The operator's safety envelope.
869    pub safety: SafetyEnvelope,
870    /// The harness identity turns run on.
871    pub harness: HarnessIdentity,
872    /// The model turns are pinned to, when one is pinned.
873    pub model: Option<ModelName>,
874    /// The installed skill's `SKILL.md`, whose prose is sent as every turn's
875    /// system prompt. The agent runs from the directory holding it, which is
876    /// where the skill's own `reference/` documents sit.
877    pub skill_path: PathBuf,
878    /// The prompt template one turn fills, when the operator supplied one.
879    pub prompt_template_path: Option<PathBuf>,
880    /// How often every active print is given a periodic observation.
881    pub observation_interval: core::time::Duration,
882    /// How long the ingress may take to answer.
883    pub ingress_answer_bound: core::time::Duration,
884    /// The shared secret every post to the ingress must carry.
885    pub ingress_shared_secret: SharedSecret,
886    /// A plaintext operator credential the configuration still carries, which
887    /// is admitted — with a warning on every start — until it is replaced by
888    /// its verifier.
889    pub api_credential: Option<ApiCredential>,
890    /// The verifier the operator's credential is checked against, when the
891    /// configuration names one. Absent, the composition root reads the one in
892    /// the state directory.
893    pub api_credential_verifier: Option<CredentialVerifier>,
894    /// Where a fresh frame of the print is fetched from, when configured.
895    pub camera_snapshot_url: Option<WebAddress>,
896    /// `Obico`'s own API, when configured; its debug form omits the token.
897    pub obico_api: Option<ObicoApi>,
898    /// How spools are checked before a print, and the margin asked for.
899    pub spools: SpoolPolicy,
900}
901
902impl ServerConfig {
903    /// Read and validate the one configuration file this program takes.
904    ///
905    /// # Errors
906    ///
907    /// Returns [`ConfigError::Unreadable`] when the file is not there,
908    /// [`ConfigError::Unparsable`] when it is not this program's configuration,
909    /// and [`ConfigError::Field`] naming the one field whose value cannot be
910    /// accepted. The two values only the machine can rule on — the `OctoPrint`
911    /// address and key — are ruled on by [`crate::Server::start`], which is
912    /// where a printer exists to ask.
913    pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
914        let path = path.as_ref();
915        Self::parse(&read(path)?, path)
916    }
917
918    /// The same, over a document already read.
919    ///
920    /// # Errors
921    ///
922    /// The same as [`ServerConfig::load`], less the unreadable file.
923    pub fn parse(text: &str, path: &Path) -> Result<Self, ConfigError> {
924        let file: ConfigFile = toml::from_str(text).map_err(|error| ConfigError::Unparsable {
925            path: path.to_path_buf(),
926            detail: error.to_string(),
927        })?;
928        Self::validate(file)
929    }
930
931    /// Rule on every value the document carries.
932    ///
933    /// Absence is ruled on here rather than by the parser, because a parser's
934    /// own "missing field" says which key it wanted and not which field of this
935    /// program that is. Every refusal below names the dotted key an operator
936    /// would edit.
937    fn validate(file: ConfigFile) -> Result<Self, ConfigError> {
938        let state_dir =
939            state_directory(required(ConfigField::StateDir, file.state_dir)?.as_path())?;
940        let listen = listen_address(&required(ConfigField::Listen, file.listen)?)?;
941        let octoprint = octoprint(&file.octoprint)?;
942        let safety = required(ConfigField::SafetyEnvelope, file.safety)?;
943        check_envelope(&safety)?;
944        let harness = harness_identity(file.supervisor.harness)?;
945        let model = match file.supervisor.model {
946            None => None,
947            Some(name) => Some(
948                ModelName::new(&named(ConfigField::Model, Some(name))?)
949                    .map_err(|error| ConfigError::about(ConfigField::Model, error.to_string()))?,
950            ),
951        };
952        let skill_path = skill(file.supervisor.skill_path.as_deref())?;
953        let prompt_template_path = readable(
954            ConfigField::PromptTemplatePath,
955            file.supervisor.prompt_template_path.as_deref(),
956        )?;
957        let observation_interval = observation_interval(file.supervisor.observation_interval_s)?;
958        let ingress_answer_bound = answer_bound(file.ingress.answer_bound_ms)?;
959        let ingress_shared_secret = SharedSecret::new(&required(
960            ConfigField::IngressSharedSecret,
961            file.ingress.shared_secret,
962        )?)?;
963        let api_credential = file
964            .api
965            .credential
966            .as_deref()
967            .map(|value| {
968                ApiCredential::new(value)
969                    .map_err(|why| ConfigError::about(ConfigField::ApiCredential, why))
970            })
971            .transpose()?;
972        let api_credential_verifier = file
973            .api
974            .credential_verifier
975            .as_deref()
976            .map(|value| {
977                CredentialVerifier::parse(value.trim())
978                    .map_err(|why| ConfigError::about(ConfigField::ApiCredentialVerifier, why))
979            })
980            .transpose()?;
981        let camera_snapshot_url = file
982            .camera
983            .snapshot_url
984            .map(|url| web_address(ConfigField::CameraSnapshotUrl, &url))
985            .transpose()?;
986        let obico_api = obico_api(file.obico)?;
987        let spools = spool_policy(&file.spools)?;
988        Ok(Self {
989            state_dir,
990            listen,
991            octoprint,
992            safety,
993            harness,
994            model,
995            skill_path,
996            prompt_template_path,
997            observation_interval,
998            ingress_answer_bound,
999            ingress_shared_secret,
1000            api_credential,
1001            api_credential_verifier,
1002            camera_snapshot_url,
1003            obico_api,
1004            spools,
1005        })
1006    }
1007
1008    /// Where this server materializes the agent's prompt template and
1009    /// assessment schema. The skill is not among them: it is the installed one
1010    /// `skill_path` names.
1011    #[must_use]
1012    pub fn assets_dir(&self) -> PathBuf {
1013        self.state_dir.join(ASSETS_DIRECTORY)
1014    }
1015}
1016
1017/// One address a field names, refused unless it is an `http` or `https` URL
1018/// naming a host, by the field's own key and without quoting the value.
1019fn web_address(field: ConfigField, url: &str) -> Result<WebAddress, ConfigError> {
1020    WebAddress::new(url).map_err(|why| ConfigError::about(field, why))
1021}
1022
1023/// `Obico`'s API, when both its address and its token are written down.
1024///
1025/// One without the other is refused naming the one that is missing: an address
1026/// with no token is a request `Obico` refuses, and a token with no address is a
1027/// secret written down for nothing.
1028fn obico_api(section: ObicoSection) -> Result<Option<ObicoApi>, ConfigError> {
1029    match (section.url, section.access_token) {
1030        (None, None) => Ok(None),
1031        (Some(_), None) => Err(ConfigError::about(
1032            ConfigField::ObicoAccessToken,
1033            "it is required when obico.url is given",
1034        )),
1035        (None, Some(_)) => Err(ConfigError::about(
1036            ConfigField::ObicoUrl,
1037            "it is required when obico.access_token is given",
1038        )),
1039        (Some(url), Some(access_token)) => {
1040            let url = web_address(ConfigField::ObicoUrl, &url)?;
1041            let access_token = AccessToken::new(&access_token)
1042                .map_err(|why| ConfigError::about(ConfigField::ObicoAccessToken, why))?;
1043            Ok(Some(ObicoApi::new(url, access_token)))
1044        }
1045    }
1046}
1047
1048/// The two values signing a harness in reads, and nothing else.
1049///
1050/// An operator signs the agent in before or after filling in the machine and
1051/// the failure detector, so `printobserver sign-in` reads the state directory
1052/// and the harness identity out of the server's own file and nothing beside
1053/// them: every other value the file carries, present or not and valid or not,
1054/// is one it never looks at.
1055#[derive(Debug, Clone, PartialEq, Eq)]
1056pub struct SignInConfig {
1057    /// Where the state lives, and so where the harness keeps its sign-in.
1058    pub state_dir: PathBuf,
1059    /// The harness identity supervision turns run on.
1060    pub harness: HarnessIdentity,
1061}
1062
1063impl SignInConfig {
1064    /// Read those two values out of one configuration file.
1065    ///
1066    /// # Errors
1067    ///
1068    /// Returns [`ConfigError::Unreadable`] when the file is not there,
1069    /// [`ConfigError::Unparsable`] when it is not a document carrying either
1070    /// value in the shape this program reads it in, and [`ConfigError::Field`]
1071    /// naming `state_dir` or `supervisor.harness` when that value cannot be
1072    /// accepted.
1073    pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
1074        let path = path.as_ref();
1075        let file: SignInFile =
1076            toml::from_str(&read(path)?).map_err(|error| ConfigError::Unparsable {
1077                path: path.to_path_buf(),
1078                detail: error.to_string(),
1079            })?;
1080        Ok(Self {
1081            state_dir: state_directory(required(ConfigField::StateDir, file.state_dir)?.as_path())?,
1082            harness: harness_identity(file.supervisor.harness)?,
1083        })
1084    }
1085}
1086
1087/// The configuration file, read for the two values signing in takes.
1088///
1089/// Unlike [`ConfigFile`] it refuses no key it does not know, because every key
1090/// but these two is one signing in does not read.
1091#[derive(Deserialize)]
1092#[serde(crate = "printobserver_types::serde")]
1093struct SignInFile {
1094    /// Where the state lives.
1095    #[serde(default)]
1096    state_dir: Option<PathBuf>,
1097    /// The supervisor's section, for its harness alone.
1098    #[serde(default)]
1099    supervisor: SignInSupervisor,
1100}
1101
1102/// The supervisor's section, read for the harness alone.
1103#[derive(Default, Deserialize)]
1104#[serde(crate = "printobserver_types::serde")]
1105struct SignInSupervisor {
1106    /// The harness identity turns run on.
1107    #[serde(default)]
1108    harness: Option<String>,
1109}
1110
1111/// One configuration file's text.
1112fn read(path: &Path) -> Result<String, ConfigError> {
1113    std::fs::read_to_string(path).map_err(|error| ConfigError::Unreadable {
1114        path: path.to_path_buf(),
1115        detail: error.to_string(),
1116    })
1117}
1118
1119/// The harness identity, refused by its own key when it names nothing.
1120fn harness_identity(value: Option<String>) -> Result<HarnessIdentity, ConfigError> {
1121    HarnessIdentity::new(&named(ConfigField::Harness, value)?)
1122        .map_err(|error| ConfigError::about(ConfigField::Harness, error.to_string()))
1123}
1124
1125/// One field the file has to carry, refused by its own key when it does not.
1126fn required<T>(field: ConfigField, value: Option<T>) -> Result<T, ConfigError> {
1127    value.ok_or_else(|| ConfigError::about(field, "the configuration file carries no value for it"))
1128}
1129
1130/// One field that has to carry a name rather than nothing at all.
1131fn named(field: ConfigField, value: Option<String>) -> Result<String, ConfigError> {
1132    let value = required(field, value)?;
1133    if value.trim().is_empty() {
1134        return Err(ConfigError::about(
1135            field,
1136            "it is empty, and an empty value names nothing",
1137        ));
1138    }
1139    Ok(value.trim().to_owned())
1140}
1141
1142/// The state directory, created where it is not there.
1143fn state_directory(named: &Path) -> Result<PathBuf, ConfigError> {
1144    if named.as_os_str().is_empty() {
1145        return Err(ConfigError::about(
1146            ConfigField::StateDir,
1147            "it names no directory, and this server's whole state lives in one",
1148        ));
1149    }
1150    std::fs::create_dir_all(named).map_err(|error| {
1151        ConfigError::about(
1152            ConfigField::StateDir,
1153            format!("{} cannot be created: {error}", named.display()),
1154        )
1155    })?;
1156    named.canonicalize().map(plainly_written).map_err(|error| {
1157        ConfigError::about(
1158            ConfigField::StateDir,
1159            format!("{} cannot be resolved: {error}", named.display()),
1160        )
1161    })
1162}
1163
1164/// A resolved path, written the way its own platform's tools write it.
1165///
1166/// Resolving a path on Windows answers it in its verbatim form, `\\?\C:\…`:
1167/// one this program opens as readily as any other, and one no operator types and
1168/// some of the programs a supervision turn runs refuse — and every image path
1169/// this server answers is written under it. Where that form names an ordinary
1170/// drive path it is written as that path. Any other path, which on every other
1171/// platform is every path, is answered as it is.
1172#[must_use]
1173pub fn plainly_written(path: PathBuf) -> PathBuf {
1174    const VERBATIM: &str = r"\\?\";
1175    let drive = path
1176        .to_str()
1177        .and_then(|text| text.strip_prefix(VERBATIM))
1178        .filter(|rest| {
1179            let bytes = rest.as_bytes();
1180            bytes.len() >= 3
1181                && bytes[0].is_ascii_alphabetic()
1182                && bytes[1] == b':'
1183                && bytes[2] == b'\\'
1184        })
1185        .map(PathBuf::from);
1186    drive.unwrap_or(path)
1187}
1188
1189/// The address to serve on, as an address rather than as text.
1190fn listen_address(named: &str) -> Result<SocketAddr, ConfigError> {
1191    named.trim().parse().map_err(|error| {
1192        ConfigError::about(
1193            ConfigField::Listen,
1194            format!("{named:?} is no address to listen on: {error}"),
1195        )
1196    })
1197}
1198
1199/// Everything the printer adapter needs to reach the instance, refused by the
1200/// field whose value it could not take.
1201fn octoprint(section: &OctoprintSection) -> Result<OctoPrintConfig, ConfigError> {
1202    let fan = fan_support(&section.fan)?;
1203    let url = named(ConfigField::OctoprintUrl, section.url.clone())?;
1204    let key = named(ConfigField::OctoprintApiKey, section.api_key.clone())?;
1205    OctoPrintConfig::new(&url, key)
1206        .map(|configured| configured.with_fan(fan))
1207        .map_err(|error| {
1208            let field = match error {
1209                printobserver_octoprint::ConfigError::EmptyApiKey => ConfigField::OctoprintApiKey,
1210                _ => ConfigField::OctoprintUrl,
1211            };
1212            ConfigError::about(field, error.to_string())
1213        })
1214}
1215
1216/// The fan setting one word of the vocabulary names.
1217fn fan_support(named: &str) -> Result<FanSupport, ConfigError> {
1218    FAN_VOCABULARY
1219        .iter()
1220        .find(|(spelling, _)| *spelling == named.trim())
1221        .map(|(_, support)| *support)
1222        .ok_or_else(|| {
1223            let vocabulary: Vec<&str> = FAN_VOCABULARY.iter().map(|(word, _)| *word).collect();
1224            ConfigError::about(
1225                ConfigField::OctoprintFan,
1226                format!("{named:?} is not one of {}", vocabulary.join(" or ")),
1227            )
1228        })
1229}
1230
1231/// The envelope, refused when a range it declares admits nothing.
1232fn check_envelope(envelope: &SafetyEnvelope) -> Result<(), ConfigError> {
1233    if envelope.allowed.is_empty() {
1234        return Err(ConfigError::about(
1235            ConfigField::SafetyEnvelope,
1236            "it allows no adjustable at all, so no adjustment could ever be accepted",
1237        ));
1238    }
1239    for (adjustable, range) in &envelope.allowed {
1240        if !range.min.is_finite() || !range.max.is_finite() || range.min > range.max {
1241            return Err(ConfigError::about(
1242                ConfigField::SafetyEnvelope,
1243                format!(
1244                    "the range allowed for {adjustable} runs from {} to {}, which admits \
1245                     no value",
1246                    range.min, range.max
1247                ),
1248            ));
1249        }
1250    }
1251    if envelope.agent_min_interval_s < 0 {
1252        return Err(ConfigError::about(
1253            ConfigField::SafetyEnvelope,
1254            format!(
1255                "the agent's minimum interval is {}s, and an interval is a count of seconds",
1256                envelope.agent_min_interval_s
1257            ),
1258        ));
1259    }
1260    Ok(())
1261}
1262
1263/// One optional path, read where it was named so that a path naming nothing is
1264/// refused here rather than hours later.
1265fn readable(field: ConfigField, named: Option<&Path>) -> Result<Option<PathBuf>, ConfigError> {
1266    let Some(path) = named else {
1267        return Ok(None);
1268    };
1269    std::fs::read_to_string(path)
1270        .map(|_| Some(path.to_path_buf()))
1271        .map_err(|error| {
1272            ConfigError::about(field, format!("{} cannot be read: {error}", path.display()))
1273        })
1274}
1275
1276/// The installed skill, refused naming how to install one when it is absent or
1277/// cannot be read.
1278fn skill(named: Option<&Path>) -> Result<PathBuf, ConfigError> {
1279    let Some(path) = named else {
1280        return Err(ConfigError::about(
1281            ConfigField::SkillPath,
1282            format!(
1283                "the configuration file carries no value for it, and this program carries \
1284                 no skill of its own: {SKILL_INSTALL}"
1285            ),
1286        ));
1287    };
1288    std::fs::read_to_string(path)
1289        .map(|_| path.to_path_buf())
1290        .map_err(|error| {
1291            ConfigError::about(
1292                ConfigField::SkillPath,
1293                format!(
1294                    "{} cannot be read: {error}. {SKILL_INSTALL}",
1295                    path.display()
1296                ),
1297            )
1298        })
1299}
1300
1301/// How spools are checked, each key left out taking the core's own default.
1302fn spool_policy(section: &SpoolsSection) -> Result<SpoolPolicy, ConfigError> {
1303    let defaults = SpoolPolicy::default();
1304    let preflight = match section.preflight.as_deref() {
1305        None => defaults.preflight,
1306        Some("refuse") => PreflightMode::Refuse,
1307        Some("warn") => PreflightMode::Warn,
1308        Some("off") => PreflightMode::Off,
1309        Some(_) => {
1310            return Err(ConfigError::about(
1311                ConfigField::SpoolsPreflight,
1312                "the spool check is one of `refuse`, `warn` or `off`",
1313            ));
1314        }
1315    };
1316    let margin = |field: ConfigField, value: Option<f64>, default: f64| match value {
1317        None => Ok(default),
1318        Some(value) if value.is_finite() && value >= 0.0 => Ok(value),
1319        Some(_) => Err(ConfigError::about(
1320            field,
1321            "a margin is a figure at or above zero; a negative one asks a spool for less \
1322             than the print needs",
1323        )),
1324    };
1325    let buffer_percent = margin(
1326        ConfigField::SpoolsBufferPercent,
1327        section.buffer_percent,
1328        defaults.buffer_percent,
1329    )?;
1330    let buffer_min_g = margin(
1331        ConfigField::SpoolsBufferMinG,
1332        section.buffer_min_g,
1333        defaults.buffer_min_g,
1334    )?;
1335    let analysis_wait_s = match section.analysis_wait_seconds {
1336        None => defaults.analysis_wait_s,
1337        Some(seconds) => u64::try_from(seconds).map_err(|_| {
1338            ConfigError::about(
1339                ConfigField::SpoolsAnalysisWaitSeconds,
1340                "a wait is a number of seconds at or above zero",
1341            )
1342        })?,
1343    };
1344    Ok(SpoolPolicy {
1345        preflight,
1346        buffer_percent,
1347        buffer_min_g,
1348        analysis_wait_s,
1349    })
1350}
1351
1352/// The observation interval, refused at zero.
1353fn observation_interval(seconds: u64) -> Result<core::time::Duration, ConfigError> {
1354    if seconds == 0 {
1355        return Err(ConfigError::about(
1356            ConfigField::ObservationIntervalS,
1357            "an interval of zero seconds observes a print again the moment its last turn \
1358             returns, which is a turn that never ends",
1359        ));
1360    }
1361    Ok(core::time::Duration::from_secs(seconds))
1362}
1363
1364/// The answer bound, refused when it is not one this program admits.
1365fn answer_bound(milliseconds: u64) -> Result<core::time::Duration, ConfigError> {
1366    if milliseconds == 0 {
1367        return Err(ConfigError::about(
1368            ConfigField::IngressAnswerBoundMs,
1369            "a bound of zero is an ingress that has run out of time before it starts",
1370        ));
1371    }
1372    if milliseconds >= OBICO_POSTING_TIMEOUT_MS {
1373        return Err(ConfigError::about(
1374            ConfigField::IngressAnswerBoundMs,
1375            format!(
1376                "{milliseconds}ms is not below the {OBICO_POSTING_TIMEOUT_MS}ms Obico posts \
1377                 under, so an alert answered at that bound is one Obico has already \
1378                 abandoned — and its posting does not retry"
1379            ),
1380        ));
1381    }
1382    Ok(core::time::Duration::from_millis(milliseconds))
1383}
1384
1385#[cfg(test)]
1386mod tests {
1387    use super::CredentialVerifier;
1388
1389    /// The SHA-256 of `abc`, as FIPS 180-2 gives it.
1390    const ABC: &str = "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
1391
1392    /// A verifier is the SHA-256 of the credential's UTF-8 bytes, written and
1393    /// read back in one spelling, and it admits that credential and no other.
1394    #[test]
1395    fn a_verifier_is_the_credentials_sha256_and_admits_only_it() {
1396        let verifier = CredentialVerifier::of("abc");
1397
1398        assert_eq!(verifier.to_string(), ABC);
1399        assert_eq!(CredentialVerifier::parse(ABC), Ok(verifier.clone()));
1400        assert!(verifier.admits(b"abc"));
1401        assert!(!verifier.admits(b"abd"));
1402        assert!(!verifier.admits(b""));
1403    }
1404
1405    /// Anything but `sha256:` and 64 lowercase hexadecimal digits is refused.
1406    #[test]
1407    fn a_verifier_in_any_other_spelling_is_refused() {
1408        for refused in [
1409            "",
1410            "sha256:",
1411            &ABC[..ABC.len() - 1],
1412            &format!("{ABC}0"),
1413            &ABC.to_uppercase(),
1414            &ABC.replace("sha256:", "sha512:"),
1415            &ABC.replace("sha256:", ""),
1416            &ABC.replace('a', "g"),
1417        ] {
1418            assert!(
1419                CredentialVerifier::parse(refused).is_err(),
1420                "{refused:?} was accepted"
1421            );
1422        }
1423    }
1424}