fix share password issues

This commit is contained in:
2025-09-06 19:19:54 +02:00
parent 5c09120c23
commit a0c90f57d5
11 changed files with 256 additions and 54 deletions

View File

@@ -60,6 +60,9 @@ pub trait WarrenMetrics: Clone + Send + Sync + 'static {
fn record_warren_share_cat_success(&self) -> impl Future<Output = ()> + Send;
fn record_warren_share_cat_failure(&self) -> impl Future<Output = ()> + Send;
fn record_warren_share_password_verification_success(&self) -> impl Future<Output = ()> + Send;
fn record_warren_share_password_verification_failure(&self) -> impl Future<Output = ()> + Send;
}
pub trait FileSystemMetrics: Clone + Send + Sync + 'static {

View File

@@ -25,6 +25,7 @@ use super::models::{
DeleteShareError, DeleteShareRequest, DeleteShareResponse, GetShareError, GetShareRequest,
GetShareResponse, ListSharesError, ListSharesRequest, ListSharesResponse, ShareCatError,
ShareCatRequest, ShareCatResponse, ShareLsError, ShareLsRequest, ShareLsResponse,
VerifySharePasswordError, VerifySharePasswordRequest, VerifySharePasswordResponse,
},
user::{
CreateUserError, CreateUserRequest, DeleteUserError, DeleteUserRequest, EditUserError,
@@ -138,6 +139,10 @@ pub trait WarrenService: Clone + Send + Sync + 'static {
&self,
request: ShareCatRequest,
) -> impl Future<Output = Result<ShareCatResponse, ShareCatError>> + Send;
fn verify_warren_share_password(
&self,
request: VerifySharePasswordRequest,
) -> impl Future<Output = Result<VerifySharePasswordResponse, VerifySharePasswordError>> + Send;
}
pub trait FileSystemService: Clone + Send + Sync + 'static {

View File

@@ -5,7 +5,7 @@ use crate::domain::warren::models::{
file::{AbsoluteFilePath, AbsoluteFilePathList, LsResponse},
share::{
CreateShareResponse, DeleteShareResponse, GetShareResponse, ListSharesResponse,
ShareCatResponse, ShareLsResponse,
ShareCatResponse, ShareLsResponse, VerifySharePasswordResponse,
},
user::{ListAllUsersAndWarrensResponse, LoginUserOidcResponse, LoginUserResponse, User},
user_warren::UserWarren,
@@ -64,6 +64,10 @@ pub trait WarrenNotifier: Clone + Send + Sync + 'static {
) -> impl Future<Output = ()> + Send;
fn warren_share_ls(&self, response: &ShareLsResponse) -> impl Future<Output = ()> + Send;
fn warren_share_cat(&self, response: &ShareCatResponse) -> impl Future<Output = ()> + Send;
fn warren_share_password_verified(
&self,
response: &VerifySharePasswordResponse,
) -> impl Future<Output = ()> + Send;
}
pub trait FileSystemNotifier: Clone + Send + Sync + 'static {

View File

@@ -6,7 +6,8 @@ use crate::domain::warren::{
DeleteShareRequest, DeleteShareResponse, GetShareError, GetShareRequest,
GetShareResponse, ListSharesError, ListSharesRequest, ListSharesResponse, Share,
ShareCatError, ShareCatRequest, ShareCatResponse, ShareLsError, ShareLsRequest,
ShareLsResponse,
ShareLsResponse, VerifySharePasswordError, VerifySharePasswordRequest,
VerifySharePasswordResponse,
},
warren::{
CreateWarrenError, CreateWarrenRequest, DeleteWarrenError, DeleteWarrenRequest,
@@ -528,4 +529,24 @@ where
Ok(response)
}
async fn verify_warren_share_password(
&self,
request: VerifySharePasswordRequest,
) -> Result<VerifySharePasswordResponse, VerifySharePasswordError> {
let result = self.repository.verify_warren_share_password(request).await;
if let Ok(response) = result.as_ref() {
self.metrics
.record_warren_share_password_verification_success()
.await;
self.notifier.warren_share_password_verified(response).await;
} else {
self.metrics
.record_warren_share_password_verification_failure()
.await;
}
result
}
}

