LCOV - code coverage report
Current view: top level - libs/utils/src - auth.rs (source / functions) Coverage Total Hit
Test: 32f4a56327bc9da697706839ed4836b2a00a408f.info Lines: 89.4 % 123 110
Test Date: 2024-02-07 07:37:29 Functions: 60.0 % 50 30

            Line data    Source code
       1              : // For details about authentication see docs/authentication.md
       2              : 
       3              : use arc_swap::ArcSwap;
       4              : use serde;
       5              : use std::{borrow::Cow, fmt::Display, fs, sync::Arc};
       6              : 
       7              : use anyhow::Result;
       8              : use camino::Utf8Path;
       9              : use jsonwebtoken::{
      10              :     decode, encode, Algorithm, DecodingKey, EncodingKey, Header, TokenData, Validation,
      11              : };
      12              : use serde::{Deserialize, Serialize};
      13              : 
      14              : use crate::{http::error::ApiError, id::TenantId};
      15              : 
      16              : /// Algorithm to use. We require EdDSA.
      17              : const STORAGE_TOKEN_ALGORITHM: Algorithm = Algorithm::EdDSA;
      18              : 
      19          804 : #[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq)]
      20              : #[serde(rename_all = "lowercase")]
      21              : pub enum Scope {
      22              :     // Provides access to all data for a specific tenant (specified in `struct Claims` below)
      23              :     // TODO: join these two?
      24              :     Tenant,
      25              :     // Provides blanket access to all tenants on the pageserver plus pageserver-wide APIs.
      26              :     // Should only be used e.g. for status check/tenant creation/list.
      27              :     PageServerApi,
      28              :     // Provides blanket access to all data on the safekeeper plus safekeeper-wide APIs.
      29              :     // Should only be used e.g. for status check.
      30              :     // Currently also used for connection from any pageserver to any safekeeper.
      31              :     SafekeeperData,
      32              : }
      33              : 
      34              : /// JWT payload. See docs/authentication.md for the format
      35         1952 : #[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
      36              : pub struct Claims {
      37              :     #[serde(default)]
      38              :     pub tenant_id: Option<TenantId>,
      39              :     pub scope: Scope,
      40              : }
      41              : 
      42              : impl Claims {
      43          184 :     pub fn new(tenant_id: Option<TenantId>, scope: Scope) -> Self {
      44          184 :         Self { tenant_id, scope }
      45          184 :     }
      46              : }
      47              : 
      48              : pub struct SwappableJwtAuth(ArcSwap<JwtAuth>);
      49              : 
      50              : impl SwappableJwtAuth {
      51           42 :     pub fn new(jwt_auth: JwtAuth) -> Self {
      52           42 :         SwappableJwtAuth(ArcSwap::new(Arc::new(jwt_auth)))
      53           42 :     }
      54            6 :     pub fn swap(&self, jwt_auth: JwtAuth) {
      55            6 :         self.0.swap(Arc::new(jwt_auth));
      56            6 :     }
      57          275 :     pub fn decode(&self, token: &str) -> std::result::Result<TokenData<Claims>, AuthError> {
      58          275 :         self.0.load().decode(token)
      59          275 :     }
      60              : }
      61              : 
      62              : impl std::fmt::Debug for SwappableJwtAuth {
      63            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
      64            0 :         write!(f, "Swappable({:?})", self.0.load())
      65            0 :     }
      66              : }
      67              : 
      68            0 : #[derive(Clone, PartialEq, Eq, Hash, Debug)]
      69              : pub struct AuthError(pub Cow<'static, str>);
      70              : 
      71              : impl Display for AuthError {
      72            3 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
      73            3 :         write!(f, "{}", self.0)
      74            3 :     }
      75              : }
      76              : 
      77              : impl From<AuthError> for ApiError {
      78            3 :     fn from(_value: AuthError) -> Self {
      79            3 :         // Don't pass on the value of the AuthError as a precautionary measure.
      80            3 :         // Being intentionally vague in public error communication hurts debugability
      81            3 :         // but it is more secure.
      82            3 :         ApiError::Forbidden("JWT authentication error".to_string())
      83            3 :     }
      84              : }
      85              : 
      86              : pub struct JwtAuth {
      87              :     decoding_keys: Vec<DecodingKey>,
      88              :     validation: Validation,
      89              : }
      90              : 
      91              : impl JwtAuth {
      92           95 :     pub fn new(decoding_keys: Vec<DecodingKey>) -> Self {
      93           95 :         let mut validation = Validation::default();
      94           95 :         validation.algorithms = vec![STORAGE_TOKEN_ALGORITHM];
      95           95 :         // The default 'required_spec_claims' is 'exp'. But we don't want to require
      96           95 :         // expiration.
      97           95 :         validation.required_spec_claims = [].into();
      98           95 :         Self {
      99           95 :             decoding_keys,
     100           95 :             validation,
     101           95 :         }
     102           95 :     }
     103              : 
     104           80 :     pub fn from_key_path(key_path: &Utf8Path) -> Result<Self> {
     105           80 :         let metadata = key_path.metadata()?;
     106           80 :         let decoding_keys = if metadata.is_dir() {
     107            2 :             let mut keys = Vec::new();
     108            3 :             for entry in fs::read_dir(key_path)? {
     109            3 :                 let path = entry?.path();
     110            3 :                 if !path.is_file() {
     111              :                     // Ignore directories (don't recurse)
     112            0 :                     continue;
     113            3 :                 }
     114            3 :                 let public_key = fs::read(path)?;
     115            3 :                 keys.push(DecodingKey::from_ed_pem(&public_key)?);
     116              :             }
     117            2 :             keys
     118           78 :         } else if metadata.is_file() {
     119           78 :             let public_key = fs::read(key_path)?;
     120           78 :             vec![DecodingKey::from_ed_pem(&public_key)?]
     121              :         } else {
     122            0 :             anyhow::bail!("path is neither a directory or a file")
     123              :         };
     124           80 :         if decoding_keys.is_empty() {
     125            0 :             anyhow::bail!("Configured for JWT auth with zero decoding keys. All JWT gated requests would be rejected.");
     126           80 :         }
     127           80 :         Ok(Self::new(decoding_keys))
     128           80 :     }
     129              : 
     130           11 :     pub fn from_key(key: String) -> Result<Self> {
     131           11 :         Ok(Self::new(vec![DecodingKey::from_ed_pem(key.as_bytes())?]))
     132           11 :     }
     133              : 
     134              :     /// Attempt to decode the token with the internal decoding keys.
     135              :     ///
     136              :     /// The function tries the stored decoding keys in succession,
     137              :     /// and returns the first yielding a successful result.
     138              :     /// If there is no working decoding key, it returns the last error.
     139          405 :     pub fn decode(&self, token: &str) -> std::result::Result<TokenData<Claims>, AuthError> {
     140          405 :         let mut res = None;
     141          410 :         for decoding_key in &self.decoding_keys {
     142          407 :             res = Some(decode(token, decoding_key, &self.validation));
     143          407 :             if let Some(Ok(res)) = res {
     144          402 :                 return Ok(res);
     145            5 :             }
     146              :         }
     147            3 :         if let Some(res) = res {
     148            3 :             res.map_err(|e| AuthError(Cow::Owned(e.to_string())))
     149              :         } else {
     150            0 :             Err(AuthError(Cow::Borrowed("no JWT decoding keys configured")))
     151              :         }
     152          405 :     }
     153              : }
     154              : 
     155              : impl std::fmt::Debug for JwtAuth {
     156            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     157            0 :         f.debug_struct("JwtAuth")
     158            0 :             .field("validation", &self.validation)
     159            0 :             .finish()
     160            0 :     }
     161              : }
     162              : 
     163              : // this function is used only for testing purposes in CLI e g generate tokens during init
     164          186 : pub fn encode_from_key_file(claims: &Claims, key_data: &[u8]) -> Result<String> {
     165          186 :     let key = EncodingKey::from_ed_pem(key_data)?;
     166          186 :     Ok(encode(&Header::new(STORAGE_TOKEN_ALGORITHM), claims, &key)?)
     167          186 : }
     168              : 
     169              : #[cfg(test)]
     170              : mod tests {
     171              :     use super::*;
     172              :     use std::str::FromStr;
     173              : 
     174              :     // Generated with:
     175              :     //
     176              :     // openssl genpkey -algorithm ed25519 -out ed25519-priv.pem
     177              :     // openssl pkey -in ed25519-priv.pem -pubout -out ed25519-pub.pem
     178              :     const TEST_PUB_KEY_ED25519: &[u8] = br#"
     179              : -----BEGIN PUBLIC KEY-----
     180              : MCowBQYDK2VwAyEARYwaNBayR+eGI0iXB4s3QxE3Nl2g1iWbr6KtLWeVD/w=
     181              : -----END PUBLIC KEY-----
     182              : "#;
     183              : 
     184              :     const TEST_PRIV_KEY_ED25519: &[u8] = br#"
     185              : -----BEGIN PRIVATE KEY-----
     186              : MC4CAQAwBQYDK2VwBCIEID/Drmc1AA6U/znNRWpF3zEGegOATQxfkdWxitcOMsIH
     187              : -----END PRIVATE KEY-----
     188              : "#;
     189              : 
     190            2 :     #[test]
     191            2 :     fn test_decode() {
     192            2 :         let expected_claims = Claims {
     193            2 :             tenant_id: Some(TenantId::from_str("3d1f7595b468230304e0b73cecbcb081").unwrap()),
     194            2 :             scope: Scope::Tenant,
     195            2 :         };
     196            2 : 
     197            2 :         // A test token containing the following payload, signed using TEST_PRIV_KEY_ED25519:
     198            2 :         //
     199            2 :         // ```
     200            2 :         // {
     201            2 :         //   "scope": "tenant",
     202            2 :         //   "tenant_id": "3d1f7595b468230304e0b73cecbcb081",
     203            2 :         //   "iss": "neon.controlplane",
     204            2 :         //   "exp": 1709200879,
     205            2 :         //   "iat": 1678442479
     206            2 :         // }
     207            2 :         // ```
     208            2 :         //
     209            2 :         let encoded_eddsa = "eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6InRlbmFudCIsInRlbmFudF9pZCI6IjNkMWY3NTk1YjQ2ODIzMDMwNGUwYjczY2VjYmNiMDgxIiwiaXNzIjoibmVvbi5jb250cm9scGxhbmUiLCJleHAiOjE3MDkyMDA4NzksImlhdCI6MTY3ODQ0MjQ3OX0.U3eA8j-uU-JnhzeO3EDHRuXLwkAUFCPxtGHEgw6p7Ccc3YRbFs2tmCdbD9PZEXP-XsxSeBQi1FY0YPcT3NXADw";
     210            2 : 
     211            2 :         // Check it can be validated with the public key
     212            2 :         let auth = JwtAuth::new(vec![DecodingKey::from_ed_pem(TEST_PUB_KEY_ED25519).unwrap()]);
     213            2 :         let claims_from_token = auth.decode(encoded_eddsa).unwrap().claims;
     214            2 :         assert_eq!(claims_from_token, expected_claims);
     215            2 :     }
     216              : 
     217            2 :     #[test]
     218            2 :     fn test_encode() {
     219            2 :         let claims = Claims {
     220            2 :             tenant_id: Some(TenantId::from_str("3d1f7595b468230304e0b73cecbcb081").unwrap()),
     221            2 :             scope: Scope::Tenant,
     222            2 :         };
     223            2 : 
     224            2 :         let encoded = encode_from_key_file(&claims, TEST_PRIV_KEY_ED25519).unwrap();
     225            2 : 
     226            2 :         // decode it back
     227            2 :         let auth = JwtAuth::new(vec![DecodingKey::from_ed_pem(TEST_PUB_KEY_ED25519).unwrap()]);
     228            2 :         let decoded = auth.decode(&encoded).unwrap();
     229            2 : 
     230            2 :         assert_eq!(decoded.claims, claims);
     231            2 :     }
     232              : }
        

Generated by: LCOV version 2.1-beta