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
//! Shared server state, caller-identity resolution, and active-organisation
//! resolution.
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use apiplant_auth::{Authenticator, OrgMembership, Principal};
use apiplant_cache::Cache;
use apiplant_core::App;
use apiplant_db::Db;
use apiplant_email::Mailer;
use ntex::web::HttpRequest;
use uuid::Uuid;
use crate::functions::FunctionRegistry;
/// Immutable state shared across every worker and request.
#[derive(Clone)]
pub struct AppState {
pub app: Arc<App>,
pub db: Db,
pub auth: Authenticator,
pub functions: Arc<FunctionRegistry>,
/// The app's email provider, when `[email]` names one. Functions reach it
/// through `send_email`; nothing else in the server sends mail.
pub mailer: Option<Mailer>,
/// The app's Redis cache, when `[cache]` names one. Functions reach it
/// through `cache`; no framework path caches through it.
pub cache: Option<Cache>,
/// Everything served alongside the API: the dashboard and the public site.
pub statics: Arc<Statics>,
/// The admin manifest for this app, built on boot.
pub admin_manifest: Arc<String>,
/// Pre-rendered OpenAPI document (JSON).
pub openapi_json: Arc<String>,
/// Pre-rendered Swagger UI page.
pub docs_html: Arc<String>,
}
/// What the server serves besides the API: the admin dashboard, the app's
/// `public/` directory, and the page for requests that match nothing.
///
/// Resolved once, on boot, so every worker registers the same routes — and so
/// the route table is decided in one place rather than at request time.
#[derive(Debug, Default, Clone)]
pub struct Statics {
/// Path the dashboard is mounted at, or `None` when it's switched off.
pub admin_path: Option<String>,
/// Static site root (`public/`) when the app has one.
pub public_dir: Option<PathBuf>,
/// Route patterns for the files in it, one entry per URL they answer on.
pub public_routes: Vec<String>,
/// Page to answer unmatched requests with.
pub not_found_page: Option<PathBuf>,
}
impl Statics {
/// Work out what a loaded app serves statically.
pub fn resolve(app: &App) -> Statics {
let admin_path = app
.config
.admin
.enabled
.then(|| app.config.admin.path.clone());
let public_dir = app.root.join(&app.config.public.dir);
let public_dir = (app.config.public.enabled && public_dir.is_dir()).then_some(public_dir);
let mut public_routes = Vec::new();
let mut not_found_page = None;
if let Some(root) = &public_dir {
let mut files = Vec::new();
crate::walk_public(root, "", &mut files);
files.sort();
public_routes = files.iter().flat_map(|f| crate::public_routes(f)).collect();
// A 404 page is opt-out, not opt-in: `404.html` is what people
// already call the file, so finding one is enough to use it.
let candidate = app.config.public.not_found.as_deref().unwrap_or("404.html");
let page = root.join(candidate);
if page.is_file() {
not_found_page = Some(page);
} else if app.config.public.not_found.is_some() {
tracing::warn!(
path = %page.display(),
"public.not_found points at a file that doesn't exist"
);
}
}
Statics {
admin_path,
public_dir,
public_routes,
not_found_page,
}
}
}
impl AppState {
/// Resolve the caller (identity + organisation memberships) from the request.
///
/// Identity comes from `Authorization: Bearer <jwt>`, `Authorization: ApiKey
/// <key>`, or `X-Api-Key: <key>`. Memberships (and the caller's role in each
/// organisation) are loaded fresh from the database so changes take effect
/// immediately. Anonymous callers resolve to `None`.
pub async fn resolve_principal(&self, req: &HttpRequest) -> Option<Principal> {
let user_id = self.resolve_user_id(req).await?;
let organizations = self.load_memberships(user_id).await;
Some(Principal {
user_id,
organizations,
})
}
async fn resolve_user_id(&self, req: &HttpRequest) -> Option<Uuid> {
if let Some(key) = req.headers().get("x-api-key").and_then(|v| v.to_str().ok()) {
if !key.is_empty() {
return self.user_id_from_api_key(key.trim()).await;
}
}
let header = req.headers().get("authorization")?.to_str().ok()?;
if let Some(token) = header.strip_prefix("Bearer ") {
return self.auth.verify_token(token.trim()).ok();
}
if let Some(key) = header.strip_prefix("ApiKey ") {
return self.user_id_from_api_key(key.trim()).await;
}
None
}
async fn user_id_from_api_key(&self, key: &str) -> Option<Uuid> {
let hash = Authenticator::hash_api_key(key);
let api_key_tbl = self.table("api_key")?;
let sql = format!(
"SELECT owner_id::text AS uid FROM {api_key_tbl} WHERE token_hash = $1 LIMIT 1"
);
let rows = self
.db
.raw_json(&sql, &[serde_json::Value::String(hash)])
.await
.ok()?;
let row = rows.as_array()?.first()?;
Uuid::parse_str(row.get("uid")?.as_str()?).ok()
}
/// Load the caller's organisation memberships, with every role they hold
/// in each.
///
/// Roles come from two places — the membership's own primary `role` column
/// and its `membership_role` rows — and both are read here, once per
/// request, so a role granted or revoked takes effect on the next call
/// rather than whenever a token happens to expire.
async fn load_memberships(&self, user_id: Uuid) -> Vec<OrgMembership> {
let Some(membership_tbl) = self.table("membership") else {
return Vec::new();
};
// An app is free to drop the built-in `membership_role` resource, in
// which case the primary role is all there is.
let sql = match self.table("membership_role") {
Some(role_tbl) => format!(
"SELECT m.organization_id::text AS org, m.role AS role, r.role AS extra \
FROM {membership_tbl} m \
LEFT JOIN {role_tbl} r ON r.membership_id = m.id \
WHERE m.user_id = $1::uuid"
),
None => format!(
"SELECT organization_id::text AS org, role, NULL AS extra \
FROM {membership_tbl} WHERE user_id = $1::uuid"
),
};
let rows = match self
.db
.raw_json(&sql, &[serde_json::Value::String(user_id.to_string())])
.await
{
Ok(v) => v,
Err(_) => return Vec::new(),
};
// The join returns one row per role, so the organisations have to be
// folded back together — in first-seen order, so the result does not
// reshuffle between requests.
let mut order: Vec<Uuid> = Vec::new();
let mut primary: HashMap<Uuid, Option<String>> = HashMap::new();
let mut extras: HashMap<Uuid, Vec<String>> = HashMap::new();
for row in rows.as_array().map(Vec::as_slice).unwrap_or_default() {
let Some(org) = row
.get("org")
.and_then(|v| v.as_str())
.and_then(|s| Uuid::parse_str(s).ok())
else {
continue;
};
// The primary role repeats on every joined row; the first one is
// the one, and it also fixes the organisation's place in the order.
if let std::collections::hash_map::Entry::Vacant(slot) = primary.entry(org) {
order.push(org);
slot.insert(
row.get("role")
.and_then(|v| v.as_str())
.map(str::to_owned)
.filter(|role| !role.is_empty()),
);
}
if let Some(extra) = row.get("extra").and_then(|v| v.as_str()) {
if !extra.is_empty() {
extras.entry(org).or_default().push(extra.to_string());
}
}
}
order
.into_iter()
.map(|org| {
OrgMembership::new(
org,
primary.get(&org).cloned().flatten(),
extras.remove(&org).unwrap_or_default(),
)
})
.collect()
}
/// Every user who shares at least one organisation with `principal`
/// (including the caller themselves).
///
/// This is what `member` means on the global `user` resource: colleagues are
/// visible to each other, strangers are not. Resolved per request from the
/// membership table, like the memberships themselves, so a user removed from
/// an organisation stops being visible immediately.
pub async fn co_member_user_ids(&self, principal: &Principal) -> Vec<Uuid> {
let orgs = principal.org_ids();
let mut ids = vec![principal.user_id];
if orgs.is_empty() {
return ids;
}
let Some(membership_tbl) = self.table("membership") else {
return ids;
};
let placeholders = (1..=orgs.len())
.map(|i| format!("${i}::uuid"))
.collect::<Vec<_>>()
.join(", ");
let sql = format!(
"SELECT DISTINCT user_id::text AS uid FROM {membership_tbl} \
WHERE organization_id IN ({placeholders})"
);
let params: Vec<serde_json::Value> = orgs
.iter()
.map(|id| serde_json::Value::String(id.to_string()))
.collect();
let rows = match self.db.raw_json(&sql, ¶ms).await {
Ok(v) => v,
Err(_) => return ids,
};
if let Some(arr) = rows.as_array() {
for row in arr {
if let Some(id) = row
.get("uid")
.and_then(|v| v.as_str())
.and_then(|s| Uuid::parse_str(s).ok())
{
if !ids.contains(&id) {
ids.push(id);
}
}
}
}
ids
}
/// Resolve the caller's active organisation for this request:
///
/// 1. the `X-Organization` header if it names an org the caller belongs to,
/// 2. otherwise the caller's only organisation (if they have exactly one),
/// 3. otherwise `None` (a multi-org caller must pick one).
pub fn active_org(&self, req: &HttpRequest, principal: &Option<Principal>) -> Option<Uuid> {
resolve_active_org(req, principal)
}
/// Quoted-safe physical table name for a resource by logical name.
pub(crate) fn table(&self, resource: &str) -> Option<String> {
self.app
.resources
.get(resource)
.map(|r| format!("\"{}\"", r.table_name()))
}
}
fn resolve_active_org(req: &HttpRequest, principal: &Option<Principal>) -> Option<Uuid> {
let principal = principal.as_ref()?;
if let Some(raw) = req
.headers()
.get("x-organization")
.and_then(|v| v.to_str().ok())
{
let org = Uuid::parse_str(raw.trim()).ok()?;
return principal.is_member(org).then_some(org);
}
if principal.organizations.len() == 1 {
return Some(principal.organizations[0].org_id);
}
None
}
#[cfg(test)]
mod tests {
use super::*;
use ntex::web::test;
fn principal(orgs: &[(Uuid, Option<&str>)]) -> Principal {
Principal {
user_id: Uuid::new_v4(),
organizations: orgs
.iter()
.map(|(org_id, role)| OrgMembership::new(*org_id, role.map(str::to_string), []))
.collect(),
}
}
#[test]
fn active_org_prefers_valid_header() {
let wanted = Uuid::new_v4();
let req = test::TestRequest::default()
.header("x-organization", wanted.to_string())
.to_http_request();
let caller = Some(principal(&[
(wanted, Some("admin")),
(Uuid::new_v4(), Some("member")),
]));
assert_eq!(resolve_active_org(&req, &caller), Some(wanted));
}
#[test]
fn active_org_falls_back_to_only_membership_and_requires_selection_otherwise() {
let only = Uuid::new_v4();
let req = test::TestRequest::default().to_http_request();
let one_org = Some(principal(&[(only, Some("member"))]));
let multi_org = Some(principal(&[
(only, Some("member")),
(Uuid::new_v4(), Some("admin")),
]));
assert_eq!(resolve_active_org(&req, &one_org), Some(only));
assert_eq!(resolve_active_org(&req, &multi_org), None);
assert_eq!(resolve_active_org(&req, &None), None);
}
}