aptos-sdk 0.4.1

A user-friendly, idiomatic Rust SDK for the Aptos blockchain
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
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
//! Keyless (OIDC-based) account support.

use crate::account::account::{Account, AuthenticationKey};
use crate::crypto::{Ed25519PrivateKey, Ed25519PublicKey, KEYLESS_SCHEME};
use crate::error::{AptosError, AptosResult};
use crate::types::AccountAddress;
use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header};
use rand::RngCore;
use serde::{Deserialize, Serialize};
use sha3::{Digest, Sha3_256};
use std::fmt;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use url::Url;

// Re-export JwkSet for use with from_jwt_with_jwks and refresh_proof_with_jwks
pub use jsonwebtoken::jwk::JwkSet;

/// Keyless signature payload for transaction authentication.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct KeylessSignature {
    /// Ephemeral public key bytes.
    pub ephemeral_public_key: Vec<u8>,
    /// Signature produced by the ephemeral key.
    pub ephemeral_signature: Vec<u8>,
    /// Zero-knowledge proof bytes.
    pub proof: Vec<u8>,
}

impl KeylessSignature {
    /// Serializes the signature using BCS.
    ///
    /// # Errors
    ///
    /// Returns an error if BCS serialization fails.
    pub fn to_bcs(&self) -> AptosResult<Vec<u8>> {
        aptos_bcs::to_bytes(self).map_err(AptosError::bcs)
    }
}

/// Short-lived key pair used for keyless signing.
#[derive(Clone)]
pub struct EphemeralKeyPair {
    private_key: Ed25519PrivateKey,
    public_key: Ed25519PublicKey,
    expiry: SystemTime,
    nonce: String,
}

impl EphemeralKeyPair {
    /// Generates a new ephemeral key pair with the given expiry (in seconds).
    pub fn generate(expiry_secs: u64) -> Self {
        let private_key = Ed25519PrivateKey::generate();
        let public_key = private_key.public_key();
        let nonce = {
            let mut bytes = [0u8; 16];
            rand::rngs::OsRng.fill_bytes(&mut bytes);
            const_hex::encode(bytes)
        };
        Self {
            private_key,
            public_key,
            expiry: SystemTime::now() + Duration::from_secs(expiry_secs),
            nonce,
        }
    }

    /// Returns true if the key pair has expired.
    pub fn is_expired(&self) -> bool {
        SystemTime::now() >= self.expiry
    }

    /// Returns the nonce associated with this key pair.
    pub fn nonce(&self) -> &str {
        &self.nonce
    }

    /// Returns the public key.
    pub fn public_key(&self) -> &Ed25519PublicKey {
        &self.public_key
    }
}

impl fmt::Debug for EphemeralKeyPair {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EphemeralKeyPair")
            .field("public_key", &self.public_key)
            .field("expiry", &self.expiry)
            .field("nonce", &self.nonce)
            .finish_non_exhaustive()
    }
}

/// Supported OIDC providers.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum OidcProvider {
    /// Google identity provider.
    Google,
    /// Apple identity provider.
    Apple,
    /// Microsoft identity provider.
    Microsoft,
    /// Custom OIDC provider.
    Custom {
        /// Issuer URL.
        issuer: String,
        /// JWKS URL.
        jwks_url: String,
    },
}

impl OidcProvider {
    /// Returns the issuer URL.
    pub fn issuer(&self) -> &str {
        match self {
            OidcProvider::Google => "https://accounts.google.com",
            OidcProvider::Apple => "https://appleid.apple.com",
            OidcProvider::Microsoft => "https://login.microsoftonline.com/common/v2.0",
            OidcProvider::Custom { issuer, .. } => issuer,
        }
    }

    /// Returns the JWKS URL.
    pub fn jwks_url(&self) -> &str {
        match self {
            OidcProvider::Google => "https://www.googleapis.com/oauth2/v3/certs",
            OidcProvider::Apple => "https://appleid.apple.com/auth/keys",
            OidcProvider::Microsoft => {
                "https://login.microsoftonline.com/common/discovery/v2.0/keys"
            }
            OidcProvider::Custom { jwks_url, .. } => jwks_url,
        }
    }

    /// Infers a provider from an issuer URL.
    ///
    /// # Security
    ///
    /// For unknown issuers, the JWKS URL is constructed as `{issuer}/.well-known/jwks.json`.
    /// Non-HTTPS issuers are accepted at construction time but will produce an empty
    /// JWKS URL, causing a clear error at JWKS fetch time. This prevents SSRF via
    /// `http://`, `file://`, or other dangerous URL schemes without changing the
    /// function signature. Callers controlling issuer input should additionally
    /// validate the host (e.g., block private IP ranges) if SSRF is a concern.
    pub fn from_issuer(issuer: &str) -> Self {
        match issuer {
            "https://accounts.google.com" => OidcProvider::Google,
            "https://appleid.apple.com" => OidcProvider::Apple,
            "https://login.microsoftonline.com/common/v2.0" => OidcProvider::Microsoft,
            _ => {
                // SECURITY: Only accept HTTPS issuers to prevent SSRF attacks.
                // A malicious JWT could set `iss` to an internal URL (e.g.,
                // http://169.254.169.254/) causing the SDK to make requests to
                // attacker-chosen endpoints when fetching JWKS.
                let jwks_url = if issuer.starts_with("https://") {
                    format!("{issuer}/.well-known/jwks.json")
                } else {
                    // Non-HTTPS issuers get an invalid JWKS URL that will fail
                    // at fetch time with a clear error rather than making requests
                    // to potentially dangerous endpoints.
                    String::new()
                };
                OidcProvider::Custom {
                    issuer: issuer.to_string(),
                    jwks_url,
                }
            }
        }
    }
}

