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