laser-wire 0.0.1-rc.10

LaserData wire contract: managed command codes, CBOR envelopes including the Agent Data Exchange Protocol (AGDX) agent envelope, the query IR, projections, schemas, KV, forks, and the HTTP surface. Runtime-free, wasm-compatible.
Documentation
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
use crate::codes::*;
use serde::{Deserialize, Serialize};

/// Whether a grant permits or forbids. `Deny` always wins over `Allow`.
#[derive(
    Clone,
    Copy,
    Debug,
    Default,
    PartialEq,
    Eq,
    Serialize,
    Deserialize,
    strum::Display,
    strum::EnumString,
    strum::VariantArray,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Effect {
    #[default]
    Allow,
    Deny,
}

/// The managed surface a grant applies to. Maps to the command bands, so a grant
/// on `Kv` is orthogonal to one on `Projection`.
#[derive(
    Clone,
    Copy,
    Debug,
    PartialEq,
    Eq,
    Hash,
    Serialize,
    Deserialize,
    strum::Display,
    strum::EnumString,
    strum::VariantArray,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Feature {
    Kv,
    Memory,
    Projection,
    Fork,
    Graph,
    Query,
    Agent,
    Workflow,
    /// Administration of the authorization layer itself (defining roles and
    /// binding them). Gated by `authz:admin`; never derived from a command code.
    Authz,
}

/// The verb a grant permits, derived from the command code by [`feature_action`].
#[derive(
    Clone,
    Copy,
    Debug,
    PartialEq,
    Eq,
    Hash,
    Serialize,
    Deserialize,
    strum::Display,
    strum::EnumString,
    strum::VariantArray,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Action {
    Read,
    Write,
    Delete,
    Admin,
}

/// How a [`ResourcePattern`] matches a request's resource selector.
#[derive(
    Clone,
    Copy,
    Debug,
    Default,
    PartialEq,
    Eq,
    Serialize,
    Deserialize,
    strum::Display,
    strum::EnumString,
    strum::VariantArray,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ResourceKind {
    /// The whole feature, ignoring `value` (the absent-pattern default).
    #[default]
    All,
    /// One exact resource name.
    Literal,
    /// Every resource name under a prefix.
    Prefix,
}

/// A resource selector on a grant: literal, prefixed, or the whole feature.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResourcePattern {
    #[serde(default)]
    pub kind: ResourceKind,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub value: String,
}

impl ResourcePattern {
    /// The whole-feature pattern.
    pub fn all() -> Self {
        Self::default()
    }

    /// An exact-name pattern.
    pub fn literal(value: impl Into<String>) -> Self {
        Self {
            kind: ResourceKind::Literal,
            value: value.into(),
        }
    }

    /// A prefix pattern (every name under `value`).
    pub fn prefix(value: impl Into<String>) -> Self {
        Self {
            kind: ResourceKind::Prefix,
            value: value.into(),
        }
    }

    /// Whether `resource` (the selector decoded from a request) matches. An
    /// unkeyed request (`None`) matches only a whole-feature pattern.
    pub fn matches(&self, resource: Option<&str>) -> bool {
        match (self.kind, resource) {
            (ResourceKind::All, _) => true,
            (ResourceKind::Literal, Some(r)) => r == self.value,
            (ResourceKind::Prefix, Some(r)) => r.starts_with(&self.value),
            (_, None) => false,
        }
    }
}

/// One capability grant: an effect on a `feature:action`, optionally scoped to a
/// resource pattern.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Grant {
    pub effect: Effect,
    pub feature: Feature,
    pub action: Action,
    #[serde(default)]
    pub resource: ResourcePattern,
}

/// A named set of grants, bound to users. A user's effective capability is the
/// union of the grants of every bound role, minus any matching deny.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Role {
    pub name: String,
    pub grants: Vec<Grant>,
}

/// The roles bound to one user (by the server-stamped `user_id`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RoleBinding {
    pub user_id: u32,
    pub roles: Vec<String>,
}

