printobserver-server 0.16.2

The printobserver server.
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
//! The credentials supervision turns authenticate with, held in memory alone.
//!
//! # One credential per run, bound before it exists
//!
//! A supervision turn's runs reach the server's API with a credential minted
//! for that run: [`GENERATED_TURN_CREDENTIAL_BYTES`] bytes from the operating
//! system's cryptographically secure random source, bound to the agent class,
//! the session the run is in and the print the turn is about. The core opens
//! one turn's issuer of them at the turn boundary through
//! [`TurnAuthority::open`], hands it to the supervisor port, and revokes it
//! when the turn returns — on success, failure and timeout alike, and when the
//! turn is abandoned, because dropping what was opened revokes too.
//!
//! # Nothing here is persisted
//!
//! The registry is a map in this process's memory, keyed by the SHA-256 of each
//! credential rather than by the credential itself: nothing is written, so a
//! server that restarts admits none of the credentials the one before it
//! minted, and no turn survives a restart for one to be owed to. Looking a
//! presented credential up by its digest takes as long whatever was guessed:
//! what varies is the digest, which says nothing about the credential.
//!
//! # A turn acknowledges only after it has looked
//!
//! The registry also notes which turns have taken a look at their print, so
//! the API can refuse an acknowledgement from a turn that judged its event
//! without one: the frames a turn's context names are already old when it
//! reads them. The note is the turn's, shared by every run it issues, and goes
//! with the turn's credentials when it returns.

use std::collections::{HashMap, HashSet};
use std::net::SocketAddr;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};

use printobserver_core::{OpenedTurn, TurnAuthority};
use printobserver_supervisor_api::{SupervisorError, TurnAccess, TurnPass, TurnSession};
use printobserver_types::PrintId;
use sha2::{Digest as _, Sha256};

/// How many random bytes a turn's credential is drawn from: the same as every
/// credential this program generates.
pub const GENERATED_TURN_CREDENTIAL_BYTES: usize = crate::config::GENERATED_CREDENTIAL_BYTES;

/// Who one turn credential authenticates as.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TurnBinding {
    /// The session the run that holds it is in.
    session: TurnSession,
    /// The print the turn is about.
    print_id: PrintId,
    /// The turn that issued it.
    scope: u64,
}

impl TurnBinding {
    /// The session the run holding this credential is in, as a request's
    /// `Actor::Agent { session_name }` spells it.
    #[must_use]
    pub fn session_name(&self) -> &str {
        self.session.as_str()
    }

    /// The print the turn holding this credential is about.
    #[must_use]
    pub const fn print_id(&self) -> PrintId {
        self.print_id
    }
}

/// One live credential, by the scope that issued it.
#[derive(Debug)]
struct Held {
    /// The turn that issued it.
    scope: u64,
    /// Who it authenticates as.
    binding: TurnBinding,
}

/// The registry behind every handle onto it.
#[derive(Debug)]
struct Registry {
    /// The live credentials, keyed by the SHA-256 of each.
    held: Mutex<HashMap<[u8; 32], Held>>,
    /// The turns that have taken a look at their print, by scope.
    looked: Mutex<HashSet<u64>>,
    /// The identifier the next scope takes.
    next_scope: AtomicU64,
    /// Where the server answers, as a turn's runs are told.
    server: Option<SocketAddr>,
}

/// Every live turn credential, by its digest. Cloning it is another handle
/// onto the same registry.
#[derive(Debug, Clone)]
pub struct TurnCredentials(Arc<Registry>);

/// One credential's digest.
fn digest(credential: &[u8]) -> [u8; 32] {
    Sha256::digest(credential).into()
}

impl TurnCredentials {
    /// An empty registry whose turns' runs are told the server is at `server`.
    #[must_use]
    pub fn new(server: Option<SocketAddr>) -> Self {
        Self(Arc::new(Registry {
            held: Mutex::new(HashMap::new()),
            looked: Mutex::new(HashSet::new()),
            next_scope: AtomicU64::new(0),
            server,
        }))
    }

    /// The registry, held.
    fn held(&self) -> MutexGuard<'_, HashMap<[u8; 32], Held>> {
        self.0
            .held
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// Who a presented credential authenticates as, when it is a live turn's.
    #[must_use]
    pub fn admit(&self, presented: &[u8]) -> Option<TurnBinding> {
        self.held()
            .get(&digest(presented))
            .map(|held| held.binding.clone())
    }

    /// How many turn credentials are live.
    #[must_use]
    pub fn live(&self) -> usize {
        self.held().len()
    }

    /// The turns that have looked, held.
    fn looked_turns(&self) -> MutexGuard<'_, HashSet<u64>> {
        self.0
            .looked
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// Note that the turn `binding` belongs to has taken a look at its print.
    pub fn note_look(&self, binding: &TurnBinding) {
        self.looked_turns().insert(binding.scope);
    }

