im-core 0.1.0

Rust IM SDK for Awiki clients built on 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
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;

pub(crate) struct ProviderBackedDidAuth {
    provider: Arc<dyn super::KeyMaterialProvider>,
    auth_mode: anp::authentication::AuthMode,
    tokens: HashMap<String, String>,
}

impl ProviderBackedDidAuth {
    pub(crate) fn new(
        provider: Arc<dyn super::KeyMaterialProvider>,
        auth_mode: anp::authentication::AuthMode,
    ) -> Self {
        Self {
            provider,
            auth_mode,
            tokens: HashMap::new(),
        }
    }

    pub(crate) fn get_auth_header(
        &mut self,
        server_url: &str,
        force_new: bool,
        method: &str,
        headers: Option<&BTreeMap<String, String>>,
        body: Option<&[u8]>,
    ) -> crate::ImResult<BTreeMap<String, String>> {
        let domain = extract_domain(server_url);
        if !force_new {
            if let Some(token) = self.tokens.get(&domain) {
                return Ok(BTreeMap::from([(
                    "Authorization".to_string(),
                    format!("Bearer {token}"),
                )]));
            }
        }

        let did_document = self.provider.did_document()?;
        let private_key = self.default_signing_key()?;
        match self.auth_mode {
            anp::authentication::AuthMode::HttpSignatures | anp::authentication::AuthMode::Auto => {
                anp::authentication::generate_http_signature_headers(
                    &did_document,
                    server_url,
                    method,
                    &private_key,
                    headers,
                    body,
                    anp::authentication::HttpSignatureOptions::default(),
                )
                .map_err(|err| crate::ImError::TransportUnavailable {
                    detail: format!("DID-WBA HTTP signature generation failed: {err}"),
                })
            }
            anp::authentication::AuthMode::LegacyDidWba => {
                let value = anp::authentication::generate_auth_header(
                    &did_document,
                    &domain,
                    &private_key,
                    "1.1",
                )
                .map_err(|err| crate::ImError::TransportUnavailable {
                    detail: format!("DID-WBA legacy auth generation failed: {err}"),
                })?;
                Ok(BTreeMap::from([("Authorization".to_string(), value)]))
            }
        }
    }

    pub(crate) fn update_token(
        &mut self,
        server_url: &str,
        headers: &BTreeMap<String, String>,
    ) -> Option<String> {
        let domain = extract_domain(server_url);
        if let Some(value) = get_header_case_insensitive(headers, "Authentication-Info") {
            let parsed = parse_header_params(value);
            if let Some(token) = parsed.get("access_token").filter(|token| !token.is_empty()) {
                self.tokens.insert(domain, token.clone());
                return Some(token.clone());
            }
        }
        if let Some(value) = get_header_case_insensitive(headers, "Authorization") {
            if let Some(token) = value.strip_prefix("Bearer ") {
                let token = token.to_string();
                self.tokens.insert(domain, token.clone());
                return Some(token);
            }
        }
        None
    }

    pub(crate) fn clear_token(&mut self, server_url: &str) {
        let domain = extract_domain(server_url);
        self.tokens.remove(&domain);
    }

    pub(crate) fn should_retry_after_401(
        &self,
        response_headers: &BTreeMap<String, String>,
    ) -> bool {
        let Some(www_authenticate) =
            get_header_case_insensitive(response_headers, "WWW-Authenticate")
        else {
            return false;
        };
        let challenge = parse_www_authenticate(www_authenticate);
        if challenge.get("nonce").is_some() {
            return true;
        }
        !matches!(
            challenge.get("error").map(|value| value.as_str()),
            Some("invalid_did") | Some("invalid_verification_method") | Some("forbidden_did")
        )
    }

