hessra-sdk 0.11.2

Hessra authorization service SDK for Rust
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
//! # Hessra SDK
//!
//! A Rust client library for interacting with Hessra authentication and authorization services.
//!
//! The Hessra SDK provides a robust and flexible way to request and verify both identity tokens
//! and authorization tokens for protected resources. Authentication can be done via mutual TLS (mTLS)
//! or using identity tokens for most operations.
//!
//! This crate combines functionality from:
//! - `hessra-token`: Authorization token verification and attestation
//! - `hessra-token-identity`: Identity token creation, verification, and delegation
//! - `hessra-config`: Configuration management
//! - `hessra-api`: HTTP client for the Hessra service
//!
//! ## Features
//!
//! - **Flexible configuration**: Load configuration from various sources (environment variables, files, etc.)
//! - **Protocol support**: HTTP/1.1 support with optional HTTP/3 via feature flag
//! - **Dual authentication**: Support for both mTLS and identity token authentication
//! - **Identity tokens**: Hierarchical, delegatable identity tokens for authentication
//! - **Authorization tokens**: Request and verify authorization tokens for resources
//! - **Local verification**: Retrieve and store public keys for offline token verification
//! - **Service chains**: Support for service chain attestation and verification
//!
//! ## Feature Flags
//!
//! - `http3`: Enables HTTP/3 protocol support
//! - `toml`: Enables configuration loading from TOML files
//! - `wasm`: Enables WebAssembly support for token verification

use std::fs::File;
use std::io::Read;
use std::path::Path;
use thiserror::Error;

// Re-export everything from the component crates
pub use hessra_token::{
    // Token attestation
    add_service_node_attestation,
    decode_token,
    encode_token,
    // Prefix restriction functions
    add_prefix_restriction,
    add_prefix_restriction_to_token,
    // Token verification
    verify_biscuit_local,
    verify_service_chain_biscuit_local,
    // Verification builder
    AuthorizationVerifier,
    // Re-exported biscuit types
    Biscuit,
    KeyPair,
    PublicKey,
    // Service chain types
    ServiceNode,
    // Token errors
    TokenError,
};

// Re-export identity token functionality
pub use hessra_token_identity::{
    add_identity_attenuation_to_token, create_identity_token, create_short_lived_identity_token,
    verify_identity_token,
};

pub use hessra_config::{ConfigError, HessraConfig, Protocol};

pub use hessra_api::{
    parse_server_address, ApiError, HessraClient, HessraClientBuilder, IdentityTokenRequest,
    IdentityTokenResponse, MintIdentityTokenRequest, MintIdentityTokenResponse, PublicKeyResponse,
    RefreshIdentityTokenRequest, SignTokenRequest, SignTokenResponse, SignoffInfo,
    StubTokenRequest, StubTokenResponse, TokenRequest, TokenResponse,
    VerifyServiceChainTokenRequest, VerifyTokenRequest, VerifyTokenResponse,
};

