maincopy-server 0.1.0

Self-hosted publishing server with exact previews and explicit release approval
Documentation
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
//! Versioned administration resources for managed source synchronization.

use axum::{
    Extension, Json,
    extract::{DefaultBodyLimit, FromRequest, FromRequestParts, Path, Query, Request, State},
    http::{HeaderMap, HeaderValue, StatusCode, header::LOCATION, request::Parts},
    response::{IntoResponse as _, Response},
};
use maincopy_shared::source::{
    BeginSourceSyncResponse, ListSourceSyncsResponse, ReconfigureSourceRequest,
    SourceDeployKeyResponse, SourceStatusResponse, SourceSyncId, SourceSyncResource,
};
use serde::Deserialize;
use utoipa::ToSchema;
use utoipa_axum::{
    router::{UtoipaMethodRouter, UtoipaMethodRouterExt as _},
    routes,
};
use uuid::Uuid;

use crate::{
    admin::{
        AdminRuntimeState, BrowserSessionContext,
        idempotency::{IdempotencyKeyError, parse_idempotency_key},
        principal::{AdminAuthentication, AdminPrincipal},
        problem::{AdminProblem, AdminProblemEnvelope, problem_response},
        request_id::RequestId,
    },
    database::store::{DatabaseAdmissionError, DatabaseCommandError, DatabaseMutationError},
    domain::{
        auth::store::{AdminMutationKey, MutationAuditContext},
        source::store::SourceLoadError,
    },
    source_sync::{SourceControlError, SourceSyncHandle, accepted_status},
};

const MAX_SOURCE_SYNC_REQUEST_BYTES: usize = 4 * 1024;
const DEFAULT_SOURCE_SYNC_PAGE_LIMIT: u16 = 20;
const MAX_SOURCE_SYNC_PAGE_LIMIT: u16 = 100;
const RETRY_AFTER_ONE_SECOND: HeaderValue = HeaderValue::from_static("1");

pub(crate) fn status_routes() -> UtoipaMethodRouter<AdminRuntimeState> {
    routes!(get_source_status)
}

pub(crate) fn configuration_routes() -> UtoipaMethodRouter<AdminRuntimeState> {
    routes!(reconfigure_source, get_deploy_key)
        .layer(DefaultBodyLimit::max(MAX_SOURCE_SYNC_REQUEST_BYTES))
}

pub(crate) fn sync_list_routes() -> UtoipaMethodRouter<AdminRuntimeState> {
    routes!(list_source_syncs)
}

pub(crate) fn sync_item_routes() -> UtoipaMethodRouter<AdminRuntimeState> {
    routes!(get_source_sync)
}

pub(crate) fn sync_mutation_routes() -> UtoipaMethodRouter<AdminRuntimeState> {
    routes!(begin_source_sync).layer(DefaultBodyLimit::max(MAX_SOURCE_SYNC_REQUEST_BYTES))
}

#[derive(Clone, Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct ListSourceSyncsQuery {
    cursor: Option<Box<str>>,
    limit: Option<u16>,
}

struct SourceSyncPage {
    cursor: Option<SourceSyncId>,
    limit: usize,
}

impl<S> FromRequestParts<S> for SourceSyncPage
where
    S: Send + Sync,
{
    type Rejection = Response;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        let request_id = RequestId::from_request_parts(parts, state)
            .await
            .map_err(|error| error.into_response())?;
        let Query(query) = Query::<ListSourceSyncsQuery>::from_request_parts(parts, state)
            .await
            .map_err(|_| {
                problem(
                    AdminProblem::bad_request(
                        "invalid_source_sync_query",
                        "cursor and limit must use valid source synchronization pagination values",
                    ),
                    request_id,
                )
            })?;
        let limit = query.limit.unwrap_or(DEFAULT_SOURCE_SYNC_PAGE_LIMIT);
        if !(1..=MAX_SOURCE_SYNC_PAGE_LIMIT).contains(&limit) {
            return Err(problem(
                AdminProblem::bad_request(
                    "invalid_source_sync_limit",
                    "limit must be between 1 and 100",
                ),
                request_id,
            ));
        }
        let cursor = match query.cursor.as_deref() {
            Some(encoded) => Some(canonical_uuid(encoded).ok_or_else(|| {
                problem(
                    AdminProblem::bad_request(
                        "invalid_source_sync_cursor",
                        "cursor must be one canonical lowercase hyphenated UUID",
                    ),
                    request_id,
                )
            })?),
            None => None,
        };
        Ok(Self {
            cursor: cursor.map(SourceSyncId::from_uuid),
            limit: usize::from(limit),
        })
    }
}