/// Pepper bytes used in keyless address derivation.
///
/// # Security
///
/// The pepper is secret material used to derive keyless account addresses.
/// It is automatically zeroized when dropped to prevent key material from
/// lingering in memory.
#[derive(Clone, PartialEq, Eq, zeroize::Zeroize, zeroize::ZeroizeOnDrop)]
pub struct Pepper(Vec<u8>);

impl std::fmt::Debug for Pepper {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Pepper(REDACTED)")
    }
}

impl Pepper {
    /// Creates a new pepper from raw bytes.
    pub fn new(bytes: Vec<u8>) -> Self {
        Self(bytes)
    }

    /// Returns the pepper as bytes.
    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    /// Creates a pepper from hex.
    ///
    /// # Errors
    ///
    /// Returns an error if the hex string is invalid or cannot be decoded.
    pub fn from_hex(hex_str: &str) -> AptosResult<Self> {
        Ok(Self(const_hex::decode(hex_str)?))
    }

    /// Returns the pepper as hex.
    pub fn to_hex(&self) -> String {
        const_hex::encode_prefixed(&self.0)
    }
}

/// Zero-knowledge proof bytes.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ZkProof(Vec<u8>);

impl ZkProof {
    /// Creates a new proof from raw bytes.
    pub fn new(bytes: Vec<u8>) -> Self {
        Self(bytes)
    }

    /// Returns the proof as bytes.
    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    /// Creates a proof from hex.
    ///
    /// # Errors
    ///
    /// Returns an error if the hex string is invalid or cannot be decoded.
    pub fn from_hex(hex_str: &str) -> AptosResult<Self> {
        Ok(Self(const_hex::decode(hex_str)?))
    }

    /// Returns the proof as hex.
    pub fn to_hex(&self) -> String {
        const_hex::encode_prefixed(&self.0)
    }
}

/// Service for obtaining pepper values.
pub trait PepperService: Send + Sync {
    /// Fetches the pepper for a JWT.
    fn get_pepper(
        &self,
        jwt: &str,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = AptosResult<Pepper>> + Send + '_>>;
}

/// Service for generating zero-knowledge proofs.
pub trait ProverService: Send + Sync {
    /// Generates the proof for keyless authentication.
    fn generate_proof<'a>(
        &'a self,
        jwt: &'a str,
        ephemeral_key: &'a EphemeralKeyPair,
        pepper: &'a Pepper,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = AptosResult<ZkProof>> + Send + 'a>>;
}

/// HTTP pepper service client.
#[derive(Clone, Debug)]
pub struct HttpPepperService {
    url: Url,
    client: reqwest::Client,
}

impl HttpPepperService {
    /// Creates a new HTTP pepper service client.
    pub fn new(url: Url) -> Self {
        Self {
            url,
            client: reqwest::Client::new(),
        }
    }
}

#[derive(Serialize)]
struct PepperRequest<'a> {
    jwt: &'a str,
}

#[derive(Deserialize)]
struct PepperResponse {
    pepper: String,
}

impl PepperService for HttpPepperService {
    fn get_pepper(
        &self,
        jwt: &str,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = AptosResult<Pepper>> + Send + '_>> {
        let jwt = jwt.to_owned();
        Box::pin(async move {
            let response = self
                .client
                .post(self.url.clone())
                .json(&PepperRequest { jwt: &jwt })
                .send()
                .await?
                .error_for_status()?;

            // SECURITY: Stream body with size limit to prevent OOM
            let bytes =
                crate::config::read_response_bounded(response, MAX_JWKS_RESPONSE_SIZE).await?;
            let payload: PepperResponse = serde_json::from_slice(&bytes).map_err(|e| {
                AptosError::InvalidJwt(format!("failed to parse pepper response: {e}"))
            })?;
            Pepper::from_hex(&payload.pepper)
        })
    }
}

/// HTTP prover service client.
#[derive(Clone, Debug)]
pub struct HttpProverService {
    url: Url,
    client: reqwest::Client,
}

impl HttpProverService {
    /// Creates a new HTTP prover service client.
    pub fn new(url: Url) -> Self {
        Self {
            url,
            client: reqwest::Client::new(),
        }
    }
}

