vellaveto-types 6.1.1

Core type definitions for Vellaveto policy engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
// Copyright 2026 Paolo Vella
// SPDX-License-Identifier: MPL-2.0

//! DID:PLC (Decentralized Identifier: PLC) data types.
//!
//! Pure data types for DID:PLC identifiers — no cryptographic operations here.
//! Crypto (hashing, signing) lives in `vellaveto-mcp/src/did_plc.rs`.
//!
//! DID:PLC is a self-authenticating decentralized identifier scheme where the
//! DID is derived from the SHA-256 hash of a signed genesis operation.
//!
//! Format: `did:plc:<24-char-base32-suffix>`

use serde::{Deserialize, Serialize};
use std::fmt;

/// A validated DID:PLC identifier.
///
/// Format: `did:plc:<suffix>` where suffix is exactly 24 lowercase Base32
/// characters (no padding) derived from the first 15 bytes of a SHA-256 hash
/// of the canonicalized genesis operation.
///
/// # Example
///
/// ```
/// use vellaveto_types::DidPlc;
///
/// let did = DidPlc::from_str_validated("did:plc:ewvi7nxsareczkwkx5pz6q6e");
/// assert!(did.is_some());
///
/// let bad = DidPlc::from_str_validated("did:plc:TOOSHORT");
/// assert!(bad.is_none());
/// ```
// SECURITY (FIND-R46-001): Custom Deserialize implementation validates the
// DID:PLC format on deserialization. Previously `#[serde(transparent)]` allowed
// any arbitrary string to deserialize into a DidPlc, bypassing validation.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
pub struct DidPlc(String);

impl<'de> serde::Deserialize<'de> for DidPlc {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        DidPlc::from_str_validated(&s).ok_or_else(|| {
            serde::de::Error::custom(format!(
                "invalid DID:PLC format: expected 'did:plc:<24-char-base32-suffix>', got '{}'",
                if s.len() > 60 { &s[..60] } else { &s }
            ))
        })
    }
}

impl DidPlc {
    /// The required prefix for all DID:PLC identifiers.
    pub const PREFIX: &'static str = "did:plc:";

    /// The exact length of the Base32 suffix (15 bytes -> 24 chars in base32).
    pub const SUFFIX_LEN: usize = 24;

    /// Validate and construct a `DidPlc` from a string.
    ///
    /// Returns `None` if:
    /// - Missing `did:plc:` prefix
    /// - Suffix is not exactly 24 characters
    /// - Suffix contains non-base32 characters (a-z, 2-7)
    pub fn from_str_validated(s: &str) -> Option<Self> {
        let suffix = s.strip_prefix(Self::PREFIX)?;
        if suffix.len() != Self::SUFFIX_LEN {
            return None;
        }
        // Base32 lowercase alphabet: a-z, 2-7
        if !suffix
            .chars()
            .all(|c| c.is_ascii_lowercase() || ('2'..='7').contains(&c))
        {
            return None;
        }
        Some(Self(s.to_string()))
    }

    /// Construct a `DidPlc` from a pre-computed Base32 suffix.
    ///
    /// Returns `None` if the suffix is not exactly 24 characters of valid
    /// Base32 (a-z, 2-7).
    ///
    /// SECURITY (FIND-R46-002): Previously accepted arbitrary strings without
    /// validation, bypassing the safety guarantees of the validated newtype.
    pub fn from_parts(suffix: String) -> Option<Self> {
        if suffix.len() != Self::SUFFIX_LEN {
            return None;
        }
        if !suffix
            .chars()
            .all(|c| c.is_ascii_lowercase() || ('2'..='7').contains(&c))
        {
            return None;
        }
        Some(Self(format!("{}{}", Self::PREFIX, suffix)))
    }

    /// Returns the full DID string (e.g., `did:plc:ewvi7nxsareczkwkx5pz6q6e`).
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Returns only the identifier suffix (after `did:plc:`).
    pub fn identifier(&self) -> &str {
        &self.0[Self::PREFIX.len()..]
    }
}

impl fmt::Display for DidPlc {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// A service endpoint in a DID:PLC document.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct DidPlcService {
    /// Service identifier (e.g., `"atproto_pds"`).
    pub id: String,
    /// Service type (e.g., `"AtprotoPersonalDataServer"`).
    pub service_type: String,
    /// Service endpoint URL.
    pub endpoint: String,
}

/// The genesis (creation) operation for a DID:PLC identifier.
///
/// The DID is derived from the SHA-256 hash of the canonicalized JSON
/// representation of this operation (with `sig` set to `null`).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct DidPlcGenesisOperation {
    /// Operation type — always `"plc_operation"` for genesis.
    #[serde(rename = "type")]
    pub op_type: String,
    /// Rotation keys (did:key format) that can update this DID document.
    #[serde(default)]
    pub rotation_keys: Vec<String>,
    /// Verification methods (did:key format) for signing.
    #[serde(default)]
    pub verification_methods: Vec<String>,
    /// Also-known-as identifiers (e.g., `at://` handles).
    #[serde(default)]
    pub also_known_as: Vec<String>,
    /// Service endpoints.
    #[serde(default)]
    pub services: Vec<DidPlcService>,
    /// Signature over the operation (set to `null` for DID derivation).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sig: Option<String>,
    /// Previous operation CID (null for genesis).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prev: Option<String>,
}

