22.9 KiB · text History 3d71adc
//! Live-database tests for `/api/v1`, driven through the real router
//! (party-slut's `tests/api_db.rs`).
//!
//! These go through HTTP rather than calling handlers, because what's worth
//! trusting is at that level: that a missing or revoked token is a JSON 401
//! and not a redirect, that nothing hidden from a viewer on the web leaks
//! through the API, that an unverified account can read but not write.
//!
//! Skipped unless `TEST_DATABASE_URL` is set (`just test-db`). They share one
//! database, so every name they create is unique per run.
use std::sync::Arc;

use axum::body::Body;
use axum::http::{Request, StatusCode};
use axum::Router;
use chrono::Utc;
use migration::MigratorTrait;
use sea_orm::*;
use serde_json::{json, Value};
use tower::ServiceExt;
use uuid::Uuid;

use recourse::auth;
use recourse::entities::{bookmarks, categories, notifications, posts, topic_reads, topics, users};
use recourse::{api, AppState, Config};

static MIGRATED: tokio::sync::OnceCell<()> = tokio::sync::OnceCell::const_new();

struct TestApp {
    router: Router,
    state: AppState,
}

async fn app() -> Option<TestApp> {
    app_with(|_| {}).await
}

async fn app_with(tweak: impl FnOnce(&mut Config)) -> Option<TestApp> {
    let url = std::env::var("TEST_DATABASE_URL").ok()?;
    let db = Database::connect(&url).await.expect("connect to TEST_DATABASE_URL");
    MIGRATED
        .get_or_init(|| async {
            migration::Migrator::up(&db, None).await.expect("migrate");
        })
        .await;
    let mut config = Config::from_env();
    config.database_url = url;
    config.require_email_verification = true;
    config.mail_prism_url = None;
    config.mail_prism_api_key = None;
    tweak(&mut config);
    let config = Arc::new(config);
    let db = Arc::new(db);
    let state = AppState {
        env: minijinja::Environment::new(),
        db: db.clone(),
        config: config.clone(),
        view_throttle: recourse::new_view_throttle(),
        mailer: recourse::mailer::build(&config, false),
    };
    let router = Router::new().nest("/api/v1", api::router(db)).with_state(state.clone());
    Some(TestApp { router, state })
}

fn tag() -> String {
    Uuid::now_v7().simple().to_string()[20..].to_string()
}

impl TestApp {
    fn db(&self) -> &DatabaseConnection {
        self.state.db.as_ref()
    }

    async fn call(&self, method: &str, path: &str, token: Option<&str>, body: Option<Value>) -> (StatusCode, Value) {
        let mut request = Request::builder().method(method).uri(format!("/api/v1{path}"));
        if let Some(token) = token {
            request = request.header("authorization", format!("Bearer {token}"));
        }
        let request = match body {
            Some(body) => request.header("content-type", "application/json").body(Body::from(body.to_string())),
            None => request.body(Body::empty()),
        }
        .unwrap();
        let response = self.router.clone().oneshot(request).await.unwrap();
        let status = response.status();
        let bytes = axum::body::to_bytes(response.into_body(), 1 << 22).await.unwrap();
        let json = if bytes.is_empty() {
            Value::Null
        } else {
            serde_json::from_slice(&bytes).unwrap_or_else(|_| panic!("not JSON: {}", String::from_utf8_lossy(&bytes)))
        };
        (status, json)
    }

    async fn get(&self, path: &str, token: &str) -> (StatusCode, Value) {
        self.call("GET", path, Some(token), None).await
    }

    async fn user(&self, name: &str, trust: i32, staff: bool, verified: bool) -> users::Model {
        let name = format!("{name}-{}", tag());
        let u = auth::create_user_direct(self.db(), &name, &format!("{name}@example.test"), "pw-not-used-123", staff)
            .await
            .unwrap();
        let mut am: users::ActiveModel = u.into();
        am.trust_level = Set(trust);
        if !verified {
            am.email_verified_at = Set(None);
        }
        am.update(self.db()).await.unwrap()
    }

