-
Notifications
You must be signed in to change notification settings - Fork 24
refactor: add auth middleware #505
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 7 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
4e930e4
refactor: add auth middleware
gusinacio f33f6dd
test: add tap test
gusinacio bdfdc13
test: add middleware composition test
gusinacio c4f9da6
refactor: use auth middleware
gusinacio 159ff4a
refactor: create context middleware
gusinacio fecfc0b
refactor: remove option from tap receipt
gusinacio 6365178
docs: add documentation to auth middleware
gusinacio 77aaa77
test: split composition tests
gusinacio 95dee9e
test: split tap middleware tests
gusinacio f805565
docs: fix typos
gusinacio 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
56 changes: 56 additions & 0 deletions
56
.sqlx/query-6c05fc541bf0bb2af20fbe62747456055d5ebda5cb136d9d015f101ebbfe495f.json
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,16 +1,19 @@ | ||
| // Copyright 2023-, Edge & Node, GraphOps, and Semiotic Labs. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| pub mod auth; | ||
| mod inject_allocation; | ||
| mod inject_context; | ||
| mod inject_deployment; | ||
| mod inject_labels; | ||
| mod inject_receipt; | ||
| mod inject_sender; | ||
| mod prometheus_metrics; | ||
|
|
||
| pub use inject_allocation::{allocation_middleware, Allocation, AllocationState}; | ||
| pub use inject_context::context_middleware; | ||
| pub use inject_deployment::deployment_middleware; | ||
| pub use inject_labels::labels_middleware; | ||
| pub use inject_receipt::receipt_middleware; | ||
| pub use inject_sender::{sender_middleware, Sender, SenderState}; | ||
| pub use inject_sender::{sender_middleware, SenderState}; | ||
| pub use prometheus_metrics::PrometheusMetricsMiddlewareLayer; |
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 |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| // Copyright 2023-, Edge & Node, GraphOps, and Semiotic Labs. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| mod bearer; | ||
| mod or; | ||
| mod tap; | ||
|
|
||
| pub use bearer::Bearer; | ||
| pub use or::OrExt; | ||
| pub use tap::tap_receipt_authorize; | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use std::time::Duration; | ||
|
|
||
| use alloy::primitives::{address, Address}; | ||
| use axum::body::Body; | ||
| use axum::http::{Request, Response}; | ||
| use reqwest::{header, StatusCode}; | ||
| use sqlx::PgPool; | ||
| use tap_core::{manager::Manager, receipt::checks::CheckList}; | ||
| use tower::{Service, ServiceBuilder, ServiceExt}; | ||
| use tower_http::auth::AsyncRequireAuthorizationLayer; | ||
|
|
||
| use crate::middleware::auth::{self, Bearer, OrExt}; | ||
| use crate::tap::IndexerTapContext; | ||
| use test_assets::{create_signed_receipt, TAP_EIP712_DOMAIN}; | ||
|
|
||
| const ALLOCATION_ID: Address = address!("deadbeefcafebabedeadbeefcafebabedeadbeef"); | ||
|
|
||
| async fn handle(_: Request<Body>) -> anyhow::Result<Response<Body>> { | ||
| Ok(Response::new(Body::default())) | ||
| } | ||
|
|
||
| #[sqlx::test(migrations = "../../migrations")] | ||
| async fn test_middleware_composition(pgpool: PgPool) { | ||
| let token = "test".to_string(); | ||
| let context = IndexerTapContext::new(pgpool.clone(), TAP_EIP712_DOMAIN.clone()).await; | ||
| let tap_manager = Box::leak(Box::new(Manager::new( | ||
| TAP_EIP712_DOMAIN.clone(), | ||
| context, | ||
| CheckList::empty(), | ||
| ))); | ||
| let metric = Box::leak(Box::new( | ||
| prometheus::register_counter_vec!( | ||
| "merge_checks_test", | ||
| "Failed queries to handler", | ||
| &["deployment"] | ||
| ) | ||
| .unwrap(), | ||
| )); | ||
| let free_query = Bearer::new(&token); | ||
| let tap_auth = auth::tap_receipt_authorize(tap_manager, metric); | ||
| let authorize_requests = free_query.or(tap_auth); | ||
|
|
||
| let authorization_middleware = AsyncRequireAuthorizationLayer::new(authorize_requests); | ||
|
|
||
| let mut service = ServiceBuilder::new() | ||
| .layer(authorization_middleware) | ||
| .service_fn(handle); | ||
|
|
||
| let handle = service.ready().await.unwrap(); | ||
|
|
||
| // should allow queries that contains the free token | ||
| // if the token does not match, return payment required | ||
| let mut req = Request::new(Default::default()); | ||
| req.headers_mut().insert( | ||
| header::AUTHORIZATION, | ||
| format!("Bearer {token}").parse().unwrap(), | ||
| ); | ||
| let res = handle.call(req).await.unwrap(); | ||
| assert_eq!(res.status(), StatusCode::OK); | ||
|
|
||
| // if the token exists but is wrong, try the receipt | ||
| let mut req = Request::new(Default::default()); | ||
| req.headers_mut() | ||
| .insert(header::AUTHORIZATION, "Bearer wrongtoken".parse().unwrap()); | ||
| let res = handle.call(req).await.unwrap(); | ||
| // we return the error from tap | ||
| assert_eq!(res.status(), StatusCode::PAYMENT_REQUIRED); | ||
|
|
||
| let receipt = create_signed_receipt(ALLOCATION_ID, 1, 1, 1).await; | ||
|
|
||
| // check with receipt | ||
| let mut req = Request::new(Default::default()); | ||
| req.extensions_mut().insert(receipt); | ||
| let res = handle.call(req).await.unwrap(); | ||
| assert_eq!(res.status(), StatusCode::OK); | ||
|
|
||
| // todo make this sleep better | ||
| tokio::time::sleep(Duration::from_millis(100)).await; | ||
anirudh2 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| // verify receipts | ||
| let result = sqlx::query!("SELECT * FROM scalar_tap_receipts") | ||
| .fetch_all(&pgpool) | ||
| .await | ||
| .unwrap(); | ||
| assert_eq!(result.len(), 1); | ||
|
|
||
| // if it has neither, should return unauthorized | ||
| // check no headers | ||
| let req = Request::new(Default::default()); | ||
| let res = handle.call(req).await.unwrap(); | ||
| assert_eq!(res.status(), StatusCode::PAYMENT_REQUIRED); | ||
| } | ||
| } | ||
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 |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| // Copyright 2023-, Edge & Node, GraphOps, and Semiotic Labs. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| //! Bearer struct from tower-http but exposing the `new()` function | ||
| //! to allow creation | ||
| //! | ||
| //! This code is from *tower-http* | ||
|
|
||
| use std::{fmt, marker::PhantomData}; | ||
|
|
||
| use axum::http::{HeaderValue, Request, Response}; | ||
| use reqwest::{header, StatusCode}; | ||
| use tower_http::validate_request::ValidateRequest; | ||
|
|
||
| pub struct Bearer<ResBody> { | ||
| header_value: HeaderValue, | ||
| _ty: PhantomData<fn() -> ResBody>, | ||
| } | ||
|
|
||
| impl<ResBody> Bearer<ResBody> { | ||
| pub fn new(token: &str) -> Self | ||
| where | ||
| ResBody: Default, | ||
| { | ||
| Self { | ||
| header_value: format!("Bearer {}", token) | ||
| .parse() | ||
| .expect("token is not a valid header value"), | ||
| _ty: PhantomData, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl<ResBody> Clone for Bearer<ResBody> { | ||
| fn clone(&self) -> Self { | ||
| Self { | ||
| header_value: self.header_value.clone(), | ||
| _ty: PhantomData, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl<ResBody> fmt::Debug for Bearer<ResBody> { | ||
| fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| f.debug_struct("Bearer") | ||
| .field("header_value", &self.header_value) | ||
| .finish() | ||
| } | ||
| } | ||
|
|
||
| impl<B, ResBody> ValidateRequest<B> for Bearer<ResBody> | ||
| where | ||
| ResBody: Default, | ||
| { | ||
| type ResponseBody = ResBody; | ||
|
|
||
| fn validate(&mut self, request: &mut Request<B>) -> Result<(), Response<Self::ResponseBody>> { | ||
| match request.headers().get(header::AUTHORIZATION) { | ||
| Some(actual) if actual == self.header_value => Ok(()), | ||
| _ => { | ||
| let mut res = Response::new(ResBody::default()); | ||
| *res.status_mut() = StatusCode::UNAUTHORIZED; | ||
| Err(res) | ||
| } | ||
| } | ||
| } | ||
| } |
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.