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.
298 lines
12 KiB
Rust
298 lines
12 KiB
Rust
//! Story 3.9: bounded portability envelope — экспорт текущего Draft / точной
|
|
//! Published Version и импорт как **нового** Draft текущего владельца.
|
|
//!
|
|
//! Транспортный контракт (allowlist ключей, base64, digest) живёт здесь, в admin-api:
|
|
//! домен (`crank-core`) отвечает только за стабильный код отказа
|
|
//! `resource_portability_envelope_invalid`. Импорт не восстанавливает идентичность:
|
|
//! `source` — только provenance, новый Resource всегда получает новый `resource_id`,
|
|
//! `current_draft_version = 1` и не публикуется. Владелец и target workspace берутся
|
|
//! из authenticated session и URL, никогда из envelope.
|
|
|
|
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
|
|
use crank_core::WorkspaceId;
|
|
use crank_core::ids::ResourceId;
|
|
use crank_core::resource::{ResourceError, ResourceKind};
|
|
use serde::Serialize;
|
|
use serde_json::{Map, Value};
|
|
|
|
use super::{DraftMetadata, NewDraft, ResourcesService};
|
|
|
|
/// Единственный поддерживаемый формат переносимого документа.
|
|
pub(crate) const ENVELOPE_FORMAT: &str = "crank-resource-portability";
|
|
pub(crate) const ENVELOPE_VERSION: u64 = 1;
|
|
|
|
/// Предел тела импорта: base64-накладные расходы (`MAX_ARTIFACT_BYTES / 3 * 4`) плюс
|
|
/// 64 KiB на metadata оболочки. Равен 415 060 байт; лимит содержимого не меняется.
|
|
pub(crate) const MAX_IMPORT_BODY_BYTES: usize =
|
|
crank_artifacts::MAX_ARTIFACT_BYTES / 3 * 4 + 64 * 1024;
|
|
|
|
const ROOT_KEYS: [&str; 5] = ["format", "version", "resource", "source", "content"];
|
|
const RESOURCE_KEYS: [&str; 6] = [
|
|
"uri",
|
|
"name",
|
|
"description",
|
|
"kind",
|
|
"mime_type",
|
|
"sensitivity",
|
|
];
|
|
const SOURCE_KEYS: [&str; 2] = ["kind", "version"];
|
|
const CONTENT_KEYS: [&str; 3] = ["size_bytes", "digest", "base64"];
|
|
|
|
/// Переносимый документ в wire-форме (экспорт и разобранный импорт).
|
|
#[derive(Clone, Debug, Serialize)]
|
|
pub(crate) struct PortableEnvelope {
|
|
pub format: &'static str,
|
|
pub version: u64,
|
|
pub resource: PortableResourceBlock,
|
|
pub source: PortableSourceBlock,
|
|
pub content: PortableContentBlock,
|
|
}
|
|
|
|
#[derive(Clone, Debug, Serialize)]
|
|
pub(crate) struct PortableResourceBlock {
|
|
pub uri: String,
|
|
pub name: String,
|
|
pub description: String,
|
|
pub kind: String,
|
|
pub mime_type: String,
|
|
pub sensitivity: String,
|
|
}
|
|
|
|
/// `source` — только provenance: `draft` с ревизией содержимого либо `published`
|
|
/// с номером точной версии. Импорт по нему ничего не восстанавливает.
|
|
#[derive(Clone, Debug, Serialize)]
|
|
pub(crate) struct PortableSourceBlock {
|
|
pub kind: String,
|
|
pub version: u32,
|
|
}
|
|
|
|
#[derive(Clone, Debug, Serialize)]
|
|
pub(crate) struct PortableContentBlock {
|
|
pub size_bytes: i64,
|
|
pub digest: String,
|
|
pub base64: String,
|
|
}
|
|
|
|
/// Разобранный envelope импорта: metadata + уже декодированные bytes.
|
|
pub(crate) struct PortableImport {
|
|
pub resource: PortableResourceBlock,
|
|
pub bytes: Vec<u8>,
|
|
pub size_bytes: i64,
|
|
pub digest: String,
|
|
}
|
|
|
|
impl ResourcesService {
|
|
/// Экспорт текущего содержимого Draft: metadata и bytes берутся из **одного**
|
|
/// pinned-разрешения версии, второй путь чтения не открывается.
|
|
pub(crate) async fn export_draft_envelope(
|
|
&self,
|
|
workspace_id: &WorkspaceId,
|
|
resource_id: &ResourceId,
|
|
) -> Result<PortableEnvelope, ResourceError> {
|
|
// Story 3.10: definition-only Resource не переносим (нет content envelope).
|
|
if self.is_template_draft(workspace_id, resource_id).await? {
|
|
return Err(ResourceError::SourceNotPortable);
|
|
}
|
|
let (bytes, resolved) = self.load_content(workspace_id, resource_id).await?;
|
|
let snapshot = resolved.snapshot;
|
|
Ok(PortableEnvelope {
|
|
format: ENVELOPE_FORMAT,
|
|
version: ENVELOPE_VERSION,
|
|
resource: PortableResourceBlock {
|
|
uri: snapshot.resource.uri,
|
|
name: snapshot.resource.name,
|
|
description: snapshot.resource.description,
|
|
kind: snapshot.resource.kind,
|
|
mime_type: snapshot.version.mime_type,
|
|
sensitivity: snapshot.version.sensitivity,
|
|
},
|
|
source: PortableSourceBlock {
|
|
kind: "draft".to_owned(),
|
|
version: snapshot.version.version,
|
|
},
|
|
content: content_block(&bytes),
|
|
})
|
|
}
|
|
|
|
/// Экспорт **точной** Published Version: immutable snapshot и его bytes из одного
|
|
/// разрешения; существующие revoke/read/integrity semantics сохраняются, второго
|
|
/// пути чтения `ArtifactStore` не открывается.
|
|
pub(crate) async fn export_published_envelope(
|
|
&self,
|
|
workspace_id: &WorkspaceId,
|
|
resource_id: &ResourceId,
|
|
version: u32,
|
|
) -> Result<PortableEnvelope, ResourceError> {
|
|
// Story 3.10: опубликованное определение шаблона не экспортируется как content.
|
|
if self
|
|
.publication_is_template(workspace_id, resource_id, version)
|
|
.await?
|
|
{
|
|
return Err(ResourceError::SourceNotPortable);
|
|
}
|
|
let (bytes, publication) = self
|
|
.load_published_content(workspace_id, resource_id, version)
|
|
.await?;
|
|
Ok(PortableEnvelope {
|
|
format: ENVELOPE_FORMAT,
|
|
version: ENVELOPE_VERSION,
|
|
resource: PortableResourceBlock {
|
|
uri: publication.uri,
|
|
name: publication.name,
|
|
description: publication.description,
|
|
kind: publication.kind,
|
|
mime_type: publication.mime_type,
|
|
sensitivity: publication.sensitivity,
|
|
},
|
|
source: PortableSourceBlock {
|
|
kind: "published".to_owned(),
|
|
version: publication.version,
|
|
},
|
|
content: content_block(&bytes),
|
|
})
|
|
}
|
|
|
|
/// Импорт envelope: integrity/bounded-проверки → существующий `create_draft`.
|
|
///
|
|
/// Никакого upsert/update: при занятых uri/name реестр отвечает существующими
|
|
/// `resource_uri_duplicate` / `resource_name_duplicate` (409). Публикации нет.
|
|
pub(crate) async fn import_envelope(
|
|
&self,
|
|
workspace_id: WorkspaceId,
|
|
import: PortableImport,
|
|
) -> Result<super::ResourceCardResponse, ResourceError> {
|
|
let PortableImport {
|
|
resource,
|
|
bytes,
|
|
size_bytes,
|
|
digest,
|
|
} = import;
|
|
if i64::try_from(bytes.len()).unwrap_or(i64::MAX) != size_bytes
|
|
|| super::sha256_hex(&bytes) != digest
|
|
{
|
|
return Err(ResourceError::ArtifactIntegrity);
|
|
}
|
|
let kind = ResourceKind::parse(&resource.kind).ok_or(ResourceError::KindMismatch)?;
|
|
if bytes.len() > self.limits.effective_limit(kind) {
|
|
return Err(ResourceError::ContentTooLarge);
|
|
}
|
|
let created = self
|
|
.create_draft(NewDraft {
|
|
workspace_id: workspace_id.clone(),
|
|
metadata: DraftMetadata {
|
|
uri: resource.uri,
|
|
name: resource.name,
|
|
description: resource.description,
|
|
kind: resource.kind,
|
|
mime_type: resource.mime_type,
|
|
sensitivity: resource.sensitivity,
|
|
},
|
|
bytes,
|
|
})
|
|
.await?;
|
|
self.card(&workspace_id, &created.resource_id).await
|
|
}
|
|
}
|
|
|
|
/// Разбор envelope со **строгим** allowlist: любой неизвестный ключ (в том числе
|
|
/// `artifact`, `owner`, `workspace_id`, `resource_id`, `status`, `path`) — отказ формы.
|
|
pub(crate) fn parse_portable_envelope(value: &Value) -> Result<PortableImport, ResourceError> {
|
|
let root = block(value, &ROOT_KEYS)?;
|
|
if root["format"].as_str() != Some(ENVELOPE_FORMAT) {
|
|
return Err(envelope_invalid());
|
|
}
|
|
if root["version"].as_u64() != Some(ENVELOPE_VERSION) {
|
|
return Err(envelope_invalid());
|
|
}
|
|
|
|
let resource = block(&root["resource"], &RESOURCE_KEYS)?;
|
|
let resource = PortableResourceBlock {
|
|
uri: text(resource, "uri")?,
|
|
name: text(resource, "name")?,
|
|
description: text(resource, "description")?,
|
|
kind: text(resource, "kind")?,
|
|
mime_type: text(resource, "mime_type")?,
|
|
sensitivity: text(resource, "sensitivity")?,
|
|
};
|
|
|
|
let source = block(&root["source"], &SOURCE_KEYS)?;
|
|
match source["kind"].as_str() {
|
|
Some("draft") | Some("published") => {}
|
|
_ => return Err(envelope_invalid()),
|
|
}
|
|
// `source.version` — только provenance: проверяется по форме (целое ≥ 1) и не
|
|
// восстанавливает ни ревизию, ни идентичность импортируемого Draft.
|
|
source["version"]
|
|
.as_u64()
|
|
.filter(|value| (1..=u32::MAX as u64).contains(value))
|
|
.ok_or_else(envelope_invalid)?;
|
|
|
|
let content = block(&root["content"], &CONTENT_KEYS)?;
|
|
let size_bytes = content["size_bytes"]
|
|
.as_i64()
|
|
.filter(|value| *value >= 0)
|
|
.ok_or_else(envelope_invalid)?;
|
|
let digest = text(content, "digest")?;
|
|
let digest_is_lowercase_hex = digest.len() == 64
|
|
&& digest
|
|
.bytes()
|
|
.all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase());
|
|
if !digest_is_lowercase_hex {
|
|
return Err(envelope_invalid());
|
|
}
|
|
let encoded = text(content, "base64")?;
|
|
let bytes = BASE64
|
|
.decode(encoded.as_bytes())
|
|
.map_err(|_| envelope_invalid())?;
|
|
|
|
Ok(PortableImport {
|
|
resource,
|
|
bytes,
|
|
size_bytes,
|
|
digest,
|
|
})
|
|
}
|
|
|
|
/// `<sanitized name>.crank-resource.json` — только ASCII, без CR/LF и traversal.
|
|
pub(crate) fn export_filename(name: &str) -> String {
|
|
let stem: String = name
|
|
.chars()
|
|
.filter(|character| character.is_ascii_alphanumeric() || matches!(character, '-' | '_'))
|
|
.take(64)
|
|
.collect();
|
|
let stem = if stem.is_empty() {
|
|
"resource"
|
|
} else {
|
|
stem.as_str()
|
|
};
|
|
format!("{stem}.crank-resource.json")
|
|
}
|
|
|
|
fn content_block(bytes: &[u8]) -> PortableContentBlock {
|
|
PortableContentBlock {
|
|
size_bytes: i64::try_from(bytes.len()).unwrap_or(i64::MAX),
|
|
digest: super::sha256_hex(bytes),
|
|
base64: BASE64.encode(bytes),
|
|
}
|
|
}
|
|
|
|
/// Ровно объявленный набор ключей: объект, ни одного лишнего, ни одного недостающего.
|
|
fn block<'a>(value: &'a Value, keys: &[&str]) -> Result<&'a Map<String, Value>, ResourceError> {
|
|
let object = value.as_object().ok_or_else(envelope_invalid)?;
|
|
if object.len() != keys.len() || object.keys().any(|key| !keys.contains(&key.as_str())) {
|
|
return Err(envelope_invalid());
|
|
}
|
|
Ok(object)
|
|
}
|
|
|
|
fn text(object: &Map<String, Value>, key: &str) -> Result<String, ResourceError> {
|
|
object[key]
|
|
.as_str()
|
|
.map(str::to_owned)
|
|
.ok_or_else(envelope_invalid)
|
|
}
|
|
|
|
fn envelope_invalid() -> ResourceError {
|
|
ResourceError::PortabilityEnvelopeInvalid
|
|
}
|