libvault 0.2.2

the libvault is modified from RustyVault
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
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
use std::time::Duration;

use better_default::Default;
use humantime::parse_duration;
use serde::{Deserialize, Serialize};
use tracing::info;

use super::{PkiBackend, PkiBackendInner, types, util::DEFAULT_MAX_TTL};
use crate::{
    errors::RvError,
    logical::{Backend, Field, FieldType, Operation, Path, Request, Response, field::FieldTrait},
    storage::StorageEntry,
    utils::{deserialize_duration, serialize_duration},
};

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RoleEntry {
    #[serde(
        serialize_with = "serialize_duration",
        deserialize_with = "deserialize_duration"
    )]
    pub ttl: Duration,
    #[serde(
        serialize_with = "serialize_duration",
        deserialize_with = "deserialize_duration"
    )]
    #[default(DEFAULT_MAX_TTL)]
    pub max_ttl: Duration,
    #[serde(
        serialize_with = "serialize_duration",
        deserialize_with = "deserialize_duration"
    )]
    pub not_before_duration: Duration,
    #[default("rsa".to_string())]
    pub key_type: String,
    #[default(2048)]
    pub key_bits: u32,
    #[default(256)]
    pub signature_bits: u32,
    pub use_pss: bool,
    #[default(true)]
    pub allow_localhost: bool,
    #[default(true)]
    pub allow_bare_domains: bool,
    #[default(true)]
    pub allow_subdomains: bool,
    #[default(true)]
    pub allow_any_name: bool,
    #[default(true)]
    pub allow_ip_sans: bool,
    pub server_flag: bool,
    pub client_flag: bool,
    #[default(true)]
    pub use_csr_sans: bool,
    #[default(true)]
    pub use_csr_common_name: bool,
    pub key_usage: Vec<String>,
    pub ext_key_usage: Vec<String>,
    pub country: String,
    pub province: String,
    pub locality: String,
    pub organization: String,
    pub ou: String,
    pub street_address: String,
    pub postal_code: String,
    #[default(true)]
    pub no_store: bool,
    pub generate_lease: bool,
    pub not_after: String,
}

