openbao 1.0.0

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
//! Database secrets engine support.

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, ListPageOptions, ResponseEnvelope,
        deserialize_bounded_string_map_or_default, deserialize_bounded_string_vec,
    },
};

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

/// Database connection configuration request.
#[derive(Clone, Default)]
pub struct DatabaseConnectionConfig {
    /// Database plugin name, such as `postgresql-database-plugin`.
    pub plugin_name: String,
    /// Optional plugin version.
    pub plugin_version: Option<String>,
    /// Whether OpenBao should verify the connection during configuration.
    pub verify_connection: Option<bool>,
    /// Roles allowed to use this connection. Use `*` to allow any role.
    pub allowed_roles: Vec<String>,
    /// Statements used to rotate the root database user's credentials.
    pub root_rotation_statements: Vec<String>,
    /// Password policy used by generated credentials.
    pub password_policy: Option<String>,
    /// Database connection URL or plugin-specific URL field.
    ///
    /// This is secret-aware because database URLs commonly embed credentials.
    /// Prefer separate `username` and `password` fields when the plugin
    /// supports them.
    pub connection_url: Option<SecretString>,
    /// Database username used by OpenBao to manage generated users.
    pub username: Option<String>,
    /// Database password used by OpenBao to manage generated users.
    pub password: Option<SecretString>,
    /// Whether to disable username/password escaping in supported plugins.
    pub disable_escaping: Option<bool>,
    /// Additional plugin-specific string fields.
    pub extra: BTreeMap<String, String>,
}

impl DatabaseConnectionConfig {
    /// Creates a database connection config request with the required plugin name.
    pub fn new(plugin_name: impl Into<String>) -> Self {
        Self {
            plugin_name: plugin_name.into(),
            ..Self::default()
        }
    }
}

impl fmt::Debug for DatabaseConnectionConfig {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("DatabaseConnectionConfig")
            .field("plugin_name", &self.plugin_name)
            .field("plugin_version", &self.plugin_version)
            .field("verify_connection", &self.verify_connection)
            .field("allowed_roles", &self.allowed_roles)
            .field("root_rotation_statements", &self.root_rotation_statements)
            .field("password_policy", &self.password_policy)
            .field("has_connection_url", &self.connection_url.is_some())
            .field("username", &self.username)
            .field("password", &self.password.as_ref().map(|_| "<redacted>"))
            .field("disable_escaping", &self.disable_escaping)
            .field("extra", &self.extra)
            .finish()
    }
}

/// Database connection configuration returned by OpenBao.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct DatabaseConnectionInfo {
    /// Roles allowed to use this connection.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub allowed_roles: Vec<String>,
    /// Connection details returned by OpenBao. Sensitive password fields are
    /// intentionally not returned by OpenBao.
    #[serde(
        default,
        deserialize_with = "deserialize_bounded_string_map_or_default"
    )]
    pub connection_details: BTreeMap<String, String>,
    /// Password policy used by generated credentials.
    #[serde(default)]
    pub password_policy: Option<String>,
    /// Database plugin name.
    pub plugin_name: String,
    /// Optional plugin version.
    #[serde(default)]
    pub plugin_version: Option<String>,
    /// Root credential rotation statements.
    #[serde(
        default,
        alias = "root_rotation_statements",
        deserialize_with = "deserialize_bounded_string_vec"
    )]
    pub root_credentials_rotate_statements: Vec<String>,
}

/// List response for database connections or roles.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct DatabaseList {
    /// Names returned by OpenBao.
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    pub keys: Vec<String>,
}

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

