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
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
// SPDX-FileCopyrightText: Szilárd Hajba
// SPDX-License-Identifier: LGPL-3.0-or-later

//! Attribute-Based Access Control (ABAC) system for Cloudillo
//!
//! Implements classic ABAC with 4-object model:
//! - Subject: Authenticated user (AuthCtx)
//! - Action: Operation being performed (string like "file:read")
//! - Object: Resource being accessed (implements AttrSet trait)
//! - Environment: Context (time, etc.)

use crate::prelude::*;
use cloudillo_types::auth_adapter::AuthCtx;
use cloudillo_types::types::AccessLevel;
use std::collections::HashMap;

/// Visibility levels for resources (files, actions, profile fields)
///
/// Stored as single char in database:
/// - None/NULL = Direct (most restrictive, owner + explicit audience only)
/// - 'P' = Public (anyone, including unauthenticated)
/// - 'V' = Verified (any authenticated user from any federated instance)
/// - '2' = 2nd degree (friend of friend, reserved for future voucher token system)
/// - 'F' = Follower (authenticated user who follows the owner)
/// - 'C' = Connected (authenticated user who is connected/mutual with owner)
///
/// Hierarchy (from most permissive to most restrictive):
/// Public > Verified > 2nd Degree > Follower > Connected > Direct
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
pub enum VisibilityLevel {
	/// Anyone can access, including unauthenticated users
	Public,
	/// Any authenticated user from any federated instance
	Verified,
	/// Friend of friend (2nd degree connection) - reserved for voucher token system
	SecondDegree,
	/// Authenticated user who follows the owner
	Follower,
	/// Authenticated user who is connected (mutual) with owner
	Connected,
	/// Readable by any active subscriber of the action's container (group members).
	/// Owner/tenant pass the base check; subscribers pass via the audience bridge.
	Subscribed,
	/// Most restrictive - only owner and explicit audience
	#[default]
	Direct,
}

impl VisibilityLevel {
	/// Parse from database char value
	pub fn from_char(c: Option<char>) -> Self {
		match c {
			Some('P') => Self::Public,
			Some('V') => Self::Verified,
			Some('2') => Self::SecondDegree,
			Some('F') => Self::Follower,
			Some('C') => Self::Connected,
			Some('S') => Self::Subscribed,
			// NULL or unknown = Direct (most restrictive, secure by default)
			None | Some(_) => Self::Direct,
		}
	}

	/// Convert to database char value (inverse of from_char)
	pub fn to_char(&self) -> Option<char> {
		match self {
			Self::Public => Some('P'),
			Self::Verified => Some('V'),
			Self::SecondDegree => Some('2'),
			Self::Follower => Some('F'),
			Self::Connected => Some('C'),
			Self::Subscribed => Some('S'),
			Self::Direct => None,
		}
	}

	/// Convert to string for attribute lookup
	pub fn as_str(&self) -> &'static str {
		match self {
			Self::Public => "public",
			Self::Verified => "verified",
			Self::SecondDegree => "second_degree",
			Self::Follower => "follower",
			Self::Connected => "connected",
			Self::Subscribed => "subscribed",
			Self::Direct => "direct",
		}
	}
}

/// Subject's access level to a resource based on their relationship with the owner
///
/// Used to determine if a subject meets the visibility requirements.
/// Higher levels grant access to more restrictive visibility settings.
///
/// Hierarchy: Owner > Connected > Follower > SecondDegree > Verified > Public > None
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
pub enum SubjectAccessLevel {
	/// No authentication or relationship
	#[default]
	None,
	/// Unauthenticated but public access requested
	Public,
	/// Authenticated user (has valid JWT from any federated instance)
	Verified,
	/// Has voucher token proving 2nd degree connection (future)
	SecondDegree,
	/// Follows the resource owner
	Follower,
	/// Connected (mutual) with resource owner
	Connected,
	/// Is the resource owner
	Owner,
}

