CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s
Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.
Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
resources/list admission fix for bound template publications.
Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
`just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
a real MCP Inspector 2.12.0 client smoke.
Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
runs only on main), story events run the changed packages, the full workspace suite
stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
release entry of the tag instead of dying with the runner workspace.
Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.
Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
705 lines
28 KiB
Rust
705 lines
28 KiB
Rust
//! Admin API Story 3.6: typed static Resource Drafts (D-16).
|
||
//!
|
||
//! Один режим просмотра (D-6): `GET .../preview` отдаёт metadata + findings +
|
||
//! инертный `text` только для text/JSON; `GET .../content` отдаёт bytes **всегда**
|
||
//! как `application/octet-stream` + `attachment` + CSP `sandbox`, поэтому
|
||
//! заявленный MIME никогда не становится HTTP content type.
|
||
//!
|
||
//! Порядок проверок D-20 обеспечивается разбором частей multipart и порядком
|
||
//! вызовов сервиса: метаданные (E) и разрешение Resource (C) обрабатываются до
|
||
//! содержимого (G) — содержимое только буферизуется, но не оценивается.
|
||
|
||
use axum::{
|
||
Extension, Json,
|
||
extract::{Multipart, Path, State, multipart::MultipartRejection, rejection::JsonRejection},
|
||
http::{HeaderMap, HeaderValue, StatusCode, header},
|
||
response::{IntoResponse, Response},
|
||
};
|
||
use crank_core::resource::ResourceKind;
|
||
use crank_registry::model::resource::RevokeResourceRequest;
|
||
use serde::Deserialize;
|
||
use serde_json::{Map, Value, json};
|
||
|
||
use crate::{
|
||
auth::AuthenticatedSession,
|
||
error::ApiError,
|
||
request_context::RequestContext,
|
||
service::resources::{
|
||
ArchiveResource, DraftMetadata, ImmutableField, NewDraft, PublishResource, UpdateDraft,
|
||
portability,
|
||
template::{NewTemplateDraft, TemplateIdentity, UpdateTemplateDraft},
|
||
},
|
||
state::AppState,
|
||
};
|
||
|
||
/// Тело ответа Draft нельзя превысить: часть содержимого — bounded bytes.
|
||
#[derive(Deserialize)]
|
||
pub struct ResourceWorkspacePath {
|
||
pub workspace_id: String,
|
||
}
|
||
|
||
#[derive(Deserialize)]
|
||
pub struct ResourcePath {
|
||
pub workspace_id: String,
|
||
pub resource_id: String,
|
||
}
|
||
|
||
#[derive(Deserialize)]
|
||
pub struct ResourceVersionPath {
|
||
pub workspace_id: String,
|
||
pub resource_id: String,
|
||
pub version: u32,
|
||
}
|
||
|
||
pub async fn create_resource(
|
||
Path(path): Path<ResourceWorkspacePath>,
|
||
State(state): State<AppState>,
|
||
multipart: Result<Multipart, MultipartRejection>,
|
||
) -> Result<Response, ApiError> {
|
||
let (metadata, content) = read_draft_multipart(multipart).await?;
|
||
// Story 3.10: `metadata.source` ⇒ template Draft без части `content`.
|
||
if metadata.contains_key("source") {
|
||
let source = content_absent(metadata.get("source"), content)?;
|
||
let created = state
|
||
.service
|
||
.resources()
|
||
.create_template_draft(NewTemplateDraft {
|
||
workspace_id: path.workspace_id.as_str().into(),
|
||
metadata: create_metadata(&metadata)?,
|
||
source,
|
||
})
|
||
.await?;
|
||
let card = state
|
||
.service
|
||
.resources()
|
||
.card(&path.workspace_id.as_str().into(), &created.resource_id)
|
||
.await?;
|
||
return Ok((StatusCode::CREATED, Json(json!(card))).into_response());
|
||
}
|
||
let metadata = create_metadata(&metadata)?;
|
||
let bytes = content.ok_or_else(malformed_multipart)?;
|
||
let created = state
|
||
.service
|
||
.resources()
|
||
.create_draft(NewDraft {
|
||
workspace_id: path.workspace_id.as_str().into(),
|
||
metadata,
|
||
bytes,
|
||
})
|
||
.await?;
|
||
let card = state
|
||
.service
|
||
.resources()
|
||
.card(&path.workspace_id.as_str().into(), &created.resource_id)
|
||
.await?;
|
||
Ok((StatusCode::CREATED, Json(json!(card))).into_response())
|
||
}
|
||
|
||
pub async fn list_resources(
|
||
Path(path): Path<ResourceWorkspacePath>,
|
||
State(state): State<AppState>,
|
||
) -> Result<Json<Value>, ApiError> {
|
||
let listed = state
|
||
.service
|
||
.resources()
|
||
.list(&path.workspace_id.as_str().into())
|
||
.await?;
|
||
Ok(Json(json!(listed)))
|
||
}
|
||
|
||
pub async fn get_resource(
|
||
Path(path): Path<ResourcePath>,
|
||
State(state): State<AppState>,
|
||
) -> Result<Json<Value>, ApiError> {
|
||
let card = state
|
||
.service
|
||
.resources()
|
||
.card(
|
||
&path.workspace_id.as_str().into(),
|
||
&path.resource_id.as_str().into(),
|
||
)
|
||
.await?;
|
||
Ok(Json(json!(card)))
|
||
}
|
||
|
||
pub async fn update_resource(
|
||
Path(path): Path<ResourcePath>,
|
||
State(state): State<AppState>,
|
||
multipart: Result<Multipart, MultipartRejection>,
|
||
) -> Result<Json<Value>, ApiError> {
|
||
let (metadata, content) = read_draft_multipart(multipart).await?;
|
||
// Story 3.10: template Draft редактируется определением, без части `content`.
|
||
if metadata.contains_key("source") {
|
||
let source = content_absent(metadata.get("source"), content)?;
|
||
let update =
|
||
update_template_draft(&path.workspace_id, &path.resource_id, &metadata, source)?;
|
||
let card = state
|
||
.service
|
||
.resources()
|
||
.update_template_draft(update)
|
||
.await?;
|
||
return Ok(Json(json!(card)));
|
||
}
|
||
if state
|
||
.service
|
||
.resources()
|
||
.is_template_draft(
|
||
&path.workspace_id.as_str().into(),
|
||
&path.resource_id.as_str().into(),
|
||
)
|
||
.await?
|
||
{
|
||
// Сохранённый template Draft без нового определения: не превращаем его в static.
|
||
return Err(crank_core::resource::ResourceError::SourceInvalid { field: "source" }.into());
|
||
}
|
||
let bytes = content.ok_or_else(malformed_multipart)?;
|
||
let update = update_draft(&path.workspace_id, &path.resource_id, &metadata, bytes)?;
|
||
let card = state.service.resources().update_draft(update).await?;
|
||
Ok(Json(json!(card)))
|
||
}
|
||
|
||
pub async fn test_resource(
|
||
Path(path): Path<ResourcePath>,
|
||
State(state): State<AppState>,
|
||
Extension(request_context): Extension<RequestContext>,
|
||
Json(body): Json<Value>,
|
||
) -> Result<Json<Value>, ApiError> {
|
||
let result = state
|
||
.service
|
||
.test_resource_read(
|
||
&path.workspace_id.as_str().into(),
|
||
&path.resource_id.as_str().into(),
|
||
body,
|
||
&request_context.correlation,
|
||
)
|
||
.await?;
|
||
Ok(Json(result))
|
||
}
|
||
|
||
pub async fn preview_resource(
|
||
Path(path): Path<ResourcePath>,
|
||
State(state): State<AppState>,
|
||
) -> Result<Json<Value>, ApiError> {
|
||
let preview = state
|
||
.service
|
||
.resources()
|
||
.preview(
|
||
&path.workspace_id.as_str().into(),
|
||
&path.resource_id.as_str().into(),
|
||
)
|
||
.await?;
|
||
Ok(Json(json!(preview)))
|
||
}
|
||
|
||
/// Публикация проверенного Draft в immutable Published Version (Story 3.7).
|
||
///
|
||
/// Тело — `{ "expected_updated_at": "<точное значение карточки>" }`. Отсутствие и
|
||
/// `null` означают «precondition не задан» и дают 428 `resource_stale` (как PUT);
|
||
/// значение другого JSON-типа — отказ формы запроса (400).
|
||
pub async fn publish_resource(
|
||
Path(path): Path<ResourcePath>,
|
||
State(state): State<AppState>,
|
||
Json(body): Json<Value>,
|
||
) -> Result<Json<Value>, ApiError> {
|
||
let expected_updated_at = lifecycle_precondition(&body)?;
|
||
let published = state
|
||
.service
|
||
.resources()
|
||
.publish(PublishResource {
|
||
workspace_id: path.workspace_id.as_str().into(),
|
||
resource_id: path.resource_id.as_str().into(),
|
||
expected_updated_at,
|
||
})
|
||
.await?;
|
||
Ok(Json(json!(published)))
|
||
}
|
||
|
||
/// Архив проверенного Resource (Story 3.7 AC05/AC06).
|
||
///
|
||
/// Тело — `{ "expected_updated_at": "<точное значение карточки>" }`; семантика
|
||
/// precondition/428 полностью совпадает с publish, а archived-отказ отдаётся
|
||
/// существующим domain-кодом `resource_lifecycle_invalid` (409).
|
||
pub async fn archive_resource(
|
||
Path(path): Path<ResourcePath>,
|
||
State(state): State<AppState>,
|
||
Json(body): Json<Value>,
|
||
) -> Result<Json<Value>, ApiError> {
|
||
let expected_updated_at = lifecycle_precondition(&body)?;
|
||
let archived = state
|
||
.service
|
||
.resources()
|
||
.archive(ArchiveResource {
|
||
workspace_id: path.workspace_id.as_str().into(),
|
||
resource_id: path.resource_id.as_str().into(),
|
||
expected_updated_at,
|
||
})
|
||
.await?;
|
||
Ok(Json(json!(archived)))
|
||
}
|
||
|
||
/// Отзыв Resource (Story 3.8, owner decision A): 204 без тела, без payload.
|
||
///
|
||
/// Actor берётся только из authenticated session, request/trace — из серверного
|
||
/// RequestContext; middleware workspace_router уже обеспечивает session/Owner/
|
||
/// CSRF/origin/rate guards. Повтор существующего отзыва — снова 204 без нового
|
||
/// события. Archive/immutable bytes/административное чтение не меняются.
|
||
pub async fn revoke_resource(
|
||
Path(path): Path<ResourcePath>,
|
||
State(state): State<AppState>,
|
||
Extension(session): Extension<AuthenticatedSession>,
|
||
Extension(request_context): Extension<RequestContext>,
|
||
) -> Result<StatusCode, ApiError> {
|
||
state
|
||
.service
|
||
.resources()
|
||
.revoke(RevokeResourceRequest {
|
||
workspace_id: path.workspace_id.as_str().into(),
|
||
resource_id: path.resource_id.as_str().into(),
|
||
actor_user_id: session.user.id.as_str().to_owned(),
|
||
request_id: request_context.request_id().to_owned(),
|
||
trace_id: request_context.trace_id().to_owned(),
|
||
revoked_at: time::OffsetDateTime::now_utc(),
|
||
})
|
||
.await?;
|
||
Ok(StatusCode::NO_CONTENT)
|
||
}
|
||
|
||
/// Story 3.9: экспорт текущего Draft как bounded portability envelope.
|
||
///
|
||
/// Ответ всегда `application/json` + `attachment` + `nosniff`: заявленный MIME
|
||
/// Resource остаётся внутри envelope и никогда не становится HTTP content type.
|
||
pub async fn export_resource(
|
||
Path(path): Path<ResourcePath>,
|
||
State(state): State<AppState>,
|
||
) -> Result<Response, ApiError> {
|
||
let envelope = state
|
||
.service
|
||
.resources()
|
||
.export_draft_envelope(
|
||
&path.workspace_id.as_str().into(),
|
||
&path.resource_id.as_str().into(),
|
||
)
|
||
.await?;
|
||
portable_response(&envelope)
|
||
}
|
||
|
||
/// Story 3.9: экспорт точной Published Version (immutable snapshot этой ревизии).
|
||
pub async fn export_resource_version(
|
||
Path(path): Path<ResourceVersionPath>,
|
||
State(state): State<AppState>,
|
||
) -> Result<Response, ApiError> {
|
||
let envelope = state
|
||
.service
|
||
.resources()
|
||
.export_published_envelope(
|
||
&path.workspace_id.as_str().into(),
|
||
&path.resource_id.as_str().into(),
|
||
path.version,
|
||
)
|
||
.await?;
|
||
portable_response(&envelope)
|
||
}
|
||
|
||
/// Story 3.9: импорт envelope как **нового** Draft текущего владельца (201 + карточка).
|
||
///
|
||
/// Target workspace берётся только из URL, владелец — только из session; envelope не
|
||
/// может задать ни ownership, ни lifecycle. Превышение тела — тот же безопасный JSON-конверт.
|
||
pub async fn import_resource(
|
||
Path(path): Path<ResourceWorkspacePath>,
|
||
State(state): State<AppState>,
|
||
body: Result<Json<Value>, JsonRejection>,
|
||
) -> Result<Response, ApiError> {
|
||
let envelope = body.map_err(import_body_error)?;
|
||
let import = portability::parse_portable_envelope(&envelope.0)?;
|
||
let card = state
|
||
.service
|
||
.resources()
|
||
.import_envelope(path.workspace_id.as_str().into(), import)
|
||
.await?;
|
||
Ok((StatusCode::CREATED, Json(json!(card))).into_response())
|
||
}
|
||
|
||
fn portable_response(envelope: &portability::PortableEnvelope) -> Result<Response, ApiError> {
|
||
let mut headers = HeaderMap::new();
|
||
headers.insert(
|
||
header::CONTENT_TYPE,
|
||
HeaderValue::from_static("application/json"),
|
||
);
|
||
headers.insert(
|
||
header::HeaderName::from_static("x-content-type-options"),
|
||
HeaderValue::from_static("nosniff"),
|
||
);
|
||
// Filename выведен из `name` (ASCII alnum/-/_) с фиксированным суффиксом: CR/LF и
|
||
// traversal структурно невозможны.
|
||
headers.insert(
|
||
header::CONTENT_DISPOSITION,
|
||
HeaderValue::from_str(&format!(
|
||
"attachment; filename=\"{}\"",
|
||
portability::export_filename(&envelope.resource.name)
|
||
))
|
||
.map_err(|_| ApiError::internal("invalid portability export filename"))?,
|
||
);
|
||
let body = serde_json::to_vec(envelope)
|
||
.map_err(|_| ApiError::internal("invalid portability envelope"))?;
|
||
Ok((headers, body).into_response())
|
||
}
|
||
|
||
/// Отказ разбора тела импорта: реальное превышение размера — 413 с Resource-кодом,
|
||
/// остальное — 400 `resource_portability_envelope_invalid`, а не generic framework rejection.
|
||
fn import_body_error(rejection: JsonRejection) -> ApiError {
|
||
if rejection.into_response().status() == StatusCode::PAYLOAD_TOO_LARGE {
|
||
ApiError::from(crank_core::resource::ResourceError::ContentTooLarge)
|
||
} else {
|
||
ApiError::from(crank_core::resource::ResourceError::PortabilityEnvelopeInvalid)
|
||
}
|
||
}
|
||
|
||
/// Точная Published Version: девять публичных metadata полей.
|
||
pub async fn get_resource_version(
|
||
Path(path): Path<ResourceVersionPath>,
|
||
State(state): State<AppState>,
|
||
) -> Result<Json<Value>, ApiError> {
|
||
let version = state
|
||
.service
|
||
.resources()
|
||
.published_version(
|
||
&path.workspace_id.as_str().into(),
|
||
&path.resource_id.as_str().into(),
|
||
path.version,
|
||
)
|
||
.await?;
|
||
Ok(Json(json!(version)))
|
||
}
|
||
|
||
/// Байты точной Published Version: та же inert-политика, что и у Draft download.
|
||
pub async fn download_resource_version(
|
||
Path(path): Path<ResourceVersionPath>,
|
||
State(state): State<AppState>,
|
||
) -> Result<Response, ApiError> {
|
||
let download = state
|
||
.service
|
||
.resources()
|
||
.read_published_content_for_download(
|
||
&path.workspace_id.as_str().into(),
|
||
&path.resource_id.as_str().into(),
|
||
path.version,
|
||
)
|
||
.await?;
|
||
Ok(download_response(&download))
|
||
}
|
||
|
||
fn download_response(download: &crate::service::resources::ResourceDownload) -> Response {
|
||
let filename = crate::service::resources::derived_filename(&download.name, &download.mime_type);
|
||
let mut headers = HeaderMap::new();
|
||
headers.insert(
|
||
header::CONTENT_TYPE,
|
||
HeaderValue::from_static("application/octet-stream"),
|
||
);
|
||
headers.insert(
|
||
header::CONTENT_SECURITY_POLICY,
|
||
HeaderValue::from_static("default-src 'none'; sandbox"),
|
||
);
|
||
// `filename` выведен из `name` и заявленного MIME: raw upload filename не
|
||
// сохраняется вообще, поэтому CR/LF и traversal структурно невозможны (D-12).
|
||
match HeaderValue::from_str(&format!(
|
||
"attachment; filename=\"{filename}\"; filename*=UTF-8''{filename}"
|
||
)) {
|
||
Ok(value) => {
|
||
headers.insert(header::CONTENT_DISPOSITION, value);
|
||
(headers, download.bytes.clone()).into_response()
|
||
}
|
||
Err(_) => ApiError::internal("invalid resource download filename").into_response(),
|
||
}
|
||
}
|
||
|
||
fn lifecycle_precondition(body: &Value) -> Result<Option<String>, ApiError> {
|
||
let object = body
|
||
.as_object()
|
||
.ok_or_else(|| ApiError::validation("resource lifecycle body must be a JSON object"))?;
|
||
match object.get("expected_updated_at") {
|
||
None | Some(Value::Null) => Ok(None),
|
||
Some(Value::String(value)) => Ok(Some(value.clone())),
|
||
Some(_) => Err(ApiError::validation(
|
||
"resource field `expected_updated_at` must be a JSON string",
|
||
)),
|
||
}
|
||
}
|
||
|
||
pub async fn download_resource(
|
||
Path(path): Path<ResourcePath>,
|
||
State(state): State<AppState>,
|
||
) -> Result<Response, ApiError> {
|
||
let download = state
|
||
.service
|
||
.resources()
|
||
.read_content_for_download(
|
||
&path.workspace_id.as_str().into(),
|
||
&path.resource_id.as_str().into(),
|
||
)
|
||
.await?;
|
||
let filename = crate::service::resources::derived_filename(&download.name, &download.mime_type);
|
||
let mut headers = HeaderMap::new();
|
||
headers.insert(
|
||
header::CONTENT_TYPE,
|
||
HeaderValue::from_static("application/octet-stream"),
|
||
);
|
||
headers.insert(
|
||
header::CONTENT_SECURITY_POLICY,
|
||
HeaderValue::from_static("default-src 'none'; sandbox"),
|
||
);
|
||
// `filename` выведен из `name` и заявленного MIME: raw upload filename не
|
||
// сохраняется вообще, поэтому CR/LF и traversal структурно невозможны (D-12).
|
||
headers.insert(
|
||
header::CONTENT_DISPOSITION,
|
||
HeaderValue::from_str(&format!(
|
||
"attachment; filename=\"{filename}\"; filename*=UTF-8''{filename}"
|
||
))
|
||
.map_err(|_| ApiError::internal("invalid resource download filename"))?,
|
||
);
|
||
Ok((headers, download.bytes).into_response())
|
||
}
|
||
|
||
/// Разбор multipart: часть `metadata` (JSON-объект) + часть `content` (сырые bytes).
|
||
///
|
||
/// Содержимое **не** оценивается здесь: превышение предела фиксируется лимитом
|
||
/// фреймворка, а стабильные коды (метаданные → precondition → содержимое)
|
||
/// назначает сервис в порядке D-20. Оборванное тело внутри окна лимита — отказ
|
||
/// формы запроса (400), а не «превышение размера»: иначе клиент получал бы
|
||
/// неверный код за запрос, который просто не дочитан (P2).
|
||
async fn read_draft_multipart(
|
||
multipart: Result<Multipart, MultipartRejection>,
|
||
) -> Result<(Map<String, Value>, Option<Vec<u8>>), ApiError> {
|
||
let mut multipart = multipart.map_err(multipart_rejection)?;
|
||
let mut metadata: Option<Map<String, Value>> = None;
|
||
let mut content: Option<Vec<u8>> = None;
|
||
while let Some(field) = multipart.next_field().await.map_err(multipart_error)? {
|
||
match field.name() {
|
||
Some("metadata") => {
|
||
if metadata.is_some() {
|
||
return Err(malformed_multipart());
|
||
}
|
||
let bytes = field.bytes().await.map_err(multipart_error)?;
|
||
let value: Value = serde_json::from_slice(&bytes)
|
||
.map_err(|_| ApiError::validation("invalid resource metadata"))?;
|
||
metadata = Some(value.as_object().cloned().ok_or_else(|| {
|
||
ApiError::validation("resource metadata must be a JSON object")
|
||
})?);
|
||
}
|
||
Some("content") => {
|
||
if content.is_some() {
|
||
return Err(malformed_multipart());
|
||
}
|
||
let bytes = field.bytes().await.map_err(multipart_error)?;
|
||
content = Some(bytes.to_vec());
|
||
}
|
||
_ => return Err(malformed_multipart()),
|
||
}
|
||
}
|
||
let metadata = metadata.ok_or_else(malformed_multipart)?;
|
||
// Story 3.10: часть `content` необязательна только для template Draft; обязательность
|
||
// для static Resource проверяет вызывающий маршрут.
|
||
Ok((metadata, content))
|
||
}
|
||
|
||
/// `metadata.source` присутствует ⇒ часть `content` обязана отсутствовать.
|
||
fn content_absent(source: Option<&Value>, content: Option<Vec<u8>>) -> Result<Value, ApiError> {
|
||
if content.is_some() {
|
||
return Err(crank_core::resource::ResourceError::SourceInvalid { field: "content" }.into());
|
||
}
|
||
source.cloned().ok_or_else(|| {
|
||
crank_core::resource::ResourceError::SourceInvalid { field: "source" }.into()
|
||
})
|
||
}
|
||
|
||
/// Обновление template Draft: `source` адресует pinned `input_schema`, а
|
||
/// identity-поля (`uri`/`name`/`kind`) принимаются только без изменения значения.
|
||
fn update_template_draft(
|
||
workspace_id: &str,
|
||
resource_id: &str,
|
||
metadata: &Map<String, Value>,
|
||
source: Value,
|
||
) -> Result<UpdateTemplateDraft, ApiError> {
|
||
Ok(UpdateTemplateDraft {
|
||
workspace_id: workspace_id.into(),
|
||
resource_id: resource_id.into(),
|
||
description: default_text(metadata, "description")?,
|
||
mime_type: required_text(metadata, "mime_type")?,
|
||
sensitivity: required_text(metadata, "sensitivity")?,
|
||
expected_updated_at: optional_timestamp(metadata, "expected_updated_at")?,
|
||
identity: template_identity(metadata)?,
|
||
source: Some(source),
|
||
})
|
||
}
|
||
|
||
fn template_identity(metadata: &Map<String, Value>) -> Result<TemplateIdentity, ApiError> {
|
||
let kind = optional_text(metadata, "kind")?;
|
||
if kind
|
||
.as_deref()
|
||
.is_some_and(|value| ResourceKind::parse(value).is_none())
|
||
{
|
||
return Err(unknown_enum("kind"));
|
||
}
|
||
Ok(TemplateIdentity {
|
||
uri: optional_text(metadata, "uri")?,
|
||
name: optional_text(metadata, "name")?,
|
||
kind,
|
||
})
|
||
}
|
||
|
||
fn optional_text(metadata: &Map<String, Value>, key: &str) -> Result<Option<String>, ApiError> {
|
||
match metadata.get(key) {
|
||
None => Ok(None),
|
||
Some(Value::String(value)) => Ok(Some(value.clone())),
|
||
Some(_) => Err(wrong_json_type(key)),
|
||
}
|
||
}
|
||
|
||
/// Метаданные создания: шаг B (форма запроса) + шаг E (поля) в порядке D-20.
|
||
///
|
||
/// Здесь проверяется только то, что относится к форме запроса (шаг B): неизвестный
|
||
/// `kind` и типы полей. Поля метаданных и значение `sensitivity` проверяются сервисом
|
||
/// на их собственном шаге E в порядке `uri → name → description → kind → mime_type →
|
||
/// sensitivity`, поэтому неизвестная `sensitivity` не может опередить более раннее поле.
|
||
fn create_metadata(metadata: &Map<String, Value>) -> Result<DraftMetadata, ApiError> {
|
||
let kind = required_text(metadata, "kind")?;
|
||
if ResourceKind::parse(&kind).is_none() {
|
||
return Err(unknown_enum("kind"));
|
||
}
|
||
Ok(DraftMetadata {
|
||
uri: required_text(metadata, "uri")?,
|
||
name: required_text(metadata, "name")?,
|
||
description: default_text(metadata, "description")?,
|
||
kind,
|
||
mime_type: required_text(metadata, "mime_type")?,
|
||
sensitivity: required_text(metadata, "sensitivity")?,
|
||
})
|
||
}
|
||
|
||
/// Обновление Draft: `uri`/`name`/`kind` не принимаются как изменяемые значения —
|
||
/// их **присутствие** уже нарушение неизменяемости (D-16), включая `null`.
|
||
///
|
||
/// Здесь проверяется форма запроса (шаг B): типы immutable-ключей и обязательных
|
||
/// полей, а неизвестный `kind` — тоже B. Само присутствие immutable-ключа — шаг D,
|
||
/// который исполняет сервис. Значение `sensitivity` (шаг E, последнее поле) сервис
|
||
/// проверяет уже после разрешения Resource (C) и шага D, поэтому неизвестная
|
||
/// `sensitivity` не может ни опередить C/D, ни превратиться во внутреннюю ошибку.
|
||
fn update_draft(
|
||
workspace_id: &str,
|
||
resource_id: &str,
|
||
metadata: &Map<String, Value>,
|
||
bytes: Vec<u8>,
|
||
) -> Result<UpdateDraft, ApiError> {
|
||
let description = default_text(metadata, "description")?;
|
||
let mime_type = required_text(metadata, "mime_type")?;
|
||
let sensitivity = required_text(metadata, "sensitivity")?;
|
||
let expected_updated_at = optional_timestamp(metadata, "expected_updated_at")?;
|
||
let immutable_fields = immutable_fields(metadata)?;
|
||
Ok(UpdateDraft {
|
||
workspace_id: workspace_id.into(),
|
||
resource_id: resource_id.into(),
|
||
description,
|
||
mime_type,
|
||
sensitivity,
|
||
expected_updated_at,
|
||
immutable_fields,
|
||
bytes,
|
||
})
|
||
}
|
||
|
||
/// Присутствие immutable-ключей (D-16) с шагом B для их неверного JSON-типа.
|
||
fn immutable_fields(metadata: &Map<String, Value>) -> Result<Vec<ImmutableField>, ApiError> {
|
||
let mut fields = Vec::new();
|
||
for (key, field) in [
|
||
("uri", ImmutableField::Uri),
|
||
("name", ImmutableField::Name),
|
||
("kind", ImmutableField::Kind),
|
||
] {
|
||
match metadata.get(key) {
|
||
// Ключа нет — валидное обновление изменяемых полей.
|
||
None => {}
|
||
// Присутствие ключа — уже нарушение неизменяемости, значение не важно.
|
||
Some(Value::Null) => fields.push(field),
|
||
Some(Value::String(value)) => {
|
||
// Неизвестный `kind` — отказ формы запроса (D-20 B), а не шаг D;
|
||
// известный `kind` остаётся нарушением неизменяемости (D).
|
||
if field == ImmutableField::Kind && ResourceKind::parse(value).is_none() {
|
||
return Err(unknown_enum("kind"));
|
||
}
|
||
fields.push(field);
|
||
}
|
||
// Значение другого JSON-типа — форма запроса не распознана (D-20 B).
|
||
Some(_) => return Err(wrong_json_type(key)),
|
||
}
|
||
}
|
||
Ok(fields)
|
||
}
|
||
|
||
/// Обязательное поле метаданных: отсутствующее или не-строковое — шаг B.
|
||
fn required_text(metadata: &Map<String, Value>, key: &str) -> Result<String, ApiError> {
|
||
match metadata.get(key) {
|
||
Some(Value::String(value)) => Ok(value.clone()),
|
||
_ => Err(wrong_json_type(key)),
|
||
}
|
||
}
|
||
|
||
/// Необязательное текстовое поле: отсутствие — значение по умолчанию `""`.
|
||
fn default_text(metadata: &Map<String, Value>, key: &str) -> Result<String, ApiError> {
|
||
match metadata.get(key) {
|
||
None => Ok(String::new()),
|
||
Some(Value::String(value)) => Ok(value.clone()),
|
||
Some(_) => Err(wrong_json_type(key)),
|
||
}
|
||
}
|
||
|
||
/// Необязательный precondition: отсутствие и `null` — «не задан» (шаг F даёт 428).
|
||
fn optional_timestamp(
|
||
metadata: &Map<String, Value>,
|
||
key: &str,
|
||
) -> Result<Option<String>, ApiError> {
|
||
match metadata.get(key) {
|
||
None | Some(Value::Null) => Ok(None),
|
||
Some(Value::String(value)) => Ok(Some(value.clone())),
|
||
Some(_) => Err(wrong_json_type(key)),
|
||
}
|
||
}
|
||
|
||
fn unknown_enum(key: &str) -> ApiError {
|
||
ApiError::validation(format!(
|
||
"resource metadata field `{key}` has an unknown value"
|
||
))
|
||
}
|
||
|
||
fn wrong_json_type(key: &str) -> ApiError {
|
||
ApiError::validation(format!(
|
||
"resource metadata field `{key}` must be a JSON string"
|
||
))
|
||
}
|
||
|
||
fn malformed_multipart() -> ApiError {
|
||
// Шаг B порядка D-20: расхождение формы запроса — generic validation_error
|
||
// без Resource-специфичного кода.
|
||
ApiError::validation("invalid resource multipart upload")
|
||
}
|
||
|
||
fn content_too_large() -> ApiError {
|
||
ApiError::from(crank_core::resource::ResourceError::ContentTooLarge)
|
||
}
|
||
|
||
/// Отказ чтения части multipart: реальное превышение размера остаётся 413,
|
||
/// оборванное или нечитаемое тело — клиентская ошибка формы (400).
|
||
fn multipart_error(error: axum::extract::multipart::MultipartError) -> ApiError {
|
||
if error.status() == StatusCode::PAYLOAD_TOO_LARGE {
|
||
content_too_large()
|
||
} else {
|
||
malformed_multipart()
|
||
}
|
||
}
|
||
|
||
fn multipart_rejection(rejection: MultipartRejection) -> ApiError {
|
||
if rejection.into_response().status() == StatusCode::PAYLOAD_TOO_LARGE {
|
||
content_too_large()
|
||
} else {
|
||
malformed_multipart()
|
||
}
|
||
}
|