/// Errors that can occur in the Hessra SDK
#[derive(Error, Debug)]
pub enum SdkError {
    /// Configuration error
    #[error("Configuration error: {0}")]
    Config(#[from] ConfigError),

    /// API error
    #[error("API error: {0}")]
    Api(#[from] ApiError),

    /// Token error
    #[error("Token error: {0}")]
    Token(#[from] TokenError),

    /// JSON serialization error
    #[error("JSON error: {0}")]
    Json(#[from] serde_json::Error),

    /// I/O error
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),

    /// Generic error
    #[error("{0}")]
    Generic(String),
}

/// A chain of service nodes
///
/// Represents an ordered sequence of service nodes that form a processing chain.
/// The order of nodes in the chain is significant - it defines the expected
/// order of processing and attestation.
#[derive(Clone, Debug, Default)]
pub struct ServiceChain {
    /// The nodes in the chain, in order
    nodes: Vec<ServiceNode>,
}

impl ServiceChain {
    /// Create a new empty service chain
    pub fn new() -> Self {
        Self { nodes: Vec::new() }
    }

    /// Create a service chain with the given nodes
    pub fn with_nodes(nodes: Vec<ServiceNode>) -> Self {
        Self { nodes }
    }

    /// Create a new service chain builder
    pub fn builder() -> ServiceChainBuilder {
        ServiceChainBuilder::new()
    }

    /// Add a node to the chain
    pub fn add_node(&mut self, node: ServiceNode) -> &mut Self {
        self.nodes.push(node);
        self
    }

    /// Add a node to the chain (builder style)
    pub fn with_node(mut self, node: ServiceNode) -> Self {
        self.nodes.push(node);
        self
    }

    /// Get the nodes in the chain
    pub fn nodes(&self) -> &[ServiceNode] {
        &self.nodes
    }

    /// Convert to internal representation for token verification
    fn to_internal(&self) -> Vec<hessra_token::ServiceNode> {
        self.nodes.to_vec()
    }

    /// Load a service chain from a JSON string
    pub fn from_json(json: &str) -> Result<Self, SdkError> {
        let nodes: Vec<ServiceNode> = serde_json::from_str(json)?;
        Ok(Self::with_nodes(nodes))
    }

    /// Load a service chain from a JSON file
    pub fn from_json_file(path: impl AsRef<Path>) -> Result<Self, SdkError> {
        let mut file = File::open(path)?;
        let mut contents = String::new();
        file.read_to_string(&mut contents)?;
        Self::from_json(&contents)
    }

    /// Load a service chain from a TOML string
    #[cfg(feature = "toml")]
    pub fn from_toml(toml_str: &str) -> Result<Self, SdkError> {
        use serde::Deserialize;

        #[derive(Deserialize)]
        struct TomlServiceChain {
            nodes: Vec<ServiceNode>,
        }

        let chain: TomlServiceChain = toml::from_str(toml_str)
            .map_err(|e| SdkError::Generic(format!("TOML parse error: {e}")))?;

        Ok(Self::with_nodes(chain.nodes))
    }

    /// Load a service chain from a TOML file
    #[cfg(feature = "toml")]
    pub fn from_toml_file(path: impl AsRef<Path>) -> Result<Self, SdkError> {
        let mut file = File::open(path)?;
        let mut contents = String::new();
        file.read_to_string(&mut contents)?;
        Self::from_toml(&contents)
    }
}

/// Builder for a service chain
#[derive(Debug, Default)]
pub struct ServiceChainBuilder {
    nodes: Vec<ServiceNode>,
}

impl ServiceChainBuilder {
    /// Create a new service chain builder
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a node to the chain
    pub fn add_node(mut self, node: ServiceNode) -> Self {
        self.nodes.push(node);
        self
    }

    /// Build the service chain
    pub fn build(self) -> ServiceChain {
        ServiceChain::with_nodes(self.nodes)
    }
}

/// Unified SDK for Hessra authentication services
///
/// This struct provides a high-level interface combining functionality
/// from all component crates (config, token, api).
pub struct Hessra {
    client: HessraClient,
    config: HessraConfig,
}

impl Hessra {
    /// Create a new Hessra SDK instance from a configuration
    pub fn new(config: HessraConfig) -> Result<Self, SdkError> {
        let client = HessraClientBuilder::new()
            .from_config(&config)
            .build()
            .map_err(|e| SdkError::Generic(e.to_string()))?;

        Ok(Self { client, config })
    }

    /// Create a builder for a Hessra SDK instance
    pub fn builder() -> HessraBuilder {
        HessraBuilder::new()
    }

    /// Setup the SDK with the public key
    ///
    /// This will fetch the public key from the Hessra service and set it in the SDK configuration.
    /// If the public key is already set, it will be overwritten.
    /// Requires a mutable reference to the SDK instance.
    pub async fn setup(&mut self) -> Result<(), SdkError> {
        match self.get_public_key().await {
            Ok(public_key) => {
                self.config.public_key = Some(public_key);
                Ok(())
            }
            Err(e) => Err(SdkError::Generic(e.to_string())),
        }
    }

    /// Setup the SDK with the public key and return a new instance
    ///
    /// This will fetch the public key from the Hessra service and set it in the SDK configuration.
    /// If the public key is already set, it will be overwritten.
    pub async fn with_setup(&self) -> Result<Self, SdkError> {
        match self.get_public_key().await {
            Ok(public_key) => {
                let config = self.config.to_builder().public_key(public_key).build()?;
                Ok(Self::new(config)?)
            }
            Err(e) => Err(SdkError::Generic(e.to_string())),
        }
    }

    /// Request a token for a resource
    /// Returns the full TokenResponse which may include pending signoffs for multi-party tokens
    ///
    /// # Arguments
    /// * `resource` - The resource identifier to request authorization for
    /// * `operation` - The operation to request authorization for
    /// * `domain` - Optional domain for domain-restricted identity token verification
    pub async fn request_token(
        &self,
        resource: impl Into<String>,
        operation: impl Into<String>,
        domain: Option<String>,
    ) -> Result<TokenResponse, SdkError> {
        self.client
            .request_token(resource.into(), operation.into(), domain)
            .await
            .map_err(|e| SdkError::Generic(e.to_string()))
    }

    /// Apply JIT attenuation to an identity token for secure transmission
    /// Creates a short-lived (5 second) version of the token
    fn apply_jit_attenuation(&self, identity_token: String) -> String {
        // Only apply JIT attenuation if we have a public key configured
        if let Some(ref public_key_pem) = self.config.public_key {
            // Parse the public key
            if let Ok(public_key) = PublicKey::from_pem(public_key_pem.as_str()) {
                // Apply JIT attenuation for 5-second expiry
                if let Ok(attenuated_token) =
                    create_short_lived_identity_token(identity_token.clone(), public_key)
                {
                    return attenuated_token;
                }
            }
        }
        // If attenuation fails or public key is not configured, return the original token
        identity_token
    }

    /// Request a token for a resource using an identity token for authentication
    /// This method should be used when you have a delegated identity token
    /// and want to request authorization tokens as that delegated identity
    /// The identity token will be automatically attenuated with a 5-second expiry for security
    ///
    /// # Arguments
    /// * `resource` - The resource identifier to request authorization for
    /// * `operation` - The operation to request authorization for
    /// * `identity_token` - The identity token to use for authentication
    /// * `domain` - Optional domain for domain-restricted identity token verification
    pub async fn request_token_with_identity(
        &self,
        resource: impl Into<String>,
        operation: impl Into<String>,
        identity_token: impl Into<String>,
        domain: Option<String>,
    ) -> Result<TokenResponse, SdkError> {
        let token = identity_token.into();
        // Apply JIT attenuation to the identity token
        let attenuated_token = self.apply_jit_attenuation(token);

        self.client
            .request_token_with_identity(
                resource.into(),
                operation.into(),
                attenuated_token,
                domain,
            )
            .await
            .map_err(|e| SdkError::Generic(e.to_string()))
    }

    /// Request a token for a resource (simple version)
    /// Returns just the token string for backward compatibility
    pub async fn request_token_simple(
        &self,
        resource: impl Into<String>,
        operation: impl Into<String>,
    ) -> Result<String, SdkError> {
        let response = self.request_token(resource, operation, None).await?;
        match response.token {
            Some(token) => Ok(token),
            None => Err(SdkError::Generic(format!(
                "Failed to get token: {}",
                response.response_msg
            ))),
        }
    }

    /// Sign a multi-party token by calling an authorization service's signoff endpoint
    pub async fn sign_token(
        &self,
        token: &str,
        resource: &str,
        operation: &str,
    ) -> Result<SignTokenResponse, SdkError> {
        self.client
            .sign_token(token, resource, operation)
            .await
            .map_err(|e| SdkError::Generic(e.to_string()))
    }

    /// Parse an authorization service URL to extract base URL and port
    /// Handles URLs like "https://hostname:port/path" or "hostname:port/path"
    /// Returns (base_url, port) where base_url is just the hostname part
    fn parse_authorization_service_url(url: &str) -> Result<(String, Option<u16>), SdkError> {
        let url_str = if url.starts_with("http://") || url.starts_with("https://") {
            url.to_string()
        } else {
            // If no protocol, assume https for parsing
            format!("https://{url}")
        };

        let parsed_url = url::Url::parse(&url_str).map_err(|e| {
            SdkError::Generic(format!(
                "Failed to parse authorization service URL '{url}': {e}"
            ))
        })?;

        let host = parsed_url
            .host_str()
            .ok_or_else(|| SdkError::Generic(format!("No host found in URL: {url}")))?;

        // For URLs where port is not explicitly specified but the scheme indicates a default port,
        // we need to check if the original URL had an explicit port
        let port = if parsed_url.port().is_some() {
            parsed_url.port()
        } else if url.contains(':') && !url.starts_with("http://") && !url.starts_with("https://") {
            // If the original URL has a colon and no protocol, it likely has an explicit port
            // Try to extract it manually
            if let Some(host_port) = url.split('/').next() {
                if let Some(port_str) = host_port.split(':').nth(1) {
                    port_str.parse::<u16>().ok()
                } else {
                    None
                }
            } else {
                None
            }
        } else {
            parsed_url.port()
        };

        Ok((host.to_string(), port))
    }

    /// Collect all required signoffs for a multi-party token
    /// Returns the fully signed token once all signoffs are collected
    pub async fn collect_signoffs(
        &self,
        initial_token_response: TokenResponse,
        resource: &str,
        operation: &str,
    ) -> Result<String, SdkError> {
        // If no pending signoffs, return the token immediately
        let pending_signoffs = match &initial_token_response.pending_signoffs {
            Some(signoffs) if !signoffs.is_empty() => signoffs,
            _ => {
                return initial_token_response
                    .token
                    .ok_or_else(|| SdkError::Generic("No token in response".to_string()))
            }
        };

        let mut current_token = initial_token_response.token.ok_or_else(|| {
            SdkError::Generic("No initial token to collect signoffs for".to_string())
        })?;

        // For each SignoffInfo in pending_signoffs, create a client and call sign_token
        for signoff_info in pending_signoffs {
            // Parse the authorization service URL to extract base URL and port
            let (base_url, port) =
                Self::parse_authorization_service_url(&signoff_info.authorization_service)?;

            // Create a temporary client for this authorization service
            // Note: This is a simplified approach. In practice, you might want to
            // have a configuration system for managing multiple service certificates
            let mut client_builder = HessraClientBuilder::new()
                .base_url(base_url)
                .protocol(self.config.protocol.clone())
                .server_ca(self.config.server_ca.clone());

            // Add mTLS if configured
            if let (Some(cert), Some(key)) = (&self.config.mtls_cert, &self.config.mtls_key) {
                client_builder = client_builder.mtls_cert(cert.clone()).mtls_key(key.clone());
            }

            if let Some(port) = port {
                client_builder = client_builder.port(port);
            }

            let signoff_client = client_builder
                .build()
                .map_err(|e| SdkError::Generic(format!("Failed to create signoff client: {e}")))?;

            let sign_response = signoff_client
                .sign_token(&current_token, resource, operation)
                .await
                .map_err(|e| {
                    SdkError::Generic(format!(
                        "Signoff failed for {}: {e}",
                        signoff_info.component
                    ))
                })?;

            current_token = sign_response.signed_token.ok_or_else(|| {
                SdkError::Generic(format!(
                    "No signed token returned from {}: {}",
                    signoff_info.component, sign_response.response_msg
                ))
            })?;
        }

        Ok(current_token)
    }

    /// Request a token and automatically collect any required signoffs
    /// This is a convenience method that combines token request and signoff collection
    pub async fn request_token_with_signoffs(
        &self,
        resource: &str,
        operation: &str,
    ) -> Result<String, SdkError> {
        let initial_response = self.request_token(resource, operation, None).await?;
        self.collect_signoffs(initial_response, resource, operation)
            .await
    }

    /// Verify a token
    ///
    /// This function verifies a token using either the remote Hessra service or
    /// locally using the service's public key if one is configured. This will always
    /// prefer to verify locally if a public key is configured.
    pub async fn verify_token(
        &self,
        token: impl Into<String>,
        subject: impl Into<String>,
        resource: impl Into<String>,
        operation: impl Into<String>,
    ) -> Result<(), SdkError> {
        if self.config.public_key.is_some() {
            self.verify_token_local(
                token.into(),
                subject.into(),
                resource.into(),
                operation.into(),
            )
        } else {
            self.verify_token_remote(
                token.into(),
                subject.into(),
                resource.into(),
                operation.into(),
            )
            .await
            .map(|_| ())
            .map_err(|e| SdkError::Generic(e.to_string()))
        }
    }

    /// Verify a token using the remote Hessra service
    pub async fn verify_token_remote(
        &self,
        token: impl Into<String>,
        subject: impl Into<String>,
        resource: impl Into<String>,
        operation: impl Into<String>,
    ) -> Result<String, SdkError> {
        self.client
            .verify_token(
                token.into(),
                subject.into(),
                resource.into(),
                operation.into(),
            )
            .await
            .map_err(|e| SdkError::Generic(e.to_string()))
    }

    /// Verify a token locally using cached public keys
    pub fn verify_token_local(
        &self,
        token: impl Into<String>,
        subject: impl AsRef<str>,
        resource: impl AsRef<str>,
        operation: impl AsRef<str>,
    ) -> Result<(), SdkError> {
        let public_key_str = match &self.config.public_key {
            Some(key) => key,
            None => return Err(SdkError::Generic("Public key not configured".to_string())),
        };

        let public_key = PublicKey::from_pem(public_key_str.as_str())
            .map_err(|e| SdkError::Token(TokenError::Generic(e.to_string())))?;

        // Convert token to Vec<u8>
        let token_vec = decode_token(&token.into())?;

        verify_biscuit_local(
            token_vec,
            public_key,
            subject.as_ref().to_string(),
            resource.as_ref().to_string(),
            operation.as_ref().to_string(),
        )
        .map_err(SdkError::Token)
    }

    /// Verify a service chain token
    ///
    /// This function verifies a service chain token using either the remote Hessra service or
    /// locally using the service's public key if one is configured. This will always
    /// prefer to verify locally if a public key is configured and a service chain is provided.
    pub async fn verify_service_chain_token(
        &self,
        token: impl Into<String>,
        subject: impl Into<String>,
        resource: impl Into<String>,
        operation: impl Into<String>,
        service_chain: Option<&ServiceChain>,
        component: Option<String>,
    ) -> Result<(), SdkError> {
        match (&self.config.public_key, service_chain) {
            (Some(_), Some(chain)) => self.verify_service_chain_token_local(
                token.into(),
                subject.into(),
                resource.into(),
                operation.into(),
                chain,
                component,
            ),
            _ => self
                .verify_service_chain_token_remote(
                    token.into(),
                    subject.into(),
                    resource.into(),
                    component,
                )
                .await
                .map(|_| ())
                .map_err(|e| SdkError::Generic(e.to_string())),
        }
    }

    /// Verify a service chain token using the remote Hessra service
    pub async fn verify_service_chain_token_remote(
        &self,
        token: impl Into<String>,
        subject: impl Into<String>,
        resource: impl Into<String>,
        component: Option<String>,
    ) -> Result<String, SdkError> {
        self.client
            .verify_service_chain_token(token.into(), subject.into(), resource.into(), component)
            .await
            .map_err(|e| SdkError::Generic(e.to_string()))
    }

    /// Verify a service chain token locally using cached public keys
    pub fn verify_service_chain_token_local(
        &self,
        token: String,
        subject: impl AsRef<str>,
        resource: impl AsRef<str>,
        operation: impl AsRef<str>,
        service_chain: &ServiceChain,
        component: Option<String>,
    ) -> Result<(), SdkError> {
        let public_key_str = match &self.config.public_key {
            Some(key) => key,
            None => return Err(SdkError::Generic("Public key not configured".to_string())),
        };

        let public_key = PublicKey::from_pem(public_key_str.as_str())
            .map_err(|e| SdkError::Token(TokenError::Generic(e.to_string())))?;

        // Convert token to Vec<u8>
        let token_vec = decode_token(&token)?;

        verify_service_chain_biscuit_local(
            token_vec,
            public_key,
            subject.as_ref().to_string(),
            resource.as_ref().to_string(),
            operation.as_ref().to_string(),
            service_chain.to_internal(),
            component,
        )
        .map_err(SdkError::Token)
    }

    /// Attest a service chain token with a new service node attestation
    /// Expects a base64 encoded token string and a service name
    /// Returns a base64 encoded token string
    pub fn attest_service_chain_token(
        &self,
        token: String,
        service: impl Into<String>,
    ) -> Result<String, SdkError> {
        let keypair_str = match &self.config.personal_keypair {
            Some(keypair) => keypair,
            None => {
                return Err(SdkError::Generic(
                    "Personal keypair not configured".to_string(),
                ))
            }
        };

        let public_key_str = match &self.config.public_key {
            Some(key) => key,
            None => return Err(SdkError::Generic("Public key not configured".to_string())),
        };

        // Parse keypair from string to KeyPair
        let keypair = KeyPair::from_private_key_pem(keypair_str.as_str())
            .map_err(|e| SdkError::Token(TokenError::Generic(e.to_string())))?;

        // Parse public key from PEM string
        let public_key = PublicKey::from_pem(public_key_str.as_str())
            .map_err(|e| SdkError::Token(TokenError::Generic(e.to_string())))?;

        // Convert token to Vec<u8>
        let token_vec = decode_token(&token)?;

        // Convert service to String
        let service_str = service.into();

        let token_vec = add_service_node_attestation(token_vec, public_key, &service_str, &keypair)
            .map_err(SdkError::Token)?;

        Ok(encode_token(&token_vec))
    }

    /// Get the public key from the Hessra service
    pub async fn get_public_key(&self) -> Result<String, SdkError> {
        self.client
            .get_public_key()
            .await
            .map_err(|e| SdkError::Generic(e.to_string()))
    }

    /// Request a new identity token from the authorization service
    ///
    /// This method requires mTLS authentication as it's the initial issuance of an identity token.
    /// Once you have an identity token, you can use it for authentication in subsequent requests
    /// instead of mTLS certificates.
    ///
    /// # Arguments
    /// * `identifier` - Optional identifier for the identity. Can be derived from mTLS certificate if not provided.
    pub async fn request_identity_token(
        &self,
        identifier: Option<String>,
    ) -> Result<IdentityTokenResponse, SdkError> {
        self.client
            .request_identity_token(identifier)
            .await
            .map_err(|e| SdkError::Generic(e.to_string()))
    }

    /// Refresh an existing identity token
    ///
    /// This method can use either mTLS or the current identity token for authentication.
    /// When the SDK client is configured without mTLS certificates, the current token
    /// will be used for authentication and the identifier parameter is required.
    ///
    /// # Arguments
    /// * `current_token` - The existing identity token to refresh
    /// * `identifier` - Optional identifier. Required when not using mTLS authentication.
    pub async fn refresh_identity_token(
        &self,
        current_token: impl Into<String>,
        identifier: Option<String>,
    ) -> Result<IdentityTokenResponse, SdkError> {
        self.client
            .refresh_identity_token(current_token.into(), identifier)
            .await
            .map_err(|e| SdkError::Generic(e.to_string()))
    }

    /// Mint a new domain-restricted identity token
    ///
    /// This method requires mTLS authentication from a "realm" identity (one without domain restriction).
    /// The minted token will be restricted to the minting identity's domain and cannot mint further sub-identities.
    /// Permissions for the minted identity are determined by domain roles configured on the server.
    ///
    /// # Arguments
    /// * `subject` - The subject identifier for the new identity (e.g., "uri:urn:test:argo-cli1:user123")
    /// * `duration` - Optional duration in seconds. If None, server uses configured default.
    ///
    /// # Example
    /// ```no_run
    /// # use hessra_sdk::Hessra;
    /// # async fn example(sdk: &Hessra) -> Result<(), Box<dyn std::error::Error>> {
    /// // Mint a domain-restricted identity token for a user
    /// let response = sdk.mint_domain_restricted_identity_token(
    ///     "uri:urn:test:argo-cli1:user123".to_string(),
    ///     Some(3600) // 1 hour
    /// ).await?;
    ///
    /// if let Some(token) = response.token {
    ///     println!("Minted identity token: {}", token);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn mint_domain_restricted_identity_token(
        &self,
        subject: impl Into<String>,
        duration: Option<u64>,
    ) -> Result<MintIdentityTokenResponse, SdkError> {
        self.client
            .mint_domain_restricted_identity_token(subject.into(), duration)
            .await
            .map_err(|e| SdkError::Generic(e.to_string()))
    }

    /// Request a stub token that requires prefix attestation before use.
    ///
    /// This method requires mTLS authentication from a "realm" identity.
    /// The minted stub token will be for a target identity within the realm's domain
    /// and will require a trusted third party (identified by prefix_attenuator_key)
    /// to add a prefix restriction before the token can be used.
    ///
    /// # Arguments
    /// * `target_identity` - The identity who will use this token (must be in minter's domain)
    /// * `resource` - The resource the stub token grants access to
    /// * `operation` - The operation allowed on the resource
    /// * `prefix_attenuator_key` - Public key that will attest the prefix (format: "ed25519/..." or "secp256r1/...")
    /// * `duration` - Optional token duration in seconds (defaults to minter's configured duration)
    ///
    /// # Example
    /// ```no_run
    /// # use hessra_sdk::Hessra;
    /// # async fn example(sdk: &Hessra) -> Result<(), Box<dyn std::error::Error>> {
    /// // Request a stub token for a user that requires prefix attestation
    /// let response = sdk.request_stub_token(
    ///     "uri:urn:test:argo-cli1:user123".to_string(),
    ///     "files".to_string(),
    ///     "read".to_string(),
    ///     "ed25519/abcdef1234567890...".to_string(),
    ///     Some(3600), // 1 hour
    /// ).await?;
    ///
    /// if let Some(token) = response.token {
    ///     println!("Got stub token: {}", token);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn request_stub_token(
        &self,
        target_identity: impl Into<String>,
        resource: impl Into<String>,
        operation: impl Into<String>,
        prefix_attenuator_key: impl Into<String>,
        duration: Option<u64>,
    ) -> Result<StubTokenResponse, SdkError> {
        self.client
            .request_stub_token(
                target_identity.into(),
                resource.into(),
                operation.into(),
                prefix_attenuator_key.into(),
                duration,
            )
            .await
            .map_err(|e| SdkError::Generic(e.to_string()))
    }

    /// Request a stub token using an identity token for authentication.
    ///
    /// This is similar to `request_stub_token` but uses an identity token
    /// instead of mTLS for authentication. The identity token will be
    /// automatically attenuated with a 5-second expiry for security.
    ///
    /// # Arguments
    /// * `target_identity` - The identity who will use this token (must be in minter's domain)
    /// * `resource` - The resource the stub token grants access to
    /// * `operation` - The operation allowed on the resource
    /// * `prefix_attenuator_key` - Public key that will attest the prefix (format: "ed25519/..." or "secp256r1/...")
    /// * `identity_token` - The identity token to use for authentication
    /// * `duration` - Optional token duration in seconds (defaults to minter's configured duration)
    pub async fn request_stub_token_with_identity(
        &self,
        target_identity: impl Into<String>,
        resource: impl Into<String>,
        operation: impl Into<String>,
        prefix_attenuator_key: impl Into<String>,
        identity_token: impl Into<String>,
        duration: Option<u64>,
    ) -> Result<StubTokenResponse, SdkError> {
        let token = identity_token.into();
        // Apply JIT attenuation to the identity token
        let attenuated_token = self.apply_jit_attenuation(token);

        self.client
            .request_stub_token_with_identity(
                target_identity.into(),
                resource.into(),
                operation.into(),
                prefix_attenuator_key.into(),
                attenuated_token,
                duration,
            )
            .await
            .map_err(|e| SdkError::Generic(e.to_string()))
    }

    /// Verify an identity token locally using the configured public key
    ///
    /// This performs offline verification of an identity token without contacting the server.
    /// Requires the public key to be configured in the SDK.
    ///
    /// # Arguments
    /// * `token` - The identity token to verify
    /// * `identity` - The identity URI to verify the token for (e.g., "urn:hessra:alice")
    pub fn verify_identity_token_local(
        &self,
        token: impl Into<String>,
        identity: impl Into<String>,
    ) -> Result<(), SdkError> {
        let public_key_str = match &self.config.public_key {
            Some(key) => key,
            None => return Err(SdkError::Generic("Public key not configured".to_string())),
        };

        let public_key = PublicKey::from_pem(public_key_str.as_str())
            .map_err(|e| SdkError::Token(TokenError::Generic(e.to_string())))?;

        verify_identity_token(token.into(), public_key, identity.into())
            .map_err(|e| SdkError::Token(TokenError::Generic(e.to_string())))
    }

    /// Attenuate an identity token by adding a delegated identity
    ///
    /// This creates a more restrictive token by delegating from the original identity to a sub-identity.
    /// The resulting token can only be used by the delegated identity and its sub-hierarchies.
    /// For example, attenuating "urn:hessra:alice" to "urn:hessra:alice:laptop" creates a token
    /// that only the laptop identity can use.
    ///
    /// # Arguments
    /// * `token` - The identity token to attenuate
    /// * `delegated_identity` - The sub-identity to delegate to (must be hierarchically under the original)
    /// * `expiration` - Optional expiration time for the attenuated token
    pub fn attenuate_identity_token(
        &self,
        token: impl Into<String>,
        delegated_identity: impl Into<String>,
        duration: i64,
    ) -> Result<String, SdkError> {
        let public_key_str = match &self.config.public_key {
            Some(key) => key,
            None => return Err(SdkError::Generic("Public key not configured".to_string())),
        };

        let public_key = PublicKey::from_pem(public_key_str.as_str())
            .map_err(|e| SdkError::Token(TokenError::Generic(e.to_string())))?;

        let time_config = hessra_token_core::TokenTimeConfig {
            start_time: None,
            duration,
        };

        add_identity_attenuation_to_token(
            token.into(),
            delegated_identity.into(),
            public_key,
            time_config,
        )
        .map_err(|e| SdkError::Token(TokenError::Generic(e.to_string())))
    }

    /// Create a new identity token locally
    ///
    /// This creates an identity token without contacting the authorization service.
    /// Typically used by services that need to create identity tokens for testing
    /// or for use within their own trust domain.
    ///
    /// # Arguments
    /// * `subject` - The identity URI for the token (e.g., "urn:hessra:service")
    /// * `expiration` - Optional expiration time (defaults to 1 hour if not specified)
    pub fn create_identity_token_local(
        &self,
        subject: impl Into<String>,
        duration: i64,
    ) -> Result<String, SdkError> {
        let keypair_str = match &self.config.personal_keypair {
            Some(keypair) => keypair,
            None => {
                return Err(SdkError::Generic(
                    "Personal keypair not configured".to_string(),
                ))
            }
        };

        let keypair = KeyPair::from_private_key_pem(keypair_str.as_str())
            .map_err(|e| SdkError::Token(TokenError::Generic(e.to_string())))?;

        let time_config = hessra_token_core::TokenTimeConfig {
            start_time: None,
            duration,
        };

        create_identity_token(subject.into(), keypair, time_config)
            .map_err(|e| SdkError::Token(TokenError::Generic(e.to_string())))
    }

    /// Get the client used by this SDK instance
    pub fn client(&self) -> &HessraClient {
        &self.client
    }

    /// Get the configuration used by this SDK instance
    pub fn config(&self) -> &HessraConfig {
        &self.config
    }
}

/// Builder for Hessra SDK instances
#[derive(Default)]
pub struct HessraBuilder {
    config_builder: hessra_config::HessraConfigBuilder,
}

impl HessraBuilder {
    /// Create a new Hessra SDK builder
    pub fn new() -> Self {
        Self {
            config_builder: HessraConfig::builder(),
        }
    }