impl SubjectAccessLevel {
	/// Check if this access level can view content with given visibility
	pub fn can_access(self, visibility: VisibilityLevel) -> bool {
		match visibility {
			VisibilityLevel::Public => true, // Everyone can access public
			VisibilityLevel::Verified => self >= Self::Verified,
			VisibilityLevel::SecondDegree => self >= Self::SecondDegree,
			VisibilityLevel::Follower => self >= Self::Follower,
			VisibilityLevel::Connected => self >= Self::Connected,
			// Both admit only owner/tenant here; subscribers/explicit-audience readers
			// pass via the audience bridge in `can_view_item`.
			VisibilityLevel::Subscribed | VisibilityLevel::Direct => self >= Self::Owner,
		}
	}

	/// Return the visibility level chars this access level can see.
	/// Returns `None` for Owner (sees everything including NULL/Direct).
	/// Used to push visibility filtering into SQL for correct pagination.
	pub fn visible_levels(self) -> Option<&'static [char]> {
		match self {
			Self::None | Self::Public => Some(&['P']),
			Self::Verified => Some(&['P', 'V']),
			Self::SecondDegree => Some(&['P', 'V', '2']),
			Self::Follower => Some(&['P', 'V', '2', 'F']),
			Self::Connected => Some(&['P', 'V', '2', 'F', 'C']),
			Self::Owner => None,
		}
	}
}

/// The one relationship ladder, shared so the endpoints that list and the
/// endpoint that searches cannot drift apart.
///
/// Callers compute the four inputs themselves, because *how* you become the
/// owner or a real authenticated caller differs by endpoint — `GET /api/search`
/// demotes every scoped caller to `Public` before asking (a file scope is handed
/// to an untrusted app and carries no ambient authority), while `GET /api/files`
/// resolves a scope through its own share lookup. What must never differ is the
/// ordering below.
///
/// [`can_view_item`] carries a third copy of the ladder with a different
/// signature: it folds the item owner into the owner test and an
/// `is_authenticated` flag into `is_real_auth`.
// Four bools on purpose: they are the ladder's rungs, and a struct would put a
// name between each caller and the ordering this function exists to fix in one
// place. Both call sites pass them in the order the doc above states.
#[allow(clippy::fn_params_excessive_bools)]
pub fn relationship_level(
	is_owner: bool,
	connected: bool,
	following: bool,
	is_real_auth: bool,
) -> SubjectAccessLevel {
	if is_owner {
		SubjectAccessLevel::Owner
	} else if connected {
		SubjectAccessLevel::Connected
	} else if following {
		SubjectAccessLevel::Follower
	} else if is_real_auth {
		SubjectAccessLevel::Verified
	} else {
		SubjectAccessLevel::Public
	}
}

/// Context for checking whether a subject can view an item
pub struct ViewCheckContext<'a> {
	pub subject_id_tag: &'a str,
	pub is_authenticated: bool,
	pub item_owner_id_tag: &'a str,
	pub tenant_id_tag: &'a str,
	pub visibility: Option<char>,
	pub subject_following_owner: bool,
	pub subject_connected_to_owner: bool,
	pub audience_tags: Option<&'a [&'a str]>,
}

/// Check if subject can view an item based on visibility and relationship
///
/// This is a standalone function for use in list filtering where we don't
/// have full ABAC context. It evaluates visibility rules directly.
pub fn can_view_item(ctx: &ViewCheckContext<'_>) -> bool {
	let visibility = VisibilityLevel::from_char(ctx.visibility);

	// Determine subject's access level
	// Note: "guest" id_tag is used for unauthenticated users - treat as Public
	let is_real_auth =
		ctx.is_authenticated && !ctx.subject_id_tag.is_empty() && ctx.subject_id_tag != "guest";
	let is_tenant = ctx.subject_id_tag == ctx.tenant_id_tag;
	let access_level = if ctx.subject_id_tag == ctx.item_owner_id_tag || is_tenant {
		SubjectAccessLevel::Owner // Tenant has same access as owner
	} else if ctx.subject_connected_to_owner {
		SubjectAccessLevel::Connected
	} else if ctx.subject_following_owner {
		SubjectAccessLevel::Follower
	} else if is_real_auth {
		SubjectAccessLevel::Verified
	} else {
		SubjectAccessLevel::Public
	};

	// Check basic access
	if access_level.can_access(visibility) {
		return true;
	}

	// Direct and Subscribed also check explicit audience. For Subscribed,
	// `filter.rs` injects the reader into `audience_tags` when they hold an active
	// SUBS to the container (group membership).
	if (visibility == VisibilityLevel::Direct || visibility == VisibilityLevel::Subscribed)
		&& let Some(tags) = ctx.audience_tags
	{
		return tags.contains(&ctx.subject_id_tag);
	}

	false
}

