greentic-runner-host 1.2.0

Host runtime shim for Greentic runner: config, pack loading, activity handling
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
//! Tests for [`super::http`] (env-configured `SorxHttpInvoker`) and
//! [`super::routed`] (per-SoR-routed `SorxRoutedInvoker`).

use greentic_aw_runtime::SorxInvoker;
use serde_json::json;
use wiremock::matchers::{body_partial_json, header, header_exists, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

use super::http::fixtures::{
    caps_response_for_pack, caps_response_landlord_plus_billing, caps_response_mixed,
    caps_response_one_business_action,
};
use super::http::{SorxHttpInvoker, parse_agent_endpoint_cap_uri};
use super::routed::SorxRoutedInvoker; // module is `pub(crate)`; see mod.rs
use crate::runner::sorla_route::test_secrets;

/// Mount a plain `200 GET /admin/v1/capabilities` response with `body` — the
/// shape every test below uses unless it also asserts on the request
/// (headers, `.expect()` counts), which stays written out in full.
async fn mount_caps_get(server: &MockServer, body: serde_json::Value) {
    Mock::given(method("GET"))
        .and(path("/admin/v1/capabilities"))
        .respond_with(ResponseTemplate::new(200).set_body_json(body))
        .mount(server)
        .await;
}

/// Mount a `{status} POST /admin/v1/capabilities/invoke` response with
/// `body` — for tests that don't also assert on the request itself.
async fn mount_invoke(server: &MockServer, status: u16, body: serde_json::Value) {
    Mock::given(method("POST"))
        .and(path("/admin/v1/capabilities/invoke"))
        .respond_with(ResponseTemplate::new(status).set_body_json(body))
        .mount(server)
        .await;
}

// ---- SorxHttpInvoker (GREENTIC_AW_SORX_URL env path) ----

#[tokio::test]
async fn fetch_surfaces_agent_endpoint_alongside_business_action() {
    let server = MockServer::start().await;
    mount_caps_get(&server, caps_response_mixed()).await;

    let invoker = SorxHttpInvoker::fetch(server.uri()).await;
    let mut ops = invoker.list_operations();
    ops.sort_by(|a, b| a.action.cmp(&b.action));

    assert_eq!(ops.len(), 2, "action + endpoint; event dropped");
    // agent-endpoint op keyed by (pack, endpoint_id), cap stored verbatim.
    let ep = ops
        .iter()
        .find(|o| o.action == "tenants.create")
        .expect("agent-endpoint op");
    assert_eq!(ep.pack, "landlord");
    assert_eq!(
        ep.cap_uri,
        "cap://greentic/agent-endpoints/landlord/tenants.create/v0.1.0"
    );
    assert_eq!(ep.description, "Create a tenant record");
}

#[tokio::test]
async fn fetch_builds_one_op_from_business_action_offer() {
    let server = MockServer::start().await;
    mount_caps_get(&server, caps_response_one_business_action()).await;

    let invoker = SorxHttpInvoker::fetch(server.uri()).await;
    let ops = invoker.list_operations();

    assert_eq!(ops.len(), 1, "the event offer must be filtered out");
    let op = &ops[0];
    assert_eq!(op.pack, "landlord");
    assert_eq!(op.action, "record_rent_payment");
    assert_eq!(
        op.cap_uri,
        "cap://greentic/business-functions/landlord/record_rent_payment/v0.1.0"
    );
    assert_eq!(op.description, "Record a rent payment");
}

#[tokio::test]
async fn fetch_degrades_to_empty_ops_on_unreachable_server() {
    // A port nothing is listening on: `fetch` must never crash worker
    // startup, just log and return an empty-ops invoker.
    let invoker = SorxHttpInvoker::fetch("http://127.0.0.1:1".to_string()).await;
    assert!(invoker.list_operations().is_empty());
}

#[tokio::test]
async fn discovery_401_yields_empty_ops_without_panicking() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/admin/v1/capabilities"))
        .respond_with(ResponseTemplate::new(401).set_body_json(json!({"secret": "leak"})))
        .mount(&server)
        .await;

    // A rejected credential must not silently read as "zero offers" with no
    // signal, and must not panic — the invoker still constructs.
    let invoker = SorxHttpInvoker::fetch(server.uri()).await;
    assert!(invoker.list_operations().is_empty());
}

#[tokio::test]
async fn invoke_happy_path_returns_result_value() {
    let server = MockServer::start().await;
    mount_caps_get(&server, caps_response_one_business_action()).await;
    mount_invoke(&server, 200, json!({"ok": true, "result": {"id": "pay-1"}})).await;

    let invoker = SorxHttpInvoker::fetch(server.uri()).await;
    let out = invoker
        .invoke("landlord", "record_rent_payment", "{}")
        .await
        .expect("invoke should succeed");
    assert_eq!(out, json!({"id": "pay-1"}));
}

