1use std::{collections::BTreeSet, sync::OnceLock};
20
21use prost::{
23 DecodeError, Message,
24 bytes::Buf,
25 encoding::{DecodeContext, WireType, decode_key, decode_varint, skip_field},
26};
27use prost_types::{DescriptorProto, FileDescriptorProto, FileDescriptorSet};
28
29use crate::{plugin, schema};
31
32pub const COMMAND_BYTES: usize = 16 * 1024 * 1024;
35pub const CONTEXT_VALUES: usize = 64;
36pub const CONTEXT_BYTES: usize = 64 * 1024;
37
38#[derive(Debug, thiserror::Error)]
45#[error("Invalid Guest Message: {0}")]
46pub struct Error(String);
47
48#[derive(Default)]
49struct ContextBudget {
50 values: usize,
51 encoded_bytes: usize,
52}
53
54enum Envelope {
57 Command,
58 Child,
59}
60
61pub fn types() -> &'static FileDescriptorSet {
68 static TYPES: OnceLock<FileDescriptorSet> = OnceLock::new();
69 TYPES.get_or_init(|| {
70 FileDescriptorSet::decode(include_bytes!("guest-descriptors.bin").as_slice()).expect("generated protocol descriptors")
71 })
72}
73
74pub fn lifecycle_fingerprint(operation: &str) -> Result<Vec<u8>, Error> {
75 let request = match operation {
76 "harmos.initialize" => "harmos.plugin.v1.GuestInitialize",
77 "harmos.shutdown" => "harmos.plugin.v1.GuestShutdown",
78 _ => return Err(Error("Declare Guest Lifecycle: Select Initialize or Shutdown".into())),
79 };
80 let mut types = types().clone();
81 types.file.push(FileDescriptorProto {
82 name: Some("google/protobuf/empty.proto".into()),
83 package: Some("google.protobuf".into()),
84 syntax: Some("proto3".into()),
85 message_type: vec![DescriptorProto {
86 name: Some("Empty".into()),
87 ..Default::default()
88 }],
89 ..Default::default()
90 });
91 schema::fingerprint(operation, &types, request, "google.protobuf.Empty").map_err(|error| Error(error.to_string()))
92}
93
94pub fn encode<M: Message>(message: &M) -> Result<Vec<u8>, Error> {
95 if message.encoded_len() > COMMAND_BYTES {
96 return Err(Error("Send Guest Message: Reduce the Encoded Payload Below the Command Byte Bound".into()));
97 }
98 Ok(message.encode_to_vec())
99}
100
101pub fn decode_command(bytes: &[u8]) -> Result<plugin::GuestCommand, Error> {
102 validate_envelope(bytes, Envelope::Command)?;
103 let command = plugin::GuestCommand::decode(bytes).map_err(encoding)?;
104 if command.phase.is_none() {
105 return Err(Error("Send Guest Command: Select a Command Phase".into()));
106 }
107 if let Some(plugin::guest_command::Phase::Initialize(invocation) | plugin::guest_command::Phase::Attempt(invocation)) = &command.phase {
108 validate_values(&invocation.values)?;
109 }
110 Ok(command)
111}
112
113pub fn decode_child(bytes: &[u8]) -> Result<plugin::GuestChild, Error> {
114 validate_envelope(bytes, Envelope::Child)?;
115 let child = plugin::GuestChild::decode(bytes).map_err(encoding)?;
116 if child.action.is_none() {
117 return Err(Error("Send Guest Child: Select a Child Action".into()));
118 }
119 if let Some(plugin::guest_child::Action::Call(call)) = &child.action {
120 validate_values(&call.values)?;
121 }
122 Ok(child)
123}
124
125pub fn validate_values(values: &[plugin::GuestValue]) -> Result<(), Error> {
126 let mut keys = BTreeSet::new();
127 let mut bytes = 0usize;
128 for value in values {
129 if value.key.is_empty() || !keys.insert(&value.key) {
130 return Err(Error("Send Guest Context: Supply Unique Nonempty Value Keys".into()));
131 }
132 bytes = bytes
133 .checked_add(value.key.len())
134 .and_then(|bytes| bytes.checked_add(value.payload.len()))
135 .ok_or_else(|| Error("Send Guest Context: Reduce the Encoded Context Size".into()))?;
136 }
137 if values.len() > CONTEXT_VALUES || bytes > CONTEXT_BYTES {
138 return Err(Error("Send Guest Context: Reduce the Value Count or Encoded Context Size".into()));
139 }
140 Ok(())
141}
142
143fn validate_envelope(mut bytes: &[u8], envelope: Envelope) -> Result<(), Error> {
147 if bytes.len() > COMMAND_BYTES {
148 return Err(Error("Send Guest Message: Reduce the Encoded Payload Below the Command Byte Bound".into()));
149 }
150 let mut budget = ContextBudget::default();
151 while bytes.has_remaining() {
152 let (tag, wire) = decode_key(&mut bytes).map_err(encoding)?;
153 let values = match envelope {
154 Envelope::Command => matches!(tag, 2 | 3).then_some(3),
155 Envelope::Child => (tag == 1).then_some(6),
156 };
157 if wire != WireType::LengthDelimited || values.is_none() {
158 skip_field(wire, tag, &mut bytes, DecodeContext::default()).map_err(encoding)?;
159 continue;
160 }
161 let nested = delimited(&mut bytes)?;
162 validate_nested(nested, values.expect("selected value field"), &mut budget)?;
163 }
164 Ok(())
165}
166
167fn validate_nested(mut bytes: &[u8], values_tag: u32, budget: &mut ContextBudget) -> Result<(), Error> {
168 while bytes.has_remaining() {
169 let (tag, wire) = decode_key(&mut bytes).map_err(encoding)?;
170 if tag != values_tag || wire != WireType::LengthDelimited {
171 skip_field(wire, tag, &mut bytes, DecodeContext::default()).map_err(encoding)?;
172 continue;
173 }
174 let value = delimited(&mut bytes)?;
175 budget.values += 1;
176 budget.encoded_bytes = budget
177 .encoded_bytes
178 .checked_add(value.len())
179 .ok_or_else(|| Error("Send Guest Context: Reduce the Encoded Context Size".into()))?;
180 let too_many_values = budget.values > CONTEXT_VALUES;
182 let too_many_bytes = budget.encoded_bytes > CONTEXT_BYTES + CONTEXT_VALUES * 20;
183 if too_many_values || too_many_bytes {
184 return Err(Error("Send Guest Context: Reduce the Value Count or Encoded Context Size".into()));
185 }
186 }
187 Ok(())
188}
189
190fn delimited<'a>(bytes: &mut &'a [u8]) -> Result<&'a [u8], Error> {
191 let size = usize::try_from(decode_varint(bytes).map_err(encoding)?).map_err(|error| Error(error.to_string()))?;
192 if size > bytes.len() {
193 return Err(Error("Decode Guest Message: Supply the Complete Length-Delimited Payload".into()));
194 }
195 let (value, rest) = bytes.split_at(size);
196 *bytes = rest;
197 Ok(value)
198}
199
200fn encoding(error: DecodeError) -> Error {
201 Error(format!("Decode Guest Message: Supply Valid Protobuf Bytes: {error}"))
202}
203
204#[cfg(test)]
207mod tests {
208 use super::*;
209 #[test]
210 fn receiving_context_rejects_amplification_and_malformed_values() {
211 let command = |values| {
212 plugin::GuestCommand {
213 phase: Some(plugin::guest_command::Phase::Attempt(plugin::GuestInvocation {
214 invocation: 1,
215 context: vec![1; 32],
216 values,
217 })),
218 }
219 .encode_to_vec()
220 };
221 let valid = plugin::GuestValue {
222 key: "trace".into(),
223 payload: vec![1, 2, 3],
224 };
225 assert!(decode_command(&command(vec![valid.clone()])).is_ok());
226 assert!(decode_command(&command(vec![valid.clone(), valid.clone()])).is_err());
227 let fragment = command(vec![valid]);
228 assert!(decode_command(&fragment.repeat(CONTEXT_VALUES + 1)).is_err());
229 assert!(decode_command(&[0x1a, 0xff]).is_err());
230 assert!(decode_command(&command(vec![plugin::GuestValue { key: String::new(), payload: Vec::new() }])).is_err());
231 assert!(
232 decode_command(&command(vec![plugin::GuestValue {
233 key: "large".into(),
234 payload: vec![0; CONTEXT_BYTES]
235 }]))
236 .is_err()
237 );
238 }
239}