Skip to main content

second_brain_core/sqlite_store/
scope.rs

1use std::borrow::Cow;
2use std::fmt;
3
4use anyhow::Result;
5use chrono::Utc;
6use rusqlite::{Connection, OptionalExtension, params};
7use uuid::Uuid;
8
9use super::{MEMORY_COLS, SqliteStore, conversion_err, row_to_memory};
10use crate::keys::identity_tag_of;
11use crate::schema::{Memory, Scope};
12
13/// Who is asking. The self-hosted daemon serves one user and acts as
14/// `Owner`; a store shared by several users (a kiln tenant) names each
15/// caller as a `User`.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub enum Principal {
18    Owner,
19    User(String),
20}
21
22/// A user asked to change a memory it may not change.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct AccessDenied {
25    pub memory_id: Uuid,
26}
27
28impl fmt::Display for AccessDenied {
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        write!(f, "memory {} belongs to another user", self.memory_id)
31    }
32}
33
34impl std::error::Error for AccessDenied {}
35
36/// A user reads its own memories and every shared one. A memory with no
37/// author predates attribution and belongs to no user.
38pub fn can_read(principal: &Principal, memory: &Memory) -> bool {
39    match principal {
40        Principal::Owner => true,
41        Principal::User(_) => memory.scope == Scope::Shared || owns(principal, memory),
42    }
43}
44
45/// Only a memory's author changes it, shared or not.
46pub fn can_change(principal: &Principal, memory: &Memory) -> bool {
47    match principal {
48        Principal::Owner => true,
49        Principal::User(_) => owns(principal, memory),
50    }
51}
52
53fn owns(principal: &Principal, memory: &Memory) -> bool {
54    matches!(principal, Principal::User(id) if memory.author.as_deref() == Some(id.as_str()))
55}
56
57impl SqliteStore {
58    /// The author a write records when its writer names none: this store's
59    /// identity, or its device until it joins one.
60    pub fn local_author(&self) -> Result<String> {
61        local_author_on(&self.reader(), self.machine_id())
62    }
63
64    /// None when no such memory exists or `principal` may not read it, so
65    /// a caller cannot tell another user's private memory from a missing
66    /// one.
67    pub fn get_memory_for(&self, id: Uuid, principal: &Principal) -> Result<Option<Memory>> {
68        Ok(crate::store::Store::get_memory(self, id)?.filter(|m| can_read(principal, m)))
69    }
70
71    /// Fails with `AccessDenied` when the memory exists and `principal` may
72    /// not change it; an absent memory passes, leaving the change itself to
73    /// report it missing.
74    pub fn check_change(&self, id: Uuid, principal: &Principal) -> Result<()> {
75        match crate::store::Store::get_memory(self, id)? {
76            Some(memory) if !can_change(principal, &memory) => {
77                Err(AccessDenied { memory_id: id }.into())
78            }
79            _ => Ok(()),
80        }
81    }
82
83    /// Sets who may read the memory, logged as an Update so every peer
84    /// converges on it. False when no such memory exists.
85    pub fn set_memory_scope(&self, id: Uuid, scope: Scope, principal: &Principal) -> Result<bool> {
86        self.with_txn(|tx| {
87            let Some(memory) = Self::memory_on_tx(tx, id)? else {
88                return Ok(false);
89            };
90            if !can_change(principal, &memory) {
91                return Err(AccessDenied { memory_id: id }.into());
92            }
93            if memory.scope == scope {
94                return Ok(true);
95            }
96            tx.execute(
97                "UPDATE memories SET scope = ?2, updated_at = ?3 WHERE id = ?1",
98                params![id.to_string(), scope_to_str(scope), Utc::now().to_rfc3339()],
99            )?;
100            if let Some(memory) = Self::memory_on_tx(tx, id)? {
101                self.log_memory_update(tx, &memory)?;
102            }
103            Ok(true)
104        })
105    }
106
107    /// Streams every memory `principal` may read, without embeddings; a cold
108    /// memory carries its full text read back from its segment.
109    pub fn export_memories_for(
110        &self,
111        principal: &Principal,
112        sink: &mut dyn FnMut(Memory) -> Result<()>,
113    ) -> Result<()> {
114        let conn = self.reader();
115        let mut stmt = conn.prepare(&format!("SELECT {MEMORY_COLS} FROM memories ORDER BY id"))?;
116        let mut rows = stmt.query([])?;
117        while let Some(row) = rows.next()? {
118            let memory = row_to_memory(row, false)?;
119            if can_read(principal, &memory) {
120                let mut full = self.full_text_form(&conn, &memory)?.into_owned();
121                full.embedding = Vec::new();
122                sink(full)?;
123            }
124        }
125        Ok(())
126    }
127
128    /// `memory` as a local write stores it: a row that already exists keeps
129    /// its author and scope, and a new row without an author gets this
130    /// store's.
131    pub(crate) fn attributed<'m>(
132        &self,
133        conn: &Connection,
134        memory: &'m Memory,
135    ) -> Result<Cow<'m, Memory>> {
136        match attribution(conn, memory.id)? {
137            Some(row) => Ok(overlay(Cow::Borrowed(memory), row)),
138            None if memory.author.is_some() => Ok(Cow::Borrowed(memory)),
139            None => Ok(Cow::Owned(Memory {
140                author: Some(local_author_on(conn, self.machine_id())?),
141                ..memory.clone()
142            })),
143        }
144    }
145
146    /// `memory` carrying its row's author and scope, which a caller's copy
147    /// may lack: every logged form of a memory carries the row's.
148    pub(crate) fn with_row_attribution<'m>(
149        conn: &Connection,
150        memory: Cow<'m, Memory>,
151    ) -> Result<Cow<'m, Memory>> {
152        Ok(match attribution(conn, memory.id)? {
153            Some(row) => overlay(memory, row),
154            None => memory,
155        })
156    }
157}
158
159fn overlay(memory: Cow<'_, Memory>, (author, scope): (Option<String>, Scope)) -> Cow<'_, Memory> {
160    if memory.author == author && memory.scope == scope {
161        return memory;
162    }
163    let mut owned = memory.into_owned();
164    owned.author = author;
165    owned.scope = scope;
166    Cow::Owned(owned)
167}
168
169fn attribution(conn: &Connection, id: Uuid) -> Result<Option<(Option<String>, Scope)>> {
170    conn.query_row(
171        "SELECT author, scope FROM memories WHERE id = ?1",
172        params![id.to_string()],
173        |r| Ok((r.get(0)?, parse_scope(&r.get::<_, String>(1)?)?)),
174    )
175    .optional()
176    .map_err(Into::into)
177}
178
179fn local_author_on(conn: &Connection, machine_id: &str) -> Result<String> {
180    Ok(identity_tag_of(conn, machine_id)?.unwrap_or_else(|| format!("device:{machine_id}")))
181}
182
183pub(crate) fn scope_to_str(scope: Scope) -> &'static str {
184    match scope {
185        Scope::Private => "private",
186        Scope::Shared => "shared",
187    }
188}
189
190pub(crate) fn parse_scope(s: &str) -> rusqlite::Result<Scope> {
191    match s {
192        "private" => Ok(Scope::Private),
193        "shared" => Ok(Scope::Shared),
194        other => Err(conversion_err(std::io::Error::other(format!(
195            "unknown scope: {other}"
196        )))),
197    }
198}