/// Dynamic database role request and response.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct DatabaseRole {
    /// Database connection name used by this role.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub db_name: String,
    /// Statements used to create and configure dynamic users.
    #[serde(default, deserialize_with = "deserialize_bounded_string_or_vec")]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub creation_statements: Vec<String>,
    /// Lease default TTL.
    #[serde(
        default,
        deserialize_with = "deserialize_optional_string_or_u64",
        skip_serializing_if = "Option::is_none"
    )]
    pub default_ttl: Option<String>,
    /// Lease maximum TTL.
    #[serde(
        default,
        deserialize_with = "deserialize_optional_string_or_u64",
        skip_serializing_if = "Option::is_none"
    )]
    pub max_ttl: Option<String>,
    /// Statements used to revoke generated users.
    #[serde(default, deserialize_with = "deserialize_bounded_string_or_vec")]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub revocation_statements: Vec<String>,
    /// Statements used to roll back failed user creation.
    #[serde(default, deserialize_with = "deserialize_bounded_string_or_vec")]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub rollback_statements: Vec<String>,
    /// Statements used to renew generated users.
    #[serde(default, deserialize_with = "deserialize_bounded_string_or_vec")]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub renew_statements: Vec<String>,
    /// Credential type, such as `password`, `rsa_private_key`, or
    /// `client_certificate`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub credential_type: Option<String>,
    /// Credential-type-specific string configuration.
    #[serde(
        default,
        deserialize_with = "deserialize_bounded_string_map_or_default"
    )]
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub credential_config: BTreeMap<String, String>,
}

impl DatabaseRole {
    /// Creates a dynamic role request with the required database connection name.
    pub fn new(db_name: impl Into<String>) -> Self {
        Self {
            db_name: db_name.into(),
            ..Self::default()
        }
    }

    /// Adds a creation statement.
    #[must_use]
    pub fn with_creation_statement(mut self, statement: impl Into<String>) -> Self {
        self.creation_statements.push(statement.into());
        self
    }
}

/// Static database role request and response.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct DatabaseStaticRole {
    /// Database connection name used by this static role.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub db_name: String,
    /// Existing database username managed by the static role.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub username: String,
    /// Rotation period.
    #[serde(
        default,
        deserialize_with = "deserialize_optional_string_or_u64",
        skip_serializing_if = "Option::is_none"
    )]
    pub rotation_period: Option<String>,
    /// Statements used to rotate the static user's password.
    #[serde(default, deserialize_with = "deserialize_bounded_string_or_vec")]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub rotation_statements: Vec<String>,
    /// Credential type.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub credential_type: Option<String>,
    /// Credential-type-specific string configuration.
    #[serde(
        default,
        deserialize_with = "deserialize_bounded_string_map_or_default"
    )]
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub credential_config: BTreeMap<String, String>,
}

impl DatabaseStaticRole {
    /// Creates a static role request with required database and username fields.
    pub fn new(db_name: impl Into<String>, username: impl Into<String>) -> Self {
        Self {
            db_name: db_name.into(),
            username: username.into(),
            ..Self::default()
        }
    }
}

/// Dynamic database credentials with lease metadata.
#[derive(Clone)]
pub struct DatabaseCredentials {
    /// Generated database username.
    pub username: String,
    /// Generated password, when the role uses password credentials.
    pub password: Option<SecretString>,
    /// Generated private key, when the role uses key credentials.
    pub private_key: Option<SecretString>,
    /// Generated client certificate, when returned by the plugin.
    pub certificate: Option<String>,
    /// Issuing CA certificate, when returned by the plugin.
    pub issuing_ca: Option<String>,
    /// CA chain, when returned by the plugin.
    pub ca_chain: 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 DatabaseCredentials {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("DatabaseCredentials")
            .field("username", &self.username)
            .field("password", &self.password.as_ref().map(|_| "<redacted>"))
            .field(
                "private_key",
                &self.private_key.as_ref().map(|_| "<redacted>"),
            )
            .field("certificate", &self.certificate)
            .field("issuing_ca", &self.issuing_ca)
            .field("ca_chain", &self.ca_chain)
            .field("lease_id", &"<redacted>")
            .field("lease_duration", &self.lease_duration)
            .field("renewable", &self.renewable)
            .finish()
    }
}

/// Static database credentials.
#[derive(Clone, Deserialize)]
pub struct DatabaseStaticCredentials {
    /// Static database username.
    pub username: String,
    /// Current static database password.
    pub password: SecretString,
    /// Last OpenBao rotation timestamp, when returned.
    #[serde(default)]
    pub last_openbao_rotation: Option<String>,
    /// Rotation period in seconds, when returned.
    #[serde(default)]
    pub rotation_period: Option<u64>,
    /// Remaining TTL in seconds, when returned.
    #[serde(default)]
    pub ttl: Option<u64>,
}

