use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use printobserver_core::SafetyEnvelope;
use printobserver_octoprint::{FanSupport, OctoPrintConfig};
use printobserver_oneharness::{HarnessIdentity, ModelName};
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};
pub const DEFAULT_INGRESS_ANSWER_BOUND_MS: u64 = 1_000;
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,
IngressAnswerBoundMs,
IngressSharedSecret,
ApiCredential,
}
impl ConfigField {
pub const ALL: [Self; 13] = [
Self::StateDir,
Self::Listen,
Self::OctoprintUrl,
Self::OctoprintApiKey,
Self::OctoprintFan,
Self::SafetyEnvelope,
Self::Harness,
Self::Model,
Self::SkillPath,
Self::PromptTemplatePath,
Self::IngressAnswerBoundMs,
Self::IngressSharedSecret,
Self::ApiCredential,
];
#[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::IngressAnswerBoundMs => "ingress.answer_bound_ms",
Self::IngressSharedSecret => "ingress.shared_secret",
Self::ApiCredential => "api.credential",
}
}
}
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")]
#[derive(Default)]
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>,
}
#[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>,
}
#[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,
}
#[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))
}
pub(crate) fn written(&self) -> &str {
&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})")
}
}
#[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 ingress_answer_bound: core::time::Duration,
pub ingress_shared_secret: SharedSecret,
pub api_credential: Option<ApiCredential>,
}
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 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()?;
Ok(Self {
state_dir,
listen,
octoprint,
safety,
harness,
model,
skill_path,
prompt_template_path,
ingress_answer_bound,
ingress_shared_secret,
api_credential,
})
}
#[must_use]
pub fn assets_dir(&self) -> PathBuf {
self.state_dir.join(ASSETS_DIRECTORY)
}
}
#[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.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 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 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))
}