assay-lua 0.15.4

General-purpose enhanced Lua runtime. Batteries-included scripting, automation, and web services.
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
mod common;

use common::{create_vm, eval_lua, run_lua};

#[tokio::test]
async fn test_jwt_sign_rs256() {
    let pem = std::fs::read_to_string("tests/fixtures/test_rsa.pem").unwrap();
    let pub_pem = std::fs::read_to_string("tests/fixtures/test_rsa_pub.pem").unwrap();

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs();
    let exp = now + 3600;

    let vm = create_vm();
    vm.globals()
        .set("test_pem", vm.create_string(&pem).unwrap())
        .unwrap();
    vm.globals().set("test_iat", now as i64).unwrap();
    vm.globals().set("test_exp", exp as i64).unwrap();

    let token: String = vm
        .load(
            r#"
            return crypto.jwt_sign({
                iss = "test-issuer",
                sub = "test-subject",
                aud = "test-audience",
                iat = test_iat,
                exp = test_exp,
            }, test_pem)
            "#,
        )
        .eval_async()
        .await
        .unwrap();

    assert!(token.contains('.'));
    let parts: Vec<&str> = token.split('.').collect();
    assert_eq!(parts.len(), 3);

    let decoding_key = jsonwebtoken::DecodingKey::from_rsa_pem(pub_pem.as_bytes()).unwrap();
    let mut validation = jsonwebtoken::Validation::new(jsonwebtoken::Algorithm::RS256);
    validation.set_audience(&["test-audience"]);
    validation.set_required_spec_claims(&["iss", "sub", "aud", "iat", "exp"]);
    let decoded: jsonwebtoken::TokenData<serde_json::Value> =
        jsonwebtoken::decode(&token, &decoding_key, &validation).unwrap();
    assert_eq!(decoded.claims["iss"], "test-issuer");
    assert_eq!(decoded.claims["sub"], "test-subject");
}

#[tokio::test]
async fn test_jwt_sign_rs256_with_kid() {
    let pem = std::fs::read_to_string("tests/fixtures/test_rsa.pem").unwrap();
    let pub_pem = std::fs::read_to_string("tests/fixtures/test_rsa_pub.pem").unwrap();

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs();
    let exp = now + 3600;

    let vm = create_vm();
    vm.globals()
        .set("test_pem", vm.create_string(&pem).unwrap())
        .unwrap();
    vm.globals().set("test_iat", now as i64).unwrap();
    vm.globals().set("test_exp", exp as i64).unwrap();

    let token: String = vm
        .load(
            r#"
            return crypto.jwt_sign({
                iss = "test-issuer",
                sub = "test-subject",
                aud = "test-audience",
                iat = test_iat,
                exp = test_exp,
            }, test_pem, "RS256", { kid = "my-key-id-123" })
            "#,
        )
        .eval_async()
        .await
        .unwrap();

    assert!(token.contains('.'));
    let parts: Vec<&str> = token.split('.').collect();
    assert_eq!(parts.len(), 3);

    let decoding_key = jsonwebtoken::DecodingKey::from_rsa_pem(pub_pem.as_bytes()).unwrap();
    let mut validation = jsonwebtoken::Validation::new(jsonwebtoken::Algorithm::RS256);
    validation.set_audience(&["test-audience"]);
    validation.set_required_spec_claims(&["iss", "sub", "aud", "iat", "exp"]);
    let decoded: jsonwebtoken::TokenData<serde_json::Value> =
        jsonwebtoken::decode(&token, &decoding_key, &validation).unwrap();
    assert_eq!(decoded.claims["iss"], "test-issuer");
    assert_eq!(decoded.header.kid, Some("my-key-id-123".to_string()));
}

#[tokio::test]
async fn test_jwt_sign_invalid_key() {
    let result = run_lua(
        r#"
        crypto.jwt_sign({ iss = "test" }, "not-a-valid-pem-key")
        "#,
    )
    .await;
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(err.contains("invalid PEM key"), "got: {err}");
}