    /// Set the base URL for the Hessra service.
    ///
    /// Accepts various address formats including:
    /// - IP:Port (e.g., "127.0.0.1:4433")
    /// - IP alone (e.g., "127.0.0.1")
    /// - hostname:port (e.g., "test.hessra.net:443")
    /// - hostname alone (e.g., "test.hessra.net")
    ///
    /// If the address includes a port, it will be automatically extracted
    /// and used unless explicitly overridden by calling `.port()`.
    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
        let base_url_str = base_url.into();
        let (host, embedded_port) = parse_server_address(&base_url_str);

        self.config_builder = self.config_builder.base_url(host);

        // If an embedded port was found, set it (can be overridden by explicit .port() call)
        if let Some(port) = embedded_port {
            self.config_builder = self.config_builder.port(port);
        }

        self
    }

    /// Set the mTLS private key
    pub fn mtls_key(mut self, mtls_key: impl Into<String>) -> Self {
        self.config_builder = self.config_builder.mtls_key(mtls_key);
        self
    }

    /// Set the mTLS client certificate
    pub fn mtls_cert(mut self, mtls_cert: impl Into<String>) -> Self {
        self.config_builder = self.config_builder.mtls_cert(mtls_cert);
        self
    }

    /// Set the server CA certificate
    pub fn server_ca(mut self, server_ca: impl Into<String>) -> Self {
        self.config_builder = self.config_builder.server_ca(server_ca);
        self
    }