impl PkiBackend {
    pub fn roles_path(&self) -> Path {
        let backend_read = self.inner.clone();
        let backend_write = self.inner.clone();
        let backend_delete = self.inner.clone();

        Path::builder()
            .pattern(r"roles/(?P<cert_type>tls|ssh)/(?P<name>\w[\w-]*)")
            .field(
                "cert_type",
                Field::builder()
                    .field_type(FieldType::Str)
                    .required(true)
                    .description("Certificate type: tls or ssh"),
            )
            .field(
                "name",
                Field::builder()
                    .field_type(FieldType::Str)
                    .required(true)
                    .description("Name of the role."),
            )
            // SSH-specific fields
            .field(
                "cert_type_ssh",
                Field::builder()
                    .field_type(FieldType::Str)
                    .default_value("user")
                    .description("SSH certificate type: user or host"),
            )
            .field(
                "allowed_users",
                Field::builder()
                    .field_type(FieldType::Str)
                    .description("Comma-separated list of allowed users (SSH)"),
            )
            .field(
                "ttl",
                Field::builder()
                    .field_type(FieldType::Str)
                    .description(
                        r#"
The lease duration (validity period of the certificate) if no specific lease
duration is requested. The lease duration controls the expiration of certificates
issued by this backend. defaults to the system default value or the value of
max_ttl, whichever is shorter."#,
                    ),
            )
            .field(
                "max_ttl",
                Field::builder()
                    .field_type(FieldType::Str)
                    .description(
                        r#"
        The maximum allowed lease duration. If not set, defaults to the system maximum lease TTL."#,
                    ),
            )
            .field(
                "use_pss",
                Field::builder()
                    .field_type(FieldType::Bool)
                    .default_value(false)
                    .description(
                        r#"
        Whether or not to use PSS signatures when using a RSA key-type issuer. Defaults to false."#,
                    ),
            )
            .field(
                "allow_localhost",
                Field::builder()
                    .field_type(FieldType::Bool)
                    .default_value(true)
                    .description(
                        r#"
Whether to allow "localhost" and "localdomain" as a valid common name in a request,
independent of allowed_domains value."#,
                    ),
            )
            .field(
                "allowed_domains",
                Field::builder()
                    .field_type(FieldType::Str)
                    .description(
                        r#"
Specifies the domains this role is allowed to issue certificates for.
This is used with the allow_bare_domains, allow_subdomains, and allow_glob_domains
to determine matches for the common name, DNS-typed SAN entries, and Email-typed
SAN entries of certificates. See the documentation for more information.
This parameter accepts a comma-separated string or list of domains."#,
                    ),
            )
            .field(
                "allow_bare_domains",
                Field::builder()
                    .field_type(FieldType::Bool)
                    .default_value(false)
                    .description(
                        r#"
If set, clients can request certificates for the base domains themselves,
e.g. "example.com" of domains listed in allowed_domains. This is a separate
option as in some cases this can be considered a security threat.
See the documentation for more information."#,
                    ),
            )
            .field(
                "allow_subdomains",
                Field::builder()
                    .field_type(FieldType::Bool)
                    .default_value(false)
                    .description(
                        r#"
If set, clients can request certificates for subdomains of domains listed in
allowed_domains, including wildcard subdomains. See the documentation for more information."#,
                    ),
            )
            .field(
                "allow_any_name",
                Field::builder()
                    .field_type(FieldType::Bool)
                    .default_value(false)
                    .description(
                        r#"
If set, clients can request certificates for any domain, regardless of allowed_domains restrictions.
See the documentation for more information."#,
                    ),
            )
            .field(
                "allow_ip_sans",
                Field::builder()
                    .field_type(FieldType::Bool)
                    .default_value(true)
                    .description(
                        r#"
        If set, IP Subject Alternative Names are allowed. Any valid IP is accepted and No authorization checking is performed."#,
                    ),
            )
            .field(
                "server_flag",
                Field::builder()
                    .field_type(FieldType::Bool)
                    .default_value(true)
                    .description(
                        r#"
        If set, certificates are flagged for server auth use. defaults to true. See also RFC 5280 Section 4.2.1.12."#,
                    ),
            )
            .field(
                "client_flag",
                Field::builder()
                    .field_type(FieldType::Bool)
                    .default_value(true)
                    .description(
                        r#"
        If set, certificates are flagged for client auth use. defaults to true. See also RFC 5280 Section 4.2.1.12."#,
                    ),
            )
            .field(
                "code_signing_flag",
                Field::builder()
                    .field_type(FieldType::Bool)
                    .description(
                        r#"
        If set, certificates are flagged for code signing use. defaults to false. See also RFC 5280 Section 4.2.1.12."#,
                    ),
            )
            .field(
                "key_type",
                Field::builder()
                    .field_type(FieldType::Str)
                    .default_value("rsa")
                    .description(
                        r#"
        The type of key to use; defaults to RSA. "rsa" "ec", "ed25519" and "any" are the only valid values."#,
                    ),
            )
            .field(
                "key_bits",
                Field::builder()
                    .field_type(FieldType::Int)
                    .default_value(0)
                    .description(
                        r#"
The number of bits to use. Allowed values are 0 (universal default); with rsa
key_type: 2048 (default), 3072, or 4096; with ec key_type: 224, 256 (default),
384, or 521; ignored with ed25519."#,
                    ),
            )
            .field(
                "signature_bits",
                Field::builder()
                    .field_type(FieldType::Int)
                    .default_value(0)
                    .description(
                        r#"
The number of bits to use in the signature algorithm; accepts 256 for SHA-2-256,
384 for SHA-2-384, and 512 for SHA-2-512. defaults to 0 to automatically detect
based on key length (SHA-2-256 for RSA keys, and matching the curve size for NIST P-Curves)."#,
                    ),
            )
            .field(
                "key_usage",
                Field::builder()
                    .field_type(FieldType::CommaStringSlice)
                    .default_value("DigitalSignature,KeyAgreement,KeyEncipherment")
                    .description(
                        r#"
A comma-separated string or list of key usages (not extended key usages).
Valid values can be found at https://golang.org/pkg/crypto/x509/#KeyUsage
-- simply drop the "KeyUsage" part of the name.
To remove all key usages from being set, set this value to an empty list. See also RFC 5280 Section 4.2.1.3.
                    "#,
                    ),
            )
            .field(
                "ext_key_usage",
                Field::builder()
                    .field_type(FieldType::CommaStringSlice)
                    .description(
                        r#"
A comma-separated string or list of extended key usages. Valid values can be found at
https://golang.org/pkg/crypto/x509/#ExtKeyUsage -- simply drop the "ExtKeyUsage" part of the name.
To remove all key usages from being set, set this value to an empty list. See also RFC 5280 Section 4.2.1.12.
                    "#,
                    ),
            )
            .field(
                "not_before_duration",
                Field::builder()
                    .field_type(FieldType::Int)
                    .default_value(30)
                    .description(
                        r#"
        The duration before now which the certificate needs to be backdated by."#,
                    ),
            )
            .field(
                "not_after",
                Field::builder()
                    .field_type(FieldType::Str)
                    .default_value("")
                    .description(
                        r#"
Set the not after field of the certificate with specified date value.
The value format should be given in UTC format YYYY-MM-ddTHH:MM:SSZ."#,
                    ),
            )
            .field(
                "ou",
                Field::builder()
                    .field_type(FieldType::Str)
                    .description(
                        r#"
        If set, OU (OrganizationalUnit) will be set to this value in certificates issued by this role."#,
                    ),
            )
            .field(
                "organization",
                Field::builder()
                    .field_type(FieldType::Str)
                    .description(
                        r#"
        If set, O (Organization) will be set to this value in certificates issued by this role."#,
                    ),
            )
            .field(
                "country",
                Field::builder()
                    .field_type(FieldType::Str)
                    .description(
                        r#"
        If set, Country will be set to this value in certificates issued by this role."#,
                    ),
            )
            .field(
                "locality",
                Field::builder()
                    .field_type(FieldType::Str)
                    .description(
                        r#"
        If set, Locality will be set to this value in certificates issued by this role."#,
                    ),
            )
            .field(
                "province",
                Field::builder()
                    .field_type(FieldType::Str)
                    .description(
                        r#"
        If set, Province will be set to this value in certificates issued by this role."#,
                    ),
            )
            .field(
                "street_address",
                Field::builder()
                    .field_type(FieldType::Str)
                    .description(
                        r#"
        If set, Street Address will be set to this value."#,
                    ),
            )
            .field(
                "postal_code",
                Field::builder()
                    .field_type(FieldType::Str)
                    .description(
                        r#"
        If set, Postal Code will be set to this value."#,
                    ),
            )
            .field(
                "use_csr_common_name",
                Field::builder()
                    .field_type(FieldType::Bool)
                    .default_value(true)
                    .description(
                        r#"
If set, when used with a signing profile, the common name in the CSR will be used. This
does *not* include any requested Subject Alternative Names; use use_csr_sans for that. defaults to true."#,
                    ),
            )
            .field(
                "use_csr_sans",
                Field::builder()
                    .field_type(FieldType::Bool)
                    .default_value(true)
                    .description(
                        r#"
If set, when used with a signing profile, the SANs in the CSR will be used. This does *not*
include the Common Name (cn); use use_csr_common_name for that. defaults to true."#,
                    ),
            )
            .field(
                "generate_lease",
                Field::builder()
                    .field_type(FieldType::Bool)
                    .default_value(false)
                    .description(
                        r#"
If set, certificates issued/signed against this role will have RustyVault leases
attached to them. Defaults to "false". Certificates can be added to the CRL by
"vault revoke <lease_id>" when certificates are associated with leases.  It can
also be done using the "pki/revoke" endpoint. However, when lease generation is
disabled, invoking "pki/revoke" would be the only way to add the certificates
to the CRL.  When large number of certificates are generated with long
lifetimes, it is recommended that lease generation be disabled, as large amount of
leases adversely affect the startup time of RustyVault."#,
                    ),
            )
            .field(
                "no_store",
                Field::builder()
                    .field_type(FieldType::Bool)
                    .default_value(false)
                    .description(
                        r#"
If set, certificates issued/signed against this role will not be stored in the
storage backend. This can improve performance when issuing large numbers of
certificates. However, certificates issued in this way cannot be enumerated
or revoked, so this option is recommended only for certificates that are
non-sensitive, or extremely short-lived. This option implies a value of "false"
for "generate_lease"."#,
                    ),
            )
            .operation(Operation::Read, {
                let handler = backend_read.clone();
                move |backend, req| {
                    let handler = handler.clone();
                    Box::pin(async move { handler.dispatch_read_role(backend, req).await })
                }
            })
            .operation(Operation::Write, {
                let handler = backend_write.clone();
                move |backend, req| {
                    let handler = handler.clone();
                    Box::pin(async move { handler.dispatch_write_role(backend, req).await })
                }
            })
            .operation(Operation::Delete, {
                let handler = backend_delete.clone();
                move |backend, req| {
                    let handler = handler.clone();
                    Box::pin(async move { handler.dispatch_delete_role(backend, req).await })
                }
            })
            .help("This path lets you manage the roles that can be created with this backend.")
            .build()
    }
}

