Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 9 additions & 17 deletions clients/rust/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -273,34 +273,26 @@ session
If your Objectstore instance enforces authorization, you must configure authentication
via [`ClientBuilder::token`]. It accepts either:

- A **[`TokenGenerator`]** — for internal services that have access to an EdDSA keypair.
The generator signs a fresh JWT for each request, scoped to the specific usecase
- A **[`SecretKey`]** — for internal services that have access to an EdDSA keypair.
The key signs a fresh JWT for each request, scoped to the specific usecase
and scope being accessed.
- A **`String` / `&str`** — a pre-signed JWT, used as-is for every request.
Use this for external services that receive a token from another source.
- An `Option` of any of the above — useful for chained builder calls.

```rust,ignore
use objectstore_client::{Client, SecretKey, TokenGenerator, Usecase};
use objectstore_client::{Client, SecretKey, Usecase};

// Option 1: Internal service with a keypair
let client = Client::builder("http://localhost:8888/")
.token(
TokenGenerator::new(SecretKey {
secret_key: "<private key>".into(),
kid: "my-service".into(),
})?
)
.token(SecretKey::new("my-service", "<private key>")?)
.build()?;

// Option 2: External service with a pre-signed JWT
// Use TokenGenerator::create_token() to obtain a static token from an authority
// Use SecretKey::create_token() to obtain a static token from an authority
let scope = Usecase::new("my_app").for_project(42, 1337);
let generator = TokenGenerator::new(SecretKey {
secret_key: "<private key>".into(),
kid: "my-service".into(),
})?;
let token = generator.create_token(&scope).sign()?;
let secret_key = SecretKey::new("my-service", "<private key>")?;
let token = secret_key.create_token(&scope).sign()?;

// Then pass the token directly to a client builder.
let client = Client::builder("http://localhost:8888/")
Expand All @@ -326,7 +318,7 @@ static CLIENT: LazyLock<Client> = LazyLock::new(|| {
// .propagate_traces(true) // default: false
// .timeout(Duration::from_secs(5)) // default: no read timeout (connect: 100ms)
// .configure_reqwest(|builder| { ... }) // customize the reqwest::ClientBuilder
// .token(token_generator) // see Authentication section
// .token(secret_key) // see Authentication section
.build()
.expect("Objectstore client to build successfully")
});
Expand All @@ -344,7 +336,7 @@ async fn example() -> Result<()> {
```

See [`ClientBuilder`] for all available options, including authentication via
[`TokenGenerator`].
[`SecretKey`].

See the [API docs](https://getsentry.github.io/objectstore/rust/objectstore_client/) for full reference documentation.

Expand Down
96 changes: 41 additions & 55 deletions clients/rust/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,49 +15,32 @@ const DEFAULT_PERMISSIONS: [Permission; 3] = [
Permission::ObjectDelete,
];

/// Key configuration that will be used to sign tokens in Objectstore requests.
pub struct SecretKey {
/// A key ID that Objectstore must use to load the corresponding public key.
pub kid: String,

/// An EdDSA private key.
pub secret_key: String,
}

impl std::fmt::Debug for SecretKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SecretKey")
.field("kid", &self.kid)
.field("secret_key", &"[redacted]")
.finish()
}
}

/// Authentication provider for Objectstore requests.
///
/// Can be either a [`TokenGenerator`] that signs a fresh JWT per request,
/// Can be either a [`SecretKey`] that signs a fresh JWT per request,
/// or a static pre-signed JWT string.
pub enum TokenProvider {
/// A pre-signed JWT token string, used as-is for every request.
Static(String),
/// A generator that signs a fresh JWT for each request using an EdDSA keypair.
Generator(TokenGenerator),
/// A secret key that signs a fresh JWT for each request using an EdDSA keypair.
SecretKey(SecretKey),
}

impl std::fmt::Debug for TokenProvider {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TokenProvider::Static(_) => f.write_str("TokenProvider::Static([redacted])"),
TokenProvider::Generator(g) => {
f.debug_tuple("TokenProvider::Generator").field(g).finish()
}
TokenProvider::SecretKey(key) => f
.debug_tuple("TokenProvider::SecretKey")
.field(key)
.finish(),
}
}
}

