LCOV - code coverage report
Current view: top level - libs/utils/src - auth.rs (source / functions) Coverage Total Hit
Test: b4ae4c4857f9ef3e144e982a35ee23bc84c71983.info Lines: 52.1 % 119 62
Test Date: 2024-10-22 22:13:45 Functions: 34.4 % 32 11

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

Generated by: LCOV version 2.1-beta