use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::fmt;
pub const PROTOCOL: &str = "rpi-shared-host";
pub const MAJOR: u16 = 1;
pub const MINOR: u16 = 6;
pub const MAX_FRAME_BYTES: usize = 1024 * 1024;
pub const MAX_RESULT_TEXT_BYTES: usize = 16 * 1024;
pub const MAX_PAGE_SIZE: usize = 128;
pub const MAX_SUBMIT_PROMPT_BYTES: usize = 256 * 1024;
macro_rules! identity {
($name:ident) => {
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct $name(uuid::Uuid);
impl $name {
pub fn new() -> Self {
Self(uuid::Uuid::new_v4())
}
}
impl Default for $name {
fn default() -> Self {
Self::new()
}
}
impl TryFrom<String> for $name {
type Error = &'static str;
fn try_from(value: String) -> Result<Self, Self::Error> {
let id = uuid::Uuid::parse_str(&value).map_err(|_| "invalid identity")?;
if id.is_nil() {
return Err("nil identity");
}
Ok(Self(id))
}
}
impl From<$name> for String {
fn from(value: $name) -> Self {
value.0.to_string()
}
}
impl fmt::Display for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
};
}
identity!(HostId);
identity!(Epoch);
identity!(AgentId);
identity!(RequestId);
identity!(CallId);
identity!(TicketId);
identity!(ControlScopeId);
identity!(ProfileVersion);
identity!(RunId);
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MiniRequest {
pub scope: ControlScopeId,
pub epoch: Epoch,
pub request_id: RequestId,
pub action: MiniAction,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
pub enum MiniAction {
Submit {
agent_id: AgentId,
prompt: String,
},
Cancel {
agent_id: AgentId,
submitted_request_id: RequestId,
run_id: RunId,
},
Close {
agent_id: AgentId,
},
}
impl MiniAction {
pub fn agent(&self) -> AgentId {
match self {
Self::Submit { agent_id, .. }
| Self::Cancel { agent_id, .. }
| Self::Close { agent_id } => *agent_id,
}
}
}
impl MiniRequest {
pub fn valid(&self) -> bool {
match &self.action {
MiniAction::Submit { prompt, .. } => {
!prompt.trim().is_empty() && prompt.len() <= MAX_SUBMIT_PROMPT_BYTES
}
_ => true,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProfileRef {
pub agent_id: AgentId,
pub version: ProfileVersion,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AdministrativeRequest {
pub scope: ControlScopeId,
pub request_id: RequestId,
pub epoch: Epoch,
pub action: AdministrativeAction,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
pub enum AdministrativeAction {
Create {
agent_id: AgentId,
},
Restore {
agent_id: AgentId,
revision: u64,
},
CreateProfile {
profile: ProfileRef,
},
RestoreProfile {
profile: ProfileRef,
revision: u64,
},
Cancel {
agent_id: AgentId,
revision: u64,
ticket_id: TicketId,
},
CancelSubmitted {
agent_id: AgentId,
revision: u64,
submitted_request_id: RequestId,
},
Close {
agent_id: AgentId,
revision: u64,
},
Stop {},
}
impl AdministrativeRequest {
pub fn valid(&self) -> bool {
match self.action {
AdministrativeAction::Restore { revision, .. }
| AdministrativeAction::RestoreProfile { revision, .. }
| AdministrativeAction::Cancel { revision, .. }
| AdministrativeAction::CancelSubmitted { revision, .. }
| AdministrativeAction::Close { revision, .. } => {
(1..=i64::MAX as u64).contains(&revision)
}
_ => true,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Version {
pub major: u16,
pub minor: u16,
}
impl Default for Version {
fn default() -> Self {
Self {
major: MAJOR,
minor: MINOR,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Capability {
Status,
List,
Inspect,
Receipts,
Results,
Profiles,
AdministrativeReceipts,
AdministrativeCreate,
AdministrativeRestore,
AdministrativeClose,
AdministrativeCancel,
AdministrativeStop,
Create,
Submit,
Cancel,
Close,
Restore,
Events,
Approvals,
Configure,
Stop,
Mini,
#[serde(other)]
Unknown,
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct AuthToken(String);
impl AuthToken {
pub fn new(value: String) -> Result<Self, &'static str> {
if !(32..=128).contains(&value.len())
|| !value
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
{
return Err("invalid authentication token");
}
Ok(Self(value))
}
pub fn matches(&self, other: &Self) -> bool {
let a = self.0.as_bytes();
let b = other.0.as_bytes();
let mut diff = a.len() ^ b.len();
for i in 0..128 {
diff |= usize::from(a.get(i).copied().unwrap_or(0) ^ b.get(i).copied().unwrap_or(0));
}
diff == 0
}
}
impl TryFrom<String> for AuthToken {
type Error = &'static str;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl From<AuthToken> for String {
fn from(value: AuthToken) -> Self {
value.0
}
}
impl fmt::Debug for AuthToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("AuthToken([redacted])")
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Hello {
pub protocol: String,
pub version: Version,
pub host_id: HostId,
pub token: AuthToken,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Limits {
pub max_frame_bytes: usize,
pub max_in_flight: usize,
pub max_page_size: usize,
}
impl Default for Limits {
fn default() -> Self {
Self {
max_frame_bytes: MAX_FRAME_BYTES,
max_in_flight: 64,
max_page_size: MAX_PAGE_SIZE,
}
}
}
impl Limits {
pub fn valid(&self) -> bool {
(512..=MAX_FRAME_BYTES).contains(&self.max_frame_bytes)
&& (1..=64).contains(&self.max_in_flight)
&& (1..=MAX_PAGE_SIZE).contains(&self.max_page_size)
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Welcome {
pub protocol: String,
pub version: Version,
pub host_id: HostId,
pub epoch: Epoch,
pub capabilities: Vec<Capability>,
pub limits: Limits,
}
impl Welcome {
pub fn compatible(&self, host: HostId) -> bool {
self.protocol == PROTOCOL
&& self.version.major == MAJOR
&& self.host_id == host
&& self.limits.valid()
&& self.capabilities.len() <= 64
}
pub fn supports(&self, capability: Capability) -> bool {
capability != Capability::Unknown
&& self.capabilities.contains(&capability)
&& (capability != Capability::Mini || self.version.minor >= 6)
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Request {
pub call_id: CallId,
pub epoch: Epoch,
pub command: Command,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
pub enum Command {
Status {},
MiniExecute {
request: MiniRequest,
},
MiniReceipt {
request: MiniRequest,
},
MiniResult {
scope: ControlScopeId,
epoch: Epoch,
agent_id: AgentId,
request_id: RequestId,
run_id: Option<RunId>,
offset: usize,
max_bytes: usize,
},
List {
after: Option<AgentId>,
limit: usize,
},
Inspect {
agent_id: AgentId,
},
Profiles {
after: Option<AgentId>,
limit: usize,
},
AdministrativeReceipt {
request: AdministrativeRequest,
},
AdministrativeCreate {
request: AdministrativeRequest,
},
AdministrativeRestore {
request: AdministrativeRequest,
},
AdministrativeClose {
request: AdministrativeRequest,
},
AdministrativeCancel {
request: AdministrativeRequest,
},
AdministrativeStop {
request: AdministrativeRequest,
},
Receipt {
agent_id: AgentId,
request_id: RequestId,
},
Result {
agent_id: AgentId,
request_id: RequestId,
run_id: Option<String>,
offset: usize,
max_bytes: usize,
},
Submit {
agent_id: AgentId,
request_id: RequestId,
prompt: String,
},
Cancel {
mutation: AgentMutation,
ticket_id: TicketId,
},
Close {
mutation: AgentMutation,
},
Restore {
mutation: AgentMutation,
},
Stop {
request_id: RequestId,
},
}
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AgentMutation {
pub request_id: RequestId,
pub agent_id: AgentId,
pub revision: u64,
}
impl Command {
pub fn capability(&self) -> Capability {
match self {
Self::Status {} => Capability::Status,
Self::MiniExecute { .. } | Self::MiniReceipt { .. } | Self::MiniResult { .. } => {
Capability::Mini
}
Self::List { .. } => Capability::List,
Self::Inspect { .. } => Capability::Inspect,
Self::Profiles { .. } => Capability::Profiles,
Self::AdministrativeReceipt { .. } => Capability::AdministrativeReceipts,
Self::AdministrativeCreate { .. } => Capability::AdministrativeCreate,
Self::AdministrativeRestore { .. } => Capability::AdministrativeRestore,
Self::AdministrativeClose { .. } => Capability::AdministrativeClose,
Self::AdministrativeCancel { .. } => Capability::AdministrativeCancel,
Self::AdministrativeStop { .. } => Capability::AdministrativeStop,
Self::Receipt { .. } => Capability::Receipts,
Self::Result { .. } => Capability::Results,
Self::Submit { .. } => Capability::Submit,
Self::Cancel { .. } => Capability::Cancel,
Self::Close { .. } => Capability::Close,
Self::Restore { .. } => Capability::Restore,
Self::Stop { .. } => Capability::Stop,
}
}
pub fn request_id(&self) -> Option<RequestId> {
match self {
Self::MiniExecute { request } => Some(request.request_id),
Self::AdministrativeCreate { request }
| Self::AdministrativeRestore { request }
| Self::AdministrativeClose { request }
| Self::AdministrativeCancel { request }
| Self::AdministrativeStop { request } => Some(request.request_id),
Self::Cancel { mutation, .. }
| Self::Close { mutation }
| Self::Restore { mutation } => Some(mutation.request_id),
Self::Submit { request_id, .. } => Some(*request_id),
Self::Stop { request_id } => Some(*request_id),
_ => None,
}
}
pub fn valid(&self, limits: Limits) -> bool {
match self {
Self::MiniExecute { request } | Self::MiniReceipt { request } => request.valid(),
Self::MiniResult {
offset,
max_bytes,
run_id,
..
} => {
(4..=MAX_RESULT_TEXT_BYTES).contains(max_bytes)
&& (*offset == 0 || run_id.is_some())
}
Self::List { limit, .. } | Self::Profiles { limit, .. } => {
(1..=limits.max_page_size).contains(limit)
}
Self::AdministrativeReceipt { request } => request.valid(),
Self::AdministrativeCreate { request } => {
request.valid()
&& matches!(request.action, AdministrativeAction::CreateProfile { .. })
}
Self::AdministrativeRestore { request } => {
request.valid()
&& matches!(request.action, AdministrativeAction::RestoreProfile { .. })
}
Self::AdministrativeClose { request } => {
request.valid() && matches!(request.action, AdministrativeAction::Close { .. })
}
Self::AdministrativeCancel { request } => {
request.valid()
&& matches!(request.action, AdministrativeAction::CancelSubmitted { .. })
}
Self::AdministrativeStop { request } => {
request.valid() && matches!(request.action, AdministrativeAction::Stop {})
}
Self::Cancel { mutation, .. }
| Self::Close { mutation }
| Self::Restore { mutation } => (1..=i64::MAX as u64).contains(&mutation.revision),
Self::Result {
run_id,
offset,
max_bytes,
..
} => {
(4..=MAX_RESULT_TEXT_BYTES).contains(max_bytes)
&& (*offset == 0 || run_id.is_some())
&& run_id
.as_ref()
.is_none_or(|id| !id.is_empty() && id.len() <= 128)
}
Self::Submit { prompt, .. } => {
!prompt.trim().is_empty() && prompt.len() <= MAX_SUBMIT_PROMPT_BYTES
}
_ => true,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrorCode {
Unsupported,
Unauthorized,
InvalidRequest,
NotFound,
Busy,
Capacity,
StaleEpoch,
StaleRevision,
Conflict,
ResyncRequired,
PersistenceUncertain,
OutcomeUnknown,
Expired,
Internal,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum Reply {
Data {
data: Value,
},
Error {
code: ErrorCode,
},
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Response {
pub call_id: CallId,
pub epoch: Epoch,
pub reply: Reply,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mini_intents_are_closed_volatile_and_never_durable_admissions() {
let request = MiniRequest {
scope: ControlScopeId::new(),
epoch: Epoch::new(),
request_id: RequestId::new(),
action: MiniAction::Submit {
agent_id: AgentId::new(),
prompt: "literal {{mini}}".into(),
},
};
let execute = Command::MiniExecute {
request: request.clone(),
};
let query = Command::MiniReceipt {
request: request.clone(),
};
assert_eq!(execute.request_id(), Some(request.request_id));
assert_eq!(query.request_id(), None);
assert_eq!(execute.capability(), Capability::Mini);
assert!(execute.valid(Limits::default()));
for key in ["grant", "session", "durable", "revision"] {
let mut value = serde_json::to_value(&execute).unwrap();
value["request"][key] = Value::Bool(true);
assert!(serde_json::from_value::<Command>(value).is_err());
}
let mut empty = request;
empty.action = MiniAction::Submit {
agent_id: AgentId::new(),
prompt: " ".into(),
};
assert!(!empty.valid());
let mut value = serde_json::to_value(Command::MiniResult {
scope: ControlScopeId::new(),
epoch: Epoch::new(),
agent_id: AgentId::new(),
request_id: RequestId::new(),
run_id: None,
offset: 1,
max_bytes: 4096,
})
.unwrap();
assert!(!serde_json::from_value::<Command>(value.clone())
.unwrap()
.valid(Limits::default()));
value["run_id"] = serde_json::json!(RunId::new());
assert!(serde_json::from_value::<Command>(value)
.unwrap()
.valid(Limits::default()));
}
#[test]
fn golden_frames_roundtrip_and_reject_ambiguous_mutations() {
let frames: Value = serde_json::from_str(include_str!("fixtures/control-v1.json")).unwrap();
let hello: Hello = serde_json::from_value(frames["hello"].clone()).unwrap();
let welcome: Welcome = serde_json::from_value(frames["welcome"].clone()).unwrap();
assert!(welcome.compatible(hello.host_id));
assert!(welcome.supports(Capability::Status));
assert!(!welcome.supports(Capability::Unknown));
for value in frames["requests"].as_array().unwrap() {
let request: Request = serde_json::from_value(value.clone()).unwrap();
assert!(request.command.valid(welcome.limits));
assert_eq!(serde_json::to_value(request).unwrap(), *value);
}
let response: Response = serde_json::from_value(frames["response"].clone()).unwrap();
assert_eq!(serde_json::to_value(response).unwrap(), frames["response"]);
let cancel = frames["requests"]
.as_array()
.unwrap()
.iter()
.position(|value| value["command"]["op"] == "cancel")
.expect("golden fixture carries a cancel mutation");
let mut request = frames["requests"][cancel].clone();
request["command"]["mutation"]["revision"] = 0.into();
assert!(!serde_json::from_value::<Request>(request.clone())
.unwrap()
.command
.valid(welcome.limits));
request["command"]["mutation"]
.as_object_mut()
.unwrap()
.remove("request_id");
assert!(serde_json::from_value::<Request>(request).is_err());
assert!(
serde_json::from_str::<CallId>("\"00000000-0000-0000-0000-000000000000\"").is_err()
);
assert!(
serde_json::from_str::<Command>(r#"{"op":"status","argv":["--approve"]}"#).is_err()
);
let agent: AgentId = "66666666-6666-4666-8666-666666666666"
.to_string()
.try_into()
.unwrap();
let request: RequestId = "99999999-9999-4999-8999-999999999999"
.to_string()
.try_into()
.unwrap();
for prompt in [String::new(), " \n ".into()] {
assert!(!Command::Submit {
agent_id: agent,
request_id: request,
prompt
}
.valid(welcome.limits));
}
assert!(!Command::Submit {
agent_id: agent,
request_id: request,
prompt: "x".repeat(MAX_SUBMIT_PROMPT_BYTES + 1),
}
.valid(welcome.limits));
assert!(Command::Submit {
agent_id: agent,
request_id: request,
prompt: "hello".into(),
}
.valid(welcome.limits));
}
#[test]
fn result_pages_are_read_only_bounded_and_require_original_run_after_offset_zero() {
let agent_id = AgentId::new();
let request_id = RequestId::new();
let make = |run_id: Option<String>, offset, max_bytes| Command::Result {
agent_id,
request_id,
run_id,
offset,
max_bytes,
};
let command = make(None, 0, MAX_RESULT_TEXT_BYTES);
assert_eq!(command.capability(), Capability::Results);
assert!(command.request_id().is_none());
assert!(command.valid(Limits::default()));
assert!(!make(None, 1, 4096).valid(Limits::default()));
assert!(!make(Some(String::new()), 0, 4096).valid(Limits::default()));
assert!(!make(Some("x".repeat(129)), 0, 4096).valid(Limits::default()));
assert!(!make(None, 0, 3).valid(Limits::default()));
assert!(!make(None, 0, MAX_RESULT_TEXT_BYTES + 1).valid(Limits::default()));
assert!(make(Some("native-run".into()), usize::MAX, 4).valid(Limits::default()));
assert!(serde_json::from_str::<Command>(r#"{"op":"result","agent_id":"66666666-6666-4666-8666-666666666666","request_id":"99999999-9999-4999-8999-999999999999","offset":0,"max_bytes":4096,"path":"/must/not/read"}"#).is_err());
}
#[test]
fn token_debug_and_errors_never_reveal_material() {
let token = AuthToken::new("fixture-only-auth-token-0123456789".into()).unwrap();
assert_eq!(format!("{token:?}"), "AuthToken([redacted])");
assert!(token.matches(&token.clone()));
assert!(
!token.matches(&AuthToken::new("fixture-only-auth-token-9876543210".into()).unwrap())
);
assert!(AuthToken::new("private/invalid\nvalue".into()).is_err());
}
#[test]
fn future_minor_and_unknown_capability_do_not_grant_authority() {
let mut welcome: Welcome = serde_json::from_value(
serde_json::from_str::<Value>(include_str!("fixtures/control-v1.json")).unwrap()
["welcome"]
.clone(),
)
.unwrap();
welcome.version.minor = u16::MAX;
welcome
.capabilities
.push(serde_json::from_str("\"future_capability\"").unwrap());
assert!(welcome.compatible(welcome.host_id));
assert!(!welcome.supports(Capability::Unknown));
welcome.version.major += 1;
assert!(!welcome.compatible(welcome.host_id));
assert!(!Limits {
max_frame_bytes: usize::MAX,
..Limits::default()
}
.valid());
}
#[test]
fn administrative_queries_are_closed_bounded_and_never_claim_mutation_identity() {
let agent = AgentId::new();
let profile = ProfileRef {
agent_id: agent,
version: ProfileVersion::new(),
};
for action in [
AdministrativeAction::Create { agent_id: agent },
AdministrativeAction::Restore {
agent_id: agent,
revision: 1,
},
AdministrativeAction::CreateProfile { profile },
AdministrativeAction::RestoreProfile {
profile,
revision: 1,
},
AdministrativeAction::Cancel {
agent_id: agent,
revision: 1,
ticket_id: TicketId::new(),
},
AdministrativeAction::Close {
agent_id: agent,
revision: 1,
},
AdministrativeAction::Stop {},
] {
let request = AdministrativeRequest {
scope: ControlScopeId::new(),
request_id: RequestId::new(),
epoch: Epoch::new(),
action,
};
let encoded = serde_json::to_value(&request).unwrap();
assert!(serde_json::to_vec(&request).unwrap().len() < 4096);
assert_eq!(
serde_json::from_value::<AdministrativeRequest>(encoded.clone()).unwrap(),
request
);
let command = Command::AdministrativeReceipt { request };
assert!(command.valid(Limits::default()));
assert_eq!(command.request_id(), None);
assert_eq!(command.capability(), Capability::AdministrativeReceipts);
let mut injected = encoded;
injected["action"]["grant"] = serde_json::json!({"stop": true});
assert!(serde_json::from_value::<AdministrativeRequest>(injected).is_err());
}
for limit in [0, MAX_PAGE_SIZE + 1, usize::MAX] {
assert!(!Command::Profiles { after: None, limit }.valid(Limits::default()));
}
assert_eq!(
Command::Profiles {
after: None,
limit: 1
}
.request_id(),
None
);
assert!(
serde_json::from_str::<ProfileVersion>("\"00000000-0000-0000-0000-000000000000\"")
.is_err()
);
}
#[test]
fn administrative_receipt_revision_limits_and_old_epoch_are_independent_from_transport() {
for revision in [0, i64::MAX as u64 + 1, u64::MAX] {
let request = AdministrativeRequest {
scope: ControlScopeId::new(),
request_id: RequestId::new(),
epoch: Epoch::new(),
action: AdministrativeAction::Close {
agent_id: AgentId::new(),
revision,
},
};
assert!(!request.valid());
}
let frames: Value = serde_json::from_str(include_str!("fixtures/control-v1.json")).unwrap();
let frame: Request = serde_json::from_value(
frames["requests"]
.as_array()
.unwrap()
.iter()
.find(|value| value["command"]["op"] == "administrative_receipt")
.expect("golden fixture carries the original historical query")
.clone(),
)
.unwrap();
let Command::AdministrativeReceipt { request } = frame.command else {
panic!("expected administrative query");
};
assert_ne!(frame.epoch, request.epoch);
assert!(request.valid());
}
#[test]
fn administrative_cancel_binds_stable_input_and_rejects_hybrid_or_unbounded_intents() {
let request = AdministrativeRequest {
scope: ControlScopeId::new(),
request_id: RequestId::new(),
epoch: Epoch::new(),
action: AdministrativeAction::CancelSubmitted {
agent_id: AgentId::new(),
revision: 1,
submitted_request_id: RequestId::new(),
},
};
let command = Command::AdministrativeCancel {
request: request.clone(),
};
assert!(command.valid(Limits::default()));
assert_eq!(command.request_id(), Some(request.request_id));
assert_eq!(command.capability(), Capability::AdministrativeCancel);
for revision in [0, i64::MAX as u64 + 1] {
let mut value = serde_json::to_value(&command).unwrap();
value["request"]["action"]["revision"] = serde_json::json!(revision);
assert!(!serde_json::from_value::<Command>(value)
.unwrap()
.valid(Limits::default()));
}
for case in 0..4 {
let mut value = serde_json::to_value(&command).unwrap();
match case {
0 => {
value["request"]["action"]["submitted_request_id"] =
serde_json::json!("00000000-0000-0000-0000-000000000000")
}
1 => value["request"]["action"]["ticket_id"] = serde_json::json!(TicketId::new()),
2 => value["request"]["grant"] = serde_json::json!({"cancel":true}),
_ => {
value["request"]["action"]
.as_object_mut()
.unwrap()
.remove("submitted_request_id");
}
}
assert!(serde_json::from_value::<Command>(value).is_err());
}
}
#[test]
fn administrative_stop_is_closed_complete_and_distinct_from_legacy_placeholder() {
let request = AdministrativeRequest {
scope: ControlScopeId::new(),
request_id: RequestId::new(),
epoch: Epoch::new(),
action: AdministrativeAction::Stop {},
};
let command = Command::AdministrativeStop {
request: request.clone(),
};
assert!(command.valid(Limits::default()));
assert_eq!(command.request_id(), Some(request.request_id));
assert_eq!(command.capability(), Capability::AdministrativeStop);
let original = serde_json::to_value(&command).unwrap();
for field in ["scope", "request_id", "epoch", "action"] {
let mut value = original.clone();
value["request"].as_object_mut().unwrap().remove(field);
assert!(serde_json::from_value::<Command>(value).is_err());
}
for field in ["scope", "request_id", "epoch"] {
let mut value = original.clone();
value["request"][field] = serde_json::json!("00000000-0000-0000-0000-000000000000");
assert!(serde_json::from_value::<Command>(value).is_err());
}
for field in ["agent_id", "revision", "grant", "ticket_id"] {
let mut value = original.clone();
value["request"]["action"][field] = serde_json::json!(1);
assert!(serde_json::from_value::<Command>(value).is_err());
}
let legacy = Command::Stop {
request_id: request.request_id,
};
assert_eq!(legacy.capability(), Capability::Stop);
assert_ne!(legacy.capability(), command.capability());
}
#[test]
fn administrative_execution_commands_match_exact_intent_and_keep_mutation_identity() {
let agent_id = AgentId::new();
let profile = ProfileRef {
agent_id,
version: ProfileVersion::new(),
};
let actions = [
AdministrativeAction::Create { agent_id },
AdministrativeAction::Restore {
agent_id,
revision: 1,
},
AdministrativeAction::CreateProfile { profile },
AdministrativeAction::RestoreProfile {
profile,
revision: 1,
},
AdministrativeAction::Cancel {
agent_id,
revision: 1,
ticket_id: TicketId::new(),
},
AdministrativeAction::Close {
agent_id,
revision: 1,
},
AdministrativeAction::Stop {},
AdministrativeAction::CancelSubmitted {
agent_id,
revision: 1,
submitted_request_id: RequestId::new(),
},
];
type Constructor = fn(AdministrativeRequest) -> Command;
let constructors: [(Constructor, Capability, usize); 5] = [
(
|request| Command::AdministrativeCreate { request },
Capability::AdministrativeCreate,
2,
),
(
|request| Command::AdministrativeRestore { request },
Capability::AdministrativeRestore,
3,
),
(
|request| Command::AdministrativeClose { request },
Capability::AdministrativeClose,
5,
),
(
|request| Command::AdministrativeCancel { request },
Capability::AdministrativeCancel,
7,
),
(
|request| Command::AdministrativeStop { request },
Capability::AdministrativeStop,
6,
),
];
for (make, capability, allowed) in constructors {
for (index, action) in actions.iter().enumerate() {
let request = AdministrativeRequest {
scope: ControlScopeId::new(),
request_id: RequestId::new(),
epoch: Epoch::new(),
action: action.clone(),
};
let id = request.request_id;
let command = make(request);
assert_eq!(command.capability(), capability);
assert_eq!(command.request_id(), Some(id));
assert_eq!(command.valid(Limits::default()), index == allowed);
let mut value = serde_json::to_value(command).unwrap();
value["request"]["grant"] = serde_json::json!({"create": true});
assert!(serde_json::from_value::<Command>(value).is_err());
}
}
}
}