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
use std::fmt;
use actix_http::BoxedPayloadStream;
use actix_web::{dev, web::Bytes, Error, FromRequest, HttpRequest};
use async_trait::async_trait;
use derive_more::Display;
use futures_core::future::LocalBoxFuture;
use futures_util::{FutureExt as _, StreamExt as _, TryFutureExt as _};
use local_channel::mpsc;
use tokio::try_join;
use tracing::trace;
#[async_trait(?Send)]
pub trait RequestSignatureScheme: Sized {
type Signature;
type Error: Into<Error>;
async fn init(req: &HttpRequest) -> Result<Self, Self::Error>;
async fn consume_chunk(&mut self, req: &HttpRequest, chunk: Bytes) -> Result<(), Self::Error>;
async fn finalize(self, req: &HttpRequest) -> Result<Self::Signature, Self::Error>;
#[allow(unused_variables)]
#[inline]
fn verify(
signature: Self::Signature,
req: &HttpRequest,
) -> Result<Self::Signature, Self::Error> {
Ok(signature)
}
}
#[derive(Clone)]
pub struct RequestSignature<T, S: RequestSignatureScheme> {
extractor: T,
signature: S::Signature,
}
impl<T, S: RequestSignatureScheme> RequestSignature<T, S> {
pub fn into_parts(self) -> (T, S::Signature) {
(self.extractor, self.signature)
}
}
#[derive(Display)]
#[non_exhaustive]
pub enum RequestSignatureError<T, S>
where
T: FromRequest,
T::Error: fmt::Debug + fmt::Display,
S: RequestSignatureScheme,
S::Error: fmt::Debug + fmt::Display,
{
#[display(fmt = "Inner extractor error: {_0}")]
Extractor(T::Error),
#[display(fmt = "Signature calculation error: {_0}")]
Signature(S::Error),
}
impl<T, S> fmt::Debug for RequestSignatureError<T, S>
where
T: FromRequest,
T::Error: fmt::Debug + fmt::Display,
S: RequestSignatureScheme,
S::Error: fmt::Debug + fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Extractor(err) => f
.debug_tuple("RequestSignatureError::Extractor")
.field(err)
.finish(),
Self::Signature(err) => f
.debug_tuple("RequestSignatureError::Signature")
.field(err)
.finish(),
}
}
}
impl<T, S> From<RequestSignatureError<T, S>> for actix_web::Error
where
T: FromRequest,
T::Error: fmt::Debug + fmt::Display,
S: RequestSignatureScheme,
S::Error: fmt::Debug + fmt::Display,
{
fn from(err: RequestSignatureError<T, S>) -> Self {
match err {
RequestSignatureError::Extractor(err) => err.into(),
RequestSignatureError::Signature(err) => err.into(),
}
}
}
impl<T, S> FromRequest for RequestSignature<T, S>
where
T: FromRequest + 'static,
T::Error: fmt::Debug + fmt::Display,
S: RequestSignatureScheme + 'static,
S::Error: fmt::Debug + fmt::Display,
{
type Error = RequestSignatureError<T, S>;
type Future = LocalBoxFuture<'static, Result<Self, Self::Error>>;
fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future {
let req = req.clone();
let payload = payload.take();
Box::pin(async move {
let (tx, mut rx) = mpsc::channel();
let proxy_stream: BoxedPayloadStream = Box::pin(payload.inspect(move |res| {
if let Ok(chunk) = res {
trace!("yielding {} byte chunk", chunk.len());
tx.send(chunk.clone()).unwrap();
}
}));
trace!("creating proxy payload");
let mut proxy_payload = dev::Payload::from(proxy_stream);
let body_fut =
T::from_request(&req, &mut proxy_payload).map_err(RequestSignatureError::Extractor);
trace!("initializing signature scheme");
let mut sig_scheme = S::init(&req)
.await
.map_err(RequestSignatureError::Signature)?;
let hash_fut = actix_web::rt::spawn({
let req = req.clone();
async move {
while let Some(chunk) = rx.recv().await {
trace!("digesting chunk");
sig_scheme.consume_chunk(&req, chunk).await?;
}
trace!("finalizing signature");
sig_scheme.finalize(&req).await
}
})
.map(Result::unwrap)
.map_err(RequestSignatureError::Signature);
trace!("driving both futures");
let (body, signature) = try_join!(body_fut, hash_fut)?;
trace!("verifying signature");
let signature = S::verify(signature, &req).map_err(RequestSignatureError::Signature)?;
let out = Self {
extractor: body,
signature,
};
Ok(out)
})
}
}
#[cfg(test)]
mod tests {
use std::convert::Infallible;
use actix_web::{
http::StatusCode,
test,
web::{self, Bytes},
App,
};
use digest::{CtOutput, Digest as _};
use hex_literal::hex;
use sha2::Sha256;
use super::*;
use crate::extract::Json;
#[derive(Debug, Default)]
struct JustHash(sha2::Sha256);
#[async_trait(?Send)]
impl RequestSignatureScheme for JustHash {
type Signature = CtOutput<sha2::Sha256>;
type Error = Infallible;
async fn init(head: &HttpRequest) -> Result<Self, Self::Error> {
let mut hasher = Sha256::new();
if let Some(path) = head.uri().path_and_query() {
hasher.update(path.as_str().as_bytes())
}
Ok(Self(hasher))
}
async fn consume_chunk(
&mut self,
_req: &HttpRequest,
chunk: Bytes,
) -> Result<(), Self::Error> {
self.0.update(&chunk);
Ok(())
}
async fn finalize(self, _req: &HttpRequest) -> Result<Self::Signature, Self::Error> {
let hash = self.0.finalize();
Ok(CtOutput::new(hash))
}
}
#[actix_web::test]
async fn correctly_hashes_payload() {
let app = test::init_service(App::new().route(
"/service/path",
web::get().to(|body: RequestSignature<Bytes, JustHash>| async move {
let (_, sig) = body.into_parts();
sig.into_bytes().to_vec()
}),
))
.await;
let req = test::TestRequest::with_uri("/service/path").to_request();
let body = test::call_and_read_body(&app, req).await;
assert_eq!(
body,
hex!("a5441a3d ec265f82 3758d164 1188ab1d d1093972 45012a45 fa66df70 32d02177")
.as_ref()
);
let req = test::TestRequest::with_uri("/service/path")
.set_payload("abc")
.to_request();
let body = test::call_and_read_body(&app, req).await;
assert_eq!(
body,
hex!("555290a8 9e75260d fb0afead 2d5d3d70 f058c85d 1ff98bf3 06807301 7ce4c847")
.as_ref()
);
}
#[actix_web::test]
async fn respects_inner_extractor_errors() {
let app = test::init_service(App::new().route(
"/",
web::get().to(
|body: RequestSignature<Json<u64, 4>, JustHash>| async move {
let (_, sig) = body.into_parts();
sig.into_bytes().to_vec()
},
),
))
.await;
let req = test::TestRequest::default().set_json(1234).to_request();
let body = test::call_and_read_body(&app, req).await;
assert_eq!(
body,
hex!("4f373f6c cadfaba3 1a32cf52 04cf3db9 367609ee 6a7d7113 8e4f28ef 7c1a87a9")
.as_ref()
);
let req = test::TestRequest::default().to_request();
let body = test::call_service(&app, req).await;
assert_eq!(body.status(), StatusCode::BAD_REQUEST);
let req = test::TestRequest::default().set_json(12345).to_request();
let body = test::call_service(&app, req).await;
assert_eq!(body.status(), StatusCode::PAYLOAD_TOO_LARGE);
}
}