impl PkiBackendInner {
    // ── Dispatch ──

    pub async fn dispatch_read_role(
        &self,
        backend: &dyn Backend,
        req: &mut Request,
    ) -> Result<Option<Response>, RvError> {
        let ct = req.get_data("cert_type")?;
        let ct = ct.as_str().ok_or(RvError::ErrRequestFieldInvalid)?;
        match ct {
            "tls" => self.read_path_role(backend, req).await,
            "ssh" => self.read_ssh_role(backend, req).await,
            _ => Err(RvError::ErrRequestFieldInvalid),
        }
    }

    pub async fn dispatch_write_role(
        &self,
        backend: &dyn Backend,
        req: &mut Request,
    ) -> Result<Option<Response>, RvError> {
        let ct = req.get_data("cert_type")?;
        let ct = ct.as_str().ok_or(RvError::ErrRequestFieldInvalid)?;
        match ct {
            "tls" => self.create_path_role(backend, req).await,
            "ssh" => self.create_ssh_role(backend, req).await,
            _ => Err(RvError::ErrRequestFieldInvalid),
        }
    }

    pub async fn dispatch_delete_role(
        &self,
        backend: &dyn Backend,
        req: &mut Request,
    ) -> Result<Option<Response>, RvError> {
        let ct = req.get_data("cert_type")?;
        let ct = ct.as_str().ok_or(RvError::ErrRequestFieldInvalid)?;
        match ct {
            "tls" => self.delete_path_role(backend, req).await,
            "ssh" => self.delete_ssh_role(backend, req).await,
            _ => Err(RvError::ErrRequestFieldInvalid),
        }
    }

