coven_format/admin.rs
1//! Admin changes in sequence slots (D6). The enclosing slot supplies identity and author.
2
3use crate::error::{require, Error, Rule};
4use crate::value::{name, Slot};
5use crate::wire::{wire_struct, Decoder, Encoder, Wire};
6pub use coven_crypto::MemberPublicKeys;
7use coven_foundation::id_source::{CircleId, DeviceId, InviteId, KeyId, MemberId, StoreId};
8use coven_merge::Audience;
9
10/// A member's role in the store (§10).
11#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
12pub enum MemberRole {
13 /// Can add and remove members and change roles.
14 Admin,
15 /// Can write data and manage their own devices.
16 Member,
17}
18
19// `coven_members.role` holds a role by its name (api.md E4).
20coven_foundation::column_names!(MemberRole, "member role", {
21 Admin => "admin",
22 Member => "member",
23});
24
25impl Wire for MemberRole {
26 fn put(&self, out: &mut Encoder) -> Result<(), Error> {
27 match self {
28 Self::Admin => 0u8,
29 Self::Member => 1,
30 }
31 .put(out)
32 }
33 fn get(input: &mut Decoder<'_>) -> Result<Self, Error> {
34 match u8::get(input)? {
35 0 => Ok(Self::Admin),
36 1 => Ok(Self::Member),
37 tag => Err(Error::UnknownTag { field: "role", tag }),
38 }
39 }
40}
41
42/// A snapshot's identity without a storage path (§16.2).
43#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
44pub struct SnapshotId {
45 /// The rows the snapshot covers.
46 pub audience: Audience,
47 /// The device that wrote the snapshot.
48 pub device: DeviceId,
49 /// The positive number in this device's snapshot sequence.
50 pub number: u64,
51}
52wire_struct!(SnapshotId, audience, device, number);
53
54/// A circle that creating a store or admitting a member makes, with the
55/// commitment to the circle key it introduces (§10.3, §13.2, D6). A creation's
56/// circles are the creator's: her private circle, whose only member she is,
57/// and the circles her first write asks for. An admission's is the admitted
58/// person's, its first and only member, and its key's one copy is the
59/// admission's own copy.
60#[derive(Clone, Debug, PartialEq, Eq)]
61pub struct NewCircle {
62 /// The new circle's id: no circle, live or deleted, has it.
63 pub circle: CircleId,
64 /// The circle's name.
65 pub name: String,
66 /// The newest breaking migration its maker's app had run, zero if none:
67 /// the circle's schema version until a raise of its own goes past it
68 /// (§15.5, §16.3).
69 pub breaking_version: u32,
70 /// The first circle key, introduced by the creation or admission.
71 pub key: KeyId,
72 /// SHA-256 of the exact 32 circle-key bytes.
73 pub key_hash: [u8; 32],
74}
75wire_struct!(NewCircle, circle, name => crate::wire::get_name, breaking_version, key, key_hash);
76impl NewCircle {
77 pub(crate) fn validate(&self) -> Result<(), Error> {
78 name(&self.name)
79 }
80}
81
82/// Every admin operation listed in §10, including store creation.
83#[derive(Clone, Debug, PartialEq, Eq)]
84pub enum StoreChange {
85 /// Create a store, name its first admin and register the writing device.
86 /// The entry's author is the first admin's stable id; `admin` supplies
87 /// that member's initial pair, which verifies this entry (D6). It records
88 /// no storage access: `SetUpStorage` does, once storage exists.
89 CreateStore {
90 /// The store's id.
91 store: StoreId,
92 /// The store's name.
93 name: String,
94 /// The first admin's initial public pair.
95 admin: MemberPublicKeys,
96 /// The first store key, introduced by this entry.
97 key: KeyId,
98 /// SHA-256 of the exact 32 store-key bytes.
99 key_hash: [u8; 32],
100 /// The name of the device that wrote this entry, belonging to its author.
101 device_name: String,
102 /// The creator's name, which every device of hers writes her profile
103 /// with, as an admission's `person` is a joiner's (§13.2).
104 person: String,
105 /// The creator's private circle, whose only member she is, as an
106 /// admission's circle is a joiner's.
107 circle: NewCircle,
108 /// The circles the creator's first write asks for, each with the
109 /// creator as its first member, in the order they were asked for.
110 circles: Vec<NewCircle>,
111 },
112 /// Record how the store's first admin reaches storage, which fixes the
113 /// kind of access every member has and, for a provider account, the
114 /// account that holds the store (§10.3). Applies once, as an admin in the
115 /// preceding state; access entries, admissions and invite shares wait
116 /// for it.
117 SetUpStorage {
118 /// The author's provider account, or the public S3 key id they use.
119 access: crate::MemberAccess,
120 },
121 /// Set the store name, as an admin in the preceding state (§10).
122 RenameStore {
123 /// The new name.
124 name: String,
125 },
126 /// Admit a joining person: add their stable id with both public keys,
127 /// their initial role and access, and register the device their request
128 /// names. Only an admission slot holds it, beside the member's key copies
129 /// (§13.2, D9).
130 AdmitMember {
131 /// The added member's stable id, fixed by the admin's invite.
132 member: MemberId,
133 /// The member's initial public pair.
134 keys: MemberPublicKeys,
135 /// The initial role.
136 role: MemberRole,
137 /// Storage access granted by the inviting owner.
138 access: crate::MemberAccess,
139 /// The joining installation, registered for the member. Never the
140 /// writing device.
141 device: DeviceId,
142 /// The joining installation's name, from its request.
143 device_name: String,
144 /// The name the member's request carried: the person's, which every
145 /// device of theirs writes their profile with (§13.2).
146 person: String,
147 /// The circle the member's request made, whose only member they are.
148 circle: NewCircle,
149 },
150 /// Recover an active member on a new device: rebind their pair, as
151 /// replace-member-keys does, set their access when the invite carried a
152 /// new S3 key, and register the device their request names. Only an
153 /// admission slot holds it (§13.2, D9).
154 RecoverMember {
155 /// The recovered member.
156 member: MemberId,
157 /// The binding which must still be current before this slot.
158 expected: MemberPublicKeys,
159 /// The member's new public pair.
160 keys: MemberPublicKeys,
161 /// The member's new storage access, as set-access records it: the
162 /// S3 key the recovery invite carries. `None` keeps their access.
163 access: Option<crate::MemberAccess>,
164 /// The new installation, registered for the member. Never the writing
165 /// device.
166 device: DeviceId,
167 /// The new installation's name, from its request.
168 device_name: String,
169 /// The new circle the member's request made, whose only member they
170 /// are: their old private circle has no reader left.
171 circle: NewCircle,
172 },
173 /// Record a member's current storage access, used by a later removal (§10):
174 /// the author's own, or an admin's replacement S3 key for another member.
175 SetAccess {
176 /// The member whose access this records.
177 member: MemberId,
178 /// The provider account, or the S3 key id and its principal; no credentials.
179 access: crate::MemberAccess,
180 },
181 /// Remove a member and delete circles left empty (§14.1).
182 RemoveMember {
183 /// The removed member.
184 member: MemberId,
185 },
186 /// Set a member's role.
187 ChangeRole {
188 /// The affected member.
189 member: MemberId,
190 /// The target role.
191 role: MemberRole,
192 },
193 /// Register the writing install for the entry's author: an install
194 /// registers only itself (§10.2).
195 AddDevice {
196 /// The device's name.
197 name: String,
198 /// The older install of the same member being replaced, if any (§19.3).
199 /// Must differ from the writing device.
200 replaces: Option<DeviceId>,
201 },
202 /// Remove a device's access.
203 RemoveDevice {
204 /// The removed install.
205 device: DeviceId,
206 },
207 /// Make a circle with its creator as its first member.
208 CreateCircle {
209 /// The new circle's id.
210 circle: CircleId,
211 /// The circle's name.
212 name: String,
213 /// The newest breaking migration its maker's app had run, zero if
214 /// none: the circle's schema version until a raise of its own goes
215 /// past it (§15.5, §16.3).
216 breaking_version: u32,
217 /// The first circle key, introduced by this entry.
218 key: KeyId,
219 /// SHA-256 of the exact 32 circle-key bytes.
220 key_hash: [u8; 32],
221 },
222 /// Rename a circle without changing its members, keys or rows.
223 RenameCircle {
224 /// The circle being renamed.
225 circle: CircleId,
226 /// Its new name.
227 name: String,
228 },
229 /// Delete a circle (§15.9).
230 DeleteCircle {
231 /// The deleted circle.
232 circle: CircleId,
233 },
234 /// Add a store member to a circle (§15.5).
235 AddCircleMember {
236 /// The circle being joined.
237 circle: CircleId,
238 /// The added member.
239 member: MemberId,
240 },
241 /// Remove a circle member, deleting the circle if left empty, and
242 /// introduce the circle's replacement key (§15.8).
243 RemoveCircleMember {
244 /// The circle being left.
245 circle: CircleId,
246 /// The removed member.
247 member: MemberId,
248 /// The replacement circle key, introduced by this entry.
249 key: KeyId,
250 /// SHA-256 of the exact 32 circle-key bytes.
251 key_hash: [u8; 32],
252 },
253 /// Introduce a key without changing audience membership (§12.1).
254 RotateKey {
255 /// The audience whose member authored the rotation.
256 audience: Audience,
257 /// The introduced key's id, which the id source supplied.
258 key: KeyId,
259 /// SHA-256 of the exact 32 key bytes.
260 key_hash: [u8; 32],
261 },
262 /// Raise an audience's app schema version with its replacement snapshot (§18.3).
263 RaiseSchema {
264 /// The new schema version.
265 version: u32,
266 /// The earlier announcement of the prepared snapshot.
267 announcement: Slot,
268 },
269 /// Reset the store's or a circle's rows to a snapshot (§19.4).
270 Reset {
271 /// The earlier announcement of the prepared reset snapshot.
272 announcement: Slot,
273 },
274 /// Replace an active member's public pair, keeping their id, role, access,
275 /// circles and devices (§10). It carries no audience keys.
276 ReplaceMemberKeys {
277 /// The member whose keys change.
278 member: MemberId,
279 /// The binding which must still be current before this slot.
280 expected: MemberPublicKeys,
281 /// The member's new public pair.
282 keys: MemberPublicKeys,
283 },
284 /// Record that the writing device's invite shares the store with a
285 /// provider account (§13.2, §14.2). Claimed before the grant, so the
286 /// owner's other devices know of the share and take it back once the
287 /// invite ends or its device is gone for good.
288 AddInviteShare {
289 /// The invite, fixed when it was made.
290 invite: InviteId,
291 /// The provider account the invite shares the store with.
292 account: String,
293 },
294 /// End the share the writing device recorded for its invite (§13.2).
295 EndInviteShare {
296 /// The invite whose share ends.
297 invite: InviteId,
298 },
299}
300
301impl StoreChange {
302 /// The circle this change makes: a circle's creation, or an admission
303 /// making its member's.
304 pub fn made_circle(&self) -> Option<&CircleId> {
305 match self {
306 Self::CreateCircle { circle, .. } => Some(circle),
307 Self::AdmitMember { circle, .. } | Self::RecoverMember { circle, .. } => {
308 Some(&circle.circle)
309 }
310 _ => None,
311 }
312 }
313
314 /// The circles a store's creation makes, in the order slot 1 makes
315 /// them: the creator's private circle, then each circle her first write
316 /// asks for. Every other change makes none of these.
317 pub fn created_circles(&self) -> impl Iterator<Item = &NewCircle> {
318 let (circle, circles) = match self {
319 Self::CreateStore { circle, circles, .. } => (Some(circle), circles.as_slice()),
320 _ => (None, [].as_slice()),
321 };
322 circle.into_iter().chain(circles)
323 }
324
325 pub(crate) fn validate(&self) -> Result<(), Error> {
326 match self {
327 Self::CreateStore { name: n, device_name, person, circle, circles, .. } => {
328 name(n)?;
329 name(device_name)?;
330 name(person)?;
331 circle.validate()?;
332 circles.iter().try_for_each(NewCircle::validate)
333 }
334 Self::AdmitMember { device_name, person, circle, .. } => {
335 name(device_name)?;
336 name(person)?;
337 circle.validate()
338 }
339 Self::RecoverMember { device_name, circle, .. } => {
340 name(device_name)?;
341 circle.validate()
342 }
343 Self::RenameStore { name: n }
344 | Self::AddDevice { name: n, .. }
345 | Self::CreateCircle { name: n, .. }
346 | Self::RenameCircle { name: n, .. } => name(n),
347 Self::RaiseSchema { version, .. } => {
348 require(*version > 0, "schema version", Rule::Required)
349 }
350 Self::Reset { .. } => Ok(()),
351 Self::AddInviteShare { account, .. } => {
352 require(!account.trim().is_empty(), "invite share account", Rule::Required)?;
353 crate::error::bound(
354 account.len(),
355 crate::member_access::MAX_TEXT,
356 "invite share account",
357 )
358 }
359 Self::RemoveMember { .. }
360 | Self::RotateKey { .. }
361 | Self::SetUpStorage { .. }
362 | Self::SetAccess { .. }
363 | Self::ChangeRole { .. }
364 | Self::RemoveDevice { .. }
365 | Self::DeleteCircle { .. }
366 | Self::AddCircleMember { .. }
367 | Self::RemoveCircleMember { .. }
368 | Self::ReplaceMemberKeys { .. }
369 | Self::EndInviteShare { .. } => Ok(()),
370 }
371 }
372}
373
374// The tag and named fields are the whole wire layout of each store change.
375macro_rules! store_changes {
376 ($($tag:literal => $variant:ident { $($field:ident $(=> $get:path)?),+ }),+ $(,)?) => {
377 impl Wire for StoreChange {
378 fn put(&self, out: &mut Encoder) -> Result<(), Error> {
379 match self { $(Self::$variant { $($field),+ } => {
380 ($tag as u8).put(out)?; $($field.put(out)?;)+ Ok(())
381 }),+ }
382 }
383 fn get(input: &mut Decoder<'_>) -> Result<Self, Error> {
384 match u8::get(input)? {
385 $($tag => Ok(Self::$variant { $($field: crate::wire::wire_struct!(@get input $(, $get)?)?),+ }),)+
386 tag => Err(Error::UnknownTag { field: "store change", tag }),
387 }
388 }
389 }
390 };
391}
392store_changes!(
393 0 => CreateStore { store, name => crate::wire::get_name, admin, device_name => crate::wire::get_name, key, key_hash, person => crate::wire::get_name, circle, circles },
394 1 => AdmitMember { member, keys, role, access, device, device_name => crate::wire::get_name, person => crate::wire::get_name, circle },
395 2 => RemoveMember { member },
396 3 => ChangeRole { member, role },
397 4 => AddDevice { name => crate::wire::get_name, replaces },
398 5 => RemoveDevice { device },
399 6 => CreateCircle { circle, name => crate::wire::get_name, breaking_version, key, key_hash },
400 7 => RenameCircle { circle, name => crate::wire::get_name },
401 8 => DeleteCircle { circle },
402 9 => AddCircleMember { circle, member },
403 10 => RemoveCircleMember { circle, member, key, key_hash },
404 11 => RaiseSchema { version, announcement },
405 13 => Reset { announcement },
406 14 => SetAccess { member, access },
407 15 => RotateKey { audience, key, key_hash },
408 16 => ReplaceMemberKeys { member, expected, keys },
409 17 => RenameStore { name => crate::wire::get_name },
410 18 => AddInviteShare { invite, account => get_account },
411 19 => EndInviteShare { invite },
412 20 => RecoverMember { member, expected, keys, access, device, device_name => crate::wire::get_name, circle },
413 21 => SetUpStorage { access },
414);
415
416/// An invite share's provider account, bounded as member access bounds an
417/// account (D6).
418fn get_account(input: &mut Decoder<'_>) -> Result<String, Error> {
419 crate::wire::get_text(input, crate::member_access::MAX_TEXT, "invite share account")
420}
421
422impl StoreChange {
423 /// Encode the one bounded kind-4 admin frame (D6).
424 pub fn encode(&self) -> Result<Vec<u8>, Error> {
425 self.validate()?;
426 crate::encode_frame(crate::kinds::ADMIN, self)
427 }
428
429 /// Decode exactly one admin frame. Slot-dependent authorization is separate.
430 pub fn decode(bytes: &[u8]) -> Result<Self, Error> {
431 let change: Self =
432 crate::wire::decode_frame_value(bytes, crate::kinds::ADMIN, "admin frame")?;
433 change.validate()?;
434 Ok(change)
435 }
436}
437
438#[cfg(test)]
439#[path = "admin_tests.rs"]
440mod tests;