Files
Oxicloud/src/interfaces/nextcloud/session.rs
T
Claude fdf445d2b0 perf: round 9 — decorator PUT reactivation, session/search/dedup alloc purges, PROPFIND join!, folder-level cascade
Benchmark-gated round (benches/ROUND9.md): every change carries a
BEFORE/AFTER bench with equivalence/safety gates; verdicts below are from
the committed harnesses on 4 cores / local PG 16.

Backend:
- Blob decorators (Retry/Cached) now forward put_blob_from_bytes_unsynced
  + sync_blobs — the trait default had silently reinstated HEAD-before-PUT
  per chunk on decorated remote stacks, undoing ROUND3 §8. Full production
  stack: 500 probes -> 0, 1.9x wall at 10 ms RTT (bench_s3_put §3).
- NC PROPFIND per-page enrichment triple (favorites / oc:fileid / dead
  props) overlapped with tokio::join!: 2.07x local, 2.86x at 5 ms RTT
  (bench_nc_enrich_join, injected-latency decide-by-bench).
- Search enrichment consumes its DTOs and carries the interned Arc<str>
  display fields end-to-end (SearchFileResultDto type change, OpenAPI
  shape preserved): enrich_file 2.0x, 11.6 -> 2.2 allocs/row; the NC
  REPORT conversion stops re-running all three classifiers per row
  (bench_search_enrich).
- NC session Arc end-to-end: SharedNcSession extractor (8 -> 0 allocs),
  Arc<FolderDto> chroot cache (4 -> 0/hit), single shared Arc<CurrentUser>
  + lazy span render (11 -> 6/build) (bench_nc_session).
- Storage micro-pack: atomic create_new chunk writes (2.1x fresh),
  stream_chunks over the manifest Arc (4097 -> 0 allocs/read incl. the
  Range path), manifest single-flight (herd 64 -> 1 loads), hex_lower for
  chunk Content-MD5 (18 -> 1 allocs) (bench_storage_micro).
- OCS capabilities memoized into OnceLock<[Bytes;2]>: 237x, 102 -> 0
  allocs/poll, byte-identical (bench_capabilities_static).
- Drive::is_empty COUNT(*) sum -> EXISTS: 34.4x on a 100k-file drive
  (bench_drive_is_empty).
- favorites/recents row-map ROUND7 port: path/name/blob_hash moved,
  -2.75 allocs/row (bench_resource_row_map §2).
- Folder rows decode binary UUIDs (ROUND6 §10 port): 1.03-1.07x page
  fetch, honest verdict incl. one noise-band wash documented
  (bench_folder_uuid_decode).
- Authz: file cascade decision decomposed into memoized folder-level
  decision + direct-grant lookup (ROUND8 deferred item). Cold shared-album
  first view 592 -> 418 µs/thumb; warm path unchanged; safety gates incl.
  new direct-grant sibling isolation, revoke-flush re-verified, full
  integration authz suite green (bench_thumbnail_cascade_cache).

Frontend (vitest gates committed beside the code):
- resolveLabel/resolveRecipient O(directory) scan -> id-keyed Map: 13.9x
  (recipients.bench.test.ts).
- ResourceList selection-prune effect skips when nothing is selected
  (100 -> 0 Set builds per drain) and the photos timeline reads a
  listener-fed mobile flag instead of matchMedia per recompute
  (listDerives.bench.test.ts).

Verification: cargo fmt + clippy --all-features --all-targets -D warnings
clean; 524 unit + 554 integration (--cfg integration_tests) tests pass;
frontend npm run check clean with 293 vitest tests green.

Deferred with rationale in ROUND9.md: CalDAV authz-before-fetch reorder
(maintainer sign-off), per-page batched parent resolution, JWT-claims
Arc<str>, batch_operations signature widening.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XDc9VtXvskJ6dnMRraSndn
2026-07-18 16:12:04 +00:00

162 lines
6.1 KiB
Rust