    // ── TLS roles ──
    pub async fn get_role(
        &self,
        req: &mut Request,
        name: &str,
    ) -> Result<Option<RoleEntry>, RvError> {
        let key = format!("roles/tls/{name}");
        let storage_entry = req.storage_get(&key).await?;
        if storage_entry.is_none() {
            return Ok(None);
        }

        let entry = storage_entry.unwrap();
        let role_entry: RoleEntry = serde_json::from_slice(entry.value.as_slice())?;
        Ok(Some(role_entry))
    }

    pub async fn read_path_role(
        &self,
        _backend: &dyn Backend,
        req: &mut Request,
    ) -> Result<Option<Response>, RvError> {
        let role_entry = self
            .get_role(
                req,
                req.get_data("name")?
                    .as_str()
                    .ok_or(RvError::ErrRequestFieldInvalid)?,
            )
            .await?;
        let role_entry = match role_entry {
            Some(r) => r,
            None => return Err(RvError::ErrPkiRoleNotFound),
        };
        let data = serde_json::to_value(role_entry)?;
        Ok(Some(Response::data_response(Some(
            data.as_object().unwrap().clone(),
        ))))
    }

    pub async fn create_path_role(
        &self,
        _backend: &dyn Backend,
        req: &mut Request,
    ) -> Result<Option<Response>, RvError> {
        let name_value = req.get_data("name")?;
        let name = name_value.as_str().ok_or(RvError::ErrRequestFieldInvalid)?;
        let mut ttl = DEFAULT_MAX_TTL;
        if let Ok(ttl_value) = req.get_data("ttl") {
            let ttl_str = ttl_value.as_str().ok_or(RvError::ErrRequestFieldInvalid)?;
            if !ttl_str.is_empty() {
                ttl = parse_duration(ttl_str)?;
            }
        }
        let mut max_ttl = DEFAULT_MAX_TTL;
        if let Ok(max_ttl_value) = req.get_data("max_ttl") {
            let max_ttl_str = max_ttl_value
                .as_str()
                .ok_or(RvError::ErrRequestFieldInvalid)?;
            if !max_ttl_str.is_empty() {
                max_ttl = parse_duration(max_ttl_str)?;
            }
        }
        let key_type_value = req.get_data_or_default("key_type")?;
        let key_type = key_type_value
            .as_str()
            .ok_or(RvError::ErrRequestFieldInvalid)?;
        let mut key_bits = req
            .get_data_or_default("key_bits")?
            .as_u64()
            .ok_or(RvError::ErrRequestFieldInvalid)?;
        match key_type {
            "rsa" => {
                if key_bits == 0 {
                    key_bits = 2048;
                }

                if key_bits != 2048 && key_bits != 3072 && key_bits != 4096 {
                    return Err(RvError::ErrPkiKeyBitsInvalid);
                }
            }
            "ec" => {
                if key_bits == 0 {
                    key_bits = 256;
                }

                if key_bits != 224 && key_bits != 256 && key_bits != 384 && key_bits != 512 {
                    return Err(RvError::ErrPkiKeyBitsInvalid);
                }
            }
            #[cfg(feature = "crypto_adaptor_tongsuo")]
            "sm2" => {
                if key_bits == 0 {
                    key_bits = 256;
                }

                if key_bits != 256 {
                    return Err(RvError::ErrPkiKeyBitsInvalid);
                }
            }
            _ => {
                return Err(RvError::ErrPkiKeyTypeInvalid);
            }
        }

        let signature_bits = req
            .get_data_or_default("signature_bits")?
            .as_u64()
            .ok_or(RvError::ErrRequestFieldInvalid)?;
        let allow_localhost = req
            .get_data_or_default("allow_localhost")?
            .as_bool()
            .ok_or(RvError::ErrRequestFieldInvalid)?;
        let allow_bare_domains = req
            .get_data_or_default("allow_bare_domains")?
            .as_bool()
            .ok_or(RvError::ErrRequestFieldInvalid)?;
        let allow_subdomains = req
            .get_data_or_default("allow_subdomains")?
            .as_bool()
            .ok_or(RvError::ErrRequestFieldInvalid)?;
        let allow_any_name = req
            .get_data_or_default("allow_any_name")?
            .as_bool()
            .ok_or(RvError::ErrRequestFieldInvalid)?;
        let allow_ip_sans = req
            .get_data_or_default("allow_ip_sans")?
            .as_bool()
            .ok_or(RvError::ErrRequestFieldInvalid)?;
        let server_flag = req
            .get_data_or_default("server_flag")?
            .as_bool()
            .ok_or(RvError::ErrRequestFieldInvalid)?;
        let client_flag = req
            .get_data_or_default("client_flag")?
            .as_bool()
            .ok_or(RvError::ErrRequestFieldInvalid)?;
        let use_csr_sans = req
            .get_data_or_default("use_csr_sans")?
            .as_bool()
            .ok_or(RvError::ErrRequestFieldInvalid)?;
        let use_csr_common_name = req
            .get_data_or_default("use_csr_common_name")?
            .as_bool()
            .ok_or(RvError::ErrRequestFieldInvalid)?;
        let key_usage = req
            .get_data_or_default("key_usage")?
            .as_comma_string_slice()
            .ok_or(RvError::ErrRequestFieldInvalid)?;
        let ext_key_usage = req
            .get_data_or_default("ext_key_usage")?
            .as_comma_string_slice()
            .ok_or(RvError::ErrRequestFieldInvalid)?;
        let country = req
            .get_data_or_default("country")?
            .as_str()
            .ok_or(RvError::ErrRequestFieldInvalid)?
            .to_string();
        let province = req
            .get_data_or_default("province")?
            .as_str()
            .ok_or(RvError::ErrRequestFieldInvalid)?
            .to_string();
        let locality = req
            .get_data_or_default("locality")?
            .as_str()
            .ok_or(RvError::ErrRequestFieldInvalid)?
            .to_string();
        let organization = req
            .get_data_or_default("organization")?
            .as_str()
            .ok_or(RvError::ErrRequestFieldInvalid)?
            .to_string();
        let ou = req
            .get_data_or_default("ou")?
            .as_str()
            .ok_or(RvError::ErrRequestFieldInvalid)?
            .to_string();
        let street_address = req
            .get_data_or_default("street_address")?
            .as_str()
            .ok_or(RvError::ErrRequestFieldInvalid)?
            .to_string();
        let postal_code = req
            .get_data_or_default("postal_code")?
            .as_str()
            .ok_or(RvError::ErrRequestFieldInvalid)?
            .to_string();
        let no_store = req
            .get_data_or_default("no_store")?
            .as_bool()
            .ok_or(RvError::ErrRequestFieldInvalid)?;
        let generate_lease = req
            .get_data_or_default("generate_lease")?
            .as_bool()
            .ok_or(RvError::ErrRequestFieldInvalid)?;
        let not_after = req
            .get_data_or_default("not_after")?
            .as_str()
            .ok_or(RvError::ErrRequestFieldInvalid)?
            .to_string();
        let not_before_duration_u64 = req
            .get_data_or_default("not_before_duration")?
            .as_u64()
            .ok_or(RvError::ErrRequestFieldInvalid)?;
        let not_before_duration = Duration::from_secs(not_before_duration_u64);

        let role_entry = RoleEntry {
            ttl,
            max_ttl,
            key_type: key_type.to_string(),
            key_bits: key_bits as u32,
            signature_bits: signature_bits as u32,
            allow_localhost,
            allow_bare_domains,
            allow_subdomains,
            allow_any_name,
            allow_ip_sans,
            server_flag,
            client_flag,
            use_csr_sans,
            use_csr_common_name,
            key_usage,
            ext_key_usage,
            country,
            province,
            locality,
            organization,
            ou,
            no_store,
            generate_lease,
            not_after,
            not_before_duration,
            street_address,
            postal_code,
            ..Default::default()
        };

        let entry = StorageEntry::new(format!("roles/tls/{name}").as_str(), &role_entry)?;

        req.storage_put(&entry).await?;

        Ok(None)
    }

