use core::num::NonZeroU64;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use printobserver_core::{
ActionKind, ActorClass, AwayFromBed, DEFAULT_CLEARANCE_MARGIN_MM, DEFAULT_MAX_LIFT_MM,
PreflightMode, RecoveryActionKind, RecoveryConfig, RecoveryGrants, SafetyEnvelope, SheetTable,
SpoolPolicy,
};
use printobserver_obico::{
AccessToken, BlankFrameBound, MAX_BLANK_FRAME_MAX_STDDEV, MIN_BLANK_FRAME_MAX_STDDEV, ObicoApi,
ObicoPrinterId,
};
use printobserver_octoprint::{FanSupport, OctoPrintConfig};
use printobserver_oneharness::{HarnessIdentity, ModelName};
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};
use printobserver_vision_api::WebAddress;
pub const DEFAULT_INGRESS_ANSWER_BOUND_MS: u64 = 1_000;
pub const DEFAULT_OBSERVATION_INTERVAL_S: u64 =
printobserver_core::DEFAULT_OBSERVATION_INTERVAL.as_secs();
pub const DEFAULT_PRINTER_POLL_S: u64 = printobserver_core::DEFAULT_PRINTER_POLL.as_secs();
pub const PRINTER_POLL_RANGE_S: (u64, u64) = (5, 300);
pub const DEFAULT_UNATTENDED_WINDOW_S: u64 =
printobserver_core::DEFAULT_UNATTENDED_WINDOW.as_secs();
pub const UNATTENDED_WINDOW_RANGE_S: (u64, u64) = (60, 86_400);
pub const DEFAULT_CHECK_TURN_TIMEOUT_S: u64 = 120;
pub const CHECK_TURN_TIMEOUT_RANGE_S: (u64, u64) = (1, 900);
pub const OBICO_POSTING_TIMEOUT_MS: u64 = 5_000;
pub const ASSETS_DIRECTORY: &str = "assets";
pub const SKILL_INSTALL: &str = "the skill is installed with `gh skill install \
nickderobertis/printobserver printobserver --dir <dir>`, and \
`supervisor.skill_path` names the installed `SKILL.md`, \
`<dir>/printobserver/SKILL.md`";
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ConfigField {
StateDir,
Listen,
OctoprintUrl,
OctoprintApiKey,
OctoprintFan,
SafetyEnvelope,
Harness,
Model,
SkillPath,
PromptTemplatePath,
ObservationIntervalS,
PrinterPollS,
UnattendedWindowS,
AutoCompactTokens,
IdleCompactTokens,
CheckTurnTimeoutS,
IngressAnswerBoundMs,
IngressSharedSecret,
ApiCredential,
ApiCredentialVerifier,
CameraSnapshotUrl,
CameraCalibration,
ObicoUrl,
ObicoAccessToken,
ObicoMlApiUrl,
ObicoPrinterId,
VisionBlankFrameMaxStddev,
SpoolsPreflight,
SpoolsBufferPercent,
SpoolsBufferMinG,
SpoolsAnalysisWaitSeconds,
SheetsAllowed,
RecoveryAwayFromBed,
RecoveryMaxZMm,
RecoveryMaxLiftMm,
RecoveryClearanceMarginMm,
RecoveryParkXy,
RecoveryZHomeXy,
RecoveryZHomeSweepsBed,
PolicyRecoveryOperator,
PolicyRecoveryAgent,
PolicyRecoveryAsserting,
}
impl ConfigField {
pub const ALL: [Self; 42] = [
Self::StateDir,
Self::Listen,
Self::OctoprintUrl,
Self::OctoprintApiKey,
Self::OctoprintFan,
Self::SafetyEnvelope,
Self::Harness,
Self::Model,
Self::SkillPath,
Self::PromptTemplatePath,
Self::ObservationIntervalS,
Self::PrinterPollS,
Self::UnattendedWindowS,
Self::AutoCompactTokens,
Self::IdleCompactTokens,
Self::CheckTurnTimeoutS,
Self::IngressAnswerBoundMs,
Self::IngressSharedSecret,
Self::ApiCredential,
Self::ApiCredentialVerifier,
Self::CameraSnapshotUrl,
Self::CameraCalibration,
Self::ObicoUrl,
Self::ObicoAccessToken,
Self::ObicoMlApiUrl,
Self::ObicoPrinterId,
Self::VisionBlankFrameMaxStddev,
Self::SpoolsPreflight,
Self::SpoolsBufferPercent,
Self::SpoolsBufferMinG,
Self::SpoolsAnalysisWaitSeconds,
Self::SheetsAllowed,
Self::RecoveryAwayFromBed,
Self::RecoveryMaxZMm,
Self::RecoveryMaxLiftMm,
Self::RecoveryClearanceMarginMm,
Self::RecoveryParkXy,
Self::RecoveryZHomeXy,
Self::RecoveryZHomeSweepsBed,
Self::PolicyRecoveryOperator,
Self::PolicyRecoveryAgent,
Self::PolicyRecoveryAsserting,
];
#[must_use]
pub const fn key(self) -> &'static str {
match self {
Self::StateDir => "state_dir",
Self::Listen => "listen",
Self::OctoprintUrl => "octoprint.url",
Self::OctoprintApiKey => "octoprint.api_key",
Self::OctoprintFan => "octoprint.fan",
Self::SafetyEnvelope => "safety",
Self::Harness => "supervisor.harness",
Self::Model => "supervisor.model",
Self::SkillPath => "supervisor.skill_path",
Self::PromptTemplatePath => "supervisor.prompt_template_path",
Self::ObservationIntervalS => "supervisor.observation_interval_s",
Self::PrinterPollS => "supervisor.printer_poll_s",
Self::UnattendedWindowS => "supervisor.unattended_window_s",
Self::AutoCompactTokens => "supervisor.auto_compact_tokens",
Self::IdleCompactTokens => "supervisor.idle_compact_tokens",
Self::CheckTurnTimeoutS => "supervisor.check_turn_timeout_s",
Self::IngressAnswerBoundMs => "ingress.answer_bound_ms",
Self::IngressSharedSecret => "ingress.shared_secret",
Self::ApiCredential => "api.credential",
Self::ApiCredentialVerifier => "api.credential_verifier",
Self::CameraSnapshotUrl => "camera.snapshot_url",
Self::CameraCalibration => "camera.calibration",
Self::ObicoUrl => "obico.url",
Self::ObicoAccessToken => "obico.access_token",
Self::ObicoMlApiUrl => "obico.ml_api_url",
Self::ObicoPrinterId => "obico.printer_id",
Self::VisionBlankFrameMaxStddev => "vision.blank_frame_max_stddev",
Self::SpoolsPreflight => "spools.preflight",
Self::SpoolsBufferPercent => "spools.buffer_percent",
Self::SpoolsBufferMinG => "spools.buffer_min_g",
Self::SpoolsAnalysisWaitSeconds => "spools.analysis_wait_seconds",
Self::SheetsAllowed => "sheets.allowed",
Self::RecoveryAwayFromBed => "recovery.away_from_bed",
Self::RecoveryMaxZMm => "recovery.max_z_mm",
Self::RecoveryMaxLiftMm => "recovery.max_lift_mm",
Self::RecoveryClearanceMarginMm => "recovery.clearance_margin_mm",
Self::RecoveryParkXy => "recovery.park_xy",
Self::RecoveryZHomeXy => "recovery.z_home_xy",
Self::RecoveryZHomeSweepsBed => "recovery.z_home_sweeps_bed",
Self::PolicyRecoveryOperator => "policy.recovery.operator",
Self::PolicyRecoveryAgent => "policy.recovery.agent",
Self::PolicyRecoveryAsserting => "policy.recovery.asserting",
}
}
}
impl core::fmt::Display for ConfigField {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
formatter.write_str(self.key())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConfigError {
Unreadable {
path: PathBuf,
detail: String,
},
Unparsable {
path: PathBuf,
detail: String,
},
Field {
field: ConfigField,
detail: String,
},
}
impl ConfigError {
#[must_use]
pub const fn field(&self) -> Option<ConfigField> {
match self {
Self::Field { field, .. } => Some(*field),
_ => None,
}
}
pub(crate) fn about(field: ConfigField, detail: impl Into<String>) -> Self {
Self::Field {
field,
detail: detail.into(),
}
}
}
impl core::fmt::Display for ConfigError {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Unreadable { path, detail } => write!(
formatter,
"the configuration file {} could not be read: {detail}",
path.display()
),
Self::Unparsable { path, detail } => write!(
formatter,
"the configuration file {} could not be read as this program's \
configuration: {detail}",
path.display()
),
Self::Field { field, detail } => write!(
formatter,
"the configuration field `{field}` cannot be accepted: {detail}"
),
}
}
}
impl core::error::Error for ConfigError {}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(
crate = "printobserver_types::serde",
deny_unknown_fields,
rename_all = "snake_case"
)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct OctoprintSection {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub api_key: Option<String>,
#[serde(default = "commandable")]
pub fan: String,
}
pub const FAN_VOCABULARY: [(&str, FanSupport); 2] = [
("commandable", FanSupport::Commandable),
("absent", FanSupport::Absent),
];
fn commandable() -> String {
FAN_VOCABULARY[0].0.to_owned()
}
impl Default for OctoprintSection {
fn default() -> Self {
Self {
url: None,
api_key: None,
fan: commandable(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(
crate = "printobserver_types::serde",
deny_unknown_fields,
rename_all = "snake_case"
)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct SupervisorSection {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub harness: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub model: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub skill_path: Option<PathBuf>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub prompt_template_path: Option<PathBuf>,
#[serde(default = "default_observation_interval_s")]
pub observation_interval_s: u64,
#[serde(default = "default_printer_poll_s")]
pub printer_poll_s: u64,
#[serde(default = "default_unattended_window_s")]
pub unattended_window_s: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub auto_compact_tokens: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub idle_compact_tokens: Option<i64>,
#[serde(default = "default_check_turn_timeout_s")]
pub check_turn_timeout_s: u64,
}
const fn default_check_turn_timeout_s() -> u64 {
DEFAULT_CHECK_TURN_TIMEOUT_S
}
const fn default_printer_poll_s() -> u64 {
DEFAULT_PRINTER_POLL_S
}
const fn default_unattended_window_s() -> u64 {
DEFAULT_UNATTENDED_WINDOW_S
}
const fn default_observation_interval_s() -> u64 {
DEFAULT_OBSERVATION_INTERVAL_S
}
impl Default for SupervisorSection {
fn default() -> Self {
Self {
harness: None,
model: None,
skill_path: None,
prompt_template_path: None,
observation_interval_s: DEFAULT_OBSERVATION_INTERVAL_S,
printer_poll_s: DEFAULT_PRINTER_POLL_S,
unattended_window_s: DEFAULT_UNATTENDED_WINDOW_S,
auto_compact_tokens: None,
idle_compact_tokens: None,
check_turn_timeout_s: DEFAULT_CHECK_TURN_TIMEOUT_S,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(
crate = "printobserver_types::serde",
deny_unknown_fields,
rename_all = "snake_case"
)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct IngressSection {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub shared_secret: Option<String>,
#[serde(default = "default_answer_bound_ms")]
pub answer_bound_ms: u64,
}
const fn default_answer_bound_ms() -> u64 {
DEFAULT_INGRESS_ANSWER_BOUND_MS
}
impl Default for IngressSection {
fn default() -> Self {
Self {
shared_secret: None,
answer_bound_ms: DEFAULT_INGRESS_ANSWER_BOUND_MS,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
#[serde(
crate = "printobserver_types::serde",
deny_unknown_fields,
rename_all = "snake_case"
)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct ApiSection {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub credential: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub credential_verifier: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
#[serde(
crate = "printobserver_types::serde",
deny_unknown_fields,
rename_all = "snake_case"
)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct CameraSection {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub snapshot_url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub calibration: Option<PathBuf>,
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
#[serde(
crate = "printobserver_types::serde",
deny_unknown_fields,
rename_all = "snake_case"
)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct ObicoSection {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub access_token: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ml_api_url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub printer_id: Option<i64>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Default)]
#[serde(
crate = "printobserver_types::serde",
deny_unknown_fields,
rename_all = "snake_case"
)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct VisionSection {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub blank_frame_max_stddev: Option<f64>,
}
impl core::fmt::Debug for ObicoSection {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
formatter
.debug_struct("ObicoSection")
.field("url", &self.url)
.field(
"access_token",
&self.access_token.as_ref().map(|_| REDACTED),
)
.field("ml_api_url", &self.ml_api_url)
.field("printer_id", &self.printer_id)
.finish()
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Default)]
#[serde(
crate = "printobserver_types::serde",
deny_unknown_fields,
rename_all = "snake_case"
)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct SpoolsSection {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub preflight: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub buffer_percent: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub buffer_min_g: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub analysis_wait_seconds: Option<i64>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
#[serde(
crate = "printobserver_types::serde",
deny_unknown_fields,
rename_all = "snake_case"
)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct SheetsSection {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub allowed: Option<std::collections::BTreeMap<String, Vec<String>>>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema, Default)]
#[serde(
crate = "printobserver_types::serde",
deny_unknown_fields,
rename_all = "snake_case"
)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct RecoverySection {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub away_from_bed: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_z_mm: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_lift_mm: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub clearance_margin_mm: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub park_xy: Option<Vec<f64>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub z_home_xy: Option<Vec<f64>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub z_home_sweeps_bed: Option<bool>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
#[serde(
crate = "printobserver_types::serde",
deny_unknown_fields,
rename_all = "snake_case"
)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct RecoveryPolicySection {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operator: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub agent: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub asserting: Option<Vec<String>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
#[serde(
crate = "printobserver_types::serde",
deny_unknown_fields,
rename_all = "snake_case"
)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct PolicySection {
#[serde(default)]
pub recovery: RecoveryPolicySection,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(
crate = "printobserver_types::serde",
deny_unknown_fields,
rename_all = "snake_case"
)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct ConfigFile {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub state_dir: Option<PathBuf>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub listen: Option<String>,
#[serde(default)]
pub octoprint: OctoprintSection,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub safety: Option<SafetyEnvelope>,
#[serde(default)]
pub supervisor: SupervisorSection,
#[serde(default)]
pub ingress: IngressSection,
#[serde(default)]
pub api: ApiSection,
#[serde(default)]
pub camera: CameraSection,
#[serde(default)]
pub obico: ObicoSection,
#[serde(default)]
pub vision: VisionSection,
#[serde(default)]
pub spools: SpoolsSection,
#[serde(default)]
pub sheets: SheetsSection,
#[serde(default)]
pub recovery: RecoverySection,
#[serde(default)]
pub policy: PolicySection,
}
#[derive(Clone, PartialEq, Eq)]
pub struct SharedSecret(String);
pub const REDACTED: &str = "<redacted>";
impl SharedSecret {
pub fn new(value: &str) -> Result<Self, ConfigError> {
if value.trim().is_empty() {
return Err(ConfigError::about(
ConfigField::IngressSharedSecret,
"it is empty, and anything that can post to the ingress can pause a printer",
));
}
Ok(Self(value.to_owned()))
}
#[must_use]
pub fn matches(&self, offered: Option<&str>) -> bool {
let Some(offered) = offered else {
return false;
};
let expected = self.0.as_bytes();
let mut difference = expected.len() ^ offered.len();
for (index, byte) in offered.bytes().enumerate() {
let against = expected[index % expected.len().max(1)];
difference |= usize::from(byte ^ against);
}
difference == 0
}
}
impl core::fmt::Display for SharedSecret {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
formatter.write_str(REDACTED)
}
}
impl core::fmt::Debug for SharedSecret {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(formatter, "SharedSecret({REDACTED})")
}
}
pub const GENERATED_CREDENTIAL_BYTES: usize = 32;
#[derive(Clone)]
pub struct ApiCredential(String);
impl ApiCredential {
pub fn new(value: &str) -> Result<Self, &'static str> {
if value.trim().is_empty() {
return Err(
"it is empty, and anything that can reach this server's API can command a printer",
);
}
if !value.bytes().all(|byte| (b' '..=b'~').contains(&byte)) {
return Err(
"it carries a control character or a character outside printable ASCII, which \
no `Authorization` header carries intact",
);
}
if value.starts_with(' ') || value.ends_with(' ') {
return Err(
"it begins or ends with a space, which an `Authorization` header does not carry",
);
}
Ok(Self(value.to_owned()))
}
pub fn generate() -> Result<Self, getrandom::Error> {
use base64::Engine as _;
let mut drawn = [0_u8; GENERATED_CREDENTIAL_BYTES];
getrandom::fill(&mut drawn)?;
Ok(Self(
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(drawn),
))
}
#[must_use]
pub fn admits(&self, presented: &[u8]) -> bool {
use subtle::ConstantTimeEq as _;
let expected = self.0.as_bytes();
expected.len() == presented.len() && bool::from(expected.ct_eq(presented))
}
#[must_use]
pub fn written(&self) -> &str {
&self.0
}
#[must_use]
pub fn verifier(&self) -> CredentialVerifier {
CredentialVerifier::of(&self.0)
}
}
impl PartialEq for ApiCredential {
fn eq(&self, other: &Self) -> bool {
self.admits(other.0.as_bytes())
}
}
impl Eq for ApiCredential {}
impl core::fmt::Display for ApiCredential {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
formatter.write_str(REDACTED)
}
}
impl core::fmt::Debug for ApiCredential {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(formatter, "ApiCredential({REDACTED})")
}
}
pub const VERIFIER_PREFIX: &str = "sha256:";
const VERIFIER_DIGITS: usize = 64;
#[derive(Clone, PartialEq, Eq)]
pub struct CredentialVerifier([u8; 32]);
impl CredentialVerifier {
#[must_use]
pub fn of(credential: &str) -> Self {
use sha2::Digest as _;
Self(sha2::Sha256::digest(credential.as_bytes()).into())
}
pub fn parse(text: &str) -> Result<Self, &'static str> {
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";
let digits = text.strip_prefix(VERIFIER_PREFIX).ok_or(SHAPE)?;
if digits.len() != VERIFIER_DIGITS
|| !digits
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
{
return Err(SHAPE);
}
let mut digest = [0_u8; 32];
for (index, pair) in digits.as_bytes().chunks(2).enumerate() {
let high = hex_value(pair[0]);
let low = hex_value(pair[1]);
digest[index] = (high << 4) | low;
}
Ok(Self(digest))
}
#[must_use]
pub fn admits(&self, presented: &[u8]) -> bool {
use sha2::Digest as _;
use subtle::ConstantTimeEq as _;
let offered: [u8; 32] = sha2::Sha256::digest(presented).into();
bool::from(self.0.ct_eq(&offered))
}
}
const fn hex_value(digit: u8) -> u8 {
if digit.is_ascii_digit() {
digit - b'0'
} else {
digit - b'a' + 10
}
}
impl core::fmt::Display for CredentialVerifier {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
formatter.write_str(VERIFIER_PREFIX)?;
for byte in self.0 {
write!(formatter, "{byte:02x}")?;
}
Ok(())
}
}
impl core::fmt::Debug for CredentialVerifier {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(formatter, "CredentialVerifier({self})")
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ServerConfig {
pub state_dir: PathBuf,
pub listen: SocketAddr,
pub octoprint: OctoPrintConfig,
pub safety: SafetyEnvelope,
pub harness: HarnessIdentity,
pub model: Option<ModelName>,
pub skill_path: PathBuf,
pub prompt_template_path: Option<PathBuf>,
pub observation_interval: core::time::Duration,
pub printer_poll: core::time::Duration,
pub unattended_window: core::time::Duration,
pub auto_compact_tokens: Option<NonZeroU64>,
pub idle_compact_tokens: Option<NonZeroU64>,
pub check_turn_timeout: core::time::Duration,
pub blank_frame_max_stddev: BlankFrameBound,
pub obico_ml_api_url: Option<WebAddress>,
pub obico_printer_id: Option<ObicoPrinterId>,
pub ingress_answer_bound: core::time::Duration,
pub ingress_shared_secret: SharedSecret,
pub api_credential: Option<ApiCredential>,
pub api_credential_verifier: Option<CredentialVerifier>,
pub camera_snapshot_url: Option<WebAddress>,
pub camera_calibration: Option<std::sync::Arc<printobserver_panels::CameraCalibration>>,
pub obico_api: Option<ObicoApi>,
pub spools: SpoolPolicy,
pub sheets: SheetTable,
pub recovery: Option<RecoveryConfig>,
pub recovery_grants: RecoveryGrants,
}
impl ServerConfig {
pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
let path = path.as_ref();
Self::parse(&read(path)?, path)
}
pub fn parse(text: &str, path: &Path) -> Result<Self, ConfigError> {
let file: ConfigFile = toml::from_str(text).map_err(|error| ConfigError::Unparsable {
path: path.to_path_buf(),
detail: error.to_string(),
})?;
Self::validate(file)
}
fn validate(file: ConfigFile) -> Result<Self, ConfigError> {
let state_dir =
state_directory(required(ConfigField::StateDir, file.state_dir)?.as_path())?;
let listen = listen_address(&required(ConfigField::Listen, file.listen)?)?;
let octoprint = octoprint(&file.octoprint)?;
let safety = required(ConfigField::SafetyEnvelope, file.safety)?;
check_envelope(&safety)?;
let harness = harness_identity(file.supervisor.harness)?;
let model = match file.supervisor.model {
None => None,
Some(name) => Some(
ModelName::new(&named(ConfigField::Model, Some(name))?)
.map_err(|error| ConfigError::about(ConfigField::Model, error.to_string()))?,
),
};
let skill_path = skill(file.supervisor.skill_path.as_deref())?;
let prompt_template_path = readable(
ConfigField::PromptTemplatePath,
file.supervisor.prompt_template_path.as_deref(),
)?;
let observation_interval = observation_interval(file.supervisor.observation_interval_s)?;
let printer_poll = seconds_within(
ConfigField::PrinterPollS,
file.supervisor.printer_poll_s,
PRINTER_POLL_RANGE_S,
)?;
let unattended_window = seconds_within(
ConfigField::UnattendedWindowS,
file.supervisor.unattended_window_s,
UNATTENDED_WINDOW_RANGE_S,
)?;
let (auto_compact_tokens, idle_compact_tokens) = compaction(
file.supervisor.auto_compact_tokens,
file.supervisor.idle_compact_tokens,
)?;
let blank_frame_max_stddev = blank_frame_bound(file.vision.blank_frame_max_stddev)?;
let (obico_ml_api_url, obico_printer_id) = detector_reads(&file.obico)?;
let ingress_answer_bound = answer_bound(file.ingress.answer_bound_ms)?;
let ingress_shared_secret = SharedSecret::new(&required(
ConfigField::IngressSharedSecret,
file.ingress.shared_secret,
)?)?;
let api_credential = file
.api
.credential
.as_deref()
.map(|value| {
ApiCredential::new(value)
.map_err(|why| ConfigError::about(ConfigField::ApiCredential, why))
})
.transpose()?;
let api_credential_verifier = file
.api
.credential_verifier
.as_deref()
.map(|value| {
CredentialVerifier::parse(value.trim())
.map_err(|why| ConfigError::about(ConfigField::ApiCredentialVerifier, why))
})
.transpose()?;
let (camera_snapshot_url, camera_calibration) = camera(file.camera)?;
let obico_api = obico_api(file.obico)?;
let spools = spool_policy(&file.spools)?;
let sheets = match file.sheets.allowed {
None => SheetTable::default(),
Some(entries) => SheetTable::new(entries)
.map_err(|why| ConfigError::about(ConfigField::SheetsAllowed, why))?,
};
let recovery = recovery_facts(&file.recovery)?;
let recovery_grants = recovery_grants(&file.policy.recovery)?;
Ok(Self {
state_dir,
listen,
octoprint,
safety,
harness,
model,
skill_path,
prompt_template_path,
observation_interval,
printer_poll,
unattended_window,
auto_compact_tokens,
idle_compact_tokens,
check_turn_timeout: check_turn_timeout(file.supervisor.check_turn_timeout_s)?,
blank_frame_max_stddev,
obico_ml_api_url,
obico_printer_id,
ingress_answer_bound,
ingress_shared_secret,
api_credential,
api_credential_verifier,
camera_snapshot_url,
camera_calibration,
obico_api,
spools,
sheets,
recovery,
recovery_grants,
})
}
#[must_use]
pub fn assets_dir(&self) -> PathBuf {
self.state_dir.join(ASSETS_DIRECTORY)
}
}
fn web_address(field: ConfigField, url: &str) -> Result<WebAddress, ConfigError> {
WebAddress::new(url).map_err(|why| ConfigError::about(field, why))
}
fn detector_reads(
section: &ObicoSection,
) -> Result<(Option<WebAddress>, Option<ObicoPrinterId>), ConfigError> {
let ml_api_url = section
.ml_api_url
.as_deref()
.map(|url| web_address(ConfigField::ObicoMlApiUrl, url))
.transpose()?;
let printer_id = section
.printer_id
.map(|id| {
ObicoPrinterId::new(id)
.map_err(|why| ConfigError::about(ConfigField::ObicoPrinterId, why))
})
.transpose()?;
Ok((ml_api_url, printer_id))
}
fn obico_api(section: ObicoSection) -> Result<Option<ObicoApi>, ConfigError> {
match (section.url, section.access_token) {
(None, None) => Ok(None),
(Some(_), None) => Err(ConfigError::about(
ConfigField::ObicoAccessToken,
"it is required when obico.url is given",
)),
(None, Some(_)) => Err(ConfigError::about(
ConfigField::ObicoUrl,
"it is required when obico.access_token is given",
)),
(Some(url), Some(access_token)) => {
let url = web_address(ConfigField::ObicoUrl, &url)?;
let access_token = AccessToken::new(&access_token)
.map_err(|why| ConfigError::about(ConfigField::ObicoAccessToken, why))?;
Ok(Some(ObicoApi::new(url, access_token)))
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SignInConfig {
pub state_dir: PathBuf,
pub harness: HarnessIdentity,
}
impl SignInConfig {
pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
let path = path.as_ref();
let file: SignInFile =
toml::from_str(&read(path)?).map_err(|error| ConfigError::Unparsable {
path: path.to_path_buf(),
detail: error.to_string(),
})?;
Ok(Self {
state_dir: state_directory(required(ConfigField::StateDir, file.state_dir)?.as_path())?,
harness: harness_identity(file.supervisor.harness)?,
})
}
}
#[derive(Deserialize)]
#[serde(crate = "printobserver_types::serde")]
struct SignInFile {
#[serde(default)]
state_dir: Option<PathBuf>,
#[serde(default)]
supervisor: SignInSupervisor,
}
#[derive(Default, Deserialize)]
#[serde(crate = "printobserver_types::serde")]
struct SignInSupervisor {
#[serde(default)]
harness: Option<String>,
}
fn read(path: &Path) -> Result<String, ConfigError> {
std::fs::read_to_string(path).map_err(|error| ConfigError::Unreadable {
path: path.to_path_buf(),
detail: error.to_string(),
})
}
fn harness_identity(value: Option<String>) -> Result<HarnessIdentity, ConfigError> {
HarnessIdentity::new(&named(ConfigField::Harness, value)?)
.map_err(|error| ConfigError::about(ConfigField::Harness, error.to_string()))
}
fn required<T>(field: ConfigField, value: Option<T>) -> Result<T, ConfigError> {
value.ok_or_else(|| ConfigError::about(field, "the configuration file carries no value for it"))
}
fn named(field: ConfigField, value: Option<String>) -> Result<String, ConfigError> {
let value = required(field, value)?;
if value.trim().is_empty() {
return Err(ConfigError::about(
field,
"it is empty, and an empty value names nothing",
));
}
Ok(value.trim().to_owned())
}
fn state_directory(named: &Path) -> Result<PathBuf, ConfigError> {
if named.as_os_str().is_empty() {
return Err(ConfigError::about(
ConfigField::StateDir,
"it names no directory, and this server's whole state lives in one",
));
}
std::fs::create_dir_all(named).map_err(|error| {
ConfigError::about(
ConfigField::StateDir,
format!("{} cannot be created: {error}", named.display()),
)
})?;
named.canonicalize().map(plainly_written).map_err(|error| {
ConfigError::about(
ConfigField::StateDir,
format!("{} cannot be resolved: {error}", named.display()),
)
})
}
#[must_use]
pub fn plainly_written(path: PathBuf) -> PathBuf {
const VERBATIM: &str = r"\\?\";
let drive = path
.to_str()
.and_then(|text| text.strip_prefix(VERBATIM))
.filter(|rest| {
let bytes = rest.as_bytes();
bytes.len() >= 3
&& bytes[0].is_ascii_alphabetic()
&& bytes[1] == b':'
&& bytes[2] == b'\\'
})
.map(PathBuf::from);
drive.unwrap_or(path)
}
fn listen_address(named: &str) -> Result<SocketAddr, ConfigError> {
named.trim().parse().map_err(|error| {
ConfigError::about(
ConfigField::Listen,
format!("{named:?} is no address to listen on: {error}"),
)
})
}
fn octoprint(section: &OctoprintSection) -> Result<OctoPrintConfig, ConfigError> {
let fan = fan_support(§ion.fan)?;
let url = named(ConfigField::OctoprintUrl, section.url.clone())?;
let key = named(ConfigField::OctoprintApiKey, section.api_key.clone())?;
OctoPrintConfig::new(&url, key)
.map(|configured| configured.with_fan(fan))
.map_err(|error| {
let field = match error {
printobserver_octoprint::ConfigError::EmptyApiKey => ConfigField::OctoprintApiKey,
_ => ConfigField::OctoprintUrl,
};
ConfigError::about(field, error.to_string())
})
}
fn fan_support(named: &str) -> Result<FanSupport, ConfigError> {
FAN_VOCABULARY
.iter()
.find(|(spelling, _)| *spelling == named.trim())
.map(|(_, support)| *support)
.ok_or_else(|| {
let vocabulary: Vec<&str> = FAN_VOCABULARY.iter().map(|(word, _)| *word).collect();
ConfigError::about(
ConfigField::OctoprintFan,
format!("{named:?} is not one of {}", vocabulary.join(" or ")),
)
})
}
fn check_envelope(envelope: &SafetyEnvelope) -> Result<(), ConfigError> {
if envelope.allowed.is_empty() {
return Err(ConfigError::about(
ConfigField::SafetyEnvelope,
"it allows no adjustable at all, so no adjustment could ever be accepted",
));
}
for (adjustable, range) in &envelope.allowed {
if !range.min.is_finite() || !range.max.is_finite() || range.min > range.max {
return Err(ConfigError::about(
ConfigField::SafetyEnvelope,
format!(
"the range allowed for {adjustable} runs from {} to {}, which admits \
no value",
range.min, range.max
),
));
}
}
if envelope
.actions
.get(&ActorClass::Agent)
.is_some_and(|granted| granted.contains(&ActionKind::ClosePrint))
{
return Err(ConfigError::about(
ConfigField::SafetyEnvelope,
"it grants `close_print` to the agent, and closing a print record is the \
operator's judgement that the print is over",
));
}
if envelope.agent_min_interval_s < 0 {
return Err(ConfigError::about(
ConfigField::SafetyEnvelope,
format!(
"the agent's minimum interval is {}s, and an interval is a count of seconds",
envelope.agent_min_interval_s
),
));
}
Ok(())
}
fn readable(field: ConfigField, named: Option<&Path>) -> Result<Option<PathBuf>, ConfigError> {
let Some(path) = named else {
return Ok(None);
};
std::fs::read_to_string(path)
.map(|_| Some(path.to_path_buf()))
.map_err(|error| {
ConfigError::about(field, format!("{} cannot be read: {error}", path.display()))
})
}
fn camera(
section: CameraSection,
) -> Result<
(
Option<WebAddress>,
Option<std::sync::Arc<printobserver_panels::CameraCalibration>>,
),
ConfigError,
> {
let snapshot_url = section
.snapshot_url
.map(|url| web_address(ConfigField::CameraSnapshotUrl, &url))
.transpose()?;
let calibration = section
.calibration
.as_deref()
.map(calibration)
.transpose()?
.map(std::sync::Arc::new);
Ok((snapshot_url, calibration))
}
fn calibration(path: &Path) -> Result<printobserver_panels::CameraCalibration, ConfigError> {
let bytes = std::fs::read(path).map_err(|error| {
ConfigError::about(
ConfigField::CameraCalibration,
format!("{} cannot be read: {error}", path.display()),
)
})?;
printobserver_panels::CameraCalibration::from_json(&bytes).map_err(|error| {
ConfigError::about(
ConfigField::CameraCalibration,
format!("{} is not a camera calibration: {error}", path.display()),
)
})
}
fn skill(named: Option<&Path>) -> Result<PathBuf, ConfigError> {
let Some(path) = named else {
return Err(ConfigError::about(
ConfigField::SkillPath,
format!(
"the configuration file carries no value for it, and this program carries \
no skill of its own: {SKILL_INSTALL}"
),
));
};
std::fs::read_to_string(path)
.map(|_| path.to_path_buf())
.map_err(|error| {
ConfigError::about(
ConfigField::SkillPath,
format!(
"{} cannot be read: {error}. {SKILL_INSTALL}",
path.display()
),
)
})
}
fn spool_policy(section: &SpoolsSection) -> Result<SpoolPolicy, ConfigError> {
let defaults = SpoolPolicy::default();
let preflight = match section.preflight.as_deref() {
None => defaults.preflight,
Some("refuse") => PreflightMode::Refuse,
Some("warn") => PreflightMode::Warn,
Some("off") => PreflightMode::Off,
Some(_) => {
return Err(ConfigError::about(
ConfigField::SpoolsPreflight,
"the spool check is one of `refuse`, `warn` or `off`",
));
}
};
let margin = |field: ConfigField, value: Option<f64>, default: f64| match value {
None => Ok(default),
Some(value) if value.is_finite() && value >= 0.0 => Ok(value),
Some(_) => Err(ConfigError::about(
field,
"a margin is a figure at or above zero; a negative one asks a spool for less \
than the print needs",
)),
};
let buffer_percent = margin(
ConfigField::SpoolsBufferPercent,
section.buffer_percent,
defaults.buffer_percent,
)?;
let buffer_min_g = margin(
ConfigField::SpoolsBufferMinG,
section.buffer_min_g,
defaults.buffer_min_g,
)?;
let analysis_wait_s = match section.analysis_wait_seconds {
None => defaults.analysis_wait_s,
Some(seconds) => u64::try_from(seconds).map_err(|_| {
ConfigError::about(
ConfigField::SpoolsAnalysisWaitSeconds,
"a wait is a number of seconds at or above zero",
)
})?,
};
Ok(SpoolPolicy {
preflight,
buffer_percent,
buffer_min_g,
analysis_wait_s,
})
}
fn recovery_facts(section: &RecoverySection) -> Result<Option<RecoveryConfig>, ConfigError> {
if *section == RecoverySection::default() {
return Ok(None);
}
let absent = |field: ConfigField| {
ConfigError::about(
field,
"`[recovery]` states this printer's facts, and this one is one of them",
)
};
let away_from_bed = match section.away_from_bed.as_deref() {
None => return Err(absent(ConfigField::RecoveryAwayFromBed)),
Some("z_plus") => AwayFromBed::ZPlus,
Some("z_minus") => AwayFromBed::ZMinus,
Some(other) => {
return Err(ConfigError::about(
ConfigField::RecoveryAwayFromBed,
format!("{other:?} is neither `z_plus` nor `z_minus`"),
));
}
};
let max_z_mm = section
.max_z_mm
.ok_or_else(|| absent(ConfigField::RecoveryMaxZMm))?;
if !(max_z_mm.is_finite() && max_z_mm > 0.0) {
return Err(ConfigError::about(
ConfigField::RecoveryMaxZMm,
format!("{max_z_mm} mm is no height a machine reaches; it is a figure above zero"),
));
}
let max_lift_mm = section
.max_lift_mm
.unwrap_or_else(|| DEFAULT_MAX_LIFT_MM.min(max_z_mm));
if !(max_lift_mm.is_finite() && max_lift_mm > 0.0 && max_lift_mm <= max_z_mm) {
return Err(ConfigError::about(
ConfigField::RecoveryMaxLiftMm,
format!(
"{max_lift_mm} mm is outside the lifts a machine of {max_z_mm} mm makes: above \
zero, and at most `recovery.max_z_mm`"
),
));
}
let clearance_margin_mm = section
.clearance_margin_mm
.unwrap_or(DEFAULT_CLEARANCE_MARGIN_MM);
if !(clearance_margin_mm.is_finite()
&& clearance_margin_mm >= 0.0
&& clearance_margin_mm < max_z_mm)
{
return Err(ConfigError::about(
ConfigField::RecoveryClearanceMarginMm,
format!(
"{clearance_margin_mm} mm is outside the margins a machine of {max_z_mm} mm \
admits: at or above zero, and below `recovery.max_z_mm`"
),
));
}
let place = |field: ConfigField, written: Option<&Vec<f64>>| match written.map(Vec::as_slice) {
None => Err(absent(field)),
Some([x, y]) if x.is_finite() && y.is_finite() && *x >= 0.0 && *y >= 0.0 => Ok([*x, *y]),
Some(_) => Err(ConfigError::about(
field,
"a place is `[x, y]`, two figures in millimetres at or above zero",
)),
};
let park_xy = place(ConfigField::RecoveryParkXy, section.park_xy.as_ref())?;
let z_home_xy = place(ConfigField::RecoveryZHomeXy, section.z_home_xy.as_ref())?;
let z_home_sweeps_bed = section
.z_home_sweeps_bed
.ok_or_else(|| absent(ConfigField::RecoveryZHomeSweepsBed))?;
Ok(Some(RecoveryConfig {
away_from_bed,
max_z_mm,
max_lift_mm,
clearance_margin_mm,
park_xy,
z_home_xy,
z_home_sweeps_bed,
}))
}
fn recovery_grants(section: &RecoveryPolicySection) -> Result<RecoveryGrants, ConfigError> {
let defaults = RecoveryGrants::default();
let actions = |field: ConfigField, written: Option<&Vec<String>>, default: Vec<_>| {
let Some(written) = written else {
return Ok(default);
};
written
.iter()
.map(|name| {
RecoveryActionKind::ALL
.iter()
.find(|kind| kind.as_str() == name.trim())
.copied()
.ok_or_else(|| {
ConfigError::about(
field,
format!("{name:?} is not a recovery action of this program"),
)
})
})
.collect::<Result<Vec<_>, _>>()
};
let operator = actions(
ConfigField::PolicyRecoveryOperator,
section.operator.as_ref(),
defaults.operator,
)?;
let agent = actions(
ConfigField::PolicyRecoveryAgent,
section.agent.as_ref(),
defaults.agent,
)?;
if agent.contains(&RecoveryActionKind::RecoverHomeZ) {
return Err(ConfigError::about(
ConfigField::PolicyRecoveryAgent,
"it grants `recover_home_z` to the agent, and only a person at the machine can \
say the bed is clear for Z to be homed",
));
}
let asserting = match section.asserting.as_ref() {
None => defaults.asserting,
Some(written) => written
.iter()
.map(|class| match class.trim() {
"operator" => Ok(ActorClass::Operator),
"agent" => Err(ConfigError::about(
ConfigField::PolicyRecoveryAsserting,
"it lets the agent assert clearance, and an assertion is a person's word \
for what they can see at the machine",
)),
other => Err(ConfigError::about(
ConfigField::PolicyRecoveryAsserting,
format!("{other:?} is not an actor whose word can count; only `operator` is"),
)),
})
.collect::<Result<Vec<_>, _>>()?,
};
Ok(RecoveryGrants {
operator,
agent,
asserting,
})
}
fn observation_interval(seconds: u64) -> Result<core::time::Duration, ConfigError> {
if seconds == 0 {
return Err(ConfigError::about(
ConfigField::ObservationIntervalS,
"an interval of zero seconds observes a print again the moment its last turn \
returns, which is a turn that never ends",
));
}
Ok(core::time::Duration::from_secs(seconds))
}
fn compaction(
auto: Option<i64>,
idle: Option<i64>,
) -> Result<(Option<NonZeroU64>, Option<NonZeroU64>), ConfigError> {
Ok((
tokens(ConfigField::AutoCompactTokens, auto)?,
tokens(ConfigField::IdleCompactTokens, idle)?,
))
}
fn tokens(field: ConfigField, count: Option<i64>) -> Result<Option<NonZeroU64>, ConfigError> {
count
.map(|count| {
u64::try_from(count)
.ok()
.and_then(NonZeroU64::new)
.ok_or_else(|| {
ConfigError::about(
field,
format!(
"{count} tokens is no conversation size: it is a whole number from 1"
),
)
})
})
.transpose()
}
fn check_turn_timeout(seconds: u64) -> Result<core::time::Duration, ConfigError> {
seconds_within(
ConfigField::CheckTurnTimeoutS,
seconds,
CHECK_TURN_TIMEOUT_RANGE_S,
)
}
fn seconds_within(
field: ConfigField,
seconds: u64,
range: (u64, u64),
) -> Result<core::time::Duration, ConfigError> {
let (least, most) = range;
if !(least..=most).contains(&seconds) {
return Err(ConfigError::about(
field,
format!("{seconds} seconds is outside the {least} to {most} seconds it admits"),
));
}
Ok(core::time::Duration::from_secs(seconds))
}
fn blank_frame_bound(written: Option<f64>) -> Result<BlankFrameBound, ConfigError> {
written.map_or(Ok(BlankFrameBound::DEFAULT), |bound| {
BlankFrameBound::new(bound).map_err(|refused| {
ConfigError::about(
ConfigField::VisionBlankFrameMaxStddev,
format!(
"{refused} is outside the {MIN_BLANK_FRAME_MAX_STDDEV} to \
{MAX_BLANK_FRAME_MAX_STDDEV} grey levels it admits"
),
)
})
})
}
fn answer_bound(milliseconds: u64) -> Result<core::time::Duration, ConfigError> {
if milliseconds == 0 {
return Err(ConfigError::about(
ConfigField::IngressAnswerBoundMs,
"a bound of zero is an ingress that has run out of time before it starts",
));
}
if milliseconds >= OBICO_POSTING_TIMEOUT_MS {
return Err(ConfigError::about(
ConfigField::IngressAnswerBoundMs,
format!(
"{milliseconds}ms is not below the {OBICO_POSTING_TIMEOUT_MS}ms Obico posts \
under, so an alert answered at that bound is one Obico has already \
abandoned — and its posting does not retry"
),
));
}
Ok(core::time::Duration::from_millis(milliseconds))
}
#[cfg(test)]
mod tests {
use super::CredentialVerifier;
const ABC: &str = "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
#[test]
fn a_verifier_is_the_credentials_sha256_and_admits_only_it() {
let verifier = CredentialVerifier::of("abc");
assert_eq!(verifier.to_string(), ABC);
assert_eq!(CredentialVerifier::parse(ABC), Ok(verifier.clone()));
assert!(verifier.admits(b"abc"));
assert!(!verifier.admits(b"abd"));
assert!(!verifier.admits(b""));
}
#[test]
fn a_verifier_in_any_other_spelling_is_refused() {
for refused in [
"",
"sha256:",
&ABC[..ABC.len() - 1],
&format!("{ABC}0"),
&ABC.to_uppercase(),
&ABC.replace("sha256:", "sha512:"),
&ABC.replace("sha256:", ""),
&ABC.replace('a', "g"),
] {
assert!(
CredentialVerifier::parse(refused).is_err(),
"{refused:?} was accepted"
);
}
}
}