quack_rs/secrets.rs
1// SPDX-License-Identifier: MIT
2// Copyright 2026 Tom F. <https://github.com/tomtom215/>
3// My way of giving something small back to the open source community
4// and encouraging more Rust development!
5
6//! Credential handling for extensions.
7//!
8//! Extensions that access external services (HTTP APIs, databases, cloud
9//! storage) commonly need credentials.
10//!
11//! # What `DuckDB` does and does not give you
12//!
13//! `DuckDB` has a native secrets system (`CREATE SECRET`), but **the extension
14//! C API exposes none of it** — there is not one `duckdb_secret_*` function
15//! among the 546 slots of `duckdb_ext_api_v1` in `DuckDB` 1.5.5. An extension
16//! cannot ask `DuckDB` for a credential through the C API at all.
17//!
18//! What it *can* do is query the `duckdb_secrets()` table function, and
19//! [`list_duckdb_secrets`] does exactly that. `DuckDB` **redacts** there the
20//! fields each secret type declares sensitive — and only those. Verified
21//! against `DuckDB` 1.5.5:
22//!
23//! ```text
24//! CREATE SECRET s (TYPE s3, KEY_ID 'AKIAEXAMPLE', SECRET 'super-secret-value');
25//! SELECT secret_string FROM duckdb_secrets();
26//! -- ...;key_id=AKIAEXAMPLE;secret=redacted
27//! ```
28//!
29//! That is not a guarantee that `secret_string` holds no credential: the
30//! built-in `http` type renders `extra_http_headers` — an `Authorization`
31//! header included — in full up to `DuckDB` 1.5.x (2.0.0 redacts it, as
32//! `default_secrets.cpp` now lists it among the type's redacted keys), a
33//! secret type that declares no sensitive keys is
34//! rendered whole, and what counts as sensitive changes between releases: an
35//! `http` secret's `bearer_token` is redacted by `DuckDB` 1.5.3 and later but
36//! shown in full by 1.4.4 and 1.5.0 (checked in CI; 1.5.1 and 1.5.2 untested). Treat
37//! `secret_string` as sensitive, and do not rely on it as a credential source
38//! either: an extension that needs a credential must obtain it some other way —
39//! an environment variable, a config option, a file, its own key store.
40//!
41//! # What this module is for
42//!
43//! [`SecretsManager`] is the trait an extension implements over **its own**
44//! credential source, and [`SecretEntry`] is what that source returns. It is
45//! not a bridge to `DuckDB`'s secrets, because no such bridge is available; it
46//! exists so the credential handling an extension has to write anyway comes
47//! with redacting `Debug`, zeroize-on-drop and no `PartialEq` already in place.
48//!
49//! [`list_duckdb_secrets`] complements it by reporting which secrets the user
50//! *has* configured, which is enough to pick a scope, warn about a missing
51//! secret, or decide which provider to use.
52//!
53//! # Security considerations
54//!
55//! `SecretEntry` is designed to minimize accidental credential leakage:
56//!
57//! - **`Debug` redacts field values** — only field keys are shown, values are
58//! replaced with `"[REDACTED]"`. Use [`get_field`][SecretEntry::get_field] to
59//! access actual values in code.
60//! - **`Drop` zeroizes sensitive data** — every field key and value, plus
61//! `provider` and `scope`, is overwritten with zeros using
62//! [`std::ptr::write_volatile`] before deallocation, so secrets do not linger
63//! in freed memory. This covers the buffers a [`SecretEntry`] owns; it cannot
64//! cover a `String` the caller passed in and still holds, nor a buffer a
65//! `String` abandoned when it grew.
66//! - **No `PartialEq`** — prevents accidental non-constant-time comparisons of
67//! secret material. Compare individual fields explicitly if needed.
68//! - **`Clone` is explicit** — cloning is supported but documented so that
69//! callers are aware they are duplicating sensitive material in memory.
70//!
71//! # Example
72//!
73//! ```rust
74//! use quack_rs::secrets::{SecretEntry, SecretsManager};
75//!
76//! struct MySecrets {
77//! // In practice, the extension's own credential source: environment
78//! // variables, a config option, a file. The C API offers no route to
79//! // DuckDB's CREATE SECRET storage (see above).
80//! entries: Vec<SecretEntry>,
81//! }
82//!
83//! impl SecretsManager for MySecrets {
84//! fn get_secret(&self, name: &str, secret_type: &str) -> Option<SecretEntry> {
85//! self.entries.iter()
86//! .find(|e| e.name() == name && e.secret_type() == secret_type)
87//! .cloned()
88//! }
89//!
90//! fn list_secrets(&self, secret_type: Option<&str>) -> Vec<SecretEntry> {
91//! self.entries.iter()
92//! .filter(|e| secret_type.is_none() || secret_type == Some(e.secret_type()))
93//! .cloned()
94//! .collect()
95//! }
96//!
97//! fn remove_secret(&self, _name: &str, _secret_type: &str) -> bool {
98//! false // read-only example
99//! }
100//! }
101//! ```
102
103use std::collections::HashMap;
104use std::fmt;
105
106use libduckdb_sys::duckdb_connection;
107
108use crate::error::ExtensionError;
109use crate::vector::complex::ListVector;
110
111/// Metadata about one secret the user has configured in `DuckDB`.
112///
113/// Not a [`SecretEntry`]: `DuckDB` hands out no credential as such.
114/// `secret_string` is `DuckDB`'s own rendering, with the fields the secret
115/// type declares sensitive replaced by `redacted` — which can still leave
116/// credentials in it (see [`list_duckdb_secrets`]). `Debug` therefore prints
117/// its length, not its text.
118///
119/// Returned by [`list_duckdb_secrets`].
120#[derive(Clone, PartialEq, Eq)]
121#[non_exhaustive]
122pub struct DuckDbSecretInfo {
123 /// The secret's name, as given to `CREATE SECRET`.
124 pub name: String,
125 /// The secret type — `s3`, `http`, `azure`, and so on.
126 pub secret_type: String,
127 /// The provider that supplied it (`config`, `credential_chain`, …).
128 pub provider: String,
129 /// Whether the secret is persisted rather than session-scoped.
130 pub persistent: bool,
131 /// Where a persistent secret is stored.
132 pub storage: String,
133 /// The URI prefixes the secret applies to, e.g. `s3://bucket/`.
134 pub scope: Vec<String>,
135 /// `DuckDB`'s own rendering of the secret, with the fields its type
136 /// declares sensitive redacted. **It can still contain credentials** (an
137 /// `http` secret's `extra_http_headers` up to `DuckDB` 1.5.x, for one), so
138 /// do not log it.
139 pub secret_string: String,
140}
141
142impl fmt::Debug for DuckDbSecretInfo {
143 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144 f.debug_struct("DuckDbSecretInfo")
145 .field("name", &self.name)
146 .field("secret_type", &self.secret_type)
147 .field("provider", &self.provider)
148 .field("persistent", &self.persistent)
149 .field("storage", &self.storage)
150 .field("scope", &self.scope)
151 .field(
152 "secret_string",
153 &format_args!("<{} bytes, not shown>", self.secret_string.len()),
154 )
155 .finish()
156 }
157}
158
159/// Lists the secrets configured in the `DuckDB` instance behind `connection`.
160///
161/// This queries the `duckdb_secrets()` table function, which is the only route
162/// an extension has: the extension C API has no secret functions at all.
163///
164/// # What it returns, and what it can leak
165///
166/// `DuckDB` redacts the fields each secret type declares sensitive. A secret
167/// created as `(TYPE s3, KEY_ID 'AKIA…', SECRET 'super-secret-value')` comes
168/// back as `…;key_id=AKIA…;secret=redacted`. Use this to discover *which*
169/// secrets exist and what they cover — to choose a scope, or to tell the user
170/// which one is missing — not to authenticate with them.
171///
172/// Redaction is per field, so `secret_string` can still hold a credential: an
173/// `http` secret's `extra_http_headers` (an `Authorization` header, say) is
174/// rendered in full up to `DuckDB` 1.5.x (2.0.0 redacts it), as is every field of a secret type that declares none
175/// sensitive, and on `DuckDB` 1.4.4 and 1.5.0 even an `http` secret's
176/// `bearer_token`. Do not log `secret_string`; [`DuckDbSecretInfo`]'s `Debug` omits
177/// it for that reason.
178///
179/// # Errors
180///
181/// Returns [`ExtensionError`] if the query fails.
182///
183/// # Safety
184///
185/// `connection` must be a valid, open `duckdb_connection`.
186///
187/// # Example
188///
189/// ```rust,no_run
190/// use quack_rs::secrets::list_duckdb_secrets;
191/// # use libduckdb_sys::duckdb_connection;
192/// # unsafe fn demo(con: duckdb_connection) -> Result<(), quack_rs::error::ExtensionError> {
193/// // SAFETY: `con` is a valid, open connection.
194/// let secrets = unsafe { list_duckdb_secrets(con) }?;
195/// if !secrets.iter().any(|s| s.secret_type == "s3") {
196/// eprintln!("no S3 secret configured; run CREATE SECRET (TYPE s3, ...)");
197/// }
198/// # Ok(())
199/// # }
200/// ```
201pub unsafe fn list_duckdb_secrets(
202 connection: duckdb_connection,
203) -> Result<Vec<DuckDbSecretInfo>, ExtensionError> {
204 // `scope` is read as the VARCHAR[] it is. Casting it to VARCHAR and
205 // splitting the rendering lost elements: DuckDB renders
206 // ['http://a/, b', 'http://it\'s/'], and a split on ", " cannot tell the
207 // separator from a comma inside an element. The table function is
208 // qualified so that a user macro of the same name cannot stand in for it.
209 const SQL: &str = "SELECT name, type, provider, persistent, storage, scope, secret_string \
210 FROM system.main.duckdb_secrets()";
211
212 // SAFETY: `connection` is valid per this function's contract.
213 let mut result = unsafe { crate::query::query(connection, SQL) }?;
214
215 let mut secrets = Vec::new();
216 while let Some(chunk) = result.next_chunk()? {
217 if chunk.column_count() != 7 {
218 return Err(ExtensionError::new(
219 "duckdb_secrets() returned an unexpected number of columns",
220 ));
221 }
222 // SAFETY: the column types are fixed by the SELECT above (six VARCHAR
223 // or BOOLEAN columns and one VARCHAR[]); every row index is within the
224 // chunk, and every string is read only after its row is checked valid.
225 unsafe {
226 let text = |col: usize, row: usize| {
227 let reader = chunk.reader(col);
228 if reader.is_valid(row) {
229 reader.read_str(row).to_owned()
230 } else {
231 String::new()
232 }
233 };
234 let scopes = chunk.vector(5);
235 let elements = ListVector::child_reader(scopes, ListVector::get_size(scopes));
236 let scope_valid = chunk.reader(5);
237 let persistent = chunk.reader(3);
238 for row in 0..chunk.size() {
239 let mut scope = Vec::new();
240 if scope_valid.is_valid(row) {
241 let entry = ListVector::get_entry(scopes, row);
242 for k in 0..entry.length {
243 let Ok(at) = usize::try_from(entry.offset + k) else {
244 break;
245 };
246 if elements.is_valid(at) {
247 scope.push(elements.read_str(at).to_owned());
248 }
249 }
250 }
251 secrets.push(DuckDbSecretInfo {
252 name: text(0, row),
253 secret_type: text(1, row),
254 provider: text(2, row),
255 persistent: persistent.is_valid(row) && persistent.read_bool(row),
256 storage: text(4, row),
257 scope,
258 secret_string: text(6, row),
259 });
260 }
261 }
262 }
263 Ok(secrets)
264}
265
266/// A single secret entry retrieved from the secrets manager.
267///
268/// Contains the secret's metadata and key-value pairs. The `fields` map holds
269/// the actual secret data (e.g., `"token"`, `"username"`, `"password"`,
270/// `"client_cert_path"`).
271///
272/// # Security
273///
274/// - [`Debug`] output redacts every field value and the scope; it shows the
275/// name, type, provider and field keys.
276/// - [`Drop`] zeroizes every field value and key, the provider and the scope
277/// before deallocation, and [`with_field`][Self::with_field],
278/// [`with_provider`][Self::with_provider] and
279/// [`with_scope`][Self::with_scope] zeroize whatever they replace.
280/// - [`Clone`] is supported but creates a second copy of sensitive data in
281/// memory — use sparingly and drop clones promptly.
282/// - `PartialEq` / `Eq` are intentionally **not** implemented to prevent
283/// accidental non-constant-time comparisons of secret material.
284pub struct SecretEntry {
285 name: String,
286 secret_type: String,
287 provider: String,
288 scope: String,
289 fields: HashMap<String, String>,
290}
291
292impl SecretEntry {
293 /// Creates a new `SecretEntry` with the given name and type.
294 ///
295 /// # Example
296 ///
297 /// ```rust
298 /// use quack_rs::secrets::SecretEntry;
299 ///
300 /// let entry = SecretEntry::new("my_api_key", "bearer")
301 /// .with_provider("config")
302 /// .with_field("token", "sk-abc123");
303 /// assert_eq!(entry.name(), "my_api_key");
304 /// assert_eq!(entry.get_field("token"), Some("sk-abc123"));
305 /// ```
306 #[must_use]
307 pub fn new(name: impl Into<String>, secret_type: impl Into<String>) -> Self {
308 Self {
309 name: name.into(),
310 secret_type: secret_type.into(),
311 provider: String::new(),
312 scope: String::new(),
313 fields: HashMap::new(),
314 }
315 }
316
317 /// Returns the name of this secret.
318 #[must_use]
319 #[inline]
320 pub fn name(&self) -> &str {
321 &self.name
322 }
323
324 /// Returns the secret type (e.g., `"bearer"`, `"s3"`, `"gcs"`).
325 #[must_use]
326 #[inline]
327 pub fn secret_type(&self) -> &str {
328 &self.secret_type
329 }
330
331 /// Returns the provider that created this secret.
332 #[must_use]
333 #[inline]
334 pub fn provider(&self) -> &str {
335 &self.provider
336 }
337
338 /// Returns the scope this secret applies to.
339 #[must_use]
340 #[inline]
341 pub fn scope(&self) -> &str {
342 &self.scope
343 }
344
345 /// Returns the field key names without exposing values.
346 ///
347 /// Use this for logging or diagnostics without leaking sensitive data.
348 #[must_use]
349 pub fn field_keys(&self) -> Vec<&str> {
350 self.fields.keys().map(String::as_str).collect()
351 }
352
353 /// Sets the provider for this secret entry. A provider set earlier is
354 /// zeroized before its buffer is freed.
355 #[must_use]
356 pub fn with_provider(mut self, provider: impl Into<String>) -> Self {
357 zeroize_string(&mut self.provider);
358 self.provider = provider.into();
359 self
360 }
361
362 /// Sets the scope for this secret entry. A scope set earlier is zeroized
363 /// before its buffer is freed.
364 #[must_use]
365 pub fn with_scope(mut self, scope: impl Into<String>) -> Self {
366 zeroize_string(&mut self.scope);
367 self.scope = scope.into();
368 self
369 }
370
371 /// Adds a key-value field to this secret entry.
372 ///
373 /// Setting a key that is already present replaces its value; the old
374 /// value is zeroized before its buffer is freed, and so is the duplicate
375 /// key.
376 #[must_use]
377 pub fn with_field(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
378 let mut key = key.into();
379 let value = value.into();
380 if let Some(existing) = self.fields.get_mut(&key) {
381 // `HashMap::insert` would hand back the old value and drop it
382 // unzeroized, and drop the new, unused key the same way.
383 zeroize_string(existing);
384 *existing = value;
385 zeroize_string(&mut key);
386 } else {
387 self.fields.insert(key, value);
388 }
389 self
390 }
391
392 /// Returns the value of a field, if present.
393 #[must_use]
394 pub fn get_field(&self, key: &str) -> Option<&str> {
395 self.fields.get(key).map(String::as_str)
396 }
397
398 /// Returns the number of fields in this secret entry.
399 #[must_use]
400 #[inline]
401 pub fn field_count(&self) -> usize {
402 self.fields.len()
403 }
404
405 /// Returns `true` if this entry has no fields.
406 #[must_use]
407 #[inline]
408 pub fn is_empty(&self) -> bool {
409 self.fields.is_empty()
410 }
411}
412
413/// Zeroize a `String`'s whole allocation using volatile writes, then clear
414/// it.
415///
416/// Uses [`std::ptr::write_volatile`] to ensure the compiler cannot elide the
417/// zeroing even if the memory is about to be freed. This is the standard
418/// approach used by the `zeroize` crate, implemented inline to avoid adding
419/// a dependency — and like the `zeroize` crate it covers the spare capacity
420/// too, not just `len` bytes: a secret that was truncated, or a buffer reused
421/// for a shorter value, keeps its old bytes past the end.
422fn zeroize_string(s: &mut String) {
423 // SAFETY: `as_mut_vec()` gives mutable access to the String's backing
424 // buffer, whose allocation is `capacity()` bytes; every byte in
425 // `0..capacity` is inside it and `u8` has no invalid bit patterns, so
426 // writing through the raw pointer is sound even past `len`. Only `0u8`
427 // is written, which is valid UTF-8, and the string is cleared right
428 // after.
429 unsafe {
430 let buffer = s.as_mut_vec();
431 let base = buffer.as_mut_ptr();
432 for i in 0..buffer.capacity() {
433 std::ptr::write_volatile(base.add(i), 0);
434 }
435 }
436 s.clear();
437}
438
439impl SecretEntry {
440 /// Overwrites every owned buffer, leaving the entry empty.
441 ///
442 /// This is [`Drop`]'s whole body, split out so it can be tested: a `Drop`
443 /// impl's effect is only observable in memory that has already been freed,
444 /// which no sound test can read.
445 fn zeroize_in_place(&mut self) {
446 // Zeroize all field values (the sensitive material).
447 for value in self.fields.values_mut() {
448 zeroize_string(value);
449 }
450 // Zeroize field keys too — key names can reveal what credentials exist.
451 // HashMap doesn't expose mutable key access, so we drain and zeroize.
452 for (mut key, mut val) in self.fields.drain() {
453 zeroize_string(&mut key);
454 zeroize_string(&mut val);
455 }
456
457 // Zeroize metadata fields that may contain sensitive context.
458 zeroize_string(&mut self.provider);
459 zeroize_string(&mut self.scope);
460 }
461}
462
463impl Drop for SecretEntry {
464 // One delegation. Replacing the body with `()` is unobservable from a test —
465 // see `zeroize_in_place`, which carries the behaviour and is tested directly.
466 #[cfg_attr(test, mutants::skip)]
467 fn drop(&mut self) {
468 self.zeroize_in_place();
469 }
470}
471
472impl Clone for SecretEntry {
473 /// Clones this secret entry, duplicating all sensitive material in memory.
474 ///
475 /// Callers should be aware that cloning creates a second copy of secret
476 /// values. Drop the clone as soon as it is no longer needed to minimize
477 /// the window during which sensitive data resides in memory.
478 fn clone(&self) -> Self {
479 Self {
480 name: self.name.clone(),
481 secret_type: self.secret_type.clone(),
482 provider: self.provider.clone(),
483 scope: self.scope.clone(),
484 fields: self.fields.clone(),
485 }
486 }
487}
488
489impl fmt::Debug for SecretEntry {
490 /// Formats the secret entry with field values and the scope redacted.
491 ///
492 /// Field keys are shown; every value, and the scope (a bucket or URL
493 /// prefix is itself sensitive context, which is why `Drop` zeroizes it),
494 /// is replaced with `"[REDACTED]"`. Use
495 /// [`get_field`][SecretEntry::get_field] and [`scope`][SecretEntry::scope]
496 /// to read them in code.
497 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
498 let redacted_fields: HashMap<&str, &str> = self
499 .fields
500 .keys()
501 .map(|k| (k.as_str(), "[REDACTED]"))
502 .collect();
503
504 f.debug_struct("SecretEntry")
505 .field("name", &self.name)
506 .field("secret_type", &self.secret_type)
507 .field("provider", &self.provider)
508 .field(
509 "scope",
510 &if self.scope.is_empty() {
511 ""
512 } else {
513 "[REDACTED]"
514 },
515 )
516 .field("fields", &redacted_fields)
517 .finish()
518 }
519}
520
521impl fmt::Display for SecretEntry {
522 /// Formats a human-readable summary without exposing any secret values.
523 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
524 write!(
525 f,
526 "Secret(name={:?}, type={:?}, provider={:?}, fields={})",
527 self.name,
528 self.secret_type,
529 self.provider,
530 self.fields.len()
531 )
532 }
533}
534
535/// Trait for accessing `DuckDB`'s secrets management system.
536///
537/// Extensions implement this trait to provide a safe Rust interface over
538/// `DuckDB`'s native `CREATE SECRET` / `DROP SECRET` storage. A typical
539/// implementation wraps `DuckDB`'s C API or maintains an in-memory cache
540/// synchronized with the `DuckDB` catalog.
541///
542/// # Thread safety
543///
544/// Implementations must be safe to call from multiple threads. `DuckDB` may
545/// invoke extension callbacks concurrently.
546///
547/// # Security
548///
549/// Implementations should:
550/// - Never log secret field values (use [`SecretEntry::field_keys`] for
551/// diagnostics).
552/// - Ensure that `remove_secret` zeroizes the secret data, not just
553/// removes the reference.
554/// - Minimize the lifetime of [`SecretEntry`] clones.
555pub trait SecretsManager: Send + Sync {
556 /// Retrieves a secret by name and type.
557 ///
558 /// Returns `None` if no matching secret exists.
559 fn get_secret(&self, name: &str, secret_type: &str) -> Option<SecretEntry>;
560
561 /// Lists all secrets, optionally filtered by type.
562 ///
563 /// If `secret_type` is `None`, all secrets are returned.
564 ///
565 /// # Security note
566 ///
567 /// The returned entries contain full secret values. Callers should avoid
568 /// storing or logging the result. For diagnostics, iterate and use
569 /// [`SecretEntry::field_keys`] instead of [`SecretEntry::get_field`].
570 fn list_secrets(&self, secret_type: Option<&str>) -> Vec<SecretEntry>;
571
572 /// Removes a secret by name and type.
573 ///
574 /// Returns `true` if the secret was found and removed, `false` otherwise.
575 /// Implementations should zeroize the secret data before deallocation.
576 fn remove_secret(&self, name: &str, secret_type: &str) -> bool;
577}
578
579#[cfg(test)]
580mod tests {
581 use super::*;
582
583 #[test]
584 fn secret_entry_builder() {
585 let entry = SecretEntry::new("test", "bearer")
586 .with_provider("config")
587 .with_scope("https://api.example.com")
588 .with_field("token", "abc123")
589 .with_field("refresh_token", "xyz789");
590
591 assert_eq!(entry.name(), "test");
592 assert_eq!(entry.secret_type(), "bearer");
593 assert_eq!(entry.provider(), "config");
594 assert_eq!(entry.scope(), "https://api.example.com");
595 assert_eq!(entry.get_field("token"), Some("abc123"));
596 assert_eq!(entry.get_field("refresh_token"), Some("xyz789"));
597 assert_eq!(entry.get_field("nonexistent"), None);
598 assert_eq!(entry.field_count(), 2);
599 assert!(!entry.is_empty());
600 }
601
602 #[test]
603 fn zeroizing_an_entry_clears_every_buffer_it_owns() {
604 // `Drop` runs exactly this, and the crate advertises zeroize-on-drop as
605 // a security property — so it is worth an assertion rather than a
606 // reading of the code.
607 let mut entry = SecretEntry::new("test", "bearer")
608 .with_provider("config")
609 .with_scope("https://api.example.com")
610 .with_field("token", "abc123");
611
612 entry.zeroize_in_place();
613
614 assert_eq!(entry.field_count(), 0, "fields must be drained");
615 assert_eq!(entry.get_field("token"), None);
616 assert_eq!(entry.provider(), "", "provider must be overwritten");
617 assert_eq!(entry.scope(), "", "scope must be overwritten");
618 }
619
620 #[test]
621 fn secret_entry_new_defaults() {
622 let entry = SecretEntry::new("s", "s3");
623 assert_eq!(entry.provider(), "");
624 assert_eq!(entry.scope(), "");
625 assert!(entry.is_empty());
626 assert_eq!(entry.field_count(), 0);
627 }
628
629 #[test]
630 #[allow(clippy::redundant_clone)]
631 fn secret_entry_clone() {
632 let e1 = SecretEntry::new("a", "b").with_field("k", "v");
633 let e2 = e1.clone();
634 assert_eq!(e2.name(), "a");
635 assert_eq!(e2.get_field("k"), Some("v"));
636 }
637
638 #[test]
639 fn debug_redacts_field_values() {
640 let entry =
641 SecretEntry::new("api_key", "bearer").with_field("token", "super-secret-value-12345");
642
643 let debug_output = format!("{entry:?}");
644
645 // The actual secret value must NOT appear in debug output.
646 assert!(
647 !debug_output.contains("super-secret-value-12345"),
648 "Debug output must not contain secret values: {debug_output}"
649 );
650 // The field key SHOULD appear (it's metadata, not the secret).
651 assert!(
652 debug_output.contains("token"),
653 "Debug should show field keys"
654 );
655 // The redaction marker should appear.
656 assert!(
657 debug_output.contains("[REDACTED]"),
658 "Debug should show [REDACTED] for values"
659 );
660 }
661
662 #[test]
663 fn debug_redacts_the_scope_that_drop_treats_as_sensitive() {
664 let entry = SecretEntry::new("n", "s3")
665 .with_provider("config")
666 .with_scope("s3://private-bucket/");
667 let debug = format!("{entry:?}");
668 assert!(!debug.contains("private-bucket"), "{debug}");
669 assert!(debug.contains("scope: \"[REDACTED]\""), "{debug}");
670 assert!(debug.contains("config"), "the provider is shown: {debug}");
671 // An unset scope is not dressed up as a redacted one.
672 let bare = format!("{:?}", SecretEntry::new("n", "s3"));
673 assert!(bare.contains("scope: \"\""), "{bare}");
674 }
675
676 #[test]
677 fn replacing_a_field_provider_or_scope_keeps_only_the_new_value() {
678 let entry = SecretEntry::new("n", "t")
679 .with_field("token", "old")
680 .with_field("token", "new")
681 .with_field("other", "x")
682 .with_provider("p1")
683 .with_provider("p2")
684 .with_scope("s1")
685 .with_scope("s2");
686 assert_eq!(entry.get_field("token"), Some("new"));
687 assert_eq!(entry.get_field("other"), Some("x"));
688 assert_eq!(entry.field_count(), 2);
689 assert_eq!(entry.provider(), "p2");
690 assert_eq!(entry.scope(), "s2");
691 }
692
693 #[test]
694 fn display_does_not_leak_values() {
695 let entry =
696 SecretEntry::new("api_key", "bearer").with_field("token", "super-secret-value-12345");
697
698 let display_output = format!("{entry}");
699
700 assert!(
701 !display_output.contains("super-secret-value-12345"),
702 "Display must not contain secret values: {display_output}"
703 );
704 assert!(
705 display_output.contains("api_key"),
706 "Display should show the secret name"
707 );
708 }
709
710 #[test]
711 fn field_keys_returns_keys_only() {
712 let entry = SecretEntry::new("x", "y")
713 .with_field("token", "secret1")
714 .with_field("key_id", "secret2");
715
716 let keys = entry.field_keys();
717 assert_eq!(keys.len(), 2);
718 assert!(keys.contains(&"token"));
719 assert!(keys.contains(&"key_id"));
720 }
721
722 #[test]
723 fn drop_zeroizes_field_values() {
724 // We cannot observe memory after drop, but we can verify that
725 // `zeroize_string` really overwrote the buffer rather than just
726 // shortening the string.
727 let mut s = String::from("sensitive-data-here");
728 let len = s.len();
729
730 zeroize_string(&mut s);
731 assert!(s.is_empty(), "String should be empty after zeroize");
732
733 // Look at the buffer *through the String*, after the mutation. Taking
734 // `s.as_ptr()` beforehand and reading it here would be a stale
735 // borrow: `zeroize_string`'s `&mut` retag invalidates it, which Miri
736 // reports as undefined behaviour under Stacked Borrows and which the
737 // compiler is free to reorder around.
738 //
739 // `clear()` does not deallocate, so bytes `0..len` are still allocated
740 // and still initialised — by zeroes, if the function did its job.
741 // SAFETY: `len <= capacity` (the string only shrank), and every byte in
742 // that range was initialised before `clear()` and overwritten with 0,
743 // which is valid UTF-8. `set_len(0)` restores the invariant before the
744 // borrow ends.
745 unsafe {
746 let buf = s.as_mut_vec();
747 assert!(len <= buf.capacity());
748 buf.set_len(len);
749 assert!(
750 buf.iter().all(|&b| b == 0),
751 "All bytes should be zero after zeroize"
752 );
753 buf.set_len(0);
754 }
755 }
756
757 #[test]
758 fn zeroize_empty_string_is_safe() {
759 let mut s = String::new();
760 zeroize_string(&mut s);
761 assert_eq!(s, "");
762 }
763
764 struct InMemorySecrets {
765 entries: Vec<SecretEntry>,
766 }
767
768 impl SecretsManager for InMemorySecrets {
769 fn get_secret(&self, name: &str, secret_type: &str) -> Option<SecretEntry> {
770 self.entries
771 .iter()
772 .find(|e| e.name() == name && e.secret_type() == secret_type)
773 .cloned()
774 }
775
776 fn list_secrets(&self, secret_type: Option<&str>) -> Vec<SecretEntry> {
777 self.entries
778 .iter()
779 .filter(|e| secret_type.is_none() || secret_type == Some(e.secret_type()))
780 .cloned()
781 .collect()
782 }
783
784 fn remove_secret(&self, _name: &str, _secret_type: &str) -> bool {
785 false
786 }
787 }
788
789 #[test]
790 fn in_memory_secrets_manager() {
791 let mgr = InMemorySecrets {
792 entries: vec![
793 SecretEntry::new("api_key", "bearer").with_field("token", "t1"),
794 SecretEntry::new("bucket", "s3").with_field("key_id", "k1"),
795 ],
796 };
797
798 assert!(mgr.get_secret("api_key", "bearer").is_some());
799 assert!(mgr.get_secret("api_key", "s3").is_none());
800 assert!(mgr.get_secret("missing", "bearer").is_none());
801
802 let all = mgr.list_secrets(None);
803 assert_eq!(all.len(), 2);
804
805 let s3_only = mgr.list_secrets(Some("s3"));
806 assert_eq!(s3_only.len(), 1);
807 assert_eq!(s3_only[0].name(), "bucket");
808 }
809
810 #[test]
811 fn secrets_manager_is_send_sync() {
812 fn assert_send_sync<T: Send + Sync>() {}
813 assert_send_sync::<InMemorySecrets>();
814 }
815
816 #[test]
817 fn secret_entry_empty_name_and_type() {
818 let entry = SecretEntry::new("", "");
819 assert_eq!(entry.name(), "");
820 assert_eq!(entry.secret_type(), "");
821 }
822
823 #[test]
824 fn with_field_overwrites_existing_key() {
825 let entry = SecretEntry::new("s", "t")
826 .with_field("token", "old-value")
827 .with_field("token", "new-value");
828 assert_eq!(entry.get_field("token"), Some("new-value"));
829 assert_eq!(entry.field_count(), 1);
830 }
831
832 #[test]
833 fn debug_redacts_empty_field_value() {
834 let entry = SecretEntry::new("s", "t").with_field("key", "");
835 let debug = format!("{entry:?}");
836 // Even empty field values must be redacted in debug output
837 assert!(debug.contains("[REDACTED]"));
838 assert!(debug.contains("key"));
839 }
840
841 #[test]
842 fn display_shows_field_count_not_values() {
843 let entry = SecretEntry::new("s", "t")
844 .with_field("a", "secret1")
845 .with_field("b", "secret2")
846 .with_field("c", "secret3");
847 let display = format!("{entry}");
848 assert!(display.contains("fields=3"));
849 assert!(!display.contains("secret1"));
850 assert!(!display.contains("secret2"));
851 assert!(!display.contains("secret3"));
852 }
853
854 /// Reads back the bytes `zeroize_string` wrote.
855 ///
856 /// Every pointer into the buffer is derived **after** `zeroize_string`
857 /// returns. Taking one beforehand — from `&s` *or* from `&mut s` — and
858 /// reading it afterwards is undefined behaviour under Stacked Borrows,
859 /// because the `&mut` retag inside `zeroize_string` pops the earlier tag off
860 /// the borrow stack. Miri catches exactly this; the CI `miri` job exists
861 /// because two earlier versions of this helper did not.
862 fn zeroize_and_read_back(text: &str) -> Vec<u8> {
863 let mut s = String::from(text);
864 let len = s.len();
865 zeroize_string(&mut s);
866 assert_eq!(s, "");
867 assert!(s.capacity() >= len, "the buffer must not have been freed");
868 // SAFETY: `clear()` sets the length to zero without deallocating, so
869 // bytes `0..len` are still allocated and still initialised — with
870 // zeroes, if the function did its job. NUL is valid UTF-8, and
871 // `set_len(0)` restores the String's invariant before the borrow ends.
872 let bytes = unsafe {
873 let buf = s.as_mut_vec();
874 buf.set_len(len);
875 let copy = buf.clone();
876 buf.set_len(0);
877 copy
878 };
879 drop(s);
880 bytes
881 }
882
883 #[test]
884 fn zeroize_string_with_special_characters() {
885 let bytes = zeroize_and_read_back("p@$$w0rd!#%^&*()_+-=[]{}|;':\",./<>?");
886 assert_ne!(bytes, [] as [u8; 0]);
887 assert!(bytes.iter().all(|&b| b == 0));
888 }
889
890 #[test]
891 fn zeroize_string_with_unicode() {
892 let bytes = zeroize_and_read_back("pässwörd🔑秘密");
893 assert!(bytes.len() > "pässwörd🔑秘密".chars().count(), "multi-byte");
894 assert!(bytes.iter().all(|&b| b == 0));
895 }
896
897 #[test]
898 fn drop_zeroizes_metadata_fields() {
899 // Verify that provider and scope are zeroized on drop
900 let mut entry = SecretEntry::new("name", "type")
901 .with_provider("my-provider")
902 .with_scope("https://example.com");
903
904 // Zeroize directly to test
905 zeroize_string(&mut entry.provider);
906 assert_eq!(entry.provider, "");
907 zeroize_string(&mut entry.scope);
908 assert_eq!(entry.scope, "");
909 }
910
911 #[test]
912 fn list_secrets_with_no_matching_type() {
913 let mgr = InMemorySecrets {
914 entries: vec![SecretEntry::new("a", "bearer").with_field("token", "t1")],
915 };
916 let result = mgr.list_secrets(Some("s3"));
917 assert!(result.is_empty());
918 }
919
920 #[test]
921 fn remove_secret_returns_false() {
922 let mgr = InMemorySecrets {
923 entries: vec![SecretEntry::new("a", "b")],
924 };
925 assert!(!mgr.remove_secret("a", "b"));
926 }
927
928 #[test]
929 fn secret_entry_many_fields() {
930 let mut entry = SecretEntry::new("s", "t");
931 for i in 0..100 {
932 entry = entry.with_field(format!("key_{i}"), format!("value_{i}"));
933 }
934 assert_eq!(entry.field_count(), 100);
935 assert_eq!(entry.get_field("key_50"), Some("value_50"));
936 assert_eq!(entry.field_keys().len(), 100);
937 }
938}