This commit is contained in:
2025-10-29 00:53:59 +01:00
parent 4b18429945
commit 3bdca88144
14 changed files with 122 additions and 91 deletions
+1 -48
View File
@@ -6,7 +6,6 @@ use chrono::{NaiveDateTime, Utc};
use diesel::prelude::*;
use rand::rngs::OsRng;
use rand::RngCore;
use serde_json::json;
use uuid::Uuid;
use crate::{
@@ -16,7 +15,6 @@ use crate::{
state::PgPooledConnection,
};
const WEB_DAV_SCOPE: &str = "webdav";
const TOKEN_PREFIX_LENGTH: usize = 12;
const TOKEN_SECRET_LENGTH: usize = 32;
@@ -30,16 +28,11 @@ pub fn create_webdav_token(
user_id: Uuid,
tenant_id: Uuid,
label: Option<String>,
scopes: Option<Vec<String>>,
expires_at: Option<NaiveDateTime>,
) -> Result<IssuedWebdavToken, AppError> {
let raw_secret = generate_secret()?;
let token_prefix = raw_secret[..TOKEN_PREFIX_LENGTH].to_string();
let token_hash = hash_secret(&raw_secret)?;
let scopes_value = scopes
.map(|scopes| json!(scopes))
.unwrap_or_else(|| json!([WEB_DAV_SCOPE]));
let new_token = NewWebdavToken {
id: Uuid::new_v4(),
user_id,
@@ -47,7 +40,6 @@ pub fn create_webdav_token(
token_prefix,
token_hash,
label,
scopes: scopes_value,
expires_at,
};
@@ -112,7 +104,7 @@ pub fn find_active_token_by_secret(
let candidates = query.load::<WebdavToken>(conn)?;
for token in candidates {
if verify_token_secret(secret, &token.token_hash)? && token_allows_webdav(&token.scopes) {
if verify_token_secret(secret, &token.token_hash)? {
return Ok(Some(token));
}
}
@@ -168,28 +160,6 @@ fn hash_secret(secret: &str) -> Result<String, AppError> {
Ok(hash.to_string())
}
pub fn parse_scopes(scopes: &serde_json::Value) -> Vec<String> {
match scopes {
serde_json::Value::Array(values) => values
.iter()
.filter_map(|value| value.as_str().map(|s| s.to_string()))
.collect(),
serde_json::Value::String(value) => value
.split(',')
.map(|s| s.trim())
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
.collect(),
_ => vec![],
}
}
pub fn token_allows_webdav(scopes: &serde_json::Value) -> bool {
parse_scopes(scopes)
.into_iter()
.any(|scope| scope == WEB_DAV_SCOPE)
}
fn _ensure_constants() {
assert!(TOKEN_PREFIX_LENGTH < TOKEN_SECRET_LENGTH * 2);
}
@@ -211,21 +181,4 @@ mod tests {
assert!(verify_token_secret(&secret, &hash).unwrap());
assert!(!verify_token_secret("wrong", &hash).unwrap());
}
#[test]
fn parse_scopes_handles_strings_and_arrays() {
let from_array = parse_scopes(&json!(["webdav", "other"]));
assert_eq!(from_array, vec!["webdav", "other"]);
let from_string = parse_scopes(&json!("webdav, other"));
assert_eq!(from_string, vec!["webdav", "other"]);
assert!(parse_scopes(&serde_json::Value::Null).is_empty());
}
#[test]
fn token_allows_webdav_matches_scope() {
assert!(token_allows_webdav(&json!(["webdav"])));
assert!(!token_allows_webdav(&json!(["api"])));
}
}