struct SourceSyncIdentifier(SourceSyncId);

impl<S> FromRequestParts<S> for SourceSyncIdentifier
where
    S: Send + Sync,
{
    type Rejection = Response;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        let request_id = RequestId::from_request_parts(parts, state)
            .await
            .map_err(|error| error.into_response())?;
        let Path(encoded) = Path::<String>::from_request_parts(parts, state)
            .await
            .map_err(|_| invalid_sync_id(request_id))?;
        canonical_uuid(&encoded)
            .map(SourceSyncId::from_uuid)
            .map(Self)
            .ok_or_else(|| invalid_sync_id(request_id))
    }
}

#[derive(Debug, Default, Deserialize, ToSchema)]
#[serde(deny_unknown_fields)]
struct BeginSourceSyncRequest {}

struct SourceSyncCommand {
    request_id: RequestId,
    handle: SourceSyncHandle,
    audit: MutationAuditContext,
}

impl FromRequest<AdminRuntimeState> for SourceSyncCommand {
    type Rejection = Response;

    async fn from_request(
        request: Request,
        state: &AdminRuntimeState,
    ) -> Result<Self, Self::Rejection> {
        let (mut parts, body) = request.into_parts();
        let request_id = RequestId::from_request_parts(&mut parts, state)
            .await
            .map_err(|error| error.into_response())?;
        let principal = AdminPrincipal::from_request_parts(&mut parts, state)
            .await
            .map_err(|error| error.into_response())?;
        let headers = parts.headers.clone();
        let request = Request::from_parts(parts, body);
        let Json(BeginSourceSyncRequest {}) =
            Json::<BeginSourceSyncRequest>::from_request(request, state)
                .await
                .map_err(|rejection| source_sync_json_rejection(rejection.status(), request_id))?;
        let idempotency_key =
            source_sync_idempotency_key(&headers).map_err(|spec| problem(spec, request_id))?;
        let handle = state.source.clone();
        Ok(Self {
            request_id,
            handle,
            audit: principal.mutation_audit(request_id, idempotency_key),
        })
    }
}

#[utoipa::path(
    get,
    path = "/api/admin/v1/source",
    responses(
        (status = OK, description = "Current redacted source configuration and synchronization state", body = SourceStatusResponse,
            headers(("x-request-id" = Uuid, description = "Request correlation ID"))),
        (status = SERVICE_UNAVAILABLE, body = AdminProblemEnvelope,
            headers(("x-request-id" = Uuid, description = "Request correlation ID")))
    ),
    tag = "Source"
)]
async fn get_source_status(
    request_id: RequestId,
    State(handle): State<SourceSyncHandle>,
) -> Response {
    match handle.status().await {
        Ok(status) => Json(status).into_response(),
        Err(error) => source_control_problem(error, request_id),
    }
}

#[utoipa::path(
    get,
    path = "/api/admin/v1/source-syncs",
    params(
        ("cursor" = Option<Uuid>, Query, description = "Stable operation UUID returned as next_cursor by the previous page"),
        ("limit" = Option<u16>, Query, description = "Page size from 1 through 100; defaults to 20")
    ),
    responses(
        (status = OK, description = "Durable source synchronizations in newest-first order", body = ListSourceSyncsResponse,
            headers(("x-request-id" = Uuid, description = "Request correlation ID"))),
        (status = BAD_REQUEST, body = AdminProblemEnvelope,
            headers(("x-request-id" = Uuid, description = "Request correlation ID"))),
        (status = SERVICE_UNAVAILABLE, body = AdminProblemEnvelope,
            headers(("x-request-id" = Uuid, description = "Request correlation ID")))
    ),
    tag = "Source"
)]
async fn list_source_syncs(
    request_id: RequestId,
    SourceSyncPage { cursor, limit }: SourceSyncPage,
    State(handle): State<SourceSyncHandle>,
) -> Response {
    match handle.list(cursor, limit).await {
        Ok(page) => Json(page).into_response(),
        Err(error) => source_control_problem(error, request_id),
    }
}

