@feltdb/core 0.12.2 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/dist/agent-runtime.d.ts +64 -2
  2. package/dist/agent-runtime.d.ts.map +1 -1
  3. package/dist/agent-runtime.js +121 -11
  4. package/dist/agent-state.d.ts +48 -0
  5. package/dist/agent-state.d.ts.map +1 -1
  6. package/dist/agent-state.js +174 -12
  7. package/dist/agent.d.ts +10 -1
  8. package/dist/agent.d.ts.map +1 -1
  9. package/dist/agent.js +10 -1
  10. package/dist/build-identity.json +4 -4
  11. package/dist/cli/commands.js +34 -7
  12. package/dist/cli/workspace-integration.js +8 -0
  13. package/dist/collection.d.ts +3 -1
  14. package/dist/collection.d.ts.map +1 -1
  15. package/dist/collection.js +30 -8
  16. package/dist/create/build-identity.json +4 -4
  17. package/dist/create/cli.js +47 -38
  18. package/dist/create/create.js +21 -8
  19. package/dist/create/package-versions.js +1 -1
  20. package/dist/create/server-source/Cargo.lock +6 -6
  21. package/dist/create/server-source/Cargo.toml +1 -1
  22. package/dist/create/server-source/crates/feltdb/src/lib.rs +126 -35
  23. package/dist/create/server-source/crates/feltdb/src/state_contract.rs +162 -53
  24. package/dist/create/server-source/crates/feltdb/src/worker_mesh.rs +341 -2
  25. package/dist/create/server-source/crates/feltdb/src/workload.rs +2094 -126
  26. package/dist/create/server-source/crates/feltdb/tests/production_readiness_contract.rs +18 -12
  27. package/dist/create/server-source/crates/feltdb/tests/workload_envelope_contract.rs +17 -5
  28. package/dist/create/server-source/crates/feltdb-client/Cargo.toml +1 -1
  29. package/dist/create/server-source/crates/feltdb-server/Cargo.toml +1 -1
  30. package/dist/create/server-source/crates/feltdb-server/README.md +6 -1
  31. package/dist/create/server-source/crates/feltdb-server/src/agent_execution.rs +511 -0
  32. package/dist/create/server-source/crates/feltdb-server/src/app_state.rs +9 -1
  33. package/dist/create/server-source/crates/feltdb-server/src/auth.rs +113 -25
  34. package/dist/create/server-source/crates/feltdb-server/src/backup.rs +4 -0
  35. package/dist/create/server-source/crates/feltdb-server/src/console_accounts.rs +1009 -0
  36. package/dist/create/server-source/crates/feltdb-server/src/control_authorization.rs +441 -0
  37. package/dist/create/server-source/crates/feltdb-server/src/identity.rs +68 -6
  38. package/dist/create/server-source/crates/feltdb-server/src/key_management.rs +355 -23
  39. package/dist/create/server-source/crates/feltdb-server/src/lib.rs +4 -0
  40. package/dist/create/server-source/crates/feltdb-server/src/main.rs +1740 -236
  41. package/dist/create/server-source/crates/feltdb-server/src/redaction.rs +208 -0
  42. package/dist/create/server-source/crates/feltdb-server/src/tenancy.rs +198 -19
  43. package/dist/create/server-source/crates/feltdb-server/tests/transaction_precondition_contract.rs +403 -0
  44. package/dist/create/setup-summary.js +40 -0
  45. package/dist/db.d.ts +91 -10
  46. package/dist/db.d.ts.map +1 -1
  47. package/dist/db.js +170 -31
  48. package/dist/deployment.d.ts +19 -0
  49. package/dist/deployment.d.ts.map +1 -1
  50. package/dist/deployment.js +38 -2
  51. package/dist/development-runtime-bridge.d.ts +20 -0
  52. package/dist/development-runtime-bridge.d.ts.map +1 -1
  53. package/dist/development-runtime-bridge.js +61 -12
  54. package/dist/embedded-query.d.ts.map +1 -1
  55. package/dist/embedded-query.js +5 -4
  56. package/dist/embedded-transaction.d.ts +8 -4
  57. package/dist/embedded-transaction.d.ts.map +1 -1
  58. package/dist/embedded-transaction.js +55 -19
  59. package/dist/error-codes.d.ts +31 -2
  60. package/dist/error-codes.d.ts.map +1 -1
  61. package/dist/error-codes.js +41 -2
  62. package/dist/feltdb.d.ts +7 -0
  63. package/dist/feltdb.d.ts.map +1 -1
  64. package/dist/file-db.d.ts +27 -0
  65. package/dist/file-db.d.ts.map +1 -1
  66. package/dist/file-db.js +145 -7
  67. package/dist/http-client.d.ts +11 -3
  68. package/dist/http-client.d.ts.map +1 -1
  69. package/dist/http-client.js +27 -14
  70. package/dist/http-db.d.ts +40 -1
  71. package/dist/http-db.d.ts.map +1 -1
  72. package/dist/http-db.js +285 -58
  73. package/dist/index.js +1 -1
  74. package/dist/local-state-lock.d.ts +34 -0
  75. package/dist/local-state-lock.d.ts.map +1 -0
  76. package/dist/local-state-lock.js +225 -0
  77. package/dist/reactive-graph.d.ts +0 -3
  78. package/dist/reactive-graph.d.ts.map +1 -1
  79. package/dist/reactive-graph.js +11 -1
  80. package/dist/runtime-registry.d.ts +7 -2
  81. package/dist/runtime-registry.d.ts.map +1 -1
  82. package/dist/runtime-registry.js +2 -2
  83. package/dist/studio/{KeyManagementPanel-D5FMvvU9.js → KeyManagementPanel-skUNnKRw.js} +36 -29
  84. package/dist/studio/app.d.ts +8 -1
  85. package/dist/studio/app.d.ts.map +1 -1
  86. package/dist/studio/components/KeyManagementPanel.d.ts.map +1 -1
  87. package/dist/studio/components/KeyManagementPanel.js +1 -1
  88. package/dist/studio/components/index.js +2 -2
  89. package/dist/studio/{components-B4eKIUN5.js → components-CJmzntBi.js} +8 -7
  90. package/dist/studio/control-plane/Data.d.ts.map +1 -1
  91. package/dist/studio/control-plane/Instance.d.ts +4 -1
  92. package/dist/studio/control-plane/Instance.d.ts.map +1 -1
  93. package/dist/studio/control-plane/Operations.d.ts +4 -1
  94. package/dist/studio/control-plane/Operations.d.ts.map +1 -1
  95. package/dist/studio/control-plane/index.js +2 -2
  96. package/dist/studio/control-plane/primitives.d.ts +16 -0
  97. package/dist/studio/control-plane/primitives.d.ts.map +1 -1
  98. package/dist/studio/{control-plane-fxMcJn74.js → control-plane-CaBA7Rgv.js} +448 -424
  99. package/dist/studio/index.d.ts +1 -0
  100. package/dist/studio/index.d.ts.map +1 -1
  101. package/dist/studio/index.js +384 -247
  102. package/dist/studio/navigation.d.ts +57 -0
  103. package/dist/studio/navigation.d.ts.map +1 -0
  104. package/dist/studio/studio.css +1 -1
  105. package/dist/studio/utils/control-plane-api.d.ts +2 -0
  106. package/dist/studio/utils/control-plane-api.d.ts.map +1 -1
  107. package/dist/studio/utils/control-plane-api.js +5 -1
  108. package/dist/studio-app/assets/{feltdb_wasm-BatwwogY.js → feltdb_wasm-BjM1ylL3.js} +1 -1
  109. package/dist/studio-app/assets/feltdb_wasm_bg-TseJn2Ax.wasm +0 -0
  110. package/dist/studio-app/assets/index-1wd0uKua.js +30 -0
  111. package/dist/studio-app/assets/{index-CiC8VY-a.css → index-vi21oEQa.css} +1 -1
  112. package/dist/studio-app/index.html +2 -2
  113. package/dist/transaction.d.ts +27 -11
  114. package/dist/transaction.d.ts.map +1 -1
  115. package/dist/transaction.js +20 -14
  116. package/dist/wasm/feltdb_wasm_bg.wasm +0 -0
  117. package/dist/wasm/package.json +1 -1
  118. package/dist/workload.d.ts +31 -3
  119. package/dist/workload.d.ts.map +1 -1
  120. package/dist/workload.js +28 -3
  121. package/dist/workspace/local-development-authority.d.ts +19 -0
  122. package/dist/workspace/local-development-authority.d.ts.map +1 -1
  123. package/dist/workspace/local-development-authority.js +335 -15
  124. package/package.json +1 -1
  125. package/dist/studio-app/assets/feltdb_wasm_bg-BX0newOr.wasm +0 -0
  126. package/dist/studio-app/assets/index-DoVvbIay.js +0 -30
