tandem-server 0.6.5

HTTP server for Tandem engine APIs
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
use super::*;

#[tokio::test]
async fn mcp_run_as_interactive_call_uses_current_actor_connection() {
    let state = test_state().await;
    let (endpoint, server) = spawn_fake_notion_oauth_mcp_server().await;
    state
        .mcp
        .add_or_update("notion".to_string(), endpoint, HashMap::new(), true)
        .await;
    let alice =
        tandem_types::TenantContext::explicit_user_workspace("org-a", "workspace-a", None, "alice");
    state
        .mcp
        .set_bearer_token_for_tenant("notion", "alice-union-token", &alice)
        .await
        .expect("store alice token");
    state
        .mcp
        .refresh_for_tenant("notion", &alice)
        .await
        .expect("refresh alice tools");
    let alice_connection_id = state.mcp.connection_id_for_tenant("notion", &alice);

    let verified = verified_mcp_execute_context(
        &alice,
        tandem_types::PrincipalRef::human_user("alice").with_tenant_actor_id("alice"),
        "assertion-alice-mcp-run-as",
    );
    let result = crate::http::mcp::call_mcp_tool_for_tenant_with_verified_context(
        &state,
        "notion",
        "alice_search",
        json!({
            "query": "roadmap",
            "__phase_tool_authority": {
                "phase": "interactive",
                "allowed_tools": ["mcp.notion.alice_search"],
                "run_id": "run-as-interactive"
            }
        }),
        &alice,
        Some(&verified),
    )
    .await
    .expect("interactive MCP call should use current actor connection");

    let run_as = result
        .metadata
        .get("mcpRunAs")
        .expect("mcp run-as metadata");
    assert_eq!(
        run_as.get("connectionId").and_then(Value::as_str),
        Some(alice_connection_id.as_str())
    );
    assert_eq!(
        run_as.pointer("/principal/type").and_then(Value::as_str),
        Some("human_actor")
    );
    assert_eq!(
        run_as
            .pointer("/effectiveTenantContext/actor_id")
            .and_then(Value::as_str),
        Some("alice")
    );
    let audit = tokio::fs::read_to_string(&state.protected_audit_path)
        .await
        .expect("protected audit file");
    assert!(audit.contains("\"event_type\":\"mcp.tool.execution\""));
    assert!(audit.contains(&alice_connection_id));
    assert!(!audit.contains("alice-union-token"));
    let reliability_path =
        crate::stateful_runtime::stateful_reliability_path_from_runtime_events_path(
            &state.runtime_events_path,
        );
    let reliability = crate::stateful_runtime::load_stateful_reliability(&reliability_path);
    let receipt = reliability
        .tool_effects
        .iter()
        .find(|effect| {
            effect.provider.as_deref() == Some("notion")
                && effect.tool.as_deref() == Some("mcp.notion.alice_search")
        })
        .expect("mcp tool effect receipt");
    assert_eq!(
        receipt
            .metadata
            .as_ref()
            .and_then(|metadata| metadata.pointer("/run_as/connectionId"))
            .and_then(Value::as_str),
        Some(alice_connection_id.as_str())
    );
    assert_eq!(
        receipt
            .metadata
            .as_ref()
            .and_then(|metadata| metadata.pointer("/run_as/principal/type"))
            .and_then(Value::as_str),
        Some("human_actor")
    );
    drop(server);
}

#[tokio::test]
async fn mcp_run_as_enterprise_policy_override_blocks_context_assertion_allow() {
    let state = test_state().await;
    let (endpoint, server) = spawn_fake_notion_oauth_mcp_server().await;
    state
        .mcp
        .add_or_update("notion".to_string(), endpoint, HashMap::new(), true)
        .await;
    let alice =
        tandem_types::TenantContext::explicit_user_workspace("org-a", "workspace-a", None, "alice");
    state
        .mcp
        .set_bearer_token_for_tenant("notion", "alice-union-token", &alice)
        .await
        .expect("store alice token");
    state
        .mcp
        .refresh_for_tenant("notion", &alice)
        .await
        .expect("refresh alice tools");
    state.enterprise.policy_rules.write().await.insert(
        "enterprise-mcp-context-deny".to_string(),
        tandem_enterprise_contract::EnterprisePolicyRule::new(
            "enterprise-mcp-context-deny",
            "enterprise-mcp-floor",
            tandem_enterprise_contract::EnterprisePolicyScopeLevel::Enterprise,
            tandem_enterprise_contract::EnterprisePolicyEffect::Deny,
        )
        .with_tenant_context(alice.clone())
        .with_tool_patterns(vec!["mcp.notion.*".to_string()])
        .with_reason(
            "enterprise_mcp_context_floor",
            "enterprise policy denies MCP execution",
        ),
    );
    let verified = verified_mcp_execute_context(
        &alice,
        tandem_types::PrincipalRef::human_user("alice").with_tenant_actor_id("alice"),
        "assertion-alice-enterprise-deny",
    );

    let err = crate::http::mcp::call_mcp_tool_for_tenant_with_verified_context(
        &state,
        "notion",
        "alice_search",
        json!({ "query": "roadmap" }),
        &alice,
        Some(&verified),
    )
    .await
    .expect_err("enterprise policy must override context assertion allow");

    assert!(err.contains("ToolDenied { reason: ContextAssertion }"));
    assert!(err.contains("enterprise policy denies MCP execution"));
    let decisions = state.list_policy_decisions(&alice, 100).await;
    let decision = decisions
        .iter()
        .find(|decision| decision.reason_code == "enterprise_mcp_context_floor")
        .expect("enterprise override policy decision");
    assert_eq!(decision.decision, tandem_types::PolicyDecisionEffect::Deny);
    drop(server);
}

