openbao 1.0.2

Secure, typed, async Rust SDK for OpenBao
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
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
//! LDAP secrets engine support.
//!
//! The LDAP secrets engine can manage static LDAP account passwords, generate
//! dynamic LDAP accounts, and broker access to pre-existing service accounts
//! through library sets.

use core::fmt;
use std::collections::BTreeMap;

use reqwest::{Method, StatusCode};
use secrecy::{ExposeSecret, SecretString};
use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Visitor, ser::SerializeMap};

use crate::{
    Authenticated, Client, Error, Result,
    path::{validate_endpoint_path, validate_mount_path},
    response::{Empty, ListEntries, ResponseEnvelope, deserialize_bounded_string_vec},
    validation::validate_duration_string,
};

/// Handle for a mounted LDAP secrets engine.
#[derive(Debug)]
pub struct Ldap<'a> {
    client: &'a Client<Authenticated>,
    mount: Vec<String>,
}

/// LDAP secrets engine configuration.
#[derive(Clone, Deserialize)]
pub struct LdapConfig {
    /// Distinguished name used by OpenBao to manage LDAP entries.
    pub binddn: String,
    /// Password used with `binddn`.
    pub bindpass: SecretString,
    /// LDAP server URL or comma-separated URL list.
    #[serde(default)]
    pub url: Option<String>,
    /// Password policy used for generated LDAP passwords.
    #[serde(default)]
    pub password_policy: Option<String>,
    /// LDAP schema, such as `openldap`, `ad`, or `racf`.
    #[serde(default)]
    pub schema: Option<String>,
    /// Base DN used for user search.
    #[serde(default)]
    pub userdn: Option<String>,
    /// Attribute used for user search.
    #[serde(default)]
    pub userattr: Option<String>,
    /// UPN domain for Active Directory.
    #[serde(default)]
    pub upndomain: Option<String>,
    /// Connection timeout as seconds or OpenBao duration string.
    #[serde(default, deserialize_with = "deserialize_optional_string_or_u64")]
    pub connection_timeout: Option<String>,
    /// Request timeout as seconds or OpenBao duration string.
    #[serde(default, deserialize_with = "deserialize_optional_string_or_u64")]
    pub request_timeout: Option<String>,
    /// Whether to use StartTLS.
    #[serde(default)]
    pub starttls: Option<bool>,
    /// Whether to skip LDAP TLS certificate verification.
    #[serde(default)]
    pub insecure_tls: Option<bool>,
    /// CA certificate for LDAP TLS verification.
    #[serde(default)]
    pub certificate: Option<String>,
    /// Client TLS certificate.
    #[serde(default)]
    pub client_tls_cert: Option<String>,
    /// Client TLS private key.
    #[serde(default)]
    pub client_tls_key: Option<SecretString>,
    /// Generated password length.
    #[serde(default)]
    pub length: Option<u64>,
}

impl LdapConfig {
    /// Creates an LDAP config with the required bind DN and password.
    pub fn new(binddn: impl Into<String>, bindpass: SecretString) -> Self {
        Self {
            binddn: binddn.into(),
            bindpass,
            url: None,
            password_policy: None,
            schema: None,
            userdn: None,
            userattr: None,
            upndomain: None,
            connection_timeout: None,
            request_timeout: None,
            starttls: None,
            insecure_tls: None,
            certificate: None,
            client_tls_cert: None,
            client_tls_key: None,
            length: None,
        }
    }

    /// Sets the LDAP URL.
    #[must_use]
    pub fn with_url(mut self, url: impl Into<String>) -> Self {
        self.url = Some(url.into());
        self
    }

    /// Sets the LDAP schema.
    #[must_use]
    pub fn with_schema(mut self, schema: impl Into<String>) -> Self {
        self.schema = Some(schema.into());
        self
    }

    fn validate(&self) -> Result<()> {
        #[cfg(not(feature = "insecure-ldap-tls-acknowledged"))]
        if self.insecure_tls == Some(true) {
            return Err(crate::Error::InvalidParameter(
                "ldap insecure_tls=true requires the insecure-ldap-tls-acknowledged Cargo feature because it disables LDAP TLS certificate verification".into(),
            ));
        }
        if self.insecure_tls == Some(true) {
            return Err(crate::Error::InvalidParameter(
                "ldap insecure_tls=true must not be combined with bindpass because credentials would cross an unverified TLS connection".into(),
            ));
        }
        #[cfg(not(feature = "insecure-ldap-tls-acknowledged"))]
        validate_ldap_urls_use_encrypted_transport(&self.url, self.starttls, "LDAP")?;
        if let Some(value) = &self.connection_timeout {
            validate_duration_or_seconds(value, "LDAP connection_timeout", true)?;
        }
        if let Some(value) = &self.request_timeout {
            validate_duration_or_seconds(value, "LDAP request_timeout", true)?;
        }
        Ok(())
    }
}

