ironshield_types/
token.rs

1use chrono::Utc;
2use serde::{
3    Deserialize, 
4    Serialize
5};
6
7use crate::serde_utils::{
8    serialize_signature, 
9    deserialize_signature
10};
11
12/// IronShield Token structure
13///
14/// * `challenge_signature`:      The Ed25519 signature of the challenge.
15/// * `valid_for`:                The Unix timestamp in unix millis.
16/// * `public_key`:               The Ed25519 public key corresponding
17///                               to the central private key (32 bytes).
18/// * `authentication_signature`: The signature over (challenge_signature
19///                               || valid_for).
20#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct IronShieldToken {
22    #[serde(
23        serialize_with = "serialize_signature",
24        deserialize_with = "deserialize_signature"
25    )]
26    pub challenge_signature: [u8; 64],
27    pub valid_for:           i64,
28    pub public_key:          [u8; 32],
29    #[serde(
30        serialize_with = "serialize_signature",
31        deserialize_with = "deserialize_signature"
32    )]
33    pub auth_signature:      [u8; 64],
34}
35
36impl IronShieldToken {
37    pub fn new(
38        challenge_signature: [u8; 64],
39        valid_for:           i64,
40        public_key:          [u8; 32],
41        auth_signature:      [u8; 64],
42    ) -> Self {
43        Self {
44            challenge_signature,
45            valid_for,
46            public_key,
47            auth_signature,
48        }
49    }
50
51    /// # Returns
52    /// * `bool`: 
53    pub fn is_expired(&self) -> bool {
54        Utc::now().timestamp_millis() > self.valid_for
55    }
56
57    /// Concatenates the token data into a string.
58    ///
59    /// Concatenates:
60    /// - `challenge_signature`       as a lowercase hex string.
61    /// - `valid_for`:                as a string.
62    /// - `public_key`:               as a lowercase hex string.
63    /// - `authentication_signature`: as a lowercase hex string.
64    pub fn concat_struct(&self) -> String {
65        format!(
66            "{}|{}|{}|{}",
67            // Use of hex::encode to convert the arrays to hex strings
68            // "Encodes data as hex string using lowercase characters."
69            // Requirement of `format!`.
70            hex::encode(self.challenge_signature),
71            self.valid_for,
72            hex::encode(self.public_key),
73            hex::encode(self.auth_signature)
74        )
75    }
76
77    /// Creates an `IronShieldToken` from a concatenated string.
78    ///
79    /// This function reverses the operation of `IronShieldToken::concat_struct`.
80    /// Expects a string in the format:
81    /// "challenge_signature|valid_for|public_key|authentication_signature"
82    ///
83    /// # Arguments
84    ///
85    /// * `concat_str`: The concatenated string to parse, typically
86    ///                 generated by `concat_struct()`.
87    ///
88    /// # Returns
89    ///
90    /// * `Result<Self, String>`: A result containing the parsed
91    ///                           `IronShieldToken` or an error message
92    ///                           if parsing fails.
93    pub fn from_concat_struct(concat_str: &str) -> Result<Self, String> {
94        let parts: Vec<&str> = concat_str.split('|').collect();
95
96        if parts.len() != 4 {
97            return Err(format!("Expected 4 parts, got {}", parts.len()));
98        }
99
100        let challenge_signature_bytes = hex::decode(parts[0])
101            .map_err(|_| "Failed to decode challenge_signature hex string")?;
102        let challenge_signature: [u8; 64] = challenge_signature_bytes.try_into()
103            .map_err(|_| "Challenge signature must be exactly 64 bytes")?;
104
105        let valid_for = parts[1].parse::<i64>()
106            .map_err(|_| "Failed to parse valid_for as i64")?;
107
108        let public_key_bytes = hex::decode(parts[2])
109            .map_err(|_| "Failed to decode public_key hex string")?;
110        let public_key: [u8; 32] = public_key_bytes.try_into()
111            .map_err(|_| "Public key must be exactly 32 bytes")?;
112
113        let auth_signature_bytes = hex::decode(parts[3])
114            .map_err(|_| "Failed to decode authentication_signature hex string")?;
115        let authentication_signature: [u8; 64] = auth_signature_bytes.try_into()
116            .map_err(|_| "Authentication signature must be exactly 64 bytes")?;
117
118        Ok(Self {
119            challenge_signature,
120            valid_for,
121            public_key,
122            auth_signature: authentication_signature,
123        })
124    }
125
126    /// Encodes the response as a base64url string for HTTP header transport.
127    ///
128    /// This method concatenates all response fields using the established `|` delimiter
129    /// format, and then base64url-encodes the result for safe transport in HTTP headers.
130    ///
131    /// # Returns
132    /// * `String` - Base64url-encoded string ready for HTTP header use
133    ///
134    /// # Example
135    /// ```
136    /// use ironshield_types::IronShieldToken;
137    /// let response = IronShieldToken::new([0xAB; 64], 12345, [0x12; 32], [0x34; 64]);
138    /// let header_value = response.to_base64url_header();
139    /// // Use header_value in HTTP header: "X-IronShield-Challenge-Response: {header_value}"
140    /// ```
141    pub fn to_base64url_header(&self) -> String {
142        crate::serde_utils::concat_struct_base64url_encode(&self.concat_struct())
143    }
144
145    /// Decodes a base64url-encoded response from an HTTP header.
146    ///
147    /// This method reverses the `to_base64url_header()` operation by first base64url-decoding
148    /// the input string and then parsing it using the established `|` delimiter format.
149    ///
150    /// # Arguments
151    /// * `encoded_header` - The base64url-encoded string from the HTTP header
152    ///
153    /// # Returns
154    /// * `Result<Self, String>` - Decoded response or detailed error message
155    ///
156    /// # Example
157    /// ```
158    /// use ironshield_types::IronShieldToken;
159    /// // Create a response and encode it
160    /// let original = IronShieldToken::new([0xAB; 64], 12345, [0x12; 32], [0x34; 64]);
161    /// let header_value = original.to_base64url_header();
162    /// // Decode it back
163    /// let decoded = IronShieldToken::from_base64url_header(&header_value).unwrap();
164    /// assert_eq!(original.challenge_signature, decoded.challenge_signature);
165    /// ```
166    pub fn from_base64url_header(encoded_header: &str) -> Result<Self, String> {
167        // Decode using the existing serde_utils function.
168        let concat_str: String = crate::serde_utils::concat_struct_base64url_decode(encoded_header.to_string())?;
169
170        // Parse using the existing concat_struct format.
171        Self::from_concat_struct(&concat_str)
172    }
173}
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178
179    #[test]
180    fn test_from_concat_struct_edge_cases() {
181        // Test with a valid minimum length hex (32 bytes = 64 hex chars for public_key, 64 bytes = 128 hex chars for signatures).
182        // Building strings programmatically.
183        let valid_32_byte_hex = "0".repeat(64);  // 32 bytes = 64 hex chars
184        let valid_64_byte_hex = "0".repeat(128); // 64 bytes = 128 hex chars
185        assert_eq!(valid_32_byte_hex.len(), 64, "32-byte hex string should be exactly 64 characters");
186        assert_eq!(valid_64_byte_hex.len(), 128, "64-byte hex string should be exactly 128 characters");
187
188        let input = format!("{}|1000000|{}|{}",
189                            valid_64_byte_hex, valid_32_byte_hex, valid_64_byte_hex);
190        let result = IronShieldToken::from_concat_struct(&input);
191
192        if result.is_err() {
193            panic!("Expected success but got error: {}", result.unwrap_err());
194        }
195
196        let parsed = result.unwrap();
197        assert_eq!(parsed.challenge_signature, [0u8; 64]);
198        assert_eq!(parsed.valid_for, 1000000);
199        assert_eq!(parsed.public_key, [0u8; 32]);
200        assert_eq!(parsed.auth_signature, [0u8; 64]);
201
202        // Test with all F's hex.
203        let all_f_32_hex = "f".repeat(64);   // 32 bytes of 0xFF
204        let all_f_64_hex = "f".repeat(128);  // 64 bytes of 0xFF
205        assert_eq!(all_f_32_hex.len(), 64, "All F's 32-byte hex string should be exactly 64 characters");
206        assert_eq!(all_f_64_hex.len(), 128, "All F's 64-byte hex string should be exactly 128 characters");
207
208        let input = format!("{}|9999999|{}|{}",
209                            all_f_64_hex, all_f_32_hex, all_f_64_hex);
210        let result = IronShieldToken::from_concat_struct(&input);
211
212        if result.is_err() {
213            panic!("Expected success but got error: {}", result.unwrap_err());
214        }
215
216        let parsed = result.unwrap();
217        assert_eq!(parsed.challenge_signature, [0xffu8; 64]);
218        assert_eq!(parsed.valid_for, 9999999);
219        assert_eq!(parsed.public_key, [0xffu8; 32]);
220        assert_eq!(parsed.auth_signature, [0xffu8; 64]);
221    }
222
223    #[test]
224    fn test_concat_struct_roundtrip() {
225        // Create a token with known values.
226        let original_token = IronShieldToken::new(
227            [0xAB; 64],
228            1700000000000,
229            [0xCD; 32],
230            [0xEF; 64],
231        );
232
233        // Convert to concat string and back.
234        let concat_str = original_token.concat_struct();
235        let parsed_token = IronShieldToken::from_concat_struct(&concat_str).unwrap();
236
237        // Verify all fields are preserved.
238        assert_eq!(original_token.challenge_signature, parsed_token.challenge_signature);
239        assert_eq!(original_token.valid_for, parsed_token.valid_for);
240        assert_eq!(original_token.public_key, parsed_token.public_key);
241        assert_eq!(original_token.auth_signature, parsed_token.auth_signature);
242    }
243
244    #[test]
245    fn test_empty_string_parsing() {
246        let result = IronShieldToken::from_concat_struct("");
247        assert!(result.is_err());
248        assert!(result.unwrap_err().contains("Expected 4 parts, got 1"));
249    }
250
251
252    #[test]
253    fn test_from_concat_struct_error_cases() {
254        // Test with the wrong number of parts.
255        let result = IronShieldToken::from_concat_struct("only|two|parts");
256        assert!(result.is_err());
257        assert!(result.unwrap_err().contains("Expected 4 parts, got 3"));
258
259        let result = IronShieldToken::from_concat_struct("too|many|parts|here|extra");
260        assert!(result.is_err());
261        assert!(result.unwrap_err().contains("Expected 4 parts, got 5"));
262
263        // Test with invalid hex for challenge_signature.
264        let valid_32_hex = "0".repeat(64);
265        let valid_64_hex = "0".repeat(128);
266        let invalid_hex = "invalid_hex_string";
267
268        let input = format!("{}|1000000|{}|{}", invalid_hex, valid_32_hex, valid_64_hex);
269        let result = IronShieldToken::from_concat_struct(&input);
270        assert!(result.is_err());
271        assert!(result.unwrap_err().contains("Failed to decode challenge_signature hex string"));
272
273        // Test with invalid hex for public_key.
274        let input = format!("{}|1000000|{}|{}", valid_64_hex, invalid_hex, valid_64_hex);
275        let result = IronShieldToken::from_concat_struct(&input);
276        assert!(result.is_err());
277        assert!(result.unwrap_err().contains("Failed to decode public_key hex string"));
278
279        // Test with invalid hex for authentication_signature.
280        let input = format!("{}|1000000|{}|{}", valid_64_hex, valid_32_hex, invalid_hex);
281        let result = IronShieldToken::from_concat_struct(&input);
282        assert!(result.is_err());
283        assert!(result.unwrap_err().contains("Failed to decode authentication_signature hex string"));
284
285        // Test with an invalid timestamp.
286        let input = format!("{}|not_a_number|{}|{}", valid_64_hex, valid_32_hex, valid_64_hex);
287        let result = IronShieldToken::from_concat_struct(&input);
288        assert!(result.is_err());
289        assert!(result.unwrap_err().contains("Failed to parse valid_for as i64"));
290
291        // Test with wrong length hex strings.
292        let short_hex = "0".repeat(32); // Too short for a 64-byte signature.
293        let input = format!("{}|1000000|{}|{}", short_hex, valid_32_hex, valid_64_hex);
294        let result = IronShieldToken::from_concat_struct(&input);
295        assert!(result.is_err());
296        assert!(result.unwrap_err().contains("Challenge signature must be exactly 64 bytes"));
297
298        let short_32_hex = "0".repeat(32); // Too short for a 32-byte public key.
299        let input = format!("{}|1000000|{}|{}", valid_64_hex, short_32_hex, valid_64_hex);
300        let result = IronShieldToken::from_concat_struct(&input);
301        assert!(result.is_err());
302        assert!(result.unwrap_err().contains("Public key must be exactly 32 bytes"));
303    }
304}