    pub async fn delete_path_role(
        &self,
        _backend: &dyn Backend,
        req: &mut Request,
    ) -> Result<Option<Response>, RvError> {
        let name_value = req.get_data("name")?;
        let name = name_value.as_str().ok_or(RvError::ErrRequestFieldInvalid)?;
        if name.is_empty() {
            return Err(RvError::ErrRequestNoDataField);
        }

        req.storage_delete(format!("roles/tls/{name}").as_str())
            .await?;
        Ok(None)
    }

    // ── SSH roles ──

    pub async fn get_ssh_role(
        &self,
        req: &mut Request,
        name: &str,
    ) -> Result<Option<types::SshRoleEntry>, RvError> {
        let key = format!("roles/ssh/{name}");
        let entry = req.storage_get(&key).await?;
        if entry.is_none() {
            return Ok(None);
        }
        let role: types::SshRoleEntry = serde_json::from_slice(entry.unwrap().value.as_slice())?;
        Ok(Some(role))
    }

    pub async fn read_ssh_role(
        &self,
        _backend: &dyn Backend,
        req: &mut Request,
    ) -> Result<Option<Response>, RvError> {
        let name_value = req.get_data("name")?;
        let name = name_value.as_str().ok_or(RvError::ErrRequestFieldInvalid)?;
        let role = match self.get_ssh_role(req, name).await? {
            Some(r) => r,
            None => return Err(RvError::ErrPkiSshRoleNotFound),
        };
        let data = serde_json::to_value(role)?;
        Ok(Some(Response::data_response(Some(
            data.as_object().unwrap().clone(),
        ))))
    }

