1use std::time::Duration;
2use std::{collections::BTreeMap, fmt};
3
4use super::{RequestId, lifecycle::CancellationToken};
5
6#[derive(Clone, Eq, PartialEq)]
8pub struct InvocationExtension {
9 key: String,
10 value: Vec<u8>,
11}
12
13impl fmt::Debug for InvocationExtension {
14 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
15 formatter
16 .debug_struct("InvocationExtension")
17 .field("key", &self.key)
18 .field("value", &"<redacted>")
19 .finish()
20 }
21}
22
23impl InvocationExtension {
24 pub fn new(key: impl Into<String>, value: Vec<u8>) -> Self {
26 Self {
27 key: key.into(),
28 value,
29 }
30 }
31
32 pub fn key(&self) -> &str {
34 &self.key
35 }
36
37 pub fn value(&self) -> &[u8] {
39 &self.value
40 }
41}
42
43#[derive(Clone, Eq, PartialEq)]
45pub struct SealedInvocationExtension {
46 key: String,
47 issuer: String,
48 audience: Vec<String>,
49 value: Vec<u8>,
50 proof: String,
51}
52
53impl SealedInvocationExtension {
54 pub fn signed(
59 key: impl Into<String>,
60 issuer: impl Into<String>,
61 audience: impl IntoIterator<Item = impl Into<String>>,
62 value: Vec<u8>,
63 proof: impl Into<String>,
64 ) -> Self {
65 Self {
66 key: key.into(),
67 issuer: issuer.into(),
68 audience: audience.into_iter().map(Into::into).collect(),
69 value,
70 proof: proof.into(),
71 }
72 }
73
74 pub fn key(&self) -> &str {
76 &self.key
77 }
78
79 pub fn issuer(&self) -> &str {
81 &self.issuer
82 }
83
84 pub fn audience(&self) -> &[String] {
86 &self.audience
87 }
88
89 pub fn value(&self) -> &[u8] {
91 &self.value
92 }
93
94 pub fn proof(&self) -> &str {
96 &self.proof
97 }
98
99 pub fn covers(&self, capability_id: &str, operation: &str) -> bool {
101 let target = format!("{capability_id}:{operation}");
102 self.audience.iter().any(|audience| audience == &target)
103 }
104}
105
106impl fmt::Debug for SealedInvocationExtension {
107 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
108 formatter
109 .debug_struct("SealedInvocationExtension")
110 .field("key", &self.key)
111 .field("issuer", &self.issuer)
112 .field("audience", &self.audience)
113 .field("value", &"<redacted>")
114 .field("proof", &"<redacted>")
115 .finish()
116 }
117}
118
119#[derive(Clone, Debug, Eq, PartialEq)]
121pub enum InvocationContextError {
122 EmptyExtensionKey,
124 ExtensionAlreadySet { key: String },
126 SealedExtensionAlreadySet { key: String },
128 InvalidSealedExtension { key: String },
130}
131
132impl std::fmt::Display for InvocationContextError {
133 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134 match self {
135 Self::EmptyExtensionKey => {
136 formatter.write_str("Invocation Context extension key is empty")
137 }
138 Self::ExtensionAlreadySet { key } => {
139 write!(
140 formatter,
141 "Invocation Context extension `{key}` is already set"
142 )
143 }
144 Self::SealedExtensionAlreadySet { key } => {
145 write!(
146 formatter,
147 "sealed Invocation Context extension `{key}` is already set"
148 )
149 }
150 Self::InvalidSealedExtension { key } => {
151 write!(
152 formatter,
153 "sealed Invocation Context extension `{key}` has invalid provenance"
154 )
155 }
156 }
157 }
158}
159
160#[derive(Clone, Debug)]
162pub struct InvocationContext {
163 pub(super) caller_instance: Option<String>,
164 pub(super) request_id: RequestId,
165 pub(super) deadline: Option<Duration>,
166 pub(super) cancellation: CancellationToken,
167 pub(super) extensions: BTreeMap<String, InvocationExtension>,
168 pub(super) sealed_extensions: BTreeMap<String, SealedInvocationExtension>,
169}
170
171impl InvocationContext {
172 pub fn new(
174 request_id: RequestId,
175 deadline: Option<Duration>,
176 cancellation: CancellationToken,
177 ) -> Self {
178 Self {
179 caller_instance: None,
180 request_id,
181 deadline,
182 cancellation,
183 extensions: BTreeMap::new(),
184 sealed_extensions: BTreeMap::new(),
185 }
186 }
187
188 #[must_use]
190 pub fn with_caller_instance(mut self, caller_instance: impl Into<String>) -> Self {
191 self.caller_instance = Some(caller_instance.into());
192 self
193 }
194
195 pub(super) fn for_caller(mut self, caller_instance: &str) -> Self {
196 if self.caller_instance.as_deref() != Some(caller_instance) {
197 self.caller_instance = Some(caller_instance.to_owned());
198 }
199 self
200 }
201
202 pub fn caller_instance(&self) -> Option<&str> {
204 self.caller_instance.as_deref()
205 }
206
207 pub const fn request_id(&self) -> RequestId {
209 self.request_id
210 }
211
212 pub const fn deadline(&self) -> Option<Duration> {
214 self.deadline
215 }
216
217 pub fn cancellation(&self) -> CancellationToken {
219 self.cancellation.clone()
220 }
221
222 pub fn with_extension(
224 mut self,
225 key: impl Into<String>,
226 value: Vec<u8>,
227 ) -> Result<Self, InvocationContextError> {
228 let extension = InvocationExtension::new(key, value);
229 if extension.key().is_empty() {
230 return Err(InvocationContextError::EmptyExtensionKey);
231 }
232 if self.sealed_extensions.contains_key(extension.key()) {
233 return Err(InvocationContextError::SealedExtensionAlreadySet {
234 key: extension.key().to_owned(),
235 });
236 }
237 if self.extensions.contains_key(extension.key()) {
238 return Err(InvocationContextError::ExtensionAlreadySet {
239 key: extension.key().to_owned(),
240 });
241 }
242 self.extensions
243 .insert(extension.key().to_owned(), extension);
244 Ok(self)
245 }
246
247 pub fn with_sealed_extension(
249 mut self,
250 extension: SealedInvocationExtension,
251 ) -> Result<Self, InvocationContextError> {
252 if extension.key().is_empty() {
253 return Err(InvocationContextError::EmptyExtensionKey);
254 }
255 if extension.issuer().is_empty()
256 || extension.audience().is_empty()
257 || extension.proof().is_empty()
258 || extension
259 .audience()
260 .iter()
261 .any(|audience| audience.is_empty())
262 {
263 return Err(InvocationContextError::InvalidSealedExtension {
264 key: extension.key().to_owned(),
265 });
266 }
267 if self.sealed_extensions.contains_key(extension.key())
268 || self.extensions.contains_key(extension.key())
269 {
270 return Err(InvocationContextError::SealedExtensionAlreadySet {
271 key: extension.key().to_owned(),
272 });
273 }
274 self.sealed_extensions
275 .insert(extension.key().to_owned(), extension);
276 Ok(self)
277 }
278
279 pub fn extension(&self, key: &str) -> Option<&[u8]> {
281 self.extensions.get(key).map(InvocationExtension::value)
282 }
283
284 pub fn extensions(&self) -> impl Iterator<Item = &InvocationExtension> {
286 self.extensions.values()
287 }
288
289 pub fn sealed_extension(&self, key: &str) -> Option<&SealedInvocationExtension> {
291 self.sealed_extensions.get(key)
292 }
293
294 pub fn sealed_extensions(&self) -> impl Iterator<Item = &SealedInvocationExtension> {
296 self.sealed_extensions.values()
297 }
298
299 #[must_use]
304 pub fn for_target(mut self, capability_id: &str, operation: &str) -> Self {
305 self.sealed_extensions
306 .retain(|_, extension| extension.covers(capability_id, operation));
307 self
308 }
309
310 pub fn is_cancelled(&self) -> bool {
312 self.cancellation.is_cancelled()
313 }
314
315 pub fn is_expired(&self, now: Duration) -> bool {
317 self.deadline.is_some_and(|deadline| deadline <= now)
318 }
319}
320
321#[cfg(test)]
322mod tests {
323 use super::*;
324
325 #[test]
326 fn resolved_caller_reuses_matching_storage_and_overrides_spoofed_identity() {
327 let context = InvocationContext::new(1, None, CancellationToken::new())
328 .with_caller_instance("consumer".to_owned());
329 let original = context.caller_instance().unwrap().as_ptr();
330 let context = context.for_caller("consumer");
331 assert_eq!(context.caller_instance().unwrap().as_ptr(), original);
332
333 let context = context.for_caller("resolved-consumer");
334 assert_eq!(context.caller_instance(), Some("resolved-consumer"));
335 }
336}