#[tokio::test]
async fn mcp_run_as_denies_explicit_tenant_without_context_assertion() {
    let state = test_state().await;
    let alice =
        tandem_types::TenantContext::explicit_user_workspace("org-a", "workspace-a", None, "alice");

    let err = crate::http::mcp::call_mcp_tool_for_tenant_with_audit(
        &state,
        "notion",
        "alice_search",
        json!({ "query": "roadmap" }),
        &alice,
    )
    .await
    .expect_err("explicit tenant MCP calls must require verified context");

    assert!(err.contains("ToolDenied { reason: ContextAssertion }"));
    assert!(err.contains("verified tenant context assertion is required"));
    let audit = tokio::fs::read_to_string(&state.protected_audit_path)
        .await
        .expect("protected audit file");
    assert!(audit.contains("\"event_type\":\"mcp.context_assertion_denied\""));
    assert!(audit.contains("missing_verified_tenant_context"));
    let decisions = state
        .list_policy_decisions_for_run(&alice, "missing-run", 100)
        .await;
    assert!(decisions.is_empty());
    assert!(state
        .list_policy_decisions(&alice, 100)
        .await
        .iter()
        .any(
            |decision| decision.policy_id.as_deref() == Some("mcp_context_assertion_preflight")
                && decision.reason_code == "missing_verified_tenant_context"
        ));
}

#[tokio::test]
async fn mcp_run_as_scheduled_automation_uses_tenant_service_principal_connection() {
    let state = test_state().await;
    let (endpoint, server) = spawn_fake_notion_oauth_mcp_server().await;
    state
        .mcp
        .add_or_update("notion".to_string(), endpoint, HashMap::new(), true)
        .await;
    let scheduled_tenant = tandem_types::TenantContext::explicit("org-a", "workspace-a", None);
    state
        .mcp
        .set_bearer_token_for_tenant("notion", "scheduled-service-token", &scheduled_tenant)
        .await
        .expect("store scheduled automation token");
    state
        .mcp
        .refresh_for_tenant("notion", &scheduled_tenant)
        .await
        .expect("refresh scheduled automation tools");
    let service_connection_id = state
        .mcp
        .connection_id_for_tenant("notion", &scheduled_tenant);

    let verified = verified_mcp_execute_context(
        &scheduled_tenant,
        tandem_types::PrincipalRef::new(
            tandem_types::PrincipalKind::ServiceAccount,
            "scheduled-automation",
        ),
        "assertion-scheduled-mcp-run-as",
    );
    let result = crate::http::mcp::call_mcp_tool_for_tenant_with_verified_context(
        &state,
        "notion",
        "alice_search",
        json!({
            "query": "roadmap",
            "__phase_tool_authority": {
                "phase": "scheduled",
                "allowed_tools": ["mcp.notion.alice_search"],
                "run_id": "run-as-scheduled"
            }
        }),
        &scheduled_tenant,
        Some(&verified),
    )
    .await
    .expect("scheduled automation MCP call should use service-principal connection");

    let run_as = result
        .metadata
        .get("mcpRunAs")
        .expect("mcp run-as metadata");
    assert_eq!(
        run_as.get("connectionId").and_then(Value::as_str),
        Some(service_connection_id.as_str())
    );
    assert_eq!(
        run_as.pointer("/principal/type").and_then(Value::as_str),
        Some("service_principal")
    );
    assert!(run_as.pointer("/effectiveTenantContext/actor_id").is_none());
    let audit = tokio::fs::read_to_string(&state.protected_audit_path)
        .await
        .expect("protected audit file");
    assert!(audit.contains("\"event_type\":\"mcp.tool.execution\""));
    assert!(audit.contains(&service_connection_id));
    assert!(!audit.contains("scheduled-service-token"));
    drop(server);
}

