anp 0.7.0

Rust SDK for Agent Network Protocol (ANP)
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//! ANP IM business proof generation and verification.

use std::collections::BTreeMap;

use base64::{
    engine::general_purpose::STANDARD,
    engine::general_purpose::URL_SAFE_NO_PAD,
    Engine as _,
};
use chrono::Utc;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;

use crate::authentication::{build_content_digest, find_verification_method};
use crate::{PrivateKeyMaterial, PublicKeyMaterial};

pub const IM_PROOF_DEFAULT_COMPONENTS: [&str; 3] =
    ["@method", "@target-uri", "content-digest"];

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ImProof {
    #[serde(rename = "contentDigest")]
    pub content_digest: String,
    #[serde(rename = "signatureInput")]
    pub signature_input: String,
    pub signature: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ParsedImSignatureInput {
    pub label: String,
    pub components: Vec<String>,
    pub signature_params: String,
    pub keyid: String,
    pub nonce: Option<String>,
    pub created: Option<i64>,
    pub expires: Option<i64>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ImProofGenerationOptions {
    pub label: String,
    pub components: Vec<String>,
    pub created: Option<i64>,
    pub expires: Option<i64>,
    pub nonce: Option<String>,
}

impl Default for ImProofGenerationOptions {
    fn default() -> Self {
        Self {
            label: "sig1".to_owned(),
            components: IM_PROOF_DEFAULT_COMPONENTS
                .iter()
                .map(|value| (*value).to_owned())
                .collect(),
            created: None,
            expires: None,
            nonce: None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ImProofVerificationResult {
    pub parsed_signature_input: ParsedImSignatureInput,
    pub verification_method: Value,
}

#[derive(Debug, Error)]
pub enum ImProofError {
    #[error("missing proof field: {0}")]
    MissingField(&'static str),
    #[error("invalid proof.signatureInput format")]
    InvalidSignatureInput,
    #[error("proof.signatureInput must include covered components")]
    MissingCoveredComponents,
    #[error("proof.signatureInput must include keyid")]
    MissingKeyId,
    #[error("invalid proof.signature encoding")]
    InvalidSignatureEncoding,
    #[error("proof contentDigest does not match request payload")]
    InvalidContentDigest,
    #[error("verification method not found in DID document")]
    VerificationMethodNotFound,
    #[error("proof keyid must belong to expected signer DID")]
    InvalidSignerDid,
    #[error("signing error")]
    SigningError,
    #[error("signature verification failed")]
    VerificationFailed,
}

pub fn build_im_content_digest(payload: &[u8]) -> String {
    build_content_digest(payload)
}

pub fn verify_im_content_digest(payload: &[u8], content_digest: &str) -> bool {
    build_im_content_digest(payload) == content_digest.trim()
}

pub fn build_im_signature_input(
    keyid: &str,
    options: ImProofGenerationOptions,
) -> Result<String, ImProofError> {
    if options.components.is_empty() {
        return Err(ImProofError::MissingCoveredComponents);
    }
    let created = options.created.unwrap_or_else(|| Utc::now().timestamp());
    let nonce = options
        .nonce
        .unwrap_or_else(|| crate::keys::base64url_encode(&rand::random::<[u8; 16]>()));
    let quoted_components = options
        .components
        .iter()
        .map(|component| format!("\"{component}\""))
        .collect::<Vec<_>>()
        .join(" ");
    let mut params = vec![format!("created={created}")];
    if let Some(expires) = options.expires {
        params.push(format!("expires={expires}"));
    }
    params.push(format!("nonce=\"{nonce}\""));
    params.push(format!("keyid=\"{keyid}\""));
    Ok(format!(
        "{}=({quoted_components});{}",
        options.label,
        params.join(";")
    ))
}

pub fn parse_im_signature_input(
    signature_input: &str,
) -> Result<ParsedImSignatureInput, ImProofError> {
    let (label, remainder) = signature_input
        .split_once('=')
        .ok_or(ImProofError::InvalidSignatureInput)?;
    let remainder = remainder.trim();
    let open = remainder.find('(').ok_or(ImProofError::InvalidSignatureInput)?;
    let close = remainder[open..]
        .find(')')
        .map(|index| open + index)
        .ok_or(ImProofError::InvalidSignatureInput)?;
    let components = remainder[open + 1..close]
        .split_whitespace()
        .map(|component| component.trim_matches('"').to_owned())
        .filter(|component| !component.is_empty())
        .collect::<Vec<_>>();
    if components.is_empty() {
        return Err(ImProofError::MissingCoveredComponents);
    }

    let params_raw = remainder[close + 1..].trim_start_matches(';');
    let mut params = BTreeMap::new();
    for raw in params_raw.split(';') {
        let raw = raw.trim();
        if raw.is_empty() {
            continue;
        }
        let (name, value) = raw
            .split_once('=')
            .ok_or(ImProofError::InvalidSignatureInput)?;
        params.insert(name.trim().to_owned(), value.trim().trim_matches('"').to_owned());
    }
    let keyid = params
        .get("keyid")
        .cloned()
        .ok_or(ImProofError::MissingKeyId)?;

    Ok(ParsedImSignatureInput {
        label: label.trim().to_owned(),
        components,
        signature_params: remainder.to_owned(),
        keyid,
        nonce: params.get("nonce").cloned(),
        created: params.get("created").and_then(|value| value.parse::<i64>().ok()),
        expires: params.get("expires").and_then(|value| value.parse::<i64>().ok()),
    })
}

pub fn encode_im_signature(signature_bytes: &[u8], label: &str) -> String {
    format!("{label}=:{}:", STANDARD.encode(signature_bytes))
}

pub fn decode_im_signature(signature: &str) -> Result<(Option<String>, Vec<u8>), ImProofError> {
    let trimmed = signature.trim();
    let (label, encoded) = if let Some((label, value)) = trimmed.split_once("=:") {
        let encoded = value.trim_end_matches(':').trim();
        (Some(label.to_owned()), encoded.to_owned())
    } else {
        (
            None,
            trimmed
                .trim_start_matches(':')
                .trim_end_matches(':')
                .trim()
                .to_owned(),
        )
    };
    STANDARD
        .decode(encoded.as_bytes())
        .or_else(|_| URL_SAFE_NO_PAD.decode(encoded.as_bytes()))
        .map(|signature_bytes| (label, signature_bytes))
        .map_err(|_| ImProofError::InvalidSignatureEncoding)
}

pub fn generate_im_proof(
    payload: &[u8],
    signature_base: &[u8],
    private_key: &PrivateKeyMaterial,
    keyid: &str,
    options: ImProofGenerationOptions,
) -> Result<ImProof, ImProofError> {
    let signature_input = build_im_signature_input(keyid, options.clone())?;
    let signature_bytes = private_key
        .sign_message(signature_base)
        .map_err(|_| ImProofError::SigningError)?;
    Ok(ImProof {
        content_digest: build_im_content_digest(payload),
        signature_input,
        signature: encode_im_signature(&signature_bytes, &options.label),
    })
}

pub fn verify_im_proof_with_document(
    proof: &ImProof,
    payload: &[u8],
    signature_base: &[u8],
    did_document: &Value,
    expected_signer_did: Option<&str>,
) -> Result<ImProofVerificationResult, ImProofError> {
    let parsed = parse_im_signature_input(&proof.signature_input)?;
    if let Some(expected_signer_did) = expected_signer_did {
        if !parsed.keyid.starts_with(expected_signer_did) {
            return Err(ImProofError::InvalidSignerDid);
        }
    }
    let verification_method = find_verification_method(did_document, &parsed.keyid)
        .ok_or(ImProofError::VerificationMethodNotFound)?;
    verify_im_proof_with_public_key(
        proof,
        payload,
        signature_base,
        &verification_method,
        expected_signer_did,
    )
}

pub fn verify_im_proof_with_public_key(
    proof: &ImProof,
    payload: &[u8],
    signature_base: &[u8],
    verification_method: &Value,
    expected_signer_did: Option<&str>,
) -> Result<ImProofVerificationResult, ImProofError> {
    let parsed = parse_im_signature_input(&proof.signature_input)?;
    if let Some(expected_signer_did) = expected_signer_did {
        if !parsed.keyid.starts_with(expected_signer_did) {
            return Err(ImProofError::InvalidSignerDid);
        }
    }
    if !verify_im_content_digest(payload, &proof.content_digest) {
        return Err(ImProofError::InvalidContentDigest);
    }
    let (_label, signature_bytes) = decode_im_signature(&proof.signature)?;
    let public_key = crate::authentication::extract_public_key(verification_method)
        .map_err(|_| ImProofError::VerificationMethodNotFound)?;
    verify_im_signature_bytes(&public_key, signature_base, &signature_bytes)?;
    Ok(ImProofVerificationResult {
        parsed_signature_input: parsed,
        verification_method: verification_method.clone(),
    })
}

fn verify_im_signature_bytes(
    public_key: &PublicKeyMaterial,
    signature_base: &[u8],
    signature_bytes: &[u8],
) -> Result<(), ImProofError> {
    public_key
        .verify_message(signature_base, signature_bytes)
        .map_err(|_| ImProofError::VerificationFailed)
}

#[cfg(test)]
mod tests {
    use super::{
        build_im_content_digest, build_im_signature_input, decode_im_signature,
        generate_im_proof, parse_im_signature_input, verify_im_proof_with_document,
        ImProofGenerationOptions,
    };
    use crate::authentication::{create_did_wba_document, DidDocumentOptions, DidProfile};
    use crate::PrivateKeyMaterial;

    fn business_signature_base(
        method: &str,
        target_uri: &str,
        content_digest: &str,
        signature_input: &str,
    ) -> Vec<u8> {
        let parsed = parse_im_signature_input(signature_input).expect("signature input should parse");
        let lines = parsed
            .components
            .iter()
            .map(|component| match component.as_str() {
                "@method" => format!("\"{component}\": {method}"),
                "@target-uri" => format!("\"{component}\": {target_uri}"),
                "content-digest" => format!("\"{component}\": {content_digest}"),
                other => panic!("unexpected component: {other}"),
            })
            .chain(std::iter::once(format!(
                "\"@signature-params\": {}",
                parsed.signature_params
            )))
            .collect::<Vec<_>>();
        lines.join("\n").into_bytes()
    }

    #[test]
    fn generates_and_verifies_e1_im_proof() {
        let bundle = create_did_wba_document(
            "example.com",
            DidDocumentOptions {
                path_segments: vec!["user".to_owned(), "alice".to_owned()],
                did_profile: DidProfile::E1,
                ..DidDocumentOptions::default()
            },
        )
        .expect("bundle should be created");
        let private_key = PrivateKeyMaterial::from_pem(&bundle.keys["key-1"].private_key_pem)
            .expect("private key should load");
        let payload = br#"{"text":"hello"}"#;
        let signature_input = build_im_signature_input(
            &format!("{}#key-1", bundle.did().expect("did should exist")),
            ImProofGenerationOptions {
                created: Some(1_712_000_000),
                nonce: Some("nonce-1".to_owned()),
                ..ImProofGenerationOptions::default()
            },
        )
        .expect("signature input should build");
        let signature_base = business_signature_base(
            "direct.send",
            &format!(
                "anp://agent/{}",
                url::form_urlencoded::byte_serialize(
                    bundle.did().expect("did should exist").as_bytes()
                )
                .collect::<String>()
            ),
            &build_im_content_digest(payload),
            &signature_input,
        );
        let proof = generate_im_proof(
            payload,
            &signature_base,
            &private_key,
            &format!("{}#key-1", bundle.did().expect("did should exist")),
            ImProofGenerationOptions {
                created: Some(1_712_000_000),
                nonce: Some("nonce-1".to_owned()),
                ..ImProofGenerationOptions::default()
            },
        )
        .expect("proof should generate");
        let result = verify_im_proof_with_document(
            &proof,
            payload,
            &signature_base,
            &bundle.did_document,
            bundle.did(),
        )
        .expect("proof should verify");
        assert_eq!(result.parsed_signature_input.nonce.as_deref(), Some("nonce-1"));
    }

    #[test]
    fn rejects_tampered_payload() {
        let bundle = create_did_wba_document(
            "example.com",
            DidDocumentOptions {
                path_segments: vec!["user".to_owned(), "eve".to_owned()],
                ..DidDocumentOptions::default()
            },
        )
        .expect("bundle should be created");
        let private_key = PrivateKeyMaterial::from_pem(&bundle.keys["key-1"].private_key_pem)
            .expect("private key should load");
        let payload = br#"{"text":"hello"}"#;
        let proof = generate_im_proof(
            payload,
            &business_signature_base(
                "direct.send",
                &format!(
                    "anp://agent/{}",
                    url::form_urlencoded::byte_serialize(
                        bundle.did().expect("did should exist").as_bytes()
                    )
                    .collect::<String>()
                ),
                &build_im_content_digest(payload),
                &build_im_signature_input(
                    &format!("{}#key-1", bundle.did().expect("did should exist")),
                    ImProofGenerationOptions::default(),
                )
                .expect("signature input should build"),
            ),
            &private_key,
            &format!("{}#key-1", bundle.did().expect("did should exist")),
            ImProofGenerationOptions::default(),
        )
        .expect("proof should generate");
        let signature_base = business_signature_base(
            "direct.send",
            &format!(
                "anp://agent/{}",
                url::form_urlencoded::byte_serialize(
                    bundle.did().expect("did should exist").as_bytes()
                )
                .collect::<String>()
            ),
            &proof.content_digest,
            &proof.signature_input,
        );
        let error = verify_im_proof_with_document(
            &proof,
            br#"{"text":"tampered"}"#,
            &signature_base,
            &bundle.did_document,
            bundle.did(),
        )
        .expect_err("tampered payload should fail");
        assert!(matches!(error, super::ImProofError::InvalidContentDigest));
    }

    #[test]
    fn signature_round_trip() {
        let encoded = super::encode_im_signature(b"hello", "sig2");
        let (label, decoded) = decode_im_signature(&encoded).expect("signature should decode");
        assert_eq!(label.as_deref(), Some("sig2"));
        assert_eq!(decoded, b"hello");
    }
}