oas-document 1.1.1

OAS Identity Document types and validation for the Open Agent Specification
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
// OAS Spec §5 — OAS Identity Document
//! Builder pattern for constructing OAS Identity Documents.

use oas_crypto::keypair::OasKeyPair;

use crate::calendar::CalendarSection;
use crate::compliance::ComplianceSection;
use crate::conformance::ConformanceLevel;
use crate::contact::ContactSection;
use crate::document::{DocumentMetadata, OasDocument};
use crate::error::DocumentError;
use crate::governance::GovernanceSection;
use crate::interop::InteroperabilitySection;
use crate::lifecycle::LifecycleStatus;
use crate::lineage_section::LineageSection;
use crate::operational::OperationalSection;
use crate::pricing::PricingSection;
use crate::profile::ProfileSection;
use crate::proof_format::DocumentProof;
use crate::relationships::RelationshipsSection;
use crate::reputation::ReputationSection;
use crate::service::ServiceEndpoint;
use crate::verification_method::VerificationMethod;

/// Builder for constructing [`OasDocument`] instances.
///
/// Provides an ergonomic API for building OAS Identity Documents
/// with proper defaults and validation.
///
/// # Examples
///
/// ```
/// use oas_document::builder::DocumentBuilder;
/// use oas_document::conformance::ConformanceLevel;
/// use oas_crypto::keypair::OasKeyPair;
///
/// let keypair = OasKeyPair::generate();
/// let doc = DocumentBuilder::new("did:oas:test:hmr:alice", "hmr")
///     .controller("did:oas:test:hmr:alice")
///     .conformance_level(ConformanceLevel::L1)
///     .add_verification_method(&keypair)
///     .name("Alice")
///     .build_and_sign(&keypair, "2026-01-15T00:00:00Z")
///     .unwrap();
/// assert_eq!(doc.kind, "hmr");
/// assert!(doc.proof.is_some());
/// ```
pub struct DocumentBuilder {
    id: String,
    kind: String,
    controller: Option<String>,
    verification_methods: Vec<VerificationMethod>,
    authentication: Vec<String>,
    assertion_method: Vec<String>,
    capability_invocation: Vec<String>,
    capability_delegation: Vec<String>,
    services: Vec<ServiceEndpoint>,
    name: Option<String>,
    description: Option<String>,
    lineage: Option<LineageSection>,
    governance: Option<GovernanceSection>,
    conformance_level: ConformanceLevel,
    lifecycle_status: Option<LifecycleStatus>,
    sequence: u64,
    // Extended identity sections (§5.8–§5.16)
    profile: Option<ProfileSection>,
    contact: Option<ContactSection>,
    calendar: Option<CalendarSection>,
    operational: Option<OperationalSection>,
    pricing: Option<PricingSection>,
    interoperability: Option<InteroperabilitySection>,
    reputation: Option<ReputationSection>,
    compliance: Option<ComplianceSection>,
    relationships: Option<RelationshipsSection>,
}

impl DocumentBuilder {
    /// Creates a new builder with the given DID and kind.
    ///
    /// # Arguments
    ///
    /// * `id` - The `did:oas` identifier.
    /// * `kind` - The entity kind string (e.g., `"hmr"`, `"agent"`).
    pub fn new(id: &str, kind: &str) -> Self {
        Self {
            id: id.to_string(),
            kind: kind.to_string(),
            controller: None,
            verification_methods: Vec::new(),
            authentication: Vec::new(),
            assertion_method: Vec::new(),
            capability_invocation: Vec::new(),
            capability_delegation: Vec::new(),
            services: Vec::new(),
            name: None,
            description: None,
            lineage: None,
            governance: None,
            conformance_level: ConformanceLevel::L0,
            lifecycle_status: None,
            sequence: 1,
            profile: None,
            contact: None,
            calendar: None,
            operational: None,
            pricing: None,
            interoperability: None,
            reputation: None,
            compliance: None,
            relationships: None,
        }
    }

    /// Sets the controller DID.
    pub fn controller(mut self, controller: &str) -> Self {
        self.controller = Some(controller.to_string());
        self
    }