// Re-export AttrSet from cloudillo-types (canonical definition)
pub use cloudillo_types::abac::AttrSet;

/// True iff `auth` carries the site-admin (SADM) role.
///
/// Single source of truth for the role-name string; callers must not
/// compare role strings inline.
pub fn is_admin(auth: &AuthCtx) -> bool {
	auth.roles.iter().any(|r| r.as_ref() == "SADM")
}

/// Environment attributes (environmental context)
#[derive(Debug, Clone)]
pub struct Environment {
	pub time: Timestamp,
	// Future: ip_address, user_agent, etc.
}

impl Environment {
	pub fn new() -> Self {
		Self { time: Timestamp::now() }
	}
}

impl Default for Environment {
	fn default() -> Self {
		Self::new()
	}
}

/// Policy rule condition
#[derive(Debug, Clone)]
pub struct Condition {
	pub attribute: String,
	pub operator: Operator,
	pub value: serde_json::Value,
}

#[derive(Debug, Clone, Copy)]
pub enum Operator {
	Equals,
	NotEquals,
	Contains,
	NotContains,
	GreaterThan,
	LessThan,
	In,      // Subject attr in object list
	HasRole, // Subject has specific role
}

impl Condition {
	/// Evaluate condition against subject, action, object, environment
	pub fn evaluate(
		&self,
		subject: &AuthCtx,
		action: &str,
		object: &dyn AttrSet,
		_environment: &Environment,
	) -> bool {
		// First, try to get value from object
		if let Some(obj_val) = object.get(&self.attribute) {
			return self.compare_value(obj_val);
		}

		// Then try subject attributes
		match self.attribute.as_str() {
			"subject.id_tag" => self.compare_value(&subject.id_tag),
			"subject.tn_id" => self.compare_value(&subject.tn_id.0.to_string()),
			"subject.roles" | "role.admin" | "role.moderator" | "role.member" => {
				// Special handling for role checks
				if let Operator::HasRole = self.operator
					&& let Some(role) = self.value.as_str()
				{
					return subject.roles.iter().any(|r| r.as_ref() == role);
				}
				// For dotted notation like "role.admin"
				if self.attribute.starts_with("role.") {
					let role_name = &self.attribute[5..];
					return subject.roles.iter().any(|r| r.as_ref() == role_name);
				}
				false
			}
			"action" => self.compare_value(action),
			_ => false,
		}
	}

	fn compare_value(&self, actual: &str) -> bool {
		match self.operator {
			Operator::Equals => self.value.as_str() == Some(actual),
			Operator::NotEquals => self.value.as_str() != Some(actual),
			Operator::Contains => {
				if let Some(needle) = self.value.as_str() {
					actual.contains(needle)
				} else {
					false
				}
			}
			Operator::NotContains => {
				if let Some(needle) = self.value.as_str() {
					!actual.contains(needle)
				} else {
					true
				}
			}
			Operator::GreaterThan => {
				if let (Some(threshold), Ok(val)) = (self.value.as_f64(), actual.parse::<f64>()) {
					val > threshold
				} else {
					false
				}
			}
			Operator::LessThan => {
				if let (Some(threshold), Ok(val)) = (self.value.as_f64(), actual.parse::<f64>()) {
					val < threshold
				} else {
					false
				}
			}
			Operator::In | Operator::HasRole => false,
		}
	}
}

