|
| 1 | +//! JWT validation utilities. |
| 2 | +
|
| 3 | +use alloy_rpc_types_engine::JwtSecret; |
| 4 | + |
| 5 | +#[cfg(feature = "engine-validation")] |
| 6 | +use crate::JwtValidationError; |
| 7 | + |
| 8 | +/// A JWT validator that can verify JWT secrets against an engine API. |
| 9 | +#[derive(Debug, Clone, Copy)] |
| 10 | +pub struct JwtValidator { |
| 11 | + secret: JwtSecret, |
| 12 | +} |
| 13 | + |
| 14 | +impl JwtValidator { |
| 15 | + /// Creates a new JWT validator with the given secret. |
| 16 | + pub const fn new(secret: JwtSecret) -> Self { |
| 17 | + Self { secret } |
| 18 | + } |
| 19 | + |
| 20 | + /// Returns the underlying JWT secret. |
| 21 | + pub const fn secret(&self) -> JwtSecret { |
| 22 | + self.secret |
| 23 | + } |
| 24 | + |
| 25 | + /// Consumes the validator and returns the JWT secret. |
| 26 | + pub const fn into_inner(self) -> JwtSecret { |
| 27 | + self.secret |
| 28 | + } |
| 29 | + |
| 30 | + /// Check if an error is related to JWT signature validation. |
| 31 | + /// |
| 32 | + /// Walks the error chain to detect JWT authentication failures by |
| 33 | + /// looking for common error message patterns. |
| 34 | + pub fn is_jwt_signature_error(error: &dyn std::error::Error) -> bool { |
| 35 | + let mut source = Some(error); |
| 36 | + while let Some(err) = source { |
| 37 | + let err_str = err.to_string().to_lowercase(); |
| 38 | + if err_str.contains("signature invalid") |
| 39 | + || (err_str.contains("jwt") && err_str.contains("invalid")) |
| 40 | + || err_str.contains("unauthorized") |
| 41 | + || err_str.contains("authentication failed") |
| 42 | + { |
| 43 | + return true; |
| 44 | + } |
| 45 | + source = err.source(); |
| 46 | + } |
| 47 | + false |
| 48 | + } |
| 49 | + |
| 50 | + /// Helper to check JWT signature error from eyre::Error (for retry condition). |
| 51 | + #[cfg(feature = "engine-validation")] |
| 52 | + pub fn is_jwt_signature_error_from_eyre(error: &eyre::Error) -> bool { |
| 53 | + Self::is_jwt_signature_error(error.as_ref() as &dyn std::error::Error) |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +#[cfg(feature = "engine-validation")] |
| 58 | +impl JwtValidator { |
| 59 | + /// Validates the JWT secret by exchanging capabilities with an engine API. |
| 60 | + /// |
| 61 | + /// Uses exponential backoff for transient failures, but fails immediately |
| 62 | + /// on authentication errors (invalid JWT signature). |
| 63 | + /// |
| 64 | + /// # Arguments |
| 65 | + /// * `engine_url` - The URL of the engine API endpoint |
| 66 | + /// |
| 67 | + /// # Returns |
| 68 | + /// * `Ok(JwtSecret)` - The validated JWT secret |
| 69 | + /// * `Err(JwtValidationError::InvalidSignature)` - JWT authentication failed |
| 70 | + /// * `Err(JwtValidationError::CapabilityExchange(_))` - Transient error after retries |
| 71 | + pub async fn validate_with_engine( |
| 72 | + self, |
| 73 | + engine_url: url::Url, |
| 74 | + ) -> Result<JwtSecret, JwtValidationError> { |
| 75 | + use alloy_provider::RootProvider; |
| 76 | + use alloy_transport_http::Http; |
| 77 | + use backon::{ExponentialBuilder, Retryable}; |
| 78 | + use kona_engine::{HyperAuthClient, OpEngineClient}; |
| 79 | + use op_alloy_network::Optimism; |
| 80 | + use op_alloy_provider::ext::engine::OpEngineApi; |
| 81 | + use tracing::{debug, error}; |
| 82 | + |
| 83 | + let engine = OpEngineClient::<RootProvider, RootProvider<Optimism>>::rpc_client::<Optimism>( |
| 84 | + engine_url, |
| 85 | + self.secret, |
| 86 | + ); |
| 87 | + |
| 88 | + let exchange = || async { |
| 89 | + match <RootProvider<Optimism> as OpEngineApi< |
| 90 | + Optimism, |
| 91 | + Http<HyperAuthClient>, |
| 92 | + >>::exchange_capabilities(&engine, vec![]) |
| 93 | + .await |
| 94 | + { |
| 95 | + Ok(_) => { |
| 96 | + debug!("Successfully exchanged capabilities with engine"); |
| 97 | + Ok(self.secret) |
| 98 | + } |
| 99 | + Err(e) => { |
| 100 | + if Self::is_jwt_signature_error(&e) { |
| 101 | + error!( |
| 102 | + "Engine API JWT secret differs from the one specified by --l2.jwt-secret/--l2.jwt-secret-encoded" |
| 103 | + ); |
| 104 | + error!( |
| 105 | + "Ensure that the JWT secret file specified is correct (by default it is `jwt.hex` in the current directory)" |
| 106 | + ); |
| 107 | + return Err(JwtValidationError::InvalidSignature.into()); |
| 108 | + } |
| 109 | + Err(JwtValidationError::CapabilityExchange(e.to_string()).into()) |
| 110 | + } |
| 111 | + } |
| 112 | + }; |
| 113 | + |
| 114 | + exchange |
| 115 | + .retry(ExponentialBuilder::default()) |
| 116 | + .when(|e: &eyre::Error| !Self::is_jwt_signature_error_from_eyre(e)) |
| 117 | + .notify(|_, duration| { |
| 118 | + debug!("Retrying engine capability handshake after {duration:?}"); |
| 119 | + }) |
| 120 | + .await |
| 121 | + .map_err(|e| { |
| 122 | + // Convert eyre::Error back to JwtValidationError |
| 123 | + if Self::is_jwt_signature_error_from_eyre(&e) { |
| 124 | + JwtValidationError::InvalidSignature |
| 125 | + } else { |
| 126 | + JwtValidationError::CapabilityExchange(e.to_string()) |
| 127 | + } |
| 128 | + }) |
| 129 | + } |
| 130 | +} |
0 commit comments