1use 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#[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 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 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
57pub type Labels = BTreeMap<String, String>;
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
62#[serde(rename_all = "snake_case")]
63pub enum VersionState {
64 Active,
66 Pending,
68 Previous,
70 Retired,
72 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
101#[serde(rename_all = "snake_case")]
102pub enum Which {
103 #[default]
105 Active,
106 Pending,
108 Previous,
110}
111
112impl Which {
113 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
125pub struct VersionMeta {
126 pub version: u32,
128 pub state: VersionState,
130 pub created_at: i64,
132 pub created_by: String,
134}
135
136#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
139#[non_exhaustive]
140pub struct SecretMeta {
141 pub id: SecretId,
143 pub scope: Scope,
145 pub name: String,
147 pub kind: String,
149 pub environment: Environment,
151 pub labels: Labels,
153 pub created_at: i64,
155 pub created_by: String,
157 pub updated_at: i64,
159 pub active_version: u32,
161 pub pending_version: Option<u32>,
163 pub previous_version: Option<u32>,
165}
166
167impl SecretMeta {
168 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
178pub 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#[derive(Debug, Clone, PartialEq, Eq)]
205#[non_exhaustive]
206pub struct NewSecret {
207 pub scope: Scope,
209 pub name: String,
211 pub kind: String,
213 pub environment: Environment,
215 pub labels: Labels,
217}
218
219impl NewSecret {
220 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 pub fn kind(mut self, kind: impl Into<String>) -> Self {
227 self.kind = kind.into();
228 self
229 }
230
231 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
255pub struct Plaintext(Zeroizing<Vec<u8>>);
257
258impl Plaintext {
259 pub(crate) fn new(bytes: Zeroizing<Vec<u8>>) -> Self {
260 Plaintext(bytes)
261 }
262
263 pub fn as_bytes(&self) -> &[u8] {
265 &self.0
266 }
267
268 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 pub fn len(&self) -> usize {
275 self.0.len()
276 }
277
278 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}