/// Policy rule
#[derive(Debug, Clone)]
pub struct PolicyRule {
	pub name: String,
	pub conditions: Vec<Condition>,
	pub effect: Effect,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Effect {
	Allow,
	Deny,
}

impl PolicyRule {
	/// Evaluate rule against subject, action, object, environment
	pub fn evaluate(
		&self,
		subject: &AuthCtx,
		action: &str,
		object: &dyn AttrSet,
		environment: &Environment,
	) -> Option<Effect> {
		// All conditions must match for rule to apply
		let all_match = self
			.conditions
			.iter()
			.all(|cond| cond.evaluate(subject, action, object, environment));

		if all_match { Some(self.effect) } else { None }
	}
}

/// ABAC Policy (collection of rules)
#[derive(Debug, Clone)]
pub struct Policy {
	pub name: String,
	pub rules: Vec<PolicyRule>,
}

impl Policy {
	/// Evaluate policy - returns Effect if any rule matches
	pub fn evaluate(
		&self,
		subject: &AuthCtx,
		action: &str,
		object: &dyn AttrSet,
		environment: &Environment,
	) -> Option<Effect> {
		for rule in &self.rules {
			if let Some(effect) = rule.evaluate(subject, action, object, environment) {
				return Some(effect);
			}
		}
		None
	}
}

/// Profile-level policy configuration (TOP + BOTTOM)
#[derive(Debug, Clone)]
pub struct ProfilePolicy {
	pub tn_id: TnId,
	pub top_policy: Policy,    // Maximum permissions (constraints)
	pub bottom_policy: Policy, // Minimum permissions (guarantees)
}

/// Collection-level policy configuration
///
/// Used for CREATE operations where no specific object exists yet.
/// Evaluates permissions based on subject attributes only.
///
/// Example: User wants to upload a file
///   - Can evaluate "can user create files?" without the file existing
///   - Checks: quota_remaining > 0, role == "creator", !banned, email_verified
#[derive(Debug, Clone)]
pub struct CollectionPolicy {
	pub resource_type: String, // "files", "actions", "profiles"
	pub action: String,        // "create", "list"
	pub top_policy: Policy,    // Denials/constraints
	pub bottom_policy: Policy, // Guarantees
}

/// Main permission checker
pub struct PermissionChecker {
	profile_policies: HashMap<TnId, ProfilePolicy>,
	collection_policies: HashMap<String, CollectionPolicy>, // key: "resource:action"
}

impl PermissionChecker {
	pub fn new() -> Self {
		Self { profile_policies: HashMap::new(), collection_policies: HashMap::new() }
	}

	/// Load profile policy for tenant (called during bootstrap)
	pub fn load_policy(&mut self, policy: ProfilePolicy) {
		self.profile_policies.insert(policy.tn_id, policy);
	}

	/// Load collection policy for resource type + action
	pub fn load_collection_policy(&mut self, policy: CollectionPolicy) {
		let key = format!("{}:{}", policy.resource_type, policy.action);
		self.collection_policies.insert(key, policy);
	}

	/// Get collection policy for resource type and action
	pub fn get_collection_policy(
		&self,
		resource_type: &str,
		action: &str,
	) -> Option<&CollectionPolicy> {
		let key = format!("{}:{}", resource_type, action);
		self.collection_policies.get(&key)
	}

	/// Core permission check function
	pub fn has_permission(
		&self,
		subject: &AuthCtx,
		action: &str,
		object: &dyn AttrSet,
		environment: &Environment,
	) -> bool {
		// Step 1: Check TOP policy (constraints)
		if let Some(profile_policy) = self.profile_policies.get(&subject.tn_id) {
			if let Some(Effect::Deny) =
				profile_policy.top_policy.evaluate(subject, action, object, environment)
			{
				info!("TOP policy denied: tn_id={}, action={}", subject.tn_id.0, action);
				return false;
			}

			// Step 2: Check BOTTOM policy (guarantees)
			if let Some(Effect::Allow) =
				profile_policy.bottom_policy.evaluate(subject, action, object, environment)
			{
				info!("BOTTOM policy allowed: tn_id={}, action={}", subject.tn_id.0, action);
				return true;
			}
		}

		// Step 3: Default permission rules (ownership, visibility, etc.)
		self.check_default_rules(subject, action, object, environment)
	}

