use std::fmt::Write as _;
use anyhow::{Context as _, Result};
use openmoat_audit::KnownSecrets;
use openmoat_core::{Action, Decision};
use openmoat_hosts::HookRequest;
use serde::{Deserialize, Serialize};
use sha2::{Digest as _, Sha256};
use super::{hex, verify_hex};
use crate::proxy_session::Key;
const DIGEST_DOMAIN: &[u8] = b"openmoat-remote-request-digest-v2\n";
const REQUEST_DOMAIN: &[u8] = b"openmoat-remote-request-v1\n";
pub const VERSION: u32 = 1;
pub const SHOWN_MAX: usize = 1500;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Request {
pub version: u32,
pub id: String,
pub digest: String,
pub host: String,
pub session: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cwd: Option<String>,
pub tool: String,
pub rules: Vec<String>,
pub shown: String,
pub cut: bool,
pub redacted: bool,
pub created_ms: i64,
pub expires_ms: i64,
#[serde(default)]
pub mac: String,
}
impl Request {
pub fn code(&self) -> &str {
self.id.get(..6).unwrap_or(&self.id)
}
pub fn deny_only(&self) -> Option<&'static str> {
if self.redacted {
Some(
"Parts of this call are hidden because they look like secrets; approve it at \
the terminal. Deny blocks it until the request expires.",
)
} else if self.cut {
Some(
"This call is too long to show in full, so it cannot be approved here; approve \
it where the agent runs. Deny blocks it until the request expires.",
)
} else {
None
}
}
pub fn expired(&self, now_ms: i64) -> bool {
now_ms >= self.expires_ms
}
fn signed_bytes(&self) -> Result<Vec<u8>> {
let mut unsigned = self.clone();
unsigned.mac.clear();
serde_json::to_vec(&unsigned).context("encoding a remote approval request")
}
pub fn sign(&mut self, key: &Key) -> Result<()> {
self.mac = hex(&key.mac(REQUEST_DOMAIN, &self.signed_bytes()?));
Ok(())
}
pub fn verified(&self, key: &Key) -> bool {
self.version == VERSION
&& self
.signed_bytes()
.is_ok_and(|bytes| verify_hex(&self.mac, &key.mac(REQUEST_DOMAIN, &bytes)))
}
}
fn field(out: &mut Sha256, bytes: &[u8]) {
out.update((bytes.len() as u64).to_le_bytes());
out.update(bytes);
}
pub fn digest(request: &HookRequest, action: &Action, decision: &Decision) -> Result<String> {
let mut out = Sha256::new();
out.update(DIGEST_DOMAIN);
field(&mut out, request.host.id().as_bytes());
field(&mut out, request.session_id.as_bytes());
field(&mut out, request.cwd.as_deref().unwrap_or("").as_bytes());
field(&mut out, request.tool.as_bytes());
let action = serde_json::to_vec(action).context("encoding the action")?;
field(&mut out, &action);
for optional in [
&request.content,
&request.patch,
&request.mcp_arguments,
&request.input,
] {
match optional {
Some(text) => {
field(&mut out, b"1");
field(&mut out, text.as_bytes());
}
None => field(&mut out, b"0"),
}
}
field(&mut out, &(request.edits.len() as u64).to_le_bytes());
for edit in &request.edits {
field(&mut out, edit.old.as_bytes());
field(&mut out, edit.new.as_bytes());
field(&mut out, &[u8::from(edit.all)]);
}
field(&mut out, &[u8::from(request.sandboxed)]);
let mut rules = decision.rules.clone();
rules.sort();
rules.dedup();
for rule in &rules {
field(&mut out, rule.as_bytes());
}
Ok(hex(&out.finalize()))
}
pub const LINE_MARK: char = '⏎';
fn lines_marked(text: &str) -> String {
text.split('\n')
.map(crate::render::clean)
.collect::<Vec<_>>()
.join(&format!("{LINE_MARK}\n"))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Shown {
pub text: String,
pub cut: bool,
pub redacted: bool,
}
pub fn shown(request: &HookRequest, action: &Action, known: &KnownSecrets) -> Shown {
let text = match action {
Action::Shell { .. }
| Action::FsRead { .. }
| Action::FsWrite { .. }
| Action::Patch { .. }
| Action::ReadFiles { .. } => crate::approvals::describe(action),
other => serde_json::to_string(other).unwrap_or_else(|_| request.tool.clone()),
};
let hidden = known.redact(&openmoat_audit::redact(&text));
let redacted = hidden != text;
let mut text = hidden;
if let Some(content) = &request.content {
let _ = write!(text, " ({} bytes of content, not shown)", content.len());
}
if !request.edits.is_empty() {
let _ = write!(text, " ({} replacement(s), not shown)", request.edits.len());
}
let text = lines_marked(&text);
Shown {
redacted,
cut: text.chars().count() > SHOWN_MAX,
text: crate::render::truncate(&text, SHOWN_MAX),
}
}