    /// Whether the turn `binding` belongs to has taken a look at its print.
    #[must_use]
    pub fn has_looked(&self, binding: &TurnBinding) -> bool {
        self.looked_turns().contains(&binding.scope)
    }

    /// Forget every credential one scope issued, and that it looked.
    fn revoke(&self, scope: u64) {
        self.held().retain(|_, held| held.scope != scope);
        self.looked_turns().remove(&scope);
    }
}

impl TurnAuthority for TurnCredentials {
    /// A turn handed its event's image has looked from the start: it decides
    /// on that image and is allowed no look of its own.
    fn open(&self, print_id: PrintId, handed_image: bool) -> OpenedTurn {
        let scope = Arc::new(Scope {
            registry: self.clone(),
            id: self.0.next_scope.fetch_add(1, Ordering::Relaxed),
            print_id,
            closed: Mutex::new(false),
        });
        if handed_image {
            self.looked_turns().insert(scope.id);
        }
        let closing = Arc::clone(&scope);
        OpenedTurn::new(scope, Box::new(move || closing.close()))
    }
}

/// One turn's issuer, as the port is handed it.
#[derive(Debug)]
struct Scope {
    /// Where the credentials it issues are admitted.
    registry: TurnCredentials,
    /// Which turn this is.
    id: u64,
    /// The print the turn is about.
    print_id: PrintId,
    /// Whether the turn has returned, after which nothing more is issued.
    closed: Mutex<bool>,
}

impl Scope {
    /// Revoke every credential this turn was issued, and issue no more.
    fn close(&self) {
        *self
            .closed
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = true;
        self.registry.revoke(self.id);
    }
}

impl TurnAccess for Scope {
    fn issue(&self, session: &TurnSession) -> Result<TurnPass, SupervisorError> {
        self.issue_drawn(session, getrandom::fill)
    }
}

impl Scope {
    /// Issue the run in `session` a credential, drawn by `draw` — the
    /// operating system's random source, for every run this server starts.
    /// A draw that is refused registers nothing.
    fn issue_drawn(
        &self,
        session: &TurnSession,
        draw: impl FnOnce(&mut [u8]) -> Result<(), getrandom::Error>,
    ) -> Result<TurnPass, SupervisorError> {
        use base64::Engine as _;

        let mut drawn = [0_u8; GENERATED_TURN_CREDENTIAL_BYTES];
        draw(&mut drawn).map_err(|error| SupervisorError::Unavailable {
            detail: format!(
                "no credential could be minted for the turn, because the operating system's \
                 random source refused: {error}"
            ),
        })?;
        let credential = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(drawn);
        let digested = digest(credential.as_bytes());
        let pass = TurnPass::new(self.registry.0.server, credential)?;
        // Held across the insertion, so a turn that returns while a run is
        // being issued its credential leaves nothing live behind it.
        let closed = self
            .closed
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if *closed {
            return Err(SupervisorError::Unavailable {
                detail: "the turn this run belongs to has already returned".to_owned(),
            });
        }
        let mut held = self.registry.held();
        held.retain(|_, live| live.scope != self.id);
        held.insert(
            digested,
            Held {
                scope: self.id,
                binding: TurnBinding {
                    session: session.clone(),
                    print_id: self.print_id,
                    scope: self.id,
                },
            },
        );
        drop(held);
        drop(closed);
        Ok(pass)
    }
}

#[cfg(test)]
mod tests {
    use printobserver_core::TurnAuthority as _;
    use printobserver_supervisor_api::{CREDENTIAL_ENV, SERVER_ENV, TurnPass, TurnSession};
    use printobserver_types::PrintId;

    use super::{GENERATED_TURN_CREDENTIAL_BYTES, TurnCredentials};

    /// One session, by a name that is one.
    fn session(name: &str) -> TurnSession {
        TurnSession::new(name).expect("a session")
    }

    /// The value one variable of a pass carries.
    fn value_of(pass: &TurnPass, name: &str) -> String {
        pass.environment()
            .into_iter()
            .find(|(named, _)| *named == name)
            .map_or_else(|| panic!("the pass carries no {name}"), |(_, value)| value)
    }

