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
|
//! What a signed value says, read the one way every part of continuum reads it: a
//! string `cv2.<value>.<meta>.<signature>` (each base64url, unpadded), the value JSON,
//! the meta JSON with exactly its fields, neither holding a newline, the signature
//! decoding. A string that isn't one in every respect is a plain string, wherever it
//! is read: the store's order and reads (`store`), the checks (`access::envelope`), the
//! API.
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD as B64URL};
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
/// What every envelope starts with.
pub(crate) const START: &str = "cv2.";
/// What a signed value says: its value, and its meta.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Payload {
pub(crate) value: JsonValue,
/// 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) user: String,
pub(crate) at: u64,
/// One more than that of the envelope it replaces; 0 where it replaces none.
pub(crate) seq: u64,
pub(crate) prev: String,
}
/// An envelope's meta, as it is written: these fields, no other.
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Meta {
swarm: String,
path: Vec<String>,
user: String,
at: u64,
seq: u64,
prev: String,
}
impl Payload {
/// The bytes its user signs: the value, a newline, the meta.
#[cfg(test)]
pub(crate) fn signed(&self) -> Vec<u8> {
let meta = Meta {
swarm: self.swarm.clone(),
path: self.path.clone(),
user: self.user.clone(),
at: self.at,
seq: self.seq,
prev: self.prev.clone(),
};
let mut bytes = serde_json::to_vec(&self.value).expect("a value is JSON");
bytes.push(b'\n');
bytes.extend(serde_json::to_vec(&meta).expect("a meta is JSON"));
bytes
}
}
/// An envelope opened, unchecked: the bytes signed, what it says, the signature's blob.
pub(crate) struct Opened {
pub(crate) signed: Vec<u8>,
pub(crate) payload: Payload,
pub(crate) signature: Vec<u8>,
}
/// `text` opened as an envelope, unchecked; why not, if it isn't one.
pub(crate) fn open(text: &str) -> Result<Opened, String> {
let not_one = || "not a signed value (cv2.<value>.<meta>.<signature>)".to_owned();
let mut parts = text.strip_prefix(START).ok_or_else(not_one)?.split('.');
let (Some(value), Some(meta), Some(signature), None) =
(parts.next(), parts.next(), parts.next(), parts.next())
else {
return Err(not_one());
};
let decoded = |part: &str, what: &str| {
let bytes = B64URL
.decode(part)
.map_err(|error| format!("its {what} doesn't decode: {error}"))?;
// One line each: the bytes signed part at the one newline between them.
if bytes.contains(&b'\n') {
return Err(format!("its {what} holds a newline"));
}
Ok(bytes)
};
let mut signed = decoded(value, "value")?;
let value: JsonValue = serde_json::from_slice(&signed)
.map_err(|error| format!("its value isn't JSON: {error}"))?;
let meta = decoded(meta, "meta")?;
let Meta {
swarm,
path,
user,
at,
seq,
prev,
} = serde_json::from_slice(&meta).map_err(|error| format!("its meta isn't one: {error}"))?;
signed.push(b'\n');
signed.extend(meta);
let signature = B64URL
.decode(signature)
.map_err(|error| format!("its signature doesn't decode: {error}"))?;
let payload = Payload {
value,
swarm,
path,
user,
at,
seq,
prev,
};
Ok(Opened {
signed,
payload,
signature,
})
}
/// What `text` says, if it is an envelope.
pub(crate) fn read(text: &str) -> Option<Payload> {
open(text).ok().map(|opened| opened.payload)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn envelope(value: &str, meta: &str, signature: &str) -> String {
format!(
"{START}{}.{}.{}",
B64URL.encode(value),
B64URL.encode(meta),
B64URL.encode(signature)
)
}
const META: &str = r#"{"swarm":"s","path":["a"],"user":"alice","at":1,"seq":2,"prev":""}"#;
/// One reading: what isn't an envelope in every respect is none.
#[test]
fn what_an_envelope_is() {
let good = envelope("1", META, "sig");
let payload = read(&good).unwrap();
assert_eq!(payload.value, json!(1));
assert_eq!(payload.seq, 2);
for not_one in [
// A meta short of its fields, or with one more.
envelope("1", r#"{"seq":2}"#, "sig"),
envelope(
"1",
r#"{"swarm":"s","path":["a"],"user":"alice","at":1,"seq":2,"prev":"","more":1}"#,
"sig",
),
// A field twice.
envelope(
"1",
r#"{"swarm":"s","path":["a"],"user":"alice","at":1,"seq":2,"seq":3,"prev":""}"#,
"sig",
),
// A fifth part, a value that isn't JSON, a newline, another prefix.
format!("{good}.more"),
envelope("not json", META, "sig"),
envelope("1\n", META, "sig"),
good.replacen("cv2.", "cv1.", 1),
] {
assert!(read(¬_one).is_none(), "{not_one}");
}
}
}
|