#[tokio::test]
async fn test_jwt_decode_basic_claims() {
    // JWT with header {"alg":"RS256","typ":"JWT"} and claims
    // {"sub":"user:alice","email":"alice@example.com","role":"admin","groups":["a","b"]}
    // Signature is fake (jwt_decode doesn't verify).
    run_lua(
        r#"
        local token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyOmFsaWNlIiwiZW1haWwiOiJhbGljZUBleGFtcGxlLmNvbSIsInJvbGUiOiJhZG1pbiIsImdyb3VwcyI6WyJhIiwiYiJdfQ.fake-signature"
        local out = crypto.jwt_decode(token)
        assert.eq(out.header.alg, "RS256")
        assert.eq(out.header.typ, "JWT")
        assert.eq(out.claims.sub, "user:alice")
        assert.eq(out.claims.email, "alice@example.com")
        assert.eq(out.claims.role, "admin")
        assert.eq(#out.claims.groups, 2)
        assert.eq(out.claims.groups[1], "a")
        assert.eq(out.claims.groups[2], "b")
        "#,
    )
    .await
    .unwrap();
}

#[tokio::test]
async fn test_jwt_decode_roundtrip_with_jwt_sign() {
    // Sign a JWT with crypto.jwt_sign, then decode it with jwt_decode
    // and verify all the claims round-trip correctly.
    let pem = std::fs::read_to_string("tests/fixtures/test_rsa.pem").unwrap();

    let vm = create_vm();
    vm.globals()
        .set("test_pem", vm.create_string(&pem).unwrap())
        .unwrap();

    vm.load(
        r#"
        local token = crypto.jwt_sign({
          sub = "user:alice",
          email = "alice@example.com",
          role = "admin",
          groups = {"a", "b", "c"},
        }, test_pem, "RS256", { kid = "test-key-1" })

        local decoded = crypto.jwt_decode(token)
        assert.eq(decoded.header.alg, "RS256")
        assert.eq(decoded.header.typ, "JWT")
        assert.eq(decoded.header.kid, "test-key-1")
        assert.eq(decoded.claims.sub, "user:alice")
        assert.eq(decoded.claims.email, "alice@example.com")
        assert.eq(decoded.claims.role, "admin")
        assert.eq(#decoded.claims.groups, 3)
        assert.eq(decoded.claims.groups[1], "a")
        assert.eq(decoded.claims.groups[3], "c")
        "#,
    )
    .exec_async()
    .await
    .unwrap();
}

#[tokio::test]
async fn test_jwt_verify_rs256_roundtrip() {
    // Sign with the private key, verify with the matching public key.
    let priv_pem = std::fs::read_to_string("tests/fixtures/test_rsa.pem").unwrap();
    let pub_pem = std::fs::read_to_string("tests/fixtures/test_rsa_pub.pem").unwrap();

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs();
    let exp = now + 3600;

    let vm = create_vm();
    vm.globals().set("priv_pem", vm.create_string(&priv_pem).unwrap()).unwrap();
    vm.globals().set("pub_pem", vm.create_string(&pub_pem).unwrap()).unwrap();
    vm.globals().set("test_iat", now as i64).unwrap();
    vm.globals().set("test_exp", exp as i64).unwrap();

    vm.load(
        r#"
        local token = crypto.jwt_sign({
            iss = "test-issuer",
            sub = "test-subject",
            aud = "test-audience",
            iat = test_iat,
            exp = test_exp,
        }, priv_pem)
        local out = crypto.jwt_verify(token, pub_pem, {
            audience = "test-audience",
            issuer = "test-issuer",
        })
        assert.eq(out.header.alg, "RS256")
        assert.eq(out.claims.iss, "test-issuer")
        assert.eq(out.claims.sub, "test-subject")
        assert.eq(out.claims.aud, "test-audience")
        "#,
    )
    .exec_async()
    .await
    .unwrap();
}

#[tokio::test]
async fn test_jwt_verify_rejects_wrong_audience() {
    let priv_pem = std::fs::read_to_string("tests/fixtures/test_rsa.pem").unwrap();
    let pub_pem = std::fs::read_to_string("tests/fixtures/test_rsa_pub.pem").unwrap();

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs() as i64;

    let vm = create_vm();
    vm.globals().set("priv_pem", vm.create_string(&priv_pem).unwrap()).unwrap();
    vm.globals().set("pub_pem", vm.create_string(&pub_pem).unwrap()).unwrap();
    vm.globals().set("test_iat", now).unwrap();
    vm.globals().set("test_exp", now + 3600).unwrap();

    let result = vm
        .load(
            r#"
            local token = crypto.jwt_sign({
                iss = "test-issuer",
                aud = "intended-audience",
                iat = test_iat,
                exp = test_exp,
            }, priv_pem)
            return crypto.jwt_verify(token, pub_pem, { audience = "different-audience" })
            "#,
        )
        .exec_async()
        .await;
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("audience") || err.contains("Audience") || err.contains("aud"),
        "got: {err}"
    );
}

#[tokio::test]
async fn test_jwt_verify_rejects_wrong_issuer() {
    let priv_pem = std::fs::read_to_string("tests/fixtures/test_rsa.pem").unwrap();
    let pub_pem = std::fs::read_to_string("tests/fixtures/test_rsa_pub.pem").unwrap();

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs() as i64;

    let vm = create_vm();
    vm.globals().set("priv_pem", vm.create_string(&priv_pem).unwrap()).unwrap();
    vm.globals().set("pub_pem", vm.create_string(&pub_pem).unwrap()).unwrap();
    vm.globals().set("test_iat", now).unwrap();
    vm.globals().set("test_exp", now + 3600).unwrap();

    let result = vm
        .load(
            r#"
            local token = crypto.jwt_sign({
                iss = "real-issuer",
                aud = "test-audience",
                iat = test_iat,
                exp = test_exp,
            }, priv_pem)
            return crypto.jwt_verify(token, pub_pem, {
                audience = "test-audience",
                issuer = "expected-issuer",
            })
            "#,
        )
        .exec_async()
        .await;
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("issuer") || err.contains("Issuer") || err.contains("iss"),
        "got: {err}"
    );
}

