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
341
342
343
344
345
346
|
//! The swarm's write protection policy (`_continuum/access/policy`): whether every node
//! judges received changes by rules by path before applying them (`access::screen`,
//! `access::rules`). Absent, nobody does: what exists keeps working as it did. Written
//! by a user who may write protocol data, as any of it.
//!
//! `{"version": 1, "signatures": "optional"}`: rules enforced; a change is its claimed
//! committer's whether or not a signature proves it (`document::signatures`).
//! `"required"`: a change is applied once a signature by its committer vouches for it,
//! and waits until then; every node signs every change it makes. `"values": "signed"`
//! (strict): signatures required, and what decides who may do what (the user registry,
//! the policy and the rest of `_continuum/access`, bans) and the paths listed in
//! `_continuum/access/userSigned` hold values their users signed (`access::envelope`),
//! so no member writes there but as a user signed it. `{"version": 2, "store": "<fold>"}`,
//! behind the `federation` feature: a swarm holding a store of that fold
//! (`docs/store.md`), written by its genesis change only (`document::events`), its
//! changes judged by what they write (`access::holding`) and signed, as required. A policy
//! this node doesn't know (another version, or a setting it lacks) stops it from taking
//! writes through the API, and it receives without judging: it can't judge as the
//! others do, so it writes nothing they might refuse, until it is upgraded.
use serde_json::Value as JsonValue;
use crate::document::{ReadDoc, meta, store};
/// The policy versions this node knows: rules by path, and a swarm holding a store.
pub(crate) const VERSION: u64 = 1;
#[cfg(feature = "federation")]
pub(crate) const STORE: u64 = 2;
/// Where the policy is.
pub(crate) fn path() -> Vec<String> {
meta::path(&[meta::ACCESS, "policy"])
}
/// What the policy says.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Policy {
/// None: changes aren't judged.
Open,
/// Rules by path enforced; with signatures `required`, only on changes a signature
/// proves.
Enforced { required: bool, strict: bool },
/// A swarm holding a store of the fold so named: changes judged by what they write,
/// and signed.
#[cfg(feature = "federation")]
Store(&'static str),
/// One this node doesn't know, and why.
Unknown(String),
}
impl Policy {
pub(crate) fn enforced(&self) -> bool {
match self {
Policy::Enforced { .. } => true,
#[cfg(feature = "federation")]
Policy::Store(_) => true,
_ => false,
}
}
/// Whether changes need a signature (`signatures: "required"`, or a store).
pub(crate) fn required(&self) -> bool {
match self {
Policy::Enforced { required, .. } => *required,
#[cfg(feature = "federation")]
Policy::Store(_) => true,
_ => false,
}
}
/// Whether values at the user-signed paths need their users' signatures
/// (`values: "signed"`, `access::envelope::signed_paths`).
pub(crate) fn strict(&self) -> bool {
matches!(self, Policy::Enforced { strict: true, .. })
}
}
/// The policy a new swarm records in its first change (`--bootstrap-policy`, its JSON),
/// checked: one this node knows; strict, only with its first users' keys
/// (`--bootstrap-keys`), or nobody could sign what decides who may do what. None
/// given: none.
pub(crate) fn first(
given: Option<&str>,
bootstrap_keys: &[String],
) -> Result<Option<JsonValue>, String> {
let Some(given) = given else {
return Ok(None);
};
let value: JsonValue = serde_json::from_str(given)
.map_err(|error| format!("bootstrap-policy isn't JSON: {error}"))?;
match as_written(&value).map_err(|error| format!("bootstrap-policy: {error}"))? {
Policy::Unknown(why) => Err(format!("bootstrap-policy: one this node doesn't know: {why}")),
Policy::Open => Err("bootstrap-policy: no policy".to_owned()),
#[cfg(feature = "federation")]
Policy::Store(_) => Err(
"bootstrap-policy: a swarm holds a store from its root's genesis change only (store-root)"
.to_owned(),
),
policy if policy.strict() && bootstrap_keys.is_empty() => Err(
"bootstrap-policy: strict, but no bootstrap-keys: nobody could sign what decides who may do what"
.to_owned(),
),
_ => Ok(Some(value)),
}
}
/// The policy `value` is, written at the policy's place, as every node reads it there.
pub(crate) fn as_written(value: &JsonValue) -> Result<Policy, String> {
let mut doc = crate::document::Document::new();
let mut write = doc.transaction();
store::write_path(&mut write, &path(), value).map_err(|error| error.to_string())?;
let policy = of(&write);
write.rollback();
Ok(policy)
}
/// The policy `doc` holds. Strict only where its `values` is a string, and a store's only
/// where its `store` is, as continuum writes them: an Automerge text there, or one holding
/// the policy, reads as a string in plain JSON, so a policy that would read so only
/// through a text is one nobody knows, never what its characters spell.
pub(crate) fn of(doc: &impl ReadDoc) -> Policy {
match store::read_plain(doc, &path()) {
Ok(Some(value)) => match read(&value) {
policy if policy.strict() && !a_string(doc, "values") => {
Policy::Unknown("values not a string".to_owned())
}
#[cfg(feature = "federation")]
Policy::Store(_) if !a_string(doc, "store") => {
Policy::Unknown("store not a string".to_owned())
}
policy => policy,
},
Ok(None) => Policy::Open,
Err(error) => Policy::Unknown(format!("it doesn't read: {error}")),
}
}
/// Whether the policy `doc` holds, read in typed JSON (where a text is tagged, and an
/// envelope reads as its payload), has a string for its `key`.
fn a_string(doc: &impl ReadDoc, key: &str) -> bool {
let typed = crate::document::typed::JsonForm {
typed: true,
..Default::default()
};
matches!(
store::read_plain_as(doc, &path(), typed),
Ok(Some(value)) if value.get(key).is_some_and(JsonValue::is_string)
)
}
/// The policy `value`, as the policy's place holds it, says.
pub(crate) fn read(value: &JsonValue) -> Policy {
let version = value.get("version").and_then(JsonValue::as_u64);
#[cfg(feature = "federation")]
if version == Some(STORE) {
return store_of(value);
}
if version != Some(VERSION) {
return Policy::Unknown(format!(
"version {}, this node knows {}",
value
.get("version")
.map_or("none".to_owned(), JsonValue::to_string),
known()
));
}
let strict = match value.get("values").and_then(JsonValue::as_str) {
None | Some("plain") => false,
Some("signed") => true,
Some(other) => return Policy::Unknown(format!("values {other:?}")),
};
match value.get("signatures").and_then(JsonValue::as_str) {
// Signed values: signed changes too.
None | Some("optional") => Policy::Enforced {
required: strict,
strict,
},
Some("required") => Policy::Enforced {
required: true,
strict,
},
Some(other) => Policy::Unknown(format!("signatures {other:?}")),
}
}
/// The versions this node knows, as its refusals name them.
fn known() -> &'static str {
#[cfg(feature = "federation")]
return "1 and 2";
#[cfg(not(feature = "federation"))]
return "1";
}
/// The store a policy of version 2 names: one this node has, and nothing else written.
#[cfg(feature = "federation")]
fn store_of(value: &JsonValue) -> Policy {
use crate::federation::store::Fold;
let fold = crate::federation::fold::Federation::NAME;
match value.as_object() {
Some(policy) if policy.len() == 2 && policy.get("store") == Some(&fold.into()) => {
Policy::Store(fold)
}
_ => Policy::Unknown(format!(
"a store, other than {}",
crate::document::events::policy(fold)
)),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::document::Document;
use crate::document::testing::change;
use serde_json::json;
fn with(policy: JsonValue) -> Policy {
let mut doc = Document::new();
change(&mut doc, |doc| {
store::write_path(doc, &path(), &policy).unwrap();
});
of(&doc)
}
#[test]
fn what_the_policy_says() {
assert_eq!(of(&Document::new()), Policy::Open);
let optional = Policy::Enforced {
required: false,
strict: false,
};
assert_eq!(with(json!({"version": 1})), optional);
assert_eq!(
with(json!({"version": 1, "signatures": "optional"})),
optional
);
assert_eq!(
with(json!({"version": 1, "signatures": "required"})),
Policy::Enforced {
required: true,
strict: false
}
);
assert_eq!(
with(json!({"version": 1, "values": "signed"})),
Policy::Enforced {
required: true,
strict: true
}
);
assert!(with(json!({"version": 1, "values": "signed"})).strict());
assert!(!with(json!({"version": 1, "signatures": "required"})).strict());
assert!(matches!(
with(json!({"version": 1, "values": "sometimes"})),
Policy::Unknown(_)
));
assert!(matches!(with(json!({"version": 2})), Policy::Unknown(_)));
assert!(matches!(with(json!({"version": 3})), Policy::Unknown(_)));
assert!(matches!(
with(json!({"version": 1, "signatures": "sometimes"})),
Policy::Unknown(_)
));
assert!(matches!(with(json!("on")), Policy::Unknown(_)));
// Strict only through a text, whatever its characters spell: one nobody knows.
let typed = |policy: JsonValue| {
use crate::document::typed::{TimestampFormat, Val};
let value = Val::from_typed_json(&policy, TimestampFormat::default()).unwrap();
let mut doc = Document::new();
change(&mut doc, |doc| {
store::write_val_path(
doc,
&path(),
&value,
store::Writing::sticky(TimestampFormat::default()),
)
.unwrap();
});
of(&doc)
};
assert!(matches!(
typed(json!({"version": 1, "values": {"$text": "signed"}})),
Policy::Unknown(_)
));
assert!(matches!(
typed(json!({"$text": "{\"version\": 1, \"values\": \"signed\"}"})),
Policy::Unknown(_)
));
}
/// A swarm holding a store of a fold this node has, as its genesis change writes it,
/// and nothing else.
#[cfg(feature = "federation")]
#[test]
fn a_store_is_one_the_node_has() {
let store = with(json!({"version": 2, "store": "federation"}));
assert_eq!(store, Policy::Store("federation"));
assert!(store.enforced() && store.required() && !store.strict());
assert!(matches!(
with(json!({"version": 2, "store": "test"})),
Policy::Unknown(_)
));
assert!(matches!(
with(json!({"version": 2, "store": "federation", "values": "signed"})),
Policy::Unknown(_)
));
let mut doc = Document::new();
change(&mut doc, |doc| {
store::write_val_path(
doc,
&path(),
&crate::document::typed::Val::Map(vec![
(
"store".to_owned(),
crate::document::typed::Val::Text("federation".to_owned()),
),
(
"version".to_owned(),
crate::document::typed::Val::Scalar(2.into()),
),
]),
store::Writing::sticky(Default::default()),
)
.unwrap();
});
assert!(matches!(of(&doc), Policy::Unknown(_)));
assert!(first(Some(r#"{"version": 2, "store": "federation"}"#), &[]).is_err());
}
/// A new swarm's policy: one this node knows; strict, only with keys to sign.
#[test]
fn the_first_policy() {
let keys = ["alice=ssh-ed25519 AAAA".to_owned()];
assert_eq!(first(None, &[]), Ok(None));
assert_eq!(
first(Some(r#"{"version": 1}"#), &[]),
Ok(Some(json!({"version": 1})))
);
assert_eq!(
first(Some(r#"{"version": 1, "values": "signed"}"#), &keys),
Ok(Some(json!({"version": 1, "values": "signed"})))
);
assert!(first(Some(r#"{"version": 1, "values": "signed"}"#), &[]).is_err());
assert!(first(Some(r#"{"version": 2}"#), &keys).is_err());
assert!(first(Some("not json"), &keys).is_err());
}
}
|