cloudillo-core 0.8.18

Core infrastructure for the Cloudillo platform: middleware, extractors, scheduler, rate limiting, and access control
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
// SPDX-FileCopyrightText: Szilárd Hajba
// SPDX-License-Identifier: LGPL-3.0-or-later

//! File access level helpers
//!
//! Provides functions to determine user access levels to files based on:
//! - Scoped tokens (file:{file_id}:{R|C|W} grants Read/Comment/Write access)
//! - Ownership (owner has Admin access — write, plus share management)
//! - FSHR action grants, but only from the file's owner (ADMIN subtype = Admin, WRITE = Write,
//!   COMMENT = Comment, else Read)

use std::sync::Arc;

use crate::dir_cache::{DirCache, DirEntry};
use crate::prelude::*;
use cloudillo_types::meta_adapter;
use cloudillo_types::meta_adapter::FileView;
use cloudillo_types::types::{AccessLevel, TokenScope};

/// Maximum parent-chain depth for bounded folder-tree traversals.
pub const MAX_PARENT_DEPTH: usize = 64;

/// Result of checking file access
pub struct FileAccessResult {
	pub file_view: FileView,
	pub access_level: AccessLevel,
	pub read_only: bool,
}

/// Error type for file access checks
pub enum FileAccessError {
	NotFound,
	AccessDenied,
	InternalError(String),
}

/// Context describing the subject requesting file access
pub struct FileAccessCtx<'a> {
	pub user_id_tag: &'a str,
	pub tenant_id_tag: &'a str,
	pub user_roles: &'a [Box<str>],
}

/// Resolve one `(tn, file_id)` → `DirEntry` through the folder cache, falling back
/// to a single `read_file` on a miss. The row is cached **only when it is a folder**
/// (`is_folder`), keeping the cache small and folder-only; non-folder rows (e.g. the
/// leaf that starts a descendant walk) are returned but never inserted.
///
/// Propagates read errors as `Err` so request-path callers can surface a genuine
/// fault as 5xx instead of mistaking it for "missing / not a descendant".
pub async fn resolve_dir_entry(
	meta: &Arc<dyn meta_adapter::MetaAdapter>,
	cache: &DirCache,
	tn_id: TnId,
	file_id: &str,
) -> ClResult<Option<DirEntry>> {
	if let Some(entry) = cache.get(tn_id, file_id) {
		return Ok(Some(entry)); // cached ⇒ folder
	}
	match meta.read_file(tn_id, file_id).await? {
		Some(view) => {
			let is_folder = view.file_tp.as_deref() == Some("FLDR");
			let entry = DirEntry {
				parent_id: view.parent_id.clone(),
				name: view.file_name.clone(),
				is_folder,
			};
			if is_folder {
				cache.put(tn_id, file_id, entry.clone());
			}
			Ok(Some(entry))
		}
		None => Ok(None),
	}
}

/// Walk the parent chain of a file to find an inherited share entry.
///
/// Checks each ancestor's share_access for the given user. Returns the first
/// (closest ancestor) match's access level, or None if no ancestor is shared.
/// Bounded to `MAX_PARENT_DEPTH` levels to prevent runaway traversal.
///
/// This is one of the single, cache-backed parent-chain walkers: every hop goes
/// through `resolve_dir_entry`, memoizing folder rows in the shared `DirCache`.
pub async fn walk_parent_chain_for_share(
	app: &App,
	tn_id: TnId,
	file_id: &str,
	user_id_tag: &str,
) -> Option<AccessLevel> {
	// DirCache is a required process-wide extension registered at app build (see
	// crates/cloudillo/src/app.rs); a missing cache means misconfiguration, so log
	// rather than silently dropping inherited-share access.
	let Ok(cache) = app.ext::<DirCache>() else {
		warn!("DirCache extension missing; skipping inherited-share parent walk");
		return None;
	};
	let mut current_id = file_id.to_string();
	for _ in 0..MAX_PARENT_DEPTH {
		// Best-effort: a read error ends the walk (treated as no inherited share).
		let Ok(Some(entry)) = resolve_dir_entry(&app.meta_adapter, cache, tn_id, &current_id).await
		else {
			break;
		};
		let Some(parent_id) = entry.parent_id else { break };
		if let Ok(Some(perm)) = app
			.meta_adapter
			.check_share_access(tn_id, 'F', &parent_id, 'U', user_id_tag)
			.await
		{
			return Some(AccessLevel::from_perm_char(perm));
		}
		current_id = parent_id.to_string();
	}
	None
}

