c2pa 0.85.2

Rust SDK for C2PA (Coalition for Content Provenance and Authenticity) implementors
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
// Loosely derived from
// https://github.com/spruceid/ssi/blob/ssi/v0.9.0/crates/dids/methods/web/src/lib.rs
// which was published under an Apache 2.0 license.

// Subsequent modifications are subject to license from Adobe
// as follows:

// Copyright 2024 Adobe. All rights reserved.
// This file is licensed to you under the Apache License,
// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
// or the MIT license (http://opensource.org/licenses/MIT),
// at your option.

// Unless required by applicable law or agreed to in writing,
// this software is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
// specific language governing permissions and limitations under
// each license.

use std::io::Read;

use super::{did::Did, did_doc::DidDocument};
use crate::http::{
    AsyncGenericResolver, AsyncHttpResolver, HttpResolverError, SyncGenericResolver,
    SyncHttpResolver,
};

/// Maximum number of bytes accepted from a DID Web server response body.
pub(crate) const MAX_DID_DOC_SIZE: u64 = 1024 * 1024; // 1 MiB

const USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"));

#[cfg(test)]
use std::{cell::RefCell, collections::HashMap};

#[cfg(test)]
thread_local! {
    /// Maps a `did:web` domain name to a URL prefix (ending in `/`) that should
    /// be used in place of the real `https://{domain}/` origin. Tests register
    /// entries here to redirect DID document resolution to a local mock server,
    /// keeping the suite hermetic.
    pub(crate) static PROXIES: RefCell<HashMap<String, String>> = RefCell::new(HashMap::new());
}

/// Redirect `did:web` resolution for `domain` to `url_prefix` (a base URL
/// ending in `/`, such as a mock server origin) for the current thread.
#[cfg(test)]
pub(crate) fn set_proxy(domain: &str, url_prefix: &str) {
    PROXIES.with(|proxies| {
        proxies
            .borrow_mut()
            .insert(domain.to_string(), url_prefix.to_string());
    });
}

/// Remove all `did:web` resolution redirects for the current thread.
#[cfg(test)]
pub(crate) fn clear_proxies() {
    PROXIES.with(|proxies| proxies.borrow_mut().clear());
}

use http::header;

#[derive(Debug, thiserror::Error)]
pub enum DidWebError {
    #[error("error building HTTP client: {0}")]
    Client(HttpResolverError),

    #[error("error sending HTTP request ({0}): {1}")]
    Request(String, HttpResolverError),

    #[error("server error: {0}")]
    Server(String),

    #[error("error reading HTTP response: {0}")]
    Response(HttpResolverError),

    #[error("the document was not found: {0}")]
    NotFound(String),

    #[error("the document was not a valid DID document: {0}")]
    InvalidData(String),

    #[error("invalid web DID: {0}")]
    InvalidWebDid(String),

    #[error("response body exceeded size limit of {MAX_DID_DOC_SIZE} bytes")]
    ResponseTooLarge,
}

fn prepare_url(did: &Did<'_>) -> Result<String, DidWebError> {
    let method = did.method_name();
    #[allow(clippy::panic)] // TEMPORARY while refactoring
    if method != "web" {
        panic!("Unexpected DID method {method}");
    }
    to_url(did.method_specific_id())
}

fn parse_did_doc(bytes: Vec<u8>, url: &str) -> Result<DidDocument, DidWebError> {
    let json = String::from_utf8(bytes).map_err(|_| DidWebError::InvalidData(url.to_owned()))?;
    DidDocument::from_json(&json).map_err(|_| DidWebError::InvalidData(url.to_owned()))
}

pub(crate) async fn resolve_async(did: &Did<'_>) -> Result<DidDocument, DidWebError> {
    let url = prepare_url(did)?;
    // TODO: https://w3c-ccg.github.io/did-method-web/#in-transit-security
    let bytes = get_did_doc(&url).await?;
    parse_did_doc(bytes, &url)
}