#[tokio::test]
async fn mcp_run_as_denies_cross_actor_connection_id() {
    let state = test_state().await;
    let (endpoint, server) = spawn_fake_notion_oauth_mcp_server().await;
    state
        .mcp
        .add_or_update("notion".to_string(), endpoint, HashMap::new(), true)
        .await;
    let alice =
        tandem_types::TenantContext::explicit_user_workspace("org-a", "workspace-a", None, "alice");
    let bob =
        tandem_types::TenantContext::explicit_user_workspace("org-a", "workspace-a", None, "bob");
    state
        .mcp
        .set_bearer_token_for_tenant("notion", "alice-union-token", &alice)
        .await
        .expect("store alice token");
    state
        .mcp
        .refresh_for_tenant("notion", &alice)
        .await
        .expect("refresh alice tools");
    state
        .mcp
        .set_bearer_token_for_tenant("notion", "bob-union-token", &bob)
        .await
        .expect("store bob token");
    state
        .mcp
        .refresh_for_tenant("notion", &bob)
        .await
        .expect("refresh bob tools");
    let bob_connection_id = state.mcp.connection_id_for_tenant("notion", &bob);

    let err = crate::http::mcp::call_mcp_tool_for_tenant_with_audit(
        &state,
        "notion",
        "alice_search",
        json!({
            "query": "roadmap",
            "__mcp_connection_id": bob_connection_id,
        }),
        &alice,
    )
    .await
    .expect_err("alice must not execute with bob's MCP connection");

    assert!(err.contains("ToolDenied { reason: McpRunAsPolicy }"));
    let audit = tokio::fs::read_to_string(&state.protected_audit_path)
        .await
        .expect("protected audit file");
    assert!(audit.contains("\"event_type\":\"mcp.run_as_denied\""));
    assert!(audit.contains("requested connection"));
    assert!(!audit.contains("bob-union-token"));
    drop(server);
}

#[tokio::test]
async fn mcp_run_as_denies_cross_tenant_connection_id() {
    let state = test_state().await;
    let (endpoint, server) = spawn_fake_notion_oauth_mcp_server().await;
    state
        .mcp
        .add_or_update("notion".to_string(), endpoint, HashMap::new(), true)
        .await;
    let tenant_a =
        tandem_types::TenantContext::explicit_user_workspace("org-a", "workspace-a", None, "alice");
    let tenant_b =
        tandem_types::TenantContext::explicit_user_workspace("org-b", "workspace-b", None, "alice");
    state
        .mcp
        .set_bearer_token_for_tenant("notion", "tenant-a-alice-token", &tenant_a)
        .await
        .expect("store tenant a token");
    state
        .mcp
        .refresh_for_tenant("notion", &tenant_a)
        .await
        .expect("refresh tenant a tools");
    state
        .mcp
        .set_bearer_token_for_tenant("notion", "tenant-b-alice-token", &tenant_b)
        .await
        .expect("store tenant b token");
    state
        .mcp
        .refresh_for_tenant("notion", &tenant_b)
        .await
        .expect("refresh tenant b tools");
    let tenant_b_connection_id = state.mcp.connection_id_for_tenant("notion", &tenant_b);

    let err = crate::http::mcp::call_mcp_tool_for_tenant_with_audit(
        &state,
        "notion",
        "alice_search",
        json!({
            "query": "roadmap",
            "__mcp_connection_id": tenant_b_connection_id.clone(),
        }),
        &tenant_a,
    )
    .await
    .expect_err("tenant a must not execute with tenant b's MCP connection");

    assert!(err.contains("ToolDenied { reason: McpRunAsPolicy }"));
    let audit = tokio::fs::read_to_string(&state.protected_audit_path)
        .await
        .expect("protected audit file");
    assert!(audit.contains("\"event_type\":\"mcp.run_as_denied\""));
    assert!(audit.contains(&tenant_b_connection_id));
    assert!(audit.contains("requested connection"));
    assert!(!audit.contains("tenant-b-alice-token"));
    drop(server);
}

