fraiseql-functions 2.3.0

Serverless functions runtime for FraiseQL — WASM and Deno backends
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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
//! Tests for `LiveHostContext` `GraphQL` query execution.

#![allow(clippy::unwrap_used, clippy::panic)] // Reason: test code, panics acceptable
#![allow(clippy::field_reassign_with_default)] // Reason: test setup is clearer with explicit field assignments
#![allow(clippy::match_same_arms)] // Reason: test match arms with distinct comments serve as documentation

use std::sync::Arc;

use super::*;

/// Mock query executor for testing.
struct MockQueryExecutor {
    /// If set, return this result; otherwise return an error.
    response: Option<serde_json::Value>,
}

impl MockQueryExecutor {
    fn new(response: serde_json::Value) -> Arc<Self> {
        Arc::new(Self {
            response: Some(response),
        })
    }

    fn error() -> Arc<Self> {
        Arc::new(Self { response: None })
    }
}

impl QueryExecutor for MockQueryExecutor {
    fn execute_query(
        &self,
        _query: &str,
        _variables: Option<&serde_json::Value>,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<serde_json::Value>> + Send + '_>>
    {
        Box::pin(async move {
            match &self.response {
                Some(value) => Ok(value.clone()),
                None => Err(fraiseql_error::FraiseQLError::Validation {
                    message: "mock query failed".to_string(),
                    path:    None,
                }),
            }
        })
    }
}

#[tokio::test]
async fn test_host_query_executes_graphql() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "User".to_string(),
        event_kind:   "created".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let response = serde_json::json!({
        "data": {
            "users": [
                {"id": "1", "name": "Alice"},
                {"id": "2", "name": "Bob"}
            ]
        }
    });
    let executor = MockQueryExecutor::new(response.clone());

    let ctx = LiveHostContext::with_executor(payload, HostContextConfig::default(), executor);

    let result = ctx.query("{ users { id name } }", serde_json::json!({})).await;

    assert!(result.is_ok());
    assert_eq!(result.unwrap(), response);
}

#[tokio::test]
async fn test_host_query_passes_variables() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "User".to_string(),
        event_kind:   "created".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let response = serde_json::json!({
        "data": {
            "user": {"id": "1", "name": "Alice"}
        }
    });
    let executor = MockQueryExecutor::new(response.clone());

    let ctx = LiveHostContext::with_executor(payload, HostContextConfig::default(), executor);

    let result = ctx
        .query("query($id: Int!) { user(id: $id) { name } }", serde_json::json!({"id": 1}))
        .await;

    assert!(result.is_ok());
    assert_eq!(result.unwrap(), response);
}

#[tokio::test]
async fn test_host_query_rejects_mutations() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "User".to_string(),
        event_kind:   "created".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let executor = MockQueryExecutor::error();
    let ctx = LiveHostContext::with_executor(payload, HostContextConfig::default(), executor);

    let result = ctx
        .query("mutation { createUser(name: \"Alice\") { id } }", serde_json::json!({}))
        .await;

    // The mock executor will reject it, but in the real implementation,
    // mutation detection should happen before executing.
    assert!(result.is_err());
}

#[tokio::test]
async fn test_host_query_invalid_graphql_returns_validation_error() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "User".to_string(),
        event_kind:   "created".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let executor = MockQueryExecutor::error();
    let ctx = LiveHostContext::with_executor(payload, HostContextConfig::default(), executor);

    let result = ctx.query("{ invalid syntax }", serde_json::json!({})).await;

    assert!(result.is_err());
}

#[tokio::test]
async fn test_host_query_without_executor_returns_unsupported() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "User".to_string(),
        event_kind:   "created".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let ctx = LiveHostContext::new(payload, HostContextConfig::default());

    let result = ctx.query("{ users { id } }", serde_json::json!({})).await;

    assert!(result.is_err());
    match result {
        Err(fraiseql_error::FraiseQLError::Unsupported { message }) => {
            assert!(message.contains("executor"));
        },
        _ => panic!("expected Unsupported error"),
    }
}

// SQL Query Tests

#[tokio::test]
async fn test_host_sql_query_returns_rows() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "User".to_string(),
        event_kind:   "created".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let ctx = LiveHostContext::new(payload, HostContextConfig::default());

    let result = ctx
        .sql_query("SELECT id, name FROM users WHERE active = $1", &[serde_json::json!(true)])
        .await;

    // Should succeed (SELECT is allowed)
    assert!(result.is_ok());
}