/// Return true if `ancestor_id` is an ancestor folder of `file_id`.
///
/// Walks the `parent_id` chain upward from `file_id`, bounded to
/// `MAX_PARENT_DEPTH` levels to prevent runaway traversal. Used to extend
/// file-scope tokens (folder share links) to every descendant of a shared
/// folder. The file itself is not considered its own descendant — callers
/// handle the direct match separately.
///
/// Propagates read errors as `Err` so callers on request paths can surface a
/// genuine fault as 5xx instead of silently treating it as "not a descendant".
///
/// This is one of the single, cache-backed parent-chain walkers: every hop goes
/// through `resolve_dir_entry`, memoizing folder rows in the shared `DirCache`.
pub async fn is_descendant_of(
	meta: &Arc<dyn meta_adapter::MetaAdapter>,
	cache: &DirCache,
	tn_id: TnId,
	file_id: &str,
	ancestor_id: &str,
) -> ClResult<bool> {
	let mut current_id = file_id.to_string();
	for _ in 0..MAX_PARENT_DEPTH {
		let Some(entry) = resolve_dir_entry(meta, cache, tn_id, &current_id).await? else {
			break;
		};
		let Some(parent_id) = entry.parent_id else { break };
		if parent_id.as_ref() == ancestor_id {
			return Ok(true);
		}
		current_id = parent_id.to_string();
	}
	Ok(false)
}

/// Return true if the scoped target file is a folder (`file_tp == "FLDR"`).
///
/// Used to gate the folder-subtree extension of a file-scope token: only a
/// scope whose target is an actual folder grants access across its `parent_id`
/// descendants. Answered straight from the folder cache via `resolve_dir_entry`:
/// returns `Ok(true)` only for an existing `FLDR` row, `Ok(false)` for a missing
/// or non-folder row, and `Err` for a genuine read fault so request-path callers
/// that can return 5xx surface the fault instead of masking it as "not a folder".
pub async fn scope_target_is_folder(
	meta: &Arc<dyn meta_adapter::MetaAdapter>,
	cache: &DirCache,
	tn_id: TnId,
	scope_file_id: &str,
) -> ClResult<bool> {
	Ok(resolve_dir_entry(meta, cache, tn_id, scope_file_id)
		.await?
		.is_some_and(|e| e.is_folder))
}

/// Check if a user has share access to a file — either a direct share entry
/// on the file itself or an inherited share from an ancestor folder.
pub async fn check_share_for_file(
	app: &App,
	tn_id: TnId,
	file_id: &str,
	user_id_tag: &str,
) -> Option<AccessLevel> {
	if let Ok(Some(perm)) =
		app.meta_adapter.check_share_access(tn_id, 'F', file_id, 'U', user_id_tag).await
	{
		return Some(AccessLevel::from_perm_char(perm));
	}
	walk_parent_chain_for_share(app, tn_id, file_id, user_id_tag).await
}

/// Access level granted purely by community-role membership on a *tenant-owned*
/// file. Only roles from `crate::roles::ROLE_HIERARCHY` count.
///
/// Membership is matched explicitly rather than by testing "the role slice is
/// non-empty": a `[""]` slice reads as "has a role" and would hand every
/// federated stranger Read access. Second defence behind `roles::parse_roles`,
/// which drops empty segments.
pub fn role_access_level(user_roles: &[Box<str>]) -> AccessLevel {
	// A leader resolves to `Admin`, not `Write`: leadership over a tenant-owned file *is* the right
	// to manage its share set, so `access_level` alone answers "may manage shares".
	if user_roles.iter().any(|r| r.as_ref() == "leader") {
		return AccessLevel::Admin;
	}
	if user_roles.iter().any(|r| matches!(r.as_ref(), "moderator" | "contributor")) {
		return AccessLevel::Write;
	}
	if user_roles
		.iter()
		.any(|r| matches!(r.as_ref(), "public" | "follower" | "supporter"))
	{
		return AccessLevel::Read;
	}
	AccessLevel::None
}