    /// Set the port for the Hessra service
    pub fn port(mut self, port: u16) -> Self {
        self.config_builder = self.config_builder.port(port);
        self
    }

    /// Set the protocol to use
    pub fn protocol(mut self, protocol: Protocol) -> Self {
        self.config_builder = self.config_builder.protocol(protocol);
        self
    }

    /// Set the public key for token verification
    pub fn public_key(mut self, public_key: impl Into<String>) -> Self {
        self.config_builder = self.config_builder.public_key(public_key);
        self
    }

    /// Set the personal keypair for service chain attestation
    pub fn personal_keypair(mut self, keypair: impl Into<String>) -> Self {
        self.config_builder = self.config_builder.personal_keypair(keypair);
        self
    }

    /// Build a Hessra SDK instance
    pub fn build(self) -> Result<Hessra, SdkError> {
        let config = self.config_builder.build()?;
        Hessra::new(config)
    }
}

/// Fetch a public key from the Hessra service
///
/// This is a convenience function that doesn't require a fully configured client.
pub async fn fetch_public_key(
    base_url: impl Into<String>,
    port: Option<u16>,
    server_ca: impl Into<String>,
) -> Result<String, SdkError> {
    HessraClient::fetch_public_key(base_url, port, server_ca)
        .await
        .map_err(|e| SdkError::Generic(e.to_string()))
}