    pub async fn create_ssh_role(
        &self,
        _backend: &dyn Backend,
        req: &mut Request,
    ) -> Result<Option<Response>, RvError> {
        let name_value = req.get_data("name")?;
        let name = name_value.as_str().ok_or(RvError::ErrRequestFieldInvalid)?;

        let cert_type = req
            .get_data_or_default("cert_type_ssh")?
            .as_str()
            .ok_or(RvError::ErrRequestFieldInvalid)?
            .to_string();
        if cert_type != "user" && cert_type != "host" {
            return Err(RvError::ErrPkiSshCertTypeInvalid);
        }

        let key_type = req
            .get_data_or_default("key_type")?
            .as_str()
            .ok_or(RvError::ErrRequestFieldInvalid)?
            .to_string();
        match key_type.as_str() {
            "rsa" | "ec" | "ed25519" => {}
            _ => return Err(RvError::ErrPkiKeyTypeInvalid),
        }

        let key_bits = req
            .get_data_or_default("key_bits")?
            .as_u64()
            .ok_or(RvError::ErrRequestFieldInvalid)? as u32;
        match key_type.as_str() {
            "rsa" => {
                if key_bits != 0 && !(2048..=8192).contains(&key_bits) {
                    return Err(RvError::ErrPkiKeyBitsInvalid);
                }
            }
            "ec" => {
                if !matches!(key_bits, 0 | 256 | 384 | 521) {
                    return Err(RvError::ErrPkiKeyBitsInvalid);
                }
            }
            "ed25519" => {}
            _ => {}
        }

        let ttl_str = req
            .get_data_or_default("ttl")?
            .as_str()
            .ok_or(RvError::ErrRequestFieldInvalid)?
            .to_string();
        let ttl = if ttl_str.is_empty() {
            Duration::from_secs(3600)
        } else {
            parse_duration(&ttl_str)?
        };

        let mut allowed_users = Vec::new();
        if let Ok(users_val) = req.get_data("allowed_users")
            && let Some(users_str) = users_val.as_str()
            && !users_str.is_empty()
        {
            allowed_users = users_str.split(',').map(|s| s.trim().to_string()).collect();
        }

        let role = types::SshRoleEntry {
            cert_type,
            key_type,
            key_bits,
            ttl,
            allowed_users,
            ..Default::default()
        };

        let entry = StorageEntry::new(format!("roles/ssh/{name}").as_str(), &role)?;
        req.storage_put(&entry).await?;

        info!(
            role = %name,
            cert_type = %role.cert_type,
            key_type = %role.key_type,
            key_bits = key_bits,
            "SSH role created"
        );

        Ok(None)
    }

    pub async fn delete_ssh_role(
        &self,
        _backend: &dyn Backend,
        req: &mut Request,
    ) -> Result<Option<Response>, RvError> {
        let name_value = req.get_data("name")?;
        let name = name_value.as_str().ok_or(RvError::ErrRequestFieldInvalid)?;
        req.storage_delete(format!("roles/ssh/{name}").as_str())
            .await?;
        Ok(None)
    }
}