LCOV - code coverage report
Current view: top level - libs/utils/src - auth.rs (source / functions) Coverage Total Hit
Test: 5445d246133daeceb0507e6cc0797ab7c1c70cb8.info Lines: 55.5 % 119 66
Test Date: 2025-03-12 18:05:02 Functions: 28.0 % 25 7

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

Generated by: LCOV version 2.1-beta