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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
use std::fmt;

use rpki::cert::Cert;
use rpki::crypto::{KeyIdentifier, PublicKey};
use rpki::csr::Csr;
use rpki::resources::{AsBlocks, IpBlocks, IpBlocksForFamily};
use rpki::uri;
use rpki::x509::Time;

use crate::commons::api::ca::{IssuedCert, RcvdCert, ResourceClassName, ResourceSet};
use crate::commons::util::ext_serde;

//------------ ProvisioningRequest -------------------------------------------

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[allow(clippy::large_enum_variant)]
pub enum ProvisioningRequest {
    List,
    Request(IssuanceRequest),
}

impl ProvisioningRequest {
    pub fn list() -> Self {
        ProvisioningRequest::List
    }
    pub fn request(r: IssuanceRequest) -> Self {
        ProvisioningRequest::Request(r)
    }
}

//------------ ProvisioningResponse -----------------------------------------

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum ProvisioningResponse {
    List(Entitlements),
}

//------------ Entitlements -------------------------------------------------

/// This structure is what is called the "Resource Class List Response"
/// in section 3.3.2 of RFC6492.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Entitlements {
    classes: Vec<EntitlementClass>,
}

impl Entitlements {
    pub fn with_default_class(
        issuer: SigningCert,
        resource_set: ResourceSet,
        not_after: Time,
        issued: Vec<IssuedCert>,
    ) -> Self {
        Entitlements {
            classes: vec![EntitlementClass {
                class_name: ResourceClassName::default(),
                issuer,
                resource_set,
                not_after,
                issued,
            }],
        }
    }
    pub fn new(classes: Vec<EntitlementClass>) -> Self {
        Entitlements { classes }
    }

    pub fn classes(&self) -> &Vec<EntitlementClass> {
        &self.classes
    }
}

impl fmt::Display for Entitlements {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let classes: Vec<String> = self
            .classes
            .iter()
            .map(EntitlementClass::to_string)
            .collect();

        let classes = classes.join(", ");

        write!(f, "{}", classes)
    }
}

//------------ EntitlementClass ----------------------------------------------

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct EntitlementClass {
    class_name: ResourceClassName,
    issuer: SigningCert,
    resource_set: ResourceSet,
    not_after: Time,
    issued: Vec<IssuedCert>,
}

impl EntitlementClass {
    pub fn new(
        class_name: ResourceClassName,
        issuer: SigningCert,
        resource_set: ResourceSet,
        not_after: Time,
        issued: Vec<IssuedCert>,
    ) -> Self {
        EntitlementClass {
            class_name,
            issuer,
            resource_set,
            not_after,
            issued,
        }
    }

    fn unwrap(
        self,
    ) -> (
        ResourceClassName,
        SigningCert,
        ResourceSet,
        Time,
        Vec<IssuedCert>,
    ) {
        (
            self.class_name,
            self.issuer,
            self.resource_set,
            self.not_after,
            self.issued,
        )
    }

    pub fn class_name(&self) -> &ResourceClassName {
        &self.class_name
    }

    pub fn issuer(&self) -> &SigningCert {
        &self.issuer
    }

    pub fn resource_set(&self) -> &ResourceSet {
        &self.resource_set
    }

    pub fn not_after(&self) -> Time {
        self.not_after
    }

    pub fn issued(&self) -> &Vec<IssuedCert> {
        &self.issued
    }

    /// Converts this into an IssuanceResponse for the given key. I.e. includes
    /// the issued certificate matching the given public key only. Returns a
    /// None if no match is found.
    pub fn into_issuance_response(self, key: &PublicKey) -> Option<IssuanceResponse> {
        let (class_name, issuer, resource_set, not_after, issued) = self.unwrap();

        issued
            .into_iter()
            .find(|issued| issued.cert().subject_public_key_info() == key)
            .map(|issued| {
                IssuanceResponse::new(class_name, issuer, resource_set, not_after, issued)
            })
    }
}

impl fmt::Display for EntitlementClass {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let issued: Vec<String> = self
            .issued
            .iter()
            .map(|c| c.cert().subject_key_identifier().to_string())
            .collect();

        let issued = issued.join(",");

        write!(
            f,
            "class name '{}' issuing key '{}' resources '{}' issued '{}'",
            self.class_name,
            self.issuer.cert.subject_key_identifier(),
            self.resource_set,
            issued
        )
    }
}

//------------ SigningCert ---------------------------------------------------

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SigningCert {
    uri: uri::Rsync,
    cert: Cert,
}

impl SigningCert {
    pub fn new(uri: uri::Rsync, cert: Cert) -> Self {
        SigningCert { uri, cert }
    }

