aep-core 0.3.0

Transport-independent protocol primitives for the Agent Enrollment Protocol.
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
use std::sync::OnceLock;

use regex::Regex;
use url::Url;

use crate::{
    Authentication, Binding, Command, GrantType, InspectClaims, InspectDocument,
    MAX_AUTHENTICATION_METHODS, ParseError, SigningAlgorithm, VERSION, ValidationError,
    validation::{issue, parse_and_validate, require_unique, result},
};

pub fn parse_inspect_document(data: &[u8]) -> Result<InspectDocument, ParseError> {
    parse_and_validate(data, "Inspect document", validate_inspect_document)
}

pub fn validate_inspect_document(document: &InspectDocument) -> Result<(), ValidationError> {
    let mut issues = Vec::new();
    if let Some(documents) = &document.service_documents {
        if documents.is_empty()
            || !document.extensions.as_ref().is_some_and(|value| {
                value
                    .supported
                    .iter()
                    .any(|value| value == crate::SERVICE_DOCUMENTS_EXTENSION)
            })
        {
            issues.push(issue(
                "$.service_documents",
                "Expected nonempty documents and the Service Documents extension.",
            ));
        }
        crate::documents::validate_document_ids(
            &documents.iter().map(|d| d.id.clone()).collect::<Vec<_>>(),
            "$.service_documents",
            &mut issues,
        );
        for descriptor in documents {
            if let Err(error) = crate::validate_service_document(descriptor) {
                issues.extend(error.issues);
            }
        }
    }
    if !version_pattern().is_match(&document.aep_version) {
        issues.push(issue(
            "$.aep_version",
            "Expected major.minor version syntax.",
        ));
    } else if !is_version_compatible(&document.aep_version, VERSION) {
        issues.push(issue(
            "$.aep_version",
            format!("Unsupported AEP major version: {}.", document.aep_version),
        ));
    }
    validate_authentication(document.authentication.as_ref(), &mut issues);
    validate_advertisements(
        document.bindings.supported.iter().map(Binding::as_str),
        "$.bindings.supported",
        true,
        &mut issues,
    );
    if !document.bindings.supported.contains(&Binding::Http) {
        issues.push(issue(
            "$.bindings.supported",
            "Expected http to be advertised.",
        ));
    }
    validate_claims(document.claims.as_ref(), &mut issues);
    validate_advertisements(
        document.commands.supported.iter().map(Command::as_str),
        "$.commands.supported",
        true,
        &mut issues,
    );
    if !document.commands.supported.contains(&Command::Inspect) {
        issues.push(issue(
            "$.commands.supported",
            "Expected inspect to be advertised.",
        ));
    }
    if document
        .commands
        .supported
        .iter()
        .any(|command| command.as_str() == "authenticate")
    {
        issues.push(issue(
            "$.commands.supported",
            "authenticate is an assertion operation, not a command.",
        ));
    }
    validate_advertisements(
        document.commands.grant_types.iter().map(GrantType::as_str),
        "$.commands.grant_types",
        false,
        &mut issues,
    );
    for name in document.commands.grant_types_config.keys() {
        let path = format!("$.commands.grant_types_config.{name}");
        if !advertisement_pattern().is_match(name) {
            issues.push(issue(&path, "Expected a lowercase grant-type identifier."));
        }
        if !document
            .commands
            .grant_types
            .iter()
            .any(|grant_type| grant_type.as_str() == name)
        {
            issues.push(issue(
                &path,
                "Expected configuration for an advertised grant type.",
            ));
        }
    }
    let advertises_grant_or_revoke = document
        .commands
        .supported
        .iter()
        .any(|command| matches!(command, Command::Grant | Command::Revoke));
    if advertises_grant_or_revoke && document.commands.grant_types.is_empty() {
        issues.push(issue(
            "$.commands.grant_types",
            "Expected at least one grant type when Grant or Revoke is advertised.",
        ));
    }
    if document.core.signing_algorithms.is_empty() {
        issues.push(issue(
            "$.core.signing_algorithms",
            "Expected at least one signing algorithm.",
        ));
    }
    if !document
        .core
        .signing_algorithms
        .contains(&SigningAlgorithm::EdDsa)
    {
        issues.push(issue(
            "$.core.signing_algorithms",
            "Expected EdDSA to be advertised.",
        ));
    }
    if !document
        .core
        .signing_algorithms
        .contains(&SigningAlgorithm::Es256)
    {
        issues.push(issue(
            "$.core.signing_algorithms",
            "Expected ES256 to be advertised.",
        ));
    }
    if let Some(extensions) = &document.extensions {
        for (index, extension) in extensions.supported.iter().enumerate() {
            if Url::parse(extension).is_err() {
                issues.push(issue(
                    format!("$.extensions.supported[{index}]"),
                    "Expected an absolute URI.",
                ));
            }
        }
    }
    // CORE-HTTP-004 appends the command path to this value with one `/` separator, so a base
    // carrying a query, a fragment, or a dot segment would steer every command URL away from the
    // advertised base. The document is refused rather than left to fail at path construction.
    if let Some(endpoint_base) = &document.http.endpoint_base
        && crate::normalize_endpoint_base(Some(endpoint_base)).is_err()
    {
        issues.push(issue(
            "$.http.endpoint_base",
            "Expected an origin-relative absolute path.",
        ));
    }
    if let Some(openapi) = &document.http.openapi
        && (openapi.url.is_empty()
            || openapi.url.chars().any(char::is_whitespace)
            || Url::parse(&openapi.url).is_err() && !is_relative_reference(&openapi.url))
    {
        issues.push(issue("$.http.openapi.url", "Expected a URI reference."));
    }
    for (index, method) in document.identity.methods.iter().enumerate() {
        if !identity_pattern().is_match(method.as_str()) {
            issues.push(issue(
                format!("$.identity.methods[{index}]"),
                "Expected an identity-method identifier.",
            ));
        }
    }
    let authenticated = document.commands.supported.iter().any(|command| {
        matches!(
            command,
            Command::Enroll | Command::Grant | Command::Revoke | Command::Status
        )
    });
    if authenticated && document.identity.methods.is_empty() {
        issues.push(issue(
            "$.identity.methods",
            "Expected at least one identity method for authenticated commands.",
        ));
    }
    if !document.service.did.starts_with("did:") {
        issues.push(issue("$.service.did", "Expected a DID."));
    }
    result("Inspect document", issues)
}

