~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
341 lines · 12.3 KB Raw History
//! Each account's private preferences: `app.bsky.actor.getPreferences` and
//! `putPreferences`, as `spec/PROXY.md` says.
//!
//! An account's preferences are kept behind a lock of their own, and each
//! `putPreferences` is an entry in `accounts.log` holding the whole list,
//! appended under that lock so that the log has an account's lists in the
//! order they were put; the answer waits, with no lock held, until the
//! entry is on disk.

use crate::proxy::{self, Request};
use crate::sessions::{self, ACCESS, Bearer, Token};
use crate::{Handler, Resp, Service, Shared, XrpcError, durable, internal, invalid, read, write};
use pds_repo::data::{civil_from_days, datetime_millis};
use serde_json::{Map, Value as Json, json};
use std::collections::HashMap;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, RwLock};

/// The kind of `accounts.log` entry that holds an account's preferences.
pub(crate) const ENTRY: &str = "preferences";

const PERSONAL: &str = "app.bsky.actor.defs#personalDetailsPref";
const DECLARED_AGE: &str = "app.bsky.actor.defs#declaredAgePref";

/// Every account's preferences, by DID.
#[derive(Default)]
pub(crate) struct Preferences(RwLock<HashMap<String, Arc<Mutex<Vec<Json>>>>>);

fn lock(k: &Mutex<Vec<Json>>) -> MutexGuard<'_, Vec<Json>> {
    k.lock().unwrap_or_else(PoisonError::into_inner)
}

/// The preferences an entry of the kind `ENTRY` holds.
pub(crate) fn parse(e: &Json) -> Result<Vec<Json>, String> {
    e["preferences"]
        .as_array()
        .filter(|p| p.iter().all(|p| p["$type"].is_string()))
        .cloned()
        .ok_or_else(|| format!("preferences that are not a list of objects with a $type: {e}"))
}

impl Preferences {
    fn keep(&self, did: &str) -> Arc<Mutex<Vec<Json>>> {
        if let Some(k) = read(&self.0).get(did) {
            return k.clone();
        }
        write(&self.0).entry(did.to_string()).or_default().clone()
    }

    /// An account's preferences, as its entries of the service log leave
    /// them: what an account loaded has (`directory`).
    pub fn put(&self, did: &str, prefs: Vec<Json>) {
        write(&self.0).insert(did.to_string(), Arc::new(Mutex::new(prefs)));
    }

    /// Forget a deleted account's preferences, logged with its deletion.
    pub fn forget(&self, did: &str) {
        write(&self.0).remove(did);
    }

    /// Every account's preferences that has any, to compare across restarts.
    #[cfg(test)]
    pub fn snapshot(&self) -> std::collections::BTreeMap<String, Vec<Json>> {
        read(&self.0)
            .iter()
            .map(|(did, k)| (did.clone(), lock(k).clone()))
            .filter(|(_, p)| !p.is_empty())
            .collect()
    }
}

pub(crate) fn handler(nsid: &str) -> Option<Handler> {
    Some(match nsid {
        "app.bsky.actor.getPreferences" => {
            Handler::Proxy(|s, r, _| Box::pin(get_preferences(s, r)))
        }
        "app.bsky.actor.putPreferences" => {
            Handler::Proxy(|s, r, b| Box::pin(put_preferences(s, r, b)))
        }
        _ => return None,
    })
}

fn is(p: &Json, t: &str) -> bool {
    p["$type"] == t
}

/// The age, in whole years in UTC, of one born at `birth` (in milliseconds since the epoch) at `now`.
fn age(birth: i64, now: i64) -> i64 {
    let date = |ms: i64| civil_from_days(ms.div_euclid(86_400_000));
    let ((by, bm, bd), (y, m, d)) = (date(birth), date(now));
    y - by - i64::from((m, d) < (bm, bd))
}

/// The token a method the server serves for the app takes: an access token,
/// and for `getPreferences` a taken-down account's too (`spec/LIFECYCLE.md`).
pub(crate) fn token(s: &Service, nsid: &str, b: Bearer) -> Result<Token, XrpcError> {
    match nsid {
        "app.bsky.actor.getPreferences" => sessions::takendown_ok_token(s, b),
        _ => sessions::access_token(s, b),
    }
}