	/// Default permission rules (when policies don't match)
	fn check_default_rules(
		&self,
		subject: &AuthCtx,
		action: &str,
		object: &dyn AttrSet,
		_environment: &Environment,
	) -> bool {
		use tracing::debug;

		// Leader override - leaders can do everything
		if subject.roles.iter().any(|r| r.as_ref() == "leader") {
			debug!(subject = %subject.id_tag, action = action, "Leader role allows access");
			return true;
		}

		// Parse action into resource:operation
		let parts: Vec<&str> = action.split(':').collect();
		if parts.len() != 2 {
			debug!(subject = %subject.id_tag, action = action, "Invalid action format (expected resource:operation)");
			return false;
		}
		let operation = parts[1];

		// Ownership check for modify operations
		if matches!(operation, "update" | "delete" | "write") {
			if let Some(owner) = object.get("owner_id_tag")
				&& owner == subject.id_tag.as_ref()
			{
				debug!(subject = %subject.id_tag, action = action, owner = owner, "Owner access allowed for modify operation");
				return true;
			}
			// Pre-computed access level (community roles, FSHR shares, scoped tokens). Ordering
			// comes from `AccessLevel` itself; an unrecognized name parses to `None` and denies.
			if let Some(al) = object.get("access_level")
				&& AccessLevel::from_str_name(al).is_some_and(AccessLevel::can_write)
			{
				debug!(subject = %subject.id_tag, action = action, "Write access level allows modify operation");
				return true;
			}
			debug!(subject = %subject.id_tag, action = action, "Denied: not owner and no write access level");
			return false;
		}

		// Visibility check for read operations
		if matches!(operation, "read") {
			// Explicit access grants (FSHR file shares, scoped tokens), same `AccessLevel`
			// ordering as the modify branch above.
			if let Some(al) = object.get("access_level")
				&& AccessLevel::from_str_name(al).is_some_and(AccessLevel::can_read)
			{
				return true;
			}
			return self.check_visibility(subject, object);
		}

		// Create operations - check quota/limits in future
		if operation == "create" {
			debug!(subject = %subject.id_tag, action = action, "Create operation allowed");
			return true; // Allow for now
		}

		// Admin operations (e.g. `profile:admin`) — community moderators and above
		// pass the gate. Leaders were already allowed by the override at the top of
		// this function; this admits moderators so they can manage lower-ranked
		// members. The finer-grained target-rank and field-level rules (a moderator
		// may only re-role members strictly below them, never rename or change
		// status) are enforced in the handler — see `patch_profile_admin`'s
		// role-hierarchy guard in `cloudillo-profile/src/update.rs`.
		if operation == "admin" {
			use crate::roles::{MODERATOR_LEVEL, highest_role_level};
			if highest_role_level(&subject.roles) >= MODERATOR_LEVEL {
				debug!(subject = %subject.id_tag, action = action, "Moderator+ role allows admin operation");
				return true;
			}
			debug!(subject = %subject.id_tag, action = action, "Denied: admin operation requires moderator+");
			return false;
		}

		// Default deny
		debug!(subject = %subject.id_tag, action = action, "Default deny: no matching rules");
		false
	}

	/// Check visibility-based access using the new VisibilityLevel enum
	///
	/// Determines subject's access level and checks against resource visibility.
	/// Supports both char-based visibility (from DB) and string-based (legacy).
	#[expect(clippy::unused_self, reason = "method may use self in future policy checks")]
	fn check_visibility(&self, subject: &AuthCtx, object: &dyn AttrSet) -> bool {
		use tracing::debug;

		// Parse visibility from object attributes
		// Try char-based first (from "visibility_char"), then fall back to string
		let visibility = if let Some(vis_char) = object.get("visibility_char") {
			VisibilityLevel::from_char(vis_char.chars().next())
		} else if let Some(vis_str) = object.get("visibility") {
			match vis_str {
				"public" | "P" => VisibilityLevel::Public,
				"verified" | "V" => VisibilityLevel::Verified,
				"second_degree" | "2" => VisibilityLevel::SecondDegree,
				"follower" | "F" => VisibilityLevel::Follower,
				"connected" | "C" => VisibilityLevel::Connected,
				// "direct" or unknown = Direct (secure by default)
				_ => VisibilityLevel::Direct,
			}
		} else {
			VisibilityLevel::Direct // No visibility = Direct (most restrictive)
		};

		// Determine subject's access level based on relationship with resource
		let is_owner = object.get("owner_id_tag") == Some(subject.id_tag.as_ref());
		let is_issuer = object.get("issuer_id_tag") == Some(subject.id_tag.as_ref());
		let is_connected = object.get("connected") == Some("true");
		let is_follower = object.get("following") == Some("true");
		let in_audience = object.contains("audience_tag", subject.id_tag.as_ref());

		// Calculate subject's effective access level
		// Note: "guest" id_tag is used for unauthenticated users - treat as Public
		let is_authenticated = !subject.id_tag.is_empty() && subject.id_tag.as_ref() != "guest";
		let access_level = if is_owner || is_issuer {
			SubjectAccessLevel::Owner
		} else if is_connected {
			SubjectAccessLevel::Connected
		} else if is_follower {
			SubjectAccessLevel::Follower
		} else if is_authenticated {
			// Authenticated user without specific relationship
			SubjectAccessLevel::Verified
		} else {
			SubjectAccessLevel::Public
		};

		// Check if access level meets visibility requirement
		let allowed = access_level.can_access(visibility);

		// For Direct visibility, also check explicit audience
		let allowed =
			if visibility == VisibilityLevel::Direct { allowed || in_audience } else { allowed };

		debug!(
			subject = %subject.id_tag,
			visibility = ?visibility,
			access_level = ?access_level,
			is_owner = is_owner,
			is_issuer = is_issuer,
			is_connected = is_connected,
			is_follower = is_follower,
			in_audience = in_audience,
			allowed = allowed,
			"Visibility check"
		);

		allowed
	}