#[tokio::test]
async fn test_host_sql_query_rejects_insert() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "User".to_string(),
        event_kind:   "created".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let ctx = LiveHostContext::new(payload, HostContextConfig::default());

    let result = ctx
        .sql_query("INSERT INTO users (name) VALUES ($1)", &[serde_json::json!("Alice")])
        .await;

    assert!(result.is_err());
    match result {
        Err(fraiseql_error::FraiseQLError::Authorization { message, .. }) => {
            assert!(message.contains("not allowed"));
        },
        other => panic!("expected Authorization error, got {:?}", other),
    }
}

#[tokio::test]
async fn test_host_sql_query_rejects_update() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "User".to_string(),
        event_kind:   "created".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let ctx = LiveHostContext::new(payload, HostContextConfig::default());

    let result = ctx
        .sql_query(
            "UPDATE users SET name = $1 WHERE id = $2",
            &[serde_json::json!("Bob"), serde_json::json!(1)],
        )
        .await;

    assert!(result.is_err());
    match result {
        Err(fraiseql_error::FraiseQLError::Authorization { .. }) => (),
        other => panic!("expected Authorization error, got {:?}", other),
    }
}

#[tokio::test]
async fn test_host_sql_query_rejects_delete() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "User".to_string(),
        event_kind:   "created".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let ctx = LiveHostContext::new(payload, HostContextConfig::default());

    let result = ctx.sql_query("DELETE FROM users WHERE id = $1", &[serde_json::json!(1)]).await;

    assert!(result.is_err());
}

#[tokio::test]
async fn test_host_sql_query_rejects_ddl() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "User".to_string(),
        event_kind:   "created".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let ctx = LiveHostContext::new(payload, HostContextConfig::default());

    let result = ctx.sql_query("DROP TABLE users", &[]).await;

    assert!(result.is_err());
    match result {
        Err(fraiseql_error::FraiseQLError::Authorization { message, .. }) => {
            assert!(message.contains("not allowed"));
        },
        other => panic!("expected Authorization error, got {:?}", other),
    }
}

#[tokio::test]
async fn test_host_sql_query_rejects_copy() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "User".to_string(),
        event_kind:   "created".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let ctx = LiveHostContext::new(payload, HostContextConfig::default());

    let result = ctx.sql_query("COPY users FROM '/tmp/data.csv'", &[]).await;

    assert!(result.is_err());
}

#[tokio::test]
async fn test_host_sql_query_rejects_create_extension() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "User".to_string(),
        event_kind:   "created".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let ctx = LiveHostContext::new(payload, HostContextConfig::default());

    let result = ctx.sql_query("CREATE EXTENSION IF NOT EXISTS pgcrypto", &[]).await;

    assert!(result.is_err());
}

#[tokio::test]
async fn test_host_sql_query_rejects_set_role() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "User".to_string(),
        event_kind:   "created".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let ctx = LiveHostContext::new(payload, HostContextConfig::default());

    let result = ctx.sql_query("SET ROLE admin", &[]).await;

    assert!(result.is_err());
}

#[tokio::test]
async fn test_host_sql_query_rejects_call() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "User".to_string(),
        event_kind:   "created".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let ctx = LiveHostContext::new(payload, HostContextConfig::default());

    let result = ctx.sql_query("CALL delete_all_users()", &[]).await;

    assert!(result.is_err());
}

#[tokio::test]
async fn test_host_sql_query_rejects_truncate() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "User".to_string(),
        event_kind:   "created".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let ctx = LiveHostContext::new(payload, HostContextConfig::default());

    let result = ctx.sql_query("TRUNCATE users", &[]).await;

    assert!(result.is_err());
}

#[tokio::test]
async fn test_host_sql_query_allows_explain_without_analyze() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "User".to_string(),
        event_kind:   "created".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let ctx = LiveHostContext::new(payload, HostContextConfig::default());

    let result = ctx.sql_query("EXPLAIN SELECT * FROM users", &[]).await;

    assert!(result.is_ok());
}

#[tokio::test]
async fn test_host_sql_query_rejects_explain_analyze() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "User".to_string(),
        event_kind:   "created".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let ctx = LiveHostContext::new(payload, HostContextConfig::default());

    let result = ctx.sql_query("EXPLAIN ANALYZE SELECT * FROM users", &[]).await;

    assert!(result.is_err());
    match result {
        Err(fraiseql_error::FraiseQLError::Authorization { message, .. }) => {
            assert!(message.contains("not allowed"));
        },
        other => panic!("expected Authorization error, got {:?}", other),
    }
}