#[tokio::test]
async fn invoke_202_approval_required_is_ok_not_err() {
    let server = MockServer::start().await;
    mount_caps_get(&server, caps_response_one_business_action()).await;
    mount_invoke(
        &server,
        202,
        json!({"ok": false, "status": "approval_required", "approval": {"id": "appr-1", "state": "pending"}}),
    )
    .await;

    let invoker = SorxHttpInvoker::fetch(server.uri()).await;
    let out = invoker
        .invoke("landlord", "record_rent_payment", "{}")
        .await
        .expect("202 approval_required must be Ok, not Err");
    assert_eq!(out["status"], "approval_required");
    assert_eq!(out["approval"]["id"], "appr-1");
}

#[tokio::test]
async fn invoke_403_maps_to_denied_error_value() {
    let server = MockServer::start().await;
    mount_caps_get(&server, caps_response_one_business_action()).await;
    mount_invoke(
        &server,
        403,
        json!({"ok": false, "error": {"code": "RUNTIME_CAPABILITY_DENIED", "message": "policy denied"}}),
    )
    .await;

    let invoker = SorxHttpInvoker::fetch(server.uri()).await;
    let out = invoker
        .invoke("landlord", "record_rent_payment", "{}")
        .await
        .expect("403 must be a structured Ok value, not Err");
    assert_eq!(out["error"], "denied");
}

#[tokio::test]
async fn invoke_404_maps_to_capability_not_found_error_value() {
    let server = MockServer::start().await;
    mount_caps_get(&server, caps_response_one_business_action()).await;
    mount_invoke(
        &server,
        404,
        json!({"ok": false, "error": {"code": "RUNTIME_CAPABILITY_NOT_FOUND", "message": "capability does not resolve to a business action"}}),
    )
    .await;

    let invoker = SorxHttpInvoker::fetch(server.uri()).await;
    let out = invoker
        .invoke("landlord", "record_rent_payment", "{}")
        .await
        .expect("404 must be a structured Ok value, not Err");
    assert_eq!(out["error"], "capability_not_found");
}

/// An unhandled status (anything but 200/202/401/403/404) must never echo the
/// SoR's response body into the error string: that error reaches the flow's
/// node output and trace, and the body may carry the SoR's own diagnostic
/// detail — or, as here, something outright secret.
#[tokio::test]
async fn invoke_500_error_names_the_status_never_the_body() {
    let server = MockServer::start().await;
    mount_caps_get(&server, caps_response_one_business_action()).await;
    mount_invoke(&server, 500, json!({"secret": "leak"})).await;

    let invoker = SorxHttpInvoker::fetch(server.uri()).await;
    let err = invoker
        .invoke("landlord", "record_rent_payment", "{}")
        .await
        .expect_err("an unhandled status must be Err");
    assert!(err.contains("status=500"), "got: {err}");
    assert!(
        !err.contains("leak"),
        "the response body must not leak: {err}"
    );
}

#[tokio::test]
#[serial_test::serial]
async fn invoke_carries_tenant_caller_and_role_headers() {
    let server = MockServer::start().await;
    mount_caps_get(&server, caps_response_one_business_action()).await;
    Mock::given(method("POST"))
        .and(path("/admin/v1/capabilities/invoke"))
        .and(header("X-Greentic-Tenant-Id", "acme"))
        .and(header("X-Greentic-Caller-Id", "dw-agent"))
        .and(header("X-Greentic-Caller-Role", "agent"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "ok": true,
            "result": {}
        })))
        .expect(1)
        .mount(&server)
        .await;

    // SAFETY: single-threaded env mutation local to this test; no other
    // test reads GREENTIC_AW_SORX_TENANT concurrently (crate convention:
    // env-mutating tests run `#[serial]` or use process-unique vars).
    #[allow(unsafe_code)]
    unsafe {
        std::env::set_var("GREENTIC_AW_SORX_TENANT", "acme");
    }
    let invoker = SorxHttpInvoker::fetch(server.uri()).await;
    let result = invoker
        .invoke("landlord", "record_rent_payment", "{}")
        .await;
    #[allow(unsafe_code)]
    unsafe {
        std::env::remove_var("GREENTIC_AW_SORX_TENANT");
    }
    result.expect("invoke should succeed; header expectation is checked by wiremock's .expect(1)");
}

#[tokio::test]
async fn invoke_unknown_pack_action_is_err() {
    let invoker = SorxHttpInvoker::fetch("http://127.0.0.1:1".to_string()).await;
    let err = invoker
        .invoke("nope", "nope", "{}")
        .await
        .expect_err("no capability registered => Err");
    assert!(err.contains("no capability"));
}

