Add opt-in pl8list connection with library sync, follows and resync

At sign-in users can choose to stay connected to pl8list on that device.
The pl8list session is then stored in the device's session row, encrypted
with XChaCha20-Poly1305 under a key derived from the device's local token
(only the browser has it) and a server key kept outside the database. It
is only decrypted during that device's own requests, re-encrypted when the
token rotates or pl8list sends a new cookie, and deleted when pl8list
rejects it.

Every sign-in now syncs the personal feed, saved tracks (imported as likes)
and saved artists (imported as follows). Connected devices resync on use
every six hours and push new likes and follows to the pl8list library with
addOnly, so nothing is ever removed there. Without the connection, the
resync button runs the email-code sign-in again.

Artists can be followed from each card (f); follows feed the ranker. The
account menu shows the sync state, resync and disconnect. Privacy policy,
export and account deletion cover the new data.
This commit is contained in:
nvrl committed 2026-11-01 12:36:00 +01:00
1 parent 54a436ae48
commit 27225332fb
22 files changed
+1366 -114

No files matched your search

+42 -2
View File
@@ -1,4 +1,5 @@
//! Data export, account deletion and signing out everywhere (Art. 15, 17, 20 GDPR).
//! Data export, account deletion and signing out everywhere (Art. 15, 17, 20 GDPR),
//! plus the pl8list connection of this device.
use axum::{
Extension, Json,
@@ -8,7 +9,7 @@ use axum::{
};
use serde_json::{Value, json};
use super::{CurrentUser, Res, St, auth::signed_out, json_error};
use super::{CurrentUser, Res, St, auth::signed_out, json_error, no_store};
use crate::db;
pub async fn export(State(app): St, Extension(current): Extension<CurrentUser>) -> Res {
@@ -41,6 +42,11 @@ pub async fn delete(State(app): St, Extension(current): Extension<CurrentUser>,
return Ok(json_error(StatusCode::BAD_REQUEST, "type your handle to confirm"));
}
let uid = user.id;
// Other devices' stored sessions can't be opened without their cookies; deleting
// the rows makes them unusable. This device's one is logged out at pl8list too.
if let Some((_, session)) = app.connected(&current).await {
app.pl8.logout(&session).await;
}
app.db.call(move |c| db::delete_user(c, uid)).await?;
tracing::info!("account deleted");
Ok(signed_out(&app, json!({ "ok": true })))
@@ -51,6 +57,40 @@ pub async fn logout_all(State(app): St, Extension(current): Extension<CurrentUse
Ok(u) => u.id,
Err(r) => return Ok(r),
};
if let Some((_, session)) = app.connected(&current).await {
app.pl8.logout(&session).await;
}
app.db.call(move |c| db::delete_user_sessions(c, uid)).await?;
Ok(signed_out(&app, json!({ "ok": true })))
}
/// The resync button. A connected device syncs with its stored session; any other
/// device has to sign in with pl8list again (409 tells the page to show the sign-in).
pub async fn sync(State(app): St, Extension(current): Extension<CurrentUser>) -> Res {
let uid = match current.require() {
Ok(u) => u.id,
Err(r) => return Ok(r),
};
let Some((sealer, session)) = app.connected(&current).await else {
return Ok(json_error(StatusCode::CONFLICT, "sign in with pl8list again to sync"));
};
if !app.limits.resync.allow(&uid.to_string()) {
return Ok(json_error(StatusCode::TOO_MANY_REQUESTS, "synced a moment ago, try again in two minutes"));
}
let started = app.sync.linked(sealer, session);
Ok((no_store(), Json(json!({ "ok": true, "started": started }))).into_response())
}
/// Stop staying connected on this device: log the session out at pl8list and delete it.
pub async fn disconnect(State(app): St, Extension(current): Extension<CurrentUser>) -> Res {
if let Err(r) = current.require() {
return Ok(r);
}
if let Some((_, session)) = app.connected(&current).await {
app.pl8.logout(&session).await;
}
if let Some(token) = current.token.clone() {
app.db.call(move |c| db::clear_link(c, &db::hash_token(&token))).await?;
}
Ok((no_store(), Json(json!({ "ok": true }))).into_response())
}
+76 -6
View File
@@ -1,4 +1,4 @@
//! The feed, likes and listening events.
//! The feed, likes, follows and listening events.
use std::{collections::HashMap, time::Duration};
@@ -11,8 +11,8 @@ use axum::{
use serde_json::{Value, json};
use tokio::time::Instant;
use super::{CurrentUser, Res, St, json_error, no_store};
use crate::{db, ranker};
use super::{App, CurrentUser, Res, St, json_error, no_store};
use crate::{db, ranker, sync};
const EVENT_KINDS: &[&str] = &["play", "like", "unlike", "skip", "complete", "dislike"];
/// On a cold start the crawler needs a few seconds before there is anything to serve.
@@ -20,11 +20,38 @@ const FEED_WAIT: Duration = Duration::from_secs(10);
pub async fn me(Extension(current): Extension<CurrentUser>) -> Response {
match current.user {
Some(u) => (no_store(), Json(json!({ "user": { "handle": u.handle, "name": u.name, "img": u.img } }))).into_response(),
Some(u) => (
no_store(),
Json(json!({
"user": { "handle": u.handle, "name": u.name, "img": u.img },
"pl8list": { "connected": current.link.is_some(), "synced_at": current.synced_at },
})),
)
.into_response(),
None => json_error(StatusCode::UNAUTHORIZED, "not signed in"),
}
}
/// Mark tracks by artists the user follows.
async fn mark_followed(app: &App, uid: i64, tracks: &mut [Value]) -> anyhow::Result<()> {
let follows = app.db.call(move |c| db::follows(c, uid)).await?;
for t in tracks {
let followed = t["handle"].as_str().is_some_and(|h| follows.contains(h));
t["followed"] = json!(followed);
}
Ok(())
}
/// A connected device resyncs in the background once its last sync is old enough.
async fn resync_if_due(app: &App, current: &CurrentUser) {
if current.link.is_none() || current.synced_at.is_some_and(|t| t > db::now() - sync::RESYNC_AFTER) {
return;
}
if let Some((sealer, session)) = app.connected(current).await {
app.sync.linked(sealer, session);
}
}
fn num(q: &HashMap<String, String>, name: &str) -> Option<f64> {
q.get(name).and_then(|v| v.parse::<f64>().ok()).filter(|v| v.is_finite())
}
@@ -43,15 +70,17 @@ pub async fn feed(State(app): St, Extension(current): Extension<CurrentUser>, Qu
bpm_min: num(&q, "bpm_min"),
bpm_max: num(&q, "bpm_max"),
};
resync_if_due(&app, &current).await;
let deadline = Instant::now() + FEED_WAIT;
let uid = user.id;
let tracks = loop {
let mut tracks = loop {
let tracks = app.db.call(move |c| ranker::pick(c, uid, n, filters, ranker)).await?;
if !tracks.is_empty() || Instant::now() >= deadline {
break tracks;
}
tokio::time::sleep(Duration::from_millis(1500)).await;
};
mark_followed(&app, uid, &mut tracks).await?;
let ids: Vec<i64> = tracks.iter().filter_map(|t| t["id"].as_i64()).collect();
let stats = app
.db
@@ -72,7 +101,8 @@ pub async fn likes(State(app): St, Extension(current): Extension<CurrentUser>) -
Ok(u) => u.id,
Err(r) => return Ok(r),
};
let tracks = app.db.call(move |c| ranker::likes(c, uid)).await?;
let mut tracks = app.db.call(move |c| ranker::likes(c, uid)).await?;
mark_followed(&app, uid, &mut tracks).await?;
Ok((no_store(), Json(json!({ "tracks": tracks }))).into_response())
}
@@ -99,5 +129,45 @@ pub async fn event(State(app): St, Extension(current): Extension<CurrentUser>, J
if kind == "like" || kind == "complete" {
app.crawler.on_positive(track_id).await;
}
if kind == "like" && app.limits.pl8_writes.allow(&uid.to_string()) {
let row = app.db.call(move |c| db::track_path(c, track_id)).await?;
if let (Some((handle, slug)), Some((sealer, session))) = (row, app.connected(&current).await) {
app.sync.push_like(sealer, session, handle, slug);
}
}
Ok((no_store(), Json(json!({ "ok": true }))).into_response())
}
/// Valid pl8list handles, as seen in every handle crawled so far.
fn valid_handle(h: &str) -> bool {
(1..=64).contains(&h.len()) && h.bytes().all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b)) && h != "." && h != ".."
}
/// Follow or unfollow an artist. Unfollowing only affects this app; on a connected
/// device a follow is also saved to the user's pl8list library.
pub async fn follow(State(app): St, Extension(current): Extension<CurrentUser>, Json(body): Json<Value>) -> Res {
let uid = match current.require() {
Ok(u) => u.id,
Err(r) => return Ok(r),
};
let handle = body.get("handle").and_then(Value::as_str).filter(|h| valid_handle(h)).map(String::from);
let on = body.get("follow").and_then(Value::as_bool);
let (Some(handle), Some(on)) = (handle, on) else {
return Ok(StatusCode::BAD_REQUEST.into_response());
};
if !app.limits.events.allow(&uid.to_string()) {
return Ok(StatusCode::TOO_MANY_REQUESTS.into_response());
}
let h = handle.clone();
let added = app
.db
.call(move |c| if on { db::add_follows(c, uid, &[h], "local") } else { db::unfollow(c, uid, &h).map(|_| 0) })
.await?;
if added > 0 {
app.crawler.discovered_artists([handle.clone()]);
if app.limits.pl8_writes.allow(&uid.to_string()) && let Some((sealer, session)) = app.connected(&current).await {
app.sync.push_follow(sealer, session, handle);
}
}
Ok((no_store(), Json(json!({ "ok": true, "followed": on }))).into_response())
}
+26 -5
View File
@@ -135,7 +135,7 @@ pub async fn resend(State(app): St, peer: Peer, headers: HeaderMap) -> Res {
Ok((no_store(), Json(json!({ "ok": true }))).into_response())
}
pub async fn verify(State(app): St, headers: HeaderMap, Json(body): Json<Value>) -> Res {
pub async fn verify(State(app): St, Extension(current): Extension<CurrentUser>, headers: HeaderMap, Json(body): Json<Value>) -> Res {
let id = login_cookie(&app, &headers).map(String::from);
let Some(pending) = app.logins.get(id.as_deref()) else { return Ok(expired()) };
let id = id.unwrap_or_default();
@@ -153,18 +153,36 @@ pub async fn verify(State(app): St, headers: HeaderMap, Json(body): Json<Value>)
Err(e) => return Ok(json_error(StatusCode::BAD_REQUEST, &e.0)),
};
app.logins.drop(&id);
// The pl8list session goes straight to the feed crawl, which logs it out afterwards.
app.crawler.crawl_feed(pl8_session);
// "Stay connected" is opt-in per device; without it the session is used for one
// sync and then logged out at pl8list.
let stay = body.get("connect").and_then(Value::as_bool) == Some(true);
let u = user.clone();
// Signing in again on a device (the resync button) replaces its old session.
let previous = current.token.clone();
if let Some(old) = app.connected(&current).await {
app.pl8.logout(&old.1).await;
}
let token = app
.db
.call(move |c| {
if let Some(t) = previous {
db::delete_session(c, &t)?;
}
db::upsert_user(c, u.id, &u.handle, u.name.as_deref(), u.img.as_deref())?;
db::create_session(c, u.id)
})
.await?;
tracing::info!("signed in: {}", user.handle);
let mut res = (no_store(), Json(json!({ "user": { "handle": user.handle, "name": user.name } }))).into_response();
if stay {
let sealer = app.sync.key.sealer(&token, user.id);
let blob = sealer.seal(&pl8_session);
let hash = sealer.token_hash.clone();
app.db.call(move |c| db::set_link(c, &hash, &blob, Some(db::now()))).await?;
app.sync.linked(sealer, pl8_session);
} else {
app.sync.once(user.id, pl8_session);
}
tracing::info!("signed in: {}{}", user.handle, if stay { " (stays connected)" } else { "" });
let mut res = (no_store(), Json(json!({ "user": { "handle": user.handle, "name": user.name }, "connected": stay }))).into_response();
let h = res.headers_mut();
h.append(header::SET_COOKIE, app.cookies.set(SESSION_COOKIE, &token, (db::SESSION_IDLE_DAYS * 86400.0) as i64));
h.append(header::SET_COOKIE, app.cookies.clear(LOGIN_COOKIE));
@@ -172,6 +190,9 @@ pub async fn verify(State(app): St, headers: HeaderMap, Json(body): Json<Value>)
}
pub async fn logout(State(app): St, Extension(current): Extension<CurrentUser>) -> Res {
if let Some((_, session)) = app.connected(&current).await {
app.pl8.logout(&session).await;
}
if let Some(token) = current.token {
app.db.call(move |c| db::delete_session(c, &token)).await?;
}
+64 -3
View File
@@ -24,13 +24,17 @@ use serde_json::json;
use tower::limit::GlobalConcurrencyLimitLayer;
use tower_http::timeout::TimeoutLayer;
use secrecy::SecretString;
use crate::{
cache::Cache,
config::Config,
crawler::Crawler,
db::{self, Db, User},
link::{LinkKey, Sealer},
pl8::Pl8,
ratelimit::RateLimiter,
sync::Syncer,
};
use security::Cookies;
@@ -46,6 +50,10 @@ pub struct Limits {
pub login_global: RateLimiter,
pub events: RateLimiter,
pub proxy: RateLimiter,
/// Saves to a user's pl8list library (likes and follows pushed from here).
pub pl8_writes: RateLimiter,
/// The resync button.
pub resync: RateLimiter,
}
pub struct App {
@@ -53,6 +61,7 @@ pub struct App {
pub db: Db,
pub pl8: Arc<Pl8>,
pub crawler: Arc<Crawler>,
pub sync: Arc<Syncer>,
pub cache: Cache,
pub logins: auth::PendingLogins,
pub limits: Limits,
@@ -64,8 +73,9 @@ pub struct App {
pub type St = State<Arc<App>>;
impl App {
pub fn new(cfg: Config, db: Db, pl8: Arc<Pl8>, crawler: Arc<Crawler>) -> Arc<Self> {
pub fn new(cfg: Config, db: Db, pl8: Arc<Pl8>, crawler: Arc<Crawler>, link: LinkKey) -> Arc<Self> {
let cache = Cache::open(cfg.cache_dir.clone(), cfg.cache_max_bytes);
let sync = Syncer::new(pl8.clone(), db.clone(), crawler.clone(), link);
let legal = legal::Pages::render(&cfg.legal);
Arc::new(App {
cookies: Cookies { secure: cfg.secure },
@@ -75,9 +85,12 @@ impl App {
login_global: RateLimiter::new(30, 600),
events: RateLimiter::new(600, 600),
proxy: RateLimiter::new(1200, 60),
pl8_writes: RateLimiter::new(60, 600),
resync: RateLimiter::new(1, 120),
},
logins: auth::PendingLogins::default(),
segments: proxy::SegmentKeys::default(),
sync,
cache,
legal,
cfg,
@@ -97,6 +110,21 @@ impl App {
self.logins.prune();
self.segments.prune();
}
/// This device's stored pl8list session, if it stays connected. A blob that no
/// longer opens (for example after the server key changed) is dropped.
pub async fn connected(&self, current: &CurrentUser) -> Option<(Sealer, SecretString)> {
let (Some(user), Some(token), Some(blob)) = (&current.user, &current.token, &current.link) else { return None };
let sealer = self.sync.key.sealer(token, user.id);
match sealer.open(blob) {
Some(session) => Some((sealer, session)),
None => {
let hash = sealer.token_hash.clone();
let _ = self.db.call(move |c| db::clear_link(c, &hash)).await;
None
}
}
}
}
// Errors ------------------------------------------------------------------
@@ -133,6 +161,9 @@ pub fn no_store() -> [(header::HeaderName, &'static str); 1] {
pub struct CurrentUser {
pub user: Option<User>,
pub token: Option<String>,
/// Encrypted pl8list session of this device (see `link.rs`).
pub link: Option<Vec<u8>>,
pub synced_at: Option<f64>,
}
impl CurrentUser {
@@ -152,14 +183,41 @@ async fn session(State(app): St, mut req: Request, next: Next) -> Response {
None => (None, false),
};
let mut set_cookie: Vec<HeaderValue> = vec![];
let mut current = CurrentUser { user: None, token: token.clone() };
let mut current = CurrentUser { user: None, token: token.clone(), link: None, synced_at: None };
if let Some(t) = token {
let lookup = t.clone();
if let Ok(Some(hit)) = app.db.call(move |c| db::session_user(c, &lookup)).await {
let mut new_token = None;
current.link = hit.link.clone();
current.synced_at = hit.synced_at;
if hit.created_at < db::now() - ROTATE_AFTER {
let (old, uid) = (t.clone(), hit.user.id);
new_token = app.db.call(move |c| db::rotate_session(c, &old, uid)).await.ok();
// The stored pl8list session is encrypted for the old token; move it over.
let reopened = hit.link.as_deref().and_then(|b| app.sync.key.sealer(&t, uid).open(b));
let key = &app.sync.key;
let synced = hit.synced_at;
new_token = match app.db.call(move |c| db::rotate_session(c, &old, uid)).await {
Ok(nt) => {
if let Some(session) = reopened {
let new = key.sealer(&nt, uid);
let blob = new.seal(&session);
let old_hash = db::hash_token(&t);
let stored = blob.clone();
let _ = app
.db
.call(move |c| {
db::set_link(c, &new.token_hash, &stored, synced)?;
db::clear_link(c, &old_hash)
})
.await;
current.link = Some(blob);
} else {
current.link = None;
}
Some(nt)
}
Err(_) => None,
};
} else if legacy {
new_token = Some(t.clone());
}
@@ -256,9 +314,12 @@ pub fn router(app: Arc<App>) -> Router {
.route("/local/feed", get(app::feed))
.route("/local/likes", get(app::likes))
.route("/local/event", post(app::event))
.route("/local/follow", post(app::follow))
.route("/account/export", get(account::export))
.route("/account/delete", post(account::delete))
.route("/account/logout-all", post(account::logout_all))
.route("/account/pl8list/sync", post(account::sync))
.route("/account/pl8list/disconnect", post(account::disconnect))
.route("/api/{handle}/{slug}/hls/playlist.m3u8", get(proxy::playlist))
.route("/api/{handle}/{slug}/hls/segment/{n}", get(proxy::segment))
.route("/img/{id}", get(proxy::image))
+160 -2
View File
@@ -16,7 +16,7 @@ use wiremock::{
};
use super::{App, router};
use crate::{config::{Config, Legal}, crawler::Crawler, db::Db, pl8::Pl8};
use crate::{config::{Config, Legal}, crawler::Crawler, db::Db, link::LinkKey, pl8::Pl8};
const LOGGED_IN: &str = "LOGGED-IN-PL8-SESSION-SECRET";
@@ -38,13 +38,15 @@ async fn setup(name: &str, pl8_base: &str) -> (Router, Arc<App>, PathBuf) {
secure: true,
cache_dir: db_path.parent().unwrap().join("cache"),
cache_max_bytes: 1 << 20,
link_key: None,
link_key_file: db_path.parent().unwrap().join("link.key"),
pl8_base: pl8_base.into(),
legal: Legal::default(),
};
let db = Db::open(&db_path).unwrap();
let pl8 = Arc::new(Pl8::new(pl8_base, Duration::ZERO).unwrap());
let crawler = Crawler::new(pl8.clone(), db.clone());
let app = App::new(cfg, db, pl8, crawler);
let app = App::new(cfg, db, pl8, crawler, LinkKey::fixed(9));
(router(app.clone()), app, db_path)
}
@@ -222,3 +224,159 @@ async fn legacy_cookie_moves_to_host_prefix() {
assert!(cookies.iter().any(|c| c.starts_with(&format!("__Host-pl8inf={token};"))));
assert!(cookies.iter().any(|c| c.starts_with("pl8inf=;") && c.contains("Max-Age=0")));
}
async fn wait_for(pl8: &MockServer, what: impl Fn(&wiremock::Request) -> bool) -> bool {
for _ in 0..50 {
if pl8.received_requests().await.unwrap().iter().any(&what) {
return true;
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
false
}
async fn sign_in(r: &Router, body: &str) -> (String, serde_json::Value) {
let res = r.clone().oneshot(req("POST", "/auth/start", Some(r#"{"email":"a@b.de"}"#), None, "203.0.113.9")).await.unwrap();
let login = cookie_pair(&set_cookies(&res), "__Host-pl8inf_login");
let res = r.clone().oneshot(req("POST", "/auth/verify", Some(body), Some(&login), "203.0.113.9")).await.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let session = cookie_pair(&set_cookies(&res), "__Host-pl8inf");
let bytes = axum::body::to_bytes(res.into_body(), 1 << 16).await.unwrap();
(session, serde_json::from_slice(&bytes).unwrap())
}
async fn json_body(res: axum::response::Response) -> serde_json::Value {
serde_json::from_slice(&axum::body::to_bytes(res.into_body(), 1 << 20).await.unwrap()).unwrap()
}
const REFRESHED: &str = "REFRESHED-PL8-SESSION-SECRET";
#[tokio::test]
async fn connected_device_syncs_library_and_pushes_likes_and_follows() {
use wiremock::matchers::path_regex;
let pl8 = fake_pl8list(0).await;
// pl8list hands out a new cookie with the feed; later calls must use it.
Mock::given(method("GET")).and(path("/api/feed"))
.respond_with(ResponseTemplate::new(200).set_body_string(r#"{"tracks":[],"totalPages":1}"#)
.insert_header("set-cookie", format!("_session={REFRESHED}; Max-Age=7776000; Path=/").as_str()))
.with_priority(1)
.mount(&pl8).await;
Mock::given(method("GET")).and(path("/library/tracks")).and(query_param("_data", "routes/library.tracks"))
.respond_with(ResponseTemplate::new(200).set_body_string(
r#"{"items":[{"track":{"id":77,"slug":"song","title":"Song","user":{"handle":"artist1"}}}],"totalPages":1}"#))
.mount(&pl8).await;
Mock::given(method("GET")).and(path("/library/artists")).and(query_param("_data", "routes/library.artists"))
.respond_with(ResponseTemplate::new(200).set_body_string(r#"{"items":[{"handle":"artist2"}],"totalPages":1}"#))
.mount(&pl8).await;
Mock::given(method("POST")).and(path_regex(r"^/api/.+/add-to-library$")).and(query_param("addOnly", "true"))
.and(has_header("cookie", format!("_session={REFRESHED}").as_str()))
.respond_with(ResponseTemplate::new(200).set_body_string(r#"{"success":true,"wasInLibrary":false}"#))
.expect(2)
.mount(&pl8).await;
Mock::given(method("GET")).and(path("/logout"))
.and(has_header("cookie", format!("_session={REFRESHED}").as_str()))
.respond_with(ResponseTemplate::new(204))
.expect(1)
.mount(&pl8).await;
let (r, app, db_path) = setup("connected", &pl8.uri()).await;
let (session, body) = sign_in(&r, r#"{"code":"123456","connect":true}"#).await;
assert_eq!(body["connected"], true);
assert!(wait_for(&pl8, |q| q.url.path() == "/library/artists").await, "library not synced");
tokio::time::sleep(Duration::from_millis(200)).await;
let me = json_body(r.clone().oneshot(req("GET", "/local/me", None, Some(&session), "203.0.113.9")).await.unwrap()).await;
assert_eq!(me["pl8list"]["connected"], true);
// Saved tracks became likes, saved artists follows.
let likes = json_body(r.clone().oneshot(req("GET", "/local/likes", None, Some(&session), "203.0.113.9")).await.unwrap()).await;
assert_eq!(likes["tracks"][0]["id"], 77);
let follows = app.db.call(|c| crate::db::follows(c, 42)).await.unwrap();
assert!(follows.contains("artist2"));
// The stored session is encrypted: neither cookie appears in the files.
let raw = [std::fs::read(&db_path).unwrap(), std::fs::read(db_path.with_extension("db-wal")).unwrap_or_default()].concat();
for secret in [LOGGED_IN, REFRESHED] {
assert!(!raw.windows(secret.len()).any(|w| w == secret.as_bytes()), "{secret} stored in plain text");
}
let res = r.clone().oneshot(req("POST", "/local/event", Some(r#"{"track_id":77,"kind":"like"}"#), Some(&session), "203.0.113.9")).await.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let res = r.clone().oneshot(req("POST", "/local/follow", Some(r#"{"handle":"artist3","follow":true}"#), Some(&session), "203.0.113.9")).await.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert!(wait_for(&pl8, |q| q.url.path() == "/api/artist1/song/add-to-library").await);
assert!(wait_for(&pl8, |q| q.url.path() == "/api/artist3/add-to-library").await);
// Resync works once, then is rate limited.
let res = r.clone().oneshot(req("POST", "/account/pl8list/sync", Some("{}"), Some(&session), "203.0.113.9")).await.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let res = r.clone().oneshot(req("POST", "/account/pl8list/sync", Some("{}"), Some(&session), "203.0.113.9")).await.unwrap();
assert_eq!(res.status(), StatusCode::TOO_MANY_REQUESTS);
tokio::time::sleep(Duration::from_millis(300)).await;
let res = r.clone().oneshot(req("POST", "/account/pl8list/disconnect", Some("{}"), Some(&session), "203.0.113.9")).await.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let me = json_body(r.clone().oneshot(req("GET", "/local/me", None, Some(&session), "203.0.113.9")).await.unwrap()).await;
assert_eq!(me["pl8list"]["connected"], false);
let res = r.clone().oneshot(req("POST", "/account/pl8list/sync", Some("{}"), Some(&session), "203.0.113.9")).await.unwrap();
assert_eq!(res.status(), StatusCode::CONFLICT);
pl8.verify().await;
}
#[tokio::test]
async fn expired_pl8list_session_disconnects_the_device() {
let pl8 = fake_pl8list(0).await;
Mock::given(method("GET")).and(path("/api/feed"))
.respond_with(ResponseTemplate::new(302).insert_header("location", "/login?continue=%2Fapi%2Ffeed"))
.with_priority(1)
.mount(&pl8).await;
let (r, _app, _) = setup("expired", &pl8.uri()).await;
let (session, _) = sign_in(&r, r#"{"code":"123456","connect":true}"#).await;
let mut connected = true;
for _ in 0..50 {
let me = json_body(r.clone().oneshot(req("GET", "/local/me", None, Some(&session), "203.0.113.9")).await.unwrap()).await;
connected = me["pl8list"]["connected"].as_bool().unwrap();
if !connected {
break;
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
assert!(!connected, "expired session still stored");
}
#[tokio::test]
async fn token_rotation_keeps_the_pl8list_connection() {
let (r, app, _) = setup("rotate", "http://127.0.0.1:9").await;
let token = app
.db
.call(|c| {
crate::db::upsert_user(c, 5, "tester", None, None)?;
crate::db::create_session(c, 5)
})
.await
.unwrap();
let blob = app.sync.key.sealer(&token, 5).seal(&secrecy::SecretString::from("PL8".to_string()));
let hash = crate::db::hash_token(&token);
app.db
.call(move |c| {
crate::db::set_link(c, &hash, &blob, Some(crate::db::now()))?;
c.execute("UPDATE sessions SET created_at = created_at - 8 * 86400", [])
})
.await
.unwrap();
let res = r.oneshot(req("GET", "/local/me", None, Some(&format!("__Host-pl8inf={token}")), "203.0.113.1")).await.unwrap();
let new = cookie_pair(&set_cookies(&res), "__Host-pl8inf").trim_start_matches("__Host-pl8inf=").to_string();
assert_ne!(new, token);
assert_eq!(json_body(res).await["pl8list"]["connected"], true);
let (new_hash, old_hash) = (crate::db::hash_token(&new), crate::db::hash_token(&token));
let (new_blob, old_blob) = app
.db
.call(move |c| {
let get = |h: &str| c.query_row("SELECT pl8_link FROM sessions WHERE token_hash=?", [h], |r| r.get::<_, Option<Vec<u8>>>(0));
Ok((get(&new_hash)?, get(&old_hash)?))
})
.await
.unwrap();
use secrecy::ExposeSecret;
assert_eq!(app.sync.key.sealer(&new, 5).open(&new_blob.unwrap()).unwrap().expose_secret(), "PL8");
assert!(old_blob.is_none());
}