Skip to main content

modkit_db/secure/
select.rs

1use sea_orm::{
2    ColumnTrait, EntityTrait, ModelTrait, PaginatorTrait, QueryFilter, QueryOrder, QuerySelect,
3    Related, sea_query::Expr,
4};
5use std::sync::Arc;
6
7use crate::secure::cond::build_scope_condition;
8use crate::secure::error::ScopeError;
9use crate::secure::{AccessScope, DBRunner, DBRunnerInternal, ScopableEntity, SeaOrmRunner};
10
11/// Typestate marker: query has not yet been scoped.
12/// Cannot execute queries in this state.
13#[derive(Debug, Clone, Copy)]
14pub struct Unscoped;
15
16/// Typestate marker: query has been scoped with access control.
17/// Can now execute queries safely.
18///
19/// This marker carries the `AccessScope` internally so that related-entity
20/// queries can automatically apply the same scope without requiring it
21/// to be passed again.
22#[derive(Debug, Clone)]
23pub struct Scoped {
24    scope: Arc<AccessScope>,
25}
26
27/// A type-safe wrapper around `SeaORM`'s `Select` that enforces scoping.
28///
29/// This wrapper uses the typestate pattern to ensure that queries cannot
30/// be executed without first applying access control via `.scope_with()`.
31///
32/// When scoped (`SecureSelect<E, Scoped>`), the query carries the `AccessScope`
33/// internally. This allows related-entity queries (`find_also_related`,
34/// `find_with_related`) to automatically apply the same scope to related
35/// entities without requiring the scope to be passed again.
36///
37/// # Type Parameters
38/// - `E`: The `SeaORM` entity type
39/// - `S`: The typestate (`Unscoped` or `Scoped`)
40///
41/// # Example
42/// ```rust,ignore
43/// use modkit_db::secure::{AccessScope, SecureEntityExt};
44///
45/// let scope = AccessScope::tenants_only(vec![tenant_id]);
46/// let users = user::Entity::find()
47///     .secure()           // Returns SecureSelect<E, Unscoped>
48///     .scope_with(&scope) // Returns SecureSelect<E, Scoped>
49///     .all(conn)          // Now can execute
50///     .await?;
51///
52/// // Related queries auto-apply scope:
53/// let orders_with_items = Order::find()
54///     .secure()
55///     .scope_with(&scope)
56///     .find_with_related(line_item::Entity)  // scope auto-applied to LineItem
57///     .all(conn)
58///     .await?;
59/// ```
60#[must_use]
61#[derive(Clone, Debug)]
62pub struct SecureSelect<E: EntityTrait, S> {
63    pub(crate) inner: sea_orm::Select<E>,
64    pub(crate) state: S,
65}
66
67/// A type-safe wrapper around `SeaORM`'s `SelectTwo` that enforces scoping.
68///
69/// This wrapper is used for `find_also_related` queries where you want to fetch
70/// an entity along with an optional related entity (1-to-0..1 relationship).
71///
72/// The wrapper carries the `AccessScope` internally so further chained operations
73/// can apply scoping consistently.
74///
75/// # Type Parameters
76/// - `E`: The primary `SeaORM` entity type
77/// - `F`: The related `SeaORM` entity type
78/// - `S`: The typestate (`Scoped` - note: only Scoped state is supported)
79///
80/// # Example
81/// ```rust,ignore
82/// use modkit_db::secure::{AccessScope, SecureEntityExt};
83///
84/// let scope = AccessScope::tenants_only(vec![tenant_id]);
85/// let rows: Vec<(fruit::Model, Option<cake::Model>)> = Fruit::find()
86///     .secure()
87///     .scope_with(&scope)
88///     .find_also_related(cake::Entity)  // scope auto-applied to cake
89///     .all(db)
90///     .await?;
91/// ```
92#[must_use]
93#[derive(Clone, Debug)]
94pub struct SecureSelectTwo<E: EntityTrait, F: EntityTrait, S> {
95    pub(crate) inner: sea_orm::SelectTwo<E, F>,
96    pub(crate) state: S,
97}
98
99/// A type-safe wrapper around `SeaORM`'s `SelectTwoMany` that enforces scoping.
100///
101/// This wrapper is used for `find_with_related` queries where you want to fetch
102/// an entity along with all its related entities (1-to-many relationship).
103///
104/// The wrapper carries the `AccessScope` internally so further chained operations
105/// can apply scoping consistently.
106///
107/// # Type Parameters
108/// - `E`: The primary `SeaORM` entity type
109/// - `F`: The related `SeaORM` entity type
110/// - `S`: The typestate (`Scoped` - note: only Scoped state is supported)
111///
112/// # Example
113/// ```rust,ignore
114/// use modkit_db::secure::{AccessScope, SecureEntityExt};
115///
116/// let scope = AccessScope::tenants_only(vec![tenant_id]);
117/// let rows: Vec<(cake::Model, Vec<fruit::Model>)> = Cake::find()
118///     .secure()
119///     .scope_with(&scope)
120///     .find_with_related(fruit::Entity)  // scope auto-applied to fruit
121///     .all(db)
122///     .await?;
123/// ```
124#[must_use]
125#[derive(Clone, Debug)]
126pub struct SecureSelectTwoMany<E: EntityTrait, F: EntityTrait, S> {
127    pub(crate) inner: sea_orm::SelectTwoMany<E, F>,
128    pub(crate) state: S,
129}
130
131/// Extension trait to convert a regular `SeaORM` `Select` into a `SecureSelect`.
132pub trait SecureEntityExt<E: EntityTrait>: Sized {
133    /// Convert this select query into a secure (unscoped) select.
134    /// You must call `.scope_with()` before executing the query.
135    fn secure(self) -> SecureSelect<E, Unscoped>;
136}
137
138impl<E> SecureEntityExt<E> for sea_orm::Select<E>
139where
140    E: EntityTrait,
141{
142    fn secure(self) -> SecureSelect<E, Unscoped> {
143        SecureSelect {
144            inner: self,
145            state: Unscoped,
146        }
147    }
148}
149
150// Methods available only on Unscoped queries
151impl<E> SecureSelect<E, Unscoped>
152where
153    E: ScopableEntity + EntityTrait,
154    E::Column: ColumnTrait + Copy,
155{
156    /// Apply access control scope to this query, transitioning to the `Scoped` state.
157    ///
158    /// The scope is stored internally and will be automatically applied to any
159    /// related-entity queries (e.g., `find_also_related`, `find_with_related`).
160    ///
161    /// This applies the implicit policy:
162    /// - Empty scope → deny all
163    /// - Tenants only → filter by tenant
164    /// - Resources only → filter by resource IDs
165    /// - Both → AND them together
166    ///
167    pub fn scope_with(self, scope: &AccessScope) -> SecureSelect<E, Scoped> {
168        let cond = build_scope_condition::<E>(scope);
169        SecureSelect {
170            inner: self.inner.filter(cond),
171            state: Scoped {
172                scope: Arc::new(scope.clone()),
173            },
174        }
175    }
176
177    /// Apply access control scope using an `Arc<AccessScope>`.
178    ///
179    /// This is useful when you already have the scope in an `Arc` and want to
180    /// avoid an extra clone.
181    pub fn scope_with_arc(self, scope: Arc<AccessScope>) -> SecureSelect<E, Scoped> {
182        let cond = build_scope_condition::<E>(&scope);
183        SecureSelect {
184            inner: self.inner.filter(cond),
185            state: Scoped { scope },
186        }
187    }
188}
189
190// Methods available only on Scoped queries
191impl<E> SecureSelect<E, Scoped>
192where
193    E: EntityTrait,
194{
195    /// Execute the query and return all matching results.
196    ///
197    /// # Errors
198    /// Returns `ScopeError::Db` if the database query fails.
199    #[allow(clippy::disallowed_methods)]
200    pub async fn all(self, runner: &impl DBRunner) -> Result<Vec<E::Model>, ScopeError> {
201        match DBRunnerInternal::as_seaorm(runner) {
202            SeaOrmRunner::Conn(db) => Ok(self.inner.all(db).await?),
203            SeaOrmRunner::Tx(tx) => Ok(self.inner.all(tx).await?),
204        }
205    }
206
207    /// Execute the query and return at most one result.
208    ///
209    /// # Errors
210    /// Returns `ScopeError::Db` if the database query fails.
211    #[allow(clippy::disallowed_methods)]
212    pub async fn one(self, runner: &impl DBRunner) -> Result<Option<E::Model>, ScopeError> {
213        match DBRunnerInternal::as_seaorm(runner) {
214            SeaOrmRunner::Conn(db) => Ok(self.inner.one(db).await?),
215            SeaOrmRunner::Tx(tx) => Ok(self.inner.one(tx).await?),
216        }
217    }
218
219    /// Execute the query and return the number of matching results.
220    ///
221    /// # Errors
222    /// Returns `ScopeError::Db` if the database query fails.
223    #[allow(clippy::disallowed_methods)]
224    pub async fn count(self, runner: &impl DBRunner) -> Result<u64, ScopeError>
225    where
226        E::Model: sea_orm::FromQueryResult + Send + Sync,
227    {
228        match DBRunnerInternal::as_seaorm(runner) {
229            SeaOrmRunner::Conn(db) => Ok(self.inner.count(db).await?),
230            SeaOrmRunner::Tx(tx) => Ok(self.inner.count(tx).await?),
231        }
232    }
233
234    // Note: count() uses SeaORM's `PaginatorTrait::count` internally.
235
236    // Note: For pagination, use `into_inner().paginate()` due to complex lifetime bounds
237
238    /// Add an additional filter for a specific resource ID.
239    ///
240    /// This is useful when you want to further narrow a scoped query
241    /// to a single resource.
242    ///
243    /// # Example
244    /// ```ignore
245    /// let user = User::find()
246    ///     .secure()
247    ///     .scope_with(&scope)?
248    ///     .and_id(user_id)
249    ///     .one(conn)
250    ///     .await?;
251    /// ```
252    ///
253    /// # Errors
254    /// Returns `ScopeError::Invalid` if the entity doesn't have a resource column.
255    pub fn and_id(self, id: uuid::Uuid) -> Result<Self, ScopeError>
256    where
257        E: ScopableEntity,
258        E::Column: ColumnTrait + Copy,
259    {
260        let resource_col = E::resource_col().ok_or(ScopeError::Invalid(
261            "Entity must have a resource_col to use and_id()",
262        ))?;
263        let cond = sea_orm::Condition::all().add(Expr::col(resource_col).eq(id));
264        Ok(self.filter(cond))
265    }
266}
267
268// Allow further chaining on Scoped queries before execution
269impl<E> SecureSelect<E, Scoped>
270where
271    E: EntityTrait,
272{
273    /// Add additional filters to the scoped query.
274    /// The scope conditions remain in place.
275    pub fn filter(mut self, filter: sea_orm::Condition) -> Self {
276        self.inner = QueryFilter::filter(self.inner, filter);
277        self
278    }
279
280    /// Add ordering to the scoped query.
281    pub fn order_by<C>(mut self, col: C, order: sea_orm::Order) -> Self
282    where
283        C: sea_orm::IntoSimpleExpr,
284    {
285        self.inner = QueryOrder::order_by(self.inner, col, order);
286        self
287    }
288
289    /// Add a limit to the scoped query.
290    pub fn limit(mut self, limit: u64) -> Self {
291        self.inner = QuerySelect::limit(self.inner, limit);
292        self
293    }
294
295    /// Add an offset to the scoped query.
296    pub fn offset(mut self, offset: u64) -> Self {
297        self.inner = QuerySelect::offset(self.inner, offset);
298        self
299    }
300
301    /// Apply scoping for a joined entity.
302    ///
303    /// This is useful when you need to filter by tenant on a joined table.
304    ///
305    /// # Example
306    /// ```ignore
307    /// // Select orders, ensuring both Order and Customer match tenant scope
308    /// Order::find()
309    ///     .secure()
310    ///     .scope_with(&scope)?
311    ///     .and_scope_for::<customer::Entity>(&scope)
312    ///     .all(conn)
313    ///     .await?
314    /// ```
315    pub fn and_scope_for<J>(mut self, scope: &AccessScope) -> Self
316    where
317        J: ScopableEntity + EntityTrait,
318        J::Column: ColumnTrait + Copy,
319    {
320        if !scope.tenant_ids().is_empty()
321            && let Some(tcol) = J::tenant_col()
322        {
323            let condition = sea_orm::Condition::all()
324                .add(Expr::col((J::default(), tcol)).is_in(scope.tenant_ids().to_vec()));
325            self.inner = QueryFilter::filter(self.inner, condition);
326        }
327        self
328    }
329
330    /// Apply scoping via EXISTS subquery on a related entity.
331    ///
332    /// This is particularly useful when the base entity doesn't have a tenant column
333    /// but is related to one that does.
334    ///
335    /// # Note
336    /// This is a simplified version that filters by tenant on the joined entity.
337    /// For complex join predicates, use `into_inner()` and build custom EXISTS clauses.
338    ///
339    /// # Example
340    /// ```ignore
341    /// // Find settings that exist in a tenant-scoped relationship
342    /// GlobalSetting::find()
343    ///     .secure()
344    ///     .scope_with(&AccessScope::resources_only(vec![]))?
345    ///     .scope_via_exists::<TenantSetting>(&scope)
346    ///     .all(conn)
347    ///     .await?
348    /// ```
349    pub fn scope_via_exists<J>(mut self, scope: &AccessScope) -> Self
350    where
351        J: ScopableEntity + EntityTrait,
352        J::Column: ColumnTrait + Copy,
353    {
354        if !scope.tenant_ids().is_empty()
355            && let Some(tcol) = J::tenant_col()
356        {
357            // Build EXISTS clause with tenant filter on joined entity
358            use sea_orm::sea_query::Query;
359
360            let mut sub = Query::select();
361            sub.expr(Expr::value(1))
362                .from(J::default())
363                .cond_where(Expr::col((J::default(), tcol)).is_in(scope.tenant_ids().to_vec()));
364
365            self.inner =
366                QueryFilter::filter(self.inner, sea_orm::Condition::all().add(Expr::exists(sub)));
367        }
368        self
369    }
370
371    /// Unwrap the inner `SeaORM` `Select` for advanced use cases.
372    ///
373    /// # Safety
374    /// The caller must ensure they don't remove or bypass the security
375    /// conditions that were applied during `.scope_with()`.
376    #[must_use]
377    pub fn into_inner(self) -> sea_orm::Select<E> {
378        self.inner
379    }
380}
381
382// =============================================================================
383// Relationship Query Methods on SecureSelect<E, Scoped>
384// =============================================================================
385
386/// Helper to apply scope filtering to a related entity if it has a tenant column.
387fn apply_related_scope<R>(scope: &AccessScope) -> Option<sea_orm::Condition>
388where
389    R: ScopableEntity + EntityTrait,
390    R::Column: ColumnTrait + Copy,
391{
392    if !scope.tenant_ids().is_empty()
393        && let Some(tcol) = R::tenant_col()
394    {
395        Some(
396            sea_orm::Condition::all()
397                .add(Expr::col((R::default(), tcol)).is_in(scope.tenant_ids().to_vec())),
398        )
399    } else {
400        None
401    }
402}
403
404impl<E> SecureSelect<E, Scoped>
405where
406    E: EntityTrait,
407{
408    /// Get a reference to the stored scope.
409    ///
410    /// This is useful when you need to pass the scope to other secure operations.
411    #[must_use]
412    pub fn scope(&self) -> &AccessScope {
413        &self.state.scope
414    }
415
416    /// Get the stored scope as an `Arc`.
417    ///
418    /// This is useful when you need to share the scope without cloning.
419    #[must_use]
420    pub fn scope_arc(&self) -> Arc<AccessScope> {
421        Arc::clone(&self.state.scope)
422    }
423
424    /// Find related entities using `find_also_related` with automatic scoping.
425    ///
426    /// This executes a LEFT JOIN to fetch the primary entity along with an
427    /// optional related entity. The related entity will be `None` if no
428    /// matching row exists.
429    ///
430    /// # Automatic Scoping
431    /// - The primary entity `E` is already scoped by the parent `SecureSelect`.
432    /// - The related entity `R` will automatically have tenant filtering applied
433    ///   **if it has a tenant column** (i.e., `R::tenant_col()` returns `Some`).
434    /// - For **global entities** (those with `#[secure(no_tenant)]`), no additional
435    ///   filtering is applied — the scoping becomes a no-op automatically.
436    ///
437    /// This unified API handles both tenant-scoped and global entities transparently.
438    /// The caller does not need to know or care whether the related entity is
439    /// tenant-scoped or global.
440    ///
441    /// # Entity Requirements
442    /// All entities used with this method must derive `Scopable`. For global entities,
443    /// use `#[secure(no_tenant, no_resource, no_owner, no_type)]`.
444    ///
445    /// # Example
446    /// ```rust,ignore
447    /// let scope = AccessScope::tenants_only(vec![tenant_id]);
448    ///
449    /// // Tenant-scoped related entity - scope is auto-applied to Customer
450    /// let rows: Vec<(order::Model, Option<customer::Model>)> = Order::find()
451    ///     .secure()
452    ///     .scope_with(&scope)
453    ///     .find_also_related(customer::Entity)
454    ///     .all(db)
455    ///     .await?;
456    ///
457    /// // Global related entity (no tenant column) - no filtering applied to GlobalConfig
458    /// let rows: Vec<(order::Model, Option<global_config::Model>)> = Order::find()
459    ///     .secure()
460    ///     .scope_with(&scope)
461    ///     .find_also_related(global_config::Entity)  // same API, auto no-op!
462    ///     .all(db)
463    ///     .await?;
464    /// ```
465    pub fn find_also_related<R>(self, r: R) -> SecureSelectTwo<E, R, Scoped>
466    where
467        R: ScopableEntity + EntityTrait,
468        R::Column: ColumnTrait + Copy,
469        E: Related<R>,
470    {
471        let select_two = self.inner.find_also_related(r);
472
473        // Auto-apply scope to the related entity R (no-op if R has no tenant_col)
474        let select_two = if let Some(cond) = apply_related_scope::<R>(&self.state.scope) {
475            QueryFilter::filter(select_two, cond)
476        } else {
477            select_two
478        };
479
480        SecureSelectTwo {
481            inner: select_two,
482            state: self.state,
483        }
484    }
485
486    /// Find all related entities using `find_with_related` with automatic scoping.
487    ///
488    /// This executes a query to fetch the primary entity along with all its
489    /// related entities (one-to-many relationship).
490    ///
491    /// # Automatic Scoping
492    /// - The primary entity `E` is already scoped by the parent `SecureSelect`.
493    /// - The related entity `R` will automatically have tenant filtering applied
494    ///   **if it has a tenant column** (i.e., `R::tenant_col()` returns `Some`).
495    /// - For **global entities** (those with `#[secure(no_tenant)]`), no additional
496    ///   filtering is applied — the scoping becomes a no-op automatically.
497    ///
498    /// This unified API handles both tenant-scoped and global entities transparently.
499    /// The caller does not need to know or care whether the related entity is
500    /// tenant-scoped or global.
501    ///
502    /// # Entity Requirements
503    /// All entities used with this method must derive `Scopable`. For global entities,
504    /// use `#[secure(no_tenant, no_resource, no_owner, no_type)]`.
505    ///
506    /// # Example
507    /// ```rust,ignore
508    /// let scope = AccessScope::tenants_only(vec![tenant_id]);
509    ///
510    /// // Tenant-scoped related entity - scope is auto-applied to LineItem
511    /// let rows: Vec<(order::Model, Vec<line_item::Model>)> = Order::find()
512    ///     .secure()
513    ///     .scope_with(&scope)
514    ///     .find_with_related(line_item::Entity)
515    ///     .all(db)
516    ///     .await?;
517    ///
518    /// // Global related entity (no tenant column) - no filtering applied to SystemTag
519    /// let rows: Vec<(order::Model, Vec<system_tag::Model>)> = Order::find()
520    ///     .secure()
521    ///     .scope_with(&scope)
522    ///     .find_with_related(system_tag::Entity)  // same API, auto no-op!
523    ///     .all(db)
524    ///     .await?;
525    /// ```
526    pub fn find_with_related<R>(self, r: R) -> SecureSelectTwoMany<E, R, Scoped>
527    where
528        R: ScopableEntity + EntityTrait,
529        R::Column: ColumnTrait + Copy,
530        E: Related<R>,
531    {
532        let select_two_many = self.inner.find_with_related(r);
533
534        // Auto-apply scope to the related entity R (no-op if R has no tenant_col)
535        let select_two_many = if let Some(cond) = apply_related_scope::<R>(&self.state.scope) {
536            QueryFilter::filter(select_two_many, cond)
537        } else {
538            select_two_many
539        };
540
541        SecureSelectTwoMany {
542            inner: select_two_many,
543            state: self.state,
544        }
545    }
546}
547
548// =============================================================================
549// SecureSelectTwo<E, F, Scoped> - Execution methods
550// =============================================================================
551
552impl<E, F> SecureSelectTwo<E, F, Scoped>
553where
554    E: EntityTrait,
555    F: EntityTrait,
556{
557    /// Get a reference to the stored scope.
558    #[must_use]
559    pub fn scope(&self) -> &AccessScope {
560        &self.state.scope
561    }
562
563    /// Get the stored scope as an `Arc`.
564    #[must_use]
565    pub fn scope_arc(&self) -> Arc<AccessScope> {
566        Arc::clone(&self.state.scope)
567    }
568
569    /// Execute the query and return all matching results.
570    ///
571    /// Returns pairs of `(E::Model, Option<F::Model>)`.
572    ///
573    /// # Errors
574    /// Returns `ScopeError::Db` if the database query fails.
575    #[allow(clippy::disallowed_methods)]
576    pub async fn all(
577        self,
578        runner: &impl DBRunner,
579    ) -> Result<Vec<(E::Model, Option<F::Model>)>, ScopeError> {
580        match DBRunnerInternal::as_seaorm(runner) {
581            SeaOrmRunner::Conn(db) => Ok(self.inner.all(db).await?),
582            SeaOrmRunner::Tx(tx) => Ok(self.inner.all(tx).await?),
583        }
584    }
585
586    /// Execute the query and return at most one result.
587    ///
588    /// # Errors
589    /// Returns `ScopeError::Db` if the database query fails.
590    #[allow(clippy::disallowed_methods)]
591    pub async fn one(
592        self,
593        runner: &impl DBRunner,
594    ) -> Result<Option<(E::Model, Option<F::Model>)>, ScopeError> {
595        match DBRunnerInternal::as_seaorm(runner) {
596            SeaOrmRunner::Conn(db) => Ok(self.inner.one(db).await?),
597            SeaOrmRunner::Tx(tx) => Ok(self.inner.one(tx).await?),
598        }
599    }
600
601    /// Add additional filters to the query.
602    pub fn filter(mut self, filter: sea_orm::Condition) -> Self {
603        self.inner = QueryFilter::filter(self.inner, filter);
604        self
605    }
606
607    /// Add ordering to the query.
608    pub fn order_by<C>(mut self, col: C, order: sea_orm::Order) -> Self
609    where
610        C: sea_orm::IntoSimpleExpr,
611    {
612        self.inner = QueryOrder::order_by(self.inner, col, order);
613        self
614    }
615
616    /// Add a limit to the query.
617    pub fn limit(mut self, limit: u64) -> Self {
618        self.inner = QuerySelect::limit(self.inner, limit);
619        self
620    }
621
622    /// Unwrap the inner `SeaORM` `SelectTwo` for advanced use cases.
623    #[must_use]
624    pub fn into_inner(self) -> sea_orm::SelectTwo<E, F> {
625        self.inner
626    }
627}
628
629// =============================================================================
630// SecureSelectTwoMany<E, F, Scoped> - Execution methods
631// =============================================================================
632
633impl<E, F> SecureSelectTwoMany<E, F, Scoped>
634where
635    E: EntityTrait,
636    F: EntityTrait,
637{
638    /// Get a reference to the stored scope.
639    #[must_use]
640    pub fn scope(&self) -> &AccessScope {
641        &self.state.scope
642    }
643
644    /// Get the stored scope as an `Arc`.
645    #[must_use]
646    pub fn scope_arc(&self) -> Arc<AccessScope> {
647        Arc::clone(&self.state.scope)
648    }
649
650    /// Execute the query and return all matching results.
651    ///
652    /// Returns pairs of `(E::Model, Vec<F::Model>)`.
653    ///
654    /// # Errors
655    /// Returns `ScopeError::Db` if the database query fails.
656    #[allow(clippy::disallowed_methods)]
657    pub async fn all(
658        self,
659        runner: &impl DBRunner,
660    ) -> Result<Vec<(E::Model, Vec<F::Model>)>, ScopeError> {
661        match DBRunnerInternal::as_seaorm(runner) {
662            SeaOrmRunner::Conn(db) => Ok(self.inner.all(db).await?),
663            SeaOrmRunner::Tx(tx) => Ok(self.inner.all(tx).await?),
664        }
665    }
666
667    /// Add additional filters to the query.
668    pub fn filter(mut self, filter: sea_orm::Condition) -> Self {
669        self.inner = QueryFilter::filter(self.inner, filter);
670        self
671    }
672
673    /// Add ordering to the query.
674    pub fn order_by<C>(mut self, col: C, order: sea_orm::Order) -> Self
675    where
676        C: sea_orm::IntoSimpleExpr,
677    {
678        self.inner = QueryOrder::order_by(self.inner, col, order);
679        self
680    }
681
682    /// Unwrap the inner `SeaORM` `SelectTwoMany` for advanced use cases.
683    #[must_use]
684    pub fn into_inner(self) -> sea_orm::SelectTwoMany<E, F> {
685        self.inner
686    }
687}
688
689// =============================================================================
690// Model-level find_related Extension Trait
691// =============================================================================
692
693/// Extension trait to perform secure `find_related` queries from a model instance.
694///
695/// This trait provides a way to find entities related to an already-loaded model
696/// while maintaining security scope constraints.
697///
698/// # Example
699/// ```rust,ignore
700/// use modkit_db::secure::{AccessScope, SecureFindRelatedExt};
701///
702/// // Load a cake
703/// let cake: cake::Model = db.find_by_id::<cake::Entity>(&scope, cake_id)?
704///     .one(db)
705///     .await?
706///     .unwrap();
707///
708/// // Find all related fruits with scoping
709/// let fruits: Vec<fruit::Model> = cake
710///     .secure_find_related(fruit::Entity, &scope)
711///     .all(db)
712///     .await?;
713/// ```
714pub trait SecureFindRelatedExt: ModelTrait {
715    /// Find related entities with access scope applied.
716    ///
717    /// This creates a scoped query for entities related to this model.
718    /// The scope is applied to the related entity to ensure tenant isolation.
719    ///
720    /// # Type Parameters
721    /// - `R`: The related entity type that must implement `ScopableEntity`
722    ///
723    /// # Arguments
724    /// - `r`: The related entity marker (e.g., `fruit::Entity`)
725    /// - `scope`: The access scope to apply to the related entity query
726    fn secure_find_related<R>(&self, r: R, scope: &AccessScope) -> SecureSelect<R, Scoped>
727    where
728        R: ScopableEntity + EntityTrait,
729        R::Column: ColumnTrait + Copy,
730        Self::Entity: Related<R>;
731}
732
733impl<M> SecureFindRelatedExt for M
734where
735    M: ModelTrait,
736{
737    fn secure_find_related<R>(&self, r: R, scope: &AccessScope) -> SecureSelect<R, Scoped>
738    where
739        R: ScopableEntity + EntityTrait,
740        R::Column: ColumnTrait + Copy,
741        Self::Entity: Related<R>,
742    {
743        // Use SeaORM's find_related to build the base query
744        let select = self.find_related(r);
745
746        // Apply scope to the related entity
747        select.secure().scope_with(scope)
748    }
749}
750
751#[cfg(test)]
752#[cfg_attr(coverage_nightly, coverage(off))]
753mod tests {
754    use super::*;
755
756    // Note: Full integration tests with real SeaORM entities should be written
757    // in application code where actual entities are available.
758    // The typestate pattern is enforced at compile time.
759    //
760    // See USAGE_EXAMPLE.md for complete usage patterns.
761
762    #[test]
763    fn test_typestate_markers_exist() {
764        // This test verifies the typestate markers compile
765        // The actual enforcement happens at compile time
766        let unscoped = Unscoped;
767        assert!(std::mem::size_of_val(&unscoped) == 0); // Unscoped is zero-sized
768
769        // Scoped now requires an AccessScope
770        let scope = AccessScope::default();
771        let scoped = Scoped {
772            scope: Arc::new(scope),
773        };
774        assert!(!scoped.scope.has_tenants()); // default scope has no tenants
775    }
776
777    #[test]
778    fn test_scoped_state_holds_scope() {
779        let tenant_id = uuid::Uuid::new_v4();
780        let scope = AccessScope::tenants_only(vec![tenant_id]);
781        let scoped = Scoped {
782            scope: Arc::new(scope),
783        };
784
785        // Verify the scope is accessible
786        assert!(scoped.scope.has_tenants());
787        assert_eq!(scoped.scope.tenant_ids().len(), 1);
788        assert!(scoped.scope.tenant_ids().contains(&tenant_id));
789    }
790
791    #[test]
792    fn test_scoped_state_is_cloneable() {
793        let scope = AccessScope::tenants_only(vec![uuid::Uuid::new_v4()]);
794        let scoped = Scoped {
795            scope: Arc::new(scope),
796        };
797
798        // Cloning should share the Arc
799        let cloned = scoped.clone();
800        assert!(Arc::ptr_eq(&scoped.scope, &cloned.scope));
801    }
802}