/
latest.rs
1864 lines (1593 loc) · 61.4 KB
/
latest.rs
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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::io::Cursor;
use std::net::SocketAddr;
use std::ops::Sub;
use std::sync::Arc;
use std::time::Duration;
use axum::body::Body;
use axum::extract::{Extension, Path, Query, State};
use axum::handler::Handler;
use axum::http::Request;
use axum::middleware::{self, from_extractor};
use axum::response::Response;
use axum::routing::{any, delete, get, post};
use axum::{Json as AxumJson, Router};
use fqdn::FQDN;
use futures::Future;
use http::header::AUTHORIZATION;
use http::{request, HeaderValue, Method, StatusCode, Uri};
use instant_acme::{AccountCredentials, ChallengeType};
use serde::{Deserialize, Serialize};
use shuttle_backends::auth::{AuthPublicKey, JwtAuthenticationLayer, ScopedLayer};
use shuttle_backends::axum::CustomErrorPath;
use shuttle_backends::cache::CacheManager;
use shuttle_backends::client::permit::Team;
use shuttle_backends::metrics::{Metrics, TraceLayer};
use shuttle_backends::project_name::ProjectName;
use shuttle_backends::request_span;
use shuttle_backends::ClaimExt;
use shuttle_common::claims::{Claim, Scope, EXP_MINUTES};
use shuttle_common::models::error::{
ApiError, InvalidCustomDomain, InvalidTeamName, ProjectCorrupted, ProjectHasBuildingDeployment,
ProjectHasResources, ProjectHasRunningDeployment,
};
use shuttle_common::models::{admin::ProjectResponse, project, stats};
use shuttle_common::models::{service, team};
use shuttle_common::{deployment, VersionInfo};
use shuttle_proto::provisioner::provisioner_client::ProvisionerClient;
use shuttle_proto::provisioner::Ping;
use tokio::sync::mpsc::Sender;
use tokio::sync::{Mutex, MutexGuard};
use tower::ServiceBuilder;
use tower_http::cors::{AllowOrigin, CorsLayer};
use tracing::{debug, error, field, info, instrument, trace, warn, Span};
use ttl_cache::TtlCache;
use ulid::Ulid;
use uuid::Uuid;
use x509_parser::nom::AsBytes;
use x509_parser::parse_x509_certificate;
use x509_parser::pem::parse_x509_pem;
use x509_parser::time::ASN1Time;
use crate::acme::{AccountWrapper, AcmeClient, CustomDomain};
use crate::api::tracing::project_name_tracing_layer;
use crate::auth::ScopedUser;
use crate::service::{ContainerSettings, GatewayService};
use crate::task::{self, BoxedTask};
use crate::tls::{GatewayCertResolver, RENEWAL_VALIDITY_THRESHOLD_IN_DAYS};
use crate::worker::WORKER_QUEUE_SIZE;
use crate::{DockerContext, AUTH_CLIENT};
use super::auth_layer::ShuttleAuthLayer;
use super::project_caller::ProjectCaller;
pub const SVC_DEGRADED_THRESHOLD: usize = 128;
pub const SHUTTLE_GATEWAY_VARIANT: &str = "shuttle-gateway";
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ComponentStatus {
Healthy,
Degraded,
Unhealthy,
}
#[derive(Serialize, Deserialize)]
pub struct StatusResponse {
status: ComponentStatus,
}
#[derive(Debug, Clone, Copy, Deserialize)]
pub struct PaginationDetails {
/// Page to fetch, starting from 0.
pub page: Option<u32>,
/// Number of results per page.
pub limit: Option<u32>,
}
impl StatusResponse {
pub fn healthy() -> Self {
Self {
status: ComponentStatus::Healthy,
}
}
pub fn degraded() -> Self {
Self {
status: ComponentStatus::Degraded,
}
}
pub fn unhealthy() -> Self {
Self {
status: ComponentStatus::Unhealthy,
}
}
}
#[instrument(skip(service))]
async fn get_project(
State(RouterState { service, .. }): State<RouterState>,
ScopedUser { scope, claim }: ScopedUser,
) -> Result<AxumJson<project::Response>, ApiError> {
let project = service.find_project_by_name(&scope).await?;
let idle_minutes = project.state.idle_minutes();
let owner = service
.permit_client
.get_project_owner(&claim.sub, &project.id)
.await?
.into();
let is_admin = service
.permit_client
.allowed(&claim.sub, &project.id, "manage")
.await?;
let response = project::Response {
id: project.id.to_uppercase(),
name: scope.to_string(),
state: project.state.into(),
idle_minutes,
owner,
is_admin,
};
Ok(AxumJson(response))
}
#[instrument(skip(service))]
async fn check_project_name(
State(RouterState { service, .. }): State<RouterState>,
CustomErrorPath(project_name): CustomErrorPath<ProjectName>,
) -> Result<AxumJson<bool>, ApiError> {
let res = service.project_name_exists(&project_name).await?;
Ok(AxumJson(res))
}
async fn get_projects_list(
State(RouterState { service, .. }): State<RouterState>,
Claim { sub, .. }: Claim,
) -> Result<AxumJson<Vec<project::Response>>, ApiError> {
let mut projects = vec![];
for proj_id in service.permit_client.get_personal_projects(&sub).await? {
let project = service.find_project_by_id(&proj_id).await?;
let idle_minutes = project.state.idle_minutes();
let owner = service
.permit_client
.get_project_owner(&sub, &proj_id)
.await?
.into();
let is_admin = service
.permit_client
.allowed(&sub, &proj_id, "manage")
.await?;
let response = project::Response {
id: project.id,
name: project.name,
state: project.state.into(),
idle_minutes,
owner,
is_admin,
};
projects.push(response);
}
// sort by descending id
projects.sort_by(|p1, p2| p2.id.cmp(&p1.id));
Ok(AxumJson(projects))
}
#[instrument(skip_all, fields(shuttle.project.name = %project_name))]
async fn create_project(
State(RouterState {
service, sender, ..
}): State<RouterState>,
claim: Claim,
CustomErrorPath(project_name): CustomErrorPath<ProjectName>,
AxumJson(config): AxumJson<project::Config>,
) -> Result<AxumJson<project::Response>, ApiError> {
let is_cch_project = project_name.is_cch_project();
// Check that the user is within their project limits.
let can_create_project = claim.can_create_project(
service
.get_project_count(&claim.sub)
.await?
.saturating_sub(is_cch_project as u32),
);
if !claim.is_admin() {
service.has_capacity(is_cch_project, &claim.tier).await?;
}
let project = service
.create_project(
project_name.clone(),
&claim.sub,
claim.is_admin(),
can_create_project,
if is_cch_project {
5
} else {
config.idle_minutes
},
)
.await?;
let idle_minutes = project.state.idle_minutes();
service
.new_task()
.project(project_name.clone())
.and_then(task::run_until_done())
.and_then(task::start_idle_deploys())
.send(&sender)
.await?;
let response = project::Response {
id: project.id.to_string().to_uppercase(),
name: project_name.to_string(),
state: project.state.into(),
idle_minutes,
owner: project::Owner::User(claim.sub),
is_admin: true,
};
Ok(AxumJson(response))
}
#[instrument(skip_all, fields(shuttle.project.name = %project_name))]
async fn destroy_project(
State(RouterState {
service, sender, ..
}): State<RouterState>,
ScopedUser {
scope: project_name,
claim,
..
}: ScopedUser,
) -> Result<AxumJson<project::Response>, ApiError> {
let project = service.find_project_by_name(&project_name).await?;
let idle_minutes = project.state.idle_minutes();
let owner = service
.permit_client
.get_project_owner(&claim.sub, &project.id)
.await?
.into();
let is_admin = service
.permit_client
.allowed(&claim.sub, &project.id, "manage")
.await?;
let mut response = project::Response {
id: project.id.to_uppercase(),
name: project_name.to_string(),
state: project.state.into(),
idle_minutes,
owner,
is_admin,
};
if response.state == shuttle_common::models::project::State::Destroyed {
return Ok(AxumJson(response));
}
// if project exists and isn't `Destroyed`, send destroy task
service
.new_task()
.project(project_name)
.and_then(task::destroy())
.send(&sender)
.await?;
response.state = shuttle_common::models::project::State::Destroying;
Ok(AxumJson(response))
}
#[derive(Deserialize)]
struct DeleteProjectParams {
// Was added in v0.30.0
// We have not needed it since 0.34.1, but have to keep in for any old CLI users
#[allow(dead_code)]
dry_run: Option<bool>,
}
#[instrument(skip_all, fields(shuttle.project.name = %scoped_user.scope))]
async fn delete_project(
State(state): State<RouterState>,
scoped_user: ScopedUser,
Query(DeleteProjectParams { dry_run }): Query<DeleteProjectParams>,
req: Request<Body>,
) -> Result<AxumJson<String>, ApiError> {
// Don't do the dry run that might come from older CLIs
if dry_run.is_some_and(|d| d) {
return Ok(AxumJson("dry run is no longer supported".to_owned()));
}
let project_name = scoped_user.scope.clone();
let project = state.service.find_project_by_name(&project_name).await?;
let project_id = Ulid::from_string(&project.id).expect("stored project id to be a valid ULID");
// We restart the project before deletion everytime
let handle = state
.service
.new_task()
.project(project_name.clone())
.and_then(task::destroy()) // This destroy might only recover the project from an errored state
.and_then(task::run_until_destroyed())
.and_then(task::restart(project_id))
.and_then(task::run_until_ready())
.and_then(task::destroy())
.and_then(task::run_until_destroyed())
.and_then(task::restart(project_id))
.and_then(task::run_until_ready())
.send(&state.sender)
.await?;
// Wait for the project to be ready
handle.await;
let new_state = state.service.find_project_by_name(&project_name).await?;
if !new_state.state.is_ready() {
warn!(state = ?new_state.state, "failed to restart project");
return Err(ProjectCorrupted.into());
}
let service = state.service.clone();
let sender = state.sender.clone();
let project_caller =
ProjectCaller::new(state.clone(), scoped_user.clone(), req.headers()).await?;
trace!("getting deployments");
// check that a deployment is not running
let mut deployments = project_caller.get_deployment_list().await?;
debug!(?deployments, "got deployments");
deployments.sort_by_key(|d| d.last_update);
// Make sure no deployment is in the building pipeline
let has_bad_state = deployments.iter().any(|d| {
!matches!(
d.state,
deployment::State::Running
| deployment::State::Completed
| deployment::State::Crashed
| deployment::State::Stopped
)
});
if has_bad_state {
warn!("has bad state");
return Err(ProjectHasBuildingDeployment.into());
}
let running_deployments = deployments
.into_iter()
.filter(|d| d.state == deployment::State::Running);
for running_deployment in running_deployments {
info!(%running_deployment, "stopping running deployment");
let res = project_caller
.stop_deployment(&running_deployment.id)
.await?;
if res.status() != StatusCode::OK {
return Err(ProjectHasRunningDeployment.into());
}
}
trace!("getting resources");
// check if any resources exist
let resources = project_caller.get_resources().await?;
let mut delete_fails = Vec::new();
for resource in resources {
info!(?resource, "deleting resource");
let resource_type = resource.r#type.to_string();
let res = project_caller.delete_resource(&resource_type).await?;
if res.status() != StatusCode::OK {
delete_fails.push(resource_type)
}
}
if !delete_fails.is_empty() {
return Err(ProjectHasResources(delete_fails).into());
}
trace!("deleting container");
let task = service
.new_task()
.project(project_name.clone())
.and_then(task::delete_project())
.send(&sender)
.await?;
task.await;
trace!("removing project from state");
service.delete_project(&project_name).await?;
Ok(AxumJson("project successfully deleted".to_owned()))
}
#[instrument(skip_all, fields(shuttle.project.name = %scoped_user.scope))]
async fn override_create_service(
state: State<RouterState>,
scoped_user: ScopedUser,
req: Request<Body>,
) -> Result<Response<Body>, ApiError> {
let user_id = scoped_user.claim.sub.clone();
let posthog_client = state.posthog_client.clone();
tokio::spawn(async move {
let event = async_posthog::Event::new("shuttle_api_start_deployment", &user_id);
if let Err(err) = posthog_client.capture(event).await {
error!(
error = &err as &dyn std::error::Error,
"failed to send event to posthog"
)
};
});
route_project(state, scoped_user, req).await
}
#[instrument(skip_all, fields(shuttle.project.name = %scoped_user.scope))]
async fn override_get_delete_service(
state: State<RouterState>,
scoped_user: ScopedUser,
req: Request<Body>,
) -> Result<Response<Body>, ApiError> {
let project_name = scoped_user.scope.to_string();
let service = state.service.clone();
let ctx = state.service.context().clone();
let ContainerSettings { fqdn: public, .. } = ctx.container_settings();
let mut res = route_project(state, scoped_user, req).await?;
// inject the (most relevant) URI that this project is being served on
let uri = service
.find_custom_domain_for_project(&project_name)
.await
.unwrap_or_default() // use project name if domain lookup fails
.map(|c| format!("https://{}", c.fqdn))
.unwrap_or_else(|| format!("https://{project_name}.{public}"));
let body = hyper::body::to_bytes(res.body_mut()).await.unwrap();
let mut json: service::Summary =
serde_json::from_slice(body.as_bytes()).expect("valid service response from deployer");
json.uri = uri;
let bytes = serde_json::to_vec(&json).unwrap();
let len = res
.headers_mut()
.entry("content-length")
.or_insert(0.into());
*len = bytes.len().into();
*res.body_mut() = bytes.into();
Ok(res)
}
#[instrument(skip_all, fields(shuttle.project.name = %scoped_user.scope))]
async fn route_project(
State(RouterState {
service, sender, ..
}): State<RouterState>,
scoped_user: ScopedUser,
req: Request<Body>,
) -> Result<Response<Body>, ApiError> {
let project_name = scoped_user.scope;
let is_cch_project = project_name.is_cch_project();
if !scoped_user.claim.is_admin() {
service
.has_capacity(is_cch_project, &scoped_user.claim.tier)
.await?;
}
let project = service
.find_or_start_project(&project_name, sender)
.await?
.0;
let res = service
.route(&project.state, &project_name, &scoped_user.claim.sub, req)
.await?;
Ok(res)
}
#[instrument(skip_all)]
async fn get_teams(
State(RouterState { service, .. }): State<RouterState>,
Claim { sub, .. }: Claim,
) -> Result<AxumJson<Vec<team::Response>>, ApiError> {
let teams = service.permit_client.get_teams(&sub).await?;
Ok(AxumJson(teams))
}
#[instrument(skip_all)]
async fn get_team(
State(RouterState { service, .. }): State<RouterState>,
CustomErrorPath(team_id): CustomErrorPath<String>,
Claim { sub, .. }: Claim,
) -> Result<AxumJson<team::Response>, ApiError> {
let team = service.permit_client.get_team(&sub, &team_id).await?;
Ok(AxumJson(team))
}
#[instrument(skip_all, fields(shuttle.team.name = %team_name, shuttle.team.id = field::Empty))]
async fn create_team(
State(RouterState { service, .. }): State<RouterState>,
CustomErrorPath(team_name): CustomErrorPath<String>,
Claim { sub, .. }: Claim,
) -> Result<AxumJson<team::Response>, ApiError> {
if team_name.chars().count() > 30 {
return Err(InvalidTeamName.into());
}
let team = Team {
id: format!("team_{}", Ulid::new()),
display_name: team_name.clone(),
};
service.permit_client.create_team(&sub, &team).await?;
Span::current().record("shuttle.team.id", &team.id);
Ok(AxumJson(team::Response {
id: team.id,
display_name: team.display_name,
is_admin: true,
}))
}
#[instrument(skip_all, fields(shuttle.team.id = %team_id))]
async fn get_team_projects(
State(RouterState { service, .. }): State<RouterState>,
CustomErrorPath(team_id): CustomErrorPath<String>,
Claim { sub, .. }: Claim,
) -> Result<AxumJson<Vec<project::Response>>, ApiError> {
let project_ids = service
.permit_client
.get_team_projects(&sub, &team_id)
.await?;
let mut projects = Vec::with_capacity(project_ids.len());
for project_id in project_ids {
let project = service.find_project_by_id(&project_id).await?;
let idle_minutes = project.state.idle_minutes();
let owner = service
.permit_client
.get_project_owner(&sub, &project_id)
.await?
.into();
let is_admin = service
.permit_client
.allowed(&sub, &project_id, "manage")
.await?;
projects.push(project::Response {
id: project.id,
name: project.name,
state: project.state.into(),
idle_minutes,
owner,
is_admin,
});
}
Ok(AxumJson(projects))
}
#[instrument(skip_all, fields(shuttle.team.id = %team_id))]
async fn delete_team(
State(RouterState { service, .. }): State<RouterState>,
CustomErrorPath(team_id): CustomErrorPath<String>,
Claim { sub, .. }: Claim,
) -> Result<String, ApiError> {
service.permit_client.delete_team(&sub, &team_id).await?;
Ok("Team deleted".to_string())
}
#[instrument(skip_all, fields(shuttle.team.id = %team_id, shuttle.project.id = %project_id))]
async fn transfer_project_to_team(
State(RouterState { service, .. }): State<RouterState>,
CustomErrorPath((team_id, project_id)): CustomErrorPath<(String, String)>,
Claim { sub, .. }: Claim,
) -> Result<String, ApiError> {
service
.permit_client
.transfer_project_to_team(&sub, &project_id, &team_id)
.await?;
Ok("Project transfered".to_string())
}
#[instrument(skip_all, fields(shuttle.team.id = %team_id, shuttle.project.id = %project_id))]
async fn transfer_project_from_team(
State(RouterState { service, .. }): State<RouterState>,
CustomErrorPath((team_id, project_id)): CustomErrorPath<(String, String)>,
Claim { sub, .. }: Claim,
) -> Result<String, ApiError> {
service
.permit_client
.transfer_project_from_team(&sub, &project_id, &team_id)
.await?;
Ok("Project transfered".to_string())
}
#[instrument(skip_all, fields(shuttle.team.id = %team_id))]
async fn get_team_members(
State(RouterState { service, .. }): State<RouterState>,
CustomErrorPath(team_id): CustomErrorPath<String>,
Claim { sub, .. }: Claim,
) -> Result<AxumJson<Vec<team::MemberResponse>>, ApiError> {
let members = service
.permit_client
.get_team_members(&sub, &team_id)
.await?;
Ok(AxumJson(members))
}
#[instrument(skip_all, fields(shuttle.team.id = %team_id))]
async fn add_member_to_team(
State(RouterState { service, .. }): State<RouterState>,
CustomErrorPath((team_id, user_id)): CustomErrorPath<(String, String)>,
Claim { sub, .. }: Claim,
) -> Result<String, ApiError> {
service
.permit_client
.add_team_member(&sub, &team_id, &user_id)
.await?;
Ok("Member added".to_string())
}
#[instrument(skip_all, fields(shuttle.team.id = %team_id))]
async fn remove_member_from_team(
State(RouterState { service, .. }): State<RouterState>,
CustomErrorPath((team_id, user_id)): CustomErrorPath<(String, String)>,
Claim { sub, .. }: Claim,
) -> Result<String, ApiError> {
service
.permit_client
.remove_team_member(&sub, &team_id, &user_id)
.await?;
Ok("Member removed".to_string())
}
async fn get_status(
State(RouterState {
sender, service, ..
}): State<RouterState>,
) -> Response<Body> {
let mut statuses = Vec::new();
// Compute gateway status.
if sender.is_closed() || sender.capacity() == 0 {
statuses.push((SHUTTLE_GATEWAY_VARIANT, StatusResponse::unhealthy()));
} else if sender.capacity() < WORKER_QUEUE_SIZE - SVC_DEGRADED_THRESHOLD {
statuses.push((SHUTTLE_GATEWAY_VARIANT, StatusResponse::degraded()));
} else {
statuses.push((SHUTTLE_GATEWAY_VARIANT, StatusResponse::healthy()));
};
// Compute provisioner status.
let provisioner_status = if let Ok(channel) = service.provisioner_uri().connect().await {
let channel = ServiceBuilder::new().service(channel);
let mut provisioner_client = ProvisionerClient::new(channel);
if provisioner_client.health_check(Ping {}).await.is_ok() {
StatusResponse::healthy()
} else {
StatusResponse::unhealthy()
}
} else {
StatusResponse::unhealthy()
};
statuses.push(("shuttle-provisioner", provisioner_status));
// Compute auth status.
let auth_status = {
let response = AUTH_CLIENT.get(service.auth_uri().clone()).await;
match response {
Ok(response) if response.status() == 200 => StatusResponse::healthy(),
Ok(_) | Err(_) => StatusResponse::unhealthy(),
}
};
statuses.push(("shuttle-auth", auth_status));
let body = serde_json::to_vec(&statuses).expect("could not make a json out of the statuses");
Response::builder()
.body(body.into())
.expect("could not make a response with the status check response")
}
#[instrument(skip_all)]
async fn post_load(
State(RouterState { running_builds, .. }): State<RouterState>,
AxumJson(build): AxumJson<stats::LoadRequest>,
) -> Result<AxumJson<stats::LoadResponse>, ApiError> {
let mut running_builds = running_builds.lock().await;
trace!(id = %build.id, "checking build queue");
let mut load = calculate_capacity(&mut running_builds);
if load.has_capacity
&& running_builds
.insert(build.id, (), Duration::from_secs(60 * EXP_MINUTES as u64))
.is_none()
{
// Only increase when an item was not already in the queue
load.builds_count += 1;
}
Ok(AxumJson(load))
}
#[instrument(skip_all)]
async fn delete_load(
State(RouterState { running_builds, .. }): State<RouterState>,
AxumJson(build): AxumJson<stats::LoadRequest>,
) -> Result<AxumJson<stats::LoadResponse>, ApiError> {
let mut running_builds = running_builds.lock().await;
running_builds.remove(&build.id);
trace!(id = %build.id, "removing from build queue");
let load = calculate_capacity(&mut running_builds);
Ok(AxumJson(load))
}
#[instrument(skip_all)]
async fn get_load_admin(
State(RouterState { running_builds, .. }): State<RouterState>,
) -> Result<AxumJson<stats::LoadResponse>, ApiError> {
let mut running_builds = running_builds.lock().await;
let load = calculate_capacity(&mut running_builds);
Ok(AxumJson(load))
}
#[instrument(skip_all)]
async fn delete_load_admin(
State(RouterState { running_builds, .. }): State<RouterState>,
) -> Result<AxumJson<stats::LoadResponse>, ApiError> {
let mut running_builds = running_builds.lock().await;
running_builds.clear();
let load = calculate_capacity(&mut running_builds);
Ok(AxumJson(load))
}
fn calculate_capacity(running_builds: &mut MutexGuard<TtlCache<Uuid, ()>>) -> stats::LoadResponse {
let active = running_builds.iter().count();
let capacity = running_builds.capacity();
let has_capacity = active < capacity;
stats::LoadResponse {
builds_count: active,
has_capacity,
}
}
#[instrument(skip_all)]
async fn revive_projects(
State(RouterState {
service, sender, ..
}): State<RouterState>,
) -> Result<(), ApiError> {
crate::project::exec::revive(service, sender).await?;
Ok(())
}
#[instrument(skip_all)]
async fn idle_cch_projects(
State(RouterState {
service, sender, ..
}): State<RouterState>,
) -> Result<(), ApiError> {
crate::project::exec::idle_cch(service, sender).await?;
Ok(())
}
#[instrument(skip_all)]
async fn destroy_projects(
State(RouterState {
service, sender, ..
}): State<RouterState>,
) -> Result<(), ApiError> {
crate::project::exec::destroy(service, sender).await?;
Ok(())
}
#[instrument(skip_all, fields(%email, ?acme_server))]
async fn create_acme_account(
Extension(acme_client): Extension<AcmeClient>,
Path(email): Path<String>,
AxumJson(acme_server): AxumJson<Option<String>>,
) -> Result<AxumJson<serde_json::Value>, ApiError> {
let res = acme_client.create_account(&email, acme_server).await?;
Ok(AxumJson(res))
}
#[instrument(skip_all, fields(shuttle.project.name = %project_name, %fqdn))]
async fn request_custom_domain_acme_certificate(
State(RouterState { service, .. }): State<RouterState>,
Extension(acme_client): Extension<AcmeClient>,
Extension(resolver): Extension<Arc<GatewayCertResolver>>,
CustomErrorPath((project_name, fqdn)): CustomErrorPath<(ProjectName, String)>,
AxumJson(credentials): AxumJson<AccountCredentials<'_>>,
) -> Result<String, ApiError> {
let fqdn: FQDN = fqdn.parse().map_err(|_| InvalidCustomDomain)?;
let (certs, private_key) = service
.create_custom_domain_certificate(&fqdn, &acme_client, &project_name, credentials)
.await?;
let mut buf = Vec::new();
buf.extend(certs.as_bytes());
buf.extend(private_key.as_bytes());
resolver
.serve_pem(&fqdn.to_string(), Cursor::new(buf))
.await?;
Ok(format!(
r#""New certificate created for {} project.""#,
project_name
))
}
#[instrument(skip_all, fields(shuttle.project.name = %project_name, %fqdn))]
async fn renew_custom_domain_acme_certificate(
State(RouterState { service, .. }): State<RouterState>,
Extension(acme_client): Extension<AcmeClient>,
Extension(resolver): Extension<Arc<GatewayCertResolver>>,
CustomErrorPath((project_name, fqdn)): CustomErrorPath<(ProjectName, String)>,
AxumJson(credentials): AxumJson<AccountCredentials<'_>>,
) -> Result<String, ApiError> {
let fqdn: FQDN = fqdn.parse().map_err(|_| InvalidCustomDomain)?;
// Try retrieve the current certificate if any.
match service.project_details_for_custom_domain(&fqdn).await {
Ok(CustomDomain {
mut certificate,
private_key,
..
}) => {
certificate.push('\n');
certificate.push('\n');
certificate.push_str(private_key.as_str());
let (_, pem) = parse_x509_pem(certificate.as_bytes()).map_err(|err| {
ApiError::internal(&format!(
"Error while parsing the pem certificate for {project_name}: {err}"
))
})?;
let (_, x509_cert_chain) =
parse_x509_certificate(pem.contents.as_bytes()).map_err(|err| {
ApiError::internal(&format!(
"Error while parsing the certificate chain for {project_name}: {err}"
))
})?;
let diff = x509_cert_chain
.validity()
.not_after
.sub(ASN1Time::now())
.unwrap_or_default();
// Renew only when the difference is `None` (meaning certificate expired) or we're within the last 30 days of validity.
if diff.whole_days() <= RENEWAL_VALIDITY_THRESHOLD_IN_DAYS {
return match acme_client
.create_certificate(&fqdn.to_string(), ChallengeType::Http01, credentials)
.await
{
// If successfully created, save the certificate in memory to be
// served in the future.
Ok((certs, private_key)) => {
service
.create_custom_domain(&project_name, &fqdn, &certs, &private_key)
.await?;
let mut buf = Vec::new();
buf.extend(certs.as_bytes());
buf.extend(private_key.as_bytes());
resolver
.serve_pem(&fqdn.to_string(), Cursor::new(buf))
.await?;
Ok(format!(
r#""Certificate renewed for {} project.""#,
project_name
))
}
Err(err) => Err(err.into()),
};
} else {
Ok(format!(
r#""Certificate renewal skipped, {} project certificate still valid for {} days.""#,
project_name, diff
))
}
}
Err(err) => Err(err.into()),
}
}
#[instrument(skip_all)]
async fn renew_gateway_acme_certificate(
State(RouterState { service, .. }): State<RouterState>,
Extension(acme_client): Extension<AcmeClient>,
Extension(resolver): Extension<Arc<GatewayCertResolver>>,
AxumJson(credentials): AxumJson<AccountCredentials<'_>>,
) -> Result<String, ApiError> {
let account = AccountWrapper::from(credentials).0;
let certs = service
.fetch_certificate(&acme_client, account.credentials())
.await;
// Safe to unwrap because a 'ChainAndPrivateKey' is built from a PEM.
let chain_and_pk = certs.into_pem().unwrap();
let (_, pem) = parse_x509_pem(chain_and_pk.as_bytes())
.unwrap_or_else(|_| panic!("Malformed existing PEM certificate for the gateway."));
let (_, x509_cert) = parse_x509_certificate(pem.contents.as_bytes())
.unwrap_or_else(|_| panic!("Malformed existing X509 certificate for the gateway."));
// We compute the difference between the certificate expiry date and current timestamp because we want to trigger the
// gateway certificate renewal only during it's last 30 days of validity or if the certificate is expired.
let diff = x509_cert.validity().not_after.sub(ASN1Time::now());
// Renew only when the difference is `None` (meaning certificate expired) or we're within the last 30 days of validity.
if diff.is_none()
|| diff
.expect("to be Some given we checked for None previously")
.whole_days()
<= RENEWAL_VALIDITY_THRESHOLD_IN_DAYS
{
let tls_path = service.state_dir.join("ssl.pem");
let certs = service
.create_certificate(&acme_client, account.credentials())
.await;
resolver
.serve_default_der(certs.clone())
.await
.expect("Failed to serve the default certs");
certs
.save_pem(&tls_path)
.expect("to save the certificate locally");
return Ok(r#""Renewed the gateway certificate.""#.to_string());
}
Ok(format!(
"\"Gateway certificate was not renewed. There are {} days until the certificate expires.\"",
diff.expect("to be Some given we checked for None previously")
.whole_days()
))
}
async fn get_projects(
State(RouterState { service, .. }): State<RouterState>,
) -> Result<AxumJson<Vec<ProjectResponse>>, ApiError> {
let projects = service
.iter_projects_detailed()
.await?
.map(Into::into)
.collect();
Ok(AxumJson(projects))
}
async fn change_project_owner(
State(RouterState { service, .. }): State<RouterState>,
Path((project_name, new_user_id)): Path<(String, String)>,
) -> Result<(), ApiError> {
service
.update_project_owner(&project_name, &new_user_id)
.await?;