Skip to main content

weirdnet_vault/
secret.rs

1//! Secret ids, metadata, new-secret requests and plaintext.
2use crate::error::{Result, VaultError};
3use crate::scope::{Environment, Scope};
4use serde::{Deserialize, Serialize};
5use std::collections::BTreeMap;
6use std::fmt;
7use std::str::FromStr;
8use zeroize::Zeroizing;
9
10/// A secret's id (a random UUID).
11#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
12#[serde(try_from = "String", into = "String")]
13pub struct SecretId(String);
14
15impl SecretId {
16    pub(crate) fn random() -> Self {
17        SecretId(uuid::Uuid::new_v4().to_string())
18    }
19
20    /// Parses a UUID.
21    pub fn parse(s: &str) -> Result<Self> {
22        uuid::Uuid::parse_str(s.trim()).map(|u| SecretId(u.hyphenated().to_string())).map_err(|_| VaultError::invalid("secret id", format!("{s:?}")))
23    }
24
25    /// The text form.
26    pub fn as_str(&self) -> &str {
27        &self.0
28    }
29}
30
31impl fmt::Display for SecretId {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        f.write_str(&self.0)
34    }
35}
36
37impl FromStr for SecretId {
38    type Err = VaultError;
39    fn from_str(s: &str) -> Result<Self> {
40        SecretId::parse(s)
41    }
42}
43
44impl TryFrom<String> for SecretId {
45    type Error = VaultError;
46    fn try_from(s: String) -> Result<Self> {
47        SecretId::parse(&s)
48    }
49}
50
51impl From<SecretId> for String {
52    fn from(s: SecretId) -> String {
53        s.0
54    }
55}
56
57/// Free-form labels.
58pub type Labels = BTreeMap<String, String>;
59
60/// Where a version stands.
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
62#[serde(rename_all = "snake_case")]
63pub enum VersionState {
64    /// Serving reads.
65    Active,
66    /// Staged by a rotation, not yet serving.
67    Pending,
68    /// The version before the last promotion, kept until retired.
69    Previous,
70    /// Replaced and wiped.
71    Retired,
72    /// A pending version dropped before promotion, wiped.
73    Discarded,
74}
75
76impl VersionState {
77    pub(crate) fn as_str(self) -> &'static str {
78        match self {
79            VersionState::Active => "active",
80            VersionState::Pending => "pending",
81            VersionState::Previous => "previous",
82            VersionState::Retired => "retired",
83            VersionState::Discarded => "discarded",
84        }
85    }
86
87    pub(crate) fn parse(s: &str) -> Result<Self> {
88        Ok(match s {
89            "active" => VersionState::Active,
90            "pending" => VersionState::Pending,
91            "previous" => VersionState::Previous,
92            "retired" => VersionState::Retired,
93            "discarded" => VersionState::Discarded,
94            other => return Err(VaultError::Storage(format!("unknown version state {other:?}"))),
95        })
96    }
97}
98
99/// Which version to use or retrieve.
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
101#[serde(rename_all = "snake_case")]
102pub enum Which {
103    /// The active version.
104    #[default]
105    Active,
106    /// The staged version (to try new credentials before promoting them).
107    Pending,
108    /// The version before the last promotion.
109    Previous,
110}
111
112impl Which {
113    /// `active`, `pending` or `previous`.
114    pub fn as_str(self) -> &'static str {
115        match self {
116            Which::Active => "active",
117            Which::Pending => "pending",
118            Which::Previous => "previous",
119        }
120    }
121}
122
123/// One version's metadata (never its value).
124#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
125pub struct VersionMeta {
126    /// Its number, from 1.
127    pub version: u32,
128    /// Where it stands.
129    pub state: VersionState,
130    /// When it was stored (ms since the Unix epoch).
131    pub created_at: i64,
132    /// Who stored it.
133    pub created_by: String,
134}
135
136/// A secret's metadata: the only secret type that is serializable, and so the only one safe
137/// to send to clients or MCP. It never holds a value.
138#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
139#[non_exhaustive]
140pub struct SecretMeta {
141    /// The id.
142    pub id: SecretId,
143    /// The scope it lives in.
144    pub scope: Scope,
145    /// Its name, unique per scope and environment.
146    pub name: String,
147    /// A free-form kind such as `api-key` or `password`.
148    pub kind: String,
149    /// Test or live; fixed at creation.
150    pub environment: Environment,
151    /// Labels.
152    pub labels: Labels,
153    /// When it was created (ms since the Unix epoch).
154    pub created_at: i64,
155    /// Who created it.
156    pub created_by: String,
157    /// When it last changed.
158    pub updated_at: i64,
159    /// The version serving reads.
160    pub active_version: u32,
161    /// A staged version, if a rotation is pending.
162    pub pending_version: Option<u32>,
163    /// The version before the last promotion, if still kept.
164    pub previous_version: Option<u32>,
165}
166
167impl SecretMeta {
168    /// The version number `which` points at, if there is one.
169    pub fn version(&self, which: Which) -> Option<u32> {
170        match which {
171            Which::Active => Some(self.active_version),
172            Which::Pending => self.pending_version,
173            Which::Previous => self.previous_version,
174        }
175    }
176}
177
178/// The most labels a secret may have.
179pub const MAX_LABELS: usize = 64;
180
181fn check_text(what: &'static str, s: &str, max: usize, allow_empty: bool) -> Result<()> {
182    if (!allow_empty && s.trim().is_empty()) || s.len() > max || s.chars().any(char::is_control) {
183        return Err(VaultError::invalid(
184            what,
185            format!("must be {}1 to {max} bytes without control characters", if allow_empty { "0 or " } else { "" }),
186        ));
187    }
188    Ok(())
189}
190
191pub(crate) fn check_identity(s: &str) -> Result<()> {
192    check_text("identity", s, 256, false)
193}
194
195/// What to create.
196///
197/// ```
198/// use weirdnet_vault::{Environment, NewSecret, Scope};
199/// let new = NewSecret::new(Scope::new(["tenant-7", "provider-a"]).unwrap(), "api", Environment::Test)
200///     .kind("api-key")
201///     .label("owner", "desk-1");
202/// assert_eq!(new.kind, "api-key");
203/// ```
204#[derive(Debug, Clone, PartialEq, Eq)]
205#[non_exhaustive]
206pub struct NewSecret {
207    /// The scope it goes in.
208    pub scope: Scope,
209    /// Its name (1 to 128 bytes), unique per scope and environment.
210    pub name: String,
211    /// A free-form kind (1 to 64 bytes); `secret` by default.
212    pub kind: String,
213    /// Test or live.
214    pub environment: Environment,
215    /// Labels (up to 64; keys 1 to 64 bytes, values up to 512).
216    pub labels: Labels,
217}
218
219impl NewSecret {
220    /// A secret named `name` in `scope`, of kind `secret`, with no labels.
221    pub fn new(scope: Scope, name: impl Into<String>, environment: Environment) -> Self {
222        NewSecret { scope, name: name.into(), kind: "secret".into(), environment, labels: Labels::new() }
223    }
224
225    /// Set the kind.
226    pub fn kind(mut self, kind: impl Into<String>) -> Self {
227        self.kind = kind.into();
228        self
229    }
230
231    /// Add a label.
232    pub fn label(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
233        self.labels.insert(key.into(), value.into());
234        self
235    }
236
237    pub(crate) fn validate(&self) -> Result<()> {
238        check_text("name", &self.name, 128, false)?;
239        check_text("kind", &self.kind, 64, false)?;
240        check_labels(&self.labels)
241    }
242}
243
244pub(crate) fn check_labels(labels: &Labels) -> Result<()> {
245    if labels.len() > MAX_LABELS {
246        return Err(VaultError::invalid("labels", format!("at most {MAX_LABELS}")));
247    }
248    for (k, v) in labels {
249        check_text("label key", k, 64, false)?;
250        check_text("label value", v, 512, true)?;
251    }
252    Ok(())
253}
254
255/// A secret value in memory: wiped on drop, never cloned, printed or serialized.
256pub struct Plaintext(Zeroizing<Vec<u8>>);
257
258impl Plaintext {
259    pub(crate) fn new(bytes: Zeroizing<Vec<u8>>) -> Self {
260        Plaintext(bytes)
261    }
262
263    /// The bytes.
264    pub fn as_bytes(&self) -> &[u8] {
265        &self.0
266    }
267
268    /// The bytes as UTF-8.
269    pub fn as_str(&self) -> Result<&str> {
270        std::str::from_utf8(&self.0).map_err(|_| VaultError::invalid("value", "not UTF-8"))
271    }
272
273    /// Length in bytes.
274    pub fn len(&self) -> usize {
275        self.0.len()
276    }
277
278    /// True when empty.
279    pub fn is_empty(&self) -> bool {
280        self.0.is_empty()
281    }
282}
283
284impl fmt::Debug for Plaintext {
285    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
286        write!(f, "Plaintext(<{} bytes redacted>)", self.0.len())
287    }
288}
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293
294    #[test]
295    fn ids_labels_and_plaintext() {
296        let id = SecretId::random();
297        assert_eq!(SecretId::parse(id.as_str()).unwrap(), id);
298        assert!(SecretId::parse("nope").is_err());
299        let p = Plaintext::new(Zeroizing::new(b"hunter2".to_vec()));
300        assert_eq!(format!("{p:?}"), "Plaintext(<7 bytes redacted>)");
301        assert_eq!(p.as_str().unwrap(), "hunter2");
302        let n = NewSecret::new(Scope::root(), "", Environment::Test);
303        assert!(n.validate().is_err());
304        let n = NewSecret::new(Scope::root(), "ok", Environment::Test).label("k", "v\n");
305        assert!(n.validate().is_err());
306        let mut l = Labels::new();
307        for i in 0..65 {
308            l.insert(format!("k{i}"), String::new());
309        }
310        assert!(check_labels(&l).is_err());
311    }
312}