Skip to main content

ic_storage/
key.rs

1use serde::{Deserialize, Deserializer, Serialize, de::Error as _};
2use std::{fmt, str::FromStr};
3
4const MAX_KEY_BYTES: usize = 128;
5
6///
7/// StableKey
8///
9/// Canonical durable logical allocation identity.
10///
11/// A stable key names the logical store, not the current storage backend or
12/// allocation ID. Once committed, the key is permanently bound to its
13/// allocation; changing the key declares a new logical store.
14///
15/// Construction and deserialization enforce the same bounded canonical grammar.
16/// A checked key establishes identity syntax, not allocation or open authority.
17///
18
19#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
20pub struct StableKey(String);
21
22impl<'de> Deserialize<'de> for StableKey {
23    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
24        // Retain the serialized newtype shape before checking its owned text.
25        #[derive(Deserialize)]
26        #[serde(rename = "StableKey")]
27        struct Text(String);
28
29        let Text(value) = Text::deserialize(deserializer)?;
30        validate(&value).map_err(D::Error::custom)?;
31        Ok(Self(value))
32    }
33}
34
35impl StableKey {
36    /// Parse and validate a canonical stable key string.
37    ///
38    /// Keys are bounded lowercase ASCII dot-separated names ending in a
39    /// nonzero `.vN` suffix.
40    pub fn parse(value: impl AsRef<str>) -> Result<Self, StableKeyError> {
41        let value = value.as_ref();
42        validate(value)?;
43        Ok(Self(value.to_string()))
44    }
45
46    /// Borrow the canonical stable-key string.
47    #[must_use]
48    pub fn as_str(&self) -> &str {
49        &self.0
50    }
51
52    /// Consume the key and return the canonical stable-key string.
53    #[must_use]
54    pub fn into_string(self) -> String {
55        self.0
56    }
57}
58
59impl AsRef<str> for StableKey {
60    fn as_ref(&self) -> &str {
61        self.as_str()
62    }
63}
64
65impl fmt::Display for StableKey {
66    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
67        formatter.write_str(self.as_str())
68    }
69}
70
71impl FromStr for StableKey {
72    type Err = StableKeyError;
73
74    fn from_str(value: &str) -> Result<Self, Self::Err> {
75        Self::parse(value)
76    }
77}
78
79///
80/// StableKeyError
81///
82/// Stable-key grammar validation failure.
83#[derive(Clone, Debug, Eq, thiserror::Error, PartialEq)]
84#[error("stable key '{stable_key}' is invalid: {reason}")]
85pub struct StableKeyError {
86    /// Rejected stable-key string.
87    pub stable_key: String,
88    /// Stable-key grammar failure.
89    pub reason: &'static str,
90}
91
92pub fn validate(stable_key: &str) -> Result<(), StableKeyError> {
93    if stable_key.is_empty() {
94        return invalid(stable_key, "must not be empty");
95    }
96    if stable_key.len() > MAX_KEY_BYTES {
97        return invalid(stable_key, "must be at most 128 bytes");
98    }
99    if !stable_key.is_ascii() {
100        return invalid(stable_key, "must be ASCII");
101    }
102    if stable_key.bytes().any(|byte| byte.is_ascii_uppercase()) {
103        return invalid(stable_key, "must be lowercase");
104    }
105    if stable_key
106        .bytes()
107        .any(|byte| matches!(byte, b'\t'..=b'\r' | b' '))
108    {
109        return invalid(stable_key, "must not contain whitespace");
110    }
111    if stable_key.bytes().any(|byte| matches!(byte, b'/' | b'-')) {
112        return invalid(stable_key, "must not contain slashes or hyphens");
113    }
114    if stable_key.starts_with('.') || stable_key.ends_with('.') {
115        return invalid(stable_key, "must not start or end with a dot");
116    }
117
118    let Some(version_index) = stable_key
119        .as_bytes()
120        .windows(2)
121        .rposition(|pair| pair == b".v")
122    else {
123        return invalid(stable_key, "must end with .vN");
124    };
125    let version = &stable_key[version_index + 2..];
126    if version.is_empty()
127        || version.starts_with('0')
128        || !version.bytes().all(|byte| byte.is_ascii_digit())
129    {
130        return invalid(stable_key, "version suffix must be nonzero .vN");
131    }
132
133    let prefix = &stable_key[..version_index];
134    if prefix.is_empty() {
135        return invalid(
136            stable_key,
137            "must contain at least one segment before version",
138        );
139    }
140
141    for segment in prefix.as_bytes().split(|byte| *byte == b'.') {
142        if let Err(reason) = validate_segment(segment) {
143            return invalid(stable_key, reason);
144        }
145    }
146
147    Ok(())
148}
149
150// A namespace plus its synthetic `v1` suffix must fit the same key grammar.
151// Borrow the prefix rather than allocating a temporary key just to discard it.
152pub fn is_key_prefix(value: &str) -> bool {
153    let Some(prefix) = value.strip_suffix('.') else {
154        return false;
155    };
156    value.len() <= MAX_KEY_BYTES - "v1".len()
157        && prefix
158            .as_bytes()
159            .split(|byte| *byte == b'.')
160            .all(|segment| validate_segment(segment).is_ok())
161}
162
163fn validate_segment(segment: &[u8]) -> Result<(), &'static str> {
164    let mut bytes = segment.iter().copied();
165    let Some(first) = bytes.next() else {
166        return Err("must not contain empty segments");
167    };
168    if !first.is_ascii_lowercase() {
169        return Err("segments must start with a lowercase letter");
170    }
171    if !bytes.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_') {
172        return Err("segments may contain only lowercase letters, digits, and underscores");
173    }
174    Ok(())
175}
176
177fn invalid<T>(stable_key: &str, reason: &'static str) -> Result<T, StableKeyError> {
178    Err(StableKeyError {
179        stable_key: stable_key.to_string(),
180        reason,
181    })
182}
183
184#[cfg(test)]
185mod tests {
186    use super::*;
187
188    #[test]
189    fn parse_stores_the_string_it_validates() {
190        struct ChangingKey(std::cell::Cell<bool>);
191
192        impl AsRef<str> for ChangingKey {
193            fn as_ref(&self) -> &str {
194                if self.0.replace(true) {
195                    "INVALID"
196                } else {
197                    "app.rows.v1"
198                }
199            }
200        }
201
202        let key = StableKey::parse(ChangingKey(std::cell::Cell::new(false))).unwrap();
203        assert_eq!(key.as_str(), "app.rows.v1");
204    }
205
206    #[test]
207    fn accepts_canonical_keys() {
208        assert_eq!(
209            StableKey::parse("app.users.primary.v1")
210                .expect("valid key")
211                .as_str(),
212            "app.users.primary.v1"
213        );
214        assert!(StableKey::parse("framework.core.auth_state.v12").is_ok());
215        assert!(StableKey::parse("app.vault.v1").is_ok());
216        assert!(StableKey::parse("app.v1.v2").is_ok());
217    }
218
219    #[test]
220    fn key_decode_enforces_grammar_and_preserves_current_encoding() {
221        let key = StableKey::parse("app.users.v1").unwrap();
222        let json = serde_json::to_string(&key).unwrap();
223        assert_eq!(json, "\"app.users.v1\"");
224        assert_eq!(serde_json::from_str::<StableKey>(&json).unwrap(), key);
225        let bytes = ic_wire::native::encode(&key, crate::StorageConfig::default().wire).unwrap();
226        assert_eq!(bytes, b"\x0capp.users.v1");
227        assert_eq!(
228            ic_wire::native::decode::<StableKey>(&bytes, crate::StorageConfig::default().wire)
229                .unwrap(),
230            key
231        );
232
233        for invalid in [
234            "App.users.v1",
235            "app.users.v0",
236            "app.vault",
237            "app.users.v1.tail",
238            "app..users.v1",
239            &"x".repeat(129),
240        ] {
241            let json = serde_json::to_string(invalid).unwrap();
242            assert!(serde_json::from_str::<StableKey>(&json).is_err());
243            let bytes =
244                ic_wire::native::encode(&invalid, crate::StorageConfig::default().wire).unwrap();
245            assert!(
246                ic_wire::native::decode::<StableKey>(&bytes, crate::StorageConfig::default().wire)
247                    .is_err()
248            );
249        }
250    }
251
252    #[test]
253    fn whitespace_rejection_preserves_input_and_precedence() {
254        for whitespace in [' ', '\t', '\n', '\u{b}', '\u{c}', '\r'] {
255            let key = format!("app.us{whitespace}ers.v1");
256            assert_eq!(
257                StableKey::parse(&key),
258                Err(StableKeyError {
259                    stable_key: key,
260                    reason: "must not contain whitespace",
261                })
262            );
263        }
264        for (key, reason) in [
265            ("app.us\u{a0}ers.v1", "must be ASCII"),
266            ("App.us\u{b}ers.v1", "must be lowercase"),
267        ] {
268            assert_eq!(StableKey::parse(key).unwrap_err().reason, reason);
269        }
270    }
271
272    #[test]
273    fn rejects_noncanonical_keys() {
274        for key in [
275            "",
276            "App.users.v1",
277            "app.users",
278            "app.users.v0",
279            "app..users.v1",
280            ".app.users.v1",
281            "app.users.v1.",
282            "app-users.v1",
283            "app/users.v1",
284            "app.1users.v1",
285        ] {
286            assert!(StableKey::parse(key).is_err(), "{key} should fail");
287        }
288    }
289}