weirdnet-songnotes 0.10.0

SongNotes collaboration: the roles, permissions, links and consent requests for a SongNotes session, built on weirdnet-collab.
Documentation
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
//! The stage-app side of a collab-managed session, shared by the drum machine, the monitor and
//! the controller (C5): a thin presence strip, gates that show a locked state with an Open in
//! Collab link, and enforcement that keeps working while the host or the collab app is closed,
//! from a [`Cert`] the host signed.
//!
//! A stage app never changes a role, a link or a grant: [`Stage`] has no call that could. It
//! reads where its person stands ([`Stage::apply_view`], every
//! [`RE_AUTH_MS`]), keeps the host's signed standing certificate
//! ([`Stage::apply_cert`], saved with [`Stage::save`]), and answers [`Stage::gate`]:
//!
//! * from the fresh view while the host answers;
//! * from the stored certificate, until it expires, when it does not;
//! * otherwise locked, with the reason.
use crate::link::{DeepLink, Panel};
use crate::service::{ProjectView, RE_AUTH_MS, Standing, why_lines};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use weirdnet_collab::{Decision, Explained, ProjectId, RoleId};
use weirdnet_contacts::UserId;
use weirdnet_net::Keypair;

/// How long a certificate lets a stage app enforce on its own by default: a day.
pub const CERT_TTL_MS: i64 = 24 * 60 * 60 * 1000;

/// A view older than this many re-authorisation intervals counts as stale.
pub const STALE_AFTER: i64 = 3;

/// The host's signed statement of where one person stands in a project and what they may do.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Cert {
    /// The project.
    pub project: ProjectId,
    /// Its title.
    pub title: String,
    /// The host who signed.
    pub host: UserId,
    /// Whom it is about.
    pub user: UserId,
    /// Where they stand.
    pub standing: Standing,
    /// Their rights, one decision per permission, with the reasons.
    pub rights: Vec<Explained>,
    /// The members and their roles when it was signed.
    pub people: Vec<(UserId, RoleId)>,
    /// When it was signed (the host's clock).
    pub issued_ms: i64,
    /// When it stops counting.
    pub expires_ms: i64,
    /// The host's public key, protobuf-encoded.
    pub key: Vec<u8>,
    /// The signature over everything above.
    pub sig: Vec<u8>,
}

/// Why a certificate was refused.
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum CertError {
    /// The signature is not the host's.
    #[error("the certificate's signature is not the host's")]
    Signature,
    /// It is about another project, host or person.
    #[error("the certificate is for another project, host or person")]
    Mismatch,
    /// It has expired.
    #[error("the certificate has expired")]
    Expired,
    /// It is older than the one held.
    #[error("the certificate is older than the one held")]
    Older,
    /// It could not be signed.
    #[error("could not sign: {0}")]
    Sign(String),
}

impl Cert {
    fn signing_bytes(&self) -> Vec<u8> {
        let mut c = self.clone();
        c.sig = Vec::new();
        let mut b = b"songnotes-stage-cert-v1\0".to_vec();
        b.extend(serde_json::to_vec(&c).unwrap_or_default());
        b
    }

    /// Signs a certificate for the caller of `view` (as the host made it), valid for `ttl_ms`.
    pub fn issue(host: &Keypair, view: &ProjectView, user: &UserId, now: i64, ttl_ms: i64) -> Result<Cert, CertError> {
        let mut c = Cert {
            project: view.project.clone(),
            title: view.title.clone(),
            host: UserId::of_keypair(host),
            user: user.clone(),
            standing: view.standing.clone(),
            rights: view.rights.clone(),
            people: view.people.iter().map(|p| (p.user.clone(), p.role.clone())).collect(),
            issued_ms: now,
            expires_ms: now + ttl_ms,
            key: host.public().encode_protobuf(),
            sig: Vec::new(),
        };
        c.sig = host.sign(&c.signing_bytes()).map_err(|e| CertError::Sign(e.to_string()))?;
        Ok(c)
    }

