semiont 0.7.2

Semiont's Rust SDK: the protocol's types, the transport contract and a client of the bus over it, and what a client needs to name its principals and hold its roles, as protocol/specs/ states it.
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
//! The sign-ins `semiont login` keeps (protocol/specs/src/sign-in-store), as a
//! `SessionStorage`: one sign-in serves the launcher's verbs and an
//! application built on this SDK.
//!
//! The launcher keeps one sign-in per stack, under the stack's key (`local`,
//! `codespace:<owner>/<name>`). A session reaches one by using that key as
//! its knowledge base id: the session of the knowledge base `local` is the
//! launcher's entry `local`. Everything else a client keeps, and the session
//! of any knowledge base the launcher has no entry for, is kept in the
//! storage this one is built over.
//!
//! What is in the file was issued to the script client and is renewed as
//! it. A session issued to another client is kept in the storage beneath,
//! never in the file: the launcher would renew it as the wrong client. It
//! is then this application's session of that knowledge base, read before
//! the file's, and the launcher's entry is left as it was.
//!
//! **A session that is `set` is a sign-in**, and its entry states who signed
//! in and at which issuer as its own access token names them, whoever the
//! entry before it was of. **A session an `update` says in place of the
//! file's is that sign-in renewed**, and keeps both as the sign-in learned
//! them, whatever the renewed token names.
//!
//! **Every change is a read, a change and a write under a lock**
//! (`tokens.lock`, beside the file): another process renewing another stack
//! at the same moment loses nothing. What the file holds that is not a
//! sign-in as this release knows one is written back as it was. Under the
//! lock, the file's directory is kept to its owner, as the launcher keeps its
//! state home: the mode, and on Windows the access list, which what is made in
//! it inherits, that protocol/specs/src/sign-in-store/owner-only.json states.
//!
//! A file that cannot be read or written is said to `on_failure`, and the
//! store then behaves as if the file held nothing, or the write was not
//! made. So is a session whose access token does not say who it is for or
//! who issued it: the file states both of every sign-in, and nothing is made
//! up for one. A write the storage beneath refuses is the write's error, and
//! the file is left as it was.

