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