Skip to main content

pmcp_package/
error.rs

1//! Crate-wide error surface for `pmcp-package`.
2//!
3//! One flat, structured `PackageError` enum covers every failure mode the
4//! crate's modules produce: digest/verify, allowlist enforcement
5//!, reference parsing, slot-conflict detection, OCI layout I/O,
6//! and (de)serialization. Variants carry concrete structured fields (not bare
7//! `String`-wrapped messages), following the `PathError`
8//! (`built-in/agents-api/crates/mcp-builtin-server-core/src/path_validator.rs`)
9//! and `PolicyManagementError`
10//! (`built-in/shared/mcp-server-common/src/code_mode/policy_management.rs`)
11//! precedents.
12//!
13//! There is deliberately NO `SlotDeviation` variant: behavior-relevant
14//! deviation detection returns `Option<Deviation>` — a value, not
15//! an error — so an error variant for it would be dead code. `SlotConflict`
16//! is the one slot-related error variant; it is returned by
17//! `slot::aggregate()` when the same behavior-relevant slot (kind+name)
18//! carries different tested values across components (a silent
19//! discard would mask a behavioral change).
20//!
21//! `serde_json::Error` has a single type covering both serialize and
22//! deserialize failures, so there is exactly one `#[from]` variant
23//! (`Serialize`) for it — a second `#[from] serde_json::Error` variant would
24//! be a duplicate `impl From` and fail to compile.
25//!
26//! No `reqwest::Error` variant exists — this crate makes no HTTP calls.
27
28/// Result type alias for this crate.
29pub type Result<T> = std::result::Result<T, PackageError>;
30
31/// All ways a `pmcp-package` operation can fail.
32#[derive(Debug, thiserror::Error)]
33pub enum PackageError {
34    /// JSON (de)serialization failure. Covers both directions — serde_json
35    /// has a single `Error` type for both, so there is exactly one variant.
36    #[error("serialization error: {0}")]
37    Serialize(#[from] serde_json::Error),
38
39    /// Filesystem I/O failure (OCI layout read/write, blob read/write).
40    #[error("I/O error: {0}")]
41    Io(#[from] std::io::Error),
42
43    /// A recomputed digest did not match the digest declared in a manifest
44    /// or descriptor (tamper detection).
45    #[error("digest mismatch: expected {expected}, got {actual}")]
46    DigestMismatch { expected: String, actual: String },
47
48    /// A digest string is not well-formed (e.g. not `sha256:<64-hex>`).
49    #[error("malformed digest: {reason}")]
50    MalformedDigest { reason: String },
51
52    /// A deploy descriptor requested a CloudFormation resource type not on
53    /// the allowlist.
54    #[error("allowlist violation: {resource}")]
55    AllowlistViolation { resource: String },
56
57    /// A `ComponentRef` string (semver range or pinned+digest form) failed
58    /// to parse.
59    #[error("invalid reference: {reason}")]
60    InvalidReference { reason: String },
61
62    /// The same behavior-relevant slot (kind+name) carried different tested
63    /// values across components during aggregation.
64    #[error("slot conflict on '{slot}': tested={tested}, proposed={proposed}")]
65    SlotConflict {
66        slot: String,
67        tested: String,
68        proposed: String,
69    },
70
71    /// An OCI Image Layout on disk was malformed or incomplete (missing
72    /// `oci-layout`, missing `index.json`, missing referenced blob, etc.).
73    #[error("OCI layout error: {reason}")]
74    Layout { reason: String },
75
76    /// A server config declared or supplied a config slot that violates the
77    /// package's slot contract (an undeclared key, a missing required key, a
78    /// key whose shape does not match its declared slot type).
79    ///
80    /// `key` names the offending config KEY and `reason` describes the
81    /// violation. Neither ever carries the key's VALUE — a config slot may
82    /// name a secret, and an error message is the wrong place for one.
83    #[error("config slot violation on '{key}': {reason}")]
84    ConfigSlotViolation { key: String, reason: String },
85
86    /// An attestation's subject digest does not name the package it was being
87    /// packed into: the supplied subject differs from the would-be UNATTESTED
88    /// manifest digest of the very package under construction.
89    ///
90    /// Returned by `pack_server` BEFORE its first blob write, which is what
91    /// makes "an attestation attached to the wrong package" unrepresentable in
92    /// a produced layout rather than merely reported afterwards.
93    ///
94    /// Distinct from [`PackageError::DigestMismatch`] on purpose, and the two
95    /// must never be merged: a digest mismatch means the BYTES are corrupt,
96    /// while a subject mismatch means the bytes are fine and the CLAIM is
97    /// wrong.
98    ///
99    /// `supplied` and `computed` are both `sha256:<hex>` digest strings, and
100    /// this variant carries nothing else. It never carries attestation payload
101    /// bytes, an issuer, or any other attestation material — the same rule
102    /// [`PackageError::ConfigSlotViolation`]'s rustdoc sets for this crate,
103    /// applied to a payload that is opaque platform-owned data this crate has
104    /// deliberately never parsed.
105    ///
106    /// # Version consequence
107    ///
108    /// `PackageError` is NOT `#[non_exhaustive]`, so adding this variant is a
109    /// breaking change for every downstream `match` over it. Plan 122-08 owns
110    /// the version number that names that break; this crate publishes nothing
111    /// on its own account.
112    #[error(
113        "attestation subject mismatch: the attestation names {supplied}, but this package's \
114         unattested manifest digest is {computed}"
115    )]
116    AttestationSubjectMismatch {
117        /// The `sha256:<hex>` subject the caller supplied with the attestation.
118        supplied: String,
119        /// The `sha256:<hex>` unattested manifest digest actually computed for
120        /// the package being packed.
121        computed: String,
122    },
123
124    /// An attestation's annotation value cannot survive this crate's canonical
125    /// JSON form, so packing it would produce a manifest no JSON parser can
126    /// read back.
127    ///
128    /// Canonical JSON (OLPC/TUF, which `olpc-cjson` implements and this crate's
129    /// `canonicalize` uses) escapes ONLY `"` and `\`. A C0 control character
130    /// (U+0000–U+001F) in any string it emits is written LITERALLY, and RFC 8259
131    /// forbids an unescaped control character inside a JSON string — so the
132    /// manifest bytes would be invalid JSON. The package would pack cleanly and
133    /// then fail to unpack, here and in every other OCI tool.
134    ///
135    /// Refused BEFORE the first blob write, for the same reason
136    /// [`PackageError::AttestationSubjectMismatch`] is: an unreadable package is
137    /// worse to produce and diagnose later than to refuse now. Attestation
138    /// annotation values arrive from the issuing platform rather than from this
139    /// repo, which is precisely why they are validated rather than trusted.
140    ///
141    /// `annotation` names the offending annotation KEY and `reason` describes
142    /// the offending code point and where it sits. Neither ever carries the
143    /// annotation's VALUE — the same rule
144    /// [`PackageError::ConfigSlotViolation`] sets, applied to untrusted input
145    /// that may be arbitrarily long or itself hostile to a terminal.
146    ///
147    /// # Version consequence
148    ///
149    /// `PackageError` is NOT `#[non_exhaustive]`, so adding this variant is a
150    /// breaking change for every downstream `match` over it. Plan 122-08 owns
151    /// the version number that names that break, together with the sibling
152    /// break [`PackageError::AttestationSubjectMismatch`] introduced.
153    #[error("attestation annotation '{annotation}' is not representable: {reason}")]
154    AttestationAnnotationInvalid {
155        /// The annotation KEY whose value was refused, e.g.
156        /// `run.pmcp.attestation.issuer`.
157        annotation: String,
158        /// What is wrong with the value, naming the code point and its byte
159        /// offset but never reproducing the value itself.
160        reason: String,
161    },
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167
168    #[test]
169    fn digest_mismatch_display_contains_structured_fields() {
170        let err = PackageError::DigestMismatch {
171            expected: "sha256:aaaa".to_string(),
172            actual: "sha256:bbbb".to_string(),
173        };
174        let msg = err.to_string();
175        assert!(msg.contains("sha256:aaaa"), "message was: {msg}");
176        assert!(msg.contains("sha256:bbbb"), "message was: {msg}");
177    }
178
179    #[test]
180    fn slot_conflict_display_contains_structured_fields() {
181        let err = PackageError::SlotConflict {
182            slot: "llm-provider".to_string(),
183            tested: "anthropic".to_string(),
184            proposed: "openai".to_string(),
185        };
186        let msg = err.to_string();
187        assert!(msg.contains("llm-provider"), "message was: {msg}");
188        assert!(msg.contains("anthropic"), "message was: {msg}");
189        assert!(msg.contains("openai"), "message was: {msg}");
190    }
191
192    #[test]
193    fn serialize_variant_wraps_serde_json_error_via_from() {
194        let json_err = serde_json::from_str::<serde_json::Value>("{not valid json")
195            .expect_err("must fail to parse");
196        let err: PackageError = json_err.into();
197        assert!(matches!(err, PackageError::Serialize(_)));
198    }
199}