fn build_request(url: &str) -> Result<http::Request<Vec<u8>>, DidWebError> {
    http::Request::get(url)
        .header(header::USER_AGENT, USER_AGENT)
        .header(header::ACCEPT, "application/did+json")
        .body(Vec::new())
        .map_err(|e| DidWebError::Request(url.to_owned(), e.into()))
}

fn check_response_status(status: http::StatusCode, url: &str) -> Result<(), DidWebError> {
    match status {
        http::StatusCode::OK => Ok(()),
        http::StatusCode::NOT_FOUND => Err(DidWebError::NotFound(url.to_string())),
        _ => Err(DidWebError::Server(status.to_string())),
    }
}

fn read_body_with_limit(body: Box<dyn Read>, url: &str) -> Result<Vec<u8>, DidWebError> {
    let mut document = Vec::new();
    body.take(MAX_DID_DOC_SIZE + 1)
        .read_to_end(&mut document)
        .map_err(|e| DidWebError::Response(e.into()))?;
    if document.len() as u64 > MAX_DID_DOC_SIZE {
        return Err(DidWebError::ResponseTooLarge);
    }
    Ok(document)
}

async fn get_did_doc(url: &str) -> Result<Vec<u8>, DidWebError> {
    let request = build_request(url)?;
    let response = AsyncGenericResolver::with_redirects()
        .unwrap_or_default()
        .with_max_response_body_size(MAX_DID_DOC_SIZE)
        .http_resolve_async(request)
        .await
        .map_err(|e| match e {
            HttpResolverError::ResponseTooLarge => DidWebError::ResponseTooLarge,
            e => DidWebError::Request(url.to_owned(), e),
        })?;
    let (parts, body) = response.into_parts();
    check_response_status(parts.status, url)?;
    read_body_with_limit(body, url)
}

pub(crate) fn resolve(did: &Did<'_>) -> Result<DidDocument, DidWebError> {
    let url = prepare_url(did)?;
    // TODO: https://w3c-ccg.github.io/did-method-web/#in-transit-security
    let bytes = get_did_doc_sync(&url)?;
    parse_did_doc(bytes, &url)
}

fn get_did_doc_sync(url: &str) -> Result<Vec<u8>, DidWebError> {
    let request = build_request(url)?;
    let response = SyncGenericResolver::with_redirects()
        .unwrap_or_default()
        .http_resolve(request)
        .map_err(|e| match e {
            HttpResolverError::ResponseTooLarge => DidWebError::ResponseTooLarge,
            e => DidWebError::Request(url.to_owned(), e),
        })?;
    let (parts, body) = response.into_parts();
    check_response_status(parts.status, url)?;
    read_body_with_limit(body, url)
}

pub(crate) fn to_url(did: &str) -> Result<String, DidWebError> {
    let mut parts = did.split(':').peekable();
    let domain_name = parts
        .next()
        .ok_or_else(|| DidWebError::InvalidWebDid(did.to_owned()))?;

    // TODO:
    // - Validate domain name: alphanumeric, hyphen, dot. no IP address.
    // - Ensure domain name matches TLS certificate common name
    // - Support punycode?
    // - Support query strings?
    let path = match parts.peek() {
        Some(_) => parts.collect::<Vec<&str>>().join("/"),
        None => ".well-known".to_string(),
    };

    // Use http for localhost, for testing purposes.
    let proto = if domain_name.starts_with("localhost") {
        "http"
    } else {
        "https"
    };

    #[allow(unused_mut)]
    let mut url = format!(
        "{proto}://{}/{path}/did.json",
        domain_name.replacen("%3A", ":", 1)
    );

    #[cfg(test)]
    PROXIES.with(|proxies| {
        if let Some(prefix) = proxies.borrow().get(domain_name) {
            url = format!("{prefix}{path}/did.json");
        }
    });

    Ok(url)
}

