Skip to main content

vault_core/
ics_feeds.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! Calendar feed tokens — Phase 24.3.
4//!
5//! A feed is a bearer credential of its own kind: 32 random bytes, shown once,
6//! stored here only as a SHA-256 hash — the same shape `users::create_user_token`
7//! already uses for API tokens, for the same reason. `GET /ics/{token}.ics`
8//! looks a presented token up by its hash and never needs the plaintext again.
9//!
10//! `user_id = NULL` means the feed belongs to the vault owner and is built from
11//! **every** entry, unfiltered. A non-null `user_id` means the feed must be
12//! re-filtered through `filter_vault_for_user` on **every fetch**, not once at
13//! creation — a permission revoked after the feed was minted has to shrink it,
14//! or the feed outlives the access it was issued under.
15
16use rusqlite::{params, Connection, OptionalExtension};
17use serde::Serialize;
18use sha2::{Digest, Sha256};
19
20/// Creates the table if absent. Called from [`crate::init_schema`].
21pub fn init_schema(conn: &Connection) -> Result<(), String> {
22    conn.execute_batch(
23        "CREATE TABLE IF NOT EXISTS ics_feeds (
24             id              TEXT PRIMARY KEY,
25             user_id         TEXT,
26             token_hash      TEXT NOT NULL UNIQUE,
27             name            TEXT NOT NULL,
28             kinds           TEXT NOT NULL,
29             scope           TEXT NOT NULL DEFAULT '',
30             created_at      TEXT NOT NULL,
31             last_fetched_at TEXT,
32             revoked_at      TEXT
33         );
34         CREATE INDEX IF NOT EXISTS ics_feeds_token ON ics_feeds(token_hash);",
35    )
36    .map_err(|e| e.to_string())
37}
38
39#[derive(Clone, Serialize)]
40pub struct FeedRecord {
41    pub id: String,
42    pub user_id: Option<String>,
43    pub name: String,
44    /// `created` / `expires` / `rotation`, comma-joined.
45    pub kinds: String,
46    /// Comma-joined opt-in flags. Only meaningful value today: `account_names`
47    /// — off by default, because an account name is often an email address and
48    /// the design's rule is that a feed says nothing beyond names and dates
49    /// unless the person creating it asks for more.
50    pub scope: String,
51    pub created_at: String,
52    pub last_fetched_at: Option<String>,
53    pub revoked_at: Option<String>,
54}
55
56impl FeedRecord {
57    pub fn is_revoked(&self) -> bool {
58        self.revoked_at.is_some()
59    }
60
61    pub fn include_account_names(&self) -> bool {
62        self.scope.split(',').any(|s| s == "account_names")
63    }
64
65    pub fn kind_list(&self) -> Vec<String> {
66        self.kinds
67            .split(',')
68            .filter(|s| !s.is_empty())
69            .map(str::to_string)
70            .collect()
71    }
72}
73
74fn sha256_hex(input: &str) -> String {
75    hex::encode(Sha256::digest(input.as_bytes()))
76}
77
78fn row_to_record(row: &rusqlite::Row) -> rusqlite::Result<FeedRecord> {
79    Ok(FeedRecord {
80        id: row.get(0)?,
81        user_id: row.get(1)?,
82        name: row.get(2)?,
83        kinds: row.get(3)?,
84        scope: row.get(4)?,
85        created_at: row.get(5)?,
86        last_fetched_at: row.get(6)?,
87        revoked_at: row.get(7)?,
88    })
89}
90
91const COLS: &str = "id, user_id, name, kinds, scope, created_at, last_fetched_at, revoked_at";
92
93/// Mints a feed. Returns the record and the plaintext token — the **only** time
94/// the plaintext exists outside the requester's own response.
95pub fn create_feed(
96    conn: &Connection,
97    user_id: Option<&str>,
98    name: &str,
99    kinds: &[String],
100    include_account_names: bool,
101) -> Result<(FeedRecord, String), String> {
102    use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
103    use rand::Rng;
104    let mut raw = [0u8; 32];
105    rand::rng().fill_bytes(&mut raw);
106    let token = URL_SAFE_NO_PAD.encode(raw);
107    let token_hash = sha256_hex(&token);
108    let id = crate::new_uuid();
109    let created_at = crate::iso_now();
110    let kinds_joined = kinds.join(",");
111    let scope = if include_account_names {
112        "account_names".to_string()
113    } else {
114        String::new()
115    };
116    conn.execute(
117        "INSERT INTO ics_feeds (id, user_id, token_hash, name, kinds, scope, created_at) \
118         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
119        params![
120            id,
121            user_id,
122            token_hash,
123            name,
124            kinds_joined,
125            scope,
126            created_at
127        ],
128    )
129    .map_err(|e| e.to_string())?;
130    Ok((
131        FeedRecord {
132            id,
133            user_id: user_id.map(str::to_string),
134            name: name.to_string(),
135            kinds: kinds_joined,
136            scope,
137            created_at,
138            last_fetched_at: None,
139            revoked_at: None,
140        },
141        token,
142    ))
143}
144
145/// Feeds visible to the caller: every feed for the owner, only the caller's own
146/// otherwise.
147pub fn list_feeds(
148    conn: &Connection,
149    is_owner: bool,
150    user_id: &str,
151) -> Result<Vec<FeedRecord>, String> {
152    let sql = format!(
153        "SELECT {COLS} FROM ics_feeds {} ORDER BY created_at DESC",
154        if is_owner { "" } else { "WHERE user_id = ?1" }
155    );
156    let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
157    let rows = if is_owner {
158        stmt.query_map([], row_to_record)
159    } else {
160        stmt.query_map(params![user_id], row_to_record)
161    }
162    .map_err(|e| e.to_string())?;
163    rows.collect::<Result<Vec<_>, _>>()
164        .map_err(|e| e.to_string())
165}
166
167/// Revokes a feed. An owner may revoke any feed; a sub-user only their own —
168/// enforced here rather than trusted to the caller, since this is the one
169/// place that decides whether a URL someone thought they killed still works.
170pub fn revoke_feed(
171    conn: &Connection,
172    feed_id: &str,
173    actor_user_id: &str,
174    is_owner: bool,
175) -> Result<bool, String> {
176    let n = if is_owner {
177        conn.execute(
178            "UPDATE ics_feeds SET revoked_at = ?1 WHERE id = ?2 AND revoked_at IS NULL",
179            params![crate::iso_now(), feed_id],
180        )
181    } else {
182        conn.execute(
183            "UPDATE ics_feeds SET revoked_at = ?1 \
184             WHERE id = ?2 AND user_id = ?3 AND revoked_at IS NULL",
185            params![crate::iso_now(), feed_id, actor_user_id],
186        )
187    }
188    .map_err(|e| e.to_string())?;
189    Ok(n > 0)
190}
191
192/// Looks a presented token up by its hash. Revoked feeds are excluded here
193/// rather than filtered by the caller, so a revoked token can never be reached
194/// by forgetting one check site.
195pub fn find_active_feed_by_token(
196    conn: &Connection,
197    raw_token: &str,
198) -> Result<Option<FeedRecord>, String> {
199    let hash = sha256_hex(raw_token);
200    conn.query_row(
201        &format!("SELECT {COLS} FROM ics_feeds WHERE token_hash = ?1 AND revoked_at IS NULL"),
202        params![hash],
203        row_to_record,
204    )
205    .optional()
206    .map_err(|e| e.to_string())
207}
208
209/// Stamps the last-fetch time. Deliberately not an audited write — a calendar
210/// client polling hourly would grow the hash-chained audit log without bound,
211/// the same reason vault reads stopped being audited.
212pub fn touch_feed(conn: &Connection, feed_id: &str) -> Result<(), String> {
213    conn.execute(
214        "UPDATE ics_feeds SET last_fetched_at = ?1 WHERE id = ?2",
215        params![crate::iso_now(), feed_id],
216    )
217    .map(|_| ())
218    .map_err(|e| e.to_string())
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224
225    fn mem() -> Connection {
226        let conn = Connection::open_in_memory().unwrap();
227        init_schema(&conn).unwrap();
228        conn
229    }
230
231    #[test]
232    fn a_revoked_feed_is_not_found_by_its_token() {
233        let conn = mem();
234        let (feed, token) =
235            create_feed(&conn, None, "Everything", &["expires".to_string()], false).unwrap();
236        assert!(find_active_feed_by_token(&conn, &token).unwrap().is_some());
237        assert!(revoke_feed(&conn, &feed.id, "owner", true).unwrap());
238        assert!(find_active_feed_by_token(&conn, &token).unwrap().is_none());
239    }
240
241    #[test]
242    fn a_sub_user_cannot_revoke_someone_elses_feed() {
243        let conn = mem();
244        let (feed, _) = create_feed(
245            &conn,
246            Some("alice"),
247            "Alice's feed",
248            &["expires".to_string()],
249            false,
250        )
251        .unwrap();
252        assert!(!revoke_feed(&conn, &feed.id, "bob", false).unwrap());
253        assert!(revoke_feed(&conn, &feed.id, "alice", false).unwrap());
254    }
255
256    #[test]
257    fn account_names_are_opt_in() {
258        let conn = mem();
259        let (feed, _) = create_feed(&conn, None, "X", &["expires".to_string()], false).unwrap();
260        assert!(!feed.include_account_names());
261        let (feed2, _) = create_feed(&conn, None, "Y", &["expires".to_string()], true).unwrap();
262        assert!(feed2.include_account_names());
263    }
264
265    #[test]
266    fn an_unknown_token_finds_nothing() {
267        let conn = mem();
268        assert!(find_active_feed_by_token(&conn, "not-a-real-token")
269            .unwrap()
270            .is_none());
271    }
272}