#[derive(Serialize)]
struct ProverRequest<'a> {
    jwt: &'a str,
    ephemeral_public_key: String,
    nonce: &'a str,
    pepper: String,
}

#[derive(Deserialize)]
struct ProverResponse {
    proof: String,
}

impl ProverService for HttpProverService {
    fn generate_proof<'a>(
        &'a self,
        jwt: &'a str,
        ephemeral_key: &'a EphemeralKeyPair,
        pepper: &'a Pepper,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = AptosResult<ZkProof>> + Send + 'a>>
    {
        Box::pin(async move {
            let request = ProverRequest {
                jwt,
                ephemeral_public_key: const_hex::encode_prefixed(
                    ephemeral_key.public_key.to_bytes(),
                ),
                nonce: ephemeral_key.nonce(),
                pepper: pepper.to_hex(),
            };

            let response = self
                .client
                .post(self.url.clone())
                .json(&request)
                .send()
                .await?
                .error_for_status()?;

            // SECURITY: Stream body with size limit to prevent OOM
            let bytes =
                crate::config::read_response_bounded(response, MAX_JWKS_RESPONSE_SIZE).await?;
            let payload: ProverResponse = serde_json::from_slice(&bytes).map_err(|e| {
                AptosError::InvalidJwt(format!("failed to parse prover response: {e}"))
            })?;
            ZkProof::from_hex(&payload.proof)
        })
    }
}

/// Account authenticated via OIDC.
pub struct KeylessAccount {
    ephemeral_key: EphemeralKeyPair,
    provider: OidcProvider,
    issuer: String,
    audience: String,
    user_id: String,
    pepper: Pepper,
    proof: ZkProof,
    address: AccountAddress,
    auth_key: AuthenticationKey,
    jwt_expiration: Option<SystemTime>,
}

impl KeylessAccount {
    /// Creates a keyless account from an OIDC JWT token.
    ///
    /// This method verifies the JWT signature using the OIDC provider's JWKS endpoint
    /// before extracting claims and creating the account.
    ///
    /// # Network Requests
    ///
    /// This method makes HTTP requests to:
    /// - The OIDC provider's JWKS endpoint to fetch signing keys
    /// - The pepper service to obtain the pepper
    /// - The prover service to generate a ZK proof
    ///
    /// For more control over network calls and caching, use [`Self::from_jwt_with_jwks`]
    /// with pre-fetched JWKS.
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - The JWT signature verification fails
    /// - The JWT cannot be decoded or is missing required claims (iss, aud, sub, nonce)
    /// - The JWT nonce doesn't match the ephemeral key's nonce
    /// - The JWT is expired
    /// - The JWKS cannot be fetched from the provider (network timeout, DNS failure,
    ///   connection errors, HTTP errors, or invalid JWKS response)
    /// - The pepper service fails to return a pepper
    /// - The prover service fails to generate a proof
    pub async fn from_jwt(
        jwt: &str,
        ephemeral_key: EphemeralKeyPair,
        pepper_service: &dyn PepperService,
        prover_service: &dyn ProverService,
    ) -> AptosResult<Self> {
        // First, decode without verification to get the issuer for JWKS lookup
        let unverified_claims = decode_claims_unverified(jwt)?;
        let issuer = unverified_claims
            .iss
            .as_ref()
            .ok_or_else(|| AptosError::InvalidJwt("missing iss claim".into()))?;

        // Determine provider and fetch JWKS
        let provider = OidcProvider::from_issuer(issuer);
        let client = reqwest::Client::builder()
            .timeout(JWKS_FETCH_TIMEOUT)
            .build()
            .map_err(|e| AptosError::InvalidJwt(format!("failed to create HTTP client: {e}")))?;
        let jwks = fetch_jwks(&client, provider.jwks_url()).await?;

        // Now verify and decode the JWT properly
        let claims = decode_and_verify_jwt(jwt, &jwks)?;
        let (issuer, audience, user_id, exp, nonce) = extract_claims(&claims)?;

        if nonce != ephemeral_key.nonce() {
            return Err(AptosError::InvalidJwt("JWT nonce mismatch".into()));
        }

        let pepper = pepper_service.get_pepper(jwt).await?;
        let proof = prover_service
            .generate_proof(jwt, &ephemeral_key, &pepper)
            .await?;

        let address = derive_keyless_address(&issuer, &audience, &user_id, &pepper);
        let auth_key = AuthenticationKey::new(address.to_bytes());

        Ok(Self {
            provider: OidcProvider::from_issuer(&issuer),
            issuer,
            audience,
            user_id,
            pepper,
            proof,
            address,
            auth_key,
            jwt_expiration: exp,
            ephemeral_key,
        })
    }