	/// Evaluate collection policy (for CREATE operations)
	///
	/// Collection policies check subject attributes without an object existing.
	/// Used for operations like "can user upload files?" or "can user create posts?"
	pub fn has_collection_permission(
		&self,
		subject: &AuthCtx,
		subject_attrs: &dyn AttrSet,
		resource_type: &str,
		action: &str,
		environment: &Environment,
	) -> bool {
		use tracing::debug;

		// Get collection policy
		let Some(policy) = self.get_collection_policy(resource_type, action) else {
			// No policy defined → allow by default
			debug!(
				subject = %subject.id_tag,
				resource_type = resource_type,
				action = action,
				"No collection policy found - allowing by default"
			);
			return true;
		};

		// Step 1: Check TOP policy (denials/constraints)
		if let Some(Effect::Deny) =
			policy.top_policy.evaluate(subject, action, subject_attrs, environment)
		{
			debug!(
				subject = %subject.id_tag,
				resource_type = resource_type,
				action = action,
				"Collection TOP policy denied"
			);
			return false;
		}

		// Step 2: Check BOTTOM policy (guarantees)
		if let Some(Effect::Allow) =
			policy.bottom_policy.evaluate(subject, action, subject_attrs, environment)
		{
			debug!(
				subject = %subject.id_tag,
				resource_type = resource_type,
				action = action,
				"Collection BOTTOM policy allowed"
			);
			return true;
		}

		// Step 3: Default deny (no policies matched)
		debug!(
			subject = %subject.id_tag,
			resource_type = resource_type,
			action = action,
			"No matching collection policies - default deny"
		);
		false
	}
}

impl Default for PermissionChecker {
	fn default() -> Self {
		Self::new()
	}
}

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

	#[test]
	fn test_environment_creation() {
		let env = Environment::new();
		assert!(env.time.0 > 0);
	}

	#[test]
	fn test_permission_checker_creation() {
		let checker = PermissionChecker::new();
		assert_eq!(checker.profile_policies.len(), 0);
	}

