Skip to main content

engenho_controllers/pv_binder/
identity.rs

1//! A claim's volume identity is its UID, never its name.
2//!
3//! ★ THE DEFECT. The binder used to name a dynamically provisioned PV
4//! `pvc-<ns>-<name>` and back it with `<root>/<ns>-<name>`. A name is
5//! reusable; an object's uid is not. Delete a claim, create another under
6//! the same namespace and name, and the new claim was handed the same PV
7//! name and the same directory: the provision re-Put the old PV over itself
8//! and the new claim mounted every byte the deleted claim had written.
9//!
10//! ★ THE SHAPE.
11//!
12//!   * [`ClaimUid`] is the only way to hold a claim's uid, and
13//!     [`ClaimUid::of`] is its only constructor. It reads `metadata.uid` and
14//!     refuses an absent one ([`NoVolumeIdentity::UidAbsent`]) and one that
15//!     cannot safely name a volume or a directory
16//!     ([`NoVolumeIdentity::UidMalformed`]): the uid becomes part of a
17//!     filesystem path, so `../..` is not a uid.
18//!   * [`PvName::for_claim`] is the only constructor of a dynamic PV's name,
19//!     and it takes a `&ClaimUid`, so a name derived from anything else does
20//!     not compile. It renders upstream's `pvc-<uid>`.
21//!   * [`PvName::local_path_dir`] is the only constructor of the backing
22//!     directory, `<root>/pvc-<uid>_<ns>_<name>` (the rancher local-path
23//!     layout: the uid keeps it unique, the namespace and name keep it
24//!     readable on the host).
25//!
26//! Tier-honest: deriving a name or a directory from a claim's name alone is
27//! unrepresentable through these types. The binder could still build a
28//! string by hand; only review keeps it on this path.
29
30use std::fmt;
31
32use serde_json::Value;
33
34/// Upstream's prefix for a dynamically provisioned PV.
35const PV_PREFIX: &str = "pvc-";
36
37/// The longest uid accepted: a DNS label, so `pvc-<uid>` is a valid object
38/// name. An upstream uid is a 36-character UUID.
39const MAX_UID_LEN: usize = 63;
40
41/// Why a claim cannot be given a volume yet. The claim stays Pending, and
42/// [`note`](Self::note) is the sweep's report note.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum NoVolumeIdentity {
45    /// `metadata.uid` is absent or null.
46    UidAbsent,
47    /// `metadata.uid` is present but is not a lowercase DNS label, so it
48    /// cannot name a PV or a directory.
49    UidMalformed,
50    /// The claim's namespace or name is not a single path component, so
51    /// the backing directory would not be one directory under the root.
52    NameNotAPathComponent,
53}
54
55impl NoVolumeIdentity {
56    /// A fixed description, used as the sweep's skip note.
57    #[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/// A claim's `metadata.uid`, checked to be safe as part of an object name
83/// and a directory name.
84#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct ClaimUid(String);
86
87impl ClaimUid {
88    /// Read `metadata.uid` off a claim.
89    ///
90    /// # Errors
91    ///
92    /// [`NoVolumeIdentity::UidAbsent`] when the field is absent or null;
93    /// [`NoVolumeIdentity::UidMalformed`] when it is not a string, or not a
94    /// lowercase DNS label (1-63 of `a-z`, `0-9`, `-`, alphanumeric at both
95    /// ends).
96    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    /// The uid a PV's `claimRef` recorded for its claim, held to the same
105    /// rule as the claim's own: at reclaim the backing directory is derived
106    /// from it again, and a directory about to be removed is exactly where
107    /// `../..` must not reach.
108    ///
109    /// # Errors
110    ///
111    /// [`NoVolumeIdentity::UidMalformed`] when `uid` is not a lowercase DNS
112    /// label.
113    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    /// The uid.
122    #[must_use]
123    pub fn as_str(&self) -> &str {
124        &self.0
125    }
126
127    /// Does a `claimRef.uid` name this claim? Only a string equal to it
128    /// does; a number or an object is not a uid that can be checked.
129    #[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/// The name of the PV dynamically provisioned for one claim: `pvc-<uid>`.
142#[derive(Debug, Clone, PartialEq, Eq)]
143pub struct PvName {
144    uid: ClaimUid,
145}
146
147impl PvName {
148    /// The PV name for the claim with this uid. The only constructor.
149    #[must_use]
150    pub fn for_claim(uid: &ClaimUid) -> Self {
151        Self { uid: uid.clone() }
152    }
153
154    /// Is `name` this PV's name?
155    #[must_use]
156    pub fn names(&self, name: &str) -> bool {
157        name.strip_prefix(PV_PREFIX) == Some(self.uid.as_str())
158    }
159
160    /// The local-path backing directory, `<root>/pvc-<uid>_<ns>_<name>`.
161    ///
162    /// # Errors
163    ///
164    /// [`NoVolumeIdentity::NameNotAPathComponent`] when `namespace` or
165    /// `name` is empty or holds `/`, `\` or NUL. The `pvc-` prefix already
166    /// keeps the component from being `.` or `..`.
167    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/// A local-path PV's backing directory. Built only by
194/// [`PvName::local_path_dir`]; renders `<root>/pvc-<uid>_<ns>_<name>`.
195#[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
213/// A lowercase DNS label: 1-63 of `a-z0-9-`, alphanumeric at both ends.
214fn 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
228/// One path component: non-empty, and no separator or NUL.
229fn 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    /// Two incarnations of one namespace/name share nothing.
257    #[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    /// The uid becomes part of a path. Anything that is not a DNS label is
293    /// refused, a traversal first among them.
294    #[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    /// A recorded uid is read by the claim's own rule, so reclaim derives
336    /// the directory provision derived and nothing else.
337    #[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}