/// Resolve the grant an `FSHR:{file_id}:{audience}` action row carries: `ADMIN` → Admin, `WRITE` →
/// Write, `COMMENT` → Comment, `DEL` → None (a revocation is not a grant), anything else → Read.
///
/// An FSHR is a *claim by its issuer* that they granted access, so only the file's owner can make
/// it credibly. Without the issuer test the row is a self-service grant: `POST /api/actions` is
/// gated only by the `contributor` role, the action DSL's `key_pattern` builds the key straight
/// from the client's `subject` and `aud`, and hooks run *after* the row is stored with no rollback,
/// so `fshr::on_create` rejecting the write leaves the row behind. Federated peers can post such a
/// token to the inbox just as easily.
///
/// Both live paths survive the test: on the recipient's node `fshr::on_accept` creates the file row
/// with `owner_tag = issuer`, and on the owner's node the grantee's access resolves earlier, from
/// the `share_entries` row.
fn fshr_grant_level(
	typ: &str,
	sub_typ: Option<&str>,
	issuer_tag: &str,
	owner_id_tag: &str,
	file_id: &str,
) -> AccessLevel {
	if typ != "FSHR" {
		return AccessLevel::None;
	}
	if issuer_tag != owner_id_tag {
		warn!(
			file_id = %file_id,
			issuer = %issuer_tag,
			owner = %owner_id_tag,
			sub_typ = ?sub_typ,
			"Ignoring FSHR grant: issuer does not own the file"
		);
		return AccessLevel::None;
	}
	match sub_typ {
		Some("ADMIN") => AccessLevel::Admin,
		Some("WRITE") => AccessLevel::Write,
		Some("COMMENT") => AccessLevel::Comment,
		// A `DEL` shares the key `FSHR:{subject}:{audience}`, so it replaces the row it revokes —
		// without this arm the catch-all reads it back as Read and revocation leaves read access.
		Some("DEL") => AccessLevel::None,
		_ => AccessLevel::Read,
	}
}

/// Get access level for a user on a file
///
/// Determines access level based on:
/// 1. Ownership — owner has Admin access
/// 2. Direct `share_entries` grant on this file, then the caller-supplied `inherited_share`, then a
///    parent-chain walk for a folder-inherited grant
/// 3. Role-based access — tenant-owned files only: leader → Admin, moderator/contributor → Write,
///    any role → Read
/// 4. FSHR action issued by the file's owner — ADMIN → Admin, WRITE → Write, COMMENT → Comment,
///    DEL → None (a revocation is not a grant), other sub-types → Read (see [`fshr_grant_level`])
/// 5. No access — returns None
pub async fn get_access_level(
	app: &App,
	tn_id: TnId,
	file_id: &str,
	owner_id_tag: &str,
	ctx: &FileAccessCtx<'_>,
	inherited_share: Option<AccessLevel>,
) -> AccessLevel {
	// The owner is the file's admin: write plus share management. Callers must test
	// `can_write()`/`can_manage_shares()` rather than `== AccessLevel::Write`.
	if ctx.user_id_tag == owner_id_tag {
		return AccessLevel::Admin;
	}

	// Direct share on this specific file
	if let Ok(Some(perm)) = app
		.meta_adapter
		.check_share_access(tn_id, 'F', file_id, 'U', ctx.user_id_tag)
		.await
	{
		return AccessLevel::from_perm_char(perm);
	}
	// Inherited share from parent folder (already resolved by caller)
	if let Some(level) = inherited_share {
		return level;
	}
	// No known inheritance — walk the parent chain
	if let Some(level) = walk_parent_chain_for_share(app, tn_id, file_id, ctx.user_id_tag).await {
		return level;
	}

	// Role-based access for tenant-owned files only (owner_id_tag == tenant_id_tag)
	// When a file has no explicit owner, it belongs to the tenant.
	// Community members with roles get access based on their role level.
	// Files owned by other users are NOT accessible via role-based access.
	if owner_id_tag == ctx.tenant_id_tag {
		let level = role_access_level(ctx.user_roles);
		if level != AccessLevel::None {
			return level;
		}
	}

	// Look up FSHR action: key pattern is "FSHR:{file_id}:{audience}"
	let action_key = format!("FSHR:{}:{}", file_id, ctx.user_id_tag);

	// `get_action_by_key` does not filter on action status, so a pending ('C') or rejected FSHR
	// resolves here too. Moot in practice: the local file row only exists once `on_accept` ran.
	match app.meta_adapter.get_action_by_key(tn_id, &action_key).await {
		Ok(Some(action)) => fshr_grant_level(
			&action.typ,
			action.sub_typ.as_ref().map(AsRef::as_ref),
			&action.issuer_tag,
			owner_id_tag,
			file_id,
		),
		Ok(None) | Err(_) => AccessLevel::None,
	}
}