    async fn token(&self, user: &users::Model) -> String {
        auth::create_api_token(self.db(), user.id, Some("test".into()), None).await.unwrap().1
    }

    async fn category(&self, name: &str, min_trust: Option<i32>) -> categories::Model {
        let slug = format!("{}-{}", name.to_lowercase(), tag());
        let now = Utc::now();
        categories::ActiveModel {
            id: Set(Uuid::now_v7()),
            name: Set(name.to_string()),
            slug: Set(slug),
            description: Set(None),
            color: Set("#7c3aed".into()),
            position: Set(0),
            parent_id: Set(None),
            min_trust_level: Set(min_trust),
            topic_min_trust: Set(None),
            reply_min_trust: Set(None),
            created_at: Set(now.into()),
            updated_at: Set(now.into()),
        }
        .insert(self.db())
        .await
        .unwrap()
    }

    /// A topic by `author` (who must be able to see the category).
    async fn topic(&self, author: &users::Model, category: &categories::Model, title: &str, tags: &str) -> topics::Model {
        recourse::actions::create_topic(&self.state, author, &category.slug, title, "Opening post body.", tags)
            .await
            .unwrap()
    }

    async fn first_post(&self, topic: &topics::Model) -> posts::Model {
        posts::Entity::find()
            .filter(posts::Column::TopicId.eq(topic.id))
            .filter(posts::Column::PostNumber.eq(1))
            .one(self.db())
            .await
            .unwrap()
            .unwrap()
    }
}

fn error_code(body: &Value) -> &str {
    body["error"]["code"].as_str().unwrap_or_else(|| panic!("no error envelope: {body}"))
}

#[tokio::test]
async fn a_request_without_a_valid_token_is_a_json_401() {
    let Some(app) = app().await else { return };
    let (status, body) = app.call("GET", "/me", None, None).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
    assert_eq!(error_code(&body), "unauthorized");

    let (status, body) = app.call("GET", "/me", Some("recourse_nope"), None).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
    assert_eq!(error_code(&body), "unauthorized");

    // A session cookie is not a credential for the API.
    let user = app.user("cookie", 1, false, true).await;
    let session = auth::create_session(app.db(), user.id, 1).await.unwrap();
    let request = Request::builder()
        .uri("/api/v1/me")
        .header("cookie", format!("session_token={}", session.session_token))
        .body(Body::empty())
        .unwrap();
    let response = app.router.clone().oneshot(request).await.unwrap();
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);

    // Unknown paths answer in the envelope too.
    let token = app.token(&user).await;
    let (status, body) = app.get("/nope", &token).await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert_eq!(error_code(&body), "not_found");
}