impl fmt::Debug for LdapConfig {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("LdapConfig")
            .field("binddn", &self.binddn)
            .field("bindpass", &"<redacted>")
            .field("url", &self.url)
            .field("password_policy", &self.password_policy)
            .field("schema", &self.schema)
            .field("userdn", &self.userdn)
            .field("userattr", &self.userattr)
            .field("upndomain", &self.upndomain)
            .field("connection_timeout", &self.connection_timeout)
            .field("request_timeout", &self.request_timeout)
            .field("starttls", &self.starttls)
            .field("insecure_tls", &self.insecure_tls)
            .field("certificate", &self.certificate)
            .field("client_tls_cert", &self.client_tls_cert)
            .field(
                "client_tls_key",
                &self.client_tls_key.as_ref().map(|_| "<redacted>"),
            )
            .field("length", &self.length)
            .finish()
    }
}

/// Static LDAP role request and response.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct LdapStaticRole {
    /// Existing LDAP username to manage.
    pub username: String,
    /// Distinguished name for the LDAP entry.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dn: Option<String>,
    /// Rotation period as seconds or OpenBao duration string.
    #[serde(
        default,
        deserialize_with = "deserialize_optional_string_or_u64",
        skip_serializing_if = "Option::is_none"
    )]
    pub rotation_period: Option<String>,
    /// Last rotation timestamp returned by OpenBao.
    #[serde(default, skip_serializing)]
    pub last_vault_rotation: Option<String>,
}

impl LdapStaticRole {
    /// Creates a static role request for an existing LDAP username.
    pub fn new(username: impl Into<String>) -> Self {
        Self {
            username: username.into(),
            ..Self::default()
        }
    }

    /// Sets the static role rotation period.
    pub fn with_rotation_period(mut self, rotation_period: impl Into<String>) -> Result<Self> {
        let rotation_period = rotation_period.into();
        validate_duration_or_seconds(&rotation_period, "LDAP static role rotation_period", false)?;
        self.rotation_period = Some(rotation_period);
        Ok(self)
    }

    /// Sets the static role rotation period from a Rust duration.
    pub fn with_rotation_period_duration(
        self,
        rotation_period: std::time::Duration,
    ) -> Result<Self> {
        self.with_rotation_period(crate::duration::nonzero_duration_to_bao_string(
            rotation_period,
            "LDAP static role rotation_period",
        )?)
    }

    fn validate(&self) -> Result<()> {
        if let Some(value) = &self.rotation_period {
            validate_duration_or_seconds(value, "LDAP static role rotation_period", false)?;
        }
        Ok(())
    }
}

/// List response for LDAP static roles, dynamic roles, or library sets.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct LdapList {
    /// Names returned by OpenBao.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub keys: Vec<String>,
}

impl ListEntries for LdapList {
    fn entries(&self) -> &[String] {
        &self.keys
    }
}

/// Static LDAP credentials.
#[derive(Clone, Deserialize)]
pub struct LdapStaticCredentials {
    /// LDAP username.
    pub username: String,
    /// Distinguished name for the LDAP entry.
    #[serde(default)]
    pub dn: Option<String>,
    /// Current LDAP password.
    pub password: SecretString,
    /// Previous LDAP password, when returned.
    #[serde(default)]
    pub last_password: Option<SecretString>,
    /// Last rotation timestamp.
    #[serde(default)]
    pub last_vault_rotation: Option<String>,
    /// Rotation period in seconds.
    #[serde(default)]
    pub rotation_period: Option<u64>,
    /// Remaining TTL in seconds.
    #[serde(default)]
    pub ttl: Option<u64>,
}

impl fmt::Debug for LdapStaticCredentials {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("LdapStaticCredentials")
            .field("username", &self.username)
            .field("dn", &self.dn)
            .field("password", &"<redacted>")
            .field(
                "last_password",
                &self.last_password.as_ref().map(|_| "<redacted>"),
            )
            .field("last_vault_rotation", &self.last_vault_rotation)
            .field("rotation_period", &self.rotation_period)
            .field("ttl", &self.ttl)
            .finish()
    }
}

/// Dynamic LDAP role request and response.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct LdapDynamicRole {
    /// Templated LDIF used to create a user account.
    pub creation_ldif: String,
    /// Templated LDIF used to delete a user account.
    pub deletion_ldif: String,
    /// Templated LDIF used to roll back failed user creation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rollback_ldif: Option<String>,
    /// Dynamic username template.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub username_template: Option<String>,
    /// Default lease TTL as seconds or OpenBao duration string.
    #[serde(
        default,
        deserialize_with = "deserialize_optional_string_or_u64",
        skip_serializing_if = "Option::is_none"
    )]
    pub default_ttl: Option<String>,
    /// Maximum lease TTL as seconds or OpenBao duration string.
    #[serde(
        default,
        deserialize_with = "deserialize_optional_string_or_u64",
        skip_serializing_if = "Option::is_none"
    )]
    pub max_ttl: Option<String>,
}

