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
//! Read-shaped query routes: transact (admin), filtered query, lookup,
//! aggregate, graph query. All non-admin paths apply read-policy
//! gates (entity-level + per-row).
use crate::{json_error, json_error_safe, parse_json, require_admin, RouterContext};
use pylon_http::HttpMethod;
pub(crate) fn handle(
ctx: &RouterContext,
method: HttpMethod,
url: &str,
body: &str,
_auth_token: Option<&str>,
) -> Option<(u16, String)> {
// POST /api/transact (admin-only; intentionally bypasses entity policies)
if url == "/api/transact" && method == HttpMethod::Post {
if let Some(err) = require_admin(ctx) {
return Some(err);
}
let ops: Vec<serde_json::Value> = match serde_json::from_str(body) {
Ok(v) => v,
Err(e) => {
return Some((
400,
json_error_safe(
"INVALID_JSON",
"Invalid request body",
&format!("Invalid JSON: {e}"),
),
));
}
};
return Some(match ctx.store.transact(&ops) {
Ok((committed, results)) => (
if committed { 200 } else { 400 },
serde_json::json!({
"committed": committed,
"results": results,
})
.to_string(),
),
Err(e) => (500, json_error(&e.code, &e.message)),
});
}
// POST /api/query/:entity (filtered)
if url.starts_with("/api/query/") && method == HttpMethod::Post {
let entity = url
.strip_prefix("/api/query/")
.unwrap_or("")
.split('?')
.next()
.unwrap_or("");
if !entity.is_empty() && entity != "filtered" {
if let pylon_policy::PolicyResult::Denied {
policy_name,
reason,
} = ctx
.policy_engine
.check_entity_read(entity, ctx.auth_ctx, None)
{
tracing::warn!("[policy] query {entity} denied by \"{policy_name}\": {reason}");
return Some((
403,
crate::json_error_with_hint(
"POLICY_DENIED",
"Access denied by policy",
"Check your auth token or the policy rules in your schema",
),
));
}
let filter: serde_json::Value = match serde_json::from_str(body) {
Ok(v) => v,
Err(e) => {
return Some((
400,
json_error_safe(
"INVALID_JSON",
"Invalid request body",
&format!("Invalid JSON: {e}"),
),
));
}
};
return Some(match ctx.store.query_filtered(entity, &filter) {
Ok(rows) => {
let allowed: Vec<serde_json::Value> = rows
.into_iter()
.filter(|row| {
matches!(
ctx.policy_engine.check_entity_read(
entity,
ctx.auth_ctx,
Some(row),
),
pylon_policy::PolicyResult::Allowed
)
})
.collect();
(
200,
serde_json::to_string(&allowed).unwrap_or_else(|_| "[]".into()),
)
}
Err(e) => (400, json_error(&e.code, &e.message)),
});
}
}
// GET /api/lookup/:entity/:field/:value
if let Some(path) = url.strip_prefix("/api/lookup/") {
let path = path.split('?').next().unwrap_or(path);
let parts: Vec<&str> = path.splitn(3, '/').collect();
if parts.len() == 3 && method == HttpMethod::Get {
// Fetch the row FIRST, then run the policy against the
// actual row data. Without this, per-row policies like
// `auth.userId == data.createdBy` see `data` as null and
// ALWAYS deny — every lookup 403s for non-admin callers.
// Same pattern the GET /api/entities/:id/:field path uses.
let row = match ctx.store.lookup(parts[0], parts[1], parts[2]) {
Ok(r) => r,
Err(e) => return Some((400, json_error(&e.code, &e.message))),
};
// Return 404 BEFORE the policy check when the row is
// missing — the existence of a row at this slug isn't
// policy-relevant, and the alternative (404 vs 403) leaks
// less information about other tenants' rows.
let row = match row {
Some(r) => r,
None => {
return Some((
404,
json_error(
"NOT_FOUND",
&format!("{}.{} = {} not found", parts[0], parts[1], parts[2]),
),
));
}
};
let check = ctx
.policy_engine
.check_entity_read(parts[0], ctx.auth_ctx, Some(&row));
if let pylon_policy::PolicyResult::Denied {
policy_name,
reason,
} = check
{
tracing::warn!(
"[policy] lookup on {} denied by \"{policy_name}\": {reason}",
parts[0]
);
return Some((403, json_error("POLICY_DENIED", "Access denied by policy")));
}
return Some((
200,
serde_json::to_string(&row).unwrap_or_else(|_| "{}".into()),
));
}
}
// POST /api/aggregate/:entity
if let Some(rest) = url.strip_prefix("/api/aggregate/") {
let entity = rest.split('?').next().unwrap_or(rest);
if method == HttpMethod::Post && !entity.is_empty() {
let check = ctx
.policy_engine
.check_entity_read(entity, ctx.auth_ctx, None);
if let pylon_policy::PolicyResult::Denied {
policy_name,
reason,
} = check
{
tracing::warn!(
"[policy] aggregate on {entity} denied by \"{policy_name}\": {reason}"
);
return Some((403, json_error("POLICY_DENIED", "Access denied by policy")));
}
let mut spec = match parse_json(body) {
Ok(v) => v,
Err((s, b)) => return Some((s, b)),
};
// Tenant clamp — if the entity has an `orgId` column and the
// caller has an active tenant, force WHERE orgId = tenantId.
// Server overwrites any client-supplied value, so a payload
// can't sum cross-tenant rows.
if let Some(tenant_id) = ctx.auth_ctx.tenant_id.as_deref() {
let manifest = ctx.store.manifest();
let has_org_id = manifest
.entities
.iter()
.find(|e| e.name == entity)
.map(|e| e.fields.iter().any(|f| f.name == "orgId"))
.unwrap_or(false);
if has_org_id {
if let Some(obj) = spec.as_object_mut() {
let entry = obj
.entry("where".to_string())
.or_insert_with(|| serde_json::json!({}));
if let Some(where_obj) = entry.as_object_mut() {
where_obj.insert(
"orgId".to_string(),
serde_json::Value::String(tenant_id.to_string()),
);
}
}
}
}
return Some(match ctx.store.aggregate(entity, &spec) {
Ok(result) => (
200,
serde_json::to_string(&result).unwrap_or_else(|_| "{}".into()),
),
Err(e) => (400, json_error(&e.code, &e.message)),
});
}
}
// POST /api/query (graph)
if url == "/api/query" && method == HttpMethod::Post {
let query: serde_json::Value = match serde_json::from_str(body) {
Ok(v) => v,
Err(e) => {
return Some((
400,
json_error_safe(
"INVALID_JSON",
"Invalid request body",
&format!("Invalid JSON: {e}"),
),
));
}
};
// Gate every entity named in the graph against the read policy.
if let Some(obj) = query.as_object() {
for entity_name in obj.keys() {
let check = ctx
.policy_engine
.check_entity_read(entity_name, ctx.auth_ctx, None);
if let pylon_policy::PolicyResult::Denied {
policy_name,
reason,
} = check
{
tracing::warn!(
"[policy] graph query on {entity_name} denied by \"{policy_name}\": {reason}"
);
return Some((403, json_error("POLICY_DENIED", "Access denied by policy")));
}
}
}
return Some(match ctx.store.query_graph(&query) {
Ok(result) => (
200,
serde_json::to_string(&result).unwrap_or_else(|_| "{}".into()),
),
Err(e) => (400, json_error(&e.code, &e.message)),
});
}
None
}