forked from SO4-Markets/so4-oracle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
290 lines (249 loc) · 8.83 KB
/
Copy pathmod.rs
File metadata and controls
290 lines (249 loc) · 8.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
use std::sync::Arc;
use axum::extract::FromRequestParts;
use axum::extract::MatchedPath;
use axum::http::header::AUTHORIZATION;
use axum::http::request::Parts;
use axum::http::{Method, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use axum::{Json, Router};
use serde::Serialize;
use std::time::Duration;
use tower_http::cors::{Any, CorsLayer};
use tower_http::request_id::{MakeRequestUuid, PropagateRequestIdLayer, SetRequestIdLayer};
use tower_http::trace::TraceLayer;
use tracing::Span;
use crate::state::AppState;
pub mod admin;
pub mod prices;
#[derive(Debug, Serialize)]
pub struct ErrorBody {
pub error: String,
}
#[derive(Debug)]
pub struct ApiError {
pub status: StatusCode,
pub message: String,
}
impl ApiError {
pub fn new(status: StatusCode, message: impl Into<String>) -> Self {
Self {
status,
message: message.into(),
}
}
}
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
(
self.status,
Json(ErrorBody {
error: self.message,
}),
)
.into_response()
}
}
#[derive(Debug, Clone, Copy)]
pub struct AdminAuth;
impl FromRequestParts<Arc<AppState>> for AdminAuth {
type Rejection = ApiError;
async fn from_request_parts(
parts: &mut Parts,
state: &Arc<AppState>,
) -> Result<Self, Self::Rejection> {
let expected = state.config.admin_api_token.as_ref().ok_or_else(|| {
ApiError::new(
StatusCode::SERVICE_UNAVAILABLE,
"ADMIN_API_TOKEN is not configured",
)
})?;
let actual = parts
.headers
.get(AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.strip_prefix("Bearer "));
match actual {
Some(actual) if constant_time_eq(actual.as_bytes(), expected.as_str().as_bytes()) => {
Ok(AdminAuth)
}
_ => {
let route = parts
.extensions
.get::<MatchedPath>()
.map(|m| m.as_str())
.unwrap_or("unknown");
state.metrics.record_http_auth_failure(route);
let request_id = parts
.extensions
.get::<tower_http::request_id::RequestId>()
.and_then(|id| id.header_value().to_str().ok())
.unwrap_or("");
tracing::warn!(
route = route,
request_id = request_id,
"unauthorized admin access attempt"
);
Err(ApiError::new(StatusCode::UNAUTHORIZED, "unauthorized"))
}
}
}
}
#[derive(Clone)]
struct RouteExt(String);
async fn track_metrics(
axum::extract::State(state): axum::extract::State<Arc<AppState>>,
request: axum::extract::Request,
next: axum::middleware::Next,
) -> axum::response::Response {
let path = if let Some(matched_path) = request.extensions().get::<MatchedPath>() {
matched_path.as_str().to_owned()
} else {
"/unmatched".to_owned()
};
let method = request.method().as_str().to_owned();
state.metrics.inc_http_in_flight();
let start = std::time::Instant::now();
let mut response = next.run(request).await;
let latency = start.elapsed();
state.metrics.dec_http_in_flight();
state.metrics.record_http_request(
&path,
&method,
response.status().as_u16(),
latency.as_millis() as u64,
);
response.extensions_mut().insert(RouteExt(path));
response
}
pub fn build_router(state: Arc<AppState>) -> Router {
let cors = CorsLayer::new()
.allow_methods([Method::GET])
.allow_origin(Any);
// CORS is only opened for the public, browser-facing price feed; admin and
// health routes are not cross-origin reachable.
let public = Router::new()
.route("/prices", get(prices::prices))
.layer(cors);
let trace_layer = TraceLayer::new_for_http()
.make_span_with(|request: &axum::http::Request<_>| {
let matched_path = request
.extensions()
.get::<MatchedPath>()
.map(|m| m.as_str())
.unwrap_or("/unmatched");
let request_id = request
.extensions()
.get::<tower_http::request_id::RequestId>()
.and_then(|id| id.header_value().to_str().ok())
.unwrap_or("");
tracing::info_span!(
"request",
method = %request.method(),
route = %matched_path,
request_id = %request_id,
status = tracing::field::Empty,
latency_ms = tracing::field::Empty,
)
})
.on_response(
|response: &axum::http::Response<_>, latency: Duration, span: &Span| {
let status = response.status().as_u16();
let latency_ms = latency.as_millis() as u64;
span.record("status", status);
span.record("latency_ms", latency_ms);
let is_health = response
.extensions()
.get::<RouteExt>()
.map(|ext| ext.0 == "/health" || ext.0 == "/ready")
.unwrap_or(false);
if is_health {
tracing::debug!("request completed");
} else {
tracing::info!("request completed");
}
},
)
.on_failure(
|error: tower_http::classify::ServerErrorsFailureClass,
_latency: Duration,
_span: &Span| {
tracing::error!(%error, "request failed");
},
);
Router::new()
.route("/health", get(prices::health))
.route("/ready", get(prices::ready))
.merge(public)
.route("/oracle/status", get(admin::oracle_status))
.route("/keeper/status", get(admin::keeper_status))
.route("/keeper/balance", get(admin::keeper_balance))
.route("/metrics", get(admin::metrics))
.route(
"/oracle/failed-submissions",
get(prices::failed_submissions),
)
.with_state(state.clone())
.layer(PropagateRequestIdLayer::x_request_id())
.layer(SetRequestIdLayer::x_request_id(MakeRequestUuid))
.layer(trace_layer)
.layer(axum::middleware::from_fn_with_state(state, track_metrics))
}
fn constant_time_eq(left: &[u8], right: &[u8]) -> bool {
let max_len = left.len().max(right.len());
let mut diff = left.len() ^ right.len();
for index in 0..max_len {
let a = left.get(index).copied().unwrap_or(0);
let b = right.get(index).copied().unwrap_or(0);
diff |= (a ^ b) as usize;
}
diff == 0
}
#[cfg(test)]
mod tests {
use super::constant_time_eq;
use crate::{AppState, Config};
use axum::body::Body;
use axum::http::Request;
use std::sync::Arc;
use tower::ServiceExt;
#[test]
fn constant_time_comparison_matches_equal_values_only() {
assert!(constant_time_eq(b"secret", b"secret"));
assert!(!constant_time_eq(b"secret", b"Secret"));
assert!(!constant_time_eq(b"secret", b"secret2"));
}
#[tokio::test]
async fn test_secrets_redacted_from_logs_and_metrics() {
let mut config = Config::default_for_tests();
let test_secret = "SCVXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
let test_admin_token = "admin_super_secret_token_123";
config.keeper_secret_key = crate::config::SecretString::new(test_secret.to_string());
config.admin_api_token = Some(crate::config::SecretString::new(
test_admin_token.to_string(),
));
let state = Arc::new(AppState::new(Arc::new(config)));
let app = super::build_router(Arc::clone(&state));
// Make an unauthorized admin request
let _request = Request::builder()
.uri("/oracle/status")
.header("Authorization", format!("Bearer {}", test_admin_token)) // wait, we want a failing one to check auth failure metrics
.body(Body::empty())
.unwrap();
let failing_request = Request::builder()
.uri("/oracle/status")
.header("Authorization", "Bearer WRONG_TOKEN")
.body(Body::empty())
.unwrap();
let _ = app.clone().oneshot(failing_request).await;
let metrics_out = state.metrics.to_prometheus();
assert!(
!metrics_out.contains(test_secret),
"keeper secret key found in metrics"
);
assert!(
!metrics_out.contains(test_admin_token),
"admin token found in metrics"
);
}
}