#[tokio::test]
async fn test_jwt_verify_rejects_expired_token() {
    let priv_pem = std::fs::read_to_string("tests/fixtures/test_rsa.pem").unwrap();
    let pub_pem = std::fs::read_to_string("tests/fixtures/test_rsa_pub.pem").unwrap();

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs() as i64;

    let vm = create_vm();
    vm.globals().set("priv_pem", vm.create_string(&priv_pem).unwrap()).unwrap();
    vm.globals().set("pub_pem", vm.create_string(&pub_pem).unwrap()).unwrap();
    vm.globals().set("test_iat", now - 7200).unwrap();
    vm.globals().set("test_exp", now - 3600).unwrap();

    let result = vm
        .load(
            r#"
            local token = crypto.jwt_sign({
                iss = "test-issuer",
                aud = "test-audience",
                iat = test_iat,
                exp = test_exp,
            }, priv_pem)
            return crypto.jwt_verify(token, pub_pem, { audience = "test-audience" })
            "#,
        )
        .exec_async()
        .await;
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("expired") || err.contains("ExpiredSignature") || err.contains("exp"),
        "got: {err}"
    );
}

#[tokio::test]
async fn test_jwt_verify_rejects_tampered_signature() {
    let priv_pem = std::fs::read_to_string("tests/fixtures/test_rsa.pem").unwrap();
    let pub_pem = std::fs::read_to_string("tests/fixtures/test_rsa_pub.pem").unwrap();

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs() as i64;

    let vm = create_vm();
    vm.globals().set("priv_pem", vm.create_string(&priv_pem).unwrap()).unwrap();
    vm.globals().set("pub_pem", vm.create_string(&pub_pem).unwrap()).unwrap();
    vm.globals().set("test_iat", now).unwrap();
    vm.globals().set("test_exp", now + 3600).unwrap();

    let result = vm
        .load(
            r#"
            -- Two different payloads → different signatures over the same key.
            -- Splice token_a's header.payload onto token_b's signature; result
            -- is well-formed base64url everywhere but signature ≠ message.
            local token_a = crypto.jwt_sign({
                iss = "test-issuer",
                aud = "test-audience",
                iat = test_iat,
                exp = test_exp,
                marker = "alpha",
            }, priv_pem)
            local token_b = crypto.jwt_sign({
                iss = "test-issuer",
                aud = "test-audience",
                iat = test_iat,
                exp = test_exp,
                marker = "beta",
            }, priv_pem)
            local sig_b = token_b:match("[^.]+$")
            local prefix_a = token_a:match("^(.+)%.[^.]+$")
            local tampered = prefix_a .. "." .. sig_b
            return crypto.jwt_verify(tampered, pub_pem, { audience = "test-audience" })
            "#,
        )
        .exec_async()
        .await;
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("InvalidSignature") || err.contains("signature") || err.contains("Signature"),
        "got: {err}"
    );
}