/// The `(feature, action)` a managed command code authorizes against. `None` for
/// a code with no capability semantics (hello, backend hello, client metadata,
/// batch, and the authz band itself), which is gated another way.
pub fn feature_action(code: u32) -> Option<(Feature, Action)> {
    let pair = match code {
        AGDX_QUERY_CODE => (Feature::Query, Action::Read),
        AGDX_GET_PROJECTION_CODE
        | AGDX_LIST_PROJECTIONS_CODE
        | AGDX_GET_SCHEMA_CODE
        | AGDX_LIST_SCHEMAS_CODE
        | AGDX_DECODE_RECORD_CODE => (Feature::Projection, Action::Read),
        AGDX_REGISTER_SCHEMA_CODE => (Feature::Projection, Action::Admin),
        AGDX_KV_GET_CODE | AGDX_KV_SCAN_CODE | AGDX_KV_NAMESPACES_CODE | AGDX_KV_EXISTS_CODE => {
            (Feature::Kv, Action::Read)
        }
        AGDX_KV_SET_CODE
        | AGDX_KV_CAS_CODE
        | AGDX_KV_CAS_FENCED_CODE
        | AGDX_KV_PATCH_CODE
        | AGDX_KV_EXPIRE_CODE
        | AGDX_KV_COPY_CODE
        | AGDX_KV_MOVE_CODE
        | AGDX_KV_LEASE_CODE
        | AGDX_KV_RELEASE_CODE => (Feature::Kv, Action::Write),
        AGDX_KV_DELETE_CODE | AGDX_KV_DELETE_MANY_CODE => (Feature::Kv, Action::Delete),
        AGDX_FORK_LIST_CODE => (Feature::Fork, Action::Read),
        AGDX_FORK_CREATE_CODE | AGDX_FORK_PUT_CODE => (Feature::Fork, Action::Write),
        AGDX_FORK_PROMOTE_CODE => (Feature::Fork, Action::Admin),
        AGDX_FORK_DELETE_CODE => (Feature::Fork, Action::Delete),
        AGDX_GRAPH_QUERY_CODE | AGDX_GRAPH_NEIGHBORS_CODE => (Feature::Graph, Action::Read),
        AGDX_GRAPH_UPSERT_CODE => (Feature::Graph, Action::Write),
        AGDX_AGENT_STATUS_CODE | AGDX_AGENT_LIST_CODE => (Feature::Agent, Action::Read),
        AGDX_AGENT_SUBMIT_CODE => (Feature::Agent, Action::Write),
        AGDX_AGENT_CANCEL_CODE => (Feature::Agent, Action::Delete),
        _ => return None,
    };
    Some(pair)
}

/// The number of [`Action`] variants: the stride of the shared coarse-capability
/// bitmask layout ([`action_index`]).
pub const ACTION_COUNT: usize = 4;

/// The bit index of a `(feature, action)` in the coarse-capability bitmask, a
/// pure function shared by every enforcer so the fork and the plane cannot drift.
/// `Feature`/`Action` are `VariantArray` enums, so the ordinal is stable per wire
/// revision.
pub fn action_index(feature: Feature, action: Action) -> usize {
    feature as usize * ACTION_COUNT + action as usize
}

/// Whether `grants` permit `(feature, action)` on `resource`, deny-wins. An
/// empty set permits nothing (there is no allow to match). `resource` is the
/// selector decoded from a request, or `None` for an unkeyed op.
pub fn grants_allow(
    grants: &[Grant],
    feature: Feature,
    action: Action,
    resource: Option<&str>,
) -> bool {
    let mut allowed = false;
    for grant in grants {
        if grant.feature == feature && grant.action == action && grant.resource.matches(resource) {
            match grant.effect {
                Effect::Deny => return false,
                Effect::Allow => allowed = true,
            }
        }
    }
    allowed
}

