second_brain_core/sqlite_store/
scope.rs1use 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#[derive(Debug, Clone, PartialEq, Eq)]
17pub enum Principal {
18 Owner,
19 User(String),
20}
21
22#[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
36pub 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
45pub 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 pub fn local_author(&self) -> Result<String> {
61 local_author_on(&self.reader(), self.machine_id())
62 }
63
64 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 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 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 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 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 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}