    /// Whether the signature is the named host's.
    pub fn verify(&self) -> bool {
        UserId::of_key_bytes(&self.key).as_ref() == Some(&self.host)
            && weirdnet_net::PublicKey::try_decode_protobuf(&self.key).map(|pk| pk.verify(&self.signing_bytes(), &self.sig)).unwrap_or(false)
    }

    /// The decision for `permission`.
    pub fn right(&self, permission: &str) -> Option<&Explained> {
        self.rights.iter().find(|e| e.permission.as_str() == permission)
    }
}

/// What a stage app should show for an action.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Gate {
    /// Go ahead.
    Allowed,
    /// Show it locked, with the reasons and a link to the collab app.
    Locked {
        /// The reasons, one line each.
        why: Vec<String>,
        /// Where the person can change it (or ask).
        open: DeepLink,
    },
    /// The audio's owner has to say yes first; the shared inline prompt asks.
    NeedsConsent {
        /// Whose consent.
        owner: UserId,
        /// The reasons.
        why: Vec<String>,
        /// Where consent is managed.
        open: DeepLink,
    },
}

impl Gate {
    /// Whether it is a plain yes.
    pub fn allowed(&self) -> bool {
        matches!(self, Gate::Allowed)
    }
}

/// Where the gate's answer came from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Source {
    /// The host's answer, fresh.
    Host,
    /// The stored certificate (the host or the collab app is not answering).
    Stored,
    /// Nothing that counts.
    None,
}

/// One person in the strip.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StripEntry {
    /// Who.
    pub user: UserId,
    /// Their role.
    pub role: RoleId,
    /// The apps they are in now (empty: offline or unknown).
    pub apps: Vec<String>,
    /// Whether it is you.
    pub me: bool,
}

/// What a stage app saves.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
struct Saved {
    certs: Vec<Cert>,
}

/// A stage app's view of one collab-managed project.
#[derive(Clone, Debug)]
pub struct Stage {
    app: String,
    me: UserId,
    project: ProjectId,
    host: UserId,
    view: Option<(ProjectView, i64)>,
    cert: Option<Cert>,
}

impl Stage {
    /// The stage of `app` for `me` in `project`, hosted by `host`.
    pub fn new(app: &str, me: UserId, project: ProjectId, host: UserId) -> Stage {
        Stage { app: app.into(), me, project, host, view: None, cert: None }
    }

    /// The app's name.
    pub fn app(&self) -> &str {
        &self.app
    }

    /// The project.
    pub fn project(&self) -> &ProjectId {
        &self.project
    }

    /// The host.
    pub fn host(&self) -> &UserId {
        &self.host
    }

    /// The certificate held, if any.
    pub fn cert(&self) -> Option<&Cert> {
        self.cert.as_ref()
    }

    /// Takes the host's view of the project, received at `now`.
    pub fn apply_view(&mut self, view: ProjectView, now: i64) {
        if view.project == self.project {
            self.view = Some((view, now));
        }
    }

    /// Forgets the view (the host stopped answering); the certificate stays.
    pub fn lost_host(&mut self) {
        self.view = None;
    }

    /// Takes a certificate from the host, checked: the host's signature, this project, host and
    /// person, not expired, not older than the one held.
    pub fn apply_cert(&mut self, cert: Cert, now: i64) -> Result<(), CertError> {
        if !cert.verify() {
            return Err(CertError::Signature);
        }
        if cert.project != self.project || cert.host != self.host || cert.user != self.me {
            return Err(CertError::Mismatch);
        }
        if cert.expires_ms <= now {
            return Err(CertError::Expired);
        }
        if self.cert.as_ref().is_some_and(|c| c.issued_ms > cert.issued_ms) {
            return Err(CertError::Older);
        }
        self.cert = Some(cert);
        Ok(())
    }

