From aaac8af01db8d12dc21cb5280d49bd2bf3b327f8 Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Thu, 16 Apr 2026 15:59:23 +0200 Subject: [PATCH 1/2] feat(clients): Add permission and expiry overrides to Session.mint_token Allow callers to mint tokens with a subset of the session's permissions and/or a custom expiry, so they can hand out restricted tokens to downstream consumers. Rust client: - `Session::mint_token()` returns a `MintTokenBuilder` (with deferred error via internal `Result`, matching `ClientBuilder` pattern). - Builder exposes `.permissions()` and `.expiry_seconds()` setters. - `.mint()` terminal method surfaces any accumulated errors. - New error variants: `NoTokenGenerator`, `PermissionEscalation`. Python client: - `Session.mint_token(permissions=..., expiry_seconds=...)` with optional overrides. - Raises `ValueError` when no `TokenGenerator` is configured or when requested permissions exceed the generator's configured set. Both clients now use a separate internal method for auth headers, keeping `mint_token` as a public API exclusively for producing restricted tokens. --- clients/python/src/objectstore_client/auth.py | 38 ++++++-- .../python/src/objectstore_client/client.py | 34 ++++++- clients/rust/src/auth.rs | 30 +++++- clients/rust/src/client.rs | 96 ++++++++++++++++++- clients/rust/src/error.rs | 8 ++ 5 files changed, 186 insertions(+), 20 deletions(-) diff --git a/clients/python/src/objectstore_client/auth.py b/clients/python/src/objectstore_client/auth.py index 0343985e..4afc2315 100644 --- a/clients/python/src/objectstore_client/auth.py +++ b/clients/python/src/objectstore_client/auth.py @@ -42,23 +42,49 @@ def __init__( self.expiry_seconds = expiry_seconds self.permissions = permissions if permissions is not None else Permission.max() - def sign_for_scope(self, usecase: str, scope: Scope) -> str: + def sign_for_scope( + self, + usecase: str, + scope: Scope, + permissions: list[Permission] | None = None, + expiry_seconds: int | None = None, + ) -> str: """ Sign a JWT for the passed-in usecase and scope using the configured key information, expiry, and permissions. - The JWT is signed using EdDSA, so `self.secret_key` must be an EdDSA private - key. `self.kid` is used by the Objectstore server to load the corresponding - public key from its configuration. + When ``permissions`` is ``None``, the generator's default permissions are + used. When provided, they override the defaults for this token only. + + When ``expiry_seconds`` is ``None``, the generator's default expiry is + used. + + Raises ``ValueError`` if any requested permission is not granted to + this generator. + + The JWT is signed using EdDSA, so ``self.secret_key`` must be an EdDSA + private key. ``self.kid`` is used by the Objectstore server to load the + corresponding public key from its configuration. """ + if permissions is not None: + escalated = set(permissions) - set(self.permissions) + if escalated: + raise ValueError( + "requested permissions not granted to this " + f"token generator: {sorted(escalated)}" + ) + headers = {"kid": self.kid} + expiry = expiry_seconds if expiry_seconds is not None else self.expiry_seconds claims = { "res": { "os:usecase": usecase, **{k: str(v) for k, v in scope.dict().items()}, }, - "permissions": self.permissions, - "exp": datetime.now(tz=UTC) + timedelta(seconds=self.expiry_seconds), + "permissions": ( + permissions if permissions is not None else self.permissions + ), + "exp": datetime.now(tz=UTC) + timedelta(seconds=expiry), } return jwt.encode(claims, self.secret_key, algorithm="EdDSA", headers=headers) diff --git a/clients/python/src/objectstore_client/client.py b/clients/python/src/objectstore_client/client.py index 02b735cc..74f18243 100644 --- a/clients/python/src/objectstore_client/client.py +++ b/clients/python/src/objectstore_client/client.py @@ -12,7 +12,7 @@ from urllib3.connectionpool import HTTPConnectionPool from objectstore_client import utils -from objectstore_client.auth import TokenGenerator, TokenProvider +from objectstore_client.auth import Permission, TokenGenerator, TokenProvider from objectstore_client.metadata import ( HEADER_EXPIRATION, HEADER_META_PREFIX, @@ -228,10 +228,36 @@ def __init__( self._scope = scope self._token = token - def mint_token(self) -> str | None: + def mint_token( + self, + permissions: list[Permission] | None = None, + expiry_seconds: int | None = None, + ) -> str: """ - Returns a signed token if a token or generator was provided or `None` otherwise. + Returns a signed token. + + When ``permissions`` is ``None``, the generator's default + permissions are used. When provided, they must be a subset of + the generator's permissions. + + When ``expiry_seconds`` is ``None``, the generator's default + expiry is used. + + Raises ``ValueError`` if no ``TokenGenerator`` is configured + or if any requested permission is not granted to the + generator. """ + if not isinstance(self._token, TokenGenerator): + raise ValueError("no token generator configured on this session") + return self._token.sign_for_scope( + self._usecase.name, + self._scope, + permissions, + expiry_seconds, + ) + + def _auth_token(self) -> str | None: + """Returns a token for internal auth headers.""" if isinstance(self._token, TokenGenerator): return self._token.sign_for_scope(self._usecase.name, self._scope) elif isinstance(self._token, str): @@ -244,7 +270,7 @@ def _make_headers(self) -> dict[str, str]: headers.update( dict(sentry_sdk.get_current_scope().iter_trace_propagation_headers()) ) - if token := self.mint_token(): + if token := self._auth_token(): headers["x-os-auth"] = f"Bearer {token}" return headers diff --git a/clients/rust/src/auth.rs b/clients/rust/src/auth.rs index 13b29077..5a19eea5 100644 --- a/clients/rust/src/auth.rs +++ b/clients/rust/src/auth.rs @@ -129,11 +129,18 @@ impl TokenGenerator { self } + /// Returns the permissions configured on this generator. + pub(crate) fn configured_permissions(&self) -> &HashSet { + &self.permissions + } + /// Sign a token for the given [`Scope`](crate::Scope), returning the JWT string. /// /// Use this to produce a static token that can be handed to an external service /// which then passes it to [`ClientBuilder::token`](crate::ClientBuilder::token). /// + /// The token is signed using the generator's configured permissions and expiry. + /// /// # Errors /// /// Returns an error if the scope is invalid or the JWT cannot be signed. @@ -148,14 +155,27 @@ impl TokenGenerator { // `InvalidScope`, unless we add a new variant and forget to update this code path. _ => return Err(scope::InvalidScopeError::Unreachable.into()), }; - self.sign_for_scope(scope) + self.sign_for_scope(scope, None, None) } - /// Sign a new token for the passed-in scope using the configured expiry and permissions. - pub(crate) fn sign_for_scope(&self, scope: &ScopeInner) -> crate::Result { + /// Sign a new token for the passed-in scope. + /// + /// Optional overrides for `permissions` and `expiry_seconds` can be provided. + /// When `None`, the generator's configured defaults are used. + pub(crate) fn sign_for_scope( + &self, + scope: &ScopeInner, + permissions: Option<&[Permission]>, + expiry_seconds: Option, + ) -> crate::Result { + let permissions = match permissions { + Some(p) => p.iter().copied().collect(), + None => self.permissions.clone(), + }; + let expiry_seconds = expiry_seconds.unwrap_or(self.expiry_seconds); let claims = JwtClaims { - exp: get_current_timestamp() + self.expiry_seconds, - permissions: self.permissions.clone(), + exp: get_current_timestamp() + expiry_seconds, + permissions, res: JwtRes { usecase: scope.usecase().name().into(), scopes: scope diff --git a/clients/rust/src/client.rs b/clients/rust/src/client.rs index 2d4eced4..e2c21b75 100644 --- a/clients/rust/src/client.rs +++ b/clients/rust/src/client.rs @@ -1,3 +1,4 @@ +use std::collections::HashSet; use std::io; use std::sync::Arc; use std::time::Duration; @@ -9,7 +10,7 @@ use objectstore_types::scope; use reqwest::RequestBuilder; use url::Url; -use crate::auth::TokenProvider; +use crate::auth::{Permission, TokenGenerator, TokenProvider}; const USER_AGENT: &str = concat!("objectstore-client/", env!("CARGO_PKG_VERSION")); @@ -436,11 +437,30 @@ impl Session { url } - /// Returns a signed token if a token or generator was provided or `None` otherwise - pub fn mint_token(&self) -> crate::Result> { + /// Returns a [`MintTokenBuilder`] that can be used to produce a signed token with + /// optional permission and expiry overrides. + /// + /// If this session was not configured with a [`TokenGenerator`], + /// [`MintTokenBuilder::mint`] will return an error. + pub fn mint_token(&self) -> MintTokenBuilder<'_> { + match &self.client.token { + Some(TokenProvider::Generator(generator)) => { + MintTokenBuilder(Ok(MintTokenBuilderInner { + generator, + scope: &self.scope, + permissions: None, + expiry_seconds: None, + })) + } + _ => MintTokenBuilder(Err(crate::Error::NoTokenGenerator)), + } + } + + /// Returns a signed token for internal use (auth headers). + fn auth_token(&self) -> crate::Result> { match &self.client.token { Some(TokenProvider::Generator(generator)) => { - Ok(Some(generator.sign_for_scope(&self.scope)?)) + Ok(Some(generator.sign_for_scope(&self.scope, None, None)?)) } Some(TokenProvider::Static(token)) => Ok(Some(token.clone())), None => Ok(None), @@ -465,7 +485,7 @@ impl Session { } fn prepare_builder(&self, mut builder: RequestBuilder) -> crate::Result { - if let Some(token) = self.mint_token()? { + if let Some(token) = self.auth_token()? { builder = builder.header("x-os-auth", format!("Bearer {token}")); } if self.client.propagate_traces { @@ -495,6 +515,72 @@ impl Session { } } +/// A builder for minting tokens with optional permission and expiry overrides. +/// +/// Obtained from [`Session::mint_token`]. +/// +/// Errors (such as requesting permissions not granted to the generator) are +/// accumulated internally and surfaced when [`mint`](Self::mint) is called, +/// following the same pattern as [`ClientBuilder`]. +#[derive(Debug)] +pub struct MintTokenBuilder<'a>(crate::Result>); + +#[derive(Debug)] +struct MintTokenBuilderInner<'a> { + generator: &'a TokenGenerator, + scope: &'a ScopeInner, + permissions: Option>, + expiry_seconds: Option, +} + +impl MintTokenBuilder<'_> { + /// Override the permissions for this token. + /// + /// The provided permissions must be a subset of the generator's configured + /// permissions. If any permission is not granted to the generator, + /// [`mint`](Self::mint) will return an + /// [`Error::PermissionEscalation`](crate::Error::PermissionEscalation) error. + pub fn permissions(mut self, permissions: &[Permission]) -> Self { + let Ok(ref mut inner) = self.0 else { + return self; + }; + let requested: HashSet = permissions.iter().copied().collect(); + let escalated: Vec<_> = requested + .difference(inner.generator.configured_permissions()) + .copied() + .collect(); + if !escalated.is_empty() { + self.0 = Err(crate::Error::PermissionEscalation(escalated)); + return self; + } + inner.permissions = Some(permissions.to_vec()); + self + } + + /// Override the expiry duration for this token. + pub fn expiry_seconds(mut self, expiry_seconds: u64) -> Self { + if let Ok(ref mut inner) = self.0 { + inner.expiry_seconds = Some(expiry_seconds); + } + self + } + + /// Mint the token, returning the signed JWT string. + /// + /// # Errors + /// + /// Returns an error if the requested permissions exceed the generator's + /// configured permissions, or if signing fails. + pub fn mint(self) -> crate::Result { + let inner = self.0?; + inner.generator.sign_for_scope( + inner.scope, + inner.permissions.as_deref(), + inner.expiry_seconds, + ) + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/clients/rust/src/error.rs b/clients/rust/src/error.rs index 098bb79a..8943afe6 100644 --- a/clients/rust/src/error.rs +++ b/clients/rust/src/error.rs @@ -1,5 +1,7 @@ use std::sync::Arc; +use objectstore_types::auth::Permission; + /// Errors that can happen within the objectstore-client #[derive(Debug, thiserror::Error)] pub enum Error { @@ -21,6 +23,12 @@ pub enum Error { /// Error when creating auth tokens, such as invalid keys. #[error(transparent)] TokenError(#[from] jsonwebtoken::errors::Error), + /// Error when trying to mint a token without a [`TokenGenerator`](crate::TokenGenerator). + #[error("no token generator configured on this session")] + NoTokenGenerator, + /// Error when minting a token with permissions not granted to the generator. + #[error("requested permissions not granted to this token generator: {0:?}")] + PermissionEscalation(Vec), /// Error when URL manipulation fails. #[error("{message}")] InvalidUrl { From 7a0271b8714d11328a0f69d4b98e1c57cbdbd364 Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Mon, 4 May 2026 17:04:59 +0200 Subject: [PATCH 2/2] revert rust changes --- clients/rust/src/auth.rs | 30 ++---------- clients/rust/src/client.rs | 96 ++------------------------------------ clients/rust/src/error.rs | 8 ---- 3 files changed, 10 insertions(+), 124 deletions(-) diff --git a/clients/rust/src/auth.rs b/clients/rust/src/auth.rs index 5a19eea5..13b29077 100644 --- a/clients/rust/src/auth.rs +++ b/clients/rust/src/auth.rs @@ -129,18 +129,11 @@ impl TokenGenerator { self } - /// Returns the permissions configured on this generator. - pub(crate) fn configured_permissions(&self) -> &HashSet { - &self.permissions - } - /// Sign a token for the given [`Scope`](crate::Scope), returning the JWT string. /// /// Use this to produce a static token that can be handed to an external service /// which then passes it to [`ClientBuilder::token`](crate::ClientBuilder::token). /// - /// The token is signed using the generator's configured permissions and expiry. - /// /// # Errors /// /// Returns an error if the scope is invalid or the JWT cannot be signed. @@ -155,27 +148,14 @@ impl TokenGenerator { // `InvalidScope`, unless we add a new variant and forget to update this code path. _ => return Err(scope::InvalidScopeError::Unreachable.into()), }; - self.sign_for_scope(scope, None, None) + self.sign_for_scope(scope) } - /// Sign a new token for the passed-in scope. - /// - /// Optional overrides for `permissions` and `expiry_seconds` can be provided. - /// When `None`, the generator's configured defaults are used. - pub(crate) fn sign_for_scope( - &self, - scope: &ScopeInner, - permissions: Option<&[Permission]>, - expiry_seconds: Option, - ) -> crate::Result { - let permissions = match permissions { - Some(p) => p.iter().copied().collect(), - None => self.permissions.clone(), - }; - let expiry_seconds = expiry_seconds.unwrap_or(self.expiry_seconds); + /// Sign a new token for the passed-in scope using the configured expiry and permissions. + pub(crate) fn sign_for_scope(&self, scope: &ScopeInner) -> crate::Result { let claims = JwtClaims { - exp: get_current_timestamp() + expiry_seconds, - permissions, + exp: get_current_timestamp() + self.expiry_seconds, + permissions: self.permissions.clone(), res: JwtRes { usecase: scope.usecase().name().into(), scopes: scope diff --git a/clients/rust/src/client.rs b/clients/rust/src/client.rs index e2c21b75..2d4eced4 100644 --- a/clients/rust/src/client.rs +++ b/clients/rust/src/client.rs @@ -1,4 +1,3 @@ -use std::collections::HashSet; use std::io; use std::sync::Arc; use std::time::Duration; @@ -10,7 +9,7 @@ use objectstore_types::scope; use reqwest::RequestBuilder; use url::Url; -use crate::auth::{Permission, TokenGenerator, TokenProvider}; +use crate::auth::TokenProvider; const USER_AGENT: &str = concat!("objectstore-client/", env!("CARGO_PKG_VERSION")); @@ -437,30 +436,11 @@ impl Session { url } - /// Returns a [`MintTokenBuilder`] that can be used to produce a signed token with - /// optional permission and expiry overrides. - /// - /// If this session was not configured with a [`TokenGenerator`], - /// [`MintTokenBuilder::mint`] will return an error. - pub fn mint_token(&self) -> MintTokenBuilder<'_> { - match &self.client.token { - Some(TokenProvider::Generator(generator)) => { - MintTokenBuilder(Ok(MintTokenBuilderInner { - generator, - scope: &self.scope, - permissions: None, - expiry_seconds: None, - })) - } - _ => MintTokenBuilder(Err(crate::Error::NoTokenGenerator)), - } - } - - /// Returns a signed token for internal use (auth headers). - fn auth_token(&self) -> crate::Result> { + /// Returns a signed token if a token or generator was provided or `None` otherwise + pub fn mint_token(&self) -> crate::Result> { match &self.client.token { Some(TokenProvider::Generator(generator)) => { - Ok(Some(generator.sign_for_scope(&self.scope, None, None)?)) + Ok(Some(generator.sign_for_scope(&self.scope)?)) } Some(TokenProvider::Static(token)) => Ok(Some(token.clone())), None => Ok(None), @@ -485,7 +465,7 @@ impl Session { } fn prepare_builder(&self, mut builder: RequestBuilder) -> crate::Result { - if let Some(token) = self.auth_token()? { + if let Some(token) = self.mint_token()? { builder = builder.header("x-os-auth", format!("Bearer {token}")); } if self.client.propagate_traces { @@ -515,72 +495,6 @@ impl Session { } } -/// A builder for minting tokens with optional permission and expiry overrides. -/// -/// Obtained from [`Session::mint_token`]. -/// -/// Errors (such as requesting permissions not granted to the generator) are -/// accumulated internally and surfaced when [`mint`](Self::mint) is called, -/// following the same pattern as [`ClientBuilder`]. -#[derive(Debug)] -pub struct MintTokenBuilder<'a>(crate::Result>); - -#[derive(Debug)] -struct MintTokenBuilderInner<'a> { - generator: &'a TokenGenerator, - scope: &'a ScopeInner, - permissions: Option>, - expiry_seconds: Option, -} - -impl MintTokenBuilder<'_> { - /// Override the permissions for this token. - /// - /// The provided permissions must be a subset of the generator's configured - /// permissions. If any permission is not granted to the generator, - /// [`mint`](Self::mint) will return an - /// [`Error::PermissionEscalation`](crate::Error::PermissionEscalation) error. - pub fn permissions(mut self, permissions: &[Permission]) -> Self { - let Ok(ref mut inner) = self.0 else { - return self; - }; - let requested: HashSet = permissions.iter().copied().collect(); - let escalated: Vec<_> = requested - .difference(inner.generator.configured_permissions()) - .copied() - .collect(); - if !escalated.is_empty() { - self.0 = Err(crate::Error::PermissionEscalation(escalated)); - return self; - } - inner.permissions = Some(permissions.to_vec()); - self - } - - /// Override the expiry duration for this token. - pub fn expiry_seconds(mut self, expiry_seconds: u64) -> Self { - if let Ok(ref mut inner) = self.0 { - inner.expiry_seconds = Some(expiry_seconds); - } - self - } - - /// Mint the token, returning the signed JWT string. - /// - /// # Errors - /// - /// Returns an error if the requested permissions exceed the generator's - /// configured permissions, or if signing fails. - pub fn mint(self) -> crate::Result { - let inner = self.0?; - inner.generator.sign_for_scope( - inner.scope, - inner.permissions.as_deref(), - inner.expiry_seconds, - ) - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/clients/rust/src/error.rs b/clients/rust/src/error.rs index 8943afe6..098bb79a 100644 --- a/clients/rust/src/error.rs +++ b/clients/rust/src/error.rs @@ -1,7 +1,5 @@ use std::sync::Arc; -use objectstore_types::auth::Permission; - /// Errors that can happen within the objectstore-client #[derive(Debug, thiserror::Error)] pub enum Error { @@ -23,12 +21,6 @@ pub enum Error { /// Error when creating auth tokens, such as invalid keys. #[error(transparent)] TokenError(#[from] jsonwebtoken::errors::Error), - /// Error when trying to mint a token without a [`TokenGenerator`](crate::TokenGenerator). - #[error("no token generator configured on this session")] - NoTokenGenerator, - /// Error when minting a token with permissions not granted to the generator. - #[error("requested permissions not granted to this token generator: {0:?}")] - PermissionEscalation(Vec), /// Error when URL manipulation fails. #[error("{message}")] InvalidUrl {