impl DidPlcGenesisOperation {
    /// Maximum entries per vector field.
    pub const MAX_ENTRIES: usize = 100;
    /// Maximum byte length per string entry.
    pub const MAX_ENTRY_LEN: usize = 4096;

    pub fn validate(&self) -> Result<(), DidPlcError> {
        // SECURITY (FIND-R216-014): Reject control/format chars in op_type.
        if crate::core::has_dangerous_chars(&self.op_type) {
            return Err(DidPlcError::InvalidFormat(
                "op_type contains control or format characters".to_string(),
            ));
        }
        let fields: &[(&str, &[String])] = &[
            ("verification_methods", &self.verification_methods),
            ("also_known_as", &self.also_known_as),
            ("rotation_keys", &self.rotation_keys),
        ];
        for &(name, vec) in fields {
            if vec.len() > Self::MAX_ENTRIES {
                return Err(DidPlcError::InvalidFormat(format!(
                    "{} count {} exceeds max {}",
                    name,
                    vec.len(),
                    Self::MAX_ENTRIES
                )));
            }
            for (i, entry) in vec.iter().enumerate() {
                if entry.len() > Self::MAX_ENTRY_LEN {
                    return Err(DidPlcError::InvalidFormat(format!(
                        "{}[{}] length {} exceeds max {}",
                        name,
                        i,
                        entry.len(),
                        Self::MAX_ENTRY_LEN
                    )));
                }
                // SECURITY (FIND-R216-014): Reject control/format chars in entries.
                if crate::core::has_dangerous_chars(entry) {
                    return Err(DidPlcError::InvalidFormat(format!(
                        "{name}[{i}] contains control or format characters",
                    )));
                }
            }
        }
        if self.services.len() > Self::MAX_ENTRIES {
            return Err(DidPlcError::InvalidFormat(format!(
                "services count {} exceeds max {}",
                self.services.len(),
                Self::MAX_ENTRIES
            )));
        }
        for (i, svc) in self.services.iter().enumerate() {
            if svc.id.len() > Self::MAX_ENTRY_LEN {
                return Err(DidPlcError::InvalidFormat(format!(
                    "services[{}].id length {} exceeds max {}",
                    i,
                    svc.id.len(),
                    Self::MAX_ENTRY_LEN
                )));
            }
            // SECURITY (FIND-R216-014): Reject control/format chars in service fields.
            if crate::core::has_dangerous_chars(&svc.id) {
                return Err(DidPlcError::InvalidFormat(format!(
                    "services[{i}].id contains control or format characters",
                )));
            }
            if svc.service_type.len() > Self::MAX_ENTRY_LEN {
                return Err(DidPlcError::InvalidFormat(format!(
                    "services[{}].service_type length {} exceeds max {}",
                    i,
                    svc.service_type.len(),
                    Self::MAX_ENTRY_LEN
                )));
            }
            if crate::core::has_dangerous_chars(&svc.service_type) {
                return Err(DidPlcError::InvalidFormat(format!(
                    "services[{i}].service_type contains control or format characters",
                )));
            }
            if svc.endpoint.len() > Self::MAX_ENTRY_LEN {
                return Err(DidPlcError::InvalidFormat(format!(
                    "services[{}].endpoint length {} exceeds max {}",
                    i,
                    svc.endpoint.len(),
                    Self::MAX_ENTRY_LEN
                )));
            }
            if crate::core::has_dangerous_chars(&svc.endpoint) {
                return Err(DidPlcError::InvalidFormat(format!(
                    "services[{i}].endpoint contains control or format characters",
                )));
            }
        }
        // SECURITY (FIND-R216-014): Validate optional sig and prev fields.
        if let Some(ref sig) = self.sig {
            if sig.len() > Self::MAX_ENTRY_LEN {
                return Err(DidPlcError::InvalidFormat(format!(
                    "sig length {} exceeds max {}",
                    sig.len(),
                    Self::MAX_ENTRY_LEN,
                )));
            }
            if crate::core::has_dangerous_chars(sig) {
                return Err(DidPlcError::InvalidFormat(
                    "sig contains control or format characters".to_string(),
                ));
            }
        }
        if let Some(ref prev) = self.prev {
            if prev.len() > Self::MAX_ENTRY_LEN {
                return Err(DidPlcError::InvalidFormat(format!(
                    "prev length {} exceeds max {}",
                    prev.len(),
                    Self::MAX_ENTRY_LEN,
                )));
            }
            if crate::core::has_dangerous_chars(prev) {
                return Err(DidPlcError::InvalidFormat(
                    "prev contains control or format characters".to_string(),
                ));
            }
        }
        Ok(())
    }
}