pub fn is_version_compatible(received: &str, supported: &str) -> bool {
    if !version_pattern().is_match(received) || !version_pattern().is_match(supported) {
        return false;
    }
    received.split_once('.').map(|parts| parts.0) == supported.split_once('.').map(|parts| parts.0)
}

fn validate_authentication(
    authentication: Option<&Authentication>,
    issues: &mut Vec<crate::ValidationIssue>,
) {
    let Some(authentication) = authentication else {
        return;
    };
    if authentication.methods.is_empty() {
        issues.push(issue(
            "$.authentication.methods",
            "Expected at least one item.",
        ));
    }
    if authentication.methods.len() > MAX_AUTHENTICATION_METHODS {
        issues.push(issue(
            "$.authentication.methods",
            "Expected at most 16 items.",
        ));
    }
    validate_advertisements(
        authentication.methods.iter().map(|method| method.as_str()),
        "$.authentication.methods",
        false,
        issues,
    );
    require_unique(&authentication.methods, "$.authentication.methods", issues);
}

fn validate_claims(claims: Option<&InspectClaims>, issues: &mut Vec<crate::ValidationIssue>) {
    let Some(claims) = claims else {
        return;
    };
    for (group, values) in [
        ("required", &claims.required),
        ("preferred", &claims.preferred),
        ("optional", &claims.optional),
    ] {
        for (index, value) in values.iter().enumerate() {
            if !claim_name_pattern().is_match(value.as_str()) {
                issues.push(issue(
                    format!("$.claims.{group}[{index}]"),
                    "Expected a registered claim-name shape.",
                ));
            }
        }
    }
}

fn validate_advertisements<'a>(
    values: impl Iterator<Item = &'a str>,
    path: &str,
    require_item: bool,
    issues: &mut Vec<crate::ValidationIssue>,
) {
    let values = values.collect::<Vec<_>>();
    if require_item && values.is_empty() {
        issues.push(issue(path, "Expected at least one item."));
    }
    for (index, value) in values.into_iter().enumerate() {
        if !advertisement_pattern().is_match(value) {
            issues.push(issue(
                format!("{path}[{index}]"),
                "Expected a lowercase advertisement identifier.",
            ));
        }
    }
}

fn is_relative_reference(value: &str) -> bool {
    !value.is_empty() && !value.starts_with("//") && !value.contains('#')
}