/// Fetch a public key from the Hessra service using HTTP/3
///
/// This is a convenience function that doesn't require a fully configured client.
#[cfg(feature = "http3")]
pub async fn fetch_public_key_http3(
    base_url: impl Into<String>,
    port: Option<u16>,
    server_ca: impl Into<String>,
) -> Result<String, SdkError> {
    HessraClient::fetch_public_key_http3(base_url, port, server_ca)
        .await
        .map_err(|e| SdkError::Generic(e.to_string()))
}

/// Fetch a CA certificate from the Hessra service
///
/// This is a convenience function that makes an unauthenticated request to the
/// `/ca_cert` endpoint to retrieve the server's CA certificate in PEM format.
/// This is useful for bootstrapping trust when setting up a new client.
///
/// Uses the system CA store for the initial connection.
pub async fn fetch_ca_cert(
    base_url: impl Into<String>,
    port: Option<u16>,
) -> Result<String, SdkError> {
    HessraClient::fetch_ca_cert(base_url, port)
        .await
        .map_err(|e| SdkError::Generic(e.to_string()))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_service_chain_creation() {
        // Create a simple service chain with two nodes
        let json = r#"[
            {
                "component": "service1",
                "public_key": "ed25519/abcdef1234567890"
            },
            {
                "component": "service2",
                "public_key": "ed25519/0987654321fedcba"
            }
        ]"#;

        let service_chain = ServiceChain::from_json(json).unwrap();
        assert_eq!(service_chain.nodes().len(), 2);
        assert_eq!(service_chain.nodes()[0].component, "service1");
        assert_eq!(
            service_chain.nodes()[0].public_key,
            "ed25519/abcdef1234567890"
        );
        assert_eq!(service_chain.nodes()[1].component, "service2");
        assert_eq!(
            service_chain.nodes()[1].public_key,
            "ed25519/0987654321fedcba"
        );

        // Test adding a node
        let mut chain = ServiceChain::new();
        let node = ServiceNode {
            component: "service3".to_string(),
            public_key: "ed25519/1122334455667788".to_string(),
        };
        chain.add_node(node);
        assert_eq!(chain.nodes().len(), 1);
        assert_eq!(chain.nodes()[0].component, "service3");
    }

    #[test]
    fn test_service_chain_builder() {
        let builder = ServiceChainBuilder::new();
        let node1 = ServiceNode {
            component: "auth".to_string(),
            public_key: "ed25519/auth123".to_string(),
        };
        let node2 = ServiceNode {
            component: "payment".to_string(),
            public_key: "ed25519/payment456".to_string(),
        };

        let chain = builder.add_node(node1).add_node(node2).build();

        assert_eq!(chain.nodes().len(), 2);
        assert_eq!(chain.nodes()[0].component, "auth");
        assert_eq!(chain.nodes()[1].component, "payment");
    }

    #[test]
    fn test_parse_authorization_service_url() {
        // Test URL with https protocol and path
        let (base_url, port) =
            Hessra::parse_authorization_service_url("https://127.0.0.1:4433/sign_token").unwrap();
        assert_eq!(base_url, "127.0.0.1");
        assert_eq!(port, Some(4433));

        // Test URL with http protocol
        let (base_url, port) =
            Hessra::parse_authorization_service_url("http://example.com:8080/api/sign").unwrap();
        assert_eq!(base_url, "example.com");
        assert_eq!(port, Some(8080));

        // Test URL without protocol but with port and path
        let (base_url, port) =
            Hessra::parse_authorization_service_url("test.hessra.net:443/sign_token").unwrap();
        assert_eq!(base_url, "test.hessra.net");
        assert_eq!(port, Some(443));

        // Test URL without protocol and without port
        let (base_url, port) =
            Hessra::parse_authorization_service_url("example.com/api/endpoint").unwrap();
        assert_eq!(base_url, "example.com");
        assert_eq!(port, None);

        // Test URL with just hostname and port (no path)
        let (base_url, port) =
            Hessra::parse_authorization_service_url("https://localhost:8443").unwrap();
        assert_eq!(base_url, "localhost");
        assert_eq!(port, Some(8443));

        // Test hostname only (no protocol, port, or path)
        let (base_url, port) = Hessra::parse_authorization_service_url("api.example.org").unwrap();
        assert_eq!(base_url, "api.example.org");
        assert_eq!(port, None);
    }
}