impl LdapDynamicRole {
    /// Creates a dynamic role request with required create/delete LDIF.
    pub fn new(creation_ldif: impl Into<String>, deletion_ldif: impl Into<String>) -> Self {
        Self {
            creation_ldif: creation_ldif.into(),
            deletion_ldif: deletion_ldif.into(),
            ..Self::default()
        }
    }

    /// Sets the default lease TTL.
    pub fn with_default_ttl(mut self, default_ttl: impl Into<String>) -> Result<Self> {
        let default_ttl = default_ttl.into();
        validate_duration_or_seconds(&default_ttl, "LDAP dynamic role default_ttl", true)?;
        self.default_ttl = Some(default_ttl);
        Ok(self)
    }

    fn validate(&self) -> Result<()> {
        if let Some(value) = &self.default_ttl {
            validate_duration_or_seconds(value, "LDAP dynamic role default_ttl", true)?;
        }
        if let Some(value) = &self.max_ttl {
            validate_duration_or_seconds(value, "LDAP dynamic role max_ttl", true)?;
        }
        Ok(())
    }
}

/// Generated dynamic LDAP credentials.
#[derive(Clone, Deserialize)]
pub struct LdapDynamicCredentials {
    /// Generated LDAP username.
    pub username: String,
    /// Generated LDAP password.
    pub password: SecretString,
    /// Distinguished names created for this lease.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub distinguished_names: Vec<String>,
    /// Lease ID for revocation/renewal.
    pub lease_id: SecretString,
    /// Lease duration in seconds.
    pub lease_duration: u64,
    /// Whether the lease is renewable.
    pub renewable: bool,
}

impl fmt::Debug for LdapDynamicCredentials {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("LdapDynamicCredentials")
            .field("username", &self.username)
            .field("password", &"<redacted>")
            .field("distinguished_names", &self.distinguished_names)
            .field("lease_id", &"<redacted>")
            .field("lease_duration", &self.lease_duration)
            .field("renewable", &self.renewable)
            .finish()
    }
}

#[derive(Deserialize)]
struct LdapDynamicCredentialData {
    username: String,
    password: SecretString,
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    distinguished_names: Vec<String>,
}

/// LDAP library set request and response.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct LdapLibrarySet {
    /// Service account names in the library set.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub service_account_names: Vec<String>,
    /// Maximum single checkout duration.
    #[serde(
        default,
        deserialize_with = "deserialize_optional_string_or_u64",
        skip_serializing_if = "Option::is_none"
    )]
    pub ttl: Option<String>,
    /// Maximum renewable checkout duration.
    #[serde(
        default,
        deserialize_with = "deserialize_optional_string_or_u64",
        skip_serializing_if = "Option::is_none"
    )]
    pub max_ttl: Option<String>,
    /// Disable same-entity/same-token check-in enforcement.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub disable_check_in_enforcement: Option<bool>,
}

impl LdapLibrarySet {
    /// Creates a library set with service account names.
    pub fn new(service_account_names: impl IntoIterator<Item = impl Into<String>>) -> Self {
        Self {
            service_account_names: service_account_names.into_iter().map(Into::into).collect(),
            ..Self::default()
        }
    }

    /// Sets the checkout TTL.
    pub fn with_ttl(mut self, ttl: impl Into<String>) -> Result<Self> {
        let ttl = ttl.into();
        validate_duration_or_seconds(&ttl, "LDAP library ttl", true)?;
        self.ttl = Some(ttl);
        Ok(self)
    }

    fn validate(&self) -> Result<()> {
        validate_count(
            self.service_account_names.len(),
            "LDAP library service accounts",
            true,
        )?;
        if let Some(value) = &self.ttl {
            validate_duration_or_seconds(value, "LDAP library ttl", true)?;
        }
        if let Some(value) = &self.max_ttl {
            validate_duration_or_seconds(value, "LDAP library max_ttl", true)?;
        }
        Ok(())
    }
}

/// LDAP library status response.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct LdapLibraryStatus {
    /// Service account statuses.
    #[serde(
        default,
        deserialize_with = "deserialize_bounded_library_account_map_or_default"
    )]
    pub service_account_names: BTreeMap<String, LdapLibraryAccountStatus>,
}

/// Status for one LDAP library service account.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct LdapLibraryAccountStatus {
    /// Service account name.
    #[serde(default)]
    pub service_account_name: String,
    /// Whether the service account is checked out.
    #[serde(default)]
    pub checked_out: bool,
    /// Current borrower client token, when returned.
    #[serde(default)]
    pub borrower_client_token: Option<SecretString>,
    /// Current borrower entity ID, when returned.
    #[serde(default)]
    pub borrower_entity_id: Option<String>,
}

/// LDAP library checkout request.
#[derive(Clone, Debug, Default, Serialize)]
pub struct LdapCheckOutRequest {
    /// Requested checkout TTL.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ttl: Option<String>,
}

