1use std::fmt;
9
10use schemars::JsonSchema;
11use serde::{Deserialize, Serialize};
12
13#[cfg(test)]
14mod tests;
15
16#[derive(
18 Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
19)]
20#[serde(deny_unknown_fields)]
21pub struct SecretName {
22 #[serde(default, skip_serializing_if = "Option::is_none")]
24 pub storage: Option<String>,
25 pub path: String,
27 #[serde(default, skip_serializing_if = "Option::is_none")]
30 pub key: Option<String>,
31 #[serde(default, skip_serializing_if = "Option::is_none")]
34 pub default: Option<String>,
35}
36
37impl SecretName {
38 #[must_use]
40 pub fn new(path: impl Into<String>, key: Option<&str>) -> Self {
41 Self {
42 storage: None,
43 path: path.into(),
44 key: key.map(str::to_owned),
45 default: None,
46 }
47 }
48
49 #[must_use]
51 pub fn spec(&self) -> String {
52 match &self.key {
53 Some(key) => format!("{}#{key}", self.path),
54 None => self.path.clone(),
55 }
56 }
57
58 pub fn check(&self) -> Result<(), String> {
64 let problem = |reason: &str| Err(format!("`{self}`: {reason}"));
65 if let Some(storage) = &self.storage
66 && let Err(reason) = check_storage_name(storage)
67 {
68 return problem(&reason);
69 }
70 if self.path.len() > 1 && self.path.ends_with('/') {
71 return problem("a path doesn't end with `/` (a prefix is `SecretPrefix(...)`)");
72 }
73 if let Err(reason) = check_path(&self.path, "path") {
74 return problem(&reason);
75 }
76 if let Some(key) = &self.key {
77 if key.is_empty() {
78 return problem("the key after `#` is empty");
79 }
80 if key.contains('#') || key.contains('\0') {
81 return problem("a key contains neither `#` nor NUL");
82 }
83 } else if self.default.is_some() {
84 return problem("a default is a key's (`.get(key, default)`)");
85 }
86 Ok(())
87 }
88}
89
90impl fmt::Display for SecretName {
91 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94 match &self.storage {
95 Some(storage) if !attribute(storage) => {
96 write!(f, "secrets.storage({})", py_str(storage))?;
97 }
98 Some(storage) => write!(f, "secrets.{storage}")?,
99 None => f.write_str("secrets")?,
100 }
101 write!(f, "[{}]", py_str(&self.path))?;
102 match (&self.key, &self.default) {
103 (None, _) => Ok(()),
104 (Some(key), None) => write!(f, "[{}]", py_str(key)),
105 (Some(key), Some(default)) => {
106 write!(f, ".get({}, {})", py_str(key), py_str(default))
107 }
108 }
109 }
110}
111
112const PYTHON_KEYWORDS: [&str; 35] = [
114 "False", "None", "True", "and", "as", "assert", "async", "await", "break", "class", "continue",
115 "def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import",
116 "in", "is", "lambda", "nonlocal", "not", "or", "pass", "raise", "return", "try", "while",
117 "with", "yield",
118];
119
120fn attribute(storage: &str) -> bool {
124 !storage.is_empty()
125 && !storage.starts_with(|c: char| c.is_ascii_digit() || c == '_')
126 && storage
127 .chars()
128 .all(|c| c.is_ascii_alphanumeric() || c == '_')
129 && storage != "storage"
130 && storage != "value"
131 && !PYTHON_KEYWORDS.contains(&storage)
132}
133
134fn py_str(text: &str) -> String {
137 use std::fmt::Write as _;
138 let quote = if text.contains('\'') && !text.contains('"') {
139 '"'
140 } else {
141 '\''
142 };
143 let mut out = String::with_capacity(text.len() + 2);
144 out.push(quote);
145 for c in text.chars() {
146 match c {
147 '\\' => out.push_str("\\\\"),
148 '\n' => out.push_str("\\n"),
149 '\r' => out.push_str("\\r"),
150 '\t' => out.push_str("\\t"),
151 c if c == quote => {
152 out.push('\\');
153 out.push(c);
154 }
155 c if c.is_control() => {
156 let _ = write!(out, "\\x{:02x}", u32::from(c));
157 }
158 c => out.push(c),
159 }
160 }
161 out.push(quote);
162 out
163}
164
165#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
169#[serde(tag = "kind", rename_all = "snake_case")]
170pub enum SecretDecl {
171 Secret(SecretName),
173 Prefix {
175 #[serde(default, skip_serializing_if = "Option::is_none")]
177 storage: Option<String>,
178 prefix: String,
180 },
181}
182
183impl SecretDecl {
184 pub fn check(&self) -> Result<(), String> {
190 match self {
191 Self::Secret(name) if name.default.is_some() => Err(format!(
192 "`{name}`: a default is for a value passed to a task, not a declaration in \
193 `secrets=`"
194 )),
195 Self::Secret(name) => name.check(),
196 Self::Prefix { storage, prefix } => {
197 let problem = |reason: &str| Err(format!("`{self}`: {reason}"));
198 if let Some(storage) = storage
199 && let Err(reason) = check_storage_name(storage)
200 {
201 return problem(&reason);
202 }
203 let Some(inner) = prefix.strip_suffix('/') else {
204 return problem("a prefix ends with `/`");
205 };
206 if let Err(reason) = check_path(inner, "prefix") {
207 return problem(&reason);
208 }
209 Ok(())
210 }
211 }
212 }
213
214 #[must_use]
217 pub fn covers(&self, name: &SecretName) -> bool {
218 match self {
219 Self::Secret(declared) => {
220 declared.storage == name.storage
221 && declared.path == name.path
222 && (declared.key.is_none() || declared.key == name.key)
223 }
224 Self::Prefix { storage, prefix } => {
225 *storage == name.storage && name.path.starts_with(prefix.as_str())
226 }
227 }
228 }
229
230 #[must_use]
232 pub fn storage(&self) -> Option<&str> {
233 match self {
234 Self::Secret(name) => name.storage.as_deref(),
235 Self::Prefix { storage, .. } => storage.as_deref(),
236 }
237 }
238}
239
240impl fmt::Display for SecretDecl {
241 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
243 match self {
244 Self::Secret(name) => name.fmt(f),
245 Self::Prefix {
246 storage: Some(storage),
247 prefix,
248 } => write!(
249 f,
250 "SecretPrefix({}, storage={})",
251 py_str(prefix),
252 py_str(storage)
253 ),
254 Self::Prefix {
255 storage: None,
256 prefix,
257 } => write!(f, "SecretPrefix({})", py_str(prefix)),
258 }
259 }
260}
261
262pub fn check_storage_name(name: &str) -> Result<(), String> {
268 if name.is_empty() {
269 return Err("the storage's name is empty".to_owned());
270 }
271 if !name
272 .chars()
273 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
274 {
275 return Err(format!(
276 "storage `{name}`: a name has only letters, digits, `_` and `-`"
277 ));
278 }
279 if name == "default" {
280 return Err("`default` names the default storage's setting, not a storage".to_owned());
281 }
282 Ok(())
283}
284
285fn check_path(path: &str, what: &str) -> Result<(), String> {
287 if path.is_empty() {
288 return Err(format!("the {what} is empty"));
289 }
290 if path.contains('#') {
291 return Err(format!("a {what} contains no `#` (it separates the key)"));
292 }
293 if path.contains('\0') {
294 return Err(format!("a {what} contains no NUL"));
295 }
296 if path.split('/').any(str::is_empty) {
297 return Err(format!(
298 "a {what} has no empty part (no leading `/`, no `//`)"
299 ));
300 }
301 Ok(())
302}