507 lines
28 KiB
Rust
507 lines
28 KiB
Rust
//! The web dashboard: Dezio's website plus per-user and per-server settings, served by the bot itself.
|
|
//!
|
|
//! / the website (web/site/: index, terms, privacy, assets/, images/)
|
|
//! /dashboard the settings app (web/dashboard/), which talks to /api/…
|
|
//! /login → Discord → /callback sign in with Discord (OAuth2, "identify" only)
|
|
//! /activity/ the Game Boy Discord Activity (activity.rs, web/activity/)
|
|
//!
|
|
//! Settings in .env:
|
|
//! DASHBOARD_CLIENT_SECRET the app's OAuth2 client secret (Developer Portal → OAuth2) — sign-in is off without it
|
|
//! DASHBOARD_URL the address people open, default http://192.168.1.71:8080;
|
|
//! add DASHBOARD_URL + "/callback" under OAuth2 → Redirects in the Developer Portal
|
|
//! DASHBOARD_HOST / _PORT where to listen (default 0.0.0.0 and the port from DASHBOARD_URL)
|
|
//!
|
|
//! Security: sessions are random server-side tokens in an HttpOnly, SameSite=Lax cookie; every change needs the
|
|
//! session's CSRF token in a header *and* a same-origin request; server permissions are checked live against
|
|
//! Discord (Manage Server, through the bot's member cache), never trusted from the browser.
|
|
//! Sessions live in data/dashboard_sessions.json in the same format the Python dashboard used, so people stay signed in.
|
|
mod activity;
|
|
mod api;
|
|
|
|
use crate::paths;
|
|
use crate::state::State;
|
|
use crate::storage::JsonStore;
|
|
use axum::extract::{Request, State as AxState};
|
|
use axum::http::{header, HeaderMap, HeaderValue, StatusCode};
|
|
use axum::middleware::{self, Next};
|
|
use axum::response::{IntoResponse, Redirect, Response};
|
|
use axum::routing::{get, post};
|
|
use axum::Router;
|
|
use serde_json::{json, Value};
|
|
use sha2::{Digest, Sha256};
|
|
use std::sync::Arc;
|
|
use std::time::{SystemTime, UNIX_EPOCH};
|
|
use tower_http::services::{ServeDir, ServeFile};
|
|
|
|
pub const SESSION_COOKIE: &str = "dezio_session";
|
|
const STATE_COOKIE: &str = "dezio_oauth_state";
|
|
const NEXT_COOKIE: &str = "dezio_next";
|
|
const AFTER_LOGIN: [&str; 2] = ["/dashboard", "/activity/"];
|
|
const SESSION_DAYS: u64 = 7;
|
|
const DISCORD: &str = "https://discord.com/api/v10";
|
|
|
|
const SECURITY_CSP: &str = "default-src 'self'; img-src 'self' data: blob: https://cdn.discordapp.com; style-src 'self'; script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'";
|
|
const ACTIVITY_CSP: &str = "default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https://cdn.discordapp.com; connect-src 'self' https://discord.com; media-src 'self' blob:; base-uri 'none'; form-action 'none'";
|
|
|
|
pub struct Cfg {
|
|
pub url: String,
|
|
pub origin: String,
|
|
pub secure: bool,
|
|
pub host: String,
|
|
pub port: u16,
|
|
pub client_secret: String,
|
|
}
|
|
|
|
impl Cfg {
|
|
pub fn from_env() -> Self {
|
|
let url = std::env::var("DASHBOARD_URL").ok().filter(|u| !u.is_empty()).unwrap_or_else(|| "http://192.168.1.71:8080".into()).trim_end_matches('/').to_string();
|
|
let parsed = reqwest::Url::parse(&url).ok();
|
|
let secure = url.starts_with("https://");
|
|
let origin = parsed.as_ref().map(|u| format!("{}://{}", u.scheme(), u.host_str().unwrap_or("localhost").to_string() + &u.port().map(|p| format!(":{p}")).unwrap_or_default())).unwrap_or_else(|| url.clone());
|
|
let default_port = parsed.as_ref().and_then(|u| u.port_or_known_default()).unwrap_or(8080);
|
|
Self {
|
|
origin,
|
|
secure,
|
|
host: std::env::var("DASHBOARD_HOST").ok().filter(|h| !h.is_empty()).unwrap_or_else(|| "0.0.0.0".into()),
|
|
port: std::env::var("DASHBOARD_PORT").ok().and_then(|p| p.parse().ok()).unwrap_or(default_port),
|
|
client_secret: std::env::var("DASHBOARD_CLIENT_SECRET").unwrap_or_default(),
|
|
url,
|
|
}
|
|
}
|
|
}
|
|
|
|
pub struct Web {
|
|
pub state: Arc<State>,
|
|
pub cfg: Cfg,
|
|
pub sessions: Arc<JsonStore>,
|
|
pub activity: Arc<activity::Activity>,
|
|
pub preview: tokio::sync::Semaphore,
|
|
}
|
|
|
|
pub type Shared = Arc<Web>;
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub struct Session {
|
|
pub user_id: u64,
|
|
pub name: String,
|
|
pub username: String,
|
|
pub avatar: Option<String>,
|
|
pub csrf: String,
|
|
}
|
|
|
|
/// An error with the status and message the page shows.
|
|
pub struct ApiError(pub StatusCode, pub String);
|
|
|
|
impl ApiError {
|
|
pub fn new(code: u16, msg: impl Into<String>) -> Self {
|
|
Self(StatusCode::from_u16(code).unwrap_or(StatusCode::BAD_REQUEST), msg.into())
|
|
}
|
|
}
|
|
|
|
impl IntoResponse for ApiError {
|
|
fn into_response(self) -> Response {
|
|
(self.0, axum::Json(json!({"error": self.1}))).into_response()
|
|
}
|
|
}
|
|
|
|
pub type ApiResult<T = Response> = Result<T, ApiError>;
|
|
|
|
pub fn sha(token: &str) -> String {
|
|
use std::fmt::Write as _;
|
|
Sha256::digest(token.as_bytes()).iter().fold(String::new(), |mut s, b| {
|
|
let _ = write!(s, "{b:02x}");
|
|
s
|
|
})
|
|
}
|
|
|
|
pub fn now() -> u64 {
|
|
SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs())
|
|
}
|
|
|
|
pub fn random_token(bytes: usize) -> String {
|
|
use base64::Engine as _;
|
|
let raw: Vec<u8> = (0..bytes).map(|_| rand::random::<u8>()).collect();
|
|
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(raw)
|
|
}
|
|
|
|
pub fn cookie_value(headers: &HeaderMap, name: &str) -> Option<String> {
|
|
headers.get_all(header::COOKIE).iter().filter_map(|v| v.to_str().ok()).flat_map(|v| v.split(';')).find_map(|p| {
|
|
let (k, v) = p.trim().split_once('=')?;
|
|
(k == name).then(|| v.to_string())
|
|
})
|
|
}
|
|
|
|
impl Web {
|
|
pub fn sign_in_ready(&self) -> bool {
|
|
!self.cfg.client_secret.is_empty()
|
|
}
|
|
|
|
fn set_cookie(&self, resp: &mut Response, name: &str, value: &str, max_age: u64) {
|
|
let c = format!("{name}={value}; Max-Age={max_age}; Path=/; HttpOnly; SameSite=Lax{}", if self.cfg.secure { "; Secure" } else { "" });
|
|
if let Ok(v) = HeaderValue::from_str(&c) {
|
|
resp.headers_mut().append(header::SET_COOKIE, v);
|
|
}
|
|
}
|
|
|
|
pub fn session(&self, headers: &HeaderMap) -> Option<Session> {
|
|
let token = cookie_value(headers, SESSION_COOKIE)?;
|
|
let d = self.sessions.get(sha(&token))?;
|
|
if d["expires"].as_u64().unwrap_or(0) < now() {
|
|
return None;
|
|
}
|
|
Some(Session {
|
|
user_id: d["user_id"].as_u64()?,
|
|
name: d["name"].as_str().or(d["username"].as_str()).unwrap_or("Someone").to_string(),
|
|
username: d["username"].as_str().unwrap_or("").to_string(),
|
|
avatar: d["avatar"].as_str().map(str::to_string),
|
|
csrf: d["csrf"].as_str().unwrap_or("").to_string(),
|
|
})
|
|
}
|
|
|
|
pub fn need_session(&self, headers: &HeaderMap) -> ApiResult<Session> {
|
|
self.session(headers).ok_or_else(|| ApiError::new(401, "Sign in first"))
|
|
}
|
|
|
|
/// Changes must come from our own page: same origin, our CSRF token, and JSON.
|
|
pub fn check_write(&self, headers: &HeaderMap, session: &Session) -> ApiResult<()> {
|
|
let origin = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()).map(str::to_string).or_else(|| {
|
|
let r = headers.get(header::REFERER)?.to_str().ok()?;
|
|
let u = reqwest::Url::parse(r).ok()?;
|
|
Some(format!("{}://{}{}", u.scheme(), u.host_str()?, u.port().map(|p| format!(":{p}")).unwrap_or_default()))
|
|
});
|
|
let host = headers.get(header::HOST).and_then(|v| v.to_str().ok()).unwrap_or("");
|
|
let same_host = format!("{}://{host}", if self.cfg.secure { "https" } else { "http" });
|
|
if !origin.as_deref().is_some_and(|o| o == self.cfg.origin || o == same_host) {
|
|
return Err(ApiError::new(403, "Cross-site request refused"));
|
|
}
|
|
let sent = headers.get("x-csrf-token").and_then(|v| v.to_str().ok()).unwrap_or("");
|
|
if sent.is_empty() || sent.len() != session.csrf.len() || sent.bytes().zip(session.csrf.bytes()).fold(0u8, |a, (x, y)| a | (x ^ y)) != 0 {
|
|
return Err(ApiError::new(403, "Missing or wrong CSRF token — reload the page"));
|
|
}
|
|
if !headers.get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(|c| c.starts_with("application/json")) {
|
|
return Err(ApiError::new(415, "Send JSON"));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn prune(&self) {
|
|
let t = now();
|
|
let dead: Vec<String> = self.sessions.snapshot().iter().filter(|(_, v)| v["expires"].as_u64().unwrap_or(0) < t).map(|(k, _)| k.clone()).collect();
|
|
for k in dead {
|
|
self.sessions.pop(k);
|
|
}
|
|
}
|
|
}
|
|
|
|
// ---- sign-in ---------------------------------------------------------------------------------------------------
|
|
|
|
async fn login(AxState(w): AxState<Shared>, axum::extract::Query(q): axum::extract::Query<std::collections::HashMap<String, String>>) -> Response {
|
|
if !w.sign_in_ready() {
|
|
return Redirect::to("/dashboard?error=setup").into_response();
|
|
}
|
|
let state = random_token(24);
|
|
let params = [("client_id", w.state.app_id().to_string()), ("redirect_uri", format!("{}/callback", w.cfg.url)), ("response_type", "code".into()), ("scope", "identify".into()), ("state", state.clone()), ("prompt", "none".into())];
|
|
let query = params.iter().map(|(k, v)| format!("{k}={}", urlencoding::encode(v))).collect::<Vec<_>>().join("&");
|
|
let mut resp = Redirect::to(&format!("https://discord.com/oauth2/authorize?{query}")).into_response();
|
|
w.set_cookie(&mut resp, STATE_COOKIE, &state, 600);
|
|
if let Some(after) = q.get("next").filter(|n| AFTER_LOGIN.contains(&n.as_str())) {
|
|
w.set_cookie(&mut resp, NEXT_COOKIE, after, 600);
|
|
}
|
|
resp
|
|
}
|
|
|
|
async fn callback(AxState(w): AxState<Shared>, headers: HeaderMap, axum::extract::Query(q): axum::extract::Query<std::collections::HashMap<String, String>>) -> Response {
|
|
let fail = |why: &str| Redirect::to(&format!("/dashboard?error={why}")).into_response();
|
|
let (state, code) = (q.get("state").cloned().unwrap_or_default(), q.get("code").cloned().unwrap_or_default());
|
|
let expected = cookie_value(&headers, STATE_COOKIE).unwrap_or_default();
|
|
if code.is_empty() || expected.is_empty() || state != expected {
|
|
return fail("state");
|
|
}
|
|
let web = &w.state.web;
|
|
let app = w.state.app_id().to_string();
|
|
let form = [("client_id", app.as_str()), ("client_secret", w.cfg.client_secret.as_str()), ("grant_type", "authorization_code"), ("code", code.as_str()), ("redirect_uri", &format!("{}/callback", w.cfg.url))];
|
|
let token: Option<Value> = async { web.post(format!("{DISCORD}/oauth2/token")).form(&form).send().await.ok()?.json().await.ok() }.await;
|
|
let Some(access) = token.as_ref().and_then(|t| t["access_token"].as_str()).map(str::to_string) else {
|
|
tracing::warn!("Dashboard sign-in: Discord refused the code");
|
|
return fail("discord");
|
|
};
|
|
let me: Option<Value> = async { web.get(format!("{DISCORD}/users/@me")).bearer_auth(&access).send().await.ok()?.json().await.ok() }.await;
|
|
// we only needed it once: revoke it so it can't be misused later
|
|
let _ = web.post(format!("{DISCORD}/oauth2/token/revoke")).form(&[("client_id", app.as_str()), ("client_secret", w.cfg.client_secret.as_str()), ("token", access.as_str()), ("token_type_hint", "access_token")]).send().await;
|
|
let Some(me) = me.filter(|m| m["id"].is_string()) else { return fail("discord") };
|
|
w.prune();
|
|
let raw = random_token(32);
|
|
let t = now();
|
|
w.sessions.set(sha(&raw), json!({
|
|
"user_id": me["id"].as_str().and_then(|i| i.parse::<u64>().ok()), "name": me["global_name"].as_str().or(me["username"].as_str()), "username": me["username"],
|
|
"avatar": me["avatar"], "csrf": random_token(24), "created": t, "expires": t + SESSION_DAYS * 86400,
|
|
}));
|
|
tracing::info!("Dashboard sign-in: {} ({})", me["username"], me["id"]);
|
|
let after = cookie_value(&headers, NEXT_COOKIE).filter(|a| AFTER_LOGIN.contains(&a.as_str())).unwrap_or_else(|| "/dashboard".into());
|
|
let mut resp = Redirect::to(&after).into_response();
|
|
w.set_cookie(&mut resp, SESSION_COOKIE, &raw, SESSION_DAYS * 86400);
|
|
w.set_cookie(&mut resp, STATE_COOKIE, "", 0);
|
|
w.set_cookie(&mut resp, NEXT_COOKIE, "", 0);
|
|
resp
|
|
}
|
|
|
|
async fn logout(AxState(w): AxState<Shared>, headers: HeaderMap) -> ApiResult {
|
|
let s = w.need_session(&headers)?;
|
|
w.check_write(&headers, &s)?;
|
|
if let Some(t) = cookie_value(&headers, SESSION_COOKIE) {
|
|
w.sessions.pop(sha(&t));
|
|
}
|
|
let mut resp = axum::Json(json!({"ok": true})).into_response();
|
|
w.set_cookie(&mut resp, SESSION_COOKIE, "", 0);
|
|
Ok(resp)
|
|
}
|
|
|
|
// ---- headers + pages --------------------------------------------------------------------------------------------
|
|
|
|
async fn headers_mw(request: Request, next: Next) -> Response {
|
|
let path = request.uri().path().to_string();
|
|
let mut resp = next.run(request).await;
|
|
let h = resp.headers_mut();
|
|
h.insert("x-content-type-options", HeaderValue::from_static("nosniff"));
|
|
if path == "/activity" || path.starts_with("/activity/") {
|
|
// shown inside Discord's iframe: its own, frameable policy
|
|
h.insert("referrer-policy", HeaderValue::from_static("no-referrer"));
|
|
h.insert(header::CONTENT_SECURITY_POLICY, HeaderValue::from_static(ACTIVITY_CSP));
|
|
} else {
|
|
h.insert("x-frame-options", HeaderValue::from_static("DENY"));
|
|
h.insert("referrer-policy", HeaderValue::from_static("same-origin"));
|
|
h.insert(header::CONTENT_SECURITY_POLICY, HeaderValue::from_static(SECURITY_CSP));
|
|
}
|
|
if path.starts_with("/api/") || path.starts_with("/activity/api/") && !path.contains("/rom/") && !path.contains("/art/") {
|
|
h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
|
|
}
|
|
resp
|
|
}
|
|
|
|
pub fn router(w: Shared) -> Router {
|
|
let site = paths::web(&["site"]);
|
|
let app = paths::web(&["dashboard"]);
|
|
let page = |dir: &std::path::Path, name: &str| ServeFile::new(dir.join(name));
|
|
Router::new()
|
|
.route("/login", get(login))
|
|
.route("/callback", get(callback))
|
|
.route("/logout", post(logout))
|
|
.merge(api::routes())
|
|
.merge(activity::routes())
|
|
.route_service("/dashboard", page(&app, "index.html"))
|
|
.route_service("/dashboard/", page(&app, "index.html"))
|
|
.route_service("/", page(&site, "index.html"))
|
|
.route_service("/index.html", page(&site, "index.html"))
|
|
.route_service("/terms", page(&site, "terms.html"))
|
|
.route_service("/terms.html", page(&site, "terms.html"))
|
|
.route_service("/privacy", page(&site, "privacy.html"))
|
|
.route_service("/privacy.html", page(&site, "privacy.html"))
|
|
.nest_service("/dashboard/static", ServeDir::new(app.join("static")))
|
|
.nest_service("/assets", ServeDir::new(site.join("assets")))
|
|
.nest_service("/images", ServeDir::new(site.join("images")))
|
|
// files too big for Discord, kept for a few hours (see hosted.rs)
|
|
.nest_service("/f", ServeDir::new(crate::hosted::dir()))
|
|
.layer(middleware::from_fn(headers_mw))
|
|
.layer(axum::extract::DefaultBodyLimit::max(64 * 1024))
|
|
.with_state(w)
|
|
}
|
|
|
|
/// For `--web-dev`: serve on 127.0.0.1:8099 with a signed-in test session (cookie `dezio_session=devtoken`).
|
|
pub fn start_dev(state: Arc<State>) {
|
|
let url = "http://127.0.0.1:8099".to_string();
|
|
let cfg = Cfg { origin: url.clone(), url, secure: false, host: "127.0.0.1".into(), port: 8099, client_secret: "dev".into() };
|
|
let sessions = JsonStore::open(std::env::temp_dir().join("dezio-dev-sessions.json"));
|
|
sessions.set(sha("devtoken"), json!({"user_id": 4242u64, "name": "Dev Tester", "username": "devtester", "avatar": null, "csrf": "devcsrf", "created": now(), "expires": now() + 86400}));
|
|
let web = Arc::new(Web { state, cfg, sessions, activity: Arc::new(activity::Activity::new()), preview: tokio::sync::Semaphore::new(2) });
|
|
let app = router(web);
|
|
tokio::spawn(async move {
|
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:8099").await.expect("port 8099");
|
|
println!("web dev server on http://127.0.0.1:8099 — set the cookie dezio_session=devtoken");
|
|
let _ = axum::serve(listener, app.into_make_service_with_connect_info::<std::net::SocketAddr>()).await;
|
|
});
|
|
}
|
|
|
|
/// Start the web server in the background. Called once when the bot is ready.
|
|
pub fn start(state: Arc<State>) {
|
|
static ONCE: std::sync::Once = std::sync::Once::new();
|
|
ONCE.call_once(|| {
|
|
let cfg = Cfg::from_env();
|
|
let web = Arc::new(Web { sessions: JsonStore::open(paths::data(&["dashboard_sessions.json"])), activity: Arc::new(activity::Activity::new()), preview: tokio::sync::Semaphore::new(2), state, cfg });
|
|
let addr = format!("{}:{}", web.cfg.host, web.cfg.port);
|
|
let ready = web.sign_in_ready();
|
|
let url = web.cfg.url.clone();
|
|
let app = router(web);
|
|
tokio::spawn(async move {
|
|
match tokio::net::TcpListener::bind(&addr).await {
|
|
Ok(listener) => {
|
|
tracing::info!("Dashboard on {url} (listening on {addr}){}", if ready { "" } else { " — sign-in is off until DASHBOARD_CLIENT_SECRET is set" });
|
|
if let Err(e) = axum::serve(listener, app.into_make_service_with_connect_info::<std::net::SocketAddr>()).await {
|
|
tracing::error!("dashboard stopped: {e}");
|
|
}
|
|
}
|
|
Err(e) => tracing::error!("the dashboard can't listen on {addr}: {e}"),
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use axum::body::Body;
|
|
use axum::http::{Method, Request as HttpRequest};
|
|
use tower::ServiceExt;
|
|
|
|
fn web() -> Shared {
|
|
let _ = rustls::crypto::ring::default_provider().install_default();
|
|
let http = Arc::new(twilight_http::Client::new("x".into()));
|
|
let state = Arc::new(State::new(http, crate::cmd::Registry::new(vec![]), "x".into()));
|
|
state.set_app_id(twilight_model::id::Id::new(1));
|
|
state.set_bot_id(twilight_model::id::Id::new(2));
|
|
let cfg = Cfg { url: "http://dashboard.test".into(), origin: "http://dashboard.test".into(), secure: false, host: "127.0.0.1".into(), port: 0, client_secret: "secret".into() };
|
|
Arc::new(Web { state, cfg, sessions: JsonStore::open(std::env::temp_dir().join(format!("dezio-ws-{}.json", rand::random::<u32>()))), activity: Arc::new(activity::Activity::new()), preview: tokio::sync::Semaphore::new(2) })
|
|
}
|
|
|
|
fn signed_in(w: &Shared) -> (String, String) {
|
|
let raw = random_token(32);
|
|
let csrf = random_token(8);
|
|
w.sessions.set(sha(&raw), json!({"user_id": 4242u64, "name": "Tester", "username": "tester", "avatar": null, "csrf": csrf, "created": now(), "expires": now() + 3600}));
|
|
(format!("{SESSION_COOKIE}={raw}"), csrf)
|
|
}
|
|
|
|
async fn call(app: &Router, req: HttpRequest<Body>) -> (StatusCode, HeaderMap, Vec<u8>) {
|
|
let r = app.clone().oneshot(req).await.unwrap();
|
|
let (status, headers) = (r.status(), r.headers().clone());
|
|
(status, headers, axum::body::to_bytes(r.into_body(), 10_000_000).await.unwrap().to_vec())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn pages_and_sign_in_gate() {
|
|
let w = web();
|
|
let app = router(w.clone());
|
|
for path in ["/", "/dashboard", "/terms", "/privacy", "/dashboard/static/app.js", "/images/dezio.png", "/activity/", "/activity/static/app.js"] {
|
|
let (status, headers, body) = call(&app, HttpRequest::get(path).body(Body::empty()).unwrap()).await;
|
|
assert_eq!(status, StatusCode::OK, "{path}");
|
|
assert!(!body.is_empty(), "{path}");
|
|
assert!(headers.contains_key("content-security-policy"), "{path}");
|
|
}
|
|
let (_, h, _) = call(&app, HttpRequest::get("/activity/").body(Body::empty()).unwrap()).await;
|
|
assert!(h["content-security-policy"].to_str().unwrap().contains("wasm-unsafe-eval") && !h.contains_key("x-frame-options"));
|
|
let (_, h, _) = call(&app, HttpRequest::get("/dashboard").body(Body::empty()).unwrap()).await;
|
|
assert_eq!(h["x-frame-options"], "DENY");
|
|
let (status, _, body) = call(&app, HttpRequest::get("/api/me").body(Body::empty()).unwrap()).await;
|
|
assert_eq!(status, StatusCode::OK);
|
|
assert_eq!(serde_json::from_slice::<Value>(&body).unwrap()["signed_in"], false);
|
|
let (status, _, _) = call(&app, HttpRequest::get("/api/user").body(Body::empty()).unwrap()).await;
|
|
assert_eq!(status, StatusCode::UNAUTHORIZED);
|
|
let (status, h, _) = call(&app, HttpRequest::get("/login").body(Body::empty()).unwrap()).await;
|
|
assert!(status.is_redirection() && h[header::LOCATION].to_str().unwrap().starts_with("https://discord.com/oauth2/authorize?"));
|
|
assert!(h.get_all(header::SET_COOKIE).iter().any(|c| c.to_str().unwrap().starts_with("dezio_oauth_state=")));
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn signed_in_users_edit_their_settings_safely() {
|
|
let w = web();
|
|
let app = router(w.clone());
|
|
let (cookie, csrf) = signed_in(&w);
|
|
let (_, _, body) = call(&app, HttpRequest::get("/api/user").header(header::COOKIE, &cookie).body(Body::empty()).unwrap()).await;
|
|
let v: Value = serde_json::from_slice(&body).unwrap();
|
|
assert_eq!(v["download_quality"], "fast");
|
|
assert!(v["quote"]["presets"].as_array().unwrap().len() >= 6);
|
|
let patch = |origin: Option<&str>, token: &str, body: Value| {
|
|
let mut r = HttpRequest::builder().method(Method::PATCH).uri("/api/user").header(header::COOKIE, &cookie).header(header::CONTENT_TYPE, "application/json").header("x-csrf-token", token).header(header::HOST, "dashboard.test");
|
|
if let Some(o) = origin {
|
|
r = r.header(header::ORIGIN, o);
|
|
}
|
|
r.body(Body::from(body.to_string())).unwrap()
|
|
};
|
|
let (s, _, _) = call(&app, patch(Some("http://evil.test"), &csrf, json!({"temp_unit": "f"}))).await;
|
|
assert_eq!(s, StatusCode::FORBIDDEN, "another site can't change settings");
|
|
let (s, _, _) = call(&app, patch(Some("http://dashboard.test"), "wrong", json!({"temp_unit": "f"}))).await;
|
|
assert_eq!(s, StatusCode::FORBIDDEN, "no CSRF token, no change");
|
|
let (s, _, _) = call(&app, patch(Some("http://dashboard.test"), &csrf, json!({"temp_unit": "kelvin"}))).await;
|
|
assert_eq!(s, StatusCode::BAD_REQUEST);
|
|
let (s, _, body) = call(&app, patch(Some("http://dashboard.test"), &csrf, json!({"temp_unit": "f", "weather_home": "Paris", "quote": {"layout": "portrait", "marks": true, "bg": "#101010"}}))).await;
|
|
assert_eq!(s, StatusCode::OK, "{}", String::from_utf8_lossy(&body));
|
|
let v: Value = serde_json::from_slice(&body).unwrap();
|
|
assert_eq!((v["settings"]["temp_unit"].as_str(), v["settings"]["weather_home"].as_str()), (Some("f"), Some("Paris")));
|
|
assert_eq!(v["settings"]["quote"]["style"]["layout"], "portrait");
|
|
let (s, _, _) = call(&app, patch(Some("http://dashboard.test"), &csrf, json!({"quote": {"layout": "sideways"}}))).await;
|
|
assert_eq!(s, StatusCode::BAD_REQUEST);
|
|
let (s, _, _) = call(&app, patch(Some("http://dashboard.test"), &csrf, json!({"quote": {"bg": "red"}}))).await;
|
|
assert_eq!(s, StatusCode::BAD_REQUEST);
|
|
// tidy up what the test saved
|
|
let (s, _, _) = call(&app, patch(Some("http://dashboard.test"), &csrf, json!({"quote": null, "weather_home": "", "temp_unit": "c"}))).await;
|
|
assert_eq!(s, StatusCode::OK);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn hosted_files_download_and_support_seeking() {
|
|
let tmp = std::env::temp_dir().join(format!("dezio-hostweb-{}.bin", rand::random::<u32>()));
|
|
std::fs::write(&tmp, b"0123456789").unwrap();
|
|
let url = crate::hosted::store(&tmp, "My clip.mp4").unwrap();
|
|
let path = url.strip_prefix(&crate::hosted::base_url()).unwrap().to_string();
|
|
let app = router(web());
|
|
let (status, headers, body) = call(&app, HttpRequest::get(&path).body(Body::empty()).unwrap()).await;
|
|
assert_eq!((status, body.as_slice()), (StatusCode::OK, &b"0123456789"[..]), "{path}");
|
|
assert_eq!(headers.get("content-type").and_then(|v| v.to_str().ok()), Some("video/mp4"));
|
|
let (status, _, body) = call(&app, HttpRequest::get(&path).header("range", "bytes=2-4").body(Body::empty()).unwrap()).await;
|
|
assert_eq!((status, body.as_slice()), (StatusCode::PARTIAL_CONTENT, &b"234"[..]));
|
|
let (status, _, _) = call(&app, HttpRequest::get("/f/0000000000000000/nothing.mp4").body(Body::empty()).unwrap()).await;
|
|
assert_eq!(status, StatusCode::NOT_FOUND);
|
|
let _ = std::fs::remove_dir_all(crate::hosted::dir().join(path.split('/').nth(2).unwrap()));
|
|
let _ = std::fs::remove_file(tmp);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn the_quote_preview_is_drawn_by_the_bot() {
|
|
let w = web();
|
|
let app = router(w.clone());
|
|
let (cookie, csrf) = signed_in(&w);
|
|
let style = crate::commands::media::quote::preset("portrait");
|
|
let req = HttpRequest::post("/api/quote/preview").header(header::COOKIE, &cookie).header(header::CONTENT_TYPE, "application/json").header("x-csrf-token", &csrf).header(header::ORIGIN, "http://dashboard.test").body(Body::from(json!({"style": style}).to_string())).unwrap();
|
|
let (s, h, body) = call(&app, req).await;
|
|
assert_eq!(s, StatusCode::OK);
|
|
assert_eq!(h[header::CONTENT_TYPE], "image/png");
|
|
let img = image::load_from_memory(&body).unwrap();
|
|
assert_eq!((img.width(), img.height()), (630, 790));
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn the_game_boy_activity_hands_out_roms_and_saves_per_player() {
|
|
let w = web();
|
|
let app = router(w.clone());
|
|
let bearer = format!("Bearer {}", w.activity.new_session(777_000_001, "Player"));
|
|
let (s, _, _) = call(&app, HttpRequest::get("/activity/api/library").body(Body::empty()).unwrap()).await;
|
|
assert_eq!(s, StatusCode::UNAUTHORIZED);
|
|
let (s, _, body) = call(&app, HttpRequest::get("/activity/api/library").header(header::AUTHORIZATION, &bearer).body(Body::empty()).unwrap()).await;
|
|
assert_eq!(s, StatusCode::OK);
|
|
let lib: Value = serde_json::from_slice(&body).unwrap();
|
|
let games = lib["games"].as_array().unwrap();
|
|
assert!(!games.is_empty(), "the ROM library should be found under assets/roms");
|
|
let id = games[0]["id"].as_str().unwrap().to_string();
|
|
let (s, _, rom) = call(&app, HttpRequest::get(format!("/activity/api/rom/{id}")).header(header::AUTHORIZATION, &bearer).body(Body::empty()).unwrap()).await;
|
|
assert_eq!(s, StatusCode::OK);
|
|
assert!(rom.len() > 1000);
|
|
let put = |uri: String, data: Vec<u8>| HttpRequest::put(uri).header(header::AUTHORIZATION, &bearer).body(Body::from(data)).unwrap();
|
|
let (s, _, _) = call(&app, put(format!("/activity/api/save/{id}"), vec![7; 2048])).await;
|
|
assert_eq!(s, StatusCode::OK);
|
|
let (s, _, got) = call(&app, HttpRequest::get(format!("/activity/api/save/{id}")).header(header::AUTHORIZATION, &bearer).body(Body::empty()).unwrap()).await;
|
|
assert_eq!((s, got), (StatusCode::OK, vec![7; 2048]));
|
|
let (s, _, _) = call(&app, put(format!("/activity/api/save/{id}"), vec![1; MAX_SAVE_FOR_TEST + 1])).await;
|
|
assert_eq!(s, StatusCode::PAYLOAD_TOO_LARGE);
|
|
let (s, _, _) = call(&app, put(format!("/activity/api/state/{id}/9"), vec![1; 10])).await;
|
|
assert_eq!(s, StatusCode::NOT_FOUND);
|
|
let (s, _, _) = call(&app, put(format!("/activity/api/state/{id}/2"), vec![5; 100])).await;
|
|
assert_eq!(s, StatusCode::OK);
|
|
let (_, _, body) = call(&app, HttpRequest::get("/activity/api/library").header(header::AUTHORIZATION, &bearer).body(Body::empty()).unwrap()).await;
|
|
let lib: Value = serde_json::from_slice(&body).unwrap();
|
|
let mine = lib["games"].as_array().unwrap().iter().find(|g| g["id"] == id.as_str()).unwrap();
|
|
assert!(mine["states"]["2"].is_u64() && mine["save"].is_u64());
|
|
let (s, _, _) = call(&app, HttpRequest::delete(format!("/activity/api/state/{id}/2")).header(header::AUTHORIZATION, &bearer).body(Body::empty()).unwrap()).await;
|
|
assert_eq!(s, StatusCode::OK);
|
|
let _ = std::fs::remove_dir_all(activity::Activity::folder_for_tests(777_000_001));
|
|
}
|
|
|
|
const MAX_SAVE_FOR_TEST: usize = 256 * 1024;
|
|
}
|