impl LdapCheckOutRequest {
    /// Creates an empty checkout request.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the requested checkout TTL.
    pub fn with_ttl(mut self, ttl: impl Into<String>) -> Result<Self> {
        let ttl = ttl.into();
        validate_duration_or_seconds(&ttl, "LDAP library checkout ttl", false)?;
        self.ttl = Some(ttl);
        Ok(self)
    }

    fn validate(&self) -> Result<()> {
        if let Some(value) = &self.ttl {
            validate_duration_or_seconds(value, "LDAP library checkout ttl", false)?;
        }
        Ok(())
    }
}

/// LDAP library checkout response.
#[derive(Clone, Deserialize)]
pub struct LdapCheckOut {
    /// Checked-out service account name.
    pub service_account_name: String,
    /// Generated service account password.
    pub password: SecretString,
    /// Lease ID for revocation/renewal.
    pub lease_id: SecretString,
    /// Lease duration in seconds.
    pub lease_duration: u64,
    /// Whether the lease is renewable.
    pub renewable: bool,
}

impl fmt::Debug for LdapCheckOut {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("LdapCheckOut")
            .field("service_account_name", &self.service_account_name)
            .field("password", &"<redacted>")
            .field("lease_id", &"<redacted>")
            .field("lease_duration", &self.lease_duration)
            .field("renewable", &self.renewable)
            .finish()
    }
}

#[derive(Deserialize)]
struct LdapCheckOutData {
    service_account_name: String,
    password: SecretString,
}

/// LDAP library check-in request.
#[derive(Clone, Debug, Default, Serialize)]
pub struct LdapCheckInRequest {
    /// Service account names to check in.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub service_account_names: Vec<String>,
}

impl LdapCheckInRequest {
    /// Creates a check-in request.
    pub fn new(service_account_names: impl IntoIterator<Item = impl Into<String>>) -> Self {
        Self {
            service_account_names: service_account_names.into_iter().map(Into::into).collect(),
        }
    }

    fn validate(&self) -> Result<()> {
        validate_count(
            self.service_account_names.len(),
            "LDAP check-in service accounts",
            false,
        )
    }
}

/// LDAP library check-in response.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct LdapCheckIn {
    /// Service account names checked in by this call.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub check_ins: Vec<String>,
}

impl Client<Authenticated> {
    /// Uses the LDAP secrets engine mounted at `ldap`.
    pub fn ldap(&self) -> Result<Ldap<'_>> {
        self.ldap_at("ldap")
    }

    /// Uses the LDAP secrets engine mounted at `mount`.
    pub fn ldap_at(&self, mount: impl Into<String>) -> Result<Ldap<'_>> {
        let mount = mount.into();
        Ok(Ldap {
            client: self,
            mount: validate_mount_path(&mount)?,
        })
    }
}