#[utoipa::path(
    get,
    path = "/api/admin/v1/source-syncs/{source_sync_id}",
    params(
        ("source_sync_id" = Uuid, Path, description = "Canonical durable source synchronization UUID")
    ),
    responses(
        (status = OK, description = "One durable source synchronization", body = SourceSyncResource,
            headers(("x-request-id" = Uuid, description = "Request correlation ID"))),
        (status = BAD_REQUEST, body = AdminProblemEnvelope,
            headers(("x-request-id" = Uuid, description = "Request correlation ID"))),
        (status = NOT_FOUND, body = AdminProblemEnvelope,
            headers(("x-request-id" = Uuid, description = "Request correlation ID"))),
        (status = SERVICE_UNAVAILABLE, body = AdminProblemEnvelope,
            headers(("x-request-id" = Uuid, description = "Request correlation ID")))
    ),
    tag = "Source"
)]
async fn get_source_sync(
    request_id: RequestId,
    SourceSyncIdentifier(source_sync_id): SourceSyncIdentifier,
    State(handle): State<SourceSyncHandle>,
) -> Response {
    match handle.sync(source_sync_id).await {
        Ok(Some(sync)) => Json(sync).into_response(),
        Ok(None) => problem(
            AdminProblem::new(
                StatusCode::NOT_FOUND,
                "source_sync_not_found",
                "the requested source synchronization does not exist",
            ),
            request_id,
        ),
        Err(error) => source_control_problem(error, request_id),
    }
}

#[utoipa::path(
    post,
    path = "/api/admin/v1/source-syncs",
    request_body = BeginSourceSyncRequest,
    params(
        ("Idempotency-Key" = Uuid, Header, description = "Canonical UUID identifying retries of this synchronization request")
    ),
    responses(
        (status = OK, description = "A prior command result was replayed", body = BeginSourceSyncResponse,
            headers(
                ("location" = String, description = "Durable operation resource"),
                ("x-request-id" = Uuid, description = "Request correlation ID")
            )),
        (status = ACCEPTED, description = "A synchronization was created or coalesced onto the active operation", body = BeginSourceSyncResponse,
            headers(
                ("location" = String, description = "Durable operation resource"),
                ("x-request-id" = Uuid, description = "Request correlation ID")
            )),
        (status = BAD_REQUEST, body = AdminProblemEnvelope,
            headers(("x-request-id" = Uuid, description = "Request correlation ID"))),
        (status = CONFLICT, body = AdminProblemEnvelope,
            headers(("x-request-id" = Uuid, description = "Request correlation ID"))),
        (status = PAYLOAD_TOO_LARGE, body = AdminProblemEnvelope,
            headers(("x-request-id" = Uuid, description = "Request correlation ID"))),
        (status = INTERNAL_SERVER_ERROR, body = AdminProblemEnvelope,
            headers(("x-request-id" = Uuid, description = "Request correlation ID"))),
        (status = SERVICE_UNAVAILABLE, body = AdminProblemEnvelope,
            headers(("x-request-id" = Uuid, description = "Request correlation ID")))
    ),
    tag = "Source"
)]
async fn begin_source_sync(command: SourceSyncCommand) -> Response {
    let SourceSyncCommand {
        request_id,
        handle,
        audit,
    } = command;
    match handle.begin_manual(audit).await {
        Ok(accepted) => {
            let status = accepted_status(accepted.admission);
            let location = format!(
                "/api/admin/v1/source-syncs/{}",
                accepted.sync.source_sync_id
            );
            let mut response = (status, Json(accepted)).into_response();
            match HeaderValue::from_str(&location) {
                Ok(location) => {
                    response.headers_mut().insert(LOCATION, location);
                    response
                }
                Err(error) => {
                    tracing::error!(%request_id, error = %error, "typed source sync location was not a valid header");
                    problem(
                        AdminProblem::internal(
                            "source_sync_response_invalid",
                            "the source synchronization response could not be represented safely",
                        ),
                        request_id,
                    )
                }
            }
        }
        Err(error) => source_control_problem(error, request_id),
    }
}

#[utoipa::path(
    get, path = "/api/admin/v1/source/deploy-key",
    responses((status = OK, body = SourceDeployKeyResponse), (status = CONFLICT, body = AdminProblemEnvelope),
        (status = SERVICE_UNAVAILABLE, body = AdminProblemEnvelope)), tag = "Source"
)]
async fn get_deploy_key(request_id: RequestId, State(handle): State<SourceSyncHandle>) -> Response {
    match handle.deploy_public_identity().await {
        Ok(identity) => Json(identity).into_response(),
        Err(error) => source_control_problem(error, request_id),
    }
}