impl fmt::Debug for DatabaseStaticCredentials {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("DatabaseStaticCredentials")
            .field("username", &self.username)
            .field("password", &"<redacted>")
            .field("last_openbao_rotation", &self.last_openbao_rotation)
            .field("rotation_period", &self.rotation_period)
            .field("ttl", &self.ttl)
            .finish()
    }
}

#[derive(Serialize)]
struct DatabaseConnectionPayload<'a> {
    plugin_name: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    plugin_version: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    verify_connection: Option<bool>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    allowed_roles: Vec<&'a str>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    root_rotation_statements: Vec<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    password_policy: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    connection_url: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    username: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    password: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    disable_escaping: Option<bool>,
    #[serde(flatten)]
    extra: &'a BTreeMap<String, String>,
}

#[derive(Deserialize)]
struct DatabaseCredentialData {
    username: String,
    #[serde(default)]
    password: Option<SecretString>,
    #[serde(default)]
    private_key: Option<SecretString>,
    #[serde(default)]
    certificate: Option<String>,
    #[serde(default)]
    issuing_ca: Option<String>,
    #[serde(default, deserialize_with = "deserialize_bounded_string_vec")]
    ca_chain: Vec<String>,
}

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

impl Database<'_> {
    /// Creates or updates a database connection configuration.
    pub async fn configure_connection(
        &self,
        name: &str,
        config: &DatabaseConnectionConfig,
    ) -> Result<Empty> {
        let payload = DatabaseConnectionPayload {
            plugin_name: &config.plugin_name,
            plugin_version: config.plugin_version.as_deref(),
            verify_connection: config.verify_connection,
            allowed_roles: config.allowed_roles.iter().map(String::as_str).collect(),
            root_rotation_statements: config
                .root_rotation_statements
                .iter()
                .map(String::as_str)
                .collect(),
            password_policy: config.password_policy.as_deref(),
            connection_url: config
                .connection_url
                .as_ref()
                .map(SecretString::expose_secret),
            username: config.username.as_deref(),
            password: config.password.as_ref().map(SecretString::expose_secret),
            disable_escaping: config.disable_escaping,
            extra: &config.extra,
        };
        self.client
            .request_json(Method::POST, &self.path(&["config", name])?, Some(&payload))
            .await
    }

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

    /// Lists database connection names.
    pub async fn list_connections(&self) -> Result<DatabaseList> {
        self.list_at("config", None, None).await
    }

    /// Deletes a database connection configuration.
    pub async fn delete_connection(&self, name: &str) -> Result<Empty> {
        self.delete_at("config", name).await
    }

    /// Resets a database connection plugin.
    pub async fn reset_connection(&self, name: &str) -> Result<Empty> {
        self.client
            .request_json(Method::POST, &self.path(&["reset", name])?, Some(&Empty {}))
            .await
    }

    /// Rotates the root credentials for a database connection.
    pub async fn rotate_root(&self, name: &str) -> Result<Empty> {
        self.client
            .request_json(
                Method::POST,
                &self.path(&["rotate-root", name])?,
                Some(&Empty {}),
            )
            .await
    }

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

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

    /// Lists dynamic database role names.
    pub async fn list_roles(&self) -> Result<DatabaseList> {
        self.list_roles_after(None, None).await
    }

    /// Lists dynamic database role names with optional pagination parameters.
    pub async fn list_roles_after(
        &self,
        after: Option<&str>,
        limit: Option<u64>,
    ) -> Result<DatabaseList> {
        self.list_at("roles", after, limit).await
    }

    /// Deletes a dynamic database role.
    pub async fn delete_role(&self, name: &str) -> Result<Empty> {
        self.delete_at("roles", name).await
    }

    /// Generates dynamic database credentials for a role.
    pub async fn credentials(&self, name: &str) -> Result<DatabaseCredentials> {
        let envelope: ResponseEnvelope<DatabaseCredentialData> = self
            .client
            .request_json(
                Method::GET,
                &self.path(&["creds", name])?,
                Option::<&Empty>::None,
            )
            .await?;
        Ok(database_credentials_from_envelope(envelope))
    }

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

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

    /// Lists static database role names.
    pub async fn list_static_roles(&self) -> Result<DatabaseList> {
        self.list_static_roles_after(None, None).await
    }

    /// Lists static database role names with optional pagination parameters.
    pub async fn list_static_roles_after(
        &self,
        after: Option<&str>,
        limit: Option<u64>,
    ) -> Result<DatabaseList> {
        self.list_at("static-roles", after, limit).await
    }

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

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

    /// Rotates credentials for a static database role.
    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
    }

    async fn list_at(
        &self,
        segment: &'static str,
        after: Option<&str>,
        limit: Option<u64>,
    ) -> Result<DatabaseList> {
        let method =
            Method::from_bytes(b"LIST").map_err(|error| Error::InvalidHeader(error.to_string()))?;
        let query = ListPageOptions::from_after_limit(after, limit)?.query_pairs();
        let envelope: ResponseEnvelope<DatabaseList> = self
            .client
            .request_json_query_accepting(
                method,
                &self.path(&[segment])?,
                &query,
                Option::<&Empty>::None,
                &[StatusCode::OK],
            )
            .await?;
        Ok(envelope.data)
    }

    async fn delete_at(&self, segment: &'static str, name: &str) -> Result<Empty> {
        self.client
            .request_json_accepting(
                Method::DELETE,
                &self.path(&[segment, name])?,
                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("/"))
    }
}