    pub(crate) fn get_challenge_auth_header(
        &mut self,
        server_url: &str,
        response_headers: &BTreeMap<String, String>,
        method: &str,
        headers: Option<&BTreeMap<String, String>>,
        body: Option<&[u8]>,
    ) -> crate::ImResult<BTreeMap<String, String>> {
        let www_authenticate = get_header_case_insensitive(response_headers, "WWW-Authenticate");
        let accept_signature = get_header_case_insensitive(response_headers, "Accept-Signature");
        let challenge = www_authenticate
            .map(|value| parse_www_authenticate(value))
            .unwrap_or_default();
        let covered_components = normalize_covered_components(
            accept_signature
                .map(|value| parse_accept_signature(value))
                .as_ref(),
            headers,
            body,
        );
        let nonce = challenge.get("nonce").cloned();

        let did_document = self.provider.did_document()?;
        let private_key = self.default_signing_key()?;
        match self.auth_mode {
            anp::authentication::AuthMode::HttpSignatures | anp::authentication::AuthMode::Auto => {
                anp::authentication::generate_http_signature_headers(
                    &did_document,
                    server_url,
                    method,
                    &private_key,
                    headers,
                    body,
                    anp::authentication::HttpSignatureOptions {
                        nonce,
                        covered_components,
                        ..anp::authentication::HttpSignatureOptions::default()
                    },
                )
                .map_err(|err| crate::ImError::TransportUnavailable {
                    detail: format!("DID-WBA challenge signature generation failed: {err}"),
                })
            }
            anp::authentication::AuthMode::LegacyDidWba => {
                let value = anp::authentication::generate_auth_header(
                    &did_document,
                    &extract_domain(server_url),
                    &private_key,
                    "1.1",
                )
                .map_err(|err| crate::ImError::TransportUnavailable {
                    detail: format!("DID-WBA challenge legacy auth generation failed: {err}"),
                })?;
                Ok(BTreeMap::from([("Authorization".to_string(), value)]))
            }
        }
    }

    fn default_signing_key(&self) -> crate::ImResult<anp::PrivateKeyMaterial> {
        let pem = self.provider.default_signing_private_pem()?;
        anp::PrivateKeyMaterial::from_pem(&pem).map_err(|err| {
            crate::ImError::TransportUnavailable {
                detail: format!("DID-WBA private key material is invalid: {err}"),
            }
        })
    }
}

fn extract_domain(server_url: &str) -> String {
    server_url
        .split_once("://")
        .map(|(_, rest)| rest)
        .and_then(|rest| rest.split(['/', '?', '#']).next())
        .and_then(|authority| {
            authority
                .rsplit_once('@')
                .map(|(_, host)| host)
                .or(Some(authority))
        })
        .map(|authority| {
            if let Some(stripped) = authority.strip_prefix('[') {
                stripped
                    .split_once(']')
                    .map(|(host, _)| host.to_string())
                    .unwrap_or_else(|| authority.to_string())
            } else {
                authority
                    .split_once(':')
                    .map(|(host, _)| host.to_string())
                    .unwrap_or_else(|| authority.to_string())
            }
        })
        .filter(|host| !host.is_empty())
        .unwrap_or_else(|| server_url.to_string())
}

fn get_header_case_insensitive<'a>(
    headers: &'a BTreeMap<String, String>,
    name: &str,
) -> Option<&'a String> {
    headers
        .iter()
        .find(|(key, _)| key.eq_ignore_ascii_case(name))
        .map(|(_, value)| value)
}

fn parse_header_params(value: &str) -> HashMap<String, String> {
    value
        .split(',')
        .filter_map(|item| item.trim().split_once('='))
        .map(|(key, raw)| {
            (
                key.trim().to_string(),
                raw.trim().trim_matches('"').to_string(),
            )
        })
        .collect()
}

fn parse_www_authenticate(value: &str) -> HashMap<String, String> {
    let normalized = value
        .trim()
        .strip_prefix("DIDWba ")
        .or_else(|| value.trim().strip_prefix("didwba "))
        .unwrap_or(value.trim());
    parse_header_params(normalized)
}

fn parse_accept_signature(value: &str) -> Vec<String> {
    let mut result = Vec::new();
    let mut remaining = value;
    while let Some((_, after_open)) = remaining.split_once('"') {
        let Some((component, after_close)) = after_open.split_once('"') else {
            break;
        };
        if !component.trim().is_empty() {
            result.push(component.to_string());
        }
        remaining = after_close;
    }
    result
}