/// Get access level for a user on a file, considering scoped tokens
///
/// Determines access level based on:
/// 1. Scoped token — file:{file_id}:{R|C|W} grants Read/Comment/Write access
///    (also checks document tree: a token for a root grants access to children)
/// 2. Everything [`get_access_level`] resolves, in its order
/// 3. No access — returns None
pub async fn get_access_level_with_scope(
	app: &App,
	tn_id: TnId,
	file_id: &str,
	owner_id_tag: &str,
	ctx: &FileAccessCtx<'_>,
	scope: Option<&str>,
	root_id: Option<&str>,
) -> AccessLevel {
	// Check scope-based access first (for share links)
	if let Some(scope_str) = scope {
		// Use typed TokenScope for safe parsing
		if let Some(token_scope) = TokenScope::parse(scope_str) {
			match &token_scope {
				TokenScope::File { file_id: scope_file_id, access } => {
					// Direct match: scope matches this file_id
					if scope_file_id == file_id {
						return *access;
					}

					// Document tree check: scope is for a root, this file is a child
					// Depth-1 invariant: root_id always points directly to a top-level file
					if let Some(root) = root_id
						&& scope_file_id.as_str() == root
					{
						return *access;
					}

					// Cross-document link: file-type share entry ('F')
					// If scope grants access to file A, check if there's a share entry
					// linking file A → target file
					// resource=container (scope_file_id), subject=target (file_id)
					if let Ok(Some(perm)) = app
						.meta_adapter
						.check_share_access(tn_id, 'F', scope_file_id, 'F', file_id)
						.await
					{
						// Cap at min(scope_access, share_permission)
						return (*access).min(AccessLevel::from_perm_char(perm));
					}

					// Folder share: scope targets a folder; grant the scope's level
					// to any file nested under it (linked via parent_id). Gated on
					// the scoped target actually being a folder, so a document/file
					// share link does not leak access across its parent_id siblings.
					// Fails closed — a missing cache or read error yields no grant,
					// since returning a bare AccessLevel here cannot signal a 5xx.
					// DirCache is a required process-wide extension registered at app
					// build (see crates/cloudillo/src/app.rs), so the else arm only
					// fires on misconfiguration — log rather than fail silently.
					if let Ok(cache) = app.ext::<DirCache>() {
						let target_is_folder =
							scope_target_is_folder(&app.meta_adapter, cache, tn_id, scope_file_id)
								.await
								.unwrap_or(false);
						let nested_under_scope = target_is_folder
							&& is_descendant_of(
								&app.meta_adapter,
								cache,
								tn_id,
								file_id,
								scope_file_id,
							)
							.await
							.unwrap_or(false);
						if nested_under_scope {
							return *access;
						}
					} else {
						warn!("DirCache extension missing; folder-share scope grant skipped");
					}

					// Scope exists for a different file - deny access
					return AccessLevel::None;
				}
				TokenScope::ApkgPublish => {
					// APKG publish scope has no file access
					return AccessLevel::None;
				}
			}
		}
		// Scope string present but unparseable — deny access (least privilege)
		return AccessLevel::None;
	}

	// Fall back to existing logic (ownership, roles, FSHR actions)
	get_access_level(app, tn_id, file_id, owner_id_tag, ctx, None).await
}