/// Errors related to DID:PLC operations.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DidPlcError {
    /// The DID string does not match the expected format.
    InvalidFormat(String),
    /// A required field is missing from the genesis operation.
    MissingField(String),
    /// Signing the genesis operation failed.
    SigningError(String),
    /// Verification of a DID operation failed.
    VerificationFailed(String),
    /// Resolution of a DID from a PLC directory failed.
    ResolutionError(String),
}

impl fmt::Display for DidPlcError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DidPlcError::InvalidFormat(msg) => write!(f, "Invalid DID:PLC format: {msg}"),
            DidPlcError::MissingField(field) => {
                write!(f, "Missing required field in genesis operation: {field}")
            }
            DidPlcError::SigningError(msg) => write!(f, "DID:PLC signing error: {msg}"),
            DidPlcError::VerificationFailed(msg) => {
                write!(f, "DID:PLC verification failed: {msg}")
            }
            DidPlcError::ResolutionError(msg) => write!(f, "DID:PLC resolution error: {msg}"),
        }
    }
}

impl std::error::Error for DidPlcError {}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_did_plc_valid() {
        let did = DidPlc::from_str_validated("did:plc:ewvi7nxsareczkwkx5pz6q6e");
        assert!(did.is_some());
        let did = did.expect("valid DID");
        assert_eq!(did.as_str(), "did:plc:ewvi7nxsareczkwkx5pz6q6e");
        assert_eq!(did.identifier(), "ewvi7nxsareczkwkx5pz6q6e");
    }

    #[test]
    fn test_did_plc_invalid_prefix() {
        assert!(DidPlc::from_str_validated("did:web:example.com").is_none());
        assert!(DidPlc::from_str_validated("ewvi7nxsareczkwkx5pz6q6e").is_none());
    }

    #[test]
    fn test_did_plc_invalid_suffix_length() {
        assert!(DidPlc::from_str_validated("did:plc:tooshort").is_none());
        assert!(DidPlc::from_str_validated("did:plc:waytoolongstringherexyz12345").is_none());
    }

    #[test]
    fn test_did_plc_invalid_characters() {
        // '8', '9', '0', '1' are not in base32 lowercase alphabet
        assert!(DidPlc::from_str_validated("did:plc:890100000000000000000000").is_none());
        // Uppercase not allowed
        assert!(DidPlc::from_str_validated("did:plc:EWVI7NXSARECZKWKX5PZ6Q6E").is_none());
    }

    #[test]
    fn test_did_plc_from_parts() {
        let did = DidPlc::from_parts("abcdefghijklmnopqrstuvwx".to_string());
        assert!(did.is_some());
        let did = did.unwrap();
        assert_eq!(did.as_str(), "did:plc:abcdefghijklmnopqrstuvwx");
        assert_eq!(did.identifier(), "abcdefghijklmnopqrstuvwx");
    }

    #[test]
    fn test_did_plc_from_parts_invalid_rejected() {
        // SECURITY (FIND-R46-002): from_parts now validates the suffix
        assert!(DidPlc::from_parts("INVALID".to_string()).is_none());
        assert!(DidPlc::from_parts("".to_string()).is_none());
        assert!(DidPlc::from_parts("890100000000000000000000".to_string()).is_none());
    }

    #[test]
    fn test_did_plc_display() {
        let did = DidPlc::from_parts("ewvi7nxsareczkwkx5pz6q6e".to_string()).unwrap();
        assert_eq!(format!("{did}"), "did:plc:ewvi7nxsareczkwkx5pz6q6e");
    }

    #[test]
    fn test_did_plc_serde_roundtrip() {
        let did = DidPlc::from_parts("ewvi7nxsareczkwkx5pz6q6e".to_string()).unwrap();
        let json = serde_json::to_string(&did).expect("serialize");
        let deserialized: DidPlc = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(did, deserialized);
    }

    // SECURITY (FIND-R46-001): Deserialization must validate the DID:PLC format
    #[test]
    fn test_did_plc_serde_rejects_invalid() {
        let result: Result<DidPlc, _> = serde_json::from_str("\"arbitrary-string\"");
        assert!(
            result.is_err(),
            "Invalid DID:PLC must be rejected on deserialization"
        );
    }

    #[test]
    fn test_did_plc_genesis_operation_serde() {
        let genesis = DidPlcGenesisOperation {
            op_type: "plc_operation".to_string(),
            rotation_keys: vec!["did:key:z123".to_string()],
            verification_methods: vec!["did:key:z456".to_string()],
            also_known_as: vec![],
            services: vec![DidPlcService {
                id: "atproto_pds".to_string(),
                service_type: "AtprotoPersonalDataServer".to_string(),
                endpoint: "https://pds.example.com".to_string(),
            }],
            sig: None,
            prev: None,
        };
        let json = serde_json::to_string(&genesis).expect("serialize");
        let deserialized: DidPlcGenesisOperation =
            serde_json::from_str(&json).expect("deserialize");
        assert_eq!(genesis, deserialized);
        // sig and prev should be omitted when None
        assert!(!json.contains("\"sig\""));
        assert!(!json.contains("\"prev\""));
    }
}