	/// Only the pre-computed `access_level`, no owner — so only the access-level branch can allow
	/// anything.
	struct AccessLevelObject(&'static str);

	impl AttrSet for AccessLevelObject {
		fn get(&self, key: &str) -> Option<&str> {
			match key {
				"access_level" => Some(self.0),
				_ => None,
			}
		}

		fn get_list(&self, _key: &str) -> Option<Vec<&str>> {
			None
		}
	}

	fn plain_subject() -> AuthCtx {
		AuthCtx {
			tn_id: TnId(1),
			id_tag: "alice.example.com".into(),
			roles: Box::new([]),
			scope: None,
			anonymous: false,
		}
	}

	#[test]
	fn admin_access_level_allows_read_and_update() {
		// The owner resolves to `AccessLevel::Admin`, so "admin" must satisfy both the modify and
		// the read branch.
		let checker = PermissionChecker::new();
		let subject = plain_subject();
		let env = Environment::new();
		let object = AccessLevelObject("admin");

		assert!(checker.has_permission(&subject, "file:read", &object, &env));
		assert!(checker.has_permission(&subject, "file:update", &object, &env));
		assert!(checker.has_permission(&subject, "file:delete", &object, &env));

		// Levels below admin are unaffected.
		let writer = AccessLevelObject("write");
		assert!(checker.has_permission(&subject, "file:read", &writer, &env));
		assert!(checker.has_permission(&subject, "file:update", &writer, &env));
		let reader = AccessLevelObject("read");
		assert!(checker.has_permission(&subject, "file:read", &reader, &env));
		assert!(!checker.has_permission(&subject, "file:update", &reader, &env));

		// A string outside the `AccessLevel::as_str` vocabulary must not read as authority.
		let bogus = AccessLevelObject("bogus");
		assert!(!checker.has_permission(&subject, "file:read", &bogus, &env));
		assert!(!checker.has_permission(&subject, "file:update", &bogus, &env));
		// ...and "none" is a recognized level that still grants nothing.
		let none = AccessLevelObject("none");
		assert!(!checker.has_permission(&subject, "file:read", &none, &env));
		assert!(!checker.has_permission(&subject, "file:update", &none, &env));
	}

	#[test]
	fn test_subscribed_level_char_roundtrip() {
		assert_eq!(VisibilityLevel::from_char(Some('S')), VisibilityLevel::Subscribed);
		assert_eq!(VisibilityLevel::Subscribed.to_char(), Some('S'));
		assert_eq!(VisibilityLevel::Subscribed.as_str(), "subscribed");
	}

	#[test]
	fn test_subscribed_can_access_base_check() {
		// Only owner/tenant pass the base check; everyone else must go through the
		// audience/subscription bridge in `can_view_item`.
		assert!(SubjectAccessLevel::Owner.can_access(VisibilityLevel::Subscribed));
		assert!(!SubjectAccessLevel::Connected.can_access(VisibilityLevel::Subscribed));
		assert!(!SubjectAccessLevel::Follower.can_access(VisibilityLevel::Subscribed));
		assert!(!SubjectAccessLevel::Verified.can_access(VisibilityLevel::Subscribed));
		assert!(!SubjectAccessLevel::Public.can_access(VisibilityLevel::Subscribed));
	}

	#[test]
	fn test_subscribed_view_via_audience_bridge() {
		// A member injected into audience_tags (by filter.rs) can view a Subscribed row
		// issued by a co-member, despite having no follow/connect relationship.
		let member = "alice.example.com";
		let ctx = ViewCheckContext {
			subject_id_tag: member,
			is_authenticated: true,
			item_owner_id_tag: "bob.example.com", // a different member
			tenant_id_tag: "home.example.com",
			visibility: Some('S'),
			subject_following_owner: false,
			subject_connected_to_owner: false,
			audience_tags: Some(&[member]),
		};
		assert!(can_view_item(&ctx));
	}

	#[test]
	fn test_subscribed_denied_when_not_member() {
		// A non-member (not in audience_tags) cannot view a Subscribed row.
		let ctx = ViewCheckContext {
			subject_id_tag: "carol.example.com",
			is_authenticated: true,
			item_owner_id_tag: "bob.example.com",
			tenant_id_tag: "home.example.com",
			visibility: Some('S'),
			subject_following_owner: false,
			subject_connected_to_owner: false,
			audience_tags: Some(&[]),
		};
		assert!(!can_view_item(&ctx));
	}

	#[test]
	fn test_subscribed_owner_and_tenant_shortcut() {
		// The issuer views their own Subscribed row without the audience bridge.
		let ctx = ViewCheckContext {
			subject_id_tag: "bob.example.com",
			is_authenticated: true,
			item_owner_id_tag: "bob.example.com",
			tenant_id_tag: "home.example.com",
			visibility: Some('S'),
			subject_following_owner: false,
			subject_connected_to_owner: false,
			audience_tags: Some(&[]),
		};
		assert!(can_view_item(&ctx));

		// The node tenant reads any Subscribed row hosted on their own node.
		let ctx_tenant = ViewCheckContext {
			subject_id_tag: "home.example.com",
			is_authenticated: true,
			item_owner_id_tag: "bob.example.com",
			tenant_id_tag: "home.example.com",
			visibility: Some('S'),
			subject_following_owner: false,
			subject_connected_to_owner: false,
			audience_tags: Some(&[]),
		};
		assert!(can_view_item(&ctx_tenant));
	}
}