alkcall 0.8.0

Call + channels RPC: structured JSON operations, streaming subscriptions, service discovery, and N-channel multiplexing over one transport stream
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
//! Operation specifications: `OperationSpec`, `OperationType`, `Visibility`,
//! `ErrorDefinition`, and `AccessControl`.
//!
//! See `docs/architecture/` for the full specification.

use std::borrow::Cow;

use crate::core::auth::Identity;
use crate::core::ownership::OwnershipProvider;
use serde_json::Value;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OperationType {
    Query,
    Mutation,
    Sub,
    Pub,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Visibility {
    External,
    Internal,
}

/// Marker on `OperationSpec` telling the channels layer "this op's
/// stream is binary, allocate a data channel for it" (ADR-047 §2). The
/// marker is registry metadata, not auth machinery — parallel to how
/// `resource_id_path` tells ADR-011 where to find the resource ID. The
/// op's `access_control` is the ACL (unchanged); the marker is the
/// dispatch hint.
///
/// `alpn` is the data-plane ALPN the channel will carry (e.g.
/// `"alk/tty"`). It is derivable from the op name
/// (`channels/<alpn>/sub` → `alk/<alpn>`), but carried here so the
/// channels layer doesn't have to parse the op name. On the wire
/// (`services/schema`), the marker is a boolean `"channel_open": true`;
/// the ALPN is not serialized (it's derivable).
///
/// The `alpn` is a `Cow<'static, str>` so that statically-registered
/// ops (the common case — ALPN crates register at compile time with a
/// `&'static str`) pay no allocation, while `from_call`-discovered ops
/// (whose ALPN is a runtime `String` parsed from the op name) can
/// supply an owned value without `Box::leak`-ing it to `'static`
/// (ADR-047 §2 said `&'static str` was "for now"; the `Cow` is the
/// deferred refactor that removes the per-discovery leak).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChannelOpenSpec {
    pub alpn: Cow<'static, str>,
}