use crate::locked;
use crate::rfc3339;
use crate::session::{
    SCRIPT_CLIENT_ID, StoredSession, kb_of_session_key, text_claim, token_expiry,
};
use crate::storage::{SessionStorage, StorageChange, StorageSubscription};
use serde_json::{Map, Value};
use std::fs::{self, OpenOptions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::SystemTime;

include!(concat!(env!("OUT_DIR"), "/sign_in.rs"));
include!(concat!(env!("OUT_DIR"), "/owner_only.rs"));

/// The file's name in the launcher's state home.
pub const FILE_NAME: &str = "tokens.json";

/// Keep `directory`, and everything made in it from then on, to its owner,
/// with the sign-in store's access list, which the launcher gives its state
/// home too. A mode keeps nobody out on Windows; the access list is what does. A
/// directory that has the list already is left as it is: setting a list
/// hands it down to everything beneath, which in a state home is no small
/// walk. The two lists are compared as Windows writes each out, which names
/// some users by an abbreviation (the built-in administrator is `LA`) rather
/// than by their SID, and with their entries in any order.
#[cfg(windows)]
#[allow(unsafe_code)]
fn owner_only(directory: &Path) -> io::Result<()> {
    use std::ffi::OsStr;
    use std::os::windows::ffi::OsStrExt;
    use std::ptr::{null, null_mut};
    use windows_sys::Win32::Foundation::{HANDLE, LocalFree};
    use windows_sys::Win32::Security::Authorization::{
        ConvertSecurityDescriptorToStringSecurityDescriptorW, ConvertSidToStringSidW,
        ConvertStringSecurityDescriptorToSecurityDescriptorW, GetNamedSecurityInfoW,
        SDDL_REVISION_1, SE_FILE_OBJECT, SetNamedSecurityInfoW,
    };
    use windows_sys::Win32::Security::{
        ACL, DACL_SECURITY_INFORMATION, GetSecurityDescriptorDacl, GetTokenInformation,
        PROTECTED_DACL_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, TOKEN_USER, TokenUser,
    };

    /// This process's token, as `GetCurrentProcessToken` names it.
    const CURRENT_PROCESS_TOKEN: HANDLE = -4isize as HANDLE;
    let wide = |text: &OsStr| text.encode_wide().chain([0]).collect::<Vec<u16>>();

    // SAFETY: each buffer handed to the system is as large as the system says
    // it needs, each pointer it hands back is read only up to the terminator
    // it writes, and what it allocates is freed once, after its last use.
    unsafe {
        /// Text the system wrote and allocated, taken and freed.
        unsafe fn taken(text: *mut u16) -> String {
            // SAFETY: the system wrote the text and its terminator.
            let length = (0..)
                .take_while(|&at| unsafe { *text.add(at) } != 0)
                .count();
            // SAFETY: as above, and the text is freed once, here.
            unsafe {
                let taken = String::from_utf16_lossy(std::slice::from_raw_parts(text, length));
                LocalFree(text.cast());
                taken
            }
        }

        /// The access list `descriptor` holds, as Windows writes it out (SDDL).
        unsafe fn written(descriptor: PSECURITY_DESCRIPTOR) -> io::Result<String> {
            let mut text = null_mut();
            // SAFETY: the descriptor is one the system made, and the text it
            // writes out is taken once.
            unsafe {
                if ConvertSecurityDescriptorToStringSecurityDescriptorW(
                    descriptor,
                    SDDL_REVISION_1,
                    DACL_SECURITY_INFORMATION,
                    &mut text,
                    null_mut(),
                ) == 0
                {
                    return Err(io::Error::last_os_error());
                }
                Ok(taken(text))
            }
        }

        /// An access list as Windows writes it out, with its entries sorted:
        /// entries that each allow mean the same in any order, and a list's
        /// own entries need not be read back in the order they were set.
        fn in_any_order(list: &str) -> String {
            let (flags, entries) = match list.find('(') {
                Some(at) => list.split_at(at),
                None => (list, ""),
            };
            let mut entries: Vec<&str> = entries.split_inclusive(')').collect();
            entries.sort_unstable();
            format!("{flags}{}", entries.concat())
        }

        let mut size = 0u32;
        GetTokenInformation(CURRENT_PROCESS_TOKEN, TokenUser, null_mut(), 0, &mut size);
        // Aligned as a TOKEN_USER is: the SID it points to follows it.
        let mut user = vec![0u64; (size as usize).div_ceil(8)];
        if GetTokenInformation(
            CURRENT_PROCESS_TOKEN,
            TokenUser,
            user.as_mut_ptr().cast(),
            size,
            &mut size,
        ) == 0
        {
            return Err(io::Error::last_os_error());
        }
        let mut named = null_mut();
        if ConvertSidToStringSidW((*user.as_ptr().cast::<TOKEN_USER>()).User.Sid, &mut named) == 0 {
            return Err(io::Error::last_os_error());
        }
        let sddl = wide(OsStr::new(&owner_only_access_list(&taken(named))));
        let mut descriptor: PSECURITY_DESCRIPTOR = null_mut();
        if ConvertStringSecurityDescriptorToSecurityDescriptorW(
            sddl.as_ptr(),
            SDDL_REVISION_1,
            &mut descriptor,
            null_mut(),
        ) == 0
        {
            return Err(io::Error::last_os_error());
        }

        let name = wide(directory.as_os_str());
        let kept = (|| {
            let (mut dacl, mut held): (*mut ACL, PSECURITY_DESCRIPTOR) = (null_mut(), null_mut());
            let failed = GetNamedSecurityInfoW(
                name.as_ptr(),
                SE_FILE_OBJECT,
                DACL_SECURITY_INFORMATION,
                null_mut(),
                null_mut(),
                &mut dacl,
                null_mut(),
                &mut held,
            );
            if failed != 0 {
                return Err(io::Error::from_raw_os_error(failed as i32));
            }
            let has = written(held);
            LocalFree(held);
            if in_any_order(&has?) == in_any_order(&written(descriptor)?) {
                return Ok(());
            }
            let (mut present, mut defaulted) = (0, 0);
            if GetSecurityDescriptorDacl(descriptor, &mut present, &mut dacl, &mut defaulted) == 0 {
                return Err(io::Error::last_os_error());
            }
            match SetNamedSecurityInfoW(
                name.as_ptr(),
                SE_FILE_OBJECT,
                DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
                null_mut(),
                null_mut(),
                dacl,
                null(),
            ) {
                0 => Ok(()),
                failed => Err(io::Error::from_raw_os_error(failed as i32)),
            }
        })();
        LocalFree(descriptor);
        kept
    }
}

/// Keep `directory` to its owner: the sign-in store's directory mode, as the
/// launcher keeps its state home.
#[cfg(unix)]
fn owner_only(directory: &Path) -> io::Result<()> {
    use std::os::unix::fs::PermissionsExt;
    fs::set_permissions(
        directory,
        fs::Permissions::from_mode(OWNER_ONLY_DIRECTORY_MODE),
    )
}

/// How a file of the store is made, or opened over what is there: written,
/// and on a system that has modes made with the store's file mode.
fn owner_only_file() -> OpenOptions {
    let mut options = OpenOptions::new();
    options.write(true).create(true).truncate(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(OWNER_ONLY_FILE_MODE);
    }
    options
}

/// The systems the state home differs by, as
/// protocol/specs/src/sign-in-store/cases.json names them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum System {
    MacOs,
    Windows,
    /// Anything else: Linux, and every other Unix.
    Other,
}