fn database_credentials_from_envelope(
    envelope: ResponseEnvelope<DatabaseCredentialData>,
) -> DatabaseCredentials {
    DatabaseCredentials {
        username: envelope.data.username,
        password: envelope.data.password,
        private_key: envelope.data.private_key,
        certificate: envelope.data.certificate,
        issuing_ca: envelope.data.issuing_ca,
        ca_chain: envelope.data.ca_chain,
        lease_id: envelope.lease_id,
        lease_duration: envelope.lease_duration,
        renewable: envelope.renewable,
    }
}

impl Serialize for DatabaseConnectionConfig {
    fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut count = 1 + self.extra.len();
        count += usize::from(self.plugin_version.is_some());
        count += usize::from(self.verify_connection.is_some());
        count += usize::from(!self.allowed_roles.is_empty());
        count += usize::from(!self.root_rotation_statements.is_empty());
        count += usize::from(self.password_policy.is_some());
        count += usize::from(self.connection_url.is_some());
        count += usize::from(self.username.is_some());
        count += usize::from(self.password.is_some());
        count += usize::from(self.disable_escaping.is_some());

        let mut map = serializer.serialize_map(Some(count))?;
        map.serialize_entry("plugin_name", &self.plugin_name)?;
        if let Some(plugin_version) = self.plugin_version.as_ref() {
            map.serialize_entry("plugin_version", plugin_version)?;
        }
        if let Some(verify_connection) = self.verify_connection {
            map.serialize_entry("verify_connection", &verify_connection)?;
        }
        if !self.allowed_roles.is_empty() {
            map.serialize_entry("allowed_roles", &self.allowed_roles)?;
        }
        if !self.root_rotation_statements.is_empty() {
            map.serialize_entry("root_rotation_statements", &self.root_rotation_statements)?;
        }
        if let Some(password_policy) = self.password_policy.as_ref() {
            map.serialize_entry("password_policy", password_policy)?;
        }
        if let Some(connection_url) = self.connection_url.as_ref() {
            map.serialize_entry("connection_url", connection_url.expose_secret())?;
        }
        if let Some(username) = self.username.as_ref() {
            map.serialize_entry("username", username)?;
        }
        if let Some(password) = self.password.as_ref() {
            map.serialize_entry("password", password.expose_secret())?;
        }
        if let Some(disable_escaping) = self.disable_escaping {
            map.serialize_entry("disable_escaping", &disable_escaping)?;
        }
        for (key, value) in &self.extra {
            map.serialize_entry(key, value)?;
        }
        map.end()
    }
}

fn deserialize_bounded_string_or_vec<'de, D>(
    deserializer: D,
) -> core::result::Result<Vec<String>, D::Error>
where
    D: Deserializer<'de>,
{
    deserializer.deserialize_any(StringOrListVisitor::<{ crate::response::MAX_RESPONSE_STRINGS }>)
}