#[tokio::test]
async fn test_jwt_verify_jwks_dispatch_by_kid() {
    let priv_pem = std::fs::read_to_string("tests/fixtures/test_rsa.pem").unwrap();
    let jwks_json = std::fs::read_to_string("tests/fixtures/test_rsa_pub.jwks.json").unwrap();

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs() as i64;

    let vm = create_vm();
    vm.globals().set("priv_pem", vm.create_string(&priv_pem).unwrap()).unwrap();
    vm.globals().set("jwks_json", vm.create_string(&jwks_json).unwrap()).unwrap();
    vm.globals().set("test_iat", now).unwrap();
    vm.globals().set("test_exp", now + 3600).unwrap();

    vm.load(
        r#"
        local jwks = json.parse(jwks_json)
        local token = crypto.jwt_sign({
            iss = "test-issuer",
            aud = "test-audience",
            iat = test_iat,
            exp = test_exp,
        }, priv_pem, "RS256", { kid = "test-key-1" })
        local out = crypto.jwt_verify(token, jwks, { audience = "test-audience" })
        assert.eq(out.header.kid, "test-key-1")
        assert.eq(out.claims.iss, "test-issuer")
        "#,
    )
    .exec_async()
    .await
    .unwrap();
}

#[tokio::test]
async fn test_jwt_verify_jwks_rejects_unknown_kid() {
    let priv_pem = std::fs::read_to_string("tests/fixtures/test_rsa.pem").unwrap();
    let jwks_json = std::fs::read_to_string("tests/fixtures/test_rsa_pub.jwks.json").unwrap();

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs() as i64;

    let vm = create_vm();
    vm.globals().set("priv_pem", vm.create_string(&priv_pem).unwrap()).unwrap();
    vm.globals().set("jwks_json", vm.create_string(&jwks_json).unwrap()).unwrap();
    vm.globals().set("test_iat", now).unwrap();
    vm.globals().set("test_exp", now + 3600).unwrap();

    let result = vm
        .load(
            r#"
            local jwks = json.parse(jwks_json)
            local token = crypto.jwt_sign({
                iss = "test-issuer",
                aud = "test-audience",
                iat = test_iat,
                exp = test_exp,
            }, priv_pem, "RS256", { kid = "missing-key" })
            return crypto.jwt_verify(token, jwks, { audience = "test-audience" })
            "#,
        )
        .exec_async()
        .await;
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("no key in JWKS matches kid") || err.contains("missing-key"),
        "got: {err}"
    );
}

#[tokio::test]
async fn test_jwt_verify_jwks_requires_kid_in_token() {
    let priv_pem = std::fs::read_to_string("tests/fixtures/test_rsa.pem").unwrap();
    let jwks_json = std::fs::read_to_string("tests/fixtures/test_rsa_pub.jwks.json").unwrap();

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs() as i64;

    let vm = create_vm();
    vm.globals().set("priv_pem", vm.create_string(&priv_pem).unwrap()).unwrap();
    vm.globals().set("jwks_json", vm.create_string(&jwks_json).unwrap()).unwrap();
    vm.globals().set("test_iat", now).unwrap();
    vm.globals().set("test_exp", now + 3600).unwrap();

    let result = vm
        .load(
            r#"
            local jwks = json.parse(jwks_json)
            -- Sign without a kid header.
            local token = crypto.jwt_sign({
                iss = "test-issuer",
                aud = "test-audience",
                iat = test_iat,
                exp = test_exp,
            }, priv_pem)
            return crypto.jwt_verify(token, jwks, { audience = "test-audience" })
            "#,
        )
        .exec_async()
        .await;
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(err.contains("missing 'kid'"), "got: {err}");
}