/// Check file access and return file view with access level
///
/// This is the main helper for WebSocket handlers. It:
/// 1. Loads file metadata
/// 2. Determines access level (considering scoped tokens for share links)
/// 3. Returns combined result or error
///
/// The scope parameter should be auth_ctx.scope.as_deref().
pub async fn check_file_access_with_scope(
	app: &App,
	tn_id: TnId,
	file_id: &str,
	ctx: &FileAccessCtx<'_>,
	scope: Option<&str>,
	via: Option<&str>,
) -> Result<FileAccessResult, FileAccessError> {
	use tracing::debug;

	// Load file metadata
	let file_view = match app.meta_adapter.read_file(tn_id, file_id).await {
		Ok(Some(f)) => f,
		Ok(None) => return Err(FileAccessError::NotFound),
		Err(e) => return Err(FileAccessError::InternalError(e.to_string())),
	};

	// Get owner id_tag from file metadata
	// If no owner, default to tenant (tenant owns all files without explicit owner)
	let owner_id_tag = file_view
		.owner
		.as_ref()
		.and_then(|p| if p.id_tag.is_empty() { None } else { Some(p.id_tag.as_ref()) })
		.unwrap_or(ctx.tenant_id_tag);

	debug!(file_id = file_id, user = ctx.user_id_tag, owner = owner_id_tag, scope = ?scope, "Checking file access");

	// Get access level (considering scope for share links and document trees)
	let mut access_level = get_access_level_with_scope(
		app,
		tn_id,
		file_id,
		owner_id_tag,
		ctx,
		scope,
		file_view.root_id.as_deref(),
	)
	.await;

	// Public files are readable by anyone (including unauthenticated guests)
	if access_level == AccessLevel::None && file_view.visibility == Some('P') {
		access_level = AccessLevel::Read;
	}

	// Cap access by file-to-file share entry when opened via embedding
	if let Some(via_file_id) = via
		&& scope.is_none()
		&& access_level != AccessLevel::None
	{
		match app.meta_adapter.check_share_access(tn_id, 'F', via_file_id, 'F', file_id).await {
			Ok(Some(perm)) => {
				access_level = access_level.min(AccessLevel::from_perm_char(perm));
			}
			Ok(None) | Err(_) => {
				// No file-to-file share entry — embedding doesn't exist, deny
				access_level = AccessLevel::None;
			}
		}
	}

	if access_level == AccessLevel::None {
		return Err(FileAccessError::AccessDenied);
	}

	let read_only = !access_level.can_write();

	Ok(FileAccessResult { file_view, access_level, read_only })
}

/// Result of checking whether a file is allowed by scope
pub enum ScopeCheck {
	/// No scope restriction — fall through to normal access checks
	NoScope,
	/// File is within scope with this access level
	Allowed(AccessLevel),
	/// File is outside scope — deny access
	Denied,
}

/// Check if a file operation is allowed by scope.
///
/// Returns `ScopeCheck::NoScope` when there is no scope restriction,
/// `ScopeCheck::Allowed(level)` when the file is within scope,
/// or `ScopeCheck::Denied` when the file is outside scope.
pub fn check_scope_allows_file(
	scope: Option<&str>,
	file_id: &str,
	root_id: Option<&str>,
) -> ScopeCheck {
	let Some(scope_str) = scope else { return ScopeCheck::NoScope };
	// If a scope string is present but can't be parsed, deny access (least privilege)
	let Some(token_scope) = TokenScope::parse(scope_str) else { return ScopeCheck::Denied };
	match &token_scope {
		TokenScope::File { file_id: scope_file_id, access } => {
			// Direct match: scope matches this file_id
			if scope_file_id == file_id {
				return ScopeCheck::Allowed(*access);
			}
			// Document tree check: scope is for a root, this file is a child
			if let Some(root) = root_id
				&& scope_file_id.as_str() == root
			{
				return ScopeCheck::Allowed(*access);
			}
			ScopeCheck::Denied
		}
		TokenScope::ApkgPublish => ScopeCheck::Denied,
	}
}

