forked from Normation/rudder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shared_files.rs
383 lines (349 loc) · 10.5 KB
/
shared_files.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
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2019-2020 Normation SAS
use crate::{
data::shared_file::{Metadata, SharedFile},
error::RudderError,
JobConfig,
};
use anyhow::Error;
use bytes::{Buf, Bytes};
use chrono::Utc;
use humantime::parse_duration;
use serde::{Deserialize, Serialize};
use std::{
io::{BufRead, BufReader, Read},
str,
str::FromStr,
sync::Arc,
time::Duration,
};
use tokio::fs;
use tracing::{debug, error, span, warn, Level};
use warp::{body, filters::method, http::StatusCode, path, query, Filter, Reply};
pub fn routes_1(
job_config: Arc<JobConfig>,
) -> impl Filter<Extract = impl Reply, Error = warp::Rejection> + Clone {
let base = path!("shared-files" / String / String / String);
let job_config_head = job_config.clone();
let head = method::head()
.map(move || job_config_head.clone())
.and(base)
.and(query::<SharedFilesHeadParams>())
.and_then(move |j, target_id, source_id, file_id, params| {
handlers::head(target_id, source_id, file_id, params, j)
});
let job_config_put = job_config;
let put = method::put()
.map(move || job_config_put.clone())
.and(base)
.and(query::<SharedFilesPutParams>())
.and(body::bytes())
.and_then(move |j, target_id, source_id, file_id, params, buf| {
handlers::put(target_id, source_id, file_id, params, buf, j)
});
head.or(put)
}
pub mod handlers {
use super::*;
use crate::JobConfig;
use warp::{reply, Rejection, Reply};
pub async fn put(
target_id: String,
source_id: String,
file_id: String,
params: SharedFilesPutParams,
buf: Bytes,
job_config: Arc<JobConfig>,
) -> Result<impl Reply, Rejection> {
Ok(reply::with_status(
"".to_string(),
match super::put(
target_id,
source_id,
file_id,
params,
job_config.clone(),
buf,
)
.await
{
Ok(x) => x,
Err(e) => {
error!("error while processing request: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
}
},
))
}
pub async fn head(
target_id: String,
source_id: String,
file_id: String,
params: SharedFilesHeadParams,
job_config: Arc<JobConfig>,
) -> Result<impl Reply, Rejection> {
Ok(reply::with_status(
"".to_string(),
match super::head(target_id, source_id, file_id, params, job_config.clone()).await {
Ok(x) => x,
Err(e) => {
error!("error while processing request: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
}
},
))
}
}
#[derive(Deserialize, Serialize, Debug)]
pub struct SharedFilesPutParams {
ttl: String,
}
impl SharedFilesPutParams {
#[cfg(test)]
fn new(ttl: &str) -> Self {
Self {
ttl: ttl.to_string(),
}
}
fn ttl(&self) -> Result<Duration, Error> {
match self.ttl.parse::<u64>() {
// No units -> seconds
Ok(s) => Ok(Duration::from_secs(s)),
// Else parse as human time
Err(_) => parse_duration(&self.ttl).map_err(|e| e.into()),
}
}
}
pub async fn put(
target_id: String,
source_id: String,
file_id: String,
params: SharedFilesPutParams,
job_config: Arc<JobConfig>,
body: Bytes,
) -> Result<StatusCode, Error> {
let span = span!(
Level::INFO,
"shared_files_put",
target_id = %target_id,
source_id = %source_id,
file_id = %file_id,
);
let _enter = span.enter();
let file = SharedFile::new(source_id, target_id, file_id)?;
if job_config.nodes.read().await.is_subnode(&file.target_id) {
put_local(file, params, job_config, body).await
} else if job_config.nodes.read().await.i_am_root_server() {
Err(RudderError::UnknownNode(file.target_id).into())
} else {
put_forward(file, params, job_config, body).await
}
}
async fn put_forward(
file: SharedFile,
params: SharedFilesPutParams,
job_config: Arc<JobConfig>,
body: Bytes,
) -> Result<StatusCode, Error> {
let client = job_config.upstream_client.read().await.client().clone();
client
.put(&format!(
"{}/{}/{}",
job_config.cfg.upstream_url(),
"relay-api/shared-files",
file.url(),
))
.query(¶ms)
.body(body)
.send()
.await
.map(|r| r.status())
.map_err(|e| e.into())
}
pub async fn put_local(
file: SharedFile,
params: SharedFilesPutParams,
job_config: Arc<JobConfig>,
body: Bytes,
) -> Result<StatusCode, Error> {
if !job_config.nodes.read().await.is_subnode(&file.source_id) {
warn!("unknown source {}", file.source_id);
return Ok(StatusCode::NOT_FOUND);
}
let mut stream = BufReader::new(body.reader());
let mut raw_meta = String::new();
// Here we cannot iterate on lines as the file content may not be valid UTF-8.
let mut read = 2;
// Let's read while we find an empty line.
while read > 1 {
read = stream.read_line(&mut raw_meta)?;
}
let meta = Metadata::from_str(&raw_meta)?;
let base_path = job_config
.cfg
.shared_files
.path
.join(&file.target_id)
.join("files")
.join(&file.source_id);
let pubkey = meta.pubkey()?;
let known_key_hash = job_config.nodes.read().await.key_hash(&file.source_id)?;
let key_hash = known_key_hash.hash_type.hash(&pubkey.public_key_to_der()?);
if key_hash != known_key_hash {
warn!(
"hash of public key ({}) does not match known hash ({})",
key_hash, known_key_hash
);
return Ok(StatusCode::NOT_FOUND);
}
// Read file content
let mut file_content = vec![];
stream.read_to_end(&mut file_content)?;
match meta.validate_signature(
&file_content,
meta.hash.hash_type,
&hex::decode(&meta.digest)?,
) {
Ok(is_valid) => {
if !is_valid {
warn!("invalid signature");
return Ok(StatusCode::INTERNAL_SERVER_ERROR);
}
}
Err(e) => {
warn!("error checking file signature: {}", e);
return Ok(StatusCode::INTERNAL_SERVER_ERROR);
}
}
// Everything is correct, let's store the file
fs::create_dir_all(&base_path).await?;
fs::write(
&base_path.join(format!("{}.metadata", file.file_id)),
format!(
"{}expires={}\n",
meta,
match params.ttl() {
// Removal timestamp = now + ttl
Ok(ttl) => (Utc::now()
+ chrono::Duration::from_std(ttl).expect("Unexpectedly large duration"))
.timestamp(),
Err(e) => {
warn!("invalid ttl: {}", e);
return Ok(StatusCode::INTERNAL_SERVER_ERROR);
}
}
),
)
.await?;
fs::write(&base_path.join(file.file_id), file_content).await?;
Ok(StatusCode::OK)
}
#[derive(Deserialize, Serialize, Debug)]
pub struct SharedFilesHeadParams {
hash: String,
}
pub async fn head(
target_id: String,
source_id: String,
file_id: String,
params: SharedFilesHeadParams,
job_config: Arc<JobConfig>,
) -> Result<StatusCode, Error> {
let span = span!(
Level::INFO,
"shared_files_head",
target_id = %target_id,
source_id = %source_id,
file_id = %file_id,
);
let _enter = span.enter();
let file = SharedFile::new(source_id, target_id, file_id)?;
if job_config.nodes.read().await.is_subnode(&file.target_id) {
head_local(file, params, job_config).await
} else if job_config.nodes.read().await.i_am_root_server() {
Err(RudderError::UnknownNode(file.target_id).into())
} else {
head_forward(file, params, job_config).await
}
}
async fn head_forward(
file: SharedFile,
params: SharedFilesHeadParams,
job_config: Arc<JobConfig>,
) -> Result<StatusCode, Error> {
let client = job_config.upstream_client.read().await.client().clone();
client
.head(&format!(
"{}/{}/{}",
job_config.cfg.upstream_url(),
"relay-api/shared-files",
file.url(),
))
.query(¶ms)
.send()
.await
.map(|r| r.status())
.map_err(|e| e.into())
}
pub async fn head_local(
file: SharedFile,
params: SharedFilesHeadParams,
job_config: Arc<JobConfig>,
) -> Result<StatusCode, Error> {
let file_path = job_config
.cfg
.shared_files
.path
.join(&file.target_id)
.join("files")
.join(&file.source_id)
.join(format!("{}.metadata", file.file_id));
if !file_path.exists() {
debug!("file {} does not exist", file_path.display());
return Ok(StatusCode::NOT_FOUND);
}
let metadata = Metadata::from_str(&fs::read_to_string(&file_path).await?)?;
let metadata_hash = metadata.hash.hex();
Ok(if metadata_hash == params.hash {
debug!(
"file {} has given hash '{}'",
file_path.display(),
metadata_hash
);
StatusCode::OK
} else {
debug!(
"file {} has '{}' hash but given hash is '{}'",
file_path.display(),
metadata_hash,
params.hash,
);
StatusCode::NOT_FOUND
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
pub fn it_parses_ttl() {
assert_eq!(
SharedFilesPutParams::new("1h 7s").ttl().unwrap(),
Duration::from_secs(3600 + 7)
);
assert_eq!(
SharedFilesPutParams::new("1hour 2minutes").ttl().unwrap(),
Duration::from_secs(3600 + 120)
);
assert_eq!(
SharedFilesPutParams::new("1d 7seconds").ttl().unwrap(),
Duration::from_secs(86400 + 7)
);
assert_eq!(
SharedFilesPutParams::new("9136").ttl().unwrap(),
Duration::from_secs(9136)
);
assert!(SharedFilesPutParams::new("913j").ttl().is_err());
assert!(SharedFilesPutParams::new("913b83").ttl().is_err());
assert!(SharedFilesPutParams::new("913h 89j").ttl().is_err());
}
}