impl System {
    /// The system this crate was built for.
    pub const fn of_this_build() -> System {
        if cfg!(target_os = "macos") {
            System::MacOs
        } else if cfg!(windows) {
            System::Windows
        } else {
            System::Other
        }
    }

    /// The system as the cases name it: `macos`, `windows`, or anything else.
    pub fn named(name: &str) -> System {
        match name {
            "macos" => System::MacOs,
            "windows" => System::Windows,
            _ => System::Other,
        }
    }
}

/// The launcher's state home, from what the system says of the person's
/// directories (protocol/specs/src/sign-in-store/cases.json): `home` is the home
/// directory (`HOME`, or `USERPROFILE` on Windows), `xdg_state_home` is
/// `XDG_STATE_HOME` and `local_app_data` is `LOCALAPPDATA`, each none when it
/// is not set. None when there is no home.
///
/// The path is composed with the system's own separator, not this build's: a
/// case gives one answer whichever machine computes it.
///
/// This crate reads no environment: a service links it, and what a service
/// reads of its environment is a contract. An application reads its own and
/// says what it found:
/// `state_dir(System::of_this_build(), home, xdg_state_home, local_app_data)`.
pub fn state_dir(
    system: System,
    home: Option<&str>,
    xdg_state_home: Option<&str>,
    local_app_data: Option<&str>,
) -> Option<PathBuf> {
    let home = home.filter(|home| !home.is_empty())?;
    let under = |separator: char, base: &str, names: &[&str]| {
        let mut dir = base.trim_end_matches(separator).to_owned();
        for name in names {
            dir.push(separator);
            dir.push_str(name);
        }
        PathBuf::from(dir)
    };
    Some(match system {
        System::MacOs => under('/', home, &["Library", "Application Support", "semiont"]),
        System::Windows => match local_app_data.filter(|local| !local.is_empty()) {
            Some(local) => under('\\', local, &["semiont"]),
            None => under('\\', home, &["AppData", "Local", "semiont"]),
        },
        System::Other => match xdg_state_home.filter(|state| !state.is_empty()) {
            Some(state) => under('/', state, &["semiont"]),
            None => under('/', home, &[".local", "state", "semiont"]),
        },
    })
}

/// A member of the document as a sign-in. One that is not a sign-in is none.
fn sign_in_of(member: &Value) -> Option<SignIn> {
    serde_json::from_value(member.clone()).ok()
}

/// A sign-in as the session a client holds: one with no refresh token is
/// none, because a session that cannot be renewed does not outlive its first
/// access token.
fn session_of(sign_in: &SignIn) -> Option<StoredSession> {
    Some(StoredSession {
        access: sign_in.token.clone(),
        refresh: sign_in
            .refresh_token
            .clone()
            .filter(|refresh| !refresh.is_empty())?,
        client_id: SCRIPT_CLIENT_ID.to_owned(),
        token_endpoint: sign_in.token_endpoint.clone(),
        revocation_endpoint: sign_in.revocation_endpoint.clone(),
    })
}