    fn fresh_view(&self, now: i64) -> Option<&ProjectView> {
        self.view.as_ref().filter(|(_, at)| now - at <= RE_AUTH_MS * STALE_AFTER).map(|(v, _)| v)
    }

    fn valid_cert(&self, now: i64) -> Option<&Cert> {
        self.cert.as_ref().filter(|c| c.expires_ms > now)
    }

    /// Where answers come from now.
    pub fn source(&self, now: i64) -> Source {
        if self.fresh_view(now).is_some() {
            Source::Host
        } else if self.valid_cert(now).is_some() {
            Source::Stored
        } else {
            Source::None
        }
    }

    /// A link to `panel` of this project in the collab app.
    pub fn open(&self, panel: Panel) -> DeepLink {
        DeepLink { project: self.project.clone(), panel }
    }

    /// Where this person stands now.
    pub fn standing(&self, now: i64) -> Option<Standing> {
        match self.source(now) {
            Source::Host => self.fresh_view(now).map(|v| v.standing.clone()),
            Source::Stored => self.valid_cert(now).map(|c| c.standing.clone()),
            Source::None => None,
        }
    }

    /// Whether `permission` is allowed, and if not, why and where to go.
    pub fn gate(&self, permission: &str, now: i64, name: impl Fn(&UserId) -> String) -> Gate {
        let e = match self.source(now) {
            Source::Host => self.fresh_view(now).and_then(|v| v.right(permission)),
            Source::Stored => self.valid_cert(now).and_then(|c| c.right(permission)),
            Source::None => {
                return Gate::Locked {
                    why: vec!["the host has not been reached and no stored certificate is valid".into()],
                    open: self.open(Panel::Collab),
                };
            }
        };
        let Some(e) = e else {
            return Gate::Locked { why: vec![format!("the host gave no answer for {permission}")], open: self.open(Panel::Settings) };
        };
        let why = why_lines(e, &name);
        match &e.decision {
            Decision::Allowed => Gate::Allowed,
            Decision::Denied => Gate::Locked { why, open: self.open(Panel::Settings) },
            Decision::NeedsConsent { owner } => Gate::NeedsConsent { owner: owner.clone(), why, open: self.open(Panel::Stage) },
        }
    }

    /// The people for the strip, you first.
    pub fn strip(&self, now: i64) -> Vec<StripEntry> {
        let mut v: Vec<StripEntry> = match (self.fresh_view(now), self.valid_cert(now)) {
            (Some(view), _) => view
                .people
                .iter()
                .map(|p| StripEntry {
                    user: p.user.clone(),
                    role: p.role.clone(),
                    apps: p.apps.iter().map(|h| h.app.clone()).collect(),
                    me: p.user == self.me,
                })
                .collect(),
            (None, Some(c)) => {
                c.people.iter().map(|(u, r)| StripEntry { user: u.clone(), role: r.clone(), apps: vec![], me: *u == self.me }).collect()
            }
            _ => vec![],
        };
        v.sort_by_key(|e| !e.me);
        v
    }

    /// One line for the strip's end: your role and where the answers come from.
    pub fn status_line(&self, now: i64) -> String {
        let role = match self.standing(now) {
            Some(Standing::Member(r)) => r.to_string(),
            Some(Standing::Pending) => "waiting for the host".into(),
            Some(Standing::Out) => "not in the project".into(),
            Some(Standing::Banned) => "banned".into(),
            None => "not checked".into(),
        };
        match self.source(now) {
            Source::Host => format!("{role} · checked with the host"),
            Source::Stored => {
                let left = self.valid_cert(now).map_or(0, |c| (c.expires_ms - now) / 60_000);
                format!("{role} · host not answering; stored record valid {left} more min")
            }
            Source::None => format!("{role} · host not reached"),
        }
    }