#[utoipa::path(
    put,
    path = "/api/admin/v1/source/configuration",
    request_body = ReconfigureSourceRequest,
    params(("Idempotency-Key" = Uuid, Header, description = "Retry identity for the proposed settings")),
    responses(
        (status = OK, body = BeginSourceSyncResponse),
        (status = ACCEPTED, body = BeginSourceSyncResponse),
        (status = BAD_REQUEST, body = AdminProblemEnvelope),
        (status = FORBIDDEN, body = AdminProblemEnvelope),
        (status = CONFLICT, body = AdminProblemEnvelope),
        (status = PAYLOAD_TOO_LARGE, body = AdminProblemEnvelope),
        (status = SERVICE_UNAVAILABLE, body = AdminProblemEnvelope)
    ),
    tag = "Source"
)]
async fn reconfigure_source(
    request_id: RequestId,
    principal: AdminPrincipal,
    browser: Option<Extension<BrowserSessionContext>>,
    State(handle): State<SourceSyncHandle>,
    headers: HeaderMap,
    request: Result<Json<ReconfigureSourceRequest>, axum::extract::rejection::JsonRejection>,
) -> Response {
    let fresh = match principal.authentication {
        AdminAuthentication::BrowserSession { session_id } => {
            browser.as_deref().is_some_and(|context| {
                context.session.session_id == session_id
                    && context.is_fresh_at(time::OffsetDateTime::now_utc())
            })
        }
        AdminAuthentication::AgentCredential { .. } => false,
    };
    if !fresh {
        return problem(
            AdminProblem::forbidden(
                "fresh_authentication_required",
                "source changes require a recent Owner sign-in",
            ),
            request_id,
        );
    }
    let request = match request {
        Ok(Json(request)) => request,
        Err(rejection) => {
            return problem(
                AdminProblem::new(
                    rejection.status(),
                    "invalid_source_configuration",
                    "source settings must contain valid values and the installed configuration version",
                ),
                request_id,
            );
        }
    };
    let key = match source_sync_idempotency_key(&headers) {
        Ok(key) => key,
        Err(spec) => return problem(spec, request_id),
    };
    match handle
        .reconfigure(request, principal.mutation_audit(request_id, key))
        .await
    {
        Ok(accepted) => {
            let location = format!(
                "/api/admin/v1/source-syncs/{}",
                accepted.sync.source_sync_id
            );
            (
                accepted_status(accepted.admission),
                [(LOCATION, location)],
                Json(accepted),
            )
                .into_response()
        }
        Err(error) => source_control_problem(error, request_id),
    }
}

fn source_sync_json_rejection(status: StatusCode, request_id: RequestId) -> Response {
    if status == StatusCode::PAYLOAD_TOO_LARGE {
        problem(
            AdminProblem::new(
                StatusCode::PAYLOAD_TOO_LARGE,
                "source_sync_request_too_large",
                "the source synchronization request body exceeds 4096 bytes",
            ),
            request_id,
        )
    } else {
        problem(
            AdminProblem::bad_request(
                "invalid_source_sync_request",
                "the source synchronization request body must be one empty JSON object",
            ),
            request_id,
        )
    }
}

fn source_sync_idempotency_key(headers: &HeaderMap) -> Result<AdminMutationKey, AdminProblem> {
    parse_idempotency_key(headers)
        .map(AdminMutationKey)
        .map_err(|error| match error {
            IdempotencyKeyError::Missing => AdminProblem::bad_request(
                "missing_idempotency_key",
                "Idempotency-Key is required for source synchronization requests",
            ),
            IdempotencyKeyError::Invalid => invalid_idempotency_key(),
        })
}

fn canonical_uuid(encoded: &str) -> Option<Uuid> {
    let uuid = Uuid::parse_str(encoded).ok()?;
    (uuid.hyphenated().to_string() == encoded).then_some(uuid)
}

fn invalid_idempotency_key() -> AdminProblem {
    AdminProblem::bad_request(
        "invalid_idempotency_key",
        "Idempotency-Key must be one canonical lowercase hyphenated UUID",
    )
}

fn invalid_sync_id(request_id: RequestId) -> Response {
    problem(
        AdminProblem::bad_request(
            "invalid_source_sync_id",
            "source_sync_id must be one canonical lowercase hyphenated UUID",
        ),
        request_id,
    )
}