/// Who signed in, when an access token names an address, and at which
/// issuer. A token the gateway admits names its issuer, so one that does not
/// is no sign-in, and is refused.
fn named_by(access: &str) -> Result<(Option<String>, String), &'static str> {
    let issuer = text_claim(access, "iss").ok_or("its access token names no issuer")?;
    Ok((text_claim(access, "email"), issuer))
}

/// A session as the sign-in the file keeps, of `email` at `issuer`.
fn entry_of(
    session: &StoredSession,
    email: Option<String>,
    issuer: String,
    now: SystemTime,
) -> Value {
    // A struct of strings always serializes to an object.
    serde_json::to_value(SignIn {
        token: session.access.clone(),
        refresh_token: Some(session.refresh.clone()),
        email,
        obtained_at: rfc3339::to_the_second(now),
        expires_at: token_expiry(&session.access).map(rfc3339::to_the_second),
        issuer,
        token_endpoint: session.token_endpoint.clone(),
        revocation_endpoint: session.revocation_endpoint.clone(),
    })
    .unwrap_or(Value::Null)
}

/// Told that the file could not be read or written, with why.
pub type OnFailure = Arc<dyn Fn(&str) + Send + Sync>;

/// See the module's documentation.
pub struct SignInStore {
    path: PathBuf,
    rest: Arc<dyn SessionStorage>,
    on_failure: OnFailure,
    /// One change at a time from this process: the file lock is between
    /// processes, and two handles of one process on one file do not exclude
    /// each other on every system.
    turn: Mutex<()>,
}

impl SignInStore {
    /// The store in the file at `path` (`FILE_NAME` in `state_dir`, for the
    /// launcher's), over `rest` for everything that is not one of its
    /// sign-ins.
    pub fn at(
        path: impl Into<PathBuf>,
        rest: Arc<dyn SessionStorage>,
        on_failure: OnFailure,
    ) -> SignInStore {
        SignInStore {
            path: path.into(),
            rest,
            on_failure,
            turn: Mutex::new(()),
        }
    }

    fn failed(&self, doing: &str, error: &io::Error) {
        (self.on_failure)(&format!("{doing} {}: {error}", self.path.display()));
    }