#[tokio::test]
async fn a_revoked_or_expired_token_stops_working() {
    let Some(app) = app().await else { return };
    let user = app.user("revoke", 1, false, true).await;
    let phone = app.token(&user).await;
    let laptop = app.token(&user).await;
    assert_eq!(app.get("/me", &phone).await.0, StatusCode::OK);

    // Only the hash is stored.
    let rows = auth::list_api_tokens(app.db(), user.id).await.unwrap();
    assert_eq!(rows.len(), 2);
    let mut stored: Vec<String> = rows.into_iter().map(|r| r.token_hash).collect();
    let mut expected = vec![auth::hash_api_token(&phone), auth::hash_api_token(&laptop)];
    stored.sort();
    expected.sort();
    assert_eq!(stored, expected);

    // Revoke the phone from the laptop: the phone's next request is a 401.
    let (_, devices) = app.get("/me/devices", &laptop).await;
    let list = devices["devices"].as_array().unwrap();
    assert_eq!(list.iter().filter(|d| d["current"] == json!(true)).count(), 1);
    let phone_id = list.iter().find(|d| d["current"] == json!(false)).unwrap()["id"].as_str().unwrap().to_string();
    let (status, _) = app.call("DELETE", &format!("/me/devices/{phone_id}"), Some(&laptop), None).await;
    assert_eq!(status, StatusCode::NO_CONTENT);
    let (status, body) = app.get("/me", &phone).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
    assert_eq!(error_code(&body), "unauthorized");

    // Signing out on a device revokes that device's own token.
    assert_eq!(app.call("DELETE", "/sessions/current", Some(&laptop), None).await.0, StatusCode::NO_CONTENT);
    assert_eq!(app.get("/me", &laptop).await.0, StatusCode::UNAUTHORIZED);

    // An expired token is a 401, and a deactivated account's tokens are too.
    let late = app.token(&user).await;
    let row = auth::list_api_tokens(app.db(), user.id).await.unwrap().remove(0);
    let mut am: recourse::entities::api_tokens::ActiveModel = row.into();
    am.expires_at = Set(Some((Utc::now() - chrono::Duration::days(1)).into()));
    am.update(app.db()).await.unwrap();
    assert_eq!(app.get("/me", &late).await.0, StatusCode::UNAUTHORIZED);

    let other = app.token(&user).await;
    auth::deactivate_user(app.db(), user.id).await.unwrap();
    assert_eq!(app.get("/me", &other).await.0, StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn using_a_token_slides_its_expiry() {
    let Some(app) = app().await else { return };
    let user = app.user("slide", 1, false, true).await;
    let token = app.token(&user).await;
    let row = auth::list_api_tokens(app.db(), user.id).await.unwrap().remove(0);
    let mut am: recourse::entities::api_tokens::ActiveModel = row.into();
    am.expires_at = Set(Some((Utc::now() + chrono::Duration::days(2)).into()));
    am.last_used_at = Set(Some((Utc::now() - chrono::Duration::days(3)).into()));
    am.update(app.db()).await.unwrap();

    assert_eq!(app.get("/me", &token).await.0, StatusCode::OK);
    let row = auth::list_api_tokens(app.db(), user.id).await.unwrap().remove(0);
    let left = row.expires_at.unwrap().with_timezone(&Utc) - Utc::now();
    assert!(left > chrono::Duration::days(89), "expiry slid to 90 days, got {left}");
}

/// Everything a min-trust category hides on the web is hidden through the
/// API: the category, its topics, a tag used only there, a search hit, a
/// bookmark and a notification from before the user lost access, and every
/// write aimed at it.
#[tokio::test]
async fn nothing_hidden_on_the_web_leaks_through_the_api() {
    let Some(app) = app().await else { return };
    let staff = app.user("staff", 4, true, true).await;
    let member = app.user("member", 1, false, true).await;
    let token = app.token(&member).await;

    let open = app.category("Open", None).await;
    let secret = app.category("Regulars", Some(3)).await;
    let marker = format!("zebra{}", tag());
    let hidden_tag = format!("hush{}", tag());
    let visible = app.topic(&staff, &open, &format!("Visible {marker}"), "").await;
    let hidden = app.topic(&staff, &secret, &format!("Hidden {marker}"), &hidden_tag).await;
    let hidden_post = app.first_post(&hidden).await;

    // Left over from when the member could see it.
    bookmarks::ActiveModel {
        id: Set(Uuid::now_v7()),
        user_id: Set(member.id),
        post_id: Set(hidden_post.id),
        created_at: Set(Utc::now().into()),
    }
    .insert(app.db())
    .await
    .unwrap();
    notifications::ActiveModel {
        id: Set(Uuid::now_v7()),
        user_id: Set(member.id),
        kind: Set("new_topic".into()),
        actor_id: Set(Some(staff.id)),
        topic_id: Set(Some(hidden.id)),
        post_id: Set(None),
        is_read: Set(false),
        created_at: Set(Utc::now().into()),
    }
    .insert(app.db())
    .await
    .unwrap();

    let (status, body) = app.get("/categories", &token).await;
    assert_eq!(status, StatusCode::OK);
    let slugs: Vec<&str> = body["categories"].as_array().unwrap().iter().map(|c| c["slug"].as_str().unwrap()).collect();
    assert!(slugs.contains(&open.slug.as_str()));
    assert!(!slugs.contains(&secret.slug.as_str()));

    assert_eq!(app.get(&format!("/categories/{}", secret.slug), &token).await.0, StatusCode::NOT_FOUND);
    let (status, body) = app.get(&format!("/topics/{}", hidden.id), &token).await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert_eq!(error_code(&body), "not_found");

    let (_, body) = app.get("/tags", &token).await;
    assert!(!body.to_string().contains(&hidden_tag));
    assert_eq!(app.get(&format!("/tags/{hidden_tag}"), &token).await.0, StatusCode::NOT_FOUND);

    let (_, body) = app.get(&format!("/search?q={marker}"), &token).await;
    let ids: Vec<&str> = body["topics"].as_array().unwrap().iter().map(|t| t["id"].as_str().unwrap()).collect();
    assert_eq!(ids, vec![visible.id.to_string().as_str()]);

    let (_, body) = app.get("/bookmarks", &token).await;
    assert!(body["bookmarks"].as_array().unwrap().is_empty(), "{body}");

    let (_, body) = app.get("/notifications", &token).await;
    assert!(!body.to_string().contains("Hidden"), "{body}");
    assert_eq!(body["unread"], json!(0));
    assert_eq!(app.get("/notifications/unread", &token).await.1["unread"], json!(0));

    // Writes aimed at it are 404s, the same answer as "doesn't exist".
    let p = format!("/posts/{}", hidden_post.id);
    for (method, path, body) in [
        ("POST", format!("/topics/{}/posts", hidden.id), json!({"body": "hi"})),
        ("PUT", format!("{p}/reaction"), json!({"key": "heart"})),
        ("PUT", format!("{p}/bookmark"), json!({"bookmarked": true})),
        ("PUT", format!("/topics/{}/tags", hidden.id), json!({"tags": ["x"]})),
        ("POST", format!("/categories/{}/topics", secret.slug), json!({"title": "t", "body": "b"})),
        ("PUT", format!("/categories/{}/watch", secret.slug), json!({"watching": true})),
    ] {
        let (status, _) = app.call(method, &path, Some(&token), Some(body)).await;
        assert_eq!(status, StatusCode::NOT_FOUND, "{method} {path}");
    }

    // Staff see it.
    let staff_token = app.token(&staff).await;
    assert_eq!(app.get(&format!("/topics/{}", hidden.id), &staff_token).await.0, StatusCode::OK);
}

#[tokio::test]
async fn an_unverified_account_reads_but_cannot_write() {
    let Some(app) = app().await else { return };
    let staff = app.user("staff", 4, true, true).await;
    let open = app.category("Open", None).await;
    let topic = app.topic(&staff, &open, "Read me", "").await;
    let post = app.first_post(&topic).await;

    let reader = app.user("unverified", 1, false, false).await;
    let token = app.token(&reader).await;
    let (status, me) = app.get("/me", &token).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(me["user"]["email_verified"], json!(false));
    assert_eq!(me["user"]["may_write"], json!(false));
    assert_eq!(me["verification_required"], json!(true));

    let (status, page) = app.get(&format!("/topics/{}", topic.id), &token).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(page["can_reply"], json!(false));

    for (method, path, body) in [
        ("POST", format!("/topics/{}/posts", topic.id), json!({"body": "hi"})),
        ("PUT", format!("/posts/{}/reaction", post.id), json!({"key": "heart"})),
        ("PUT", format!("/posts/{}/bookmark", post.id), json!({"bookmarked": true})),
        ("POST", format!("/categories/{}/topics", open.slug), json!({"title": "t", "body": "b"})),
    ] {
        let (status, body) = app.call(method, &path, Some(&token), Some(body)).await;
        assert_eq!(status, StatusCode::FORBIDDEN, "{method} {path}");
        assert_eq!(error_code(&body), "unverified");
    }
    // Nothing was written.
    let count = posts::Entity::find().filter(posts::Column::TopicId.eq(topic.id)).count(app.db()).await.unwrap();
    assert_eq!(count, 1);

    // The same account verified can.
    recourse::auth::verification::mark_verified(app.db(), &reader).await.unwrap();
    let (status, reply) = app.call("POST", &format!("/topics/{}/posts", topic.id), Some(&token), Some(json!({"body": "**hi**"}))).await;
    assert_eq!(status, StatusCode::CREATED);
    assert_eq!(reply["post_number"], json!(2));
    assert!(reply["cooked"].as_str().unwrap().contains("<strong>hi</strong>"));
}

#[tokio::test]
async fn reading_a_topic_counts_one_view_per_window_and_marks_it_read() {
    let Some(app) = app().await else { return };
    let staff = app.user("staff", 4, true, true).await;
    let open = app.category("Open", None).await;
    let topic = app.topic(&staff, &open, "Count me", "").await;
    let reader = app.user("reader", 1, false, true).await;
    let token = app.token(&reader).await;

    let (_, listing) = app.get(&format!("/categories/{}", open.slug), &token).await;
    let tile = &listing["topics"].as_array().unwrap()[0];
    assert_eq!(tile["is_new"], json!(true));

    for _ in 0..3 {
        assert_eq!(app.get(&format!("/topics/{}", topic.id), &token).await.0, StatusCode::OK);
    }
    let views = topics::Entity::find_by_id(topic.id).one(app.db()).await.unwrap().unwrap().views;
    assert_eq!(views, 1);
    let read = topic_reads::Entity::find_by_id((reader.id, topic.id)).one(app.db()).await.unwrap().unwrap();
    assert_eq!(read.last_read_post_number, 1);

    let (_, listing) = app.get(&format!("/categories/{}", open.slug), &token).await;
    let tile = &listing["topics"].as_array().unwrap()[0];
    assert_eq!(tile["is_new"], json!(false));
    assert_eq!(tile["unread"], json!(0));
}

#[tokio::test]
async fn toggles_take_the_desired_state() {
    let Some(app) = app().await else { return };
    let staff = app.user("staff", 4, true, true).await;
    let open = app.category("Open", None).await;
    let topic = app.topic(&staff, &open, "Toggle me", "").await;
    let post = app.first_post(&topic).await;
    let user = app.user("toggler", 1, false, true).await;
    let token = app.token(&user).await;

    for _ in 0..2 {
        let (status, body) = app.call("PUT", &format!("/posts/{}/bookmark", post.id), Some(&token), Some(json!({"bookmarked": true}))).await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(body["bookmarked"], json!(true));
    }
    let (_, body) = app.get("/bookmarks", &token).await;
    assert_eq!(body["bookmarks"].as_array().unwrap().len(), 1);

    for _ in 0..2 {
        let (_, body) = app.call("PUT", &format!("/posts/{}/reaction", post.id), Some(&token), Some(json!({"key": "heart"}))).await;
        let like = body["reactions"].as_array().unwrap().iter().find(|r| r["key"] == json!("heart")).unwrap().clone();
        assert_eq!(like["count"], json!(1));
        assert_eq!(like["reacted"], json!(true));
    }
    let (_, body) = app.call("PUT", &format!("/posts/{}/reaction", post.id), Some(&token), Some(json!({"key": null}))).await;
    assert!(body["reactions"].as_array().unwrap().iter().all(|r| r["count"] == json!(0)));
    let (status, body) = app.call("PUT", &format!("/posts/{}/reaction", post.id), Some(&token), Some(json!({"key": "nope"}))).await;
    assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
    assert_eq!(error_code(&body), "invalid");

    let (_, body) = app.call("PUT", &format!("/categories/{}/watch", open.slug), Some(&token), Some(json!({"watching": true}))).await;
    assert_eq!(body["watching"], json!(true));
    let (_, page) = app.get(&format!("/topics/{}", topic.id), &token).await;
    assert_eq!(page["watching"], json!(true));

    let (status, me) = app.call("PATCH", "/me", Some(&token), Some(json!({"layout": "focus", "sort": "hot"}))).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(me["user"]["preferred_view"], json!("focus"));
    assert_eq!(me["user"]["preferred_sort"], json!("hot"));
    let (status, body) = app.call("PATCH", "/me", Some(&token), Some(json!({"layout": "grid"}))).await;
    assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{body}");

    let (status, body) = app.call("POST", "/topics/not-a-uuid/posts", Some(&token), Some(json!({"body": "x"}))).await;
    assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
}

/// Real responses for the Android app's ContractTest to decode, written to
/// android/app/src/test/resources/api/ when WRITE_ANDROID_FIXTURES is set
/// (`just fixtures`). Without it this still makes every call, so a response
/// that stops being produced fails here before the app finds out.
#[tokio::test]
async fn android_fixtures() {
    let Some(app) = app().await else { return };
    let write = std::env::var_os("WRITE_ANDROID_FIXTURES").is_some();
    let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("android/app/src/test/resources/api");
    let save = |name: &str, body: &Value| {
        if write {
            std::fs::create_dir_all(&dir).unwrap();
            let pretty = serde_json::to_string_pretty(body).unwrap() + "\n";
            std::fs::write(dir.join(format!("{name}.json")), pretty).unwrap();
        }
    };

    let staff = app.user("fixture-staff", 4, true, true).await;
    let user = app.user("fixture", 1, false, true).await;
    let token = app.token(&user).await;
    let open = app.category("General", None).await;
    let fixture_tag = format!("fixture{}", tag());
    let topic = app.topic(&staff, &open, "Welcome to the forum", &fixture_tag).await;
    let post = app.first_post(&topic).await;
    app.call("POST", &format!("/topics/{}/posts", topic.id), Some(&token), Some(json!({"body": "Thanks — *glad* to be here."})))
        .await;
    app.call("PUT", &format!("/posts/{}/reaction", post.id), Some(&token), Some(json!({"key": "heart"}))).await;
    app.call("PUT", &format!("/posts/{}/bookmark", post.id), Some(&token), Some(json!({"bookmarked": true}))).await;
    recourse::handlers::notifications::notify_new_topic(app.db(), topic.id, staff.id, &[open.id]).await.unwrap();
    recourse::actions::set_watch(&app.state, &user, &open.slug, true).await.unwrap();
    app.topic(&staff, &open, "A second topic", "").await;

    let mut calls: Vec<(&str, String)> = vec![
        ("me", "/me".into()),
        ("devices", "/me/devices".into()),
        ("categories", "/categories".into()),
        ("category", format!("/categories/{}", open.slug)),
        ("topic", format!("/topics/{}", topic.id)),
        ("tags", "/tags".into()),
        ("tag", format!("/tags/{fixture_tag}")),
        ("search", "/search?q=welcome".into()),
        ("bookmarks", "/bookmarks".into()),
        ("notifications", "/notifications".into()),
        ("unread", "/notifications/unread".into()),
    ];
    for (name, path) in calls.drain(..) {
        let (status, body) = app.get(&path, &token).await;
        assert_eq!(status, StatusCode::OK, "{path}: {body}");
        save(name, &body);
    }

    let (status, body) =
        app.call("POST", &format!("/topics/{}/posts", topic.id), Some(&token), Some(json!({"body": "One more."}))).await;
    assert_eq!(status, StatusCode::CREATED);
    save("reply", &body);
    let (status, body) = app.call("PUT", &format!("/posts/{}/reaction", post.id), Some(&token), Some(json!({"key": "heart"}))).await;
    assert_eq!(status, StatusCode::OK);
    save("reaction", &body);
    let (status, body) = app.call("PUT", &format!("/topics/{}/tags", topic.id), Some(&token), Some(json!({"tags": []}))).await;
    assert_eq!(status, StatusCode::FORBIDDEN);
    save("error_forbidden", &body);
    let (status, body) = app.call("GET", "/me", None, None).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
    save("error", &body);
}