use super::{control_error_frame, control_flags, ControlHandler};
use crate::operator_apps::COMPILED_APP;
use crate::operator_confirm::Outcome;
use serde::{de::DeserializeOwned, Serialize};
use sha2::{Digest, Sha256};
use std::{collections::BTreeMap, fmt::Debug, fs, path::PathBuf};
use subc_control::{
ops, AppTrustReply, AppTrustRequest, ConnectionDescribeReply, ConnectionDevBuild,
TrustedAppBuild,
};
use subc_protocol::{
error_codes, peer::OperatorApp, ErrorBody, Frame, FrameType, ModuleHelloAckBody,
PROTOCOL_VERSION,
};
const FIXTURE_HASH: &str = "0123456789abcdef0123456789abcdef01234567";
const TRUST_OPS: [&str; 3] = [ops::APP_TRUST, ops::APP_TRUSTED, ops::APP_UNTRUST];
fn sample_dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../vectors/app-trust-v1")
}
fn read_sample(name: &str) -> Vec<u8> {
fs::read(sample_dir().join(name)).unwrap_or_else(|error| panic!("{name}: {error}"))
}
fn decode_sample<T: DeserializeOwned>(name: &str, bytes: &[u8]) -> T {
serde_json::from_slice(bytes).unwrap_or_else(|error| panic!("{name}: {error}"))
}
#[cfg(target_os = "macos")]
pub(super) fn check_daemon_sample<T: DeserializeOwned + PartialEq + Debug>(name: &str, body: T) {
assert_eq!(body, decode_sample(name, &read_sample(name)), "{name}");
}
#[derive(Default)]
struct Samples {
sums: BTreeMap<&'static str, String>,
}
impl Samples {
fn pin<T: Serialize + DeserializeOwned + PartialEq + Debug>(
&mut self,
name: &'static str,
expected: &T,
) {
self.pin_json(
name,
expected,
serde_json::to_string_pretty(expected).unwrap(),
);
}
fn pin_json<T: DeserializeOwned + PartialEq + Debug>(
&mut self,
name: &'static str,
expected: &T,
mut json: String,
) {
json.push('\n');
let bytes = json.as_bytes();
if std::env::var_os("UPDATE_GOLDEN").is_some() {
fs::write(sample_dir().join(name), bytes).unwrap();
}
let actual = read_sample(name);
let decoded: T = decode_sample(name, &actual);
assert_eq!(&decoded, expected, "{name}");
assert_eq!(actual, bytes, "{name}; regenerate with UPDATE_GOLDEN=1");
self.sums
.insert(name, format!("{:x} {name}\n", Sha256::digest(bytes)));
}
fn check_sums(self) {
let sums: String = self.sums.into_values().collect();
if std::env::var_os("UPDATE_GOLDEN").is_some() {
fs::write(sample_dir().join("SHA256SUMS"), &sums).unwrap();
}
assert_eq!(read_sample("SHA256SUMS"), sums.as_bytes());
}
fn pin_error_frame(&mut self, name: &'static str, frame: Frame) {
assert_eq!(frame.header.ty, FrameType::Error, "{name}");
let body: ErrorBody = decode_sample(name, &frame.body);
assert_eq!(
serde_json::to_value(&body).unwrap(),
decode_sample::<serde_json::Value>(name, &frame.body),
"{name}: ErrorBody must account for every field in the frame"
);
self.pin(name, &body);
}
}
pub(super) fn hello_ack_ops() -> Vec<String> {
let hello = Frame::build(FrameType::Hello, control_flags(), 0, 0, 7, vec![]).unwrap();
let reply = ControlHandler::default()
.build_hello_ack(&hello, PROTOCOL_VERSION, "probe")
.unwrap();
assert_eq!(reply.header.ty, FrameType::HelloAck);
let ops = decode_sample::<ModuleHelloAckBody>("HELLO_ACK", &reply.body).subc_ops;
let raw: serde_json::Value = decode_sample("HELLO_ACK", &reply.body);
assert_eq!(raw["subc_ops"], serde_json::to_value(&ops).unwrap());
ops
}
fn pin_describe_samples(samples: &mut Samples) {
let stamped =
ConnectionDescribeReply::new(true, Some(OperatorApp::new(COMPILED_APP.id.unwrap(), 4242)));
samples.pin("connection-describe-operator-app.json", &stamped);
let mut reply = ConnectionDescribeReply::new(true, None);
samples.pin("connection-describe-neither.json", &reply);
for (name, dev_build) in [
(
"connection-describe-untrusted.json",
ConnectionDevBuild::Untrusted {
cdhash: FIXTURE_HASH.into(),
},
),
(
"connection-describe-ineligible.json",
ConnectionDevBuild::Ineligible {
reason: "The app lacks a hardened runtime signature.".into(),
},
),
(
"connection-describe-unavailable.json",
ConnectionDevBuild::Unavailable {
reason: "The daemon could not read the trust store.".into(),
},
),
] {
reply.dev_build = Some(dev_build);
samples.pin(name, &reply);
}
reply.dev_build = Some(ConnectionDevBuild::Unknown);
let json = serde_json::to_string_pretty(&reply).unwrap();
let future = json.replacen(
"\"status\": \"unknown\"",
"\"status\": \"future_status\"",
1,
);
assert_ne!(future, json);
samples.pin_json("connection-describe-unknown-status.json", &reply, future);
}
fn pin_trust_samples(samples: &mut Samples) {
let trust = AppTrustRequest::new("/absolute/path/Alfonso.app".into());
samples.pin("app-trust-request.json", &trust);
let reply = AppTrustReply::new(TrustedAppBuild::new(
"dev.cortexkit.alfonso".into(),
FIXTURE_HASH.into(),
"0.1.0".into(),
Some("2026-11-29T12:00:00Z".into()),
1_795_953_601_000,
));
samples.pin("app-trust-added.json", &reply);
samples.pin("app-trust-already-trusted.json", &reply);
let request = Frame::build(
FrameType::Request,
control_flags(),
0,
0,
7,
serde_json::to_vec(&trust).unwrap(),
)
.unwrap();
for (name, code, message) in [
(
"app-trust-busy.json",
"app_trust_busy",
"Another build is being reviewed; try again after that approval ends.",
),
(
"app-trust-build-ineligible.json",
"app_build_ineligible",
"The signing identifier must be dev.cortexkit.alfonso.",
),
(
"app-trust-caller-not-authorized.json",
"caller_not_authorized",
"Only an owner-local connection can manage trusted app builds.",
),
(
"app-trust-store-unavailable.json",
"app_trust_store_unavailable",
"Trusted builds require a signed daemon with access to its macOS keychain group; \
no file fallback is available.",
),
] {
let frame = control_error_frame(&request, code, message).unwrap();
samples.pin_error_frame(name, frame);
}
let mut declined = Outcome::refusal(error_codes::OPERATOR_DECLINED);
declined.reason = "person";
for (name, outcome) in [
("app-trust-operator-declined.json", declined),
(
"app-trust-no-presence.json",
Outcome::unavailable("no_presence"),
),
("app-trust-timeout.json", Outcome::unavailable("timeout")),
] {
samples.pin_error_frame(name, outcome.frame(&request));
}
}
#[test]
fn app_trust_vectors_match_wire_bytes() {
let mut samples = Samples::default();
pin_describe_samples(&mut samples);
pin_trust_samples(&mut samples);
let native = hello_ack_ops();
let mut alternate = native.clone();
let (macos, other) = if cfg!(target_os = "macos") {
alternate.retain(|op| !TRUST_OPS.contains(&op.as_str()));
(native, alternate)
} else {
let end = super::SUBC_CONTROL_OPS.len();
alternate.splice(end..end, TRUST_OPS.map(str::to_owned));
(alternate, native)
};
samples.pin("hello-ack-subc-ops-macos.json", &macos);
samples.pin("hello-ack-subc-ops-other.json", &other);
samples.check_sums();
}