aboutsummaryrefslogtreecommitdiffstats
path: root/src/access/envelope.rs
blob: e0c8909ff3359eacf8daf96e4893b21467dfe412 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
//! Values signed by their user: under a strict policy (`access::policy`), at what
//! decides who may do what and at the paths the swarm lists as user-signed
//! (`_continuum/access/userSigned`, `listed`; `signed_paths`), the value is a signed envelope, one
//! string, `cv1.<payload>.<signature>` (each base64url, unpadded). The payload is JSON:
//! the `path` it is for (segments), the `value` (`null`: deleted), the `user` who
//! signed it, when (`at`, Unix ms, by the signer's clock), and `prev`: the SHA-256 (hex)
//! of the envelope it replaces, empty if none. The signature is the user's, with one
//! of its keys (`registry::User::keys`), over the payload's bytes, as
//! `ssh-keygen -Y sign -n continuum-value` makes it (`access::sshsig`), its SSHSIG blob.
//!
//! It travels with the value, through replays and snapshots alike, and anyone can check
//! it (`check`): a node before it writes or applies one, a client reading it. `prev`
//! keeps a member from putting an older signed value back: an envelope only replaces
//! the one it names. A node never writes there but as its user signed it.

use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD as B64URL};
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
use sha2::{Digest, Sha256};

use super::{Right, registry, sshsig};
use crate::document::{ReadDoc, meta, store};

/// What a signature over a payload is for (`sshsig`).
pub(crate) const NAMESPACE: &str = "continuum-value";
/// What every envelope starts with.
const PREFIX: &str = "cv1";

/// Where the swarm lists the user-signed paths: a list of paths, each a list of
/// segments.
pub(crate) fn listed_at() -> Vec<String> {
    meta::path(&[meta::ACCESS, "userSigned"])
}

/// The paths `doc` lists as user-signed; an entry that isn't a list of strings is left
/// out.
pub(crate) fn listed(doc: &impl ReadDoc) -> Vec<Vec<String>> {
    let Ok(Some(JsonValue::Array(entries))) = store::read_plain(doc, &listed_at()) else {
        return Vec::new();
    };
    entries
        .iter()
        .filter_map(|entry| {
            entry
                .as_array()?
                .iter()
                .map(|segment| segment.as_str().map(str::to_owned))
                .collect()
        })
        .collect()
}

/// What decides who may do what, whose values are always user-signed under a strict
/// policy (`access::policy`): every user's entry, every entry of `_continuum/access`,
/// every ban. A `*` segment stands for any one key.
fn deciding() -> Vec<Vec<String>> {
    [meta::USERS, meta::ACCESS, meta::BANNED]
        .iter()
        .map(|part| meta::path(&[part, "*"]))
        .collect()
}

/// The paths whose values their users sign under a strict policy: what decides who may
/// do what (`deciding`), and those `doc` lists (`listed`).
pub(crate) fn signed_paths(doc: &impl ReadDoc) -> Vec<Vec<String>> {
    let mut paths = deciding();
    paths.extend(listed(doc));
    paths
}

/// The user-signed path `path` is at or within, if any, of `signed` (`signed_paths`):
/// its `*` segments as `path` has them.
pub(crate) fn signed_path(signed: &[Vec<String>], path: &[String]) -> Option<Vec<String>> {
    signed.iter().find_map(|pattern| {
        (path.len() >= pattern.len() && agree(pattern, path))
            .then(|| path[..pattern.len()].to_vec())
    })
}

/// Whether `path` is where a user-signed value goes, of `signed` (`signed_paths`).
pub(crate) fn is_signed(signed: &[Vec<String>], path: &[String]) -> bool {
    signed
        .iter()
        .any(|pattern| pattern.len() == path.len() && agree(pattern, path))
}

/// Whether a user-signed value of `signed` may be below `path` (`signed_paths`).
pub(crate) fn above_signed(signed: &[Vec<String>], path: &[String]) -> bool {
    signed
        .iter()
        .any(|pattern| pattern.len() > path.len() && agree(pattern, path))
}

/// Whether a write at `path` reaches a user-signed value of `signed` (`signed_paths`):
/// at one, within one, or above one.
pub(crate) fn reaches_signed(signed: &[Vec<String>], path: &[String]) -> bool {
    signed.iter().any(|pattern| agree(pattern, path))
}

/// Whether `pattern` and `path` agree as far as both go (`*`: any key).
fn agree(pattern: &[String], path: &[String]) -> bool {
    pattern
        .iter()
        .zip(path)
        .all(|(segment, key)| segment == "*" || segment == key)
}