/// The on-behalf-of check: an agent acting for a user is permitted an op only
/// when both its own grants and the invoking user's grants permit it. The agent
/// can never exceed the user who invoked it (permission intersection).
pub fn delegated_allow(
    agent: &[Grant],
    user: &[Grant],
    feature: Feature,
    action: Action,
    resource: Option<&str>,
) -> bool {
    grants_allow(agent, feature, action, resource) && grants_allow(user, feature, action, resource)
}

/// Request the caller's own effective capabilities.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct WhoamiReq {
    pub v: u32,
}

/// The caller's bound roles and their flattened grants.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct WhoamiReply {
    pub v: u32,
    pub roles: Vec<String>,
    pub grants: Vec<Grant>,
}

/// Request to list roles, optionally filtered. Absent filters list every role,
/// the same bounded-registry browse as `ListProjections`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ListRolesReq {
    pub v: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name_prefix: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub search: Option<String>,
}

/// Every matching role with its full grant set.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ListRolesReply {
    pub v: u32,
    pub roles: Vec<Role>,
}

/// Request one role by name.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GetRoleReq {
    pub v: u32,
    pub name: String,
}

/// Request one user's bound role names.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GetBindingsReq {
    pub v: u32,
    pub user_id: u32,
}

/// One user's bound role names.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct BindingsReply {
    pub v: u32,
    pub roles: Vec<String>,
}

/// Define or replace a role (upsert, carries the full grant set).
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DefineRoleReq {
    pub v: u32,
    pub role: Role,
}

/// Delete a role by name.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeleteRoleReq {
    pub v: u32,
    pub name: String,
}

/// Bind roles to a user (replace the user's whole role set).
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BindRolesReq {
    pub v: u32,
    pub user_id: u32,
    pub roles: Vec<String>,
}

/// Reply to any authorization command, shaped per request.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum AuthzReply {
    /// A mutating command applied (`define_role`, `delete_role`, `bind_roles`).
    Ok,
    /// `whoami`: the caller's effective capabilities.
    Whoami(WhoamiReply),
    /// `list_roles`: every matching role.
    Roles(ListRolesReply),
    /// `get_role`: the role with the requested name, or `None`.
    Role(Option<Role>),
    /// `get_bindings`: one user's bound role names.
    Bindings(BindingsReply),
    Err(AuthzError),
}

/// An authorization command failure.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
#[non_exhaustive]
pub enum AuthzError {
    #[error("authz not supported: {0}")]
    Unsupported(String),
    #[error("unauthorized")]
    Unauthorized,
    #[error("unknown role: {0}")]
    UnknownRole(String),
    #[error("unsupported authz op version (expected {expected}, got {got})")]
    Version { expected: u32, got: u32 },
}

#[cfg(all(test, feature = "cbor"))]
mod tests {
    use super::*;
    use crate::framing::{decode_named, encode_named};

    #[test]
    fn given_a_role_when_round_tripped_then_should_preserve_grants() {
        let role = Role {
            name: "kv-reader".to_string(),
            grants: vec![
                Grant {
                    effect: Effect::Allow,
                    feature: Feature::Kv,
                    action: Action::Read,
                    resource: ResourcePattern::prefix("agent-abc/"),
                },
                Grant {
                    effect: Effect::Deny,
                    feature: Feature::Kv,
                    action: Action::Read,
                    resource: ResourcePattern::literal("agent-abc/secret"),
                },
            ],
        };
        let bytes = encode_named(&role).expect("role serializes");
        let back: Role = decode_named(&bytes).expect("role deserializes");
        assert_eq!(back, role);
    }

    #[test]
    fn given_a_resource_pattern_when_matched_then_should_honor_its_kind() {
        assert!(ResourcePattern::all().matches(Some("anything")));
        assert!(ResourcePattern::all().matches(None));
        assert!(ResourcePattern::literal("ns").matches(Some("ns")));
        assert!(!ResourcePattern::literal("ns").matches(Some("ns2")));
        assert!(ResourcePattern::prefix("agent-").matches(Some("agent-abc")));
        assert!(!ResourcePattern::prefix("agent-").matches(Some("other")));
        // Unkeyed requests are whole-surface operations, so scoped grants must
        // not widen to them.
        assert!(!ResourcePattern::literal("ns").matches(None));
        assert!(!ResourcePattern::prefix("agent-").matches(None));
    }