#[tokio::test]
async fn test_host_sql_query_invalid_returns_validation_error() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "User".to_string(),
        event_kind:   "created".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let ctx = LiveHostContext::new(payload, HostContextConfig::default());

    let result = ctx.sql_query("INVALID SYNTAX HERE", &[]).await;

    assert!(result.is_err());
    match result {
        Err(fraiseql_error::FraiseQLError::Validation { .. }) => (),
        other => panic!("expected Validation error, got {:?}", other),
    }
}

// HTTP Request Tests

#[tokio::test]
async fn test_host_http_valid_domain_passes_validation() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "API".to_string(),
        event_kind:   "called".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    // Configure to allow a specific domain
    let mut config = HostContextConfig::default();
    config.allowed_domains = vec!["api.example.com".to_string()];

    let client = Arc::new(reqwest::Client::builder().build().expect("failed to create client"));
    let ctx = LiveHostContext::with_http_client(payload, config, client);

    // This URL passes domain allowlist but will fail connection (expected)
    let result = ctx.http_request("GET", "https://api.example.com/api/test", &[], None).await;

    // Should not be blocked by domain allowlist; error is from connection attempt
    match result {
        Ok(_) => {}, // Success (unexpected but ok)
        Err(fraiseql_error::FraiseQLError::Authorization { message, .. }) => {
            panic!("should not block allowed domain: {}", message);
        },
        Err(_) => {}, // Connection error is expected (domain doesn't exist)
    }
}

#[tokio::test]
async fn test_host_http_subdomain_glob_pattern() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "API".to_string(),
        event_kind:   "called".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    // Configure with glob pattern
    let mut config = HostContextConfig::default();
    config.allowed_domains = vec!["*.example.com".to_string()];

    let client = Arc::new(reqwest::Client::builder().build().expect("failed to create client"));
    let ctx = LiveHostContext::with_http_client(payload, config, client);

    // Should pass domain check
    let result = ctx.http_request("GET", "https://api.example.com/test", &[], None).await;

    match result {
        Ok(_) => {},
        Err(fraiseql_error::FraiseQLError::Authorization { message, .. })
            if message.contains("domain") =>
        {
            panic!("should allow subdomain matching glob pattern: {}", message);
        },
        Err(_) => {}, // Connection error is expected
    }
}

#[tokio::test]
async fn test_host_http_blocks_disallowed_domain() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "API".to_string(),
        event_kind:   "called".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let mut config = HostContextConfig::default();
    config.allowed_domains = vec!["allowed.com".to_string()];
    let ctx = LiveHostContext::new(payload, config);

    let result = ctx.http_request("GET", "https://blocked.com/api", &[], None).await;

    assert!(result.is_err());
    match result {
        Err(fraiseql_error::FraiseQLError::Authorization { .. }) => (),
        other => panic!("expected Authorization error, got {:?}", other),
    }
}

#[tokio::test]
async fn test_host_http_blocks_private_ipv4() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "API".to_string(),
        event_kind:   "called".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let ctx = LiveHostContext::new(payload, HostContextConfig::default());

    let private_ips = vec![
        "http://127.0.0.1/api",
        "http://10.0.0.1/api",
        "http://192.168.1.1/api",
        "http://172.16.0.1/api",
    ];

    for ip_url in private_ips {
        let result = ctx.http_request("GET", ip_url, &[], None).await;
        assert!(result.is_err(), "should block {}", ip_url);
    }
}

#[tokio::test]
async fn test_host_http_blocks_ipv6_loopback() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "API".to_string(),
        event_kind:   "called".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let ctx = LiveHostContext::new(payload, HostContextConfig::default());

    let result = ctx.http_request("GET", "http://[::1]/api", &[], None).await;

    assert!(result.is_err());
}

#[tokio::test]
async fn test_host_http_blocks_ipv6_link_local() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "API".to_string(),
        event_kind:   "called".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let ctx = LiveHostContext::new(payload, HostContextConfig::default());

    let result = ctx.http_request("GET", "http://[fe80::1]/api", &[], None).await;

    assert!(result.is_err());
}

#[tokio::test]
async fn test_host_http_allows_public_ipv4() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "API".to_string(),
        event_kind:   "called".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let ctx = LiveHostContext::new(payload, HostContextConfig::default());

    // This will fail because the IP doesn't respond, but it should pass the SSRF check
    let result = ctx.http_request("GET", "http://8.8.8.8/api", &[], None).await;

    // The request itself may fail (DNS, connection), but not due to SSRF
    match result {
        Ok(_) => {}, // Request succeeded (unlikely in test environment)
        Err(fraiseql_error::FraiseQLError::Authorization { .. }) => {
            panic!("should not block public IP")
        },
        Err(_) => {}, // Other error is fine (connection, DNS, etc.)
    }
}