//! Per-request NextCloud session context.
//!
//! Bundles WHO the caller is, the raw wire username they presented,
//! and (for path-scoped endpoints) WHERE they're confined to. Built
//! by `basic_auth_middleware` and stashed in request extensions as
//! `Arc<NcSession>`; handlers extract it via [`SharedNcSession`]
//! (derefs to `NcSession`) — declare `session: SharedNcSession` in
//! the signature.
//!
//! ## Source of truth
//!
//! - `user`: authenticated identity (id, canonical username, role).
//! - `raw_username`: the opaque wire identifier from the Basic Auth
//! header. Today: plain `user` (single-drive) or `user~{drive_uuid}`
//! (multi-drive POC). May look different again when future auth
//! schemes land. **Handlers MUST NOT parse it** — it's used verbatim
//! only for echoing back into DAV/OCS URLs the client expects to
//! see (notably OCS `cloud/user`'s `id` field, which NC desktop
//! splices into every subsequent DAV path it builds) and for
//! audit logs.
//! - `chroot`: folder the request is jailed inside. `Some` for every
//! authenticated NC request today (the home folder when no drive
//! marker is present, or the resolved drive when one is). `None`
//! is reserved for future routes that don't operate on a single
//! folder (admin / cross-drive queries).
//!
//! ## Why this lives in middleware, not routes.rs
//!
//! The auth step already has every input needed (raw username from
//! header + drive marker after `~` + authenticated user). Resolving
//! the chroot there means every NC handler — DAV, OCS, uploads,
//! trashbin, sharees, … — gets a uniform `NcSession` regardless of
//! whether its URL carries a `{user}` segment. The URL `{user}`
//! segment becomes informational; the auth header is canonical.
use std::sync::Arc;
use axum::{
extract::FromRequestParts,
http::{StatusCode, request::Parts},
response::{IntoResponse, Response},
};
use crate::application::dtos::folder_dto::FolderDto;
use crate::interfaces::errors::AppError;
use crate::interfaces::middleware::auth::CurrentUser;
#[derive(Debug, Clone)]
pub struct NcSession {
/// Shared with the `Arc<CurrentUser>` request extension — one identity
/// build per request instead of a clone per consumer.
pub user: Arc<CurrentUser>,
pub raw_username: String,
/// Shared with `NC_CHROOT_CACHE` (markerless branch) — a cache hit is
/// an `Arc` bump, not a `FolderDto` deep-clone.
pub chroot: Option<Arc<FolderDto>>,
}
impl NcSession {
/// Return the chroot, or 500 if a path-scoped handler is reached
/// without one. Documents the invariant that every NC route
/// today is path-scoped — if this fires, route wiring is wrong.
pub fn require_chroot(&self) -> Result<&FolderDto, AppError> {
self.chroot.as_deref().ok_or_else(|| {
AppError::internal_error(
"NcSession: path-scoped handler reached without a chroot — route wiring bug",
)
})
}
/// True when the session is scoped to the user's home folder
/// (no drive marker in the Basic Auth username). Useful for
/// handlers that want to render a friendlier display when the
/// user is on their default drive.
pub fn is_home(&self) -> bool {
!self.raw_username.contains('~')
}
}
/// Pull the `{user}` segment out of a NC DAV URL.
///
/// Expected URL shapes:
/// - `/remote.php/dav/files/{user}` (root)
/// - `/remote.php/dav/files/{user}/{*subpath}`
/// - `/remote.php/dav/uploads/{user}/{upload_id}[/{*rest}]`
/// - `/remote.php/dav/trashbin/{user}[/{*subpath}]`
///
/// Returns `None` for anything that doesn't follow this shape (notably
/// the OCS surfaces, where there is no `{user}` segment to compare).
fn extract_url_user(path: &str) -> Option<String> {
let mut segments = path.split('/');
if !segments.next()?.is_empty() {
return None;
}
if segments.next()? != "remote.php" {
return None;
}
if segments.next()? != "dav" {
return None;
}
let _surface = segments.next()?; // files / uploads / trashbin
let user_seg = segments.next()?;
if user_seg.is_empty() {
return None;
}
urlencoding::decode(user_seg).ok().map(|s| s.into_owned())
}
/// Axum extractor: the shared handle to the request's [`NcSession`].
///
/// Derefs to `NcSession`, so handler bodies read `session.user`,
/// `session.require_chroot()`, … unchanged. Extraction is one `Arc`
/// refcount increment — the previous extractor deep-cloned the whole
/// session (`CurrentUser` + `raw_username` + chroot `FolderDto`, ~8-9
/// `String` allocs) on every authenticated NC request.
///
/// On path-scoped DAV routes (`/remote.php/dav/{files,uploads,
/// trashbin}/{user}/…`), the URL `{user}` segment is cross-checked
/// against `session.raw_username` and 403'd on mismatch. This is a
/// consistency check, NOT a security boundary — the chroot ACL
/// (`get_folder_with_perms`) is what actually prevents cross-user
/// access. It just surfaces malformed requests early (403) instead
/// of silently letting them through.
#[derive(Debug, Clone)]
pub struct SharedNcSession(Arc<NcSession>);
impl SharedNcSession {
/// Wrap an already-shared session (used by the bench harness; the
/// middleware inserts the `Arc` into request extensions directly).
pub fn from_arc(session: Arc<NcSession>) -> Self {
Self(session)
}
}
impl std::ops::Deref for SharedNcSession {
type Target = NcSession;
fn deref(&self) -> &NcSession {
&self.0
}
}
impl<S: Send + Sync> FromRequestParts<S> for SharedNcSession {
type Rejection = Response;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let session = parts
.extensions
.get::<Arc<NcSession>>()
.cloned()
.ok_or_else(|| StatusCode::UNAUTHORIZED.into_response())?;
if let Some(url_user) = extract_url_user(parts.uri.path())
&& url_user != session.raw_username
{
return Err(StatusCode::FORBIDDEN.into_response());
}
Ok(Self(session))
}
}