#[tokio::test]
async fn test_jwt_verify_audience_array() {
    // `audience` accepts both a string and an array of strings; either acts
    // as an allowlist (token's aud must match at least one entry).
    let priv_pem = std::fs::read_to_string("tests/fixtures/test_rsa.pem").unwrap();
    let pub_pem = std::fs::read_to_string("tests/fixtures/test_rsa_pub.pem").unwrap();

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs() as i64;

    let vm = create_vm();
    vm.globals().set("priv_pem", vm.create_string(&priv_pem).unwrap()).unwrap();
    vm.globals().set("pub_pem", vm.create_string(&pub_pem).unwrap()).unwrap();
    vm.globals().set("test_iat", now).unwrap();
    vm.globals().set("test_exp", now + 3600).unwrap();

    vm.load(
        r#"
        local token = crypto.jwt_sign({
            iss = "test-issuer",
            aud = "second-audience",
            iat = test_iat,
            exp = test_exp,
        }, priv_pem)
        local out = crypto.jwt_verify(token, pub_pem, {
            audience = { "first-audience", "second-audience", "third-audience" },
        })
        assert.eq(out.claims.aud, "second-audience")
        "#,
    )
    .exec_async()
    .await
    .unwrap();
}

#[tokio::test]
async fn test_jwt_verify_skip_exp_validation() {
    let priv_pem = std::fs::read_to_string("tests/fixtures/test_rsa.pem").unwrap();
    let pub_pem = std::fs::read_to_string("tests/fixtures/test_rsa_pub.pem").unwrap();

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs() as i64;

    let vm = create_vm();
    vm.globals().set("priv_pem", vm.create_string(&priv_pem).unwrap()).unwrap();
    vm.globals().set("pub_pem", vm.create_string(&pub_pem).unwrap()).unwrap();
    vm.globals().set("test_iat", now - 7200).unwrap();
    vm.globals().set("test_exp", now - 3600).unwrap();

    vm.load(
        r#"
        local token = crypto.jwt_sign({
            iss = "test-issuer",
            aud = "test-audience",
            iat = test_iat,
            exp = test_exp,
        }, priv_pem)
        -- An expired token verifies fine when validate_exp is off and the
        -- exp claim is no longer required.
        local out = crypto.jwt_verify(token, pub_pem, {
            audience = "test-audience",
            validate_exp = false,
            required_claims = {},
        })
        assert.eq(out.claims.iss, "test-issuer")
        "#,
    )
    .exec_async()
    .await
    .unwrap();
}

