Skip to main content

link_cli/protocol/
sessions.rs

1//! Sessions of a links server, each with its subject (issue #149).
2//!
3//! [`LinksSessions`] is what a [`LinksServer`](super::LinksServer) gives
4//! every connection, without the network. The C# counterparts are
5//! `LinksSessions` and `LinksSession`.
6
7use std::collections::{HashMap, HashSet};
8use std::panic::{self, AssertUnwindSafe};
9
10use anyhow::Result;
11use links_notation::binary::{format_document, parse_document, LinoDocument};
12use links_notation::LiNo;
13
14use super::links_operations::{Change, LinksOperation};
15use super::server::{error_document, error_message, execute_observed_request, execute_request};
16use super::triplets_operations::{execute_observed_triplets_request, TripletsOperation};
17use crate::changes_simplifier::simplify_changes;
18use crate::link::Link;
19use crate::named_type_links::NamedTypeLinks;
20use crate::permissions::{AccessPolicy, PermissionPolicy, PermissionsDecorator};
21use crate::query_processor::QueryProcessor;
22use crate::triplets::{TripletChange, TripletMarkers, TripletsOverDoublets};
23use crate::undoable_links::UndoableLinksDecorator;
24
25/// The subject of a token, or `None` when the token is not valid: answers
26/// `(auth: token)`.
27///
28/// It is given the store the sessions serve, below any permissions, so a
29/// [`LinksTokenTable`](crate::LinksTokenTable) kept in the data can read it:
30/// `Box::new(|store, token| LinksTokenTable::new(store).authenticate(token))`.
31/// An error fails the authentication.
32pub type Authenticator = Box<dyn FnMut(&mut dyn NamedTypeLinks, &str) -> Result<Option<u32>>>;
33
34/// A session of a [`LinksSessions`], as [`LinksSessions::open`] returns it.
35#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
36pub struct SessionId(u64);
37
38/// What a session keeps between its requests.
39#[derive(Debug, Default)]
40struct Session {
41    subject: u32,
42    /// The links the subject created, while they are its own.
43    created: HashSet<u32>,
44}
45
46enum Store<S: NamedTypeLinks, P: AccessPolicy> {
47    Plain(S),
48    Permitted(PermissionsDecorator<UndoableLinksDecorator<S>, P>),
49}
50
51/// A store served to many sessions, each with its subject (issue #149).
52///
53/// Without permissions every session sees and changes the whole store,
54/// exactly as before permissions existed. With them
55/// ([`with_permissions`](Self::with_permissions)), a session sees the store
56/// through a [`PermissionsDecorator`] of its subject, and every request is
57/// atomic: one that fails is undone whole, the writes the store made on its
58/// own (cascades, merges) and the names it took included, even where they
59/// touched links the subject cannot see.
60///
61/// `(auth: token)` sets the subject of the session to the one the
62/// [`Authenticator`] gives the token, and answers `(subject: i)`; an unknown
63/// token, or sessions without an authenticator, answer
64/// `(error: 'Forbidden: authentication failed')`.
65///
66/// With [`with_triplets`](Self::with_triplets) the sessions read every request
67/// as triplets (issue #152; see [`TripletsOperation`]), and permissions judge
68/// each triplet as a whole, not the wrappers and pairs that store it.
69///
70/// Requests run one at a time, as `&mut self` already demands.
71pub struct LinksSessions<S: NamedTypeLinks, P: AccessPolicy = PermissionPolicy> {
72    store: Store<S, P>,
73    processor: QueryProcessor,
74    triplets: Option<TripletMarkers>,
75    authenticate: Option<Authenticator>,
76    subject: u32,
77    sessions: HashMap<SessionId, Session>,
78    next: u64,
79}
80
81impl<S: NamedTypeLinks> LinksSessions<S> {
82    /// Sessions that see and change the whole store.
83    pub fn new(store: S) -> Self {
84        Self::of(Store::Plain(store))
85    }
86}
87
88impl<S: NamedTypeLinks, P: AccessPolicy> LinksSessions<S, P> {
89    /// Sessions that see the store as `policy` lets their subjects.
90    pub fn with_permissions(store: S, policy: P) -> Self {
91        Self::of(Store::Permitted(PermissionsDecorator::new(
92            UndoableLinksDecorator::new(store),
93            policy,
94            0,
95        )))
96    }
97
98    fn of(store: Store<S, P>) -> Self {
99        Self {
100            store,
101            processor: QueryProcessor::new(false),
102            triplets: None,
103            authenticate: None,
104            subject: 0,
105            sessions: HashMap::new(),
106            next: 0,
107        }
108    }
109
110    /// Answers `(auth: token)` with `authenticate`.
111    pub fn with_authenticator(
112        mut self,
113        authenticate: impl FnMut(&mut dyn NamedTypeLinks, &str) -> Result<Option<u32>> + 'static,
114    ) -> Self {
115        self.authenticate = Some(Box::new(authenticate));
116        self
117    }
118
119    /// The subject of a session before any `(auth: token)`; the null link
120    /// (0, the default) is a guest.
121    pub fn with_subject(mut self, subject: u32) -> Self {
122        self.subject = subject;
123        self
124    }
125
126    /// Passed to [`QueryProcessor::with_auto_create_missing_references`].
127    pub fn with_auto_create_missing_references(mut self, enabled: bool) -> Self {
128        self.processor = QueryProcessor::new(false).with_auto_create_missing_references(enabled);
129        self
130    }
131
132    /// Reads every request as triplets; the markers of the encoding are
133    /// created in the store when they are missing, whatever the subject of a
134    /// session may do.
135    pub fn with_triplets(mut self) -> Result<Self> {
136        self.ensure_triplets()?;
137        Ok(self)
138    }
139
140    /// Like [`with_triplets`](Self::with_triplets), on sessions already built.
141    pub fn ensure_triplets(&mut self) -> Result<TripletMarkers> {
142        if let Some(markers) = self.triplets {
143            return Ok(markers);
144        }
145        let markers = TripletMarkers::ensure(self.store_mut())?;
146        self.triplets = Some(markers);
147        Ok(markers)
148    }
149
150    /// Whether the sessions read every request as triplets.
151    pub fn has_triplets(&self) -> bool {
152        self.triplets.is_some()
153    }
154
155    /// Whether the sessions see the store through permissions.
156    pub fn has_permissions(&self) -> bool {
157        matches!(self.store, Store::Permitted(_))
158    }
159
160    /// The store.
161    pub fn store(&self) -> &S {
162        match &self.store {
163            Store::Plain(store) => store,
164            Store::Permitted(view) => view.inner().inner(),
165        }
166    }
167
168    /// The store, to read or write it as no session.
169    pub fn store_mut(&mut self) -> &mut S {
170        match &mut self.store {
171            Store::Plain(store) => store,
172            Store::Permitted(view) => view.inner_mut().inner_mut(),
173        }
174    }
175
176    /// The policy, when there are permissions.
177    pub fn policy(&self) -> Option<&P> {
178        match &self.store {
179            Store::Plain(_) => None,
180            Store::Permitted(view) => Some(view.policy()),
181        }
182    }
183
184    pub fn into_inner(self) -> S {
185        match self.store {
186            Store::Plain(store) => store,
187            Store::Permitted(view) => view.into_inner().into_inner(),
188        }
189    }
190
191    /// Opens a session of `subject`, by default the one of
192    /// [`with_subject`](Self::with_subject).
193    pub fn open(&mut self, subject: Option<u32>) -> SessionId {
194        let id = SessionId(self.next);
195        self.next += 1;
196        self.sessions.insert(
197            id,
198            Session {
199                subject: subject.unwrap_or(self.subject),
200                created: HashSet::new(),
201            },
202        );
203        id
204    }
205
206    /// Closes a session.
207    pub fn close(&mut self, session: SessionId) {
208        self.sessions.remove(&session);
209    }
210
211    /// The sessions that are open.
212    pub fn sessions(&self) -> Vec<SessionId> {
213        let mut sessions: Vec<SessionId> = self.sessions.keys().copied().collect();
214        sessions.sort();
215        sessions
216    }
217
218    /// The subject the requests of `session` run as, while it is open.
219    pub fn subject(&self, session: SessionId) -> Option<u32> {
220        self.sessions.get(&session).map(|session| session.subject)
221    }
222
223    /// The links `session` created, while they are its own.
224    pub fn created(&self, session: SessionId) -> Option<&HashSet<u32>> {
225        self.sessions.get(&session).map(|session| &session.created)
226    }
227
228    /// Answers a request written as LiNo text, as the text protocol does.
229    pub fn request(&mut self, session: SessionId, text: &str) -> String {
230        let parsed = match self.store().query_limits() {
231            Some(limits) => super::server::parse_document_with_limits(text, limits),
232            None => parse_document(text).map_err(Into::into),
233        };
234        let reply = match parsed {
235            Ok(document) => self.execute(session, &document),
236            Err(error) => error_document(&error.to_string()),
237        };
238        format_document(&reply)
239    }
240
241    /// Answers one request document of `session`; a session that is not
242    /// open is opened.
243    pub fn execute(&mut self, session: SessionId, document: &[LiNo<String>]) -> LinoDocument {
244        self.execute_observed(session, document, &mut Vec::new())
245    }
246
247    /// Like [`execute`](Self::execute), adding the net change of every link
248    /// the request changed in the store to `changed`, with plain numbers:
249    /// the cascades and merges a write led to as well, even where the
250    /// subject cannot see them. A request undone for failing changed nothing.
251    pub fn execute_observed(
252        &mut self,
253        session: SessionId,
254        document: &[LiNo<String>],
255        changed: &mut Vec<Change>,
256    ) -> LinoDocument {
257        self.run(session, document, changed, &mut Vec::new())
258    }
259
260    /// Like [`execute`](Self::execute) on sessions that read requests as
261    /// triplets, adding every triplet the request changed to `changed`, with
262    /// plain numbers: those it took along too, even where the subject cannot
263    /// see them. A request undone for failing changed nothing.
264    pub fn execute_triplets_observed(
265        &mut self,
266        session: SessionId,
267        document: &[LiNo<String>],
268        changed: &mut Vec<TripletChange>,
269    ) -> LinoDocument {
270        self.run(session, document, &mut Vec::new(), changed)
271    }
272
273    fn run(
274        &mut self,
275        session: SessionId,
276        document: &[LiNo<String>],
277        changed: &mut Vec<Change>,
278        triplets_changed: &mut Vec<TripletChange>,
279    ) -> LinoDocument {
280        if let Some(limits) = self.store().query_limits() {
281            if let Err(error) = super::server::admit_document(document, limits) {
282                return error_document(&error.to_string());
283            }
284        }
285        let mut state = self.sessions.remove(&session).unwrap_or(Session {
286            subject: self.subject,
287            created: HashSet::new(),
288        });
289        let reply = self.execute_as(&mut state, document, changed, triplets_changed);
290        self.sessions.insert(session, state);
291        reply
292    }
293
294    /// Whether the subject of `session` may read `link`: always, without
295    /// permissions; a session that is not open is a guest.
296    pub fn can_read(&mut self, session: SessionId, link: &Link) -> bool {
297        let view = match &mut self.store {
298            Store::Plain(_) => return true,
299            Store::Permitted(view) => view,
300        };
301        let (subject, created) = match self.sessions.get_mut(&session) {
302            Some(state) => (state.subject, std::mem::take(&mut state.created)),
303            None => (self.subject, HashSet::new()),
304        };
305        view.set_subject(subject);
306        let created = view.replace_created(created);
307        let readable = if self.triplets.is_some() {
308            view.can_read_triplet(link)
309        } else {
310            view.can_read(link)
311        };
312        let created = view.replace_created(created);
313        if let Some(state) = self.sessions.get_mut(&session) {
314            state.created = created;
315        }
316        readable
317    }
318
319    fn execute_as(
320        &mut self,
321        session: &mut Session,
322        document: &[LiNo<String>],
323        changed: &mut Vec<Change>,
324        triplets_changed: &mut Vec<TripletChange>,
325    ) -> LinoDocument {
326        if let [LiNo::Link {
327            id: Some(id),
328            values,
329        }] = document
330        {
331            if id == "auth" {
332                return self.authenticate(session, values);
333            }
334        }
335        let markers = self.triplets;
336        let view = match &mut self.store {
337            Store::Plain(store) => {
338                return match markers {
339                    Some(markers) => execute_observed_triplets_request(
340                        &mut TripletsOverDoublets::with_markers(store, markers),
341                        document,
342                        triplets_changed,
343                    ),
344                    None => execute_observed_request(store, &self.processor, document, changed),
345                };
346            }
347            Store::Permitted(view) => view,
348        };
349        view.set_subject(session.subject);
350        view.replace_created(std::mem::take(&mut session.created));
351        view.inner_mut().begin();
352        let processor = &self.processor;
353        let observed = triplets_changed.len();
354        let outcome = panic::catch_unwind(AssertUnwindSafe(|| match markers {
355            Some(markers) => triplets_request(view, markers, document, triplets_changed),
356            None => request(view, document, |view, document| {
357                execute_request(view, processor, document)
358            }),
359        }));
360        let reply = match outcome {
361            Ok(reply) if error_message(&reply).is_none() => {
362                let deleted: HashSet<u32> = view
363                    .inner()
364                    .log()
365                    .changes()
366                    .iter()
367                    .filter_map(|change| match change {
368                        (Some(before), None) => Some(before.index),
369                        _ => None,
370                    })
371                    .collect();
372                let changes = view
373                    .inner()
374                    .log()
375                    .changes()
376                    .iter()
377                    .map(|(before, after)| {
378                        (
379                            before.unwrap_or_else(Link::null),
380                            after.unwrap_or_else(Link::null),
381                        )
382                    })
383                    .collect();
384                changed.extend(
385                    simplify_changes(changes)
386                        .into_iter()
387                        .filter(|(before, after)| before != after),
388                );
389                view.inner_mut().commit();
390                // The links are gone: no other session owns them any more.
391                for other in self.sessions.values_mut() {
392                    other.created.retain(|index| !deleted.contains(index));
393                }
394                reply
395            }
396            Ok(reply) => {
397                triplets_changed.truncate(observed);
398                match undo(view) {
399                    Ok(()) => reply,
400                    Err(error) => error_document(&format!(
401                        "{}; undoing it failed: {error:#}",
402                        error_message(&reply).unwrap_or_default()
403                    )),
404                }
405            }
406            Err(panicked) => {
407                let _ = undo(view);
408                session.created = view.replace_created(HashSet::new());
409                panic::resume_unwind(panicked);
410            }
411        };
412        session.created = view.replace_created(HashSet::new());
413        reply
414    }
415
416    fn authenticate(&mut self, session: &mut Session, values: &[LiNo<String>]) -> LinoDocument {
417        let found = match (values, self.authenticate.as_mut()) {
418            ([LiNo::Ref(token)], Some(authenticate)) => {
419                let store: &mut dyn NamedTypeLinks = match &mut self.store {
420                    Store::Plain(store) => store,
421                    Store::Permitted(view) => view.inner_mut().inner_mut(),
422                };
423                authenticate(store, token).ok().flatten()
424            }
425            _ => None,
426        };
427        match found {
428            Some(subject) => {
429                session.subject = subject;
430                vec![LiNo::Link {
431                    id: Some("subject".to_string()),
432                    values: vec![LiNo::Ref(subject.to_string())],
433                }]
434            }
435            None => error_document("Forbidden: authentication failed"),
436        }
437    }
438}
439
440/// Undoes the request, and forgets the links it created.
441fn undo<S: NamedTypeLinks, P: AccessPolicy>(
442    view: &mut PermissionsDecorator<UndoableLinksDecorator<S>, P>,
443) -> Result<()> {
444    for created in view.inner_mut().rollback()? {
445        view.forget(created);
446    }
447    Ok(())
448}
449
450/// A request as the subject sees the store: names of links it cannot read
451/// are not found, and `run` answers everything else.
452fn request<L: NamedTypeLinks, P: AccessPolicy>(
453    view: &mut PermissionsDecorator<L, P>,
454    document: &[LiNo<String>],
455    run: impl FnOnce(&mut PermissionsDecorator<L, P>, &[LiNo<String>]) -> LinoDocument,
456) -> LinoDocument {
457    let operation = match LinksOperation::from_document(document) {
458        Ok(operation) => operation,
459        Err(error) => return error_document(&error.to_string()),
460    };
461    match operation {
462        Some(LinksOperation::GetName(link)) if !view.exists(link) => Vec::new(),
463        Some(LinksOperation::GetByName(name)) => match view.get_by_name(&name) {
464            Ok(Some(link)) if link != 0 && view.exists(link) => run(view, document),
465            Ok(_) => Vec::new(),
466            Err(error) => error_document(&format!("{error:#}")),
467        },
468        _ => run(view, document),
469    }
470}
471
472/// A request over triplets as the subject sees the store: the permissions move
473/// above the triplets, which write their wrappers and pairs straight to the
474/// store below, still inside the transaction of the request.
475fn triplets_request<S: NamedTypeLinks, P: AccessPolicy>(
476    view: &mut PermissionsDecorator<UndoableLinksDecorator<S>, P>,
477    markers: TripletMarkers,
478    document: &[LiNo<String>],
479    changed: &mut Vec<TripletChange>,
480) -> LinoDocument {
481    let subject = view.subject();
482    let created = view.replace_created(HashSet::new());
483    let (links, policy) = view.parts_mut();
484    let mut layer = PermissionsDecorator::new(
485        TripletsOverDoublets::with_markers(links, markers),
486        policy,
487        subject,
488    )
489    .with_created(created);
490    // A triplet operation holds four parts where one over doublets holds three:
491    // only what is left, the names, is for `request` to look at.
492    let reply = if matches!(TripletsOperation::from_document(document), Ok(None)) {
493        request(&mut layer, document, |layer, document| {
494            execute_observed_triplets_request(layer, document, changed)
495        })
496    } else {
497        execute_observed_triplets_request(&mut layer, document, changed)
498    };
499    let created = layer.replace_created(HashSet::new());
500    view.replace_created(created);
501    reply
502}