Skip to main content

rustango_cms/
collection_view_restriction.rs

1//! `CollectionViewRestriction` — gate served media bytes behind a
2//! login requirement or group membership check.
3//!
4//! Mirrors [`crate::view_restriction::PageViewRestriction`] but keyed
5//! by [`crate::media::MediaCollection`]. Restrictions inherit DOWN
6//! the collection tree: a restriction on "Internal docs" covers
7//! every child collection unless a child declares its own.
8//!
9//! The public renderer enforces the restriction in
10//! [`crate::rendition_route`] — `<img src="/__media__/.../<id>">`
11//! returns 401 / 403 when the request doesn't satisfy the nearest
12//! restriction.
13
14use chrono::{DateTime, Utc};
15use rustango::sql::Auto;
16use rustango::Model;
17use serde::{Deserialize, Serialize};
18
19pub use crate::view_restriction::RestrictionKind;
20
21#[derive(Model, Debug, Clone, Serialize, Deserialize)]
22#[rustango(
23    table = "cms_collection_view_restriction",
24    app = "cms",
25    display = "collection_id",
26    admin(
27        list_display = "collection_id, kind, created_at",
28        ordering = "-created_at",
29        list_filter = "kind",
30    )
31)]
32pub struct CollectionViewRestriction {
33    #[rustango(primary_key)]
34    pub id: Auto<i64>,
35
36    /// One restriction per collection — application-enforced UNIQUE.
37    #[rustango(fk = "cms_media_collection", on = "id", index)]
38    pub collection_id: i64,
39
40    /// `RestrictionKind::as_str()`.
41    #[rustango(max_length = 16, index)]
42    pub kind: String,
43
44    /// Argon2id PHC hash. Empty string when `kind != password`.
45    #[rustango(max_length = 255, default = "''")]
46    pub password_hash: String,
47
48    /// JSON array of `rustango_roles.id` integers — admitted groups
49    /// when `kind = groups`. Empty array on other kinds.
50    pub group_ids: serde_json::Value,
51
52    /// JSON array of permission codename strings — admitted permissions
53    /// when `kind = permission` (any one grants access). Empty array on
54    /// other kinds. See [`RestrictionKind::Permission`].
55    #[rustango(default = "'[]'")]
56    pub codenames: serde_json::Value,
57
58    #[rustango(auto_now_add)]
59    pub created_at: Auto<DateTime<Utc>>,
60
61    #[rustango(auto_now)]
62    pub updated_at: Auto<DateTime<Utc>>,
63}
64
65impl CollectionViewRestriction {
66    #[must_use]
67    pub fn parsed_kind(&self) -> Option<RestrictionKind> {
68        RestrictionKind::parse(&self.kind)
69    }
70
71    #[must_use]
72    pub fn parsed_groups(&self) -> Vec<i64> {
73        self.group_ids
74            .as_array()
75            .map(|arr| arr.iter().filter_map(|v| v.as_i64()).collect::<Vec<_>>())
76            .unwrap_or_default()
77    }
78
79    /// Read `codenames` as `Vec<String>`. Returns empty when the field
80    /// is malformed or missing (a NULL column on a pre-migration row).
81    #[must_use]
82    pub fn parsed_codenames(&self) -> Vec<String> {
83        self.codenames
84            .as_array()
85            .map(|arr| {
86                arr.iter()
87                    .filter_map(|v| v.as_str().map(str::to_owned))
88                    .collect::<Vec<_>>()
89            })
90            .unwrap_or_default()
91    }
92}
93
94/// Look up a direct (non-inherited) restriction on a single collection.
95///
96/// # Errors
97/// Driver / query failures.
98pub async fn direct_for_collection(
99    pool: &rustango::sql::Pool,
100    collection_id: i64,
101) -> Result<Option<CollectionViewRestriction>, rustango::sql::ExecError> {
102    use rustango::core::Column as _;
103    use rustango::sql::FetcherPool as _;
104    let rows: Vec<CollectionViewRestriction> = CollectionViewRestriction::objects()
105        .where_(CollectionViewRestriction::collection_id.eq(collection_id))
106        .fetch(pool)
107        .await?;
108    Ok(rows.into_iter().next())
109}
110
111/// Walk the collection + every ancestor in parent order (current
112/// first, then parent, then grand-parent, …) and return the *nearest*
113/// restriction found. Mirrors
114/// [`crate::view_restriction::effective_for_page`] for collections.
115///
116/// # Errors
117/// Driver / query failures.
118pub async fn effective_for_collection(
119    pool: &rustango::sql::Pool,
120    collection_id: i64,
121) -> Result<Option<CollectionViewRestriction>, rustango::sql::ExecError> {
122    use rustango::core::Column as _;
123    use rustango::sql::FetcherPool as _;
124
125    // Resolve the ancestor chain by walking `parent_id` up to a max
126    // depth — collections are shallow trees (a handful of levels
127    // typical), so the N+1 lookup is acceptable. Bail out on cycles.
128    let mut chain: Vec<i64> = vec![collection_id];
129    let mut seen: std::collections::HashSet<i64> = std::collections::HashSet::new();
130    seen.insert(collection_id);
131    let mut current_id = collection_id;
132    for _ in 0..16 {
133        let rows: Vec<crate::media::MediaCollection> = crate::media::MediaCollection::objects()
134            .where_(crate::media::MediaCollection::id.eq(current_id))
135            .fetch(pool)
136            .await?;
137        let Some(c) = rows.into_iter().next() else {
138            break;
139        };
140        let Some(pid) = c.parent_id else {
141            break;
142        };
143        if !seen.insert(pid) {
144            break;
145        }
146        chain.push(pid);
147        current_id = pid;
148    }
149
150    let restrictions: Vec<CollectionViewRestriction> = CollectionViewRestriction::objects()
151        .where_(CollectionViewRestriction::collection_id.is_in(chain.clone()))
152        .fetch(pool)
153        .await?;
154    if restrictions.is_empty() {
155        return Ok(None);
156    }
157    let by_collection: std::collections::HashMap<i64, CollectionViewRestriction> = restrictions
158        .into_iter()
159        .map(|r| (r.collection_id, r))
160        .collect();
161    for cid in chain {
162        if let Some(r) = by_collection.get(&cid) {
163            return Ok(Some(r.clone()));
164        }
165    }
166    Ok(None)
167}
168
169/// Which of `collection_ids` this viewer may **not** see.
170///
171/// The batched counterpart to [`effective_for_collection`], which walks
172/// the ancestor chain with a query per level — fine for one asset, hopeless
173/// for a list of them. This loads every collection and every restriction
174/// once, then resolves each chain in memory.
175///
176/// It exists because the JSON list endpoints did no collection gating at
177/// all: `/__media__/{spec}/{id}` refuses an asset in a login-gated
178/// collection, while `/api/v2/images/` happily listed its title, filename
179/// and dimensions to anyone. The bytes were protected; the catalogue was
180/// not.
181pub async fn denied_collection_ids(
182    pool: &rustango::sql::Pool,
183    viewer: Option<&rustango::tenancy::auth::User>,
184    collection_ids: &[i64],
185) -> std::collections::HashSet<i64> {
186    use rustango::sql::FetcherPool as _;
187    use std::collections::{HashMap, HashSet};
188
189    let mut denied: HashSet<i64> = HashSet::new();
190    if collection_ids.is_empty() {
191        return denied;
192    }
193
194    let restrictions: Vec<CollectionViewRestriction> =
195        match CollectionViewRestriction::objects().fetch(pool).await {
196            Ok(r) => r,
197            Err(e) => {
198                // Fail *closed* would break every gallery on a transient
199                // error; fail open matches `access_context`, which logs
200                // and allows. The bytes stay gated either way.
201                tracing::warn!(
202                    target: "rustango_cms::collection_view_restriction",
203                    error = %e,
204                    "collection restriction lookup failed; treating collections as public",
205                );
206                return denied;
207            }
208        };
209    if restrictions.is_empty() {
210        return denied;
211    }
212    let by_collection: HashMap<i64, &CollectionViewRestriction> = restrictions
213        .iter()
214        .map(|r| (r.collection_id, r))
215        .collect();
216
217    let parents: HashMap<i64, Option<i64>> = crate::media::MediaCollection::objects()
218        .fetch(pool)
219        .await
220        .unwrap_or_default()
221        .into_iter()
222        .filter_map(|c| c.id.get().copied().map(|id| (id, c.parent_id)))
223        .collect();
224
225    let facts = crate::view_restriction::viewer_facts(pool, viewer, true).await;
226
227    for &id in collection_ids {
228        // Nearest restriction wins, walking up. Bounded and cycle-safe,
229        // like `effective_for_collection`.
230        let mut current = Some(id);
231        let mut seen: HashSet<i64> = HashSet::new();
232        for _ in 0..16 {
233            let Some(cid) = current else { break };
234            if !seen.insert(cid) {
235                break;
236            }
237            if let Some(r) = by_collection.get(&cid) {
238                if !facts.satisfies(r.parsed_kind(), &r.parsed_groups(), &r.parsed_codenames()) {
239                    denied.insert(id);
240                }
241                break;
242            }
243            current = parents.get(&cid).copied().flatten();
244        }
245    }
246    denied
247}