    /// Saves the certificate to `path` (owner-only on Unix), next to any for other projects.
    pub fn save(&self, path: &Path) -> std::io::Result<()> {
        let mut saved: Saved = std::fs::read(path).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
        if let Some(c) = &self.cert {
            saved.certs.retain(|x| !(x.project == c.project && x.user == c.user));
            saved.certs.push(c.clone());
        }
        if let Some(d) = path.parent() {
            std::fs::create_dir_all(d)?;
        }
        let tmp = path.with_extension("tmp");
        std::fs::write(&tmp, serde_json::to_vec_pretty(&saved).map_err(std::io::Error::other)?)?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600))?;
        }
        std::fs::rename(&tmp, path)
    }

    /// Loads this project's stored certificate from `path`, checked as [`Stage::apply_cert`]
    /// does; returns why it was not taken, if it was not.
    pub fn load(&mut self, path: &Path, now: i64) -> Result<bool, CertError> {
        let saved: Saved = std::fs::read(path).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
        match saved.certs.into_iter().find(|c| c.project == self.project && c.user == self.me) {
            Some(c) => self.apply_cert(c, now).map(|()| true),
            None => Ok(false),
        }
    }
}

impl Stage {
    /// The stage of `app` for `project` rebuilt from the newest valid certificate stored in
    /// `path`, for a stage app started while the collab app is closed (who you are and who
    /// hosts come from the certificate). `None` when there is none.
    pub fn restore(app: &str, project: &ProjectId, path: &Path, now: i64) -> Option<Stage> {
        let saved: Saved = std::fs::read(path).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
        let c = saved.certs.into_iter().filter(|c| &c.project == project && c.verify() && c.expires_ms > now).max_by_key(|c| c.issued_ms)?;
        let mut s = Stage::new(app, c.user.clone(), project.clone(), c.host.clone());
        s.apply_cert(c, now).ok()?;
        Some(s)
    }
}

