-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintegrations_github.rs
More file actions
639 lines (584 loc) · 21.8 KB
/
integrations_github.rs
File metadata and controls
639 lines (584 loc) · 21.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
//! GitHub App install flow (Phase 1): routes, state, and persistence.
use async_trait::async_trait;
use axum::body::Body;
use boardtask::app::config::Config;
use boardtask::app::integrations::github::{
GitHubConnectError, GitHubConnectionAdapter, GitHubInstallAdapter, GitHubSetupCallback,
};
use boardtask::app::AppState;
use hmac::{Hmac, Mac};
use sha2::Sha256;
use std::sync::Arc;
use tower::ServiceExt;
mod common;
use crate::common::*;
/// Login only (user must already exist). `authenticated_cookie` always inserts a new user.
async fn login_cookie(app: &axum::Router, email: &str, password: &str) -> String {
let login_body = login_form_body(email, password);
let login_request = http::Request::builder()
.method("POST")
.uri("/login")
.header("content-type", "application/x-www-form-urlencoded")
.body(Body::from(login_body))
.unwrap();
let login_response = app.clone().oneshot(login_request).await.unwrap();
assert_eq!(login_response.status(), http::StatusCode::SEE_OTHER);
let set_cookie = login_response
.headers()
.get("set-cookie")
.unwrap()
.to_str()
.unwrap();
let session_id = extract_session_id_from_cookie(set_cookie).unwrap();
format!("session_id={}", session_id)
}
fn github_app_state(pool: sqlx::SqlitePool) -> AppState {
let mut config = Config::for_tests();
config.github_webhook_secret = Some("0123456789abcdef0123456789abcdef".to_string());
config.github_app_slug = Some("boardtask-test-app".to_string());
let github_connection = GitHubConnectionAdapter::try_from_config(&config)
.map(|a| Arc::new(a) as Arc<dyn GitHubInstallAdapter + Send + Sync>);
AppState {
db: pool,
mail: Arc::new(boardtask::app::mail::ConsoleMailer),
config,
resend_cooldown: Arc::new(std::sync::RwLock::new(std::collections::HashMap::new())),
github_connection,
}
}
async fn pool_with_seeds() -> sqlx::SqlitePool {
let pool = test_pool().await;
boardtask::seeds::run_seeds(&pool).await.unwrap();
pool
}
fn github_router(pool: sqlx::SqlitePool) -> axum::Router {
let state = github_app_state(pool);
boardtask::create_router(state)
}
#[test]
fn github_adapter_can_be_enabled_without_webhook_secret() {
let mut config = Config::for_tests();
config.github_app_slug = Some("boardtask-test-app".to_string());
let adapter = GitHubConnectionAdapter::try_from_config(&config);
assert!(adapter.is_some());
}
/// Test double: does not require GitHub install URL env; only used for install-redirect coverage.
struct StubGitHubInstallAdapter;
#[async_trait]
impl GitHubInstallAdapter for StubGitHubInstallAdapter {
async fn build_install_redirect_url(
&self,
state_token: &str,
) -> Result<String, GitHubConnectError> {
Ok(format!(
"https://stub.example/install?state={}",
urlencoding::encode(state_token)
))
}
async fn parse_setup_callback(
&self,
_raw_query: &str,
) -> Result<GitHubSetupCallback, GitHubConnectError> {
Err(GitHubConnectError::InvalidCallback)
}
}
#[tokio::test]
async fn github_install_redirect_uses_stub_adapter_url() {
let pool = pool_with_seeds().await;
let config = Config::for_tests();
// No slug/url: real adapter would be off; stub proves handler uses the port.
let state = AppState {
db: pool.clone(),
mail: Arc::new(boardtask::app::mail::ConsoleMailer),
config,
resend_cooldown: Arc::new(std::sync::RwLock::new(std::collections::HashMap::new())),
github_connection: Some(
Arc::new(StubGitHubInstallAdapter) as Arc<dyn GitHubInstallAdapter + Send + Sync>
),
};
let app = boardtask::create_router(state);
let request = http::Request::builder()
.method("GET")
.uri("/app/integrations/github/install")
.header("cookie", &cookie)
.body(Body::empty())
.unwrap();
let response = app.oneshot(request).await.unwrap();
assert_eq!(response.status(), http::StatusCode::TEMPORARY_REDIRECT);
let loc = response
.headers()
.get("location")
.unwrap()
.to_str()
.unwrap();
assert!(loc.starts_with("https://stub.example/install?state="));
}
#[tokio::test]
async fn github_install_redirect_forbidden_for_member() {
let pool = pool_with_seeds().await;
let app = github_router(pool.clone());
let user_id = user_id_from_cookie(&pool, &cookie).await;
let user = boardtask::app::db::users::find_by_id(
&pool,
&boardtask::app::domain::UserId::from_string(&user_id).unwrap(),
)
.await
.unwrap()
.unwrap();
let org_id = user.organization_id.clone();
let team = boardtask::app::db::teams::find_default_for_org(
&pool,
&boardtask::app::domain::OrganizationId::from_string(&org_id).unwrap(),
)
.await
.unwrap()
.unwrap();
let request = http::Request::builder()
.method("GET")
.uri("/app/integrations/github/install")
.header("cookie", &member_cookie)
.body(Body::empty())
.unwrap();
let response = app.oneshot(request).await.unwrap();
assert_eq!(response.status(), http::StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn github_install_redirect_owner_goes_to_github() {
let pool = pool_with_seeds().await;
let app = github_router(pool.clone());
let request = http::Request::builder()
.method("GET")
.uri("/app/integrations/github/install")
.header("cookie", &cookie)
.body(Body::empty())
.unwrap();
let response = app.oneshot(request).await.unwrap();
assert_eq!(response.status(), http::StatusCode::TEMPORARY_REDIRECT);
let loc = response
.headers()
.get("location")
.unwrap()
.to_str()
.unwrap();
assert!(loc.starts_with("https://github.com/apps/boardtask-test-app/installations/new"));
assert!(loc.contains("state="));
}
#[tokio::test]
async fn github_callback_bad_state_redirects_with_error() {
let pool = pool_with_seeds().await;
let app = github_router(pool.clone());
let request = http::Request::builder()
.method("GET")
.uri("/app/integrations/github/callback?installation_id=999&setup_action=install&state=not-valid")
.header("cookie", &cookie)
.body(Body::empty())
.unwrap();
let response = app.oneshot(request).await.unwrap();
assert_eq!(response.status(), http::StatusCode::SEE_OTHER);
let loc = response
.headers()
.get("location")
.unwrap()
.to_str()
.unwrap();
assert!(loc.contains("/app/integrations"));
assert!(loc.contains("error="));
assert!(loc.contains("github_state_invalid"));
}
#[tokio::test]
async fn github_callback_missing_installation_id_redirects_with_generic_error() {
let pool = pool_with_seeds().await;
let app = github_router(pool.clone());
let user_id = user_id_from_cookie(&pool, &cookie).await;
let user = boardtask::app::db::users::find_by_id(
&pool,
&boardtask::app::domain::UserId::from_string(&user_id).unwrap(),
)
.await
.unwrap()
.unwrap();
let org_id = user.organization_id.clone();
let state_token = boardtask::app::db::github_install_pending::create(&pool, &org_id)
.await
.unwrap();
let qs = format!(
"setup_action=install&state={}",
urlencoding::encode(&state_token)
);
let uri = format!("/app/integrations/github/callback?{}", qs);
let request = http::Request::builder()
.method("GET")
.uri(&uri)
.header("cookie", &cookie)
.body(Body::empty())
.unwrap();
let response = app.oneshot(request).await.unwrap();
assert_eq!(response.status(), http::StatusCode::SEE_OTHER);
let loc = response
.headers()
.get("location")
.unwrap()
.to_str()
.unwrap();
assert!(loc.starts_with("/app/integrations?"));
assert!(loc.contains("error="));
assert!(loc.contains("github_connect_failed"));
}
#[tokio::test]
async fn github_callback_missing_state_redirects_with_error() {
let pool = pool_with_seeds().await;
let app = github_router(pool.clone());
let request = http::Request::builder()
.method("GET")
.uri("/app/integrations/github/callback?installation_id=999&setup_action=install")
.header("cookie", &cookie)
.body(Body::empty())
.unwrap();
let response = app.oneshot(request).await.unwrap();
assert_eq!(response.status(), http::StatusCode::SEE_OTHER);
let loc = response
.headers()
.get("location")
.unwrap()
.to_str()
.unwrap();
assert!(loc.contains("github_missing_state"));
}
#[tokio::test]
async fn github_callback_org_mismatch_keeps_pending_state() {
let pool = pool_with_seeds().await;
let app = github_router(pool.clone());
let org1_user_id = user_id_from_cookie(&pool, &org1_cookie).await;
let org1_user = boardtask::app::db::users::find_by_id(
&pool,
&boardtask::app::domain::UserId::from_string(&org1_user_id).unwrap(),
)
.await
.unwrap()
.unwrap();
let org1_id = org1_user.organization_id.clone();
let state_token = boardtask::app::db::github_install_pending::create(&pool, &org1_id)
.await
.unwrap();
let uri = format!(
"/app/integrations/github/callback?installation_id=999&setup_action=install&state={}",
urlencoding::encode(&state_token)
);
let request = http::Request::builder()
.method("GET")
.uri(&uri)
.header("cookie", &org2_cookie)
.body(Body::empty())
.unwrap();
let response = app.oneshot(request).await.unwrap();
assert_eq!(response.status(), http::StatusCode::SEE_OTHER);
let loc = response
.headers()
.get("location")
.unwrap()
.to_str()
.unwrap();
assert!(loc.contains("github_org_mismatch"));
let pending_org = boardtask::app::db::github_install_pending::find_valid(&pool, &state_token)
.await
.unwrap();
assert_eq!(pending_org.as_deref(), Some(org1_id.as_str()));
}
#[tokio::test]
async fn github_callback_success_persists_installation_and_enables_integration() {
let pool = pool_with_seeds().await;
let app = github_router(pool.clone());
let user_id = user_id_from_cookie(&pool, &cookie).await;
let user = boardtask::app::db::users::find_by_id(
&pool,
&boardtask::app::domain::UserId::from_string(&user_id).unwrap(),
)
.await
.unwrap()
.unwrap();
let org_id = user.organization_id.clone();
let state_token = boardtask::app::db::github_install_pending::create(&pool, &org_id)
.await
.unwrap();
let qs = format!(
"installation_id=424242&setup_action=install&state={}",
urlencoding::encode(&state_token)
);
let uri = format!("/app/integrations/github/callback?{}", qs);
let request = http::Request::builder()
.method("GET")
.uri(&uri)
.header("cookie", &cookie)
.body(Body::empty())
.unwrap();
let response = app.clone().oneshot(request).await.unwrap();
assert_eq!(response.status(), http::StatusCode::SEE_OTHER);
let loc = response
.headers()
.get("location")
.unwrap()
.to_str()
.unwrap();
assert!(loc.contains("success=github_connected"));
let row = boardtask::app::db::github_installations::find_by_org(&pool, &org_id)
.await
.unwrap()
.expect("installation row");
assert_eq!(row.github_installation_id, 424242);
let gh = boardtask::app::db::integrations::find_by_slug(&pool, "github")
.await
.unwrap()
.expect("github integration");
let links = boardtask::app::db::integrations::find_org_integrations(&pool, &org_id)
.await
.unwrap();
let enabled = links
.iter()
.find(|l| l.integration_id == gh.id)
.expect("org integration link");
assert_eq!(enabled.enabled, 1);
}
#[tokio::test]
async fn github_installations_upsert_for_org() {
let pool = test_pool().await;
let org_id = boardtask::app::domain::OrganizationId::new();
boardtask::app::db::organizations::insert(
&pool,
&boardtask::app::db::organizations::NewOrganization {
id: org_id.clone(),
name: "Gh Org".to_string(),
},
)
.await
.unwrap();
let org_str = org_id.as_str();
boardtask::app::db::github_installations::upsert_for_org(&pool, &org_str, 111, None, None)
.await
.unwrap();
let first = boardtask::app::db::github_installations::find_by_org(&pool, &org_str)
.await
.unwrap()
.unwrap();
assert_eq!(first.github_installation_id, 111);
boardtask::app::db::github_installations::upsert_for_org(
&pool,
&org_str,
222,
Some("acme"),
Some("Organization"),
)
.await
.unwrap();
let second = boardtask::app::db::github_installations::find_by_org(&pool, &org_str)
.await
.unwrap()
.unwrap();
assert_eq!(second.github_installation_id, 222);
assert_eq!(second.account_login.as_deref(), Some("acme"));
assert_eq!(second.account_type.as_deref(), Some("Organization"));
}
fn github_signature(secret: &[u8], body: &[u8]) -> String {
type HmacSha256 = Hmac<Sha256>;
let mut mac = HmacSha256::new_from_slice(secret).expect("hmac key");
mac.update(body);
format!("sha256={}", hex::encode(mac.finalize().into_bytes()))
}
#[tokio::test]
async fn github_webhook_rejects_invalid_signature() {
let pool = pool_with_seeds().await;
let app = github_router(pool.clone());
let body = br#"{"action":"opened","installation":{"id":1},"repository":{"id":1,"full_name":"a/b"},"pull_request":{"id":1,"number":1,"html_url":"http://x","title":"t","body":null,"state":"open","draft":false,"merged":false,"head":{"ref":"h","sha":"s"},"base":{"ref":"main"},"user":{"login":"u"}}}"#;
let request = http::Request::builder()
.method("POST")
.uri(boardtask::app::config::Config::github_webhook_path())
.header("x-github-event", "pull_request")
.header("x-hub-signature-256", "sha256=deadbeef")
.body(Body::from(body.as_slice()))
.unwrap();
let response = app.oneshot(request).await.unwrap();
assert_eq!(response.status(), http::StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn github_webhook_missing_secret_returns_503() {
let pool = pool_with_seeds().await;
let mut config = Config::for_tests();
config.github_webhook_secret = None;
config.github_app_slug = Some("boardtask-test-app".to_string());
let github_connection = GitHubConnectionAdapter::try_from_config(&config)
.map(|a| Arc::new(a) as Arc<dyn GitHubInstallAdapter + Send + Sync>);
let state = AppState {
db: pool,
mail: Arc::new(boardtask::app::mail::ConsoleMailer),
config,
resend_cooldown: Arc::new(std::sync::RwLock::new(std::collections::HashMap::new())),
github_connection,
};
let app = boardtask::create_router(state);
let body = br#"{}"#;
let request = http::Request::builder()
.method("POST")
.uri(boardtask::app::config::Config::github_webhook_path())
.header("x-github-event", "pull_request")
.body(Body::from(body.as_slice()))
.unwrap();
let response = app.oneshot(request).await.unwrap();
assert_eq!(response.status(), http::StatusCode::SERVICE_UNAVAILABLE);
}
#[tokio::test]
async fn github_webhook_non_pull_request_event_noop_200() {
let pool = pool_with_seeds().await;
let app = github_router(pool.clone());
let secret = b"0123456789abcdef0123456789abcdef";
let body = br#"{"zen":"speak easy"}"#;
let sig = github_signature(secret, body);
let request = http::Request::builder()
.method("POST")
.uri(boardtask::app::config::Config::github_webhook_path())
.header("x-github-event", "ping")
.header("x-hub-signature-256", &sig)
.body(Body::from(body.as_slice()))
.unwrap();
let response = app.oneshot(request).await.unwrap();
assert_eq!(response.status(), http::StatusCode::OK);
}
#[tokio::test]
async fn github_webhook_pull_request_opened_persists_and_links_nodes() {
let pool = pool_with_seeds().await;
let app = github_router(pool.clone());
let user_id = user_id_from_cookie(&pool, &cookie).await;
let user = boardtask::app::db::users::find_by_id(
&pool,
&boardtask::app::domain::UserId::from_string(&user_id).unwrap(),
)
.await
.unwrap()
.unwrap();
let org_id = user.organization_id.clone();
let org = boardtask::app::domain::OrganizationId::from_string(&org_id).unwrap();
let team = boardtask::app::db::teams::find_default_for_org(&pool, &org)
.await
.unwrap()
.unwrap();
boardtask::app::db::teams::set_short_name(&pool, &team.id, "AJJ")
.await
.unwrap();
let project_id = ulid::Ulid::new().to_string();
boardtask::app::db::projects::insert(
&pool,
&boardtask::app::db::projects::NewProject {
id: project_id.clone(),
title: "P".to_string(),
user_id: user_id.clone(),
organization_id: org_id.clone(),
team_id: team.id.clone(),
due_utc: None,
due_timezone: None,
},
)
.await
.unwrap();
let n1 = ulid::Ulid::new().to_string();
let n2 = ulid::Ulid::new().to_string();
boardtask::app::db::nodes::insert(
&pool,
&boardtask::app::db::nodes::NewNode {
id: n1.clone(),
project_id: project_id.clone(),
organization_id: org_id.clone(),
public_ref: "AJJ-1".to_string(),
node_type_id: "01JNODETYPE00000000TASK000".to_string(),
status_id: "01JSTATUS00000000TODO0000".to_string(),
title: "A".to_string(),
description: None,
estimated_minutes: None,
slot_id: None,
assigned_user_id: None,
due_utc: None,
due_timezone: None,
priority: "medium".to_string(),
},
)
.await
.unwrap();
boardtask::app::db::nodes::insert(
&pool,
&boardtask::app::db::nodes::NewNode {
id: n2.clone(),
project_id: project_id.clone(),
organization_id: org_id.clone(),
public_ref: "AJJ-2".to_string(),
node_type_id: "01JNODETYPE00000000TASK000".to_string(),
status_id: "01JSTATUS00000000TODO0000".to_string(),
title: "B".to_string(),
description: None,
estimated_minutes: None,
slot_id: None,
assigned_user_id: None,
due_utc: None,
due_timezone: None,
priority: "medium".to_string(),
},
)
.await
.unwrap();
boardtask::app::db::github_installations::upsert_for_org(&pool, &org_id, 424242, None, None)
.await
.unwrap();
let payload = serde_json::json!({
"action": "opened",
"installation": { "id": 424242 },
"repository": { "id": 99, "full_name": "acme/repo" },
"pull_request": {
"id": 1001,
"number": 7,
"html_url": "https://github.com/acme/repo/pull/7",
"title": "Fix AJJ-1",
"body": "See AJJ-2",
"state": "open",
"draft": false,
"merged": false,
"head": { "ref": "feat", "sha": "abc123" },
"base": { "ref": "main" },
"user": { "login": "alice" },
"created_at": "2020-01-01T00:00:00Z"
}
});
let body = serde_json::to_vec(&payload).unwrap();
let secret = b"0123456789abcdef0123456789abcdef";
let sig = github_signature(secret, &body);
let request = http::Request::builder()
.method("POST")
.uri(boardtask::app::config::Config::github_webhook_path())
.header("x-github-event", "pull_request")
.header("x-hub-signature-256", &sig)
.body(Body::from(body))
.unwrap();
let response = app.oneshot(request).await.unwrap();
assert_eq!(response.status(), http::StatusCode::OK);
let row_id =
boardtask::app::db::github_pull_requests::find_id_by_org_repo(&pool, &org_id, 99, 7)
.await
.unwrap()
.expect("pr row");
let row = boardtask::app::db::github_pull_requests::find_by_id(&pool, &row_id)
.await
.unwrap()
.expect("pr row by id");
assert_eq!(row.title, "Fix AJJ-1");
let count = boardtask::app::db::github_pull_requests::count_node_links_for_pr(&pool, &row_id)
.await
.unwrap();
assert_eq!(count, 2);
}