#[tokio::test]
async fn test_host_http_invalid_url() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "API".to_string(),
        event_kind:   "called".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let ctx = LiveHostContext::new(payload, HostContextConfig::default());

    let result = ctx.http_request("GET", "not a valid url", &[], None).await;

    assert!(result.is_err());
}

// Storage Tests

#[tokio::test]
async fn test_host_storage_get_returns_bytes() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "File".to_string(),
        event_kind:   "created".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let backend = super::storage::MockStorageBackend::new();
    let test_data = b"hello world".to_vec();
    backend.store("documents", "file.txt", test_data.clone());

    let mut ctx = LiveHostContext::new(payload, HostContextConfig::default());
    ctx.storage_backend = Some(backend as Arc<dyn super::storage::StorageBackend>);

    let result = ctx.storage_get("documents", "file.txt").await;

    assert!(result.is_ok());
    assert_eq!(result.unwrap(), test_data);
}

#[tokio::test]
async fn test_host_storage_put_creates_object() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "File".to_string(),
        event_kind:   "created".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let backend = super::storage::MockStorageBackend::new();
    let mut ctx = LiveHostContext::new(payload, HostContextConfig::default());
    ctx.storage_backend = Some(backend.clone() as Arc<dyn super::storage::StorageBackend>);

    let test_data = b"test file content".as_slice();
    let result = ctx.storage_put("documents", "newfile.txt", test_data, "text/plain").await;

    assert!(result.is_ok());
    // Verify the data was stored
    assert_eq!(backend.get_stored("documents", "newfile.txt"), Some(test_data.to_vec()));
}

#[tokio::test]
async fn test_host_storage_get_nonexistent_returns_not_found() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "File".to_string(),
        event_kind:   "created".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let backend = super::storage::MockStorageBackend::new();
    let mut ctx = LiveHostContext::new(payload, HostContextConfig::default());
    ctx.storage_backend = Some(backend as Arc<dyn super::storage::StorageBackend>);

    let result = ctx.storage_get("documents", "nonexistent.txt").await;

    assert!(result.is_err());
    match result {
        Err(fraiseql_error::FraiseQLError::File(fraiseql_error::FileError::NotFound { id })) => {
            assert!(id.contains("nonexistent.txt"), "expected key in NotFound id, got {id}");
        },
        other => panic!("expected FileError::NotFound, got {other:?}"),
    }
}

#[tokio::test]
async fn test_host_storage_put_respects_size_limit() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "File".to_string(),
        event_kind:   "created".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let backend = super::storage::MockStorageBackend::new();

    // Create config with very small size limit
    let mut config = HostContextConfig::default();
    config.max_storage_upload_bytes = 10; // 10 bytes limit

    let mut ctx = LiveHostContext::new(payload, config);
    ctx.storage_backend = Some(backend as Arc<dyn super::storage::StorageBackend>);

    // Try to upload larger than limit
    let oversized_data = vec![0u8; 100];
    let result = ctx.storage_put("documents", "large.txt", &oversized_data, "text/plain").await;

    assert!(result.is_err());
    match result {
        Err(fraiseql_error::FraiseQLError::Validation { message, .. }) => {
            assert!(message.contains("exceeds") || message.contains("size limit"));
        },
        other => panic!("expected Validation error, got {:?}", other),
    }
}

// Note: test_host_storage_without_backend_returns_unsupported is in host/mod.rs
// as a trait-level test since it doesn't require a real storage backend

// Auth & Environment Tests

#[tokio::test]
async fn test_host_auth_context_returns_claims() {
    use fraiseql_core::security::SecurityContext;

    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "User".to_string(),
        event_kind:   "created".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let mut ctx = LiveHostContext::new(payload, HostContextConfig::default());
    ctx.security_context = SecurityContext {
        user_id:          fraiseql_core::types::UserId("user123".to_string()),
        roles:            vec!["admin".to_string(), "user".to_string()],
        scopes:           vec!["read:users".to_string(), "write:users".to_string()],
        tenant_id:        Some(fraiseql_core::types::TenantId("tenant456".to_string())),
        expires_at:       chrono::Utc::now() + chrono::Duration::hours(1),
        authenticated_at: chrono::Utc::now(),
        request_id:       "req-123".to_string(),
        ip_address:       None,
        attributes:       std::collections::HashMap::new(),
        issuer:           None,
        audience:         None,
        email:            None,
        display_name:     None,
    };

    let result = ctx.auth_context();

    assert!(result.is_ok());
    let value = result.unwrap();
    assert_eq!(value["sub"], "user123");
    assert!(value["roles"].is_array());
    assert_eq!(value["roles"][0], "admin");
    assert!(value["scopes"].is_array());
    assert!(value["expires_at"].is_string());
}