/// A signed value's payload.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub(crate) struct Payload {
    /// The swarm it is for: one user, with the same name and key in two swarms, signs
    /// for one only.
    pub(crate) swarm: String,
    pub(crate) path: Vec<String>,
    pub(crate) value: JsonValue,
    pub(crate) user: String,
    pub(crate) at: u64,
    pub(crate) prev: String,
}

/// An envelope checked (`check`): what it says, and the key that signed it.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Signed {
    pub(crate) payload: Payload,
    pub(crate) key: sshsig::PublicKey,
}

/// What `prev` names for `envelope`, the one replaced (none: empty).
pub(crate) fn digest(envelope: Option<&str>) -> String {
    envelope.map_or_else(String::new, |envelope| {
        Sha256::digest(envelope.as_bytes())
            .iter()
            .map(|byte| format!("{byte:02x}"))
            .collect()
    })
}

/// The envelope of `payload` (its exact bytes) signed by `signature` (armored, as
/// `ssh-keygen -Y sign` writes it).
pub(crate) fn seal(payload: &[u8], armored: &str) -> Result<String, String> {
    let blob = sshsig::dearmor(armored)?;
    Ok(format!(
        "{PREFIX}.{}.{}",
        B64URL.encode(payload),
        B64URL.encode(blob)
    ))
}

/// What `envelope` holds, unchecked: its payload's bytes, the payload, the signature's
/// blob.
fn open(envelope: &str) -> Result<(Vec<u8>, Payload, Vec<u8>), String> {
    let mut parts = envelope.split('.');
    let (Some(PREFIX), Some(payload), Some(signature), None) =
        (parts.next(), parts.next(), parts.next(), parts.next())
    else {
        return Err("not a signed value (cv1.<payload>.<signature>)".to_owned());
    };
    let bytes = B64URL
        .decode(payload)
        .map_err(|error| format!("its payload doesn't decode: {error}"))?;
    let parsed: Payload = serde_json::from_slice(&bytes)
        .map_err(|error| format!("its payload isn't one: {error}"))?;
    let signature = B64URL
        .decode(signature)
        .map_err(|error| format!("its signature doesn't decode: {error}"))?;
    Ok((bytes, parsed, signature))
}

/// What `envelope` says, unchecked: for showing a value (`check` before taking it).
pub(crate) fn read(envelope: &str) -> Result<Payload, String> {
    open(envelope).map(|(_, payload, _)| payload)
}

