d7d18246 Andy McCall 23 days ago ↶
1
2
3
4
5
6
use oxy_core:: repo:: Repo;
7
use oxygenhub:: backups:: { self , Destination, Directory, Setting} ;
8
use oxygenhub:: config:: Config;
9
use oxygenhub:: repos:: RepoName;
10
use oxygenhub:: { db, Shared} ;
11
use std:: path:: Path;
12
use std:: sync:: Arc;
13
14
fn hermetic ( ) {
15
static ONCE : std:: sync:: Once = std:: sync:: Once:: new( ) ;
16
static DIR : std:: sync:: OnceLock< tempfile:: TempDir> = std:: sync:: OnceLock:: new( ) ;
17
ONCE .call_once ( | | {
18
let d = tempfile:: tempdir( ) .unwrap ( ) ;
19
std:: env:: set_var( " OXY_HOME" , d.path ( ) ) ;
20
DIR .set ( d) .ok ( ) ;
21
} ) ;
22
}
23
24
struct Hub {
25
app : Shared,
26
base : String,
27
_dir : tempfile:: TempDir,
28
}
29
30
async fn hub ( backups : & Path) -> Hub {
35fea423 Andy McCall 23 days ago ↶
31
hub_with ( backups, None ) .await
32
}
33
34
async fn hub_with ( backups : & Path, google : Option< & str > ) -> Hub {
d7d18246 Andy McCall 23 days ago ↶
35
hermetic ( ) ;
36
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
37
let mut config = Config:: load( dir.path ( ) ) .unwrap ( ) ;
38
config.auth.push_tokens = vec! [ " site" .into ( ) ] ;
39
config.backups.directories = vec! [ backups.to_path_buf ( ) ] ;
35fea423 Andy McCall 23 days ago ↶
40
if let Some ( g) = google {
41
config.backups.sts_url = g.to_string ( ) ;
42
config.backups.storage_url = g.to_string ( ) ;
43
}
d7d18246 Andy McCall 23 days ago ↶
44
let listener = tokio:: net:: TcpListener:: bind( " 127.0.0.1:0" ) .await.unwrap ( ) ;
45
let port = listener.local_addr ( ) .unwrap ( ) .port ( ) ;
46
config.server.base_url = format! ( " http://127.0.0.1:{port} " ) ;
47
let app = oxygenhub:: build( config) .await.unwrap ( ) ;
48
let router = oxygenhub:: router( app.clone ( ) ) ;
49
tokio:: spawn( async move { axum:: serve( listener, router) .await.unwrap ( ) } ) ;
50
Hub { app, base: format! ( " http://127.0.0.1:{port} " ) , _dir: dir }
51
}
52
53
fn write ( root : & Path, rel : & str , content : & str ) {
54
let p = root.join ( rel) ;
55
std:: fs:: create_dir_all( p.parent ( ) .unwrap ( ) ) .unwrap ( ) ;
56
std:: fs:: write( p, content) .unwrap ( ) ;
57
}
58
59
async fn create ( app : & Shared, owner : & str , name : & str , visibility : hub_api:: Visibility) {
60
app.repos.create ( & RepoName:: parse( & format! ( " {owner} /{name} " ) ) .unwrap ( ) , None ) .unwrap ( ) ;
61
db:: repos:: create( & app.db, owner, name, " a demo" , visibility) .await.unwrap ( ) ;
62
}
63
64
fn push ( url : & str , work : & Path, files : & [( &str , &str ) ]) {
65
let mut c = Repo:: init( work) .unwrap ( ) ;
66
c.config.set ( " remote.origin.url" , url) .unwrap ( ) ;
67
c.config.set ( " remote.origin.token" , " site" ) .unwrap ( ) ;
68
c.save_config ( ) .unwrap ( ) ;
69
for ( f, t) in files {
70
write ( work, f, t) ;
71
}
72
c.snapshot ( " t" ) .unwrap ( ) ;
73
c.commit ( " Some work" , & [ ] ) .unwrap ( ) ;
74
assert! ( c.push ( " origin" , false ) .unwrap ( ) .iter ( ) .all ( | r | r.ok ) ) ;
75
}
76
77
78
fn files ( dir : & Path) -> Vec< ( String, Vec< u8 > ) > {
79
let mut out = Vec :: new( ) ;
80
let mut stack = vec! [ dir.to_path_buf ( ) ] ;
81
while let Some ( d) = stack.pop ( ) {
82
for e in std:: fs:: read_dir( & d) .unwrap ( ) .flatten ( ) {
83
let p = e.path ( ) ;
84
if p.is_dir ( ) {
85
stack.push ( p) ;
86
} else {
87
out.push ( ( p.strip_prefix ( dir) .unwrap ( ) .to_string_lossy ( ) .into_owned ( ) , std:: fs:: read( & p) .unwrap ( ) ) ) ;
88
}
89
}
90
}
91
out.sort ( ) ;
92
out
93
}
94
95
# [ tokio ::test ( flavor = " multi_thread" ) ]
96
async fn a_backup_restores_the_same_repository_and_sends_only_what_changed ( ) {
97
let store = tempfile:: tempdir( ) .unwrap ( ) ;
98
let h = hub ( store.path ( ) ) .await;
99
db:: accounts:: create_account( & h.app.db, " andy" , " [email protected] " , " x" , " salt" , false ) .await.unwrap ( ) ;
100
db:: accounts:: create_account( & h.app.db, " bob" , " [email protected] " , " x" , " salt" , false ) .await.unwrap ( ) ;
101
create ( & h.app, " andy" , " demo" , hub_api:: Visibility:: Private) .await;
102
create ( & h.app, " bob" , " other" , hub_api:: Visibility:: Public) .await;
103
let work = tempfile:: tempdir( ) .unwrap ( ) ;
104
push ( & format! ( " {} /andy/demo" , h.base) , work.path ( ) , & [ ( " README.md" , " hello\n " ) , ( " src/main.rs" , " fn main() {}\n " ) ] ) ;
105
let other = tempfile:: tempdir( ) .unwrap ( ) ;
106
push ( & format! ( " {} /bob/other" , h.base) , other.path ( ) , & [ ( " x.txt" , " bob's\n " ) ] ) ;
107
108
109
let target = store.path ( ) .display ( ) .to_string ( ) ;
110
let mut s = Setting:: off( " andy" , " user" ) ;
111
s.every = " hourly" .into ( ) ;
112
s.target = target.clone ( ) ;
113
backups:: save( & h.app.db, & s) .await.unwrap ( ) ;
114
let first = backups:: run( & h.app, " andy" , " now" ) .await.unwrap ( ) ;
115
assert_eq! ( ( first.status.as_str ( ) , first.repos) , ( " ok" , 1 ) , " {}" , first.detail) ;
116
assert! ( first.sent > 0 & & first.bytes > 0 ) ;
117
let dest = Directory { root: store.path ( ) .join ( " andy" ) } ;
118
assert! ( dest.exists ( & format! ( " runs/{} /DONE" , first.at) ) .unwrap ( ) ) ;
119
let records: serde_json:: Value = serde_json:: from_slice( & dest.get ( & format! ( " runs/{} /records/demo.json" , first.at) ) .unwrap ( ) ) .unwrap ( ) ;
120
assert_eq! ( records[ " repositories" ] [ 0 ] [ " visibility" ] , " private" ) ;
121
let text = String :: from_utf8_lossy( & dest.get ( & format! ( " runs/{} /records/demo.json" , first.at) ) .unwrap ( ) ) .into_owned ( ) ;
122
assert! ( ! text.contains ( " bob/other" ) & & ! text.contains ( " \" other\" " ) , " nothing of another owner" ) ;
123
assert! ( ! store.path ( ) .join ( " bob" ) .exists ( ) , " bob set up no backup" ) ;
124
125
126
tokio:: time:: sleep( std:: time:: Duration:: from_millis( 1100 ) ) .await;
127
let second = backups:: run( & h.app, " andy" , " now" ) .await.unwrap ( ) ;
128
assert_eq! ( ( second.status.as_str ( ) , second.sent) , ( " ok" , 0 ) , " {}" , second.detail) ;
129
130
131
let empty = tempfile:: tempdir( ) .unwrap ( ) ;
132
let fresh = hub ( empty.path ( ) ) .await;
133
let dest: Arc< dyn Destination> = Arc:: new( Directory { root: store.path ( ) .join ( " andy" ) } ) ;
134
let done = backups:: restore_into_hub( & fresh.app, dest, None ) .await.unwrap ( ) ;
135
assert_eq! ( done, vec! [ " andy/demo (repos)" ] ) ;
136
let name = RepoName:: parse( " andy/demo" ) .unwrap ( ) ;
137
assert_eq! ( files ( & fresh.app.repos.dir ( & name) ) , files ( & h.app.repos.dir ( & name) ) , " byte for byte" ) ;
138
let row = db:: repos:: get( & fresh.app.db, " andy" , " demo" ) .await.unwrap ( ) .expect ( " listed on the hub" ) ;
139
assert_eq! ( ( row.visibility.as_str ( ) , row.description.as_str ( ) ) , ( " private" , " a demo" ) ) ;
140
let ( a, b) = ( h.app.repos.open ( & name) .unwrap ( ) , fresh.app.repos.open ( & name) .unwrap ( ) ) ;
141
assert_eq! (
142
a.bookmarks ( ) .unwrap ( ) .iter ( ) .map ( | b | b.heads.clone ( ) ) .collect:: < Vec< _ > > ( ) ,
143
b.bookmarks ( ) .unwrap ( ) .iter ( ) .map ( | b | b.heads.clone ( ) ) .collect:: < Vec< _ > > ( )
144
) ;
145
146
147
let mut bad = Setting:: off( " andy" , " user" ) ;
148
bad.every = " hourly" .into ( ) ;
149
bad.target = " /tmp/somewhere-else" .into ( ) ;
150
backups:: save( & h.app.db, & bad) .await.unwrap ( ) ;
151
let refused = backups:: run( & h.app, " andy" , " now" ) .await.unwrap ( ) ;
152
assert_eq! ( refused.status, " failed" ) ;
153
assert! ( refused.detail.contains ( " not a backup directory this hub allows" ) , " {}" , refused.detail) ;
154
}
155
156
# [ tokio ::test ( flavor = " multi_thread" ) ]
157
async fn backups_fall_due_on_their_schedule ( ) {
158
let store = tempfile:: tempdir( ) .unwrap ( ) ;
159
let h = hub ( store.path ( ) ) .await;
160
let mut s = Setting:: off( " andy" , " user" ) ;
161
s.target = store.path ( ) .display ( ) .to_string ( ) ;
162
backups:: save( & h.app.db, & s) .await.unwrap ( ) ;
163
assert! ( backups:: due( & h.app.db) .await.unwrap ( ) .is_empty ( ) , " off is never due" ) ;
164
s.every = " hourly" .into ( ) ;
165
backups:: save( & h.app.db, & s) .await.unwrap ( ) ;
166
assert_eq! ( backups:: due( & h.app.db) .await.unwrap ( ) .len ( ) , 1 , " never run: due" ) ;
3b1bc27f Andy McCall 20 days ago
167
sqlx:: query( " INSERT INTO backup_runs (owner, started_ms, status) VALUES ('andy', $1, 'ok')" )
d7d18246 Andy McCall 23 days ago ↶
168
.bind ( db:: now_ms( ) )
169
.execute ( & h.app.db)
170
.await
171
.unwrap ( ) ;
172
assert! ( backups:: due( & h.app.db) .await.unwrap ( ) .is_empty ( ) , " ran just now" ) ;
35fea423 Andy McCall 23 days ago ↶
173
}
174
175
176
177
178
# [ derive ( Default ) ]
179
struct Google {
180
181
objects : std:: collections:: BTreeMap< ( String, String) , Vec< u8 > > ,
182
183
exchanged : Vec< ( String, String) > ,
184
}
185
186
type Shared2 = Arc< std:: sync:: Mutex< Google> > ;
187
188
fn decode ( s : & str ) -> String {
189
let b = s.as_bytes ( ) ;
190
let mut out = Vec :: new( ) ;
191
let mut i = 0 ;
192
while i < b.len ( ) {
193
if b[ i] = = b ' %' & & i + 2 < b.len ( ) {
194
out.push ( u8 :: from_str_radix( & s[ i + 1 .. i + 3 ] , 16 ) .unwrap ( ) ) ;
195
i + = 3 ;
196
} else {
197
out.push ( b[ i] ) ;
198
i + = 1 ;
199
}
200
}
201
String :: from_utf8( out) .unwrap ( )
202
}
203
204
fn query ( uri : & axum:: http:: Uri, key : & str ) -> Option< String> {
205
uri.query ( ) ? .split ( ' &' ) .find_map ( | kv | kv.split_once ( ' =' ) .filter ( | ( k , _) | * k = = key) .map ( | ( _, v ) | decode ( v) ) )
206
}
207
208
209
210
211
async fn fake_google ( ) -> ( String, Shared2) {
212
use axum:: extract:: { Request, State} ;
213
use axum:: http:: StatusCode;
214
use axum:: response:: IntoResponse;
215
let state: Shared2 = Default :: default( ) ;
216
async fn handle ( State( g ) : State< Shared2> , req : Request) -> axum:: response:: Response {
217
let ( parts, body) = req.into_parts ( ) ;
218
let bytes = http_body_util:: BodyExt:: collect( body) .await.unwrap ( ) .to_bytes ( ) ;
219
let path = parts.uri.path ( ) .to_string ( ) ;
220
if path = = " /v1/token" {
221
let v: serde_json:: Value = serde_json:: from_slice( & bytes) .unwrap ( ) ;
222
let jwt = v[ " subjectToken" ] .as_str ( ) .unwrap ( ) ;
223
let payload = jwt.split ( ' .' ) .nth ( 1 ) .unwrap ( ) ;
224
let claims: serde_json:: Value = serde_json:: from_slice( & base64url ( payload) ) .unwrap ( ) ;
225
let ( sub, aud) = ( claims[ " sub" ] .as_str ( ) .unwrap ( ) .to_string ( ) , claims[ " aud" ] .as_str ( ) .unwrap ( ) .to_string ( ) ) ;
226
let provider = v[ " audience" ] .as_str ( ) .unwrap ( ) ;
227
g.lock ( ) .unwrap ( ) .exchanged.push ( ( sub.clone ( ) , aud.clone ( ) ) ) ;
228
if ! sub.starts_with ( " backup:" ) | | aud ! = format! ( " https:{provider} " ) {
229
return (
230
StatusCode:: BAD_REQUEST ,
231
axum:: Json( serde_json:: json! ( { " error" : " invalid_grant" , " error_description" : " not admitted" } ) ) ,
232
)
233
.into_response ( ) ;
234
}
235
return axum:: Json( serde_json:: json! ( { " access_token" : format! ( " tok-{sub} " ) , " expires_in" : 3600 } ) ) .into_response ( ) ;
236
}
237
let auth = parts.headers.get ( " authorization" ) .and_then ( | v | v.to_str ( ) .ok ( ) ) .unwrap_or ( " " ) .to_string ( ) ;
238
let segs: Vec< & str > = path.split ( ' /' ) .collect ( ) ;
239
240
let upload = segs.get ( 1 ) = = Some ( & " upload" ) ;
241
let at = if upload { 5 } else { 4 } ;
242
let bucket = segs.get ( at) .unwrap_or ( & " " ) .to_string ( ) ;
243
let owner = bucket.trim_end_matches ( " -backup" ) ;
244
if auth ! = format! ( " Bearer tok-backup:{owner} " ) {
245
return ( StatusCode:: FORBIDDEN , " caller does not have storage.objects access" ) .into_response ( ) ;
246
}
247
let mut g = g.lock ( ) .unwrap ( ) ;
248
if upload {
249
let name = query ( & parts.uri, " name" ) .unwrap ( ) ;
250
g.objects.insert ( ( bucket, name) , bytes.to_vec ( ) ) ;
251
return axum:: Json( serde_json:: json! ( { } ) ) .into_response ( ) ;
252
}
253
let name = segs.get ( at + 2 ) .map ( | n | decode ( n) ) ;
254
match ( parts.method.as_str ( ) , name) {
255
( " GET" , Some ( n) ) => match g.objects.get ( & ( bucket, n.clone ( ) ) ) {
256
Some ( b) if query ( & parts.uri, " alt" ) .as_deref ( ) = = Some ( " media" ) => b.clone ( ) .into_response ( ) ,
257
Some ( _ ) => axum:: Json( serde_json:: json! ( { " name" : n } ) ) .into_response ( ) ,
258
None => StatusCode:: NOT_FOUND .into_response ( ) ,
259
} ,
260
( " DELETE" , Some ( n) ) => {
261
g.objects.remove ( & ( bucket, n) ) ;
262
StatusCode:: NO_CONTENT .into_response ( )
263
}
264
( " GET" , None ) => {
265
let prefix = query ( & parts.uri, " prefix" ) .unwrap_or_default ( ) ;
266
let delimited = query ( & parts.uri, " delimiter" ) .is_some ( ) ;
267
let ( mut items, mut prefixes) = ( Vec :: new( ) , std:: collections:: BTreeSet:: new( ) ) ;
268
for ( b, n) in g.objects.keys ( ) {
269
if * b ! = bucket | | ! n.starts_with ( & prefix) {
270
continue ;
271
}
272
let rest = & n[ prefix.len ( ) .. ] ;
273
match rest.find ( ' /' ) {
274
Some ( i) if delimited => {
275
prefixes.insert ( format! ( " {prefix} {} " , & rest[ .. = i] ) ) ;
276
}
277
_ => items.push ( serde_json:: json! ( { " name" : n } ) ) ,
278
}
279
}
280
axum:: Json( serde_json:: json! ( { " items" : items, " prefixes" : prefixes } ) ) .into_response ( )
281
}
282
_ => StatusCode:: METHOD_NOT_ALLOWED .into_response ( ) ,
283
}
284
}
285
let app = axum:: Router:: new( ) .fallback ( handle) .with_state ( state.clone ( ) ) ;
286
let listener = tokio:: net:: TcpListener:: bind( " 127.0.0.1:0" ) .await.unwrap ( ) ;
287
let port = listener.local_addr ( ) .unwrap ( ) .port ( ) ;
288
tokio:: spawn( async move { axum:: serve( listener, app) .await.unwrap ( ) } ) ;
289
( format! ( " http://127.0.0.1:{port} " ) , state)
290
}
291
292
fn base64url ( s : & str ) -> Vec< u8 > {
293
let table = b " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" ;
294
let mut bits = 0 u32 ;
295
let mut n = 0 ;
296
let mut out = Vec :: new( ) ;
297
for c in s.bytes ( ) {
298
let v = table.iter ( ) .position ( | t | * t = = c) .unwrap ( ) as u32 ;
299
bits = ( bits < < 6 ) | v;
300
n + = 6 ;
301
if n > = 8 {
302
n - = 8 ;
303
out.push ( ( bits > > n) as u8 ) ;
304
bits & = ( 1 < < n) - 1 ;
305
}
306
}
307
out
308
}
309
310
const PROVIDER : & str = " //iam.googleapis.com/projects/1/locations/global/workloadIdentityPools/oxygenhub/providers/oxygenhub-io" ;
311
312
fn gcs ( owner : & str , bucket : & str ) -> Setting {
313
let mut s = Setting:: off( owner, " user" ) ;
314
s.every = " hourly" .into ( ) ;
315
s.destination = " gcs" .into ( ) ;
316
s.target = bucket.into ( ) ;
317
s.provider = PROVIDER .into ( ) ;
318
s
319
}
320
321
# [ tokio ::test ( flavor = " multi_thread" ) ]
322
async fn a_gcs_backup_needs_no_key_and_restores_the_same_repository ( ) {
323
let ( google, seen) = fake_google ( ) .await;
324
let store = tempfile:: tempdir( ) .unwrap ( ) ;
325
let h = hub_with ( store.path ( ) , Some ( & google) ) .await;
326
db:: accounts:: create_account( & h.app.db, " andy" , " [email protected] " , " x" , " salt" , false ) .await.unwrap ( ) ;
327
db:: accounts:: create_account( & h.app.db, " bob" , " [email protected] " , " x" , " salt" , false ) .await.unwrap ( ) ;
328
create ( & h.app, " andy" , " demo" , hub_api:: Visibility:: Public) .await;
329
let work = tempfile:: tempdir( ) .unwrap ( ) ;
330
push ( & format! ( " {} /andy/demo" , h.base) , work.path ( ) , & [ ( " README.md" , " hello\n " ) ] ) ;
331
332
backups:: save( & h.app.db, & gcs ( " andy" , " andy-backup" ) ) .await.unwrap ( ) ;
333
let first = backups:: run( & h.app, " andy" , " now" ) .await.unwrap ( ) ;
334
assert_eq! ( ( first.status.as_str ( ) , first.repos) , ( " ok" , 1 ) , " {}" , first.detail) ;
335
{
336
let g = seen.lock ( ) .unwrap ( ) ;
337
assert! ( g.objects.keys ( ) .any ( | ( b , n ) | b = = " andy-backup" & & n = = & format! ( " runs/{} /DONE" , first.at) ) ) ;
338
assert! ( g.objects.keys ( ) .all ( | ( b , _) | b = = " andy-backup" ) ) ;
339
let ( sub, aud) = g.exchanged.first ( ) .unwrap ( ) ;
340
assert_eq! (
341
( sub.as_str ( ) , aud.as_str ( ) ) ,
342
( " backup:andy" , format! ( " https:{PROVIDER} " ) .as_str ( ) ) ,
343
" the hub signs in as the owner, for the provider"
344
) ;
345
}
346
tokio:: time:: sleep( std:: time:: Duration:: from_millis( 1100 ) ) .await;
347
let second = backups:: run( & h.app, " andy" , " now" ) .await.unwrap ( ) ;
348
assert_eq! ( ( second.status.as_str ( ) , second.sent) , ( " ok" , 0 ) , " {}" , second.detail) ;
349
350
let before = seen.lock ( ) .unwrap ( ) .objects.len ( ) ;
351
let dest = backups:: destination( & h.app, & gcs ( " andy" , " andy-backup" ) ) .unwrap ( ) ;
352
tokio:: task:: spawn_blocking( move | | backups:: probe( dest.as_ref ( ) ) ) .await.unwrap ( ) .unwrap ( ) ;
353
assert_eq! ( seen.lock ( ) .unwrap ( ) .objects.len ( ) , before) ;
354
355
356
let empty = tempfile:: tempdir( ) .unwrap ( ) ;
357
let fresh = hub_with ( empty.path ( ) , Some ( & google) ) .await;
358
let dest: Arc< dyn Destination> = backups:: destination( & fresh.app, & gcs ( " andy" , " andy-backup" ) ) .unwrap ( ) .into ( ) ;
359
assert_eq! ( backups:: restore_into_hub( & fresh.app, dest, None ) .await.unwrap ( ) , vec! [ " andy/demo (repos)" ] ) ;
360
let name = RepoName:: parse( " andy/demo" ) .unwrap ( ) ;
361
assert_eq! ( files ( & fresh.app.repos.dir ( & name) ) , files ( & h.app.repos.dir ( & name) ) , " byte for byte" ) ;
362
363
364
365
backups:: save( & h.app.db, & gcs ( " bob" , " andy-backup" ) ) .await.unwrap ( ) ;
366
let refused = backups:: run( & h.app, " bob" , " now" ) .await.unwrap ( ) ;
367
assert_eq! ( refused.status, " failed" ) ;
368
assert! ( refused.detail.contains ( " roles/storage.objectAdmin" ) & & refused.detail.contains ( " backup:bob" ) , " {}" , refused.detail) ;
d7d18246 Andy McCall 23 days ago ↶
369
}
5ef6cf72 Andy McCall 23 days ago ↶
370
371
372
373
374
375
376
# [ tokio ::test ( flavor = " multi_thread" ) ]
377
async fn a_restore_brings_back_issues_proposals_and_releases ( ) {
378
let store = tempfile:: tempdir( ) .unwrap ( ) ;
379
let h = hub ( store.path ( ) ) .await;
380
let andy = db:: accounts:: create_account( & h.app.db, " andy" , " [email protected] " , " x" , " salt" , false ) .await.unwrap ( ) ;
381
let bob = db:: accounts:: create_account( & h.app.db, " bob" , " [email protected] " , " x" , " salt" , false ) .await.unwrap ( ) ;
382
create ( & h.app, " andy" , " demo" , hub_api:: Visibility:: Public) .await;
383
let work = tempfile:: tempdir( ) .unwrap ( ) ;
384
push ( & format! ( " {} /andy/demo" , h.base) , work.path ( ) , & [ ( " README.md" , " hello\n " ) ] ) ;
385
let row = db:: repos:: get( & h.app.db, " andy" , " demo" ) .await.unwrap ( ) .unwrap ( ) ;
386
db:: repos:: set_diffusion( & h.app.db, row.id, " green" ) .await.unwrap ( ) ;
387
388
for n in 0 .. 3 {
389
db:: issues:: upsert_label( & h.app.db, row.id, & format! ( " spare{n} " ) , " #000000" , " " ) .await.unwrap ( ) ;
390
}
391
let bug = db:: issues:: upsert_label( & h.app.db, row.id, " bug" , " #d73a4a" , " Something is wrong" ) .await.unwrap ( ) ;
392
let m = db:: issues:: upsert_milestone( & h.app.db, row.id, " 1.0" , " the first" , None ) .await.unwrap ( ) ;
393
let issue = db:: issues:: create(
394
& h.app.db,
395
db:: issues:: NewIssue { repo_id: row.id, title: " Sprites flicker" , body: " on level two" , author_id: Some ( andy.id) , author: " andy" } ,
396
)
397
.await
398
.unwrap ( ) ;
399
db:: issues:: add_comment( & h.app.db, issue.id, Some ( bob.id) , " bob" , " seen it too" ) .await.unwrap ( ) ;
400
db:: issues:: set_issue_label( & h.app.db, issue.id, bug.id, true ) .await.unwrap ( ) ;
401
db:: issues:: set_milestone( & h.app.db, issue.id, Some ( m.id) ) .await.unwrap ( ) ;
402
db:: issues:: set_assignee( & h.app.db, issue.id, andy.id, true ) .await.unwrap ( ) ;
403
db:: issues:: set_assignee( & h.app.db, issue.id, bob.id, true ) .await.unwrap ( ) ;
404
let p = db:: proposals:: create(
405
& h.app.db,
406
db:: proposals:: NewProposal {
407
repo_id: row.id,
408
title: " Double-buffer the sprites" ,
409
body: " fixes the flicker" ,
410
author_id: Some ( bob.id) ,
411
author: " bob" ,
412
draft: false ,
413
target: " main" ,
414
source_kind: " bookmark" ,
415
source_repo_id: Some ( row.id) ,
416
source_bookmark: " fix" ,
417
source_changes: " " ,
418
} ,
419
)
420
.await
421
.unwrap ( ) ;
422
db:: proposals:: add_event( & h.app.db, p.id, " bob" , " opened" , " " ) .await.unwrap ( ) ;
423
db:: proposals:: add_review( & h.app.db, p.id, andy.id, " andy" , " approve" , " nice" ) .await.unwrap ( ) ;
424
let release = db:: releases:: create( & h.app.db, row.id, " v1.0" , " One" , " notes" , false , Some ( ( andy.id, " andy" ) ) ) .await.unwrap ( ) ;
425
let asset = b " a game image" .to_vec ( ) ;
426
let hash = blake3:: hash( & asset) .to_hex ( ) .to_string ( ) ;
427
let path = h.app.config.data.join ( " assets" ) .join ( & hash[ .. 2 ] ) .join ( & hash) ;
428
std:: fs:: create_dir_all( path.parent ( ) .unwrap ( ) ) .unwrap ( ) ;
429
std:: fs:: write( & path, & asset) .unwrap ( ) ;
430
db:: releases:: add_asset( & h.app.db, release.id, " game.prg" , asset.len ( ) as i64 , & hash, " application/octet-stream" ) .await.unwrap ( ) ;
431
db:: hooks:: create_hook( & h.app.db, Some ( row.id) , None , " https://example.com/hook" , " s3cret-value" , " push" ) .await.unwrap ( ) ;
432
433
let mut s = Setting:: off( " andy" , " user" ) ;
434
s.every = " hourly" .into ( ) ;
435
s.target = store.path ( ) .display ( ) .to_string ( ) ;
436
backups:: save( & h.app.db, & s) .await.unwrap ( ) ;
437
let run = backups:: run( & h.app, " andy" , " now" ) .await.unwrap ( ) ;
438
assert_eq! ( run.status, " ok" , " {}" , run.detail) ;
439
let dest = Directory { root: store.path ( ) .join ( " andy" ) } ;
440
let text = String :: from_utf8_lossy( & dest.get ( & format! ( " runs/{} /records/demo.json" , run.at) ) .unwrap ( ) ) .into_owned ( ) ;
441
assert! ( ! text.contains ( " s3cret-value" ) , " never a secret" ) ;
442
assert! ( text.contains ( " \" _names\" " ) & & text.contains ( " \" bob\" " ) , " accounts by name" ) ;
443
444
445
let empty = tempfile:: tempdir( ) .unwrap ( ) ;
446
let fresh = hub ( empty.path ( ) ) .await;
447
let andy2 = db:: accounts:: create_account( & fresh.app.db, " andy" , " [email protected] " , " x" , " salt" , false ) .await.unwrap ( ) ;
448
let dest: Arc< dyn Destination> = Arc:: new( Directory { root: store.path ( ) .join ( " andy" ) } ) ;
449
let done = backups:: restore_into_hub( & fresh.app, dest, None ) .await.unwrap ( ) ;
450
assert_eq! ( done[ 0 ] , " andy/demo (repos)" ) ;
451
let notes = done[ 1 .. ] .join ( " \n " ) ;
452
assert! ( notes.contains ( " webhook https://example.com/hook: enter its secret again" ) , " {notes}" ) ;
453
assert! ( notes.contains ( " issue_assignees: 1 row(s) left out" ) , " bob is not on this hub: {notes}" ) ;
454
let r2 = db:: repos:: get( & fresh.app.db, " andy" , " demo" ) .await.unwrap ( ) .unwrap ( ) ;
455
assert_eq! ( r2.diffusion, " green" , " settings come back" ) ;
456
3b1bc27f Andy McCall 20 days ago
457
let issues: Vec< ( i64 , i64 , String, Option< i64 > ) > = sqlx:: query_as( " SELECT id, number, title, author_id FROM issues WHERE repo_id = $1" )
5ef6cf72 Andy McCall 23 days ago ↶
458
.bind ( r2.id)
459
.fetch_all ( & fresh.app.db)
460
.await
461
.unwrap ( ) ;
462
assert_eq! ( issues.len ( ) , 1 ) ;
463
let ( iid, number, title, author) = issues[ 0 ] .clone ( ) ;
464
assert_eq! ( ( number, title.as_str ( ) , author) , ( issue.number, " Sprites flicker" , Some ( andy2.id) ) ) ;
465
let comments = db:: issues:: comments( & fresh.app.db, iid) .await.unwrap ( ) ;
466
assert_eq! ( comments.len ( ) , 1 ) ;
467
assert_eq! ( ( comments[ 0 ] .author.as_str ( ) , comments[ 0 ] .body.as_str ( ) ) , ( " bob" , " seen it too" ) ) ;
468
let labels: Vec< String> =
3b1bc27f Andy McCall 20 days ago
469
sqlx:: query_scalar( " SELECT l.name FROM issue_labels il JOIN labels l ON l.id = il.label_id WHERE il.issue_id = $1" )
5ef6cf72 Andy McCall 23 days ago ↶
470
.bind ( iid)
471
.fetch_all ( & fresh.app.db)
472
.await
473
.unwrap ( ) ;
474
assert_eq! ( labels, vec! [ " bug" ] , " the label, its id mapped" ) ;
475
let milestone: Option< String> =
3b1bc27f Andy McCall 20 days ago
476
sqlx:: query_scalar( " SELECT m.title FROM issues i JOIN milestones m ON m.id = i.milestone_id WHERE i.id = $1" )
5ef6cf72 Andy McCall 23 days ago ↶
477
.bind ( iid)
478
.fetch_one ( & fresh.app.db)
479
.await
480
.unwrap ( ) ;
481
assert_eq! ( milestone.as_deref ( ) , Some ( " 1.0" ) ) ;
482
assert_eq! ( db:: issues:: assignees( & fresh.app.db, iid) .await.unwrap ( ) , vec! [ " andy" ] ) ;
483
484
let p2 = db:: proposals:: get( & fresh.app.db, r2.id, p.number) .await.unwrap ( ) .expect ( " the proposal" ) ;
485
assert_eq! ( ( p2.title.as_str ( ) , p2.author.as_str ( ) , p2.author_id) , ( " Double-buffer the sprites" , " bob" , None ) ) ;
3b1bc27f Andy McCall 20 days ago
486
let reviews: Vec< ( String, String) > = sqlx:: query_as( " SELECT author, verdict FROM proposal_reviews WHERE proposal_id = $1" )
5ef6cf72 Andy McCall 23 days ago ↶
487
.bind ( p2.id)
488
.fetch_all ( & fresh.app.db)
489
.await
490
.unwrap ( ) ;
491
assert_eq! ( reviews, vec! [ ( " andy" .to_string ( ) , " approve" .to_string ( ) ) ] ) ;
492
assert! ( db:: proposals:: events( & fresh.app.db, p2.id) .await.unwrap ( ) .iter ( ) .any ( | e | e.event = = " opened" ) ) ;
493
494
let rel = db:: releases:: get( & fresh.app.db, r2.id, " v1.0" ) .await.unwrap ( ) .expect ( " the release" ) ;
495
let assets = db:: releases:: assets( & fresh.app.db, rel.id) .await.unwrap ( ) ;
496
assert_eq! ( assets.len ( ) , 1 ) ;
497
assert_eq! ( std:: fs:: read( fresh.app.config.data.join ( " assets" ) .join ( & hash[ .. 2 ] ) .join ( & hash) ) .unwrap ( ) , asset) ;
498
499
let hits = db:: notify:: search( & fresh.app.db, " flicker" , Some ( r2.id) , 10 ) .await.unwrap ( ) ;
500
assert! ( hits.iter ( ) .any ( | h | h.kind = = " issue" & & h.target_id = = iid ) , " {:?}" , hits.iter ( ) .map ( | h | & h.title) .collect:: < Vec< _ > > ( ) ) ;
501
502
let next = db:: issues:: create(
503
& fresh.app.db,
504
db:: issues:: NewIssue { repo_id: r2.id, title: " After" , body: " " , author_id: Some ( andy2.id) , author: " andy" } ,
505
)
506
.await
507
.unwrap ( ) ;
508
assert! ( next.number > p.number, " {} after {}" , next.number, p.number) ;
509
}
d3b048b2 Andy McCall 23 days ago ↶
510
511
512
513
514
515
# [ tokio ::test ( flavor = " multi_thread" ) ]
516
async fn repositories_choose_their_own_backup ( ) {
517
let store = tempfile:: tempdir( ) .unwrap ( ) ;
518
let h = hub ( store.path ( ) ) .await;
519
db:: accounts:: create_account( & h.app.db, " andy" , " [email protected] " , " x" , " salt" , false ) .await.unwrap ( ) ;
520
for n in [ " game" , " notes" , " secret" ] {
521
create ( & h.app, " andy" , n, hub_api:: Visibility:: Public) .await;
522
let work = tempfile:: tempdir( ) .unwrap ( ) ;
523
push ( & format! ( " {} /andy/{n} " , h.base) , work.path ( ) , & [ ( " README.md" , n) ] ) ;
524
}
525
let id = | n : & 'static str | {
526
let db = h.app.db.clone ( ) ;
527
async move { db:: repos:: get( & db, " andy" , n) .await.unwrap ( ) .unwrap ( ) .id }
528
} ;
529
db:: repos:: set_backup( & h.app.db, id ( " secret" ) .await, " off" ) .await.unwrap ( ) ;
530
let mut s = Setting:: off( " andy" , " user" ) ;
531
s.every = " daily" .into ( ) ;
532
s.target = store.path ( ) .display ( ) .to_string ( ) ;
533
backups:: save( & h.app.db, & s) .await.unwrap ( ) ;
534
let names = | at : String| {
535
let dest = Directory { root: store.path ( ) .join ( " andy" ) } ;
536
let mut v = dest.list ( & format! ( " runs/{at} /records" ) ) .unwrap ( ) ;
537
v.sort ( ) ;
538
v
539
} ;
540
let first = backups:: run( & h.app, " andy" , " schedule" ) .await.unwrap ( ) ;
541
assert_eq! ( ( first.status.as_str ( ) , first.repos) , ( " ok" , 2 ) , " {}" , first.detail) ;
542
assert_eq! ( names ( first.at.clone ( ) ) , vec! [ " game.json" , " notes.json" ] , " the one left out is not in it" ) ;
543
544
assert! ( backups:: due( & h.app.db) .await.unwrap ( ) .is_empty ( ) ) ;
545
db:: repos:: set_backup( & h.app.db, id ( " game" ) .await, " hourly" ) .await.unwrap ( ) ;
546
sqlx:: query( " UPDATE backup_runs SET started_ms = started_ms - 2 * 3600 * 1000" ) .execute ( & h.app.db) .await.unwrap ( ) ;
547
assert_eq! ( backups:: due( & h.app.db) .await.unwrap ( ) .len ( ) , 1 , " hourly for the game" ) ;
548
549
s.every = " off" .into ( ) ;
550
backups:: save( & h.app.db, & s) .await.unwrap ( ) ;
551
assert_eq! ( backups:: due( & h.app.db) .await.unwrap ( ) .len ( ) , 1 ) ;
552
tokio:: time:: sleep( std:: time:: Duration:: from_millis( 1100 ) ) .await;
553
let second = backups:: run( & h.app, " andy" , " schedule" ) .await.unwrap ( ) ;
554
assert_eq! ( names ( second.at.clone ( ) ) , vec! [ " game.json" ] ) ;
555
556
tokio:: time:: sleep( std:: time:: Duration:: from_millis( 1100 ) ) .await;
557
let third = backups:: run( & h.app, " andy" , " now" ) .await.unwrap ( ) ;
558
assert_eq! ( names ( third.at.clone ( ) ) , vec! [ " game.json" , " notes.json" ] ) ;
559
560
let ( owners, uncovered) = backups:: overview( & h.app.db) .await.unwrap ( ) ;
561
assert_eq! ( ( owners[ 0 ] .repos, uncovered.len ( ) ) , ( 1 , 0 ) ) ;
562
}
7b9f4570 Andy McCall 23 days ago ↶
563
564
565
566
567
568
async fn fake_aws ( ) -> ( String, Shared2) {
569
use axum:: extract:: { Request, State} ;
570
use axum:: http:: StatusCode;
571
use axum:: response:: IntoResponse;
572
let state: Shared2 = Default :: default( ) ;
573
async fn handle ( State( g ) : State< Shared2> , req : Request) -> axum:: response:: Response {
574
let ( parts, body) = req.into_parts ( ) ;
575
let bytes = http_body_util:: BodyExt:: collect( body) .await.unwrap ( ) .to_bytes ( ) ;
576
let path = parts.uri.path ( ) .to_string ( ) ;
577
let header = | h : & str | parts.headers.get ( h) .and_then ( | v | v.to_str ( ) .ok ( ) ) .unwrap_or ( " " ) .to_string ( ) ;
578
if path = = " /" & & parts.method = = " POST" {
579
let form: Vec< ( String, String) > = String :: from_utf8_lossy( & bytes)
580
.split ( ' &' )
581
.filter_map ( | kv | kv.split_once ( ' =' ) .map ( | ( k , v ) | ( k.to_string ( ) , decode ( & v.replace ( ' +' , " " ) ) ) ) )
582
.collect ( ) ;
583
let field = | k : & str | form.iter ( ) .find ( | ( f , _) | f = = k ) .map ( | ( _, v ) | v.clone ( ) ) .unwrap_or_default ( ) ;
584
let jwt = field ( " WebIdentityToken" ) ;
585
let claims: serde_json:: Value = serde_json:: from_slice( & base64url ( jwt.split ( ' .' ) .nth ( 1 ) .unwrap ( ) ) ) .unwrap ( ) ;
586
let ( sub, aud) = ( claims[ " sub" ] .as_str ( ) .unwrap ( ) .to_string ( ) , claims[ " aud" ] .as_str ( ) .unwrap ( ) .to_string ( ) ) ;
587
g.lock ( ) .unwrap ( ) .exchanged.push ( ( sub.clone ( ) , aud.clone ( ) ) ) ;
588
if field ( " Action" ) ! = " AssumeRoleWithWebIdentity" | | ! sub.starts_with ( " backup:" ) | | aud ! = " sts.amazonaws.com" {
589
return ( StatusCode:: FORBIDDEN , " <ErrorResponse><Error><Code>AccessDenied</Code><Message>Not authorized to perform sts:AssumeRoleWithWebIdentity</Message></Error></ErrorResponse>" ) .into_response ( ) ;
590
}
591
let owner = sub.trim_start_matches ( " backup:" ) ;
592
return format! (
593
" <AssumeRoleWithWebIdentityResponse><AssumeRoleWithWebIdentityResult><Credentials>\
594
<AccessKeyId>ASIA{owner} </AccessKeyId><SecretAccessKey>secret/{owner} </SecretAccessKey>\
595
<SessionToken>session-{owner} </SessionToken><Expiration>2030-01-01T00:00:00Z</Expiration>\
596
</Credentials></AssumeRoleWithWebIdentityResult></AssumeRoleWithWebIdentityResponse>"
597
)
598
.into_response ( ) ;
599
}
600
601
let rest = path.strip_prefix ( " /s3/" ) .unwrap_or ( " " ) ;
602
let ( bucket, key) = rest.split_once ( ' /' ) .unwrap_or ( ( rest, " " ) ) ;
603
let ( bucket, key) = ( bucket.to_string ( ) , decode ( key) ) ;
604
let owner = bucket.trim_end_matches ( " -backup" ) .to_string ( ) ;
605
606
let session = header ( " x-amz-security-token" ) ;
607
let who = session.trim_start_matches ( " session-" ) .to_string ( ) ;
608
let query: Vec< ( String, String) > = parts
609
.uri
610
.query ( )
611
.unwrap_or ( " " )
612
.split ( ' &' )
613
.filter ( | kv | ! kv.is_empty ( ) )
614
.map ( | kv | kv.split_once ( ' =' ) .map ( | ( k , v ) | ( decode ( k) , decode ( v) ) ) .unwrap_or ( ( decode ( kv) , String :: new( ) ) ) )
615
.collect ( ) ;
616
let signed = vec! [
617
( " host" .to_string ( ) , header ( " host" ) ) ,
618
( " x-amz-content-sha256" .to_string ( ) , header ( " x-amz-content-sha256" ) ) ,
619
( " x-amz-date" .to_string ( ) , header ( " x-amz-date" ) ) ,
620
( " x-amz-security-token" .to_string ( ) , session.clone ( ) ) ,
621
] ;
622
let id = format! ( " ASIA{who} " ) ;
623
let secret = format! ( " secret/{who} " ) ;
624
let want = oxygenhub:: backups:: sigv4(
625
parts.method.as_str ( ) ,
626
& path,
627
& query,
628
& signed,
629
& header ( " x-amz-content-sha256" ) ,
630
( & id, & secret) ,
631
" eu-west-2" ,
632
" s3" ,
633
& header ( " x-amz-date" ) ,
634
) ;
635
use sha2:: Digest;
636
let body_hash = hex:: encode( sha2:: Sha256:: digest( & bytes) ) ;
637
if header ( " authorization" ) ! = want | | header ( " x-amz-content-sha256" ) ! = body_hash {
638
return (
639
StatusCode:: FORBIDDEN ,
640
" <Error><Code>SignatureDoesNotMatch</Code><Message>The request signature we calculated does not match</Message></Error>" ,
641
)
642
.into_response ( ) ;
643
}
644
if who ! = owner {
645
return ( StatusCode:: FORBIDDEN , " <Error><Code>AccessDenied</Code><Message>Access Denied</Message></Error>" ) .into_response ( ) ;
646
}
647
let mut g = g.lock ( ) .unwrap ( ) ;
648
match ( parts.method.as_str ( ) , key.is_empty ( ) ) {
649
( " PUT" , false ) => {
650
g.objects.insert ( ( bucket, key) , bytes.to_vec ( ) ) ;
651
StatusCode:: OK .into_response ( )
652
}
653
( " GET" , false ) | ( " HEAD" , false ) => match g.objects.get ( & ( bucket, key) ) {
654
Some ( b) => b.clone ( ) .into_response ( ) ,
655
None => ( StatusCode:: NOT_FOUND , " <Error><Code>NoSuchKey</Code></Error>" ) .into_response ( ) ,
656
} ,
657
( " DELETE" , false ) => {
658
g.objects.remove ( & ( bucket, key) ) ;
659
StatusCode:: NO_CONTENT .into_response ( )
660
}
661
( " GET" , true ) => {
662
let prefix = query.iter ( ) .find ( | ( k , _) | k = = " prefix" ) .map ( | ( _, v ) | v.clone ( ) ) .unwrap_or_default ( ) ;
663
let delimited = query.iter ( ) .any ( | ( k , _) | k = = " delimiter" ) ;
664
let ( mut keys, mut prefixes) = ( String :: new( ) , std:: collections:: BTreeSet:: new( ) ) ;
665
for ( b, n) in g.objects.keys ( ) {
666
if * b ! = bucket | | ! n.starts_with ( & prefix) {
667
continue ;
668
}
669
match n[ prefix.len ( ) .. ] .find ( ' /' ) {
670
Some ( i) if delimited => {
671
prefixes.insert ( format! ( " {prefix} {} " , & n[ prefix.len ( ) .. prefix.len ( ) + i + 1 ] ) ) ;
672
}
673
_ => keys.push_str ( & format! ( " <Contents><Key>{n} </Key></Contents>" ) ) ,
674
}
675
}
676
let common: String = prefixes.iter ( ) .map ( | p | format! ( " <CommonPrefixes><Prefix>{p} </Prefix></CommonPrefixes>" ) ) .collect ( ) ;
677
format! ( " <ListBucketResult><Prefix>{prefix} </Prefix><IsTruncated>false</IsTruncated>{keys} {common} </ListBucketResult>" )
678
.into_response ( )
679
}
680
_ => StatusCode:: METHOD_NOT_ALLOWED .into_response ( ) ,
681
}
682
}
683
let app = axum:: Router:: new( ) .fallback ( handle) .with_state ( state.clone ( ) ) ;
684
let listener = tokio:: net:: TcpListener:: bind( " 127.0.0.1:0" ) .await.unwrap ( ) ;
685
let port = listener.local_addr ( ) .unwrap ( ) .port ( ) ;
686
tokio:: spawn( async move { axum:: serve( listener, app) .await.unwrap ( ) } ) ;
687
( format! ( " http://127.0.0.1:{port} " ) , state)
688
}
689
690
async fn hub_aws ( backups : & Path, aws : & str ) -> Hub {
691
hermetic ( ) ;
692
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
693
let mut config = Config:: load( dir.path ( ) ) .unwrap ( ) ;
694
config.auth.push_tokens = vec! [ " site" .into ( ) ] ;
695
config.backups.directories = vec! [ backups.to_path_buf ( ) ] ;
696
config.backups.aws_sts_url = aws.to_string ( ) ;
697
config.backups.s3_url = format! ( " {aws} /s3/{{ bucket}} " ) ;
698
let listener = tokio:: net:: TcpListener:: bind( " 127.0.0.1:0" ) .await.unwrap ( ) ;
699
let port = listener.local_addr ( ) .unwrap ( ) .port ( ) ;
700
config.server.base_url = format! ( " http://127.0.0.1:{port} " ) ;
701
let app = oxygenhub:: build( config) .await.unwrap ( ) ;
702
let router = oxygenhub:: router( app.clone ( ) ) ;
703
tokio:: spawn( async move { axum:: serve( listener, router) .await.unwrap ( ) } ) ;
704
Hub { app, base: format! ( " http://127.0.0.1:{port} " ) , _dir: dir }
705
}
706
707
const ROLE : & str = " arn:aws:iam::123456789012:role/oxygenhub-backup" ;
708
709
fn s3 ( owner : & str , bucket : & str ) -> Setting {
710
let mut s = Setting:: off( owner, " user" ) ;
711
s.every = " hourly" .into ( ) ;
712
s.destination = " s3" .into ( ) ;
713
s.target = bucket.into ( ) ;
714
s.provider = ROLE .into ( ) ;
715
s.region = " eu-west-2" .into ( ) ;
716
s.prefix = " oxygen hub" .into ( ) ;
717
s
718
}
719
720
721
722
723
724
725
# [ tokio ::test ( flavor = " multi_thread" ) ]
726
async fn an_s3_backup_needs_no_key_and_restores_the_same_repository ( ) {
727
let ( aws, seen) = fake_aws ( ) .await;
728
let store = tempfile:: tempdir( ) .unwrap ( ) ;
729
let h = hub_aws ( store.path ( ) , & aws) .await;
730
db:: accounts:: create_account( & h.app.db, " andy" , " [email protected] " , " x" , " salt" , false ) .await.unwrap ( ) ;
731
db:: accounts:: create_account( & h.app.db, " bob" , " [email protected] " , " x" , " salt" , false ) .await.unwrap ( ) ;
732
create ( & h.app, " andy" , " demo" , hub_api:: Visibility:: Public) .await;
733
let work = tempfile:: tempdir( ) .unwrap ( ) ;
734
push ( & format! ( " {} /andy/demo" , h.base) , work.path ( ) , & [ ( " README.md" , " hello\n " ) , ( " src/a b+c.rs" , " fn main() {}\n " ) ] ) ;
735
736
backups:: save( & h.app.db, & s3 ( " andy" , " andy-backup" ) ) .await.unwrap ( ) ;
737
let first = backups:: run( & h.app, " andy" , " now" ) .await.unwrap ( ) ;
738
assert_eq! ( ( first.status.as_str ( ) , first.repos) , ( " ok" , 1 ) , " {}" , first.detail) ;
739
{
740
let g = seen.lock ( ) .unwrap ( ) ;
741
assert! (
742
g.objects.keys ( ) .any ( | ( b , n ) | b = = " andy-backup" & & n = = & format! ( " oxygen hub/runs/{} /DONE" , first.at) ) ,
743
" under the prefix"
744
) ;
745
assert_eq! ( g.exchanged.first ( ) .map ( | ( s , a ) | ( s.as_str ( ) , a.as_str ( ) ) ) , Some ( ( " backup:andy" , " sts.amazonaws.com" ) ) ) ;
746
}
747
tokio:: time:: sleep( std:: time:: Duration:: from_millis( 1100 ) ) .await;
748
let second = backups:: run( & h.app, " andy" , " now" ) .await.unwrap ( ) ;
749
assert_eq! ( ( second.status.as_str ( ) , second.sent) , ( " ok" , 0 ) , " {}" , second.detail) ;
750
let before = seen.lock ( ) .unwrap ( ) .objects.len ( ) ;
751
let dest = backups:: destination( & h.app, & s3 ( " andy" , " andy-backup" ) ) .unwrap ( ) ;
752
tokio:: task:: spawn_blocking( move | | backups:: probe( dest.as_ref ( ) ) ) .await.unwrap ( ) .unwrap ( ) ;
753
assert_eq! ( seen.lock ( ) .unwrap ( ) .objects.len ( ) , before, " the probe cleans up" ) ;
754
755
let empty = tempfile:: tempdir( ) .unwrap ( ) ;
756
let fresh = hub_aws ( empty.path ( ) , & aws) .await;
757
let dest: Arc< dyn Destination> = backups:: destination( & fresh.app, & s3 ( " andy" , " andy-backup" ) ) .unwrap ( ) .into ( ) ;
758
assert_eq! ( backups:: restore_into_hub( & fresh.app, dest, None ) .await.unwrap ( ) , vec! [ " andy/demo (repos)" ] ) ;
759
let name = RepoName:: parse( " andy/demo" ) .unwrap ( ) ;
760
assert_eq! ( files ( & fresh.app.repos.dir ( & name) ) , files ( & h.app.repos.dir ( & name) ) , " byte for byte" ) ;
761
762
backups:: save( & h.app.db, & s3 ( " bob" , " andy-backup" ) ) .await.unwrap ( ) ;
763
let refused = backups:: run( & h.app, " bob" , " now" ) .await.unwrap ( ) ;
764
assert_eq! ( refused.status, " failed" ) ;
765
assert! ( refused.detail.contains ( " s3:PutObject" ) & & refused.detail.contains ( ROLE ) , " {}" , refused.detail) ;
766
}
2e9188ca Andy McCall 22 days ago ↶
767
768
769
async fn api (
770
app : & Shared,
771
method : & str ,
772
path : & str ,
773
token : & str ,
774
body : Option< serde_json:: Value> ,
775
) -> ( axum:: http:: StatusCode, serde_json:: Value) {
776
use axum:: body:: Body;
777
use http_body_util:: BodyExt;
778
use tower:: ServiceExt;
779
let mut req =
780
axum:: http:: Request:: builder( ) .method ( method) .uri ( format! ( " /api/v1{path} " ) ) .header ( " authorization" , format! ( " Bearer {token} " ) ) ;
781
let body = match body {
782
Some ( b) => {
783
req = req.header ( " content-type" , " application/json" ) ;
784
Body:: from( b.to_string ( ) )
785
}
786
None => Body:: empty( ) ,
787
} ;
788
let res = oxygenhub:: router( app.clone ( ) ) .oneshot ( req.body ( body) .unwrap ( ) ) .await.unwrap ( ) ;
789
let st = res.status ( ) ;
790
let bytes = res.into_body ( ) .collect ( ) .await.unwrap ( ) .to_bytes ( ) ;
791
( st, serde_json:: from_slice( & bytes) .unwrap_or ( serde_json:: Value:: Null) )
792
}
793
794
795
796
797
# [ tokio ::test ( flavor = " multi_thread" ) ]
798
async fn backups_are_set_up_and_run_through_the_api ( ) {
799
let store = tempfile:: tempdir( ) .unwrap ( ) ;
800
let h = hub ( store.path ( ) ) .await;
801
let andy = db:: accounts:: create_account( & h.app.db, " andy" , " [email protected] " , " x" , " salt" , false ) .await.unwrap ( ) ;
802
let bob = db:: accounts:: create_account( & h.app.db, " bob" , " [email protected] " , " x" , " salt" , false ) .await.unwrap ( ) ;
803
db:: accounts:: create_org( & h.app.db, " club" , " Club" , andy.id) .await.unwrap ( ) ;
804
create ( & h.app, " andy" , " demo" , hub_api:: Visibility:: Public) .await;
805
create ( & h.app, " club" , " game" , hub_api:: Visibility:: Private) .await;
806
let token = | id : i64 , scopes : & 'static str | {
807
let db = h.app.db.clone ( ) ;
808
async move {
809
let ( t, hash) = oxygenhub:: auth:: new_token( ) ;
810
db:: accounts:: create_token( & db, id, " t" , & hash, scopes, " " , None ) .await.unwrap ( ) ;
811
t
812
}
813
} ;
814
let ( andy_t , bob_t , weak) = ( token ( andy.id, " repo:admin" ) .await, token ( bob.id, " repo:admin" ) .await, token ( andy.id, " repo:read" ) .await) ;
815
let dir = store.path ( ) .display ( ) .to_string ( ) ;
816
817
let ( st, empty) = api ( & h.app, " GET" , " /user/backups" , & andy_t , None ) .await;
818
assert_eq! ( st, 200 ) ;
819
assert! ( empty[ " setting" ] .is_null ( ) & & empty[ " runs" ] .as_array ( ) .unwrap ( ) .is_empty ( ) , " {empty}" ) ;
820
let ( st, _ ) = api ( & h.app, " POST" , " /user/backups/run" , & andy_t , None ) .await;
821
assert_eq! ( st, 409 , " nothing saved yet" ) ;
822
let ( st, _ ) =
823
api ( & h.app, " PUT" , " /user/backups" , & weak, Some ( serde_json:: json! ( { " every" : " hourly" , " destination" : " dir" , " dir" : dir } ) ) ) .await;
824
assert_eq! ( st, 403 , " repo:admin only" ) ;
825
let ( st, bad) = api (
826
& h.app,
827
" PUT" ,
828
" /user/backups" ,
829
& andy_t ,
830
Some ( serde_json:: json! ( { " every" : " hourly" , " destination" : " gcs" , " bucket" : " andy-backup" , " provider" : " nope" } ) ) ,
831
)
832
.await;
833
assert_eq! ( st, 400 , " checked as the page checks it: {bad}" ) ;
834
let ( st, saved) = api (
835
& h.app,
836
" PUT" ,
837
" /user/backups" ,
838
& andy_t ,
839
Some ( serde_json:: json! ( { " every" : " hourly" , " destination" : " dir" , " dir" : dir, " keep_days" : 30 } ) ) ,
840
)
841
.await;
842
assert_eq! ( st, 200 , " {saved}" ) ;
843
assert_eq! ( ( saved[ " setting" ] [ " every" ] .as_str ( ) , saved[ " place" ] .as_str ( ) ) , ( Some ( " hourly" ) , Some ( format! ( " {dir} /andy" ) .as_str ( ) ) ) ) ;
844
let ( st, probe) = api ( & h.app, " POST" , " /user/backups/test" , & andy_t , None ) .await;
845
assert_eq! ( ( st.as_u16 ( ) , probe[ " ok" ] .as_bool ( ) ) , ( 200 , Some ( true ) ) , " {probe}" ) ;
846
let ( st, started) = api ( & h.app, " POST" , " /user/backups/run" , & andy_t , None ) .await;
847
assert_eq! ( st, 202 , " {started}" ) ;
848
let mut done = serde_json:: Value:: Null;
849
for _ in 0 .. 200 {
850
let ( _ , runs) = api ( & h.app, " GET" , " /user/backups/runs" , & andy_t , None ) .await;
851
if runs[ 0 ] [ " status" ] .as_str ( ) .is_some_and ( | s | s ! = " running" ) {
852
done = runs[ 0 ] .clone ( ) ;
853
break ;
854
}
855
tokio:: time:: sleep( std:: time:: Duration:: from_millis( 50 ) ) .await;
856
}
857
assert_eq! ( ( done[ " status" ] .as_str ( ) , done[ " repos" ] .as_i64 ( ) , done[ " trigger" ] .as_str ( ) ) , ( Some ( " ok" ) , Some ( 1 ) , Some ( " now" ) ) , " {done}" ) ;
bff9106e Andy McCall 22 days ago ↶
858
859
860
sqlx:: query( " INSERT INTO backup_runs (owner, started_ms, finished_ms, status, at, trigger, detail) VALUES ('andy', 1, 2, 'failed', 'x', 'schedule', 'GCS refused')" )
861
.execute ( & h.app.db)
862
.await
863
.unwrap ( ) ;
864
tokio:: time:: sleep( std:: time:: Duration:: from_millis( 1100 ) ) .await;
865
let again = backups:: run( & h.app, " andy" , " now" ) .await.unwrap ( ) ;
866
assert_eq! ( again.status, " ok" ) ;
3b1bc27f Andy McCall 20 days ago
867
let told = | db : oxygenhub:: db:: Pool| async move { db:: notify:: inbox( & db, andy.id, 20 ) .await.unwrap ( ) } ;
bff9106e Andy McCall 22 days ago ↶
868
assert! ( told ( h.app.db.clone ( ) ) .await.iter ( ) .any ( | n | n.kind = = " backup.recovered" & & n.title.contains ( " works again" ) ) ) ;
869
assert_eq! ( backups:: daily_summary( & h.app, db:: now_ms( ) , true ) .await.unwrap ( ) , 1 ) ;
870
let summary = told ( h.app.db.clone ( ) ) .await.into_iter ( ) .find ( | n | n.kind = = " backup.summary" ) .expect ( " a summary" ) ;
871
assert! ( summary.title.contains ( " Backups of andy today" ) & & summary.title.contains ( " runs" ) , " {}" , summary.title) ;
2e9188ca Andy McCall 22 days ago ↶
872
873
874
let ( st, _ ) =
875
api ( & h.app, " PUT" , " /orgs/club/backups" , & bob_t , Some ( serde_json:: json! ( { " every" : " hourly" , " destination" : " dir" , " dir" : dir } ) ) )
876
.await;
877
assert_eq! ( st, 404 ) ;
878
let ( st, org) = api (
879
& h.app,
880
" PUT" ,
881
" /orgs/club/backups" ,
882
& andy_t ,
883
Some ( serde_json:: json! ( { " every" : " daily" , " destination" : " dir" , " dir" : dir, " keep_days" : 90 } ) ) ,
884
)
885
.await;
886
assert_eq! ( st, 200 , " {org}" ) ;
887
assert_eq! ( ( org[ " setting" ] [ " kind" ] .as_str ( ) , org[ " setting" ] [ " keep_days" ] .as_i64 ( ) ) , ( Some ( " org" ) , Some ( 90 ) ) ) ;
888
let ( st, _ ) = api ( & h.app, " GET" , " /orgs/club/backups" , & bob_t , None ) .await;
889
assert_eq! ( st, 404 ) ;
890
}