#[tokio::test]
async fn mcp_connect_events_are_tenant_tagged_and_content_free() {
    let state = test_state().await;
    let mut rx = state.event_bus.subscribe();
    let (endpoint, server) = spawn_fake_notion_oauth_mcp_server().await;
    state
        .mcp
        .add_or_update("notion".to_string(), endpoint, HashMap::new(), true)
        .await;
    let alice =
        tandem_types::TenantContext::explicit_user_workspace("org-a", "workspace-a", None, "alice");
    state
        .mcp
        .set_bearer_token_for_tenant("notion", "alice-union-token", &alice)
        .await
        .expect("store alice token");
    let connection_id = state.mcp.connection_id_for_tenant("notion", &alice);

    let app = app_router(state.clone());
    let connect_resp = app
        .oneshot(tenant_request(
            "POST",
            "/mcp/notion/connect",
            "org-a",
            "workspace-a",
            "alice",
        ))
        .await
        .expect("connect response");
    assert_eq!(connect_resp.status(), StatusCode::OK);

    let connected = crate::test_support::next_event_of_type(&mut rx, "mcp.server.connected").await;
    let tools = crate::test_support::next_event_of_type(&mut rx, "mcp.tools.updated").await;
    for event in [&connected, &tools] {
        assert_eq!(
            event.properties.get("connectionId").and_then(Value::as_str),
            Some(connection_id.as_str())
        );
        assert_eq!(
            event
                .properties
                .pointer("/tenantContext/actor_id")
                .and_then(Value::as_str),
            Some("alice")
        );
        assert_eq!(
            event
                .properties
                .pointer("/principal/type")
                .and_then(Value::as_str),
            Some("human_actor")
        );
        let properties = serde_json::to_string(&event.properties).expect("event properties json");
        assert!(!properties.contains("alice-union-token"));
    }

    drop(server);
}

#[tokio::test]
async fn mcp_run_as_denies_unsupported_shared_connection_with_audit() {
    let state = test_state().await;
    let (endpoint, server) = spawn_fake_notion_oauth_mcp_server().await;
    state
        .mcp
        .add_or_update("notion".to_string(), endpoint, HashMap::new(), true)
        .await;
    let alice =
        tandem_types::TenantContext::explicit_user_workspace("org-a", "workspace-a", None, "alice");

    let err = crate::http::mcp::call_mcp_tool_for_tenant_with_audit(
        &state,
        "notion",
        "alice_search",
        json!({
            "query": "roadmap",
            "__mcp_principal": {
                "type": "shared_connection",
                "grant_id": "shared-grant-1",
            },
        }),
        &alice,
    )
    .await
    .expect_err("shared connection grants should fail closed until bridge support exists");

    assert!(err.contains("ToolDenied { reason: McpRunAsPolicy }"));
    assert!(err.contains("not executable by the current bridge"));
    let audit = tokio::fs::read_to_string(&state.protected_audit_path)
        .await
        .expect("protected audit file");
    assert!(audit.contains("\"event_type\":\"mcp.run_as_denied\""));
    assert!(audit.contains("not executable by the current bridge"));
    assert!(!audit.contains("shared-grant-token"));
    drop(server);
}

#[tokio::test]
async fn mcp_run_as_denies_actor_selected_service_principal_without_trusted_grant() {
    let state = test_state().await;
    let (endpoint, server) = spawn_fake_notion_oauth_mcp_server().await;
    state
        .mcp
        .add_or_update("notion".to_string(), endpoint, HashMap::new(), true)
        .await;
    let alice =
        tandem_types::TenantContext::explicit_user_workspace("org-a", "workspace-a", None, "alice");
    let service = tandem_types::TenantContext::explicit("org-a", "workspace-a", None);
    state
        .mcp
        .set_bearer_token_for_tenant("notion", "service-principal-token", &service)
        .await
        .expect("store service token");
    state
        .mcp
        .refresh_for_tenant("notion", &service)
        .await
        .expect("refresh service tools");
    let service_connection_id = state.mcp.connection_id_for_tenant("notion", &service);
    let service_principal = state
        .mcp
        .list_connections()
        .await
        .get(&service_connection_id)
        .map(|connection| connection.owner.clone())
        .expect("service connection owner");

    let err = crate::http::mcp::call_mcp_tool_for_tenant_with_audit(
        &state,
        "notion",
        "alice_search",
        json!({
            "query": "roadmap",
            "__mcp_run_as": {
                "connection_id": service_connection_id,
                "principal": service_principal,
            },
        }),
        &alice,
    )
    .await
    .expect_err("actor-scoped calls must not self-select tenant service principal");

    assert!(err.contains("ToolDenied { reason: McpRunAsPolicy }"));
    assert!(err.contains("requires a server-side connection grant"));
    let audit = tokio::fs::read_to_string(&state.protected_audit_path)
        .await
        .expect("protected audit file");
    assert!(audit.contains("\"event_type\":\"mcp.run_as_denied\""));
    assert!(audit.contains(&service_connection_id));
    assert!(!audit.contains("service-principal-token"));
    drop(server);
}