async fn get_preferences(s: Shared, r: Request) -> Result<Resp, XrpcError> {
    let t = sessions::takendown_ok_token(&s, r.bearer())?;
    if proxy::names_other(&s, r.proxy.as_deref()) {
        let target = proxy::target(&s, r.proxy.as_deref()).await?;
        let got = proxy::forward_query(
            &s,
            &r,
            &target,
            Some((&t.did, &target.did, "app.bsky.actor.getPreferences")),
        )
        .await?;
        return Ok(proxy::answered(got, true));
    }
    let (kept, n) = {
        let keep = s.prefs.keep(&t.did);
        let kept = lock(&keep).clone();
        (kept, s.log.written())
    };
    let full = t.scope == ACCESS;
    let birth = kept
        .iter()
        .find(|p| is(p, PERSONAL))
        .and_then(|p| p["birthDate"].as_str())
        .and_then(datetime_millis);
    let mut out: Vec<Json> = kept
        .into_iter()
        .filter(|p| full || !is(p, PERSONAL))
        .collect();
    if let Some(birth) = birth {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis() as i64;
        let age = age(birth, now);
        out.push(json!({ "$type": DECLARED_AGE, "isOverAge13": age >= 13, "isOverAge16": age >= 16, "isOverAge18": age >= 18 }));
    }
    durable(s.log.clone(), n).await?;
    Ok(Resp::Json(json!({ "preferences": out })))
}

