1use std::{
2 collections::{BTreeMap, BTreeSet},
3 path::{Component, Path, PathBuf},
4};
5
6use chrono::{DateTime, Utc};
7use serde::{Deserialize, Serialize};
8use uuid::Uuid;
9
10use crate::{FolderbaseError, Result};
11
12#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
13pub struct FolderbaseRegistration {
14 pub folderbase_id: String,
15 pub owner_member_id: String,
16 pub name: String,
17}
18
19#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
20pub struct ShareGrant {
21 pub id: String,
22 pub folderbase_id: String,
23 pub grantee_member_id: String,
24 pub scope: ShareScope,
25 pub permissions: BTreeSet<SharePermission>,
26 pub expires_at: Option<DateTime<Utc>>,
27 pub include_future_content: bool,
28 pub revoked_at: Option<DateTime<Utc>>,
29}
30
31#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
32#[serde(tag = "type", rename_all = "snake_case")]
33pub enum ShareScope {
34 Folderbase,
35 Folder {
36 path: PathBuf,
37 },
38 Object {
39 object_id: String,
40 path: PathBuf,
41 },
42 View {
43 view_id: String,
44 paths: Vec<PathBuf>,
45 },
46}
47
48#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
49#[serde(rename_all = "snake_case")]
50pub enum SharePermission {
51 Read,
52 Edit,
53 Download,
54 Reshare,
55}
56
57#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
58pub struct AccessRequest {
59 pub member_id: String,
60 pub agent_session: Option<String>,
61 pub folderbase_id: String,
62 pub path: PathBuf,
63 pub permission: SharePermission,
64 pub at: DateTime<Utc>,
65}
66
67#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
68pub struct AccessDecision {
69 pub allowed: bool,
70 pub reason: AccessReason,
71 pub grant_id: Option<String>,
72}
73
74#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
75#[serde(rename_all = "snake_case")]
76pub enum AccessReason {
77 Owner,
78 ExplicitGrant,
79 NoGrant,
80 Expired,
81 Revoked,
82 OutsideScope,
83 PermissionMissing,
84}
85
86#[derive(Debug, Default)]
91pub struct SharingControlPlane {
92 folderbases: BTreeMap<String, FolderbaseRegistration>,
93 grants: BTreeMap<String, ShareGrant>,
94}
95
96impl SharingControlPlane {
97 pub fn new() -> Self {
98 Self::default()
99 }
100
101 pub fn register_folderbase(&mut self, registration: FolderbaseRegistration) -> Result<()> {
102 if !registration.folderbase_id.starts_with("folderbase_")
103 || registration.owner_member_id.trim().is_empty()
104 || registration.name.trim().is_empty()
105 {
106 return Err(FolderbaseError::InvalidRecord {
107 path: PathBuf::from("folderbase-registration"),
108 message: "folderbase id, owner, and name are required".to_owned(),
109 });
110 }
111 if self.folderbases.contains_key(®istration.folderbase_id) {
112 return Err(FolderbaseError::WouldOverwrite(PathBuf::from(
113 registration.folderbase_id,
114 )));
115 }
116 self.folderbases
117 .insert(registration.folderbase_id.clone(), registration);
118 Ok(())
119 }
120
121 #[allow(clippy::too_many_arguments)]
122 pub fn create_grant(
123 &mut self,
124 owner_member_id: &str,
125 folderbase_id: &str,
126 grantee_member_id: impl Into<String>,
127 scope: ShareScope,
128 permissions: BTreeSet<SharePermission>,
129 expires_at: Option<DateTime<Utc>>,
130 include_future_content: bool,
131 ) -> Result<ShareGrant> {
132 let registration =
133 self.folderbases
134 .get(folderbase_id)
135 .ok_or_else(|| FolderbaseError::InvalidRecord {
136 path: PathBuf::from(folderbase_id),
137 message: "folderbase is not registered".to_owned(),
138 })?;
139 if registration.owner_member_id != owner_member_id {
140 return Err(FolderbaseError::InvalidRecord {
141 path: PathBuf::from(folderbase_id),
142 message: "only the folderbase owner may create a grant".to_owned(),
143 });
144 }
145 validate_scope(&scope)?;
146 if permissions.is_empty() {
147 return Err(FolderbaseError::InvalidRecord {
148 path: PathBuf::from(folderbase_id),
149 message: "a grant must name at least one permission".to_owned(),
150 });
151 }
152 let grantee_member_id = grantee_member_id.into();
153 if grantee_member_id.trim().is_empty() {
154 return Err(FolderbaseError::InvalidRecord {
155 path: PathBuf::from(folderbase_id),
156 message: "grantee member id is required".to_owned(),
157 });
158 }
159 let grant = ShareGrant {
160 id: format!("grant_{}", Uuid::now_v7()),
161 folderbase_id: folderbase_id.to_owned(),
162 grantee_member_id,
163 scope,
164 permissions,
165 expires_at,
166 include_future_content,
167 revoked_at: None,
168 };
169 self.grants.insert(grant.id.clone(), grant.clone());
170 Ok(grant)
171 }
172
173 pub fn revoke(
174 &mut self,
175 owner_member_id: &str,
176 grant_id: &str,
177 at: DateTime<Utc>,
178 ) -> Result<()> {
179 let grant =
180 self.grants
181 .get_mut(grant_id)
182 .ok_or_else(|| FolderbaseError::InvalidRecord {
183 path: PathBuf::from(grant_id),
184 message: "grant does not exist".to_owned(),
185 })?;
186 let folderbase = self.folderbases.get(&grant.folderbase_id).ok_or_else(|| {
187 FolderbaseError::InvalidRecord {
188 path: PathBuf::from(&grant.folderbase_id),
189 message: "grant references an unregistered folderbase".to_owned(),
190 }
191 })?;
192 if folderbase.owner_member_id != owner_member_id {
193 return Err(FolderbaseError::InvalidRecord {
194 path: PathBuf::from(grant_id),
195 message: "only the folderbase owner may revoke a grant".to_owned(),
196 });
197 }
198 grant.revoked_at = Some(at);
199 Ok(())
200 }
201
202 pub fn authorize(&self, request: &AccessRequest) -> Result<AccessDecision> {
203 ensure_safe_relative(&request.path)?;
204 let registration = self
205 .folderbases
206 .get(&request.folderbase_id)
207 .ok_or_else(|| FolderbaseError::InvalidRecord {
208 path: PathBuf::from(&request.folderbase_id),
209 message: "folderbase is not registered".to_owned(),
210 })?;
211 if registration.owner_member_id == request.member_id {
212 return Ok(AccessDecision {
213 allowed: true,
214 reason: AccessReason::Owner,
215 grant_id: None,
216 });
217 }
218
219 let candidates = self
220 .grants
221 .values()
222 .filter(|grant| {
223 grant.folderbase_id == request.folderbase_id
224 && grant.grantee_member_id == request.member_id
225 })
226 .collect::<Vec<_>>();
227 if candidates.is_empty() {
228 return Ok(denied(AccessReason::NoGrant));
229 }
230
231 let mut most_specific_denial = AccessReason::OutsideScope;
232 for grant in candidates {
233 if grant
234 .revoked_at
235 .is_some_and(|revoked| revoked <= request.at)
236 {
237 most_specific_denial = AccessReason::Revoked;
238 continue;
239 }
240 if grant.expires_at.is_some_and(|expiry| expiry <= request.at) {
241 most_specific_denial = AccessReason::Expired;
242 continue;
243 }
244 if !scope_contains(&grant.scope, &request.path) {
245 continue;
246 }
247 if !grant.permissions.contains(&request.permission) {
248 most_specific_denial = AccessReason::PermissionMissing;
249 continue;
250 }
251 return Ok(AccessDecision {
252 allowed: true,
253 reason: AccessReason::ExplicitGrant,
254 grant_id: Some(grant.id.clone()),
255 });
256 }
257 Ok(denied(most_specific_denial))
258 }
259}
260
261fn denied(reason: AccessReason) -> AccessDecision {
262 AccessDecision {
263 allowed: false,
264 reason,
265 grant_id: None,
266 }
267}
268
269fn validate_scope(scope: &ShareScope) -> Result<()> {
270 match scope {
271 ShareScope::Folderbase => Ok(()),
272 ShareScope::Folder { path } | ShareScope::Object { path, .. } => ensure_safe_relative(path),
273 ShareScope::View { paths, .. } => {
274 if paths.is_empty() {
275 return Err(FolderbaseError::InvalidRecord {
276 path: PathBuf::from("view"),
277 message: "a shared view must include at least one path".to_owned(),
278 });
279 }
280 for path in paths {
281 ensure_safe_relative(path)?;
282 }
283 Ok(())
284 }
285 }
286}
287
288fn scope_contains(scope: &ShareScope, requested: &Path) -> bool {
289 match scope {
290 ShareScope::Folderbase => true,
291 ShareScope::Folder { path } => requested == path || requested.starts_with(path),
292 ShareScope::Object { path, .. } => requested == path,
293 ShareScope::View { paths, .. } => paths
294 .iter()
295 .any(|path| requested == path || requested.starts_with(path)),
296 }
297}
298
299fn ensure_safe_relative(path: &Path) -> Result<()> {
300 if path.as_os_str().is_empty()
301 || path.is_absolute()
302 || path
303 .components()
304 .any(|component| !matches!(component, Component::Normal(_)))
305 {
306 return Err(FolderbaseError::UnsafePath(path.to_path_buf()));
307 }
308 Ok(())
309}