fn version_pattern() -> &'static Regex {
    static PATTERN: OnceLock<Regex> = OnceLock::new();
    PATTERN.get_or_init(|| {
        Regex::new(r"^(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)$").expect("valid version pattern")
    })
}

fn advertisement_pattern() -> &'static Regex {
    static PATTERN: OnceLock<Regex> = OnceLock::new();
    PATTERN.get_or_init(|| {
        Regex::new(r"^[a-z0-9]+(?:-[a-z0-9]+)*$").expect("valid advertisement pattern")
    })
}

fn identity_pattern() -> &'static Regex {
    static PATTERN: OnceLock<Regex> = OnceLock::new();
    PATTERN.get_or_init(|| {
        Regex::new(r"^[a-z0-9]+(?::[a-z0-9]+)*(?:-[a-z0-9]+)*$")
            .expect("valid identity method pattern")
    })
}

fn claim_name_pattern() -> &'static Regex {
    static PATTERN: OnceLock<Regex> = OnceLock::new();
    PATTERN.get_or_init(|| {
        Regex::new(r"^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*$").expect("valid claim name pattern")
    })
}

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

    fn valid_document() -> InspectDocument {
        parse_inspect_document(
            br#"{
                "aep_version":"1.0",
                "bindings":{"supported":["http"]},
                "commands":{"supported":["inspect","enroll"]},
                "core":{"signing_algorithms":["EdDSA","ES256"]},
                "http":{},
                "identity":{"methods":["did:web"]},
                "service":{"did":"did:web:service.example"}
            }"#,
        )
        .expect("valid Inspect document")
    }

    #[test]
    fn accepts_unknown_well_formed_advertisements() {
        let document = parse_inspect_document(
            br#"{
                "aep_version":"1.1",
                "bindings":{"supported":["http","future-binding"]},
                "commands":{"supported":["inspect","future-command"]},
                "core":{"signing_algorithms":["EdDSA","ES256","future"]},
                "http":{},
                "identity":{"methods":[]},
                "service":{"did":"did:web:service.example"}
            }"#,
        )
        .expect("same-major additive document");
        assert_eq!(document.commands.supported[1].as_str(), "future-command");
    }

    #[test]
    fn rejects_an_incompatible_major_version() {
        let error = parse_inspect_document(
            br#"{"aep_version":"2.0","bindings":{"supported":["http"]},"commands":{"supported":["inspect"]},"core":{"signing_algorithms":["EdDSA","ES256"]},"http":{},"identity":{"methods":[]},"service":{"did":"did:web:service.example"}}"#,
        )
        .expect_err("major version must fail");
        assert!(matches!(error, ParseError::Validation(_)));
    }

    #[test]
    fn rejects_invalid_required_advertisements() {
        let mut document = valid_document();
        document.bindings.supported.clear();
        assert!(validate_inspect_document(&document).is_err());

        let mut document = valid_document();
        document.commands.supported = vec![Command::Enroll];
        document.commands.grant_types.clear();
        assert!(validate_inspect_document(&document).is_err());

        let mut document = valid_document();
        document.core.signing_algorithms = vec![SigningAlgorithm::EdDsa];
        assert!(validate_inspect_document(&document).is_err());

        let mut document = valid_document();
        document.identity.methods.clear();
        assert!(validate_inspect_document(&document).is_err());

        let mut document = valid_document();
        document
            .commands
            .supported
            .push(Command::Other("authenticate".to_owned()));
        assert!(validate_inspect_document(&document).is_err());
    }

    #[test]
    fn rejects_invalid_optional_advertisements() {
        let mut document = valid_document();
        document.authentication = Some(Authentication { methods: vec![] });
        assert!(validate_inspect_document(&document).is_err());

        let mut document = valid_document();
        document.http.endpoint_base = Some("//wrong".to_owned());
        assert!(validate_inspect_document(&document).is_err());

        let mut document = valid_document();
        document.extensions = Some(crate::Extensions {
            supported: vec!["relative".to_owned()],
            additional: Default::default(),
        });
        assert!(validate_inspect_document(&document).is_err());

        let mut document = valid_document();
        document.service.did = "not-a-did".to_owned();
        assert!(validate_inspect_document(&document).is_err());
    }

    #[test]
    fn compares_only_compatible_major_versions() {
        assert!(is_version_compatible("1.9", "1.0"));
        assert!(!is_version_compatible("2.0", "1.0"));
        assert!(!is_version_compatible("invalid", "1.0"));
    }
}