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