fraiseql-functions 2.13.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
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
//! 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::new(payload, HostContextConfig::default()).with_executor(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::new(payload, HostContextConfig::default()).with_executor(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::new(payload, HostContextConfig::default()).with_executor(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::new(payload, HostContextConfig::default()).with_executor(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_readonly_is_unimplemented() {
    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;

    // The SELECT passes read-only classification, but execution is not wired
    // (M-sql-query-stub): it fails loud with `Unsupported` rather than silently
    // returning zero rows.
    assert!(result.is_err());
    match result {
        Err(fraiseql_error::FraiseQLError::Unsupported { message }) => {
            assert!(message.contains("not implemented"), "got {message}");
        },
        other => panic!("expected Unsupported error, got {:?}", other),
    }
}

#[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;

    // EXPLAIN (without ANALYZE) classifies as read-only, so it is NOT rejected with
    // an Authorization error. Execution is unimplemented (M-sql-query-stub), so it
    // fails loud with `Unsupported` rather than being treated as a write.
    match result {
        Err(fraiseql_error::FraiseQLError::Unsupported { .. }) => (),
        other => {
            panic!("expected Unsupported error (read-only but unimplemented), got {:?}", other)
        },
    }
}

#[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(),
    };

    // Deny-by-default: explicitly allow the public IP so this test exercises the
    // IP/SSRF gate (a public address must pass) rather than the allowlist gate.
    let config = HostContextConfig {
        allowed_domains: vec!["8.8.8.8".to_string()],
        ..HostContextConfig::default()
    };
    let ctx = LiveHostContext::new(payload, config);

    // 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());
}

/// The connected user's verified sending identity surfaces in the auth context —
/// the per-user `from` any paired outbound email must use
/// (`crate::outbound::resolve_sender_identity`).
#[tokio::test]
async fn test_host_auth_context_exposes_verified_sending_identity() {
    use fraiseql_core::security::SecurityContext;

    let payload = EventPayload {
        trigger_type: "test".to_string(),
        entity:       "Deal".to_string(),
        event_kind:   "updated".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![],
        scopes:           vec![],
        tenant_id:        None,
        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:            Some("rep@outreach.example".to_string()),
        display_name:     Some("Sales Rep".to_string()),
    };

    let value = ctx.auth_context().expect("auth context");
    assert_eq!(value["email"], "rep@outreach.example");
    assert_eq!(value["display_name"], "Sales Rep");

    let identity =
        crate::outbound::resolve_sender_identity(&value).expect("per-user sender resolves");
    assert_eq!(identity.address, "rep@outreach.example");
    assert_eq!(identity.display_name, Some("Sales Rep".to_string()));
}

#[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);
}

// ── send_email host op (host-owned `from`) ──────────────────────────────────────

use crate::outbound::{
    BoxFuture, EmailTransport, LoginEmailSender, SendContext, SendEmailRequest, SendEmailResponse,
    SendPolicyError, SenderIdentity, SenderIdentityResolver,
};

/// What a [`RecordingTransport`] captured on its last send: the resolved sender,
/// the request, and the per-dispatch send-id / tenant the host threaded in.
#[derive(Clone)]
struct RecordedSend {
    sender:  SenderIdentity,
    request: SendEmailRequest,
    send_id: Option<String>,
    tenant:  Option<String>,
}

/// A transport that records the send it was last asked to make and returns success
/// — so a test can assert on the host-owned `from` the op bound and the
/// per-dispatch context (send-id / tenant) the host threaded through.
#[derive(Default)]
struct RecordingTransport {
    last: std::sync::Mutex<Option<RecordedSend>>,
}

impl EmailTransport for RecordingTransport {
    fn send<'a>(
        &'a self,
        sender: &'a SenderIdentity,
        request: &'a SendEmailRequest,
        context: SendContext<'a>,
    ) -> BoxFuture<'a, Result<SendEmailResponse>> {
        *self.last.lock().unwrap() = Some(RecordedSend {
            sender:  sender.clone(),
            request: request.clone(),
            send_id: context.send_id.map(ToString::to_string),
            tenant:  context.tenant.map(ToString::to_string),
        });
        Box::pin(async {
            Ok(SendEmailResponse {
                message_id: Some("recorded".to_string()),
                accepted:   true,
            })
        })
    }
}

/// A resolver that fails **transiently** (a retry may succeed) — models the
/// identity store being momentarily unavailable.
struct TransientResolver;

impl SenderIdentityResolver for TransientResolver {
    fn resolve_sender<'a>(
        &'a self,
        _auth_context: &'a serde_json::Value,
    ) -> BoxFuture<'a, std::result::Result<SenderIdentity, SendPolicyError>> {
        Box::pin(async { Err(SendPolicyError::transient("identity store unavailable")) })
    }
}

fn send_email_payload() -> EventPayload {
    EventPayload {
        trigger_type: "after:mutation:Deal:update".to_string(),
        entity:       "Deal".to_string(),
        event_kind:   "updated".to_string(),
        data:         serde_json::json!({}),
        timestamp:    chrono::Utc::now(),
    }
}