    /// The document as it is now. A file that is not there holds nothing.
    fn read(&self) -> io::Result<Map<String, Value>> {
        let text = match fs::read_to_string(&self.path) {
            Ok(text) => text,
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Map::new()),
            Err(error) => return Err(error),
        };
        serde_json::from_str(&text)
            .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
    }

    fn entry(&self, kb_id: &str) -> Option<Value> {
        match self.read() {
            Ok(mut document) => document.remove(kb_id),
            Err(error) => {
                self.failed("Could not read", &error);
                None
            }
        }
    }

    /// Change the document as one step: read it, change it, and write it
    /// when `change` says it changed, with the lock held throughout. What
    /// the storage beneath refused is the error.
    fn change(
        &self,
        change: impl FnOnce(
            &mut Map<String, Value>,
        ) -> (bool, Result<(), Box<dyn std::error::Error + Send + Sync>>),
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let _turn = locked(&self.turn);
        let changed = (|| -> io::Result<Result<(), Box<dyn std::error::Error + Send + Sync>>> {
            // A path with no directory part is in the current one, as Go and Python read it.
            let directory = match self.path.parent() {
                Some(parent) if !parent.as_os_str().is_empty() => parent,
                _ => Path::new("."),
            };
            fs::create_dir_all(directory)?;
            let lock = owner_only_file().open(self.path.with_extension("lock"))?;
            lock.lock()?;
            // Under the lock: setting the list hands it down to the file, and
            // another writer renaming over the file at that moment would be
            // refused.
            owner_only(directory)?;
            let mut document = self.read()?;
            let (changed, beneath) = change(&mut document);
            if changed {
                self.write(&document)?;
            }
            Ok(beneath)
        })();
        match changed {
            Ok(beneath) => beneath,
            Err(error) => {
                self.failed("Could not change", &error);
                Ok(())
            }
        }
    }

    /// Written beside the file and renamed over it: no reader sees half a
    /// document, and no credential is left in a stray file.
    fn write(&self, document: &Map<String, Value>) -> io::Result<()> {
        let mut text = serde_json::to_string_pretty(document)
            .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
        text.push('\n');
        let beside = self.path.with_extension("json.tmp");
        let written = owner_only_file()
            .open(&beside)
            .and_then(|mut file| file.write_all(text.as_bytes()))
            .and_then(|()| fs::rename(&beside, &self.path));
        if written.is_err() {
            let _ = fs::remove_file(&beside);
        }
        written
    }

    /// Put `next` under the session key of `kb_id`: a session of the script
    /// client in the file, any other value beneath it, and nothing in
    /// neither. `renewed` is the sign-in a session of the script client
    /// renews, and none when the session is a sign-in of its own: one that
    /// is no sign-in is kept nowhere, and that is said. `document` is the
    /// file's, held under the lock. Whether the document changed, and what
    /// the storage beneath refused, which changes nothing.
    fn put(
        &self,
        document: &mut Map<String, Value>,
        key: &str,
        kb_id: &str,
        next: Option<&str>,
        renewed: Option<&SignIn>,
    ) -> (bool, Result<(), Box<dyn std::error::Error + Send + Sync>>) {
        match (next, next.and_then(StoredSession::read)) {
            (_, Some(session)) if session.client_id == SCRIPT_CLIENT_ID => {
                let signed_in = match renewed {
                    Some(sign_in) => Ok((sign_in.email.clone(), sign_in.issuer.clone())),
                    None => named_by(&session.access),
                };
                match signed_in {
                    Ok((email, issuer)) => {
                        if let Err(refused) = self.rest.delete(key) {
                            return (false, Err(refused));
                        }
                        document.insert(
                            kb_id.to_owned(),
                            entry_of(&session, email, issuer, SystemTime::now()),
                        );
                        (true, Ok(()))
                    }
                    Err(lacking) => {
                        (self.on_failure)(&format!(
                            "The sign-in to {kb_id} was not kept: {lacking}"
                        ));
                        (false, Ok(()))
                    }
                }
            }
            (Some(next), _) => (false, self.rest.set(key, next)),
            (None, _) => match self.rest.delete(key) {
                Ok(()) => (document.remove(kb_id).is_some(), Ok(())),
                Err(refused) => (false, Err(refused)),
            },
        }
    }
}

impl SessionStorage for SignInStore {
    fn get(&self, key: &str) -> Option<String> {
        self.rest.get(key).or_else(|| {
            let sign_in = sign_in_of(&self.entry(kb_of_session_key(key)?)?)?;
            Some(session_of(&sign_in)?.written())
        })
    }

    fn set(&self, key: &str, value: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        match kb_of_session_key(key) {
            Some(kb_id) => {
                self.change(|document| self.put(document, key, kb_id, Some(value), None))
            }
            None => self.rest.set(key, value),
        }
    }

    fn delete(&self, key: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        match kb_of_session_key(key) {
            Some(kb_id) => self.change(|document| self.put(document, key, kb_id, None, None)),
            None => self.rest.delete(key),
        }
    }

    fn update(
        &self,
        key: &str,
        change: &mut dyn FnMut(Option<&str>) -> Option<String>,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let Some(kb_id) = kb_of_session_key(key) else {
            return self.rest.update(key, change);
        };
        self.change(|document| {
            let beneath = self.rest.get(key);
            let sign_in = match beneath {
                Some(_) => None,
                None => document.get(kb_id).and_then(sign_in_of),
            };
            let held = sign_in
                .as_ref()
                .and_then(session_of)
                .map(|session| session.written());
            // Only a sign-in `change` is given is renewed by what it says.
            let renewed = sign_in.filter(|_| held.is_some());
            let current = beneath.or(held);
            let next = change(current.as_deref());
            if next == current {
                return (false, Ok(()));
            }
            self.put(document, key, kb_id, next.as_deref(), renewed.as_ref())
        })
    }

    /// What another context writes to the storage beneath. The file is not
    /// watched: what another process renewed is read the next time this
    /// one renews, and used as it is (protocol/specs/src/sign-in-store/README.md,
    /// Renewing it).
    fn subscribe(&self, on_change: StorageChange) -> Option<StorageSubscription> {
        self.rest.subscribe(on_change)
    }
}