Skip to main content

rustflexstack/security/pki_client/
authorization.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2024 Fundació Privada Internet i Innovació Digital a Catalunya (i2CAT)
3
4//! Authorization of an enrolled ITS-S with an AA (ETSI TS 102 941 V2.2.1
5//! clause 6.2.3.3): request an Authorization Ticket (AT). The message
6//! construction is in [`super::messages`]; this module sends the request and
7//! checks the response.
8
9use std::fmt;
10
11use crate::security::certificate::{Certificate, OwnCertificate};
12use crate::security::ecdsa_backend::{EcdsaBackend, KeyAlgorithm};
13use crate::security::pki_asn::etsi_ts102941_base_types::CertificateSubjectAttributes;
14use crate::security::pki_asn::etsi_ts102941_types_authorization::AuthorizationResponseCode;
15use crate::security::pki_client::messages::{self, PkiProtocolError, CT_REQUEST};
16use crate::security::pki_client::transport::{
17    post_with_retry, PkiTransport, PkiTransportError, Retry,
18};
19
20/// The authorization failed: `code` is the AuthorizationResponseCode returned
21/// by the AA (e.g. `its-aa-unknownea`) or the name of the failed check.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct AuthorizationError {
24    pub code: String,
25    pub message: String,
26}
27
28impl AuthorizationError {
29    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
30        Self {
31            code: code.into(),
32            message: message.into(),
33        }
34    }
35}
36
37impl fmt::Display for AuthorizationError {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        write!(f, "{}: {}", self.code, self.message)
40    }
41}
42
43impl std::error::Error for AuthorizationError {}
44
45impl From<PkiProtocolError> for AuthorizationError {
46    fn from(e: PkiProtocolError) -> Self {
47        Self::new(e.code, e.message)
48    }
49}
50
51impl From<PkiTransportError> for AuthorizationError {
52    fn from(e: PkiTransportError) -> Self {
53        Self::new("transport", e.0)
54    }
55}
56
57/// ASN.1 name of an AuthorizationResponseCode (`its-aa-unknownea`, ...).
58pub fn response_code_name(code: AuthorizationResponseCode) -> String {
59    format!("{code:?}").replace('_', "-")
60}
61
62/// Send an AuthorizationRequestMessage (with POP when `pop`) to `aa_url` and
63/// return the issued AT. With `retry` the same message is repeated while no
64/// response is received (ETSI TS 103 601 V2.1.1 clause 5.2).
65#[allow(clippy::too_many_arguments)]
66pub fn authorize(
67    transport: &dyn PkiTransport,
68    aa_url: &str,
69    aa_cert: &Certificate,
70    ea_cert: &Certificate,
71    ec_own: &OwnCertificate,
72    backend: &mut EcdsaBackend,
73    attributes: CertificateSubjectAttributes,
74    now: f64,
75    pop: bool,
76    retry: Option<&Retry>,
77) -> Result<OwnCertificate, AuthorizationError> {
78    let request = messages::build_authorization_request(
79        backend,
80        aa_cert,
81        ea_cert,
82        ec_own,
83        attributes,
84        now,
85        pop,
86        KeyAlgorithm::NistP256,
87    )?;
88    let response = post_with_retry(transport, aa_url, &request.message, CT_REQUEST, retry)?;
89    let inner = messages::read_authorization_response(&response, &request, aa_cert, backend)?;
90    if inner.response_code != AuthorizationResponseCode::ok {
91        let code = response_code_name(inner.response_code);
92        return Err(AuthorizationError::new(
93            code.clone(),
94            format!("AA rejected the request: {code}"),
95        ));
96    }
97    let certificate = inner
98        .certificate
99        .ok_or_else(|| AuthorizationError::new("cantparse", "positive response without AT"))?;
100    let at = Certificate::from_asn(certificate, Some(aa_cert.clone()));
101    if !messages::certifies(&at, &backend.get_public_key(request.key_id)) {
102        return Err(AuthorizationError::new(
103            "its-aa-keysdontmatch",
104            "the AT does not certify the requested key",
105        ));
106    }
107    if !at.check_corresponding_issuer(aa_cert) {
108        return Err(AuthorizationError::new(
109            "invalidaasignature",
110            "the AT is not issued by the AA",
111        ));
112    }
113    Ok(OwnCertificate::new(at, request.key_id))
114}