    pub fn uri(&self) -> &uri::Rsync {
        &self.uri
    }
    pub fn cert(&self) -> &Cert {
        &self.cert
    }
}

impl PartialEq for SigningCert {
    fn eq(&self, other: &SigningCert) -> bool {
        self.uri == other.uri
            && self.cert.to_captured().as_slice() == other.cert.to_captured().as_slice()
    }
}

impl Eq for SigningCert {}

impl From<&RcvdCert> for SigningCert {
    fn from(c: &RcvdCert) -> Self {
        SigningCert {
            uri: c.uri().clone(),
            cert: c.cert().clone(),
        }
    }
}

//------------ IssuanceRequest -----------------------------------------------

/// This type reflects the content of a Certificate Issuance Request
/// defined in section 3.4.1 of RFC6492.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct IssuanceRequest {
    class_name: ResourceClassName,
    limit: RequestResourceLimit,
    csr: Csr,
}

impl IssuanceRequest {
    pub fn new(class_name: ResourceClassName, limit: RequestResourceLimit, csr: Csr) -> Self {
        IssuanceRequest {
            class_name,
            limit,
            csr,
        }
    }

    pub fn unwrap(self) -> (ResourceClassName, RequestResourceLimit, Csr) {
        (self.class_name, self.limit, self.csr)
    }

    pub fn class_name(&self) -> &ResourceClassName {
        &self.class_name
    }
    pub fn limit(&self) -> &RequestResourceLimit {
        &self.limit
    }
    pub fn csr(&self) -> &Csr {
        &self.csr
    }
}

impl PartialEq for IssuanceRequest {
    fn eq(&self, other: &IssuanceRequest) -> bool {
        self.class_name == other.class_name
            && self.limit == other.limit
            && self.csr.to_captured().as_slice() == other.csr.to_captured().as_slice()
    }
}

impl Eq for IssuanceRequest {}

impl fmt::Display for IssuanceRequest {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let ki = self.csr.public_key().key_identifier();
        let none = "<none>".to_string();
        let rpki_notify = self
            .csr
            .rpki_notify()
            .map(uri::Https::to_string)
            .unwrap_or_else(|| none.clone());
        let ca_repo = self
            .csr
            .ca_repository()
            .map(uri::Rsync::to_string)
            .unwrap_or_else(|| none.clone());
        let rpki_manifest = self
            .csr
            .rpki_manifest()
            .map(uri::Rsync::to_string)
            .unwrap_or_else(|| none.clone());

        write!(
            f,
            "class name '{}' limit '{}' csr for key '{}' rrdp notify '{}' ca repo '{}' mft '{}'",
            self.class_name, self.limit, ki, rpki_notify, ca_repo, rpki_manifest
        )
    }
}

//------------ IssuanceResponse ----------------------------------------------

/// A Certificate Issuance Response equivalent to the one defined in
/// section 3.4.2 of RFC6492.
///
/// Note that this is like a single EntitlementClass response, except that
/// it includes the one certificate which has just been issued only.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct IssuanceResponse {
    class_name: ResourceClassName,
    issuer: SigningCert,
    resource_set: ResourceSet, // resources allowed on a cert
    not_after: Time,
    issued: IssuedCert,
}

impl IssuanceResponse {
    pub fn new(
        class_name: ResourceClassName,
        issuer: SigningCert,
        resource_set: ResourceSet, // resources allowed on a cert
        not_after: Time,
        issued: IssuedCert,
    ) -> Self {
        IssuanceResponse {
            class_name,
            issuer,
            resource_set,
            not_after,
            issued,
        }
    }

    pub fn unwrap(self) -> (ResourceClassName, SigningCert, ResourceSet, IssuedCert) {
        (self.class_name, self.issuer, self.resource_set, self.issued)
    }

    pub fn class_name(&self) -> &ResourceClassName {
        &self.class_name
    }

    pub fn issuer(&self) -> &SigningCert {
        &self.issuer
    }

    pub fn resource_set(&self) -> &ResourceSet {
        &self.resource_set
    }

    pub fn not_after(&self) -> Time {
        self.not_after
    }

    pub fn issued(&self) -> &IssuedCert {
        &self.issued
    }
}

//------------ RequestResourceLimit ------------------------------------------