#[tokio::test]
async fn test_host_auth_context_redacts_sensitive() {
    use fraiseql_core::security::SecurityContext;

    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "User".to_string(),
        event_kind:   "created".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let mut ctx = LiveHostContext::new(payload, HostContextConfig::default());
    ctx.security_context = SecurityContext {
        user_id:          fraiseql_core::types::UserId("user123".to_string()),
        roles:            vec!["admin".to_string()],
        scopes:           vec!["read:users".to_string()],
        tenant_id:        Some(fraiseql_core::types::TenantId("tenant456".to_string())),
        expires_at:       chrono::Utc::now() + chrono::Duration::hours(1),
        authenticated_at: chrono::Utc::now(),
        request_id:       "req-123".to_string(),
        ip_address:       Some("192.168.1.1".to_string()),
        attributes:       std::collections::HashMap::new(),
        issuer:           None,
        audience:         None,
        email:            None,
        display_name:     None,
    };

    let result = ctx.auth_context();

    assert!(result.is_ok());
    let value = result.unwrap();
    // Should NOT include ip_address or raw tokens
    assert!(value.get("ip_address").is_none());
    assert!(value.get("raw_token").is_none());
    assert!(value.get("token").is_none());
}

#[tokio::test]
async fn test_host_env_var_returns_allowed() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "Config".to_string(),
        event_kind:   "accessed".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let mut config = HostContextConfig::default();
    config.allowed_env_vars =
        vec!["APP_URL".to_string(), "APP_NAME".to_string()].into_iter().collect();

    let ctx = LiveHostContext::new(payload, config);

    // Set the environment variable for the test
    std::env::set_var("APP_URL", "https://example.com");

    let result = ctx.env_var("APP_URL");

    assert!(result.is_ok());
    assert_eq!(result.unwrap(), Some("https://example.com".to_string()));

    std::env::remove_var("APP_URL");
}

#[tokio::test]
async fn test_host_env_var_blocks_disallowed() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "Config".to_string(),
        event_kind:   "accessed".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let mut config = HostContextConfig::default();
    config.allowed_env_vars = vec!["ALLOWED_VAR".to_string()].into_iter().collect();

    let ctx = LiveHostContext::new(payload, config);

    // Set an env var that's not in allowlist
    std::env::set_var("DATABASE_URL", "postgres://secret:password@localhost/db");

    let result = ctx.env_var("DATABASE_URL");

    assert!(result.is_ok());
    // Should return None silently, not error
    assert_eq!(result.unwrap(), None);

    std::env::remove_var("DATABASE_URL");
}

#[tokio::test]
async fn test_host_env_var_nonexistent_returns_none() {
    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "Config".to_string(),
        event_kind:   "accessed".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    };

    let mut config = HostContextConfig::default();
    config.allowed_env_vars = vec!["NONEXISTENT_VAR".to_string()].into_iter().collect();

    let ctx = LiveHostContext::new(payload, config);

    // Make sure the variable doesn't exist
    std::env::remove_var("NONEXISTENT_VAR");

    let result = ctx.env_var("NONEXISTENT_VAR");

    assert!(result.is_ok());
    assert_eq!(result.unwrap(), None);
}

#[tokio::test]
async fn test_host_event_payload_returns_trigger_data() {
    let event_data = serde_json::json!({
        "id": "123",
        "name": "Test Event",
        "status": "active"
    });

    let payload = EventPayload {
        trigger_type: "user.created".to_string(),
        entity:       "User".to_string(),
        event_kind:   "created".to_string(),
        data:         event_data.clone(),
        timestamp:    chrono::Utc::now(),
    };

    let ctx = LiveHostContext::new(payload, HostContextConfig::default());

    let returned_payload = ctx.event_payload();

    assert_eq!(returned_payload.trigger_type, "user.created");
    assert_eq!(returned_payload.entity, "User");
    assert_eq!(returned_payload.event_kind, "created");
    assert_eq!(returned_payload.data, event_data);
}