#[tokio::test]
async fn invoke_dispatches_agent_endpoint_cap_verbatim_and_parses_result() {
    let server = MockServer::start().await;
    mount_caps_get(&server, caps_response_mixed()).await;
    // The invoke MUST carry the agent-endpoint cap URI verbatim in the body.
    Mock::given(method("POST"))
        .and(path("/admin/v1/capabilities/invoke"))
        .and(body_partial_json(json!({
            "capability": "cap://greentic/agent-endpoints/landlord/tenants.create/v0.1.0"
        })))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "ok": true,
            "schema": "greentic.sorx.agent-endpoint-invoke-result.v1",
            "result": {"tenant_id": "t-1"},
            "events": []
        })))
        .expect(1)
        .mount(&server)
        .await;

    let invoker = SorxHttpInvoker::fetch(server.uri()).await;
    let out = invoker
        .invoke("landlord", "tenants.create", "{}")
        .await
        .expect("agent-endpoint invoke should succeed");
    assert_eq!(out, json!({"tenant_id": "t-1"}));
}

#[test]
fn parses_agent_endpoint_cap_uri_and_rejects_wrong_namespace() {
    assert_eq!(
        parse_agent_endpoint_cap_uri(
            "cap://greentic/agent-endpoints/landlord/tenants.create/v0.1.0"
        ),
        Some(("landlord".to_string(), "tenants.create".to_string()))
    );
    // Wrong namespace (business-functions) → None.
    assert_eq!(
        parse_agent_endpoint_cap_uri(
            "cap://greentic/business-functions/landlord/record_rent_payment/v0.1.0"
        ),
        None
    );
    // Missing trailing version segment → None.
    assert_eq!(
        parse_agent_endpoint_cap_uri("cap://greentic/agent-endpoints/landlord/tenants.create"),
        None
    );
    // Empty pack/id → None.
    assert_eq!(
        parse_agent_endpoint_cap_uri("cap://greentic/agent-endpoints//tenants.create/v0.1.0"),
        None
    );
    // Missing scheme prefix → None.
    assert_eq!(
        parse_agent_endpoint_cap_uri("greentic/agent-endpoints/a/b/v1"),
        None
    );
}

// ---- SorxRoutedInvoker (per-SoR routed) ----

/// A `secrets://default/acme/_/sorla/<sor>` document body for `url`, with an
/// optional bearer token.
fn route_doc(url: &str, token: Option<&str>) -> String {
    match token {
        Some(t) => format!(r#"{{"url":"{url}","token":"{t}","tenant":"acme"}}"#),
        None => format!(r#"{{"url":"{url}","tenant":"acme"}}"#),
    }
}

/// Build a [`SorxRoutedInvoker`] over `sors` (each `(sor, url, token)`),
/// under tenant `"acme"`. Returns the backing secrets fake too, so a test
/// can rewrite a route after construction (see
/// `invoke_rereads_the_route_on_every_call`).
async fn routed_invoker(
    sors: &[(&str, &str, Option<&str>)],
) -> (test_secrets::Handle, SorxRoutedInvoker) {
    let entries: Vec<(String, String)> = sors
        .iter()
        .map(|(sor, url, token)| {
            (
                format!("secrets://default/acme/_/sorla/{sor}"),
                route_doc(url, *token),
            )
        })
        .collect();
    let refs: Vec<(&str, &str)> = entries
        .iter()
        .map(|(u, b)| (u.as_str(), b.as_str()))
        .collect();
    let secrets = test_secrets::Handle::with(&refs);
    let names = sors.iter().map(|(sor, _, _)| sor.to_string()).collect();
    let inv =
        SorxRoutedInvoker::discover_all(names, secrets.manager(), "acme".to_string(), None).await;
    (secrets, inv)
}

#[tokio::test]
async fn no_token_sends_no_authorization_header() {
    let server = MockServer::start().await;
    mount_caps_get(&server, caps_response_one_business_action()).await;
    Mock::given(method("POST"))
        .and(path("/admin/v1/capabilities/invoke"))
        .and(header_exists("authorization"))
        .respond_with(ResponseTemplate::new(500))
        .expect(0)
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(path("/admin/v1/capabilities/invoke"))
        .and(header("X-Greentic-Tenant-Id", "acme"))
        .respond_with(
            ResponseTemplate::new(200).set_body_json(json!({"ok": true, "result": {"id": "r1"}})),
        )
        .expect(1)
        .mount(&server)
        .await;

    let (_secrets, inv) = routed_invoker(&[("landlord", &server.uri(), None)]).await;
    let out = inv
        .invoke("landlord", "record_rent_payment", "{}")
        .await
        .expect("ok");
    assert_eq!(out, json!({"id": "r1"}));
}

#[tokio::test]
async fn a_token_is_sent_as_bearer_on_discovery_and_invoke() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/admin/v1/capabilities"))
        .and(header("authorization", "Bearer t0k"))
        .respond_with(ResponseTemplate::new(200).set_body_json(caps_response_one_business_action()))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(path("/admin/v1/capabilities/invoke"))
        .and(header("authorization", "Bearer t0k"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true, "result": {}})))
        .expect(1)
        .mount(&server)
        .await;

    let (_secrets, inv) = routed_invoker(&[("landlord", &server.uri(), Some("t0k"))]).await;
    inv.invoke("landlord", "record_rent_payment", "{}")
        .await
        .expect("ok");
}