#[cfg(test)]
mod tests {
    #![allow(clippy::panic)]
    #![allow(clippy::unwrap_used)]

    #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
    use wasm_bindgen_test::wasm_bindgen_test;

    use crate::identity::claim_aggregation::w3c_vc::{did::Did, did_web};

    #[test]
    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test
    )]
    fn to_url() {
        // https://w3c-ccg.github.io/did-method-web/#example-3-creating-the-did
        assert_eq!(
            did_web::to_url(did("did:web:w3c-ccg.github.io").method_specific_id()).unwrap(),
            "https://w3c-ccg.github.io/.well-known/did.json"
        );
        // https://w3c-ccg.github.io/did-method-web/#example-4-creating-the-did-with-optional-path
        assert_eq!(
            did_web::to_url(did("did:web:w3c-ccg.github.io:user:alice").method_specific_id())
                .unwrap(),
            "https://w3c-ccg.github.io/user/alice/did.json"
        );
        // https://w3c-ccg.github.io/did-method-web/#optional-path-considerations
        assert_eq!(
            did_web::to_url(did("did:web:example.com:u:bob").method_specific_id()).unwrap(),
            "https://example.com/u/bob/did.json"
        );
        // https://w3c-ccg.github.io/did-method-web/#example-creating-the-did-with-optional-path-and-port
        assert_eq!(
            did_web::to_url(did("did:web:example.com%3A443:u:bob").method_specific_id()).unwrap(),
            "https://example.com:443/u/bob/did.json"
        );
    }

    #[cfg(not(target_arch = "wasm32"))]
    mod resolve {
        use httpmock::prelude::*;

        use super::did;
        use crate::identity::claim_aggregation::w3c_vc::{
            did_doc::DidDocument,
            did_web::{self, DidWebError, MAX_DID_DOC_SIZE},
        };

        #[tokio::test]
        // #[cfg_attr(all(target_arch = "wasm32", not(target_os = "wasi")),
        // wasm_bindgen_test)] Can't test this on WASM until we find an httpmock
        // replacement.
        async fn from_did_key() {
            const DID_JSON: &str = r#"{
            "@context": "https://www.w3.org/ns/did/v1",
            "id": "did:web:localhost",
            "verificationMethod": [{
                "id": "did:web:localhost#key1",
                "type": "Ed25519VerificationKey2018",
                "controller": "did:web:localhost",
                "publicKeyBase58": "2sXRz2VfrpySNEL6xmXJWQg6iY94qwNp1qrJJFBuPWmH"
            }],
            "assertionMethod": ["did:web:localhost#key1"]
        }"#;

            let server = MockServer::start();

            let server_url = server.url("/").replace("127.0.0.1", "localhost");
            did_web::set_proxy("localhost", &server_url);

            let did_doc_mock = server.mock(|when, then| {
                when.method(GET).path("/.well-known/did.json");
                then.status(200)
                    .header("content-type", "application/json")
                    .body(DID_JSON);
            });

            let doc = did_web::resolve_async(&did("did:web:localhost"))
                .await
                .unwrap();
            let doc_expected = DidDocument::from_json(DID_JSON).unwrap();
            assert_eq!(doc, doc_expected);

            did_web::clear_proxies();

            did_doc_mock.assert();
        }

        #[tokio::test]
        async fn content_length_above_limit_rejected() {
            let server = MockServer::start();

            let server_url = server.url("/").replace("127.0.0.1", "localhost");
            did_web::set_proxy("localhost", &server_url);

            // Server explicitly advertises Content-Length above the limit.
            // The Content-Length pre-check in AsyncGenericResolver rejects the
            // response immediately, before passing any body bytes to the caller.
            let oversized_body = vec![b'X'; (MAX_DID_DOC_SIZE + 1) as usize];
            let _mock = server.mock(|when, then| {
                when.method(GET).path("/.well-known/did.json");
                then.status(200)
                    .header("content-type", "application/did+json")
                    .header("content-length", (MAX_DID_DOC_SIZE + 1).to_string())
                    .body(oversized_body);
            });

            let result = did_web::resolve_async(&did("did:web:localhost")).await;

            did_web::clear_proxies();

            assert!(
                matches!(result, Err(did_web::DidWebError::ResponseTooLarge)),
                "expected ResponseTooLarge, got {result:?}"
            );
        }

        #[tokio::test]
        async fn oversized_response_returns_error() {
            let server = MockServer::start();

            let server_url = server.url("/").replace("127.0.0.1", "localhost");
            did_web::set_proxy("localhost", &server_url);

            // Serve a body one byte larger than the allowed limit.
            let oversized_body = vec![b'X'; (MAX_DID_DOC_SIZE + 1) as usize];
            let _mock = server.mock(|when, then| {
                when.method(GET).path("/.well-known/did.json");
                then.status(200)
                    .header("content-type", "application/did+json")
                    .body(oversized_body);
            });

            let result = did_web::resolve_async(&did("did:web:localhost")).await;

            did_web::clear_proxies();

            assert!(
                matches!(result, Err(did_web::DidWebError::ResponseTooLarge)),
                "expected ResponseTooLarge, got {result:?}"
            );
        }

        /*
            #[tokio::test]
        #[cfg_attr(all(target_arch = "wasm32", not(target_os = "wasi")), wasm_bindgen_test)]
            async fn credential_prove_verify_did_web() {
                let didweb = VerificationMethodDIDResolver::new(DIDWeb);
                let params = VerificationParameters::from_resolver(&didweb);

                let (url, shutdown) = web_server().unwrap();
                PROXY.with(|proxy| {
                    proxy.replace(Some(url));
                });

                let cred = JsonCredential::new(
                    None,
                    did!("did:web:localhost").to_owned().into_uri().into(),
                    "2021-01-26T16:57:27Z".parse().unwrap(),
                    vec![serde_json::json!({
                        "id": "did:web:localhost"
                    })],
                );

                let key: JWK = include_str!("../../../../../tests/ed25519-2020-10-18.json")
                    .parse()
                    .unwrap();
                let verification_method = iri!("did:web:localhost#key1").to_owned().into();
                let suite = AnySuite::pick(&key, Some(&verification_method)).unwrap();
                let issue_options = ProofOptions::new(
                    "2021-01-26T16:57:27Z".parse().unwrap(),
                    verification_method,
                    ProofPurpose::Assertion,
                    Default::default(),
                );
                let signer = SingleSecretSigner::new(key).into_local();
                let vc = suite
                    .sign(cred, &didweb, &signer, issue_options)
                    .await
                    .unwrap();

                println!(
                    "proof: {}",
                    serde_json::to_string_pretty(&vc.proofs).unwrap()
                );
                assert_eq!(vc.proofs.first().unwrap().signature.as_ref(), "eyJhbGciOiJFZERTQSIsImNyaXQiOlsiYjY0Il0sImI2NCI6ZmFsc2V9..BCvVb4jz-yVaTeoP24Wz0cOtiHKXCdPcmFQD_pxgsMU6aCAj1AIu3cqHyoViU93nPmzqMLswOAqZUlMyVnmzDw");
                assert!(vc.verify(&params).await.unwrap().is_ok());

                // test that issuer property is used for verification
                let mut vc_bad_issuer = vc.clone();
                vc_bad_issuer.issuer = uri!("did:pkh:example:bad").to_owned().into();
                // It should fail.
                assert!(vc_bad_issuer.verify(params).await.unwrap().is_err());

                PROXY.with(|proxy| {
                    proxy.replace(None);
                });
                shutdown().ok();
            }
            */
    }

    fn did(s: &'static str) -> Did<'static> {
        Did::new(s).unwrap()
    }
}