impl Ldap<'_> {
    /// Creates or updates LDAP engine configuration.
    pub async fn write_config(&self, config: &LdapConfig) -> Result<Empty> {
        config.validate()?;
        self.client
            .request_json(Method::POST, &self.path(&["config"])?, Some(config))
            .await
    }

    /// Reads LDAP engine configuration.
    pub async fn read_config(&self) -> Result<LdapConfig> {
        let envelope: ResponseEnvelope<LdapConfig> = self
            .client
            .request_json(
                Method::GET,
                &self.path(&["config"])?,
                Option::<&Empty>::None,
            )
            .await?;
        Ok(envelope.data)
    }

    /// Deletes LDAP engine configuration.
    pub async fn delete_config(&self) -> Result<Empty> {
        self.delete_at(&["config"]).await
    }

    /// Rotates the LDAP bind user's password.
    pub async fn rotate_root(&self) -> Result<Empty> {
        self.client
            .request_json(Method::POST, &self.path(&["rotate-root"])?, Some(&Empty {}))
            .await
    }

    /// Creates or updates a static LDAP role.
    pub async fn write_static_role(&self, name: &str, role: &LdapStaticRole) -> Result<Empty> {
        role.validate()?;
        self.client
            .request_json(
                Method::POST,
                &self.path(&["static-role", name])?,
                Some(role),
            )
            .await
    }

    /// Reads a static LDAP role.
    pub async fn read_static_role(&self, name: &str) -> Result<LdapStaticRole> {
        let envelope: ResponseEnvelope<LdapStaticRole> = self
            .client
            .request_json(
                Method::GET,
                &self.path(&["static-role", name])?,
                Option::<&Empty>::None,
            )
            .await?;
        Ok(envelope.data)
    }

    /// Lists static LDAP role names.
    pub async fn list_static_roles(&self) -> Result<LdapList> {
        self.list_at(&["static-role"]).await
    }

    /// Deletes a static LDAP role.
    pub async fn delete_static_role(&self, name: &str) -> Result<Empty> {
        self.delete_at(&["static-role", name]).await
    }

    /// Reads static LDAP credentials.
    pub async fn static_credentials(&self, name: &str) -> Result<LdapStaticCredentials> {
        let envelope: ResponseEnvelope<LdapStaticCredentials> = self
            .client
            .request_json(
                Method::GET,
                &self.path(&["static-cred", name])?,
                Option::<&Empty>::None,
            )
            .await?;
        Ok(envelope.data)
    }

    /// Rotates a static LDAP role password.
    pub async fn rotate_static_role(&self, name: &str) -> Result<Empty> {
        self.client
            .request_json(
                Method::POST,
                &self.path(&["rotate-role", name])?,
                Some(&Empty {}),
            )
            .await
    }

    /// Creates or updates a dynamic LDAP role.
    pub async fn write_dynamic_role(&self, name: &str, role: &LdapDynamicRole) -> Result<Empty> {
        role.validate()?;
        self.client
            .request_json(Method::POST, &self.path(&["role", name])?, Some(role))
            .await
    }

    /// Reads a dynamic LDAP role.
    pub async fn read_dynamic_role(&self, name: &str) -> Result<LdapDynamicRole> {
        let envelope: ResponseEnvelope<LdapDynamicRole> = self
            .client
            .request_json(
                Method::GET,
                &self.path(&["role", name])?,
                Option::<&Empty>::None,
            )
            .await?;
        Ok(envelope.data)
    }

    /// Deletes a dynamic LDAP role.
    pub async fn delete_dynamic_role(&self, name: &str) -> Result<Empty> {
        self.delete_at(&["role", name]).await
    }

    /// Generates dynamic LDAP credentials.
    pub async fn dynamic_credentials(&self, name: &str) -> Result<LdapDynamicCredentials> {
        let envelope: ResponseEnvelope<LdapDynamicCredentialData> = self
            .client
            .request_json(
                Method::GET,
                &self.path(&["creds", name])?,
                Option::<&Empty>::None,
            )
            .await?;
        Ok(LdapDynamicCredentials {
            username: envelope.data.username,
            password: envelope.data.password,
            distinguished_names: envelope.data.distinguished_names,
            lease_id: envelope.lease_id,
            lease_duration: envelope.lease_duration,
            renewable: envelope.renewable,
        })
    }

    /// Creates or updates a library set.
    pub async fn write_library_set(&self, name: &str, set: &LdapLibrarySet) -> Result<Empty> {
        set.validate()?;
        self.client
            .request_json(Method::POST, &self.path(&["library", name])?, Some(set))
            .await
    }

    /// Reads a library set.
    pub async fn read_library_set(&self, name: &str) -> Result<LdapLibrarySet> {
        let envelope: ResponseEnvelope<LdapLibrarySet> = self
            .client
            .request_json(
                Method::GET,
                &self.path(&["library", name])?,
                Option::<&Empty>::None,
            )
            .await?;
        Ok(envelope.data)
    }

    /// Lists library set names.
    pub async fn list_library_sets(&self) -> Result<LdapList> {
        self.list_at(&["library"]).await
    }

    /// Deletes a library set.
    pub async fn delete_library_set(&self, name: &str) -> Result<Empty> {
        self.delete_at(&["library", name]).await
    }

    /// Reads library set account status.
    pub async fn library_status(&self, name: &str) -> Result<LdapLibraryStatus> {
        let envelope: ResponseEnvelope<LdapLibraryStatus> = self
            .client
            .request_json(
                Method::GET,
                &self.path(&["library", name, "status"])?,
                Option::<&Empty>::None,
            )
            .await?;
        Ok(envelope.data)
    }

    /// Checks out one service account from a library set.
    pub async fn check_out(
        &self,
        name: &str,
        request: &LdapCheckOutRequest,
    ) -> Result<LdapCheckOut> {
        request.validate()?;
        let envelope: ResponseEnvelope<LdapCheckOutData> = self
            .client
            .request_json(
                Method::POST,
                &self.path(&["library", name, "check-out"])?,
                Some(request),
            )
            .await?;
        Ok(LdapCheckOut {
            service_account_name: envelope.data.service_account_name,
            password: envelope.data.password,
            lease_id: envelope.lease_id,
            lease_duration: envelope.lease_duration,
            renewable: envelope.renewable,
        })
    }

    /// Checks service accounts back into a library set.
    pub async fn check_in(&self, name: &str, request: &LdapCheckInRequest) -> Result<LdapCheckIn> {
        request.validate()?;
        let envelope: ResponseEnvelope<LdapCheckIn> = self
            .client
            .request_json(
                Method::POST,
                &self.path(&["library", name, "check-in"])?,
                Some(request),
            )
            .await?;
        Ok(envelope.data)
    }

    /// Force-checks service accounts back into a library set through the
    /// privileged management endpoint.
    pub async fn force_check_in(
        &self,
        name: &str,
        request: &LdapCheckInRequest,
    ) -> Result<LdapCheckIn> {
        request.validate()?;
        let envelope: ResponseEnvelope<LdapCheckIn> = self
            .client
            .request_json(
                Method::POST,
                &self.path(&["library", "manage", name, "check-in"])?,
                Some(request),
            )
            .await?;
        Ok(envelope.data)
    }

    async fn list_at(&self, tail: &[&str]) -> Result<LdapList> {
        let method =
            Method::from_bytes(b"LIST").map_err(|error| Error::InvalidHeader(error.to_string()))?;
        let envelope: ResponseEnvelope<LdapList> = self
            .client
            .request_json_query_accepting(
                method,
                &self.path(tail)?,
                &[],
                Option::<&Empty>::None,
                &[StatusCode::OK],
            )
            .await?;
        Ok(envelope.data)
    }

    async fn delete_at(&self, tail: &[&str]) -> Result<Empty> {
        self.client
            .request_json_accepting(
                Method::DELETE,
                &self.path(tail)?,
                Option::<&Empty>::None,
                &[StatusCode::OK, StatusCode::NO_CONTENT],
            )
            .await
    }

    fn path(&self, tail: &[&str]) -> Result<String> {
        let mut segments = self.mount.clone();
        for segment in tail {
            segments.extend(validate_endpoint_path(segment)?);
        }
        Ok(segments.join("/"))
    }
}

