-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathintegration.rs
More file actions
580 lines (487 loc) · 18.5 KB
/
integration.rs
File metadata and controls
580 lines (487 loc) · 18.5 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
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
/*
* SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
use dashmap::DashMap;
use flexi_logger::{Logger, LoggerHandle};
use futures::future::select;
use futures::{pin_mut, FutureExt};
use futures::{SinkExt, StreamExt};
use http_auth_basic::Credentials;
use nextcloud_config_parser::{RedisConfig, RedisConnectionAddr, RedisConnectionInfo};
use notify_push::config::{Bind, Config};
use notify_push::message::DEBOUNCE_ENABLE;
use notify_push::redis::open_single;
use notify_push::{listen_loop, serve, App};
use once_cell::sync::Lazy;
use redis::AsyncCommands;
use smallvec::alloc::sync::Arc;
use sqlx::AnyPool;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicU16, Ordering};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::oneshot;
use tokio::task::spawn;
use tokio::time::timeout;
use tokio::time::{sleep, Duration};
use tokio_stream::wrappers::TcpListenerStream;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};
use warp::http::StatusCode;
use warp::{Filter, Reply};
static LAST_PORT: AtomicU16 = AtomicU16::new(1024);
async fn listen_available_port() -> Option<TcpListener> {
for _ in LAST_PORT.load(Ordering::SeqCst)..65535 {
let port = LAST_PORT.fetch_add(1, Ordering::SeqCst);
if let Ok(tcp) = TcpListener::bind(("127.0.0.1", port)).await {
return Some(tcp);
}
}
None
}
struct Services {
redis: SocketAddr,
nextcloud: SocketAddr,
_redis_shutdown: oneshot::Sender<()>,
_nextcloud_shutdown: oneshot::Sender<()>,
users: Arc<DashMap<String, String>>,
db: AnyPool,
}
static LOG_HANDLE: Lazy<LoggerHandle> =
Lazy::new(|| Logger::try_with_str("").unwrap().start().unwrap());
impl Services {
pub async fn new() -> Self {
sqlx::any::install_default_drivers();
DEBOUNCE_ENABLE.store(false, Ordering::SeqCst);
let redis_tcp = listen_available_port()
.await
.expect("Can't find open port for redis");
let nextcloud_tcp = listen_available_port()
.await
.expect("Can't find open port for nextcloud mock");
let redis_addr = redis_tcp
.local_addr()
.expect("Failed to get redis socket address");
let nextcloud_addr = nextcloud_tcp
.local_addr()
.expect("Failed to get nextcloud mock socket address");
// use the port in the db name to prevent collisions
let db = AnyPool::connect(&format!(
"sqlite:file:memory{}?mode=memory&cache=shared",
nextcloud_addr.port()
))
.await
.expect("Failed to connect sqlite database");
sqlx::query("CREATE TABLE oc_filecache(fileid BIGINT, path TEXT)")
.execute(&db)
.await
.unwrap();
sqlx::query("CREATE INDEX fc_id ON oc_filecache (fileid)")
.execute(&db)
.await
.unwrap();
sqlx::query("CREATE TABLE oc_mounts(storage_id BIGINT, root_id BIGINT, user_id TEXT)")
.execute(&db)
.await
.unwrap();
sqlx::query("CREATE INDEX mount_storage ON oc_mounts (storage_id)")
.execute(&db)
.await
.unwrap();
sqlx::query("CREATE INDEX mount_root ON oc_mounts (root_id)")
.execute(&db)
.await
.unwrap();
let users: Arc<DashMap<String, String>> = Arc::default();
let users_filter = users.clone();
let users_filter = warp::any().map(move || users_filter.clone());
let uid = warp::any()
.and(warp::header::<String>("authorization"))
.and(users_filter)
.map(|auth, users: Arc<DashMap<String, String>>| {
let credentials = match Credentials::from_header(auth) {
Ok(credentials) => credentials,
Err(_) => return Box::new(StatusCode::BAD_REQUEST) as Box<dyn Reply>,
};
match users.get(&credentials.user_id) {
Some(pass) if pass.value() == &credentials.password => {
Box::new(credentials.user_id)
}
_ => Box::new(StatusCode::UNAUTHORIZED),
}
});
let (redis_shutdown, redis_shutdown_rx) = oneshot::channel();
let (nextcloud_shutdown, nextcloud_shutdown_rx) = oneshot::channel();
spawn(async move {
warp::serve(uid)
.serve_incoming_with_graceful_shutdown(
TcpListenerStream::new(nextcloud_tcp),
nextcloud_shutdown_rx.map(|_| ()),
)
.await;
});
spawn(async move {
mini_redis::server::run(redis_tcp, redis_shutdown_rx)
.await
.ok();
});
Self {
redis: redis_addr,
nextcloud: nextcloud_addr,
_redis_shutdown: redis_shutdown,
_nextcloud_shutdown: nextcloud_shutdown,
users,
db,
}
}
fn config(&self) -> Config {
Config {
database: "sqlite::memory:?cache=shared".parse().unwrap(),
database_prefix: "oc_".to_string(),
redis: RedisConfig::Single(RedisConnectionInfo {
addr: RedisConnectionAddr::Tcp {
host: self.redis.ip().to_string(),
port: self.redis.port(),
tls: false,
},
db: 0,
username: None,
password: None,
tls_params: None,
}),
nextcloud_url: format!("http://{}/", self.nextcloud),
metrics_bind: None,
log_level: "".to_string(),
bind: Bind::Tcp(self.nextcloud),
allow_self_signed: false,
no_ansi: false,
tls: None,
max_debounce_time: 15,
max_connection_time: 0,
}
}
async fn app(&self) -> App {
let config = self.config();
App::with_connection(self.db.clone(), config, LOG_HANDLE.clone(), false)
.await
.unwrap()
}
async fn spawn_server(&self) -> ServerHandle {
let app = Arc::new(self.app().await);
let addr = async {
let tcp = listen_available_port().await.unwrap();
tcp.local_addr()
}
.await
.unwrap();
let (serve_tx, serve_rx) = oneshot::channel();
let (listen_tx, listen_rx) = oneshot::channel();
let bind = Bind::Tcp(addr);
spawn(async move {
let serve = serve(app.clone(), bind, serve_rx, None, 15, 0).unwrap();
let listen = listen_loop(app.clone(), listen_rx);
pin_mut!(serve);
pin_mut!(listen);
select(serve, listen).await;
});
sleep(Duration::from_millis(10)).await;
ServerHandle {
_serve_handle: serve_tx,
_listen_handle: listen_tx,
port: addr.port(),
}
}
async fn redis_client(&self) -> redis::aio::MultiplexedConnection {
let client = open_single(&self.config().redis.as_single().unwrap()).unwrap();
client.get_multiplexed_async_connection().await.unwrap()
}
fn add_user(&self, username: &str, password: &str) {
self.users.insert(username.into(), password.into());
}
async fn add_storage_mapping(&self, username: &str, storage: u32, root: u32) {
sqlx::query("INSERT INTO oc_mounts(storage_id, root_id, user_id) VALUES(?, ?, ?)")
.bind(storage as i64)
.bind(root as i64)
.bind(username)
.execute(&self.db)
.await
.unwrap();
}
async fn add_filecache_item(&self, fileid: u32, path: &str) {
sqlx::query("INSERT INTO oc_filecache(fileid, path) VALUES(?, ?)")
.bind(fileid as i64)
.bind(path)
.execute(&self.db)
.await
.unwrap();
}
}
struct ServerHandle {
_serve_handle: oneshot::Sender<()>,
_listen_handle: oneshot::Sender<()>,
port: u16,
}
impl ServerHandle {
async fn connect(&self) -> WebSocketStream<MaybeTlsStream<TcpStream>> {
tokio_tungstenite::connect_async(format!("ws://127.0.0.1:{}/ws", self.port))
.await
.unwrap()
.0
}
async fn connect_auth(
&self,
username: &str,
password: &str,
) -> WebSocketStream<MaybeTlsStream<TcpStream>> {
let mut client =
tokio_tungstenite::connect_async(format!("ws://127.0.0.1:{}/ws", self.port))
.await
.unwrap()
.0;
client.send(Message::Text(username.into())).await.unwrap();
client.send(Message::Text(password.into())).await.unwrap();
assert_next_message(&mut client, "authenticated").await;
client
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_auth() {
let services = Services::new().await;
services.add_user("foo", "bar");
let server_handle = services.spawn_server().await;
let mut client = server_handle.connect().await;
client.send(Message::Text("foo".into())).await.unwrap();
client.send(Message::Text("bar".into())).await.unwrap();
assert_next_message(&mut client, "authenticated").await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_auth_failure() {
let services = Services::new().await;
services.add_user("foo", "bar");
let server_handle = services.spawn_server().await;
let mut client = server_handle.connect().await;
client.send(Message::Text("foo".into())).await.unwrap();
client.send(Message::Text("not_bar".into())).await.unwrap();
assert_next_message(&mut client, "err: Invalid credentials").await;
}
async fn assert_next_message(
client: &mut WebSocketStream<MaybeTlsStream<TcpStream>>,
expected: &str,
) {
sleep(Duration::from_millis(100)).await;
assert_eq!(
timeout(Duration::from_millis(200), client.next())
.await
.unwrap()
.unwrap()
.unwrap(),
Message::Text(expected.into())
);
}
async fn assert_no_message(client: &mut WebSocketStream<MaybeTlsStream<TcpStream>>) {
sleep(Duration::from_millis(5)).await;
assert!(timeout(Duration::from_millis(10), client.next())
.await
.is_err());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_notify_activity() {
let services = Services::new().await;
services.add_user("foo", "bar");
let server_handle = services.spawn_server().await;
let mut client = server_handle.connect_auth("foo", "bar").await;
let mut redis = services.redis_client().await;
redis
.publish::<_, _, ()>("0_notify_activity", r#"{"user":"foo"}"#)
.await
.unwrap();
assert_next_message(&mut client, "notify_activity").await;
std::mem::forget(services);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_notify_activity_other_user() {
let services = Services::new().await;
services.add_user("foo", "bar");
let server_handle = services.spawn_server().await;
let mut client = server_handle.connect_auth("foo", "bar").await;
let mut redis = services.redis_client().await;
redis
.publish::<_, _, ()>("0_notify_activity", r#"{"user":"someone_else"}"#)
.await
.unwrap();
assert_no_message(&mut client).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_notify_file() {
let services = Services::new().await;
services.add_user("foo", "bar");
services.add_filecache_item(10, "foo").await;
services.add_filecache_item(11, "foo/bar").await;
services.add_storage_mapping("foo", 10, 11).await;
let server_handle = services.spawn_server().await;
let mut client = server_handle.connect_auth("foo", "bar").await;
let mut redis = services.redis_client().await;
redis
.publish::<_, _, ()>(
"0_notify_storage_update",
r#"{"storage":10, "path":"foo/bar", "file_id":5}"#,
)
.await
.unwrap();
assert_next_message(&mut client, "notify_file").await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_notify_file_different_storage() {
let services = Services::new().await;
services.add_user("foo", "bar");
services.add_filecache_item(10, "foo").await;
services.add_filecache_item(11, "foo/bar").await;
services.add_storage_mapping("foo", 10, 11).await;
let server_handle = services.spawn_server().await;
let mut client = server_handle.connect_auth("foo", "bar").await;
let mut redis = services.redis_client().await;
redis
.publish::<_, _, ()>(
"0_notify_storage_update",
r#"{"storage":11, "path":"foo/bar", "file_id":5}"#,
)
.await
.unwrap();
assert_no_message(&mut client).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_notify_file_multiple() {
let services = Services::new().await;
services.add_user("foo", "bar");
services.add_user("foo2", "bar");
services.add_user("foo3", "bar");
services.add_filecache_item(10, "foo").await;
services.add_filecache_item(11, "foo/bar").await;
services.add_filecache_item(12, "foo/outside").await;
services.add_storage_mapping("foo", 10, 10).await;
services.add_storage_mapping("foo2", 10, 11).await;
services.add_storage_mapping("foo2", 10, 12).await;
let server_handle = services.spawn_server().await;
let mut client1 = server_handle.connect_auth("foo", "bar").await;
let mut client2 = server_handle.connect_auth("foo2", "bar").await;
let mut client3 = server_handle.connect_auth("foo3", "bar").await;
let mut redis = services.redis_client().await;
redis
.publish::<_, _, ()>(
"0_notify_storage_update",
r#"{"storage":10, "path":"foo/bar", "file_id":5}"#,
)
.await
.unwrap();
assert_next_message(&mut client1, "notify_file").await;
assert_next_message(&mut client2, "notify_file").await;
assert_no_message(&mut client3).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_pre_auth() {
let services = Services::new().await;
let server_handle = services.spawn_server().await;
sleep(Duration::from_millis(500)).await;
let mut redis = services.redis_client().await;
redis
.publish::<_, _, ()>("0_notify_pre_auth", r#"{"user":"foo", "token": "token"}"#)
.await
.unwrap();
sleep(Duration::from_millis(100)).await;
let mut client = server_handle.connect_auth("", "token").await;
// verify that we are the correct user
redis
.publish::<_, _, ()>("0_notify_activity", r#"{"user":"foo"}"#)
.await
.unwrap();
assert_next_message(&mut client, "notify_activity").await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_notify_notification() {
let services = Services::new().await;
services.add_user("foo", "bar");
services.add_user("foo2", "bar");
let server_handle = services.spawn_server().await;
let mut client1 = server_handle.connect_auth("foo", "bar").await;
let mut client2 = server_handle.connect_auth("foo2", "bar").await;
let mut redis = services.redis_client().await;
redis
.publish::<_, _, ()>("0_notify_notification", r#"{"user":"foo"}"#)
.await
.unwrap();
assert_next_message(&mut client1, "notify_notification").await;
assert_no_message(&mut client2).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_notify_share() {
let services = Services::new().await;
services.add_user("foo", "bar");
services.add_user("foo2", "bar");
let server_handle = services.spawn_server().await;
let mut client1 = server_handle.connect_auth("foo", "bar").await;
let mut client2 = server_handle.connect_auth("foo2", "bar").await;
let mut redis = services.redis_client().await;
redis
.publish::<_, _, ()>("0_notify_user_share_created", r#"{"user":"foo"}"#)
.await
.unwrap();
assert_next_message(&mut client1, "notify_file").await;
assert_no_message(&mut client2).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_notify_group() {
let services = Services::new().await;
services.add_user("foo", "bar");
services.add_user("foo2", "bar");
let server_handle = services.spawn_server().await;
let mut client1 = server_handle.connect_auth("foo", "bar").await;
let mut client2 = server_handle.connect_auth("foo2", "bar").await;
let mut redis = services.redis_client().await;
redis
.publish::<_, _, ()>(
"0_notify_group_membership_update",
r#"{"user":"foo", "group":"asd"}"#,
)
.await
.unwrap();
assert_next_message(&mut client1, "notify_file").await;
assert_no_message(&mut client2).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_notify_custom() {
let services = Services::new().await;
services.add_user("foo", "bar");
services.add_user("foo2", "bar");
let server_handle = services.spawn_server().await;
let mut client1 = server_handle.connect_auth("foo", "bar").await;
let mut client2 = server_handle.connect_auth("foo2", "bar").await;
let mut redis = services.redis_client().await;
redis
.publish::<_, _, ()>(
"0_notify_custom",
r#"{"user":"foo", "message":"my_custom_message"}"#,
)
.await
.unwrap();
assert_next_message(&mut client1, "my_custom_message").await;
assert_no_message(&mut client2).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_notify_custom_body() {
let services = Services::new().await;
services.add_user("foo", "bar");
services.add_user("foo2", "bar");
let server_handle = services.spawn_server().await;
let mut client1 = server_handle.connect_auth("foo", "bar").await;
let mut client2 = server_handle.connect_auth("foo2", "bar").await;
let mut redis = services.redis_client().await;
redis
.publish::<_, _, ()>(
"0_notify_custom",
r#"{"user":"foo", "message":"my_custom_message", "body": [1,2,3]}"#,
)
.await
.unwrap();
assert_next_message(&mut client1, "my_custom_message [1,2,3]").await;
assert_no_message(&mut client2).await;
}