1use 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
87pub const DEFAULT_INGRESS_ANSWER_BOUND_MS: u64 = 1_000;
94
95pub const DEFAULT_OBSERVATION_INTERVAL_S: u64 =
98 printobserver_core::DEFAULT_OBSERVATION_INTERVAL.as_secs();
99
100pub const OBICO_POSTING_TIMEOUT_MS: u64 = 5_000;
109
110pub const ASSETS_DIRECTORY: &str = "assets";
115
116pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
133pub enum ConfigField {
134 StateDir,
136 Listen,
138 OctoprintUrl,
140 OctoprintApiKey,
142 OctoprintFan,
144 SafetyEnvelope,
146 Harness,
148 Model,
150 SkillPath,
152 PromptTemplatePath,
154 ObservationIntervalS,
156 IngressAnswerBoundMs,
158 IngressSharedSecret,
160 ApiCredential,
163 ApiCredentialVerifier,
165 CameraSnapshotUrl,
168 ObicoUrl,
170 ObicoAccessToken,
172 SpoolsPreflight,
174 SpoolsBufferPercent,
176 SpoolsBufferMinG,
178 SpoolsAnalysisWaitSeconds,
180}
181
182impl ConfigField {
183 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 #[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#[derive(Debug, Clone, PartialEq, Eq)]
250pub enum ConfigError {
251 Unreadable {
253 path: PathBuf,
255 detail: String,
257 },
258 Unparsable {
260 path: PathBuf,
262 detail: String,
264 },
265 Field {
267 field: ConfigField,
269 detail: String,
271 },
272}
273
274impl ConfigError {
275 #[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 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#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
328 pub url: Option<String>,
329 #[serde(default, skip_serializing_if = "Option::is_none")]
331 pub api_key: Option<String>,
332 #[serde(default = "commandable")]
334 pub fan: String,
335}
336
337pub const FAN_VOCABULARY: [(&str, FanSupport); 2] = [
340 ("commandable", FanSupport::Commandable),
341 ("absent", FanSupport::Absent),
342];
343
344fn 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#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
370 pub harness: Option<String>,
371 #[serde(default, skip_serializing_if = "Option::is_none")]
373 pub model: Option<String>,
374 #[serde(default, skip_serializing_if = "Option::is_none")]
378 pub skill_path: Option<PathBuf>,
379 #[serde(default, skip_serializing_if = "Option::is_none")]
382 pub prompt_template_path: Option<PathBuf>,
383 #[serde(default = "default_observation_interval_s")]
386 pub observation_interval_s: u64,
387}
388
389const 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#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
417 pub shared_secret: Option<String>,
418 #[serde(default = "default_answer_bound_ms")]
420 pub answer_bound_ms: u64,
421}
422
423const 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#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
450 pub credential: Option<String>,
451 #[serde(default, skip_serializing_if = "Option::is_none")]
457 pub credential_verifier: Option<String>,
458}
459
460#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
472 pub snapshot_url: Option<String>,
473}
474
475#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
489 pub url: Option<String>,
490 #[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#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
527 pub preflight: Option<String>,
528 #[serde(default, skip_serializing_if = "Option::is_none")]
530 pub buffer_percent: Option<f64>,
531 #[serde(default, skip_serializing_if = "Option::is_none")]
533 pub buffer_min_g: Option<f64>,
534 #[serde(default, skip_serializing_if = "Option::is_none")]
537 pub analysis_wait_seconds: Option<i64>,
538}
539
540#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
555 pub state_dir: Option<PathBuf>,
556 #[serde(default, skip_serializing_if = "Option::is_none")]
558 pub listen: Option<String>,
559 #[serde(default)]
561 pub octoprint: OctoprintSection,
562 #[serde(default, skip_serializing_if = "Option::is_none")]
564 pub safety: Option<SafetyEnvelope>,
565 #[serde(default)]
567 pub supervisor: SupervisorSection,
568 #[serde(default)]
570 pub ingress: IngressSection,
571 #[serde(default)]
573 pub api: ApiSection,
574 #[serde(default)]
576 pub camera: CameraSection,
577 #[serde(default)]
579 pub obico: ObicoSection,
580 #[serde(default)]
582 pub spools: SpoolsSection,
583}
584
585#[derive(Clone, PartialEq, Eq)]
592pub struct SharedSecret(String);
593
594pub const REDACTED: &str = "<redacted>";
596
597impl SharedSecret {
598 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 #[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
648pub const GENERATED_CREDENTIAL_BYTES: usize = 32;
650
651#[derive(Clone)]
661pub struct ApiCredential(String);
662
663impl ApiCredential {
664 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 Ok(Self(value.to_owned()))
691 }
692
693 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 #[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 #[must_use]
728 pub fn written(&self) -> &str {
729 &self.0
730 }
731
732 #[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
759pub const VERIFIER_PREFIX: &str = "sha256:";
761
762const VERIFIER_DIGITS: usize = 64;
764
765#[derive(Clone, PartialEq, Eq)]
776pub struct CredentialVerifier([u8; 32]);
777
778impl CredentialVerifier {
779 #[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 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 #[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
827const 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#[derive(Debug, Clone, PartialEq)]
861pub struct ServerConfig {
862 pub state_dir: PathBuf,
864 pub listen: SocketAddr,
866 pub octoprint: OctoPrintConfig,
868 pub safety: SafetyEnvelope,
870 pub harness: HarnessIdentity,
872 pub model: Option<ModelName>,
874 pub skill_path: PathBuf,
878 pub prompt_template_path: Option<PathBuf>,
880 pub observation_interval: core::time::Duration,
882 pub ingress_answer_bound: core::time::Duration,
884 pub ingress_shared_secret: SharedSecret,
886 pub api_credential: Option<ApiCredential>,
890 pub api_credential_verifier: Option<CredentialVerifier>,
894 pub camera_snapshot_url: Option<WebAddress>,
896 pub obico_api: Option<ObicoApi>,
898 pub spools: SpoolPolicy,
900}
901
902impl ServerConfig {
903 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 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 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 #[must_use]
1012 pub fn assets_dir(&self) -> PathBuf {
1013 self.state_dir.join(ASSETS_DIRECTORY)
1014 }
1015}
1016
1017fn web_address(field: ConfigField, url: &str) -> Result<WebAddress, ConfigError> {
1020 WebAddress::new(url).map_err(|why| ConfigError::about(field, why))
1021}
1022
1023fn 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#[derive(Debug, Clone, PartialEq, Eq)]
1056pub struct SignInConfig {
1057 pub state_dir: PathBuf,
1059 pub harness: HarnessIdentity,
1061}
1062
1063impl SignInConfig {
1064 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#[derive(Deserialize)]
1092#[serde(crate = "printobserver_types::serde")]
1093struct SignInFile {
1094 #[serde(default)]
1096 state_dir: Option<PathBuf>,
1097 #[serde(default)]
1099 supervisor: SignInSupervisor,
1100}
1101
1102#[derive(Default, Deserialize)]
1104#[serde(crate = "printobserver_types::serde")]
1105struct SignInSupervisor {
1106 #[serde(default)]
1108 harness: Option<String>,
1109}
1110
1111fn 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
1119fn 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
1125fn 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
1130fn 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
1142fn 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#[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
1189fn 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
1199fn octoprint(section: &OctoprintSection) -> Result<OctoPrintConfig, ConfigError> {
1202 let fan = fan_support(§ion.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
1216fn 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
1231fn 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
1263fn 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
1276fn 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
1301fn 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
1352fn 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
1364fn 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 const ABC: &str = "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
1391
1392 #[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 #[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}