impl Serialize for LdapConfig {
    fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut count = 2;
        count += usize::from(self.url.is_some());
        count += usize::from(self.password_policy.is_some());
        count += usize::from(self.schema.is_some());
        count += usize::from(self.userdn.is_some());
        count += usize::from(self.userattr.is_some());
        count += usize::from(self.upndomain.is_some());
        count += usize::from(self.connection_timeout.is_some());
        count += usize::from(self.request_timeout.is_some());
        count += usize::from(self.starttls.is_some());
        count += usize::from(self.insecure_tls.is_some());
        count += usize::from(self.certificate.is_some());
        count += usize::from(self.client_tls_cert.is_some());
        count += usize::from(self.client_tls_key.is_some());
        count += usize::from(self.length.is_some());

        let mut map = serializer.serialize_map(Some(count))?;
        map.serialize_entry("binddn", &self.binddn)?;
        map.serialize_entry("bindpass", self.bindpass.expose_secret())?;
        if let Some(value) = self.url.as_ref() {
            map.serialize_entry("url", value)?;
        }
        if let Some(value) = self.password_policy.as_ref() {
            map.serialize_entry("password_policy", value)?;
        }
        if let Some(value) = self.schema.as_ref() {
            map.serialize_entry("schema", value)?;
        }
        if let Some(value) = self.userdn.as_ref() {
            map.serialize_entry("userdn", value)?;
        }
        if let Some(value) = self.userattr.as_ref() {
            map.serialize_entry("userattr", value)?;
        }
        if let Some(value) = self.upndomain.as_ref() {
            map.serialize_entry("upndomain", value)?;
        }
        if let Some(value) = self.connection_timeout.as_ref() {
            map.serialize_entry("connection_timeout", value)?;
        }
        if let Some(value) = self.request_timeout.as_ref() {
            map.serialize_entry("request_timeout", value)?;
        }
        if let Some(value) = self.starttls {
            map.serialize_entry("starttls", &value)?;
        }
        if let Some(value) = self.insecure_tls {
            map.serialize_entry("insecure_tls", &value)?;
        }
        if let Some(value) = self.certificate.as_ref() {
            map.serialize_entry("certificate", value)?;
        }
        if let Some(value) = self.client_tls_cert.as_ref() {
            map.serialize_entry("client_tls_cert", value)?;
        }
        if let Some(value) = self.client_tls_key.as_ref() {
            map.serialize_entry("client_tls_key", value.expose_secret())?;
        }
        if let Some(value) = self.length {
            map.serialize_entry("length", &value)?;
        }
        map.end()
    }
}

fn validate_duration_or_seconds(value: &str, field: &'static str, allow_zero: bool) -> Result<()> {
    if value
        .parse::<u64>()
        .is_ok_and(|seconds| allow_zero || seconds > 0)
        || validate_duration_string(value, allow_zero)
    {
        return Ok(());
    }
    Err(Error::InvalidParameter(format!(
        "{field} must be a duration such as 30s, 5m, or 1h or an unsigned second count"
    )))
}

#[cfg(not(feature = "insecure-ldap-tls-acknowledged"))]
fn validate_ldap_urls_use_encrypted_transport(
    urls: &Option<String>,
    starttls: Option<bool>,
    label: &'static str,
) -> Result<()> {
    let Some(urls) = urls else {
        return Ok(());
    };
    if starttls == Some(true) {
        return Ok(());
    }
    for url in urls.split(',') {
        let url = url.trim();
        if url.is_empty() {
            continue;
        }
        if !url
            .get(..8)
            .is_some_and(|prefix| prefix.eq_ignore_ascii_case("ldaps://"))
        {
            return Err(Error::InvalidParameter(format!(
                "{label} URL must use ldaps:// or starttls=true unless insecure LDAP TLS is explicitly acknowledged"
            )));
        }
    }
    Ok(())
}