    /// Creates a keyless account from a JWT with pre-fetched JWKS.
    ///
    /// This method is useful when you want to:
    /// - Cache the JWKS to avoid repeated network requests
    /// - Have more control over HTTP client configuration
    /// - Implement custom caching strategies based on HTTP cache headers
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - The JWT signature verification fails
    /// - The JWT cannot be decoded or is missing required claims (iss, aud, sub, nonce)
    /// - The JWT nonce doesn't match the ephemeral key's nonce
    /// - The JWT is expired
    /// - The pepper service fails to return a pepper
    /// - The prover service fails to generate a proof
    pub async fn from_jwt_with_jwks(
        jwt: &str,
        jwks: &JwkSet,
        ephemeral_key: EphemeralKeyPair,
        pepper_service: &dyn PepperService,
        prover_service: &dyn ProverService,
    ) -> AptosResult<Self> {
        // Verify and decode the JWT using the provided JWKS
        let claims = decode_and_verify_jwt(jwt, jwks)?;
        let (issuer, audience, user_id, exp, nonce) = extract_claims(&claims)?;

        if nonce != ephemeral_key.nonce() {
            return Err(AptosError::InvalidJwt("JWT nonce mismatch".into()));
        }

        let pepper = pepper_service.get_pepper(jwt).await?;
        let proof = prover_service
            .generate_proof(jwt, &ephemeral_key, &pepper)
            .await?;

        let address = derive_keyless_address(&issuer, &audience, &user_id, &pepper);
        let auth_key = AuthenticationKey::new(address.to_bytes());

        Ok(Self {
            provider: OidcProvider::from_issuer(&issuer),
            issuer,
            audience,
            user_id,
            pepper,
            proof,
            address,
            auth_key,
            jwt_expiration: exp,
            ephemeral_key,
        })
    }

    /// Returns the OIDC provider.
    pub fn provider(&self) -> &OidcProvider {
        &self.provider
    }

    /// Returns the issuer.
    pub fn issuer(&self) -> &str {
        &self.issuer
    }

    /// Returns the audience.
    pub fn audience(&self) -> &str {
        &self.audience
    }

    /// Returns the user identifier (sub claim).
    pub fn user_id(&self) -> &str {
        &self.user_id
    }

    /// Returns the proof.
    pub fn proof(&self) -> &ZkProof {
        &self.proof
    }

    /// Returns true if the account is still valid.
    pub fn is_valid(&self) -> bool {
        if self.ephemeral_key.is_expired() {
            return false;
        }

        match self.jwt_expiration {
            Some(exp) => SystemTime::now() < exp,
            None => true,
        }
    }

    /// Refreshes the proof using a new JWT.
    ///
    /// This method verifies the JWT signature using the OIDC provider's JWKS endpoint.
    ///
    /// # Network Requests
    ///
    /// This method makes HTTP requests to fetch the JWKS from the OIDC provider.
    /// For more control over network calls and caching, use [`Self::refresh_proof_with_jwks`].
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The JWKS cannot be fetched (network timeout, DNS failure, connection errors)
    /// - The JWT signature verification fails
    /// - The JWT cannot be decoded
    /// - The JWT nonce does not match the ephemeral key
    /// - The JWT identity does not match the account
    /// - The prover service fails to generate a new proof
    pub async fn refresh_proof(
        &mut self,
        jwt: &str,
        prover_service: &dyn ProverService,
    ) -> AptosResult<()> {
        // Fetch JWKS and verify JWT
        let client = reqwest::Client::builder()
            .timeout(JWKS_FETCH_TIMEOUT)
            .build()
            .map_err(|e| AptosError::InvalidJwt(format!("failed to create HTTP client: {e}")))?;
        let jwks = fetch_jwks(&client, self.provider.jwks_url()).await?;
        self.refresh_proof_with_jwks(jwt, &jwks, prover_service)
            .await
    }

    /// Refreshes the proof using a new JWT with pre-fetched JWKS.
    ///
    /// This method is useful for caching the JWKS or using a custom HTTP client.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The JWT signature verification fails
    /// - The JWT cannot be decoded
    /// - The JWT nonce does not match the ephemeral key
    /// - The JWT identity does not match the account
    /// - The prover service fails to generate a new proof
    pub async fn refresh_proof_with_jwks(
        &mut self,
        jwt: &str,
        jwks: &JwkSet,
        prover_service: &dyn ProverService,
    ) -> AptosResult<()> {
        let claims = decode_and_verify_jwt(jwt, jwks)?;
        let (issuer, audience, user_id, exp, nonce) = extract_claims(&claims)?;

        if nonce != self.ephemeral_key.nonce() {
            return Err(AptosError::InvalidJwt("JWT nonce mismatch".into()));
        }

        if issuer != self.issuer || audience != self.audience || user_id != self.user_id {
            return Err(AptosError::InvalidJwt(
                "JWT identity does not match account".into(),
            ));
        }

        let proof = prover_service
            .generate_proof(jwt, &self.ephemeral_key, &self.pepper)
            .await?;
        self.proof = proof;
        self.jwt_expiration = exp;
        Ok(())
    }