/// Check if a scoped token allows file creation, honoring folder subtrees.
///
/// Like the simple document-tree scope check (Write scope where
/// `root_id == scope_file_id`), but also permits creation when the new file's
/// parent is the scoped folder itself or a descendant of it. This is the path
/// used by folder share links with editor (Write) access, letting guests upload
/// directly into the shared folder (or any subfolder).
///
/// Allowed (with Write scope) when ANY of:
/// - `root_id == scope_file_id` (document-tree rule, same as the sync variant)
/// - `parent_id == scope_file_id` (direct child of the shared folder)
/// - `parent_id` is a descendant of `scope_file_id` (nested subfolder)
///
/// Returns `Ok(())` if allowed, `Err(Error::PermissionDenied)` if denied.
pub async fn check_scope_allows_create_in(
	meta: &Arc<dyn meta_adapter::MetaAdapter>,
	cache: &DirCache,
	tn_id: TnId,
	scope: Option<&str>,
	parent_id: Option<&str>,
	root_id: Option<&str>,
) -> Result<(), Error> {
	let Some(scope_str) = scope else { return Ok(()) };
	// If a scope string is present but can't be parsed, deny access (least privilege)
	let Some(token_scope) = TokenScope::parse(scope_str) else {
		return Err(Error::PermissionDenied);
	};
	match &token_scope {
		TokenScope::File { file_id: scope_file_id, access } => {
			if !access.can_write() {
				return Err(Error::PermissionDenied);
			}
			// Document-tree rule: new file is a child in the scoped document tree.
			if root_id == Some(scope_file_id.as_str()) {
				return Ok(());
			}
			// Folder-subtree rule: new file's parent is the scoped folder or nested
			// under it. Only applies when the scoped target is actually a folder, so
			// a document/file share link can't authorize creation across its
			// parent_id siblings.
			if let Some(parent) = parent_id
				&& scope_target_is_folder(meta, cache, tn_id, scope_file_id).await?
				&& (parent == scope_file_id.as_str()
					|| is_descendant_of(meta, cache, tn_id, parent, scope_file_id).await?)
			{
				return Ok(());
			}
			Err(Error::PermissionDenied)
		}
		TokenScope::ApkgPublish => Ok(()), // Middleware already restricts to /api/files/apkg/
	}
}