#[tokio::test]
async fn test_jwt_verify_rejects_malformed_token() {
    let pub_pem = std::fs::read_to_string("tests/fixtures/test_rsa_pub.pem").unwrap();
    let vm = create_vm();
    vm.globals().set("pub_pem", vm.create_string(&pub_pem).unwrap()).unwrap();

    let result = vm
        .load(r#"return crypto.jwt_verify("only.two", pub_pem)"#)
        .exec_async()
        .await;
    assert!(result.is_err());
}

#[tokio::test]
async fn test_jwt_verify_rejects_invalid_pem() {
    let result = run_lua(
        r#"
        crypto.jwt_verify("a.b.c", "not-a-real-pem-key")
        "#,
    )
    .await;
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(err.contains("invalid PEM key"), "got: {err}");
}

#[tokio::test]
async fn test_jwt_decode_rejects_malformed_token() {
    // Not three segments
    let result = run_lua(r#"crypto.jwt_decode("only.two")"#).await;
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(err.contains("three '.'-separated segments"), "got: {err}");

    // Invalid base64url in payload
    let result = run_lua(r#"crypto.jwt_decode("eyJhbGciOiJSUzI1NiJ9.!!!notbase64.sig")"#).await;
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("invalid base64url") || err.contains("payload"),
        "got: {err}"
    );

    // Valid base64url but invalid JSON in payload (base64url of "not json")
    let result = run_lua(r#"crypto.jwt_decode("eyJhbGciOiJSUzI1NiJ9.bm90LWpzb24.sig")"#).await;
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(err.contains("invalid JSON") || err.contains("payload"), "got: {err}");
}

#[tokio::test]
async fn test_sha256_default() {
    let result: String = eval_lua(r#"return crypto.hash("hello")"#).await;
    assert_eq!(
        result,
        "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
    );
}

#[tokio::test]
async fn test_sha256_explicit() {
    let result: String = eval_lua(r#"return crypto.hash("hello", "sha256")"#).await;
    assert_eq!(
        result,
        "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
    );
}

#[tokio::test]
async fn test_sha512() {
    let result: String = eval_lua(r#"return crypto.hash("hello", "sha512")"#).await;
    assert_eq!(result.len(), 128);
    assert!(result.starts_with("9b71d224"));
}

#[tokio::test]
async fn test_sha3_256() {
    let result: String = eval_lua(r#"return crypto.hash("hello", "sha3-256")"#).await;
    assert_eq!(result.len(), 64);
    assert_eq!(
        result,
        "3338be694f50c5f338814986cdf0686453a888b84f424d792af4b9202398f392"
    );
}

#[tokio::test]
async fn test_sha224() {
    let result: String = eval_lua(r#"return crypto.hash("hello", "sha224")"#).await;
    assert_eq!(result.len(), 56);
}

#[tokio::test]
async fn test_unsupported_algorithm() {
    let result = run_lua(r#"crypto.hash("hello", "md5")"#).await;
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(err.contains("unsupported algorithm"), "got: {err}");
}

#[tokio::test]
async fn test_empty_input() {
    let result: String = eval_lua(r#"return crypto.hash("", "sha256")"#).await;
    assert_eq!(
        result,
        "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
    );
}

#[tokio::test]
async fn test_default_length() {
    let result: String = eval_lua(r#"return crypto.random()"#).await;
    assert_eq!(result.len(), 32);
    assert!(result.chars().all(|c| c.is_ascii_alphanumeric()));
}

#[tokio::test]
async fn test_custom_length() {
    let result: String = eval_lua(r#"return crypto.random(64)"#).await;
    assert_eq!(result.len(), 64);
    assert!(result.chars().all(|c| c.is_ascii_alphanumeric()));
}

#[tokio::test]
async fn test_short_length() {
    let result: String = eval_lua(r#"return crypto.random(1)"#).await;
    assert_eq!(result.len(), 1);
}

#[tokio::test]
async fn test_uniqueness() {
    let script = r#"
        local a = crypto.random(32)
        local b = crypto.random(32)
        if a == b then
            error("crypto.random produced identical values")
        end
        return a
    "#;
    let result: String = eval_lua(script).await;
    assert_eq!(result.len(), 32);
}

#[tokio::test]
async fn test_invalid_length() {
    assert!(run_lua(r#"crypto.random(0)"#).await.is_err());
    assert!(run_lua(r#"crypto.random(-1)"#).await.is_err());
}

#[tokio::test]
async fn test_hmac_sha256_basic() {
    let result: String =
        eval_lua(r#"return crypto.hmac("Jefe", "what do ya want for nothing?", "sha256")"#).await;
    assert_eq!(
        result,
        "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
    );
}

#[tokio::test]
async fn test_hmac_sha256_raw_output() {
    let vm = create_vm();
    let raw_bytes: mlua::String = vm
        .load(r#"return crypto.hmac("Jefe", "what do ya want for nothing?", "sha256", true)"#)
        .eval_async()
        .await
        .unwrap();
    assert_eq!(raw_bytes.as_bytes().len(), 32);
}

#[tokio::test]
async fn test_hmac_sha256_key_chaining() {
    let script = r#"
        local k1 = crypto.hmac("AWS4" .. "secret", "20130524", "sha256", true)
        local k2 = crypto.hmac(k1, "us-east-1", "sha256", true)
        local k3 = crypto.hmac(k2, "s3", "sha256", true)
        local k4 = crypto.hmac(k3, "aws4_request", "sha256", true)
        return #k4
    "#;
    let len: i64 = eval_lua(script).await;
    assert_eq!(len, 32);
}

#[tokio::test]
async fn test_hmac_default_algorithm() {
    let result: String = eval_lua(r#"return crypto.hmac("key", "data")"#).await;
    let explicit: String = eval_lua(r#"return crypto.hmac("key", "data", "sha256")"#).await;
    assert_eq!(result, explicit);
}

#[tokio::test]
async fn test_hmac_sha512() {
    let result: String =
        eval_lua(r#"return crypto.hmac("Jefe", "what do ya want for nothing?", "sha512")"#).await;
    assert_eq!(result.len(), 128);
    assert_eq!(
        result,
        "164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea2505549758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737"
    );
}

#[tokio::test]
async fn test_hmac_unsupported_algorithm() {
    let result = run_lua(r#"crypto.hmac("key", "data", "md5")"#).await;
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(err.contains("unsupported algorithm"), "got: {err}");
}

#[tokio::test]
async fn test_hmac_empty_data() {
    let result: String = eval_lua(r#"return crypto.hmac("key", "")"#).await;
    assert_eq!(
        result,
        "5d5d139563c95b5967b9bd9a8c9b233a9dedb45072794cd232dc1b74832607d0"
    );
}