    /// Signs a message and returns the structured keyless signature.
    pub fn sign_keyless(&self, message: &[u8]) -> KeylessSignature {
        let signature = self.ephemeral_key.private_key.sign(message).to_bytes();
        KeylessSignature {
            ephemeral_public_key: self.ephemeral_key.public_key.to_bytes().to_vec(),
            ephemeral_signature: signature.to_vec(),
            proof: self.proof.as_bytes().to_vec(),
        }
    }

    /// Creates a keyless account from pre-verified JWT claims.
    ///
    /// This is useful for testing or when JWT verification is handled externally.
    /// The caller is responsible for ensuring the JWT was properly verified.
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - The nonce doesn't match the ephemeral key's nonce
    /// - The pepper service fails to return a pepper
    /// - The prover service fails to generate a proof
    #[doc(hidden)]
    #[allow(clippy::too_many_arguments)]
    pub async fn from_verified_claims(
        issuer: String,
        audience: String,
        user_id: String,
        nonce: String,
        exp: Option<SystemTime>,
        ephemeral_key: EphemeralKeyPair,
        pepper_service: &dyn PepperService,
        prover_service: &dyn ProverService,
        jwt_for_services: &str,
    ) -> AptosResult<Self> {
        if nonce != ephemeral_key.nonce() {
            return Err(AptosError::InvalidJwt("nonce mismatch".into()));
        }

        let pepper = pepper_service.get_pepper(jwt_for_services).await?;
        let proof = prover_service
            .generate_proof(jwt_for_services, &ephemeral_key, &pepper)
            .await?;

        let address = derive_keyless_address(&issuer, &audience, &user_id, &pepper);
        let auth_key = AuthenticationKey::new(address.to_bytes());

        Ok(Self {
            provider: OidcProvider::from_issuer(&issuer),
            issuer,
            audience,
            user_id,
            pepper,
            proof,
            address,
            auth_key,
            jwt_expiration: exp,
            ephemeral_key,
        })
    }
}

impl Account for KeylessAccount {
    fn address(&self) -> AccountAddress {
        self.address
    }

    fn authentication_key(&self) -> AuthenticationKey {
        self.auth_key
    }

    fn sign(&self, message: &[u8]) -> crate::error::AptosResult<Vec<u8>> {
        let signature = self.sign_keyless(message);
        signature
            .to_bcs()
            .map_err(|e| crate::error::AptosError::Bcs(e.to_string()))
    }

    fn public_key_bytes(&self) -> Vec<u8> {
        self.ephemeral_key.public_key.to_bytes().to_vec()
    }

    fn signature_scheme(&self) -> u8 {
        KEYLESS_SCHEME
    }
}

impl fmt::Debug for KeylessAccount {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("KeylessAccount")
            .field("address", &self.address)
            .field("provider", &self.provider)
            .field("issuer", &self.issuer)
            .field("audience", &self.audience)
            .field("user_id", &self.user_id)
            .finish_non_exhaustive()
    }
}

#[derive(Debug, Deserialize)]
struct JwtClaims {
    iss: Option<String>,
    aud: Option<AudClaim>,
    sub: Option<String>,
    exp: Option<u64>,
    nonce: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum AudClaim {
    Single(String),
    Multiple(Vec<String>),
}

impl AudClaim {
    fn first(&self) -> Option<&str> {
        match self {
            AudClaim::Single(value) => Some(value.as_str()),
            AudClaim::Multiple(values) => values.first().map(std::string::String::as_str),
        }
    }
}

/// Default timeout for JWKS fetch requests (10 seconds).
const JWKS_FETCH_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);

/// Maximum JWKS response size: 1 MB (JWKS payloads are typically under 10 KB).
const MAX_JWKS_RESPONSE_SIZE: usize = 1024 * 1024;

/// Fetches the JWKS (JSON Web Key Set) from an OIDC provider.
///
/// # Errors
///
/// Returns an error if:
/// - The JWKS cannot be fetched (network timeouts, DNS resolution failures,
///   TLS/connection errors, or HTTP errors)
/// - The JWKS endpoint returns a non-success status code
/// - The response cannot be parsed as valid JWKS JSON
async fn fetch_jwks(client: &reqwest::Client, jwks_url: &str) -> AptosResult<JwkSet> {
    // SECURITY: Validate the JWKS URL scheme to prevent SSRF.
    // The issuer comes from an untrusted JWT, so the derived JWKS URL could
    // point to internal services (e.g., cloud metadata endpoints).
    let parsed_url = Url::parse(jwks_url)
        .map_err(|e| AptosError::InvalidJwt(format!("invalid JWKS URL: {e}")))?;
    if parsed_url.scheme() != "https" {
        return Err(AptosError::InvalidJwt(format!(
            "JWKS URL must use HTTPS scheme, got: {}",
            parsed_url.scheme()
        )));
    }

    // Note: timeout is configured on the client, not per-request
    let response = client.get(jwks_url).send().await?;

    if !response.status().is_success() {
        return Err(AptosError::InvalidJwt(format!(
            "JWKS endpoint returned status: {}",
            response.status()
        )));
    }

    // SECURITY: Stream body with size limit to prevent OOM from a
    // compromised or malicious JWKS endpoint (including chunked encoding).
    let bytes = crate::config::read_response_bounded(response, MAX_JWKS_RESPONSE_SIZE).await?;
    let jwks: JwkSet = serde_json::from_slice(&bytes)
        .map_err(|e| AptosError::InvalidJwt(format!("failed to parse JWKS: {e}")))?;
    Ok(jwks)
}