struct StringOrListVisitor<const MAX: usize>;

impl<'de, const MAX: usize> Visitor<'de> for StringOrListVisitor<MAX> {
    type Value = Vec<String>;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "a comma-separated string or a list of at most {MAX} strings"
        )
    }

    fn visit_unit<E>(self) -> core::result::Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(Vec::new())
    }

    fn visit_str<E>(self, value: &str) -> core::result::Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        if value.trim().is_empty() {
            return Ok(Vec::new());
        }
        let values: Vec<String> = value
            .split(',')
            .map(str::trim)
            .filter(|part| !part.is_empty())
            .map(str::to_owned)
            .collect();
        if values.len() > MAX {
            return Err(E::custom("OpenBao string list exceeds item limit"));
        }
        Ok(values)
    }

    fn visit_seq<A>(self, mut seq: A) -> core::result::Result<Self::Value, A::Error>
    where
        A: serde::de::SeqAccess<'de>,
    {
        let mut values = Vec::new();
        while values.len() < MAX {
            let Some(value) = seq.next_element::<String>()? else {
                return Ok(values);
            };
            values.push(value);
        }
        if seq.next_element::<serde::de::IgnoredAny>()?.is_some() {
            return Err(serde::de::Error::custom(
                "OpenBao string list exceeds item limit",
            ));
        }
        Ok(values)
    }
}

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, integer, null, or omitted value")
    }

    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_str<E>(self, value: &str) -> core::result::Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(Some(value.to_owned()))
    }

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

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

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

    use secrecy::{ExposeSecret, SecretString};

    use super::{DatabaseCredentials, DatabaseList, DatabaseRole, DatabaseStaticCredentials};

    #[test]
    fn database_credentials_debug_redacts_password_and_lease() {
        let credentials = DatabaseCredentials {
            username: "app".to_owned(),
            password: Some(SecretString::from("db-password")),
            private_key: Some(SecretString::from("private-key")),
            certificate: None,
            issuing_ca: None,
            ca_chain: Vec::new(),
            lease_id: SecretString::from("database/creds/app/lease"),
            lease_duration: 3600,
            renewable: true,
        };
        let debug = format!("{credentials:?}");
        assert!(debug.contains("<redacted>"));
        assert!(!debug.contains("db-password"));
        assert!(!debug.contains("private-key"));
        assert!(!debug.contains("database/creds/app/lease"));
    }

    #[test]
    fn database_static_credentials_debug_redacts_password() {
        let credentials = DatabaseStaticCredentials {
            username: "static-user".to_owned(),
            password: SecretString::from("static-password"),
            last_openbao_rotation: None,
            rotation_period: Some(3600),
            ttl: Some(300),
        };
        let debug = format!("{credentials:?}");
        assert!(debug.contains("<redacted>"));
        assert!(!debug.contains("static-password"));
    }

    #[test]
    fn database_list_is_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 });
        let error = match serde_json::from_value::<DatabaseList>(value) {
            Ok(_) => panic!("oversized database list unexpectedly decoded"),
            Err(error) => error,
        };
        assert!(error.to_string().contains("exceeds item limit"));
    }

    #[test]
    fn database_role_accepts_integer_ttls_and_string_statements() {
        let role: DatabaseRole = serde_json::from_str(
            r#"{"db_name":"postgres","creation_statements":"CREATE ROLE {{name}}","default_ttl":3600,"max_ttl":"24h"}"#,
        )
        .unwrap_or_else(|error| panic!("{error}"));
        assert_eq!(role.creation_statements, ["CREATE ROLE {{name}}"]);
        assert_eq!(role.default_ttl.as_deref(), Some("3600"));
        assert_eq!(role.max_ttl.as_deref(), Some("24h"));
    }

    #[test]
    fn database_static_password_deserializes_secret() {
        let credentials: DatabaseStaticCredentials =
            serde_json::from_str(r#"{"username":"static","password":"secret"}"#)
                .unwrap_or_else(|error| panic!("{error}"));
        assert_eq!(credentials.password.expose_secret(), "secret");
    }
}