-
Notifications
You must be signed in to change notification settings - Fork 639
Add AuthCtx to ReducerContext for rust #3288
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 16 commits
Commits
Show all changes
35 commits
Select commit
Hold shift + click to select a range
1decd97
Add abi for credentials
jsdt 3f3b225
Add AuthCtx to the ReducerContext
jsdt 61ffd83
Expose sender_auth with a function.
jsdt 58b5f26
Cleanup
jsdt 70af0ae
Merge branch 'master' into jsdt/cred-bindings
jsdt 57a024f
Update dep snapshot
jsdt f7042cb
Use bytes source instead of having a jwt len function
jsdt bdff86c
Merge branch 'master' into jsdt/cred-bindings
jsdt bfdc636
Cleanup
jsdt a89b883
Merge branch 'master' into jsdt/cred-bindings
jsdt 7c4da19
Update comments and use helper to read byte source of jwt
jsdt fba36f1
Merge branch 'master' into jsdt/cred-bindings
jsdt 0f61291
fmt
jsdt 0a274d3
Merge branch 'master' into jsdt/cred-bindings
jsdt 7d872c5
Cargo update
jsdt 291c20b
Update comment
jsdt ee9c69d
Use error codes for get_jwt
jsdt 9f9919f
Merge branch 'master' into jsdt/cred-bindings
jsdt de914e6
Merge branch 'master' into jsdt/cred-bindings
jsdt 989785b
fmt
jsdt 979b048
Update ui tests?
jsdt 416ac1a
Merge branch 'master' into jsdt/cred-bindings
jsdt 48a6283
Take ui test output from master.
jsdt 8525962
Merge branch 'master' into jsdt/cred-bindings
jsdt 76d9760
Rewrite Cargo.lock
jsdt 2f04ff6
Update ui test outputs
jsdt 6876dd6
Update views.stderr from CI output
jsdt 50f6ecf
Use a new ABI version
jsdt 3d79561
Merge branch 'master' into jsdt/cred-bindings
jsdt 499493d
Remove logging of credentials.
jsdt 95a8001
Update comments and small tweaks.
jsdt b4ce12b
Another comment update
jsdt 907fd40
Update dep snapshot
jsdt 3cb0c75
Merge branch 'master' into jsdt/cred-bindings
jsdt 8fdf1f5
Merge branch 'master' into jsdt/cred-bindings
jsdt File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -12,12 +12,13 @@ pub mod rt; | |
| #[doc(hidden)] | ||
| pub mod table; | ||
|
|
||
| use spacetimedb_lib::bsatn; | ||
| use std::cell::RefCell; | ||
|
|
||
| pub use log; | ||
| #[cfg(feature = "rand")] | ||
| pub use rand08 as rand; | ||
| use spacetimedb_lib::bsatn; | ||
| use std::cell::{OnceCell, RefCell}; | ||
| use std::ops::Deref; | ||
| use std::sync::LazyLock; | ||
|
|
||
| #[cfg(feature = "unstable")] | ||
| pub use client_visibility_filter::Filter; | ||
|
|
@@ -732,6 +733,8 @@ pub struct ReducerContext { | |
| /// See the [`#[table]`](macro@crate::table) macro for more information. | ||
| pub db: Local, | ||
|
|
||
| sender_auth: AuthCtx, | ||
|
|
||
| #[cfg(feature = "rand08")] | ||
| rng: std::cell::OnceCell<StdbRng>, | ||
| } | ||
|
|
@@ -744,10 +747,32 @@ impl ReducerContext { | |
| sender: Identity::__dummy(), | ||
| timestamp: Timestamp::UNIX_EPOCH, | ||
| connection_id: None, | ||
| sender_auth: AuthCtx::internal(), | ||
| rng: std::cell::OnceCell::new(), | ||
| } | ||
| } | ||
|
|
||
| #[doc(hidden)] | ||
| fn new(db: Local, sender: Identity, connection_id: Option<ConnectionId>, timestamp: Timestamp) -> Self { | ||
| let sender_auth = match connection_id { | ||
| Some(cid) => AuthCtx::from_connection_id(cid), | ||
| None => AuthCtx::internal(), | ||
| }; | ||
| Self { | ||
| db, | ||
| sender, | ||
| timestamp, | ||
| connection_id, | ||
| sender_auth, | ||
| #[cfg(feature = "rand08")] | ||
| rng: std::cell::OnceCell::new(), | ||
| } | ||
| } | ||
|
|
||
| pub fn sender_auth(&self) -> &AuthCtx { | ||
| &self.sender_auth | ||
| } | ||
|
|
||
| /// Read the current module's [`Identity`]. | ||
| pub fn identity(&self) -> Identity { | ||
| // Hypothetically, we *could* read the module identity out of the system tables. | ||
|
|
@@ -796,6 +821,112 @@ impl DbContext for ReducerContext { | |
| #[non_exhaustive] | ||
| pub struct Local {} | ||
|
|
||
| #[non_exhaustive] | ||
| pub struct JwtClaims { | ||
| payload: String, | ||
| parsed: OnceCell<serde_json::Value>, | ||
| audience: OnceCell<Vec<String>>, | ||
| } | ||
|
|
||
| /// Authentication information for the caller of a reducer. | ||
| pub struct AuthCtx { | ||
| is_internal: bool, | ||
| // I can't directly use a LazyLock without making this struct generic. | ||
jsdt marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| jwt: Box<dyn Deref<Target = Option<JwtClaims>>>, | ||
| } | ||
|
|
||
| impl AuthCtx { | ||
| fn new<F>(is_internal: bool, jwt_fn: F) -> Self | ||
| where | ||
| F: FnOnce() -> Option<JwtClaims> + 'static, | ||
| { | ||
jsdt marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| AuthCtx { | ||
| is_internal, | ||
| jwt: Box::new(LazyLock::new(jwt_fn)), | ||
jsdt marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
|
|
||
| /// Create an [`AuthCtx`] for an internal call, with no JWT. | ||
| /// This represents a scheduled reducer. | ||
| pub fn internal() -> AuthCtx { | ||
| Self::new(true, || None) | ||
| } | ||
|
|
||
| /// Creates an [`AuthCtx`] using the json claims from a JWT. | ||
| /// This can be used to write unit tests. | ||
| pub fn from_jwt_payload(jwt_payload: String) -> AuthCtx { | ||
| Self::new(false, move || Some(JwtClaims::new(jwt_payload))) | ||
| } | ||
|
|
||
| /// Creates an [`AuthCtx`] that reads the JWT for the given connection id. | ||
| fn from_connection_id(connection_id: ConnectionId) -> AuthCtx { | ||
| Self::new(false, move || rt::get_jwt(connection_id).map(JwtClaims::new)) | ||
| } | ||
|
|
||
| /// True if this reducer was spawned from inside the database. | ||
jsdt marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| pub fn is_internal(&self) -> bool { | ||
| self.is_internal | ||
| } | ||
|
|
||
| /// Check if there is a JWT without loading it. | ||
| /// If is_internal is true, this will be false. | ||
jsdt marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| pub fn has_jwt(&self) -> bool { | ||
| self.jwt.is_some() | ||
| } | ||
|
|
||
| /// Load the jwt. | ||
| pub fn jwt(&self) -> Option<&JwtClaims> { | ||
| self.jwt.as_ref().deref().as_ref() | ||
| } | ||
| } | ||
|
|
||
| impl JwtClaims { | ||
| fn new(jwt: String) -> Self { | ||
| Self { | ||
| payload: jwt, | ||
| parsed: OnceCell::new(), | ||
| audience: OnceCell::new(), | ||
| } | ||
| } | ||
|
|
||
| fn get_parsed(&self) -> &serde_json::Value { | ||
| self.parsed | ||
| .get_or_init(|| serde_json::from_str(&self.payload).expect("Failed to parse JWT payload")) | ||
| } | ||
|
|
||
| pub fn subject(&self) -> &str { | ||
jsdt marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| // TODO: Add more error messages here. | ||
jsdt marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| self.get_parsed().get("sub").unwrap().as_str().unwrap() | ||
| } | ||
|
|
||
| pub fn issuer(&self) -> &str { | ||
jsdt marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| self.get_parsed().get("iss").unwrap().as_str().unwrap() | ||
| } | ||
|
|
||
| fn extract_audience(&self) -> Vec<String> { | ||
| let aud = self.get_parsed().get("aud").unwrap(); | ||
| match aud { | ||
| serde_json::Value::String(s) => vec![s.clone()], | ||
| serde_json::Value::Array(arr) => arr.iter().filter_map(|v| v.as_str().map(String::from)).collect(), | ||
| _ => panic!("Unexpected type for 'aud' claim in JWT"), | ||
| } | ||
| } | ||
|
|
||
| pub fn audience(&self) -> &[String] { | ||
jsdt marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| self.audience.get_or_init(|| self.extract_audience()) | ||
| } | ||
|
|
||
| // A convenience method, since this may not be in the token. | ||
| pub fn identity(&self) -> Identity { | ||
jsdt marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| Identity::from_claims(self.issuer(), self.subject()) | ||
| } | ||
|
|
||
| // We can expose the whole payload for users that want to parse custom claims. | ||
| pub fn raw_payload(&self) -> &str { | ||
jsdt marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| &self.payload | ||
| } | ||
| } | ||
|
|
||
| // #[cfg(target_arch = "wasm32")] | ||
| // #[global_allocator] | ||
| // static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; | ||
|
|
@@ -900,3 +1031,37 @@ macro_rules! __volatile_nonatomic_schedule_immediate_impl { | |
| } | ||
| }; | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
|
|
||
| #[test] | ||
| fn parse_single_audience() { | ||
| let example_payload = r#" | ||
| { | ||
| "iss": "https://securetoken.google.com/my-project-id", | ||
| "aud": "my-project-id", | ||
| "auth_time": 1695560000, | ||
| "user_id": "abc123XYZ", | ||
| "sub": "abc123XYZ", | ||
| "iat": 1695560100, | ||
| "exp": 1695563700, | ||
| "email": "[email protected]", | ||
| "email_verified": true, | ||
| "firebase": { | ||
| "identities": { | ||
| "email": ["[email protected]"] | ||
| }, | ||
| "sign_in_provider": "password" | ||
| }, | ||
| "name": "Jane Doe", | ||
| "picture": "https://lh3.googleusercontent.com/a-/profile.jpg" | ||
| } | ||
| "#; | ||
| let auth = AuthCtx::from_jwt_payload(example_payload.to_string()); | ||
| let audience = auth.jwt().unwrap().audience(); | ||
| assert_eq!(audience.len(), 1); | ||
| assert_eq!(audience, &["my-project-id".to_string()]); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.