-
Notifications
You must be signed in to change notification settings - Fork 24
refactor: add attestation middleware #506
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
gusinacio
merged 8 commits into
main
from
gustavo/tap-308-create-middleware-for-attestation
Nov 25, 2024
Merged
Changes from 5 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
36fff08
refactor: add inject attestation signer
gusinacio 3895893
refactor: add attestation middleware
gusinacio 10d3d64
refactor: use attestation middleware
gusinacio 3734dbb
refactor: move process_request to request handler
gusinacio 36de277
refactor: rename middlewares
gusinacio 59973bf
docs: update word in attestation
gusinacio bf97f2d
refactor: remove magic constant from request handler
gusinacio 3fde238
test: refactor send request in attestation
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
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,19 +1,23 @@ | ||
| // Copyright 2023-, Edge & Node, GraphOps, and Semiotic Labs. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| mod allocation; | ||
| mod attestation; | ||
| mod attestation_signer; | ||
| pub mod auth; | ||
| mod inject_allocation; | ||
| mod inject_context; | ||
| mod inject_deployment; | ||
| mod inject_labels; | ||
| mod inject_receipt; | ||
| mod inject_sender; | ||
| mod deployment; | ||
| mod labels; | ||
| mod prometheus_metrics; | ||
| mod sender; | ||
| mod tap_context; | ||
| mod tap_receipt; | ||
|
|
||
| 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, SenderState}; | ||
| pub use allocation::{allocation_middleware, Allocation, AllocationState}; | ||
| pub use attestation::{attestation_middleware, AttestationInput}; | ||
| pub use attestation_signer::{signer_middleware, AttestationState}; | ||
| pub use deployment::deployment_middleware; | ||
| pub use labels::labels_middleware; | ||
| pub use prometheus_metrics::PrometheusMetricsMiddlewareLayer; | ||
| pub use sender::{sender_middleware, SenderState}; | ||
| pub use tap_context::context_middleware; | ||
| pub use tap_receipt::receipt_middleware; |
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 |
|---|---|---|
| @@ -0,0 +1,217 @@ | ||
| // Copyright 2023-, Edge & Node, GraphOps, and Semiotic Labs. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| use std::string::FromUtf8Error; | ||
|
|
||
| use axum::{ | ||
| body::to_bytes, | ||
| extract::Request, | ||
| middleware::Next, | ||
| response::{IntoResponse, Response}, | ||
| }; | ||
| use reqwest::StatusCode; | ||
| use serde::Serialize; | ||
| use thegraph_core::Attestation; | ||
|
|
||
| use indexer_attestation::AttestationSigner; | ||
|
|
||
| #[derive(Clone)] | ||
| pub enum AttestationInput { | ||
| Attestable { req: String }, | ||
| NotAttestable, | ||
| } | ||
|
|
||
| #[derive(Debug, Serialize)] | ||
| #[cfg_attr(test, derive(serde::Deserialize))] | ||
| pub struct IndexerResponsePayload { | ||
| #[serde(rename = "graphQLResponse")] | ||
| graphql_response: String, | ||
| attestation: Option<Attestation>, | ||
| } | ||
|
|
||
| /// Check if the query can be attestable generates attestation | ||
| /// | ||
| /// Executes query -> return subgraph response: (string, attestable (bool)) | ||
| /// if attestable && allocation id: | ||
| /// - look for signer | ||
| /// - create attestation | ||
| /// - return response with attestation | ||
| /// else: | ||
| /// - return with no attestation | ||
| /// | ||
| /// Requires AttestationSigner | ||
| pub async fn attestation_middleware( | ||
| request: Request, | ||
| next: Next, | ||
| ) -> Result<Response, AttestationError> { | ||
| let signer = request | ||
| .extensions() | ||
| .get::<AttestationSigner>() | ||
| .cloned() | ||
| .ok_or(AttestationError::CouldNotFindSigner)?; | ||
|
|
||
| let (parts, graphql_response) = next.run(request).await.into_parts(); | ||
| let attestation_response = parts.extensions.get::<AttestationInput>(); | ||
| let bytes = to_bytes(graphql_response, usize::MAX).await?; | ||
| let res = String::from_utf8(bytes.into())?; | ||
|
|
||
| let attestation = match attestation_response { | ||
| Some(AttestationInput::Attestable { req }) => Some(signer.create_attestation(req, &res)), | ||
| _ => None, | ||
| }; | ||
|
|
||
| let response = serde_json::to_string(&IndexerResponsePayload { | ||
| graphql_response: res, | ||
| attestation, | ||
| })?; | ||
|
|
||
| Ok(Response::new(response.into())) | ||
| } | ||
|
|
||
| #[derive(thiserror::Error, Debug)] | ||
| pub enum AttestationError { | ||
| #[error("Could not find signer for allocation")] | ||
| CouldNotFindSigner, | ||
|
|
||
| #[error("There was an AxumError: {0}")] | ||
| AxumError(#[from] axum::Error), | ||
|
|
||
| #[error("There was an error converting the response to UTF-8 string: {0}")] | ||
| FromUtf8Error(#[from] FromUtf8Error), | ||
|
|
||
| #[error("there was an error while serializing the response: {0}")] | ||
| SerializationError(#[from] serde_json::Error), | ||
| } | ||
|
|
||
| impl IntoResponse for AttestationError { | ||
| fn into_response(self) -> Response { | ||
| match self { | ||
| AttestationError::CouldNotFindSigner | ||
| | AttestationError::AxumError(_) | ||
| | AttestationError::FromUtf8Error(_) | ||
| | AttestationError::SerializationError(_) => StatusCode::INTERNAL_SERVER_ERROR, | ||
| } | ||
| .into_response() | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use alloy::primitives::Address; | ||
| use axum::{ | ||
| body::{to_bytes, Body}, | ||
| http::{Request, Response}, | ||
| middleware::from_fn, | ||
| routing::get, | ||
| Router, | ||
| }; | ||
| use indexer_allocation::Allocation; | ||
| use indexer_attestation::AttestationSigner; | ||
| use reqwest::StatusCode; | ||
| use test_assets::{INDEXER_ALLOCATIONS, INDEXER_MNEMONIC}; | ||
| use tower::ServiceExt; | ||
|
|
||
| use crate::middleware::{ | ||
| attestation::IndexerResponsePayload, attestation_middleware, AttestationInput, | ||
| }; | ||
|
|
||
| const REQUEST: &str = "request"; | ||
| const RESPONSE: &str = "response"; | ||
|
|
||
| fn allocation_signer() -> (Allocation, AttestationSigner) { | ||
| let allocation = INDEXER_ALLOCATIONS | ||
| .values() | ||
| .collect::<Vec<_>>() | ||
| .pop() | ||
| .unwrap() | ||
| .clone(); | ||
| let signer = | ||
| AttestationSigner::new(&INDEXER_MNEMONIC.to_string(), &allocation, 1, Address::ZERO) | ||
| .unwrap(); | ||
| (allocation, signer) | ||
| } | ||
|
|
||
| async fn payload_from_response(res: Response<Body>) -> IndexerResponsePayload { | ||
| let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap(); | ||
|
|
||
| serde_json::from_slice(&bytes).unwrap() | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn test_create_attestation() { | ||
| let (allocation, signer) = allocation_signer(); | ||
| let middleware = from_fn(attestation_middleware); | ||
|
|
||
| let handle = move |_: Request<Body>| async move { | ||
| let mut res = Response::new(RESPONSE.to_string()); | ||
| res.extensions_mut().insert(AttestationInput::Attestable { | ||
| req: REQUEST.to_string(), | ||
| }); | ||
| res | ||
| }; | ||
|
|
||
| let app = Router::new().route("/", get(handle)).layer(middleware); | ||
|
|
||
| // with signer | ||
| let res = app | ||
|
||
| .oneshot( | ||
| Request::builder() | ||
| .uri("/") | ||
| .extension(signer.clone()) | ||
| .body(Body::empty()) | ||
| .unwrap(), | ||
| ) | ||
| .await | ||
| .unwrap(); | ||
| assert_eq!(res.status(), StatusCode::OK); | ||
|
|
||
| let response = payload_from_response(res).await; | ||
| assert_eq!(response.graphql_response, RESPONSE.to_string()); | ||
|
|
||
| let attestation = response.attestation.unwrap(); | ||
| assert!(signer | ||
| .verify(&attestation, REQUEST, RESPONSE, &allocation.id) | ||
| .is_ok()); | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn test_non_assignable() { | ||
| let (_, signer) = allocation_signer(); | ||
| let handle = move |_: Request<Body>| async move { Response::new(RESPONSE.to_string()) }; | ||
|
|
||
| let middleware = from_fn(attestation_middleware); | ||
| let app = Router::new().route("/", get(handle)).layer(middleware); | ||
|
|
||
| let res = app | ||
| .oneshot( | ||
| Request::builder() | ||
| .uri("/") | ||
| .extension(signer.clone()) | ||
| .body(Body::empty()) | ||
| .unwrap(), | ||
| ) | ||
| .await | ||
| .unwrap(); | ||
| assert_eq!(res.status(), StatusCode::OK); | ||
|
|
||
| let response = payload_from_response(res).await; | ||
| assert_eq!(response.graphql_response, RESPONSE.to_string()); | ||
| assert!(response.attestation.is_none()); | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn test_no_signer() { | ||
| let handle = move |_: Request<Body>| async move { | ||
| Response::new(RESPONSE.to_string()); | ||
| }; | ||
|
|
||
| let middleware = from_fn(attestation_middleware); | ||
| let app = Router::new().route("/", get(handle)).layer(middleware); | ||
|
|
||
| let res = app | ||
| .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap()) | ||
| .await | ||
| .unwrap(); | ||
| assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR); | ||
| } | ||
| } | ||
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is worded strangely. I think you meant to say "is attestable?"