/// Checks `envelope` as the value at `path`, replacing `previous` (the envelope there
/// before, if any), against the user registry `doc` holds (as the writer saw it): for
/// its swarm, that path, naming what it replaces, signed by one of its user's keys, a user who may
/// write there.
pub(crate) fn check(
    doc: &impl ReadDoc,
    envelope: &str,
    path: &[String],
    previous: Option<&str>,
) -> Result<Signed, String> {
    let (bytes, payload, signature) = open(envelope)?;
    let swarm = store::read_path(
        doc,
        &crate::document::meta::path(&[crate::document::meta::SWARM]),
    )
    .ok()
    .flatten();
    if swarm.as_ref().and_then(JsonValue::as_str) != Some(payload.swarm.as_str()) {
        return Err(format!("signed for swarm {}, not this one", payload.swarm));
    }
    if payload.path != path {
        return Err(format!(
            "signed for /{}, not /{}",
            payload.path.join("/"),
            path.join("/")
        ));
    }
    if payload.prev != digest(previous) {
        return Err("it doesn't replace the value there (prev)".to_owned());
    }
    let key = sshsig::verify_blob(&signature, NAMESPACE, &bytes)?;
    let user =
        registry::user(doc, &payload.user).ok_or_else(|| format!("no user {}", payload.user))?;
    if !user.keys.values().any(|known| *known == key) {
        return Err(format!("{} has no key {}", payload.user, key.fingerprint()));
    }
    if !user.caps().allows(Right::Write, path) {
        return Err(format!(
            "{} may not write /{}",
            payload.user,
            path.join("/")
        ));
    }
    Ok(Signed { payload, key })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::document::Document;
    use crate::document::testing::change;
    use ed25519_dalek::SigningKey;
    use serde_json::json;

    fn path(text: &str) -> Vec<String> {
        text.split('/').map(str::to_owned).collect()
    }

    /// A registry with alice, who may write `config` and holds `key`'s public key, and
    /// bob, who holds it too but may write nothing.
    fn registry_with(key: &SigningKey) -> Document {
        let line = sshsig::PublicKey(key.verifying_key().to_bytes()).line();
        let mut doc = Document::new();
        change(&mut doc, |doc| {
            store::write_path(doc, &path("_continuum/swarm"), &json!("s")).unwrap();
            let mut alice = registry::entry("root", 1, &[(path("config"), &[Right::Write][..])]);
            alice["keys"] = json!({ "laptop": line });
            store::write_path(doc, &registry::user_path("alice"), &alice).unwrap();
            let mut bob = registry::entry("root", 1, &[]);
            bob["keys"] = json!({ "laptop": line });
            store::write_path(doc, &registry::user_path("bob"), &bob).unwrap();
        });
        doc
    }

    fn signed(key: &SigningKey, payload: &Payload) -> String {
        let bytes = serde_json::to_vec(payload).unwrap();
        seal(&bytes, &sshsig::sign(key, NAMESPACE, &bytes)).unwrap()
    }

    fn payload(user: &str, at: &str, value: JsonValue, prev: &str) -> Payload {
        Payload {
            swarm: "s".to_owned(),
            path: path(at),
            value,
            user: user.to_owned(),
            at: 1,
            prev: prev.to_owned(),
        }
    }

    /// Signed for its path, replacing what is there, by one of its user's keys, a user
    /// who may write there: taken; anything else refused.
    #[test]
    fn what_an_envelope_must_be() {
        let key = SigningKey::from_bytes(&[5; 32]);
        let other = SigningKey::from_bytes(&[6; 32]);
        let doc = registry_with(&key);
        let first = signed(
            &key,
            &payload("alice", "config", json!({"mode": "fast"}), ""),
        );
        let checked = check(&doc, &first, &path("config"), None).unwrap();
        assert_eq!(checked.payload.value, json!({"mode": "fast"}));
        assert_eq!(read(&first).unwrap().user, "alice");
        // Another path, another key, a user who may not, an unknown one.
        assert!(check(&doc, &first, &path("other"), None).is_err());
        let foreign = signed(&other, &payload("alice", "config", json!(1), ""));
        assert!(check(&doc, &foreign, &path("config"), None).is_err());
        let bobs = signed(&key, &payload("bob", "config", json!(1), ""));
        assert!(check(&doc, &bobs, &path("config"), None).is_err());
        let nobodys = signed(&key, &payload("carol", "config", json!(1), ""));
        assert!(check(&doc, &nobodys, &path("config"), None).is_err());
        // Replacing: only what it names.
        let second = signed(
            &key,
            &payload("alice", "config", json!(null), &digest(Some(&first))),
        );
        assert!(check(&doc, &second, &path("config"), Some(&first)).is_ok());
        assert!(check(&doc, &second, &path("config"), None).is_err());
        assert!(check(&doc, &first, &path("config"), Some(&second)).is_err());
        // Tampered with.
        let tampered = first.replacen("cv1.", "cv1.e30", 1);
        assert!(check(&doc, &tampered, &path("config"), None).is_err());
        assert!(check(&doc, "plain", &path("config"), None).is_err());
        // For another swarm.
        let elsewhere = signed(
            &key,
            &Payload {
                swarm: "t".to_owned(),
                ..payload("alice", "config", json!({"mode": "fast"}), "")
            },
        );
        assert!(check(&doc, &elsewhere, &path("config"), None).is_err());
    }

    #[test]
    fn listed_paths() {
        let mut doc = Document::new();
        change(&mut doc, |doc| {
            store::write_path(doc, &listed_at(), &json!([["config"], ["a", "b"], "junk"])).unwrap();
        });
        assert_eq!(listed(&doc), vec![path("config"), path("a/b")]);
        let signed = signed_paths(&doc);
        assert_eq!(signed_path(&signed, &path("config")), Some(path("config")));
        assert_eq!(signed_path(&signed, &path("a/b/c")), Some(path("a/b")));
        assert_eq!(signed_path(&signed, &path("a")), None);
        assert_eq!(
            signed_path(&signed, &path("_continuum/users/alice/caps")),
            Some(path("_continuum/users/alice"))
        );
        assert_eq!(signed_path(&signed, &path("_continuum/users")), None);
        assert_eq!(
            signed_path(&signed, &path("_continuum/access/policy")),
            Some(path("_continuum/access/policy"))
        );
        assert!(is_signed(&signed, &path("_continuum/users/alice")));
        assert!(!is_signed(&signed, &path("_continuum/users/alice/caps")));
        assert!(above_signed(&signed, &path("_continuum/users")));
        assert!(above_signed(&signed, &path("a")));
        assert!(!above_signed(&signed, &path("a/b")));
        assert!(reaches_signed(&signed, &path("a")));
        assert!(reaches_signed(&signed, &path("a/b/c")));
        assert!(!reaches_signed(&signed, &path("a/c")));
        assert!(!reaches_signed(&signed, &path("_continuum/members/x")));
    }
}