/// `putPreferences`, its token and input checked, its rate limits paid and
/// the free space found enough (`limits::guard`).
async fn put_preferences(
    s: Shared,
    r: Request,
    input: Map<String, Json>,
) -> Result<Resp, XrpcError> {
    let t = sessions::access_token(&s, r.bearer())?;
    // The reference forwards only queries.
    if proxy::names_other(&s, r.proxy.as_deref()) {
        return internal();
    }
    let Some(given) = input.get("preferences").and_then(Json::as_array) else {
        return invalid("Input/preferences must be an array");
    };
    for p in given {
        let t = p["$type"].as_str().unwrap_or_default();
        if !(t == "app.bsky" || t.starts_with("app.bsky.")) {
            return invalid(format!(
                "Some preferences are not in the app.bsky namespace: {t:?}"
            ));
        }
    }
    let full = t.scope == ACCESS;
    if !full && given.iter().any(|p| is(p, PERSONAL)) {
        return invalid("Do not have authorization to set preferences.");
    }
    let Some(a) = s.account(&t.did) else {
        return crate::lifecycle::account_not_found();
    };
    let n = {
        // Held while the put is logged, as a deletion holds it while it is:
        // no put is logged after its account's deletion (`spec/LIFECYCLE.md`).
        let state = read(&a.state);
        if state.deleted {
            return crate::lifecycle::account_not_found();
        }
        let keep = s.prefs.keep(&t.did);
        let mut k = lock(&keep);
        let mut next: Vec<Json> = if full {
            vec![]
        } else {
            k.iter().filter(|p| is(p, PERSONAL)).cloned().collect()
        };
        next.extend(given.iter().filter(|p| !is(p, DECLARED_AGE)).cloned());
        let n = match s
            .log
            .append(&[json!({ "t": ENTRY, "did": t.did, "preferences": next })])
        {
            Ok(n) => n,
            Err(e) => {
                crate::ops::failed("writing accounts.log failed", e);
                return internal();
            }
        };
        *k = next;
        n
    };
    durable(s.log.clone(), n).await?;
    Ok(Resp::Nothing)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::testing::*;

    fn ms(s: &str) -> i64 {
        datetime_millis(s).unwrap()
    }

    #[test]
    fn ages() {
        let now = ms("2026-11-09T12:00:00Z");
        assert_eq!(age(ms("2008-11-09T00:00:00Z"), now), 18);
        assert_eq!(age(ms("2008-11-10T00:00:00Z"), now), 17);
        assert_eq!(age(ms("2013-11-08T00:00:00Z"), now), 13);
        // In UTC: 23:00 at -05:00 is the next day.
        assert_eq!(age(ms("2008-11-09T23:00:00-05:00"), now), 17);
    }

    /// Preferences as the server answers them, by session.
    async fn get(s: &Shared, token: &str) -> Json {
        call(s, "app.bsky.actor.getPreferences", Some(token), Json::Null)
            .await
            .unwrap()["preferences"]
            .clone()
    }

    #[tokio::test]
    async fn put_and_get() {
        let plc = plc().await;
        let dir = scratch("prefs");
        let cfg = || {
            let mut c = config(&plc);
            c.proxy.appview = Some(proxy::AppView {
                url: "http://127.0.0.1:1".into(),
                did: "did:web:appview.test".into(),
            });
            c
        };
        let s = Arc::new(crate::Service::open(&dir, cfg()).unwrap());
        let (did, full) = create(&s, "alice").await;
        let app = call(
            &s,
            "com.atproto.server.createAppPassword",
            Some(&full),
            json!({ "name": "phone" }),
        )
        .await
        .unwrap();
        let login = json!({ "identifier": "alice.test", "password": app["password"] });
        let phone = call(&s, "com.atproto.server.createSession", None, login)
            .await
            .unwrap()["accessJwt"]
            .as_str()
            .unwrap()
            .to_string();
        assert_eq!(get(&s, &full).await, json!([]));
        let put = |token: &str, prefs: Json| {
            let (s, token) = (s.clone(), token.to_string());
            async move {
                call(
                    &s,
                    "app.bsky.actor.putPreferences",
                    Some(&token),
                    json!({ "preferences": prefs, "other": 1 }),
                )
                .await
            }
        };
        let personal = json!({ "$type": PERSONAL, "birthDate": "2000-01-01T00:00:00.000Z" });
        let adult = json!({ "$type": "app.bsky.actor.defs#adultContentPref" });
        let other = json!({ "$type": "app.bsky.x y", "anything": [1] });
        let declared = json!({ "$type": DECLARED_AGE, "isOverAge13": false });
        assert_eq!(
            put(&full, json!([personal, adult, other, declared, adult])).await,
            Ok(Json::Null)
        );
        let age = json!({ "$type": DECLARED_AGE, "isOverAge13": true, "isOverAge16": true, "isOverAge18": true });
        let filled = json!({ "$type": "app.bsky.actor.defs#adultContentPref", "enabled": false });
        assert_eq!(
            get(&s, &full).await,
            json!([personal, filled, other, filled, age])
        );
        // An app password's session sees no personal details, but the age they make.
        assert_eq!(get(&s, &phone).await, json!([filled, other, filled, age]));
        // It cannot write them, and keeps them when it puts the rest.
        assert_eq!(
            put(&phone, json!([personal])).await,
            Err("InvalidRequest".into())
        );
        assert_eq!(put(&phone, json!([other])).await, Ok(Json::Null));
        assert_eq!(get(&s, &full).await, json!([personal, other, age]));
        // Refusals, each leaving the preferences as they were.
        for bad in [
            json!([{ "$type": "com.example.pref" }]),
            json!([{ "$type": "" }]),
            json!([{ "enabled": true }]),
            json!([{ "$type": PERSONAL, "birthDate": "2000-01-01" }]),
            json!([{ "$type": "app.bsky.actor.defs#interestsPref", "tags": ["x".repeat(65)] }]),
            json!({}),
        ] {
            assert_eq!(
                put(&full, bad.clone()).await,
                Err("InvalidRequest".into()),
                "{bad}"
            );
        }
        assert_eq!(
            call(&s, "app.bsky.actor.putPreferences", Some(&full), json!({})).await,
            Err("InvalidRequest".into())
        );
        assert_eq!(
            call(
                &s,
                "app.bsky.actor.putPreferences",
                None,
                json!({ "preferences": [] })
            )
            .await,
            Err("AuthMissing".into())
        );
        assert_eq!(
            call(&s, "app.bsky.actor.getPreferences", None, Json::Null).await,
            Err("AuthMissing".into())
        );
        assert_eq!(get(&s, &full).await, json!([personal, other, age]));
        // Another account's are its own.
        let (_, bob) = create(&s, "bob").await;
        assert_eq!(get(&s, &bob).await, json!([]));
        // They survive a restart.
        drop(s);
        let s = Arc::new(crate::Service::open(&dir, cfg()).unwrap());
        assert_eq!(get(&s, &full).await, json!([personal, other, age]));
        assert_eq!(s.prefs.snapshot().keys().collect::<Vec<_>>(), [&did]);
        let _ = std::fs::remove_dir_all(&dir);
    }
}