View File

@@ -13,6 +13,7 @@ use crate::{
},
inbound::http::{
AppState,
handlers::extractors::SharePasswordHeader,
responses::{ApiError, ApiSuccess},
},
};
@@ -59,17 +60,14 @@ impl From<ParseShareLsHttpRequestError> for ApiError {
pub(super) struct LsShareHttpRequestBody {
share_id: Uuid,
path: String,
password: Option<String>,
}
impl LsShareHttpRequestBody {
fn try_into_domain(self) -> Result<ShareLsRequest, ParseShareLsHttpRequestError> {
fn try_into_domain(
self,
password: Option<SharePassword>,
) -> Result<ShareLsRequest, ParseShareLsHttpRequestError> {
let path = FilePath::new(&self.path)?.try_into()?;
let password = if let Some(password) = self.password.as_ref() {
Some(SharePassword::new(password)?)
} else {
None
};
Ok(ShareLsRequest::new(self.share_id, path, password))
}
@@ -98,9 +96,10 @@ impl From<ShareLsResponse> for ShareLsResponseData {
pub async fn ls_share<WS: WarrenService, AS: AuthService>(
State(state): State<AppState<WS, AS>>,
SharePasswordHeader(password): SharePasswordHeader,
Json(request): Json<LsShareHttpRequestBody>,
) -> Result<ApiSuccess<ShareLsResponseData>, ApiError> {
let domain_request = request.try_into_domain()?;
let domain_request = request.try_into_domain(password)?;
state
.warren_service

View File

@@ -7,6 +7,7 @@ mod list_shares;
mod list_warrens;
mod ls_share;
mod upload_warren_files;
mod verify_share_password;
mod warren_cat;
mod warren_cp;
mod warren_ls;
@@ -37,6 +38,7 @@ use get_share::get_share;
use list_shares::list_shares;
use ls_share::ls_share;
use upload_warren_files::warren_save;
use verify_share_password::verify_share_password;
use warren_cat::fetch_file;
use warren_cp::warren_cp;
use warren_mv::warren_mv;
@@ -116,4 +118,5 @@ pub fn routes<WS: WarrenService, AS: AuthService>() -> Router<AppState<WS, AS>>
.route("/files/get_share", post(get_share))
.route("/files/ls_share", post(ls_share))
.route("/files/cat_share", get(cat_share))
.route("/files/verify_share_password", post(verify_share_password))
}

View File

@@ -0,0 +1,72 @@
use axum::{Json, extract::State, http::StatusCode};
use serde::Deserialize;
use thiserror::Error;
use uuid::Uuid;
use crate::{
domain::warren::{
models::share::{SharePassword, SharePasswordError, VerifySharePasswordRequest},
ports::{AuthService, WarrenService},
},
inbound::http::{
AppState,
responses::{ApiError, ApiSuccess},
},
};
#[derive(Debug, Error)]
enum ParseVerifySharePasswordHttpRequestError {
#[error(transparent)]
SharePassword(#[from] SharePasswordError),
}
impl From<ParseVerifySharePasswordHttpRequestError> for ApiError {
fn from(value: ParseVerifySharePasswordHttpRequestError) -> Self {
match value {
ParseVerifySharePasswordHttpRequestError::SharePassword(err) => Self::BadRequest(
match err {
SharePasswordError::Empty => "The provided password is empty",
SharePasswordError::LeadingWhitespace
| SharePasswordError::TrailingWhitespace
| SharePasswordError::TooShort
| SharePasswordError::TooLong => "",
}
.to_string(),
),
}
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct VerifySharePasswordHttpRequestBody {
share_id: Uuid,
password: String,
}
impl VerifySharePasswordHttpRequestBody {
fn try_into_domain(
self,
) -> Result<VerifySharePasswordRequest, ParseVerifySharePasswordHttpRequestError> {
let password = SharePassword::new(&self.password)?;
Ok(VerifySharePasswordRequest::new(
self.share_id,
Some(password),
))
}
}
pub async fn verify_share_password<WS: WarrenService, AS: AuthService>(
State(state): State<AppState<WS, AS>>,
Json(request): Json<VerifySharePasswordHttpRequestBody>,
) -> Result<ApiSuccess<()>, ApiError> {
let domain_request = request.try_into_domain()?;
state
.warren_service
.verify_warren_share_password(domain_request)
.await
.map(|_| ApiSuccess::new(StatusCode::OK, ()))
.map_err(ApiError::from)
}

View File

@@ -151,6 +151,13 @@ impl WarrenMetrics for MetricsDebugLogger {
async fn record_warren_share_cat_failure(&self) {
tracing::debug!("[Metrics] Warren share cat failed");
}
async fn record_warren_share_password_verification_success(&self) {
tracing::debug!("[Metrics] Warren share password verification succeeded");
}
async fn record_warren_share_password_verification_failure(&self) {
tracing::debug!("[Metrics] Warren share password verification failed");
}
}
impl FileSystemMetrics for MetricsDebugLogger {

View File

@@ -11,7 +11,7 @@ use crate::domain::{
file::{AbsoluteFilePath, AbsoluteFilePathList, LsResponse},
share::{
CreateShareResponse, DeleteShareResponse, GetShareResponse, ListSharesResponse,
ShareCatResponse, ShareLsResponse,
ShareCatResponse, ShareLsResponse, VerifySharePasswordResponse,
},
user::{
ListAllUsersAndWarrensResponse, LoginUserOidcResponse, LoginUserResponse, User,
@@ -201,6 +201,13 @@ impl WarrenNotifier for NotifierDebugLogger {
response.share().id(),
);
}
async fn warren_share_password_verified(&self, response: &VerifySharePasswordResponse) {
tracing::debug!(
"[Notifier] Verified password for share {}",
response.share().id()
);
}
}
impl FileSystemNotifier for NotifierDebugLogger {

View File

@@ -120,19 +120,24 @@ export async function listShareFiles(
| { success: true; files: DirectoryEntry[]; parent: DirectoryEntry | null }
| { success: false }
> {
const { data } = await useFetch<
const { data, error } = await useFetch<
ApiResponse<{ files: DirectoryEntry[]; parent: DirectoryEntry | null }>
>(getApiUrl('warrens/files/ls_share'), {
method: 'POST',
headers: getApiHeaders(),
// This is only required for development
headers:
password != null
? { ...getApiHeaders(), 'X-Share-Password': password }
: getApiHeaders(),
body: JSON.stringify({
shareId: shareId,
path: path,
password: password,
}),
});
if (data.value == null) {
const errorMessage = await error.value?.data;
console.log(errorMessage);
return {
success: false,
};
@@ -174,3 +179,32 @@ export async function fetchShareFile(
data: data.value,
};
}
export async function verifySharePassword(
shareId: string,
password: string
): Promise<{ success: boolean }> {
const { data } = await useFetch<ApiResponse<null>>(
getApiUrl(`warrens/files/verify_share_password`),
{
method: 'POST',
headers: getApiHeaders(),
body: JSON.stringify({
shareId: shareId,
password: password,
}),
responseType: 'json',
cache: 'default',
}
);
if (data.value == null || data.value.status !== 200) {
return {
success: false,
};
}
return {
success: true,
};
}

View File

@@ -1,5 +1,12 @@
<script lang="ts" setup>
import { fetchShareFile, getShare, listShareFiles } from '~/lib/api/shares';
import byteSize from 'byte-size';
import { toast } from 'vue-sonner';
import {
fetchShareFile,
getShare,
listShareFiles,
verifySharePassword,
} from '~/lib/api/shares';
import type { DirectoryEntry } from '~/shared/types';
import type { Share } from '~/shared/types/shares';
import { useImageViewer, useTextEditor } from '~/stores/viewers';
@@ -60,25 +67,14 @@ async function getShareFromQuery(): Promise<{
}
async function submitPassword() {
loadFiles();
}
async function loadFiles() {
if (loading.value || share == null || warrenStore.current == null) {
return;
}
if (share.file.fileType !== 'directory') {
if (share == null || loading.value) {
return;
}
if (!passwordValid.value) {
loading.value = true;
const result = await listShareFiles(
share.data.id,
warrenStore.current.path,
password.value.length > 0 ? password.value : null
);
const result = await verifySharePassword(share.data.id, password.value);
loading.value = false;
if (result.success) {
passwordValid.value = true;
@@ -92,7 +88,34 @@ async function loadFiles() {
}
document.cookie = cookie;
} else {
toast.error('Share', {
id: 'SHARE_PASSWORD_TOAST',
description: 'Invalid password',
});
return;
}
}
if (share.file.fileType === 'directory') {
loadFiles();
}
}
async function loadFiles() {
if (loading.value || share == null || warrenStore.current == null) {
return;
}
loading.value = true;
const result = await listShareFiles(
share.data.id,
warrenStore.current.path,
password.value.length > 0 ? password.value : null
);
if (result.success) {
warrenStore.setCurrentWarrenEntries(result.files, result.parent);
}
@@ -102,7 +125,11 @@ async function loadFiles() {
async function onEntryClicked(entry: DirectoryEntry, event: MouseEvent) {
event.stopPropagation();
if (warrenStore.current == null) {
if (
warrenStore.current == null ||
share == null ||
(share.data.password && !passwordValid.value)
) {
return;
}
@@ -110,7 +137,10 @@ async function onEntryClicked(entry: DirectoryEntry, event: MouseEvent) {
return;
}
const entryPath = joinPaths(warrenStore.current.path, entry.name);
const entryPath =
entry !== share.file
? joinPaths(warrenStore.current.path, entry.name)
: warrenStore.current.path;
if (entry.fileType === 'directory') {
warrenStore.setCurrentWarrenPath(entryPath);
@@ -217,17 +247,35 @@ function onEntryDownload(entry: DirectoryEntry) {
>
<div
:class="[
'h-[min(98vh,600px)] w-full max-w-screen-xl rounded-lg border transition-all',
passwordValid ? 'max-w-screen-xl' : 'max-w-lg',
'w-full rounded-lg border transition-all',
passwordValid && share.file.fileType === 'directory'
? 'h-[min(98vh,600px)] max-w-screen-xl'
: 'max-w-2xl',
]"
>
<div
class="flex flex-row items-center justify-between gap-4 px-6 pt-6"
<div class="flex flex-row items-center justify-between gap-4 p-6">
<button
:disabled="share.data.password && !passwordValid"
:class="[
'flex min-w-0 grow flex-row items-center gap-2 text-left',
(!share.data.password || passwordValid) &&
'cursor-pointer',
]"
@click="(e) => onEntryClicked(share!.file, e)"
>
<div class="flex w-full flex-row">
<div class="flex grow flex-col gap-1.5">
<h3 class="leading-none font-semibold">Share</h3>
<p class="text-muted-foreground text-sm">
<DirectoryEntryIcon :entry="share.file" />
<div class="flex flex-col overflow-hidden">
<h3
:title="share.file.name"
class="truncate leading-none font-semibold"
>
{{ share.file.name }}
</h3>
<p class="text-muted-foreground text-sm text-nowrap">
{{ byteSize(share.file.size) }}
</p>
<p class="text-muted-foreground text-sm text-nowrap">
Created
{{
$dayjs(share.data.createdAt).format(
@@ -236,19 +284,12 @@ function onEntryDownload(entry: DirectoryEntry) {
}}
</p>
</div>
<div class="flex flex-row items-center justify-end gap-4">
<p>{{ share.file.name }}</p>
<DirectoryEntryIcon
:entry="{ ...share.file, name: '/' }"
/>
</div>
</div>
</button>
<div class="flex flex-row items-end">
<Button
:class="
share.file.fileType !== 'file' &&
entries == null &&
'hidden'
share.data.password && !passwordValid && 'hidden'
"
size="icon"
variant="outline"
@@ -258,7 +299,13 @@ function onEntryDownload(entry: DirectoryEntry) {
</div>
</div>
<div class="flex w-full flex-col p-6">
<div
v-if="
share.file.fileType === 'directory' ||
(share.data.password && !passwordValid)
"
class="flex w-full flex-col px-6 pb-6"
>
<DirectoryList
v-if="entries != null"
:entries