/// Decodes and verifies a JWT using the provided JWKS.
///
/// This function:
/// 1. Extracts the `kid` (key ID) from the JWT header
/// 2. Finds the matching key in the JWKS
/// 3. Verifies the signature and decodes the claims
///
/// # Errors
///
/// Returns an error if:
/// - The JWT header cannot be decoded
/// - No matching key is found in the JWKS
/// - The signature verification fails
/// - The claims cannot be decoded
fn decode_and_verify_jwt(jwt: &str, jwks: &JwkSet) -> AptosResult<JwtClaims> {
    // Decode header to get the key ID
    let header = decode_header(jwt)
        .map_err(|e| AptosError::InvalidJwt(format!("failed to decode JWT header: {e}")))?;

    let kid = header
        .kid
        .as_ref()
        .ok_or_else(|| AptosError::InvalidJwt("JWT header missing 'kid' field".into()))?;

    // Find the matching key in the JWKS
    let signing_key = jwks.find(kid).ok_or_else(|| {
        AptosError::InvalidJwt("no matching key found for provided key identifier".into())
    })?;

    // Create decoding key from JWK
    let decoding_key = DecodingKey::from_jwk(signing_key)
        .map_err(|e| AptosError::InvalidJwt(format!("failed to create decoding key: {e}")))?;

    // Determine the algorithm strictly from the JWK to prevent algorithm substitution attacks
    let jwk_alg = signing_key
        .common
        .key_algorithm
        .ok_or_else(|| AptosError::InvalidJwt("JWK missing 'alg' (key_algorithm) field".into()))?;

    let algorithm = match jwk_alg {
        // RSA algorithms
        jsonwebtoken::jwk::KeyAlgorithm::RS256 => Algorithm::RS256,
        jsonwebtoken::jwk::KeyAlgorithm::RS384 => Algorithm::RS384,
        jsonwebtoken::jwk::KeyAlgorithm::RS512 => Algorithm::RS512,
        // RSA-PSS algorithms
        jsonwebtoken::jwk::KeyAlgorithm::PS256 => Algorithm::PS256,
        jsonwebtoken::jwk::KeyAlgorithm::PS384 => Algorithm::PS384,
        jsonwebtoken::jwk::KeyAlgorithm::PS512 => Algorithm::PS512,
        // ECDSA algorithms
        jsonwebtoken::jwk::KeyAlgorithm::ES256 => Algorithm::ES256,
        jsonwebtoken::jwk::KeyAlgorithm::ES384 => Algorithm::ES384,
        // EdDSA algorithm
        jsonwebtoken::jwk::KeyAlgorithm::EdDSA => Algorithm::EdDSA,
        _ => {
            return Err(AptosError::InvalidJwt(format!(
                "unsupported JWK algorithm: {jwk_alg:?}"
            )));
        }
    };

    // Ensure the JWT header algorithm matches the JWK algorithm to prevent substitution
    if header.alg != algorithm {
        return Err(AptosError::InvalidJwt(format!(
            "JWT header algorithm ({:?}) does not match JWK algorithm ({:?})",
            header.alg, algorithm
        )));
    }

    // Configure validation - we'll validate exp ourselves with more detailed errors
    let mut validation = Validation::new(algorithm);
    validation.validate_exp = false;
    validation.validate_aud = false; // We'll check aud after decoding
    validation.set_required_spec_claims::<String>(&[]);

    let data = decode::<JwtClaims>(jwt, &decoding_key, &validation)
        .map_err(|e| AptosError::InvalidJwt(format!("JWT verification failed: {e}")))?;

    Ok(data.claims)
}

/// Decodes JWT claims without signature verification.
///
/// This is used only to extract the issuer (and other metadata) before we know
/// which JWKS endpoint to fetch. This is safe because:
/// 1. The extracted issuer is only used to determine which JWKS endpoint to fetch.
/// 2. The JWT is fully verified immediately afterwards using `decode_and_verify_jwt`.
/// 3. No security decisions are made based on these unverified claims.
fn decode_claims_unverified(jwt: &str) -> AptosResult<JwtClaims> {
    // Use dangerous decode only for initial issuer extraction to select the JWKS.
    // The JWT is not trusted at this point: no authorization decisions are made
    // based on these unverified claims, and the token is fully verified (including
    // signature and claims validation) in `decode_and_verify_jwt` right after the
    // appropriate JWKS has been fetched.
    let data = jsonwebtoken::dangerous::insecure_decode::<JwtClaims>(jwt)
        .map_err(|e| AptosError::InvalidJwt(format!("failed to decode JWT claims: {e}")))?;
    Ok(data.claims)
}