/// The scope of resources that a child CA wants to have certified. By default
/// there are no limits, i.e. all the child wants all resources the parent is
/// willing to give. Only if some values are specified for certain resource
/// types will the scope be limited for that type only. Note that asking for
/// more than you are entitled to as a child, will anger a parent. In this case
/// the IssuanceRequest will be rejected.
///
/// See: https://tools.ietf.org/html/rfc6492#section-3.4.1
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct RequestResourceLimit {
    #[serde(
        deserialize_with = "ext_serde::de_as_blocks_opt",
        serialize_with = "ext_serde::ser_as_blocks_opt"
    )]
    asn: Option<AsBlocks>,

    #[serde(
        deserialize_with = "ext_serde::de_ip_blocks_4_opt",
        serialize_with = "ext_serde::ser_ip_blocks_4_opt"
    )]
    v4: Option<IpBlocks>,

    #[serde(
        deserialize_with = "ext_serde::de_ip_blocks_6_opt",
        serialize_with = "ext_serde::ser_ip_blocks_6_opt"
    )]
    v6: Option<IpBlocks>,
}

impl RequestResourceLimit {
    pub fn new() -> RequestResourceLimit {
        Self::default()
    }

    pub fn is_empty(&self) -> bool {
        self.asn == None && self.v4 == None && self.v6 == None
    }

    pub fn with_asn(&mut self, asn: AsBlocks) {
        self.asn = Some(asn);
    }

    pub fn with_ipv4(&mut self, ipv4: IpBlocks) {
        self.v4 = Some(ipv4);
    }

    pub fn with_ipv6(&mut self, ipv6: IpBlocks) {
        self.v6 = Some(ipv6);
    }

    pub fn asn(&self) -> Option<&AsBlocks> {
        self.asn.as_ref()
    }

    pub fn v4(&self) -> Option<&IpBlocks> {
        self.v4.as_ref()
    }

    pub fn v6(&self) -> Option<&IpBlocks> {
        self.v6.as_ref()
    }
}

impl Default for RequestResourceLimit {
    fn default() -> Self {
        RequestResourceLimit {
            asn: None,
            v4: None,
            v6: None,
        }
    }
}

impl fmt::Display for RequestResourceLimit {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let all = "all".to_string();
        let v4_string = self
            .v4
            .as_ref()
            .map(|blocks| IpBlocksForFamily::v4(blocks).to_string())
            .unwrap_or_else(|| all.clone());
        let v6_string = self
            .v6
            .as_ref()
            .map(|blocks| IpBlocksForFamily::v6(blocks).to_string())
            .unwrap_or_else(|| all.clone());
        let asn_string = self
            .asn
            .as_ref()
            .map(AsBlocks::to_string)
            .unwrap_or_else(|| all);

        write!(
            f,
            "v4 '{}' v6 '{}' asn '{}'",
            v4_string, v6_string, asn_string
        )
    }
}

//------------ RevocationRequest ---------------------------------------------

/// This type represents a Certificate Revocation Request as
/// defined in section 3.5.1 of RFC6492.
#[derive(Clone, Debug, Deserialize, Display, Eq, PartialEq, Serialize)]
#[display(fmt = "class name '{}' key '{}'", class_name, key)]
pub struct RevocationRequest {
    class_name: ResourceClassName,
    key: KeyIdentifier,
}

impl RevocationRequest {
    pub fn new(class_name: ResourceClassName, key: KeyIdentifier) -> Self {
        RevocationRequest { class_name, key }
    }

    pub fn class_name(&self) -> &ResourceClassName {
        &self.class_name
    }
    pub fn key(&self) -> &KeyIdentifier {
        &self.key
    }

    pub fn unpack(self) -> (ResourceClassName, KeyIdentifier) {
        (self.class_name, self.key)
    }
}

//------------ RevocationResponse --------------------------------------------

/// This type represents a Certificate Revocation Response as
/// defined in section 3.5.2 of RFC6492.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct RevocationResponse {
    class_name: ResourceClassName,
    key: KeyIdentifier,
}

impl RevocationResponse {
    pub fn new(class_name: ResourceClassName, key: KeyIdentifier) -> Self {
        RevocationResponse { class_name, key }
    }

    pub fn unpack(self) -> (ResourceClassName, KeyIdentifier) {
        (self.class_name, self.key)
    }

    pub fn class_name(&self) -> &ResourceClassName {
        &self.class_name
    }
    pub fn key(&self) -> &KeyIdentifier {
        &self.key
    }
}

impl From<&RevocationRequest> for RevocationResponse {
    fn from(req: &RevocationRequest) -> Self {
        RevocationResponse {
            class_name: req.class_name.clone(),
            key: req.key,
        }
    }
}

impl From<RevocationRequest> for RevocationResponse {
    fn from(req: RevocationRequest) -> Self {
        RevocationResponse {
            class_name: req.class_name,
            key: req.key,
        }
    }
}