/// Conversion into an optional [`TokenProvider`] for [`ClientBuilder::token`].
///
/// This is implemented for [`TokenGenerator`], `String`, and `&str`, each of which yields a
/// This is implemented for [`SecretKey`], `String`, and `&str`, each of which yields a
/// configured provider. It is also implemented for any `Option<T>` where `T: IntoTokenProvider`,
/// so a `None` resolves to no authentication and a `Some(value)` to the inner provider. This lets
/// callers pass optional auth configuration to [`ClientBuilder::token`] without an explicit
Expand All @@ -78,9 +61,9 @@ where
}
}

impl IntoTokenProvider for TokenGenerator {
impl IntoTokenProvider for SecretKey {
fn into_token_provider(self) -> Option<TokenProvider> {
Some(TokenProvider::Generator(self))
Some(TokenProvider::SecretKey(self))
}
}

Expand All @@ -96,17 +79,17 @@ impl IntoTokenProvider for &str {
}
}

/// A utility to generate auth tokens to be used in Objectstore requests.
/// An EdDSA keypair used to sign auth tokens for Objectstore requests.
///
/// Tokens are signed with an EdDSA private key and have certain permissions and expiry timeouts
/// Tokens are signed with the private key and have certain permissions and expiry timeouts
/// applied.
///
/// Use this for internal services that have access to an EdDSA keypair. A `TokenGenerator`
/// Use this for internal services that have access to an EdDSA keypair. A `SecretKey`
/// implements [`IntoTokenProvider`], so it can be passed directly to
/// [`ClientBuilder::token`](crate::ClientBuilder::token), where it becomes a
/// [`TokenProvider::Generator`].
/// [`TokenProvider::SecretKey`].
#[derive(Debug)]
pub struct TokenGenerator {
pub struct SecretKey {
kid: String,
encoding_key: EncodingKey,
expiry_seconds: u64,
Expand All @@ -129,25 +112,31 @@ struct JwtClaims {
res: JwtRes,
}

impl TokenGenerator {
/// Create a new [`TokenGenerator`] for a given key configuration.
pub fn new(secret_key: SecretKey) -> crate::Result<TokenGenerator> {
let encoding_key = EncodingKey::from_ed_pem(secret_key.secret_key.as_bytes())?;
Ok(TokenGenerator {
kid: secret_key.kid,
impl SecretKey {
/// Creates a new [`SecretKey`] from a key ID and a PEM-encoded EdDSA private key.
///
/// `kid` is the key ID that Objectstore uses to load the corresponding public key.
///
/// # Errors
///
/// Returns an error if `secret_key` is not a valid PEM-encoded EdDSA private key.
pub fn new(kid: impl Into<String>, secret_key: &str) -> crate::Result<SecretKey> {
let encoding_key = EncodingKey::from_ed_pem(secret_key.as_bytes())?;
Ok(SecretKey {
kid: kid.into(),
encoding_key,
expiry_seconds: DEFAULT_EXPIRY_SECONDS,
permissions: HashSet::from(DEFAULT_PERMISSIONS),
})
}

/// Set the expiry duration for tokens signed by this generator.
/// Set the expiry duration for tokens signed by this key.
pub fn expiry_seconds(mut self, expiry_seconds: u64) -> Self {
self.expiry_seconds = expiry_seconds;
self
}

/// Set the permissions that will be granted to tokens signed by this generator.
/// Set the permissions that will be granted to tokens signed by this key.
pub fn permissions(mut self, permissions: &[Permission]) -> Self {
self.permissions = HashSet::from_iter(permissions.iter().copied());
self
Expand All @@ -158,11 +147,11 @@ impl TokenGenerator {
/// 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).
///
/// By default, the token is signed with the generator's default permissions and expiry.
/// By default, the token is signed with the key's default permissions and expiry.
/// Use the builder methods on the returned [`TokenRequest`] to customize them.
pub fn create_token<'a>(&'a self, scope: &'a Scope) -> TokenRequest<'a> {
TokenRequest {
generator: self,
key: self,
scope: scope.0.as_ref(),
permissions: None,
expiry_seconds: None,
Expand All @@ -171,15 +160,15 @@ impl TokenGenerator {

pub(crate) fn request_inner<'a>(&'a self, scope: &'a ScopeInner) -> TokenRequest<'a> {
TokenRequest {
generator: self,
key: self,
scope: Ok(scope),
permissions: None,
expiry_seconds: None,
}
}

/// Resolves the permissions to embed in a token, validating that any explicitly requested
/// permissions are a subset of those granted to this generator.
/// permissions are a subset of those granted to this key.
fn resolve_permissions(
&self,
requested: Option<&[Permission]>,
Expand All @@ -199,24 +188,24 @@ impl TokenGenerator {
}
}

/// A request to mint a new token returned from [`TokenGenerator::create_token`].
/// A request to mint a new token returned from [`SecretKey::create_token`].
#[derive(Debug)]
pub struct TokenRequest<'a> {
generator: &'a TokenGenerator,
key: &'a SecretKey,
scope: Result<&'a ScopeInner, &'a crate::Error>,
permissions: Option<Vec<Permission>>,
expiry_seconds: Option<u64>,
}

impl TokenRequest<'_> {
/// Override the permissions for this token, which must be a subset of the generator's
/// Override the permissions for this token, which must be a subset of the key's
/// permissions.
pub fn permissions(mut self, permissions: &[Permission]) -> Self {
self.permissions = Some(permissions.to_vec());
self
}

/// Set the expiry duration for this token, overriding the generator's default.
/// Set the expiry duration for this token, overriding the key's default.
pub fn expiry_seconds(mut self, expiry_seconds: u64) -> Self {
self.expiry_seconds = Some(expiry_seconds);
self
Expand All @@ -238,11 +227,8 @@ impl TokenRequest<'_> {
};

let claims = JwtClaims {
exp: get_current_timestamp()
+ self.expiry_seconds.unwrap_or(self.generator.expiry_seconds),
permissions: self
.generator
.resolve_permissions(self.permissions.as_deref())?,
exp: get_current_timestamp() + self.expiry_seconds.unwrap_or(self.key.expiry_seconds),
permissions: self.key.resolve_permissions(self.permissions.as_deref())?,
res: JwtRes {
usecase: scope.usecase().name().into(),
scopes: scope
Expand All @@ -254,8 +240,8 @@ impl TokenRequest<'_> {
};

let mut header = Header::new(Algorithm::EdDSA);
header.kid = Some(self.generator.kid.clone());
header.kid = Some(self.key.kid.clone());

Ok(encode(&header, &claims, &self.generator.encoding_key)?)
Ok(encode(&header, &claims, &self.key.encoding_key)?)
}
}
40 changes: 17 additions & 23 deletions clients/rust/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,8 @@ impl ClientBuilder {
/// Sets the authentication token to use for requests to Objectstore.
///
/// Accepts anything that implements [`IntoTokenProvider`]:
/// - A [`TokenGenerator`](crate::TokenGenerator) — for internal services that have access to
/// an EdDSA keypair. The generator signs a fresh JWT for each request.
/// - A [`SecretKey`](crate::SecretKey) — for internal services that have access to
/// an EdDSA keypair. The key signs a fresh JWT for each request.
/// - A `String` or `&str` — a pre-signed JWT, used as-is for every request.
/// - An `Option` of any of the above — a `None` leaves the client unauthenticated, which is
/// convenient when authentication is configured conditionally.
Expand Down Expand Up @@ -340,8 +340,8 @@ pub(crate) struct ClientInner {
/// authentication via [`ClientBuilder::token`]. It accepts anything that converts
/// into a [`TokenProvider`]:
///
/// - **[`TokenGenerator`](crate::TokenGenerator)** — for internal services that have access to
/// an EdDSA keypair. The generator signs a fresh JWT for each request, scoped to the
/// - **[`SecretKey`](crate::SecretKey)** — for internal services that have access to
/// an EdDSA keypair. The key signs a fresh JWT for each request, scoped to the
/// specific usecase and scope being accessed.
/// - **`String` / `&str`** — a pre-signed JWT, used as-is for every request.
/// Use this for external services that receive a token from another source.
Expand All @@ -352,38 +352,34 @@ pub(crate) struct ClientInner {
///
/// ```no_run
/// use std::time::Duration;
/// use objectstore_client::{Client, SecretKey, TokenGenerator, Usecase};
/// use objectstore_client::{Client, SecretKey, Usecase};
/// use objectstore_types::auth::Permission;
///
/// # async fn example() -> objectstore_client::Result<()> {
/// let token_generator = TokenGenerator::new(SecretKey {
/// secret_key: "<safely inject secret key>".into(),
/// kid: "my-service".into(),
/// })?
/// let secret_key = SecretKey::new("my-service", "<safely inject secret key>")?
/// .expiry_seconds(30)
/// .permissions(&[Permission::ObjectRead]);
///
/// let client = Client::builder("http://localhost:8888/")
/// .timeout(Duration::from_secs(1))
/// .propagate_traces(true)
/// .token(token_generator)
/// .token(secret_key)
/// .build()?;
/// # Ok(())
/// # }
/// ```
///
/// External service with a pre-signed JWT (obtained via
/// [`TokenGenerator::create_token`](crate::TokenGenerator::create_token)):
/// [`SecretKey::create_token`](crate::SecretKey::create_token)):
///
/// ```no_run
/// use objectstore_client::{Client, SecretKey, TokenGenerator, Usecase};
/// use objectstore_client::{Client, SecretKey, Usecase};
///
/// # fn example() -> objectstore_client::Result<()> {
/// let scope = Usecase::new("my_app").for_project(42, 1337);
/// let token = TokenGenerator::new(SecretKey {
/// secret_key: "<private key>".into(),
/// kid: "my-service".into(),
/// })?.create_token(&scope).sign()?;
/// let token = SecretKey::new("my-service", "<private key>")?
/// .create_token(&scope)
/// .sign()?;
///
/// let client = Client::builder("http://localhost:8888/")
/// .token(token)
Expand Down Expand Up @@ -481,7 +477,7 @@ impl Session {

/// Returns a token authorizing access to this session's scope.
///
/// With a [`TokenGenerator`](crate::TokenGenerator), each call signs a fresh token whose expiry
/// With a [`SecretKey`](crate::SecretKey), each call signs a fresh token whose expiry
/// starts now, using the configured permissions; use [`create_token`](Self::create_token) to
/// narrow either.
///
Expand All @@ -496,8 +492,8 @@ impl Session {
/// pre-signed token never fails.
pub fn get_token(&self) -> crate::Result<Option<String>> {
match self.client.token {
Some(TokenProvider::Generator(ref generator)) => {
generator.request_inner(&self.scope).sign().map(Some)
Some(TokenProvider::SecretKey(ref key)) => {
key.request_inner(&self.scope).sign().map(Some)
}
Some(TokenProvider::Static(ref token)) => Ok(Some(token.clone())),
None => Ok(None),
Expand All @@ -517,14 +513,12 @@ impl Session {
///
/// # Errors
///
/// This requires a [`TokenGenerator`](crate::TokenGenerator) to sign a new token.
/// This requires a [`SecretKey`](crate::SecretKey) to sign a new token.
/// If not available, this will result in an error. To retrieve a token with the current
/// session's default permissions and expiry, use [`get_token`](Self::get_token) instead.
pub fn create_token(&self) -> crate::Result<Option<TokenRequest<'_>>> {
match self.client.token {
Some(TokenProvider::Generator(ref generator)) => {
Ok(Some(generator.request_inner(&self.scope)))
}
Some(TokenProvider::SecretKey(ref key)) => Ok(Some(key.request_inner(&self.scope))),
Some(TokenProvider::Static(_)) => Err(crate::Error::StaticTokenOverride),
None => Ok(None),
}
Expand Down
6 changes: 3 additions & 3 deletions clients/rust/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ pub enum Error {
#[error(transparent)]
TokenError(#[from] jsonwebtoken::errors::Error),
/// Error when the permissions requested for a token exceed those granted to the
/// [`TokenGenerator`](crate::TokenGenerator).
#[error("requested permissions not granted to this token generator: {escalated:?}")]
/// [`SecretKey`](crate::SecretKey).
#[error("requested permissions not granted to this secret key: {escalated:?}")]
PermissionEscalation {
/// The requested permissions that are not granted to the generator.
/// The requested permissions that are not granted to the key.
escalated: Vec<objectstore_types::auth::Permission>,
},
/// Error when per-token permission or expiry overrides are requested for a static
Expand Down
Loading
Loading