Skip to main content

objectstore_client/
auth.rs

1use std::collections::{BTreeMap, HashSet};
2
3use jsonwebtoken::{Algorithm, EncodingKey, Header, encode, get_current_timestamp};
4use objectstore_types::scope;
5use serde::{Deserialize, Serialize};
6
7use crate::{Scope, ScopeInner};
8
9pub use objectstore_types::auth::Permission;
10
11const DEFAULT_EXPIRY_SECONDS: u64 = 60;
12const DEFAULT_PERMISSIONS: [Permission; 3] = [
13    Permission::ObjectRead,
14    Permission::ObjectWrite,
15    Permission::ObjectDelete,
16];
17
18/// An error creating or signing an auth token, such as an invalid key.
19///
20/// The message describes the cause. The underlying signing library is an implementation detail
21/// and not part of the public API.
22#[derive(Debug, thiserror::Error)]
23#[error(transparent)]
24pub struct TokenError(jsonwebtoken::errors::Error);
25
26/// Key configuration that will be used to sign tokens in Objectstore requests.
27pub struct SecretKey {
28    /// A key ID that Objectstore must use to load the corresponding public key.
29    pub kid: String,
30
31    /// An EdDSA private key.
32    pub secret_key: String,
33}
34
35impl std::fmt::Debug for SecretKey {
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        f.debug_struct("SecretKey")
38            .field("kid", &self.kid)
39            .field("secret_key", &"[redacted]")
40            .finish()
41    }
42}
43
44/// Authentication provider for Objectstore requests.
45///
46/// Can be either a [`TokenGenerator`] that signs a fresh JWT per request,
47/// or a static pre-signed JWT string.
48pub enum TokenProvider {
49    /// A pre-signed JWT token string, used as-is for every request.
50    Static(String),
51    /// A generator that signs a fresh JWT for each request using an EdDSA keypair.
52    Generator(TokenGenerator),
53}
54
55impl std::fmt::Debug for TokenProvider {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        match self {
58            TokenProvider::Static(_) => f.write_str("TokenProvider::Static([redacted])"),
59            TokenProvider::Generator(g) => {
60                f.debug_tuple("TokenProvider::Generator").field(g).finish()
61            }
62        }
63    }
64}
65
66/// Conversion into an optional [`TokenProvider`] for [`ClientBuilder::token`].
67///
68/// This is implemented for [`TokenGenerator`], `String`, and `&str`, each of which yields a
69/// configured provider. It is also implemented for any `Option<T>` where `T: IntoTokenProvider`,
70/// so a `None` resolves to no authentication and a `Some(value)` to the inner provider. This lets
71/// callers pass optional auth configuration to [`ClientBuilder::token`] without an explicit
72/// conditional.
73///
74/// [`ClientBuilder::token`]: crate::ClientBuilder::token
75pub trait IntoTokenProvider {
76    /// Converts `self` into an optional [`TokenProvider`].
77    fn into_token_provider(self) -> Option<TokenProvider>;
78}
79
80impl<T> IntoTokenProvider for Option<T>
81where
82    T: IntoTokenProvider,
83{
84    fn into_token_provider(self) -> Option<TokenProvider> {
85        self.and_then(|t| t.into_token_provider())
86    }
87}
88
89impl IntoTokenProvider for TokenGenerator {
90    fn into_token_provider(self) -> Option<TokenProvider> {
91        Some(TokenProvider::Generator(self))
92    }
93}
94
95impl IntoTokenProvider for String {
96    fn into_token_provider(self) -> Option<TokenProvider> {
97        Some(TokenProvider::Static(self))
98    }
99}
100
101impl IntoTokenProvider for &str {
102    fn into_token_provider(self) -> Option<TokenProvider> {
103        Some(TokenProvider::Static(self.to_owned()))
104    }
105}
106
107/// A utility to generate auth tokens to be used in Objectstore requests.
108///
109/// Tokens are signed with an EdDSA private key and have certain permissions and expiry timeouts
110/// applied.
111///
112/// Use this for internal services that have access to an EdDSA keypair. A `TokenGenerator`
113/// implements [`IntoTokenProvider`], so it can be passed directly to
114/// [`ClientBuilder::token`](crate::ClientBuilder::token), where it becomes a
115/// [`TokenProvider::Generator`].
116#[derive(Debug)]
117pub struct TokenGenerator {
118    kid: String,
119    encoding_key: EncodingKey,
120    expiry_seconds: u64,
121    permissions: HashSet<Permission>,
122}
123
124#[derive(Serialize, Deserialize)]
125struct JwtRes {
126    #[serde(rename = "os:usecase")]
127    usecase: String,
128
129    #[serde(flatten)]
130    scopes: BTreeMap<String, String>,
131}
132
133#[derive(Serialize, Deserialize)]
134struct JwtClaims {
135    exp: u64,
136    permissions: HashSet<Permission>,
137    res: JwtRes,
138}
139
140impl TokenGenerator {
141    /// Create a new [`TokenGenerator`] for a given key configuration.
142    pub fn new(secret_key: SecretKey) -> crate::Result<TokenGenerator> {
143        let encoding_key =
144            EncodingKey::from_ed_pem(secret_key.secret_key.as_bytes()).map_err(TokenError)?;
145        Ok(TokenGenerator {
146            kid: secret_key.kid,
147            encoding_key,
148            expiry_seconds: DEFAULT_EXPIRY_SECONDS,
149            permissions: HashSet::from(DEFAULT_PERMISSIONS),
150        })
151    }
152
153    /// Set the expiry duration for tokens signed by this generator.
154    pub fn expiry_seconds(mut self, expiry_seconds: u64) -> Self {
155        self.expiry_seconds = expiry_seconds;
156        self
157    }
158
159    /// Set the permissions that will be granted to tokens signed by this generator.
160    pub fn permissions(mut self, permissions: &[Permission]) -> Self {
161        self.permissions = HashSet::from_iter(permissions.iter().copied());
162        self
163    }
164
165    /// Create a token for the given [`Scope`].
166    ///
167    /// Use this to produce a static token that can be handed to an external service
168    /// which then passes it to [`ClientBuilder::token`](crate::ClientBuilder::token).
169    ///
170    /// By default, the token is signed with the generator's default permissions and expiry.
171    /// Use the builder methods on the returned [`TokenRequest`] to customize them.
172    pub fn create_token<'a>(&'a self, scope: &'a Scope) -> TokenRequest<'a> {
173        TokenRequest {
174            generator: self,
175            scope: scope.0.as_ref(),
176            permissions: None,
177            expiry_seconds: None,
178        }
179    }
180
181    pub(crate) fn request_inner<'a>(&'a self, scope: &'a ScopeInner) -> TokenRequest<'a> {
182        TokenRequest {
183            generator: self,
184            scope: Ok(scope),
185            permissions: None,
186            expiry_seconds: None,
187        }
188    }
189
190    /// Resolves the permissions to embed in a token, validating that any explicitly requested
191    /// permissions are a subset of those granted to this generator.
192    fn resolve_permissions(
193        &self,
194        requested: Option<&[Permission]>,
195    ) -> crate::Result<HashSet<Permission>> {
196        let Some(requested) = requested else {
197            return Ok(self.permissions.clone());
198        };
199
200        let requested: HashSet<Permission> = requested.iter().copied().collect();
201        let mut escalated: Vec<Permission> =
202            requested.difference(&self.permissions).copied().collect();
203        if !escalated.is_empty() {
204            escalated.sort_by_key(Permission::to_string);
205            return Err(crate::Error::PermissionEscalation { escalated });
206        }
207        Ok(requested)
208    }
209}
210
211/// A request to mint a new token returned from [`TokenGenerator::create_token`].
212#[derive(Debug)]
213pub struct TokenRequest<'a> {
214    generator: &'a TokenGenerator,
215    scope: Result<&'a ScopeInner, &'a crate::Error>,
216    permissions: Option<Vec<Permission>>,
217    expiry_seconds: Option<u64>,
218}
219
220impl TokenRequest<'_> {
221    /// Override the permissions for this token, which must be a subset of the generator's
222    /// permissions.
223    pub fn permissions(mut self, permissions: &[Permission]) -> Self {
224        self.permissions = Some(permissions.to_vec());
225        self
226    }
227
228    /// Set the expiry duration for this token, overriding the generator's default.
229    pub fn expiry_seconds(mut self, expiry_seconds: u64) -> Self {
230        self.expiry_seconds = Some(expiry_seconds);
231        self
232    }
233
234    /// Finalizes and signs the token, returning the JWT string.
235    ///
236    /// # Errors
237    ///
238    /// Returns an error if the scope is invalid or the JWT cannot be signed.
239    pub fn sign(&self) -> crate::Result<String> {
240        let scope = match self.scope {
241            Ok(inner) => inner,
242            Err(crate::Error::InvalidScope(err)) => return Err(err.clone().into()),
243            // Return an ad-hoc `Unreachable` variant to avoid panicking.
244            // It should be impossible to run into a different error variant other than
245            // `InvalidScope`, unless we add a new variant and forget to update this code path.
246            _ => return Err(scope::InvalidScopeError::Unreachable.into()),
247        };
248
249        let claims = JwtClaims {
250            exp: get_current_timestamp()
251                + self.expiry_seconds.unwrap_or(self.generator.expiry_seconds),
252            permissions: self
253                .generator
254                .resolve_permissions(self.permissions.as_deref())?,
255            res: JwtRes {
256                usecase: scope.usecase().name().into(),
257                scopes: scope
258                    .scopes()
259                    .iter()
260                    .map(|scope| (scope.name().to_string(), scope.value().to_string()))
261                    .collect(),
262            },
263        };
264
265        let mut header = Header::new(Algorithm::EdDSA);
266        header.kid = Some(self.generator.kid.clone());
267
268        let token = encode(&header, &claims, &self.generator.encoding_key).map_err(TokenError)?;
269        Ok(token)
270    }
271}