1use std::collections::BTreeSet;
34use std::sync::Arc;
35
36use adk_awp::signing::jws::{DocumentSigner, document_digest, jwk_thumbprint, sign, verify};
37use adk_awp::v2::capability::{CapabilityCall, CapabilityError, CapabilityHandler, CapabilityTool};
38use adk_core::{AdkError, ErrorCategory, ErrorComponent};
39use adk_kernel::drivers::{DriverManifest, DriverSandbox, EffectClass};
40use async_trait::async_trait;
41use awp_types::{CapabilityEffect, CapabilityV2, ContentKind, Digest, Proof};
42use serde::{Deserialize, Serialize};
43use serde_json::Value;
44
45use super::trust::TrustList;
46use crate::team::AgentRole;
47
48pub const PACK_FORMAT: &str = "adk-website.pack/1";
50
51pub const MAX_BUNDLE_BYTES: usize = 4 * 1024 * 1024;
53
54const MAX_PLAYBOOK_BYTES: usize = 64 * 1024;
55const MAX_CAPABILITIES: usize = 256;
56const MAX_PLAYBOOKS: usize = 64;
57const MAX_DRIVERS: usize = 32;
58const MAX_DESCRIPTION_CHARS: usize = 2_000;
59
60#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
63#[non_exhaustive]
64pub enum PackError {
65 #[error("not a capability pack bundle: {0}")]
67 Malformed(String),
68 #[error("the bundle's format is `{0}`; this release reads `{PACK_FORMAT}`")]
70 Format(String),
71 #[error(
73 "the pack is not signed: a pack installs only with its publisher's signature over its \
74 content digest; ask the publisher for the signed bundle"
75 )]
76 Unsigned,
77 #[error(
79 "the pack's content is not what its publisher signed: {0}; get the pack again from \
80 its publisher"
81 )]
82 Tampered(String),
83 #[error(
85 "the pack's publisher `{publisher}` (key `{kid}`) is not in the trust list; add the \
86 publisher's public key with `adk-rust site packs trust` only if you trust them"
87 )]
88 UnknownPublisher {
89 publisher: String,
91 kid: String,
93 },
94 #[error(
96 "`{name}` {installed} is installed and {offered} is older; a pack is never downgraded \
97 in place: remove it first to go back"
98 )]
99 Downgrade {
100 name: String,
102 installed: String,
104 offered: String,
106 },
107 #[error(
109 "`{name}` {version} is installed with other content; a published version never \
110 changes, so its publisher must release a new version"
111 )]
112 Republished {
113 name: String,
115 version: String,
117 },
118 #[error("the pack is invalid: {0}")]
120 Invalid(String),
121 #[error("the pack conflicts with the site's packs: {0}")]
123 Conflict(String),
124 #[error("no installed pack is named `{0}`; `adk-rust site packs list` shows the site's packs")]
126 NotInstalled(String),
127 #[error(
129 "`{0}` is a built-in pack: it ships with adk-website, and the site's kind chooses which \
130 of its capabilities the site offers"
131 )]
132 BuiltIn(String),
133 #[error("{0}")]
135 Io(String),
136}
137
138impl PackError {
139 pub fn code(&self) -> &'static str {
142 match self {
143 Self::Malformed(_) => "malformed",
144 Self::Format(_) => "format",
145 Self::Unsigned => "unsigned",
146 Self::Tampered(_) => "tampered",
147 Self::UnknownPublisher { .. } => "unknown_publisher",
148 Self::Downgrade { .. } => "downgrade",
149 Self::Republished { .. } => "republished",
150 Self::Invalid(_) => "invalid",
151 Self::Conflict(_) => "conflict",
152 Self::NotInstalled(_) => "not_installed",
153 Self::BuiltIn(_) => "built_in",
154 Self::Io(_) => "io",
155 }
156 }
157}
158
159impl From<PackError> for AdkError {
160 fn from(error: PackError) -> Self {
161 let (category, code) = match &error {
162 PackError::Malformed(_) => (ErrorCategory::InvalidInput, "website.pack.malformed"),
163 PackError::Format(_) => (ErrorCategory::Unsupported, "website.pack.format"),
164 PackError::Unsigned => (ErrorCategory::Forbidden, "website.pack.unsigned"),
165 PackError::Tampered(_) => (ErrorCategory::Forbidden, "website.pack.tampered"),
166 PackError::UnknownPublisher { .. } => {
167 (ErrorCategory::Forbidden, "website.pack.unknown_publisher")
168 }
169 PackError::Downgrade { .. } => (ErrorCategory::Conflict, "website.pack.downgrade"),
170 PackError::Republished { .. } => (ErrorCategory::Conflict, "website.pack.republished"),
171 PackError::Invalid(_) => (ErrorCategory::InvalidInput, "website.pack.invalid"),
172 PackError::Conflict(_) => (ErrorCategory::Conflict, "website.pack.conflict"),
173 PackError::NotInstalled(_) => (ErrorCategory::NotFound, "website.pack.not_installed"),
174 PackError::BuiltIn(_) => (ErrorCategory::InvalidInput, "website.pack.built_in"),
175 PackError::Io(_) => (ErrorCategory::Internal, "website.pack.io"),
176 };
177 AdkError::new(ErrorComponent::Deploy, category, code, error.to_string())
178 }
179}
180
181#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
183#[serde(rename_all = "camelCase", deny_unknown_fields)]
184pub struct PackPublisher {
185 pub id: String,
187 #[serde(default, skip_serializing_if = "Option::is_none")]
189 pub name: Option<String>,
190}
191
192impl PackPublisher {
193 pub fn new(id: impl Into<String>) -> Self {
195 Self { id: id.into(), name: None }
196 }
197
198 #[must_use]
200 pub fn named(mut self, name: impl Into<String>) -> Self {
201 self.name = Some(name.into());
202 self
203 }
204}
205
206#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
208#[serde(rename_all = "snake_case")]
209pub enum OrderOperation {
210 Place,
212 Status,
214 Return,
216}
217
218#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
220#[serde(rename_all = "snake_case")]
221pub enum BookingOperation {
222 Availability,
224 Book,
226}
227
228#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
255#[serde(tag = "handler", rename_all = "snake_case")]
256#[non_exhaustive]
257pub enum HandlerConfig {
258 Form,
260 Quote,
262 Order {
264 operation: OrderOperation,
266 },
267 Payment,
269 Booking {
271 operation: BookingOperation,
273 },
274 Search,
276 Listing {
278 content: ContentKind,
280 },
281 Status,
283}
284
285impl HandlerConfig {
286 pub fn label(&self) -> String {
288 match self {
289 Self::Form => "form".into(),
290 Self::Quote => "quote".into(),
291 Self::Order { operation } => format!("order/{}", json_name(operation)),
292 Self::Payment => "payment".into(),
293 Self::Booking { operation } => format!("booking/{}", json_name(operation)),
294 Self::Search => "search".into(),
295 Self::Listing { content } => format!("listing/{}", json_name(content)),
296 Self::Status => "status".into(),
297 }
298 }
299
300 pub fn minimum_effect(&self) -> CapabilityEffect {
303 match self {
304 Self::Form | Self::Quote => CapabilityEffect::Idempotent,
305 Self::Order { operation: OrderOperation::Place | OrderOperation::Return }
306 | Self::Payment
307 | Self::Booking { operation: BookingOperation::Book } => {
308 CapabilityEffect::NonIdempotent
309 }
310 Self::Order { operation: OrderOperation::Status }
311 | Self::Booking { operation: BookingOperation::Availability }
312 | Self::Search
313 | Self::Listing { .. }
314 | Self::Status => CapabilityEffect::ReadOnly,
315 }
316 }
317
318 pub fn reads(&self) -> &'static [&'static str] {
320 match self {
321 Self::Quote => &["items"],
322 Self::Order { operation: OrderOperation::Place } => &["quoteId"],
323 Self::Order { operation: OrderOperation::Status | OrderOperation::Return } => {
324 &["orderId"]
325 }
326 Self::Booking { operation: BookingOperation::Book } => &["slot"],
327 Self::Search => &["query"],
328 Self::Status => &["reference"],
329 Self::Form
330 | Self::Payment
331 | Self::Booking { operation: BookingOperation::Availability }
332 | Self::Listing { .. } => &[],
333 }
334 }
335
336 pub fn dispatches_as(&self) -> Option<&'static str> {
340 match self {
341 Self::Order { operation: OrderOperation::Place } => Some("place_order"),
342 Self::Order { operation: OrderOperation::Status } => Some("order_status"),
343 Self::Order { operation: OrderOperation::Return } => Some("request_return"),
344 Self::Booking { operation: BookingOperation::Availability } => {
345 Some("check_availability")
346 }
347 Self::Form
348 | Self::Quote
349 | Self::Payment
350 | Self::Booking { operation: BookingOperation::Book }
351 | Self::Search
352 | Self::Listing { .. }
353 | Self::Status => None,
354 }
355 }
356}
357
358#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
360#[serde(rename_all = "camelCase", deny_unknown_fields)]
361pub struct PackPlaybook {
362 pub id: String,
364 pub job: String,
366 pub agents: Vec<AgentRole>,
368 pub text: String,
370}
371
372#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
375#[serde(rename_all = "camelCase", deny_unknown_fields)]
376pub struct PackDriver {
377 pub id: String,
379 pub manifest: String,
381}
382
383#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
409#[serde(rename_all = "camelCase", deny_unknown_fields)]
410pub struct PackBundle {
411 pub format: String,
413 pub name: String,
415 pub version: String,
417 pub publisher: PackPublisher,
419 pub description: String,
421 #[serde(default)]
423 pub capabilities: Vec<CapabilityV2>,
424 #[serde(default)]
426 pub handlers: std::collections::BTreeMap<String, HandlerConfig>,
427 #[serde(default, skip_serializing_if = "Vec::is_empty")]
429 pub playbooks: Vec<PackPlaybook>,
430 #[serde(default, skip_serializing_if = "Vec::is_empty")]
432 pub drivers: Vec<PackDriver>,
433 #[serde(default, skip_serializing_if = "Option::is_none")]
435 pub digest: Option<Digest>,
436 #[serde(default, skip_serializing_if = "Option::is_none")]
438 pub proof: Option<Proof>,
439}
440
441#[derive(Debug, Clone, PartialEq)]
444pub struct VerifiedPack {
445 pub bundle: PackBundle,
447 pub digest: Digest,
449 pub kid: String,
451 pub thumbprint: String,
453}
454
455impl VerifiedPack {
456 pub fn version(&self) -> semver::Version {
458 semver::Version::parse(&self.bundle.version)
460 .unwrap_or_else(|_| semver::Version::new(0, 0, 0))
461 }
462}
463
464fn valid_slug(text: &str, max: usize, extra: &[u8]) -> bool {
465 let bytes = text.as_bytes();
466 !bytes.is_empty()
467 && bytes.len() <= max
468 && (bytes[0].is_ascii_lowercase() || bytes[0].is_ascii_digit())
469 && bytes.iter().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || extra.contains(b))
470}
471
472pub fn is_valid_pack_name(name: &str) -> bool {
475 valid_slug(name, 64, b"-")
476}
477
478pub fn is_valid_publisher_id(id: &str) -> bool {
481 valid_slug(id, 128, b".-")
482}
483
484fn strictness(effect: CapabilityEffect) -> u8 {
485 match effect {
486 CapabilityEffect::ReadOnly => 0,
487 CapabilityEffect::Idempotent => 1,
488 _ => 2,
490 }
491}
492
493fn json_name<T: Serialize + std::fmt::Debug>(value: &T) -> String {
495 match serde_json::to_value(value) {
496 Ok(Value::String(name)) => name,
497 _ => format!("{value:?}"),
498 }
499}
500
501fn front_matter_name(text: &str) -> Option<&str> {
504 let rest = text.strip_prefix("---\n")?;
505 let end = rest.find("\n---")?;
506 let header = &rest[..end];
507 if !header.lines().any(|line| line.starts_with("description:")) {
508 return None;
509 }
510 header.lines().find_map(|line| {
511 line.strip_prefix("name:").map(|value| value.trim().trim_matches('"').trim_matches('\''))
512 })
513}
514
515struct Unserved;
517
518#[async_trait]
519impl CapabilityHandler for Unserved {
520 async fn handle(&self, _call: CapabilityCall) -> Result<Value, CapabilityError> {
521 Err(CapabilityError::Failed("not served".into()))
522 }
523}
524
525impl PackBundle {
526 pub fn new(
528 name: impl Into<String>,
529 version: impl Into<String>,
530 publisher: PackPublisher,
531 description: impl Into<String>,
532 ) -> Self {
533 Self {
534 format: PACK_FORMAT.into(),
535 name: name.into(),
536 version: version.into(),
537 publisher,
538 description: description.into(),
539 capabilities: Vec::new(),
540 handlers: std::collections::BTreeMap::new(),
541 playbooks: Vec::new(),
542 drivers: Vec::new(),
543 digest: None,
544 proof: None,
545 }
546 }
547
548 #[must_use]
550 pub fn capability(mut self, declaration: CapabilityV2, handler: HandlerConfig) -> Self {
551 self.handlers.insert(declaration.name.clone(), handler);
552 self.capabilities.push(declaration);
553 self
554 }
555
556 #[must_use]
558 pub fn playbook(mut self, playbook: PackPlaybook) -> Self {
559 self.playbooks.push(playbook);
560 self
561 }
562
563 #[must_use]
565 pub fn driver(mut self, driver: PackDriver) -> Self {
566 self.drivers.push(driver);
567 self
568 }
569
570 pub fn semver(&self) -> Result<semver::Version, PackError> {
576 let version = semver::Version::parse(&self.version).map_err(|error| {
577 PackError::Invalid(format!(
578 "version `{}` is not a Semantic Version such as 1.2.0: {error}",
579 self.version
580 ))
581 })?;
582 if !version.build.is_empty() {
583 return Err(PackError::Invalid(format!(
584 "version `{}` carries build metadata, which orders no versions; drop the `+…`",
585 self.version
586 )));
587 }
588 Ok(version)
589 }
590
591 pub fn content_digest(&self) -> Result<Digest, PackError> {
598 let value =
599 serde_json::to_value(self).map_err(|error| PackError::Malformed(error.to_string()))?;
600 content_digest(&value)
601 }
602
603 pub async fn seal(mut self, signer: &dyn DocumentSigner) -> Result<Self, PackError> {
612 self.digest = None;
613 self.proof = None;
614 self.digest = Some(self.content_digest()?);
615 let proof = sign(&self, signer).await.map_err(|error| PackError::Io(error.to_string()))?;
616 self.proof = Some(proof);
617 Ok(self)
618 }
619
620 pub fn to_json(&self) -> Result<Vec<u8>, PackError> {
626 let mut bytes = serde_json::to_vec_pretty(self)
627 .map_err(|error| PackError::Malformed(error.to_string()))?;
628 bytes.push(b'\n');
629 Ok(bytes)
630 }
631
632 pub fn parse(bytes: &[u8]) -> Result<Self, PackError> {
639 Ok(Self::parse_value(bytes)?.0)
640 }
641
642 fn parse_value(bytes: &[u8]) -> Result<(Self, Value), PackError> {
643 if bytes.len() > MAX_BUNDLE_BYTES {
644 return Err(PackError::Malformed(format!(
645 "the file is {} bytes; a bundle is at most {MAX_BUNDLE_BYTES}",
646 bytes.len()
647 )));
648 }
649 let value: Value = serde_json::from_slice(bytes)
650 .map_err(|error| PackError::Malformed(format!("not JSON: {error}")))?;
651 if let Some(format) = value.get("format").and_then(Value::as_str)
652 && format != PACK_FORMAT
653 {
654 return Err(PackError::Format(format.to_string()));
655 }
656 let bundle: Self = serde_json::from_value(value.clone())
657 .map_err(|error| PackError::Malformed(error.to_string()))?;
658 Ok((bundle, value))
659 }
660
661 pub fn verify(bytes: &[u8], trust: &TrustList) -> Result<VerifiedPack, PackError> {
671 let (bundle, value) = Self::parse_value(bytes)?;
672 let Some(proof) = bundle.proof.clone() else {
673 return Err(PackError::Unsigned);
674 };
675 let Some(digest) = bundle.digest.clone() else {
676 return Err(PackError::Malformed(
677 "the bundle has a proof but no content digest".into(),
678 ));
679 };
680 let computed = content_digest(&value)?;
681 if computed != digest {
682 return Err(PackError::Tampered(format!(
683 "its content digest is {computed}, not the {digest} it names"
684 )));
685 }
686 let key = trust.key(&bundle.publisher.id, &proof.kid).ok_or_else(|| {
687 PackError::UnknownPublisher {
688 publisher: bundle.publisher.id.clone(),
689 kid: proof.kid.clone(),
690 }
691 })?;
692 verify(&value, &proof, key).map_err(|error| {
693 PackError::Tampered(format!(
694 "the signature does not verify with key `{}`: {error}",
695 proof.kid
696 ))
697 })?;
698 bundle.check()?;
699 Ok(VerifiedPack { thumbprint: jwk_thumbprint(key), kid: proof.kid, digest, bundle })
700 }
701
702 pub fn check(&self) -> Result<(), PackError> {
715 let invalid = |reason: String| Err(PackError::Invalid(reason));
716 if self.format != PACK_FORMAT {
717 return Err(PackError::Format(self.format.clone()));
718 }
719 if !is_valid_pack_name(&self.name) {
720 return invalid(format!(
721 "name `{}` is not 1–64 lowercase letters, digits and `-`",
722 self.name
723 ));
724 }
725 self.semver()?;
726 if !is_valid_publisher_id(&self.publisher.id) {
727 return invalid(format!(
728 "publisher `{}` is not 1–128 lowercase letters, digits, `.` and `-`",
729 self.publisher.id
730 ));
731 }
732 let description = self.description.trim();
733 if description.is_empty() || description.chars().count() > MAX_DESCRIPTION_CHARS {
734 return invalid(format!(
735 "the description must say what the pack adds, in at most {MAX_DESCRIPTION_CHARS} characters"
736 ));
737 }
738 if self.capabilities.is_empty() && self.playbooks.is_empty() && self.drivers.is_empty() {
739 return invalid("the pack adds no capability, playbook or driver".into());
740 }
741 if self.capabilities.len() > MAX_CAPABILITIES
742 || self.playbooks.len() > MAX_PLAYBOOKS
743 || self.drivers.len() > MAX_DRIVERS
744 {
745 return invalid(format!(
746 "a pack holds at most {MAX_CAPABILITIES} capabilities, {MAX_PLAYBOOKS} playbooks and {MAX_DRIVERS} drivers"
747 ));
748 }
749 self.check_capabilities()?;
750 self.check_playbooks()?;
751 self.check_drivers()
752 }
753
754 fn check_capabilities(&self) -> Result<(), PackError> {
755 let invalid = |reason: String| Err(PackError::Invalid(reason));
756 let mut names = BTreeSet::new();
757 for declaration in &self.capabilities {
758 let name = declaration.name.as_str();
759 if !names.insert(name) {
760 return invalid(format!("capability `{name}` is declared twice"));
761 }
762 CapabilityTool::new("pack.invalid", declaration.clone(), Arc::new(Unserved))
763 .map_err(|error| PackError::Invalid(format!("capability `{name}`: {error}")))?;
764 let Some(handler) = self.handlers.get(name) else {
765 return invalid(format!(
766 "capability `{name}` names no handler; add it to `handlers`"
767 ));
768 };
769 let least = handler.minimum_effect();
770 if strictness(declaration.effect) < strictness(least) {
771 return invalid(format!(
772 "capability `{name}` is declared `{}`, but the `{}` handler's calls are at \
773 least `{}`; declare the effect the handler has",
774 json_name(&declaration.effect),
775 handler.label(),
776 json_name(&least)
777 ));
778 }
779 let properties = declaration
780 .input_schema
781 .as_ref()
782 .and_then(|schema| schema.get("properties"))
783 .and_then(Value::as_object);
784 for member in handler.reads() {
785 if !properties.is_some_and(|properties| properties.contains_key(*member)) {
786 return invalid(format!(
787 "capability `{name}`'s input schema declares no `{member}`, which the \
788 `{}` handler reads",
789 handler.label()
790 ));
791 }
792 }
793 if properties.is_some_and(|properties| properties.contains_key("email"))
794 && declaration.consent.is_none()
795 {
796 return invalid(format!(
797 "capability `{name}` takes an email address without asking for consent; \
798 declare `consent` (spec 3.5 A-I8)"
799 ));
800 }
801 if let Some(consent) = &declaration.consent
802 && consent.policy_version != super::POLICY_VERSION
803 {
804 return invalid(format!(
805 "capability `{name}`'s consent names policy version `{}`; the site's \
806 policy, its public terms, is version `{}`",
807 consent.policy_version,
808 super::POLICY_VERSION
809 ));
810 }
811 }
812 if let Some(stray) = self.handlers.keys().find(|name| !names.contains(name.as_str())) {
813 return invalid(format!("handler for `{stray}`, which the pack does not declare"));
814 }
815 Ok(())
816 }
817
818 fn check_playbooks(&self) -> Result<(), PackError> {
819 let invalid = |reason: String| Err(PackError::Invalid(reason));
820 let mut ids = BTreeSet::new();
821 for playbook in &self.playbooks {
822 let id = playbook.id.as_str();
823 if !is_valid_pack_name(id) {
824 return invalid(format!(
825 "playbook `{id}` is not named with 1–64 lowercase letters, digits and `-`"
826 ));
827 }
828 if !ids.insert(id) {
829 return invalid(format!("playbook `{id}` appears twice"));
830 }
831 if crate::playbooks::playbook(id).is_some() {
832 return Err(PackError::Conflict(format!(
833 "playbook `{id}` is the product's own; name the pack's playbook differently"
834 )));
835 }
836 if playbook.text.len() > MAX_PLAYBOOK_BYTES {
837 return invalid(format!("playbook `{id}` is over {MAX_PLAYBOOK_BYTES} bytes"));
838 }
839 if front_matter_name(&playbook.text) != Some(id) {
840 return invalid(format!(
841 "playbook `{id}` must open with front matter naming it (`---\\nname: {id}\\n\
842 description: …\\n---`)"
843 ));
844 }
845 let Some(job) = crate::jobs::job(&playbook.job) else {
846 return invalid(format!(
847 "playbook `{id}` names job `{}`, which is not a job of spec 3.5 §7.20",
848 playbook.job
849 ));
850 };
851 if playbook.agents.is_empty() {
852 return invalid(format!("playbook `{id}` names no agent"));
853 }
854 if let Some(agent) = playbook.agents.iter().find(|agent| !job.agents.contains(agent)) {
855 return invalid(format!(
856 "playbook `{id}` is for {agent}, who does not run the `{}` job",
857 job.id
858 ));
859 }
860 }
861 Ok(())
862 }
863
864 fn check_drivers(&self) -> Result<(), PackError> {
865 let invalid = |reason: String| Err(PackError::Invalid(reason));
866 let mut ids = BTreeSet::new();
867 for driver in &self.drivers {
868 let id = driver.id.as_str();
869 if !is_valid_pack_name(id) {
870 return invalid(format!(
871 "driver `{id}` is not named with 1–64 lowercase letters, digits and `-`"
872 ));
873 }
874 if !ids.insert(id) {
875 return invalid(format!("driver `{id}` appears twice"));
876 }
877 let manifest = DriverManifest::from_toml(&driver.manifest)
878 .map_err(|error| PackError::Invalid(format!("driver `{id}`: {error}")))?;
879 if manifest.id != id {
880 return invalid(format!("driver `{id}`'s manifest is for `{}`", manifest.id));
881 }
882 if manifest.sandbox == DriverSandbox::Unsandboxed {
883 return invalid(format!(
884 "driver `{id}` runs unsandboxed; a pack's drivers run in the OS sandbox or a \
885 container"
886 ));
887 }
888 let partitions = [adk_drivers::PUBLIC_PARTITION, adk_drivers::BACK_OFFICE_PARTITION];
889 if manifest.partitions.is_empty()
890 || manifest.partitions.iter().any(|p| !partitions.contains(&p.as_str()))
891 {
892 return invalid(format!(
893 "driver `{id}` must serve the `{}` or `{}` partition",
894 partitions[0], partitions[1]
895 ));
896 }
897 if manifest.tools.is_empty() {
898 return invalid(format!("driver `{id}` lists no tools with their effect classes"));
899 }
900 if let Some((tool, _)) =
901 manifest.tools.iter().find(|(_, class)| **class == EffectClass::Other)
902 {
903 return invalid(format!(
904 "driver `{id}`'s tool `{tool}` is classed `other`; declare its effect class"
905 ));
906 }
907 }
908 Ok(())
909 }
910}
911
912fn content_digest(value: &Value) -> Result<Digest, PackError> {
914 let mut content = value.clone();
915 if let Some(object) = content.as_object_mut() {
916 object.remove("digest");
917 object.remove("proof");
918 }
919 document_digest(&content).map_err(|error| PackError::Malformed(error.to_string()))
920}
921
922#[cfg(test)]
923mod tests {
924 use super::*;
925 use adk_awp::signing::jws::Ed25519DocumentSigner;
926 use awp_types::{ConsentRequirement, ConsentScope};
927 use serde_json::json;
928
929 use crate::packs::trust::TrustedKey;
930
931 fn key() -> Ed25519DocumentSigner {
932 Ed25519DocumentSigner::from_seed("tables-2026", [4; 32]).unwrap()
933 }
934
935 fn trust() -> TrustList {
936 TrustList::new().with(TrustedKey::new("tables.example", "tables-2026", key().public_key()))
937 }
938
939 fn waitlist() -> PackBundle {
940 let join = CapabilityV2 {
941 consent: Some(ConsentRequirement {
942 scope: ConsentScope::Custom("contact".into()),
943 policy_version: "1".into(),
944 }),
945 input_schema: Some(json!({
946 "type": "object",
947 "properties": { "email": { "type": "string", "maxLength": 254 }, "party": { "type": "integer" } },
948 "required": ["email"],
949 "additionalProperties": false
950 })),
951 ..CapabilityV2::new(
952 "join_waitlist",
953 "Join tonight's waiting list",
954 CapabilityEffect::NonIdempotent,
955 )
956 };
957 PackBundle::new(
958 "waitlist",
959 "1.0.0",
960 PackPublisher::new("tables.example").named("Tables"),
961 "A waiting list for fully booked evenings",
962 )
963 .capability(join, HandlerConfig::Form)
964 .playbook(PackPlaybook {
965 id: "waitlist-capture".into(),
966 job: "capture".into(),
967 agents: vec![AgentRole::Concierge],
968 text: "---\nname: waitlist-capture\ndescription: Offer the waiting list.\n---\n\nOffer it.\n".into(),
969 })
970 .driver(PackDriver {
971 id: "tables-pos".into(),
972 manifest: "id = \"tables-pos\"\ncommand = \"mcp-tables\"\npartitions = [\"back-office\"]\n\n[tools]\ntables_list = \"read\"\n".into(),
973 })
974 }
975
976 async fn sealed(bundle: PackBundle) -> Vec<u8> {
977 bundle.seal(&key()).await.unwrap().to_json().unwrap()
978 }
979
980 fn refused(bytes: &[u8]) -> String {
981 PackBundle::verify(bytes, &trust()).unwrap_err().code().to_string()
982 }
983
984 #[tokio::test]
985 async fn a_sealed_bundle_verifies_and_reports_its_publisher_key() {
986 let verified = PackBundle::verify(&sealed(waitlist()).await, &trust()).unwrap();
987 assert_eq!(verified.bundle.name, "waitlist");
988 assert_eq!(verified.kid, "tables-2026");
989 assert_eq!(verified.thumbprint, jwk_thumbprint(&key().public_key()));
990 assert_eq!(Some(verified.digest), verified.bundle.digest);
991 }
992
993 #[tokio::test]
994 async fn unsigned_unknown_and_tampered_bundles_are_refused() {
995 assert_eq!(refused(&waitlist().to_json().unwrap()), "unsigned");
996 let bytes = sealed(waitlist()).await;
997 assert_eq!(
998 PackBundle::verify(&bytes, &TrustList::new()).unwrap_err().code(),
999 "unknown_publisher"
1000 );
1001 let other = TrustList::new().with(TrustedKey::new(
1002 "tables.example",
1003 "tables-2027",
1004 key().public_key(),
1005 ));
1006 assert_eq!(PackBundle::verify(&bytes, &other).unwrap_err().code(), "unknown_publisher");
1007
1008 let mut value: Value = serde_json::from_slice(&bytes).unwrap();
1009 value["capabilities"][0]["effect"] = json!("read_only");
1010 assert_eq!(refused(&serde_json::to_vec(&value).unwrap()), "tampered");
1011
1012 let digest = content_digest(&value).unwrap();
1014 value["digest"] = json!(digest);
1015 assert_eq!(refused(&serde_json::to_vec(&value).unwrap()), "tampered");
1016
1017 let thief = Ed25519DocumentSigner::from_seed("tables-2026", [5; 32]).unwrap();
1019 let forged = waitlist().seal(&thief).await.unwrap().to_json().unwrap();
1020 assert_eq!(refused(&forged), "tampered");
1021 }
1022
1023 #[tokio::test]
1024 async fn verification_reads_the_signed_json_not_a_reformatting() {
1025 let bytes = sealed(waitlist()).await;
1026 let value: Value = serde_json::from_slice(&bytes).unwrap();
1027 assert!(PackBundle::verify(&serde_json::to_vec(&value).unwrap(), &trust()).is_ok());
1028 let mut extra = value.clone();
1029 extra["capabilities"][0]["x-note"] = json!("added");
1030 assert_eq!(refused(&serde_json::to_vec(&extra).unwrap()), "tampered");
1031 let mut top = value;
1032 top["note"] = json!("added");
1033 assert_eq!(refused(&serde_json::to_vec(&top).unwrap()), "malformed");
1034 assert_eq!(refused(b"[1, 2"), "malformed");
1035 let mut later = serde_json::from_slice::<Value>(&bytes).unwrap();
1036 later["format"] = json!("adk-website.pack/2");
1037 assert_eq!(refused(&serde_json::to_vec(&later).unwrap()), "format");
1038 }
1039
1040 fn invalid(bundle: PackBundle) -> String {
1041 bundle.check().unwrap_err().to_string()
1042 }
1043
1044 #[test]
1045 fn handlers_must_fit_their_capabilities() {
1046 let mut weak = waitlist();
1047 weak.capabilities[0].effect = CapabilityEffect::ReadOnly;
1048 assert!(invalid(weak).contains("at least `idempotent`"));
1049
1050 let mut unhandled = waitlist();
1051 unhandled.handlers.clear();
1052 assert!(invalid(unhandled).contains("names no handler"));
1053
1054 let mut stray = waitlist();
1055 stray.handlers.insert("other_thing".into(), HandlerConfig::Search);
1056 assert!(invalid(stray).contains("does not declare"));
1057
1058 let booking =
1059 CapabilityV2::new("reserve_table", "Reserve", CapabilityEffect::NonIdempotent);
1060 let unread = waitlist()
1061 .capability(booking, HandlerConfig::Booking { operation: BookingOperation::Book });
1062 assert!(invalid(unread).contains("declares no `slot`"));
1063
1064 let mut no_consent = waitlist();
1065 no_consent.capabilities[0].consent = None;
1066 assert!(invalid(no_consent).contains("A-I8"));
1067
1068 let mut policy = waitlist();
1069 policy.capabilities[0].consent.as_mut().unwrap().policy_version = "7".into();
1070 assert!(invalid(policy).contains("policy version"));
1071
1072 let mut twice = waitlist();
1073 twice.capabilities.push(twice.capabilities[0].clone());
1074 assert!(invalid(twice).contains("declared twice"));
1075
1076 let mut bad_name = waitlist();
1077 bad_name.capabilities[0].name = "Join".into();
1078 bad_name.handlers = [("Join".to_string(), HandlerConfig::Form)].into();
1079 assert!(invalid(bad_name).contains("capability `Join`"));
1080 }
1081
1082 #[test]
1083 fn names_versions_and_publishers_are_checked() {
1084 let mut named = waitlist();
1085 named.name = "Wait List".into();
1086 assert!(invalid(named).contains("lowercase"));
1087 for version in ["1.0", "v1.0.0", "1.0.0+build.7"] {
1088 let mut versioned = waitlist();
1089 versioned.version = version.into();
1090 assert_eq!(versioned.check().unwrap_err().code(), "invalid", "{version}");
1091 }
1092 let mut publisher = waitlist();
1093 publisher.publisher.id = "Tables Ltd".into();
1094 assert!(invalid(publisher).contains("publisher"));
1095 let empty =
1096 PackBundle::new("empty", "1.0.0", PackPublisher::new("tables.example"), "Nothing");
1097 assert!(invalid(empty).contains("adds no"));
1098 let mut quiet = waitlist();
1099 quiet.description = " ".into();
1100 assert!(invalid(quiet).contains("description"));
1101 }
1102
1103 #[test]
1104 fn playbooks_are_skill_files_for_a_job_their_agents_run() {
1105 let with = |change: &dyn Fn(&mut PackPlaybook)| {
1106 let mut bundle = waitlist();
1107 change(&mut bundle.playbooks[0]);
1108 bundle.check().unwrap_err()
1109 };
1110 assert!(with(&|p| p.text = "Offer it.".into()).to_string().contains("front matter"));
1111 assert!(
1112 with(&|p| p.text = "---\nname: other\ndescription: x\n---\n".into())
1113 .to_string()
1114 .contains("front matter")
1115 );
1116 assert!(with(&|p| p.job = "world-domination".into()).to_string().contains("not a job"));
1117 assert!(
1118 with(&|p| p.agents = vec![AgentRole::Finance]).to_string().contains("does not run")
1119 );
1120 assert!(with(&|p| p.agents.clear()).to_string().contains("names no agent"));
1121 let product = with(&|p| {
1122 p.id = "sell".into();
1123 p.text = "---\nname: sell\ndescription: x\n---\n".into();
1124 });
1125 assert_eq!(product.code(), "conflict");
1126 }
1127
1128 #[test]
1129 fn drivers_are_sandboxed_and_declare_every_effect() {
1130 let with = |manifest: &str| {
1131 let mut bundle = waitlist();
1132 bundle.drivers[0].manifest = manifest.into();
1133 bundle.check().unwrap_err().to_string()
1134 };
1135 let base =
1136 "id = \"tables-pos\"\ncommand = \"mcp-tables\"\npartitions = [\"back-office\"]\n";
1137 assert!(
1138 with(&format!("{base}sandbox = \"unsandboxed\"\n[tools]\ntables_list = \"read\"\n"))
1139 .contains("unsandboxed")
1140 );
1141 assert!(
1142 with(&format!("{base}[tools]\ntables_list = \"other\"\n")).contains("classed `other`")
1143 );
1144 assert!(with(base).contains("lists no tools"));
1145 assert!(
1146 with("id = \"tables-pos\"\ncommand = \"mcp-tables\"\n[tools]\nx = \"read\"\n")
1147 .contains("partition")
1148 );
1149 assert!(with("id = \"till\"\ncommand = \"mcp-tables\"\npartitions = [\"public\"]\n[tools]\nx = \"read\"\n").contains("is for `till`"));
1150 assert!(with("not toml at all = = =").contains("driver `tables-pos`"));
1151 }
1152
1153 #[test]
1154 fn handler_configuration_reads_as_json() {
1155 for (text, config) in [
1156 (r#"{"handler":"form"}"#, HandlerConfig::Form),
1157 (
1158 r#"{"handler":"order","operation":"return"}"#,
1159 HandlerConfig::Order { operation: OrderOperation::Return },
1160 ),
1161 (
1162 r#"{"handler":"listing","content":"notice"}"#,
1163 HandlerConfig::Listing { content: ContentKind::Notice },
1164 ),
1165 ] {
1166 assert_eq!(serde_json::from_str::<HandlerConfig>(text).unwrap(), config);
1167 assert_eq!(serde_json::to_string(&config).unwrap(), text);
1168 }
1169 assert_eq!(HandlerConfig::Listing { content: ContentKind::Event }.label(), "listing/event");
1170 assert!(serde_json::from_str::<HandlerConfig>(r#"{"handler":"shell"}"#).is_err());
1171 }
1172
1173 #[test]
1174 fn refusals_map_to_adk_errors() {
1175 let error: AdkError = PackError::Unsigned.into();
1176 assert_eq!(error.category, ErrorCategory::Forbidden);
1177 assert_eq!(error.code, "website.pack.unsigned");
1178 }
1179}