#[tokio::test]
async fn test_send_email_from_is_host_owned_not_guest_supplied() {
    let mut host = LiveHostContext::new(send_email_payload(), HostContextConfig::default());
    host.security_context.email = Some("alice@example.com".to_string());
    let transport = Arc::new(RecordingTransport::default());
    let host = host.with_email(Arc::new(LoginEmailSender), transport.clone());

    // A guest request that *tries* to set `from`. `SendEmailRequest` has no `from`
    // field, so the attempted value is dropped on deserialization; the op binds
    // `from` from the auth context regardless.
    let request: SendEmailRequest = serde_json::from_str(
        r#"{"from":"attacker@evil.example","to":"bob@example.com","subject":"hi","text":"b"}"#,
    )
    .unwrap();

    let response = host.send_email(&request).await.unwrap();
    assert!(response.accepted);

    let recorded = transport.last.lock().unwrap().clone().unwrap();
    // The transport was handed the connected user's verified address, never the
    // guest's attempted `from`.
    assert_eq!(recorded.sender.address, "alice@example.com");
    assert_eq!(recorded.request.to, "bob@example.com");
}

#[tokio::test]
async fn test_send_email_threads_the_idempotency_token_as_send_id() {
    // The per-dispatch idempotency token reaches the transport as the VERP send-id /
    // exactly-once key, and the tenant is threaded through for RLS scoping. Both are
    // host-owned context, never guest input.
    let host = LiveHostContext::new(send_email_payload(), HostContextConfig::default())
        .with_idempotency_token("abc123def456");
    let mut host = host;
    host.security_context.email = Some("alice@example.com".to_string());
    host.security_context.tenant_id = Some(fraiseql_core::types::TenantId::new("tenant-7"));
    let transport = Arc::new(RecordingTransport::default());
    let host = host.with_email(Arc::new(LoginEmailSender), transport.clone());

    let request = SendEmailRequest {
        to:       "bob@example.com".to_string(),
        subject:  "hi".to_string(),
        text:     Some("b".to_string()),
        html:     None,
        reply_to: None,
    };
    host.send_email(&request).await.unwrap();

    let recorded = transport.last.lock().unwrap().clone().unwrap();
    assert_eq!(recorded.send_id.as_deref(), Some("abc123def456"), "send-id = host token");
    assert_eq!(recorded.tenant.as_deref(), Some("tenant-7"), "tenant threaded for RLS");
}

#[tokio::test]
async fn test_send_email_without_idempotency_token_sends_uncorrelated() {
    // Zero-config (no HMAC secret → no token): the send still happens, just without
    // a VERP send-id or tenant scope.
    let mut host = LiveHostContext::new(send_email_payload(), HostContextConfig::default());
    host.security_context.email = Some("alice@example.com".to_string());
    let transport = Arc::new(RecordingTransport::default());
    let host = host.with_email(Arc::new(LoginEmailSender), transport.clone());

    let request = SendEmailRequest {
        to:       "bob@example.com".to_string(),
        subject:  "hi".to_string(),
        text:     Some("b".to_string()),
        html:     None,
        reply_to: None,
    };
    host.send_email(&request).await.unwrap();

    let recorded = transport.last.lock().unwrap().clone().unwrap();
    assert_eq!(recorded.send_id, None, "no token → no send-id");
    assert_eq!(recorded.tenant, None, "no tenant → no scope");
}

#[tokio::test]
async fn test_send_email_fails_closed_without_verified_identity() {
    let mut host = LiveHostContext::new(send_email_payload(), HostContextConfig::default());
    host.security_context.email = None; // no verified sending address
    let transport = Arc::new(RecordingTransport::default());
    let host = host.with_email(Arc::new(LoginEmailSender), transport.clone());

    let request = SendEmailRequest {
        to:       "bob@example.com".to_string(),
        subject:  "hi".to_string(),
        text:     Some("b".to_string()),
        html:     None,
        reply_to: None,
    };

    let error = host.send_email(&request).await.unwrap_err();
    // Permanent policy denial → 403 (durable dispatch dead-letters, does not retry).
    assert_eq!(error.status_code(), 403);
    // Never attempted a send.
    assert!(transport.last.lock().unwrap().is_none());
}

#[tokio::test]
async fn test_send_email_transient_identity_failure_is_retryable() {
    let mut host = LiveHostContext::new(send_email_payload(), HostContextConfig::default());
    host.security_context.email = Some("alice@example.com".to_string());
    let transport = Arc::new(RecordingTransport::default());
    let host = host.with_email(Arc::new(TransientResolver), transport.clone());

    let request = SendEmailRequest {
        to:       "bob@example.com".to_string(),
        subject:  "hi".to_string(),
        text:     Some("b".to_string()),
        html:     None,
        reply_to: None,
    };

    let error = host.send_email(&request).await.unwrap_err();
    // Transient failure → 503 (durable dispatch retries rather than dead-letters).
    assert_eq!(error.status_code(), 503);
    assert!(transport.last.lock().unwrap().is_none());
}

#[tokio::test]
async fn test_send_email_unconfigured_fails_loud() {
    let mut host = LiveHostContext::new(send_email_payload(), HostContextConfig::default());
    host.security_context.email = Some("alice@example.com".to_string());
    // No `.with_email(...)` → resolver + transport absent.

    let request = SendEmailRequest {
        to:       "bob@example.com".to_string(),
        subject:  "hi".to_string(),
        text:     Some("b".to_string()),
        html:     None,
        reply_to: None,
    };

    let error = host.send_email(&request).await.unwrap_err();
    // Fail loud (Unsupported / 501), never a silent phantom success — mirror
    // `sql_query`.
    assert_eq!(error.status_code(), 501);
}