use std::path::Path;
use anyhow::{Context as _, Result, bail};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use super::channel::{Options, local_id};
use super::{hex, verify_hex};
use crate::proxy_session::Key;
const DOMAIN: &[u8] = b"openmoat-remote-settings-v1\n";
const CHANNEL_DOMAIN: &[u8] = b"openmoat-remote-channel-settings-v1\n";
const VERSION: u32 = 1;
pub const DEFAULT_EXPIRY_S: u64 = 5 * 60;
pub const MIN_EXPIRY_S: u64 = 60;
pub const MAX_EXPIRY_S: u64 = 60 * 60;
pub(super) trait Signed: Serialize + DeserializeOwned + Clone {
const DOMAIN: &'static [u8];
fn version(&self) -> u32;
fn mac(&mut self) -> &mut String;
fn signed_bytes(&self) -> Result<Vec<u8>> {
let mut unsigned = self.clone();
unsigned.mac().clear();
serde_json::to_vec(&unsigned).context("encoding the approval settings")
}
fn load(path: &Path, key: &Key) -> Result<Self> {
let text =
std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
let mut value: Self = serde_json::from_str(&text)
.with_context(|| format!("{} is not approval settings", path.display()))?;
let signed = value.signed_bytes()?;
let mac = value.mac().clone();
if value.version() != VERSION || !verify_hex(&mac, &key.mac(Self::DOMAIN, &signed)) {
bail!(
"{} is not signed with this machine's approval key, so no remote answer is \
accepted; run `openmoat approvals connect` again",
path.display()
);
}
Ok(value)
}
fn save(&mut self, path: &Path, key: &Key) -> Result<()> {
let mac = hex(&key.mac(Self::DOMAIN, &self.signed_bytes()?));
*self.mac() = mac;
let mut text = serde_json::to_string_pretty(self).context("encoding the settings")?;
text.push('\n');
crate::home::write_private(path, text.as_bytes())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Settings {
pub version: u32,
pub channel: String,
pub approvers: Vec<String>,
pub expiry_s: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub wait_s: Option<u64>,
#[serde(default)]
pub mac: String,
}
impl Signed for Settings {
const DOMAIN: &'static [u8] = DOMAIN;
fn version(&self) -> u32 {
self.version
}
fn mac(&mut self) -> &mut String {
&mut self.mac
}
}
impl Settings {
pub fn new(channel: &str, expiry_s: u64) -> Result<Self> {
if !(MIN_EXPIRY_S..=MAX_EXPIRY_S).contains(&expiry_s) {
bail!(
"a request waits between {} and {} minutes",
MIN_EXPIRY_S / 60,
MAX_EXPIRY_S / 60
);
}
Ok(Self {
version: VERSION,
channel: channel.to_owned(),
approvers: Vec::new(),
expiry_s,
wait_s: None,
mac: String::new(),
})
}
pub fn wait(&self) -> std::time::Duration {
std::time::Duration::from_secs(self.wait_s.unwrap_or(super::wait::DEFAULT_WAIT_S))
}
pub fn set_wait(&mut self, seconds: u64) -> Result<()> {
if seconds > super::wait::MAX_WAIT_S {
bail!(
"the hook waits at most {} seconds for an answer (0 turns the wait off)",
super::wait::MAX_WAIT_S
);
}
self.wait_s = Some(seconds);
Ok(())
}
pub fn approver(&self, id: &str) -> bool {
self.approvers.iter().any(|a| a == id)
}
pub fn load(path: &Path, key: &Key) -> Result<Self> {
let settings = <Self as Signed>::load(path, key)?;
if !(MIN_EXPIRY_S..=MAX_EXPIRY_S).contains(&settings.expiry_s) {
bail!("{} sets an expiry out of range", path.display());
}
if settings.wait_s.is_some_and(|s| s > super::wait::MAX_WAIT_S) {
bail!("{} sets a wait out of range", path.display());
}
settings.check_approvers()?;
Ok(settings)
}
fn check_approvers(&self) -> Result<()> {
if let Some(other) = self
.approvers
.iter()
.find(|a| local_id(&self.channel, a).is_none_or(str::is_empty))
{
bail!(
"the approver `{}` is not of the connected channel {}",
crate::render::clean(other),
self.channel
);
}
Ok(())
}
pub fn save(&mut self, path: &Path, key: &Key) -> Result<()> {
self.approvers.sort();
self.approvers.dedup();
self.check_approvers()?;
<Self as Signed>::save(self, path, key)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ChannelSettings {
pub version: u32,
pub channel: String,
pub account: String,
#[serde(default)]
pub options: Options,
#[serde(default)]
pub mac: String,
}
impl Signed for ChannelSettings {
const DOMAIN: &'static [u8] = CHANNEL_DOMAIN;
fn version(&self) -> u32 {
self.version
}
fn mac(&mut self) -> &mut String {
&mut self.mac
}
}
impl ChannelSettings {
pub fn new(channel: &str, account: String, options: Options) -> Self {
Self {
version: VERSION,
channel: channel.to_owned(),
account,
options,
mac: String::new(),
}
}
pub fn load(path: &Path, key: &Key, channel: &str) -> Result<Self> {
let settings = <Self as Signed>::load(path, key)?;
if settings.channel != channel {
bail!("{} belongs to another channel", path.display());
}
Ok(settings)
}
pub fn save(&mut self, path: &Path, key: &Key) -> Result<()> {
<Self as Signed>::save(self, path, key)
}
}