fn extract_claims(
    claims: &JwtClaims,
) -> AptosResult<(String, String, String, Option<SystemTime>, String)> {
    let issuer = claims
        .iss
        .clone()
        .ok_or_else(|| AptosError::InvalidJwt("missing iss claim".into()))?;
    let audience = claims
        .aud
        .as_ref()
        .and_then(|aud| aud.first())
        .map(std::string::ToString::to_string)
        .ok_or_else(|| AptosError::InvalidJwt("missing aud claim".into()))?;
    let user_id = claims
        .sub
        .clone()
        .ok_or_else(|| AptosError::InvalidJwt("missing sub claim".into()))?;
    let nonce = claims
        .nonce
        .clone()
        .ok_or_else(|| AptosError::InvalidJwt("missing nonce claim".into()))?;

    let exp_time = claims.exp.map(|exp| UNIX_EPOCH + Duration::from_secs(exp));
    if let Some(exp) = exp_time
        && SystemTime::now() >= exp
    {
        let exp_secs = claims.exp.unwrap_or(0);
        return Err(AptosError::InvalidJwt(format!(
            "JWT is expired (exp: {exp_secs} seconds since UNIX_EPOCH)"
        )));
    }

    Ok((issuer, audience, user_id, exp_time, nonce))
}

fn derive_keyless_address(
    issuer: &str,
    audience: &str,
    user_id: &str,
    pepper: &Pepper,
) -> AccountAddress {
    let issuer_hash = sha3_256_bytes(issuer.as_bytes());
    let audience_hash = sha3_256_bytes(audience.as_bytes());
    let user_hash = sha3_256_bytes(user_id.as_bytes());

    let mut hasher = Sha3_256::new();
    hasher.update(issuer_hash);
    hasher.update(audience_hash);
    hasher.update(user_hash);
    hasher.update(pepper.as_bytes());
    hasher.update([KEYLESS_SCHEME]);
    let result = hasher.finalize();

    let mut address = [0u8; 32];
    address.copy_from_slice(&result);
    AccountAddress::new(address)
}

fn sha3_256_bytes(data: &[u8]) -> [u8; 32] {
    let mut hasher = Sha3_256::new();
    hasher.update(data);
    let result = hasher.finalize();
    let mut output = [0u8; 32];
    output.copy_from_slice(&result);
    output
}

#[cfg(test)]
mod tests {
    use super::*;
    use jsonwebtoken::{Algorithm, EncodingKey, Header, encode};

    struct StaticPepperService {
        pepper: Pepper,
    }

    impl PepperService for StaticPepperService {
        fn get_pepper(
            &self,
            _jwt: &str,
        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = AptosResult<Pepper>> + Send + '_>>
        {
            Box::pin(async move { Ok(self.pepper.clone()) })
        }
    }

    struct StaticProverService {
        proof: ZkProof,
    }

    impl ProverService for StaticProverService {
        fn generate_proof<'a>(
            &'a self,
            _jwt: &'a str,
            _ephemeral_key: &'a EphemeralKeyPair,
            _pepper: &'a Pepper,
        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = AptosResult<ZkProof>> + Send + 'a>>
        {
            Box::pin(async move { Ok(self.proof.clone()) })
        }
    }

    #[derive(Serialize, Deserialize)]
    struct TestClaims {
        iss: String,
        aud: String,
        sub: String,
        exp: u64,
        nonce: String,
    }

    #[tokio::test]
    async fn test_keyless_account_creation() {
        let ephemeral = EphemeralKeyPair::generate(3600);
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time went backwards")
            .as_secs();

        // Create a test JWT for the services (they don't validate it)
        let claims = TestClaims {
            iss: "https://accounts.google.com".to_string(),
            aud: "client-id".to_string(),
            sub: "user-123".to_string(),
            exp: now + 3600,
            nonce: ephemeral.nonce().to_string(),
        };

        let jwt = encode(
            &Header::new(Algorithm::HS256),
            &claims,
            &EncodingKey::from_secret(b"secret"),
        )
        .unwrap();

        let pepper_service = StaticPepperService {
            pepper: Pepper::new(vec![1, 2, 3, 4]),
        };
        let prover_service = StaticProverService {
            proof: ZkProof::new(vec![9, 9, 9]),
        };

        // Use from_verified_claims for unit testing since we can't mock JWKS
        let exp_time = UNIX_EPOCH + std::time::Duration::from_secs(now + 3600);
        let account = KeylessAccount::from_verified_claims(
            "https://accounts.google.com".to_string(),
            "client-id".to_string(),
            "user-123".to_string(),
            ephemeral.nonce().to_string(),
            Some(exp_time),
            ephemeral,
            &pepper_service,
            &prover_service,
            &jwt,
        )
        .await
        .unwrap();

        assert_eq!(account.issuer(), "https://accounts.google.com");
        assert_eq!(account.audience(), "client-id");
        assert_eq!(account.user_id(), "user-123");
        assert!(account.is_valid());
        assert!(!account.address().is_zero());
    }