    #[test]
    fn given_delegation_when_checked_then_agent_is_intersected_with_the_user() {
        let allow = |feature, action, resource| Grant {
            effect: Effect::Allow,
            feature,
            action,
            resource,
        };
        // Agent may read+write kv anywhere; the user it acts for may only read kv
        // under `shared/`. The intersection permits only what BOTH allow.
        let agent = vec![
            allow(Feature::Kv, Action::Read, ResourcePattern::all()),
            allow(Feature::Kv, Action::Write, ResourcePattern::all()),
        ];
        let user = vec![allow(
            Feature::Kv,
            Action::Read,
            ResourcePattern::prefix("shared/"),
        )];
        assert!(delegated_allow(
            &agent,
            &user,
            Feature::Kv,
            Action::Read,
            Some("shared/x")
        ));
        // Outside the user's prefix: agent alone would allow, the user does not.
        assert!(!delegated_allow(
            &agent,
            &user,
            Feature::Kv,
            Action::Read,
            Some("private/x")
        ));
        // The user cannot write at all, so the agent cannot write on its behalf.
        assert!(!delegated_allow(
            &agent,
            &user,
            Feature::Kv,
            Action::Write,
            Some("shared/x")
        ));
        // An empty grant set permits nothing.
        assert!(!grants_allow(&[], Feature::Kv, Action::Read, None));
    }

    #[test]
    fn given_a_command_code_when_classified_then_should_map_to_feature_and_action() {
        assert_eq!(
            feature_action(AGDX_KV_GET_CODE),
            Some((Feature::Kv, Action::Read))
        );
        assert_eq!(
            feature_action(AGDX_KV_SET_CODE),
            Some((Feature::Kv, Action::Write))
        );
        assert_eq!(
            feature_action(AGDX_KV_DELETE_CODE),
            Some((Feature::Kv, Action::Delete))
        );
        assert_eq!(
            feature_action(AGDX_REGISTER_SCHEMA_CODE),
            Some((Feature::Projection, Action::Admin))
        );
        assert_eq!(
            feature_action(AGDX_QUERY_CODE),
            Some((Feature::Query, Action::Read))
        );
        assert_eq!(
            feature_action(AGDX_GRAPH_UPSERT_CODE),
            Some((Feature::Graph, Action::Write))
        );
        // No capability semantics: hello, batch, and the authz band self-gate.
        assert_eq!(feature_action(AGDX_HELLO_CODE), None);
        assert_eq!(feature_action(AGDX_BATCH_CODE), None);
        assert_eq!(feature_action(AGDX_AUTHZ_WHOAMI_CODE), None);
    }

    #[test]
    fn given_feature_action_pairs_when_indexed_then_should_fit_a_u64_mask() {
        use strum::VariantArray;
        let mut seen = std::collections::HashSet::new();
        for &feature in Feature::VARIANTS {
            for &action in Action::VARIANTS {
                let index = action_index(feature, action);
                assert!(index < 64, "index {index} must fit a u64 mask");
                assert!(seen.insert(index), "index {index} collided");
            }
        }
    }

    #[test]
    fn given_an_authz_reply_when_round_tripped_then_should_preserve_the_variant() {
        let reply = AuthzReply::Whoami(WhoamiReply {
            v: AUTHZ_OP_VERSION,
            roles: vec!["admin".to_string()],
            grants: vec![Grant {
                effect: Effect::Allow,
                feature: Feature::Kv,
                action: Action::Write,
                resource: ResourcePattern::all(),
            }],
        });
        let bytes = encode_named(&reply).expect("reply serializes");
        let back: AuthzReply = decode_named(&bytes).expect("reply deserializes");
        assert_eq!(back, reply);
    }
}