-
Notifications
You must be signed in to change notification settings - Fork 0
/
file29.rs
2469 lines (2274 loc) · 89.5 KB
/
file29.rs
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Request header/body/query extractors
//!
//! Handles ensuring the header's, body, and query parameters are correct, extraction to
//! relevant types, and failing correctly with the appropriate errors if issues arise.
use std::{self, collections::HashMap, num::ParseIntError, str::FromStr};
use actix_web::{
dev::{ConnectionInfo, Extensions, Payload, RequestHead},
http::{
header::{qitem, Accept, ContentType, Header, HeaderMap},
Uri,
},
web::{Data, Json, Query},
Error, FromRequest, HttpMessage, HttpRequest,
};
use futures::future::{self, FutureExt, LocalBoxFuture, Ready, TryFutureExt};
use lazy_static::lazy_static;
use mime::STAR_STAR;
use regex::Regex;
use serde::{
de::{Deserializer, Error as SerdeError, IgnoredAny},
Deserialize, Serialize,
};
use serde_json::Value;
use validator::{Validate, ValidationError};
use crate::db::transaction::DbTransactionPool;
use crate::db::{util::SyncTimestamp, DbPool, Sorting};
use crate::error::{ApiError, ApiErrorKind};
use crate::server::{metrics, ServerState, BSO_ID_REGEX, COLLECTION_ID_REGEX};
use crate::settings::Secrets;
use crate::web::{
auth::HawkPayload,
error::{HawkErrorKind, ValidationErrorKind},
tags::Tags,
X_WEAVE_RECORDS,
};
const BATCH_MAX_IDS: usize = 100;
// BSO const restrictions
const BSO_MAX_TTL: u32 = 999_999_999;
const BSO_MAX_SORTINDEX_VALUE: i32 = 999_999_999;
const BSO_MIN_SORTINDEX_VALUE: i32 = -999_999_999;
const ACCEPTED_CONTENT_TYPES: [&str; 3] =
["application/json", "text/plain", "application/newlines"];
lazy_static! {
static ref KNOWN_BAD_PAYLOAD_REGEX: Regex =
Regex::new(r#"IV":\s*"AAAAAAAAAAAAAAAAAAAAAA=="#).unwrap();
static ref VALID_ID_REGEX: Regex = Regex::new(&format!("^{}$", BSO_ID_REGEX)).unwrap();
static ref VALID_COLLECTION_ID_REGEX: Regex =
Regex::new(&format!("^{}$", COLLECTION_ID_REGEX)).unwrap();
static ref TRUE_REGEX: Regex = Regex::new("^(?i)true$").unwrap();
}
#[derive(Deserialize)]
pub struct UidParam {
#[allow(dead_code)] // Not really dead, but Rust can't see the deserialized use.
uid: u64,
}
fn urldecode(s: &str) -> Result<String, ApiError> {
let decoded: String = urlencoding::decode(s).map_err(|e| {
debug!("unclean entry: {:?} {:?}", s, e);
ApiErrorKind::Internal(e.to_string())
})?;
Ok(decoded)
}
#[derive(Clone, Debug, Deserialize, Validate)]
pub struct BatchBsoBody {
#[validate(custom = "validate_body_bso_id")]
pub id: String,
#[validate(custom = "validate_body_bso_sortindex")]
pub sortindex: Option<i32>,
pub payload: Option<String>,
#[validate(custom = "validate_body_bso_ttl")]
pub ttl: Option<u32>,
}
impl BatchBsoBody {
/// Function to convert valid raw JSON BSO body to a BatchBsoBody
fn from_raw_bso(val: &Value) -> Result<BatchBsoBody, String> {
let map = val.as_object().ok_or("invalid json")?;
// Verify all the keys are valid. modified/collection are allowed but ignored
let valid_keys = [
"id",
"sortindex",
"payload",
"ttl",
"modified",
"collection",
];
for key_name in map.keys() {
if !valid_keys.contains(&key_name.as_str()) {
return Err(format!("unknown field {}", key_name));
}
}
serde_json::from_value(val.clone())
.map_err(|_| "invalid json".to_string())
.and_then(|v: BatchBsoBody| match v.validate() {
Ok(()) => Ok(v),
Err(e) => Err(format!("invalid bso: {}", e)),
})
}
}
// This tries to do the right thing to get the Accepted header according to
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept, but some corners can absolutely be cut.
// This will pull the first accepted content type listed, or the highest rated non-accepted type.
fn get_accepted(req: &HttpRequest, accepted: &[&str], default: &'static str) -> String {
let mut candidates = Accept::parse(req).unwrap_or_else(|_| {
Accept(vec![qitem(
mime::Mime::from_str(default).expect("Could not get accept in get_accepted"),
)])
});
if candidates.is_empty() {
return default.to_owned();
}
candidates.sort_by(|a, b| {
b.quality
.partial_cmp(&a.quality)
.unwrap_or(std::cmp::Ordering::Equal)
});
for qitem in candidates.to_vec() {
if qitem.item == STAR_STAR {
return default.to_owned();
}
let lc = qitem.item.to_string().to_lowercase();
if accepted.contains(&lc.as_str()) {
return lc;
}
}
"invalid".to_string()
}
#[derive(Clone, Default, Deserialize)]
pub struct BsoBodies {
pub valid: Vec<BatchBsoBody>,
pub invalid: HashMap<String, String>,
}
impl FromRequest for BsoBodies {
type Config = ();
type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self, Self::Error>>;
/// Extract the BSO Bodies from the request
///
/// This extraction ensures the following conditions:
/// - Total payload size does not exceed `BATCH_MAX_BYTES`
/// - All BSO's deserialize from the request correctly
/// - Request content-type is a valid value
/// - Valid BSO's include a BSO id
///
/// No collection id is used, so payload checks are not done here.
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
// Only try and parse the body if its a valid content-type
let metrics = metrics::Metrics::from(req);
let tags = Tags::from_request_head(req.head());
let ctype = match ContentType::parse(req) {
Ok(v) => v,
Err(e) => {
return Box::pin(future::err(
ValidationErrorKind::FromDetails(
format!("Unreadable Content-Type: {:?}", e),
RequestErrorLocation::Header,
Some("Content-Type".to_owned()),
Some(tags),
label!("request.validate.bad_content_type"),
)
.into(),
))
}
};
let content_type = format!("{}/{}", ctype.type_(), ctype.subtype());
debug!("content_type: {:?}", &content_type);
if !ACCEPTED_CONTENT_TYPES.contains(&content_type.as_ref()) {
metrics.incr("request.error.invalid_content_type");
return Box::pin(future::err(
ValidationErrorKind::FromDetails(
format!("Invalid Content-Type {:?}", content_type),
RequestErrorLocation::Header,
Some("Content-Type".to_owned()),
Some(tags),
label!("request.validate.bad_content_type"),
)
.into(),
));
}
// Load the entire request into a String
let fut = <String>::from_request(req, payload).map_err(|e| {
warn!("⚠️ Payload read error: {:?}", e);
ValidationErrorKind::FromDetails(
"Mimetype/encoding/content-length error".to_owned(),
RequestErrorLocation::Header,
None,
None,
None,
)
.into()
});
// Avoid duplicating by defining our error func now, doesn't need the box wrapper
fn make_error(tags: Option<Tags>, metrics: metrics::Metrics) -> Error {
metrics.incr_with_tags("request.error.invalid_json", tags.clone());
ValidationErrorKind::FromDetails(
"Invalid JSON in request body".to_owned(),
RequestErrorLocation::Body,
Some("bsos".to_owned()),
tags,
label!("request.validate.invalid_body_json"),
)
.into()
}
// Define a new bool to check from a static closure to release the reference on the
// content_type header
let newlines: bool = content_type == "application/newlines";
// Grab the max sizes
let state = match req.app_data::<Data<ServerState>>() {
Some(s) => s,
None => {
error!("⚠️ Could not load the app state");
return Box::pin(future::err(
ValidationErrorKind::FromDetails(
"Internal error".to_owned(),
RequestErrorLocation::Unknown,
Some("app_data".to_owned()),
None,
None,
)
.into(),
));
}
};
// ### debug_client
if let Some(uids) = &state.limits.debug_client {
for uid in uids.split(',') {
debug!("### checking uaid: {:?}", &uid);
match u64::from_str(uid.trim()) {
Ok(v) => {
if v == HawkIdentifier::uid_from_path(req.uri(), None).unwrap_or(0) {
error!("Returning over quota for {:?}", v);
return Box::pin(future::err(
ValidationErrorKind::FromDetails(
"over-quota".to_owned(),
RequestErrorLocation::Unknown,
Some("over-quota".to_owned()),
Some(tags),
label!("storage.over_quota"),
)
.into(),
));
}
}
Err(_) => {
debug!("{:?} is not a u64", uid);
}
};
}
}
let max_payload_size = state.limits.max_record_payload_bytes as usize;
let max_post_bytes = state.limits.max_post_bytes as usize;
let fut = fut.and_then(move |body| {
// Get all the raw / values
let bsos: Vec<Value> = if newlines {
let mut bsos = Vec::new();
for item in body.lines() {
// Check that its a valid JSON map like we expect
if let Ok(raw_json) = serde_json::from_str::<Value>(&item) {
bsos.push(raw_json);
} else {
// Per Python version, BSO's must json deserialize
return future::err(make_error(None, metrics));
}
}
bsos
} else if let Ok(json_vals) = serde_json::from_str::<Vec<Value>>(&body) {
json_vals
} else {
// Per Python version, BSO's must json deserialize
return future::err(make_error(None, metrics));
};
// Validate all the BSO's, move invalid to our other list. Assume they'll all make
// it with our pre-allocation
let mut valid: Vec<BatchBsoBody> = Vec::with_capacity(bsos.len());
// Invalid BSO's are any BSO that can deserialize despite how wrong the contents are
// per the way the Python version works.
let mut invalid: HashMap<String, String> = HashMap::new();
// Keep track of our total payload size
let mut total_payload_size = 0;
// Temporarily track the bso id's for dupe detection
let mut bso_ids: Vec<String> = Vec::with_capacity(bsos.len());
for bso in bsos {
// Error out if its not a JSON mapping type
if !bso.is_object() {
return future::err(make_error(None, metrics));
}
// Save all id's we get, check for missing id, or duplicate.
let bso_id = if let Some(id) = bso.get("id").and_then(serde_json::Value::as_str) {
let id = id.to_string();
if bso_ids.contains(&id) {
return future::err(
ValidationErrorKind::FromDetails(
"Input BSO has duplicate ID".to_owned(),
RequestErrorLocation::Body,
Some("bsos".to_owned()),
Some(tags),
label!("request.store.duplicate_bso_id"),
)
.into(),
);
} else {
bso_ids.push(id.clone());
id
}
} else {
return future::err(
ValidationErrorKind::FromDetails(
"Input BSO has no ID".to_owned(),
RequestErrorLocation::Body,
Some("bsos".to_owned()),
Some(tags),
label!("request.store.missing_bso_id"),
)
.into(),
);
};
match BatchBsoBody::from_raw_bso(&bso) {
Ok(b) => {
// Is this record too large? Deny if it is.
let payload_size = b
.payload
.as_ref()
.map(std::string::String::len)
.unwrap_or_default();
total_payload_size += payload_size;
if payload_size <= max_payload_size && total_payload_size <= max_post_bytes
{
valid.push(b);
} else {
invalid.insert(b.id, "retry bytes".to_string());
}
}
Err(e) => {
invalid.insert(bso_id, e);
}
}
}
future::ok(BsoBodies { valid, invalid })
});
Box::pin(fut)
}
}
#[derive(Default, Debug, Deserialize, Serialize, Validate)]
#[serde(deny_unknown_fields)]
pub struct BsoBody {
#[validate(custom = "validate_body_bso_id")]
pub id: Option<String>,
#[validate(custom = "validate_body_bso_sortindex")]
pub sortindex: Option<i32>,
pub payload: Option<String>,
#[validate(custom = "validate_body_bso_ttl")]
pub ttl: Option<u32>,
/// Any client-supplied value for these fields are ignored
#[serde(rename(deserialize = "modified"), skip_serializing)]
pub _ignored_modified: Option<IgnoredAny>,
#[serde(rename(deserialize = "collection"), skip_serializing)]
pub _ignored_collection: Option<IgnoredAny>,
}
impl FromRequest for BsoBody {
type Config = ();
type Error = Error;
type Future = LocalBoxFuture<'static, Result<BsoBody, Self::Error>>;
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
// Only try and parse the body if its a valid content-type
let tags = Tags::from_request_head(req.head());
let ftags = tags.clone();
let fftags = tags.clone();
let ctype = match ContentType::parse(req) {
Ok(v) => v,
Err(e) => {
return Box::pin(future::err(
ValidationErrorKind::FromDetails(
format!("Unreadable Content-Type: {:?}", e),
RequestErrorLocation::Header,
Some("Content-Type".to_owned()),
Some(tags),
label!("request.validate.bad_content_type"),
)
.into(),
))
}
};
let content_type = format!("{}/{}", ctype.type_(), ctype.subtype());
if !ACCEPTED_CONTENT_TYPES.contains(&content_type.as_ref()) {
return Box::pin(future::err(
ValidationErrorKind::FromDetails(
"Invalid Content-Type".to_owned(),
RequestErrorLocation::Header,
Some("Content-Type".to_owned()),
Some(tags),
label!("request.validate.bad_content_type"),
)
.into(),
));
}
let state = match req.app_data::<Data<ServerState>>() {
Some(s) => s,
None => {
error!("⚠️ Could not load the app state");
return Box::pin(future::err(
ValidationErrorKind::FromDetails(
"Internal error".to_owned(),
RequestErrorLocation::Unknown,
Some("app_data".to_owned()),
None,
None,
)
.into(),
));
}
};
// ### debug_client
if let Some(uids) = &state.limits.debug_client {
for uid in uids.split(',') {
debug!("### checking uaid: {:?}", &uid);
match u64::from_str(uid.trim()) {
Ok(v) => {
if v == HawkIdentifier::uid_from_path(req.uri(), None).unwrap_or(0) {
debug!("### returning quota exceeded.");
error!("Returning over quota for {:?}", v);
return Box::pin(future::err(
ValidationErrorKind::FromDetails(
"over-quota".to_owned(),
RequestErrorLocation::Unknown,
Some("over-quota".to_owned()),
Some(tags),
label!("request.store.user_over_quota"),
)
.into(),
));
}
}
Err(_) => {
debug!("{:?} is not a u64", uid);
}
};
}
}
let max_payload_size = state.limits.max_record_payload_bytes as usize;
let fut = <Json<BsoBody>>::from_request(&req, payload)
.map_err(|e| {
warn!("⚠️ Could not parse BSO Body: {:?}", e);
let err: ApiError = ValidationErrorKind::FromDetails(
e.to_string(),
RequestErrorLocation::Body,
Some("bso".to_owned()),
Some(tags),
label!("request.validate.bad_bso_body"),
)
.into();
err.into()
})
.and_then(move |bso: Json<BsoBody>| {
// Check the max payload size manually with our desired limit
if bso
.payload
.as_ref()
.map(std::string::String::len)
.unwrap_or_default()
> max_payload_size
{
let err: ApiError = ValidationErrorKind::FromDetails(
"payload too large".to_owned(),
RequestErrorLocation::Body,
Some("bso".to_owned()),
Some(ftags),
label!("request.validate.payload_too_large"),
)
.into();
return future::err(err.into());
}
if let Err(e) = bso.validate() {
let err: ApiError = ValidationErrorKind::FromValidationErrors(
e,
RequestErrorLocation::Body,
Some(fftags),
None,
)
.into();
return future::err(err.into());
}
future::ok(bso.into_inner())
});
Box::pin(fut)
}
}
/// Bso id parameter extractor
#[derive(Clone, Debug, Deserialize, Validate)]
pub struct BsoParam {
#[validate(regex = "VALID_ID_REGEX")]
pub bso: String,
}
impl BsoParam {
fn bsoparam_from_path(uri: &Uri, tags: &Tags) -> Result<Self, Error> {
// TODO: replace with proper path parser
// path: "/1.5/{uid}/storage/{collection}/{bso}"
let elements: Vec<&str> = uri.path().split('/').collect();
let elem = elements.get(3);
if elem.is_none() || elem != Some(&"storage") || elements.len() != 6 {
return Err(ValidationErrorKind::FromDetails(
"Invalid BSO".to_owned(),
RequestErrorLocation::Path,
Some("bso".to_owned()),
Some(tags.clone()),
label!("request.process.invalid_bso"),
))?;
}
if let Some(v) = elements.get(5) {
let sv = urldecode(&String::from_str(v).map_err(|e| {
warn!("⚠️ Invalid BsoParam Error: {:?} {:?}", v, e; tags);
ValidationErrorKind::FromDetails(
"Invalid BSO".to_owned(),
RequestErrorLocation::Path,
Some("bso".to_owned()),
Some(tags.clone()),
label!("request.process.invalid_bso"),
)
})?)
.map_err(|e| {
warn!("⚠️ Invalid BsoParam Error: {:?} {:?}", v, e; tags);
ValidationErrorKind::FromDetails(
"Invalid BSO".to_owned(),
RequestErrorLocation::Path,
Some("bso".to_owned()),
Some(tags.clone()),
label!("request.process.invalid_bso"),
)
})?;
Ok(Self { bso: sv })
} else {
warn!("⚠️ Missing BSO: {:?}", uri.path(); tags);
Err(ValidationErrorKind::FromDetails(
"Missing BSO".to_owned(),
RequestErrorLocation::Path,
Some("bso".to_owned()),
Some(tags.clone()),
label!("request.process.missing_bso"),
))?
}
}
pub fn extrude(head: &RequestHead, extensions: &mut Extensions) -> Result<Self, Error> {
let uri = head.uri.clone();
let tags = Tags::from_request_head(head);
if let Some(bso) = extensions.get::<BsoParam>() {
return Ok(bso.clone());
}
let bso = Self::bsoparam_from_path(&uri, &tags)?;
bso.validate().map_err(|e| {
ValidationErrorKind::FromValidationErrors(
e,
RequestErrorLocation::Path,
Some(tags.clone()),
None,
)
})?;
extensions.insert(bso.clone());
Ok(bso)
}
}
impl FromRequest for BsoParam {
type Config = ();
type Error = Error;
type Future = Ready<Result<Self, Self::Error>>;
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
future::ready(Self::extrude(req.head(), &mut req.extensions_mut()))
}
}
/// Collection parameter Extractor
#[derive(Clone, Debug, Deserialize, Validate)]
pub struct CollectionParam {
#[validate(regex = "VALID_COLLECTION_ID_REGEX")]
pub collection: String,
}
impl CollectionParam {
fn col_from_path(uri: &Uri, tags: &Tags) -> Result<Option<CollectionParam>, Error> {
// TODO: replace with proper path parser.
// path: "/1.5/{uid}/storage/{collection}"
let elements: Vec<&str> = uri.path().split('/').collect();
let elem = elements.get(3);
if elem.is_none() || elem != Some(&"storage") || !(5..=6).contains(&elements.len()) {
return Ok(None);
}
if let Some(v) = elements.get(4) {
let mut sv = String::from_str(v).map_err(|_e| {
ValidationErrorKind::FromDetails(
"Missing Collection".to_owned(),
RequestErrorLocation::Path,
Some("collection".to_owned()),
Some(tags.clone()),
label!("request.process.missing_collection"),
)
})?;
sv = urldecode(&sv).map_err(|_e| {
ValidationErrorKind::FromDetails(
"Invalid Collection".to_owned(),
RequestErrorLocation::Path,
Some("collection".to_owned()),
Some(tags.clone()),
label!("request.process.invalid_collection"),
)
})?;
Ok(Some(Self { collection: sv }))
} else {
Err(ValidationErrorKind::FromDetails(
"Missing Collection".to_owned(),
RequestErrorLocation::Path,
Some("collection".to_owned()),
Some(tags.clone()),
label!("request.process.missing_collection"),
))?
}
}
pub fn extrude(
uri: &Uri,
extensions: &mut Extensions,
tags: &Tags,
) -> Result<Option<Self>, Error> {
if let Some(collection) = extensions.get::<Option<Self>>() {
return Ok(collection.clone());
}
let collection = Self::col_from_path(&uri, tags)?;
let result = if let Some(collection) = collection {
collection.validate().map_err(|e| {
ValidationErrorKind::FromValidationErrors(
e,
RequestErrorLocation::Path,
Some(tags.clone()),
None,
)
})?;
Some(collection)
} else {
None
};
extensions.insert(result.clone());
Ok(result)
}
}
impl FromRequest for CollectionParam {
type Config = ();
type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self, Self::Error>>;
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
let fut = Tags::from_request(req, payload);
let req = req.clone();
Box::pin(async move {
let tags = fut.await?;
if let Some(collection) = Self::extrude(&req.uri(), &mut req.extensions_mut(), &tags)? {
Ok(collection)
} else {
Err(ValidationErrorKind::FromDetails(
"Missing Collection".to_owned(),
RequestErrorLocation::Path,
Some("collection".to_owned()),
Some(tags),
label!("request.process.missing_collection"),
))?
}
})
}
}
/// Information Requests extractor
///
/// Only the database and user identifier is required for information
/// requests: https://mozilla-services.readthedocs.io/en/latest/storage/apis-1.5.html#general-info
pub struct MetaRequest {
pub user_id: HawkIdentifier,
pub metrics: metrics::Metrics,
pub tags: Tags,
}
impl FromRequest for MetaRequest {
type Config = ();
type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self, Self::Error>>;
fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
let req = req.clone();
let mut payload = Payload::None;
async move {
// Call the precondition stuff to init database handles and what-not
let tags = {
let exts = req.extensions();
match exts.get::<Tags>() {
Some(t) => t.clone(),
None => Tags::from_request_head(req.head()),
}
};
let user_id = HawkIdentifier::from_request(&req, &mut payload).await?;
Ok(MetaRequest {
user_id,
metrics: metrics::Metrics::from(&req),
tags,
})
}
.boxed_local()
}
}
/// Desired reply format for a Collection Get request
#[derive(Copy, Clone, Debug)]
pub enum ReplyFormat {
Json,
Newlines,
}
/// Collection Request Delete/Get extractor
///
/// Extracts/validates information needed for collection delete/get requests.
pub struct CollectionRequest {
pub collection: String,
pub user_id: HawkIdentifier,
pub query: BsoQueryParams,
pub reply: ReplyFormat,
pub metrics: metrics::Metrics,
pub tags: Option<Tags>,
}
impl FromRequest for CollectionRequest {
type Config = ();
type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self, Self::Error>>;
fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
let req = req.clone();
let mut payload = Payload::None;
async move {
let user_id = HawkIdentifier::from_request(&req, &mut payload).await?;
let query = BsoQueryParams::from_request(&req, &mut payload).await?;
let collection = CollectionParam::from_request(&req, &mut payload)
.await?
.collection;
let tags = {
let exts = req.extensions();
match exts.get::<Tags>() {
Some(t) => t.clone(),
None => Tags::from_request_head(req.head()),
}
};
let accept = get_accepted(&req, &ACCEPTED_CONTENT_TYPES, "application/json");
let reply = match accept.as_str() {
"application/newlines" => ReplyFormat::Newlines,
"application/json" | "" => ReplyFormat::Json,
_ => {
return Err(ValidationErrorKind::FromDetails(
format!("Invalid Accept header specified: {:?}", accept),
RequestErrorLocation::Header,
Some("accept".to_string()),
Some(tags),
label!("request.validate.invalid_accept_header"),
)
.into());
}
};
Ok(CollectionRequest {
collection,
user_id,
query,
reply,
metrics: metrics::Metrics::from(&req),
tags: Some(tags),
})
}
.boxed_local()
}
}
/// Collection Request Post extractor
///
/// Extracts/validates information needed for batch collection POST requests.
pub struct CollectionPostRequest {
pub collection: String,
pub user_id: HawkIdentifier,
pub query: BsoQueryParams,
pub bsos: BsoBodies,
pub batch: Option<BatchRequest>,
pub metrics: metrics::Metrics,
}
impl FromRequest for CollectionPostRequest {
type Config = ();
type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self, Self::Error>>;
/// Extractor for Collection Posts (Batch BSO upload)
///
/// Utilizes the `BsoBodies` for parsing, and add's two validation steps not
/// done previously:
/// - If the collection is 'crypto', known bad payloads are checked for
/// - Any valid BSO's beyond `BATCH_MAX_RECORDS` are moved to invalid
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
let req = req.clone();
let mut payload = payload.take();
Box::pin(async move {
let tags = match req.extensions().get::<Tags>() {
Some(t) => t.clone(),
None => Tags::from_request_head(req.head()),
};
let state = match req.app_data::<Data<ServerState>>() {
Some(s) => s,
None => {
error!("⚠️ Could not load the app state");
return Err(ValidationErrorKind::FromDetails(
"Internal error".to_owned(),
RequestErrorLocation::Unknown,
Some("app_data".to_owned()),
Some(tags),
None,
)
.into());
}
};
let max_post_records = i64::from(state.limits.max_post_records);
let user_id = HawkIdentifier::from_request(&req, &mut payload).await?;
let collection = CollectionParam::from_request(&req, &mut payload).await?;
let query = BsoQueryParams::from_request(&req, &mut payload).await?;
let mut bsos = BsoBodies::from_request(&req, &mut payload).await?;
let collection = collection.collection;
if collection == "crypto" {
// Verify the client didn't mess up the crypto if we have a payload
for bso in &bsos.valid {
if let Some(ref data) = bso.payload {
if KNOWN_BAD_PAYLOAD_REGEX.is_match(data) {
return Err(ValidationErrorKind::FromDetails(
"Known-bad BSO payload".to_owned(),
RequestErrorLocation::Body,
Some("bsos".to_owned()),
Some(tags),
label!("request.process.known_bad_bso"),
)
.into());
}
}
}
}
// Trim the excess BSO's to be under the batch size
let overage: i64 = (bsos.valid.len() as i64) - max_post_records;
if overage > 0 {
for _ in 1..=overage {
if let Some(last) = bsos.valid.pop() {
bsos.invalid.insert(last.id, "retry bso".to_string());
}
}
}
// XXX: let's not use extract here (maybe convert to extrude?)
let batch = BatchRequestOpt::extract(&req).await?;
Ok(CollectionPostRequest {
collection,
user_id,
query,
bsos,
batch: batch.opt,
metrics: metrics::Metrics::from(&req),
})
})
}
}
/// BSO Request Delete/Get extractor
///
/// Extracts/validates information needed for BSO delete/get requests.
#[derive(Debug)]
pub struct BsoRequest {
pub collection: String,
pub user_id: HawkIdentifier,
pub query: BsoQueryParams,
pub bso: String,
pub metrics: metrics::Metrics,
}
impl FromRequest for BsoRequest {
type Config = ();
type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self, Self::Error>>;
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
let req = req.clone();
let mut payload = payload.take();
Box::pin(async move {
let user_id = HawkIdentifier::from_request(&req, &mut payload).await?;
let query = BsoQueryParams::from_request(&req, &mut payload).await?;
let collection = CollectionParam::from_request(&req, &mut payload)
.await?
.collection;
let bso = BsoParam::from_request(&req, &mut payload).await?;
Ok(BsoRequest {
collection,
user_id,
query,
bso: bso.bso,
metrics: metrics::Metrics::from(&req),
})
})
}
}
/// BSO Request Put extractor
///
/// Extracts/validates information needed for BSO put requests.
pub struct BsoPutRequest {
pub collection: String,
pub user_id: HawkIdentifier,
pub query: BsoQueryParams,
pub bso: String,
pub body: BsoBody,
pub metrics: metrics::Metrics,
}
impl FromRequest for BsoPutRequest {
type Config = ();
type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self, Self::Error>>;
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
let metrics = metrics::Metrics::from(req);
let req = req.clone();
let mut payload = payload.take();
async move {
let user_id = HawkIdentifier::from_request(&req, &mut payload).await?;
let collection = CollectionParam::from_request(&req, &mut payload).await?;
let query = BsoQueryParams::from_request(&req, &mut payload).await?;
let bso = BsoParam::from_request(&req, &mut payload).await?;
let body = BsoBody::from_request(&req, &mut payload).await?;
let tags = Tags::from_request(&req, &mut payload).await?;
let collection = collection.collection;
if collection == "crypto" {
// Verify the client didn't mess up the crypto if we have a payload
if let Some(ref data) = body.payload {
if KNOWN_BAD_PAYLOAD_REGEX.is_match(data) {
return Err(ValidationErrorKind::FromDetails(
"Known-bad BSO payload".to_owned(),
RequestErrorLocation::Body,
Some("bsos".to_owned()),
Some(tags),
label!("request.process.known_bad_bso"),
)
.into());
}
}
}