@@ -0,0 +1,441 @@
1
+ //! Control-plane (`/api/*`) and operator-route authorization.
2
+ //!
3
+ //! Before 0.14.1 the request middleware skipped its authorization decision for
4
+ //! every `/api/*` path and left it to each handler. The key handlers had none,
5
+ //! so a self-serve end-user session could list every key and mint a wildcard
6
+ //! service key (Phase 1 managed audit, GAP-01). This module is the replacement:
7
+ //! every control-plane route has an explicit [`Requirement`], every principal
8
+ //! has a [`PrincipalClass`], and [`decide`] combines them before any handler
9
+ //! runs. An `/api/*` route that is not in [`control_plane_requirement`] is
10
+ //! refused, so a new route fails closed until someone decides who may call it.
11
+ //!
12
+ //! Console users (human platform sessions) carry no direct scopes: they are
13
+ //! authorized by tenant/application membership, which the handlers evaluate
14
+ //! through [`crate::tenancy::TenancyStore`]. Machine principals (service and
15
+ //! worker keys) must hold the route's capability as a direct grant *and* pass
16
+ //! the handler's tenancy check. Application end-user sessions (minted by
17
+ //! `/v1/auth/signup` / `/v1/auth/signin`) never reach the control plane.
18
+
19
+ use axum::http::Method;
20
+ use serde_json::json;
21
+
22
+ use crate::tenancy::application_role_grants;
23
+
24
+ /// Who is calling, as far as control-plane authorization is concerned.
25
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
26
+ pub enum PrincipalClass {
27
+ /// Authentication disabled (`--auth` not set): the development principal.
28
+ Development,
29
+ /// A service or worker API key.
30
+ Machine,
31
+ /// A human console (platform) session: membership-authorized.
32
+ ConsoleUser,
33
+ /// An application end-user session from `/v1/auth/signup` or `signin`.
34
+ EndUser,
35
+ }
36
+
37
+ /// What a route demands of its caller.
38
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
39
+ pub enum Requirement {
40
+ /// Acts only on the caller's own session or identity; any authenticated
41
+ /// principal may call it.
42
+ SelfOnly,
43
+ /// Machine principals need this capability as a direct grant; console users
44
+ /// are authorized by membership in the handler; end users are refused.
45
+ Capability(&'static str),
46
+ /// No decision exists for this route, so nobody may call it.
47
+ Unmapped,
48
+ }
49
+
50
+ /// A refusal with a stable reason and an actionable message.
51
+ #[derive(Debug, Clone, PartialEq, Eq)]
52
+ pub struct Denial {
53
+ pub reason: &'static str,
54
+ pub message: String,
55
+ pub required_scope: Option<String>,
56
+ }
57
+
58
+ impl Denial {
59
+ pub fn new(reason: &'static str, message: impl Into<String>) -> Self {
60
+ Self {
61
+ reason,
62
+ message: message.into(),
63
+ required_scope: None,
64
+ }
65
+ }
66
+
67
+ pub fn missing_scope(scope: &str) -> Self {
68
+ Self {
69
+ reason: MISSING_SCOPE,
70
+ message: format!(
71
+ "missing scope {scope} — use a key that holds {scope}; end-user sessions cannot use the control plane"
72
+ ),
73
+ required_scope: Some(scope.to_string()),
74
+ }
75
+ }
76
+
77
+ pub fn with_scope(mut self, scope: &str) -> Self {
78
+ self.required_scope = Some(scope.to_string());
79
+ self
80
+ }
81
+
82
+ /// The JSON message `ApiError` turns into the response body. The wire
83
+ /// `code` stays the canonical `FORBIDDEN`; `reason` is the stable detail.
84
+ pub fn body(&self) -> String {
85
+ let mut body = json!({ "message": self.message, "reason": self.reason });
86
+ if let Some(scope) = &self.required_scope {
87
+ body["required_scope"] = json!(scope);
88
+ }
89
+ body.to_string()
90
+ }
91
+ }
92
+
93
+ pub const MISSING_SCOPE: &str = "MISSING_SCOPE";
94
+ pub const END_USER_SESSION_FORBIDDEN: &str = "END_USER_SESSION_FORBIDDEN";
95
+ pub const PRIVILEGE_ESCALATION_DENIED: &str = "PRIVILEGE_ESCALATION_DENIED";
96
+ pub const APPLICATION_SCOPE_REQUIRED: &str = "APPLICATION_SCOPE_REQUIRED";
97
+ pub const UNMAPPED_CONTROL_ROUTE: &str = "UNMAPPED_CONTROL_ROUTE";
98
+
99
+ /// Key listing, creation, rotation and revocation.
100
+ pub const KEYS_ADMIN: &str = "keys:admin";
101
+ /// `/metrics` and `/v1/status`.
102
+ pub const OPERATOR_READ: &str = "operator:read";
103
+
104
+ fn segments(path: &str) -> Vec<&str> {
105
+ path.trim_matches('/').split('/').collect()
106
+ }
107
+
108
+ /// The requirement of a control-plane route, or `None` for a path outside `/api/`.
109
+ pub fn control_plane_requirement(method: &Method, path: &str) -> Option<Requirement> {
110
+ if !path.starts_with("/api/") {
111
+ return None;
112
+ }
113
+ let get = method == Method::GET;
114
+ let s = segments(path);
115
+ use Requirement::*;
116
+ let requirement = match s.as_slice() {
117
+ ["api", "session", "revoke"] | ["api", "platform", "access"] => SelfOnly,
118
+ ["api", "keys"] | ["api", "keys", _] | ["api", "keys", _, "rotate"] => {
119
+ Capability(KEYS_ADMIN)
120
+ }
121
+ ["api", "platform"] | ["api", "platform", "users", _] => Capability("platform:admin"),
122
+ ["api", "platform", "applications", _, "members", _] => Capability("platform:admin"),
123
+ ["api", "tenants"] | ["api", "tenants", _, "applications"] => Capability(if get {
124
+ "applications:read"
125
+ } else {
126
+ "applications:write"
127
+ }),
128
+ ["api", "tenants", _] => Capability("applications:read"),
129
+ ["api", "applications", _] => Capability(if get {
130
+ "applications:read"
131
+ } else {
132
+ "applications:write"
133
+ }),
134
+ ["api", "applications", _, "qualification", "destroy"] => Capability("applications:write"),
135
+ ["api", "applications", _, "members"] => Capability("members:read"),
136
+ ["api", "applications", _, "invitations"] => Capability("members:invite"),
137
+ ["api", "applications", _, "audit"] => Capability("audit:read"),
138
+ ["api", "applications", _, "principals"] => Capability(if get {
139
+ "applications:read"
140
+ } else {
141
+ "applications:write"
142
+ }),
143
+ ["api", "principals", _, "capabilities"] => Capability("applications:write"),
144
+ ["api", "agents", _, "workloads"] => Capability("workloads:execute"),
145
+ ["api", "applications", _, "connections"] => Capability(if get {
146
+ "connections:read"
147
+ } else {
148
+ "connections:write"
149
+ }),
150
+ ["api", "connections", _] | ["api", "connections", _, "disable"] => {
151
+ Capability("connections:write")
152
+ }
153
+ ["api", "applications", _, "secrets"] => Capability(if get {
154
+ "applications:read"
155
+ } else {
156
+ "applications:write"
157
+ }),
158
+ ["api", "secrets", _, "rotate"] => Capability("applications:write"),
159
+ ["api", "applications", _, "drafts"] => Capability("application:revision:create"),
160
+ ["api", "applications", _, "drafts", _] => Capability(if get {
161
+ "application:revision:read"
162
+ } else {
163
+ "application:write"
164
+ }),
165
+ ["api", "applications", _, "drafts", _, "validate" | "commit" | "runtime"] => {
166
+ Capability("application:revision:create")
167
+ }
168
+ ["api", "applications", _, "drafts", _, "run"] => Capability("application:runtime:run"),
169
+ ["api", "applications", _, "drafts", _, "stop"] => Capability("application:runtime:stop"),
170
+ ["api", "applications", _, "import"] => Capability("application:revision:create"),
171
+ ["api", "applications", _, "runtime"] => Capability("application:revision:read"),
172
+ ["api", "applications", _, "revisions"]
173
+ | ["api", "applications", _, "revisions", _]
174
+ | ["api", "applications", _, "previews", _] => Capability("application:revision:read"),
175
+ ["api", "applications", _, "revisions", _, "diff" | "export" | "runtime"]
176
+ | ["api", "applications", _, "revisions", _, "validate-runtime"] => {
177
+ Capability("application:revision:read")
178
+ }
179
+ ["api", "applications", _, "revisions", _, "actions" | "queries" | "workflows" | "triggers"]
180
+ if get =>
181
+ {
182
+ Capability("application:revision:read")
183
+ }
184
+ ["api", "applications", _, "revisions", _, "preview"] => {
185
+ Capability("application:revision:preview")
186
+ }
187
+ ["api", "applications", _, "revisions", _, "promote"] => {
188
+ Capability("application:revision:promote")
189
+ }
190
+ ["api", "applications", _, "revisions", _, "run"] => Capability("application:runtime:run"),
191
+ ["api", "applications", _, "revisions", _, "stop"] => {
192
+ Capability("application:runtime:stop")
193
+ }
194
+ ["api", "applications", _, "revisions", _, "actions", _] => Capability("state:write"),
195
+ ["api", "applications", _, "revisions", _, "queries", _] => Capability("state:read"),
196
+ ["api", "applications", _, "revisions", _, "workflows", _, "run"] => {
197
+ Capability("workflows:run")
198
+ }
199
+ ["api", "applications", _, "environments"]
200
+ | ["api", "applications", _, "environments", _]
201
+ | ["api", "applications", _, "environments", _, "history" | "readiness"] => {
202
+ Capability("application:environment:read")
203
+ }
204
+ ["api", "applications", _, "environments", _, "promote"] => {
205
+ Capability("application:revision:promote")
206
+ }
207
+ ["api", "applications", _, "environments", _, "rollback"] => {
208
+ Capability("application:revision:rollback")
209
+ }
210
+ _ => Unmapped,
211
+ };
212
+ Some(requirement)
213
+ }
214
+
215
+ fn holds(scopes: &[String], required: &str) -> bool {
216
+ scopes.iter().any(|scope| scope == "*" || scope == required)
217
+ }
218
+
219
+ /// The middleware decision for a control-plane route.
220
+ pub fn decide(
221
+ class: PrincipalClass,
222
+ scopes: &[String],
223
+ requirement: Requirement,
224
+ ) -> Result<(), Denial> {
225
+ match (class, requirement) {
226
+ (_, Requirement::Unmapped) => Err(Denial::new(
227
+ UNMAPPED_CONTROL_ROUTE,
228
+ "this control-plane route has no authorization decision and is refused",
229
+ )),
230
+ (PrincipalClass::Development, _) => Ok(()),
231
+ (_, Requirement::SelfOnly) => Ok(()),
232
+ (PrincipalClass::EndUser, Requirement::Capability(scope)) => Err(Denial::new(
233
+ END_USER_SESSION_FORBIDDEN,
234
+ "end-user sessions cannot use the control plane (/api/*) or manage keys — sign in to the console as an application member, or use a service key that holds the required scope",
235
+ )
236
+ .with_scope(scope)),
237
+ // Membership (tenant and application roles) is the console user's
238
+ // authority; every handler routed here evaluates it.
239
+ (PrincipalClass::ConsoleUser, Requirement::Capability(_)) => Ok(()),
240
+ (PrincipalClass::Machine, Requirement::Capability(scope)) => {
241
+ if holds(scopes, scope) {
242
+ Ok(())
243
+ } else {
244
+ Err(Denial::missing_scope(scope))
245
+ }
246
+ }
247
+ }
248
+ }
249
+
250
+ /// Scopes a credential may hold only when an operator key that holds them
251
+ /// delegates them. A console user can never mint these, whatever its role.
252
+ pub fn is_operator_scope(scope: &str) -> bool {
253
+ scope == "*"
254
+ || scope == KEYS_ADMIN
255
+ || scope == OPERATOR_READ
256
+ || ["cluster:", "sync:", "admin:", "backup:", "platform:", "keys:", "operator:"]
257
+ .iter()
258
+ .any(|prefix| scope.starts_with(prefix))
259
+ || scope.contains('*')
260
+ }
261
+
262
+ /// Application-level capabilities a console user may delegate to an
263
+ /// application-bound key (subject to its own role in that application).
264
+ pub fn console_delegable(scope: &str) -> bool {
265
+ !is_operator_scope(scope)
266
+ && application_role_grants()
267
+ .iter()
268
+ .flat_map(|role| role.capabilities.iter())
269
+ .any(|capability| capability != "*" && capability == scope)
270
+ }
271
+
272
+ /// No privilege amplification: every requested scope is already held.
273
+ pub fn scopes_within(requested: &[String], held: &[String]) -> Result<(), Denial> {
274
+ match requested.iter().find(|scope| {
275
+ if scope.as_str() == "*" {
276
+ !held.iter().any(|value| value == "*")
277
+ } else {
278
+ !holds(held, scope)
279
+ }
280
+ }) {
281
+ Some(scope) => Err(Denial::new(
282
+ PRIVILEGE_ESCALATION_DENIED,
283
+ format!(
284
+ "cannot delegate scope {scope}: a caller may only grant scopes it holds itself"
285
+ ),
286
+ )),
287
+ None => Ok(()),
288
+ }
289
+ }
290
+
291
+ /// No escape from the caller's namespaces.
292
+ pub fn namespaces_within(requested: &str, held: &[String]) -> Result<(), Denial> {
293
+ let allowed = if requested == "*" {
294
+ held.iter().any(|value| value == "*")
295
+ } else {
296
+ held.iter().any(|value| value == "*" || value == requested)
297
+ };
298
+ if allowed {
299
+ Ok(())
300
+ } else {
301
+ Err(Denial::new(
302
+ PRIVILEGE_ESCALATION_DENIED,
303
+ format!("cannot issue a key for namespace {requested}: it is outside the caller's namespaces"),
304
+ ))
305
+ }
306
+ }
307
+
308
+ #[cfg(test)]
309
+ mod tests {
310
+ use super::*;
311
+
312
+ fn owned(values: &[&str]) -> Vec<String> {
313
+ values.iter().map(|value| value.to_string()).collect()
314
+ }
315
+
316
+ /// Every `/api/*` route the server registers. A route added to the router
317
+ /// without a decision here is `Unmapped` and refused; this list keeps the
318
+ /// mapping honest about the routes that exist today.
319
+ const ROUTES: &[(&str, &str)] = &[
320
+ ("GET", "/api/tenants"),
321
+ ("POST", "/api/tenants"),
322
+ ("GET", "/api/platform"),
323
+ ("PATCH", "/api/platform/users/u"),
324
+ ("PATCH", "/api/platform/applications/a/members/u"),
325
+ ("GET", "/api/tenants/t"),
326
+ ("GET", "/api/keys"),
327
+ ("POST", "/api/keys"),
328
+ ("DELETE", "/api/keys/k"),
329
+ ("POST", "/api/keys/k/rotate"),
330
+ ("GET", "/api/tenants/t/applications"),
331
+ ("POST", "/api/tenants/t/applications"),
332
+ ("GET", "/api/applications/a"),
333
+ ("PATCH", "/api/applications/a"),
334
+ ("DELETE", "/api/applications/a"),
335
+ ("POST", "/api/applications/a/qualification/destroy"),
336
+ ("GET", "/api/applications/a/members"),
337
+ ("POST", "/api/applications/a/invitations"),
338
+ ("GET", "/api/applications/a/audit"),
339
+ ("POST", "/api/applications/a/drafts"),
340
+ ("GET", "/api/applications/a/drafts/d"),
341
+ ("PUT", "/api/applications/a/drafts/d"),
342
+ ("POST", "/api/applications/a/drafts/d/validate"),
343
+ ("GET", "/api/applications/a/drafts/d/runtime"),
344
+ ("POST", "/api/applications/a/drafts/d/run"),
345
+ ("POST", "/api/applications/a/drafts/d/stop"),
346
+ ("POST", "/api/applications/a/drafts/d/commit"),
347
+ ("GET", "/api/applications/a/revisions"),
348
+ ("GET", "/api/applications/a/revisions/r"),
349
+ ("GET", "/api/applications/a/revisions/r/diff"),
350
+ ("POST", "/api/applications/a/revisions/r/preview"),
351
+ ("GET", "/api/applications/a/previews/p"),
352
+ ("GET", "/api/applications/a/environments"),
353
+ ("GET", "/api/applications/a/environments/e"),
354
+ ("POST", "/api/applications/a/environments/e/promote"),
355
+ ("POST", "/api/applications/a/environments/e/rollback"),
356
+ ("GET", "/api/applications/a/environments/e/history"),
357
+ ("GET", "/api/applications/a/environments/e/readiness"),
358
+ ("POST", "/api/applications/a/revisions/r/promote"),
359
+ ("GET", "/api/applications/a/revisions/r/export"),
360
+ ("POST", "/api/applications/a/import"),
361
+ ("GET", "/api/applications/a/runtime"),
362
+ ("GET", "/api/applications/a/revisions/r/runtime"),
363
+ ("POST", "/api/applications/a/revisions/r/validate-runtime"),
364
+ ("POST", "/api/applications/a/revisions/r/run"),
365
+ ("POST", "/api/applications/a/revisions/r/stop"),
366
+ ("GET", "/api/applications/a/revisions/r/actions"),
367
+ ("POST", "/api/applications/a/revisions/r/actions/x"),
368
+ ("GET", "/api/applications/a/revisions/r/queries"),
369
+ ("POST", "/api/applications/a/revisions/r/queries/q"),
370
+ ("GET", "/api/applications/a/revisions/r/workflows"),
371
+ ("POST", "/api/applications/a/revisions/r/workflows/w/run"),
372
+ ("GET", "/api/applications/a/revisions/r/triggers"),
373
+ ("POST", "/api/session/revoke"),
374
+ ("GET", "/api/platform/access"),
375
+ ("GET", "/api/applications/a/principals"),
376
+ ("POST", "/api/applications/a/principals"),
377
+ ("POST", "/api/principals/p/capabilities"),
378
+ ("POST", "/api/agents/a/workloads"),
379
+ ("GET", "/api/applications/a/connections"),
380
+ ("POST", "/api/applications/a/connections"),
381
+ ("GET", "/api/applications/a/secrets"),
382
+ ("POST", "/api/applications/a/secrets"),
383
+ ("POST", "/api/secrets/s/rotate"),
384
+ ("POST", "/api/connections/c/disable"),
385
+ ("DELETE", "/api/connections/c"),
386
+ ];
387
+
388
+ #[test]
389
+ fn every_registered_control_route_has_an_explicit_requirement() {
390
+ for (method, path) in ROUTES {
391
+ let method = Method::from_bytes(method.as_bytes()).unwrap();
392
+ let requirement = control_plane_requirement(&method, path).expect("an /api path");
393
+ assert_ne!(requirement, Requirement::Unmapped, "{method} {path} is unmapped");
394
+ }
395
+ assert_eq!(
396
+ control_plane_requirement(&Method::GET, "/api/unknown/thing"),
397
+ Some(Requirement::Unmapped)
398
+ );
399
+ assert_eq!(control_plane_requirement(&Method::GET, "/v1/state"), None);
400
+ }
401
+
402
+ #[test]
403
+ fn key_routes_require_keys_admin_and_end_users_never_pass() {
404
+ for (method, path) in [("GET", "/api/keys"), ("POST", "/api/keys"), ("DELETE", "/api/keys/x"), ("POST", "/api/keys/x/rotate")] {
405
+ let requirement =
406
+ control_plane_requirement(&Method::from_bytes(method.as_bytes()).unwrap(), path)
407
+ .unwrap();
408
+ assert_eq!(requirement, Requirement::Capability(KEYS_ADMIN));
409
+ let denial = decide(PrincipalClass::EndUser, &owned(&["*"]), requirement).unwrap_err();
410
+ assert_eq!(denial.reason, END_USER_SESSION_FORBIDDEN);
411
+ let denial = decide(PrincipalClass::Machine, &owned(&["state:write"]), requirement)
412
+ .unwrap_err();
413
+ assert_eq!(denial.reason, MISSING_SCOPE);
414
+ assert!(denial.message.contains("missing scope keys:admin"));
415
+ assert!(decide(PrincipalClass::Machine, &owned(&[KEYS_ADMIN]), requirement).is_ok());
416
+ }
417
+ assert!(decide(PrincipalClass::Machine, &owned(&["*"]), Requirement::Unmapped).is_err());
418
+ assert!(decide(PrincipalClass::Development, &[], Requirement::Unmapped).is_err());
419
+ }
420
+
421
+ #[test]
422
+ fn delegation_never_amplifies() {
423
+ let held = owned(&[KEYS_ADMIN, "state:read"]);
424
+ assert!(scopes_within(&owned(&["state:read"]), &held).is_ok());
425
+ assert!(scopes_within(&owned(&["*"]), &held).is_err());
426
+ assert!(scopes_within(&owned(&["state:write"]), &held).is_err());
427
+ assert!(scopes_within(&owned(&["*"]), &owned(&["*"])).is_ok());
428
+ assert!(namespaces_within("ns", &owned(&["ns"])).is_ok());
429
+ assert!(namespaces_within("*", &owned(&["ns"])).is_err());
430
+ assert!(namespaces_within("other", &owned(&["ns"])).is_err());
431
+ }
432
+
433
+ #[test]
434
+ fn console_users_delegate_only_application_capabilities() {
435
+ assert!(console_delegable("state:read"));
436
+ assert!(console_delegable("application:revision:create"));
437
+ for scope in ["*", "keys:admin", "cluster:write", "sync:write", "backup:restore", "admin:logs", "operator:read", "state:*", "made:up"] {
438
+ assert!(!console_delegable(scope), "{scope}");
439
+ }
440
+ }
441
+ }
@@ -9,6 +9,21 @@ use std::{
9
9
  time::{SystemTime, UNIX_EPOCH},
10
10
  };
11
11
 
12
+ /// A session bearer token: 32 random alphanumeric characters (about 190 bits).
13
+ fn session_token() -> String {
14
+ let random: String = rand::thread_rng()
15
+ .sample_iter(&Alphanumeric)
16
+ .take(32)
17
+ .map(char::from)
18
+ .collect();
19
+ format!("session_token_{random}")
20
+ }
21
+
22
+ fn session_token_digest(token: &str) -> String {
23
+ use sha2::{Digest, Sha256};
24
+ format!("{:x}", Sha256::digest(token.as_bytes()))
25
+ }
26
+
12
27
  fn now() -> u64 {
13
28
  SystemTime::now()
14
29
  .duration_since(UNIX_EPOCH)
@@ -60,7 +75,16 @@ pub struct IdentitySession {
60
75
  pub provider: String,
61
76
  pub status: String,
62
77
  pub revocation_reason: Option<String>,
78
+ /// Argon2 hash of the token, written by releases before 0.15.0. Never
79
+ /// matched any more: see `token_digest`.
63
80
  pub refresh_hash: Option<String>,
81
+ /// SHA-256 of the session token. Session tokens are random and
82
+ /// short-lived, so a fast digest is enough, and it lets a bearer token be
83
+ /// looked up instead of Argon2-verified against every stored session —
84
+ /// which made each request with an unknown token cost one Argon2
85
+ /// verification per session ever issued.
86
+ #[serde(default, skip_serializing_if = "Option::is_none")]
87
+ pub token_digest: Option<String>,
64
88
  }
65
89
  #[derive(Debug, Default, Serialize, Deserialize)]
66
90
  struct State {
@@ -210,16 +234,14 @@ impl IdentityStore {
210
234
  }
211
235
  pub fn authenticate_session(&self, token: &str) -> Option<IdentitySession> {
212
236
  let current = now();
237
+ let digest = session_token_digest(token);
213
238
  self.state
214
239
  .read()
215
240
  .ok()?
216
241
  .sessions
217
242
  .iter()
218
243
  .find(|value| {
219
- value
220
- .refresh_hash
221
- .as_deref()
222
- .is_some_and(|hash| Self::verify_password(hash, token))
244
+ value.token_digest.as_deref() == Some(digest.as_str())
223
245
  && value.status == "active"
224
246
  && value.expires_at > current
225
247
  })
@@ -245,7 +267,7 @@ impl IdentityStore {
245
267
  ) -> Result<(IdentitySession, String), String> {
246
268
  let mut s = self.state.write().map_err(|_| "identity lock poisoned")?;
247
269
  let t = now();
248
- let token = id("session_token");
270
+ let token = session_token();
249
271
  let x = IdentitySession {
250
272
  session_id: id("session"),
251
273
  identity_id: identity.identity_id.clone(),
@@ -257,7 +279,8 @@ impl IdentityStore {
257
279
  provider: provider.into(),
258
280
  status: "active".into(),
259
281
  revocation_reason: None,
260
- refresh_hash: Some(Self::hash_password(&token)?),
282
+ refresh_hash: None,
283
+ token_digest: Some(session_token_digest(&token)),
261
284
  };
262
285
  s.sessions.push(x.clone());
263
286
  self.persist(&s)?;
@@ -355,4 +378,43 @@ mod tests {
355
378
  assert!(store.authenticate_session(&token).is_none());
356
379
  let _ = std::fs::remove_file(p);
357
380
  }
381
+ #[test]
382
+ fn an_unknown_bearer_token_is_rejected_without_password_hashing() {
383
+ let p = std::env::temp_dir().join(format!("identity-session-{}.json", id("test")));
384
+ let store = IdentityStore::load(&p).unwrap();
385
+ let (_, _, token) = store
386
+ .sign_up("many@example.com", "correct horse", None)
387
+ .unwrap();
388
+ for _ in 0..200 {
389
+ let identity = store.list().unwrap()[0].clone();
390
+ store.issue_session(&identity, "password", None, 900).unwrap();
391
+ }
392
+ // 201 stored sessions. Before 0.15.0 this rejection ran 201 Argon2
393
+ // verifications (seconds); a digest lookup is microseconds.
394
+ let started = std::time::Instant::now();
395
+ for _ in 0..50 {
396
+ assert!(store.authenticate_session("session_token_not-a-real-one").is_none());
397
+ }
398
+ assert!(started.elapsed() < std::time::Duration::from_millis(200), "{:?}", started.elapsed());
399
+ assert!(store.authenticate_session(&token).is_some());
400
+ let _ = std::fs::remove_file(p);
401
+ }
402
+ #[test]
403
+ fn a_session_from_before_the_digest_is_not_accepted() {
404
+ let p = std::env::temp_dir().join(format!("identity-session-{}.json", id("test")));
405
+ let store = IdentityStore::load(&p).unwrap();
406
+ let (identity, _, _) = store.sign_up("old@example.com", "correct horse", None).unwrap();
407
+ let legacy_token = "session_token_legacylegacylegacy";
408
+ {
409
+ let mut state = store.state.write().unwrap();
410
+ let mut legacy = state.sessions[0].clone();
411
+ legacy.session_id = "legacy".into();
412
+ legacy.refresh_hash = Some(IdentityStore::hash_password(legacy_token).unwrap());
413
+ legacy.token_digest = None;
414
+ legacy.subject_id = identity.subject_id.clone();
415
+ state.sessions.push(legacy);
416
+ }
417
+ assert!(store.authenticate_session(legacy_token).is_none());
418
+ let _ = std::fs::remove_file(p);
419
+ }
358
420
  }