fn validate_count(count: usize, field: &'static str, require_non_empty: bool) -> Result<()> {
    if require_non_empty && count == 0 {
        return Err(Error::InvalidParameter(format!(
            "{field} must include at least one item"
        )));
    }
    if count > crate::response::MAX_RESPONSE_STRINGS {
        return Err(Error::InvalidParameter(format!(
            "{field} exceeds maximum item count"
        )));
    }
    Ok(())
}

fn deserialize_optional_string_or_u64<'de, D>(
    deserializer: D,
) -> core::result::Result<Option<String>, D::Error>
where
    D: Deserializer<'de>,
{
    deserializer.deserialize_any(OptionalStringOrU64Visitor)
}

struct OptionalStringOrU64Visitor;

impl<'de> Visitor<'de> for OptionalStringOrU64Visitor {
    type Value = Option<String>;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("a string, an unsigned integer, or null")
    }

    fn visit_none<E>(self) -> core::result::Result<Self::Value, E> {
        Ok(None)
    }

    fn visit_unit<E>(self) -> core::result::Result<Self::Value, E> {
        Ok(None)
    }

    fn visit_some<D>(self, deserializer: D) -> core::result::Result<Self::Value, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_any(Self)
    }

    fn visit_u64<E>(self, value: u64) -> core::result::Result<Self::Value, E> {
        Ok(Some(value.to_string()))
    }

    fn visit_i64<E>(self, value: i64) -> core::result::Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        let value =
            u64::try_from(value).map_err(|_| E::custom("duration seconds must not be negative"))?;
        Ok(Some(value.to_string()))
    }

    fn visit_str<E>(self, value: &str) -> core::result::Result<Self::Value, E> {
        Ok(Some(value.to_owned()))
    }

    fn visit_string<E>(self, value: String) -> core::result::Result<Self::Value, E> {
        Ok(Some(value))
    }
}

fn deserialize_bounded_library_account_map_or_default<'de, D>(
    deserializer: D,
) -> core::result::Result<BTreeMap<String, LdapLibraryAccountStatus>, D::Error>
where
    D: Deserializer<'de>,
{
    Option::<BoundedLibraryAccountMap>::deserialize(deserializer)
        .map(|value| value.map(|value| value.0).unwrap_or_default())
}

#[derive(Deserialize)]
struct BoundedLibraryAccountMap(
    #[serde(deserialize_with = "deserialize_bounded_library_account_map")]
    BTreeMap<String, LdapLibraryAccountStatus>,
);

fn deserialize_bounded_library_account_map<'de, D>(
    deserializer: D,
) -> core::result::Result<BTreeMap<String, LdapLibraryAccountStatus>, D::Error>
where
    D: Deserializer<'de>,
{
    deserializer.deserialize_map(
        BoundedLibraryAccountMapVisitor::<{ crate::response::MAX_RESPONSE_STRINGS }>,
    )
}

struct BoundedLibraryAccountMapVisitor<const MAX: usize>;

