1#![forbid(unsafe_code)]
2#![cfg_attr(test, allow(clippy::unwrap_used))]
3#![cfg_attr(
4 test,
5 allow(
6 clippy::disallowed_methods,
7 clippy::disallowed_types,
8 reason = "tests spawn, join and drain freely; production sites carry their own expectation"
9 )
10)]
11use std::{collections::BTreeMap, fmt, io, time::Duration};
12
13#[cfg(unix)]
14use std::{
15 env,
16 os::unix::fs::{FileTypeExt as _, MetadataExt as _, PermissionsExt as _},
17 path::{Path, PathBuf},
18};
19
20pub use dekopon_capability::{InvocationOutcome, InvocationResult};
21pub use dekopon_core::ProviderFailureDetail;
22
23mod conversation;
24#[cfg(unix)]
25mod descriptor;
26#[cfg(unix)]
27pub use descriptor::DescriptorStream;
28#[cfg(unix)]
29use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
30
31pub use conversation::{
32 Conversation, ConversationKind, ConversationKindMatch, ConversationMatch,
33 ConversationMatchProblem,
34};
35use conversation::{
36 bounded_scope_part, canonical_meta_decimal, canonical_positive_service_decimal,
37 canonical_signed_decimal, canonical_slack_timestamp, canonical_unsigned_decimal,
38};
39use dekopon_core::{
40 AgentId, AttestedSubject, CapabilityId, InvocationId, PrincipalId, ProviderId,
41 SecretUseProposal, TraceId, TraceIdError, TransportId,
42};
43use dekopon_provider_sdk::ProviderCapability;
44pub use dekopon_provider_sdk::{CommandRunOutcome, ComponentFailure};
45use serde::{Deserialize, Serialize, de::DeserializeOwned};
46use serde_json::Value;
47use thiserror::Error;
48use tokio::{
49 io::{AsyncRead, AsyncReadExt as _, AsyncWrite, AsyncWriteExt as _},
50 time::timeout,
51};
52
53#[cfg(unix)]
54use tokio::net::UnixStream;
55
56pub const PROTOCOL_VERSION: &str = "dekopon.dev/broker/v1alpha2";
57pub const DEFAULT_MAX_FRAME_BYTES: usize = 2 * 1024 * 1024;
58pub const HARD_MAX_FRAME_BYTES: usize = 16 * 1024 * 1024;
59pub const DEFAULT_IO_TIMEOUT: Duration = Duration::from_secs(30);
60pub const ERROR_UNAUTHENTICATED: &str = "unauthenticated";
61const ERROR_UNMAPPED_SUBJECT: &str = "unmapped-subject";
62const ERROR_AGENT_DENIED: &str = "agent-denied";
63
64#[derive(Clone, Debug, PartialEq, Eq)]
65pub enum SessionRefusal {
66 UnmappedSubject,
67 AgentDenied { principal: PrincipalId },
68 Other,
69}
70
71impl SessionRefusal {
72 pub fn from_error(code: &str, message: &str) -> Result<Self, dekopon_core::IdentifierError> {
73 match code {
74 ERROR_UNMAPPED_SUBJECT => Ok(Self::UnmappedSubject),
75 ERROR_AGENT_DENIED => message
76 .parse()
77 .map(|principal| Self::AgentDenied { principal }),
78 _ => Ok(Self::Other),
79 }
80 }
81}
82
83pub const ERROR_INVALID_REQUEST: &str = "invalid-request";
84pub const ERROR_BROKER_UNAVAILABLE: &str = "broker-unavailable";
85
86pub const ERROR_OUTCOME_UNAUDITED: &str = "outcome-unaudited";
87pub const ERROR_STORAGE_QUOTA: &str = "storage-quota";
88pub const ERROR_STORAGE_BUSY: &str = "storage-busy";
89pub const ERROR_STORAGE_TIMEOUT: &str = "storage-timeout";
90pub const ERROR_STORAGE_CORRUPT: &str = "storage-corrupt";
91pub const ERROR_STORAGE_IO: &str = "storage-io";
92
93pub const ERROR_CAPACITY_EXHAUSTED: &str = "capacity-exhausted";
94
95#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
96pub enum ProtocolVersion {
97 #[serde(rename = "dekopon.dev/broker/v1alpha2")]
98 V1Alpha2,
99 #[serde(rename = "dekopon.dev/broker/v1alpha3")]
100 V1Alpha3,
101}
102
103#[derive(Clone, Copy, Debug, Eq, PartialEq)]
104pub struct TraceParent {
105 trace: TraceId,
106 parent_id: [u8; 8],
107 flags: u8,
108}
109
110impl TraceParent {
111 pub const fn new(
112 trace_id: [u8; 16],
113 parent_id: [u8; 8],
114 flags: u8,
115 ) -> Result<Self, TraceParentError> {
116 let Ok(trace) = TraceId::new(trace_id) else {
117 return Err(TraceParentError::ZeroTraceId);
118 };
119 if u64::from_be_bytes(parent_id) == 0 {
120 return Err(TraceParentError::ZeroParentId);
121 }
122 Ok(Self {
123 trace,
124 parent_id,
125 flags,
126 })
127 }
128
129 #[must_use]
130 pub const fn trace(&self) -> TraceId {
131 self.trace
132 }
133
134 #[must_use]
135 pub const fn trace_id(&self) -> [u8; 16] {
136 self.trace.to_bytes()
137 }
138
139 #[must_use]
140 pub const fn parent_id(&self) -> [u8; 8] {
141 self.parent_id
142 }
143
144 #[must_use]
145 pub const fn flags(&self) -> u8 {
146 self.flags
147 }
148}
149
150impl fmt::Display for TraceParent {
151 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
152 write!(formatter, "00-{}-", self.trace)?;
153 for byte in self.parent_id {
154 write!(formatter, "{byte:02x}")?;
155 }
156 write!(formatter, "-{:02x}", self.flags)
157 }
158}
159
160impl std::str::FromStr for TraceParent {
161 type Err = TraceParentError;
162
163 fn from_str(value: &str) -> Result<Self, Self::Err> {
164 let mut fields = value.split('-');
165 let (Some(version), Some(trace), Some(parent), Some(flags), None) = (
166 fields.next(),
167 fields.next(),
168 fields.next(),
169 fields.next(),
170 fields.next(),
171 ) else {
172 return Err(TraceParentError::Malformed);
173 };
174 if version != "00" {
175 return Err(TraceParentError::UnsupportedVersion {
176 version: version.to_owned(),
177 });
178 }
179 let trace = trace.parse::<TraceId>().map_err(|error| match error {
180 TraceIdError::Zero => TraceParentError::ZeroTraceId,
181 TraceIdError::Malformed => TraceParentError::Malformed,
182 })?;
183 let mut parent_id = [0_u8; 8];
184 decode_hex(parent, &mut parent_id)?;
185 let mut flag_byte = [0_u8; 1];
186 decode_hex(flags, &mut flag_byte)?;
187 Self::new(trace.to_bytes(), parent_id, flag_byte[0])
188 }
189}
190
191#[allow(
192 clippy::map_err_ignore,
193 reason = "the guards below already proved exact width and all-lowercase ASCII hex, so the \
194 digit-pair ParseIntError is unreachable"
195)]
196fn decode_hex(text: &str, output: &mut [u8]) -> Result<(), TraceParentError> {
197 if text.len() != output.len() * 2 || !text.bytes().all(|byte| byte.is_ascii_hexdigit()) {
198 return Err(TraceParentError::Malformed);
199 }
200 if text.bytes().any(|byte| byte.is_ascii_uppercase()) {
203 return Err(TraceParentError::Malformed);
204 }
205 for (index, slot) in output.iter_mut().enumerate() {
206 let start = index * 2;
207 *slot = u8::from_str_radix(&text[start..start + 2], 16)
208 .map_err(|_| TraceParentError::Malformed)?;
209 }
210 Ok(())
211}
212
213impl Serialize for TraceParent {
214 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
215 serializer.collect_str(self)
216 }
217}
218
219impl<'de> Deserialize<'de> for TraceParent {
220 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
221 let text = String::deserialize(deserializer)?;
222 text.parse().map_err(serde::de::Error::custom)
223 }
224}
225
226#[derive(Clone, Debug, Error, Eq, PartialEq)]
227pub enum TraceParentError {
228 #[error("traceparent must be `00-<32 hex>-<16 hex>-<2 hex>`")]
229 Malformed,
230 #[error("unsupported traceparent version {version:?}; only `00` is accepted")]
231 UnsupportedVersion { version: String },
232 #[error("traceparent trace identifier must not be all zeroes")]
233 ZeroTraceId,
234 #[error("traceparent parent identifier must not be all zeroes")]
235 ZeroParentId,
236}
237
238#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
239#[serde(deny_unknown_fields, rename_all = "camelCase")]
240pub struct InvocationRequest {
241 pub id: InvocationId,
242 pub capability: CapabilityId,
243 pub trace_parent: TraceParent,
244 #[serde(default, skip_serializing_if = "Option::is_none")]
245 pub secret_use: Option<SecretUseProposal>,
246 pub input: Value,
247}
248
249#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
250#[serde(rename_all = "camelCase")]
251pub enum ChatTransportKind {
252 Fauxlack,
253 Slack,
254 Discord,
255 Telegram,
256 Whatsapp,
257 Github,
258 Local,
259}
260
261impl fmt::Display for ChatTransportKind {
262 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
263 formatter.write_str(match self {
264 Self::Fauxlack => "fauxlack",
265 Self::Slack => "slack",
266 Self::Discord => "discord",
267 Self::Telegram => "telegram",
268 Self::Whatsapp => "whatsapp",
269 Self::Github => "github",
270 Self::Local => "local",
271 })
272 }
273}
274
275#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
276#[serde(rename_all = "camelCase")]
277pub enum Trigger {
278 Message,
279 Wake,
280 Probe,
281 Job,
282}
283
284impl Trigger {
285 #[must_use]
286 pub const fn as_str(self) -> &'static str {
287 match self {
288 Self::Message => "message",
289 Self::Wake => "wake",
290 Self::Probe => "probe",
291 Self::Job => "job",
292 }
293 }
294}
295
296#[derive(Clone, Deserialize, Eq, PartialEq, Serialize)]
297#[serde(deny_unknown_fields, rename_all = "camelCase")]
298pub struct ChatScopeClaim {
299 pub transport: TransportId,
300 pub kind: ChatTransportKind,
301 pub conversation: Conversation,
302 pub trigger: Trigger,
303 #[serde(default, skip_serializing_if = "Option::is_none")]
304 pub delivery: Option<DeliveryIdentity>,
305 #[serde(default, skip_serializing_if = "Option::is_none")]
306 pub participant: Option<String>,
307 #[serde(default, skip_serializing_if = "Option::is_none")]
308 pub github: Option<dekopon_core::github::GithubBatch>,
309}
310
311impl fmt::Debug for ChatScopeClaim {
312 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
313 formatter.write_str("ChatScopeClaim([REDACTED])")
314 }
315}
316
317impl ChatScopeClaim {
318 #[must_use]
319 pub fn is_bounded(&self) -> bool {
320 self.conversation.is_bounded()
321 && self.participant.as_deref().is_none_or(|handle| {
322 handle
323 .strip_prefix('p')
324 .and_then(|n| n.parse::<u8>().ok())
325 .is_some_and(|n| n > 0 && handle == format!("p{n}"))
326 })
327 }
328}
329
330fn deserialize_scope_part<'de, D>(deserializer: D) -> Result<String, D::Error>
331where
332 D: serde::Deserializer<'de>,
333{
334 let value = deserialize_bounded_string::<D, 256>(deserializer)?;
335 bounded_scope_part(&value)
336 .then_some(value)
337 .ok_or_else(|| serde::de::Error::custom("chat scope part is not canonical"))
338}
339
340fn deserialize_bounded_string<'de, D, const MAXIMUM: usize>(
341 deserializer: D,
342) -> Result<String, D::Error>
343where
344 D: serde::Deserializer<'de>,
345{
346 struct Visitor<const MAXIMUM: usize>;
347
348 impl<'de, const MAXIMUM: usize> serde::de::Visitor<'de> for Visitor<MAXIMUM> {
349 type Value = String;
350
351 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
352 write!(formatter, "a string no longer than {MAXIMUM} bytes")
353 }
354
355 fn visit_borrowed_str<E>(self, value: &'de str) -> Result<Self::Value, E>
356 where
357 E: serde::de::Error,
358 {
359 self.visit_str(value)
360 }
361
362 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
363 where
364 E: serde::de::Error,
365 {
366 if value.len() > MAXIMUM {
367 return Err(E::invalid_length(value.len(), &self));
368 }
369 Ok(value.to_owned())
370 }
371
372 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
373 where
374 E: serde::de::Error,
375 {
376 if value.len() > MAXIMUM {
377 return Err(E::invalid_length(value.len(), &self));
378 }
379 Ok(value)
380 }
381 }
382
383 deserializer.deserialize_string(Visitor::<MAXIMUM>)
384}
385
386#[derive(Clone, Deserialize, Eq, PartialEq, Serialize)]
387#[serde(deny_unknown_fields, rename_all = "camelCase")]
388pub struct Attestation {
389 pub subjects: AttestedSubject,
390 pub agent: AgentId,
391 #[serde(default, skip_serializing_if = "Option::is_none")]
392 pub scope: Option<ChatScopeClaim>,
393 #[serde(default, skip_serializing_if = "Option::is_none")]
394 pub invocation: Option<InvocationId>,
395}
396
397impl fmt::Debug for Attestation {
398 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
399 formatter.write_str("Attestation([REDACTED])")
400 }
401}
402
403impl Attestation {
404 #[must_use]
405 pub const fn for_subject(subjects: AttestedSubject, agent: AgentId) -> Self {
406 Self {
407 subjects,
408 agent,
409 scope: None,
410 invocation: None,
411 }
412 }
413
414 #[must_use]
415 pub const fn for_chat(
416 subjects: AttestedSubject,
417 agent: AgentId,
418 scope: ChatScopeClaim,
419 ) -> Self {
420 Self {
421 subjects,
422 agent,
423 scope: Some(scope),
424 invocation: None,
425 }
426 }
427
428 #[must_use]
429 pub fn bound_to(&self, invocation: InvocationId) -> Self {
430 Self {
431 invocation: Some(invocation),
432 ..self.clone()
433 }
434 }
435
436 #[must_use]
437 pub fn is_well_formed(&self) -> bool {
438 self.scope.as_ref().is_none_or(ChatScopeClaim::is_bounded)
439 }
440
441 #[must_use]
442 pub fn binds(&self, invocation: &InvocationId) -> bool {
443 self.invocation.as_ref() == Some(invocation)
444 }
445}
446
447#[derive(Clone, Deserialize, Eq, PartialEq, Serialize)]
448#[serde(
449 tag = "kind",
450 deny_unknown_fields,
451 rename_all = "camelCase",
452 rename_all_fields = "camelCase"
453)]
454pub enum DeliveryIdentity {
455 Fauxlack {
456 #[serde(deserialize_with = "deserialize_scope_part")]
457 channel: String,
458 #[serde(deserialize_with = "deserialize_scope_part")]
459 message: String,
460 },
461 Github {
462 #[serde(deserialize_with = "deserialize_scope_part")]
463 delivery: String,
464 },
465 Slack {
466 #[serde(deserialize_with = "deserialize_scope_part")]
467 channel: String,
468 #[serde(deserialize_with = "deserialize_scope_part")]
469 timestamp: String,
470 },
471 Discord {
472 #[serde(deserialize_with = "deserialize_scope_part")]
473 channel: String,
474 #[serde(deserialize_with = "deserialize_scope_part")]
475 message: String,
476 },
477 Telegram {
478 #[serde(deserialize_with = "deserialize_signed_service_decimal")]
479 chat: String,
480 #[serde(
481 default,
482 deserialize_with = "deserialize_optional_positive_service_decimal"
483 )]
484 topic: Option<String>,
485 #[serde(deserialize_with = "deserialize_positive_service_decimal")]
486 message: String,
487 },
488 Whatsapp {
489 #[serde(deserialize_with = "deserialize_meta_decimal")]
490 waba: String,
491 #[serde(deserialize_with = "deserialize_meta_decimal")]
492 phone_number: String,
493 #[serde(deserialize_with = "deserialize_whatsapp_message_id")]
494 message: String,
495 },
496 Local {
497 transport: TransportId,
498 #[serde(deserialize_with = "deserialize_scope_part")]
499 conversation: String,
500 #[serde(deserialize_with = "deserialize_scope_part")]
501 boot_nonce: String,
502 connection: u64,
503 sequence: u64,
504 },
505}
506
507impl fmt::Debug for DeliveryIdentity {
508 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
509 formatter.write_str("DeliveryIdentity([REDACTED])")
510 }
511}
512
513impl DeliveryIdentity {
514 #[must_use]
515 pub fn is_canonical_for(&self, scope: &ChatScopeClaim) -> bool {
516 let conversation = &scope.conversation;
517 let kind = match self {
518 Self::Fauxlack { .. } => ChatTransportKind::Fauxlack,
519 Self::Slack { .. } => ChatTransportKind::Slack,
520 Self::Discord { .. } => ChatTransportKind::Discord,
521 Self::Telegram { .. } => ChatTransportKind::Telegram,
522 Self::Whatsapp { .. } => ChatTransportKind::Whatsapp,
523 Self::Github { .. } => ChatTransportKind::Github,
524 Self::Local { .. } => ChatTransportKind::Local,
525 };
526 if kind != scope.kind {
527 return false;
528 }
529 match self {
530 Self::Fauxlack { channel, message } => {
531 channel == &conversation.id && conversation::canonical_fauxlack_message(message)
532 }
533 Self::Github { delivery } => bounded_scope_part(delivery),
534 Self::Slack { channel, timestamp } => {
535 channel == &conversation.id && canonical_slack_timestamp(timestamp)
536 }
537 Self::Discord { channel, message } => {
538 channel == conversation.api_channel(ChatTransportKind::Discord)
541 && canonical_unsigned_decimal(channel)
542 && canonical_unsigned_decimal(message)
543 }
544 Self::Telegram {
545 chat,
546 topic,
547 message,
548 } => {
549 chat == &conversation.id
550 && canonical_signed_decimal(chat)
551 && topic.as_deref() == conversation.thread.as_deref()
552 && topic
553 .as_deref()
554 .is_none_or(canonical_positive_service_decimal)
555 && canonical_positive_service_decimal(message)
556 }
557 Self::Whatsapp {
558 waba,
559 phone_number,
560 message,
561 } => {
562 conversation.container.as_deref() == Some(&format!("{waba}:{phone_number}"))
563 && canonical_meta_decimal(waba)
564 && canonical_meta_decimal(phone_number)
565 && canonical_whatsapp_message_id(message)
566 }
567 Self::Local {
568 transport,
569 conversation: named,
570 boot_nonce,
571 connection,
572 sequence,
573 } => {
574 transport == &scope.transport
575 && named == &conversation.key()
576 && boot_nonce.len() == 32
577 && boot_nonce
578 .bytes()
579 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
580 && *connection > 0
581 && *sequence > 0
582 }
583 }
584 }
585}
586
587fn deserialize_whatsapp_message_id<'de, D>(deserializer: D) -> Result<String, D::Error>
588where
589 D: serde::Deserializer<'de>,
590{
591 let value = deserialize_bounded_string::<D, 256>(deserializer)?;
592 canonical_whatsapp_message_id(&value)
593 .then_some(value)
594 .ok_or_else(|| serde::de::Error::custom("WhatsApp message ID is not canonical"))
595}
596
597fn canonical_whatsapp_message_id(value: &str) -> bool {
598 !value.is_empty() && value.len() <= 256 && value.bytes().all(|byte| byte.is_ascii_graphic())
599}
600
601fn deserialize_meta_decimal<'de, D>(deserializer: D) -> Result<String, D::Error>
602where
603 D: serde::Deserializer<'de>,
604{
605 let value = deserialize_bounded_string::<D, 64>(deserializer)?;
606 canonical_meta_decimal(&value)
607 .then_some(value)
608 .ok_or_else(|| serde::de::Error::custom("identifier is not a canonical Meta decimal"))
609}
610
611fn deserialize_positive_service_decimal<'de, D>(deserializer: D) -> Result<String, D::Error>
612where
613 D: serde::Deserializer<'de>,
614{
615 let value = deserialize_bounded_string::<D, 256>(deserializer)?;
616 canonical_positive_service_decimal(&value)
617 .then_some(value)
618 .ok_or_else(|| serde::de::Error::custom("identifier is outside the positive service range"))
619}
620
621fn deserialize_signed_service_decimal<'de, D>(deserializer: D) -> Result<String, D::Error>
622where
623 D: serde::Deserializer<'de>,
624{
625 let value = deserialize_bounded_string::<D, 256>(deserializer)?;
626 canonical_signed_decimal(&value)
627 .then_some(value)
628 .ok_or_else(|| serde::de::Error::custom("identifier is outside the signed service range"))
629}
630
631fn deserialize_optional_positive_service_decimal<'de, D>(
632 deserializer: D,
633) -> Result<Option<String>, D::Error>
634where
635 D: serde::Deserializer<'de>,
636{
637 struct OptionalServiceDecimal;
638
639 impl<'de> serde::de::Visitor<'de> for OptionalServiceDecimal {
640 type Value = Option<String>;
641
642 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
643 formatter.write_str("null or a canonical positive signed-service identifier")
644 }
645
646 fn visit_none<E>(self) -> Result<Self::Value, E>
647 where
648 E: serde::de::Error,
649 {
650 Ok(None)
651 }
652
653 fn visit_unit<E>(self) -> Result<Self::Value, E>
654 where
655 E: serde::de::Error,
656 {
657 Ok(None)
658 }
659
660 fn visit_some<Inner>(self, deserializer: Inner) -> Result<Self::Value, Inner::Error>
661 where
662 Inner: serde::Deserializer<'de>,
663 {
664 deserialize_positive_service_decimal(deserializer).map(Some)
665 }
666 }
667
668 deserializer.deserialize_option(OptionalServiceDecimal)
669}
670
671const MAX_DELIVERED_TURN_TEXT_BYTES: usize = 64 * 1024;
672
673#[derive(Clone, Eq, PartialEq, Serialize)]
674#[serde(transparent)]
675pub struct DeliveredAnswer(String);
676
677impl DeliveredAnswer {
678 #[must_use]
679 pub fn accepted_by_transport(text: String) -> Self {
680 Self(text)
681 }
682
683 #[must_use]
684 pub fn as_str(&self) -> &str {
685 &self.0
686 }
687}
688
689#[derive(Clone, Deserialize, Eq, PartialEq, Serialize)]
690#[serde(deny_unknown_fields, rename_all = "camelCase")]
691pub struct DeliveredTurnRequest {
692 pub id: InvocationId,
693 pub trace_parent: TraceParent,
694 pub delivery: DeliveryIdentity,
695 #[serde(deserialize_with = "deserialize_turn_text")]
696 user: String,
697 #[serde(deserialize_with = "deserialize_delivered_answer")]
698 assistant: DeliveredAnswer,
699}
700
701impl fmt::Debug for DeliveredTurnRequest {
702 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
703 formatter.write_str("DeliveredTurnRequest([REDACTED])")
704 }
705}
706
707impl DeliveredTurnRequest {
708 #[must_use]
709 pub fn new(
710 id: InvocationId,
711 trace_parent: TraceParent,
712 delivery: DeliveryIdentity,
713 mut user: String,
714 assistant: DeliveredAnswer,
715 ) -> Self {
716 let budget = MAX_DELIVERED_TURN_TEXT_BYTES.saturating_sub(assistant.0.len());
717 if user.len() > budget {
718 const MARKER: &str = "[…]";
719 user.truncate(user.floor_char_boundary(budget.saturating_sub(MARKER.len())));
720 user.push_str(MARKER);
721 }
722 Self {
723 id,
724 trace_parent,
725 delivery,
726 user,
727 assistant,
728 }
729 }
730
731 #[must_use]
732 pub fn user(&self) -> &str {
733 &self.user
734 }
735
736 #[must_use]
737 pub fn assistant(&self) -> &DeliveredAnswer {
738 &self.assistant
739 }
740
741 #[must_use]
742 pub fn is_bounded(&self) -> bool {
743 self.user
744 .len()
745 .checked_add(self.assistant.0.len())
746 .is_some_and(|bytes| bytes <= MAX_DELIVERED_TURN_TEXT_BYTES)
747 }
748}
749
750fn deserialize_turn_text<'de, D>(deserializer: D) -> Result<String, D::Error>
751where
752 D: serde::Deserializer<'de>,
753{
754 deserialize_bounded_string::<D, MAX_DELIVERED_TURN_TEXT_BYTES>(deserializer)
755}
756
757fn deserialize_delivered_answer<'de, D>(deserializer: D) -> Result<DeliveredAnswer, D::Error>
758where
759 D: serde::Deserializer<'de>,
760{
761 deserialize_turn_text(deserializer).map(DeliveredAnswer)
762}
763
764#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
765#[serde(deny_unknown_fields, rename_all = "camelCase")]
766pub struct ChatMemorySurface {
767 pub max_lookback_turns: u32,
768 pub prompt_note: String,
769}
770
771#[derive(Clone, Debug, PartialEq)]
772pub struct SessionSurface {
773 pub capabilities: Vec<AvailableCapability>,
774 pub command_words: Vec<String>,
775 pub command_word_help: BTreeMap<String, String>,
776 pub chat_memory: Option<ChatMemorySurface>,
777 pub principal: Option<PrincipalId>,
778 pub space: Option<Vec<CapabilityId>>,
779}
780
781#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
782#[serde(deny_unknown_fields, rename_all = "camelCase")]
783pub struct AvailableCapability {
784 pub provider: ProviderId,
785 pub capability: ProviderCapability,
786}
787
788#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
789#[serde(deny_unknown_fields, rename_all = "camelCase")]
790pub struct RequestEnvelope {
791 pub api_version: ProtocolVersion,
792 pub request: BrokerRequest,
793}
794
795impl RequestEnvelope {
796 #[must_use]
797 pub const fn capabilities(attestation: Option<Attestation>) -> Self {
798 Self {
799 api_version: ProtocolVersion::V1Alpha2,
800 request: BrokerRequest::Capabilities { attestation },
801 }
802 }
803
804 #[must_use]
805 pub const fn invoke(
806 attestation: Option<Attestation>,
807 invocation: InvocationRequest,
808 assets: Vec<AssetRow>,
809 sends_remaining: u8,
810 streams: Option<StreamDescriptors>,
811 ) -> Self {
812 Self {
813 api_version: ProtocolVersion::V1Alpha2,
814 request: BrokerRequest::Invoke {
815 attestation,
816 invocation,
817 assets,
818 sends_remaining,
819 streams,
820 },
821 }
822 }
823
824 #[must_use]
825 pub fn upcall_result(exit: UpcallExit) -> Self {
826 Self {
827 api_version: ProtocolVersion::V1Alpha2,
828 request: BrokerRequest::UpcallResult {
829 status: exit.status,
830 stderr: exit.stderr,
831 },
832 }
833 }
834
835 #[must_use]
836 pub const fn record_delivered_turn(
837 attestation: Attestation,
838 turn: DeliveredTurnRequest,
839 ) -> Self {
840 Self {
841 api_version: ProtocolVersion::V1Alpha2,
842 request: BrokerRequest::RecordDeliveredTurn { attestation, turn },
843 }
844 }
845}
846
847#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
848#[serde(tag = "operation", deny_unknown_fields, rename_all = "camelCase")]
849pub enum BrokerRequest {
850 Capabilities {
851 #[serde(default, skip_serializing_if = "Option::is_none")]
852 attestation: Option<Attestation>,
853 },
854 Run {
855 #[serde(default, skip_serializing_if = "Option::is_none")]
856 attestation: Option<Attestation>,
857 #[serde(rename = "traceParent")]
858 trace_parent: TraceParent,
859 invocation: InvocationId,
860 word: String,
861 argv: Vec<Arg>,
862 #[serde(default)]
863 assets: Vec<AssetRow>,
864 #[serde(rename = "sendsRemaining")]
865 sends_remaining: u8,
866 streams: StreamDescriptors,
867 },
868 Invoke {
869 #[serde(default, skip_serializing_if = "Option::is_none")]
870 attestation: Option<Attestation>,
871 invocation: InvocationRequest,
872 #[serde(default)]
873 assets: Vec<AssetRow>,
874 #[serde(default, rename = "sendsRemaining")]
875 sends_remaining: u8,
876 #[serde(default, skip_serializing_if = "Option::is_none")]
877 streams: Option<StreamDescriptors>,
878 },
879 RecordDeliveredTurn {
880 attestation: Attestation,
881 turn: DeliveredTurnRequest,
882 },
883 UpcallResult {
884 status: u8,
885 stderr: String,
886 },
887 PrepareGeneration {
889 digest: String,
890 },
891 CommitGeneration {
892 digest: String,
893 },
894 AbortGeneration {
895 digest: String,
896 },
897 ObserveGeneration,
898}
899
900impl BrokerRequest {
901 pub fn validate(&self) -> Result<(), ProtocolError> {
902 match self {
903 Self::Run { argv, assets, .. } => {
904 if assets.len() > MAX_ASSET_DESCRIPTORS {
905 return Err(ProtocolError::TooManyAssetRows);
906 }
907 let mut named = [false; MAX_ASSET_DESCRIPTORS];
908 for argument in argv {
909 match argument {
910 Arg::Text(_) => {}
911 Arg::Asset(index) => {
912 let index = usize::from(index.0);
913 if index >= assets.len() {
914 return Err(ProtocolError::UnknownAssetIndex);
915 }
916 named[index] = true;
917 }
918 }
919 }
920 let mut ids = std::collections::BTreeSet::new();
921 for (index, row) in assets.iter().enumerate() {
922 if !ids.insert(row.id) {
923 return Err(ProtocolError::DuplicateAssetRow);
924 }
925 if !named[index] {
926 return Err(ProtocolError::UnreferencedAsset);
927 }
928 }
929 Ok(())
930 }
931 Self::Invoke { assets, .. } if assets.len() > MAX_ASSET_ROWS => {
932 Err(ProtocolError::TooManyAssetRows)
933 }
934 Self::PrepareGeneration { digest }
935 | Self::CommitGeneration { digest }
936 | Self::AbortGeneration { digest }
937 if !valid_generation_digest(digest) =>
938 {
939 Err(ProtocolError::InvalidGenerationDigest)
940 }
941 Self::Invoke { .. }
942 | Self::Capabilities { .. }
943 | Self::RecordDeliveredTurn { .. }
944 | Self::UpcallResult { .. }
945 | Self::PrepareGeneration { .. }
946 | Self::CommitGeneration { .. }
947 | Self::AbortGeneration { .. }
948 | Self::ObserveGeneration => Ok(()),
949 }
950 }
951}
952
953fn valid_generation_digest(digest: &str) -> bool {
954 digest.len() == 64
955 && digest
956 .bytes()
957 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
958}
959
960pub struct RunRequest {
961 pub invocation: InvocationId,
962 pub trace_parent: TraceParent,
963 pub word: String,
964 pub argv: Vec<Arg>,
965}
966
967#[cfg(unix)]
968pub struct RunResponse {
969 pub outcome: RunOutcome,
970 pub descriptors: Vec<OwnedFd>,
971}
972
973#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
974#[serde(rename_all = "camelCase", deny_unknown_fields)]
975pub enum Arg {
976 Text(String),
977 Asset(AssetIndex),
978}
979
980#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)]
981#[serde(try_from = "u8", into = "u8")]
982pub struct AssetIndex(u8);
983
984impl AssetIndex {
985 #[must_use]
986 pub const fn get(self) -> u8 {
987 self.0
988 }
989}
990
991impl TryFrom<u8> for AssetIndex {
992 type Error = ProtocolError;
993 fn try_from(index: u8) -> Result<Self, Self::Error> {
994 if usize::from(index) < MAX_ASSET_DESCRIPTORS {
995 Ok(Self(index))
996 } else {
997 Err(ProtocolError::UnknownAssetIndex)
998 }
999 }
1000}
1001
1002impl From<AssetIndex> for u8 {
1003 fn from(index: AssetIndex) -> Self {
1004 index.0
1005 }
1006}
1007
1008#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
1009#[serde(tag = "type", rename_all = "camelCase", deny_unknown_fields)]
1010#[expect(
1011 clippy::large_enum_variant,
1012 reason = "the frozen wire contract keeps InvocationResult inline"
1013)]
1014pub enum RunOutcome {
1015 Rendered {
1016 stdout: String,
1017 stderr: String,
1018 status: u8,
1019 },
1020 Refused {
1021 error: ComponentFailure,
1022 },
1023 NotGranted {
1024 capability: CapabilityId,
1025 },
1026 NotFound,
1027 Invoked {
1028 capability: CapabilityId,
1029 input: Value,
1030 #[serde(default, skip_serializing_if = "Option::is_none")]
1031 secret_use: Option<SecretUseProposal>,
1032 result: InvocationResult,
1033 #[serde(default)]
1034 attached: Vec<NewAsset>,
1035 #[serde(default)]
1036 removed: Vec<u64>,
1037 #[serde(default)]
1038 sent: Vec<u64>,
1039 },
1040}
1041
1042pub const MAX_ASSET_ROWS: usize = MAX_ASSET_DESCRIPTORS;
1043pub const MAX_ASSET_DESCRIPTORS: usize = 5;
1044pub const MAX_DECODED_INPUT_BYTES: usize =
1045 MAX_ASSET_DESCRIPTORS * dekopon_core::asset::MAX_DECODED_DOCUMENT_BYTES;
1046pub const MAX_STREAM_DESCRIPTORS: usize = 2;
1047pub const MAX_DESCRIPTORS_PER_FRAME: usize = 8;
1048
1049#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
1050#[serde(deny_unknown_fields, rename_all = "camelCase")]
1051pub struct StreamDescriptors {
1052 pub stdin: bool,
1053}
1054
1055impl StreamDescriptors {
1056 #[must_use]
1057 pub const fn count(self) -> usize {
1058 if self.stdin { 2 } else { 1 }
1059 }
1060}
1061
1062#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
1063#[serde(rename_all = "camelCase")]
1064pub enum UpcallStdin {
1065 None,
1066 Inherit,
1067 Reader,
1068}
1069
1070impl UpcallStdin {
1071 #[must_use]
1072 pub const fn descriptor_count(self) -> usize {
1073 match self {
1074 Self::None => 1,
1075 Self::Inherit | Self::Reader => 2,
1076 }
1077 }
1078
1079 fn check(self, count: usize) -> Result<(), ProtocolError> {
1080 match count.cmp(&self.descriptor_count()) {
1081 std::cmp::Ordering::Less => Err(ProtocolError::MissingStreamDescriptors),
1082 std::cmp::Ordering::Greater => Err(ProtocolError::UnexpectedDescriptors),
1083 std::cmp::Ordering::Equal => Ok(()),
1084 }
1085 }
1086}
1087
1088#[cfg(unix)]
1089#[derive(Debug)]
1090pub struct UpcallStreams {
1091 pub stdout: OwnedFd,
1092 pub stdin: Option<OwnedFd>,
1093}
1094
1095#[cfg(unix)]
1096impl UpcallStreams {
1097 pub fn receive(stdin: UpcallStdin, descriptors: Vec<OwnedFd>) -> Result<Self, ProtocolError> {
1098 stdin.check(descriptors.len())?;
1099 let mut descriptors = descriptors.into_iter().map(stream_socket);
1100 let stdout = descriptors
1101 .next()
1102 .ok_or(ProtocolError::MissingStreamDescriptors)??;
1103 Ok(Self {
1104 stdout,
1105 stdin: descriptors.next().transpose()?,
1106 })
1107 }
1108
1109 #[must_use]
1110 pub fn descriptors(&self) -> Vec<BorrowedFd<'_>> {
1111 std::iter::once(self.stdout.as_fd())
1112 .chain(self.stdin.as_ref().map(AsFd::as_fd))
1113 .collect()
1114 }
1115}
1116
1117#[cfg(unix)]
1118#[derive(Debug)]
1119pub struct Upcall {
1120 pub parent: InvocationId,
1121 pub script: String,
1122 pub trace_parent: Option<TraceParent>,
1123 pub streams: UpcallStreams,
1124}
1125
1126#[derive(Clone, Debug, Eq, PartialEq)]
1127pub struct UpcallExit {
1128 pub status: u8,
1129 pub stderr: String,
1130}
1131
1132#[cfg(unix)]
1133fn stream_socket(descriptor: OwnedFd) -> Result<OwnedFd, ProtocolError> {
1134 let file = std::fs::File::from(descriptor);
1135 let socket = file
1136 .metadata()
1137 .map_err(|source| ProtocolError::Io { source })?
1138 .file_type()
1139 .is_socket();
1140 if socket
1141 && rustix::net::sockopt::socket_type(&file).map_err(|source| ProtocolError::Io {
1142 source: source.into(),
1143 })? == rustix::net::SocketType::STREAM
1144 {
1145 Ok(OwnedFd::from(file))
1146 } else {
1147 Err(ProtocolError::UnexpectedDescriptors)
1148 }
1149}
1150
1151#[cfg(unix)]
1152#[derive(Debug)]
1153pub struct Streams {
1154 pub stdin: Option<OwnedFd>,
1155 pub stdout: OwnedFd,
1156}
1157
1158#[cfg(unix)]
1159impl Streams {
1160 #[must_use]
1161 pub const fn descriptors(&self) -> StreamDescriptors {
1162 StreamDescriptors {
1163 stdin: self.stdin.is_some(),
1164 }
1165 }
1166
1167 pub fn split_from(
1168 descriptors: &mut Vec<OwnedFd>,
1169 shape: StreamDescriptors,
1170 ) -> Result<Self, ProtocolError> {
1171 let stdout = descriptors
1172 .pop()
1173 .ok_or(ProtocolError::MissingStreamDescriptors)?;
1174 let stdin = if shape.stdin {
1175 Some(
1176 descriptors
1177 .pop()
1178 .ok_or(ProtocolError::MissingStreamDescriptors)?,
1179 )
1180 } else {
1181 None
1182 };
1183 if descriptors.len() > MAX_ASSET_DESCRIPTORS {
1184 return Err(ProtocolError::TooManyDescriptors);
1185 }
1186 Ok(Self { stdin, stdout })
1187 }
1188}
1189
1190#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
1191#[serde(deny_unknown_fields, rename_all = "camelCase")]
1192pub struct AssetRow {
1193 pub id: u64,
1194 pub content_type: String,
1195 pub encoding: AssetEncoding,
1196 pub bytes: Option<u64>,
1197 pub origin: String,
1198 pub sent: bool,
1199}
1200
1201#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
1202#[serde(rename_all = "lowercase")]
1203pub enum AssetEncoding {
1204 Identity,
1205 Base64,
1206}
1207
1208#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
1209#[serde(deny_unknown_fields, rename_all = "camelCase")]
1210pub struct NewAsset {
1211 pub descriptor: u32,
1212 pub content_type: String,
1213 pub encoding: AssetEncoding,
1214 pub bytes: u64,
1215 pub sha256: String,
1216}
1217
1218#[cfg(unix)]
1219#[derive(Debug, Default)]
1220pub struct InvokeAssets {
1221 pub rows: Vec<AssetRow>,
1222 pub sends_remaining: u8,
1223 pub descriptors: Vec<OwnedFd>,
1224 pub streams: Option<Streams>,
1225}
1226
1227#[cfg(unix)]
1228#[derive(Debug)]
1229pub struct AssetInvocationOutcome {
1230 pub result: InvocationResult,
1231 pub attached: Vec<NewAsset>,
1232 pub removed: Vec<u64>,
1233 pub sent: Vec<u64>,
1234 pub descriptors: Vec<OwnedFd>,
1235}
1236
1237#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
1238#[serde(deny_unknown_fields, rename_all = "camelCase")]
1239pub struct ResponseEnvelope {
1240 pub api_version: ProtocolVersion,
1241 pub response: BrokerResponse,
1242}
1243
1244impl ResponseEnvelope {
1245 #[must_use]
1246 pub fn with_space(mut self, grants: Option<Vec<CapabilityId>>) -> Self {
1247 match &mut self.response {
1248 BrokerResponse::Capabilities { space, .. } => *space = grants,
1249 BrokerResponse::Ran { .. }
1250 | BrokerResponse::Invocation { .. }
1251 | BrokerResponse::CommandRun { .. }
1252 | BrokerResponse::Upcall { .. }
1253 | BrokerResponse::Error { .. }
1254 | BrokerResponse::Generation { .. } => {}
1255 }
1256 self
1257 }
1258
1259 #[must_use]
1260 pub const fn capabilities(
1261 capabilities: Vec<AvailableCapability>,
1262 command_words: Vec<String>,
1263 command_word_help: BTreeMap<String, String>,
1264 ) -> Self {
1265 Self {
1266 api_version: ProtocolVersion::V1Alpha2,
1267 response: BrokerResponse::Capabilities {
1268 capabilities,
1269 command_words,
1270 command_word_help,
1271 chat_memory: None,
1272 principal: None,
1273 space: None,
1274 },
1275 }
1276 }
1277
1278 #[must_use]
1279 pub const fn chat_capabilities(
1280 capabilities: Vec<AvailableCapability>,
1281 command_words: Vec<String>,
1282 command_word_help: BTreeMap<String, String>,
1283 chat_memory: Option<ChatMemorySurface>,
1284 principal: Option<PrincipalId>,
1285 ) -> Self {
1286 Self {
1287 api_version: ProtocolVersion::V1Alpha2,
1288 response: BrokerResponse::Capabilities {
1289 capabilities,
1290 command_words,
1291 command_word_help,
1292 chat_memory,
1293 principal,
1294 space: None,
1295 },
1296 }
1297 }
1298
1299 #[must_use]
1300 pub const fn command_run(result: CommandRunOutcome) -> Self {
1301 Self {
1302 api_version: ProtocolVersion::V1Alpha2,
1303 response: BrokerResponse::CommandRun { result },
1304 }
1305 }
1306
1307 #[must_use]
1308 pub const fn invocation(
1309 result: InvocationResult,
1310 attached: Vec<NewAsset>,
1311 removed: Vec<u64>,
1312 sent: Vec<u64>,
1313 ) -> Self {
1314 Self {
1315 api_version: ProtocolVersion::V1Alpha2,
1316 response: BrokerResponse::Invocation {
1317 result,
1318 attached,
1319 removed,
1320 sent,
1321 },
1322 }
1323 }
1324
1325 #[must_use]
1326 pub fn session_refused(refusal: &SessionRefusal) -> Self {
1327 match refusal {
1328 SessionRefusal::UnmappedSubject => {
1329 Self::error(ERROR_UNMAPPED_SUBJECT, "subject is not mapped")
1330 }
1331 SessionRefusal::AgentDenied { principal } => {
1332 Self::error(ERROR_AGENT_DENIED, principal.as_str())
1333 }
1334 SessionRefusal::Other => Self::error(
1335 ERROR_UNAUTHENTICATED,
1336 "attestation refused: no attestor authority for this subject",
1337 ),
1338 }
1339 }
1340
1341 #[must_use]
1342 pub fn error(code: impl Into<String>, message: impl Into<String>) -> Self {
1343 Self {
1344 api_version: ProtocolVersion::V1Alpha2,
1345 response: BrokerResponse::Error {
1346 code: code.into(),
1347 message: message.into(),
1348 },
1349 }
1350 }
1351}
1352
1353#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
1354#[serde(tag = "type", deny_unknown_fields, rename_all = "camelCase")]
1355pub enum BrokerResponse {
1356 Ran {
1357 outcome: RunOutcome,
1358 },
1359 Capabilities {
1360 capabilities: Vec<AvailableCapability>,
1361 #[serde(default)]
1362 command_words: Vec<String>,
1363 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1364 command_word_help: BTreeMap<String, String>,
1365 #[serde(default, skip_serializing_if = "Option::is_none")]
1366 chat_memory: Option<ChatMemorySurface>,
1367 #[serde(default, skip_serializing_if = "Option::is_none")]
1368 principal: Option<PrincipalId>,
1369 #[serde(default, skip_serializing_if = "Option::is_none")]
1370 space: Option<Vec<CapabilityId>>,
1371 },
1372 Invocation {
1373 result: InvocationResult,
1374 #[serde(default)]
1375 attached: Vec<NewAsset>,
1376 #[serde(default)]
1377 removed: Vec<u64>,
1378 #[serde(default)]
1379 sent: Vec<u64>,
1380 },
1381 CommandRun {
1382 result: CommandRunOutcome,
1383 },
1384 Upcall {
1385 parent: InvocationId,
1386 script: String,
1387 #[serde(
1388 default,
1389 rename = "traceParent",
1390 skip_serializing_if = "Option::is_none"
1391 )]
1392 trace_parent: Option<TraceParent>,
1393 stdin: UpcallStdin,
1394 },
1395 Error {
1396 code: String,
1397 message: String,
1398 },
1399 Generation {
1400 digest: String,
1401 outcome: GenerationOutcome,
1402 },
1403}
1404
1405#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)]
1406#[serde(rename_all = "camelCase")]
1407pub enum GenerationOutcome {
1408 Prepared,
1409 Applied,
1410 Aborted,
1411 Active,
1412 Refused,
1413}
1414
1415#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1416pub struct FrameLimits {
1417 pub max_frame_bytes: usize,
1418 pub io_timeout: Duration,
1419}
1420
1421impl Default for FrameLimits {
1422 fn default() -> Self {
1423 Self {
1424 max_frame_bytes: DEFAULT_MAX_FRAME_BYTES,
1425 io_timeout: DEFAULT_IO_TIMEOUT,
1426 }
1427 }
1428}
1429
1430impl FrameLimits {
1431 pub fn validate(self) -> Result<Self, ProtocolError> {
1432 if self.max_frame_bytes == 0 || self.max_frame_bytes > HARD_MAX_FRAME_BYTES {
1433 return Err(ProtocolError::InvalidFrameLimit {
1434 maximum: HARD_MAX_FRAME_BYTES,
1435 });
1436 }
1437 if self.io_timeout.is_zero() {
1438 return Err(ProtocolError::ZeroTimeout);
1439 }
1440 Ok(self)
1441 }
1442}
1443
1444const FRAME_PREFIX_BYTES: usize = 4;
1445const READ_CHUNK_BYTES: usize = 64 * 1024;
1446
1447pub async fn read_frame<R, T>(reader: &mut R, limits: FrameLimits) -> Result<T, ProtocolError>
1448where
1449 R: AsyncRead + Unpin,
1450 T: DeserializeOwned,
1451{
1452 let limits = limits.validate()?;
1453 #[allow(
1454 clippy::map_err_ignore,
1455 reason = "tokio's Elapsed says only that io_timeout expired, which ProtocolError::Timeout \
1456 already states"
1457 )]
1458 let bytes = timeout(limits.io_timeout, async {
1459 let mut prefix = [0_u8; FRAME_PREFIX_BYTES];
1460 reader.read_exact(&mut prefix).await?;
1461 let length = usize::try_from(u32::from_be_bytes(prefix)).unwrap_or(usize::MAX);
1462 if length == 0 {
1463 return Err(ReadFrameError::Empty);
1464 }
1465 if length > limits.max_frame_bytes {
1466 return Err(ReadFrameError::TooLarge { length });
1467 }
1468 read_payload(reader, length).await
1469 })
1470 .await
1471 .map_err(|_| ProtocolError::Timeout)?
1472 .map_err(|error| match error {
1473 ReadFrameError::Io(source) => ProtocolError::Io { source },
1474 ReadFrameError::Empty => ProtocolError::EmptyFrame,
1475 ReadFrameError::TooLarge { length } => ProtocolError::FrameTooLarge {
1476 length,
1477 maximum: limits.max_frame_bytes,
1478 },
1479 })?;
1480 serde_json::from_slice(&bytes).map_err(|source| ProtocolError::Deserialize { source })
1481}
1482
1483async fn read_payload<R>(reader: &mut R, length: usize) -> Result<Vec<u8>, ReadFrameError>
1484where
1485 R: AsyncRead + Unpin,
1486{
1487 let mut bytes = Vec::new();
1488 let mut filled = 0;
1489 while filled < length {
1490 if bytes.len() == filled {
1491 let target = bytes.len().saturating_add(READ_CHUNK_BYTES).min(length);
1492 bytes.reserve_exact(target - bytes.len());
1493 bytes.resize(target, 0);
1494 }
1495 let read = reader.read(&mut bytes[filled..]).await?;
1496 if read == 0 {
1497 return Err(ReadFrameError::Io(io::Error::new(
1498 io::ErrorKind::UnexpectedEof,
1499 "broker frame ended before its declared length",
1500 )));
1501 }
1502 filled += read;
1503 }
1504 bytes.truncate(filled);
1505 Ok(bytes)
1506}
1507
1508#[derive(Debug)]
1509enum ReadFrameError {
1510 Io(io::Error),
1511 Empty,
1512 TooLarge { length: usize },
1513}
1514
1515impl From<io::Error> for ReadFrameError {
1516 fn from(source: io::Error) -> Self {
1517 Self::Io(source)
1518 }
1519}
1520
1521pub async fn write_frame<W, T>(
1522 writer: &mut W,
1523 value: &T,
1524 limits: FrameLimits,
1525) -> Result<(), ProtocolError>
1526where
1527 W: AsyncWrite + Unpin,
1528 T: Serialize,
1529{
1530 let limits = limits.validate()?;
1531 let mut counter = BoundedJsonCounter::new(limits.max_frame_bytes);
1534 if let Err(source) = serde_json::to_writer(&mut counter, value) {
1535 return Err(frame_write_failure(
1536 source,
1537 counter.exceeded,
1538 limits.max_frame_bytes,
1539 ));
1540 }
1541 let mut buffer = BoundedJsonBuffer::new(limits.max_frame_bytes, counter.length);
1542 if let Err(source) = serde_json::to_writer(&mut buffer, value) {
1543 return Err(frame_write_failure(
1544 source,
1545 buffer.exceeded,
1546 limits.max_frame_bytes,
1547 ));
1548 }
1549 let payload = buffer.payload_len();
1550 #[allow(
1551 clippy::map_err_ignore,
1552 reason = "TryFromIntError carries only out-of-range, and FrameTooLarge already names the \
1553 length and the maximum"
1554 )]
1555 let length = u32::try_from(payload).map_err(|_| ProtocolError::FrameTooLarge {
1556 length: payload,
1557 maximum: limits.max_frame_bytes,
1558 })?;
1559 buffer.frame[..FRAME_PREFIX_BYTES].copy_from_slice(&length.to_be_bytes());
1560 #[allow(
1561 clippy::map_err_ignore,
1562 reason = "tokio's Elapsed says only that io_timeout expired, which ProtocolError::Timeout \
1563 already states"
1564 )]
1565 timeout(limits.io_timeout, async {
1566 writer.write_all(&buffer.frame).await?;
1567 writer.flush().await
1568 })
1569 .await
1570 .map_err(|_| ProtocolError::Timeout)?
1571 .map_err(|source| ProtocolError::Io { source })
1572}
1573
1574fn frame_write_failure(source: serde_json::Error, exceeded: bool, maximum: usize) -> ProtocolError {
1575 if exceeded {
1576 return ProtocolError::FrameTooLarge {
1577 length: maximum.saturating_add(1),
1578 maximum,
1579 };
1580 }
1581 ProtocolError::Serialize { source }
1582}
1583
1584struct BoundedJsonCounter {
1585 length: usize,
1586 maximum: usize,
1587 exceeded: bool,
1588}
1589
1590impl BoundedJsonCounter {
1591 fn new(maximum: usize) -> Self {
1592 Self {
1593 length: 0,
1594 maximum,
1595 exceeded: false,
1596 }
1597 }
1598}
1599
1600impl io::Write for BoundedJsonCounter {
1601 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
1602 let Some(length) = self.length.checked_add(bytes.len()) else {
1603 self.exceeded = true;
1604 return Err(io::Error::other("bounded JSON frame overflowed"));
1605 };
1606 if length > self.maximum {
1607 self.exceeded = true;
1608 return Err(io::Error::other("bounded JSON frame exceeded its limit"));
1609 }
1610 self.length = length;
1611 Ok(bytes.len())
1612 }
1613
1614 fn flush(&mut self) -> io::Result<()> {
1615 Ok(())
1616 }
1617}
1618
1619struct BoundedJsonBuffer {
1620 frame: Vec<u8>,
1621 maximum: usize,
1622 exceeded: bool,
1623}
1624
1625impl BoundedJsonBuffer {
1626 fn new(maximum: usize, payload: usize) -> Self {
1627 let mut frame = Vec::with_capacity(FRAME_PREFIX_BYTES + payload);
1628 frame.extend_from_slice(&[0_u8; FRAME_PREFIX_BYTES]);
1629 Self {
1630 frame,
1631 maximum,
1632 exceeded: false,
1633 }
1634 }
1635
1636 fn payload_len(&self) -> usize {
1637 self.frame.len() - FRAME_PREFIX_BYTES
1638 }
1639}
1640
1641impl io::Write for BoundedJsonBuffer {
1642 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
1643 let Some(length) = self.payload_len().checked_add(bytes.len()) else {
1644 self.exceeded = true;
1645 return Err(io::Error::other("bounded JSON frame overflowed"));
1646 };
1647 if length > self.maximum {
1648 self.exceeded = true;
1649 return Err(io::Error::other("bounded JSON frame exceeded its limit"));
1650 }
1651 self.frame.extend_from_slice(bytes);
1652 Ok(bytes.len())
1653 }
1654
1655 fn flush(&mut self) -> io::Result<()> {
1656 Ok(())
1657 }
1658}
1659
1660#[derive(Debug, Error)]
1661pub enum ProtocolError {
1662 #[error("broker frame descriptors were truncated")]
1663 DescriptorsTruncated,
1664 #[error("could not set broker descriptor close-on-exec flags")]
1665 DescriptorFlags {
1666 #[source]
1667 source: io::Error,
1668 },
1669 #[error("broker frame has too many descriptors")]
1670 TooManyDescriptors,
1671 #[error("broker frame has unexpected descriptors")]
1672 UnexpectedDescriptors,
1673 #[error("broker frame is missing its stream descriptors")]
1674 MissingStreamDescriptors,
1675 #[error("broker frame has invalid descriptor indexes")]
1676 DescriptorIndex,
1677 #[error("broker generation digest must be lowercase SHA-256")]
1678 InvalidGenerationDigest,
1679 #[error("broker frame has too many asset rows")]
1680 TooManyAssetRows,
1681 #[error("unknown asset index")]
1682 UnknownAssetIndex,
1683 #[error("unreferenced asset row")]
1684 UnreferencedAsset,
1685 #[error("duplicate asset row")]
1686 DuplicateAssetRow,
1687 #[error("frame maximum must be between 1 and {maximum} bytes")]
1688 InvalidFrameLimit { maximum: usize },
1689 #[error("frame I/O timeout must be greater than zero")]
1690 ZeroTimeout,
1691 #[error("broker frame I/O timed out")]
1692 Timeout,
1693 #[error("broker frame I/O failed")]
1694 Io {
1695 #[source]
1696 source: io::Error,
1697 },
1698 #[error("broker frame must not be empty")]
1699 EmptyFrame,
1700 #[error("broker frame is {length} bytes; maximum is {maximum}")]
1701 FrameTooLarge { length: usize, maximum: usize },
1702 #[error("could not serialize broker frame")]
1703 Serialize {
1704 #[source]
1705 source: serde_json::Error,
1706 },
1707 #[error("broker frame is not valid protocol JSON")]
1708 Deserialize {
1709 #[source]
1710 source: serde_json::Error,
1711 },
1712}
1713
1714#[cfg(unix)]
1715#[derive(Clone, Debug)]
1716pub struct BrokerClient {
1717 socket: PathBuf,
1718 expected_server_uid: u32,
1719 limits: FrameLimits,
1720 connect_window: Duration,
1721}
1722
1723#[cfg(unix)]
1724const CONNECT_BACKOFF: Duration = Duration::from_millis(50);
1725#[cfg(unix)]
1726const MAX_CONNECT_BACKOFF: Duration = Duration::from_secs(1);
1727
1728#[cfg(unix)]
1729impl BrokerClient {
1730 pub fn new(
1731 socket: impl Into<PathBuf>,
1732 expected_server_uid: u32,
1733 limits: FrameLimits,
1734 ) -> Result<Self, ClientError> {
1735 Ok(Self {
1736 socket: socket.into(),
1737 expected_server_uid,
1738 limits: limits.validate().map_err(ClientError::Limits)?,
1739 connect_window: Duration::ZERO,
1740 })
1741 }
1742
1743 #[must_use]
1744 pub const fn with_connect_window(mut self, window: Duration) -> Self {
1745 self.connect_window = window;
1746 self
1747 }
1748
1749 pub async fn session_surface(
1750 &self,
1751 attestation: Option<Attestation>,
1752 ) -> Result<SessionSurface, ClientError> {
1753 match self
1754 .exchange(RequestEnvelope::capabilities(attestation))
1755 .await?
1756 {
1757 BrokerResponse::Capabilities {
1758 capabilities,
1759 command_words,
1760 command_word_help,
1761 chat_memory,
1762 principal,
1763 space,
1764 } => Ok(SessionSurface {
1765 capabilities,
1766 command_words,
1767 command_word_help,
1768 chat_memory,
1769 principal,
1770 space,
1771 }),
1772 BrokerResponse::Error { code, message } => {
1773 match SessionRefusal::from_error(&code, &message) {
1774 Ok(SessionRefusal::Other) => Err(ClientError::Remote { code, message }),
1775 Ok(
1776 refusal @ (SessionRefusal::UnmappedSubject
1777 | SessionRefusal::AgentDenied { .. }),
1778 ) => Err(ClientError::SessionRefused(refusal)),
1779 Err(source) => Err(ClientError::MalformedRefusal { source }),
1780 }
1781 }
1782 BrokerResponse::CommandRun { .. }
1783 | BrokerResponse::Ran { .. }
1784 | BrokerResponse::Invocation { .. }
1785 | BrokerResponse::Upcall { .. }
1786 | BrokerResponse::Generation { .. } => Err(ClientError::UnexpectedResponse),
1787 }
1788 }
1789
1790 pub async fn capabilities(&self) -> Result<Vec<AvailableCapability>, ClientError> {
1791 Ok(self.session_surface(None).await?.capabilities)
1792 }
1793
1794 pub async fn run(
1795 &self,
1796 attestation: Option<Attestation>,
1797 request: RunRequest,
1798 assets: InvokeAssets,
1799 mut upcalls: impl AsyncFnMut(Upcall) -> UpcallExit,
1800 ) -> Result<RunResponse, ClientError> {
1801 let attestation = attestation.map(|claim| claim.bound_to(request.invocation.clone()));
1802 if assets.descriptors.len() > MAX_ASSET_DESCRIPTORS {
1803 return Err(ClientError::Protocol {
1804 phase: ExchangePhase::Request,
1805 source: ProtocolError::TooManyDescriptors,
1806 });
1807 }
1808 let shape = assets.streams.as_ref().map(Streams::descriptors);
1809 let descriptors: Vec<_> = assets
1810 .descriptors
1811 .iter()
1812 .chain(
1813 assets
1814 .streams
1815 .as_ref()
1816 .and_then(|streams| streams.stdin.as_ref()),
1817 )
1818 .chain(assets.streams.as_ref().map(|streams| &streams.stdout))
1819 .map(|fd| fd.as_fd())
1820 .collect();
1821 let mut stream = self
1822 .open(
1823 RequestEnvelope {
1824 api_version: ProtocolVersion::V1Alpha2,
1825 request: BrokerRequest::Run {
1826 attestation,
1827 invocation: request.invocation,
1828 trace_parent: request.trace_parent,
1829 word: request.word,
1830 argv: request.argv,
1831 assets: assets.rows,
1832 sends_remaining: assets.sends_remaining,
1833 streams: shape.ok_or(ClientError::Protocol {
1834 phase: ExchangePhase::Request,
1835 source: ProtocolError::MissingStreamDescriptors,
1836 })?,
1837 },
1838 },
1839 &descriptors,
1840 )
1841 .await?;
1842 let (response, descriptors) = loop {
1843 let (response, descriptors) = stream
1844 .read_frame_when_ready::<ResponseEnvelope>(self.limits)
1845 .await
1846 .and_then(|(response, descriptors)| {
1847 validate_response_descriptors(&response.response, descriptors.len())?;
1848 Ok((response.response, descriptors))
1849 })
1850 .map_err(response_failure)?;
1851 let BrokerResponse::Upcall {
1852 parent,
1853 script,
1854 trace_parent,
1855 stdin,
1856 } = response
1857 else {
1858 break (response, descriptors);
1859 };
1860 let streams = UpcallStreams::receive(stdin, descriptors).map_err(response_failure)?;
1861 let exit = upcalls(Upcall {
1862 parent,
1863 script,
1864 trace_parent,
1865 streams,
1866 })
1867 .await;
1868 stream
1869 .write_frame(&RequestEnvelope::upcall_result(exit), &[], self.limits)
1870 .await
1871 .map_err(response_failure)?;
1872 };
1873 match response {
1874 BrokerResponse::Ran { outcome } => Ok(RunResponse {
1875 outcome,
1876 descriptors,
1877 }),
1878 BrokerResponse::Error { code, message } => Err(ClientError::Remote { code, message }),
1879 BrokerResponse::Capabilities { .. }
1880 | BrokerResponse::Invocation { .. }
1881 | BrokerResponse::CommandRun { .. }
1882 | BrokerResponse::Upcall { .. }
1883 | BrokerResponse::Generation { .. } => Err(ClientError::UnexpectedResponse),
1884 }
1885 }
1886
1887 pub async fn invoke(
1888 &self,
1889 attestation: Option<Attestation>,
1890 request: InvocationRequest,
1891 assets: InvokeAssets,
1892 mut upcalls: impl AsyncFnMut(Upcall) -> UpcallExit,
1893 ) -> Result<AssetInvocationOutcome, ClientError> {
1894 let attestation = attestation.map(|claim| claim.bound_to(request.id.clone()));
1895 if assets.descriptors.len() > MAX_ASSET_DESCRIPTORS {
1896 return Err(ClientError::Protocol {
1897 phase: ExchangePhase::Request,
1898 source: ProtocolError::TooManyDescriptors,
1899 });
1900 }
1901 let shape = assets.streams.as_ref().map(Streams::descriptors);
1902 let descriptors: Vec<_> = assets
1903 .descriptors
1904 .iter()
1905 .chain(
1906 assets
1907 .streams
1908 .as_ref()
1909 .and_then(|streams| streams.stdin.as_ref()),
1910 )
1911 .chain(assets.streams.as_ref().map(|streams| &streams.stdout))
1912 .map(|fd| fd.as_fd())
1913 .collect();
1914 let mut stream = self
1915 .open(
1916 RequestEnvelope::invoke(
1917 attestation,
1918 request,
1919 assets.rows,
1920 assets.sends_remaining,
1921 shape,
1922 ),
1923 &descriptors,
1924 )
1925 .await?;
1926 let (response, descriptors) = loop {
1927 let (response, descriptors) = stream
1928 .read_frame_when_ready::<ResponseEnvelope>(self.limits)
1929 .await
1930 .and_then(|(response, descriptors)| {
1931 validate_response_descriptors(&response.response, descriptors.len())?;
1932 Ok((response.response, descriptors))
1933 })
1934 .map_err(response_failure)?;
1935 let BrokerResponse::Upcall {
1936 parent,
1937 script,
1938 trace_parent,
1939 stdin,
1940 } = response
1941 else {
1942 break (response, descriptors);
1943 };
1944 let streams = UpcallStreams::receive(stdin, descriptors).map_err(response_failure)?;
1945 let exit = upcalls(Upcall {
1946 parent,
1947 script,
1948 trace_parent,
1949 streams,
1950 })
1951 .await;
1952 stream
1953 .write_frame(&RequestEnvelope::upcall_result(exit), &[], self.limits)
1954 .await
1955 .map_err(response_failure)?;
1956 };
1957 match response {
1958 BrokerResponse::Invocation {
1959 result,
1960 attached,
1961 removed,
1962 sent,
1963 } => Ok(AssetInvocationOutcome {
1964 result,
1965 attached,
1966 removed,
1967 sent,
1968 descriptors,
1969 }),
1970 BrokerResponse::Error { code, message } => Err(ClientError::Remote { code, message }),
1971 BrokerResponse::Capabilities { .. }
1972 | BrokerResponse::Ran { .. }
1973 | BrokerResponse::CommandRun { .. }
1974 | BrokerResponse::Upcall { .. }
1975 | BrokerResponse::Generation { .. } => Err(ClientError::UnexpectedResponse),
1976 }
1977 }
1978
1979 pub async fn record_delivered_turn(
1980 &self,
1981 attestation: Attestation,
1982 turn: DeliveredTurnRequest,
1983 ) -> Result<InvocationResult, ClientError> {
1984 let attestation = attestation.bound_to(turn.id.clone());
1985 match self
1986 .exchange(RequestEnvelope::record_delivered_turn(attestation, turn))
1987 .await?
1988 {
1989 BrokerResponse::Invocation { result, .. } => Ok(result),
1990 BrokerResponse::Error { code, message } => Err(ClientError::Remote { code, message }),
1991 BrokerResponse::Capabilities { .. }
1992 | BrokerResponse::Ran { .. }
1993 | BrokerResponse::CommandRun { .. }
1994 | BrokerResponse::Upcall { .. }
1995 | BrokerResponse::Generation { .. } => Err(ClientError::UnexpectedResponse),
1996 }
1997 }
1998
1999 pub async fn prepare_generation(
2000 &self,
2001 expected_active: String,
2002 ) -> Result<(String, GenerationOutcome), ClientError> {
2003 match self
2004 .exchange(RequestEnvelope {
2005 api_version: ProtocolVersion::V1Alpha3,
2006 request: BrokerRequest::PrepareGeneration {
2007 digest: expected_active,
2008 },
2009 })
2010 .await?
2011 {
2012 BrokerResponse::Generation { digest, outcome } => Ok((digest, outcome)),
2013 BrokerResponse::Error { code, message } => Err(ClientError::Remote { code, message }),
2014 BrokerResponse::Capabilities { .. }
2015 | BrokerResponse::Ran { .. }
2016 | BrokerResponse::Invocation { .. }
2017 | BrokerResponse::CommandRun { .. }
2018 | BrokerResponse::Upcall { .. } => Err(ClientError::UnexpectedResponse),
2019 }
2020 }
2021
2022 pub async fn commit_generation(
2023 &self,
2024 digest: String,
2025 ) -> Result<GenerationOutcome, ClientError> {
2026 self.generation(BrokerRequest::CommitGeneration { digest })
2027 .await
2028 }
2029
2030 pub async fn abort_generation(&self, digest: String) -> Result<GenerationOutcome, ClientError> {
2031 self.generation(BrokerRequest::AbortGeneration { digest })
2032 .await
2033 }
2034
2035 pub async fn observe_generation(&self) -> Result<(String, GenerationOutcome), ClientError> {
2036 match self
2037 .exchange(RequestEnvelope {
2038 api_version: ProtocolVersion::V1Alpha3,
2039 request: BrokerRequest::ObserveGeneration,
2040 })
2041 .await?
2042 {
2043 BrokerResponse::Generation { digest, outcome } => Ok((digest, outcome)),
2044 BrokerResponse::Error { code, message } => Err(ClientError::Remote { code, message }),
2045 BrokerResponse::Capabilities { .. }
2046 | BrokerResponse::Ran { .. }
2047 | BrokerResponse::Invocation { .. }
2048 | BrokerResponse::CommandRun { .. }
2049 | BrokerResponse::Upcall { .. } => Err(ClientError::UnexpectedResponse),
2050 }
2051 }
2052
2053 async fn generation(&self, request: BrokerRequest) -> Result<GenerationOutcome, ClientError> {
2054 let digest = match &request {
2055 BrokerRequest::CommitGeneration { digest }
2056 | BrokerRequest::AbortGeneration { digest } => digest,
2057 BrokerRequest::Capabilities { .. }
2058 | BrokerRequest::Run { .. }
2059 | BrokerRequest::Invoke { .. }
2060 | BrokerRequest::RecordDeliveredTurn { .. }
2061 | BrokerRequest::UpcallResult { .. }
2062 | BrokerRequest::PrepareGeneration { .. }
2063 | BrokerRequest::ObserveGeneration => return Err(ClientError::UnexpectedResponse),
2064 };
2065 let expected = digest.clone();
2066 match self
2067 .exchange(RequestEnvelope {
2068 api_version: ProtocolVersion::V1Alpha3,
2069 request,
2070 })
2071 .await?
2072 {
2073 BrokerResponse::Generation { digest, outcome } if digest == expected => Ok(outcome),
2074 BrokerResponse::Error { code, message } => Err(ClientError::Remote { code, message }),
2075 BrokerResponse::Generation { .. }
2076 | BrokerResponse::Capabilities { .. }
2077 | BrokerResponse::Ran { .. }
2078 | BrokerResponse::Invocation { .. }
2079 | BrokerResponse::CommandRun { .. }
2080 | BrokerResponse::Upcall { .. } => Err(ClientError::UnexpectedResponse),
2081 }
2082 }
2083
2084 async fn exchange(&self, request: RequestEnvelope) -> Result<BrokerResponse, ClientError> {
2085 let mut stream = self.open(request, &[]).await?;
2086 let (response, descriptors) = stream
2087 .read_frame::<ResponseEnvelope>(self.limits)
2088 .await
2089 .map_err(response_failure)?;
2090 validate_response_descriptors(&response.response, descriptors.len())
2091 .map_err(response_failure)?;
2092 Ok(response.response)
2093 }
2094
2095 async fn open(
2096 &self,
2097 request: RequestEnvelope,
2098 descriptors: &[BorrowedFd<'_>],
2099 ) -> Result<DescriptorStream, ClientError> {
2100 request
2101 .request
2102 .validate()
2103 .map_err(|source| ClientError::Protocol {
2104 phase: ExchangePhase::Request,
2105 source,
2106 })?;
2107 let stream = self.connect().await?;
2108 let credentials = match stream.peer_cred() {
2109 Ok(credentials) => credentials,
2110 Err(source) => {
2111 let mut stream = DescriptorStream::new(stream);
2112 return Err(refusal_before_credentials(&mut stream, source, self.limits).await);
2113 }
2114 };
2115 if credentials.uid() != self.expected_server_uid {
2116 return Err(ClientError::ServerIdentity {
2117 expected: self.expected_server_uid,
2118 actual: credentials.uid(),
2119 });
2120 }
2121 let mut stream = DescriptorStream::new(stream);
2122 if let Err(source) = stream.write_frame(&request, descriptors, self.limits).await {
2123 return Err(refusal_after_write_failure(&mut stream, source, self.limits).await);
2124 }
2125 Ok(stream)
2126 }
2127}
2128
2129#[cfg(unix)]
2130impl BrokerClient {
2131 async fn connect(&self) -> Result<UnixStream, ClientError> {
2132 let started = tokio::time::Instant::now();
2133 let mut backoff = CONNECT_BACKOFF;
2134 let mut budget = if self.connect_window.is_zero() {
2135 self.limits.io_timeout
2136 } else {
2137 self.connect_window.min(self.limits.io_timeout)
2138 };
2139 loop {
2140 let absent = match self.connect_once(budget).await {
2141 Err(error) if error.is_absent_broker() => error,
2142 result => return result,
2143 };
2144 let remaining = self.connect_window.saturating_sub(started.elapsed());
2145 if remaining.is_zero() {
2146 return Err(absent);
2147 }
2148 tokio::time::sleep(backoff.min(remaining)).await;
2149 budget = self
2150 .connect_window
2151 .saturating_sub(started.elapsed())
2152 .min(self.limits.io_timeout);
2153 if budget.is_zero() {
2154 return Err(absent);
2155 }
2156 backoff = backoff.saturating_mul(2).min(MAX_CONNECT_BACKOFF);
2157 }
2158 }
2159
2160 async fn connect_once(&self, budget: Duration) -> Result<UnixStream, ClientError> {
2161 #[allow(
2162 clippy::map_err_ignore,
2163 reason = "tokio's Elapsed says only that the attempt's budget expired, which \
2164 ClientError::ConnectTimeout already states"
2165 )]
2166 timeout(budget, async {
2167 validate_socket_path(&self.socket, self.expected_server_uid).await?;
2168 UnixStream::connect(&self.socket)
2169 .await
2170 .map_err(|source| ClientError::Connect { source })
2171 })
2172 .await
2173 .map_err(|_| ClientError::ConnectTimeout)?
2174 }
2175}
2176
2177#[cfg(unix)]
2178const fn response_failure(source: ProtocolError) -> ClientError {
2179 ClientError::Protocol {
2180 phase: ExchangePhase::Response,
2181 source,
2182 }
2183}
2184
2185#[cfg(unix)]
2188async fn refusal_before_credentials(
2189 stream: &mut DescriptorStream,
2190 source: io::Error,
2191 limits: FrameLimits,
2192) -> ClientError {
2193 if source.kind() == io::ErrorKind::NotConnected
2194 && let Ok((
2195 ResponseEnvelope {
2196 response: BrokerResponse::Error { code, message },
2197 ..
2198 },
2199 _,
2200 )) = stream.read_frame::<ResponseEnvelope>(limits).await
2201 && code == ERROR_CAPACITY_EXHAUSTED
2202 {
2203 return ClientError::Remote { code, message };
2204 }
2205 ClientError::PeerCredentials { source }
2206}
2207
2208#[cfg(unix)]
2211async fn refusal_after_write_failure(
2212 stream: &mut DescriptorStream,
2213 source: ProtocolError,
2214 limits: FrameLimits,
2215) -> ClientError {
2216 if let ProtocolError::Io { source: error } = &source
2217 && matches!(
2218 error.kind(),
2219 io::ErrorKind::BrokenPipe | io::ErrorKind::ConnectionReset
2220 )
2221 && let Ok((
2222 ResponseEnvelope {
2223 response: BrokerResponse::Error { code, message },
2224 ..
2225 },
2226 _,
2227 )) = stream.read_frame::<ResponseEnvelope>(limits).await
2228 {
2229 return ClientError::Remote { code, message };
2230 }
2231 ClientError::Protocol {
2232 phase: ExchangePhase::Request,
2233 source,
2234 }
2235}
2236
2237#[cfg(unix)]
2238#[expect(
2239 clippy::wildcard_enum_match_arm,
2240 reason = "reshaped by the unit that next rewrites this"
2241)]
2242fn validate_response_descriptors(
2243 response: &BrokerResponse,
2244 count: usize,
2245) -> Result<(), ProtocolError> {
2246 match response {
2247 BrokerResponse::Upcall { stdin, .. } => stdin.check(count)?,
2248 BrokerResponse::Invocation { attached, .. }
2249 | BrokerResponse::Ran {
2250 outcome: RunOutcome::Invoked { attached, .. },
2251 } => {
2252 if attached.len() != count
2253 || attached
2254 .iter()
2255 .enumerate()
2256 .any(|(index, asset)| usize::try_from(asset.descriptor) != Ok(index))
2257 {
2258 return Err(ProtocolError::DescriptorIndex);
2259 }
2260 }
2261 _ if count != 0 => return Err(ProtocolError::UnexpectedDescriptors),
2262 _ => {}
2263 }
2264 Ok(())
2265}
2266
2267#[cfg(unix)]
2268async fn validate_socket_path(path: &Path, expected_uid: u32) -> Result<(), ClientError> {
2269 let metadata = tokio::fs::symlink_metadata(path)
2270 .await
2271 .map_err(|source| ClientError::SocketMetadata { source })?;
2272 let parent = path.parent().ok_or(ClientError::UnsafeSocket)?;
2273 let parent = if parent.as_os_str().is_empty() {
2274 Path::new(".")
2275 } else {
2276 parent
2277 };
2278 let parent = tokio::fs::symlink_metadata(parent)
2279 .await
2280 .map_err(|source| ClientError::SocketMetadata { source })?;
2281 if !secure_socket_parent(&parent, expected_uid)
2282 || !secure_socket(&metadata, expected_uid, &parent)
2283 {
2284 return Err(ClientError::UnsafeSocket);
2285 }
2286 Ok(())
2287}
2288
2289#[cfg(unix)]
2290#[derive(Debug, Error)]
2291pub enum ClientError {
2292 #[error("could not inspect broker socket")]
2293 SocketMetadata {
2294 #[source]
2295 source: io::Error,
2296 },
2297 #[error("broker socket or parent has unsafe permissions or ownership")]
2298 UnsafeSocket,
2299 #[error("broker connection timed out")]
2300 ConnectTimeout,
2301 #[error("could not connect to broker socket")]
2302 Connect {
2303 #[source]
2304 source: io::Error,
2305 },
2306 #[error("could not authenticate broker peer credentials")]
2307 PeerCredentials {
2308 #[source]
2309 source: io::Error,
2310 },
2311 #[error("broker peer UID {actual} does not match expected UID {expected}")]
2312 ServerIdentity { expected: u32, actual: u32 },
2313 #[error("broker client limits are invalid: {0}")]
2314 Limits(#[source] ProtocolError),
2315 #[error("broker {phase} framing failed: {source}")]
2316 Protocol {
2317 phase: ExchangePhase,
2318 #[source]
2319 source: ProtocolError,
2320 },
2321 #[error("broker refused the session: {0:?}")]
2322 SessionRefused(SessionRefusal),
2323 #[error("broker session refusal has an invalid principal")]
2324 MalformedRefusal {
2325 #[source]
2326 source: dekopon_core::IdentifierError,
2327 },
2328 #[error("broker returned {code}: {message}")]
2329 Remote { code: String, message: String },
2330 #[error("broker returned an unexpected response variant")]
2331 UnexpectedResponse,
2332}
2333
2334#[cfg(unix)]
2335#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2336pub enum ExchangePhase {
2337 Request,
2338 Response,
2339}
2340
2341#[cfg(unix)]
2342impl fmt::Display for ExchangePhase {
2343 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2344 formatter.write_str(match self {
2345 Self::Request => "request",
2346 Self::Response => "response",
2347 })
2348 }
2349}
2350
2351#[cfg(unix)]
2352impl ClientError {
2353 #[must_use]
2354 #[expect(
2355 clippy::wildcard_enum_match_arm,
2356 reason = "only the two pre-connect failures name an absent broker"
2357 )]
2358 fn is_absent_broker(&self) -> bool {
2359 match self {
2360 Self::SocketMetadata { source } => source.kind() == io::ErrorKind::NotFound,
2361 Self::Connect { source } => matches!(
2362 source.kind(),
2363 io::ErrorKind::NotFound | io::ErrorKind::ConnectionRefused
2364 ),
2365 _ => false,
2366 }
2367 }
2368
2369 #[must_use]
2370 #[expect(
2371 clippy::wildcard_enum_match_arm,
2372 reason = "reshaped by the unit that next rewrites this"
2373 )]
2374 pub fn may_have_executed(&self) -> bool {
2375 match self {
2376 Self::Protocol { phase, .. } => *phase == ExchangePhase::Response,
2377 Self::Remote { code, .. } => code == ERROR_OUTCOME_UNAUDITED,
2378 Self::UnexpectedResponse => true,
2379 _ => false,
2380 }
2381 }
2382}
2383
2384impl fmt::Display for ProtocolVersion {
2385 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2386 formatter.write_str(match self {
2387 Self::V1Alpha2 => PROTOCOL_VERSION,
2388 Self::V1Alpha3 => "dekopon.dev/broker/v1alpha3",
2389 })
2390 }
2391}
2392
2393#[cfg(unix)]
2394#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2395pub enum BrokerSocketTier {
2396 Explicit,
2397 Environment,
2398 XdgRuntimeDir,
2399 Home,
2400}
2401
2402#[cfg(unix)]
2403impl BrokerSocketTier {
2404 #[must_use]
2405 pub const fn label(self) -> &'static str {
2406 match self {
2407 Self::Explicit => "explicit",
2408 Self::Environment => "environment",
2409 Self::XdgRuntimeDir => "xdg-runtime-dir",
2410 Self::Home => "home",
2411 }
2412 }
2413}
2414
2415#[cfg(unix)]
2416impl fmt::Display for BrokerSocketTier {
2417 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2418 formatter.write_str(self.label())
2419 }
2420}
2421
2422#[cfg(unix)]
2423#[derive(Clone, Debug, Eq, PartialEq)]
2424pub struct ResolvedBrokerSocket {
2425 path: PathBuf,
2426 tier: BrokerSocketTier,
2427}
2428
2429#[cfg(unix)]
2430impl ResolvedBrokerSocket {
2431 #[must_use]
2432 pub fn path(&self) -> &Path {
2433 &self.path
2434 }
2435
2436 #[must_use]
2437 pub fn into_path(self) -> PathBuf {
2438 self.path
2439 }
2440
2441 #[must_use]
2442 pub const fn tier(&self) -> BrokerSocketTier {
2443 self.tier
2444 }
2445}
2446
2447#[cfg(unix)]
2448#[must_use]
2449pub fn secure_socket_parent(parent: &std::fs::Metadata, expected_uid: u32) -> bool {
2450 let mode = parent.permissions().mode();
2451 parent.file_type().is_dir()
2452 && parent.uid() == expected_uid
2453 && mode & 0o027 == 0
2454 && matches!(mode & 0o070, 0 | 0o010 | 0o050)
2455}
2456
2457#[cfg(unix)]
2458#[must_use]
2459pub fn secure_socket(
2460 socket: &std::fs::Metadata,
2461 expected_uid: u32,
2462 parent: &std::fs::Metadata,
2463) -> bool {
2464 let mode = socket.permissions().mode() & 0o7777;
2465 socket.file_type().is_socket()
2466 && socket.uid() == expected_uid
2467 && socket.nlink() == 1
2468 && (mode == 0o600
2469 || (mode == 0o660
2470 && parent.permissions().mode() & 0o010 != 0
2471 && socket.gid() == parent.gid()))
2472}
2473
2474#[cfg(unix)]
2475#[must_use]
2476pub fn ipc_socket_mode(parent: &std::fs::Metadata) -> u32 {
2477 if parent.permissions().mode() & 0o010 == 0 {
2478 0o600
2479 } else {
2480 0o660
2481 }
2482}
2483
2484#[cfg(unix)]
2485#[derive(Clone, Debug, Default, Eq, PartialEq)]
2486pub struct BrokerSocketDiscovery {
2487 explicit: Option<PathBuf>,
2488 environment: Option<PathBuf>,
2489 xdg_runtime_dir: Option<PathBuf>,
2490 home: Option<PathBuf>,
2491}
2492
2493#[cfg(unix)]
2494impl BrokerSocketDiscovery {
2495 #[must_use]
2496 pub fn from_process(explicit: Option<PathBuf>) -> Self {
2497 Self {
2498 explicit,
2499 environment: env::var_os("DEKOPON_BROKER_SOCKET")
2500 .filter(|value| !value.is_empty())
2501 .map(PathBuf::from),
2502 xdg_runtime_dir: env::var_os("XDG_RUNTIME_DIR")
2503 .filter(|value| !value.is_empty())
2504 .map(PathBuf::from),
2505 home: env::var_os("HOME")
2506 .filter(|value| !value.is_empty())
2507 .map(PathBuf::from),
2508 }
2509 }
2510
2511 #[must_use]
2512 pub const fn new(
2513 explicit: Option<PathBuf>,
2514 environment: Option<PathBuf>,
2515 xdg_runtime_dir: Option<PathBuf>,
2516 home: Option<PathBuf>,
2517 ) -> Self {
2518 Self {
2519 explicit,
2520 environment,
2521 xdg_runtime_dir,
2522 home,
2523 }
2524 }
2525
2526 #[must_use]
2527 pub fn resolve(&self) -> Option<ResolvedBrokerSocket> {
2528 if let Some(path) = &self.explicit {
2529 return Some(ResolvedBrokerSocket {
2530 path: path.clone(),
2531 tier: BrokerSocketTier::Explicit,
2532 });
2533 }
2534 if let Some(path) = &self.environment {
2535 return Some(ResolvedBrokerSocket {
2536 path: path.clone(),
2537 tier: BrokerSocketTier::Environment,
2538 });
2539 }
2540 if let Some(root) = &self.xdg_runtime_dir {
2541 return Some(ResolvedBrokerSocket {
2542 path: root.join("dekopon/broker.sock"),
2543 tier: BrokerSocketTier::XdgRuntimeDir,
2544 });
2545 }
2546 if let Some(home) = &self.home {
2547 return Some(ResolvedBrokerSocket {
2548 path: home.join(".local/run/dekopon/broker.sock"),
2549 tier: BrokerSocketTier::Home,
2550 });
2551 }
2552 None
2553 }
2554}
2555
2556#[cfg(test)]
2557mod tests;
2558
2559#[cfg(test)]
2560mod run_tests;