fn normalize_covered_components(
    covered_components: Option<&Vec<String>>,
    headers: Option<&BTreeMap<String, String>>,
    body: Option<&[u8]>,
) -> Option<Vec<String>> {
    let covered_components = covered_components?;
    let body_present = body.map(|bytes| !bytes.is_empty()).unwrap_or(false);
    let normalized_headers = headers
        .cloned()
        .unwrap_or_default()
        .into_iter()
        .filter_map(|(key, value)| (!value.is_empty()).then(|| (key.to_ascii_lowercase(), value)))
        .collect::<BTreeMap<_, _>>();

    let mut result = Vec::new();
    for component in covered_components {
        let lower = component.to_ascii_lowercase();
        if lower == "content-digest" && !body_present {
            continue;
        }
        if lower == "content-length"
            && !body_present
            && !normalized_headers.contains_key("content-length")
        {
            continue;
        }
        if lower == "content-type" && !normalized_headers.contains_key("content-type") {
            continue;
        }
        if !lower.starts_with('@')
            && lower != "content-length"
            && lower != "content-digest"
            && !normalized_headers.contains_key(&lower)
        {
            continue;
        }
        result.push(component.clone());
    }
    (!result.is_empty()).then_some(result)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::internal::key_provider::FileBackedKeyMaterialProvider;

    #[test]
    fn provider_did_auth_generates_http_signature_headers() {
        let bundle = anp::authentication::create_did_wba_document(
            "example.com",
            anp::authentication::DidDocumentOptions::default(),
        )
        .expect("DID creation should succeed");
        let root = tempfile::tempdir().unwrap();
        let identity_dir = root.path().join("identity");
        std::fs::create_dir_all(&identity_dir).unwrap();
        std::fs::write(
            identity_dir.join("did.json"),
            serde_json::to_vec(&bundle.did_document).unwrap(),
        )
        .unwrap();
        std::fs::write(
            identity_dir.join("private.key"),
            &bundle.keys["key-1"].private_key_pem,
        )
        .unwrap();

        let provider = Arc::new(FileBackedKeyMaterialProvider::new(identity_dir));
        let mut auth =
            ProviderBackedDidAuth::new(provider, anp::authentication::AuthMode::HttpSignatures);
        let headers = auth
            .get_auth_header("https://api.example.com/orders", false, "GET", None, None)
            .expect("headers should generate");

        assert!(headers.contains_key("Signature-Input"));
        assert!(headers.contains_key("Signature"));
    }

    #[test]
    fn provider_did_auth_challenge_uses_http_signature_nonce() {
        let bundle = anp::authentication::create_did_wba_document(
            "example.com",
            anp::authentication::DidDocumentOptions::default(),
        )
        .expect("DID creation should succeed");
        let root = tempfile::tempdir().unwrap();
        let identity_dir = root.path().join("identity");
        std::fs::create_dir_all(&identity_dir).unwrap();
        std::fs::write(
            identity_dir.join("did.json"),
            serde_json::to_vec(&bundle.did_document).unwrap(),
        )
        .unwrap();
        std::fs::write(
            identity_dir.join("private.key"),
            &bundle.keys["key-1"].private_key_pem,
        )
        .unwrap();

        let provider = Arc::new(FileBackedKeyMaterialProvider::new(identity_dir));
        let mut auth =
            ProviderBackedDidAuth::new(provider, anp::authentication::AuthMode::HttpSignatures);
        let request_headers =
            BTreeMap::from([("Content-Type".to_string(), "application/json".to_string())]);
        let challenge_headers = BTreeMap::from([(
            "WWW-Authenticate".to_string(),
            r#"DIDWba nonce="server-nonce-42""#.to_string(),
        )]);
        let signed_headers = auth
            .get_challenge_auth_header(
                "https://api.example.com/orders",
                &challenge_headers,
                "POST",
                Some(&request_headers),
                Some(br#"{"ok":true}"#),
            )
            .expect("challenge signature should generate");

        let metadata = anp::authentication::extract_signature_metadata(&signed_headers)
            .expect("signature metadata should parse");
        assert_eq!(metadata.nonce.as_deref(), Some("server-nonce-42"));
    }

    #[test]
    fn provider_did_auth_reuses_cached_bearer_token_without_reading_key() {
        let root = tempfile::tempdir().unwrap();
        let identity_dir = root.path().join("identity");
        std::fs::create_dir_all(&identity_dir).unwrap();

        let provider = Arc::new(FileBackedKeyMaterialProvider::new(identity_dir));
        let mut auth =
            ProviderBackedDidAuth::new(provider, anp::authentication::AuthMode::HttpSignatures);
        auth.update_token(
            "https://api.example.com/orders",
            &BTreeMap::from([(
                "Authentication-Info".to_string(),
                r#"access_token="cached-token""#.to_string(),
            )]),
        );

        let headers = auth
            .get_auth_header("https://api.example.com/orders", false, "GET", None, None)
            .expect("cached token should be used before key material is read");

        assert_eq!(
            headers.get("Authorization").map(String::as_str),
            Some("Bearer cached-token")
        );
    }
}