#[tokio::test]
async fn two_sors_discover_and_invoke_independently() {
    let server_a = MockServer::start().await;
    let server_b = MockServer::start().await;

    mount_caps_get(&server_a, caps_response_one_business_action()).await;
    mount_caps_get(&server_b, caps_response_for_pack("billing")).await;

    Mock::given(method("POST"))
        .and(path("/admin/v1/capabilities/invoke"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_json(json!({"ok": true, "result": {"from": "landlord"}})),
        )
        .expect(1)
        .mount(&server_a)
        .await;
    Mock::given(method("POST"))
        .and(path("/admin/v1/capabilities/invoke"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_json(json!({"ok": true, "result": {"from": "billing"}})),
        )
        .expect(1)
        .mount(&server_b)
        .await;

    let (_secrets, inv) = routed_invoker(&[
        ("landlord", &server_a.uri(), None),
        ("billing", &server_b.uri(), None),
    ])
    .await;

    let packs: std::collections::HashSet<_> = inv
        .list_operations()
        .into_iter()
        .map(|op| op.pack)
        .collect();
    assert!(packs.contains("landlord"));
    assert!(packs.contains("billing"));

    let from_landlord = inv
        .invoke("landlord", "record_rent_payment", "{}")
        .await
        .expect("landlord invoke should reach server_a");
    assert_eq!(from_landlord, json!({"from": "landlord"}));

    let from_billing = inv
        .invoke("billing", "record_rent_payment", "{}")
        .await
        .expect("billing invoke should reach server_b");
    assert_eq!(from_billing, json!({"from": "billing"}));
}

#[tokio::test]
async fn invoke_rereads_the_route_on_every_call() {
    let server_a = MockServer::start().await;
    let server_b = MockServer::start().await;

    mount_caps_get(&server_a, caps_response_one_business_action()).await;
    Mock::given(method("POST"))
        .and(path("/admin/v1/capabilities/invoke"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true, "result": {}})))
        .expect(0)
        .mount(&server_a)
        .await;
    Mock::given(method("POST"))
        .and(path("/admin/v1/capabilities/invoke"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true, "result": {}})))
        .expect(1)
        .mount(&server_b)
        .await;

    let (secrets, inv) = routed_invoker(&[("landlord", &server_a.uri(), None)]).await;

    // The sorx child restarted on a new port: rewrite the route document in
    // the shared secrets fake without rebuilding the invoker.
    secrets.set(
        "secrets://default/acme/_/sorla/landlord",
        &route_doc(&server_b.uri(), None),
    );

    inv.invoke("landlord", "record_rent_payment", "{}")
        .await
        .expect("invoke should reach the rewritten route, not the discovery-time one");
}

#[tokio::test]
async fn a_401_is_sorla_unauthorized_without_the_body() {
    let server = MockServer::start().await;
    mount_caps_get(&server, caps_response_one_business_action()).await;
    mount_invoke(&server, 401, json!({"secret": "leak"})).await;

    let (_secrets, inv) = routed_invoker(&[("landlord", &server.uri(), None)]).await;
    let err = inv
        .invoke("landlord", "record_rent_payment", "{}")
        .await
        .expect_err("401 must be Err");
    assert!(err.contains("sorla_unauthorized"));
    assert!(!err.contains("leak"));
}

#[tokio::test]
async fn an_offer_for_another_pack_is_dropped_not_listed_under_the_bound_sor() {
    // `landlord`'s server also offers a `billing` op — a misbehaving or
    // shared-deployment SoR. The SoR key is the cap-URI pack segment (global
    // constraint), so only `landlord`'s own op may surface for this SoR.
    let server = MockServer::start().await;
    mount_caps_get(&server, caps_response_landlord_plus_billing()).await;

    let (_secrets, inv) = routed_invoker(&[("landlord", &server.uri(), None)]).await;
    let ops = inv.list_operations();
    assert_eq!(ops.len(), 1, "the billing op must be dropped, not listed");
    assert_eq!(ops[0].pack, "landlord");
    assert_eq!(ops[0].action, "record_rent_payment");
}