    /// Adds a verification method from a keypair.
    ///
    /// Automatically adds the key to authentication, assertionMethod,
    /// capabilityInvocation, and capabilityDelegation relationships.
    pub fn add_verification_method(mut self, keypair: &OasKeyPair) -> Self {
        let key_num = self.verification_methods.len() as u32 + 1;
        let vm = VerificationMethod::new(&self.id, key_num, &keypair.public_key_multibase());
        let key_ref = vm.id.clone();
        self.verification_methods.push(vm);
        self.authentication.push(key_ref.clone());
        self.assertion_method.push(key_ref.clone());
        self.capability_invocation.push(key_ref.clone());
        self.capability_delegation.push(key_ref);
        self
    }

    /// Sets the conformance level.
    pub fn conformance_level(mut self, level: ConformanceLevel) -> Self {
        self.conformance_level = level;
        self
    }

    /// Sets the human-readable name.
    pub fn name(mut self, name: &str) -> Self {
        self.name = Some(name.to_string());
        self
    }

    /// Sets the human-readable description.
    pub fn description(mut self, description: &str) -> Self {
        self.description = Some(description.to_string());
        self
    }

    /// Sets the lineage section.
    pub fn lineage(mut self, lineage: LineageSection) -> Self {
        self.lineage = Some(lineage);
        self
    }

    /// Sets the governance section (ENR entities only).
    pub fn governance(mut self, governance: GovernanceSection) -> Self {
        self.governance = Some(governance);
        self
    }

    /// Sets the lifecycle status.
    pub fn lifecycle_status(mut self, status: LifecycleStatus) -> Self {
        self.lifecycle_status = Some(status);
        self
    }

    /// Sets the sequence number.
    pub fn sequence(mut self, seq: u64) -> Self {
        self.sequence = seq;
        self
    }

    /// Adds a service endpoint.
    pub fn add_service(mut self, service: ServiceEndpoint) -> Self {
        self.services.push(service);
        self
    }

    /// Sets the profile section (§5.8).
    pub fn profile(mut self, profile: ProfileSection) -> Self {
        self.profile = Some(profile);
        self
    }

    /// Sets the contact directory (§5.9).
    pub fn contact(mut self, contact: ContactSection) -> Self {
        self.contact = Some(contact);
        self
    }

    /// Sets the calendar & scheduling section (§5.10).
    pub fn calendar(mut self, calendar: CalendarSection) -> Self {
        self.calendar = Some(calendar);
        self
    }

    /// Sets the operational specification (§5.11).
    pub fn operational(mut self, operational: OperationalSection) -> Self {
        self.operational = Some(operational);
        self
    }

    /// Sets the pricing & economics section (§5.12).
    pub fn pricing(mut self, pricing: PricingSection) -> Self {
        self.pricing = Some(pricing);
        self
    }

    /// Sets the interoperability section (§5.13).
    pub fn interoperability(mut self, interop: InteroperabilitySection) -> Self {
        self.interoperability = Some(interop);
        self
    }

    /// Sets the reputation summary (§5.14).
    pub fn reputation(mut self, reputation: ReputationSection) -> Self {
        self.reputation = Some(reputation);
        self
    }

    /// Sets the compliance & jurisdiction section (§5.15).
    pub fn compliance(mut self, compliance: ComplianceSection) -> Self {
        self.compliance = Some(compliance);
        self
    }

    /// Sets the relationships & affiliations section (§5.16).
    pub fn relationships(mut self, relationships: RelationshipsSection) -> Self {
        self.relationships = Some(relationships);
        self
    }