fn source_control_problem(error: SourceControlError, request_id: RequestId) -> Response {
    let spec = match error {
        SourceControlError::Unsupported => AdminProblem::conflict(
            "source_sync_unsupported",
            "manual synchronization is unavailable in external-checkout source mode",
        ),
        SourceControlError::ShuttingDown => source_unavailable(),
        SourceControlError::ConfigurationUnavailable => source_unavailable(),
        SourceControlError::CredentialUnavailable => AdminProblem::unavailable(
            "source_credential_unavailable",
            "the selected deploy public identity could not be inspected",
        ),
        SourceControlError::Load(SourceLoadError::CursorNotFound) => AdminProblem::bad_request(
            "invalid_source_sync_cursor",
            "the source synchronization cursor does not exist",
        ),
        SourceControlError::Load(SourceLoadError::InvalidPageLimit) => AdminProblem::internal(
            "source_sync_pagination_invalid",
            "the source synchronization page could not be represented safely",
        ),
        SourceControlError::Load(SourceLoadError::Query(_) | SourceLoadError::Corrupt { .. }) => {
            source_unavailable()
        }
        SourceControlError::Mutation(DatabaseMutationError::Admission(
            DatabaseAdmissionError::QueueFull | DatabaseAdmissionError::WriterClosed,
        ))
        | SourceControlError::Mutation(DatabaseMutationError::Command(
            DatabaseCommandError::OutcomeUnknown,
        )) => source_unavailable(),
        SourceControlError::Mutation(DatabaseMutationError::Command(
            DatabaseCommandError::IdempotencyConflict,
        )) => AdminProblem::conflict(
            "idempotency_key_conflict",
            "Idempotency-Key is already bound to a different source synchronization command",
        ),
        SourceControlError::Mutation(DatabaseMutationError::Command(
            DatabaseCommandError::Rejected,
        )) => AdminProblem::conflict(
            "source_sync_conflict",
            "the source synchronization request conflicts with current durable state",
        ),
        SourceControlError::Mutation(DatabaseMutationError::Command(
            DatabaseCommandError::InvalidValue,
        )) => AdminProblem::internal(
            "source_sync_state_invalid",
            "the source synchronization command could not be represented safely",
        ),
    };
    if spec.status.is_server_error() {
        tracing::error!(%request_id, error = %error, "source synchronization administration failed");
    }
    problem(spec, request_id)
}

const fn source_unavailable() -> AdminProblem {
    AdminProblem::unavailable(
        "source_unavailable",
        "source synchronization state is temporarily unavailable",
    )
}

fn problem(spec: AdminProblem, request_id: RequestId) -> Response {
    let mut response = problem_response(spec, request_id);
    if spec.status == StatusCode::SERVICE_UNAVAILABLE {
        response
            .headers_mut()
            .insert("retry-after", RETRY_AFTER_ONE_SECOND);
    }
    response
}

#[cfg(test)]
mod tests {
    use maincopy_shared::publication::IDEMPOTENCY_KEY_HEADER;

    use super::*;

    #[test]
    fn idempotency_keys_are_single_canonical_uuids() {
        let canonical = "67e55044-10b1-426f-9247-bb680e5fe0c8";
        let mut headers = HeaderMap::new();
        assert_eq!(
            source_sync_idempotency_key(&headers).unwrap_err().code,
            "missing_idempotency_key"
        );
        headers.insert(IDEMPOTENCY_KEY_HEADER, HeaderValue::from_static(canonical));
        assert_eq!(
            source_sync_idempotency_key(&headers),
            Ok(AdminMutationKey(Uuid::parse_str(canonical).unwrap()))
        );
        for invalid in [
            "67E55044-10B1-426F-9247-BB680E5FE0C8",
            "67e5504410b1426f9247bb680e5fe0c8",
            "not-a-uuid",
        ] {
            headers.insert(
                IDEMPOTENCY_KEY_HEADER,
                HeaderValue::from_str(invalid).unwrap(),
            );
            assert_eq!(
                source_sync_idempotency_key(&headers).unwrap_err().code,
                "invalid_idempotency_key"
            );
        }
        headers.insert(IDEMPOTENCY_KEY_HEADER, HeaderValue::from_static(canonical));
        headers.append(IDEMPOTENCY_KEY_HEADER, HeaderValue::from_static(canonical));
        assert_eq!(
            source_sync_idempotency_key(&headers).unwrap_err().code,
            "invalid_idempotency_key"
        );
    }
}