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 crate::changes_simplifier::simplify_changes;
17use crate::link::Link;
18use crate::named_type_links::NamedTypeLinks;
19use crate::permissions::{AccessPolicy, PermissionPolicy, PermissionsDecorator};
20use crate::query_processor::QueryProcessor;
21use crate::undoable_links::UndoableLinksDecorator;
22
23/// The subject of a token, or `None` when the token is not valid: answers
24/// `(auth: token)`.
25///
26/// It is given the store the sessions serve, below any permissions, so a
27/// [`LinksTokenTable`](crate::LinksTokenTable) kept in the data can read it:
28/// `Box::new(|store, token| LinksTokenTable::new(store).authenticate(token))`.
29/// An error fails the authentication.
30pub type Authenticator = Box<dyn FnMut(&mut dyn NamedTypeLinks, &str) -> Result<Option<u32>>>;
31
32/// A session of a [`LinksSessions`], as [`LinksSessions::open`] returns it.
33#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
34pub struct SessionId(u64);
35
36/// What a session keeps between its requests.
37#[derive(Debug, Default)]
38struct Session {
39    subject: u32,
40    /// The links the subject created, while they are its own.
41    created: HashSet<u32>,
42}
43
44enum Store<S: NamedTypeLinks, P: AccessPolicy> {
45    Plain(S),
46    Permitted(PermissionsDecorator<UndoableLinksDecorator<S>, P>),
47}
48
49/// A store served to many sessions, each with its subject (issue #149).
50///
51/// Without permissions every session sees and changes the whole store,
52/// exactly as before permissions existed. With them
53/// ([`with_permissions`](Self::with_permissions)), a session sees the store
54/// through a [`PermissionsDecorator`] of its subject, and every request is
55/// atomic: one that fails is undone whole, the writes the store made on its
56/// own (cascades, merges) and the names it took included, even where they
57/// touched links the subject cannot see.
58///
59/// `(auth: token)` sets the subject of the session to the one the
60/// [`Authenticator`] gives the token, and answers `(subject: i)`; an unknown
61/// token, or sessions without an authenticator, answer
62/// `(error: 'Forbidden: authentication failed')`.
63///
64/// Requests run one at a time, as `&mut self` already demands.
65pub struct LinksSessions<S: NamedTypeLinks, P: AccessPolicy = PermissionPolicy> {
66    store: Store<S, P>,
67    processor: QueryProcessor,
68    authenticate: Option<Authenticator>,
69    subject: u32,
70    sessions: HashMap<SessionId, Session>,
71    next: u64,
72}
73
74impl<S: NamedTypeLinks> LinksSessions<S> {
75    /// Sessions that see and change the whole store.
76    pub fn new(store: S) -> Self {
77        Self::of(Store::Plain(store))
78    }
79}
80
81impl<S: NamedTypeLinks, P: AccessPolicy> LinksSessions<S, P> {
82    /// Sessions that see the store as `policy` lets their subjects.
83    pub fn with_permissions(store: S, policy: P) -> Self {
84        Self::of(Store::Permitted(PermissionsDecorator::new(
85            UndoableLinksDecorator::new(store),
86            policy,
87            0,
88        )))
89    }
90
91    fn of(store: Store<S, P>) -> Self {
92        Self {
93            store,
94            processor: QueryProcessor::new(false),
95            authenticate: None,
96            subject: 0,
97            sessions: HashMap::new(),
98            next: 0,
99        }
100    }
101
102    /// Answers `(auth: token)` with `authenticate`.
103    pub fn with_authenticator(
104        mut self,
105        authenticate: impl FnMut(&mut dyn NamedTypeLinks, &str) -> Result<Option<u32>> + 'static,
106    ) -> Self {
107        self.authenticate = Some(Box::new(authenticate));
108        self
109    }
110
111    /// The subject of a session before any `(auth: token)`; the null link
112    /// (0, the default) is a guest.
113    pub fn with_subject(mut self, subject: u32) -> Self {
114        self.subject = subject;
115        self
116    }
117
118    /// Passed to [`QueryProcessor::with_auto_create_missing_references`].
119    pub fn with_auto_create_missing_references(mut self, enabled: bool) -> Self {
120        self.processor = QueryProcessor::new(false).with_auto_create_missing_references(enabled);
121        self
122    }
123
124    /// Whether the sessions see the store through permissions.
125    pub fn has_permissions(&self) -> bool {
126        matches!(self.store, Store::Permitted(_))
127    }
128
129    /// The store.
130    pub fn store(&self) -> &S {
131        match &self.store {
132            Store::Plain(store) => store,
133            Store::Permitted(view) => view.inner().inner(),
134        }
135    }
136
137    /// The store, to read or write it as no session.
138    pub fn store_mut(&mut self) -> &mut S {
139        match &mut self.store {
140            Store::Plain(store) => store,
141            Store::Permitted(view) => view.inner_mut().inner_mut(),
142        }
143    }
144
145    /// The policy, when there are permissions.
146    pub fn policy(&self) -> Option<&P> {
147        match &self.store {
148            Store::Plain(_) => None,
149            Store::Permitted(view) => Some(view.policy()),
150        }
151    }
152
153    pub fn into_inner(self) -> S {
154        match self.store {
155            Store::Plain(store) => store,
156            Store::Permitted(view) => view.into_inner().into_inner(),
157        }
158    }
159
160    /// Opens a session of `subject`, by default the one of
161    /// [`with_subject`](Self::with_subject).
162    pub fn open(&mut self, subject: Option<u32>) -> SessionId {
163        let id = SessionId(self.next);
164        self.next += 1;
165        self.sessions.insert(
166            id,
167            Session {
168                subject: subject.unwrap_or(self.subject),
169                created: HashSet::new(),
170            },
171        );
172        id
173    }
174
175    /// Closes a session.
176    pub fn close(&mut self, session: SessionId) {
177        self.sessions.remove(&session);
178    }
179
180    /// The sessions that are open.
181    pub fn sessions(&self) -> Vec<SessionId> {
182        let mut sessions: Vec<SessionId> = self.sessions.keys().copied().collect();
183        sessions.sort();
184        sessions
185    }
186
187    /// The subject the requests of `session` run as, while it is open.
188    pub fn subject(&self, session: SessionId) -> Option<u32> {
189        self.sessions.get(&session).map(|session| session.subject)
190    }
191
192    /// The links `session` created, while they are its own.
193    pub fn created(&self, session: SessionId) -> Option<&HashSet<u32>> {
194        self.sessions.get(&session).map(|session| &session.created)
195    }
196
197    /// Answers a request written as LiNo text, as the text protocol does.
198    pub fn request(&mut self, session: SessionId, text: &str) -> String {
199        let reply = match parse_document(text) {
200            Ok(document) => self.execute(session, &document),
201            Err(error) => error_document(&error.to_string()),
202        };
203        format_document(&reply)
204    }
205
206    /// Answers one request document of `session`; a session that is not
207    /// open is opened.
208    pub fn execute(&mut self, session: SessionId, document: &[LiNo<String>]) -> LinoDocument {
209        self.execute_observed(session, document, &mut Vec::new())
210    }
211
212    /// Like [`execute`](Self::execute), adding the net change of every link
213    /// the request changed in the store to `changed`, with plain numbers:
214    /// the cascades and merges a write led to as well, even where the
215    /// subject cannot see them. A request undone for failing changed nothing.
216    pub fn execute_observed(
217        &mut self,
218        session: SessionId,
219        document: &[LiNo<String>],
220        changed: &mut Vec<Change>,
221    ) -> LinoDocument {
222        let mut state = self.sessions.remove(&session).unwrap_or(Session {
223            subject: self.subject,
224            created: HashSet::new(),
225        });
226        let reply = self.execute_as(&mut state, document, changed);
227        self.sessions.insert(session, state);
228        reply
229    }
230
231    /// Whether the subject of `session` may read `link`: always, without
232    /// permissions; a session that is not open is a guest.
233    pub fn can_read(&mut self, session: SessionId, link: &Link) -> bool {
234        let view = match &mut self.store {
235            Store::Plain(_) => return true,
236            Store::Permitted(view) => view,
237        };
238        let (subject, created) = match self.sessions.get_mut(&session) {
239            Some(state) => (state.subject, std::mem::take(&mut state.created)),
240            None => (self.subject, HashSet::new()),
241        };
242        view.set_subject(subject);
243        let created = view.replace_created(created);
244        let readable = view.can_read(link);
245        let created = view.replace_created(created);
246        if let Some(state) = self.sessions.get_mut(&session) {
247            state.created = created;
248        }
249        readable
250    }
251
252    fn execute_as(
253        &mut self,
254        session: &mut Session,
255        document: &[LiNo<String>],
256        changed: &mut Vec<Change>,
257    ) -> LinoDocument {
258        if let [LiNo::Link {
259            id: Some(id),
260            values,
261        }] = document
262        {
263            if id == "auth" {
264                return self.authenticate(session, values);
265            }
266        }
267        let view = match &mut self.store {
268            Store::Plain(store) => {
269                return execute_observed_request(store, &self.processor, document, changed)
270            }
271            Store::Permitted(view) => view,
272        };
273        view.set_subject(session.subject);
274        view.replace_created(std::mem::take(&mut session.created));
275        view.inner_mut().begin();
276        let processor = &self.processor;
277        let outcome = panic::catch_unwind(AssertUnwindSafe(|| request(view, processor, document)));
278        let reply = match outcome {
279            Ok(reply) if error_message(&reply).is_none() => {
280                let deleted: HashSet<u32> = view
281                    .inner()
282                    .log()
283                    .changes()
284                    .iter()
285                    .filter_map(|change| match change {
286                        (Some(before), None) => Some(before.index),
287                        _ => None,
288                    })
289                    .collect();
290                let changes = view
291                    .inner()
292                    .log()
293                    .changes()
294                    .iter()
295                    .map(|(before, after)| {
296                        (
297                            before.unwrap_or_else(Link::null),
298                            after.unwrap_or_else(Link::null),
299                        )
300                    })
301                    .collect();
302                changed.extend(
303                    simplify_changes(changes)
304                        .into_iter()
305                        .filter(|(before, after)| before != after),
306                );
307                view.inner_mut().commit();
308                // The links are gone: no other session owns them any more.
309                for other in self.sessions.values_mut() {
310                    other.created.retain(|index| !deleted.contains(index));
311                }
312                reply
313            }
314            Ok(reply) => match undo(view) {
315                Ok(()) => reply,
316                Err(error) => error_document(&format!(
317                    "{}; undoing it failed: {error:#}",
318                    error_message(&reply).unwrap_or_default()
319                )),
320            },
321            Err(panicked) => {
322                let _ = undo(view);
323                session.created = view.replace_created(HashSet::new());
324                panic::resume_unwind(panicked);
325            }
326        };
327        session.created = view.replace_created(HashSet::new());
328        reply
329    }
330
331    fn authenticate(&mut self, session: &mut Session, values: &[LiNo<String>]) -> LinoDocument {
332        let found = match (values, self.authenticate.as_mut()) {
333            ([LiNo::Ref(token)], Some(authenticate)) => {
334                let store: &mut dyn NamedTypeLinks = match &mut self.store {
335                    Store::Plain(store) => store,
336                    Store::Permitted(view) => view.inner_mut().inner_mut(),
337                };
338                authenticate(store, token).ok().flatten()
339            }
340            _ => None,
341        };
342        match found {
343            Some(subject) => {
344                session.subject = subject;
345                vec![LiNo::Link {
346                    id: Some("subject".to_string()),
347                    values: vec![LiNo::Ref(subject.to_string())],
348                }]
349            }
350            None => error_document("Forbidden: authentication failed"),
351        }
352    }
353}
354
355/// Undoes the request, and forgets the links it created.
356fn undo<S: NamedTypeLinks, P: AccessPolicy>(
357    view: &mut PermissionsDecorator<UndoableLinksDecorator<S>, P>,
358) -> Result<()> {
359    for created in view.inner_mut().rollback()? {
360        view.forget(created);
361    }
362    Ok(())
363}
364
365/// A request as the subject sees the store: names of links it cannot read
366/// are not found, and references are checked in the store below.
367fn request<L: NamedTypeLinks, P: AccessPolicy>(
368    view: &mut PermissionsDecorator<L, P>,
369    processor: &QueryProcessor,
370    document: &[LiNo<String>],
371) -> LinoDocument {
372    let operation = match LinksOperation::from_document(document) {
373        Ok(operation) => operation,
374        Err(error) => return error_document(&error.to_string()),
375    };
376    match operation {
377        Some(LinksOperation::GetName(link)) if !view.exists(link) => Vec::new(),
378        Some(LinksOperation::GetByName(name)) => match view.get_by_name(&name) {
379            Ok(Some(link)) if link != 0 && view.exists(link) => {
380                execute_request(view, processor, document)
381            }
382            Ok(_) => Vec::new(),
383            Err(error) => error_document(&format!("{error:#}")),
384        },
385        _ => execute_request(view, processor, document),
386    }
387}