|
| 1 | +use crate::{ |
| 2 | + errors::* |
| 3 | +}; |
| 4 | +use serde::{Serialize, Deserialize}; |
| 5 | +use jsonwebtoken::{encode, Header, EncodingKey}; |
| 6 | +use time::{OffsetDateTime}; |
| 7 | +use serde_json::Value; |
| 8 | + |
| 9 | +#[derive(Debug, Serialize, Deserialize)] |
| 10 | +#[serde(rename_all = "camelCase")] |
| 11 | +struct TenantTokenClaim { |
| 12 | + api_key_prefix: String, |
| 13 | + search_rules: Value, |
| 14 | + #[serde(with = "time::serde::timestamp::option")] |
| 15 | + exp: Option<OffsetDateTime>, |
| 16 | +} |
| 17 | + |
| 18 | +pub fn generate_tenant_token(search_rules: Value, api_key: impl AsRef<str>, expires_at: Option<OffsetDateTime>) -> Result<String, Error> { |
| 19 | + if api_key.as_ref().chars().count() < 8 { |
| 20 | + return Err(Error::TenantTokensInvalidApiKey) |
| 21 | + } |
| 22 | + |
| 23 | + if expires_at.map_or(false, |expires_at| OffsetDateTime::now_utc() > expires_at) { |
| 24 | + return Err(Error::TenantTokensExpiredSignature) |
| 25 | + } |
| 26 | + |
| 27 | + let key_prefix = api_key.as_ref().chars().take(8).collect(); |
| 28 | + let claims = TenantTokenClaim { |
| 29 | + api_key_prefix: key_prefix, |
| 30 | + exp: expires_at, |
| 31 | + search_rules |
| 32 | + }; |
| 33 | + |
| 34 | + let token = encode( |
| 35 | + &Header::default(), |
| 36 | + &claims, |
| 37 | + &EncodingKey::from_secret(api_key.as_ref().as_bytes()), |
| 38 | + ); |
| 39 | + |
| 40 | + Ok(token?) |
| 41 | +} |
| 42 | + |
| 43 | +#[cfg(test)] |
| 44 | +mod tests { |
| 45 | + use serde_json::json; |
| 46 | + use crate::tenant_tokens::*; |
| 47 | + use jsonwebtoken::{decode, DecodingKey, Validation, Algorithm}; |
| 48 | + use std::collections::HashSet; |
| 49 | + |
| 50 | + const SEARCH_RULES: [&str; 1] = ["*"]; |
| 51 | + const VALID_KEY: &str = "a19b6ec84ee31324efa560cd1f7e6939"; |
| 52 | + |
| 53 | + fn build_validation() -> Validation { |
| 54 | + let mut validation = Validation::new(Algorithm::HS256); |
| 55 | + validation.validate_exp = false; |
| 56 | + validation.required_spec_claims = HashSet::new(); |
| 57 | + |
| 58 | + validation |
| 59 | + } |
| 60 | + |
| 61 | + #[test] |
| 62 | + fn test_generate_token_with_given_key() { |
| 63 | + let token = generate_tenant_token(json!(SEARCH_RULES), VALID_KEY, None).unwrap(); |
| 64 | + |
| 65 | + let valid_key = decode::<TenantTokenClaim>( |
| 66 | + &token, &DecodingKey::from_secret(VALID_KEY.as_ref()), &build_validation() |
| 67 | + ); |
| 68 | + let invalid_key = decode::<TenantTokenClaim>( |
| 69 | + &token, &DecodingKey::from_secret("not-the-same-key".as_ref()), &build_validation() |
| 70 | + ); |
| 71 | + |
| 72 | + assert!(valid_key.is_ok()); |
| 73 | + assert!(invalid_key.is_err()); |
| 74 | + } |
| 75 | + |
| 76 | + #[test] |
| 77 | + fn test_generate_token_without_key() { |
| 78 | + let key = String::from(""); |
| 79 | + let token = generate_tenant_token(json!(SEARCH_RULES), &key, None); |
| 80 | + |
| 81 | + assert!(token.is_err()); |
| 82 | + } |
| 83 | + |
| 84 | + #[test] |
| 85 | + fn test_generate_token_with_expiration() { |
| 86 | + let exp = OffsetDateTime::now_utc() + time::Duration::HOUR; |
| 87 | + let token = generate_tenant_token(json!(SEARCH_RULES), VALID_KEY, Some(exp)).unwrap(); |
| 88 | + |
| 89 | + let decoded = decode::<TenantTokenClaim>( |
| 90 | + &token, &DecodingKey::from_secret(VALID_KEY.as_ref()), &Validation::new(Algorithm::HS256) |
| 91 | + ); |
| 92 | + |
| 93 | + assert!(decoded.is_ok()); |
| 94 | + } |
| 95 | + |
| 96 | + #[test] |
| 97 | + fn test_generate_token_with_expires_at_in_the_past() { |
| 98 | + let exp = OffsetDateTime::now_utc() - time::Duration::HOUR; |
| 99 | + let token = generate_tenant_token(json!(SEARCH_RULES), VALID_KEY, Some(exp)); |
| 100 | + |
| 101 | + assert!(token.is_err()); |
| 102 | + } |
| 103 | + |
| 104 | + #[test] |
| 105 | + fn test_generate_token_contains_claims() { |
| 106 | + let token = generate_tenant_token(json!(SEARCH_RULES), VALID_KEY, None).unwrap(); |
| 107 | + |
| 108 | + let decoded = decode::<TenantTokenClaim>( |
| 109 | + &token, &DecodingKey::from_secret(VALID_KEY.as_ref()), &build_validation() |
| 110 | + ).expect("Cannot decode the token"); |
| 111 | + |
| 112 | + assert_eq!(decoded.claims.api_key_prefix, &VALID_KEY[..8]); |
| 113 | + assert_eq!(decoded.claims.search_rules, json!(SEARCH_RULES)); |
| 114 | + } |
| 115 | + |
| 116 | + #[test] |
| 117 | + fn test_generate_token_with_multi_byte_chars() { |
| 118 | + let key = "Ëa1ทt9bVcL-vãUทtP3OpXW5qPc%bWH5ทvw09"; |
| 119 | + let token = generate_tenant_token(json!(SEARCH_RULES), key, None).unwrap(); |
| 120 | + |
| 121 | + let decoded = decode::<TenantTokenClaim>( |
| 122 | + &token, &DecodingKey::from_secret(key.as_ref()), &build_validation() |
| 123 | + ).expect("Cannot decode the token"); |
| 124 | + |
| 125 | + assert_eq!(decoded.claims.api_key_prefix, "Ëa1ทt9bV"); |
| 126 | + } |
| 127 | +} |
0 commit comments