Repository navigation
Expand file tree
/
Copy pathartifacts_router.rs
More file actions
703 lines (660 loc) · 27.2 KB
/
Copy pathartifacts_router.rs
File metadata and controls
703 lines (660 loc) · 27.2 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
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
use std::time::Duration;
use axum::{
Json,
body::Body,
extract::{Path, Query, State},
http::{HeaderMap, Request, StatusCode},
response::{IntoResponse, Response},
};
use chrono::Utc;
use futures::{StreamExt, TryStreamExt};
use http::header;
use percent_encoding::percent_decode_str;
use utoipa_axum::{router::OpenApiRouter, routes};
use crate::{
api::{MonoApiServiceState, api_doc::ARTIFACTS_TAG, api_write_auth::authorize_trunk_api_write},
common::errors::{ApiError, MegaError},
contract::api::artifacts::{
ARTIFACT_PRESIGN_URL_TTL_SECS, ArtifactBatchRequest, ArtifactBatchResponse,
ArtifactCommitRequest, ArtifactCommitResponse, ArtifactDiscoveryResponse, ArtifactLink,
ArtifactListSetsResponse, ArtifactObjectReadActions, ArtifactObjectReadResponse,
ArtifactObjectType, ArtifactResolveFileResponse, ArtifactSetDetailResponse,
DownloadArtifactObjectQuery, GetArtifactSetQuery, ListArtifactSetsQuery,
ResolveArtifactFileQuery,
},
jupiter::service::artifact_service::ArtifactService,
};
/// Artifact HTTP routes merged under [`crate::api::api_router`] → `/api/v1`.
///
/// `#[utoipa::path(path = ...)]` values are **suffixes only**, relative to
/// `nest("/repos/{repo}/artifacts", ...)` here (same pattern as `lfs_router` / `merge_queue_router`).
/// Example: `path = "/discovery"` → OpenAPI `/api/v1/repos/{repo}/artifacts/discovery`.
pub fn routers() -> OpenApiRouter<MonoApiServiceState> {
OpenApiRouter::new().nest(
"/repos/{repo}/artifacts",
OpenApiRouter::new()
.routes(routes!(discovery))
.routes(routes!(list_artifact_sets))
.routes(routes!(get_artifact_set))
.routes(routes!(resolve_artifact_file))
.routes(routes!(download_object, head_artifact_object))
.routes(routes!(batch))
.routes(routes!(commit))
.routes(routes!(upload_object_fallback)),
)
}
fn decode_path_segment(segment: &str) -> String {
percent_decode_str(segment).decode_utf8_lossy().into_owned()
}
/// Trunk / storage-only write gate (plan-20260921 AR-01 / ADR-AR-01):
/// `git.push_auth` exists exactly on the storage-only morphology, so when it
/// is set the write is authorized through `authorize_trunk_api_write` against
/// the decoded repo path with a leading `/` (ADR-AR-02). On Review
/// (`push_auth = None`) this is a no-op and `cedar_guard` keeps deciding.
fn authorize_artifacts_write(
state: &MonoApiServiceState,
headers: &HeaderMap,
repo: &str,
) -> Result<(), ApiError> {
let config = state.storage.config();
if config.git.push_auth.is_none() {
return Ok(());
}
let path = if repo.starts_with('/') {
repo.to_owned()
} else {
format!("/{repo}")
};
authorize_trunk_api_write(&config.git, headers, &path)?;
Ok(())
}
fn mega_to_api(err: MegaError) -> ApiError {
ApiError::from(anyhow::Error::from(err))
}
/// Discover artifact protocol capabilities for a repo (see `docs/artifacts-protocol.md`).
#[utoipa::path(
get,
path = "/discovery",
params(
("repo" = String, Path, description = "Single URL path segment identifying the repo (use %2F for `/` inside names, e.g. `org%2Fproject`)")
),
responses(
(status = 200, description = "Discovery payload", body = ArtifactDiscoveryResponse, content_type = "application/json"),
(status = 401, description = "Missing or invalid Bearer token when the deployment requires auth")
),
tag = ARTIFACTS_TAG
)]
pub async fn discovery(
State(state): State<MonoApiServiceState>,
Path(_repo): Path<String>,
) -> Result<Json<ArtifactDiscoveryResponse>, ApiError> {
Ok(Json(state.storage.artifact_service.discovery_response()))
}
/// List committed artifact sets for a repo (paginated).
#[utoipa::path(
get,
path = "/sets",
params(
("repo" = String, Path, description = "Single URL path segment identifying the repo (use %2F for `/` inside names, e.g. `org%2Fproject`)"),
("namespace" = String, Query, description = "Artifact namespace"),
("object_type" = ArtifactObjectType, Query, description = "Object type label"),
("limit" = Option<u32>, Query, description = "Page size"),
("cursor" = Option<String>, Query, description = "Pagination cursor"),
("run_id" = Option<String>, Query, description = "Filter metadata.run_id"),
("commit_sha" = Option<String>, Query, description = "Filter metadata.commit_sha")
),
responses(
(status = 200, description = "Paged sets", body = ArtifactListSetsResponse, content_type = "application/json"),
(status = 400, description = "Invalid cursor", content_type = "application/json"),
(status = 500, description = "Database error", content_type = "application/json")
),
tag = ARTIFACTS_TAG
)]
pub async fn list_artifact_sets(
State(state): State<MonoApiServiceState>,
Path(repo): Path<String>,
Query(q): Query<ListArtifactSetsQuery>,
) -> Result<Json<ArtifactListSetsResponse>, ApiError> {
let repo = decode_path_segment(&repo);
let body = state
.storage
.artifact_service
.list_artifact_sets(&repo, &q)
.await
.map_err(mega_to_api)?;
Ok(Json(body))
}
/// Get one artifact set manifest (metadata + files).
#[utoipa::path(
get,
path = "/sets/{artifact_set_id}",
params(
("repo" = String, Path, description = "Single URL path segment identifying the repo (use %2F for `/` inside names, e.g. `org%2Fproject`)"),
("artifact_set_id" = String, Path, description = "Client commit idempotency key for the set"),
("namespace" = String, Query, description = "Artifact namespace"),
("object_type" = ArtifactObjectType, Query, description = "Object type label")
),
responses(
(status = 200, description = "Set detail", body = ArtifactSetDetailResponse, content_type = "application/json"),
(status = 404, description = "Set not found", content_type = "application/json"),
(status = 500, description = "Database error", content_type = "application/json")
),
tag = ARTIFACTS_TAG
)]
pub async fn get_artifact_set(
State(state): State<MonoApiServiceState>,
Path((repo, artifact_set_id)): Path<(String, String)>,
Query(q): Query<GetArtifactSetQuery>,
) -> Result<Json<ArtifactSetDetailResponse>, ApiError> {
let repo = decode_path_segment(&repo);
let artifact_set_id = decode_path_segment(&artifact_set_id);
let body = state
.storage
.artifact_service
.get_artifact_set_detail(&repo, &artifact_set_id, &q)
.await
.map_err(mega_to_api)?;
Ok(Json(body))
}
/// Resolve latest committed file row by logical path and optional metadata filters.
#[utoipa::path(
get,
path = "/resolve-file",
params(
("repo" = String, Path, description = "Single URL path segment identifying the repo (use %2F for `/` inside names, e.g. `org%2Fproject`)"),
("namespace" = String, Query, description = "Artifact namespace"),
("object_type" = ArtifactObjectType, Query, description = "Object type label"),
("path" = String, Query, description = "Logical artifact path"),
("run_id" = Option<String>, Query, description = "Filter metadata.run_id"),
("commit_sha" = Option<String>, Query, description = "Filter metadata.commit_sha")
),
responses(
(status = 200, description = "Resolved file row", body = ArtifactResolveFileResponse, content_type = "application/json"),
(status = 404, description = "No matching file", content_type = "application/json"),
(status = 500, description = "Database error", content_type = "application/json")
),
tag = ARTIFACTS_TAG
)]
pub async fn resolve_artifact_file(
State(state): State<MonoApiServiceState>,
Path(repo): Path<String>,
Query(q): Query<ResolveArtifactFileQuery>,
) -> Result<Json<ArtifactResolveFileResponse>, ApiError> {
let repo = decode_path_segment(&repo);
let body = state
.storage
.artifact_service
.resolve_artifact_file(&repo, &q)
.await
.map_err(mega_to_api)?;
Ok(Json(body))
}
/// Download object bytes, redirect to signed URL, or return a JSON download link (see protocol §8.7.4).
#[utoipa::path(
get,
path = "/objects/{oid}",
params(
("repo" = String, Path, description = "Single URL path segment identifying the repo (use %2F for `/` inside names, e.g. `org%2Fproject`)"),
("oid" = String, Path, description = "Artifact object id (UUID string per RFC 4122)"),
("mode" = Option<String>, Query, description = "Use `link` for JSON `actions.download` when presigned GET is supported; omit for 302 or proxied bytes")
),
responses(
(status = 200, description = "Object bytes", content_type = "application/octet-stream"),
(status = 200, description = "Download link wrapper", body = ArtifactObjectReadResponse, content_type = "application/json"),
(status = 206, description = "Partial content (Range)", content_type = "application/octet-stream"),
(status = 302, description = "Redirect to signed GET URL"),
(status = 304, description = "Not modified (If-None-Match)"),
(status = 400, description = "Bad query (e.g. mode=link without presign support)", content_type = "application/json"),
(status = 404, description = "Object not available for this repo", content_type = "application/json"),
(status = 416, description = "Range not satisfiable", content_type = "application/json"),
(status = 500, description = "Storage or database error", content_type = "application/json")
),
tag = ARTIFACTS_TAG
)]
pub async fn download_object(
State(state): State<MonoApiServiceState>,
Path((repo, oid)): Path<(String, String)>,
Query(q): Query<DownloadArtifactObjectQuery>,
headers: HeaderMap,
) -> Result<Response, ApiError> {
let repo = decode_path_segment(&repo);
let oid = decode_path_segment(&oid);
let svc = &state.storage.artifact_service;
let model = svc
.artifact_object_model_for_committed_repo_download(&repo, &oid)
.await
.map_err(mega_to_api)?;
let etag = ArtifactService::weak_etag_for_oid_size(&model.oid, model.size_bytes);
let range_hdr = headers.get(header::RANGE).and_then(|v| v.to_str().ok());
if range_hdr.is_none()
&& let Some(inm) = headers.get(header::IF_NONE_MATCH)
&& inm.to_str().ok().map(str::trim) == Some(etag.trim())
{
return Response::builder()
.status(StatusCode::NOT_MODIFIED)
.header(header::ETAG, &etag)
.body(Body::empty())
.map_err(ApiError::internal);
}
if q.mode.as_deref() == Some("link") && !svc.supports_artifact_presigned_urls() {
return Err(ApiError::bad_request(anyhow::anyhow!(
"mode=link requires presigned URL support (S3/GCS); omit mode for server-proxied download"
)));
}
let presign_ttl = Duration::from_secs(ARTIFACT_PRESIGN_URL_TTL_SECS);
let signed_get = svc
.artifact_object_signed_get_url(&oid, presign_ttl)
.await
.map_err(mega_to_api)?;
if let Some(url) = signed_get {
if q.mode.as_deref() == Some("link") {
let expires_at = (Utc::now()
+ chrono::Duration::seconds(ARTIFACT_PRESIGN_URL_TTL_SECS as i64))
.to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
let body = ArtifactObjectReadResponse {
actions: ArtifactObjectReadActions {
download: ArtifactLink {
href: url,
header: None,
expires_at: Some(expires_at),
},
},
};
return Ok(Json(body).into_response());
}
return Response::builder()
.status(StatusCode::FOUND)
.header(header::LOCATION, url)
.body(Body::empty())
.map_err(ApiError::internal);
}
let len = model.size_bytes.max(0) as u64;
let range_parsed = match ArtifactService::parse_artifact_object_range(range_hdr, len) {
Ok(v) => v,
Err(e) => {
let msg = e.to_string();
if msg.contains("[code:416]") {
return Response::builder()
.status(StatusCode::RANGE_NOT_SATISFIABLE)
.header(header::CONTENT_RANGE, format!("bytes */{len}"))
.body(Body::empty())
.map_err(ApiError::internal);
}
return Err(mega_to_api(e));
}
};
let content_type = model
.content_type
.as_deref()
.unwrap_or("application/octet-stream");
match range_parsed {
None => {
let stream = svc
.get_artifact_object_byte_stream(&oid)
.await
.map_err(mega_to_api)?;
let mapped = stream.map(|r| r.map_err(std::io::Error::other));
Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, content_type)
.header(header::CONTENT_LENGTH, model.size_bytes.to_string())
.header(header::ETAG, &etag)
.body(Body::from_stream(mapped))
.map_err(ApiError::internal)
}
Some((start, end_exclusive)) => {
let stream = svc
.get_artifact_object_range_byte_stream(&oid, start, end_exclusive)
.await
.map_err(mega_to_api)?;
let mapped = stream.map(|r| r.map_err(std::io::Error::other));
let range_len = end_exclusive.saturating_sub(start);
let last = end_exclusive.saturating_sub(1);
let content_range = format!("bytes {start}-{last}/{len}");
Response::builder()
.status(StatusCode::PARTIAL_CONTENT)
.header(header::CONTENT_TYPE, content_type)
.header(header::CONTENT_LENGTH, range_len.to_string())
.header(header::CONTENT_RANGE, content_range)
.header(header::ETAG, &etag)
.body(Body::from_stream(mapped))
.map_err(ApiError::internal)
}
}
}
/// `HEAD .../objects/{oid}` — metadata only (protocol §8.7.4 optional).
#[utoipa::path(
head,
path = "/objects/{oid}",
params(
("repo" = String, Path, description = "Single URL path segment identifying the repo (use %2F for `/` inside names, e.g. `org%2Fproject`)"),
("oid" = String, Path, description = "Artifact object id (UUID string per RFC 4122)")
),
responses(
(status = 200, description = "Headers only", content_type = "application/octet-stream"),
(status = 404, description = "Object not available for this repo", content_type = "application/json"),
(status = 500, description = "Storage or database error", content_type = "application/json")
),
tag = ARTIFACTS_TAG
)]
pub async fn head_artifact_object(
State(state): State<MonoApiServiceState>,
Path((repo, oid)): Path<(String, String)>,
) -> Result<Response, ApiError> {
let repo = decode_path_segment(&repo);
let oid = decode_path_segment(&oid);
let svc = &state.storage.artifact_service;
let model = svc
.artifact_object_model_for_committed_repo_download(&repo, &oid)
.await
.map_err(mega_to_api)?;
let etag = ArtifactService::weak_etag_for_oid_size(&model.oid, model.size_bytes);
let content_type = model
.content_type
.as_deref()
.unwrap_or("application/octet-stream");
Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, content_type)
.header(header::CONTENT_LENGTH, model.size_bytes.to_string())
.header(header::ETAG, etag)
.body(Body::empty())
.map_err(ApiError::internal)
}
/// Batch negotiate repo-scoped artifact uploads.
#[utoipa::path(
post,
path = "/batch",
params(
("repo" = String, Path, description = "Single URL path segment identifying the repo (use %2F for `/` inside names, e.g. `org%2Fproject`)")
),
request_body = ArtifactBatchRequest,
responses(
(status = 200, description = "Batch response with upload actions", body = ArtifactBatchResponse, content_type = "application/json"),
(status = 400, description = "Invalid request (namespace, oid, path, size, limits)", content_type = "application/json"),
(status = 500, description = "Database error", content_type = "application/json")
),
tag = ARTIFACTS_TAG
)]
pub async fn batch(
State(state): State<MonoApiServiceState>,
Path(repo): Path<String>,
headers: HeaderMap,
Json(req): Json<ArtifactBatchRequest>,
) -> Result<Json<ArtifactBatchResponse>, ApiError> {
let repo = decode_path_segment(&repo);
authorize_artifacts_write(&state, &headers, &repo)?;
let body = state
.storage
.artifact_service
.batch_artifacts(&req)
.await
.map_err(mega_to_api)?;
Ok(Json(body))
}
/// Commit an artifact set manifest to make it queryable.
#[utoipa::path(
post,
path = "/commit",
params(
("repo" = String, Path, description = "Single URL path segment identifying the repo (use %2F for `/` inside names, e.g. `org%2Fproject`)")
),
request_body = ArtifactCommitRequest,
responses(
(status = 200, description = "Commit response (ok or missing_objects)", body = ArtifactCommitResponse, content_type = "application/json"),
(status = 400, description = "Invalid request or size mismatch", content_type = "application/json"),
(status = 409, description = "artifact_set_id already committed with a different manifest", content_type = "application/json"),
(status = 500, description = "Database error", content_type = "application/json")
),
tag = ARTIFACTS_TAG
)]
pub async fn commit(
State(state): State<MonoApiServiceState>,
Path(repo): Path<String>,
headers: HeaderMap,
Json(req): Json<ArtifactCommitRequest>,
) -> Result<Json<ArtifactCommitResponse>, ApiError> {
let repo = decode_path_segment(&repo);
authorize_artifacts_write(&state, &headers, &repo)?;
let body = state
.storage
.artifact_service
.commit_artifacts(&repo, &req)
.await
.map_err(mega_to_api)?;
Ok(Json(body))
}
/// Fallback endpoint to upload object bytes through the Mono server (when signed URLs are unavailable).
#[utoipa::path(
put,
path = "/objects/{oid}",
params(
("repo" = String, Path, description = "Single URL path segment identifying the repo (use %2F for `/` inside names, e.g. `org%2Fproject`)"),
("oid" = String, Path, description = "Artifact object id (UUID string per RFC 4122)")
),
request_body(content = Vec<u8>, content_type = "application/octet-stream", description = "Object bytes"),
responses(
(status = 204, description = "Uploaded (or already exists)"),
(status = 400, description = "Invalid oid or body", content_type = "application/json"),
(status = 409, description = "Oid exists with a different size", content_type = "application/json"),
(status = 500, description = "Storage or database error", content_type = "application/json")
),
tag = ARTIFACTS_TAG
)]
pub async fn upload_object_fallback(
State(state): State<MonoApiServiceState>,
Path((repo, oid)): Path<(String, String)>,
headers: HeaderMap,
req: Request<Body>,
) -> Result<StatusCode, ApiError> {
let repo = decode_path_segment(&repo);
let oid = decode_path_segment(&oid);
authorize_artifacts_write(&state, &headers, &repo)?;
let content_length = req
.headers()
.get(header::CONTENT_LENGTH)
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse::<usize>().ok());
let body_bytes: Vec<u8> = req
.into_body()
.into_data_stream()
.try_fold(Vec::new(), |mut acc, chunk| async move {
acc.extend_from_slice(&chunk);
Ok(acc)
})
.await
.map_err(ApiError::internal)?;
if let Some(expected) = content_length
&& expected != body_bytes.len()
{
return Err(ApiError::bad_request(anyhow::anyhow!(
"Content-Length ({expected}) does not match received body size ({})",
body_bytes.len()
)));
}
state
.storage
.artifact_service
.upload_artifact_object_bytes(&oid, body_bytes)
.await
.map_err(mega_to_api)?;
Ok(StatusCode::NO_CONTENT)
}
#[cfg(test)]
mod tests {
use utoipa::OpenApi;
use utoipa_axum::router::OpenApiRouter;
use super::*;
use crate::api::api_doc::ApiDoc;
fn path_list(router: OpenApiRouter<MonoApiServiceState>) -> Vec<String> {
OpenApiRouter::with_openapi(ApiDoc::openapi())
.merge(router)
.split_for_parts()
.1
.paths
.paths
.keys()
.cloned()
.collect()
}
fn assert_artifacts_paths_present(paths: &[String]) {
for needle in [
"/repos/{repo}/artifacts/discovery",
"/repos/{repo}/artifacts/sets",
"/repos/{repo}/artifacts/sets/{artifact_set_id}",
"/repos/{repo}/artifacts/resolve-file",
"/repos/{repo}/artifacts/objects/{oid}",
"/repos/{repo}/artifacts/batch",
"/repos/{repo}/artifacts/commit",
] {
assert!(
paths.iter().any(|p| p == needle),
"must register {needle}: {paths:?}"
);
}
}
/// AR-01: the storage-only / trunk router mounts the artifacts protocol.
#[test]
fn storage_only_router_registers_artifacts_paths() {
let paths = path_list(crate::api::api_router::storage_only_routers());
assert_artifacts_paths_present(&paths);
}
/// AR-01 regression: the review router keeps the artifacts paths (they
/// were already merged there before this plan).
#[test]
fn review_router_keeps_artifacts_paths() {
let paths = path_list(crate::api::api_router::routers());
assert_artifacts_paths_present(&paths);
}
/// AR-01: artifact writes authorize through `authorize_trunk_api_write`
/// when `git.push_auth` is set — a missing credential is 401, a token
/// scoped to another repo is 403, and a covering token passes the gate.
#[tokio::test]
async fn artifact_writes_call_trunk_write_gate() {
use std::sync::Arc;
use axum::{
body::Body,
http::{HeaderValue, Request, StatusCode, header::AUTHORIZATION},
response::IntoResponse,
};
use crate::{
api::oauth::api_store::{BrowserSessionStore, CountingSessionStore},
ceres::api_service::cache::GitObjectCache,
config::{PushAuth, PushTokenConfig},
contract::policy::entitystore::SharedEntityStore,
};
let temp = tempfile::tempdir().expect("temp dir");
let mut config = crate::config::testing::isolated_config(temp.path().join("config"));
config.git.push_auth = Some(PushAuth::Token);
config.git.push_tokens = vec![PushTokenConfig {
name: "ar01-ci".to_owned(),
token: "secret-ok".to_owned(),
paths: Some(vec!["/project".to_owned()]),
}];
let storage = crate::jupiter::tests::test_storage_with_config(temp.path(), config).await;
let state = MonoApiServiceState {
session_store: BrowserSessionStore::Counting(CountingSessionStore::new(vec![Ok(None)])),
git_object_cache: Arc::new(GitObjectCache {
connection: ::redis::aio::ConnectionManager::new_lazy_with_config(
::redis::Client::open("redis://127.0.0.1:6379").expect("open redis client"),
::redis::aio::ConnectionManagerConfig::new(),
)
.expect("lazy connection manager"),
prefix: "ar01-test".to_string(),
}),
listen_addr: "http://127.0.0.1:0".to_string(),
entity_store: Arc::new(SharedEntityStore::new()),
storage,
};
let oid = uuid::Uuid::new_v4().to_string();
let batch_body = || {
Json(ArtifactBatchRequest {
namespace: "ar01".to_owned(),
object_type: ArtifactObjectType::Snapshot,
intent: crate::contract::api::artifacts::ArtifactIntent::Upload,
objects: vec![crate::contract::api::artifacts::ArtifactObjectDescriptor {
path: "bin/app".to_owned(),
oid: oid.clone(),
size: 4,
content_type: None,
}],
metadata: None,
})
};
// Missing credential → 401 on all three write handlers.
let Err(err) = batch(
State(state.clone()),
Path("project".to_owned()),
HeaderMap::new(),
batch_body(),
)
.await
else {
panic!("batch without credential must be rejected");
};
assert_eq!(err.into_response().status(), StatusCode::UNAUTHORIZED);
let commit_req = |namespace: &str| {
Json(ArtifactCommitRequest {
namespace: namespace.to_owned(),
object_type: ArtifactObjectType::Snapshot,
artifact_set_id: None,
files: vec![],
metadata: None,
expires_in_seconds: None,
})
};
let Err(err) = commit(
State(state.clone()),
Path("project".to_owned()),
HeaderMap::new(),
commit_req("ar01"),
)
.await
else {
panic!("commit without credential must be rejected");
};
assert_eq!(err.into_response().status(), StatusCode::UNAUTHORIZED);
let upload_req = || {
Request::builder()
.method("PUT")
.body(Body::from(vec![1_u8, 2, 3, 4]))
.expect("upload request")
};
let Err(err) = upload_object_fallback(
State(state.clone()),
Path(("project".to_owned(), oid.clone())),
HeaderMap::new(),
upload_req(),
)
.await
else {
panic!("upload without credential must be rejected");
};
assert_eq!(err.into_response().status(), StatusCode::UNAUTHORIZED);
// Valid token scoped to /project, repo /other → 403.
let mut headers = HeaderMap::new();
headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer secret-ok"));
let Err(err) = batch(
State(state.clone()),
Path("other".to_owned()),
headers.clone(),
batch_body(),
)
.await
else {
panic!("uncovered repo must be rejected");
};
assert_eq!(err.into_response().status(), StatusCode::FORBIDDEN);
// Covering token passes the gate; the batch itself succeeds.
let result = batch(
State(state),
Path("project".to_owned()),
headers,
batch_body(),
)
.await;
let Json(body) = result.expect("covered token must pass the write gate");
assert_eq!(body.objects.len(), 1);
assert!(!body.objects[0].exists);
}
}