/// Returns true when a scoped token is itself sufficient authorization for a
/// collection-level operation, letting the middleware skip the role/quota path.
///
/// A file share link with Write access authorizes file *creation* only; the
/// file handlers (`check_scope_allows_create_in`) then enforce the scope's
/// subtree boundary. It must NOT authorize action/app creation, trash emptying,
/// or any other collection operation.
pub fn scope_grants_collection_op(scope: Option<&str>, resource_type: &str, action: &str) -> bool {
	let Some(scope) = scope else { return false };
	// `Write` is the top of the scope vocabulary — `AccessLevel::to_scope_char` caps `Admin` at
	// `'W'` and `TokenScope::parse` refuses any other char, so `Admin` is unreachable here.
	matches!(TokenScope::parse(scope), Some(TokenScope::File { access: AccessLevel::Write, .. }))
		&& resource_type == "file"
		&& action == "create"
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn folder_write_scope_grants_file_create() {
		assert!(scope_grants_collection_op(Some("file:f1~abc:W"), "file", "create"));
	}

	#[test]
	fn write_scope_denies_non_file_create_ops() {
		assert!(!scope_grants_collection_op(Some("file:f1~abc:W"), "action", "create"));
		assert!(!scope_grants_collection_op(Some("file:f1~abc:W"), "file", "delete"));
	}

	#[test]
	fn read_scope_denies_file_create() {
		assert!(!scope_grants_collection_op(Some("file:f1~abc:R"), "file", "create"));
	}

	#[test]
	fn no_scope_denies_file_create() {
		assert!(!scope_grants_collection_op(None, "file", "create"));
	}

	#[test]
	fn unparseable_scope_denies_file_create() {
		assert!(!scope_grants_collection_op(Some("not-a-valid-scope"), "file", "create"));
	}

	#[test]
	fn role_access_level_requires_a_known_role() {
		// The federated-stranger case.
		assert_eq!(role_access_level(&[]), AccessLevel::None);
		// A single empty role string is not a role.
		assert_eq!(role_access_level(&["".into()]), AccessLevel::None);
		assert_eq!(role_access_level(&["SADM".into()]), AccessLevel::None);
	}

	#[test]
	fn role_access_level_maps_community_roles() {
		assert_eq!(role_access_level(&["public".into()]), AccessLevel::Read);
		assert_eq!(role_access_level(&["follower".into()]), AccessLevel::Read);
		assert_eq!(role_access_level(&["supporter".into()]), AccessLevel::Read);
		assert_eq!(role_access_level(&["contributor".into()]), AccessLevel::Write);
		assert_eq!(role_access_level(&["moderator".into()]), AccessLevel::Write);
		// Leadership over a tenant-owned file carries share management, hence Admin not Write.
		assert_eq!(role_access_level(&["leader".into()]), AccessLevel::Admin);
		// The highest role in a mixed set wins.
		assert_eq!(
			role_access_level(&["public".into(), "follower".into(), "leader".into()]),
			AccessLevel::Admin
		);
		assert_eq!(role_access_level(&["public".into(), "contributor".into()]), AccessLevel::Write);
	}

	const OWNER: &str = "alice.example.com";
	const ATTACKER: &str = "mallory.example.com";

	#[test]
	fn fshr_from_a_non_owner_grants_nothing() {
		// The action row is stored before `fshr::on_create` runs and a hook denial does not roll it
		// back, so any contributor — or any followed peer posting to the inbox — can self-address
		// an FSHR naming someone else's file. Every sub-type must be inert, `ADMIN` above all: it
		// would otherwise read back as share-manager standing with an admin grant ceiling.
		for sub_typ in [Some("ADMIN"), Some("WRITE"), Some("COMMENT"), Some("READ"), None] {
			assert_eq!(
				fshr_grant_level("FSHR", sub_typ, ATTACKER, OWNER, "f1~doc"),
				AccessLevel::None,
				"{sub_typ:?} from a non-owner must grant nothing"
			);
		}
	}

	#[test]
	fn fshr_from_the_owner_grants_its_sub_type() {
		// The live path: on the recipient's node `fshr::on_accept` writes `owner_tag = issuer`, so
		// the grant resolves exactly as the sender sent it.
		for (sub_typ, level) in [
			(Some("ADMIN"), AccessLevel::Admin),
			(Some("WRITE"), AccessLevel::Write),
			(Some("COMMENT"), AccessLevel::Comment),
			(Some("READ"), AccessLevel::Read),
			(None, AccessLevel::Read),
		] {
			assert_eq!(fshr_grant_level("FSHR", sub_typ, OWNER, OWNER, "f1~doc"), level);
		}
	}

	#[test]
	fn a_del_from_the_owner_revokes_rather_than_granting_read() {
		// `delete_share` drops the `share_entries` row and emits an FSHR `DEL`, which — same key —
		// overwrites the grant. Falling through to the catch-all would hand the read back.
		assert_eq!(
			fshr_grant_level("FSHR", Some("DEL"), OWNER, OWNER, "f1~doc"),
			AccessLevel::None
		);
	}

	#[test]
	fn only_fshr_rows_grant_anything() {
		// The key is `FSHR:{file}:{audience}`, but `get_action_by_key` does not filter on type.
		assert_eq!(
			fshr_grant_level("CONN", Some("ADMIN"), OWNER, OWNER, "f1~doc"),
			AccessLevel::None
		);
	}
}

// vim: ts=4