impl ChannelOpenSpec {
    pub fn new(alpn: impl Into<Cow<'static, str>>) -> Self {
        Self { alpn: alpn.into() }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ErrorDefinition {
    pub code: String,
    pub description: String,
    pub schema: Value,
    pub http_status: Option<u16>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AccessControl {
    pub required_scopes: Vec<String>,
    pub required_scopes_any: Option<Vec<String>>,
    pub resource_type: Option<String>,
    pub resource_action: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AccessResult {
    Allowed,
    Forbidden(String),
}

impl AccessResult {
    pub fn is_allowed(&self) -> bool {
        matches!(self, AccessResult::Allowed)
    }
}

impl AccessControl {
    pub fn has_restrictions(&self) -> bool {
        !self.required_scopes.is_empty()
            || self.required_scopes_any.is_some()
            || self.resource_type.is_some()
            || self.resource_action.is_some()
    }

    pub fn check(
        &self,
        identity: Option<&Identity>,
        resource_id: Option<&str>,
        ownership: Option<&dyn OwnershipProvider>,
    ) -> AccessResult {
        if !self.has_restrictions() {
            return AccessResult::Allowed;
        }
        let identity = match identity {
            Some(id) => id,
            None => return AccessResult::Forbidden("authentication required".to_string()),
        };

        for scope in &self.required_scopes {
            if !identity.scopes.iter().any(|s| s == scope) {
                return AccessResult::Forbidden(format!("missing required scope: {scope}"));
            }
        }

        if let Some(any) = &self.required_scopes_any {
            let has_one = any.iter().any(|s| identity.scopes.iter().any(|i| i == s));
            if !has_one {
                return AccessResult::Forbidden(
                    "missing required scope (any of: ".to_string() + &any.join(", ") + ")",
                );
            }
        }

        if let Some(p) = ownership {
            if let Some(rt) = &self.resource_type {
                match resource_id {
                    Some(rid) => {
                        let action = self.resource_action.as_deref().unwrap_or("");
                        if !p.owns(identity, rt, rid, action) {
                            return AccessResult::Forbidden(format!(
                                "not owner of resource: {rt}/{rid}"
                            ));
                        }
                    }
                    None => {
                        if !p.owns_any(identity, rt) {
                            return AccessResult::Forbidden(format!(
                                "no owned resources of type: {rt}"
                            ));
                        }
                    }
                }
                return AccessResult::Allowed;
            }
        }

        if let Some(rt) = &self.resource_type {
            let allowed = identity.resources.get(rt);
            match &self.resource_action {
                Some(action) => match allowed {
                    Some(actions) if actions.iter().any(|a| a == action) => {}
                    _ => {
                        return AccessResult::Forbidden(format!("missing resource: {rt}/{action}"))
                    }
                },
                None => match allowed {
                    Some(actions) if !actions.is_empty() => {}
                    _ => return AccessResult::Forbidden(format!("missing resource: {rt}")),
                },
            }
        } else if let Some(action) = &self.resource_action {
            let found = identity
                .resources
                .values()
                .any(|actions| actions.iter().any(|a| a == action));
            if !found {
                return AccessResult::Forbidden(format!("missing resource action: {action}"));
            }
        }

        AccessResult::Allowed
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct OperationSpec {
    pub name: String,
    pub namespace: String,
    pub op_type: OperationType,
    pub visibility: Visibility,
    pub input_schema: Value,
    pub output_schema: Value,
    pub error_schemas: Vec<ErrorDefinition>,
    pub access_control: AccessControl,
    /// Human-readable op description, disclosed by `services/list` when
    /// set and by `services/schema` (`spec_to_json_pub`) — review 006
    /// E-02. `None` (absent on the wire) for ops that declare none; the
    /// field is additive and registry-side (it describes the op, not the
    /// produced resource set — ADR-047 §6 keeps the live half of
    /// discovery in `channel/resources/subscribe`).
    pub description: Option<String>,
    /// JSON pointer into the input for the resource ID, when
    /// `access_control.resource_type` is set and the operation targets a
    /// specific runtime-spawned resource (ADR-011). e.g. `"$.containerId"`
    /// for `docker/container/exec`. Absent for no-specific-resource
    /// operations (the `list` case). `None` for operations with no
    /// `resource_type` or with static resource sets.
    pub resource_id_path: Option<String>,
    /// Schema for each published chunk's `input` (Pub ops only, ADR-046).
    /// `None` for Query/Mutation/Sub ops. When set, the dispatch path
    /// validates each `call.published` event's `payload.input` against
    /// this schema before yielding it to the `SinkHandler`. When `None`
    /// (Pub op with no per-chunk validation), chunks are yielded as-is.
    pub publish_schema: Option<Value>,
    /// Marker telling the channels layer "this op's stream is binary,
    /// allocate a data channel for it" (ADR-047 §2). `None` for ops
    /// whose stream is JSON (Query/Mutation/Sub/Pub without a binary
    /// data plane). When set, the op is a channel-open op
    /// (`channels/<alpn>/sub` or `channels/<alpn>/pub`); the channels
    /// layer's `ChannelCore` wrapper reads the marker to know the op
    /// needs a binary channel. The marker is orthogonal to
    /// `access_control` (the ACL) and to `op_type` (the direction) —
    /// it's the dispatch hint for binary vs JSON framing.
    pub channel_open: Option<ChannelOpenSpec>,
}

impl OperationSpec {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        name: impl Into<String>,
        op_type: OperationType,
        visibility: Visibility,
        input_schema: Value,
        output_schema: Value,
        error_schemas: Vec<ErrorDefinition>,
        access_control: AccessControl,
        resource_id_path: Option<String>,
    ) -> Self {
        let name = name.into();
        let namespace = name
            .split('/')
            .next()
            .filter(|s| !s.is_empty())
            .unwrap_or("")
            .to_string();
        Self {
            name,
            namespace,
            op_type,
            visibility,
            input_schema,
            output_schema,
            error_schemas,
            access_control,
            description: None,
            resource_id_path,
            publish_schema: None,
            channel_open: None,
        }
    }

    /// Set the op's `description` (review 006 E-02). Disclosed by
    /// `services/list` when set; carried in the `services/schema` wire
    /// shape (`spec_to_json_pub` / `rebuild_spec_for`). Builder-style;
    /// returns `self` for chaining at registration sites.
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Set the `publish_schema` (Pub ops only, ADR-046). Validates each
    /// `call.published` chunk's `input`. Builder-style; returns `self`
    /// for chaining at registration sites.
    pub fn with_publish_schema(mut self, schema: Value) -> Self {
        self.publish_schema = Some(schema);
        self
    }

    /// Set the `channel_open` marker (ADR-047 §2). Tells the channels
    /// layer "this op's stream is binary, allocate a data channel for
    /// it." Builder-style; returns `self` for chaining at registration
    /// sites. Used by `channels/<alpn>/sub` and `channels/<alpn>/pub`
    /// ops.
    pub fn with_channel_open(mut self, spec: ChannelOpenSpec) -> Self {
        self.channel_open = Some(spec);
        self
    }

    pub fn path(&self) -> String {
        format!("/{}", self.name)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    fn identity(scopes: &[&str], resources: &[(&str, &[&str])]) -> Identity {
        let mut res = HashMap::new();
        for (k, v) in resources {
            res.insert(
                (*k).to_string(),
                v.iter().map(|s| (*s).to_string()).collect(),
            );
        }
        Identity {
            id: "caller".to_string(),
            scopes: scopes.iter().map(|s| (*s).to_string()).collect(),
            resources: res,
        }
    }

    #[test]
    fn path_has_leading_slash() {
        let spec = OperationSpec::new(
            "fs/readFile",
            OperationType::Query,
            Visibility::External,
            serde_json::json!({}),
            serde_json::json!({}),
            vec![],
            AccessControl::default(),
            None,
        );
        assert_eq!(spec.path(), "/fs/readFile");
    }

    #[test]
    fn namespace_derived_from_name() {
        let spec = OperationSpec::new(
            "agent/chat",
            OperationType::Sub,
            Visibility::External,
            serde_json::json!({}),
            serde_json::json!({}),
            vec![],
            AccessControl::default(),
            None,
        );
        assert_eq!(spec.namespace, "agent");
        assert_eq!(spec.name, "agent/chat");
    }

    #[test]
    fn namespace_for_single_segment() {
        let spec = OperationSpec::new(
            "list",
            OperationType::Query,
            Visibility::Internal,
            serde_json::json!({}),
            serde_json::json!({}),
            vec![],
            AccessControl::default(),
            None,
        );
        assert_eq!(spec.namespace, "list");
    }

    #[test]
    fn resource_id_path_defaults_to_none() {
        let spec = OperationSpec::new(
            "fs/readFile",
            OperationType::Query,
            Visibility::External,
            serde_json::json!({}),
            serde_json::json!({}),
            vec![],
            AccessControl::default(),
            None,
        );
        assert_eq!(spec.resource_id_path, None);
    }

    #[test]
    fn channel_open_defaults_to_none() {
        let spec = OperationSpec::new(
            "channels/tty/sub",
            OperationType::Sub,
            Visibility::External,
            serde_json::json!({}),
            serde_json::json!({}),
            vec![],
            AccessControl::default(),
            None,
        );
        assert_eq!(spec.channel_open, None);
    }

    #[test]
    fn description_defaults_to_none_and_builder_sets_it() {
        let spec = OperationSpec::new(
            "channels/tty/sub",
            OperationType::Sub,
            Visibility::External,
            serde_json::json!({}),
            serde_json::json!({}),
            vec![],
            AccessControl::default(),
            None,
        );
        assert_eq!(spec.description, None);

        let described = spec.with_description("Interactive TTY sessions");
        assert_eq!(
            described.description.as_deref(),
            Some("Interactive TTY sessions")
        );
    }

    #[test]
    fn with_channel_open_sets_marker() {
        let spec = OperationSpec::new(
            "channels/tty/sub",
            OperationType::Sub,
            Visibility::External,
            serde_json::json!({}),
            serde_json::json!({}),
            vec![],
            AccessControl::default(),
            None,
        )
        .with_channel_open(ChannelOpenSpec::new("alk/tty"));
        let marker = spec.channel_open.expect("channel_open set");
        assert_eq!(marker.alpn, "alk/tty");
    }

    #[test]
    fn empty_access_control_allowed_for_all() {
        let acl = AccessControl::default();
        assert_eq!(acl.check(None, None, None), AccessResult::Allowed);
        let id = identity(&[], &[]);
        assert_eq!(acl.check(Some(&id), None, None), AccessResult::Allowed);
    }

    #[test]
    fn none_identity_with_restrictions_forbidden() {
        let acl = AccessControl {
            required_scopes: vec!["read".to_string()],
            ..Default::default()
        };
        assert_eq!(
            acl.check(None, None, None),
            AccessResult::Forbidden("authentication required".to_string())
        );

        let acl2 = AccessControl {
            required_scopes_any: Some(vec!["read".to_string()]),
            ..Default::default()
        };
        assert_eq!(
            acl2.check(None, None, None),
            AccessResult::Forbidden("authentication required".to_string())
        );

        let acl3 = AccessControl {
            resource_type: Some("service".to_string()),
            ..Default::default()
        };
        assert_eq!(
            acl3.check(None, None, None),
            AccessResult::Forbidden("authentication required".to_string())
        );
    }

    #[test]
    fn required_scopes_and_checked() {
        let acl = AccessControl {
            required_scopes: vec!["a".to_string(), "b".to_string()],
            ..Default::default()
        };
        let id_missing = identity(&["a"], &[]);
        assert!(matches!(
            acl.check(Some(&id_missing), None, None),
            AccessResult::Forbidden(_)
        ));
        let id_ok = identity(&["a", "b", "c"], &[]);
        assert_eq!(acl.check(Some(&id_ok), None, None), AccessResult::Allowed);
    }

    #[test]
    fn required_scopes_any_or_checked() {
        let acl = AccessControl {
            required_scopes_any: Some(vec!["x".to_string(), "y".to_string()]),
            ..Default::default()
        };
        let id_x = identity(&["x"], &[]);
        assert_eq!(acl.check(Some(&id_x), None, None), AccessResult::Allowed);
        let id_y = identity(&["y"], &[]);
        assert_eq!(acl.check(Some(&id_y), None, None), AccessResult::Allowed);
        let id_none = identity(&["z"], &[]);
        assert!(matches!(
            acl.check(Some(&id_none), None, None),
            AccessResult::Forbidden(_)
        ));
    }

    #[test]
    fn resource_check_with_type_and_action() {
        let acl = AccessControl {
            resource_type: Some("service".to_string()),
            resource_action: Some("read".to_string()),
            ..Default::default()
        };
        let id_ok = identity(&[], &[("service", &["read"])]);
        assert_eq!(acl.check(Some(&id_ok), None, None), AccessResult::Allowed);
        let id_missing_action = identity(&[], &[("service", &["write"])]);
        assert!(matches!(
            acl.check(Some(&id_missing_action), None, None),
            AccessResult::Forbidden(_)
        ));
        let id_missing_type = identity(&[], &[("other", &["read"])]);
        assert!(matches!(
            acl.check(Some(&id_missing_type), None, None),
            AccessResult::Forbidden(_)
        ));
    }

    #[test]
    fn combined_scopes_and_resources() {
        let acl = AccessControl {
            required_scopes: vec!["admin".to_string()],
            resource_type: Some("service".to_string()),
            resource_action: Some("read".to_string()),
            ..Default::default()
        };
        let id_ok = identity(&["admin"], &[("service", &["read"])]);
        assert_eq!(acl.check(Some(&id_ok), None, None), AccessResult::Allowed);
        let id_missing_scope = identity(&["user"], &[("service", &["read"])]);
        assert!(matches!(
            acl.check(Some(&id_missing_scope), None, None),
            AccessResult::Forbidden(_)
        ));
    }

    struct MockOwnership {
        owned: Vec<(String, String)>,
    }

    impl OwnershipProvider for MockOwnership {
        fn owns(
            &self,
            _identity: &Identity,
            resource_type: &str,
            resource_id: &str,
            _action: &str,
        ) -> bool {
            self.owned
                .iter()
                .any(|(rt, rid)| rt == resource_type && rid == resource_id)
        }

        fn owned_resources(&self, _identity: &Identity, resource_type: &str) -> Vec<String> {
            self.owned
                .iter()
                .filter(|(rt, _)| rt == resource_type)
                .map(|(_, rid)| rid.clone())
                .collect()
        }

        fn owns_any(&self, _identity: &Identity, resource_type: &str) -> bool {
            self.owned.iter().any(|(rt, _)| rt == resource_type)
        }
    }

    fn empty_identity(id: &str) -> Identity {
        Identity {
            id: id.to_string(),
            scopes: vec![],
            resources: HashMap::new(),
        }
    }

    #[test]
    fn ownership_provider_allows_owned_resource() {
        let acl = AccessControl {
            resource_type: Some("container".to_string()),
            resource_action: Some("exec".to_string()),
            ..Default::default()
        };
        let id = empty_identity("alice");
        let provider = MockOwnership {
            owned: vec![("container".to_string(), "c1".to_string())],
        };
        assert_eq!(
            acl.check(
                Some(&id),
                Some("c1"),
                Some(&provider as &dyn OwnershipProvider)
            ),
            AccessResult::Allowed
        );
    }

    #[test]
    fn ownership_provider_forbids_unowned_resource() {
        let acl = AccessControl {
            resource_type: Some("container".to_string()),
            resource_action: Some("exec".to_string()),
            ..Default::default()
        };
        let id = empty_identity("alice");
        let provider = MockOwnership {
            owned: vec![("container".to_string(), "c1".to_string())],
        };
        assert!(matches!(
            acl.check(
                Some(&id),
                Some("c2"),
                Some(&provider as &dyn OwnershipProvider)
            ),
            AccessResult::Forbidden(_)
        ));
    }

    #[test]
    fn ownership_provider_forbids_none_identity() {
        let acl = AccessControl {
            resource_type: Some("container".to_string()),
            resource_action: Some("exec".to_string()),
            ..Default::default()
        };
        let provider = MockOwnership {
            owned: vec![("container".to_string(), "c1".to_string())],
        };
        assert!(matches!(
            acl.check(None, Some("c1"), Some(&provider as &dyn OwnershipProvider)),
            AccessResult::Forbidden(_)
        ));
    }

    #[test]
    fn ownership_provider_list_allowed_when_owns_any() {
        let acl = AccessControl {
            resource_type: Some("container".to_string()),
            resource_action: Some("exec".to_string()),
            ..Default::default()
        };
        let id = empty_identity("alice");
        let provider = MockOwnership {
            owned: vec![("container".to_string(), "c1".to_string())],
        };
        assert_eq!(
            acl.check(Some(&id), None, Some(&provider as &dyn OwnershipProvider)),
            AccessResult::Allowed
        );
    }

    #[test]
    fn ownership_provider_list_forbidden_when_not_owns_any() {
        let acl = AccessControl {
            resource_type: Some("container".to_string()),
            resource_action: Some("exec".to_string()),
            ..Default::default()
        };
        let id = empty_identity("alice");
        let provider = MockOwnership {
            owned: vec![("volume".to_string(), "v1".to_string())],
        };
        assert!(matches!(
            acl.check(Some(&id), None, Some(&provider as &dyn OwnershipProvider)),
            AccessResult::Forbidden(_)
        ));
    }

    #[test]
    fn ownership_none_falls_back_to_static() {
        let acl = AccessControl {
            resource_type: Some("service".to_string()),
            resource_action: Some("read".to_string()),
            ..Default::default()
        };
        let id_ok = identity(&[], &[("service", &["read"])]);
        assert_eq!(acl.check(Some(&id_ok), None, None), AccessResult::Allowed);
        let id_missing = identity(&[], &[("service", &["write"])]);
        assert!(matches!(
            acl.check(Some(&id_missing), None, None),
            AccessResult::Forbidden(_)
        ));
    }
}