Compare commits
2 Commits
e8659f49d5
...
a9460c3750
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a9460c3750 | ||
| f3dba4c483 |
@ -1,10 +1,8 @@
|
||||
use crate::auth_persistence::AuthStorage;
|
||||
use crate::csrf::{CsrfState, set_csrf_cookie};
|
||||
use crate::items;
|
||||
use crate::proto_utils::Proto;
|
||||
use rocket::State;
|
||||
use rocket::futures::lock::Mutex;
|
||||
use rocket::http::CookieJar;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use uuid::Uuid;
|
||||
|
||||
@ -130,9 +128,7 @@ impl<'r> rocket::request::FromRequest<'r> for AdminToken {
|
||||
#[post("/login", data = "<request>")]
|
||||
pub async fn login(
|
||||
state: &State<AuthState>,
|
||||
csrf_state: &State<CsrfState>,
|
||||
user_list: &State<Mutex<Vec<crate::User>>>,
|
||||
jar: &CookieJar<'_>,
|
||||
request: Proto<items::LoginRequest>,
|
||||
) -> items::LoginResponse {
|
||||
let req = request.into_inner();
|
||||
@ -148,9 +144,6 @@ pub async fn login(
|
||||
tokens.insert(token.clone(), req.username.clone());
|
||||
state.storage.save_tokens(&tokens);
|
||||
|
||||
let csrf_token = csrf_state.generate_token();
|
||||
set_csrf_cookie(jar, &csrf_token);
|
||||
|
||||
return items::LoginResponse {
|
||||
token,
|
||||
success: true,
|
||||
@ -191,8 +184,6 @@ pub async fn logout(
|
||||
pub async fn get_auth_status(
|
||||
state: &State<AuthState>,
|
||||
admin_state: &State<AdminState>,
|
||||
csrf_state: &State<CsrfState>,
|
||||
jar: &CookieJar<'_>,
|
||||
request: Proto<items::AuthStatusRequest>,
|
||||
) -> items::AuthStatusResponse {
|
||||
let req = request.into_inner();
|
||||
@ -202,9 +193,6 @@ pub async fn get_auth_status(
|
||||
let admins = admin_state.admins.lock().await;
|
||||
let is_admin = crate::store::is_admin(username, &admins);
|
||||
|
||||
let csrf_token = csrf_state.generate_token();
|
||||
set_csrf_cookie(jar, &csrf_token);
|
||||
|
||||
items::AuthStatusResponse {
|
||||
authenticated: true,
|
||||
username: username.clone(),
|
||||
|
||||
@ -1,95 +0,0 @@
|
||||
use rocket::Build;
|
||||
use rocket::Request;
|
||||
use rocket::Rocket;
|
||||
use rocket::fairing::{Fairing, Info, Kind};
|
||||
use rocket::http::{Cookie, CookieJar, SameSite, Status};
|
||||
use rocket::request::{FromRequest, Outcome};
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
|
||||
const CSRF_COOKIE_NAME: &str = "csrf_token";
|
||||
const CSRF_HEADER_NAME: &str = "X-CSRF-Token";
|
||||
const CSRF_EXPIRATION_HOURS: u64 = 24;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CsrfToken(pub String);
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CsrfState {
|
||||
tokens: Arc<std::sync::Mutex<HashSet<String>>>,
|
||||
}
|
||||
|
||||
impl CsrfState {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
tokens: Arc::new(std::sync::Mutex::new(HashSet::new())),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn generate_token(&self) -> String {
|
||||
let token = Uuid::new_v4().to_string();
|
||||
self.tokens.lock().unwrap().insert(token.clone());
|
||||
token
|
||||
}
|
||||
|
||||
pub fn validate_token(&self, token: &str) -> bool {
|
||||
self.tokens.lock().unwrap().remove(token)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for CsrfState {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[rocket::async_trait]
|
||||
impl<'r> FromRequest<'r> for CsrfToken {
|
||||
type Error = ();
|
||||
|
||||
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
|
||||
let header_token = request.headers().get_one(CSRF_HEADER_NAME);
|
||||
let cookie_jar = request.guard::<&CookieJar<'_>>().await;
|
||||
|
||||
let cookie_token = match cookie_jar {
|
||||
Outcome::Success(jar) => jar
|
||||
.get(CSRF_COOKIE_NAME)
|
||||
.map(|c: &Cookie<'_>| c.value().to_string()),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
match (header_token, cookie_token) {
|
||||
(Some(header), Some(cookie)) if header == cookie => {
|
||||
Outcome::Success(CsrfToken(header.to_string()))
|
||||
}
|
||||
_ => Outcome::Error((Status::Forbidden, ())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CsrfFairing;
|
||||
|
||||
#[rocket::async_trait]
|
||||
impl Fairing for CsrfFairing {
|
||||
fn info(&self) -> Info {
|
||||
Info {
|
||||
name: "CSRF Protection",
|
||||
kind: Kind::Ignite,
|
||||
}
|
||||
}
|
||||
|
||||
async fn on_ignite(&self, rocket: Rocket<Build>) -> Result<Rocket<Build>, Rocket<Build>> {
|
||||
Ok(rocket.manage(CsrfState::new()))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_csrf_cookie(jar: &CookieJar<'_>, token: &str) {
|
||||
jar.add(
|
||||
Cookie::build((CSRF_COOKIE_NAME, token.to_owned()))
|
||||
.http_only(true)
|
||||
.same_site(SameSite::Strict)
|
||||
.max_age(rocket::time::Duration::hours(CSRF_EXPIRATION_HOURS as i64))
|
||||
.path("/"),
|
||||
);
|
||||
}
|
||||
@ -7,13 +7,11 @@ pub mod items {
|
||||
|
||||
pub mod auth;
|
||||
pub mod auth_persistence;
|
||||
pub mod csrf;
|
||||
pub mod proto_utils;
|
||||
pub mod security_headers;
|
||||
pub mod store;
|
||||
pub mod validation;
|
||||
|
||||
pub use auth::AdminState;
|
||||
pub use csrf::{CsrfFairing, CsrfState, CsrfToken, set_csrf_cookie};
|
||||
pub use security_headers::SecurityHeaders;
|
||||
pub use store::User;
|
||||
|
||||
@ -4,7 +4,6 @@ use rocket::futures::lock::Mutex;
|
||||
|
||||
use backend::auth;
|
||||
use backend::auth::AdminState;
|
||||
use backend::csrf::{CsrfFairing, CsrfToken};
|
||||
use backend::items::{self, Game};
|
||||
use backend::proto_utils;
|
||||
use backend::security_headers::SecurityHeaders;
|
||||
@ -90,7 +89,6 @@ async fn get_games(
|
||||
#[post("/game", data = "<game>", rank = 1)]
|
||||
async fn add_game(
|
||||
_token: auth::Token,
|
||||
_csrf: CsrfToken,
|
||||
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
||||
user_list: &rocket::State<Mutex<Vec<User>>>,
|
||||
game: proto_utils::Proto<items::Game>,
|
||||
@ -133,7 +131,6 @@ async fn add_game(
|
||||
#[patch("/game", data = "<game>", rank = 1)]
|
||||
async fn update_game(
|
||||
_token: auth::AdminToken,
|
||||
_csrf: CsrfToken,
|
||||
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
||||
user_list: &rocket::State<Mutex<Vec<User>>>,
|
||||
game: proto_utils::Proto<items::Game>,
|
||||
@ -196,7 +193,6 @@ async fn update_game(
|
||||
#[delete("/game/<title>", rank = 1)]
|
||||
async fn delete_game(
|
||||
_token: auth::AdminToken,
|
||||
_csrf: CsrfToken,
|
||||
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
||||
user_list: &rocket::State<Mutex<Vec<User>>>,
|
||||
title: &str,
|
||||
@ -227,7 +223,6 @@ async fn delete_game(
|
||||
#[post("/refresh", rank = 1)]
|
||||
async fn refresh_state(
|
||||
_token: auth::AdminToken,
|
||||
_csrf: CsrfToken,
|
||||
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
||||
user_list: &rocket::State<Mutex<Vec<User>>>,
|
||||
admin_state: &rocket::State<AdminState>,
|
||||
@ -256,7 +251,6 @@ async fn refresh_state(
|
||||
#[post("/opinion", data = "<req>", rank = 1)]
|
||||
async fn add_opinion(
|
||||
token: auth::Token,
|
||||
_csrf: CsrfToken,
|
||||
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
||||
user_list: &rocket::State<Mutex<Vec<User>>>,
|
||||
req: proto_utils::Proto<items::AddOpinionRequest>,
|
||||
@ -309,7 +303,6 @@ async fn add_opinion(
|
||||
#[patch("/opinion", data = "<req>", rank = 1)]
|
||||
async fn remove_opinion(
|
||||
token: auth::Token,
|
||||
_csrf: CsrfToken,
|
||||
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
||||
user_list: &rocket::State<Mutex<Vec<User>>>,
|
||||
req: proto_utils::Proto<items::RemoveOpinionRequest>,
|
||||
@ -495,7 +488,6 @@ async fn main() -> Result<(), std::io::Error> {
|
||||
|
||||
rocket::build()
|
||||
.attach(SecurityHeaders)
|
||||
.attach(CsrfFairing)
|
||||
.manage(Mutex::new(user_list))
|
||||
.manage(auth::AuthState::new())
|
||||
.manage(auth::AdminState::new())
|
||||
|
||||
22
frontend/pnpm-lock.yaml
generated
22
frontend/pnpm-lock.yaml
generated
@ -29,7 +29,7 @@ importers:
|
||||
version: 9.39.2
|
||||
'@types/node':
|
||||
specifier: ^24.10.7
|
||||
version: 24.10.7
|
||||
version: 24.10.9
|
||||
'@types/react':
|
||||
specifier: ^19.2.8
|
||||
version: 19.2.8
|
||||
@ -38,7 +38,7 @@ importers:
|
||||
version: 19.2.3(@types/react@19.2.8)
|
||||
'@vitejs/plugin-react':
|
||||
specifier: ^5.1.2
|
||||
version: 5.1.2(rolldown-vite@7.2.5(@types/node@24.10.7))
|
||||
version: 5.1.2(rolldown-vite@7.2.5(@types/node@24.10.9))
|
||||
eslint:
|
||||
specifier: ^9.39.2
|
||||
version: 9.39.2
|
||||
@ -62,7 +62,7 @@ importers:
|
||||
version: 8.53.0(eslint@9.39.2)(typescript@5.9.3)
|
||||
vite:
|
||||
specifier: npm:rolldown-vite@7.2.5
|
||||
version: rolldown-vite@7.2.5(@types/node@24.10.7)
|
||||
version: rolldown-vite@7.2.5(@types/node@24.10.9)
|
||||
|
||||
packages:
|
||||
|
||||
@ -351,8 +351,8 @@ packages:
|
||||
'@types/json-schema@7.0.15':
|
||||
resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==}
|
||||
|
||||
'@types/node@24.10.7':
|
||||
resolution: {integrity: sha512-+054pVMzVTmRQV8BhpGv3UyfZ2Llgl8rdpDTon+cUH9+na0ncBVXj3wTUKh14+Kiz18ziM3b4ikpP5/Pc0rQEQ==}
|
||||
'@types/node@24.10.9':
|
||||
resolution: {integrity: sha512-ne4A0IpG3+2ETuREInjPNhUGis1SFjv1d5asp8MzEAGtOZeTeHVDOYqOgqfhvseqg/iXty2hjBf1zAOb7RNiNw==}
|
||||
|
||||
'@types/react-dom@19.2.3':
|
||||
resolution: {integrity: sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==}
|
||||
@ -425,7 +425,7 @@ packages:
|
||||
resolution: {integrity: sha512-EcA07pHJouywpzsoTUqNh5NwGayl2PPVEJKUSinGGSxFGYn+shYbqMGBg6FXDqgXum9Ou/ecb+411ssw8HImJQ==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
peerDependencies:
|
||||
vite: ^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0
|
||||
vite: npm:rolldown-vite@7.2.5
|
||||
|
||||
acorn-jsx@5.3.2:
|
||||
resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==}
|
||||
@ -1347,7 +1347,7 @@ snapshots:
|
||||
|
||||
'@types/json-schema@7.0.15': {}
|
||||
|
||||
'@types/node@24.10.7':
|
||||
'@types/node@24.10.9':
|
||||
dependencies:
|
||||
undici-types: 7.16.0
|
||||
|
||||
@ -1450,7 +1450,7 @@ snapshots:
|
||||
'@typescript-eslint/types': 8.53.0
|
||||
eslint-visitor-keys: 4.2.1
|
||||
|
||||
'@vitejs/plugin-react@5.1.2(rolldown-vite@7.2.5(@types/node@24.10.7))':
|
||||
'@vitejs/plugin-react@5.1.2(rolldown-vite@7.2.5(@types/node@24.10.9))':
|
||||
dependencies:
|
||||
'@babel/core': 7.28.6
|
||||
'@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/core@7.28.6)
|
||||
@ -1458,7 +1458,7 @@ snapshots:
|
||||
'@rolldown/pluginutils': 1.0.0-beta.53
|
||||
'@types/babel__core': 7.20.5
|
||||
react-refresh: 0.18.0
|
||||
vite: rolldown-vite@7.2.5(@types/node@24.10.7)
|
||||
vite: rolldown-vite@7.2.5(@types/node@24.10.9)
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
@ -1864,7 +1864,7 @@ snapshots:
|
||||
|
||||
resolve-from@4.0.0: {}
|
||||
|
||||
rolldown-vite@7.2.5(@types/node@24.10.7):
|
||||
rolldown-vite@7.2.5(@types/node@24.10.9):
|
||||
dependencies:
|
||||
'@oxc-project/runtime': 0.97.0
|
||||
fdir: 6.5.0(picomatch@4.0.3)
|
||||
@ -1874,7 +1874,7 @@ snapshots:
|
||||
rolldown: 1.0.0-beta.50
|
||||
tinyglobby: 0.2.15
|
||||
optionalDependencies:
|
||||
'@types/node': 24.10.7
|
||||
'@types/node': 24.10.9
|
||||
fsevents: 2.3.3
|
||||
|
||||
rolldown@1.0.0-beta.50:
|
||||
|
||||
@ -1,26 +1,16 @@
|
||||
import { AuthStatusRequest, AuthStatusResponse } from "../items";
|
||||
|
||||
export const getCsrfToken = (): string | null => {
|
||||
const match = document.cookie.match(/csrf_token=([^;]+)/);
|
||||
return match ? decodeURIComponent(match[1]) : null;
|
||||
};
|
||||
|
||||
export const apiFetch = async (
|
||||
url: string,
|
||||
options: RequestInit = {}
|
||||
): Promise<Response> => {
|
||||
const token = localStorage.getItem("token");
|
||||
const csrfToken = getCsrfToken();
|
||||
const headers = new Headers(options.headers);
|
||||
|
||||
if (token) {
|
||||
headers.set("Authorization", `Bearer ${token}`);
|
||||
}
|
||||
|
||||
if (csrfToken) {
|
||||
headers.set("X-CSRF-Token", csrfToken);
|
||||
}
|
||||
|
||||
const config = {
|
||||
...options,
|
||||
headers,
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user