19bb31ff Andy McCall 1 month ago ↶
1
2
3
4
use axum:: body:: Body;
5
use axum:: http:: { header, Request, StatusCode} ;
6
use http_body_util:: BodyExt;
7
use oxy_core:: repo:: Repo;
8
use oxygenhub:: config:: Config;
9
use oxygenhub:: db;
10
use oxygenhub:: Shared;
11
use std:: path:: Path;
12
use tower:: ServiceExt;
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
fn write ( root : & Path, rel : & str , content : & [u8 ]) {
25
let p = root.join ( rel) ;
26
std:: fs:: create_dir_all( p.parent ( ) .unwrap ( ) ) .unwrap ( ) ;
27
std:: fs:: write( p, content) .unwrap ( ) ;
28
}
29
30
struct Hub {
31
app : Shared,
32
base : String,
33
_dir : tempfile:: TempDir,
34
}
35
36
async fn hub ( ) -> Hub {
37
hermetic ( ) ;
38
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
39
let mut config = Config:: load( dir.path ( ) ) .unwrap ( ) ;
c8684d44 Andy McCall 21 days ago
40
41
config.registration.setup_code = " test-setup" .into ( ) ;
19bb31ff Andy McCall 1 month ago ↶
42
let listener = tokio:: net:: TcpListener:: bind( " 127.0.0.1:0" ) .await.unwrap ( ) ;
43
let port = listener.local_addr ( ) .unwrap ( ) .port ( ) ;
44
config.server.base_url = format! ( " http://127.0.0.1:{port} " ) ;
9a777fec Andy McCall 22 days ago ↶
45
46
config.outbound.allow = vec! [ " http://127.0.0.1" .into ( ) ] ;
19bb31ff Andy McCall 1 month ago ↶
47
config.registration.mode = " invite" .into ( ) ;
48
let app = oxygenhub:: build( config) .await.unwrap ( ) ;
49
let router = oxygenhub:: router( app.clone ( ) ) ;
50
tokio:: spawn( async move { axum:: serve( listener, router) .await.unwrap ( ) } ) ;
51
Hub { app, base: format! ( " http://127.0.0.1:{port} " ) , _dir: dir }
52
}
53
54
struct Res {
55
status : StatusCode,
56
body : String,
83940d53 Andy McCall 1 month ago ↶
57
19bb31ff Andy McCall 1 month ago ↶
58
cookie : Option< String> ,
59
location : Option< String> ,
83940d53 Andy McCall 1 month ago ↶
60
61
raw_cookies : Vec< String> ,
19bb31ff Andy McCall 1 month ago ↶
62
}
63
64
async fn send ( app : & Shared, method : & str , path : & str , cookie : Option< & str > , form : Option< & str > ) -> Res {
83940d53 Andy McCall 1 month ago ↶
65
let header_value = cookie.map ( | c | format! ( " oxyhub={c} " ) ) ;
66
send_with ( app, method, path, header_value.as_deref ( ) , form) .await
67
}
68
69
70
async fn send_with ( app : & Shared, method : & str , path : & str , cookie_header : Option< & str > , form : Option< & str > ) -> Res {
19bb31ff Andy McCall 1 month ago ↶
71
let mut req = Request:: builder( ) .method ( method) .uri ( path) ;
83940d53 Andy McCall 1 month ago ↶
72
if let Some ( c) = cookie_header {
73
req = req.header ( header:: COOKIE , c.to_string ( ) ) ;
19bb31ff Andy McCall 1 month ago ↶
74
}
75
let body = match form {
76
Some ( f) => {
77
req = req.header ( header:: CONTENT_TYPE , " application/x-www-form-urlencoded" ) ;
78
Body:: from( f.to_string ( ) )
79
}
80
None => Body:: empty( ) ,
81
} ;
82
let res = oxygenhub:: router( app.clone ( ) ) .oneshot ( req.body ( body) .unwrap ( ) ) .await.unwrap ( ) ;
83
let status = res.status ( ) ;
83940d53 Andy McCall 1 month ago ↶
84
let raw_cookies: Vec< String> =
85
res.headers ( ) .get_all ( header:: SET_COOKIE ) .iter ( ) .filter_map ( | v | v.to_str ( ) .ok ( ) ) .map ( String :: from) .collect ( ) ;
86
let cookie =
87
raw_cookies.iter ( ) .filter_map ( | c | c.split ( ' ;' ) .next ( ) ) .filter_map ( | kv | kv.strip_prefix ( " oxyhub=" ) ) .map ( String :: from) .next ( ) ;
19bb31ff Andy McCall 1 month ago ↶
88
let location = res.headers ( ) .get ( header:: LOCATION ) .and_then ( | v | v.to_str ( ) .ok ( ) ) .map ( String :: from) ;
89
let bytes = res.into_body ( ) .collect ( ) .await.unwrap ( ) .to_bytes ( ) ;
83940d53 Andy McCall 1 month ago ↶
90
Res { status, body: String :: from_utf8_lossy( & bytes) .into_owned ( ) , cookie, location, raw_cookies }
19bb31ff Andy McCall 1 month ago ↶
91
}
92
93
async fn get ( app : & Shared, path : & str , cookie : Option< & str > ) -> Res {
94
send ( app, " GET" , path, cookie, None ) .await
95
}
96
97
async fn post ( app : & Shared, path : & str , cookie : Option< & str > , form : & str ) -> Res {
98
send ( app, " POST" , path, cookie, Some ( form) ) .await
99
}
100
c7067c7b Andy McCall 17 days ago
101
102
103
async fn settled ( app : & Shared, r : Res, cookie : Option< & str > , page : & str ) -> Res {
104
assert_eq! ( r.status, StatusCode:: SEE_OTHER , " {}" , r.body) ;
105
let to = r.location.expect ( " a redirect" ) ;
106
assert! ( to.starts_with ( & format! ( " {page} ?" ) ) , " {to} is not {page}" ) ;
107
get ( app, & to, cookie) .await
108
}
109
19bb31ff Andy McCall 1 month ago ↶
110
111
async fn register ( app : & Shared, user : & str , invite : & str ) -> String {
c8684d44 Andy McCall 21 days ago
112
let r = post (
113
app,
114
" /register" ,
115
None ,
116
& format! ( " username={user} &email={user} %40example.com&password=correct-horse-battery&setup=test-setup&invite={invite} " ) ,
117
)
118
.await;
19bb31ff Andy McCall 1 month ago ↶
119
assert_eq! ( r.status, StatusCode:: SEE_OTHER , " {}" , r.body) ;
120
r.cookie.expect ( " session cookie" )
121
}
122
78763257 Andy McCall 17 days ago ↶
123
124
async fn upload_identity ( app : & Shared, cookie : & str , csrf : & str , object : & [u8 ]) -> String {
125
let boundary = " XYZ" ;
126
let mut multipart = Vec :: new( ) ;
127
multipart.extend_from_slice ( format! ( " --{boundary} \r \n Content-Disposition: form-data; name=\" _csrf\" \r \n \r \n {csrf} \r \n " ) .as_bytes ( ) ) ;
128
multipart.extend_from_slice ( format! ( " --{boundary} \r \n Content-Disposition: form-data; name=\" identity\" ; filename=\" me.identity\" \r \n Content-Type: application/octet-stream\r \n \r \n " ) .as_bytes ( ) ) ;
129
multipart.extend_from_slice ( object) ;
130
multipart.extend_from_slice ( format! ( " \r \n --{boundary} --\r \n " ) .as_bytes ( ) ) ;
131
let req = Request:: builder( )
132
.method ( " POST" )
133
.uri ( " /settings/keys/upload" )
134
.header ( header:: COOKIE , format! ( " oxyhub={cookie} " ) )
135
.header ( header:: CONTENT_TYPE , format! ( " multipart/form-data; boundary={boundary} " ) )
136
.body ( Body:: from( multipart) )
137
.unwrap ( ) ;
138
let res = oxygenhub:: router( app.clone ( ) ) .oneshot ( req) .await.unwrap ( ) ;
139
assert_eq! ( res.status ( ) , StatusCode:: OK ) ;
140
String :: from_utf8_lossy( & res.into_body ( ) .collect ( ) .await.unwrap ( ) .to_bytes ( ) ) .into_owned ( )
141
}
142
19bb31ff Andy McCall 1 month ago ↶
143
fn csrf_of ( page : & str ) -> String {
144
let i = page.find ( " name=\" _csrf\" value=\" " ) .expect ( " csrf field" ) + " name=\" _csrf\" value=\" " .len ( ) ;
145
page[ i.. ] .split ( ' "' ) .next ( ) .unwrap ( ) .to_string ( )
146
}
147
148
# [ tokio ::test ( flavor = " multi_thread" ) ]
149
async fn accounts_roles_tokens_and_attribution ( ) {
150
let h = hub ( ) .await;
151
let app = & h.app;
152
153
154
let andy = register ( app, " andy" , " " ) .await;
155
let me = db:: accounts:: account_by_name( & app.db, " andy" ) .await.unwrap ( ) .unwrap ( ) ;
156
assert! ( me.is_admin) ;
157
c8684d44 Andy McCall 21 days ago
158
let r = post ( app, " /register" , None , " username=mallory&email=m%40example.com&password=correct-horse-battery&setup=test-setup&invite=" )
159
.await;
19bb31ff Andy McCall 1 month ago ↶
160
assert_eq! ( r.status, StatusCode:: OK ) ;
161
assert! ( r.body.contains ( " invitation" ) , " {}" , r.body) ;
162
let admin_page = get ( app, " /admin" , Some ( & andy) ) .await;
163
assert_eq! ( admin_page.status, StatusCode:: OK ) ;
164
let csrf = csrf_of ( & admin_page.body) ;
165
let r = post ( app, " /admin/invite" , Some ( & andy) , & format! ( " _csrf={csrf} " ) ) .await;
166
let code = r.body.split ( " register?invite=" ) .nth ( 1 ) .unwrap ( ) .split ( ' <' ) .next ( ) .unwrap ( ) .trim ( ) .to_string ( ) ;
167
let bob = register ( app, " bob" , & code) .await;
168
assert! ( ! db:: accounts:: account_by_name( & app.db, " bob" ) .await.unwrap ( ) .unwrap ( ) .is_admin) ;
169
170
assert_eq! ( post ( app, " /login" , None , " username=andy&password=nope" ) .await.status, StatusCode:: OK ) ;
171
assert_eq! ( post ( app, " /settings" , Some ( & andy) , " _csrf=bogus&display_name=x&email=y" ) .await.status, StatusCode:: BAD_REQUEST ) ;
172
assert_eq! ( get ( app, " /settings" , None ) .await.status, StatusCode:: SEE_OTHER , " anonymous settings redirects to sign in" ) ;
173
174
175
let new_page = get ( app, " /new" , Some ( & andy) ) .await;
176
let csrf = csrf_of ( & new_page.body) ;
177
let r = post ( app, " /new" , Some ( & andy) , & format! ( " _csrf={csrf} &owner=andy&name=secret&description=hush&visibility=private" ) ) .await;
178
assert_eq! ( r.status, StatusCode:: SEE_OTHER , " {}" , r.body) ;
179
assert_eq! ( get ( app, " /andy/secret" , Some ( & andy) ) .await.status, StatusCode:: OK ) ;
180
assert_eq! ( get ( app, " /andy/secret" , Some ( & bob) ) .await.status, StatusCode:: NOT_FOUND ) ;
181
assert_eq! ( get ( app, " /andy/secret" , None ) .await.status, StatusCode:: NOT_FOUND ) ;
182
assert! ( ! get ( app, " /" , Some ( & bob) ) .await.body.contains ( " secret" ) ) ;
183
assert! ( get ( app, " /" , Some ( & andy) ) .await.body.contains ( " secret" ) ) ;
184
185
186
let tokens_page = get ( app, " /settings/tokens" , Some ( & andy) ) .await;
187
let csrf = csrf_of ( & tokens_page.body) ;
188
let r = post ( app, " /settings/tokens" , Some ( & andy) , & format! ( " _csrf={csrf} &name=ro&scopes=repo%3Aread" ) ) .await;
189
let ro = r.body.split ( " oxyhub_" ) .nth ( 1 ) .map ( | s | format! ( " oxyhub_{} " , s.split ( ' <' ) .next ( ) .unwrap ( ) .trim ( ) ) ) .unwrap ( ) ;
190
let r = post ( app, " /settings/tokens" , Some ( & andy) , & format! ( " _csrf={csrf} &name=rw&scopes=repo%3Aread&scopes=repo%3Awrite" ) ) .await;
191
let rw = r.body.split ( " oxyhub_" ) .nth ( 1 ) .map ( | s | format! ( " oxyhub_{} " , s.split ( ' <' ) .next ( ) .unwrap ( ) .trim ( ) ) ) .unwrap ( ) ;
192
let work = tempfile:: tempdir( ) .unwrap ( ) ;
193
let mut client = Repo:: init( work.path ( ) ) .unwrap ( ) ;
194
client.create_identity ( " Andy McCall" , " [email protected] " , oxy_core:: repo:: IdentityScope:: User) .unwrap ( ) ;
195
client.config.set ( " remote.origin.url" , & format! ( " {} /andy/secret" , h.base) ) .unwrap ( ) ;
196
client.config.set ( " core.sign" , " change" ) .unwrap ( ) ;
197
client.save_config ( ) .unwrap ( ) ;
198
write ( work.path ( ) , " a.txt" , b " a\n " ) ;
199
client.snapshot ( " t" ) .unwrap ( ) ;
200
let c1 = client.commit ( " first" , & [ ] ) .unwrap ( ) ;
201
let err = client.push ( " origin" , false ) .err ( ) .unwrap ( ) .to_string ( ) ;
202
assert! ( err.contains ( " 404" ) , " anonymous cannot even see it: {err}" ) ;
203
client.config.set ( " remote.origin.token" , & ro) .unwrap ( ) ;
204
let err = client.push ( " origin" , false ) .err ( ) .unwrap ( ) .to_string ( ) ;
205
assert! ( err.contains ( " 403" ) , " read-only token cannot push: {err}" ) ;
206
client.config.set ( " remote.origin.token" , & rw) .unwrap ( ) ;
207
assert! ( client.push ( " origin" , false ) .unwrap ( ) .iter ( ) .all ( | r | r.ok ) ) ;
208
209
let bob_tokens = get ( app, " /settings/tokens" , Some ( & bob) ) .await;
210
let csrf_b = csrf_of ( & bob_tokens.body) ;
211
let r = post ( app, " /settings/tokens" , Some ( & bob) , & format! ( " _csrf={csrf_b} &name=b&scopes=repo%3Aread&scopes=repo%3Awrite" ) ) .await;
212
let bob_tok = r.body.split ( " oxyhub_" ) .nth ( 1 ) .map ( | s | format! ( " oxyhub_{} " , s.split ( ' <' ) .next ( ) .unwrap ( ) .trim ( ) ) ) .unwrap ( ) ;
213
std:: env:: set_var( " OXY_TOKEN" , & bob_tok) ;
214
let err = Repo:: clone( & format! ( " {} /andy/secret" , h.base) , & work.path ( ) .join ( " bobclone" ) ) .err ( ) .unwrap ( ) .to_string ( ) ;
215
std:: env:: remove_var( " OXY_TOKEN" ) ;
216
assert! ( err.contains ( " 404" ) , " {err}" ) ;
217
218
tokio:: time:: sleep( std:: time:: Duration:: from_millis( 150 ) ) .await;
219
let pushes = get ( app, " /andy/secret/pushes" , Some ( & andy) ) .await.body;
220
assert! ( pushes.contains ( " andy" ) , " {pushes}" ) ;
221
222
223
let settings = get ( app, " /andy/secret/settings" , Some ( & andy) ) .await;
224
assert_eq! ( settings.status, StatusCode:: OK ) ;
225
let csrf = csrf_of ( & settings.body) ;
226
let r = post ( app, " /andy/secret/settings/collaborators" , Some ( & andy) , & format! ( " _csrf={csrf} &username=bob&role=write" ) ) .await;
c7067c7b Andy McCall 17 days ago
227
let r = settled ( app, r, Some ( & andy) , " /andy/secret/settings/collaborators" ) .await;
228
assert! ( r.body.contains ( " bob now has write access." ) , " {}" , r.body) ;
19bb31ff Andy McCall 1 month ago ↶
229
assert_eq! ( get ( app, " /andy/secret" , Some ( & bob) ) .await.status, StatusCode:: OK ) ;
230
assert_eq! ( get ( app, " /andy/secret/settings" , Some ( & bob) ) .await.status, StatusCode:: NOT_FOUND , " write is not maintain" ) ;
231
std:: env:: set_var( " OXY_TOKEN" , & bob_tok) ;
232
let ok = Repo:: clone( & format! ( " {} /andy/secret" , h.base) , & work.path ( ) .join ( " bobclone2" ) ) .is_ok ( ) ;
233
std:: env:: remove_var( " OXY_TOKEN" ) ;
234
assert! ( ok) ;
235
2bbe88a8 Andy McCall 1 month ago ↶
236
237
238
let store = oxy_core:: credentials:: Credentials:: user( ) ;
239
let hub = oxy_core:: credentials:: hub_of( & h.base) .unwrap ( ) ;
240
store.save ( & hub, & rw, Some ( " andy" ) , None ) .unwrap ( ) ;
241
let signed_in = Repo:: clone( & format! ( " {} /andy/secret" , h.base) , & work.path ( ) .join ( " signedin" ) ) ;
242
store.remove ( & hub) .unwrap ( ) ;
243
let signed_in = signed_in.unwrap ( ) ;
244
assert! ( signed_in.config.remote_tokens.is_empty ( ) ) ;
245
assert_eq! ( signed_in.bookmark_heads ( ) .unwrap ( ) , vec! [ c1] ) ;
246
19bb31ff Andy McCall 1 month ago ↶
247
248
let ( key, identity) = {
249
let k = client.config.author_key.unwrap ( ) ;
250
( k, client.identity ( & k) .unwrap ( ) )
251
} ;
252
let keys_page = get ( app, " /settings/keys" , Some ( & andy) ) .await;
253
let csrf = csrf_of ( & keys_page.body) ;
78763257 Andy McCall 17 days ago ↶
254
let body = upload_identity ( app, & andy, & csrf, & identity.encode ( ) ) .await;
19bb31ff Andy McCall 1 month ago ↶
255
let challenge_hex = body.split ( " sign-challenge " ) .nth ( 1 ) .unwrap ( ) .split ( ' <' ) .next ( ) .unwrap ( ) .trim ( ) .to_string ( ) ;
256
let challenge_id = body.split ( " name=\" challenge\" value=\" " ) .nth ( 1 ) .unwrap ( ) .split ( ' "' ) .next ( ) .unwrap ( ) .to_string ( ) ;
257
let ( _ , sk) = client.secret_key ( ) .unwrap ( ) .unwrap ( ) ;
258
let sig = sk.sign_challenge ( & key, & hex:: decode( & challenge_hex) .unwrap ( ) ) .unwrap ( ) ;
259
let sig_hex = hex:: encode( oxy_core:: identity:: Signature:: encode_list( & [ sig] ) ) ;
260
let r = post ( app, " /settings/keys/verify" , Some ( & andy) , & format! ( " _csrf={csrf} &challenge={challenge_id} &signature={sig_hex} " ) ) .await;
261
assert! ( r.body.contains ( " Key linked" ) , " {}" , r.body) ;
262
let hist = get ( app, " /andy/secret/changes/main" , Some ( & andy) ) .await.body;
263
assert! ( hist.contains ( " href=\" /andy\" >Andy McCall</a>" ) , " author linked to the account: {hist}" ) ;
264
let change = get ( app, & format! ( " /andy/secret/change/{} " , c1.to_hex ( ) ) , Some ( & andy) ) .await.body;
265
assert! ( change.contains ( " @andy" ) , " {change}" ) ;
266
267
let r = post ( app, " /settings/keys/verify" , Some ( & andy) , & format! ( " _csrf={csrf} &challenge=999&signature={sig_hex} " ) ) .await;
268
assert! ( r.body.contains ( " expired" ) , " {}" , r.body) ;
78763257 Andy McCall 17 days ago ↶
269
270
271
let body = upload_identity ( app, & andy, & csrf, & app.hub_key.identity.encode ( ) ) .await;
272
assert! ( body.contains ( " this hub's own key" ) | | body.contains ( " this hub's own key" ) , " {body}" ) ;
273
assert! ( ! body.contains ( " sign-challenge " ) , " no challenge for the hub's key: {body}" ) ;
274
let other = oxy_core:: identity:: SecretKey:: generate( ) .identity ( " Other" , " [email protected] " , 1 ) ;
275
let body = upload_identity ( app, & andy, & csrf, & other.encode ( ) ) .await;
276
let challenge_hex = body.split ( " sign-challenge " ) .nth ( 1 ) .unwrap ( ) .split ( ' <' ) .next ( ) .unwrap ( ) .trim ( ) .to_string ( ) ;
277
let challenge_id = body.split ( " name=\" challenge\" value=\" " ) .nth ( 1 ) .unwrap ( ) .split ( ' "' ) .next ( ) .unwrap ( ) .to_string ( ) ;
278
let sig = sk.sign_challenge ( & key, & hex:: decode( & challenge_hex) .unwrap ( ) ) .unwrap ( ) ;
279
let sig_hex = hex:: encode( oxy_core:: identity:: Signature:: encode_list( & [ sig] ) ) ;
280
let r = post ( app, " /settings/keys/verify" , Some ( & andy) , & format! ( " _csrf={csrf} &challenge={challenge_id} &signature={sig_hex} " ) ) .await;
281
assert! (
282
r.body.contains ( & format! ( " That signature is by key {} " , key.short ( 12 ) ) ) & & r.body.contains ( & other.hash ( ) .short ( 12 ) ) ,
283
" {}" ,
284
r.body
285
) ;
19bb31ff Andy McCall 1 month ago ↶
286
287
288
let org_page = get ( app, " /orgs/new" , Some ( & andy) ) .await;
289
let csrf = csrf_of ( & org_page.body) ;
290
let r = post ( app, " /orgs/new" , Some ( & andy) , & format! ( " _csrf={csrf} &name=acme&display_name=Acme" ) ) .await;
291
assert_eq! ( r.status, StatusCode:: SEE_OTHER , " {}" , r.body) ;
292
let new_page = get ( app, " /new" , Some ( & andy) ) .await;
293
let csrf = csrf_of ( & new_page.body) ;
294
assert_eq! (
295
post ( app, " /new" , Some ( & andy) , & format! ( " _csrf={csrf} &owner=acme&name=plans&visibility=private" ) ) .await.status,
296
StatusCode:: SEE_OTHER
297
) ;
298
assert_eq! ( get ( app, " /acme/plans" , Some ( & bob) ) .await.status, StatusCode:: NOT_FOUND ) ;
299
let org_settings = get ( app, " /orgs/acme/settings" , Some ( & andy) ) .await;
300
let csrf = csrf_of ( & org_settings.body) ;
301
assert_eq! (
302
post ( app, " /orgs/acme/settings/members" , Some ( & andy) , & format! ( " _csrf={csrf} &username=bob&role=member" ) ) .await.status,
303
StatusCode:: OK
304
) ;
305
assert_eq! ( get ( app, " /acme/plans" , Some ( & bob) ) .await.status, StatusCode:: OK , " members read by default" ) ;
306
assert_eq! ( get ( app, " /orgs/acme/settings" , Some ( & bob) ) .await.status, StatusCode:: NOT_FOUND , " members do not administer" ) ;
307
308
let r = post (
309
app,
310
" /new" ,
311
Some ( & bob) ,
312
& format! ( " _csrf={} &owner=acme&name=bobs&visibility=public" , csrf_of ( & get ( app, " /new" , Some ( & bob) ) .await.body) ) ,
313
)
314
.await;
315
assert_eq! ( r.status, StatusCode:: SEE_OTHER , " {}" , r.body) ;
316
317
318
let sec = get ( app, " /settings/security" , Some ( & andy) ) .await;
319
let csrf = csrf_of ( & sec.body) ;
320
let r = post ( app, " /settings/security/sessions" , Some ( & andy) , & format! ( " _csrf={csrf} " ) ) .await;
321
assert_eq! ( r.status, StatusCode:: SEE_OTHER ) ;
322
assert_eq! ( get ( app, " /settings" , Some ( & andy) ) .await.status, StatusCode:: SEE_OTHER , " old session is gone" ) ;
323
let fresh = r.cookie.unwrap ( ) ;
324
assert_eq! ( get ( app, " /settings" , Some ( & fresh) ) .await.status, StatusCode:: OK ) ;
325
326
327
let sec = get ( app, " /settings/security" , Some ( & fresh) ) .await;
328
let csrf = csrf_of ( & sec.body) ;
329
let r = post ( app, " /settings/security/totp/begin" , Some ( & fresh) , & format! ( " _csrf={csrf} " ) ) .await;
330
let secret = r.body.split ( " name=\" secret\" value=\" " ) .nth ( 1 ) .unwrap ( ) .split ( ' "' ) .next ( ) .unwrap ( ) .to_string ( ) ;
331
let now = ( db:: now_ms( ) / 1000 ) as u64 ;
332
let code = oxygenhub:: auth:: totp:: current( & secret, now) .unwrap ( ) ;
333
let r = post ( app, " /settings/security/totp/enable" , Some ( & fresh) , & format! ( " _csrf={csrf} &secret={secret} &code={code} " ) ) .await;
334
assert! ( r.body.contains ( " Recovery codes" ) , " {}" , r.body) ;
c8684d44 Andy McCall 21 days ago
335
let r = post ( app, " /login" , None , " username=andy&password=correct-horse-battery&setup=test-setup" ) .await;
19bb31ff Andy McCall 1 month ago ↶
336
assert! ( r.body.contains ( " authenticator" ) , " second step asked: {}" , r.body) ;
1b3a0098 Andy McCall 1 month ago ↶
337
338
339
let form = & r.body[ r.body.find ( " <form class=\" card\" method=\" post\" action=\" /login\" >" ) .unwrap ( ) .. ] ;
340
let form = & form[ .. form.find ( " </form>" ) .unwrap ( ) ] ;
341
let names: Vec< & str > = form.split ( " name=\" " ) .skip ( 1 ) .map ( | t | t.split ( ' "' ) .next ( ) .unwrap ( ) ) .collect ( ) ;
342
let mut unique = names.clone ( ) ;
343
unique.sort ( ) ;
344
unique.dedup ( ) ;
345
assert_eq! ( unique.len ( ) , names.len ( ) , " a field named twice: {names:?}" ) ;
bff9106e Andy McCall 23 days ago ↶
346
347
348
assert! ( ! names.contains ( & " password" ) , " {names:?}" ) ;
349
let pending = form.split ( " name=\" pending\" value=\" " ) .nth ( 1 ) .unwrap ( ) .split ( ' "' ) .next ( ) .unwrap ( ) .to_string ( ) ;
19bb31ff Andy McCall 1 month ago ↶
350
let code = oxygenhub:: auth:: totp:: current( & secret, ( db:: now_ms( ) / 1000 ) as u64 ) .unwrap ( ) ;
bff9106e Andy McCall 23 days ago ↶
351
let fill = | pending : & str | -> String {
352
names
353
.iter ( )
354
.map ( | n | match * n {
355
" username" => " username=andy" .to_string ( ) ,
356
" pending" => format! ( " pending={pending} " ) ,
357
" code" => format! ( " code={code} " ) ,
358
other => format! ( " {other} =" ) ,
359
} )
360
.collect:: < Vec< _ > > ( )
361
.join ( " &" )
362
} ;
363
364
let r = post ( app, " /login" , None , & fill ( " 1.forged" ) ) .await;
365
assert! ( r.body.contains ( " sign in again" ) & & r.cookie.is_none ( ) , " {}" , r.body) ;
366
let r = post ( app, " /login" , None , & fill ( & pending) ) .await;
19bb31ff Andy McCall 1 month ago ↶
367
assert_eq! ( r.status, StatusCode:: SEE_OTHER , " {}" , r.body) ;
368
assert! ( r.cookie.is_some ( ) ) ;
369
assert! ( r.location.as_deref ( ) = = Some ( " /" ) ) ;
370
}
a160b98f Andy McCall 1 month ago ↶
371
372
373
fn picture_form ( csrf : & str , action : & str , file : & [u8 ]) -> ( String, Vec< u8 > ) {
374
let boundary = " picture-boundary-1234" ;
375
let mut body = Vec :: new( ) ;
376
body.extend_from_slice ( format! ( " --{boundary} \r \n Content-Disposition: form-data; name=\" _csrf\" \r \n \r \n {csrf} \r \n " ) .as_bytes ( ) ) ;
377
body.extend_from_slice ( format! ( " --{boundary} \r \n Content-Disposition: form-data; name=\" action\" \r \n \r \n {action} \r \n " ) .as_bytes ( ) ) ;
378
body.extend_from_slice (
379
format! ( " --{boundary} \r \n Content-Disposition: form-data; name=\" picture\" ; filename=\" me.png\" \r \n Content-Type: image/png\r \n \r \n " )
380
.as_bytes ( ) ,
381
) ;
382
body.extend_from_slice ( file) ;
383
body.extend_from_slice ( format! ( " \r \n --{boundary} --\r \n " ) .as_bytes ( ) ) ;
384
( format! ( " multipart/form-data; boundary={boundary} " ) , body)
385
}
386
387
async fn upload ( app : & Shared, path : & str , cookie : & str , csrf : & str , action : & str , file : & [u8 ]) -> Res {
388
let ( ct, body) = picture_form ( csrf, action, file) ;
389
let req = Request:: post( path)
390
.header ( header:: COOKIE , format! ( " oxyhub={cookie} " ) )
391
.header ( header:: CONTENT_TYPE , ct)
392
.body ( Body:: from( body) )
393
.unwrap ( ) ;
394
let res = oxygenhub:: router( app.clone ( ) ) .oneshot ( req) .await.unwrap ( ) ;
395
let status = res.status ( ) ;
396
let bytes = res.into_body ( ) .collect ( ) .await.unwrap ( ) .to_bytes ( ) ;
83940d53 Andy McCall 1 month ago ↶
397
Res { status, body: String :: from_utf8_lossy( & bytes) .into_owned ( ) , cookie: None , location: None , raw_cookies: vec! [ ] }
a160b98f Andy McCall 1 month ago ↶
398
}
399
400
401
async fn picture ( app : & Shared, name : & str ) -> ( StatusCode, String, Vec< u8 > ) {
402
let res = oxygenhub:: router( app.clone ( ) ) .oneshot ( Request:: get( format! ( " /avatar/{name} " ) ) .body ( Body:: empty( ) ) .unwrap ( ) ) .await.unwrap ( ) ;
403
let ct = res.headers ( ) .get ( header:: CONTENT_TYPE ) .and_then ( | v | v.to_str ( ) .ok ( ) ) .unwrap_or ( " " ) .to_string ( ) ;
404
let status = res.status ( ) ;
405
( status, ct, res.into_body ( ) .collect ( ) .await.unwrap ( ) .to_bytes ( ) .to_vec ( ) )
406
}
407
408
fn png ( w : u32 , h : u32 , alpha : bool ) -> Vec< u8 > {
409
let img = if alpha {
410
image:: DynamicImage:: ImageRgba8( image:: RgbaImage:: from_fn( w, h, | x , _| {
411
image:: Rgba( [ 0 , 114 , 255 , if x % 2 = = 0 { 0 } else { 255 } ] )
412
} ) )
413
} else {
414
image:: DynamicImage:: ImageRgb8( image:: RgbImage:: from_fn( w, h, | x , y | image:: Rgb( [ x as u8 , y as u8 , 128 ] ) ) )
415
} ;
416
let mut out = Vec :: new( ) ;
417
img.write_to ( & mut std:: io:: Cursor:: new( & mut out) , image:: ImageFormat:: Png) .unwrap ( ) ;
418
out
c7067c7b Andy McCall 17 days ago
419
}
420
421
422
423
424
# [ tokio ::test ( flavor = " multi_thread" ) ]
425
async fn repository_settings_are_a_page_each_by_role ( ) {
426
let h = hub ( ) .await;
427
let app = & h.app;
428
let andy = register ( app, " andy" , " " ) .await;
429
let mut invited = vec! [ ] ;
430
for name in [ " bob" , " carol" ] {
431
let csrf = csrf_of ( & get ( app, " /admin" , Some ( & andy) ) .await.body) ;
432
let r = post ( app, " /admin/invite" , Some ( & andy) , & format! ( " _csrf={csrf} " ) ) .await;
433
let code = r.body.split ( " register?invite=" ) .nth ( 1 ) .unwrap ( ) .split ( ' <' ) .next ( ) .unwrap ( ) .trim ( ) .to_string ( ) ;
434
invited.push ( register ( app, name, & code) .await) ;
435
}
436
let ( bob, carol) = ( invited[ 0 ] .clone ( ) , invited[ 1 ] .clone ( ) ) ;
437
let csrf = csrf_of ( & get ( app, " /new" , Some ( & andy) ) .await.body) ;
438
let r = post ( app, " /new" , Some ( & andy) , & format! ( " _csrf={csrf} &owner=andy&name=demo&visibility=public" ) ) .await;
439
assert_eq! ( r.status, StatusCode:: SEE_OTHER , " {}" , r.body) ;
440
let csrf = csrf_of ( & get ( app, " /andy/demo/settings" , Some ( & andy) ) .await.body) ;
441
for ( who, role) in [ ( " bob" , " maintain" ) , ( " carol" , " write" ) ] {
442
let r = post ( app, " /andy/demo/settings/collaborators" , Some ( & andy) , & format! ( " _csrf={csrf} &username={who} &role={role} " ) ) .await;
443
let page = settled ( app, r, Some ( & andy) , " /andy/demo/settings/collaborators" ) .await;
444
assert! ( page.body.contains ( & format! ( " {who} now has {role} access." ) ) , " {}" , page.body) ;
445
}
446
447
let marked = | slug : & str | format! ( " href=\" /andy/demo/settings/{slug} \" data-slug=\" {slug} \" class=\" on\" aria-current=\" page\" " ) ;
448
let maintainers =
449
[ " general" , " landing" , " checks" , " push-protection" , " flow" , " runs" , " gates" , " coverage" , " git-mirror" , " diffusion" , " backup" ] ;
450
let admins = [ " collaborators" , " runners" , " variables" , " secrets" , " webhooks" , " assistants" , " advanced" ] ;
451
452
let general = get ( app, " /andy/demo/settings" , Some ( & andy) ) .await;
453
assert_eq! ( general.status, StatusCode:: OK ) ;
454
assert! ( general.body.contains ( & marked ( " general" ) ) & & general.body.contains ( " id=\" general\" " ) , " {}" , general.body) ;
455
for group in [ " General" , " Code" , " Flow" , " Integrations" , " Data" , " Danger zone" ] {
456
assert! ( general.body.contains ( & format! ( " <h2>{group} </h2>" ) ) , " group {group}" ) ;
457
}
458
assert! ( general.body.contains ( " data-settings-anchors" ) , " kept #anchor links are sent on from General" ) ;
459
460
for slug in maintainers.iter ( ) .chain ( admins.iter ( ) ) {
461
let page = get ( app, & format! ( " /andy/demo/settings/{slug} " ) , Some ( & andy) ) .await;
462
assert_eq! ( page.status, StatusCode:: OK , " {slug}" ) ;
463
assert! ( page.body.contains ( & marked ( slug) ) , " {slug} is marked: {}" , page.body) ;
464
for other in maintainers.iter ( ) .chain ( admins.iter ( ) ) .filter ( | o | * o ! = slug) {
465
assert! ( ! page.body.contains ( & marked ( other) ) , " {slug} marks {other}" ) ;
466
}
467
}
468
let runs = get ( app, " /andy/demo/settings/runs" , Some ( & andy) ) .await.body;
469
assert! ( runs.contains ( " id=\" flow-priority\" " ) & & runs.contains ( " id=\" flow-supersede\" " ) & & ! runs.contains ( " id=\" general\" " ) ) ;
470
471
assert_eq! ( get ( app, " /andy/demo/settings/storage" , Some ( & andy) ) .await.status, StatusCode:: NOT_FOUND ) ;
472
assert! ( ! general.body.contains ( " /andy/demo/settings/storage\" " ) ) ;
473
assert_eq! ( get ( app, " /andy/demo/settings/nope" , Some ( & andy) ) .await.status, StatusCode:: NOT_FOUND ) ;
474
475
476
477
let page = get ( app, " /andy/demo/settings" , Some ( & bob) ) .await;
478
assert_eq! ( page.status, StatusCode:: OK ) ;
479
for slug in maintainers {
480
assert_eq! ( get ( app, & format! ( " /andy/demo/settings/{slug} " ) , Some ( & bob) ) .await.status, StatusCode:: OK , " {slug}" ) ;
481
assert! ( page.body.contains ( & format! ( " data-slug=\" {slug} \" " ) ) , " {slug} listed" ) ;
482
}
483
for slug in admins {
484
assert_eq! ( get ( app, & format! ( " /andy/demo/settings/{slug} " ) , Some ( & bob) ) .await.status, StatusCode:: NOT_FOUND , " {slug}" ) ;
485
assert! ( ! page.body.contains ( & format! ( " data-slug=\" {slug} \" " ) ) , " {slug} not listed" ) ;
486
}
487
assert! ( ! page.body.contains ( " <h2>Danger zone</h2>" ) , " an empty group is left out" ) ;
488
let bob_csrf = csrf_of ( & page.body) ;
489
let r = post ( app, " /andy/demo/settings/flow-priority" , Some ( & bob) , & format! ( " _csrf={bob_csrf} &priority=normal" ) ) .await;
490
let back = settled ( app, r, Some ( & bob) , " /andy/demo/settings/runs" ) .await;
491
assert! ( back.body.contains ( " Its jobs are normal priority." ) & & back.body.contains ( & marked ( " runs" ) ) , " {}" , back.body) ;
492
493
assert_eq! ( get ( app, " /andy/demo/settings" , Some ( & carol) ) .await.status, StatusCode:: NOT_FOUND ) ;
494
for slug in [ " general" , " push-protection" , " advanced" ] {
495
assert_eq! ( get ( app, & format! ( " /andy/demo/settings/{slug} " ) , Some ( & carol) ) .await.status, StatusCode:: NOT_FOUND , " {slug}" ) ;
496
}
497
498
499
for ( path, form, page, says) in [
500
( " " , " description=Demo&default_bookmark=main&visibility=public&topics=" , " general" , " Saved." ) ,
501
( " /requirements" , " required_approvals=1" , " landing" , " Landing requirements saved." ) ,
502
( " /checks" , " required_checks=build" , " checks" , " Required checks saved." ) ,
503
( " /push-protection" , " " , " push-protection" , " Push protection is off" ) ,
504
( " /push-protection" , " protect=on" , " push-protection" , " Push protection is on" ) ,
505
( " /secret-bypass" , " fingerprint=0123456789abcdef&reason=a+test+fixture" , " push-protection" , " is allowed here" ) ,
506
( " /flow" , " flow=sometimes" , " flow" , " Pick on, own runners, off or the site default." ) ,
507
( " /flow-priority" , " priority=low" , " runs" , " Its jobs are low priority." ) ,
508
( " /flow-supersede" , " running=on" , " runs" , " cancels the older runs it supersedes, queued or running" ) ,
509
( " /agent-gates" , " agents=on" , " gates" , " may now approve or reject" ) ,
510
( " /variables" , " action=set&name=RUST_LOG&value=debug" , " variables" , " RUST_LOG set." ) ,
511
( " /coverage" , " min=80&max_drop=" , " coverage" , " Coverage rules saved" ) ,
512
( " /hooks" , " action=delete&id=999" , " webhooks" , " Webhook deleted." ) ,
513
( " /mirror" , " " , " git-mirror" , " The Git mirror is off." ) ,
514
( " /diffusion" , " diffusion=off&land=propose" , " diffusion" , " Diffusion is off" ) ,
515
( " /backup" , " backup=off" , " backup" , " left out of its owner" ) ,
516
( " /archive" , " action=neither" , " advanced" , " Unknown action." ) ,
517
] {
518
let r = post ( app, & format! ( " /andy/demo/settings{path} " ) , Some ( & andy) , & format! ( " _csrf={csrf} &{form} " ) ) .await;
519
let back = settled ( app, r, Some ( & andy) , & format! ( " /andy/demo/settings/{page} " ) ) .await;
520
assert_eq! ( back.status, StatusCode:: OK , " {path}" ) ;
521
assert! ( back.body.contains ( says) & & back.body.contains ( & marked ( page) ) , " {path}: {}" , back.body) ;
522
}
523
524
525
let js = get ( app, " /static/hub.js" , None ) .await.body;
526
assert! ( js.contains ( " [data-settings-anchors]" ) & & js.contains ( " \" flow-priority\" : \" runs\" " ) , " {js}" ) ;
a160b98f Andy McCall 1 month ago ↶
527
}
528
529
# [ tokio ::test ( flavor = " multi_thread" ) ]
530
async fn profile_pictures_and_logos ( ) {
531
let h = hub ( ) .await;
532
let app = & h.app;
533
let andy = register ( app, " andy" , " " ) .await;
534
assert_eq! ( picture ( app, " andy" ) .await.1 , " image/svg+xml" , " the identicon first" ) ;
535
let csrf = csrf_of ( & get ( app, " /settings" , Some ( & andy) ) .await.body) ;
536
assert! ( get ( app, " /settings" , Some ( & andy) ) .await.body.contains ( " id=\" picture\" " ) ) ;
537
538
539
let r = upload ( app, " /settings/avatar" , & andy, & csrf, " upload" , & png ( 640 , 480 , false ) ) .await;
540
assert! ( r.body.contains ( " Picture saved" ) , " {}" , r.body) ;
541
let ( st, ct, bytes) = picture ( app, " andy" ) .await;
542
assert_eq! ( ( st, ct.as_str ( ) ) , ( StatusCode:: OK , " image/jpeg" ) ) ;
543
let img = image:: load_from_memory( & bytes) .unwrap ( ) ;
544
assert_eq! ( ( img.width ( ) , img.height ( ) ) , ( 400 , 400 ) ) ;
545
let stored = db:: accounts:: account_by_name( & app.db, " andy" ) .await.unwrap ( ) .unwrap ( ) .avatar;
546
assert! ( stored.starts_with ( " jpeg:" ) , " {stored}" ) ;
547
548
549
let r = upload (
550
app,
551
" /settings/avatar" ,
552
& andy,
553
& csrf,
554
" upload" ,
555
b " <svg xmlns=\" http://www.w3.org/2000/svg\" ><script>alert(1)</script></svg>" ,
556
)
557
.await;
558
assert! ( r.body.contains ( " not a PNG, JPEG or WebP" ) , " {}" , r.body) ;
559
let r = upload ( app, " /settings/avatar" , & andy, " wrong" , " upload" , & png ( 10 , 10 , false ) ) .await;
560
assert_ne! ( r.status, StatusCode:: OK ) ;
561
assert_eq! ( picture ( app, " andy" ) .await.1 , " image/jpeg" ) ;
562
563
let r = upload ( app, " /settings/avatar" , & andy, & csrf, " remove" , b " " ) .await;
564
assert! ( r.body.contains ( " Picture removed" ) ) ;
565
assert_eq! ( picture ( app, " andy" ) .await.1 , " image/svg+xml" ) ;
566
567
568
let me = db:: accounts:: account_by_name( & app.db, " andy" ) .await.unwrap ( ) .unwrap ( ) ;
569
db:: accounts:: create_org( & app.db, " acme" , " Acme" , me.id) .await.unwrap ( ) ;
570
let org_csrf = csrf_of ( & get ( app, " /orgs/acme/settings" , Some ( & andy) ) .await.body) ;
571
let r = upload ( app, " /orgs/acme/settings/avatar" , & andy, & org_csrf, " upload" , & png ( 120 , 120 , true ) ) .await;
572
assert! ( r.body.contains ( " Picture saved" ) , " {}" , r.body) ;
573
let ( _ , ct, bytes) = picture ( app, " acme" ) .await;
574
assert_eq! ( ct, " image/png" ) ;
575
assert! ( image:: load_from_memory( & bytes) .unwrap ( ) .color ( ) .has_alpha ( ) ) ;
576
let invite = {
577
let admin = get ( app, " /admin" , Some ( & andy) ) .await;
578
let r = post ( app, " /admin/invite" , Some ( & andy) , & format! ( " _csrf={} " , csrf_of ( & admin.body) ) ) .await;
579
let i = r.body.find ( " invite=" ) .map ( | i | i + 7 ) .expect ( " an invitation" ) ;
580
r.body[ i.. ] .chars ( ) .take_while ( | c | c.is_ascii_alphanumeric ( ) ) .collect:: < String> ( )
581
} ;
582
let bob = register ( app, " bob" , & invite) .await;
583
let bob_csrf = csrf_of ( & get ( app, " /settings" , Some ( & bob) ) .await.body) ;
584
let r = upload ( app, " /orgs/acme/settings/avatar" , & bob, & bob_csrf, " remove" , b " " ) .await;
585
assert_eq! ( r.status, StatusCode:: NOT_FOUND , " not an owner" ) ;
586
assert_eq! ( picture ( app, " acme" ) .await.1 , " image/png" ) ;
587
}
8fb35df7 Andy McCall 1 month ago ↶
588
589
# [ tokio ::test ( flavor = " multi_thread" ) ]
590
async fn organisation_webhooks_and_storage ( ) {
591
let h = hub ( ) .await;
592
let app = & h.app;
593
let andy = register ( app, " andy" , " " ) .await;
594
let me = db:: accounts:: account_by_name( & app.db, " andy" ) .await.unwrap ( ) .unwrap ( ) ;
595
let org = db:: accounts:: create_org( & app.db, " acme" , " Acme" , me.id) .await.unwrap ( ) ;
596
ff656953 Andy McCall 1 month ago ↶
597
598
599
600
let alone = db:: repos:: create( & app.db, " acme" , " alone" , " " , hub_api:: Visibility:: Public) .await.unwrap ( ) ;
601
let solo = db:: repos:: create( & app.db, " andy" , " solo" , " " , hub_api:: Visibility:: Public) .await.unwrap ( ) ;
602
assert_eq! ( db:: proposals:: requirements( & app.db, alone.id) .await.unwrap ( ) .required_approvals, 0 ) ;
603
assert_eq! ( db:: proposals:: requirements( & app.db, solo.id) .await.unwrap ( ) .required_approvals, 0 ) ;
604
let bobby = db:: accounts:: create_account( & app.db, " bobby" , " [email protected] " , " x" , " salt" , false ) .await.unwrap ( ) ;
605
db:: accounts:: set_org_member( & app.db, org.id, bobby.id, " member" ) .await.unwrap ( ) ;
462f88d1 Andy McCall 1 month ago ↶
606
let tools = db:: repos:: create( & app.db, " acme" , " tools" , " " , hub_api:: Visibility:: Public) .await.unwrap ( ) ;
607
assert_eq! ( db:: proposals:: requirements( & app.db, tools.id) .await.unwrap ( ) .required_approvals, 1 ) ;
608
8fb35df7 Andy McCall 1 month ago ↶
609
610
let page = get ( app, " /orgs/acme/settings" , Some ( & andy) ) .await;
611
assert! ( page.body.contains ( " id=\" webhooks\" " ) & & page.body.contains ( " href=\" #webhooks\" " ) ) ;
612
let csrf = csrf_of ( & page.body) ;
613
let r = post ( app, " /orgs/acme/settings/hooks" , Some ( & andy) , & format! ( " _csrf={csrf} &url=ftp%3A%2F%2Fx&events=*" ) ) .await;
614
assert! ( r.body.contains ( " starts with http" ) , " {}" , r.body) ;
615
let r = post (
616
app,
617
" /orgs/acme/settings/hooks" ,
618
Some ( & andy) ,
619
& format! ( " _csrf={csrf} &url=https%3A%2F%2Fhooks.invalid%2Facme&secret=s&events=push" ) ,
620
)
621
.await;
622
assert! ( r.body.contains ( " Webhook added" ) ) ;
623
let hooks = db:: hooks:: hooks_for_org( & app.db, org.id) .await.unwrap ( ) ;
624
assert_eq! ( hooks.len ( ) , 1 ) ;
625
let id = hooks[ 0 ] .id;
626
assert! ( post ( app, " /orgs/acme/settings/hooks" , Some ( & andy) , & format! ( " _csrf={csrf} &id={id} &action=ping" ) )
627
.await
628
.body
629
.contains ( " Ping queued" ) ) ;
630
let deliveries = get ( app, & format! ( " /orgs/acme/settings/hooks/{id} /deliveries" ) , Some ( & andy) ) .await;
631
assert_eq! ( deliveries.status, StatusCode:: OK ) ;
632
assert! ( deliveries.body.contains ( " >ping<" ) & & deliveries.body.contains ( " /orgs/acme/settings#webhooks" ) ) ;
633
634
let repo = oxygenhub:: repos:: RepoName:: parse( " andy/demo" ) .unwrap ( ) ;
635
app.repos.create ( & repo, None ) .unwrap ( ) ;
636
let row = db:: repos:: create( & app.db, " andy" , " demo" , " " , hub_api:: Visibility:: Public) .await.unwrap ( ) ;
637
let repo_hook = db:: hooks:: create_hook( & app.db, Some ( row.id) , None , " https://hooks.invalid/repo" , " " , " *" ) .await.unwrap ( ) .id;
638
post ( app, " /orgs/acme/settings/hooks" , Some ( & andy) , & format! ( " _csrf={csrf} &id={repo_hook} &action=delete" ) ) .await;
639
assert! ( db:: hooks:: hook( & app.db, repo_hook) .await.unwrap ( ) .is_some ( ) , " not the organisation's" ) ;
640
assert_eq! ( get ( app, & format! ( " /orgs/acme/settings/hooks/{repo_hook} /deliveries" ) , Some ( & andy) ) .await.status, StatusCode:: NOT_FOUND ) ;
641
c7067c7b Andy McCall 17 days ago
642
let rs = get ( app, " /andy/demo/settings/webhooks" , Some ( & andy) ) .await;
8fb35df7 Andy McCall 1 month ago ↶
643
assert! ( rs.body.contains ( " https://hooks.invalid/repo" ) & & rs.body.contains ( " action=\" /andy/demo/settings/hooks\" " ) ) ;
644
645
646
let work = tempfile:: tempdir( ) .unwrap ( ) ;
647
let mut client = Repo:: init( work.path ( ) ) .unwrap ( ) ;
648
client.config.set ( " remote.origin.url" , & format! ( " {} /andy/demo" , h.base) ) .unwrap ( ) ;
649
let ( token, hash) = oxygenhub:: auth:: new_token( ) ;
650
db:: accounts:: create_token( & app.db, me.id, " push" , & hash, " repo:write" , " " , None ) .await.unwrap ( ) ;
651
client.config.set ( " remote.origin.token" , & token) .unwrap ( ) ;
652
client.save_config ( ) .unwrap ( ) ;
653
write ( work.path ( ) , " a.txt" , b " a\n " ) ;
654
client.snapshot ( " t" ) .unwrap ( ) ;
655
client.commit ( " one" , & [ ] ) .unwrap ( ) ;
656
assert! ( client.push ( " origin" , false ) .unwrap ( ) .iter ( ) .all ( | r | r.ok ) ) ;
657
let storage = get ( app, " /admin/storage" , Some ( & andy) ) .await;
658
assert_eq! ( storage.status, StatusCode:: OK ) ;
659
assert! ( storage.body.contains ( " href=\" /andy/demo\" " ) ) ;
660
let loose_before = std:: fs:: read_dir( app.repos.dir ( & repo) .join ( " .oxy/objects/loose" ) ) .map ( | d | d.count ( ) ) .unwrap_or ( 0 ) ;
661
assert! ( loose_before > 0 , " the push left loose objects" ) ;
662
let r = post ( app, " /admin/storage" , Some ( & andy) , & format! ( " _csrf={} &repo=andy%2Fdemo" , csrf_of ( & storage.body) ) ) .await;
663
assert! ( r.body.contains ( " Maintained 1 repository" ) & & r.body.contains ( " loose objects packed" ) , " {}" , r.body) ;
7c06f5b2 Andy McCall 19 days ago ↶
664
665
666
let loose_after = Repo:: open( & app.repos.dir ( & repo) ) .unwrap ( ) .store ( ) .loose_count ( ) .unwrap ( ) ;
8fb35df7 Andy McCall 1 month ago ↶
667
assert_eq! ( loose_after, 0 , " packed" ) ;
668
let audit = db:: accounts:: audit_rows( & app.db, 20 ) .await.unwrap ( ) ;
669
assert! ( audit.iter ( ) .any ( | a | a.action = = " admin.gc" & & a.target = = " andy/demo" ) ) ;
670
let r = post ( app, " /admin/storage" , Some ( & andy) , & format! ( " _csrf={} &repo=nobody%2Fnone" , csrf_of ( & storage.body) ) ) .await;
671
assert! ( r.body.contains ( " No repository nobody/none" ) ) ;
672
}
673
6a178055 Andy McCall 1 month ago ↶
674
675
676
677
# [ tokio ::test ( flavor = " multi_thread" ) ]
678
async fn admins_disable_enable_and_delete_accounts ( ) {
679
let h = hub ( ) .await;
680
let app = & h.app;
681
let andy = register ( app, " andy" , " " ) .await;
682
let invite = | app : Shared, andy : String| async move {
683
let csrf = csrf_of ( & get ( & app, " /admin" , Some ( & andy) ) .await.body) ;
684
let r = post ( & app, " /admin/invite" , Some ( & andy) , & format! ( " _csrf={csrf} " ) ) .await;
685
r.body.split ( " register?invite=" ) .nth ( 1 ) .unwrap ( ) .split ( ' <' ) .next ( ) .unwrap ( ) .trim ( ) .to_string ( )
686
} ;
687
let bob = register ( app, " bob" , & invite ( app.clone ( ) , andy.clone ( ) ) .await) .await;
688
let act = | who : & 'static str , action : & 'static str , confirm : & 'static str | {
689
let ( app, andy) = ( app.clone ( ) , andy.clone ( ) ) ;
690
async move {
691
let csrf = csrf_of ( & get ( & app, " /admin" , Some ( & andy) ) .await.body) ;
692
post ( & app, " /admin/account" , Some ( & andy) , & format! ( " _csrf={csrf} &username={who} &action={action} &confirm={confirm} " ) ) .await.body
693
}
694
} ;
695
let login = | user : & 'static str | {
696
let app = app.clone ( ) ;
c8684d44 Andy McCall 21 days ago
697
async move { post ( & app, " /login" , None , & format! ( " username={user} &password=correct-horse-battery&setup=test-setup" ) ) .await }
6a178055 Andy McCall 1 month ago ↶
698
} ;
699
700
701
act ( " bob" , " disable" , " " ) .await;
702
assert! ( db:: accounts:: account_by_name( & app.db, " bob" ) .await.unwrap ( ) .unwrap ( ) .disabled) ;
703
let r = login ( " bob" ) .await;
704
assert! ( r.body.contains ( " Your account has been disabled" ) , " {}" , r.body) ;
705
assert! ( r.cookie.is_none ( ) ) ;
706
assert_eq! ( get ( app, " /settings" , Some ( & bob) ) .await.status, StatusCode:: SEE_OTHER , " the session is refused" ) ;
707
assert! ( act ( " andy" , " disable" , " " ) .await.contains ( " Not on yourself" ) ) ;
708
709
act ( " bob" , " enable" , " " ) .await;
710
assert_eq! ( login ( " bob" ) .await.status, StatusCode:: SEE_OTHER ) ;
711
712
713
let bob = login ( " bob" ) .await.cookie.unwrap ( ) ;
714
let csrf = csrf_of ( & get ( app, " /new" , Some ( & bob) ) .await.body) ;
715
assert_eq! (
716
post ( app, " /new" , Some ( & bob) , & format! ( " _csrf={csrf} &owner=bob&name=keep&visibility=public" ) ) .await.status,
717
StatusCode:: SEE_OTHER
718
) ;
719
assert! ( act ( " bob" , " delete" , " bo" ) .await.contains ( " type bob to confirm" ) ) ;
720
let page = act ( " bob" , " delete" , " bob" ) .await;
721
assert! ( page.contains ( " still owns bob/keep" ) , " {page}" ) ;
722
assert! ( db:: accounts:: account_by_name( & app.db, " bob" ) .await.unwrap ( ) .is_some ( ) ) ;
723
let row = db:: repos:: get( & app.db, " bob" , " keep" ) .await.unwrap ( ) .unwrap ( ) ;
724
db:: repos:: delete( & app.db, row.id) .await.unwrap ( ) ;
725
let page = act ( " bob" , " delete" , " bob" ) .await;
726
assert! ( page.contains ( " bob deleted" ) , " {page}" ) ;
727
assert! ( db:: accounts:: account_by_name( & app.db, " bob" ) .await.unwrap ( ) .is_none ( ) ) ;
728
assert_eq! ( get ( app, " /settings" , Some ( & bob) ) .await.status, StatusCode:: SEE_OTHER ) ;
729
730
let code = invite ( app.clone ( ) , andy.clone ( ) ) .await;
c8684d44 Andy McCall 21 days ago
731
let r = post (
732
app,
733
" /register" ,
734
None ,
735
& format! ( " username=bob&email=b%40example.com&password=correct-horse-battery&setup=test-setup&invite={code} " ) ,
736
)
737
.await;
6a178055 Andy McCall 1 month ago ↶
738
assert! ( r.body.contains ( " That name is taken" ) , " {}" , r.body) ;
739
740
assert! ( act ( " andy" , " delete" , " andy" ) .await.contains ( " Not on yourself" ) ) ;
741
}
5dead1f4 Andy McCall 1 month ago ↶
742
743
744
745
# [ tokio ::test ( flavor = " multi_thread" ) ]
746
async fn admins_set_the_job_time_limits ( ) {
747
let h = hub ( ) .await;
748
let app = & h.app;
749
let andy = register ( app, " andy" , " " ) .await;
750
let page = get ( app, " /admin/runners/settings" , Some ( & andy) ) .await;
751
assert_eq! ( page.status, StatusCode:: OK ) ;
752
assert! ( page.body.contains ( " Job time limits" ) & & page.body.contains ( " value=\" 60\" " ) , " the hub.toml default shows" ) ;
753
let csrf = csrf_of ( & page.body) ;
754
let r = post ( app, " /admin/runners/settings" , Some ( & andy) , & format! ( " _csrf={csrf} &default_minutes=200&max_minutes=120&grace_minutes=5" ) )
755
.await;
756
assert! ( r.body.contains ( " cannot be longer than the maximum" ) , " {}" , r.body) ;
757
let r = post ( app, " /admin/runners/settings" , Some ( & andy) , & format! ( " _csrf={csrf} &default_minutes=90&max_minutes=240&grace_minutes=10" ) )
758
.await;
759
assert! ( r.body.contains ( " Saved." ) , " {}" , r.body) ;
760
let l = oxygenhub:: flow:: limits( app) .await;
761
assert_eq! ( ( l.default_s, l.max_s, l.grace_ms) , ( 5400 , 14400 , 600_000 ) ) ;
762
assert! ( get ( app, " /admin/runners" , Some ( & andy) ) .await.body.contains ( " href=\" /admin/runners/settings\" " ) ) ;
763
let code = {
764
let csrf = csrf_of ( & get ( app, " /admin" , Some ( & andy) ) .await.body) ;
765
let r = post ( app, " /admin/invite" , Some ( & andy) , & format! ( " _csrf={csrf} " ) ) .await;
766
r.body.split ( " register?invite=" ) .nth ( 1 ) .unwrap ( ) .split ( ' <' ) .next ( ) .unwrap ( ) .trim ( ) .to_string ( )
767
} ;
768
let bob = register ( app, " bob" , & code) .await;
769
assert_ne! ( get ( app, " /admin/runners/settings" , Some ( & bob) ) .await.status, StatusCode:: OK , " not for others" ) ;
770
}
3556d08e Andy McCall 1 month ago ↶
771
772
773
774
# [ tokio ::test ( flavor = " multi_thread" ) ]
775
async fn mail_settings_are_saved_masked_and_tested_from_the_admin_page ( ) {
776
let h = hub ( ) .await;
777
let app = & h.app;
778
let andy = register ( app, " andy" , " " ) .await;
779
let page = get ( app, " /admin" , Some ( & andy) ) .await.body;
780
assert! ( page.contains ( " Mail is off" ) , " {page}" ) ;
781
let csrf = csrf_of ( & page) ;
782
783
let outbox = tempfile:: tempdir( ) .unwrap ( ) ;
784
let r = post (
785
app,
786
" /admin/mail" ,
787
Some ( & andy) ,
788
& format! ( " _csrf={csrf} &smtp=file%3A%2F%2F{} &from=Hub+%3Chub%40example.org%3E" , outbox.path ( ) .display ( ) ) ,
789
)
790
.await;
791
assert! ( r.body.contains ( " Mail settings saved" ) & & r.body.contains ( " Mail is on" ) , " {}" , r.body) ;
792
assert! ( oxygenhub:: mail:: enabled( app) ) ;
793
let r = post ( app, " /admin/mail/test" , Some ( & andy) , & format! ( " _csrf={csrf} " ) ) .await;
794
assert! ( r.body.contains ( " Sent a test message to" ) , " {}" , r.body) ;
795
let sent: Vec< _ > = std:: fs:: read_dir( outbox.path ( ) ) .unwrap ( ) .flatten ( ) .collect ( ) ;
796
assert_eq! ( sent.len ( ) , 1 ) ;
797
let text = std:: fs:: read_to_string( sent[ 0 ] .path ( ) ) .unwrap ( ) ;
798
assert! ( text.contains ( " Subject: [" ) & & text.contains ( " Test message" ) & & text.contains ( " From: Hub <[email protected] >" ) , " {text}" ) ;
799
800
let r = post (
801
app,
802
" /admin/mail" ,
803
Some ( & andy) ,
804
& format! ( " _csrf={csrf} &smtp=smtps%3A%2F%2Fhub%3Asecret%40mail.example.org%3A465&from=Hub+%3Chub%40example.org%3E" ) ,
805
)
806
.await;
2a83f530 Andy McCall 1 month ago ↶
807
assert! ( r.body.contains ( " smtps://hub:***@mail.example.org:465" ) & & ! r.body.contains ( " hub:secret" ) , " {}" , r.body) ;
3556d08e Andy McCall 1 month ago ↶
808
let r = post (
809
app,
810
" /admin/mail" ,
811
Some ( & andy) ,
812
& format! ( " _csrf={csrf} &smtp=smtps%3A%2F%2Fhub%3A***%40mail.example.org%3A465&from=Hub+%3Chub%40example.org%3E" ) ,
813
)
814
.await;
815
assert! ( r.body.contains ( " Mail settings saved" ) , " {}" , r.body) ;
816
assert_eq! ( oxygenhub:: mail:: settings( app) .smtp, " smtps://hub:[email protected] :465" ) ;
817
818
let r = post ( app, " /admin/mail" , Some ( & andy) , & format! ( " _csrf={csrf} &smtp=mail.example.org&from=x" ) ) .await;
819
assert! ( r.body.contains ( " starts with smtp://" ) , " {}" , r.body) ;
820
let r = post ( app, " /admin/mail" , Some ( & andy) , & format! ( " _csrf={csrf} &smtp=&from=" ) ) .await;
821
assert! ( r.body.contains ( " Mail is off" ) , " {}" , r.body) ;
822
assert! ( ! oxygenhub:: mail:: enabled( app) ) ;
823
824
let r = post ( app, " /admin/mail" , None , & format! ( " _csrf={csrf} &smtp=&from=" ) ) .await;
825
assert_ne! ( r.status, StatusCode:: OK ) ;
cd46e56b Andy McCall 23 days ago ↶
826
827
828
829
let from = " from=OxygenHub+%3Cnoreply%40example.org%3E" ;
830
let r = post ( app, " /admin/mail" , Some ( & andy) , & format! ( " _csrf={csrf} &service=resend&secret=&{from} " ) ) .await;
831
assert! ( r.body.contains ( " Give the Resend API key" ) , " {}" , r.body) ;
832
let r = post ( app, " /admin/mail" , Some ( & andy) , & format! ( " _csrf={csrf} &service=resend&secret=re_test_key_1&{from} " ) ) .await;
833
assert! ( r.body.contains ( " Mail settings saved" ) & & ! r.body.contains ( " re_test_key_1" ) , " {}" , r.body) ;
834
assert! ( r.body.contains ( r # "<option value="resend" selected>"# ) & & r.body.contains ( " saved: leave empty to keep it" ) , " {}" , r.body) ;
835
assert_eq! ( oxygenhub:: mail:: settings( app) .smtp, " smtps://resend:[email protected] :465" ) ;
836
let r = post ( app, " /admin/mail" , Some ( & andy) , & format! ( " _csrf={csrf} &service=resend&secret=&{from} " ) ) .await;
837
assert! ( r.body.contains ( " Mail settings saved" ) , " {}" , r.body) ;
838
assert_eq! ( oxygenhub:: mail:: settings( app) .smtp, " smtps://resend:[email protected] :465" , " kept" ) ;
839
840
let r =
841
post ( app, " /admin/mail" , Some ( & andy) , & format! ( " _csrf={csrf} &service=ses®ion=eu-west-2&user=AKIAEXAMPLE&secret=s3cret&{from} " ) )
842
.await;
843
assert! ( r.body.contains ( r # "<option value="ses" selected>"# ) , " {}" , r.body) ;
844
assert_eq! ( oxygenhub:: mail:: settings( app) .smtp, " smtps://AKIAEXAMPLE:[email protected] :465" ) ;
845
let r = post ( app, " /admin/mail" , Some ( & andy) , & format! ( " _csrf={csrf} &service=off&{from} " ) ) .await;
846
assert! ( r.body.contains ( " Mail is off" ) , " {}" , r.body) ;
3556d08e Andy McCall 1 month ago ↶
847
}
e71846aa Andy McCall 1 month ago ↶
848
849
850
851
async fn mock_assistant ( ) -> ( String, std:: sync:: Arc< std:: sync:: Mutex< Vec< String> > > ) {
852
use std:: sync:: { Arc, Mutex} ;
853
let seen: Arc< Mutex< Vec< String> > > = Arc:: new( Mutex:: new( vec! [ ] ) ) ;
854
let s2 = seen.clone ( ) ;
855
let router = axum:: Router:: new( ) .route (
856
" /v1/chat/completions" ,
857
axum:: routing:: post( move | headers: axum:: http:: HeaderMap, body: String | {
858
let s2 = s2.clone ( ) ;
859
async move {
860
let auth = headers.get ( " authorization" ) .and_then ( | v | v.to_str ( ) .ok ( ) ) .unwrap_or ( " " ) .to_string ( ) ;
861
s2.lock ( ) .unwrap ( ) .push ( format! ( " {auth} {body} " ) ) ;
862
axum:: Json( serde_json:: json! ( { " choices" : [ { " message" : { " role" : " assistant" , " content" : " OK from mock" } } ] } ) )
863
}
864
} ) ,
865
) ;
866
let listener = tokio:: net:: TcpListener:: bind( " 127.0.0.1:0" ) .await.unwrap ( ) ;
867
let port = listener.local_addr ( ) .unwrap ( ) .port ( ) ;
868
tokio:: spawn( async move { axum:: serve( listener, router) .await.unwrap ( ) } ) ;
869
( format! ( " http://127.0.0.1:{port} /v1/chat/completions" ) , seen)
870
}
871
872
fn enc ( s : & str ) -> String {
873
s.replace ( ' %' , " %25" ) .replace ( ' :' , " %3A" ) .replace ( ' /' , " %2F" ) .replace ( ' ' , " +" ) .replace ( ' \n ' , " %0A" ) .replace ( ' &' , " %26" )
874
}
875
876
# [ tokio ::test ( flavor = " multi_thread" ) ]
877
async fn ai_assistants_are_kept_per_level_with_sealed_tokens_and_combined_downwards ( ) {
878
use oxygenhub:: assistants:: { self , Scope} ;
879
let h = hub ( ) .await;
880
let app = & h.app;
881
let andy = register ( app, " andy" , " " ) .await;
882
let ( endpoint, seen) = mock_assistant ( ) .await;
883
884
885
let page = get ( app, " /admin" , Some ( & andy) ) .await.body;
886
assert! ( page.contains ( " AI assistants" ) & & page.contains ( " Add an assistant" ) , " {page}" ) ;
887
let csrf = csrf_of ( & page) ;
888
let add = | name : & str , extra : & str | {
889
format! (
890
" _csrf={csrf} &action=add&name={name} &endpoint={} &api=chat-completions&model=claude-opus-5-5&token=sk-test-secret&enabled=1&budget=50000{extra} " ,
891
enc ( & endpoint)
892
)
893
} ;
894
let r = post ( app, " /admin/assistants" , Some ( & andy) , & add ( " Claude" , " " ) ) .await;
206c1fc1 Andy McCall 1 month ago ↶
895
assert! ( r.body.contains ( " Claude added and answered: OK from mock" ) & & r.body.contains ( " token set" ) , " {}" , r.body) ;
e71846aa Andy McCall 1 month ago ↶
896
assert! ( ! r.body.contains ( " sk-test-secret" ) , " the token never comes back" ) ;
897
let site = assistants:: list( & app.db, Scope:: Site) .await.unwrap ( ) ;
898
assert_eq! ( site.len ( ) , 1 ) ;
899
let claude = & site[ 0 ] ;
900
assert! ( ! String :: from_utf8_lossy( & claude.token) .contains ( " sk-test" ) , " sealed at rest" ) ;
901
assert_eq! ( app.assistant_key.open ( & claude.token) .as_deref ( ) , Some ( " sk-test-secret" ) ) ;
902
903
let r = post ( app, " /admin/assistants" , Some ( & andy) , & add ( " claude" , " " ) ) .await;
904
assert! ( r.body.contains ( " already an assistant called" ) , " {}" , r.body) ;
905
let r = post (
906
app,
907
" /admin/assistants" ,
908
Some ( & andy) ,
909
& format! ( " _csrf={csrf} &action=add&name=Bad&endpoint=ftp%3A%2F%2Fx&api=chat-completions&model=m" ) ,
910
)
911
.await;
912
assert! ( r.body.contains ( " starting with https://" ) , " {}" , r.body) ;
913
914
915
let r = post ( app, " /admin/assistants" , Some ( & andy) , & format! ( " _csrf={csrf} &action=test&id={} " , claude.id) ) .await;
916
assert! ( r.body.contains ( " Claude answered: OK from mock" ) , " {}" , r.body) ;
917
{
918
let calls = seen.lock ( ) .unwrap ( ) ;
206c1fc1 Andy McCall 1 month ago ↶
919
assert_eq! ( calls.len ( ) , 2 , " once on add, once on test" ) ;
e71846aa Andy McCall 1 month ago ↶
920
assert! ( calls[ 0 ] .starts_with ( " Bearer sk-test-secret " ) , " {}" , calls[ 0 ] ) ;
921
assert! ( calls[ 0 ] .contains ( " \" model\" :\" claude-opus-5-5\" " ) & & calls[ 0 ] .contains ( " Reply with the single word OK" ) , " {}" , calls[ 0 ] ) ;
922
}
923
924
let r = post (
925
app,
926
" /admin/assistants" ,
927
Some ( & andy) ,
928
& format! ( " _csrf={csrf} &action=update&id={} &name=Claude&endpoint={} &api=chat-completions&model=claude-opus-5-5&token=&enabled=1&budget=60000" , claude.id, enc ( & endpoint) ) ,
929
)
930
.await;
931
assert! ( r.body.contains ( " Claude updated." ) & & r.body.contains ( " context 60000 characters" ) , " {}" , r.body) ;
932
assert_eq! (
933
app.assistant_key.open ( & assistants:: get( & app.db, claude.id) .await.unwrap ( ) .unwrap ( ) .token) .as_deref ( ) ,
934
Some ( " sk-test-secret" )
935
) ;
936
937
let r =
938
post ( app, " /admin/assistants" , Some ( & andy) , & format! ( " _csrf={csrf} &action=prompt&prompt={} " , enc ( " Review for correctness first." ) ) )
939
.await;
940
assert! ( r.body.contains ( " Prompt saved." ) & & r.body.contains ( " Review for correctness first." ) , " {}" , r.body) ;
941
942
943
let r = post ( app, " /orgs/new" , Some ( & andy) , & format! ( " _csrf={csrf} &name=acme&display_name=Acme" ) ) .await;
944
assert_eq! ( r.status, StatusCode:: SEE_OTHER , " {}" , r.body) ;
945
let r = post ( app, " /new" , Some ( & andy) , & format! ( " _csrf={csrf} &owner=acme&name=plans&visibility=public" ) ) .await;
946
assert_eq! ( r.status, StatusCode:: SEE_OTHER , " {}" , r.body) ;
947
let org_page = get ( app, " /orgs/acme/settings" , Some ( & andy) ) .await.body;
948
assert! ( org_page.contains ( " Inherited" ) & & org_page.contains ( " from the site" ) & & org_page.contains ( " None of its own" ) , " {org_page}" ) ;
949
assert! ( org_page.contains ( " From the site" ) & & org_page.contains ( " Review for correctness first." ) , " {org_page}" ) ;
950
let repo = db:: repos:: get( & app.db, " acme" , " plans" ) .await.unwrap ( ) .unwrap ( ) ;
951
let on = assistants:: enabled_for_repo( & app.db, & repo) .await.unwrap ( ) ;
952
assert_eq! ( on.iter ( ) .map ( | a | a.name.as_str ( ) ) .collect:: < Vec< _ > > ( ) , [ " Claude" ] ) ;
953
954
955
956
let r = post (
957
app,
958
" /orgs/acme/settings/assistants" ,
959
Some ( & andy) ,
960
& format! ( " _csrf={csrf} &action=prompt&prompt={} " , enc ( " We write 6502 assembly." ) ) ,
961
)
962
.await;
963
assert! ( r.body.contains ( " Prompt saved." ) , " {}" , r.body) ;
964
let r = post ( app, " /orgs/acme/settings/assistants" , Some ( & andy) , & add ( " DeepSeek" , " " ) ) .await;
206c1fc1 Andy McCall 1 month ago ↶
965
assert! ( r.body.contains ( " DeepSeek added and answered" ) , " {}" , r.body) ;
e71846aa Andy McCall 1 month ago ↶
966
let prompt = assistants:: prompt_for_repo( & app.db, & repo) .await.unwrap ( ) ;
967
assert! ( prompt.starts_with ( " ## Instructions from the site\n \n Review for correctness first.\n \n ## Instructions from the acme organisation\n \n We write 6502 assembly." ) , " {prompt}" ) ;
c7067c7b Andy McCall 17 days ago
968
let repo_page = get ( app, " /acme/plans/settings/assistants" , Some ( & andy) ) .await.body;
e71846aa Andy McCall 1 month ago ↶
969
assert! ( repo_page.contains ( " from the acme organisation" ) & & repo_page.contains ( " From the acme organisation" ) , " {repo_page}" ) ;
970
let on = assistants:: enabled_for_repo( & app.db, & repo) .await.unwrap ( ) ;
971
assert_eq! ( on.iter ( ) .map ( | a | a.name.as_str ( ) ) .collect:: < Vec< _ > > ( ) , [ " Claude" , " DeepSeek" ] ) ;
972
973
974
975
976
let r = post ( app, " /admin/assistants" , Some ( & andy) , & format! ( " _csrf={csrf} &action=toggle&id={} " , claude.id) ) .await;
977
assert! ( r.body.contains ( " Claude is off." ) , " {}" , r.body) ;
978
let r = post ( app, " /acme/plans/settings/assistants" , Some ( & andy) , & add ( " Claude" , " " ) ) .await;
c7067c7b Andy McCall 17 days ago
979
let r = settled ( app, r, Some ( & andy) , " /acme/plans/settings/assistants" ) .await;
206c1fc1 Andy McCall 1 month ago ↶
980
assert! ( r.body.contains ( " Claude added and answered" ) , " {}" , r.body) ;
e71846aa Andy McCall 1 month ago ↶
981
let on = assistants:: enabled_for_repo( & app.db, & repo) .await.unwrap ( ) ;
982
assert_eq! ( on.iter ( ) .map ( | a | a.name.as_str ( ) ) .collect:: < Vec< _ > > ( ) , [ " DeepSeek" ] ) ;
c7067c7b Andy McCall 17 days ago
983
let repo_page = get ( app, " /acme/plans/settings/assistants" , Some ( & andy) ) .await.body;
e71846aa Andy McCall 1 month ago ↶
984
assert! ( repo_page.contains ( " off above" ) , " {repo_page}" ) ;
985
post ( app, " /admin/assistants" , Some ( & andy) , & format! ( " _csrf={csrf} &action=toggle&id={} " , claude.id) ) .await;
986
let on = assistants:: enabled_for_repo( & app.db, & repo) .await.unwrap ( ) ;
987
assert_eq! ( on.iter ( ) .map ( | a | ( a.name.as_str ( ) , a.scope.as_str ( ) ) ) .collect:: < Vec< _ > > ( ) , [ ( " DeepSeek" , " org" ) , ( " Claude" , " repo" ) ] ) ;
988
989
990
let invite = {
991
let r = post ( app, " /admin/invite" , Some ( & andy) , & format! ( " _csrf={csrf} " ) ) .await;
992
let i = r.body.find ( " invite=" ) .map ( | i | i + 7 ) .expect ( " an invitation" ) ;
993
r.body[ i.. ] .chars ( ) .take_while ( | c | c.is_ascii_alphanumeric ( ) ) .collect:: < String> ( )
994
} ;
995
let bob = register ( app, " bob" , & invite) .await;
996
assert_eq! (
997
post ( app, " /admin/assistants" , Some ( & bob) , & format! ( " _csrf={csrf} &action=prompt&prompt=x" ) ) .await.status,
998
StatusCode:: NOT_FOUND
999
) ;
1000
assert_eq! (
1001
post ( app, " /orgs/acme/settings/assistants" , Some ( & bob) , & format! ( " _csrf={csrf} &action=prompt&prompt=x" ) ) .await.status,
1002
StatusCode:: NOT_FOUND
1003
) ;
1004
assert_eq! (
1005
post ( app, " /acme/plans/settings/assistants" , Some ( & bob) , & format! ( " _csrf={csrf} &action=prompt&prompt=x" ) ) .await.status,
1006
StatusCode:: NOT_FOUND
1007
) ;
1008
1009
let r = post ( app, " /acme/plans/settings/delete" , Some ( & andy) , & format! ( " _csrf={csrf} &confirm=acme%2Fplans" ) ) .await;
1010
assert! ( r.status = = StatusCode:: SEE_OTHER | | r.status = = StatusCode:: OK , " {} {}" , r.status, r.body) ;
1011
assert! ( assistants:: list( & app.db, Scope:: Repo( repo.id) ) .await.unwrap ( ) .is_empty ( ) ) ;
1012
}
89e89836 Andy McCall 1 month ago ↶
1013
1014
# [ tokio ::test ( flavor = " multi_thread" ) ]
1015
async fn accounts_elsewhere_are_checked_and_shown_on_the_profile ( ) {
1016
let h = hub ( ) .await;
1017
let app = & h.app;
1018
let andy = register ( app, " andy" , " " ) .await;
1019
let page = get ( app, " /settings" , Some ( & andy) ) .await.body;
1020
let csrf = csrf_of ( & page) ;
1021
let base = format! ( " _csrf={csrf} &display_name=Andy&email=andy%40example.com&bio=&website=&location=" ) ;
1022
let r = post ( app, " /settings" , Some ( & andy) , & format! ( " {base} &bluesky=%40Andy.bsky.social&mastodon=https%3A%2F%2FFosstodon.org%2F%40andy&github=https%3A%2F%2Fgithub.com%2Fandymccall%2F" ) ) .await;
1023
assert! (
1024
r.body.contains ( " value=\" andy.bsky.social\" " )
1025
& & r.body.contains ( " value=\" @[email protected] \" " )
1026
& & r.body.contains ( " value=\" andymccall\" " ) ,
1027
" {}" ,
1028
r.body
1029
) ;
1030
let profile = get ( app, " /andy" , None ) .await.body;
1031
assert! ( profile.contains ( " href=\" https://bsky.app/profile/andy.bsky.social\" " ) & & profile.contains ( " @andy.bsky.social" ) , " {profile}" ) ;
1032
assert! ( profile.contains ( " href=\" https://fosstodon.org/@andy\" " ) & & profile.contains ( " rel=\" nofollow noopener me\" " ) , " {profile}" ) ;
1033
assert! ( profile.contains ( " href=\" https://github.com/andymccall\" " ) & & profile.contains ( " title=\" GitHub\" " ) , " {profile}" ) ;
1034
1035
let r = post ( app, " /settings" , Some ( & andy) , & format! ( " {base} &bluesky=not+a+handle&mastodon=&github=" ) ) .await;
1036
assert! ( r.body.contains ( " not a Bluesky handle" ) , " {}" , r.body) ;
1037
assert! ( get ( app, " /andy" , None ) .await.body.contains ( " andy.bsky.social" ) ) ;
1038
1039
post ( app, " /settings" , Some ( & andy) , & format! ( " {base} &bluesky=&mastodon=&github=" ) ) .await;
1040
assert! ( ! get ( app, " /andy" , None ) .await.body.contains ( " class=\" social\" " ) ) ;
83940d53 Andy McCall 1 month ago ↶
1041
}
1042
1043
1044
async fn mock_provider ( ) -> ( String, std:: sync:: Arc< std:: sync:: Mutex< Vec< String> > > ) {
1045
use std:: sync:: { Arc, Mutex} ;
1046
let seen: Arc< Mutex< Vec< String> > > = Arc:: new( Mutex:: new( vec! [ ] ) ) ;
1047
let s1 = seen.clone ( ) ;
1048
let s2 = seen.clone ( ) ;
1049
let router = axum:: Router:: new( )
1050
.route (
1051
" /github/token" ,
1052
axum:: routing:: post( move | body: String | {
1053
let s1 = s1.clone ( ) ;
1054
async move {
1055
s1.lock ( ) .unwrap ( ) .push ( format! ( " github token {body} " ) ) ;
1056
axum:: Json( serde_json:: json! ( { " access_token" : " gh-token" , " token_type" : " bearer" } ) )
1057
}
1058
} ) ,
1059
)
1060
.route (
1061
" /github/userinfo" ,
1062
axum:: routing:: get( | headers : axum:: http:: HeaderMap| async move {
1063
assert_eq! ( headers.get ( " authorization" ) .and_then ( | v | v.to_str ( ) .ok ( ) ) , Some ( " Bearer gh-token" ) ) ;
1064
axum:: Json( serde_json:: json! ( { " id" : 583231 , " login" : " octocat" , " name" : " The Octocat" , " email" : null } ) )
1065
} ) ,
1066
)
1067
.route (
1068
" /github/userinfo/emails" ,
1069
axum:: routing:: get( | | async {
1070
axum:: Json( serde_json:: json! ( [
1071
{ " email" : " [email protected] " , " primary" : false , " verified" : false } ,
1072
{ " email" : " [email protected] " , " primary" : true , " verified" : true }
1073
] ) )
1074
} ) ,
1075
)
1076
.route (
1077
" /google/token" ,
1078
axum:: routing:: post( move | body: String | {
1079
let s2 = s2.clone ( ) ;
1080
async move {
1081
s2.lock ( ) .unwrap ( ) .push ( format! ( " google token {body} " ) ) ;
1082
axum:: Json( serde_json:: json! ( { " access_token" : " g-token" , " id_token" : " x" } ) )
1083
}
1084
} ) ,
1085
)
1086
.route (
810896d4 Andy McCall 22 days ago ↶
1087
" /gitlab/token" ,
1088
axum:: routing:: post( | | async { axum:: Json( serde_json:: json! ( { " access_token" : " gl-token" , " token_type" : " Bearer" } ) ) } ) ,
1089
)
1090
.route (
1091
" /gitlab/userinfo" ,
1092
axum:: routing:: get( | headers : axum:: http:: HeaderMap| async move {
1093
assert_eq! ( headers.get ( " authorization" ) .and_then ( | v | v.to_str ( ) .ok ( ) ) , Some ( " Bearer gl-token" ) ) ;
1094
axum:: Json( serde_json:: json! ( { " sub" : " 1234567" , " nickname" : " tanuki" , " name" : " The Tanuki" , " email" : " [email protected] " , " email_verified" : true } ) )
1095
} ) ,
1096
)
1097
.route (
83940d53 Andy McCall 1 month ago ↶
1098
" /google/userinfo" ,
1099
axum:: routing:: get( | | async {
1100
axum:: Json( serde_json:: json! ( { " sub" : " 1076915035000615071" , " email" : " [email protected] " , " email_verified" : true , " name" : " Andy McCall" } ) )
1101
} ) ,
1102
) ;
1103
let listener = tokio:: net:: TcpListener:: bind( " 127.0.0.1:0" ) .await.unwrap ( ) ;
1104
let port = listener.local_addr ( ) .unwrap ( ) .port ( ) ;
1105
tokio:: spawn( async move { axum:: serve( listener, router) .await.unwrap ( ) } ) ;
1106
( format! ( " http://127.0.0.1:{port} " ) , seen)
1107
}
1108
1109
fn state_of ( res : & Res) -> ( String, String) {
1110
let cookie = res.raw_cookies.iter ( ) .find ( | c | c.starts_with ( " oxyhub_signin=" ) ) .expect ( " state cookie" ) .clone ( ) ;
1111
let value = cookie.trim_start_matches ( " oxyhub_signin=" ) .split ( ' ;' ) .next ( ) .unwrap ( ) .to_string ( ) ;
1112
( cookie, value)
1113
}
1114
1115
# [ tokio ::test ( flavor = " multi_thread" ) ]
1116
async fn people_sign_in_with_github_or_google_once_an_admin_sets_it_up ( ) {
1117
hermetic ( ) ;
1118
let ( mock, seen) = mock_provider ( ) .await;
1119
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
1120
let mut config = Config:: load( dir.path ( ) ) .unwrap ( ) ;
c8684d44 Andy McCall 21 days ago
1121
1122
config.registration.setup_code = " test-setup" .into ( ) ;
83940d53 Andy McCall 1 month ago ↶
1123
let listener = tokio:: net:: TcpListener:: bind( " 127.0.0.1:0" ) .await.unwrap ( ) ;
1124
let port = listener.local_addr ( ) .unwrap ( ) .port ( ) ;
1125
config.server.base_url = format! ( " http://127.0.0.1:{port} " ) ;
1126
config.registration.mode = " open" .into ( ) ;
1127
config.auth.signin_mock = Some ( mock.clone ( ) ) ;
1128
let app = oxygenhub:: build( config) .await.unwrap ( ) ;
1129
let router = oxygenhub:: router( app.clone ( ) ) ;
1130
tokio:: spawn( async move { axum:: serve( listener, router) .await.unwrap ( ) } ) ;
1131
let app = & app;
1132
let andy = register ( app, " andy" , " " ) .await;
1133
let andy_row = db:: accounts:: account_by_name( & app.db, " andy" ) .await.unwrap ( ) .unwrap ( ) ;
1134
db:: accounts:: set_email_verified( & app.db, andy_row.id, true ) .await.unwrap ( ) ;
1135
1136
1137
assert! ( ! get ( app, " /login" , None ) .await.body.contains ( " /login/github" ) ) ;
1138
let admin = get ( app, " /admin" , Some ( & andy) ) .await.body;
1139
assert! ( admin.contains ( " Sign in with" ) & & admin.contains ( & format! ( " http://127.0.0.1:{port} /login/github/callback" ) ) , " {admin}" ) ;
1140
let csrf = csrf_of ( & admin) ;
1141
let r =
1142
post ( app, " /admin/signin" , Some ( & andy) , & format! ( " _csrf={csrf} &provider=github&client_id=gh-cid&secret=gh-sek&enabled=1" ) ) .await;
1143
assert! ( r.body.contains ( " Signing in with GitHub is on." ) & & ! r.body.contains ( " gh-sek" ) , " {}" , r.body) ;
1144
let r = post ( app, " /admin/signin" , Some ( & andy) , & format! ( " _csrf={csrf} &provider=google&client_id=g-cid&secret=g-sek&enabled=1" ) ) .await;
1145
assert! ( r.body.contains ( " Signing in with Google is on." ) , " {}" , r.body) ;
1146
let login = get ( app, " /login" , None ) .await.body;
1147
assert! ( login.contains ( " href=\" /login/github\" " ) & & login.contains ( " href=\" /login/google\" " ) , " {login}" ) ;
1148
1149
1150
let r = get ( app, " /login/github" , None ) .await;
1151
assert_eq! ( r.status, StatusCode:: SEE_OTHER ) ;
1152
let to = r.location.clone ( ) .unwrap ( ) ;
1153
assert! ( to.starts_with ( & format! ( " {mock} /github/authorize?client_id=gh-cid&redirect_uri=" ) ) & & to.contains ( " &state=" ) , " {to}" ) ;
1154
let ( cookie, state) = state_of ( & r) ;
1155
let bad = send_with ( app, " GET" , " /login/github/callback?code=c1&state=wrong" , Some ( & cookie) , None ) .await;
1156
assert! ( bad.location.as_deref ( ) .unwrap_or ( " " ) .starts_with ( " /login?error=" ) , " {:?}" , bad.location) ;
1157
let ok = send_with ( app, " GET" , & format! ( " /login/github/callback?code=c1&state={state} " ) , Some ( & cookie) , None ) .await;
1158
assert_eq! ( ok.status, StatusCode:: SEE_OTHER , " {}" , ok.body) ;
1159
assert_eq! ( ok.location.as_deref ( ) , Some ( " /" ) ) ;
1160
let octo_cookie = ok.cookie.clone ( ) .expect ( " signed in" ) ;
1161
let octo = db:: accounts:: account_by_name( & app.db, " octocat" ) .await.unwrap ( ) .expect ( " account made from the GitHub login" ) ;
1162
assert! (
1163
( octo.email.as_str ( ) , octo.email_verified, octo.display_name.as_str ( ) ) = = ( " [email protected] " , true , " The Octocat" ) ,
1164
" {octo:?}"
1165
) ;
1166
assert! ( seen.lock ( ) .unwrap ( ) .iter ( ) .any ( | s | s.contains ( " github token" ) & & s.contains ( " code=c1" ) & & s.contains ( " client_secret=gh-sek" ) ) ) ;
1167
assert! ( get ( app, " /settings" , Some ( & octo_cookie) ) .await.body.contains ( " octocat" ) ) ;
1168
1169
let r = get ( app, " /login/github" , None ) .await;
1170
let ( cookie, state) = state_of ( & r) ;
1171
let ok = send_with ( app, " GET" , & format! ( " /login/github/callback?code=c2&state={state} " ) , Some ( & cookie) , None ) .await;
1172
assert_eq! ( ok.location.as_deref ( ) , Some ( " /" ) ) ;
1173
assert_eq! ( db:: accounts:: account_count( & app.db) .await.unwrap ( ) , 2 ) ;
810896d4 Andy McCall 22 days ago ↶
1174
1175
1176
1177
let r = post (
1178
app,
1179
" /admin/signin" ,
1180
Some ( & andy) ,
1181
& format! ( " _csrf={csrf} &provider=gitlab&client_id=gl-cid&secret=gl-sek&enabled=1&base=http%3A%2F%2Fgitlab.example.org" ) ,
1182
)
1183
.await;
1184
assert! ( r.body.contains ( " is an https:// address" ) , " {}" , r.body) ;
1185
let r = post (
1186
app,
1187
" /admin/signin" ,
1188
Some ( & andy) ,
1189
& format! ( " _csrf={csrf} &provider=gitlab&client_id=gl-cid&secret=gl-sek&enabled=1&base=https%3A%2F%2Fgitlab.example.org%2F" ) ,
1190
)
1191
.await;
1192
assert! ( r.body.contains ( " Signing in with GitLab is on." ) & & r.body.contains ( " value=\" https://gitlab.example.org\" " ) , " {}" , r.body) ;
1193
let r = post (
1194
app,
1195
" /admin/signin" ,
1196
Some ( & andy) ,
1197
& format! ( " _csrf={csrf} &provider=github&client_id=gh-cid&enabled=1&base=https%3A%2F%2Fx.org" ) ,
1198
)
1199
.await;
1200
assert! ( r.body.contains ( " GitHub has no address to set." ) , " {}" , r.body) ;
1201
let login = get ( app, " /login" , None ) .await.body;
1202
assert! ( login.contains ( " signin-btn gitlab" ) & & login.contains ( " Sign in with GitLab" ) , " {login}" ) ;
1203
let r = get ( app, " /login/gitlab" , None ) .await;
1204
assert! ( r.location.clone ( ) .unwrap ( ) .contains ( " scope=openid%20profile%20email" ) , " {:?}" , r.location) ;
1205
let ( cookie, state) = state_of ( & r) ;
1206
let ok = send_with ( app, " GET" , & format! ( " /login/gitlab/callback?code=c9&state={state} " ) , Some ( & cookie) , None ) .await;
1207
assert_eq! ( ok.location.as_deref ( ) , Some ( " /" ) , " {}" , ok.body) ;
1208
let tanuki = db:: accounts:: account_by_name( & app.db, " tanuki" ) .await.unwrap ( ) .expect ( " account made from the GitLab username" ) ;
1209
assert! ( ( tanuki.email.as_str ( ) , tanuki.email_verified) = = ( " [email protected] " , true ) , " {tanuki:?}" ) ;
1210
assert_eq! ( db:: accounts:: account_count( & app.db) .await.unwrap ( ) , 3 ) ;
83940d53 Andy McCall 1 month ago ↶
1211
1212
1213
let r = get ( app, " /login/google" , None ) .await;
1214
assert! ( r.location.clone ( ) .unwrap ( ) .contains ( " prompt=select_account" ) ) ;
1215
let ( cookie, state) = state_of ( & r) ;
1216
let ok = send_with ( app, " GET" , & format! ( " /login/google/callback?code=c3&state={state} " ) , Some ( & cookie) , None ) .await;
1217
assert_eq! ( ok.location.as_deref ( ) , Some ( " /" ) , " {}" , ok.body) ;
1218
let as_andy = ok.cookie.clone ( ) .unwrap ( ) ;
1219
let sec = get ( app, " /settings/security" , Some ( & as_andy) ) .await.body;
1220
assert! (
1221
sec.contains ( " Connected accounts" )
1222
& & sec.contains ( " Google: <strong>andy</strong>" )
1223
& & sec.contains ( " GitHub: <a href=\" /settings/security/connect/github\" >connect</a>" ) ,
1224
" {sec}"
1225
) ;
810896d4 Andy McCall 22 days ago ↶
1226
assert_eq! ( db:: accounts:: account_count( & app.db) .await.unwrap ( ) , 3 , " no fourth account" ) ;
83940d53 Andy McCall 1 month ago ↶
1227
1228
let csrf_s = csrf_of ( & sec) ;
1229
let r = post ( app, " /settings/security/disconnect/google" , Some ( & as_andy) , & format! ( " _csrf={csrf_s} " ) ) .await;
1230
assert! ( r.location.as_deref ( ) .unwrap_or ( " " ) .contains ( " notice=Google%20disconnected" ) , " {:?}" , r.location) ;
1231
assert! ( ! get ( app, " /settings/security" , Some ( & as_andy) ) .await.body.contains ( " Google: <strong>andy</strong>" ) ) ;
1232
let r = get ( app, " /settings/security/connect/google" , Some ( & as_andy) ) .await;
1233
assert_eq! ( r.status, StatusCode:: SEE_OTHER ) ;
1234
let ( cookie, state) = state_of ( & r) ;
1235
let both = format! ( " {cookie} ; oxyhub={as_andy} " ) ;
1236
let ok = send_with ( app, " GET" , & format! ( " /login/google/callback?code=c4&state={state} " ) , Some ( & both) , None ) .await;
1237
assert! ( ok.location.as_deref ( ) .unwrap_or ( " " ) .contains ( " notice=Google%20connected%20as%20andy" ) , " {:?} {}" , ok.location, ok.body) ;
1238
1239
1240
db:: accounts:: set_setting( & app.db, " registration_mode" , " closed" ) .await.unwrap ( ) ;
1241
sqlx:: query( " DELETE FROM account_logins WHERE provider = 'github'" ) .execute ( & app.db) .await.unwrap ( ) ;
3b1bc27f Andy McCall 21 days ago
1242
sqlx:: query( " UPDATE accounts SET email_verified = FALSE WHERE username = 'octocat'" ) .execute ( & app.db) .await.unwrap ( ) ;
83940d53 Andy McCall 1 month ago ↶
1243
let r = get ( app, " /login/github" , None ) .await;
1244
let ( cookie, state) = state_of ( & r) ;
1245
let no = send_with ( app, " GET" , & format! ( " /login/github/callback?code=c5&state={state} " ) , Some ( & cookie) , None ) .await;
1246
assert! ( no.location.as_deref ( ) .unwrap_or ( " " ) .contains ( " registration%20is%20closed" ) , " {:?}" , no.location) ;
1247
assert! ( no.cookie.is_none ( ) ) ;
89e89836 Andy McCall 1 month ago ↶
1248
}
e8e7158b Andy McCall 1 month ago ↶
1249
1250
# [ tokio ::test ( flavor = " multi_thread" ) ]
1251
async fn administration_is_sectioned_and_its_audit_log_pages ( ) {
1252
let h = hub ( ) .await;
1253
let app = & h.app;
1254
let andy = register ( app, " andy" , " " ) .await;
1255
let andy_row = db:: accounts:: account_by_name( & app.db, " andy" ) .await.unwrap ( ) .unwrap ( ) ;
1256
for i in 0 .. 60 {
1257
db:: accounts:: audit( & app.db, Some ( & andy_row) , " test.event" , & format! ( " t{i} " ) , " " ) .await.unwrap ( ) ;
1258
}
1259
let page = get ( app, " /admin" , Some ( & andy) ) .await.body;
1260
for id in [ " accounts" , " registration" , " organisations" , " signin" , " mail" , " variables" , " secrets" , " assistants" , " audit" ] {
1261
assert! ( page.contains ( & format! ( " href=\" #{id} \" " ) ) & & page.contains ( & format! ( " id=\" {id} \" " ) ) , " section {id}: {page}" ) ;
1262
}
1263
assert! ( page.contains ( " class=\" section-nav\" " ) ) ;
1264
assert! ( page.contains ( " >t59<" ) & & ! page.contains ( " >t5<" ) , " the newest page only" ) ;
1265
let i = page.find ( " audit_before=" ) .expect ( " an older link" ) + " audit_before=" .len ( ) ;
1266
let before: String = page[ i.. ] .chars ( ) .take_while ( | c | c.is_ascii_digit ( ) ) .collect ( ) ;
1267
let older = get ( app, & format! ( " /admin?audit_before={before} " ) , Some ( & andy) ) .await.body;
1268
assert! ( older.contains ( " >t5<" ) & & ! older.contains ( " >t59<" ) , " the next page: {older}" ) ;
1269
}
155cab14 Andy McCall 1 month ago ↶
1270
1271
# [ tokio ::test ( flavor = " multi_thread" ) ]
1272
async fn adding_an_assistant_offers_providers_and_only_models_the_endpoint_lists ( ) {
1273
let h = hub ( ) .await;
1274
let app = & h.app;
1275
let andy = register ( app, " andy" , " " ) .await;
1276
let router = axum:: Router:: new( )
1277
.route (
1278
" /v1/models" ,
1279
axum:: routing:: get( | headers : axum:: http:: HeaderMap| async move {
1280
assert_eq! ( headers.get ( " authorization" ) .and_then ( | v | v.to_str ( ) .ok ( ) ) , Some ( " Bearer sk-m" ) ) ;
1281
axum:: Json( serde_json:: json! ( { " data" : [
1282
{ " id" : " models/gemini-3-pro" } , { " id" : " gemini-3-flash" } , { " id" : " text-embedding-004" }
1283
] } ) )
1284
} ) ,
1285
)
1286
.route (
1287
" /v1/chat/completions" ,
1288
axum:: routing:: post( | | async { axum:: Json( serde_json:: json! ( { " choices" : [ { " message" : { " content" : " OK" } } ] } ) ) } ) ,
1289
) ;
1290
let listener = tokio:: net:: TcpListener:: bind( " 127.0.0.1:0" ) .await.unwrap ( ) ;
1291
let port = listener.local_addr ( ) .unwrap ( ) .port ( ) ;
1292
tokio:: spawn( async move { axum:: serve( listener, router) .await.unwrap ( ) } ) ;
1293
let ep = format! ( " http%3A%2F%2F127.0.0.1%3A{port} %2Fv1%2Fchat%2Fcompletions" ) ;
1294
1295
let page = get ( app, " /admin" , Some ( & andy) ) .await.body;
1296
assert! ( page.contains ( " data-preset-select" ) & & page.contains ( " Google Gemini" ) & & page.contains ( " Other (enter the endpoint)" ) , " {page}" ) ;
1297
assert! ( page.contains ( " LIST MODELS" ) ) ;
1298
let csrf = csrf_of ( & page) ;
1299
1300
let r =
1301
post ( app, " /admin/assistants/models" , Some ( & andy) , & format! ( " _csrf={csrf} &endpoint={ep} &api=chat-completions&token=sk-m" ) ) .await;
1302
let v: serde_json:: Value = serde_json:: from_str( & r.body) .unwrap ( ) ;
1303
assert_eq! ( v[ " models" ] , serde_json:: json! ( [ " gemini-3-flash" , " gemini-3-pro" ] ) , " {}" , r.body) ;
1304
1305
let r = post (
1306
app,
1307
" /admin/assistants" ,
1308
Some ( & andy) ,
1309
& format! ( " _csrf={csrf} &action=add&preset=gemini&endpoint={ep} &model=gemini-2.5-pro&token=sk-m&enabled=1" ) ,
1310
)
1311
.await;
1312
assert! ( r.body.contains ( " gemini-2.5-pro is not a model this endpoint offers" ) & & r.body.contains ( " gemini-3-pro" ) , " {}" , r.body) ;
1313
1314
let r = post (
1315
app,
1316
" /admin/assistants" ,
1317
Some ( & andy) ,
1318
& format! ( " _csrf={csrf} &action=add&preset=gemini&endpoint={ep} &model=gemini-3-pro&token=sk-m&enabled=1" ) ,
1319
)
1320
.await;
1321
assert! ( r.body.contains ( " Gemini added and answered: OK" ) , " {}" , r.body) ;
1322
let a = & oxygenhub:: assistants:: list( & app.db, oxygenhub:: levels:: Scope:: Site) .await.unwrap ( ) [ 0 ] ;
1323
assert_eq! ( ( a.name.as_str ( ) , a.api.as_str ( ) , a.model.as_str ( ) ) , ( " Gemini" , " chat-completions" , " gemini-3-pro" ) ) ;
1324
1325
let r =
1326
post ( app, " /admin/assistants/models" , Some ( & andy) , & format! ( " _csrf={csrf} &id={} &endpoint={ep} &api=chat-completions" , a.id) ) .await;
1327
assert! ( r.body.contains ( " gemini-3-flash" ) , " {}" , r.body) ;
1328
}
2a0c09c0 Andy McCall 22 days ago ↶
1329
1330
1331
1332
1333
1334
# [ tokio ::test ( flavor = " multi_thread" ) ]
1335
async fn a_profile_shows_the_year_as_a_signal ( ) {
1336
let h = hub ( ) .await;
1337
let app = & h.app;
1338
register ( app, " andy" , " " ) .await;
1339
let andy = db:: accounts:: account_by_name( & app.db, " andy" ) .await.unwrap ( ) .unwrap ( ) ;
c0095389 Andy McCall 22 days ago ↶
1340
3b1bc27f Andy McCall 21 days ago
1341
sqlx:: query( " UPDATE accounts SET created_ms = $1 WHERE id = $2" )
a2fbad48 Andy McCall 22 days ago ↶
1342
.bind ( db:: now_ms( ) - 400 * 86_400_000 )
1343
.bind ( andy.id)
1344
.execute ( & app.db)
1345
.await
1346
.unwrap ( ) ;
2a0c09c0 Andy McCall 22 days ago ↶
1347
let game = db:: repos:: create( & app.db, " andy" , " game" , " " , hub_api:: Visibility:: Public) .await.unwrap ( ) ;
1348
let secret = db:: repos:: create( & app.db, " andy" , " secret" , " " , hub_api:: Visibility:: Private) .await.unwrap ( ) ;
1349
let now = db:: now_ms( ) ;
1350
for ( repo, ago_days, changes, reason, via) in [
1351
( game.id, 3 , 5 , " " , " " ) ,
1352
( game.id, 3 , 2 , " " , " Claude" ) ,
1353
( game.id, 40 , 4 , " " , " " ) ,
1354
( game.id, 2 , 9 , " landed #1 (web)" , " " ) ,
1355
( secret.id, 1 , 50 , " " , " " ) ,
1356
] {
3b1bc27f Andy McCall 21 days ago
1357
sqlx:: query( " INSERT INTO pushes (repo_id, at_ms, reference, ok, reason, changes, account_id, pusher, via) VALUES ($1, $2, 'main', TRUE, $3, $4, $5, 'andy', $6)" )
2a0c09c0 Andy McCall 22 days ago ↶
1358
.bind ( repo)
1359
.bind ( now - ago_days * 86_400_000 )
1360
.bind ( reason)
1361
.bind ( changes)
1362
.bind ( andy.id)
1363
.bind ( via)
1364
.execute ( & app.db)
1365
.await
1366
.unwrap ( ) ;
1367
}
3b1bc27f Andy McCall 21 days ago
1368
sqlx:: query( " INSERT INTO releases (repo_id, tag, title, author_id, author, created_ms) VALUES ($1, 'v1.0', 'One', $2, 'andy', $3)" )
2a0c09c0 Andy McCall 22 days ago ↶
1369
.bind ( game.id)
1370
.bind ( andy.id)
1371
.bind ( now - 3 * 86_400_000 )
1372
.execute ( & app.db)
1373
.await
1374
.unwrap ( ) ;
1375
1376
let page = get ( app, " /andy" , None ) .await.body;
1377
let start = page.find ( " id=\" pulse-data\" >" ) .expect ( " the pulse is on the profile" ) + " id=\" pulse-data\" >" .len ( ) ;
1378
let json: serde_json:: Value = serde_json:: from_str( & page[ start.. start + page[ start.. ] .find ( " </script>" ) .unwrap ( ) ] ) .unwrap ( ) ;
1379
assert_eq! ( json[ " repos" ] , serde_json:: json! ( [ " andy/game" ] ) ) ;
1380
let days = json[ " days" ] .as_array ( ) .unwrap ( ) ;
c0095389 Andy McCall 22 days ago ↶
1381
1382
assert_eq! ( ( days.len ( ) , json[ " months" ] .as_i64 ( ) ) , ( 91 , Some ( 3 ) ) ) ;
2a0c09c0 Andy McCall 22 days ago ↶
1383
let total: i64 = days.iter ( ) .map ( | d | d[ 0 ] .as_i64 ( ) .unwrap ( ) ) .sum ( ) ;
1384
let via: i64 = days.iter ( ) .map ( | d | d[ 1 ] .as_i64 ( ) .unwrap ( ) ) .sum ( ) ;
1385
assert_eq! ( ( total, via) , ( 11 , 2 ) , " 5 + 2 + 4 changes, 2 via an agent; the landing and the private push left out" ) ;
c0095389 Andy McCall 22 days ago ↶
1386
assert_eq! ( days[ 87 ] , serde_json:: json! ( [ 7 , 2 , [ [ 0 , 7 ] ] ] ) , " three days ago" ) ;
1387
assert_eq! ( json[ " peaks" ] [ 0 ] , serde_json:: json! ( [ 87 , " game v1.0" ] ) ) ;
a2fbad48 Andy McCall 22 days ago ↶
1388
db:: accounts:: create_account( & app.db, " bea" , " [email protected] " , " x" , " salt" , false ) .await.unwrap ( ) ;
1389
assert! ( get ( app, " /bea" , None ) .await.body.contains ( " No changes pushed" ) , " a new account with no pushes says so" ) ;
2a0c09c0 Andy McCall 22 days ago ↶
1390
assert! (
1391
page.contains ( " data-total=\" 11\" " ) & & page.find ( " pulse-box" ) .unwrap ( ) < page.find ( " <h2>Repositories</h2>" ) .unwrap ( ) ,
1392
" above the repositories"
1393
) ;
1394
}
9a8e3b44 Andy McCall 22 days ago ↶
1395
1396
1397
1398
1399
1400
# [ tokio ::test ( flavor = " multi_thread" ) ]
1401
async fn an_https_site_takes_nothing_over_http ( ) {
1402
hermetic ( ) ;
1403
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
1404
let mut config = Config:: load( dir.path ( ) ) .unwrap ( ) ;
c8684d44 Andy McCall 21 days ago
1405
1406
config.registration.setup_code = " test-setup" .into ( ) ;
9a8e3b44 Andy McCall 22 days ago ↶
1407
config.server.base_url = " https://hub.example.org" .into ( ) ;
1408
config.registration.mode = " open" .into ( ) ;
1409
let app = oxygenhub:: build( config) .await.unwrap ( ) ;
1410
let call = | method : & 'static str , path : & 'static str , header : Option< ( & 'static str , & 'static str ) > , body : Option< & 'static str > | {
1411
let app = app.clone ( ) ;
1412
async move {
1413
let mut req = Request:: builder( ) .method ( method) .uri ( path) ;
1414
if let Some ( ( k, v) ) = header {
1415
req = req.header ( k, v) ;
1416
}
1417
if body.is_some ( ) {
1418
req = req.header ( header:: CONTENT_TYPE , " application/x-www-form-urlencoded" ) ;
1419
}
1420
oxygenhub:: router( app) .oneshot ( req.body ( body.map ( Body:: from) .unwrap_or_else ( Body:: empty) ) .unwrap ( ) ) .await.unwrap ( )
1421
}
1422
} ;
1423
1424
let r = call ( " GET" , " /login?next=%2Fx" , Some ( ( " x-forwarded-proto" , " http" ) ) , None ) .await;
1425
assert! ( r.status ( ) .is_redirection ( ) , " {}" , r.status ( ) ) ;
1426
assert_eq! ( r.headers ( ) .get ( header:: LOCATION ) .unwrap ( ) , " https://hub.example.org/login?next=%2Fx" ) ;
1427
1428
let r = call ( " POST" , " /login" , Some ( ( " cf-visitor" , r # "{"scheme":"http"}"# ) ) , Some ( " username=a&password=b" ) ) .await;
1429
assert_eq! ( r.status ( ) , StatusCode:: BAD_REQUEST ) ;
1430
1431
assert_eq! ( call ( " GET" , " /login" , Some ( ( " x-forwarded-proto" , " https" ) ) , None ) .await.status ( ) , StatusCode:: OK ) ;
1432
assert_eq! ( call ( " GET" , " /login" , None , None ) .await.status ( ) , StatusCode:: OK ) ;
1433
1434
let r = call (
1435
" POST" ,
1436
" /register" ,
1437
Some ( ( " x-forwarded-proto" , " https" ) ) ,
c8684d44 Andy McCall 21 days ago
1438
Some ( " username=andy&email=a%40example.org&password=correct-horse-battery&setup=test-setup" ) ,
9a8e3b44 Andy McCall 22 days ago ↶
1439
)
1440
.await;
1441
let cookie = r.headers ( ) .get ( header:: SET_COOKIE ) .expect ( " signed in" ) .to_str ( ) .unwrap ( ) ;
1442
assert! ( cookie.contains ( " ; Secure" ) & & cookie.contains ( " HttpOnly" ) , " {cookie}" ) ;
2cbf6f34 Andy McCall 21 days ago ↶
1443
1444
assert! ( call ( " GET" , " /login" , Some ( ( " x-forwarded-proto" , " https" ) ) , None )
1445
.await
1446
.headers ( )
1447
.get ( header:: STRICT_TRANSPORT_SECURITY )
1448
.is_none ( ) ) ;
1449
assert_eq! ( oxygenhub:: headers:: hsts( " https://hub.example.org" , 300 ) .unwrap ( ) , " max-age=300" ) ;
1450
assert! ( oxygenhub:: headers:: hsts( " http://127.0.0.1:7300" , 300 ) .is_none ( ) , " never over plain http" ) ;
1451
assert! ( oxygenhub:: headers:: hsts( " https://hub.example.org" , 0 ) .is_none ( ) ) ;
9a8e3b44 Andy McCall 22 days ago ↶
1452
}
aa0bfbd1 Andy McCall 22 days ago ↶
1453
1454
# [ tokio ::test ]
1455
async fn guessing_passwords_is_slowed_per_account_and_per_address ( ) {
1456
hermetic ( ) ;
1457
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
1458
let mut config = Config:: load( dir.path ( ) ) .unwrap ( ) ;
c8684d44 Andy McCall 21 days ago
1459
1460
config.registration.setup_code = " test-setup" .into ( ) ;
aa0bfbd1 Andy McCall 22 days ago ↶
1461
config.server.behind_proxy = true ;
1462
config.registration.mode = " open" .into ( ) ;
1463
let app = oxygenhub:: build( config) .await.unwrap ( ) ;
1464
let from = | addr : & 'static str , form : String| {
1465
let app = app.clone ( ) ;
1466
async move {
1467
let req = Request:: builder( )
1468
.method ( " POST" )
1469
.uri ( " /login" )
1470
.header ( " x-forwarded-for" , addr)
1471
.header ( header:: CONTENT_TYPE , " application/x-www-form-urlencoded" ) ;
1472
let res = oxygenhub:: router( app) .oneshot ( req.body ( Body:: from( form) ) .unwrap ( ) ) .await.unwrap ( ) ;
1473
let status = res.status ( ) ;
1474
( status, String :: from_utf8_lossy( & res.into_body ( ) .collect ( ) .await.unwrap ( ) .to_bytes ( ) ) .into_owned ( ) )
1475
}
1476
} ;
1477
register ( & app, " andy" , " " ) .await;
c8684d44 Andy McCall 21 days ago
1478
let right = | | " username=andy&password=correct-horse-battery&setup=test-setup" .to_string ( ) ;
aa0bfbd1 Andy McCall 22 days ago ↶
1479
1480
1481
1482
for i in 0 .. 6 {
1483
let ( _ , body) = from ( " 198.51.100.1" , " username=andy&password=wrong" .into ( ) ) .await;
1484
assert! ( body.contains ( " Wrong username or password." ) , " try {i}" ) ;
1485
}
1486
let ( status, body) = from ( " 198.51.100.2" , right ( ) ) .await;
1487
assert_eq! ( status, StatusCode:: OK , " not signed in" ) ;
1488
assert! ( body.contains ( " Too many tries: try again in" ) , " {body}" ) ;
1489
let audit = db:: accounts:: audit_rows( & app.db, 50 ) .await.unwrap ( ) ;
1490
assert! ( audit.iter ( ) .any ( | r | r.action = = " login.throttled" & & r.target = = " andy" & & r.detail.contains ( " 198.51.100.1" ) ) ) ;
1491
app.throttle.lock ( ) .unwrap ( ) .cleared ( & oxygenhub:: throttle:: Key:: account( " login" , " andy" ) ) ;
1492
1493
1494
1495
for i in 0 .. 21 {
1496
let ( _ , body) = from ( " 203.0.113.7" , format! ( " username=nobody{i} &password=wrong" ) ) .await;
1497
assert! ( body.contains ( " Wrong username or password." ) , " try {i}" ) ;
1498
}
1499
let ( _ , body) = from ( " 203.0.113.7" , right ( ) ) .await;
1500
assert! ( body.contains ( " Too many tries" ) , " {body}" ) ;
1501
let ( status, _ ) = from ( " 198.51.100.3" , right ( ) ) .await;
1502
assert_eq! ( status, StatusCode:: SEE_OTHER , " another address signs in" ) ;
1503
}
d74ce22f Andy McCall 22 days ago ↶
1504
1505
# [ tokio ::test ]
1506
async fn every_page_carries_the_security_headers_and_violations_are_reported ( ) {
1507
let h = hub ( ) .await;
1508
let res = oxygenhub:: router( h.app.clone ( ) ) .oneshot ( Request:: get( " /login" ) .body ( Body:: empty( ) ) .unwrap ( ) ) .await.unwrap ( ) ;
1509
let hd = res.headers ( ) ;
1510
assert_eq! ( hd[ header:: X_CONTENT_TYPE_OPTIONS ] , " nosniff" ) ;
1511
assert_eq! ( hd[ header:: REFERRER_POLICY ] , " strict-origin-when-cross-origin" ) ;
1512
assert_eq! ( hd[ header:: X_FRAME_OPTIONS ] , " DENY" ) ;
1513
assert! ( hd[ " permissions-policy" ] .to_str ( ) .unwrap ( ) .contains ( " camera=()" ) ) ;
1514
1515
let csp = hd[ header:: CONTENT_SECURITY_POLICY_REPORT_ONLY ] .to_str ( ) .unwrap ( ) ;
1516
for part in [
1517
" default-src 'self'" ,
1518
" object-src 'none'" ,
1519
" frame-ancestors 'none'" ,
1520
" form-action 'self'" ,
1521
" 'wasm-unsafe-eval'" ,
1522
" report-uri /csp-report" ,
1523
] {
1524
assert! ( csp.contains ( part) , " {part} in {csp}" ) ;
1525
}
1526
assert! ( hd.get ( header:: CONTENT_SECURITY_POLICY ) .is_none ( ) & & hd.get ( header:: STRICT_TRANSPORT_SECURITY ) .is_none ( ) ) ;
1527
1528
let res = oxygenhub:: router( h.app.clone ( ) ) .oneshot ( Request:: get( " /no/such/page" ) .body ( Body:: empty( ) ) .unwrap ( ) ) .await.unwrap ( ) ;
1529
assert_eq! ( res.headers ( ) [ header:: X_CONTENT_TYPE_OPTIONS ] , " nosniff" ) ;
1530
1531
let report =
1532
r # "{"csp-report":{"document-uri":"http://127.0.0.1/login","violated-directive":"script-src-elem","blocked-uri":"inline"}}"# ;
1533
let req = Request:: post( " /csp-report" ) .header ( header:: CONTENT_TYPE , " application/csp-report" ) .body ( Body:: from( report) ) .unwrap ( ) ;
1534
assert_eq! ( oxygenhub:: router( h.app.clone ( ) ) .oneshot ( req) .await.unwrap ( ) .status ( ) , StatusCode:: NO_CONTENT ) ;
1535
let big = Request:: post( " /csp-report" ) .body ( Body:: from( vec! [ b ' ' ; 64 * 1024 ] ) ) .unwrap ( ) ;
1536
assert_eq! ( oxygenhub:: router( h.app.clone ( ) ) .oneshot ( big) .await.unwrap ( ) .status ( ) , StatusCode:: PAYLOAD_TOO_LARGE ) ;
1537
}
3dd6582d Andy McCall 22 days ago ↶
1538
1539
# [ tokio ::test ]
1540
async fn security_txt_names_the_contact_an_administrator_sets ( ) {
1541
let h = hub ( ) .await;
1542
let app = & h.app;
1543
assert_eq! ( get ( app, " /.well-known/security.txt" , None ) .await.status, StatusCode:: NOT_FOUND , " no contact, no file" ) ;
1544
let andy = register ( app, " andy" , " " ) .await;
1545
let page = get ( app, " /admin" , Some ( & andy) ) .await.body;
1546
assert! ( page.contains ( " No contact yet" ) , " the panel" ) ;
1547
let csrf = csrf_of ( & page) ;
1548
let set = | contact : & 'static str , policy : & 'static str | {
1549
let ( andy, csrf) = ( andy.clone ( ) , csrf.clone ( ) ) ;
1550
async move { post ( app, " /admin/security" , Some ( & andy) , & format! ( " _csrf={csrf} &contact={contact} &policy={policy} " ) ) .await }
1551
} ;
1552
assert_eq! ( set ( " javascript%3Aalert(1)" , " " ) .await.status, StatusCode:: BAD_REQUEST ) ;
1553
assert_eq! ( set ( " sec%40example.org" , " http%3A%2F%2Fexample.org" ) .await.status, StatusCode:: BAD_REQUEST , " policy over https only" ) ;
1554
let r = set ( " sec%40example.org" , " https%3A%2F%2Fexample.org%2Fpolicy" ) .await;
1555
assert! ( r.body.contains ( " Security contact saved" ) , " {}" , r.body) ;
1556
for path in [ " /.well-known/security.txt" , " /security.txt" ] {
1557
let r = get ( app, path, None ) .await;
1558
assert_eq! ( r.status, StatusCode:: OK ) ;
1559
assert! ( r.body.starts_with ( " Contact: mailto:[email protected] \n Expires: 20" ) , " {}" , r.body) ;
1560
assert! ( r.body.contains ( " Policy: https://example.org/policy\n " ) & & r.body.contains ( " /.well-known/security.txt\n " ) , " {}" , r.body) ;
1561
}
1562
1563
let r = post ( app, " /admin/invite" , Some ( & andy) , & format! ( " _csrf={csrf} " ) ) .await;
1564
let code = r.body.split ( " register?invite=" ) .nth ( 1 ) .unwrap ( ) .split ( ' <' ) .next ( ) .unwrap ( ) .trim ( ) .to_string ( ) ;
1565
let bob = register ( app, " bob" , & code) .await;
1566
let r = post ( app, " /admin/security" , Some ( & bob) , & format! ( " _csrf={csrf} &contact=x%40evil.example" ) ) .await;
1567
assert_ne! ( r.status, StatusCode:: OK ) ;
1568
1569
set ( " " , " " ) .await;
1570
assert_eq! ( get ( app, " /security.txt" , None ) .await.status, StatusCode:: NOT_FOUND ) ;
2cbf6f34 Andy McCall 21 days ago ↶
1571
1572
1573
1574
let page = get ( app, " /security-contact" , None ) .await;
1575
assert_eq! ( page.status, StatusCode:: OK ) ;
1576
assert! ( page.body.contains ( " Report a security problem" ) & & page.body.contains ( " tell us privately" ) , " {}" , page.body) ;
1577
let r = post (
1578
app,
1579
" /admin/security" ,
1580
Some ( & andy) ,
1581
& format! (
1582
" _csrf={csrf} &contact=https%3A%2F%2Fhub.example%2Fsecurity-contact&email=security%40example.org&page=Mail+us.+**Thank+you.**"
1583
) ,
1584
)
1585
.await;
1586
assert! ( r.body.contains ( " Security contact saved" ) , " {}" , r.body) ;
1587
let page = get ( app, " /security-contact" , None ) .await.body;
1588
assert! (
1589
page.contains ( " [email protected] " ) & & page.contains ( " <strong>Thank you.</strong>" ) & & ! page.contains ( " tell us privately" ) ,
1590
" {page}"
1591
) ;
1592
let r = post ( app, " /admin/security" , Some ( & andy) , & format! ( " _csrf={csrf} &contact=sec%40example.org&email=not-an-address" ) ) .await;
1593
assert_eq! ( r.status, StatusCode:: BAD_REQUEST ) ;
1594
assert! ( ! oxygenhub:: repos:: names:: valid_owner( " security-contact" ) & & ! oxygenhub:: repos:: names:: valid_owner( " live" ) , " reserved" ) ;
3dd6582d Andy McCall 22 days ago ↶
1595
}
0024ccb1 Andy McCall 22 days ago ↶
1596
1597
# [ tokio ::test ]
1598
async fn sessions_are_records_that_can_be_listed_ended_and_expire ( ) {
1599
let h = hub ( ) .await;
1600
let app = & h.app;
1601
let a = register ( app, " andy" , " " ) .await;
1602
assert_eq! ( a.len ( ) , 64 , " a random id, not the account's name" ) ;
c8684d44 Andy McCall 21 days ago
1603
let b =
1604
post ( app, " /login" , None , " username=andy&password=correct-horse-battery&setup=test-setup" ) .await.cookie.expect ( " signed in again" ) ;
0024ccb1 Andy McCall 22 days ago ↶
1605
assert_ne! ( a, b, " each sign-in is a new session" ) ;
1606
1607
let page = get ( app, " /settings/security" , Some ( & a) ) .await.body;
1608
assert_eq! ( page.matches ( " /end\" " ) .count ( ) , 2 , " both browsers listed" ) ;
1609
1610
let entries: Vec< & str > = page.split ( " <li><strong>" ) .skip ( 1 ) .filter ( | e | e.contains ( " /end\" " ) ) .collect ( ) ;
1611
assert_eq! ( entries.iter ( ) .filter ( | e | e.contains ( " <span class=\" tag\" >this browser</span>" ) ) .count ( ) , 1 ) ;
1612
let other = entries.iter ( ) .find ( | e | ! e.contains ( " class=\" tag\" >this browser" ) ) .unwrap ( ) ;
1613
let other: i64 = other.split ( " /settings/security/sessions/" ) .nth ( 1 ) .unwrap ( ) .split ( ' /' ) .next ( ) .unwrap ( ) .parse ( ) .unwrap ( ) ;
1614
let csrf = csrf_of ( & page) ;
1615
let r = post ( app, & format! ( " /settings/security/sessions/{other} /end" ) , Some ( & a) , & format! ( " _csrf={csrf} " ) ) .await;
1616
assert_eq! ( r.status, StatusCode:: SEE_OTHER ) ;
1617
let signed_in = | c : String| async move { get ( app, " /settings/security" , Some ( & c) ) .await.body.contains ( " SIGN OUT EVERYWHERE" ) } ;
1618
assert! ( signed_in ( a.clone ( ) ) .await, " this browser stays" ) ;
1619
assert! ( ! signed_in ( b.clone ( ) ) .await, " that browser is signed out" ) ;
1620
1621
1622
sqlx:: query( " UPDATE sessions SET seen_ms = seen_ms - 15 * 86400000" ) .execute ( & app.db) .await.unwrap ( ) ;
1623
assert! ( ! signed_in ( a.clone ( ) ) .await, " idle too long" ) ;
1624
1625
c8684d44 Andy McCall 21 days ago
1626
let c = post ( app, " /login" , None , " username=andy&password=correct-horse-battery&setup=test-setup" ) .await.cookie.unwrap ( ) ;
0024ccb1 Andy McCall 22 days ago ↶
1627
let csrf = csrf_of ( & get ( app, " /settings/security" , Some ( & c) ) .await.body) ;
1628
post ( app, " /logout" , Some ( & c) , & format! ( " _csrf={csrf} " ) ) .await;
1629
assert! ( ! signed_in ( c) .await, " the old cookie no longer works" ) ;
1630
1631
assert! ( ! signed_in ( " andy.0123456789abcdef" .into ( ) ) .await) ;
1632
}
3ff52534 Andy McCall 22 days ago ↶
1633
1634
# [ tokio ::test ]
1635
async fn an_invitation_signs_up_through_a_provider_once ( ) {
1636
hermetic ( ) ;
1637
let ( mock, _ ) = mock_provider ( ) .await;
1638
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
1639
let mut config = Config:: load( dir.path ( ) ) .unwrap ( ) ;
c8684d44 Andy McCall 21 days ago
1640
1641
config.registration.setup_code = " test-setup" .into ( ) ;
3ff52534 Andy McCall 22 days ago ↶
1642
let listener = tokio:: net:: TcpListener:: bind( " 127.0.0.1:0" ) .await.unwrap ( ) ;
1643
let port = listener.local_addr ( ) .unwrap ( ) .port ( ) ;
1644
config.server.base_url = format! ( " http://127.0.0.1:{port} " ) ;
1645
config.registration.mode = " invite" .into ( ) ;
1646
config.auth.signin_mock = Some ( mock.clone ( ) ) ;
1647
let app = oxygenhub:: build( config) .await.unwrap ( ) ;
1648
let router = oxygenhub:: router( app.clone ( ) ) ;
1649
tokio:: spawn( async move { axum:: serve( listener, router) .await.unwrap ( ) } ) ;
1650
let app = & app;
1651
let andy = register ( app, " andy" , " " ) .await;
1652
let admin = get ( app, " /admin" , Some ( & andy) ) .await.body;
1653
let csrf = csrf_of ( & admin) ;
1654
post ( app, " /admin/signin" , Some ( & andy) , & format! ( " _csrf={csrf} &provider=github&client_id=gh-cid&secret=gh-sek&enabled=1" ) ) .await;
1655
1656
1657
assert! ( ! get ( app, " /register" , None ) .await.body.contains ( " /login/github" ) ) ;
1658
let r = get ( app, " /login/github" , None ) .await;
1659
let ( cookie, state) = state_of ( & r) ;
1660
let no = send_with ( app, " GET" , & format! ( " /login/github/callback?code=c1&state={state} " ) , Some ( & cookie) , None ) .await;
1661
assert! ( no.location.as_deref ( ) .unwrap_or ( " " ) .contains ( " by%20invitation" ) , " {:?}" , no.location) ;
1662
assert_eq! ( db:: accounts:: account_count( & app.db) .await.unwrap ( ) , 1 ) ;
1663
1664
1665
1666
let r = post ( app, " /admin/invite" , Some ( & andy) , & format! ( " _csrf={csrf} " ) ) .await;
1667
let code = r.body.split ( " register?invite=" ) .nth ( 1 ) .unwrap ( ) .split ( ' <' ) .next ( ) .unwrap ( ) .trim ( ) .to_string ( ) ;
1668
let page = get ( app, & format! ( " /register?invite={code} " ) , None ) .await.body;
1669
assert! ( page.contains ( & format! ( " href=\" /login/github?invite={code} \" " ) ) & & page.contains ( " Sign up with GitHub" ) , " {page}" ) ;
1670
let r = get ( app, & format! ( " /login/github?invite={code} " ) , None ) .await;
1671
assert_eq! ( r.status, StatusCode:: SEE_OTHER ) ;
1672
let ( cookie, state) = state_of ( & r) ;
1673
let ok = send_with ( app, " GET" , & format! ( " /login/github/callback?code=c2&state={state} " ) , Some ( & cookie) , None ) .await;
1674
assert_eq! ( ok.location.as_deref ( ) , Some ( " /" ) , " {}" , ok.body) ;
1675
let octo = db:: accounts:: account_by_name( & app.db, " octocat" ) .await.unwrap ( ) .expect ( " signed up through the invitation" ) ;
1676
assert! ( ! db:: accounts:: invitation_unused( & app.db, & code) .await.unwrap ( ) , " the invitation is spent" ) ;
1677
let used_by: Option< i64 > =
3b1bc27f Andy McCall 21 days ago
1678
sqlx:: query_scalar( " SELECT used_by FROM invitations WHERE code = $1" ) .bind ( & code) .fetch_one ( & app.db) .await.unwrap ( ) ;
3ff52534 Andy McCall 22 days ago ↶
1679
assert_eq! ( used_by, Some ( octo.id) ) ;
1680
1681
1682
assert! ( ! get ( app, & format! ( " /register?invite={code} " ) , None ) .await.body.contains ( " /login/github" ) ) ;
1683
let r = get ( app, & format! ( " /login/github?invite={code} " ) , None ) .await;
1684
assert_eq! ( r.status, StatusCode:: BAD_REQUEST ) ;
1685
assert! ( r.body.contains ( " That invitation has been used or does not exist." ) , " {}" , r.body) ;
1686
assert_eq! ( get ( app, " /login/github?invite=not-a.code" , None ) .await.status, StatusCode:: BAD_REQUEST ) ;
c8684d44 Andy McCall 21 days ago
1687
}
1688
1689
1690
1691
1692
# [ tokio ::test ( flavor = " multi_thread" ) ]
1693
async fn the_first_account_needs_the_setup_code_the_hub_made ( ) {
1694
hermetic ( ) ;
1695
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
1696
let config = Config:: load( dir.path ( ) ) .unwrap ( ) ;
1697
let app = oxygenhub:: build( config) .await.unwrap ( ) ;
1698
let file = dir.path ( ) .join ( " setup-code" ) ;
1699
let code = std:: fs:: read_to_string( & file) .expect ( " an empty hub makes a setup code" ) .trim ( ) .to_string ( ) ;
1700
assert_eq! ( code.len ( ) , 24 ) ;
1701
# [ cfg ( unix ) ]
1702
{
1703
use std:: os:: unix:: fs:: PermissionsExt;
1704
assert_eq! ( std:: fs:: metadata( & file) .unwrap ( ) .permissions ( ) .mode ( ) & 0o777 , 0o600 ) ;
1705
}
1706
let page = get ( & app, " /register" , None ) .await.body;
1707
assert! ( page.contains ( " name=\" setup\" " ) & & ! page.contains ( & code) , " asks for the code, never shows it" ) ;
1708
1709
let form = | setup : & str | format! ( " username=mallory&email=m%40example.com&password=correct-horse-battery&setup={setup} " ) ;
1710
for wrong in [ " " , " 0123456789abcdef01234567" ] {
1711
let r = post ( & app, " /register" , None , & form ( wrong) ) .await;
1712
assert! ( r.cookie.is_none ( ) & & r.body.contains ( " needs the setup code" ) , " {}" , r.body) ;
1713
}
1714
assert_eq! ( db:: accounts:: account_count( & app.db) .await.unwrap ( ) , 0 ) ;
1715
1716
let r = post ( & app, " /register" , None , & form ( & code) .replace ( " mallory" , " andy" ) ) .await;
1717
assert_eq! ( r.status, StatusCode:: SEE_OTHER , " {}" , r.body) ;
1718
assert! ( db:: accounts:: account_by_name( & app.db, " andy" ) .await.unwrap ( ) .unwrap ( ) .is_admin) ;
1719
assert! ( ! file.exists ( ) , " the code is spent" ) ;
1720
1721
let r = post ( & app, " /register" , None , & form ( & code) ) .await;
1722
assert! ( r.body.contains ( " invitation" ) , " {}" , r.body) ;
3ff52534 Andy McCall 22 days ago ↶
1723
}
8a48dd83 Andy McCall 20 days ago ↶
1724
1725
1726
1727
1728
1729
# [ tokio ::test ( flavor = " multi_thread" ) ]
1730
async fn the_bell_inbox_and_dashboard_listen_on_the_viewer_s_topics ( ) {
1731
let h = hub ( ) .await;
1732
let app = & h.app;
1733
let andy = register ( app, " andy" , " " ) .await;
1734
let id = db:: accounts:: account_by_name( & app.db, " andy" ) .await.unwrap ( ) .unwrap ( ) .id;
1735
let topic = format! ( " user:{id} " ) ;
1736
let page = get ( app, " /explore" , Some ( & andy) ) .await.body;
1737
assert! ( page.contains ( & format! ( " data-live=\" {topic} \" data-fragment=\" bell\" " ) ) , " the bell on every page" ) ;
1738
let inbox = get ( app, " /notifications" , Some ( & andy) ) .await.body;
1739
assert! ( inbox.contains ( & format! ( " data-live=\" {topic} \" data-fragment=\" inbox\" " ) ) , " the inbox list" ) ;
1740
let dash = get ( app, " /" , Some ( & andy) ) .await.body;
1741
assert! ( dash.contains ( " data-fragment=\" cards\" " ) & & dash.contains ( " data-fragment=\" feed\" " ) , " {dash}" ) ;
1742
assert! ( dash.contains ( & format! ( " data-live=\" {topic} " ) ) , " the dashboard listens on the viewer" ) ;
1743
let anon = get ( app, " /explore" , None ) .await.body;
1744
assert! ( ! anon.contains ( " data-fragment=\" bell\" " ) , " nothing to hear signed out" ) ;
1745
}