impl<'de, const MAX: usize> Visitor<'de> for BoundedLibraryAccountMapVisitor<MAX> {
    type Value = BTreeMap<String, LdapLibraryAccountStatus>;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "a map of at most {MAX} LDAP library accounts")
    }

    fn visit_map<A>(self, mut map: A) -> core::result::Result<Self::Value, A::Error>
    where
        A: serde::de::MapAccess<'de>,
    {
        let mut values = BTreeMap::new();
        while values.len() < MAX {
            let Some((key, value)) = map.next_entry::<String, LdapLibraryAccountStatus>()? else {
                return Ok(values);
            };
            values.insert(key, value);
        }
        if map
            .next_entry::<serde::de::IgnoredAny, serde::de::IgnoredAny>()?
            .is_some()
        {
            return Err(serde::de::Error::custom(
                "OpenBao LDAP library account map exceeds item limit",
            ));
        }
        Ok(values)
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::panic)]
    #![allow(deprecated)]

    use secrecy::{ExposeSecret, SecretString};

    use crate::{Client, OpenBaoConfig};

    use super::{
        LdapCheckOut, LdapConfig, LdapDynamicCredentials, LdapLibrarySet, LdapLibraryStatus,
        LdapList, LdapStaticCredentials,
    };

    #[test]
    fn ldap_paths_are_validated() {
        let config = OpenBaoConfig::new("http://127.0.0.1:8200")
            .and_then(OpenBaoConfig::allow_localhost_http)
            .unwrap_or_else(|error| panic!("{error}"));
        let client = Client::from_config(config)
            .unwrap_or_else(|error| panic!("{error}"))
            .with_token(SecretString::from("token"));
        let ldap = client
            .ldap_at("ldap")
            .unwrap_or_else(|error| panic!("{error}"));
        assert_eq!(
            ldap.path(&["static-role", "app"])
                .unwrap_or_else(|error| panic!("{error}")),
            "ldap/static-role/app"
        );
        assert!(client.ldap_at("../ldap").is_err());
        assert!(ldap.path(&["static-role", "../app"]).is_err());
    }

    #[test]
    fn ldap_lists_are_bounded() {
        let mut keys = Vec::new();
        for index in 0..=crate::response::MAX_RESPONSE_STRINGS {
            keys.push(format!("role-{index}"));
        }
        let value = serde_json::json!({ "keys": keys });
        assert!(serde_json::from_value::<LdapList>(value).is_err());

        let mut accounts = Vec::new();
        for index in 0..=crate::response::MAX_RESPONSE_STRINGS {
            accounts.push((
                format!("account-{index}"),
                serde_json::json!({
                    "checked_out": false
                }),
            ));
        }
        let value = serde_json::json!({ "service_account_names": accounts.into_iter().collect::<serde_json::Map<_, _>>() });
        assert!(serde_json::from_value::<LdapLibraryStatus>(value).is_err());
    }

    #[test]
    fn ldap_debug_redacts_secret_fields() {
        let config = LdapConfig::new(
            "cn=openbao,ou=Users,dc=example,dc=com",
            SecretString::from("bind-password"),
        );
        let debug = format!("{config:?}");
        assert!(debug.contains("LdapConfig"));
        assert!(!debug.contains("bind-password"));

        let static_credentials = LdapStaticCredentials {
            username: "app".to_owned(),
            dn: None,
            password: SecretString::from("current-password"),
            last_password: Some(SecretString::from("last-password")),
            last_vault_rotation: None,
            rotation_period: Some(3600),
            ttl: Some(300),
        };
        let debug = format!("{static_credentials:?}");
        assert!(!debug.contains(static_credentials.password.expose_secret()));
        assert!(!debug.contains("last-password"));

        let dynamic_credentials = LdapDynamicCredentials {
            username: "generated".to_owned(),
            password: SecretString::from("dynamic-password"),
            distinguished_names: vec!["cn=generated,ou=Users,dc=example,dc=com".to_owned()],
            lease_id: SecretString::from("ldap/creds/app/lease"),
            lease_duration: 3600,
            renewable: true,
        };
        let debug = format!("{dynamic_credentials:?}");
        assert!(!debug.contains(dynamic_credentials.password.expose_secret()));
        assert!(!debug.contains(dynamic_credentials.lease_id.expose_secret()));

        let checkout = LdapCheckOut {
            service_account_name: "service@example.com".to_owned(),
            password: SecretString::from("checkout-password"),
            lease_id: SecretString::from("ldap/library/app/check-out/lease"),
            lease_duration: 3600,
            renewable: true,
        };
        let debug = format!("{checkout:?}");
        assert!(!debug.contains(checkout.password.expose_secret()));
        assert!(!debug.contains(checkout.lease_id.expose_secret()));
    }

    #[test]
    fn ldap_request_validation_bounds_service_accounts() {
        let set = LdapLibrarySet::new(Vec::<String>::new());
        assert!(set.validate().is_err());

        let mut names = Vec::new();
        for index in 0..=crate::response::MAX_RESPONSE_STRINGS {
            names.push(format!("service-{index}"));
        }
        let set = LdapLibrarySet::new(names);
        assert!(set.validate().is_err());
    }

    #[cfg(not(feature = "insecure-ldap-tls-acknowledged"))]
    #[test]
    fn ldap_insecure_tls_requires_acknowledgement_feature() {
        let mut config = LdapConfig::new("cn=openbao", SecretString::from("bind-password"));
        config.insecure_tls = Some(true);

        assert!(config.validate().is_err());
    }

    #[cfg(feature = "insecure-ldap-tls-acknowledged")]
    #[test]
    fn ldap_insecure_tls_rejects_bind_credentials_even_when_acknowledged() {
        let mut config = LdapConfig::new("cn=openbao", SecretString::from("bind-password"));
        config.insecure_tls = Some(true);

        assert!(config.validate().is_err());
    }

    #[cfg(not(feature = "insecure-ldap-tls-acknowledged"))]
    #[test]
    fn ldap_config_requires_encrypted_urls() {
        let mut config = LdapConfig::new("cn=openbao", SecretString::from("bind-password"))
            .with_url("ldap://ldap.example.com");
        assert!(config.validate().is_err());

        config.starttls = Some(true);
        assert!(config.validate().is_ok());

        let config = LdapConfig::new("cn=openbao", SecretString::from("bind-password"))
            .with_url("ldaps://ldap.example.com");
        assert!(config.validate().is_ok());
    }
}