Skip to main content

rustflexstack/security/
sign_service.rs

1//! Sign service — ETSI TS 103 097 message signing.
2//!
3//! Provides [`SignService`] which wraps [`EcdsaBackend`] and
4//! [`CertificateLibrary`] to produce signed `Ieee1609Dot2Data` envelopes.
5//!
6//! Three message profiles are supported:
7//! - CAM  (ITS-AID 36) — §7.1.1
8//! - DENM (ITS-AID 37) — §7.1.2
9//! - Other              — §7.1.3
10
11use crate::security::header_extensions::{encode_requests, TrustListRequest};
12use rasn::prelude::*;
13
14use crate::security::certificate::{
15    encode_ieee1609_dot2_data, encode_tbs_data, Certificate, OwnCertificate,
16};
17use crate::security::certificate_library::CertificateLibrary;
18use crate::security::ecdsa_backend::EcdsaBackend;
19use crate::security::security_asn::ieee1609_dot2::Certificate as AsnCertificate;
20use crate::security::security_asn::ieee1609_dot2::HeaderInfo;
21use crate::security::security_asn::ieee1609_dot2::{
22    Ieee1609Dot2Content, Ieee1609Dot2Data, SequenceOfCertificate, SignedData, SignedDataPayload,
23    SignerIdentifier, ToBeSignedData,
24};
25use crate::security::security_asn::ieee1609_dot2_base_types::{
26    Elevation, HashAlgorithm, HashedId8, Latitude, Longitude, NinetyDegreeInt, OneEightyDegreeInt,
27    Opaque, Psid, ThreeDLocation, Time64, Uint16, Uint64, Uint8,
28};
29use crate::security::sn_sap::{GenerationLocation, SNSignConfirm, SNSignRequest};
30use crate::security::time_service::{unix_time_secs, ELAPSED_SECONDS, ITS_EPOCH};
31use crate::security::validity::{app_permission, location_permitted, ssp_covers, valid_at};
32
33/// No authorization ticket may sign the message: none has the ITS-AID with
34/// the requested SSP, is valid now and is valid at the current position
35/// (IEEE Std 1609.2-2016 clause 5.2.3.2.2). The message shall not be sent.
36#[derive(Debug, Clone, PartialEq)]
37pub enum SigningError {
38    NoAuthorizationTicket(u64),
39    MissingGenerationLocation,
40}
41
42impl std::fmt::Display for SigningError {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        match self {
45            SigningError::NoAuthorizationTicket(aid) => {
46                write!(f, "no valid authorization ticket for ITS-AID {aid}")
47            }
48            SigningError::MissingGenerationLocation => {
49                write!(f, "DENM requires generation_location")
50            }
51        }
52    }
53}
54
55impl std::error::Error for SigningError {}
56
57// ─── CAM security handler ───────────────────────────────────────────────
58
59/// Handles the signing and signer selection of CAMs according to ETSI TS 103 097 V2.2.1 (2026-03) §7.1.1:
60/// - As default, the choice digest shall be included.
61/// - The choice certificate shall be included once, one second after the last inclusion of the choice certificate.
62/// - If the ITS-S receives a CAM signed by a previously unknown AT, it shall include the choice certificate immediately
63///   in its next CAM, instead of including the choice digest. In this case, the timer for the next inclusion of the choice
64///   certificate shall be restarted.
65/// - If an ITS-S receives a CAM that includes a `tbsData.headerInfo` component of type `inlineP2pcdRequest`,
66///   and finds its own AT's digest in that list, it shall include the choice certificate immediately in its next CAM.
67
68#[derive(Clone, Debug)]
69pub struct CooperativeAwarenessMessageSecurityHandler {
70    pub backend: EcdsaBackend,
71    pub last_signer_full_certificate_time: f64,
72    pub requested_own_certificate: bool,
73}
74
75pub type CamSignerState = CooperativeAwarenessMessageSecurityHandler;
76
77impl CooperativeAwarenessMessageSecurityHandler {
78    pub fn new(backend: EcdsaBackend) -> Self {
79        Self {
80            backend,
81            last_signer_full_certificate_time: 0.0,
82            requested_own_certificate: false,
83        }
84    }
85
86    /// Set up the signer choice for a CAM at the given timestamp in seconds.
87    ///
88    /// The whole certificate is attached if:
89    /// - At least 1 second has elapsed since the last full certificate attachment, or
90    /// - Own certificate was explicitly requested (e.g. peer sent unknown AT or P2PCD request).
91    ///
92    /// Otherwise, the digest (HashedId8) is attached.
93    pub fn set_up_signer_at(
94        &mut self,
95        cert: &OwnCertificate,
96        current_time: f64,
97    ) -> SignerIdentifier {
98        // Compared in microseconds so that exactly one second counts as elapsed.
99        let elapsed_us =
100            ((current_time - self.last_signer_full_certificate_time) * 1e6).round() as i64;
101        if elapsed_us >= 1_000_000 || self.requested_own_certificate {
102            self.last_signer_full_certificate_time = current_time;
103            self.requested_own_certificate = false;
104            let asn_cert: AsnCertificate = cert.cert.inner.0.clone();
105            SignerIdentifier::certificate(SequenceOfCertificate(vec![asn_cert]))
106        } else {
107            let h = cert.as_hashedid8();
108            SignerIdentifier::digest(HashedId8(FixedOctetString::from(h)))
109        }
110    }
111
112    /// Set up the signer choice using the current system time (`time_service::unix_time_secs()`).
113    pub fn set_up_signer(&mut self, cert: &OwnCertificate) -> SignerIdentifier {
114        let now = crate::security::time_service::unix_time_secs();
115        self.set_up_signer_at(cert, now)
116    }
117
118    /// Compatibility alias for earlier internal `choose_signer`.
119    pub fn choose_signer(&mut self, cert: &OwnCertificate) -> SignerIdentifier {
120        self.set_up_signer(cert)
121    }
122}
123
124// ─── SignService ─────────────────────────────────────────────────────────
125
126/// Time source of the sign service: the current UTC time in seconds since the
127/// Unix epoch. It dates the messages (generationTime), drives the
128/// certificate-inclusion timers and selects the ATs valid now.
129pub type SignClock = std::sync::Arc<dyn Fn() -> f64 + Send + Sync>;
130
131/// Source of the peer-to-peer CRL / CTL request inserted in the next CAM (ETSI
132/// TS 103 601 V2.1.1 clause 5.3.4), set by the CRL / CTL distribution service.
133pub type TrustListRequestProvider =
134    std::sync::Arc<dyn Fn() -> Option<TrustListRequest> + Send + Sync>;
135
136/// Signing service for ETSI TS 103 097-secured messages.
137pub struct SignService {
138    pub backend: EcdsaBackend,
139    pub cert_library: CertificateLibrary,
140    pub cam_handler: CooperativeAwarenessMessageSecurityHandler,
141    /// Certificate timer of the messages other than CAM and DENM (clause
142    /// 7.1.3): the certificate once per second, the digest otherwise.
143    pub other_handler: CooperativeAwarenessMessageSecurityHandler,
144    /// HashedId3 values of unknown ATs to include in `inlineP2pcdRequest`.
145    pub unknown_ats: Vec<[u8; 3]>,
146    /// HashedId3 values for which we should embed `requestedCertificate`.
147    pub requested_ats: Vec<[u8; 3]>,
148    /// P2P CRL / CTL request for the next CAM (TS 103 601 clause 5.3.4).
149    pub trust_list_request: Option<TrustListRequestProvider>,
150    clock: Option<SignClock>,
151}
152
153impl SignService {
154    pub fn new(backend: EcdsaBackend, cert_library: CertificateLibrary) -> Self {
155        let cam_handler = CooperativeAwarenessMessageSecurityHandler::new(backend.clone());
156        let other_handler = CooperativeAwarenessMessageSecurityHandler::new(backend.clone());
157        Self {
158            backend,
159            cert_library,
160            cam_handler,
161            other_handler,
162            unknown_ats: Vec::new(),
163            requested_ats: Vec::new(),
164            trust_list_request: None,
165            clock: None,
166        }
167    }
168
169    /// Use `clock` instead of the system time (UTC seconds since the Unix epoch).
170    pub fn with_clock(mut self, clock: SignClock) -> Self {
171        self.clock = Some(clock);
172        self
173    }
174
175    /// Current UTC time in seconds (the injected clock, or the system time).
176    pub fn now_secs(&self) -> f64 {
177        self.clock
178            .as_ref()
179            .map_or_else(unix_time_secs, |clock| clock())
180    }
181
182    /// Current ITS time (TAI) in microseconds, as `generationTime` (Time64).
183    pub fn now_its_us(&self) -> u64 {
184        ((self.now_secs() - ITS_EPOCH as f64 + ELAPSED_SECONDS as f64) * 1e6).round() as u64
185    }
186
187    /// Accessor for CAM security handler (cam_state).
188    pub fn cam_state(&self) -> &CooperativeAwarenessMessageSecurityHandler {
189        &self.cam_handler
190    }
191
192    /// Mutable accessor for CAM security handler (cam_state).
193    pub fn cam_state_mut(&mut self) -> &mut CooperativeAwarenessMessageSecurityHandler {
194        &mut self.cam_handler
195    }
196
197    /// Route to the correct profile based on ITS-AID.
198    ///
199    /// # Panics
200    /// When no authorization ticket may sign the message; use
201    /// [`SignService::try_sign_request`] to handle that case.
202    pub fn sign_request(&mut self, request: &SNSignRequest) -> SNSignConfirm {
203        self.try_sign_request(request).expect("No AT for signing")
204    }
205
206    /// Route to the correct profile based on ITS-AID; `Err` when no AT may
207    /// sign the message (the message shall then not be sent).
208    pub fn try_sign_request(
209        &mut self,
210        request: &SNSignRequest,
211    ) -> Result<SNSignConfirm, SigningError> {
212        match request.its_aid {
213            36 => self.try_sign_cam_at(request, None),
214            37 => self.try_sign_denm(request),
215            _ => self.try_sign_other(request),
216        }
217    }
218
219    /// Find the own certificate that may sign for the given ITS-AID now.
220    pub fn get_present_at(&self, its_aid: u64) -> Option<&OwnCertificate> {
221        self.select_at(its_aid, &[], None)
222    }
223
224    /// Parity alias for Python `get_present_at_for_signging`.
225    pub fn get_present_at_for_signging(&self, its_aid: u64) -> Option<&OwnCertificate> {
226        self.get_present_at(its_aid)
227    }
228
229    /// Select the AT to sign with (IEEE Std 1609.2-2016 clause 5.2.3.2.2):
230    /// its appPermissions contain the ITS-AID with an SSP granting the
231    /// requested `permissions`, the current time lies in the validity period
232    /// of its chain and, when `location` is given, the position lies in the
233    /// region of its chain.
234    pub fn select_at(
235        &self,
236        its_aid: u64,
237        permissions: &[u8],
238        location: Option<&GenerationLocation>,
239    ) -> Option<&OwnCertificate> {
240        let now_us = self.now_its_us();
241        self.cert_library.own_certificates.values().find(|cert| {
242            let (permitted, ssp) = app_permission(cert.tbs(), its_aid);
243            permitted
244                && ssp_covers(ssp.as_deref(), permissions)
245                && valid_at(&cert.cert, now_us)
246                && location.is_none_or(|l| location_permitted(&cert.cert, l.latitude, l.longitude))
247        })
248    }
249
250    fn at_for(&self, request: &SNSignRequest) -> Result<&OwnCertificate, SigningError> {
251        self.select_at(
252            request.its_aid,
253            &request.permissions,
254            request.generation_location.as_ref(),
255        )
256        .ok_or(SigningError::NoAuthorizationTicket(request.its_aid))
257    }
258
259    /// Look up a known CA certificate by its HashedId3 for inclusion in `requestedCertificate`.
260    pub fn get_known_at_for_request(&self, hashedid3: &[u8; 3]) -> Result<AsnCertificate, String> {
261        self.cert_library
262            .get_ca_certificate_by_hashedid3(hashedid3)
263            .map(|c| c.inner.0.clone())
264            .ok_or_else(|| format!("No CA certificate found for HashedId3 {:02x?}", hashedid3))
265    }
266
267    // ── Helper: build the Ieee1609Dot2Data envelope ──────────────────────
268
269    pub(crate) fn build_signed_data(
270        &self,
271        payload: &[u8],
272        header_info: HeaderInfo,
273        signer: SignerIdentifier,
274        at: &OwnCertificate,
275    ) -> Vec<u8> {
276        let inner_data = Ieee1609Dot2Data::new(
277            Uint8(3),
278            Ieee1609Dot2Content::unsecuredData(Opaque(payload.to_vec().into())),
279        );
280
281        let tbs_data = ToBeSignedData::new(
282            Box::new(SignedDataPayload {
283                data: Some(inner_data),
284                ext_data_hash: None,
285                omitted: None,
286            }),
287            header_info,
288        );
289
290        let tbs_bytes = encode_tbs_data(&tbs_data);
291        let signature = at.sign_message(&self.backend, &tbs_bytes);
292
293        let hash_id = if at.cert.uses_sha384() {
294            HashAlgorithm::sha384
295        } else {
296            HashAlgorithm::sha256
297        };
298        let signed_data = SignedData::new(hash_id, tbs_data, signer, signature);
299
300        let outer = Ieee1609Dot2Data::new(Uint8(3), Ieee1609Dot2Content::signedData(signed_data));
301        encode_ieee1609_dot2_data(&outer)
302    }
303
304    // ── §7.1.3 generic signed messages ───────────────────────────────────
305
306    pub fn sign_other(&mut self, request: &SNSignRequest) -> SNSignConfirm {
307        self.try_sign_other(request).expect("No AT for signing")
308    }
309
310    /// Messages other than CAM and DENM (TS 103 097 clause 7.1.3, which does
311    /// not constrain the signer): the certificate once per second, so that
312    /// receivers can verify them without having heard a CAM, the digest
313    /// otherwise.
314    pub fn try_sign_other(
315        &mut self,
316        request: &SNSignRequest,
317    ) -> Result<SNSignConfirm, SigningError> {
318        let at = self.at_for(request)?.clone();
319        let now = self.now_secs();
320        let signer = self.other_handler.set_up_signer_at(&at, now);
321
322        let header_info = HeaderInfo::new(
323            Psid(Integer::from(request.its_aid as i64)),
324            Some(Time64(Uint64(self.now_its_us()))),
325            None,
326            None,
327            None,
328            None,
329            None,
330            None,
331            None,
332            None,
333            None,
334        );
335
336        let sec_message = self.build_signed_data(&request.tbs_message, header_info, signer, &at);
337        Ok(SNSignConfirm { sec_message })
338    }
339
340    // ── §7.1.2 DENM ─────────────────────────────────────────────────────
341
342    pub fn sign_denm(&self, request: &SNSignRequest) -> SNSignConfirm {
343        self.try_sign_denm(request).expect("No AT for signing DENM")
344    }
345
346    pub fn try_sign_denm(&self, request: &SNSignRequest) -> Result<SNSignConfirm, SigningError> {
347        let gen_loc = request
348            .generation_location
349            .as_ref()
350            .ok_or(SigningError::MissingGenerationLocation)?;
351        let at = self.at_for(request)?;
352
353        let asn_cert: AsnCertificate = at.cert.inner.0.clone();
354        let signer = SignerIdentifier::certificate(SequenceOfCertificate(vec![asn_cert]));
355
356        let header_info = HeaderInfo::new(
357            Psid(Integer::from(request.its_aid as i64)),
358            Some(Time64(Uint64(self.now_its_us()))),
359            None,
360            Some(ThreeDLocation {
361                latitude: Latitude(NinetyDegreeInt(gen_loc.latitude)),
362                longitude: Longitude(OneEightyDegreeInt(gen_loc.longitude)),
363                elevation: Elevation(Uint16(gen_loc.elevation)),
364            }),
365            None,
366            None,
367            None,
368            None,
369            None,
370            None,
371            None,
372        );
373
374        let sec_message = self.build_signed_data(&request.tbs_message, header_info, signer, at);
375        Ok(SNSignConfirm { sec_message })
376    }
377
378    // ── §7.1.1 CAM ──────────────────────────────────────────────────────
379
380    pub fn sign_cam(&mut self, request: &SNSignRequest) -> SNSignConfirm {
381        self.sign_cam_at(request, None)
382    }
383
384    /// Sign a CAM according to ETSI TS 103 097 V2.2.1 §5.2 and §7.1.1,
385    /// with an optional timestamp in seconds (for deterministic testing).
386    pub fn sign_cam_at(
387        &mut self,
388        request: &SNSignRequest,
389        timestamp_secs: Option<f64>,
390    ) -> SNSignConfirm {
391        self.try_sign_cam_at(request, timestamp_secs)
392            .expect("No AT for signing CAM")
393    }
394
395    /// [`SignService::sign_cam_at`] returning `Err` when no AT may sign.
396    pub fn try_sign_cam_at(
397        &mut self,
398        request: &SNSignRequest,
399        timestamp_secs: Option<f64>,
400    ) -> Result<SNSignConfirm, SigningError> {
401        let at = self.at_for(request)?.clone();
402
403        let now = timestamp_secs.unwrap_or_else(|| self.now_secs());
404        let signer = self.cam_handler.set_up_signer_at(&at, now);
405
406        // inlineP2pcdRequest: the certificates still unknown (TS 103 097
407        // clause 7.1.1); an entry is removed when the certificate is learned.
408        let inline_p2pcd = if !self.unknown_ats.is_empty() {
409            let hashes: Vec<_> = self
410                .unknown_ats
411                .iter()
412                .copied()
413                .map(|h3| {
414                    crate::security::security_asn::ieee1609_dot2_base_types::HashedId3(
415                        FixedOctetString::from(h3),
416                    )
417                })
418                .collect();
419            Some(
420                crate::security::security_asn::ieee1609_dot2_base_types::SequenceOfHashedId3(
421                    hashes,
422                ),
423            )
424        } else {
425            None
426        };
427
428        // requestedCertificate: only in a CAM signed with a digest; while the
429        // signer is a certificate the request stays pending (clause 7.1.1).
430        let requested_cert =
431            if !self.requested_ats.is_empty() && matches!(signer, SignerIdentifier::digest(_)) {
432                let h3 = self.requested_ats.remove(0);
433                self.get_known_at_for_request(&h3).ok()
434            } else {
435                None
436            };
437
438        // contributedExtensions: a single P2P CRL / CTL request per CAM (TS 103
439        // 601 clauses 5.3.2 and 5.3.4; TS 103 097 clause 7.1.1 allows them).
440        let contributed = self
441            .trust_list_request
442            .as_ref()
443            .and_then(|provider| provider())
444            .map(|r| encode_requests(std::slice::from_ref(&r)));
445
446        let header_info = HeaderInfo::new(
447            Psid(Integer::from(request.its_aid as i64)),
448            Some(Time64(Uint64(self.now_its_us()))),
449            None,
450            None,
451            None,
452            None,
453            None,
454            inline_p2pcd,
455            requested_cert,
456            None,
457            contributed,
458        );
459
460        let sec_message = self.build_signed_data(&request.tbs_message, header_info, signer, &at);
461        Ok(SNSignConfirm { sec_message })
462    }
463
464    // ── P2PCD notification helpers ───────────────────────────────────────
465
466    /// Record an unknown AT HashedId3 and force own cert inclusion in next CAM.
467    pub fn notify_unknown_at(&mut self, hashedid8: &[u8; 8]) {
468        let h3 = [hashedid8[5], hashedid8[6], hashedid8[7]];
469        if !self.unknown_ats.contains(&h3) {
470            self.unknown_ats.push(h3);
471        }
472        self.cam_handler.requested_own_certificate = true;
473    }
474
475    /// An AT was learned (received as certificate signer): stop requesting it.
476    pub fn notify_known_at(&mut self, hashedid8: &[u8; 8]) {
477        let h3 = [hashedid8[5], hashedid8[6], hashedid8[7]];
478        self.unknown_ats.retain(|x| *x != h3);
479    }
480
481    /// Process a received `inlineP2pcdRequest`.
482    pub fn notify_inline_p2pcd_request(&mut self, request_list: &[[u8; 3]]) {
483        for own in self.cert_library.own_certificates.values() {
484            let own_h3 = {
485                let h8 = own.as_hashedid8();
486                [h8[5], h8[6], h8[7]]
487            };
488            if request_list.contains(&own_h3) {
489                self.cam_handler.requested_own_certificate = true;
490            }
491        }
492        for h3 in request_list {
493            if self
494                .cert_library
495                .get_ca_certificate_by_hashedid3(h3)
496                .is_some()
497                && !self.requested_ats.contains(h3)
498            {
499                self.requested_ats.push(*h3);
500            }
501        }
502    }
503
504    /// Process a received CA certificate from `requestedCertificate`.
505    pub fn notify_received_ca_certificate(&mut self, cert: Certificate) {
506        let h3 = cert.as_hashedid3();
507        self.requested_ats.retain(|x| *x != h3);
508        self.unknown_ats.retain(|x| *x != h3);
509        self.cert_library
510            .add_authorization_authority(&self.backend, cert);
511    }
512
513    /// Add an own certificate.
514    pub fn add_own_certificate(&mut self, cert: OwnCertificate) {
515        self.cert_library.add_own_certificate(&self.backend, cert);
516    }
517}
518
519#[cfg(test)]
520mod tests {
521    use super::*;
522    use crate::security::certificate::{decode_ieee1609_dot2_data, OwnCertificate};
523    use crate::security::certificate_library::CertificateLibrary;
524    use crate::security::ecdsa_backend::EcdsaBackend;
525    use crate::security::security_asn::ieee1609_dot2::{
526        CertificateId, EndEntityType, Ieee1609Dot2Content, PsidGroupPermissions,
527        SequenceOfPsidGroupPermissions, SubjectPermissions, ToBeSignedCertificate,
528        VerificationKeyIndicator,
529    };
530    use crate::security::security_asn::ieee1609_dot2_base_types::{
531        CrlSeries, Duration as AsnDuration, EccP256CurvePoint, HashedId3, Psid, PsidSsp,
532        PublicVerificationKey, SequenceOfPsidSsp, Time32, Uint16, Uint32, ValidityPeriod,
533    };
534    use crate::security::sn_sap::{GenerationLocation, SNSignRequest};
535
536    fn make_root_tbs() -> ToBeSignedCertificate {
537        let validity = ValidityPeriod::new(Time32(Uint32(0)), AsnDuration::years(Uint16(30)));
538        let perms = SequenceOfPsidGroupPermissions(vec![PsidGroupPermissions::new(
539            SubjectPermissions::all(()),
540            Integer::from(1),
541            Integer::from(0),
542            {
543                let mut bits = FixedBitString::<8>::default();
544                bits.set(0, true);
545                EndEntityType(bits)
546            },
547        )]);
548        let pk =
549            PublicVerificationKey::ecdsaNistP256(EccP256CurvePoint::x_only(vec![0u8; 32].into()));
550        ToBeSignedCertificate::new(
551            CertificateId::none(()),
552            HashedId3(FixedOctetString::from([0u8; 3])),
553            CrlSeries(Uint16(0)),
554            validity,
555            None,
556            None,
557            None,
558            Some(perms),
559            None,
560            None,
561            None,
562            VerificationKeyIndicator::verificationKey(pk),
563            None,
564            None,
565            None,
566            None,
567        )
568    }
569
570    fn make_at_tbs(its_aid: i64) -> ToBeSignedCertificate {
571        // Valid now: started a minute ago, one year long
572        let now_s =
573            (crate::security::time_service::timestamp_its_microseconds() / 1_000_000) as u32;
574        let validity =
575            ValidityPeriod::new(Time32(Uint32(now_s - 60)), AsnDuration::years(Uint16(1)));
576        let app_perms = SequenceOfPsidSsp(vec![PsidSsp::new(Psid(Integer::from(its_aid)), None)]);
577        let pk =
578            PublicVerificationKey::ecdsaNistP256(EccP256CurvePoint::x_only(vec![0u8; 32].into()));
579        ToBeSignedCertificate::new(
580            CertificateId::none(()),
581            HashedId3(FixedOctetString::from([0u8; 3])),
582            CrlSeries(Uint16(0)),
583            validity,
584            None,
585            None,
586            Some(app_perms),
587            None,
588            None,
589            None,
590            None,
591            VerificationKeyIndicator::verificationKey(pk),
592            None,
593            None,
594            None,
595            None,
596        )
597    }
598
599    fn make_sign_service() -> SignService {
600        let mut backend = EcdsaBackend::new();
601        let root = OwnCertificate::initialize_self_signed(&mut backend, make_root_tbs());
602        let aa = OwnCertificate::initialize_issued(&mut backend, make_root_tbs(), &root);
603        let at_cam = OwnCertificate::initialize_issued(&mut backend, make_at_tbs(36), &aa);
604        let at_denm = OwnCertificate::initialize_issued(&mut backend, make_at_tbs(37), &aa);
605
606        let lib = CertificateLibrary::new(
607            &backend,
608            vec![root.cert.clone()],
609            vec![aa.cert.clone()],
610            vec![],
611        );
612        let mut svc = SignService::new(backend, lib);
613        svc.add_own_certificate(at_cam);
614        svc.add_own_certificate(at_denm);
615        svc
616    }
617
618    #[test]
619    fn sign_cam_produces_nonempty_message() {
620        let mut svc = make_sign_service();
621        let req = SNSignRequest {
622            tbs_message: vec![0xCA, 0xFE],
623            its_aid: 36,
624            permissions: vec![],
625            generation_location: None,
626        };
627        let confirm = svc.sign_request(&req);
628        assert!(!confirm.sec_message.is_empty());
629    }
630
631    #[test]
632    fn sign_denm_produces_nonempty_message() {
633        let mut svc = make_sign_service();
634        let req = SNSignRequest {
635            tbs_message: vec![0xDE, 0x01],
636            its_aid: 37,
637            permissions: vec![],
638            generation_location: Some(GenerationLocation {
639                latitude: 415520000,
640                longitude: 21340000,
641                elevation: 0xF000,
642            }),
643        };
644        let confirm = svc.sign_request(&req);
645        assert!(!confirm.sec_message.is_empty());
646    }
647
648    #[test]
649    fn sign_other_aid_produces_nonempty_message() {
650        // Add a cert for a custom AID
651        let mut backend = EcdsaBackend::new();
652        let root = OwnCertificate::initialize_self_signed(&mut backend, make_root_tbs());
653        let aa = OwnCertificate::initialize_issued(&mut backend, make_root_tbs(), &root);
654        let at = OwnCertificate::initialize_issued(&mut backend, make_at_tbs(99), &aa);
655        let lib = CertificateLibrary::new(
656            &backend,
657            vec![root.cert.clone()],
658            vec![aa.cert.clone()],
659            vec![],
660        );
661        let mut svc = SignService::new(backend, lib);
662        svc.add_own_certificate(at);
663
664        let req = SNSignRequest {
665            tbs_message: vec![0x01, 0x02],
666            its_aid: 99,
667            permissions: vec![],
668            generation_location: None,
669        };
670        let confirm = svc.sign_request(&req);
671        assert!(!confirm.sec_message.is_empty());
672    }
673
674    #[test]
675    fn sign_cam_first_call_includes_certificate() {
676        let mut svc = make_sign_service();
677        let req = SNSignRequest {
678            tbs_message: vec![0xCA],
679            its_aid: 36,
680            permissions: vec![],
681            generation_location: None,
682        };
683        // First CAM should include full certificate (signer = certificate)
684        let confirm1 = svc.sign_request(&req);
685        assert!(!confirm1.sec_message.is_empty());
686    }
687
688    #[test]
689    fn sign_cam_first_call_includes_full_certificate_decoded() {
690        let mut svc = make_sign_service();
691        let req = SNSignRequest {
692            tbs_message: vec![0xCA, 0x01],
693            its_aid: 36,
694            permissions: vec![],
695            generation_location: None,
696        };
697        let confirm1 = svc.sign_cam(&req);
698        let dot2 = decode_ieee1609_dot2_data(&confirm1.sec_message);
699        if let Ieee1609Dot2Content::signedData(sd) = dot2.content {
700            match sd.signer {
701                SignerIdentifier::certificate(certs) => {
702                    assert_eq!(certs.0.len(), 1, "Exactly one certificate attached");
703                }
704                _ => panic!("Expected SignerIdentifier::certificate on first call"),
705            }
706        } else {
707            panic!("Expected signedData");
708        }
709    }
710
711    #[test]
712    fn sign_cam_second_call_within_one_second_includes_digest_decoded() {
713        let mut svc = make_sign_service();
714        let req = SNSignRequest {
715            tbs_message: vec![0xCA, 0x02],
716            its_aid: 36,
717            permissions: vec![],
718            generation_location: None,
719        };
720        // 1st call -> certificate
721        let _confirm1 = svc.sign_cam(&req);
722
723        // 2nd call immediately -> digest
724        let confirm2 = svc.sign_cam(&req);
725        let dot2 = decode_ieee1609_dot2_data(&confirm2.sec_message);
726        if let Ieee1609Dot2Content::signedData(sd) = dot2.content {
727            match sd.signer {
728                SignerIdentifier::digest(h8) => {
729                    let at = svc.get_present_at(36).unwrap();
730                    assert_eq!(h8.0.as_ref(), &at.as_hashedid8());
731                }
732                _ => panic!("Expected SignerIdentifier::digest on second call within 1 second"),
733            }
734        } else {
735            panic!("Expected signedData");
736        }
737    }
738
739    #[test]
740    fn sign_cam_after_one_second_includes_full_certificate_again() {
741        let mut svc = make_sign_service();
742        let req = SNSignRequest {
743            tbs_message: vec![0xCA, 0x03],
744            its_aid: 36,
745            permissions: vec![],
746            generation_location: None,
747        };
748
749        // Call 1 at t = 100.0s -> full certificate
750        let confirm1 = svc.sign_cam_at(&req, Some(100.0));
751        let dot2_1 = decode_ieee1609_dot2_data(&confirm1.sec_message);
752        if let Ieee1609Dot2Content::signedData(sd) = dot2_1.content {
753            assert!(
754                matches!(sd.signer, SignerIdentifier::certificate(_)),
755                "1st call must be certificate"
756            );
757        }
758
759        // Call 2 at t = 100.5s (0.5s later) -> digest
760        let confirm2 = svc.sign_cam_at(&req, Some(100.5));
761        let dot2_2 = decode_ieee1609_dot2_data(&confirm2.sec_message);
762        if let Ieee1609Dot2Content::signedData(sd) = dot2_2.content {
763            assert!(
764                matches!(sd.signer, SignerIdentifier::digest(_)),
765                "Call within 1s must be digest"
766            );
767        }
768
769        // Call 3 at t = 100.999s (just under 1.0s later) -> digest
770        let confirm3 = svc.sign_cam_at(&req, Some(100.999));
771        let dot2_3 = decode_ieee1609_dot2_data(&confirm3.sec_message);
772        if let Ieee1609Dot2Content::signedData(sd) = dot2_3.content {
773            assert!(
774                matches!(sd.signer, SignerIdentifier::digest(_)),
775                "Call under 1.0s is digest"
776            );
777        }
778
779        // Call 4 at t = 101.0s (one second later, TS 103 097 clause 7.1.1) -> full certificate again
780        let confirm4 = svc.sign_cam_at(&req, Some(101.0));
781        let dot2_4 = decode_ieee1609_dot2_data(&confirm4.sec_message);
782        if let Ieee1609Dot2Content::signedData(sd) = dot2_4.content {
783            match sd.signer {
784                SignerIdentifier::certificate(certs) => {
785                    assert_eq!(certs.0.len(), 1);
786                }
787                _ => panic!("Call 1s later must attach full certificate again"),
788            }
789        }
790        assert_eq!(svc.cam_handler.last_signer_full_certificate_time, 101.0);
791    }
792
793    #[test]
794    fn sign_cam_requested_own_certificate_forces_immediate_certificate() {
795        let mut svc = make_sign_service();
796        let req = SNSignRequest {
797            tbs_message: vec![0xCA, 0x04],
798            its_aid: 36,
799            permissions: vec![],
800            generation_location: None,
801        };
802
803        // Call 1 at t = 100.0s -> certificate
804        let _confirm1 = svc.sign_cam_at(&req, Some(100.0));
805
806        // Unknown peer AT seen at t = 100.2s -> triggers requested_own_certificate
807        svc.notify_unknown_at(&[1, 2, 3, 4, 5, 6, 7, 8]);
808        assert!(svc.cam_handler.requested_own_certificate);
809
810        // Call 2 at t = 100.2s (only 0.2s elapsed) -> MUST include full certificate!
811        let confirm2 = svc.sign_cam_at(&req, Some(100.2));
812        let dot2_2 = decode_ieee1609_dot2_data(&confirm2.sec_message);
813        if let Ieee1609Dot2Content::signedData(sd) = dot2_2.content {
814            assert!(
815                matches!(sd.signer, SignerIdentifier::certificate(_)),
816                "Forced certificate must include certificate even within 1 second"
817            );
818        }
819        assert!(!svc.cam_handler.requested_own_certificate);
820        assert_eq!(svc.cam_handler.last_signer_full_certificate_time, 100.2);
821    }
822
823    #[test]
824    fn cam_handler_set_up_signer_at() {
825        let mut backend = EcdsaBackend::new();
826        let root = OwnCertificate::initialize_self_signed(&mut backend, make_root_tbs());
827        let aa = OwnCertificate::initialize_issued(&mut backend, make_root_tbs(), &root);
828        let at = OwnCertificate::initialize_issued(&mut backend, make_at_tbs(36), &aa);
829
830        let mut handler = CooperativeAwarenessMessageSecurityHandler::new(backend);
831        assert_eq!(handler.last_signer_full_certificate_time, 0.0);
832        assert!(!handler.requested_own_certificate);
833
834        // First call at 100.0 -> certificate
835        let signer1 = handler.set_up_signer_at(&at, 100.0);
836        assert!(matches!(signer1, SignerIdentifier::certificate(_)));
837        assert_eq!(handler.last_signer_full_certificate_time, 100.0);
838
839        // Second call at 100.9 -> digest (under one second)
840        let signer2 = handler.set_up_signer_at(&at, 100.9);
841        assert!(matches!(signer2, SignerIdentifier::digest(_)));
842        assert_eq!(handler.last_signer_full_certificate_time, 100.0);
843
844        // Third call with requested_own_certificate = true -> certificate
845        handler.requested_own_certificate = true;
846        let signer3 = handler.set_up_signer_at(&at, 100.95);
847        assert!(matches!(signer3, SignerIdentifier::certificate(_)));
848        assert!(!handler.requested_own_certificate);
849        assert_eq!(handler.last_signer_full_certificate_time, 100.95);
850
851        // One second after the last inclusion -> certificate (TS 103 097 clause 7.1.1)
852        assert!(matches!(
853            handler.set_up_signer_at(&at, 101.9),
854            SignerIdentifier::digest(_)
855        ));
856        assert!(matches!(
857            handler.set_up_signer_at(&at, 101.95),
858            SignerIdentifier::certificate(_)
859        ));
860        assert_eq!(handler.last_signer_full_certificate_time, 101.95);
861
862        // Later call at 102.5 -> digest (0.55 s elapsed); at 103.0 -> certificate
863        assert!(matches!(
864            handler.set_up_signer_at(&at, 102.5),
865            SignerIdentifier::digest(_)
866        ));
867        let signer4 = handler.set_up_signer_at(&at, 102.95);
868        assert!(matches!(signer4, SignerIdentifier::certificate(_)));
869        assert_eq!(handler.last_signer_full_certificate_time, 102.95);
870    }
871
872    #[test]
873    fn sign_denm_always_uses_certificate() {
874        let svc = make_sign_service();
875        let req = SNSignRequest {
876            tbs_message: vec![0xDE, 0x01],
877            its_aid: 37,
878            permissions: vec![],
879            generation_location: Some(GenerationLocation {
880                latitude: 415520000,
881                longitude: 21340000,
882                elevation: 0xF000,
883            }),
884        };
885        let confirm = svc.sign_denm(&req);
886        let dot2 = decode_ieee1609_dot2_data(&confirm.sec_message);
887        if let Ieee1609Dot2Content::signedData(sd) = dot2.content {
888            assert!(matches!(sd.signer, SignerIdentifier::certificate(_)));
889        } else {
890            panic!("Expected signedData");
891        }
892    }
893
894    /// Clause 7.1.3 messages: the certificate once per second, the digest
895    /// otherwise (own timer, independent of the CAM one).
896    #[test]
897    fn sign_other_certificate_once_per_second() {
898        let mut backend = EcdsaBackend::new();
899        let root = OwnCertificate::initialize_self_signed(&mut backend, make_root_tbs());
900        let aa = OwnCertificate::initialize_issued(&mut backend, make_root_tbs(), &root);
901        let at = OwnCertificate::initialize_issued(&mut backend, make_at_tbs(139), &aa);
902        let lib = CertificateLibrary::new(
903            &backend,
904            vec![root.cert.clone()],
905            vec![aa.cert.clone()],
906            vec![],
907        );
908        let mut svc = SignService::new(backend, lib);
909        svc.add_own_certificate(at);
910
911        let req = SNSignRequest {
912            tbs_message: vec![0x11, 0x22],
913            its_aid: 139,
914            permissions: vec![],
915            generation_location: None,
916        };
917        let signer_is_certificate = |svc: &mut SignService| {
918            let confirm = svc.sign_other(&req);
919            match decode_ieee1609_dot2_data(&confirm.sec_message).content {
920                Ieee1609Dot2Content::signedData(sd) => {
921                    matches!(sd.signer, SignerIdentifier::certificate(_))
922                }
923                _ => panic!("Expected signedData"),
924            }
925        };
926        assert!(signer_is_certificate(&mut svc));
927        assert!(!signer_is_certificate(&mut svc));
928        assert_eq!(svc.cam_handler.last_signer_full_certificate_time, 0.0);
929        svc.other_handler.last_signer_full_certificate_time -= 1.5;
930        assert!(signer_is_certificate(&mut svc));
931        assert!(!signer_is_certificate(&mut svc));
932    }
933
934    #[test]
935    fn notify_unknown_at() {
936        let mut svc = make_sign_service();
937        let h8 = [1, 2, 3, 4, 5, 6, 7, 8];
938        svc.notify_unknown_at(&h8);
939        assert_eq!(svc.unknown_ats.len(), 1);
940        assert_eq!(svc.unknown_ats[0], [6, 7, 8]); // last 3 bytes
941        assert!(svc.cam_handler.requested_own_certificate);
942    }
943
944    #[test]
945    fn notify_unknown_at_no_duplicates() {
946        let mut svc = make_sign_service();
947        let h8 = [1, 2, 3, 4, 5, 6, 7, 8];
948        svc.notify_unknown_at(&h8);
949        svc.notify_unknown_at(&h8);
950        assert_eq!(svc.unknown_ats.len(), 1);
951    }
952
953    #[test]
954    fn notify_inline_p2pcd_request_match_own() {
955        let mut svc = make_sign_service();
956        let own_at = svc.get_present_at(36).unwrap();
957        let own_h8 = own_at.as_hashedid8();
958        let own_h3 = [own_h8[5], own_h8[6], own_h8[7]];
959
960        svc.notify_inline_p2pcd_request(&[own_h3]);
961        assert!(svc.cam_handler.requested_own_certificate);
962    }
963
964    #[test]
965    fn notify_inline_p2pcd_request_ca_match() {
966        let mut svc = make_sign_service();
967        let aa = svc
968            .cert_library
969            .known_authorization_authorities
970            .values()
971            .next()
972            .unwrap()
973            .clone();
974        let aa_h3 = aa.as_hashedid3();
975
976        svc.notify_inline_p2pcd_request(&[aa_h3]);
977        assert_eq!(svc.requested_ats, vec![aa_h3]);
978    }
979
980    #[test]
981    fn notify_inline_p2pcd_request_no_match() {
982        let mut svc = make_sign_service();
983        svc.notify_inline_p2pcd_request(&[[0x99, 0x88, 0x77]]);
984        assert!(!svc.cam_handler.requested_own_certificate);
985        assert!(svc.requested_ats.is_empty());
986    }
987
988    #[test]
989    fn notify_received_ca_certificate() {
990        let mut svc = make_sign_service();
991        let mut backend = EcdsaBackend::new();
992        let root = OwnCertificate::initialize_self_signed(&mut backend, make_root_tbs());
993        let aa = OwnCertificate::initialize_issued(&mut backend, make_root_tbs(), &root);
994        let aa_h3 = aa.cert.as_hashedid3();
995
996        svc.requested_ats.push(aa_h3);
997        svc.unknown_ats.push(aa_h3);
998
999        svc.notify_received_ca_certificate(aa.cert.clone());
1000        assert!(svc.requested_ats.is_empty());
1001        assert!(svc.unknown_ats.is_empty());
1002    }
1003
1004    #[test]
1005    fn get_known_at_for_request() {
1006        let svc = make_sign_service();
1007        let aa = svc
1008            .cert_library
1009            .known_authorization_authorities
1010            .values()
1011            .next()
1012            .unwrap();
1013        let aa_h3 = aa.as_hashedid3();
1014
1015        let cert = svc.get_known_at_for_request(&aa_h3);
1016        assert!(cert.is_ok());
1017
1018        let not_found = svc.get_known_at_for_request(&[0xFF, 0xEE, 0xDD]);
1019        assert!(not_found.is_err());
1020    }
1021
1022    #[test]
1023    fn get_present_at_for_signging() {
1024        let svc = make_sign_service();
1025        let at_cam = svc.get_present_at_for_signging(36);
1026        assert!(at_cam.is_some());
1027        assert_eq!(at_cam.unwrap().get_list_of_its_aid(), vec![36]);
1028
1029        let at_none = svc.get_present_at_for_signging(9999);
1030        assert!(at_none.is_none());
1031    }
1032}