engenho_controllers/pv_binder/
identity.rs1use std::fmt;
31
32use serde_json::Value;
33
34const PV_PREFIX: &str = "pvc-";
36
37const MAX_UID_LEN: usize = 63;
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum NoVolumeIdentity {
45 UidAbsent,
47 UidMalformed,
50 NameNotAPathComponent,
53}
54
55impl NoVolumeIdentity {
56 #[must_use]
58 pub const fn note(self) -> &'static str {
59 match self {
60 Self::UidAbsent => {
61 "PVC has no metadata.uid; a volume is named by the claim's uid, so the claim \
62 stays Pending until it has one"
63 }
64 Self::UidMalformed => {
65 "PVC metadata.uid is not a lowercase DNS label, so it cannot name a volume or \
66 its directory; the claim stays Pending"
67 }
68 Self::NameNotAPathComponent => {
69 "PVC namespace or name is empty or contains a path separator, so it cannot \
70 name a local-path directory; the claim stays Pending"
71 }
72 }
73 }
74}
75
76impl fmt::Display for NoVolumeIdentity {
77 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78 f.write_str(self.note())
79 }
80}
81
82#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct ClaimUid(String);
86
87impl ClaimUid {
88 pub fn of(claim: &Value) -> Result<Self, NoVolumeIdentity> {
97 match claim.get("metadata").and_then(|m| m.get("uid")) {
98 None | Some(Value::Null) => Err(NoVolumeIdentity::UidAbsent),
99 Some(Value::String(uid)) => Self::recorded(uid),
100 Some(_) => Err(NoVolumeIdentity::UidMalformed),
101 }
102 }
103
104 pub fn recorded(uid: &str) -> Result<Self, NoVolumeIdentity> {
114 if is_dns_label(uid) {
115 Ok(Self(uid.to_owned()))
116 } else {
117 Err(NoVolumeIdentity::UidMalformed)
118 }
119 }
120
121 #[must_use]
123 pub fn as_str(&self) -> &str {
124 &self.0
125 }
126
127 #[must_use]
130 pub fn is(&self, claim_ref_uid: &Value) -> bool {
131 claim_ref_uid.as_str() == Some(self.as_str())
132 }
133}
134
135impl fmt::Display for ClaimUid {
136 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137 f.write_str(&self.0)
138 }
139}
140
141#[derive(Debug, Clone, PartialEq, Eq)]
143pub struct PvName {
144 uid: ClaimUid,
145}
146
147impl PvName {
148 #[must_use]
150 pub fn for_claim(uid: &ClaimUid) -> Self {
151 Self { uid: uid.clone() }
152 }
153
154 #[must_use]
156 pub fn names(&self, name: &str) -> bool {
157 name.strip_prefix(PV_PREFIX) == Some(self.uid.as_str())
158 }
159
160 pub fn local_path_dir<'a>(
168 &'a self,
169 root: &'a str,
170 namespace: &'a str,
171 name: &'a str,
172 ) -> Result<LocalPathDir<'a>, NoVolumeIdentity> {
173 if is_path_component(namespace) && is_path_component(name) {
174 Ok(LocalPathDir {
175 root: root.trim_end_matches('/'),
176 pv: self,
177 namespace,
178 name,
179 })
180 } else {
181 Err(NoVolumeIdentity::NameNotAPathComponent)
182 }
183 }
184}
185
186impl fmt::Display for PvName {
187 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188 f.write_str(PV_PREFIX)?;
189 f.write_str(self.uid.as_str())
190 }
191}
192
193#[derive(Debug, Clone, Copy)]
196pub struct LocalPathDir<'a> {
197 root: &'a str,
198 pv: &'a PvName,
199 namespace: &'a str,
200 name: &'a str,
201}
202
203impl fmt::Display for LocalPathDir<'_> {
204 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205 write!(
206 f,
207 "{}/{}_{}_{}",
208 self.root, self.pv, self.namespace, self.name
209 )
210 }
211}
212
213fn is_dns_label(s: &str) -> bool {
215 let bytes = s.as_bytes();
216 let alnum = |b: &u8| b.is_ascii_lowercase() || b.is_ascii_digit();
217 match (bytes.first(), bytes.last()) {
218 (Some(first), Some(last)) => {
219 bytes.len() <= MAX_UID_LEN
220 && alnum(first)
221 && alnum(last)
222 && bytes.iter().all(|b| alnum(b) || *b == b'-')
223 }
224 _ => false,
225 }
226}
227
228fn is_path_component(s: &str) -> bool {
230 !s.is_empty() && !s.contains(['/', '\\', '\0'])
231}
232
233#[cfg(test)]
234mod tests {
235 use super::*;
236 use serde_json::json;
237
238 fn claim(uid: &Value) -> Value {
239 json!({ "metadata": { "name": "data", "namespace": "ns1", "uid": uid } })
240 }
241
242 #[test]
243 fn a_uuid_uid_names_the_pv_and_the_directory() {
244 let uid = ClaimUid::of(&claim(&json!("3f2a9c1e-0b7d-4e8a-9f10-2c3d4e5f6a7b"))).unwrap();
245 let pv = PvName::for_claim(&uid);
246 assert_eq!(pv.to_string(), "pvc-3f2a9c1e-0b7d-4e8a-9f10-2c3d4e5f6a7b");
247 assert!(pv.names("pvc-3f2a9c1e-0b7d-4e8a-9f10-2c3d4e5f6a7b"));
248 assert_eq!(
249 pv.local_path_dir("/data/local-path/", "ns1", "data")
250 .unwrap()
251 .to_string(),
252 "/data/local-path/pvc-3f2a9c1e-0b7d-4e8a-9f10-2c3d4e5f6a7b_ns1_data"
253 );
254 }
255
256 #[test]
258 fn two_uids_under_one_name_get_two_volumes() {
259 let first = PvName::for_claim(&ClaimUid::of(&claim(&json!("uid-first"))).unwrap());
260 let second = PvName::for_claim(&ClaimUid::of(&claim(&json!("uid-second"))).unwrap());
261 assert_ne!(first, second);
262 assert!(!second.names(&first.to_string()));
263 assert!(
264 !second.names("pvc-ns1-data"),
265 "a legacy name is not this claim's"
266 );
267 assert_ne!(
268 first
269 .local_path_dir("/r", "ns1", "data")
270 .unwrap()
271 .to_string(),
272 second
273 .local_path_dir("/r", "ns1", "data")
274 .unwrap()
275 .to_string()
276 );
277 }
278
279 #[test]
280 fn an_absent_or_null_uid_is_absent() {
281 assert_eq!(
282 ClaimUid::of(&json!({"metadata": {"name": "data"}})),
283 Err(NoVolumeIdentity::UidAbsent)
284 );
285 assert_eq!(
286 ClaimUid::of(&claim(&Value::Null)),
287 Err(NoVolumeIdentity::UidAbsent)
288 );
289 assert_eq!(ClaimUid::of(&json!({})), Err(NoVolumeIdentity::UidAbsent));
290 }
291
292 #[test]
295 fn a_uid_that_is_not_a_dns_label_is_malformed() {
296 for bad in [
297 json!(""),
298 json!("../../etc"),
299 json!("a/b"),
300 json!("UPPER"),
301 json!("-leading"),
302 json!("trailing-"),
303 json!("has_underscore"),
304 json!("x".repeat(MAX_UID_LEN + 1)),
305 json!(42),
306 json!({"uid": "x"}),
307 ] {
308 assert_eq!(
309 ClaimUid::of(&claim(&bad)),
310 Err(NoVolumeIdentity::UidMalformed),
311 "{bad}"
312 );
313 }
314 assert!(ClaimUid::of(&claim(&json!("x".repeat(MAX_UID_LEN)))).is_ok());
315 assert!(ClaimUid::of(&claim(&json!("u-1"))).is_ok());
316 }
317
318 #[test]
319 fn a_namespace_or_name_that_is_not_one_component_has_no_directory() {
320 let pv = PvName::for_claim(&ClaimUid::of(&claim(&json!("u-1"))).unwrap());
321 for (ns, name) in [
322 ("", "data"),
323 ("ns1", ""),
324 ("ns1", "a/../../b"),
325 ("n\\s", "d"),
326 ] {
327 assert_eq!(
328 pv.local_path_dir("/r", ns, name).map(|d| d.to_string()),
329 Err(NoVolumeIdentity::NameNotAPathComponent),
330 "{ns:?}/{name:?}"
331 );
332 }
333 }
334
335 #[test]
338 fn a_recorded_uid_obeys_the_claims_rule() {
339 let provisioned = ClaimUid::of(&claim(&json!("u-1"))).unwrap();
340 assert_eq!(ClaimUid::recorded("u-1"), Ok(provisioned));
341 for bad in ["", "../../etc", "a/b", "UPPER"] {
342 assert_eq!(
343 ClaimUid::recorded(bad),
344 Err(NoVolumeIdentity::UidMalformed),
345 "{bad:?}"
346 );
347 }
348 }
349
350 #[test]
351 fn only_an_equal_string_claim_ref_uid_names_the_claim() {
352 let uid = ClaimUid::of(&claim(&json!("u-1"))).unwrap();
353 assert!(uid.is(&json!("u-1")));
354 assert!(!uid.is(&json!("u-2")));
355 assert!(!uid.is(&Value::Null));
356 assert!(!uid.is(&json!(1)));
357 }
358}