-
Notifications
You must be signed in to change notification settings - Fork 245
Expand file tree
/
Copy pathauth.rs
More file actions
451 lines (375 loc) · 15.4 KB
/
auth.rs
File metadata and controls
451 lines (375 loc) · 15.4 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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
use crate::{
constant::{X_API_KEY, X_HMAC_SIGNATURE, X_TIMESTAMP},
rpc_server::middleware_utils::{extract_parts_and_body_bytes, get_jsonrpc_method},
};
use hmac::{Hmac, Mac};
use http::{Request, Response, StatusCode};
use jsonrpsee::server::logger::Body;
use sha2::Sha256;
#[derive(Clone)]
pub struct ApiKeyAuthLayer {
api_key: String,
}
impl ApiKeyAuthLayer {
pub fn new(api_key: String) -> Self {
Self { api_key }
}
}
#[derive(Clone)]
pub struct ApiKeyAuthService<S> {
inner: S,
api_key: String,
}
impl<S> tower::Layer<S> for ApiKeyAuthLayer {
type Service = ApiKeyAuthService<S>;
fn layer(&self, inner: S) -> Self::Service {
ApiKeyAuthService { inner, api_key: self.api_key.clone() }
}
}
impl<S> tower::Service<Request<Body>> for ApiKeyAuthService<S>
where
S: tower::Service<Request<Body>, Response = Response<Body>> + Clone + Send + 'static,
S::Future: Send + 'static,
{
type Response = S::Response;
type Error = S::Error;
type Future = std::pin::Pin<
Box<dyn std::future::Future<Output = Result<Self::Response, Self::Error>> + Send>,
>;
fn poll_ready(
&mut self,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, request: Request<Body>) -> Self::Future {
let api_key = self.api_key.clone();
let mut inner = self.inner.clone();
Box::pin(async move {
let unauthorized_response = Response::builder()
.status(StatusCode::UNAUTHORIZED)
.body(Body::empty())
.expect("Failed to build unauthorized response");
let (parts, body_bytes) = extract_parts_and_body_bytes(request).await;
// Bypass auth for liveness endpoint
if let Some(method) = get_jsonrpc_method(&body_bytes) {
if method == "liveness" {
let new_body = Body::from(body_bytes);
let new_request = Request::from_parts(parts, new_body);
return inner.call(new_request).await;
}
}
// Check for API key header
let req = Request::from_parts(parts, Body::from(body_bytes));
if let Some(provided_key) = req.headers().get(X_API_KEY) {
if provided_key.to_str().unwrap_or("") == api_key {
return inner.call(req).await;
}
}
Ok(unauthorized_response)
})
}
}
#[derive(Clone)]
pub struct HmacAuthLayer {
secret: String,
max_timestamp_age: i64,
}
impl HmacAuthLayer {
pub fn new(secret: String, max_timestamp_age: i64) -> Self {
Self { secret, max_timestamp_age }
}
}
impl<S> tower::Layer<S> for HmacAuthLayer {
type Service = HmacAuthService<S>;
fn layer(&self, inner: S) -> Self::Service {
HmacAuthService {
inner,
secret: self.secret.clone(),
max_timestamp_age: self.max_timestamp_age,
}
}
}
#[derive(Clone)]
pub struct HmacAuthService<S> {
inner: S,
secret: String,
max_timestamp_age: i64,
}
impl<S> tower::Service<Request<Body>> for HmacAuthService<S>
where
S: tower::Service<Request<Body>, Response = Response<Body>> + Clone + Send + 'static,
S::Future: Send + 'static,
{
type Response = S::Response;
type Error = S::Error;
type Future = std::pin::Pin<
Box<dyn std::future::Future<Output = Result<Self::Response, Self::Error>> + Send>,
>;
fn poll_ready(
&mut self,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, request: Request<Body>) -> Self::Future {
let secret = self.secret.clone();
let max_timestamp_age = self.max_timestamp_age;
let mut inner = self.inner.clone();
Box::pin(async move {
let unauthorized_response = Response::builder()
.status(StatusCode::UNAUTHORIZED)
.body(Body::empty())
.expect("Failed to build unauthorized response");
let signature_header = request.headers().get(X_HMAC_SIGNATURE).cloned();
let timestamp_header = request.headers().get(X_TIMESTAMP).cloned();
let (parts, body_bytes) = extract_parts_and_body_bytes(request).await;
// Bypass auth for liveness endpoint
if let Some(method) = get_jsonrpc_method(&body_bytes) {
if method == "liveness" {
let new_body = Body::from(body_bytes);
let new_request = Request::from_parts(parts, new_body);
return inner.call(new_request).await;
}
}
let (signature, timestamp) =
match (signature_header.as_ref(), timestamp_header.as_ref()) {
(Some(sig), Some(ts)) => (sig, ts),
_ => return Ok(unauthorized_response),
};
let signature = signature.to_str().unwrap_or("");
let timestamp = timestamp.to_str().unwrap_or("");
// Verify timestamp is within allowed age
let parsed_timestamp = timestamp.parse::<i64>();
if parsed_timestamp.is_err() {
return Ok(unauthorized_response);
}
let ts = parsed_timestamp.expect("timestamp already validated");
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_err(|e| {
log::error!("System time error: {e:?}");
e
})
.unwrap_or_else(|_| std::time::Duration::from_secs(0))
.as_secs() as i64;
if (now - ts).abs() > max_timestamp_age {
return Ok(unauthorized_response);
}
// Verify HMAC signature using timestamp + body
let body_str = std::str::from_utf8(&body_bytes).unwrap_or("");
let message = format!("{}{}", timestamp, body_str);
let mut mac = match Hmac::<Sha256>::new_from_slice(secret.as_bytes()) {
Ok(mac) => mac,
Err(_) => {
log::error!("HMAC authentication failed");
return Ok(unauthorized_response);
}
};
mac.update(message.as_bytes());
let signature_bytes = match hex::decode(signature) {
Ok(bytes) => bytes,
Err(_) => {
log::error!("HMAC signature hex decode failed");
return Ok(unauthorized_response);
}
};
// Constant time comparison prevents timing attacks
if mac.verify_slice(&signature_bytes).is_err() {
return Ok(unauthorized_response);
}
// Reconstruct the request with the consumed body
let new_body = Body::from(body_bytes);
let new_request = Request::from_parts(parts, new_body);
inner.call(new_request).await
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::constant::{DEFAULT_MAX_TIMESTAMP_AGE, X_API_KEY, X_HMAC_SIGNATURE, X_TIMESTAMP};
use hmac::{Hmac, Mac};
use http::Method;
use jsonrpsee::server::logger::Body;
use sha2::Sha256;
use std::{
future::Ready,
task::{Context, Poll},
};
use tower::{Layer, Service, ServiceExt};
// Mock service that always returns OK
#[derive(Clone)]
struct MockService;
impl tower::Service<Request<Body>> for MockService {
type Response = Response<Body>;
type Error = std::convert::Infallible;
type Future = Ready<Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, _: Request<Body>) -> Self::Future {
std::future::ready(Ok(Response::builder().status(200).body(Body::empty()).unwrap()))
}
}
#[tokio::test]
async fn test_api_key_auth_valid_key() {
let layer = ApiKeyAuthLayer::new("test-key".to_string());
let mut service = layer.layer(MockService);
let body = r#"{"jsonrpc":"2.0","method":"getConfig","id":1}"#;
let request = Request::builder()
.uri("/test")
.header(X_API_KEY, "test-key")
.body(Body::from(body))
.unwrap();
let response = service.ready().await.unwrap().call(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
#[tokio::test]
async fn test_api_key_auth_invalid_key() {
let layer = ApiKeyAuthLayer::new("test-key".to_string());
let mut service = layer.layer(MockService);
let body = r#"{"jsonrpc":"2.0","method":"getConfig","id":1}"#;
let request = Request::builder()
.uri("/test")
.header(X_API_KEY, "wrong-key")
.body(Body::from(body))
.unwrap();
let response = service.ready().await.unwrap().call(request).await.unwrap();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn test_api_key_auth_missing_header() {
let layer = ApiKeyAuthLayer::new("test-key".to_string());
let mut service = layer.layer(MockService);
let body = r#"{"jsonrpc":"2.0","method":"getConfig","id":1}"#;
let request = Request::builder().uri("/test").body(Body::from(body)).unwrap();
let response = service.ready().await.unwrap().call(request).await.unwrap();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn test_api_key_auth_liveness_bypass() {
let layer = ApiKeyAuthLayer::new("test-key".to_string());
let mut service = layer.layer(MockService);
let liveness_body = r#"{"jsonrpc":"2.0","method":"liveness","params":[],"id":1}"#;
let request = Request::builder()
.method(Method::POST)
.uri("/")
.body(Body::from(liveness_body))
.unwrap();
let response = service.ready().await.unwrap().call(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
#[tokio::test]
async fn test_hmac_auth_valid_signature() {
let secret = "test-secret";
let layer = HmacAuthLayer::new(secret.to_string(), DEFAULT_MAX_TIMESTAMP_AGE);
let mut service = layer.layer(MockService);
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs()
.to_string();
let body = r#"{"jsonrpc":"2.0","method":"getConfig","id":1}"#;
let message = format!("{timestamp}{body}");
let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).unwrap();
mac.update(message.as_bytes());
let signature = hex::encode(mac.finalize().into_bytes());
let request = Request::builder()
.method(Method::POST)
.uri("/test")
.header(X_TIMESTAMP, ×tamp)
.header(X_HMAC_SIGNATURE, &signature)
.body(Body::from(body))
.unwrap();
let response = service.ready().await.unwrap().call(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
#[tokio::test]
async fn test_hmac_auth_invalid_signature() {
let secret = "test-secret";
let layer = HmacAuthLayer::new(secret.to_string(), DEFAULT_MAX_TIMESTAMP_AGE);
let mut service = layer.layer(MockService);
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs()
.to_string();
let body = r#"{"jsonrpc":"2.0","method":"getConfig","id":1}"#;
let request = Request::builder()
.method(Method::POST)
.uri("/test")
.header(X_TIMESTAMP, ×tamp)
.header(X_HMAC_SIGNATURE, "invalid-signature")
.body(Body::from(body))
.unwrap();
let response = service.ready().await.unwrap().call(request).await.unwrap();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn test_hmac_auth_missing_headers() {
let secret = "test-secret";
let layer = HmacAuthLayer::new(secret.to_string(), DEFAULT_MAX_TIMESTAMP_AGE);
let mut service = layer.layer(MockService);
let body = r#"{"jsonrpc":"2.0","method":"getConfig","id":1}"#;
let request =
Request::builder().method(Method::POST).uri("/test").body(Body::from(body)).unwrap();
let response = service.ready().await.unwrap().call(request).await.unwrap();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn test_hmac_auth_expired_timestamp() {
let secret = "test-secret";
let layer = HmacAuthLayer::new(secret.to_string(), DEFAULT_MAX_TIMESTAMP_AGE);
let mut service = layer.layer(MockService);
// Timestamp from 10 minutes ago (expired)
let expired_timestamp =
(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs()
- 600)
.to_string();
let body = r#"{"jsonrpc":"2.0","method":"getConfig","id":1}"#;
let message = format!("{expired_timestamp}{body}");
let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).unwrap();
mac.update(message.as_bytes());
let signature = hex::encode(mac.finalize().into_bytes());
let request = Request::builder()
.method(Method::POST)
.uri("/test")
.header(X_TIMESTAMP, &expired_timestamp)
.header(X_HMAC_SIGNATURE, &signature)
.body(Body::from(body))
.unwrap();
let response = service.ready().await.unwrap().call(request).await.unwrap();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn test_hmac_auth_malformed_timestamp() {
let secret = "test-secret";
let layer = HmacAuthLayer::new(secret.to_string(), DEFAULT_MAX_TIMESTAMP_AGE);
let mut service = layer.layer(MockService);
let body = r#"{"jsonrpc":"2.0","method":"getConfig","id":1}"#;
let request = Request::builder()
.method(Method::POST)
.uri("/test")
.header(X_TIMESTAMP, "not-a-number")
.header(X_HMAC_SIGNATURE, "some-signature")
.body(Body::from(body))
.unwrap();
let response = service.ready().await.unwrap().call(request).await.unwrap();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn test_hmac_auth_liveness_bypass() {
let secret = "test-secret";
let layer = HmacAuthLayer::new(secret.to_string(), DEFAULT_MAX_TIMESTAMP_AGE);
let mut service = layer.layer(MockService);
let liveness_body = r#"{"jsonrpc":"2.0","method":"liveness","params":[],"id":1}"#;
let request = Request::builder()
.method(Method::POST)
.uri("/")
.body(Body::from(liveness_body))
.unwrap();
let response = service.ready().await.unwrap().call(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
}