1use std::net::SocketAddr;
115use std::path::{Path, PathBuf};
116
117use printobserver_core::{
118 ActionKind, ActorClass, AwayFromBed, DEFAULT_CLEARANCE_MARGIN_MM, DEFAULT_MAX_LIFT_MM,
119 PreflightMode, RecoveryActionKind, RecoveryConfig, RecoveryGrants, SafetyEnvelope, SheetTable,
120 SpoolPolicy,
121};
122use printobserver_obico::{
123 AccessToken, BlankFrameBound, MAX_BLANK_FRAME_MAX_STDDEV, MIN_BLANK_FRAME_MAX_STDDEV, ObicoApi,
124};
125use printobserver_octoprint::{FanSupport, OctoPrintConfig};
126use printobserver_oneharness::{HarnessIdentity, ModelName};
127use printobserver_types::schemars::JsonSchema;
128use printobserver_types::serde::{Deserialize, Serialize};
129use printobserver_vision_api::WebAddress;
130
131pub const DEFAULT_INGRESS_ANSWER_BOUND_MS: u64 = 1_000;
138
139pub const DEFAULT_OBSERVATION_INTERVAL_S: u64 =
142 printobserver_core::DEFAULT_OBSERVATION_INTERVAL.as_secs();
143
144pub const DEFAULT_PRINTER_POLL_S: u64 = printobserver_core::DEFAULT_PRINTER_POLL.as_secs();
147
148pub const PRINTER_POLL_RANGE_S: (u64, u64) = (5, 300);
150
151pub const DEFAULT_UNATTENDED_WINDOW_S: u64 =
154 printobserver_core::DEFAULT_UNATTENDED_WINDOW.as_secs();
155
156pub const UNATTENDED_WINDOW_RANGE_S: (u64, u64) = (60, 86_400);
158
159pub const OBICO_POSTING_TIMEOUT_MS: u64 = 5_000;
168
169pub const ASSETS_DIRECTORY: &str = "assets";
174
175pub const SKILL_INSTALL: &str = "the skill is installed with `gh skill install \
182 nickderobertis/printobserver printobserver --dir <dir>`, and \
183 `supervisor.skill_path` names the installed `SKILL.md`, \
184 `<dir>/printobserver/SKILL.md`";
185
186#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
192pub enum ConfigField {
193 StateDir,
195 Listen,
197 OctoprintUrl,
199 OctoprintApiKey,
201 OctoprintFan,
203 SafetyEnvelope,
205 Harness,
207 Model,
209 SkillPath,
211 PromptTemplatePath,
213 ObservationIntervalS,
215 PrinterPollS,
217 UnattendedWindowS,
220 IngressAnswerBoundMs,
222 IngressSharedSecret,
224 ApiCredential,
227 ApiCredentialVerifier,
229 CameraSnapshotUrl,
232 ObicoUrl,
234 ObicoAccessToken,
236 ObicoMlApiUrl,
238 VisionBlankFrameMaxStddev,
240 SpoolsPreflight,
242 SpoolsBufferPercent,
244 SpoolsBufferMinG,
246 SpoolsAnalysisWaitSeconds,
248 SheetsAllowed,
250 RecoveryAwayFromBed,
252 RecoveryMaxZMm,
254 RecoveryMaxLiftMm,
256 RecoveryClearanceMarginMm,
258 RecoveryParkXy,
260 RecoveryZHomeXy,
262 RecoveryZHomeSweepsBed,
264 PolicyRecoveryOperator,
266 PolicyRecoveryAgent,
268 PolicyRecoveryAsserting,
270}
271
272impl ConfigField {
273 pub const ALL: [Self; 37] = [
275 Self::StateDir,
276 Self::Listen,
277 Self::OctoprintUrl,
278 Self::OctoprintApiKey,
279 Self::OctoprintFan,
280 Self::SafetyEnvelope,
281 Self::Harness,
282 Self::Model,
283 Self::SkillPath,
284 Self::PromptTemplatePath,
285 Self::ObservationIntervalS,
286 Self::PrinterPollS,
287 Self::UnattendedWindowS,
288 Self::IngressAnswerBoundMs,
289 Self::IngressSharedSecret,
290 Self::ApiCredential,
291 Self::ApiCredentialVerifier,
292 Self::CameraSnapshotUrl,
293 Self::ObicoUrl,
294 Self::ObicoAccessToken,
295 Self::ObicoMlApiUrl,
296 Self::VisionBlankFrameMaxStddev,
297 Self::SpoolsPreflight,
298 Self::SpoolsBufferPercent,
299 Self::SpoolsBufferMinG,
300 Self::SpoolsAnalysisWaitSeconds,
301 Self::SheetsAllowed,
302 Self::RecoveryAwayFromBed,
303 Self::RecoveryMaxZMm,
304 Self::RecoveryMaxLiftMm,
305 Self::RecoveryClearanceMarginMm,
306 Self::RecoveryParkXy,
307 Self::RecoveryZHomeXy,
308 Self::RecoveryZHomeSweepsBed,
309 Self::PolicyRecoveryOperator,
310 Self::PolicyRecoveryAgent,
311 Self::PolicyRecoveryAsserting,
312 ];
313
314 #[must_use]
316 pub const fn key(self) -> &'static str {
317 match self {
318 Self::StateDir => "state_dir",
319 Self::Listen => "listen",
320 Self::OctoprintUrl => "octoprint.url",
321 Self::OctoprintApiKey => "octoprint.api_key",
322 Self::OctoprintFan => "octoprint.fan",
323 Self::SafetyEnvelope => "safety",
324 Self::Harness => "supervisor.harness",
325 Self::Model => "supervisor.model",
326 Self::SkillPath => "supervisor.skill_path",
327 Self::PromptTemplatePath => "supervisor.prompt_template_path",
328 Self::ObservationIntervalS => "supervisor.observation_interval_s",
329 Self::PrinterPollS => "supervisor.printer_poll_s",
330 Self::UnattendedWindowS => "supervisor.unattended_window_s",
331 Self::IngressAnswerBoundMs => "ingress.answer_bound_ms",
332 Self::IngressSharedSecret => "ingress.shared_secret",
333 Self::ApiCredential => "api.credential",
334 Self::ApiCredentialVerifier => "api.credential_verifier",
335 Self::CameraSnapshotUrl => "camera.snapshot_url",
336 Self::ObicoUrl => "obico.url",
337 Self::ObicoAccessToken => "obico.access_token",
338 Self::ObicoMlApiUrl => "obico.ml_api_url",
339 Self::VisionBlankFrameMaxStddev => "vision.blank_frame_max_stddev",
340 Self::SpoolsPreflight => "spools.preflight",
341 Self::SpoolsBufferPercent => "spools.buffer_percent",
342 Self::SpoolsBufferMinG => "spools.buffer_min_g",
343 Self::SpoolsAnalysisWaitSeconds => "spools.analysis_wait_seconds",
344 Self::SheetsAllowed => "sheets.allowed",
345 Self::RecoveryAwayFromBed => "recovery.away_from_bed",
346 Self::RecoveryMaxZMm => "recovery.max_z_mm",
347 Self::RecoveryMaxLiftMm => "recovery.max_lift_mm",
348 Self::RecoveryClearanceMarginMm => "recovery.clearance_margin_mm",
349 Self::RecoveryParkXy => "recovery.park_xy",
350 Self::RecoveryZHomeXy => "recovery.z_home_xy",
351 Self::RecoveryZHomeSweepsBed => "recovery.z_home_sweeps_bed",
352 Self::PolicyRecoveryOperator => "policy.recovery.operator",
353 Self::PolicyRecoveryAgent => "policy.recovery.agent",
354 Self::PolicyRecoveryAsserting => "policy.recovery.asserting",
355 }
356 }
357}
358
359impl core::fmt::Display for ConfigField {
360 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
361 formatter.write_str(self.key())
362 }
363}
364
365#[derive(Debug, Clone, PartialEq, Eq)]
370pub enum ConfigError {
371 Unreadable {
373 path: PathBuf,
375 detail: String,
377 },
378 Unparsable {
380 path: PathBuf,
382 detail: String,
384 },
385 Field {
387 field: ConfigField,
389 detail: String,
391 },
392}
393
394impl ConfigError {
395 #[must_use]
397 pub const fn field(&self) -> Option<ConfigField> {
398 match self {
399 Self::Field { field, .. } => Some(*field),
400 _ => None,
401 }
402 }
403
404 pub(crate) fn about(field: ConfigField, detail: impl Into<String>) -> Self {
406 Self::Field {
407 field,
408 detail: detail.into(),
409 }
410 }
411}
412
413impl core::fmt::Display for ConfigError {
414 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
415 match self {
416 Self::Unreadable { path, detail } => write!(
417 formatter,
418 "the configuration file {} could not be read: {detail}",
419 path.display()
420 ),
421 Self::Unparsable { path, detail } => write!(
422 formatter,
423 "the configuration file {} could not be read as this program's \
424 configuration: {detail}",
425 path.display()
426 ),
427 Self::Field { field, detail } => write!(
428 formatter,
429 "the configuration field `{field}` cannot be accepted: {detail}"
430 ),
431 }
432 }
433}
434
435impl core::error::Error for ConfigError {}
436
437#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
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 OctoprintSection {
446 #[serde(default, skip_serializing_if = "Option::is_none")]
448 pub url: Option<String>,
449 #[serde(default, skip_serializing_if = "Option::is_none")]
451 pub api_key: Option<String>,
452 #[serde(default = "commandable")]
454 pub fan: String,
455}
456
457pub const FAN_VOCABULARY: [(&str, FanSupport); 2] = [
460 ("commandable", FanSupport::Commandable),
461 ("absent", FanSupport::Absent),
462];
463
464fn commandable() -> String {
466 FAN_VOCABULARY[0].0.to_owned()
467}
468
469impl Default for OctoprintSection {
470 fn default() -> Self {
471 Self {
472 url: None,
473 api_key: None,
474 fan: commandable(),
475 }
476 }
477}
478
479#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
481#[serde(
482 crate = "printobserver_types::serde",
483 deny_unknown_fields,
484 rename_all = "snake_case"
485)]
486#[schemars(crate = "printobserver_types::schemars")]
487pub struct SupervisorSection {
488 #[serde(default, skip_serializing_if = "Option::is_none")]
490 pub harness: Option<String>,
491 #[serde(default, skip_serializing_if = "Option::is_none")]
493 pub model: Option<String>,
494 #[serde(default, skip_serializing_if = "Option::is_none")]
498 pub skill_path: Option<PathBuf>,
499 #[serde(default, skip_serializing_if = "Option::is_none")]
502 pub prompt_template_path: Option<PathBuf>,
503 #[serde(default = "default_observation_interval_s")]
506 pub observation_interval_s: u64,
507 #[serde(default = "default_printer_poll_s")]
510 pub printer_poll_s: u64,
511 #[serde(default = "default_unattended_window_s")]
515 pub unattended_window_s: u64,
516}
517
518const fn default_printer_poll_s() -> u64 {
520 DEFAULT_PRINTER_POLL_S
521}
522
523const fn default_unattended_window_s() -> u64 {
525 DEFAULT_UNATTENDED_WINDOW_S
526}
527
528const fn default_observation_interval_s() -> u64 {
530 DEFAULT_OBSERVATION_INTERVAL_S
531}
532
533impl Default for SupervisorSection {
534 fn default() -> Self {
535 Self {
536 harness: None,
537 model: None,
538 skill_path: None,
539 prompt_template_path: None,
540 observation_interval_s: DEFAULT_OBSERVATION_INTERVAL_S,
541 printer_poll_s: DEFAULT_PRINTER_POLL_S,
542 unattended_window_s: DEFAULT_UNATTENDED_WINDOW_S,
543 }
544 }
545}
546
547#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
549#[serde(
550 crate = "printobserver_types::serde",
551 deny_unknown_fields,
552 rename_all = "snake_case"
553)]
554#[schemars(crate = "printobserver_types::schemars")]
555pub struct IngressSection {
556 #[serde(default, skip_serializing_if = "Option::is_none")]
558 pub shared_secret: Option<String>,
559 #[serde(default = "default_answer_bound_ms")]
561 pub answer_bound_ms: u64,
562}
563
564const fn default_answer_bound_ms() -> u64 {
566 DEFAULT_INGRESS_ANSWER_BOUND_MS
567}
568
569impl Default for IngressSection {
570 fn default() -> Self {
571 Self {
572 shared_secret: None,
573 answer_bound_ms: DEFAULT_INGRESS_ANSWER_BOUND_MS,
574 }
575 }
576}
577
578#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
580#[serde(
581 crate = "printobserver_types::serde",
582 deny_unknown_fields,
583 rename_all = "snake_case"
584)]
585#[schemars(crate = "printobserver_types::schemars")]
586pub struct ApiSection {
587 #[serde(default, skip_serializing_if = "Option::is_none")]
591 pub credential: Option<String>,
592 #[serde(default, skip_serializing_if = "Option::is_none")]
598 pub credential_verifier: Option<String>,
599}
600
601#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
603#[serde(
604 crate = "printobserver_types::serde",
605 deny_unknown_fields,
606 rename_all = "snake_case"
607)]
608#[schemars(crate = "printobserver_types::schemars")]
609pub struct CameraSection {
610 #[serde(default, skip_serializing_if = "Option::is_none")]
613 pub snapshot_url: Option<String>,
614}
615
616#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
620#[serde(
621 crate = "printobserver_types::serde",
622 deny_unknown_fields,
623 rename_all = "snake_case"
624)]
625#[schemars(crate = "printobserver_types::schemars")]
626pub struct ObicoSection {
627 #[serde(default, skip_serializing_if = "Option::is_none")]
630 pub url: Option<String>,
631 #[serde(default, skip_serializing_if = "Option::is_none")]
635 pub access_token: Option<String>,
636 #[serde(default, skip_serializing_if = "Option::is_none")]
641 pub ml_api_url: Option<String>,
642}
643
644#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Default)]
646#[serde(
647 crate = "printobserver_types::serde",
648 deny_unknown_fields,
649 rename_all = "snake_case"
650)]
651#[schemars(crate = "printobserver_types::schemars")]
652pub struct VisionSection {
653 #[serde(default, skip_serializing_if = "Option::is_none")]
656 pub blank_frame_max_stddev: Option<f64>,
657}
658
659impl core::fmt::Debug for ObicoSection {
660 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
661 formatter
662 .debug_struct("ObicoSection")
663 .field("url", &self.url)
664 .field(
665 "access_token",
666 &self.access_token.as_ref().map(|_| REDACTED),
667 )
668 .field("ml_api_url", &self.ml_api_url)
669 .finish()
670 }
671}
672
673#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Default)]
680#[serde(
681 crate = "printobserver_types::serde",
682 deny_unknown_fields,
683 rename_all = "snake_case"
684)]
685#[schemars(crate = "printobserver_types::schemars")]
686pub struct SpoolsSection {
687 #[serde(default, skip_serializing_if = "Option::is_none")]
690 pub preflight: Option<String>,
691 #[serde(default, skip_serializing_if = "Option::is_none")]
693 pub buffer_percent: Option<f64>,
694 #[serde(default, skip_serializing_if = "Option::is_none")]
696 pub buffer_min_g: Option<f64>,
697 #[serde(default, skip_serializing_if = "Option::is_none")]
700 pub analysis_wait_seconds: Option<i64>,
701}
702
703#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
708#[serde(
709 crate = "printobserver_types::serde",
710 deny_unknown_fields,
711 rename_all = "snake_case"
712)]
713#[schemars(crate = "printobserver_types::schemars")]
714pub struct SheetsSection {
715 #[serde(default, skip_serializing_if = "Option::is_none")]
719 pub allowed: Option<std::collections::BTreeMap<String, Vec<String>>>,
720}
721
722#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Default)]
729#[serde(
730 crate = "printobserver_types::serde",
731 deny_unknown_fields,
732 rename_all = "snake_case"
733)]
734#[schemars(crate = "printobserver_types::schemars")]
735pub struct RecoverySection {
736 #[serde(default, skip_serializing_if = "Option::is_none")]
739 pub away_from_bed: Option<String>,
741 #[serde(default, skip_serializing_if = "Option::is_none")]
743 pub max_z_mm: Option<f64>,
744 #[serde(default, skip_serializing_if = "Option::is_none")]
747 pub max_lift_mm: Option<f64>,
748 #[serde(default, skip_serializing_if = "Option::is_none")]
751 pub clearance_margin_mm: Option<f64>,
752 #[serde(default, skip_serializing_if = "Option::is_none")]
754 pub park_xy: Option<Vec<f64>>,
755 #[serde(default, skip_serializing_if = "Option::is_none")]
757 pub z_home_xy: Option<Vec<f64>>,
758 #[serde(default, skip_serializing_if = "Option::is_none")]
761 pub z_home_sweeps_bed: Option<bool>,
762}
763
764#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
768#[serde(
769 crate = "printobserver_types::serde",
770 deny_unknown_fields,
771 rename_all = "snake_case"
772)]
773#[schemars(crate = "printobserver_types::schemars")]
774pub struct RecoveryPolicySection {
775 #[serde(default, skip_serializing_if = "Option::is_none")]
777 pub operator: Option<Vec<String>>,
779 #[serde(default, skip_serializing_if = "Option::is_none")]
782 pub agent: Option<Vec<String>>,
784 #[serde(default, skip_serializing_if = "Option::is_none")]
787 pub asserting: Option<Vec<String>>,
789}
790
791#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
793#[serde(
794 crate = "printobserver_types::serde",
795 deny_unknown_fields,
796 rename_all = "snake_case"
797)]
798#[schemars(crate = "printobserver_types::schemars")]
799pub struct PolicySection {
800 #[serde(default)]
802 pub recovery: RecoveryPolicySection,
803}
804
805#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
811#[serde(
812 crate = "printobserver_types::serde",
813 deny_unknown_fields,
814 rename_all = "snake_case"
815)]
816#[schemars(crate = "printobserver_types::schemars")]
817pub struct ConfigFile {
818 #[serde(default, skip_serializing_if = "Option::is_none")]
820 pub state_dir: Option<PathBuf>,
821 #[serde(default, skip_serializing_if = "Option::is_none")]
823 pub listen: Option<String>,
824 #[serde(default)]
826 pub octoprint: OctoprintSection,
827 #[serde(default, skip_serializing_if = "Option::is_none")]
829 pub safety: Option<SafetyEnvelope>,
830 #[serde(default)]
832 pub supervisor: SupervisorSection,
833 #[serde(default)]
835 pub ingress: IngressSection,
836 #[serde(default)]
838 pub api: ApiSection,
839 #[serde(default)]
841 pub camera: CameraSection,
842 #[serde(default)]
844 pub obico: ObicoSection,
845 #[serde(default)]
847 pub vision: VisionSection,
848 #[serde(default)]
850 pub spools: SpoolsSection,
851 #[serde(default)]
853 pub sheets: SheetsSection,
854 #[serde(default)]
856 pub recovery: RecoverySection,
857 #[serde(default)]
859 pub policy: PolicySection,
860}
861
862#[derive(Clone, PartialEq, Eq)]
869pub struct SharedSecret(String);
870
871pub const REDACTED: &str = "<redacted>";
873
874impl SharedSecret {
875 pub fn new(value: &str) -> Result<Self, ConfigError> {
883 if value.trim().is_empty() {
884 return Err(ConfigError::about(
885 ConfigField::IngressSharedSecret,
886 "it is empty, and anything that can post to the ingress can pause a printer",
887 ));
888 }
889 Ok(Self(value.to_owned()))
890 }
891
892 #[must_use]
899 pub fn matches(&self, offered: Option<&str>) -> bool {
900 let Some(offered) = offered else {
901 return false;
902 };
903 let expected = self.0.as_bytes();
904 let mut difference = expected.len() ^ offered.len();
905 for (index, byte) in offered.bytes().enumerate() {
906 let against = expected[index % expected.len().max(1)];
907 difference |= usize::from(byte ^ against);
908 }
909 difference == 0
910 }
911}
912
913impl core::fmt::Display for SharedSecret {
914 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
915 formatter.write_str(REDACTED)
916 }
917}
918
919impl core::fmt::Debug for SharedSecret {
920 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
921 write!(formatter, "SharedSecret({REDACTED})")
922 }
923}
924
925pub const GENERATED_CREDENTIAL_BYTES: usize = 32;
927
928#[derive(Clone)]
938pub struct ApiCredential(String);
939
940impl ApiCredential {
941 pub fn new(value: &str) -> Result<Self, &'static str> {
950 if value.trim().is_empty() {
951 return Err(
952 "it is empty, and anything that can reach this server's API can command a printer",
953 );
954 }
955 if !value.bytes().all(|byte| (b' '..=b'~').contains(&byte)) {
956 return Err(
957 "it carries a control character or a character outside printable ASCII, which \
958 no `Authorization` header carries intact",
959 );
960 }
961 if value.starts_with(' ') || value.ends_with(' ') {
962 return Err(
963 "it begins or ends with a space, which an `Authorization` header does not carry",
964 );
965 }
966 Ok(Self(value.to_owned()))
968 }
969
970 pub fn generate() -> Result<Self, getrandom::Error> {
980 use base64::Engine as _;
981
982 let mut drawn = [0_u8; GENERATED_CREDENTIAL_BYTES];
983 getrandom::fill(&mut drawn)?;
984 Ok(Self(
985 base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(drawn),
986 ))
987 }
988
989 #[must_use]
995 pub fn admits(&self, presented: &[u8]) -> bool {
996 use subtle::ConstantTimeEq as _;
997
998 let expected = self.0.as_bytes();
999 expected.len() == presented.len() && bool::from(expected.ct_eq(presented))
1000 }
1001
1002 #[must_use]
1005 pub fn written(&self) -> &str {
1006 &self.0
1007 }
1008
1009 #[must_use]
1011 pub fn verifier(&self) -> CredentialVerifier {
1012 CredentialVerifier::of(&self.0)
1013 }
1014}
1015
1016impl PartialEq for ApiCredential {
1017 fn eq(&self, other: &Self) -> bool {
1018 self.admits(other.0.as_bytes())
1019 }
1020}
1021
1022impl Eq for ApiCredential {}
1023
1024impl core::fmt::Display for ApiCredential {
1025 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1026 formatter.write_str(REDACTED)
1027 }
1028}
1029
1030impl core::fmt::Debug for ApiCredential {
1031 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1032 write!(formatter, "ApiCredential({REDACTED})")
1033 }
1034}
1035
1036pub const VERIFIER_PREFIX: &str = "sha256:";
1038
1039const VERIFIER_DIGITS: usize = 64;
1041
1042#[derive(Clone, PartialEq, Eq)]
1053pub struct CredentialVerifier([u8; 32]);
1054
1055impl CredentialVerifier {
1056 #[must_use]
1058 pub fn of(credential: &str) -> Self {
1059 use sha2::Digest as _;
1060
1061 Self(sha2::Sha256::digest(credential.as_bytes()).into())
1062 }
1063
1064 pub fn parse(text: &str) -> Result<Self, &'static str> {
1071 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";
1072 let digits = text.strip_prefix(VERIFIER_PREFIX).ok_or(SHAPE)?;
1073 if digits.len() != VERIFIER_DIGITS
1074 || !digits
1075 .bytes()
1076 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
1077 {
1078 return Err(SHAPE);
1079 }
1080 let mut digest = [0_u8; 32];
1081 for (index, pair) in digits.as_bytes().chunks(2).enumerate() {
1082 let high = hex_value(pair[0]);
1083 let low = hex_value(pair[1]);
1084 digest[index] = (high << 4) | low;
1085 }
1086 Ok(Self(digest))
1087 }
1088
1089 #[must_use]
1095 pub fn admits(&self, presented: &[u8]) -> bool {
1096 use sha2::Digest as _;
1097 use subtle::ConstantTimeEq as _;
1098
1099 let offered: [u8; 32] = sha2::Sha256::digest(presented).into();
1100 bool::from(self.0.ct_eq(&offered))
1101 }
1102}
1103
1104const fn hex_value(digit: u8) -> u8 {
1106 if digit.is_ascii_digit() {
1107 digit - b'0'
1108 } else {
1109 digit - b'a' + 10
1110 }
1111}
1112
1113impl core::fmt::Display for CredentialVerifier {
1114 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1115 formatter.write_str(VERIFIER_PREFIX)?;
1116 for byte in self.0 {
1117 write!(formatter, "{byte:02x}")?;
1118 }
1119 Ok(())
1120 }
1121}
1122
1123impl core::fmt::Debug for CredentialVerifier {
1124 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1125 write!(formatter, "CredentialVerifier({self})")
1126 }
1127}
1128
1129#[derive(Debug, Clone, PartialEq)]
1138pub struct ServerConfig {
1139 pub state_dir: PathBuf,
1141 pub listen: SocketAddr,
1143 pub octoprint: OctoPrintConfig,
1145 pub safety: SafetyEnvelope,
1147 pub harness: HarnessIdentity,
1149 pub model: Option<ModelName>,
1151 pub skill_path: PathBuf,
1155 pub prompt_template_path: Option<PathBuf>,
1157 pub observation_interval: core::time::Duration,
1159 pub printer_poll: core::time::Duration,
1161 pub unattended_window: core::time::Duration,
1164 pub blank_frame_max_stddev: BlankFrameBound,
1166 pub obico_ml_api_url: Option<WebAddress>,
1169 pub ingress_answer_bound: core::time::Duration,
1171 pub ingress_shared_secret: SharedSecret,
1173 pub api_credential: Option<ApiCredential>,
1177 pub api_credential_verifier: Option<CredentialVerifier>,
1181 pub camera_snapshot_url: Option<WebAddress>,
1183 pub obico_api: Option<ObicoApi>,
1185 pub spools: SpoolPolicy,
1187 pub sheets: SheetTable,
1189 pub recovery: Option<RecoveryConfig>,
1191 pub recovery_grants: RecoveryGrants,
1193}
1194
1195impl ServerConfig {
1196 pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
1207 let path = path.as_ref();
1208 Self::parse(&read(path)?, path)
1209 }
1210
1211 pub fn parse(text: &str, path: &Path) -> Result<Self, ConfigError> {
1217 let file: ConfigFile = toml::from_str(text).map_err(|error| ConfigError::Unparsable {
1218 path: path.to_path_buf(),
1219 detail: error.to_string(),
1220 })?;
1221 Self::validate(file)
1222 }
1223
1224 fn validate(file: ConfigFile) -> Result<Self, ConfigError> {
1231 let state_dir =
1232 state_directory(required(ConfigField::StateDir, file.state_dir)?.as_path())?;
1233 let listen = listen_address(&required(ConfigField::Listen, file.listen)?)?;
1234 let octoprint = octoprint(&file.octoprint)?;
1235 let safety = required(ConfigField::SafetyEnvelope, file.safety)?;
1236 check_envelope(&safety)?;
1237 let harness = harness_identity(file.supervisor.harness)?;
1238 let model = match file.supervisor.model {
1239 None => None,
1240 Some(name) => Some(
1241 ModelName::new(&named(ConfigField::Model, Some(name))?)
1242 .map_err(|error| ConfigError::about(ConfigField::Model, error.to_string()))?,
1243 ),
1244 };
1245 let skill_path = skill(file.supervisor.skill_path.as_deref())?;
1246 let prompt_template_path = readable(
1247 ConfigField::PromptTemplatePath,
1248 file.supervisor.prompt_template_path.as_deref(),
1249 )?;
1250 let observation_interval = observation_interval(file.supervisor.observation_interval_s)?;
1251 let printer_poll = seconds_within(
1252 ConfigField::PrinterPollS,
1253 file.supervisor.printer_poll_s,
1254 PRINTER_POLL_RANGE_S,
1255 )?;
1256 let unattended_window = seconds_within(
1257 ConfigField::UnattendedWindowS,
1258 file.supervisor.unattended_window_s,
1259 UNATTENDED_WINDOW_RANGE_S,
1260 )?;
1261 let blank_frame_max_stddev = blank_frame_bound(file.vision.blank_frame_max_stddev)?;
1262 let obico_ml_api_url = file
1263 .obico
1264 .ml_api_url
1265 .as_deref()
1266 .map(|url| web_address(ConfigField::ObicoMlApiUrl, url))
1267 .transpose()?;
1268 let ingress_answer_bound = answer_bound(file.ingress.answer_bound_ms)?;
1269 let ingress_shared_secret = SharedSecret::new(&required(
1270 ConfigField::IngressSharedSecret,
1271 file.ingress.shared_secret,
1272 )?)?;
1273 let api_credential = file
1274 .api
1275 .credential
1276 .as_deref()
1277 .map(|value| {
1278 ApiCredential::new(value)
1279 .map_err(|why| ConfigError::about(ConfigField::ApiCredential, why))
1280 })
1281 .transpose()?;
1282 let api_credential_verifier = file
1283 .api
1284 .credential_verifier
1285 .as_deref()
1286 .map(|value| {
1287 CredentialVerifier::parse(value.trim())
1288 .map_err(|why| ConfigError::about(ConfigField::ApiCredentialVerifier, why))
1289 })
1290 .transpose()?;
1291 let camera_snapshot_url = file
1292 .camera
1293 .snapshot_url
1294 .map(|url| web_address(ConfigField::CameraSnapshotUrl, &url))
1295 .transpose()?;
1296 let obico_api = obico_api(file.obico)?;
1297 let spools = spool_policy(&file.spools)?;
1298 let sheets = match file.sheets.allowed {
1299 None => SheetTable::default(),
1300 Some(entries) => SheetTable::new(entries)
1301 .map_err(|why| ConfigError::about(ConfigField::SheetsAllowed, why))?,
1302 };
1303 let recovery = recovery_facts(&file.recovery)?;
1304 let recovery_grants = recovery_grants(&file.policy.recovery)?;
1305 Ok(Self {
1306 state_dir,
1307 listen,
1308 octoprint,
1309 safety,
1310 harness,
1311 model,
1312 skill_path,
1313 prompt_template_path,
1314 observation_interval,
1315 printer_poll,
1316 unattended_window,
1317 blank_frame_max_stddev,
1318 obico_ml_api_url,
1319 ingress_answer_bound,
1320 ingress_shared_secret,
1321 api_credential,
1322 api_credential_verifier,
1323 camera_snapshot_url,
1324 obico_api,
1325 spools,
1326 sheets,
1327 recovery,
1328 recovery_grants,
1329 })
1330 }
1331
1332 #[must_use]
1336 pub fn assets_dir(&self) -> PathBuf {
1337 self.state_dir.join(ASSETS_DIRECTORY)
1338 }
1339}
1340
1341fn web_address(field: ConfigField, url: &str) -> Result<WebAddress, ConfigError> {
1344 WebAddress::new(url).map_err(|why| ConfigError::about(field, why))
1345}
1346
1347fn obico_api(section: ObicoSection) -> Result<Option<ObicoApi>, ConfigError> {
1353 match (section.url, section.access_token) {
1354 (None, None) => Ok(None),
1355 (Some(_), None) => Err(ConfigError::about(
1356 ConfigField::ObicoAccessToken,
1357 "it is required when obico.url is given",
1358 )),
1359 (None, Some(_)) => Err(ConfigError::about(
1360 ConfigField::ObicoUrl,
1361 "it is required when obico.access_token is given",
1362 )),
1363 (Some(url), Some(access_token)) => {
1364 let url = web_address(ConfigField::ObicoUrl, &url)?;
1365 let access_token = AccessToken::new(&access_token)
1366 .map_err(|why| ConfigError::about(ConfigField::ObicoAccessToken, why))?;
1367 Ok(Some(ObicoApi::new(url, access_token)))
1368 }
1369 }
1370}
1371
1372#[derive(Debug, Clone, PartialEq, Eq)]
1380pub struct SignInConfig {
1381 pub state_dir: PathBuf,
1383 pub harness: HarnessIdentity,
1385}
1386
1387impl SignInConfig {
1388 pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
1398 let path = path.as_ref();
1399 let file: SignInFile =
1400 toml::from_str(&read(path)?).map_err(|error| ConfigError::Unparsable {
1401 path: path.to_path_buf(),
1402 detail: error.to_string(),
1403 })?;
1404 Ok(Self {
1405 state_dir: state_directory(required(ConfigField::StateDir, file.state_dir)?.as_path())?,
1406 harness: harness_identity(file.supervisor.harness)?,
1407 })
1408 }
1409}
1410
1411#[derive(Deserialize)]
1416#[serde(crate = "printobserver_types::serde")]
1417struct SignInFile {
1418 #[serde(default)]
1420 state_dir: Option<PathBuf>,
1421 #[serde(default)]
1423 supervisor: SignInSupervisor,
1424}
1425
1426#[derive(Default, Deserialize)]
1428#[serde(crate = "printobserver_types::serde")]
1429struct SignInSupervisor {
1430 #[serde(default)]
1432 harness: Option<String>,
1433}
1434
1435fn read(path: &Path) -> Result<String, ConfigError> {
1437 std::fs::read_to_string(path).map_err(|error| ConfigError::Unreadable {
1438 path: path.to_path_buf(),
1439 detail: error.to_string(),
1440 })
1441}
1442
1443fn harness_identity(value: Option<String>) -> Result<HarnessIdentity, ConfigError> {
1445 HarnessIdentity::new(&named(ConfigField::Harness, value)?)
1446 .map_err(|error| ConfigError::about(ConfigField::Harness, error.to_string()))
1447}
1448
1449fn required<T>(field: ConfigField, value: Option<T>) -> Result<T, ConfigError> {
1451 value.ok_or_else(|| ConfigError::about(field, "the configuration file carries no value for it"))
1452}
1453
1454fn named(field: ConfigField, value: Option<String>) -> Result<String, ConfigError> {
1456 let value = required(field, value)?;
1457 if value.trim().is_empty() {
1458 return Err(ConfigError::about(
1459 field,
1460 "it is empty, and an empty value names nothing",
1461 ));
1462 }
1463 Ok(value.trim().to_owned())
1464}
1465
1466fn state_directory(named: &Path) -> Result<PathBuf, ConfigError> {
1468 if named.as_os_str().is_empty() {
1469 return Err(ConfigError::about(
1470 ConfigField::StateDir,
1471 "it names no directory, and this server's whole state lives in one",
1472 ));
1473 }
1474 std::fs::create_dir_all(named).map_err(|error| {
1475 ConfigError::about(
1476 ConfigField::StateDir,
1477 format!("{} cannot be created: {error}", named.display()),
1478 )
1479 })?;
1480 named.canonicalize().map(plainly_written).map_err(|error| {
1481 ConfigError::about(
1482 ConfigField::StateDir,
1483 format!("{} cannot be resolved: {error}", named.display()),
1484 )
1485 })
1486}
1487
1488#[must_use]
1497pub fn plainly_written(path: PathBuf) -> PathBuf {
1498 const VERBATIM: &str = r"\\?\";
1499 let drive = path
1500 .to_str()
1501 .and_then(|text| text.strip_prefix(VERBATIM))
1502 .filter(|rest| {
1503 let bytes = rest.as_bytes();
1504 bytes.len() >= 3
1505 && bytes[0].is_ascii_alphabetic()
1506 && bytes[1] == b':'
1507 && bytes[2] == b'\\'
1508 })
1509 .map(PathBuf::from);
1510 drive.unwrap_or(path)
1511}
1512
1513fn listen_address(named: &str) -> Result<SocketAddr, ConfigError> {
1515 named.trim().parse().map_err(|error| {
1516 ConfigError::about(
1517 ConfigField::Listen,
1518 format!("{named:?} is no address to listen on: {error}"),
1519 )
1520 })
1521}
1522
1523fn octoprint(section: &OctoprintSection) -> Result<OctoPrintConfig, ConfigError> {
1526 let fan = fan_support(§ion.fan)?;
1527 let url = named(ConfigField::OctoprintUrl, section.url.clone())?;
1528 let key = named(ConfigField::OctoprintApiKey, section.api_key.clone())?;
1529 OctoPrintConfig::new(&url, key)
1530 .map(|configured| configured.with_fan(fan))
1531 .map_err(|error| {
1532 let field = match error {
1533 printobserver_octoprint::ConfigError::EmptyApiKey => ConfigField::OctoprintApiKey,
1534 _ => ConfigField::OctoprintUrl,
1535 };
1536 ConfigError::about(field, error.to_string())
1537 })
1538}
1539
1540fn fan_support(named: &str) -> Result<FanSupport, ConfigError> {
1542 FAN_VOCABULARY
1543 .iter()
1544 .find(|(spelling, _)| *spelling == named.trim())
1545 .map(|(_, support)| *support)
1546 .ok_or_else(|| {
1547 let vocabulary: Vec<&str> = FAN_VOCABULARY.iter().map(|(word, _)| *word).collect();
1548 ConfigError::about(
1549 ConfigField::OctoprintFan,
1550 format!("{named:?} is not one of {}", vocabulary.join(" or ")),
1551 )
1552 })
1553}
1554
1555fn check_envelope(envelope: &SafetyEnvelope) -> Result<(), ConfigError> {
1557 if envelope.allowed.is_empty() {
1558 return Err(ConfigError::about(
1559 ConfigField::SafetyEnvelope,
1560 "it allows no adjustable at all, so no adjustment could ever be accepted",
1561 ));
1562 }
1563 for (adjustable, range) in &envelope.allowed {
1564 if !range.min.is_finite() || !range.max.is_finite() || range.min > range.max {
1565 return Err(ConfigError::about(
1566 ConfigField::SafetyEnvelope,
1567 format!(
1568 "the range allowed for {adjustable} runs from {} to {}, which admits \
1569 no value",
1570 range.min, range.max
1571 ),
1572 ));
1573 }
1574 }
1575 if envelope
1578 .actions
1579 .get(&ActorClass::Agent)
1580 .is_some_and(|granted| granted.contains(&ActionKind::ClosePrint))
1581 {
1582 return Err(ConfigError::about(
1583 ConfigField::SafetyEnvelope,
1584 "it grants `close_print` to the agent, and closing a print record is the \
1585 operator's judgement that the print is over",
1586 ));
1587 }
1588 if envelope.agent_min_interval_s < 0 {
1589 return Err(ConfigError::about(
1590 ConfigField::SafetyEnvelope,
1591 format!(
1592 "the agent's minimum interval is {}s, and an interval is a count of seconds",
1593 envelope.agent_min_interval_s
1594 ),
1595 ));
1596 }
1597 Ok(())
1598}
1599
1600fn readable(field: ConfigField, named: Option<&Path>) -> Result<Option<PathBuf>, ConfigError> {
1603 let Some(path) = named else {
1604 return Ok(None);
1605 };
1606 std::fs::read_to_string(path)
1607 .map(|_| Some(path.to_path_buf()))
1608 .map_err(|error| {
1609 ConfigError::about(field, format!("{} cannot be read: {error}", path.display()))
1610 })
1611}
1612
1613fn skill(named: Option<&Path>) -> Result<PathBuf, ConfigError> {
1616 let Some(path) = named else {
1617 return Err(ConfigError::about(
1618 ConfigField::SkillPath,
1619 format!(
1620 "the configuration file carries no value for it, and this program carries \
1621 no skill of its own: {SKILL_INSTALL}"
1622 ),
1623 ));
1624 };
1625 std::fs::read_to_string(path)
1626 .map(|_| path.to_path_buf())
1627 .map_err(|error| {
1628 ConfigError::about(
1629 ConfigField::SkillPath,
1630 format!(
1631 "{} cannot be read: {error}. {SKILL_INSTALL}",
1632 path.display()
1633 ),
1634 )
1635 })
1636}
1637
1638fn spool_policy(section: &SpoolsSection) -> Result<SpoolPolicy, ConfigError> {
1640 let defaults = SpoolPolicy::default();
1641 let preflight = match section.preflight.as_deref() {
1642 None => defaults.preflight,
1643 Some("refuse") => PreflightMode::Refuse,
1644 Some("warn") => PreflightMode::Warn,
1645 Some("off") => PreflightMode::Off,
1646 Some(_) => {
1647 return Err(ConfigError::about(
1648 ConfigField::SpoolsPreflight,
1649 "the spool check is one of `refuse`, `warn` or `off`",
1650 ));
1651 }
1652 };
1653 let margin = |field: ConfigField, value: Option<f64>, default: f64| match value {
1654 None => Ok(default),
1655 Some(value) if value.is_finite() && value >= 0.0 => Ok(value),
1656 Some(_) => Err(ConfigError::about(
1657 field,
1658 "a margin is a figure at or above zero; a negative one asks a spool for less \
1659 than the print needs",
1660 )),
1661 };
1662 let buffer_percent = margin(
1663 ConfigField::SpoolsBufferPercent,
1664 section.buffer_percent,
1665 defaults.buffer_percent,
1666 )?;
1667 let buffer_min_g = margin(
1668 ConfigField::SpoolsBufferMinG,
1669 section.buffer_min_g,
1670 defaults.buffer_min_g,
1671 )?;
1672 let analysis_wait_s = match section.analysis_wait_seconds {
1673 None => defaults.analysis_wait_s,
1674 Some(seconds) => u64::try_from(seconds).map_err(|_| {
1675 ConfigError::about(
1676 ConfigField::SpoolsAnalysisWaitSeconds,
1677 "a wait is a number of seconds at or above zero",
1678 )
1679 })?,
1680 };
1681 Ok(SpoolPolicy {
1682 preflight,
1683 buffer_percent,
1684 buffer_min_g,
1685 analysis_wait_s,
1686 })
1687}
1688
1689fn recovery_facts(section: &RecoverySection) -> Result<Option<RecoveryConfig>, ConfigError> {
1691 if *section == RecoverySection::default() {
1692 return Ok(None);
1693 }
1694 let absent = |field: ConfigField| {
1695 ConfigError::about(
1696 field,
1697 "`[recovery]` states this printer's facts, and this one is one of them",
1698 )
1699 };
1700 let away_from_bed = match section.away_from_bed.as_deref() {
1701 None => return Err(absent(ConfigField::RecoveryAwayFromBed)),
1702 Some("z_plus") => AwayFromBed::ZPlus,
1703 Some("z_minus") => AwayFromBed::ZMinus,
1704 Some(other) => {
1705 return Err(ConfigError::about(
1706 ConfigField::RecoveryAwayFromBed,
1707 format!("{other:?} is neither `z_plus` nor `z_minus`"),
1708 ));
1709 }
1710 };
1711 let max_z_mm = section
1712 .max_z_mm
1713 .ok_or_else(|| absent(ConfigField::RecoveryMaxZMm))?;
1714 if !(max_z_mm.is_finite() && max_z_mm > 0.0) {
1715 return Err(ConfigError::about(
1716 ConfigField::RecoveryMaxZMm,
1717 format!("{max_z_mm} mm is no height a machine reaches; it is a figure above zero"),
1718 ));
1719 }
1720 let max_lift_mm = section
1721 .max_lift_mm
1722 .unwrap_or_else(|| DEFAULT_MAX_LIFT_MM.min(max_z_mm));
1723 if !(max_lift_mm.is_finite() && max_lift_mm > 0.0 && max_lift_mm <= max_z_mm) {
1724 return Err(ConfigError::about(
1725 ConfigField::RecoveryMaxLiftMm,
1726 format!(
1727 "{max_lift_mm} mm is outside the lifts a machine of {max_z_mm} mm makes: above \
1728 zero, and at most `recovery.max_z_mm`"
1729 ),
1730 ));
1731 }
1732 let clearance_margin_mm = section
1733 .clearance_margin_mm
1734 .unwrap_or(DEFAULT_CLEARANCE_MARGIN_MM);
1735 if !(clearance_margin_mm.is_finite()
1736 && clearance_margin_mm >= 0.0
1737 && clearance_margin_mm < max_z_mm)
1738 {
1739 return Err(ConfigError::about(
1740 ConfigField::RecoveryClearanceMarginMm,
1741 format!(
1742 "{clearance_margin_mm} mm is outside the margins a machine of {max_z_mm} mm \
1743 admits: at or above zero, and below `recovery.max_z_mm`"
1744 ),
1745 ));
1746 }
1747 let place = |field: ConfigField, written: Option<&Vec<f64>>| match written.map(Vec::as_slice) {
1748 None => Err(absent(field)),
1749 Some([x, y]) if x.is_finite() && y.is_finite() && *x >= 0.0 && *y >= 0.0 => Ok([*x, *y]),
1750 Some(_) => Err(ConfigError::about(
1751 field,
1752 "a place is `[x, y]`, two figures in millimetres at or above zero",
1753 )),
1754 };
1755 let park_xy = place(ConfigField::RecoveryParkXy, section.park_xy.as_ref())?;
1756 let z_home_xy = place(ConfigField::RecoveryZHomeXy, section.z_home_xy.as_ref())?;
1757 let z_home_sweeps_bed = section
1758 .z_home_sweeps_bed
1759 .ok_or_else(|| absent(ConfigField::RecoveryZHomeSweepsBed))?;
1760 Ok(Some(RecoveryConfig {
1761 away_from_bed,
1762 max_z_mm,
1763 max_lift_mm,
1764 clearance_margin_mm,
1765 park_xy,
1766 z_home_xy,
1767 z_home_sweeps_bed,
1768 }))
1769}
1770
1771fn recovery_grants(section: &RecoveryPolicySection) -> Result<RecoveryGrants, ConfigError> {
1774 let defaults = RecoveryGrants::default();
1775 let actions = |field: ConfigField, written: Option<&Vec<String>>, default: Vec<_>| {
1776 let Some(written) = written else {
1777 return Ok(default);
1778 };
1779 written
1780 .iter()
1781 .map(|name| {
1782 RecoveryActionKind::ALL
1783 .iter()
1784 .find(|kind| kind.as_str() == name.trim())
1785 .copied()
1786 .ok_or_else(|| {
1787 ConfigError::about(
1788 field,
1789 format!("{name:?} is not a recovery action of this program"),
1790 )
1791 })
1792 })
1793 .collect::<Result<Vec<_>, _>>()
1794 };
1795 let operator = actions(
1796 ConfigField::PolicyRecoveryOperator,
1797 section.operator.as_ref(),
1798 defaults.operator,
1799 )?;
1800 let agent = actions(
1801 ConfigField::PolicyRecoveryAgent,
1802 section.agent.as_ref(),
1803 defaults.agent,
1804 )?;
1805 if agent.contains(&RecoveryActionKind::RecoverHomeZ) {
1808 return Err(ConfigError::about(
1809 ConfigField::PolicyRecoveryAgent,
1810 "it grants `recover_home_z` to the agent, and only a person at the machine can \
1811 say the bed is clear for Z to be homed",
1812 ));
1813 }
1814 let asserting = match section.asserting.as_ref() {
1815 None => defaults.asserting,
1816 Some(written) => written
1817 .iter()
1818 .map(|class| match class.trim() {
1819 "operator" => Ok(ActorClass::Operator),
1820 "agent" => Err(ConfigError::about(
1823 ConfigField::PolicyRecoveryAsserting,
1824 "it lets the agent assert clearance, and an assertion is a person's word \
1825 for what they can see at the machine",
1826 )),
1827 other => Err(ConfigError::about(
1828 ConfigField::PolicyRecoveryAsserting,
1829 format!("{other:?} is not an actor whose word can count; only `operator` is"),
1830 )),
1831 })
1832 .collect::<Result<Vec<_>, _>>()?,
1833 };
1834 Ok(RecoveryGrants {
1835 operator,
1836 agent,
1837 asserting,
1838 })
1839}
1840
1841fn observation_interval(seconds: u64) -> Result<core::time::Duration, ConfigError> {
1843 if seconds == 0 {
1844 return Err(ConfigError::about(
1845 ConfigField::ObservationIntervalS,
1846 "an interval of zero seconds observes a print again the moment its last turn \
1847 returns, which is a turn that never ends",
1848 ));
1849 }
1850 Ok(core::time::Duration::from_secs(seconds))
1851}
1852
1853fn seconds_within(
1855 field: ConfigField,
1856 seconds: u64,
1857 range: (u64, u64),
1858) -> Result<core::time::Duration, ConfigError> {
1859 let (least, most) = range;
1860 if !(least..=most).contains(&seconds) {
1861 return Err(ConfigError::about(
1862 field,
1863 format!("{seconds} seconds is outside the {least} to {most} seconds it admits"),
1864 ));
1865 }
1866 Ok(core::time::Duration::from_secs(seconds))
1867}
1868
1869fn blank_frame_bound(written: Option<f64>) -> Result<BlankFrameBound, ConfigError> {
1871 written.map_or(Ok(BlankFrameBound::DEFAULT), |bound| {
1872 BlankFrameBound::new(bound).map_err(|refused| {
1873 ConfigError::about(
1874 ConfigField::VisionBlankFrameMaxStddev,
1875 format!(
1876 "{refused} is outside the {MIN_BLANK_FRAME_MAX_STDDEV} to \
1877 {MAX_BLANK_FRAME_MAX_STDDEV} grey levels it admits"
1878 ),
1879 )
1880 })
1881 })
1882}
1883
1884fn answer_bound(milliseconds: u64) -> Result<core::time::Duration, ConfigError> {
1886 if milliseconds == 0 {
1887 return Err(ConfigError::about(
1888 ConfigField::IngressAnswerBoundMs,
1889 "a bound of zero is an ingress that has run out of time before it starts",
1890 ));
1891 }
1892 if milliseconds >= OBICO_POSTING_TIMEOUT_MS {
1893 return Err(ConfigError::about(
1894 ConfigField::IngressAnswerBoundMs,
1895 format!(
1896 "{milliseconds}ms is not below the {OBICO_POSTING_TIMEOUT_MS}ms Obico posts \
1897 under, so an alert answered at that bound is one Obico has already \
1898 abandoned — and its posting does not retry"
1899 ),
1900 ));
1901 }
1902 Ok(core::time::Duration::from_millis(milliseconds))
1903}
1904
1905#[cfg(test)]
1906mod tests {
1907 use super::CredentialVerifier;
1908
1909 const ABC: &str = "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
1911
1912 #[test]
1915 fn a_verifier_is_the_credentials_sha256_and_admits_only_it() {
1916 let verifier = CredentialVerifier::of("abc");
1917
1918 assert_eq!(verifier.to_string(), ABC);
1919 assert_eq!(CredentialVerifier::parse(ABC), Ok(verifier.clone()));
1920 assert!(verifier.admits(b"abc"));
1921 assert!(!verifier.admits(b"abd"));
1922 assert!(!verifier.admits(b""));
1923 }
1924
1925 #[test]
1927 fn a_verifier_in_any_other_spelling_is_refused() {
1928 for refused in [
1929 "",
1930 "sha256:",
1931 &ABC[..ABC.len() - 1],
1932 &format!("{ABC}0"),
1933 &ABC.to_uppercase(),
1934 &ABC.replace("sha256:", "sha512:"),
1935 &ABC.replace("sha256:", ""),
1936 &ABC.replace('a', "g"),
1937 ] {
1938 assert!(
1939 CredentialVerifier::parse(refused).is_err(),
1940 "{refused:?} was accepted"
1941 );
1942 }
1943 }
1944}