    /// A look one run of a turn took counts for every run the turn issues
    /// after it, and for no other turn; it goes when the turn returns.
    #[test]
    fn a_look_is_the_turns_whichever_of_its_runs_took_it() {
        let registry = TurnCredentials::new(None);
        let print_id = PrintId::new();
        let opened = registry.open(print_id, false);
        let access = opened.access();
        let first = value_of(
            &access.issue(&session("print-a")).expect("minted"),
            CREDENTIAL_ENV,
        );
        let looking = registry.admit(first.as_bytes()).expect("admitted");
        assert!(!registry.has_looked(&looking));
        registry.note_look(&looking);
        let second = value_of(
            &access.issue(&session("print-a-2")).expect("minted"),
            CREDENTIAL_ENV,
        );
        let moved = registry.admit(second.as_bytes()).expect("admitted");
        assert!(
            registry.has_looked(&moved),
            "the turn's second run lost its look"
        );

        let other = registry.open(print_id, false);
        let elsewhere = value_of(
            &other.access().issue(&session("print-b")).expect("minted"),
            CREDENTIAL_ENV,
        );
        let unlooked = registry.admit(elsewhere.as_bytes()).expect("admitted");
        assert!(
            !registry.has_looked(&unlooked),
            "another turn took this one's look"
        );

        drop(opened);
        assert!(
            !registry.has_looked(&moved),
            "a returned turn's look outlived it"
        );
    }

    /// A turn handed its event's image has looked from the start, on every
    /// run it issues; a turn handed none has not.
    #[test]
    fn a_turn_handed_an_image_has_looked_from_the_start() {
        let registry = TurnCredentials::new(None);
        let print_id = PrintId::new();
        for (handed_image, session_name) in [(true, "print-a"), (false, "print-b")] {
            let opened = registry.open(print_id, handed_image);
            let access = opened.access();
            let credential = value_of(
                &access.issue(&session(session_name)).expect("minted"),
                CREDENTIAL_ENV,
            );
            let binding = registry.admit(credential.as_bytes()).expect("admitted");
            assert_eq!(
                registry.has_looked(&binding),
                handed_image,
                "handed an image: {handed_image}"
            );
        }
    }

    /// A credential is admitted as the session and print it was issued for
    /// while its turn runs, a second issue replaces the first, and revoking
    /// the turn admits none of them and issues no more.
    #[test]
    fn a_turns_credential_lives_exactly_as_long_as_its_turn() {
        let registry = TurnCredentials::new(Some("127.0.0.1:1".parse().expect("an address")));
        let print_id = PrintId::new();
        let opened = registry.open(print_id, false);
        let access = opened.access();
        let pass = access.issue(&session("print-a")).expect("one is minted");
        let first = value_of(&pass, CREDENTIAL_ENV);

        assert_eq!(value_of(&pass, SERVER_ENV), "http://127.0.0.1:1");
        // Unpadded URL-safe base64 of the drawn bytes.
        assert_eq!(
            first.len(),
            (GENERATED_TURN_CREDENTIAL_BYTES * 4).div_ceil(3)
        );
        assert_eq!(
            registry
                .admit(first.as_bytes())
                .map(|binding| (binding.session_name().to_owned(), binding.print_id())),
            Some(("print-a".to_owned(), print_id))
        );
        let second = value_of(
            &access.issue(&session("print-a-2")).expect("minted"),
            CREDENTIAL_ENV,
        );
        assert_ne!(first, second);
        assert_eq!(registry.admit(first.as_bytes()), None);
        assert_eq!(registry.live(), 1);

        opened.revoke();
        assert_eq!(registry.admit(second.as_bytes()), None);
        assert!(access.issue(&session("print-a-3")).is_err());
        assert_eq!(registry.live(), 0);
    }

    /// A draw the random source refuses issues nothing and registers nothing,
    /// so the run it was for is not started.
    #[test]
    fn a_refused_draw_issues_and_registers_nothing() {
        let registry = TurnCredentials::new(None);
        let scope = super::Scope {
            registry: registry.clone(),
            id: 0,
            print_id: PrintId::new(),
            closed: std::sync::Mutex::new(false),
        };

        let Err(refused) =
            scope.issue_drawn(&session("print-a"), |_| Err(getrandom::Error::UNSUPPORTED))
        else {
            panic!("a refused draw issued a credential");
        };

        assert!(
            refused.to_string().contains("random source refused"),
            "{refused}"
        );
        assert_eq!(registry.live(), 0);
    }

    /// Dropping one turn's opened issuer revokes it, and another turn's
    /// credential is left alone.
    #[test]
    fn dropping_one_turn_revokes_its_own_credential_and_no_other() {
        let registry = TurnCredentials::new(None);
        let kept = registry.open(PrintId::new(), false);
        let kept_credential = value_of(
            &kept.access().issue(&session("kept")).expect("minted"),
            CREDENTIAL_ENV,
        );
        let dropped = registry.open(PrintId::new(), false);
        let dropped_credential = value_of(
            &dropped.access().issue(&session("gone")).expect("minted"),
            CREDENTIAL_ENV,
        );
        drop(dropped);

        assert_eq!(registry.admit(dropped_credential.as_bytes()), None);
        assert!(registry.admit(kept_credential.as_bytes()).is_some());
    }
}