-
Notifications
You must be signed in to change notification settings - Fork 45
/
auth.rs
576 lines (498 loc) · 17.4 KB
/
auth.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
//! Types for parsing and authenticating HAWK headers.
//! Matches the [Python logic](https://github.com/mozilla-services/tokenlib).
//! We may want to extract this to its own repo/crate in due course.
#![cfg_attr(
feature = "no_auth",
allow(dead_code, unused_imports, unused_variables)
)]
use std::convert::TryInto;
use chrono::offset::Utc;
use hawk::{self, Header as HawkHeader, Key, RequestBuilder};
use hkdf::Hkdf;
use hmac::{Hmac, Mac, NewMac};
use serde::{Deserialize, Serialize};
use sha2::Sha256;
use time::Duration;
use actix_web::dev::ConnectionInfo;
use actix_web::http::Uri;
use super::{
error::{HawkErrorKind, ValidationErrorKind},
extractors::RequestErrorLocation,
};
use crate::error::{ApiErrorKind, ApiResult};
use crate::settings::Secrets;
/// A parsed and authenticated JSON payload
/// extracted from the signed `id` property
/// of a Hawk `Authorization` header.
///
/// Not included here are the `fxa_uid` and `device_id` properties,
/// which may also be present in the JSON payload.
#[derive(Debug, Deserialize, PartialEq, Serialize)]
pub struct HawkPayload {
/// Expiry time for the payload, in seconds.
pub expires: f64,
/// Base URI for the storage node.
pub node: String,
/// Salt used during HKDF-expansion of the token secret.
pub salt: String,
/// User identifier.
#[serde(rename = "uid")]
pub user_id: u64,
#[serde(default)]
pub fxa_uid: String,
#[serde(default)]
pub fxa_kid: String,
#[serde(default, rename = "hashed_device_id")]
pub device_id: String,
}
impl HawkPayload {
/// Parse and authenticate a payload
/// using the supplied arguments.
///
/// Assumes that the header string
/// includes the `Hawk ` prefix.
fn new(
header: &str,
method: &str,
path: &str,
host: &str,
port: u16,
secrets: &Secrets,
expiry: u64,
) -> ApiResult<HawkPayload> {
if header.len() < 5 || &header[0..5] != "Hawk " {
Err(HawkErrorKind::MissingPrefix)?;
}
let header: HawkHeader = header[5..].parse()?;
let id = header.id.as_ref().ok_or(HawkErrorKind::MissingId)?;
let payload = HawkPayload::extract_and_validate(id, secrets, expiry)?;
let token_secret = hkdf_expand_32(
format!("services.mozilla.com/tokenlib/v1/derive/{}", id).as_bytes(),
Some(payload.salt.as_bytes()),
&secrets.master_secret,
)?;
let token_secret = base64::encode_config(&token_secret, base64::URL_SAFE);
let request = RequestBuilder::new(method, host, port, path).request();
#[cfg(feature = "no_auth")]
{
Ok(payload)
}
#[cfg(not(feature = "no_auth"))]
{
let mut duration: std::time::Duration = Duration::weeks(52)
.try_into()
.map_err(|_| ApiErrorKind::Internal("Duration::weeks".to_owned()))?;
if cfg!(test) {
// test cases are valid until 3018. Add millenia as required.
duration *= 1000;
}
if request.validate_header(
&header,
&Key::new(token_secret.as_bytes(), hawk::DigestAlgorithm::Sha256)?,
// Allow plenty of leeway for clock skew, because
// client timestamps tend to be all over the shop
duration,
) {
Ok(payload)
} else {
Err(HawkErrorKind::InvalidHeader)?
}
}
}
/// Decode the `id` property of a Hawk header
/// and verify the payload part against the signature part.
fn extract_and_validate(id: &str, secrets: &Secrets, expiry: u64) -> ApiResult<HawkPayload> {
let decoded_id = base64::decode_config(id, base64::URL_SAFE)?;
if decoded_id.len() <= 32 {
Err(HawkErrorKind::TruncatedId)?;
}
let payload_length = decoded_id.len() - 32;
let payload = &decoded_id[0..payload_length];
let signature = &decoded_id[payload_length..];
#[cfg(not(feature = "no_auth"))]
verify_hmac(payload, &secrets.signing_secret, signature)?;
let payload: HawkPayload = serde_json::from_slice(payload)?;
if expiry == 0 || (payload.expires.round() as u64) > expiry {
Ok(payload)
} else {
Err(HawkErrorKind::Expired)?
}
}
#[cfg(test)]
pub fn test_default(user_id: u64) -> Self {
HawkPayload {
expires: Utc::now().timestamp() as f64 + 200_000.0,
node: "friendly-node".to_string(),
salt: "saltysalt".to_string(),
user_id,
fxa_uid: "xxx_test".to_owned(),
fxa_kid: "xxx_test".to_owned(),
device_id: "xxx_test".to_owned(),
}
}
}
impl HawkPayload {
pub fn extrude(
header: &str,
method: &str,
secrets: &Secrets,
ci: &ConnectionInfo,
uri: &Uri,
) -> ApiResult<Self> {
let host_port: Vec<_> = ci.host().splitn(2, ':').collect();
let host = host_port[0];
let port = if host_port.len() == 2 {
host_port[1].parse().map_err(|_| {
ValidationErrorKind::FromDetails(
"Invalid port (hostname:port) specified".to_owned(),
RequestErrorLocation::Header,
None,
label!("request.validate.hawk.invalid_port"),
)
})?
} else if ci.scheme() == "https" {
443
} else {
80
};
let path = uri.path_and_query().ok_or(HawkErrorKind::MissingPath)?;
let expiry = if path.path().ends_with("/info/collections") {
0
} else {
Utc::now().timestamp() as u64
};
HawkPayload::new(header, method, path.as_str(), host, port, secrets, expiry)
}
}
/// Helper function for [HKDF](https://tools.ietf.org/html/rfc5869) expansion to 32 bytes.
pub fn hkdf_expand_32(info: &[u8], salt: Option<&[u8]>, key: &[u8]) -> ApiResult<[u8; 32]> {
let mut result = [0u8; 32];
let hkdf = Hkdf::<Sha256>::new(salt, key);
// This unwrap will never panic because 32 bytes is a valid size for Hkdf<Sha256>
hkdf.expand(info, &mut result)
.map_err(|e| ApiErrorKind::Internal(format!("HKDF Error: {:?}", e)))?;
Ok(result)
}
/// Helper function for [HMAC](https://tools.ietf.org/html/rfc2104) verification.
fn verify_hmac(info: &[u8], key: &[u8], expected: &[u8]) -> ApiResult<()> {
let mut hmac = Hmac::<Sha256>::new_from_slice(key)?;
hmac.update(info);
hmac.verify(expected).map_err(From::from)
}
#[cfg(test)]
mod tests {
use super::{HawkPayload, Secrets};
use crate::settings::Settings;
#[test]
fn valid_header() {
let fixture = TestFixture::new();
let result = HawkPayload::new(
&fixture.header.to_string(),
&fixture.request.method,
&fixture.request.path,
&fixture.request.host,
fixture.request.port,
&fixture.settings.master_secret,
fixture.expected.expires.round() as u64 - 1,
);
assert!(result.is_ok());
result
.map(|payload| assert_eq!(payload, fixture.expected))
.unwrap();
}
#[test]
fn valid_header_with_querystring() {
let mut fixture = TestFixture::new();
fixture.header.mac = "E7j1UjN7//mh7pYXsgGi3n0KGR+sUPpuyogDVzJWaHg=".to_string();
fixture.header.nonce = "4Rj7c+0=".to_string();
fixture.header.ts = 1_569_608_439;
fixture.request.method = "POST".to_string();
fixture
.request
.path
.push_str("?batch=MTUzNjE5ODk3NjkyMQ==&commit=true");
let result = HawkPayload::new(
&fixture.header.to_string(),
&fixture.request.method,
&fixture.request.path,
&fixture.request.host,
fixture.request.port,
&fixture.settings.master_secret,
fixture.expected.expires.round() as u64 - 1,
);
assert!(result.is_ok());
result
.map(|payload| assert_eq!(payload, fixture.expected))
.unwrap();
}
#[test]
fn missing_hawk_prefix() {
let fixture = TestFixture::new();
let result = HawkPayload::new(
&fixture.header.to_string()[1..],
&fixture.request.method,
&fixture.request.path,
&fixture.request.host,
fixture.request.port,
&fixture.settings.master_secret,
fixture.expected.expires.round() as u64 - 1,
);
assert!(result.is_err());
}
#[test]
fn bad_short_header() {
let fixture = TestFixture::new();
let result = HawkPayload::new(
"True",
&fixture.request.method,
&fixture.request.path,
&fixture.request.host,
fixture.request.port,
&fixture.settings.master_secret,
fixture.expected.expires.round() as u64 - 1,
);
assert!(result.is_err());
}
#[test]
fn bad_master_secret() {
let fixture = TestFixture::new();
let result = HawkPayload::new(
&fixture.header.to_string(),
&fixture.request.method,
&fixture.request.path,
&fixture.request.host,
fixture.request.port,
&Secrets::new("wibble").unwrap(),
fixture.expected.expires.round() as u64 - 1,
);
assert!(result.is_err());
}
#[test]
fn bad_signature() {
let mut fixture = TestFixture::new();
let signature_index = fixture.header.id.len() - 32;
fixture
.header
.id
.replace_range(signature_index.., "01234567890123456789012345678901");
let result = HawkPayload::new(
&fixture.header.to_string(),
&fixture.request.method,
&fixture.request.path,
&fixture.request.host,
fixture.request.port,
&fixture.settings.master_secret,
fixture.expected.expires.round() as u64 - 1,
);
assert!(result.is_err());
}
#[test]
fn expired_payload() {
let fixture = TestFixture::new();
let result = HawkPayload::new(
&fixture.header.to_string(),
&fixture.request.method,
&fixture.request.path,
&fixture.request.host,
fixture.request.port,
&fixture.settings.master_secret,
fixture.expected.expires.round() as u64,
);
assert!(result.is_err());
}
#[test]
fn bad_mac() {
let mut fixture = TestFixture::new();
fixture.header.mac = "xRVjP7607eZUWCBxJKwTo1CsLcNf4TZwUUNrLPUqkdQ=".to_string();
let result = HawkPayload::new(
&fixture.header.to_string(),
&fixture.request.method,
&fixture.request.path,
&fixture.request.host,
fixture.request.port,
&fixture.settings.master_secret,
fixture.expected.expires.round() as u64 - 1,
);
assert!(result.is_err());
}
#[test]
fn bad_nonce() {
let mut fixture = TestFixture::new();
fixture.header.nonce = "1d4mRs0=".to_string();
let result = HawkPayload::new(
&fixture.header.to_string(),
&fixture.request.method,
&fixture.request.path,
&fixture.request.host,
fixture.request.port,
&fixture.settings.master_secret,
fixture.expected.expires.round() as u64 - 1,
);
assert!(result.is_err());
}
#[test]
fn bad_ts() {
let mut fixture = TestFixture::new();
fixture.header.ts = 1_536_198_978;
let result = HawkPayload::new(
&fixture.header.to_string(),
&fixture.request.method,
&fixture.request.path,
&fixture.request.host,
fixture.request.port,
&fixture.settings.master_secret,
fixture.expected.expires.round() as u64 - 1,
);
assert!(result.is_err());
}
#[test]
fn bad_method() {
let mut fixture = TestFixture::new();
fixture.request.method = "POST".to_string();
let result = HawkPayload::new(
&fixture.header.to_string(),
&fixture.request.method,
&fixture.request.path,
&fixture.request.host,
fixture.request.port,
&fixture.settings.master_secret,
fixture.expected.expires.round() as u64 - 1,
);
assert!(result.is_err());
}
#[test]
fn bad_path() {
let mut fixture = TestFixture::new();
fixture
.request
.path
.push_str("?batch=MTUzNjE5ODk3NjkyMQ==&commit=true");
let result = HawkPayload::new(
&fixture.header.to_string(),
&fixture.request.method,
&fixture.request.path,
&fixture.request.host,
fixture.request.port,
&fixture.settings.master_secret,
fixture.expected.expires.round() as u64 - 1,
);
assert!(result.is_err());
}
#[test]
fn bad_host() {
let mut fixture = TestFixture::new();
fixture.request.host.push_str(".com");
let result = HawkPayload::new(
&fixture.header.to_string(),
&fixture.request.method,
&fixture.request.path,
&fixture.request.host,
fixture.request.port,
&fixture.settings.master_secret,
fixture.expected.expires.round() as u64 - 1,
);
assert!(result.is_err());
}
#[test]
fn bad_port() {
let mut fixture = TestFixture::new();
fixture.request.port += 1;
let result = HawkPayload::new(
&fixture.header.to_string(),
&fixture.request.method,
&fixture.request.path,
&fixture.request.host,
fixture.request.port,
&fixture.settings.master_secret,
fixture.expected.expires.round() as u64 - 1,
);
assert!(result.is_err());
}
#[derive(Debug)]
struct TestFixture {
pub header: HawkHeader,
pub request: Request,
pub settings: Settings,
pub expected: HawkPayload,
}
impl TestFixture {
fn new() -> TestFixture {
TestFixture {
header: HawkHeader::new(
"eyJ1aWQiOiAxLCAibm9kZSI6ICJodHRwOi8vbG9jYWxob3N0OjUwMDAiLCAiZXhwaXJlcyI6IDE4ODQ5Njg0MzkuMCwgImZ4YV91aWQiOiAiMzE5Yjk4Zjk5NjFmZjFkYmRkMDczMTNjZDZiYTkyNWEiLCAiZnhhX2tpZCI6ICJkZTY5N2FkNjZkODQ1YjI4NzNjOWQ3ZTEzYjg5NzFhZiIsICJoYXNoZWRfZnhhX3VpZCI6ICIwZThkZjVkNDEzOThhMzg5OTEzYmQ4NDAyNDM1NjQ5NTE4YWY0NjQ5M2RhMWQ0YTQzN2E0NmRjMTc4NGM1MDFhIiwgImhhc2hlZF9kZXZpY2VfaWQiOiAiMmJjYjkyZjRkNDY5OGMzZDdiMDgzYTNjNjk4YTE2Y2NkNzhiYzJhOGQyMGE5NmU0YmIxMjhkZGNlYWY0ZTBiNiIsICJzYWx0IjogIjJiMzA3YiJ9lXaC5pIOenf7qL1AWlgKFvYH63nakyniTXP-7acS5cw=",
"UwDpC+DSrHCSTQSfMOWlueB6kM6gHb0Hsv8eU9ZcTVs=",
"h1Ch4vo=",
1_569_608_439,
),
request: Request::new(
"GET",
"/storage/1.5/1/storage/col2",
"localhost",
5000,
),
settings: Settings {
debug: false,
port: 0,
host: "127.0.0.1".to_string(),
database_url: "".to_string(),
database_pool_max_size: None,
database_use_test_transactions: false,
limits: Default::default(),
master_secret: Secrets::new("Ted Koppel is a robot").unwrap(),
..Default::default()
},
expected: HawkPayload {
expires: 1_884_968_439.0,
node: "http://localhost:5000".to_string(),
salt: "2b307b".to_string(),
user_id: 1,
fxa_uid: "319b98f9961ff1dbdd07313cd6ba925a".to_owned(),
fxa_kid: "de697ad66d845b2873c9d7e13b8971af".to_owned(),
device_id: "2bcb92f4d4698c3d7b083a3c698a16ccd78bc2a8d20a96e4bb128ddceaf4e0b6".to_owned(),
},
}
}
}
#[derive(Debug)]
struct HawkHeader {
pub id: String,
pub mac: String,
pub nonce: String,
pub ts: u64,
}
impl HawkHeader {
fn new(id: &str, mac: &str, nonce: &str, ts: u64) -> HawkHeader {
HawkHeader {
id: id.to_string(),
mac: mac.to_string(),
nonce: nonce.to_string(),
ts,
}
}
}
impl ToString for HawkHeader {
fn to_string(&self) -> String {
format!(
"Hawk id=\"{}\", mac=\"{}\", nonce=\"{}\", ts=\"{}\"",
self.id, self.mac, self.nonce, self.ts
)
}
}
#[derive(Debug)]
struct Request {
pub method: String,
pub path: String,
pub host: String,
pub port: u16,
}
impl Request {
fn new(method: &str, path: &str, host: &str, port: u16) -> Request {
Request {
method: method.to_string(),
path: path.to_string(),
host: host.to_string(),
port,
}
}
}
}