    /// Builds the document and signs it.
    ///
    /// # Arguments
    ///
    /// * `signing_keypair` - The keypair to sign the document with.
    /// * `created` - ISO 8601 timestamp for both document creation and proof.
    ///
    /// # Returns
    ///
    /// A complete, signed [`OasDocument`].
    ///
    /// # Errors
    ///
    /// Returns [`DocumentError`] if signing fails.
    pub fn build_and_sign(
        self,
        signing_keypair: &OasKeyPair,
        created: &str,
    ) -> Result<OasDocument, DocumentError> {
        let controller = self.controller.unwrap_or_else(|| self.id.clone());

        let mut doc = OasDocument {
            context: OasDocument::default_context(),
            id: self.id,
            controller,
            verification_method: self.verification_methods,
            authentication: self.authentication,
            assertion_method: self.assertion_method,
            capability_invocation: self.capability_invocation,
            capability_delegation: self.capability_delegation,
            service: self.services,
            oas_version: crate::document::OAS_VERSION.to_string(),
            kind: self.kind,
            name: self.name,
            description: self.description,
            lineage: self.lineage,
            governance: self.governance,
            conformance_level: self.conformance_level,
            lifecycle_status: self.lifecycle_status,
            sequence: self.sequence,
            metadata: DocumentMetadata {
                created: created.to_string(),
                updated: None,
                version: None,
            },
            proof: None,
            revoked: None,
            revoked_at: None,
            profile: self.profile,
            contact: self.contact,
            calendar: self.calendar,
            operational: self.operational,
            pricing: self.pricing,
            interoperability: self.interoperability,
            reputation: self.reputation,
            compliance: self.compliance,
            relationships: self.relationships,
        };

        // Generate proof: serialize without proof, sign, attach
        let doc_json =
            serde_json::to_value(&doc).map_err(|e| DocumentError::ProofGenerationFailed {
                reason: format!("failed to serialize document: {e}"),
            })?;

        let vm_id = doc
            .verification_method
            .first()
            .map(|vm| vm.id.as_str())
            .ok_or_else(|| DocumentError::ProofGenerationFailed {
                reason: "no verification method available for signing".to_string(),
            })?
            .to_string();

        let proof = DocumentProof::generate(&doc_json, signing_keypair, &vm_id, created)?;
        doc.proof = Some(proof);

        Ok(doc)
    }
}

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

    #[test]
    fn build_hmr_document() {
        let keypair = OasKeyPair::generate();
        let doc = DocumentBuilder::new("did:oas:test:hmr:alice", "hmr")
            .controller("did:oas:test:hmr:alice")
            .conformance_level(ConformanceLevel::L1)
            .add_verification_method(&keypair)
            .name("Alice")
            .build_and_sign(&keypair, "2026-01-15T00:00:00Z");

        assert!(doc.is_ok());
        let doc = doc.unwrap_or_else(|_| unreachable_doc());
        assert_eq!(doc.kind, "hmr");
        assert!(doc.proof.is_some());
        assert_eq!(doc.sequence, 1);
        assert!(doc.is_root());
    }

    #[test]
    fn build_agent_document_with_lineage() {
        let keypair = OasKeyPair::generate();
        let lineage = LineageSection {
            human_root_did: "did:oas:test:hmr:alice".to_string(),
            creator_did: "did:oas:test:hmr:alice".to_string(),
            generation: 0,
            derivation_proof: None,
            human_root_chain: vec![
                "did:oas:test:agent:bot".to_string(),
                "did:oas:test:hmr:alice".to_string(),
            ],
            org_inclusion_proof: None,
            anchor_refs: None,
        };

        let doc = DocumentBuilder::new("did:oas:test:agent:bot", "agent")
            .controller("did:oas:test:hmr:alice")
            .conformance_level(ConformanceLevel::L1)
            .add_verification_method(&keypair)
            .lineage(lineage)
            .lifecycle_status(LifecycleStatus::Active)
            .build_and_sign(&keypair, "2026-01-15T00:00:00Z");

        assert!(doc.is_ok());
        let doc = doc.unwrap_or_else(|_| unreachable_doc());
        assert!(doc.lineage.is_some());
        assert!(!doc.is_root());
    }

    fn unreachable_doc() -> OasDocument {
        OasDocument {
            context: vec![],
            id: String::new(),
            controller: String::new(),
            verification_method: vec![],
            authentication: vec![],
            assertion_method: vec![],
            capability_invocation: vec![],
            capability_delegation: vec![],
            service: vec![],
            oas_version: String::new(),
            kind: String::new(),
            name: None,
            description: None,
            lineage: None,
            governance: None,
            conformance_level: ConformanceLevel::L0,
            lifecycle_status: None,
            sequence: 0,
            metadata: DocumentMetadata {
                created: String::new(),
                updated: None,
                version: None,
            },
            proof: None,
            revoked: None,
            revoked_at: None,
            profile: None,
            contact: None,
            calendar: None,
            operational: None,
            pricing: None,
            interoperability: None,
            reputation: None,
            compliance: None,
            relationships: None,
        }
    }
}