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 21 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
450
451
let page = get ( app, " /orgs/acme/settings" , Some ( & andy) ) .await;
452
assert! ( page.body.contains ( " id=\" webhooks\" " ) & & page.body.contains ( " href=\" #webhooks\" " ) ) ;
453
let csrf = csrf_of ( & page.body) ;
454
let r = post ( app, " /orgs/acme/settings/hooks" , Some ( & andy) , & format! ( " _csrf={csrf} &url=ftp%3A%2F%2Fx&events=*" ) ) .await;
455
assert! ( r.body.contains ( " starts with http" ) , " {}" , r.body) ;
456
let r = post (
457
app,
458
" /orgs/acme/settings/hooks" ,
459
Some ( & andy) ,
460
& format! ( " _csrf={csrf} &url=https%3A%2F%2Fhooks.invalid%2Facme&secret=s&events=push" ) ,
461
)
462
.await;
463
assert! ( r.body.contains ( " Webhook added" ) ) ;
464
let hooks = db:: hooks:: hooks_for_org( & app.db, org.id) .await.unwrap ( ) ;
465
assert_eq! ( hooks.len ( ) , 1 ) ;
466
let id = hooks[ 0 ] .id;
467
assert! ( post ( app, " /orgs/acme/settings/hooks" , Some ( & andy) , & format! ( " _csrf={csrf} &id={id} &action=ping" ) )
468
.await
469
.body
470
.contains ( " Ping queued" ) ) ;
471
let deliveries = get ( app, & format! ( " /orgs/acme/settings/hooks/{id} /deliveries" ) , Some ( & andy) ) .await;
472
assert_eq! ( deliveries.status, StatusCode:: OK ) ;
473
assert! ( deliveries.body.contains ( " >ping<" ) & & deliveries.body.contains ( " /orgs/acme/settings#webhooks" ) ) ;
474
475
let repo = oxygenhub:: repos:: RepoName:: parse( " andy/demo" ) .unwrap ( ) ;
476
app.repos.create ( & repo, None ) .unwrap ( ) ;
477
let row = db:: repos:: create( & app.db, " andy" , " demo" , " " , hub_api:: Visibility:: Public) .await.unwrap ( ) ;
478
let repo_hook = db:: hooks:: create_hook( & app.db, Some ( row.id) , None , " https://hooks.invalid/repo" , " " , " *" ) .await.unwrap ( ) .id;
479
post ( app, " /orgs/acme/settings/hooks" , Some ( & andy) , & format! ( " _csrf={csrf} &id={repo_hook} &action=delete" ) ) .await;
480
assert! ( db:: hooks:: hook( & app.db, repo_hook) .await.unwrap ( ) .is_some ( ) , " not the organisation's" ) ;
481
assert_eq! ( get ( app, & format! ( " /orgs/acme/settings/hooks/{repo_hook} /deliveries" ) , Some ( & andy) ) .await.status, StatusCode:: NOT_FOUND ) ;
482
483
let rs = get ( app, " /andy/demo/settings" , Some ( & andy) ) .await;
484
assert! ( rs.body.contains ( " https://hooks.invalid/repo" ) & & rs.body.contains ( " action=\" /andy/demo/settings/hooks\" " ) ) ;
485
486
487
let work = tempfile:: tempdir( ) .unwrap ( ) ;
488
let mut client = Repo:: init( work.path ( ) ) .unwrap ( ) ;
489
client.config.set ( " remote.origin.url" , & format! ( " {} /andy/demo" , h.base) ) .unwrap ( ) ;
490
let ( token, hash) = oxygenhub:: auth:: new_token( ) ;
491
db:: accounts:: create_token( & app.db, me.id, " push" , & hash, " repo:write" , " " , None ) .await.unwrap ( ) ;
492
client.config.set ( " remote.origin.token" , & token) .unwrap ( ) ;
493
client.save_config ( ) .unwrap ( ) ;
494
write ( work.path ( ) , " a.txt" , b " a\n " ) ;
495
client.snapshot ( " t" ) .unwrap ( ) ;
496
client.commit ( " one" , & [ ] ) .unwrap ( ) ;
497
assert! ( client.push ( " origin" , false ) .unwrap ( ) .iter ( ) .all ( | r | r.ok ) ) ;
498
let storage = get ( app, " /admin/storage" , Some ( & andy) ) .await;
499
assert_eq! ( storage.status, StatusCode:: OK ) ;
500
assert! ( storage.body.contains ( " href=\" /andy/demo\" " ) ) ;
501
let loose_before = std:: fs:: read_dir( app.repos.dir ( & repo) .join ( " .oxy/objects/loose" ) ) .map ( | d | d.count ( ) ) .unwrap_or ( 0 ) ;
502
assert! ( loose_before > 0 , " the push left loose objects" ) ;
503
let r = post ( app, " /admin/storage" , Some ( & andy) , & format! ( " _csrf={} &repo=andy%2Fdemo" , csrf_of ( & storage.body) ) ) .await;
504
assert! ( r.body.contains ( " Maintained 1 repository" ) & & r.body.contains ( " loose objects packed" ) , " {}" , r.body) ;
505
let loose_after: usize = walk_files ( & app.repos.dir ( & repo) .join ( " .oxy/objects/loose" ) ) ;
506
assert_eq! ( loose_after, 0 , " packed" ) ;
507
let audit = db:: accounts:: audit_rows( & app.db, 20 ) .await.unwrap ( ) ;
508
assert! ( audit.iter ( ) .any ( | a | a.action = = " admin.gc" & & a.target = = " andy/demo" ) ) ;
509
let r = post ( app, " /admin/storage" , Some ( & andy) , & format! ( " _csrf={} &repo=nobody%2Fnone" , csrf_of ( & storage.body) ) ) .await;
510
assert! ( r.body.contains ( " No repository nobody/none" ) ) ;
511
}
512
513
fn walk_files ( dir : & Path) -> usize {
514
let Ok ( rd) = std:: fs:: read_dir( dir) else { return 0 } ;
515
rd.flatten ( ) .map ( | e | if e.path ( ) .is_dir ( ) { walk_files ( & e.path ( ) ) } else { 1 } ) .sum ( )
516
}
6a178055 Andy McCall 1 month ago ↶
517
518
519
520
521
# [ tokio ::test ( flavor = " multi_thread" ) ]
522
async fn admins_disable_enable_and_delete_accounts ( ) {
523
let h = hub ( ) .await;
524
let app = & h.app;
525
let andy = register ( app, " andy" , " " ) .await;
526
let invite = | app : Shared, andy : String| async move {
527
let csrf = csrf_of ( & get ( & app, " /admin" , Some ( & andy) ) .await.body) ;
528
let r = post ( & app, " /admin/invite" , Some ( & andy) , & format! ( " _csrf={csrf} " ) ) .await;
529
r.body.split ( " register?invite=" ) .nth ( 1 ) .unwrap ( ) .split ( ' <' ) .next ( ) .unwrap ( ) .trim ( ) .to_string ( )
530
} ;
531
let bob = register ( app, " bob" , & invite ( app.clone ( ) , andy.clone ( ) ) .await) .await;
532
let act = | who : & 'static str , action : & 'static str , confirm : & 'static str | {
533
let ( app, andy) = ( app.clone ( ) , andy.clone ( ) ) ;
534
async move {
535
let csrf = csrf_of ( & get ( & app, " /admin" , Some ( & andy) ) .await.body) ;
536
post ( & app, " /admin/account" , Some ( & andy) , & format! ( " _csrf={csrf} &username={who} &action={action} &confirm={confirm} " ) ) .await.body
537
}
538
} ;
539
let login = | user : & 'static str | {
540
let app = app.clone ( ) ;
541
async move { post ( & app, " /login" , None , & format! ( " username={user} &password=correct-horse-battery" ) ) .await }
542
} ;
543
544
545
act ( " bob" , " disable" , " " ) .await;
546
assert! ( db:: accounts:: account_by_name( & app.db, " bob" ) .await.unwrap ( ) .unwrap ( ) .disabled) ;
547
let r = login ( " bob" ) .await;
548
assert! ( r.body.contains ( " Your account has been disabled" ) , " {}" , r.body) ;
549
assert! ( r.cookie.is_none ( ) ) ;
550
assert_eq! ( get ( app, " /settings" , Some ( & bob) ) .await.status, StatusCode:: SEE_OTHER , " the session is refused" ) ;
551
assert! ( act ( " andy" , " disable" , " " ) .await.contains ( " Not on yourself" ) ) ;
552
553
act ( " bob" , " enable" , " " ) .await;
554
assert_eq! ( login ( " bob" ) .await.status, StatusCode:: SEE_OTHER ) ;
555
556
557
let bob = login ( " bob" ) .await.cookie.unwrap ( ) ;
558
let csrf = csrf_of ( & get ( app, " /new" , Some ( & bob) ) .await.body) ;
559
assert_eq! (
560
post ( app, " /new" , Some ( & bob) , & format! ( " _csrf={csrf} &owner=bob&name=keep&visibility=public" ) ) .await.status,
561
StatusCode:: SEE_OTHER
562
) ;
563
assert! ( act ( " bob" , " delete" , " bo" ) .await.contains ( " type bob to confirm" ) ) ;
564
let page = act ( " bob" , " delete" , " bob" ) .await;
565
assert! ( page.contains ( " still owns bob/keep" ) , " {page}" ) ;
566
assert! ( db:: accounts:: account_by_name( & app.db, " bob" ) .await.unwrap ( ) .is_some ( ) ) ;
567
let row = db:: repos:: get( & app.db, " bob" , " keep" ) .await.unwrap ( ) .unwrap ( ) ;
568
db:: repos:: delete( & app.db, row.id) .await.unwrap ( ) ;
569
let page = act ( " bob" , " delete" , " bob" ) .await;
570
assert! ( page.contains ( " bob deleted" ) , " {page}" ) ;
571
assert! ( db:: accounts:: account_by_name( & app.db, " bob" ) .await.unwrap ( ) .is_none ( ) ) ;
572
assert_eq! ( get ( app, " /settings" , Some ( & bob) ) .await.status, StatusCode:: SEE_OTHER ) ;
573
574
let code = invite ( app.clone ( ) , andy.clone ( ) ) .await;
575
let r = post ( app, " /register" , None , & format! ( " username=bob&email=b%40example.com&password=correct-horse-battery&invite={code} " ) ) .await;
576
assert! ( r.body.contains ( " That name is taken" ) , " {}" , r.body) ;
577
578
assert! ( act ( " andy" , " delete" , " andy" ) .await.contains ( " Not on yourself" ) ) ;
579
}
5dead1f4 Andy McCall 1 month ago ↶
580
581
582
583
# [ tokio ::test ( flavor = " multi_thread" ) ]
584
async fn admins_set_the_job_time_limits ( ) {
585
let h = hub ( ) .await;
586
let app = & h.app;
587
let andy = register ( app, " andy" , " " ) .await;
588
let page = get ( app, " /admin/runners/settings" , Some ( & andy) ) .await;
589
assert_eq! ( page.status, StatusCode:: OK ) ;
590
assert! ( page.body.contains ( " Job time limits" ) & & page.body.contains ( " value=\" 60\" " ) , " the hub.toml default shows" ) ;
591
let csrf = csrf_of ( & page.body) ;
592
let r = post ( app, " /admin/runners/settings" , Some ( & andy) , & format! ( " _csrf={csrf} &default_minutes=200&max_minutes=120&grace_minutes=5" ) )
593
.await;
594
assert! ( r.body.contains ( " cannot be longer than the maximum" ) , " {}" , r.body) ;
595
let r = post ( app, " /admin/runners/settings" , Some ( & andy) , & format! ( " _csrf={csrf} &default_minutes=90&max_minutes=240&grace_minutes=10" ) )
596
.await;
597
assert! ( r.body.contains ( " Saved." ) , " {}" , r.body) ;
598
let l = oxygenhub:: flow:: limits( app) .await;
599
assert_eq! ( ( l.default_s, l.max_s, l.grace_ms) , ( 5400 , 14400 , 600_000 ) ) ;
600
assert! ( get ( app, " /admin/runners" , Some ( & andy) ) .await.body.contains ( " href=\" /admin/runners/settings\" " ) ) ;
601
let code = {
602
let csrf = csrf_of ( & get ( app, " /admin" , Some ( & andy) ) .await.body) ;
603
let r = post ( app, " /admin/invite" , Some ( & andy) , & format! ( " _csrf={csrf} " ) ) .await;
604
r.body.split ( " register?invite=" ) .nth ( 1 ) .unwrap ( ) .split ( ' <' ) .next ( ) .unwrap ( ) .trim ( ) .to_string ( )
605
} ;
606
let bob = register ( app, " bob" , & code) .await;
607
assert_ne! ( get ( app, " /admin/runners/settings" , Some ( & bob) ) .await.status, StatusCode:: OK , " not for others" ) ;
608
}
3556d08e Andy McCall 1 month ago ↶
609
610
611
612
# [ tokio ::test ( flavor = " multi_thread" ) ]
613
async fn mail_settings_are_saved_masked_and_tested_from_the_admin_page ( ) {
614
let h = hub ( ) .await;
615
let app = & h.app;
616
let andy = register ( app, " andy" , " " ) .await;
617
let page = get ( app, " /admin" , Some ( & andy) ) .await.body;
618
assert! ( page.contains ( " Mail is off" ) , " {page}" ) ;
619
let csrf = csrf_of ( & page) ;
620
621
let outbox = tempfile:: tempdir( ) .unwrap ( ) ;
622
let r = post (
623
app,
624
" /admin/mail" ,
625
Some ( & andy) ,
626
& format! ( " _csrf={csrf} &smtp=file%3A%2F%2F{} &from=Hub+%3Chub%40example.org%3E" , outbox.path ( ) .display ( ) ) ,
627
)
628
.await;
629
assert! ( r.body.contains ( " Mail settings saved" ) & & r.body.contains ( " Mail is on" ) , " {}" , r.body) ;
630
assert! ( oxygenhub:: mail:: enabled( app) ) ;
631
let r = post ( app, " /admin/mail/test" , Some ( & andy) , & format! ( " _csrf={csrf} " ) ) .await;
632
assert! ( r.body.contains ( " Sent a test message to" ) , " {}" , r.body) ;
633
let sent: Vec< _ > = std:: fs:: read_dir( outbox.path ( ) ) .unwrap ( ) .flatten ( ) .collect ( ) ;
634
assert_eq! ( sent.len ( ) , 1 ) ;
635
let text = std:: fs:: read_to_string( sent[ 0 ] .path ( ) ) .unwrap ( ) ;
636
assert! ( text.contains ( " Subject: [" ) & & text.contains ( " Test message" ) & & text.contains ( " From: Hub <[email protected] >" ) , " {text}" ) ;
637
638
let r = post (
639
app,
640
" /admin/mail" ,
641
Some ( & andy) ,
642
& format! ( " _csrf={csrf} &smtp=smtps%3A%2F%2Fhub%3Asecret%40mail.example.org%3A465&from=Hub+%3Chub%40example.org%3E" ) ,
643
)
644
.await;
2a83f530 Andy McCall 1 month ago ↶
645
assert! ( r.body.contains ( " smtps://hub:***@mail.example.org:465" ) & & ! r.body.contains ( " hub:secret" ) , " {}" , r.body) ;
3556d08e Andy McCall 1 month ago ↶
646
let r = post (
647
app,
648
" /admin/mail" ,
649
Some ( & andy) ,
650
& format! ( " _csrf={csrf} &smtp=smtps%3A%2F%2Fhub%3A***%40mail.example.org%3A465&from=Hub+%3Chub%40example.org%3E" ) ,
651
)
652
.await;
653
assert! ( r.body.contains ( " Mail settings saved" ) , " {}" , r.body) ;
654
assert_eq! ( oxygenhub:: mail:: settings( app) .smtp, " smtps://hub:[email protected] :465" ) ;
655
656
let r = post ( app, " /admin/mail" , Some ( & andy) , & format! ( " _csrf={csrf} &smtp=mail.example.org&from=x" ) ) .await;
657
assert! ( r.body.contains ( " starts with smtp://" ) , " {}" , r.body) ;
658
let r = post ( app, " /admin/mail" , Some ( & andy) , & format! ( " _csrf={csrf} &smtp=&from=" ) ) .await;
659
assert! ( r.body.contains ( " Mail is off" ) , " {}" , r.body) ;
660
assert! ( ! oxygenhub:: mail:: enabled( app) ) ;
661
662
let r = post ( app, " /admin/mail" , None , & format! ( " _csrf={csrf} &smtp=&from=" ) ) .await;
663
assert_ne! ( r.status, StatusCode:: OK ) ;
664
}
e71846aa Andy McCall 1 month ago ↶
665
666
667
668
async fn mock_assistant ( ) -> ( String, std:: sync:: Arc< std:: sync:: Mutex< Vec< String> > > ) {
669
use std:: sync:: { Arc, Mutex} ;
670
let seen: Arc< Mutex< Vec< String> > > = Arc:: new( Mutex:: new( vec! [ ] ) ) ;
671
let s2 = seen.clone ( ) ;
672
let router = axum:: Router:: new( ) .route (
673
" /v1/chat/completions" ,
674
axum:: routing:: post( move | headers: axum:: http:: HeaderMap, body: String | {
675
let s2 = s2.clone ( ) ;
676
async move {
677
let auth = headers.get ( " authorization" ) .and_then ( | v | v.to_str ( ) .ok ( ) ) .unwrap_or ( " " ) .to_string ( ) ;
678
s2.lock ( ) .unwrap ( ) .push ( format! ( " {auth} {body} " ) ) ;
679
axum:: Json( serde_json:: json! ( { " choices" : [ { " message" : { " role" : " assistant" , " content" : " OK from mock" } } ] } ) )
680
}
681
} ) ,
682
) ;
683
let listener = tokio:: net:: TcpListener:: bind( " 127.0.0.1:0" ) .await.unwrap ( ) ;
684
let port = listener.local_addr ( ) .unwrap ( ) .port ( ) ;
685
tokio:: spawn( async move { axum:: serve( listener, router) .await.unwrap ( ) } ) ;
686
( format! ( " http://127.0.0.1:{port} /v1/chat/completions" ) , seen)
687
}
688
689
fn enc ( s : & str ) -> String {
690
s.replace ( ' %' , " %25" ) .replace ( ' :' , " %3A" ) .replace ( ' /' , " %2F" ) .replace ( ' ' , " +" ) .replace ( ' \n ' , " %0A" ) .replace ( ' &' , " %26" )
691
}
692
693
# [ tokio ::test ( flavor = " multi_thread" ) ]
694
async fn ai_assistants_are_kept_per_level_with_sealed_tokens_and_combined_downwards ( ) {
695
use oxygenhub:: assistants:: { self , Scope} ;
696
let h = hub ( ) .await;
697
let app = & h.app;
698
let andy = register ( app, " andy" , " " ) .await;
699
let ( endpoint, seen) = mock_assistant ( ) .await;
700
701
702
let page = get ( app, " /admin" , Some ( & andy) ) .await.body;
703
assert! ( page.contains ( " AI assistants" ) & & page.contains ( " Add an assistant" ) , " {page}" ) ;
704
let csrf = csrf_of ( & page) ;
705
let add = | name : & str , extra : & str | {
706
format! (
707
" _csrf={csrf} &action=add&name={name} &endpoint={} &api=chat-completions&model=claude-opus-5-5&token=sk-test-secret&enabled=1&budget=50000{extra} " ,
708
enc ( & endpoint)
709
)
710
} ;
711
let r = post ( app, " /admin/assistants" , Some ( & andy) , & add ( " Claude" , " " ) ) .await;
206c1fc1 Andy McCall 1 month ago ↶
712
assert! ( r.body.contains ( " Claude added and answered: OK from mock" ) & & r.body.contains ( " token set" ) , " {}" , r.body) ;
e71846aa Andy McCall 1 month ago ↶
713
assert! ( ! r.body.contains ( " sk-test-secret" ) , " the token never comes back" ) ;
714
let site = assistants:: list( & app.db, Scope:: Site) .await.unwrap ( ) ;
715
assert_eq! ( site.len ( ) , 1 ) ;
716
let claude = & site[ 0 ] ;
717
assert! ( ! String :: from_utf8_lossy( & claude.token) .contains ( " sk-test" ) , " sealed at rest" ) ;
718
assert_eq! ( app.assistant_key.open ( & claude.token) .as_deref ( ) , Some ( " sk-test-secret" ) ) ;
719
720
let r = post ( app, " /admin/assistants" , Some ( & andy) , & add ( " claude" , " " ) ) .await;
721
assert! ( r.body.contains ( " already an assistant called" ) , " {}" , r.body) ;
722
let r = post (
723
app,
724
" /admin/assistants" ,
725
Some ( & andy) ,
726
& format! ( " _csrf={csrf} &action=add&name=Bad&endpoint=ftp%3A%2F%2Fx&api=chat-completions&model=m" ) ,
727
)
728
.await;
729
assert! ( r.body.contains ( " starting with https://" ) , " {}" , r.body) ;
730
731
732
let r = post ( app, " /admin/assistants" , Some ( & andy) , & format! ( " _csrf={csrf} &action=test&id={} " , claude.id) ) .await;
733
assert! ( r.body.contains ( " Claude answered: OK from mock" ) , " {}" , r.body) ;
734
{
735
let calls = seen.lock ( ) .unwrap ( ) ;
206c1fc1 Andy McCall 1 month ago ↶
736
assert_eq! ( calls.len ( ) , 2 , " once on add, once on test" ) ;
e71846aa Andy McCall 1 month ago ↶
737
assert! ( calls[ 0 ] .starts_with ( " Bearer sk-test-secret " ) , " {}" , calls[ 0 ] ) ;
738
assert! ( calls[ 0 ] .contains ( " \" model\" :\" claude-opus-5-5\" " ) & & calls[ 0 ] .contains ( " Reply with the single word OK" ) , " {}" , calls[ 0 ] ) ;
739
}
740
741
let r = post (
742
app,
743
" /admin/assistants" ,
744
Some ( & andy) ,
745
& 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) ) ,
746
)
747
.await;
748
assert! ( r.body.contains ( " Claude updated." ) & & r.body.contains ( " context 60000 characters" ) , " {}" , r.body) ;
749
assert_eq! (
750
app.assistant_key.open ( & assistants:: get( & app.db, claude.id) .await.unwrap ( ) .unwrap ( ) .token) .as_deref ( ) ,
751
Some ( " sk-test-secret" )
752
) ;
753
754
let r =
755
post ( app, " /admin/assistants" , Some ( & andy) , & format! ( " _csrf={csrf} &action=prompt&prompt={} " , enc ( " Review for correctness first." ) ) )
756
.await;
757
assert! ( r.body.contains ( " Prompt saved." ) & & r.body.contains ( " Review for correctness first." ) , " {}" , r.body) ;
758
759
760
let r = post ( app, " /orgs/new" , Some ( & andy) , & format! ( " _csrf={csrf} &name=acme&display_name=Acme" ) ) .await;
761
assert_eq! ( r.status, StatusCode:: SEE_OTHER , " {}" , r.body) ;
762
let r = post ( app, " /new" , Some ( & andy) , & format! ( " _csrf={csrf} &owner=acme&name=plans&visibility=public" ) ) .await;
763
assert_eq! ( r.status, StatusCode:: SEE_OTHER , " {}" , r.body) ;
764
let org_page = get ( app, " /orgs/acme/settings" , Some ( & andy) ) .await.body;
765
assert! ( org_page.contains ( " Inherited" ) & & org_page.contains ( " from the site" ) & & org_page.contains ( " None of its own" ) , " {org_page}" ) ;
766
assert! ( org_page.contains ( " From the site" ) & & org_page.contains ( " Review for correctness first." ) , " {org_page}" ) ;
767
let repo = db:: repos:: get( & app.db, " acme" , " plans" ) .await.unwrap ( ) .unwrap ( ) ;
768
let on = assistants:: enabled_for_repo( & app.db, & repo) .await.unwrap ( ) ;
769
assert_eq! ( on.iter ( ) .map ( | a | a.name.as_str ( ) ) .collect:: < Vec< _ > > ( ) , [ " Claude" ] ) ;
770
771
772
773
let r = post (
774
app,
775
" /orgs/acme/settings/assistants" ,
776
Some ( & andy) ,
777
& format! ( " _csrf={csrf} &action=prompt&prompt={} " , enc ( " We write 6502 assembly." ) ) ,
778
)
779
.await;
780
assert! ( r.body.contains ( " Prompt saved." ) , " {}" , r.body) ;
781
let r = post ( app, " /orgs/acme/settings/assistants" , Some ( & andy) , & add ( " DeepSeek" , " " ) ) .await;
206c1fc1 Andy McCall 1 month ago ↶
782
assert! ( r.body.contains ( " DeepSeek added and answered" ) , " {}" , r.body) ;
e71846aa Andy McCall 1 month ago ↶
783
let prompt = assistants:: prompt_for_repo( & app.db, & repo) .await.unwrap ( ) ;
784
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}" ) ;
785
let repo_page = get ( app, " /acme/plans/settings" , Some ( & andy) ) .await.body;
786
assert! ( repo_page.contains ( " from the acme organisation" ) & & repo_page.contains ( " From the acme organisation" ) , " {repo_page}" ) ;
787
let on = assistants:: enabled_for_repo( & app.db, & repo) .await.unwrap ( ) ;
788
assert_eq! ( on.iter ( ) .map ( | a | a.name.as_str ( ) ) .collect:: < Vec< _ > > ( ) , [ " Claude" , " DeepSeek" ] ) ;
789
790
791
792
793
let r = post ( app, " /admin/assistants" , Some ( & andy) , & format! ( " _csrf={csrf} &action=toggle&id={} " , claude.id) ) .await;
794
assert! ( r.body.contains ( " Claude is off." ) , " {}" , r.body) ;
795
let r = post ( app, " /acme/plans/settings/assistants" , Some ( & andy) , & add ( " Claude" , " " ) ) .await;
206c1fc1 Andy McCall 1 month ago ↶
796
assert! ( r.body.contains ( " Claude added and answered" ) , " {}" , r.body) ;
e71846aa Andy McCall 1 month ago ↶
797
let on = assistants:: enabled_for_repo( & app.db, & repo) .await.unwrap ( ) ;
798
assert_eq! ( on.iter ( ) .map ( | a | a.name.as_str ( ) ) .collect:: < Vec< _ > > ( ) , [ " DeepSeek" ] ) ;
799
let repo_page = get ( app, " /acme/plans/settings" , Some ( & andy) ) .await.body;
800
assert! ( repo_page.contains ( " off above" ) , " {repo_page}" ) ;
801
post ( app, " /admin/assistants" , Some ( & andy) , & format! ( " _csrf={csrf} &action=toggle&id={} " , claude.id) ) .await;
802
let on = assistants:: enabled_for_repo( & app.db, & repo) .await.unwrap ( ) ;
803
assert_eq! ( on.iter ( ) .map ( | a | ( a.name.as_str ( ) , a.scope.as_str ( ) ) ) .collect:: < Vec< _ > > ( ) , [ ( " DeepSeek" , " org" ) , ( " Claude" , " repo" ) ] ) ;
804
805
806
let invite = {
807
let r = post ( app, " /admin/invite" , Some ( & andy) , & format! ( " _csrf={csrf} " ) ) .await;
808
let i = r.body.find ( " invite=" ) .map ( | i | i + 7 ) .expect ( " an invitation" ) ;
809
r.body[ i.. ] .chars ( ) .take_while ( | c | c.is_ascii_alphanumeric ( ) ) .collect:: < String> ( )
810
} ;
811
let bob = register ( app, " bob" , & invite) .await;
812
assert_eq! (
813
post ( app, " /admin/assistants" , Some ( & bob) , & format! ( " _csrf={csrf} &action=prompt&prompt=x" ) ) .await.status,
814
StatusCode:: NOT_FOUND
815
) ;
816
assert_eq! (
817
post ( app, " /orgs/acme/settings/assistants" , Some ( & bob) , & format! ( " _csrf={csrf} &action=prompt&prompt=x" ) ) .await.status,
818
StatusCode:: NOT_FOUND
819
) ;
820
assert_eq! (
821
post ( app, " /acme/plans/settings/assistants" , Some ( & bob) , & format! ( " _csrf={csrf} &action=prompt&prompt=x" ) ) .await.status,
822
StatusCode:: NOT_FOUND
823
) ;
824
825
let r = post ( app, " /acme/plans/settings/delete" , Some ( & andy) , & format! ( " _csrf={csrf} &confirm=acme%2Fplans" ) ) .await;
826
assert! ( r.status = = StatusCode:: SEE_OTHER | | r.status = = StatusCode:: OK , " {} {}" , r.status, r.body) ;
827
assert! ( assistants:: list( & app.db, Scope:: Repo( repo.id) ) .await.unwrap ( ) .is_empty ( ) ) ;
828
}
89e89836 Andy McCall 1 month ago ↶
829
830
# [ tokio ::test ( flavor = " multi_thread" ) ]
831
async fn accounts_elsewhere_are_checked_and_shown_on_the_profile ( ) {
832
let h = hub ( ) .await;
833
let app = & h.app;
834
let andy = register ( app, " andy" , " " ) .await;
835
let page = get ( app, " /settings" , Some ( & andy) ) .await.body;
836
let csrf = csrf_of ( & page) ;
837
let base = format! ( " _csrf={csrf} &display_name=Andy&email=andy%40example.com&bio=&website=&location=" ) ;
838
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;
839
assert! (
840
r.body.contains ( " value=\" andy.bsky.social\" " )
841
& & r.body.contains ( " value=\" @[email protected] \" " )
842
& & r.body.contains ( " value=\" andymccall\" " ) ,
843
" {}" ,
844
r.body
845
) ;
846
let profile = get ( app, " /andy" , None ) .await.body;
847
assert! ( profile.contains ( " href=\" https://bsky.app/profile/andy.bsky.social\" " ) & & profile.contains ( " @andy.bsky.social" ) , " {profile}" ) ;
848
assert! ( profile.contains ( " href=\" https://fosstodon.org/@andy\" " ) & & profile.contains ( " rel=\" nofollow noopener me\" " ) , " {profile}" ) ;
849
assert! ( profile.contains ( " href=\" https://github.com/andymccall\" " ) & & profile.contains ( " title=\" GitHub\" " ) , " {profile}" ) ;
850
851
let r = post ( app, " /settings" , Some ( & andy) , & format! ( " {base} &bluesky=not+a+handle&mastodon=&github=" ) ) .await;
852
assert! ( r.body.contains ( " not a Bluesky handle" ) , " {}" , r.body) ;
853
assert! ( get ( app, " /andy" , None ) .await.body.contains ( " andy.bsky.social" ) ) ;
854
855
post ( app, " /settings" , Some ( & andy) , & format! ( " {base} &bluesky=&mastodon=&github=" ) ) .await;
856
assert! ( ! get ( app, " /andy" , None ) .await.body.contains ( " class=\" social\" " ) ) ;
83940d53 Andy McCall 1 month ago ↶
857
}
858
859
860
async fn mock_provider ( ) -> ( String, std:: sync:: Arc< std:: sync:: Mutex< Vec< String> > > ) {
861
use std:: sync:: { Arc, Mutex} ;
862
let seen: Arc< Mutex< Vec< String> > > = Arc:: new( Mutex:: new( vec! [ ] ) ) ;
863
let s1 = seen.clone ( ) ;
864
let s2 = seen.clone ( ) ;
865
let router = axum:: Router:: new( )
866
.route (
867
" /github/token" ,
868
axum:: routing:: post( move | body: String | {
869
let s1 = s1.clone ( ) ;
870
async move {
871
s1.lock ( ) .unwrap ( ) .push ( format! ( " github token {body} " ) ) ;
872
axum:: Json( serde_json:: json! ( { " access_token" : " gh-token" , " token_type" : " bearer" } ) )
873
}
874
} ) ,
875
)
876
.route (
877
" /github/userinfo" ,
878
axum:: routing:: get( | headers : axum:: http:: HeaderMap| async move {
879
assert_eq! ( headers.get ( " authorization" ) .and_then ( | v | v.to_str ( ) .ok ( ) ) , Some ( " Bearer gh-token" ) ) ;
880
axum:: Json( serde_json:: json! ( { " id" : 583231 , " login" : " octocat" , " name" : " The Octocat" , " email" : null } ) )
881
} ) ,
882
)
883
.route (
884
" /github/userinfo/emails" ,
885
axum:: routing:: get( | | async {
886
axum:: Json( serde_json:: json! ( [
887
{ " email" : " [email protected] " , " primary" : false , " verified" : false } ,
888
{ " email" : " [email protected] " , " primary" : true , " verified" : true }
889
] ) )
890
} ) ,
891
)
892
.route (
893
" /google/token" ,
894
axum:: routing:: post( move | body: String | {
895
let s2 = s2.clone ( ) ;
896
async move {
897
s2.lock ( ) .unwrap ( ) .push ( format! ( " google token {body} " ) ) ;
898
axum:: Json( serde_json:: json! ( { " access_token" : " g-token" , " id_token" : " x" } ) )
899
}
900
} ) ,
901
)
902
.route (
810896d4 Andy McCall 22 days ago ↶
903
" /gitlab/token" ,
904
axum:: routing:: post( | | async { axum:: Json( serde_json:: json! ( { " access_token" : " gl-token" , " token_type" : " Bearer" } ) ) } ) ,
905
)
906
.route (
907
" /gitlab/userinfo" ,
908
axum:: routing:: get( | headers : axum:: http:: HeaderMap| async move {
909
assert_eq! ( headers.get ( " authorization" ) .and_then ( | v | v.to_str ( ) .ok ( ) ) , Some ( " Bearer gl-token" ) ) ;
910
axum:: Json( serde_json:: json! ( { " sub" : " 1234567" , " nickname" : " tanuki" , " name" : " The Tanuki" , " email" : " [email protected] " , " email_verified" : true } ) )
911
} ) ,
912
)
913
.route (
83940d53 Andy McCall 1 month ago ↶
914
" /google/userinfo" ,
915
axum:: routing:: get( | | async {
916
axum:: Json( serde_json:: json! ( { " sub" : " 1076915035000615071" , " email" : " [email protected] " , " email_verified" : true , " name" : " Andy McCall" } ) )
917
} ) ,
918
) ;
919
let listener = tokio:: net:: TcpListener:: bind( " 127.0.0.1:0" ) .await.unwrap ( ) ;
920
let port = listener.local_addr ( ) .unwrap ( ) .port ( ) ;
921
tokio:: spawn( async move { axum:: serve( listener, router) .await.unwrap ( ) } ) ;
922
( format! ( " http://127.0.0.1:{port} " ) , seen)
923
}
924
925
fn state_of ( res : & Res) -> ( String, String) {
926
let cookie = res.raw_cookies.iter ( ) .find ( | c | c.starts_with ( " oxyhub_signin=" ) ) .expect ( " state cookie" ) .clone ( ) ;
927
let value = cookie.trim_start_matches ( " oxyhub_signin=" ) .split ( ' ;' ) .next ( ) .unwrap ( ) .to_string ( ) ;
928
( cookie, value)
929
}
930
931
# [ tokio ::test ( flavor = " multi_thread" ) ]
932
async fn people_sign_in_with_github_or_google_once_an_admin_sets_it_up ( ) {
933
hermetic ( ) ;
934
let ( mock, seen) = mock_provider ( ) .await;
935
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
936
let mut config = Config:: load( dir.path ( ) ) .unwrap ( ) ;
937
let listener = tokio:: net:: TcpListener:: bind( " 127.0.0.1:0" ) .await.unwrap ( ) ;
938
let port = listener.local_addr ( ) .unwrap ( ) .port ( ) ;
939
config.server.base_url = format! ( " http://127.0.0.1:{port} " ) ;
940
config.registration.mode = " open" .into ( ) ;
941
config.auth.signin_mock = Some ( mock.clone ( ) ) ;
942
let app = oxygenhub:: build( config) .await.unwrap ( ) ;
943
let router = oxygenhub:: router( app.clone ( ) ) ;
944
tokio:: spawn( async move { axum:: serve( listener, router) .await.unwrap ( ) } ) ;
945
let app = & app;
946
let andy = register ( app, " andy" , " " ) .await;
947
let andy_row = db:: accounts:: account_by_name( & app.db, " andy" ) .await.unwrap ( ) .unwrap ( ) ;
948
db:: accounts:: set_email_verified( & app.db, andy_row.id, true ) .await.unwrap ( ) ;
949
950
951
assert! ( ! get ( app, " /login" , None ) .await.body.contains ( " /login/github" ) ) ;
952
let admin = get ( app, " /admin" , Some ( & andy) ) .await.body;
953
assert! ( admin.contains ( " Sign in with" ) & & admin.contains ( & format! ( " http://127.0.0.1:{port} /login/github/callback" ) ) , " {admin}" ) ;
954
let csrf = csrf_of ( & admin) ;
955
let r =
956
post ( app, " /admin/signin" , Some ( & andy) , & format! ( " _csrf={csrf} &provider=github&client_id=gh-cid&secret=gh-sek&enabled=1" ) ) .await;
957
assert! ( r.body.contains ( " Signing in with GitHub is on." ) & & ! r.body.contains ( " gh-sek" ) , " {}" , r.body) ;
958
let r = post ( app, " /admin/signin" , Some ( & andy) , & format! ( " _csrf={csrf} &provider=google&client_id=g-cid&secret=g-sek&enabled=1" ) ) .await;
959
assert! ( r.body.contains ( " Signing in with Google is on." ) , " {}" , r.body) ;
960
let login = get ( app, " /login" , None ) .await.body;
961
assert! ( login.contains ( " href=\" /login/github\" " ) & & login.contains ( " href=\" /login/google\" " ) , " {login}" ) ;
962
963
964
let r = get ( app, " /login/github" , None ) .await;
965
assert_eq! ( r.status, StatusCode:: SEE_OTHER ) ;
966
let to = r.location.clone ( ) .unwrap ( ) ;
967
assert! ( to.starts_with ( & format! ( " {mock} /github/authorize?client_id=gh-cid&redirect_uri=" ) ) & & to.contains ( " &state=" ) , " {to}" ) ;
968
let ( cookie, state) = state_of ( & r) ;
969
let bad = send_with ( app, " GET" , " /login/github/callback?code=c1&state=wrong" , Some ( & cookie) , None ) .await;
970
assert! ( bad.location.as_deref ( ) .unwrap_or ( " " ) .starts_with ( " /login?error=" ) , " {:?}" , bad.location) ;
971
let ok = send_with ( app, " GET" , & format! ( " /login/github/callback?code=c1&state={state} " ) , Some ( & cookie) , None ) .await;
972
assert_eq! ( ok.status, StatusCode:: SEE_OTHER , " {}" , ok.body) ;
973
assert_eq! ( ok.location.as_deref ( ) , Some ( " /" ) ) ;
974
let octo_cookie = ok.cookie.clone ( ) .expect ( " signed in" ) ;
975
let octo = db:: accounts:: account_by_name( & app.db, " octocat" ) .await.unwrap ( ) .expect ( " account made from the GitHub login" ) ;
976
assert! (
977
( octo.email.as_str ( ) , octo.email_verified, octo.display_name.as_str ( ) ) = = ( " [email protected] " , true , " The Octocat" ) ,
978
" {octo:?}"
979
) ;
980
assert! ( seen.lock ( ) .unwrap ( ) .iter ( ) .any ( | s | s.contains ( " github token" ) & & s.contains ( " code=c1" ) & & s.contains ( " client_secret=gh-sek" ) ) ) ;
981
assert! ( get ( app, " /settings" , Some ( & octo_cookie) ) .await.body.contains ( " octocat" ) ) ;
982
983
let r = get ( app, " /login/github" , None ) .await;
984
let ( cookie, state) = state_of ( & r) ;
985
let ok = send_with ( app, " GET" , & format! ( " /login/github/callback?code=c2&state={state} " ) , Some ( & cookie) , None ) .await;
986
assert_eq! ( ok.location.as_deref ( ) , Some ( " /" ) ) ;
987
assert_eq! ( db:: accounts:: account_count( & app.db) .await.unwrap ( ) , 2 ) ;
810896d4 Andy McCall 22 days ago ↶
988
989
990
991
let r = post (
992
app,
993
" /admin/signin" ,
994
Some ( & andy) ,
995
& format! ( " _csrf={csrf} &provider=gitlab&client_id=gl-cid&secret=gl-sek&enabled=1&base=http%3A%2F%2Fgitlab.example.org" ) ,
996
)
997
.await;
998
assert! ( r.body.contains ( " is an https:// address" ) , " {}" , r.body) ;
999
let r = post (
1000
app,
1001
" /admin/signin" ,
1002
Some ( & andy) ,
1003
& format! ( " _csrf={csrf} &provider=gitlab&client_id=gl-cid&secret=gl-sek&enabled=1&base=https%3A%2F%2Fgitlab.example.org%2F" ) ,
1004
)
1005
.await;
1006
assert! ( r.body.contains ( " Signing in with GitLab is on." ) & & r.body.contains ( " value=\" https://gitlab.example.org\" " ) , " {}" , r.body) ;
1007
let r = post (
1008
app,
1009
" /admin/signin" ,
1010
Some ( & andy) ,
1011
& format! ( " _csrf={csrf} &provider=github&client_id=gh-cid&enabled=1&base=https%3A%2F%2Fx.org" ) ,
1012
)
1013
.await;
1014
assert! ( r.body.contains ( " GitHub has no address to set." ) , " {}" , r.body) ;
1015
let login = get ( app, " /login" , None ) .await.body;
1016
assert! ( login.contains ( " signin-btn gitlab" ) & & login.contains ( " Sign in with GitLab" ) , " {login}" ) ;
1017
let r = get ( app, " /login/gitlab" , None ) .await;
1018
assert! ( r.location.clone ( ) .unwrap ( ) .contains ( " scope=openid%20profile%20email" ) , " {:?}" , r.location) ;
1019
let ( cookie, state) = state_of ( & r) ;
1020
let ok = send_with ( app, " GET" , & format! ( " /login/gitlab/callback?code=c9&state={state} " ) , Some ( & cookie) , None ) .await;
1021
assert_eq! ( ok.location.as_deref ( ) , Some ( " /" ) , " {}" , ok.body) ;
1022
let tanuki = db:: accounts:: account_by_name( & app.db, " tanuki" ) .await.unwrap ( ) .expect ( " account made from the GitLab username" ) ;
1023
assert! ( ( tanuki.email.as_str ( ) , tanuki.email_verified) = = ( " [email protected] " , true ) , " {tanuki:?}" ) ;
1024
assert_eq! ( db:: accounts:: account_count( & app.db) .await.unwrap ( ) , 3 ) ;
83940d53 Andy McCall 1 month ago ↶
1025
1026
1027
let r = get ( app, " /login/google" , None ) .await;
1028
assert! ( r.location.clone ( ) .unwrap ( ) .contains ( " prompt=select_account" ) ) ;
1029
let ( cookie, state) = state_of ( & r) ;
1030
let ok = send_with ( app, " GET" , & format! ( " /login/google/callback?code=c3&state={state} " ) , Some ( & cookie) , None ) .await;
1031
assert_eq! ( ok.location.as_deref ( ) , Some ( " /" ) , " {}" , ok.body) ;
1032
let as_andy = ok.cookie.clone ( ) .unwrap ( ) ;
1033
let sec = get ( app, " /settings/security" , Some ( & as_andy) ) .await.body;
1034
assert! (
1035
sec.contains ( " Connected accounts" )
1036
& & sec.contains ( " Google: <strong>andy</strong>" )
1037
& & sec.contains ( " GitHub: <a href=\" /settings/security/connect/github\" >connect</a>" ) ,
1038
" {sec}"
1039
) ;
810896d4 Andy McCall 22 days ago ↶
1040
assert_eq! ( db:: accounts:: account_count( & app.db) .await.unwrap ( ) , 3 , " no fourth account" ) ;
83940d53 Andy McCall 1 month ago ↶
1041
1042
let csrf_s = csrf_of ( & sec) ;
1043
let r = post ( app, " /settings/security/disconnect/google" , Some ( & as_andy) , & format! ( " _csrf={csrf_s} " ) ) .await;
1044
assert! ( r.location.as_deref ( ) .unwrap_or ( " " ) .contains ( " notice=Google%20disconnected" ) , " {:?}" , r.location) ;
1045
assert! ( ! get ( app, " /settings/security" , Some ( & as_andy) ) .await.body.contains ( " Google: <strong>andy</strong>" ) ) ;
1046
let r = get ( app, " /settings/security/connect/google" , Some ( & as_andy) ) .await;
1047
assert_eq! ( r.status, StatusCode:: SEE_OTHER ) ;
1048
let ( cookie, state) = state_of ( & r) ;
1049
let both = format! ( " {cookie} ; oxyhub={as_andy} " ) ;
1050
let ok = send_with ( app, " GET" , & format! ( " /login/google/callback?code=c4&state={state} " ) , Some ( & both) , None ) .await;
1051
assert! ( ok.location.as_deref ( ) .unwrap_or ( " " ) .contains ( " notice=Google%20connected%20as%20andy" ) , " {:?} {}" , ok.location, ok.body) ;
1052
1053
1054
db:: accounts:: set_setting( & app.db, " registration_mode" , " closed" ) .await.unwrap ( ) ;
1055
sqlx:: query( " DELETE FROM account_logins WHERE provider = 'github'" ) .execute ( & app.db) .await.unwrap ( ) ;
1056
sqlx:: query( " UPDATE accounts SET email_verified = 0 WHERE username = 'octocat'" ) .execute ( & app.db) .await.unwrap ( ) ;
1057
let r = get ( app, " /login/github" , None ) .await;
1058
let ( cookie, state) = state_of ( & r) ;
1059
let no = send_with ( app, " GET" , & format! ( " /login/github/callback?code=c5&state={state} " ) , Some ( & cookie) , None ) .await;
1060
assert! ( no.location.as_deref ( ) .unwrap_or ( " " ) .contains ( " registration%20is%20closed" ) , " {:?}" , no.location) ;
1061
assert! ( no.cookie.is_none ( ) ) ;
89e89836 Andy McCall 1 month ago ↶
1062
}
e8e7158b Andy McCall 1 month ago ↶
1063
1064
# [ tokio ::test ( flavor = " multi_thread" ) ]
1065
async fn administration_is_sectioned_and_its_audit_log_pages ( ) {
1066
let h = hub ( ) .await;
1067
let app = & h.app;
1068
let andy = register ( app, " andy" , " " ) .await;
1069
let andy_row = db:: accounts:: account_by_name( & app.db, " andy" ) .await.unwrap ( ) .unwrap ( ) ;
1070
for i in 0 .. 60 {
1071
db:: accounts:: audit( & app.db, Some ( & andy_row) , " test.event" , & format! ( " t{i} " ) , " " ) .await.unwrap ( ) ;
1072
}
1073
let page = get ( app, " /admin" , Some ( & andy) ) .await.body;
1074
for id in [ " accounts" , " registration" , " organisations" , " signin" , " mail" , " variables" , " secrets" , " assistants" , " audit" ] {
1075
assert! ( page.contains ( & format! ( " href=\" #{id} \" " ) ) & & page.contains ( & format! ( " id=\" {id} \" " ) ) , " section {id}: {page}" ) ;
1076
}
1077
assert! ( page.contains ( " class=\" section-nav\" " ) ) ;
1078
assert! ( page.contains ( " >t59<" ) & & ! page.contains ( " >t5<" ) , " the newest page only" ) ;
1079
let i = page.find ( " audit_before=" ) .expect ( " an older link" ) + " audit_before=" .len ( ) ;
1080
let before: String = page[ i.. ] .chars ( ) .take_while ( | c | c.is_ascii_digit ( ) ) .collect ( ) ;
1081
let older = get ( app, & format! ( " /admin?audit_before={before} " ) , Some ( & andy) ) .await.body;
1082
assert! ( older.contains ( " >t5<" ) & & ! older.contains ( " >t59<" ) , " the next page: {older}" ) ;
1083
}
155cab14 Andy McCall 1 month ago ↶
1084
1085
# [ tokio ::test ( flavor = " multi_thread" ) ]
1086
async fn adding_an_assistant_offers_providers_and_only_models_the_endpoint_lists ( ) {
1087
let h = hub ( ) .await;
1088
let app = & h.app;
1089
let andy = register ( app, " andy" , " " ) .await;
1090
let router = axum:: Router:: new( )
1091
.route (
1092
" /v1/models" ,
1093
axum:: routing:: get( | headers : axum:: http:: HeaderMap| async move {
1094
assert_eq! ( headers.get ( " authorization" ) .and_then ( | v | v.to_str ( ) .ok ( ) ) , Some ( " Bearer sk-m" ) ) ;
1095
axum:: Json( serde_json:: json! ( { " data" : [
1096
{ " id" : " models/gemini-3-pro" } , { " id" : " gemini-3-flash" } , { " id" : " text-embedding-004" }
1097
] } ) )
1098
} ) ,
1099
)
1100
.route (
1101
" /v1/chat/completions" ,
1102
axum:: routing:: post( | | async { axum:: Json( serde_json:: json! ( { " choices" : [ { " message" : { " content" : " OK" } } ] } ) ) } ) ,
1103
) ;
1104
let listener = tokio:: net:: TcpListener:: bind( " 127.0.0.1:0" ) .await.unwrap ( ) ;
1105
let port = listener.local_addr ( ) .unwrap ( ) .port ( ) ;
1106
tokio:: spawn( async move { axum:: serve( listener, router) .await.unwrap ( ) } ) ;
1107
let ep = format! ( " http%3A%2F%2F127.0.0.1%3A{port} %2Fv1%2Fchat%2Fcompletions" ) ;
1108
1109
let page = get ( app, " /admin" , Some ( & andy) ) .await.body;
1110
assert! ( page.contains ( " data-preset-select" ) & & page.contains ( " Google Gemini" ) & & page.contains ( " Other (enter the endpoint)" ) , " {page}" ) ;
1111
assert! ( page.contains ( " LIST MODELS" ) ) ;
1112
let csrf = csrf_of ( & page) ;
1113
1114
let r =
1115
post ( app, " /admin/assistants/models" , Some ( & andy) , & format! ( " _csrf={csrf} &endpoint={ep} &api=chat-completions&token=sk-m" ) ) .await;
1116
let v: serde_json:: Value = serde_json:: from_str( & r.body) .unwrap ( ) ;
1117
assert_eq! ( v[ " models" ] , serde_json:: json! ( [ " gemini-3-flash" , " gemini-3-pro" ] ) , " {}" , r.body) ;
1118
1119
let r = post (
1120
app,
1121
" /admin/assistants" ,
1122
Some ( & andy) ,
1123
& format! ( " _csrf={csrf} &action=add&preset=gemini&endpoint={ep} &model=gemini-2.5-pro&token=sk-m&enabled=1" ) ,
1124
)
1125
.await;
1126
assert! ( r.body.contains ( " gemini-2.5-pro is not a model this endpoint offers" ) & & r.body.contains ( " gemini-3-pro" ) , " {}" , r.body) ;
1127
1128
let r = post (
1129
app,
1130
" /admin/assistants" ,
1131
Some ( & andy) ,
1132
& format! ( " _csrf={csrf} &action=add&preset=gemini&endpoint={ep} &model=gemini-3-pro&token=sk-m&enabled=1" ) ,
1133
)
1134
.await;
1135
assert! ( r.body.contains ( " Gemini added and answered: OK" ) , " {}" , r.body) ;
1136
let a = & oxygenhub:: assistants:: list( & app.db, oxygenhub:: levels:: Scope:: Site) .await.unwrap ( ) [ 0 ] ;
1137
assert_eq! ( ( a.name.as_str ( ) , a.api.as_str ( ) , a.model.as_str ( ) ) , ( " Gemini" , " chat-completions" , " gemini-3-pro" ) ) ;
1138
1139
let r =
1140
post ( app, " /admin/assistants/models" , Some ( & andy) , & format! ( " _csrf={csrf} &id={} &endpoint={ep} &api=chat-completions" , a.id) ) .await;
1141
assert! ( r.body.contains ( " gemini-3-flash" ) , " {}" , r.body) ;
1142
}
2a0c09c0 Andy McCall 21 days ago ↶
1143
1144
1145
1146
1147
1148
# [ tokio ::test ( flavor = " multi_thread" ) ]
1149
async fn a_profile_shows_the_year_as_a_signal ( ) {
1150
let h = hub ( ) .await;
1151
let app = & h.app;
1152
register ( app, " andy" , " " ) .await;
1153
let andy = db:: accounts:: account_by_name( & app.db, " andy" ) .await.unwrap ( ) .unwrap ( ) ;
1154
let game = db:: repos:: create( & app.db, " andy" , " game" , " " , hub_api:: Visibility:: Public) .await.unwrap ( ) ;
1155
let secret = db:: repos:: create( & app.db, " andy" , " secret" , " " , hub_api:: Visibility:: Private) .await.unwrap ( ) ;
1156
let now = db:: now_ms( ) ;
1157
for ( repo, ago_days, changes, reason, via) in [
1158
( game.id, 3 , 5 , " " , " " ) ,
1159
( game.id, 3 , 2 , " " , " Claude" ) ,
1160
( game.id, 40 , 4 , " " , " " ) ,
1161
( game.id, 2 , 9 , " landed #1 (web)" , " " ) ,
1162
( secret.id, 1 , 50 , " " , " " ) ,
1163
] {
1164
sqlx:: query( " INSERT INTO pushes (repo_id, at_ms, reference, ok, reason, changes, account_id, pusher, via) VALUES (?, ?, 'main', 1, ?, ?, ?, 'andy', ?)" )
1165
.bind ( repo)
1166
.bind ( now - ago_days * 86_400_000 )
1167
.bind ( reason)
1168
.bind ( changes)
1169
.bind ( andy.id)
1170
.bind ( via)
1171
.execute ( & app.db)
1172
.await
1173
.unwrap ( ) ;
1174
}
1175
sqlx:: query( " INSERT INTO releases (repo_id, tag, title, author_id, author, created_ms) VALUES (?, 'v1.0', 'One', ?, 'andy', ?)" )
1176
.bind ( game.id)
1177
.bind ( andy.id)
1178
.bind ( now - 3 * 86_400_000 )
1179
.execute ( & app.db)
1180
.await
1181
.unwrap ( ) ;
1182
1183
let page = get ( app, " /andy" , None ) .await.body;
1184
let start = page.find ( " id=\" pulse-data\" >" ) .expect ( " the pulse is on the profile" ) + " id=\" pulse-data\" >" .len ( ) ;
1185
let json: serde_json:: Value = serde_json:: from_str( & page[ start.. start + page[ start.. ] .find ( " </script>" ) .unwrap ( ) ] ) .unwrap ( ) ;
1186
assert_eq! ( json[ " repos" ] , serde_json:: json! ( [ " andy/game" ] ) ) ;
1187
let days = json[ " days" ] .as_array ( ) .unwrap ( ) ;
1188
assert_eq! ( days.len ( ) , 365 ) ;
1189
let total: i64 = days.iter ( ) .map ( | d | d[ 0 ] .as_i64 ( ) .unwrap ( ) ) .sum ( ) ;
1190
let via: i64 = days.iter ( ) .map ( | d | d[ 1 ] .as_i64 ( ) .unwrap ( ) ) .sum ( ) ;
1191
assert_eq! ( ( total, via) , ( 11 , 2 ) , " 5 + 2 + 4 changes, 2 via an agent; the landing and the private push left out" ) ;
1192
assert_eq! ( days[ 361 ] , serde_json:: json! ( [ 7 , 2 , [ [ 0 , 7 ] ] ] ) , " three days ago" ) ;
1193
assert_eq! ( json[ " peaks" ] [ 0 ] , serde_json:: json! ( [ 361 , " game v1.0" ] ) ) ;
1194
assert! (
1195
page.contains ( " data-total=\" 11\" " ) & & page.find ( " pulse-box" ) .unwrap ( ) < page.find ( " <h2>Repositories</h2>" ) .unwrap ( ) ,
1196
" above the repositories"
1197
) ;
1198
}
9a8e3b44 Andy McCall 21 days ago ↶
1199
1200
1201
1202
1203
1204
# [ tokio ::test ( flavor = " multi_thread" ) ]
1205
async fn an_https_site_takes_nothing_over_http ( ) {
1206
hermetic ( ) ;
1207
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
1208
let mut config = Config:: load( dir.path ( ) ) .unwrap ( ) ;
1209
config.server.base_url = " https://hub.example.org" .into ( ) ;
1210
config.registration.mode = " open" .into ( ) ;
1211
let app = oxygenhub:: build( config) .await.unwrap ( ) ;
1212
let call = | method : & 'static str , path : & 'static str , header : Option< ( & 'static str , & 'static str ) > , body : Option< & 'static str > | {
1213
let app = app.clone ( ) ;
1214
async move {
1215
let mut req = Request:: builder( ) .method ( method) .uri ( path) ;
1216
if let Some ( ( k, v) ) = header {
1217
req = req.header ( k, v) ;
1218
}
1219
if body.is_some ( ) {
1220
req = req.header ( header:: CONTENT_TYPE , " application/x-www-form-urlencoded" ) ;
1221
}
1222
oxygenhub:: router( app) .oneshot ( req.body ( body.map ( Body:: from) .unwrap_or_else ( Body:: empty) ) .unwrap ( ) ) .await.unwrap ( )
1223
}
1224
} ;
1225
1226
let r = call ( " GET" , " /login?next=%2Fx" , Some ( ( " x-forwarded-proto" , " http" ) ) , None ) .await;
1227
assert! ( r.status ( ) .is_redirection ( ) , " {}" , r.status ( ) ) ;
1228
assert_eq! ( r.headers ( ) .get ( header:: LOCATION ) .unwrap ( ) , " https://hub.example.org/login?next=%2Fx" ) ;
1229
1230
let r = call ( " POST" , " /login" , Some ( ( " cf-visitor" , r # "{"scheme":"http"}"# ) ) , Some ( " username=a&password=b" ) ) .await;
1231
assert_eq! ( r.status ( ) , StatusCode:: BAD_REQUEST ) ;
1232
1233
assert_eq! ( call ( " GET" , " /login" , Some ( ( " x-forwarded-proto" , " https" ) ) , None ) .await.status ( ) , StatusCode:: OK ) ;
1234
assert_eq! ( call ( " GET" , " /login" , None , None ) .await.status ( ) , StatusCode:: OK ) ;
1235
1236
let r = call (
1237
" POST" ,
1238
" /register" ,
1239
Some ( ( " x-forwarded-proto" , " https" ) ) ,
1240
Some ( " username=andy&email=a%40example.org&password=correct-horse-battery" ) ,
1241
)
1242
.await;
1243
let cookie = r.headers ( ) .get ( header:: SET_COOKIE ) .expect ( " signed in" ) .to_str ( ) .unwrap ( ) ;
1244
assert! ( cookie.contains ( " ; Secure" ) & & cookie.contains ( " HttpOnly" ) , " {cookie}" ) ;
1245
}
aa0bfbd1 Andy McCall 21 days ago ↶
1246
1247
# [ tokio ::test ]
1248
async fn guessing_passwords_is_slowed_per_account_and_per_address ( ) {
1249
hermetic ( ) ;
1250
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
1251
let mut config = Config:: load( dir.path ( ) ) .unwrap ( ) ;
1252
config.server.behind_proxy = true ;
1253
config.registration.mode = " open" .into ( ) ;
1254
let app = oxygenhub:: build( config) .await.unwrap ( ) ;
1255
let from = | addr : & 'static str , form : String| {
1256
let app = app.clone ( ) ;
1257
async move {
1258
let req = Request:: builder( )
1259
.method ( " POST" )
1260
.uri ( " /login" )
1261
.header ( " x-forwarded-for" , addr)
1262
.header ( header:: CONTENT_TYPE , " application/x-www-form-urlencoded" ) ;
1263
let res = oxygenhub:: router( app) .oneshot ( req.body ( Body:: from( form) ) .unwrap ( ) ) .await.unwrap ( ) ;
1264
let status = res.status ( ) ;
1265
( status, String :: from_utf8_lossy( & res.into_body ( ) .collect ( ) .await.unwrap ( ) .to_bytes ( ) ) .into_owned ( ) )
1266
}
1267
} ;
1268
register ( & app, " andy" , " " ) .await;
1269
let right = | | " username=andy&password=correct-horse-battery" .to_string ( ) ;
1270
1271
1272
1273
for i in 0 .. 6 {
1274
let ( _ , body) = from ( " 198.51.100.1" , " username=andy&password=wrong" .into ( ) ) .await;
1275
assert! ( body.contains ( " Wrong username or password." ) , " try {i}" ) ;
1276
}
1277
let ( status, body) = from ( " 198.51.100.2" , right ( ) ) .await;
1278
assert_eq! ( status, StatusCode:: OK , " not signed in" ) ;
1279
assert! ( body.contains ( " Too many tries: try again in" ) , " {body}" ) ;
1280
let audit = db:: accounts:: audit_rows( & app.db, 50 ) .await.unwrap ( ) ;
1281
assert! ( audit.iter ( ) .any ( | r | r.action = = " login.throttled" & & r.target = = " andy" & & r.detail.contains ( " 198.51.100.1" ) ) ) ;
1282
app.throttle.lock ( ) .unwrap ( ) .cleared ( & oxygenhub:: throttle:: Key:: account( " login" , " andy" ) ) ;
1283
1284
1285
1286
for i in 0 .. 21 {
1287
let ( _ , body) = from ( " 203.0.113.7" , format! ( " username=nobody{i} &password=wrong" ) ) .await;
1288
assert! ( body.contains ( " Wrong username or password." ) , " try {i}" ) ;
1289
}
1290
let ( _ , body) = from ( " 203.0.113.7" , right ( ) ) .await;
1291
assert! ( body.contains ( " Too many tries" ) , " {body}" ) ;
1292
let ( status, _ ) = from ( " 198.51.100.3" , right ( ) ) .await;
1293
assert_eq! ( status, StatusCode:: SEE_OTHER , " another address signs in" ) ;
1294
}
d74ce22f Andy McCall 21 days ago ↶
1295
1296
# [ tokio ::test ]
1297
async fn every_page_carries_the_security_headers_and_violations_are_reported ( ) {
1298
let h = hub ( ) .await;
1299
let res = oxygenhub:: router( h.app.clone ( ) ) .oneshot ( Request:: get( " /login" ) .body ( Body:: empty( ) ) .unwrap ( ) ) .await.unwrap ( ) ;
1300
let hd = res.headers ( ) ;
1301
assert_eq! ( hd[ header:: X_CONTENT_TYPE_OPTIONS ] , " nosniff" ) ;
1302
assert_eq! ( hd[ header:: REFERRER_POLICY ] , " strict-origin-when-cross-origin" ) ;
1303
assert_eq! ( hd[ header:: X_FRAME_OPTIONS ] , " DENY" ) ;
1304
assert! ( hd[ " permissions-policy" ] .to_str ( ) .unwrap ( ) .contains ( " camera=()" ) ) ;
1305
1306
let csp = hd[ header:: CONTENT_SECURITY_POLICY_REPORT_ONLY ] .to_str ( ) .unwrap ( ) ;
1307
for part in [
1308
" default-src 'self'" ,
1309
" object-src 'none'" ,
1310
" frame-ancestors 'none'" ,
1311
" form-action 'self'" ,
1312
" 'wasm-unsafe-eval'" ,
1313
" report-uri /csp-report" ,
1314
] {
1315
assert! ( csp.contains ( part) , " {part} in {csp}" ) ;
1316
}
1317
assert! ( hd.get ( header:: CONTENT_SECURITY_POLICY ) .is_none ( ) & & hd.get ( header:: STRICT_TRANSPORT_SECURITY ) .is_none ( ) ) ;
1318
1319
let res = oxygenhub:: router( h.app.clone ( ) ) .oneshot ( Request:: get( " /no/such/page" ) .body ( Body:: empty( ) ) .unwrap ( ) ) .await.unwrap ( ) ;
1320
assert_eq! ( res.headers ( ) [ header:: X_CONTENT_TYPE_OPTIONS ] , " nosniff" ) ;
1321
1322
let report =
1323
r # "{"csp-report":{"document-uri":"http://127.0.0.1/login","violated-directive":"script-src-elem","blocked-uri":"inline"}}"# ;
1324
let req = Request:: post( " /csp-report" ) .header ( header:: CONTENT_TYPE , " application/csp-report" ) .body ( Body:: from( report) ) .unwrap ( ) ;
1325
assert_eq! ( oxygenhub:: router( h.app.clone ( ) ) .oneshot ( req) .await.unwrap ( ) .status ( ) , StatusCode:: NO_CONTENT ) ;
1326
let big = Request:: post( " /csp-report" ) .body ( Body:: from( vec! [ b ' ' ; 64 * 1024 ] ) ) .unwrap ( ) ;
1327
assert_eq! ( oxygenhub:: router( h.app.clone ( ) ) .oneshot ( big) .await.unwrap ( ) .status ( ) , StatusCode:: PAYLOAD_TOO_LARGE ) ;
1328
}
3dd6582d Andy McCall 21 days ago ↶
1329
1330
# [ tokio ::test ]
1331
async fn security_txt_names_the_contact_an_administrator_sets ( ) {
1332
let h = hub ( ) .await;
1333
let app = & h.app;
1334
assert_eq! ( get ( app, " /.well-known/security.txt" , None ) .await.status, StatusCode:: NOT_FOUND , " no contact, no file" ) ;
1335
let andy = register ( app, " andy" , " " ) .await;
1336
let page = get ( app, " /admin" , Some ( & andy) ) .await.body;
1337
assert! ( page.contains ( " No contact yet" ) , " the panel" ) ;
1338
let csrf = csrf_of ( & page) ;
1339
let set = | contact : & 'static str , policy : & 'static str | {
1340
let ( andy, csrf) = ( andy.clone ( ) , csrf.clone ( ) ) ;
1341
async move { post ( app, " /admin/security" , Some ( & andy) , & format! ( " _csrf={csrf} &contact={contact} &policy={policy} " ) ) .await }
1342
} ;
1343
assert_eq! ( set ( " javascript%3Aalert(1)" , " " ) .await.status, StatusCode:: BAD_REQUEST ) ;
1344
assert_eq! ( set ( " sec%40example.org" , " http%3A%2F%2Fexample.org" ) .await.status, StatusCode:: BAD_REQUEST , " policy over https only" ) ;
1345
let r = set ( " sec%40example.org" , " https%3A%2F%2Fexample.org%2Fpolicy" ) .await;
1346
assert! ( r.body.contains ( " Security contact saved" ) , " {}" , r.body) ;
1347
for path in [ " /.well-known/security.txt" , " /security.txt" ] {
1348
let r = get ( app, path, None ) .await;
1349
assert_eq! ( r.status, StatusCode:: OK ) ;
1350
assert! ( r.body.starts_with ( " Contact: mailto:[email protected] \n Expires: 20" ) , " {}" , r.body) ;
1351
assert! ( r.body.contains ( " Policy: https://example.org/policy\n " ) & & r.body.contains ( " /.well-known/security.txt\n " ) , " {}" , r.body) ;
1352
}
1353
1354
let r = post ( app, " /admin/invite" , Some ( & andy) , & format! ( " _csrf={csrf} " ) ) .await;
1355
let code = r.body.split ( " register?invite=" ) .nth ( 1 ) .unwrap ( ) .split ( ' <' ) .next ( ) .unwrap ( ) .trim ( ) .to_string ( ) ;
1356
let bob = register ( app, " bob" , & code) .await;
1357
let r = post ( app, " /admin/security" , Some ( & bob) , & format! ( " _csrf={csrf} &contact=x%40evil.example" ) ) .await;
1358
assert_ne! ( r.status, StatusCode:: OK ) ;
1359
1360
set ( " " , " " ) .await;
1361
assert_eq! ( get ( app, " /security.txt" , None ) .await.status, StatusCode:: NOT_FOUND ) ;
1362
}