/// The default file a stage app keeps its certificates in: `songnotes/<app>/stage.json` under
/// the data folder (`$XDG_DATA_HOME`, else `~/.local/share`).
pub fn default_store(app: &str) -> Option<PathBuf> {
    let base = std::env::var_os("XDG_DATA_HOME")
        .map(PathBuf::from)
        .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local").join("share")))?;
    Some(base.join("songnotes").join(app).join("stage.json"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::service::Person;
    use weirdnet_collab::{Permission, Step};

    fn right(user: &UserId, p: &str, d: Decision) -> Explained {
        Explained { who: user.clone(), permission: Permission::new(p), decision: d, chain: vec![Step::DefaultDeny] }
    }

    fn view(host: &UserId, me: &UserId, edit: bool) -> ProjectView {
        ProjectView {
            project: ProjectId::new("p1"),
            title: "Jam".into(),
            host: host.clone(),
            standing: Standing::Member(RoleId::new("viewer")),
            people: vec![
                Person { user: host.clone(), role: RoleId::new("host"), apps: vec![] },
                Person { user: me.clone(), role: RoleId::new("viewer"), apps: vec![] },
            ],
            audit: vec![],
            consent_requests: vec![],
            grants: vec![],
            rights: vec![
                right(me, crate::perm::PROJECT_EDIT, if edit { Decision::Allowed } else { Decision::Denied }),
                right(me, crate::perm::STREAM_RECORD, Decision::NeedsConsent { owner: host.clone() }),
            ],
            at_ms: 0,
        }
    }

    #[test]
    fn gates_come_from_the_host_then_the_stored_cert_then_lock() {
        let host = Keypair::generate_ed25519();
        let me_kp = Keypair::generate_ed25519();
        let (h, me) = (UserId::of_keypair(&host), UserId::of_keypair(&me_kp));
        let name = |u: &UserId| u.as_str()[..6].to_string();
        let mut s = Stage::new("drummachine", me.clone(), ProjectId::new("p1"), h.clone());
        assert!(matches!(s.gate(crate::perm::PROJECT_EDIT, 0, name), Gate::Locked { .. }), "nothing checked yet");
        s.apply_view(view(&h, &me, true), 1_000);
        assert_eq!(s.source(1_000), Source::Host);
        assert!(s.gate(crate::perm::PROJECT_EDIT, 1_000, name).allowed());
        assert!(matches!(s.gate(crate::perm::STREAM_RECORD, 1_000, name), Gate::NeedsConsent { .. }));
        assert_eq!(s.strip(1_000)[0].user, me, "you first");
        // the host signs a certificate that says editing is denied
        let cert = Cert::issue(&host, &view(&h, &me, false), &me, 2_000, 60_000).unwrap();
        assert!(cert.verify());
        s.apply_cert(cert.clone(), 2_000).unwrap();
        // the host stops answering: the stored certificate decides
        let later = 1_000 + RE_AUTH_MS * STALE_AFTER + 1;
        assert_eq!(s.source(later), Source::Stored);
        match s.gate(crate::perm::PROJECT_EDIT, later, name) {
            Gate::Locked { why, open } => {
                assert_eq!(why, vec!["nothing allows it".to_string()]);
                assert_eq!(open.to_string(), "weirdnet-songnotes://collab/p1/settings");
            }
            g => panic!("{g:?}"),
        }
        assert!(s.status_line(later).contains("stored record"));
        // saved and loaded again (owner-only file)
        let path = std::env::temp_dir().join(format!("sn-stage-{}", std::process::id())).join("stage.json");
        s.save(&path).unwrap();
        let mut again = Stage::new("drummachine", me.clone(), ProjectId::new("p1"), h.clone());
        assert_eq!(again.load(&path, later), Ok(true));
        assert_eq!(again.source(later), Source::Stored);
        let restored = Stage::restore("drummachine", &ProjectId::new("p1"), &path, later).expect("restored from the file");
        assert_eq!((restored.host(), restored.source(later)), (&h, Source::Stored));
        assert!(Stage::restore("drummachine", &ProjectId::new("p2"), &path, later).is_none());
        // and when it expires, everything is locked
        assert_eq!(again.source(62_001), Source::None);
        assert!(!again.gate(crate::perm::PROJECT_EDIT, 62_001, name).allowed());
        let _ = std::fs::remove_dir_all(path.parent().unwrap());
    }

    #[test]
    fn a_forged_or_foreign_cert_is_refused() {
        let host = Keypair::generate_ed25519();
        let other = Keypair::generate_ed25519();
        let me_kp = Keypair::generate_ed25519();
        let (h, me) = (UserId::of_keypair(&host), UserId::of_keypair(&me_kp));
        let mut s = Stage::new("monitor", me.clone(), ProjectId::new("p1"), h.clone());
        let mut c = Cert::issue(&host, &view(&h, &me, false), &me, 0, 60_000).unwrap();
        // the person edits their stored certificate to allow themselves to edit
        c.rights[0].decision = Decision::Allowed;
        assert_eq!(s.apply_cert(c, 1), Err(CertError::Signature));
        // someone else's signature
        let c = Cert::issue(&other, &view(&h, &me, true), &me, 0, 60_000).unwrap();
        assert_eq!(s.apply_cert(c, 1), Err(CertError::Mismatch));
        // a certificate for someone else
        let c = Cert::issue(&host, &view(&h, &h, true), &h, 0, 60_000).unwrap();
        assert_eq!(s.apply_cert(c, 1), Err(CertError::Mismatch));
        let c = Cert::issue(&host, &view(&h, &me, true), &me, 0, 10).unwrap();
        assert_eq!(s.apply_cert(c, 11), Err(CertError::Expired));
        let new = Cert::issue(&host, &view(&h, &me, true), &me, 100, 60_000).unwrap();
        s.apply_cert(new, 101).unwrap();
        let old = Cert::issue(&host, &view(&h, &me, true), &me, 50, 60_000).unwrap();
        assert_eq!(s.apply_cert(old, 102), Err(CertError::Older));
    }
}