    #[tokio::test]
    async fn test_keyless_account_nonce_mismatch() {
        let ephemeral = EphemeralKeyPair::generate(3600);
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time went backwards")
            .as_secs();

        let claims = TestClaims {
            iss: "https://accounts.google.com".to_string(),
            aud: "client-id".to_string(),
            sub: "user-123".to_string(),
            exp: now + 3600,
            nonce: ephemeral.nonce().to_string(),
        };

        let jwt = encode(
            &Header::new(Algorithm::HS256),
            &claims,
            &EncodingKey::from_secret(b"secret"),
        )
        .unwrap();

        let pepper_service = StaticPepperService {
            pepper: Pepper::new(vec![1, 2, 3, 4]),
        };
        let prover_service = StaticProverService {
            proof: ZkProof::new(vec![9, 9, 9]),
        };

        // Use a different nonce to trigger mismatch
        let result = KeylessAccount::from_verified_claims(
            "https://accounts.google.com".to_string(),
            "client-id".to_string(),
            "user-123".to_string(),
            "wrong-nonce".to_string(), // This doesn't match ephemeral.nonce()
            None,
            ephemeral,
            &pepper_service,
            &prover_service,
            &jwt,
        )
        .await;

        assert!(result.is_err());
        assert!(matches!(result, Err(AptosError::InvalidJwt(_))));
    }

    #[test]
    fn test_decode_claims_unverified() {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time went backwards")
            .as_secs();

        let claims = TestClaims {
            iss: "https://accounts.google.com".to_string(),
            aud: "test-aud".to_string(),
            sub: "test-sub".to_string(),
            exp: now + 3600,
            nonce: "test-nonce".to_string(),
        };

        let jwt = encode(
            &Header::new(Algorithm::HS256),
            &claims,
            &EncodingKey::from_secret(b"secret"),
        )
        .unwrap();

        let decoded = decode_claims_unverified(&jwt).unwrap();
        assert_eq!(decoded.iss.unwrap(), "https://accounts.google.com");
        assert_eq!(decoded.sub.unwrap(), "test-sub");
        assert_eq!(decoded.nonce.unwrap(), "test-nonce");
    }

    #[test]
    fn test_oidc_provider_detection() {
        assert!(matches!(
            OidcProvider::from_issuer("https://accounts.google.com"),
            OidcProvider::Google
        ));
        assert!(matches!(
            OidcProvider::from_issuer("https://appleid.apple.com"),
            OidcProvider::Apple
        ));
        assert!(matches!(
            OidcProvider::from_issuer("https://unknown.example.com"),
            OidcProvider::Custom { .. }
        ));
    }

    #[test]
    fn test_decode_and_verify_jwt_missing_kid() {
        // Create a JWT without a kid in the header
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time went backwards")
            .as_secs();

        let claims = TestClaims {
            iss: "https://accounts.google.com".to_string(),
            aud: "test-aud".to_string(),
            sub: "test-sub".to_string(),
            exp: now + 3600,
            nonce: "test-nonce".to_string(),
        };

        // HS256 JWT without kid
        let jwt = encode(
            &Header::new(Algorithm::HS256),
            &claims,
            &EncodingKey::from_secret(b"secret"),
        )
        .unwrap();

        // Empty JWKS
        let jwks = JwkSet { keys: vec![] };

        let result = decode_and_verify_jwt(&jwt, &jwks);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(&err, AptosError::InvalidJwt(msg) if msg.contains("kid")),
            "Expected error about missing kid, got: {err:?}"
        );
    }

    #[test]
    fn test_decode_and_verify_jwt_no_matching_key() {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("time went backwards")
            .as_secs();

        let claims = TestClaims {
            iss: "https://accounts.google.com".to_string(),
            aud: "test-aud".to_string(),
            sub: "test-sub".to_string(),
            exp: now + 3600,
            nonce: "test-nonce".to_string(),
        };

        // Create JWT with a kid in header (using HS256 for encoding)
        let mut header = Header::new(Algorithm::HS256);
        header.kid = Some("test-kid-123".to_string());

        let jwt = encode(&header, &claims, &EncodingKey::from_secret(b"secret")).unwrap();

        // Empty JWKS - no matching key
        let jwks = JwkSet { keys: vec![] };

        let result = decode_and_verify_jwt(&jwt, &jwks);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(&err, AptosError::InvalidJwt(msg) if msg.contains("no matching key")),
            "Expected error about no matching key, got: {err:?}"
        );
    }

    #[test]
    fn test_decode_and_verify_jwt_invalid_jwt_format() {
        let jwks = JwkSet { keys: vec![] };

        // Completely invalid JWT
        let result = decode_and_verify_jwt("not-a-valid-jwt", &jwks);
        assert!(result.is_err());

        // JWT with invalid base64
        let result = decode_and_verify_jwt("aaa.bbb.ccc", &jwks);
        assert!(result.is_err());
    }
}