Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9e9c326c3e | ||
|
|
178093e81b | ||
|
|
ad23cd9a46 | ||
|
|
31f6f00d3b | ||
|
|
f685616ae8 |
No files matched your search
@@ -304,6 +304,14 @@ jobs:
|
||||
crank/mcp-server:ci \
|
||||
crank/ui:ci
|
||||
|
||||
- name: Save Community image scan evidence
|
||||
if: always()
|
||||
uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 # v4
|
||||
with:
|
||||
name: image-scan-evidence
|
||||
path: .tmp/image-scan-evidence
|
||||
if-no-files-found: warn
|
||||
|
||||
- name: Start Community image stack
|
||||
run: |
|
||||
mkdir -p .tmp
|
||||
@@ -458,6 +466,14 @@ jobs:
|
||||
docker push '${{ env.UI_IMAGE }}:${{ env.IMAGE_TAG }}'
|
||||
docker push '${{ env.UI_IMAGE }}:main'
|
||||
|
||||
- name: Save deploy image scan evidence
|
||||
if: always()
|
||||
uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 # v4
|
||||
with:
|
||||
name: deploy-image-scan-evidence
|
||||
path: .tmp/image-scan-evidence
|
||||
if-no-files-found: warn
|
||||
|
||||
- name: Configure SSH key
|
||||
run: |
|
||||
. "$OPENBAO_ENV_FILE"
|
||||
|
||||
Generated
+2
@@ -43,7 +43,9 @@ dependencies = [
|
||||
"metrics",
|
||||
"metrics-util",
|
||||
"opentelemetry",
|
||||
"opentelemetry-proto",
|
||||
"opentelemetry_sdk",
|
||||
"prost",
|
||||
"rand 0.10.2",
|
||||
"reqwest 0.12.28",
|
||||
"serde",
|
||||
|
||||
@@ -52,7 +52,9 @@ crank-test-support = { path = "../../crates/crank-test-support" }
|
||||
metrics.workspace = true
|
||||
metrics-util = "0.20.4"
|
||||
opentelemetry.workspace = true
|
||||
opentelemetry-proto.workspace = true
|
||||
opentelemetry_sdk.workspace = true
|
||||
prost.workspace = true
|
||||
reqwest.workspace = true
|
||||
serial_test = "3"
|
||||
tower.workspace = true
|
||||
|
||||
+29
-10
@@ -15,33 +15,52 @@ RUN --mount=type=cache,id=crank-admin-cargo-registry,target=/usr/local/cargo/reg
|
||||
&& cp /app/target/release/admin-api /tmp/admin-api \
|
||||
&& cp /app/target/release/crank-migrate /tmp/crank-migrate
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
# Trusted CA bundle source for the package stage. The slim image ships no CA
|
||||
# certificates, so the HTTPS Debian mirror can only be reached after seeding
|
||||
# them; the Rust base image provides the bundle without rebuilding the app.
|
||||
FROM rust:1.96.1-bookworm AS ca-bundle
|
||||
|
||||
RUN test -s /etc/ssl/certs/ca-certificates.crt
|
||||
|
||||
# Package stage: install the security-refreshed Debian packages, then assemble
|
||||
# the minimal runtime rootfs. Kept independent of the Rust builder so it can be
|
||||
# built and reviewed on its own.
|
||||
FROM debian:bookworm-slim AS runtime-rootfs
|
||||
|
||||
ARG CRANK_SECURITY_REFRESH
|
||||
|
||||
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
|
||||
COPY --from=ca-bundle /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
|
||||
COPY scripts/prepare-runtime-rootfs.sh /usr/local/bin/prepare-runtime-rootfs
|
||||
|
||||
RUN sed -i 's|http://deb.debian.org|https://deb.debian.org|g' /etc/apt/sources.list.d/debian.sources \
|
||||
&& apt-get update \
|
||||
&& apt-get install -y --no-install-recommends --only-upgrade libpcre2-8-0 perl-base \
|
||||
&& apt-get install -y --no-install-recommends --only-upgrade \
|
||||
base-files libc6 libgcc-s1 gcc-12-base bash dash libtinfo6 libselinux1 libpcre2-8-0 coreutils \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& dpkg --compare-versions "$(dpkg-query -W -f='${Version}' libpcre2-8-0)" ge '10.42-1+deb12u2' \
|
||||
&& dpkg --compare-versions "$(dpkg-query -W -f='${Version}' perl-base)" ge '5.36.0-7+deb12u4' \
|
||||
&& sh /usr/local/bin/prepare-runtime-rootfs /runtime \
|
||||
&& echo "crank-security-refresh=${CRANK_SECURITY_REFRESH}"
|
||||
|
||||
WORKDIR /app
|
||||
COPY apps/admin-api/docker-entrypoint.sh /runtime/usr/local/bin/crank-admin-entrypoint
|
||||
COPY scripts/docker-http-healthcheck.sh /runtime/usr/local/bin/crank-http-healthcheck
|
||||
|
||||
RUN chmod 0755 /runtime/usr/local/bin/crank-admin-entrypoint \
|
||||
&& chmod 0755 /runtime/usr/local/bin/crank-http-healthcheck
|
||||
|
||||
FROM scratch
|
||||
|
||||
COPY --from=ca-bundle /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
|
||||
COPY --from=runtime-rootfs /runtime /
|
||||
|
||||
COPY --from=builder /tmp/admin-api /usr/local/bin/admin-api
|
||||
COPY --from=builder /tmp/crank-migrate /usr/local/bin/crank-migrate
|
||||
COPY apps/admin-api/docker-entrypoint.sh /usr/local/bin/crank-admin-entrypoint
|
||||
COPY scripts/docker-http-healthcheck.sh /usr/local/bin/crank-http-healthcheck
|
||||
|
||||
RUN test -s /etc/ssl/certs/ca-certificates.crt \
|
||||
&& chmod 0755 /usr/local/bin/crank-admin-entrypoint /usr/local/bin/crank-http-healthcheck
|
||||
|
||||
ENV PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
||||
ENV CRANK_ADMIN_BIND=0.0.0.0:3001
|
||||
ENV CRANK_STORAGE_ROOT=/var/lib/crank/storage
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
EXPOSE 3001
|
||||
|
||||
ENTRYPOINT ["/usr/local/bin/crank-admin-entrypoint"]
|
||||
|
||||
@@ -4,7 +4,7 @@ set -eu
|
||||
# Docker creates a fresh named volume as root:root 0755. The artifact store
|
||||
# deliberately rejects that mode: before starting the API, provision exactly
|
||||
# the private root its pinned-directory checks require.
|
||||
if [ "$#" -gt 0 ] && [ "$1" = "admin-api" ]; then
|
||||
provision_storage_root() {
|
||||
storage_root="${CRANK_STORAGE_ROOT:-/var/lib/crank/storage}"
|
||||
case "$storage_root" in
|
||||
/*) ;;
|
||||
@@ -20,6 +20,17 @@ if [ "$#" -gt 0 ] && [ "$1" = "admin-api" ]; then
|
||||
umask 077
|
||||
mkdir -p -- "$storage_root"
|
||||
chmod 0700 -- "$storage_root"
|
||||
}
|
||||
|
||||
# The dedicated init service calls this entrypoint as `crank-storage-init`; it
|
||||
# provisions the artifact root and exits without running a server binary.
|
||||
if [ "${1:-}" = "crank-storage-init" ]; then
|
||||
provision_storage_root
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ "${1:-}" = "admin-api" ]; then
|
||||
provision_storage_root
|
||||
fi
|
||||
|
||||
exec "$@"
|
||||
@@ -0,0 +1,49 @@
|
||||
//! Read-only database observation for the local Playwright harness.
|
||||
//! This example is never packaged as an application endpoint or executable.
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let workspace = std::env::args().nth(1).expect("test workspace argument");
|
||||
assert!(
|
||||
!workspace.is_empty()
|
||||
&& workspace.len() <= 128
|
||||
&& workspace
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || b"_-".contains(&byte)),
|
||||
"invalid test workspace argument"
|
||||
);
|
||||
let config = crank_config::parse_migrator(
|
||||
crank_config::ConfigSource::from_os_for_migrator().expect("test configuration source"),
|
||||
)
|
||||
.expect("test database configuration");
|
||||
let database = config.database;
|
||||
let options = if let Some(url) = &database.url {
|
||||
url.expose_secret()
|
||||
.parse::<sqlx::postgres::PgConnectOptions>()
|
||||
.expect("test database URL")
|
||||
} else {
|
||||
sqlx::postgres::PgConnectOptions::new()
|
||||
.host(&database.host)
|
||||
.port(database.port)
|
||||
.database(&database.database)
|
||||
.username(&database.username)
|
||||
.password(database.password.expose_secret())
|
||||
};
|
||||
let pool = sqlx::postgres::PgPoolOptions::new()
|
||||
.max_connections(1)
|
||||
.connect_with(options)
|
||||
.await
|
||||
.expect("test database connection");
|
||||
let (sources, operations, versions): (i64, i64, i64) = sqlx::query_as(
|
||||
"select
|
||||
(select count(*) from artifact_sources where workspace_id=$1),
|
||||
(select count(*) from operations where workspace_id=$1),
|
||||
(select count(*) from operation_versions v
|
||||
join operations o on o.id=v.operation_id where o.workspace_id=$1)",
|
||||
)
|
||||
.bind(workspace)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.expect("test storage observation");
|
||||
println!("{{\"sources\":{sources},\"operations\":{operations},\"versions\":{versions}}}");
|
||||
}
|
||||
@@ -12,6 +12,7 @@ use std::{
|
||||
use async_trait::async_trait;
|
||||
use crank_artifacts::{ReconciliationRegistration, RegisteredArtifact};
|
||||
use crank_registry::MigrationAuthority;
|
||||
use sqlx::Row;
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -688,3 +689,6 @@ async fn expired_claim_cursor_prevents_unsafe_prefix_starvation_across_ticks() {
|
||||
.unwrap();
|
||||
assert_eq!(second_lifecycle, "unavailable");
|
||||
}
|
||||
|
||||
#[path = "tests/commit_failure.rs"]
|
||||
mod commit_failure;
|
||||
@@ -0,0 +1,149 @@
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn finalize_commit_failure_stays_retryable_and_recovers_on_a_fresh_cycle() {
|
||||
let database_url =
|
||||
crank_test_support::postgres_schema_url("admin_reconciliation_commit_failure").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
let registry = PostgresRegistry::connect(&database_url).await.unwrap();
|
||||
let root = TestRoot::new();
|
||||
let store = ArtifactStore::open(&root.0).unwrap();
|
||||
let now = OffsetDateTime::now_utc();
|
||||
|
||||
let artifact = store
|
||||
.put_registered(b"commit-failure physical absence\n")
|
||||
.unwrap();
|
||||
let outcome = registry
|
||||
.claim_artifact_reconciliation(ClaimArtifactReconciliationRequest {
|
||||
artifact: &artifact,
|
||||
token: ArtifactClaimToken::generate(),
|
||||
claimed_at: now - time::Duration::minutes(10),
|
||||
lease_expires_at: now - time::Duration::minutes(5),
|
||||
detached_grace: time::Duration::hours(24),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(matches!(outcome, ArtifactClaimOutcome::Claimed(_)));
|
||||
remove_registered_artifact(&store, &artifact);
|
||||
sqlx::query(
|
||||
"update artifact_blobs
|
||||
set claim_expires_at = clock_timestamp() - interval '1 second'
|
||||
where digest = $1",
|
||||
)
|
||||
.bind(artifact.artifact_ref().digest_hex())
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// A deferred constraint trigger fails the COMMIT that records
|
||||
// `unavailable`, modelling a real failure after the physical unlink that
|
||||
// removed the last bytes already succeeded. It lives only in this isolated
|
||||
// test schema.
|
||||
sqlx::raw_sql(
|
||||
"create function crank_test_fail_unavailable() returns trigger language plpgsql as $$
|
||||
begin
|
||||
if new.storage_lifecycle = 'unavailable' then
|
||||
raise exception 'injected finalize commit failure';
|
||||
end if;
|
||||
return new;
|
||||
end $$;
|
||||
create constraint trigger crank_test_fail_unavailable_guard
|
||||
after update on artifact_blobs
|
||||
deferrable initially deferred
|
||||
for each row execute function crank_test_fail_unavailable();",
|
||||
)
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let backend = PostgresReconciliationBackend::new(registry.clone(), Arc::new(store.clone()));
|
||||
let mut coordinator = ReconciliationCoordinator::new(backend);
|
||||
let failed = coordinator.tick().await.unwrap();
|
||||
|
||||
// A real commit failure must surface as retryable work, never as idle.
|
||||
assert!(failed.retryable);
|
||||
assert_eq!(failed.mutation_attempts, 1);
|
||||
assert_eq!(
|
||||
store
|
||||
.reconciliation_presence(artifact.artifact_ref())
|
||||
.unwrap(),
|
||||
ReconciliationPresence::Absent
|
||||
);
|
||||
let retained = sqlx::query(
|
||||
"select claim_token, claim_expires_at, storage_lifecycle
|
||||
from artifact_blobs where digest = $1",
|
||||
)
|
||||
.bind(artifact.artifact_ref().digest_hex())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
retained
|
||||
.try_get::<Option<String>, _>("claim_token")
|
||||
.unwrap()
|
||||
.is_some(),
|
||||
"the failed commit must roll back the claim clear"
|
||||
);
|
||||
assert!(
|
||||
retained
|
||||
.try_get::<Option<time::OffsetDateTime>, _>("claim_expires_at")
|
||||
.unwrap()
|
||||
.is_some()
|
||||
);
|
||||
assert_eq!(
|
||||
retained.get::<String, _>("storage_lifecycle"),
|
||||
"available",
|
||||
"the failed commit must roll back the unavailable transition"
|
||||
);
|
||||
|
||||
// Removing the injected trigger and retrying a fresh coordinator clears the
|
||||
// retained claim and records the confirmed absence as `unavailable`.
|
||||
sqlx::raw_sql(
|
||||
"drop trigger crank_test_fail_unavailable_guard on artifact_blobs;
|
||||
drop function crank_test_fail_unavailable();",
|
||||
)
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"update artifact_blobs
|
||||
set claim_expires_at = clock_timestamp() - interval '1 second'
|
||||
where digest = $1",
|
||||
)
|
||||
.bind(artifact.artifact_ref().digest_hex())
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let mut recovered_coordinator = ReconciliationCoordinator::new(
|
||||
PostgresReconciliationBackend::new(registry.clone(), Arc::new(store.clone())),
|
||||
);
|
||||
let recovered = recovered_coordinator.tick().await.unwrap();
|
||||
assert!(!recovered.retryable);
|
||||
assert_eq!(
|
||||
store
|
||||
.reconciliation_presence(artifact.artifact_ref())
|
||||
.unwrap(),
|
||||
ReconciliationPresence::Absent
|
||||
);
|
||||
let cleared = sqlx::query(
|
||||
"select claim_token, claim_expires_at, storage_lifecycle
|
||||
from artifact_blobs where digest = $1",
|
||||
)
|
||||
.bind(artifact.artifact_ref().digest_hex())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
cleared.try_get::<Option<String>, _>("claim_token").unwrap(),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
cleared
|
||||
.try_get::<Option<time::OffsetDateTime>, _>("claim_expires_at")
|
||||
.unwrap(),
|
||||
None
|
||||
);
|
||||
assert_eq!(cleared.get::<String, _>("storage_lifecycle"), "unavailable");
|
||||
}
|
||||
@@ -7,8 +7,8 @@ use crank_core::{
|
||||
};
|
||||
use crank_import::rest::{
|
||||
ImportFinding, ImportFindingSeverity, ImportNameConflict, ImportOperationCandidate,
|
||||
NORMALIZER_VERSION, PROJECTION_VERSION, operation_draft_from_candidate,
|
||||
validate_document_source_safe,
|
||||
NORMALIZER_VERSION, PROJECTION_VERSION, canonical_external_document_uri,
|
||||
operation_draft_from_candidate, validate_document_source_safe,
|
||||
};
|
||||
use crank_registry::{
|
||||
ApplyImportJobRequest, ArtifactSourceId, ArtifactSourceSensitivity,
|
||||
@@ -55,7 +55,7 @@ const IMPORT_JOB_TTL_HOURS: i64 = 24;
|
||||
const OPENAPI_PARSE_DEADLINE: std::time::Duration = std::time::Duration::from_secs(30);
|
||||
const OPENAPI_PARSE_CONCURRENCY: usize = 4;
|
||||
const MAX_IMPORT_PLAN_KEYS: usize = 2_000;
|
||||
const OPENAPI_SUPPORT_MATRIX_VERSION: &str = "1.0.3";
|
||||
const OPENAPI_SUPPORT_MATRIX_VERSION: &str = "1.0.4";
|
||||
const MAX_IMPORT_PLAN_KEY_BYTES: usize = 4_096;
|
||||
const MAX_IMPORT_PLAN_SERVER_URL_BYTES: usize = 8_192;
|
||||
const MAX_IMPORT_PLAN_NAME_BYTES: usize = 256;
|
||||
@@ -664,24 +664,6 @@ impl AdminService {
|
||||
}
|
||||
}
|
||||
|
||||
fn canonical_external_document_uri(base: Option<&str>, reference: &str) -> Option<String> {
|
||||
if reference.starts_with('#') {
|
||||
return None;
|
||||
}
|
||||
let mut url = match base {
|
||||
Some(base) => url::Url::parse(base).ok()?.join(reference).ok()?,
|
||||
None => url::Url::parse(reference).ok()?,
|
||||
};
|
||||
if !matches!(url.scheme(), "http" | "https")
|
||||
|| !url.username().is_empty()
|
||||
|| url.password().is_some()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
url.set_fragment(None);
|
||||
Some(url.to_string())
|
||||
}
|
||||
|
||||
fn openapi_import_response(applied: ImportJobApplyResult) -> OpenApiImportCreateResponse {
|
||||
let created = applied
|
||||
.created
|
||||
|
||||
@@ -210,6 +210,10 @@ fn import_replay_contract(
|
||||
| ("normalized-ir-v3", "preview-v3")
|
||||
| ("normalized-ir-v4", "preview-v4")
|
||||
| ("normalized-ir-v5", "preview-v5")
|
||||
// The v5/preview-v6 pair predates the shared external-URI identity
|
||||
// (normalized-ir-v6). Its saved projection is authoritative and is
|
||||
// replayed verbatim, never reparsed under the current normalizer.
|
||||
| ("normalized-ir-v5", "preview-v6")
|
||||
) {
|
||||
return Err(ApiError::openapi_upload(locale, "source_integrity"));
|
||||
}
|
||||
|
||||
@@ -16,6 +16,13 @@ const REGISTERED_MASTER_KEY: &str = "registered-master-key-CANARY_SECRET_VALUE-0
|
||||
const WRONG_MASTER_KEY: &str = "wrong-master-key-CANARY_SECRET_VALUE-0000000000000";
|
||||
static NEXT_STORAGE_ROOT: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
fn isolated_metrics_bind() -> String {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("ephemeral metrics port");
|
||||
let addr = listener.local_addr().unwrap().to_string();
|
||||
drop(listener);
|
||||
addr
|
||||
}
|
||||
|
||||
fn run_with(entries: &[(&str, &str)]) -> String {
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_admin-api"));
|
||||
for field in crank_config::field_registry() {
|
||||
@@ -27,6 +34,7 @@ fn run_with(entries: &[(&str, &str)]) -> String {
|
||||
("CRANK_PASSWORD_PEPPER", "pepper"),
|
||||
("CRANK_BOOTSTRAP_ADMIN_EMAIL", "owner@example.test"),
|
||||
("CRANK_BOOTSTRAP_ADMIN_PASSWORD", "password"),
|
||||
("CRANK_ADMIN_METRICS_BIND", isolated_metrics_bind().as_str()),
|
||||
]);
|
||||
for (name, value) in entries {
|
||||
command.env(name, value);
|
||||
@@ -137,6 +145,7 @@ async fn real_admin_startup_runs_immediate_import_maintenance() {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let bind_addr = listener.local_addr().unwrap().to_string();
|
||||
drop(listener);
|
||||
let metrics_bind = isolated_metrics_bind();
|
||||
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_admin-api"));
|
||||
for field in crank_config::field_registry() {
|
||||
@@ -151,6 +160,7 @@ async fn real_admin_startup_runs_immediate_import_maintenance() {
|
||||
("CRANK_BOOTSTRAP_ADMIN_EMAIL", "owner@example.test"),
|
||||
("CRANK_BOOTSTRAP_ADMIN_PASSWORD", "password"),
|
||||
("CRANK_ADMIN_BIND", bind_addr.as_str()),
|
||||
("CRANK_ADMIN_METRICS_BIND", metrics_bind.as_str()),
|
||||
("CRANK_STORAGE_ROOT", storage_root.to_str().unwrap()),
|
||||
])
|
||||
.stdout(Stdio::null())
|
||||
|
||||
@@ -6,6 +6,8 @@ use serde_json::{Value, json};
|
||||
use serial_test::serial;
|
||||
|
||||
mod replay;
|
||||
mod telemetry;
|
||||
mod telemetry_startup;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
|
||||
@@ -0,0 +1,301 @@
|
||||
use super::*;
|
||||
use std::{collections::BTreeSet, time::Duration};
|
||||
|
||||
use axum::{
|
||||
Router,
|
||||
body::Bytes,
|
||||
extract::Request,
|
||||
http::StatusCode,
|
||||
middleware::{self, Next},
|
||||
routing::post,
|
||||
};
|
||||
use crank_core::{ProductEventKind, WorkspaceId};
|
||||
use crank_observability::{
|
||||
OtlpBatchConfig, OtlpTraceConfig, ServiceIdentity, build_tracer_provider,
|
||||
};
|
||||
use opentelemetry::trace::TracerProvider as _;
|
||||
use opentelemetry_proto::tonic::{
|
||||
collector::trace::v1::ExportTraceServiceRequest,
|
||||
common::v1::{KeyValue, any_value},
|
||||
};
|
||||
use opentelemetry_sdk::trace::SdkTracerProvider;
|
||||
use prost::Message;
|
||||
use tokio::{net::TcpListener, sync::mpsc};
|
||||
use tracing::instrument::WithSubscriber;
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
|
||||
pub(super) const RAW_DOCUMENT_CANARY: &str = "openapi: 3.1.0 raw-document-canary";
|
||||
pub(super) const USER_ID_CANARY: &str = "user-id-canary-should-not-export";
|
||||
const REQUEST_ID: &str = "req_onboarding_optin_0001";
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn onboarding_http_event_keeps_default_trace_export_disabled() {
|
||||
let registry = test_registry().await;
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let config = OtlpTraceConfig::default();
|
||||
let identity = service_identity();
|
||||
assert!(!config.is_enabled());
|
||||
assert!(
|
||||
build_tracer_provider(&identity, &config)
|
||||
.expect("disabled OTLP config is valid")
|
||||
.is_none(),
|
||||
"default config must not construct an exporter or batch queue"
|
||||
);
|
||||
|
||||
let (collector_listener, _) = loopback_listener().await;
|
||||
let (dispatch, provider) = local_trace_dispatch();
|
||||
let app = app_with_request_dispatch(
|
||||
build_test_app(
|
||||
registry.clone(),
|
||||
test_storage_root("onboarding_telemetry_default"),
|
||||
),
|
||||
dispatch,
|
||||
);
|
||||
let base_url = spawn_admin_api(app).await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
let revision = onboarding_revision(&client, &base_url).await;
|
||||
|
||||
reject_canary_payload(&client, &base_url, revision).await;
|
||||
let event = post_started_event(&client, &base_url, revision, false).await;
|
||||
assert_eq!(event.status(), reqwest::StatusCode::OK);
|
||||
assert_eq!(event.json::<Value>().await.unwrap()["accepted"], true);
|
||||
assert_event_is_local(®istry, &workspace_id, "ui:telemetry-default-event").await;
|
||||
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(300), collector_listener.accept())
|
||||
.await
|
||||
.is_err(),
|
||||
"default telemetry config must make no connection to the external collector"
|
||||
);
|
||||
provider
|
||||
.shutdown()
|
||||
.expect("local trace provider shuts down");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn onboarding_http_event_exports_only_sanitized_trace_when_operator_opts_in() {
|
||||
let registry = test_registry().await;
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let (endpoint, mut exported_requests, collector_task) = spawn_otlp_collector().await;
|
||||
let config = OtlpTraceConfig::try_new(
|
||||
Some(endpoint),
|
||||
Some("http/protobuf".to_owned()),
|
||||
Duration::from_secs(2),
|
||||
OtlpBatchConfig::try_new(128, 128, Duration::from_secs(60), Duration::from_secs(2))
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let identity = service_identity();
|
||||
assert!(config.is_enabled());
|
||||
let (provider, tracer) = build_tracer_provider(&identity, &config)
|
||||
.expect("explicit OTLP config is valid")
|
||||
.expect("operator endpoint enables the real exporter");
|
||||
let subscriber =
|
||||
tracing_subscriber::registry().with(tracing_opentelemetry::layer().with_tracer(tracer));
|
||||
let dispatch = tracing::Dispatch::new(subscriber);
|
||||
let app = app_with_request_dispatch(
|
||||
build_test_app(
|
||||
registry.clone(),
|
||||
test_storage_root("onboarding_telemetry_optin"),
|
||||
),
|
||||
dispatch,
|
||||
);
|
||||
let base_url = spawn_admin_api(app).await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
let revision = onboarding_revision(&client, &base_url).await;
|
||||
|
||||
reject_canary_payload(&client, &base_url, revision).await;
|
||||
let event = post_started_event(&client, &base_url, revision, true).await;
|
||||
assert_eq!(event.status(), reqwest::StatusCode::OK);
|
||||
assert_eq!(event.json::<Value>().await.unwrap()["accepted"], true);
|
||||
assert_event_is_local(®istry, &workspace_id, "ui:telemetry-optin-event").await;
|
||||
|
||||
provider
|
||||
.force_flush()
|
||||
.expect("flush trace spans to the operator collector");
|
||||
provider.shutdown().expect("exporter shuts down cleanly");
|
||||
let mut request_count = 0;
|
||||
let mut onboarding_request_id_exported = false;
|
||||
while let Ok(body) = exported_requests.try_recv() {
|
||||
request_count += 1;
|
||||
let export = ExportTraceServiceRequest::decode(body.as_ref())
|
||||
.expect("collector receives valid OTLP protobuf");
|
||||
for resource_spans in export.resource_spans {
|
||||
for scope_spans in resource_spans.scope_spans {
|
||||
for span in scope_spans.spans {
|
||||
assert_eq!(span.name, "http.request");
|
||||
assert!(span.events.is_empty());
|
||||
assert!(span.links.is_empty());
|
||||
let attribute_keys: BTreeSet<&str> = span
|
||||
.attributes
|
||||
.iter()
|
||||
.map(|attribute| attribute.key.as_str())
|
||||
.collect();
|
||||
assert!(
|
||||
attribute_keys.iter().all(|key| *key == "request_id"),
|
||||
"request spans may export only the request_id attribute"
|
||||
);
|
||||
if string_attribute(&span.attributes, "request_id") == Some(REQUEST_ID) {
|
||||
onboarding_request_id_exported = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(!body_contains(&body, RAW_DOCUMENT_CANARY));
|
||||
assert!(!body_contains(&body, USER_ID_CANARY));
|
||||
}
|
||||
assert!(
|
||||
request_count > 0,
|
||||
"explicit opt-in must reach the collector"
|
||||
);
|
||||
assert!(
|
||||
onboarding_request_id_exported,
|
||||
"the collected trace must include the real onboarding HTTP request"
|
||||
);
|
||||
collector_task.abort();
|
||||
}
|
||||
|
||||
fn service_identity() -> ServiceIdentity {
|
||||
ServiceIdentity::try_new("admin-api", "integration-test", "test")
|
||||
.expect("static service identity is valid")
|
||||
}
|
||||
|
||||
fn local_trace_dispatch() -> (tracing::Dispatch, SdkTracerProvider) {
|
||||
let provider = SdkTracerProvider::builder().build();
|
||||
let tracer = provider.tracer("crank");
|
||||
let subscriber =
|
||||
tracing_subscriber::registry().with(tracing_opentelemetry::layer().with_tracer(tracer));
|
||||
(tracing::Dispatch::new(subscriber), provider)
|
||||
}
|
||||
|
||||
fn app_with_request_dispatch(app: Router, dispatch: tracing::Dispatch) -> Router {
|
||||
app.layer(middleware::from_fn(move |request: Request, next: Next| {
|
||||
let dispatch = dispatch.clone();
|
||||
async move { next.run(request).with_subscriber(dispatch).await }
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) async fn loopback_listener() -> (TcpListener, String) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let endpoint = format!("http://{}/v1/traces", listener.local_addr().unwrap());
|
||||
(listener, endpoint)
|
||||
}
|
||||
|
||||
pub(super) async fn spawn_otlp_collector() -> (
|
||||
String,
|
||||
mpsc::UnboundedReceiver<Bytes>,
|
||||
tokio::task::JoinHandle<()>,
|
||||
) {
|
||||
let (listener, endpoint) = loopback_listener().await;
|
||||
let (sender, receiver) = mpsc::unbounded_channel();
|
||||
let app = Router::new().route(
|
||||
"/v1/traces",
|
||||
post(move |body: Bytes| {
|
||||
let sender = sender.clone();
|
||||
async move {
|
||||
let _ = sender.send(body);
|
||||
StatusCode::OK
|
||||
}
|
||||
}),
|
||||
);
|
||||
let handle = tokio::spawn(async move {
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
});
|
||||
(endpoint, receiver, handle)
|
||||
}
|
||||
|
||||
pub(super) async fn onboarding_revision(
|
||||
client: &reqwest::Client,
|
||||
base_url: &(impl AsRef<str> + ?Sized),
|
||||
) -> i64 {
|
||||
let base_url = base_url.as_ref();
|
||||
let response = client
|
||||
.get(format!("{base_url}/onboarding"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), reqwest::StatusCode::OK);
|
||||
response.json::<Value>().await.unwrap()["revision"]
|
||||
.as_i64()
|
||||
.expect("onboarding returns a server revision")
|
||||
}
|
||||
|
||||
pub(super) async fn reject_canary_payload(
|
||||
client: &reqwest::Client,
|
||||
base_url: &(impl AsRef<str> + ?Sized),
|
||||
revision: i64,
|
||||
) {
|
||||
let base_url = base_url.as_ref();
|
||||
let response = client
|
||||
.post(format!("{base_url}/onboarding/events"))
|
||||
.json(&json!({
|
||||
"event": "started",
|
||||
"idempotency_key": "ui:telemetry-canary-rejection",
|
||||
"expected_revision": revision,
|
||||
"user_id": USER_ID_CANARY,
|
||||
"openapi_document": RAW_DOCUMENT_CANARY,
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), reqwest::StatusCode::UNPROCESSABLE_ENTITY);
|
||||
let body = response.text().await.unwrap();
|
||||
assert!(!body.contains(USER_ID_CANARY));
|
||||
assert!(!body.contains(RAW_DOCUMENT_CANARY));
|
||||
}
|
||||
|
||||
async fn post_started_event(
|
||||
client: &reqwest::Client,
|
||||
base_url: &(impl AsRef<str> + ?Sized),
|
||||
revision: i64,
|
||||
with_request_id: bool,
|
||||
) -> reqwest::Response {
|
||||
let base_url = base_url.as_ref();
|
||||
let mut request = client
|
||||
.post(format!("{base_url}/onboarding/events"))
|
||||
.json(&json!({
|
||||
"event": "started",
|
||||
"idempotency_key": if with_request_id {
|
||||
"ui:telemetry-optin-event"
|
||||
} else {
|
||||
"ui:telemetry-default-event"
|
||||
},
|
||||
"expected_revision": revision,
|
||||
}));
|
||||
if with_request_id {
|
||||
request = request.header("x-request-id", REQUEST_ID);
|
||||
}
|
||||
request.send().await.unwrap()
|
||||
}
|
||||
|
||||
async fn assert_event_is_local(
|
||||
registry: &crank_registry::PostgresRegistry,
|
||||
workspace_id: &WorkspaceId,
|
||||
idempotency_key: &str,
|
||||
) {
|
||||
let record = registry
|
||||
.get_product_event_by_idempotency_key(workspace_id, idempotency_key)
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("successful HTTP event is persisted in the local product event store");
|
||||
assert_eq!(record.event.kind, ProductEventKind::OnboardingStarted);
|
||||
assert_eq!(record.event.idempotency_key, idempotency_key);
|
||||
}
|
||||
|
||||
pub(super) fn string_attribute<'a>(attributes: &'a [KeyValue], key: &str) -> Option<&'a str> {
|
||||
attributes.iter().find_map(|attribute| {
|
||||
(attribute.key == key)
|
||||
.then_some(attribute.value.as_ref()?.value.as_ref()?)
|
||||
.and_then(|value| match value {
|
||||
any_value::Value::StringValue(value) => Some(value.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn body_contains(body: &[u8], canary: &str) -> bool {
|
||||
body.windows(canary.len())
|
||||
.any(|window| window == canary.as_bytes())
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
use super::telemetry::{
|
||||
RAW_DOCUMENT_CANARY, USER_ID_CANARY, body_contains, loopback_listener, onboarding_revision,
|
||||
reject_canary_payload, string_attribute,
|
||||
};
|
||||
use super::*;
|
||||
use axum::{
|
||||
Router,
|
||||
body::{self, Bytes},
|
||||
extract::Request,
|
||||
http::StatusCode,
|
||||
routing::any,
|
||||
};
|
||||
use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest;
|
||||
use prost::Message;
|
||||
use std::{
|
||||
collections::BTreeSet,
|
||||
fs::{self, OpenOptions},
|
||||
net::TcpListener as StdTcpListener,
|
||||
os::unix::fs::{OpenOptionsExt, PermissionsExt},
|
||||
path::PathBuf,
|
||||
process::{Child, Command, Stdio},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
const MASTER_KEY: &str = "test-master-key-00000000000000000000000000000000";
|
||||
const SESSION_SECRET: &str = "test-session-secret";
|
||||
const PASSWORD_PEPPER: &str = "test-password-pepper";
|
||||
const ADMIN_EMAIL: &str = "owner@crank.local";
|
||||
const ADMIN_PASSWORD: &str = "test-password";
|
||||
const REQUEST_ID: &str = "req_admin_process_optin_0001";
|
||||
|
||||
struct AdminProcess {
|
||||
child: Child,
|
||||
log_path: PathBuf,
|
||||
secrets: Vec<String>,
|
||||
}
|
||||
|
||||
impl AdminProcess {
|
||||
fn stop_and_assert_logs_are_safe(&mut self) {
|
||||
let _ = self.child.kill();
|
||||
self.child.wait().expect("admin-api child must be reaped");
|
||||
let logs = fs::read_to_string(&self.log_path).expect("child log must be readable");
|
||||
for secret in &self.secrets {
|
||||
assert!(
|
||||
!logs.contains(secret),
|
||||
"admin-api process log must not contain configured secrets or request canaries"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for AdminProcess {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn production_admin_process_keeps_default_otlp_export_disabled() {
|
||||
let (registry, database_url) = test_registry_with_single_connection().await;
|
||||
let _registry = registry;
|
||||
let storage_root = test_storage_root("onboarding_telemetry_startup_default");
|
||||
let (collector_listener, _) = loopback_listener().await;
|
||||
let (mut process, base_url) = start_admin_process(&database_url, &storage_root, None);
|
||||
wait_until_ready(&mut process, &base_url).await;
|
||||
|
||||
let workspace_url = format!("{base_url}/api/admin/workspaces/ws_default");
|
||||
let client = authorized_client(&workspace_url).await;
|
||||
let revision = onboarding_revision(&client, &workspace_url).await;
|
||||
reject_canary_payload(&client, &workspace_url, revision).await;
|
||||
let response = post_startup_event(&client, &workspace_url, revision, false).await;
|
||||
assert_eq!(response.status(), reqwest::StatusCode::OK);
|
||||
assert_eq!(response.json::<Value>().await.unwrap()["accepted"], true);
|
||||
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_secs(2), collector_listener.accept())
|
||||
.await
|
||||
.is_err(),
|
||||
"default production startup must not connect to an OTLP collector"
|
||||
);
|
||||
process.stop_and_assert_logs_are_safe();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn production_admin_process_exports_only_sanitized_request_trace_when_opted_in() {
|
||||
let (registry, database_url) = test_registry_with_single_connection().await;
|
||||
let _registry = registry;
|
||||
let storage_root = test_storage_root("onboarding_telemetry_startup_optin");
|
||||
let (endpoint, mut exported_requests, collector_task) = spawn_startup_collector().await;
|
||||
let (mut process, base_url) =
|
||||
start_admin_process(&database_url, &storage_root, Some(&endpoint));
|
||||
wait_until_ready(&mut process, &base_url).await;
|
||||
|
||||
let workspace_url = format!("{base_url}/api/admin/workspaces/ws_default");
|
||||
let client = authorized_client(&workspace_url).await;
|
||||
let revision = onboarding_revision(&client, &workspace_url).await;
|
||||
reject_canary_payload(&client, &workspace_url, revision).await;
|
||||
let response = post_startup_event(&client, &workspace_url, revision, true).await;
|
||||
assert_eq!(response.status(), reqwest::StatusCode::OK);
|
||||
assert_eq!(response.json::<Value>().await.unwrap()["accepted"], true);
|
||||
|
||||
let mut request_id_exported = false;
|
||||
tokio::time::timeout(Duration::from_secs(12), async {
|
||||
while !request_id_exported {
|
||||
let (path, body) = exported_requests
|
||||
.recv()
|
||||
.await
|
||||
.expect("collector task must remain active");
|
||||
assert_eq!(path, "/v1/traces", "trace-specific endpoint path is exact");
|
||||
let export = ExportTraceServiceRequest::decode(body.as_ref())
|
||||
.expect("production process must send valid OTLP protobuf");
|
||||
for resource_spans in export.resource_spans {
|
||||
for scope_spans in resource_spans.scope_spans {
|
||||
for span in scope_spans.spans {
|
||||
assert_eq!(span.name, "http.request");
|
||||
assert!(span.events.is_empty());
|
||||
assert!(span.links.is_empty());
|
||||
let attribute_keys: BTreeSet<&str> = span
|
||||
.attributes
|
||||
.iter()
|
||||
.map(|attribute| attribute.key.as_str())
|
||||
.collect();
|
||||
assert!(
|
||||
attribute_keys.iter().all(|key| *key == "request_id"),
|
||||
"production request spans may export only the request_id attribute"
|
||||
);
|
||||
if string_attribute(&span.attributes, "request_id") == Some(REQUEST_ID) {
|
||||
request_id_exported = true;
|
||||
}
|
||||
let encoded = format!("{} {:?}", span.name, span.attributes);
|
||||
assert!(!encoded.contains(USER_ID_CANARY));
|
||||
assert!(!encoded.contains(RAW_DOCUMENT_CANARY));
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(!body_contains(&body, USER_ID_CANARY));
|
||||
assert!(!body_contains(&body, RAW_DOCUMENT_CANARY));
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("production exporter must send the onboarding request in a bounded OTLP batch");
|
||||
assert!(
|
||||
request_id_exported,
|
||||
"collector must receive the trace for the onboarding event request"
|
||||
);
|
||||
process.stop_and_assert_logs_are_safe();
|
||||
collector_task.abort();
|
||||
}
|
||||
|
||||
fn start_admin_process(
|
||||
database_url: &str,
|
||||
storage_root: &std::path::Path,
|
||||
otlp_endpoint: Option<&str>,
|
||||
) -> (AdminProcess, String) {
|
||||
fs::create_dir_all(storage_root).expect("isolated storage root must be created");
|
||||
#[cfg(unix)]
|
||||
fs::set_permissions(storage_root, fs::Permissions::from_mode(0o700))
|
||||
.expect("isolated storage root must be private");
|
||||
|
||||
let listener = StdTcpListener::bind("127.0.0.1:0").expect("reserve an ephemeral API port");
|
||||
let address = listener.local_addr().unwrap();
|
||||
drop(listener);
|
||||
let base_url = format!("http://{address}");
|
||||
let log_path = storage_root.join("admin-api.log");
|
||||
let stdout = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.mode(0o600)
|
||||
.open(&log_path)
|
||||
.expect("private child log must be created");
|
||||
let stderr = stdout.try_clone().expect("child stderr log handle");
|
||||
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_admin-api"));
|
||||
command
|
||||
.env_clear()
|
||||
.env("CRANK_DATABASE_URL", database_url)
|
||||
.env("CRANK_ADMIN_BIND", address.to_string())
|
||||
.env("CRANK_STORAGE_ROOT", storage_root)
|
||||
.env("CRANK_MASTER_KEY", MASTER_KEY)
|
||||
.env("CRANK_SESSION_SECRET", SESSION_SECRET)
|
||||
.env("CRANK_PASSWORD_PEPPER", PASSWORD_PEPPER)
|
||||
.env("CRANK_SESSION_TTL_HOURS", "24")
|
||||
.env("CRANK_BOOTSTRAP_ADMIN_EMAIL", ADMIN_EMAIL)
|
||||
.env("CRANK_BOOTSTRAP_ADMIN_PASSWORD", ADMIN_PASSWORD)
|
||||
.env("CRANK_BOOTSTRAP_ADMIN_DISPLAY_NAME", "Integration Test")
|
||||
.env("CRANK_METRICS_ENABLED", "false")
|
||||
.env("CRANK_BASE_URL", &base_url)
|
||||
.env("CRANK_LOG_LEVEL", "info")
|
||||
.stdout(Stdio::from(stdout))
|
||||
.stderr(Stdio::from(stderr));
|
||||
if let Some(endpoint) = otlp_endpoint {
|
||||
command
|
||||
.env("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", endpoint)
|
||||
.env("OTEL_EXPORTER_OTLP_TRACES_PROTOCOL", "http/protobuf")
|
||||
.env("OTEL_BSP_MAX_QUEUE_SIZE", "16")
|
||||
.env("OTEL_BSP_MAX_EXPORT_BATCH_SIZE", "1")
|
||||
.env("OTEL_BSP_SCHEDULE_DELAY", "100")
|
||||
.env("OTEL_BSP_EXPORT_TIMEOUT", "2000");
|
||||
}
|
||||
let child = command.spawn().expect("production admin-api binary starts");
|
||||
(
|
||||
AdminProcess {
|
||||
child,
|
||||
log_path,
|
||||
secrets: vec![
|
||||
database_url.to_owned(),
|
||||
MASTER_KEY.to_owned(),
|
||||
SESSION_SECRET.to_owned(),
|
||||
PASSWORD_PEPPER.to_owned(),
|
||||
ADMIN_PASSWORD.to_owned(),
|
||||
USER_ID_CANARY.to_owned(),
|
||||
RAW_DOCUMENT_CANARY.to_owned(),
|
||||
],
|
||||
},
|
||||
base_url,
|
||||
)
|
||||
}
|
||||
|
||||
async fn spawn_startup_collector() -> (
|
||||
String,
|
||||
tokio::sync::mpsc::UnboundedReceiver<(String, Bytes)>,
|
||||
tokio::task::JoinHandle<()>,
|
||||
) {
|
||||
let (listener, endpoint) = loopback_listener().await;
|
||||
let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
|
||||
let app = Router::new().fallback(any(move |request: Request| {
|
||||
let sender = sender.clone();
|
||||
async move {
|
||||
let path = request.uri().path().to_owned();
|
||||
let body = body::to_bytes(request.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("collector request body must be readable");
|
||||
let _ = sender.send((path, body));
|
||||
StatusCode::OK
|
||||
}
|
||||
}));
|
||||
let handle = tokio::spawn(async move {
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
});
|
||||
(endpoint, receiver, handle)
|
||||
}
|
||||
|
||||
async fn wait_until_ready(process: &mut AdminProcess, base_url: &str) {
|
||||
let deadline = Instant::now() + Duration::from_secs(45);
|
||||
loop {
|
||||
if let Some(status) = process.child.try_wait().expect("child status is readable") {
|
||||
panic!("production admin-api exited before readiness: {status}");
|
||||
}
|
||||
if reqwest::Client::new()
|
||||
.get(format!("{base_url}/health"))
|
||||
.timeout(Duration::from_millis(500))
|
||||
.send()
|
||||
.await
|
||||
.is_ok_and(|response| response.status().is_success())
|
||||
{
|
||||
return;
|
||||
}
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"production admin-api readiness deadline"
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn post_startup_event(
|
||||
client: &reqwest::Client,
|
||||
workspace_url: &str,
|
||||
revision: i64,
|
||||
with_request_id: bool,
|
||||
) -> reqwest::Response {
|
||||
let mut request = client
|
||||
.post(format!("{workspace_url}/onboarding/events"))
|
||||
.json(&json!({
|
||||
"event": "started",
|
||||
"idempotency_key": if with_request_id {
|
||||
"ui:telemetry-process-optin"
|
||||
} else {
|
||||
"ui:telemetry-process-default"
|
||||
},
|
||||
"expected_revision": revision,
|
||||
}));
|
||||
if with_request_id {
|
||||
request = request.header("x-request-id", REQUEST_ID);
|
||||
}
|
||||
request.send().await.unwrap()
|
||||
}
|
||||
@@ -1,11 +1,22 @@
|
||||
use super::super::common::test_service_with_external_references;
|
||||
use super::super::common::{
|
||||
authorized_client, build_test_app_with_external_references, spawn_admin_api,
|
||||
test_service_with_external_references,
|
||||
};
|
||||
mod isolation;
|
||||
mod uri_transport;
|
||||
use super::*;
|
||||
use axum::{Router, routing::get};
|
||||
use admin_api::error::ApiError;
|
||||
use axum::{Router, body::to_bytes, http::StatusCode, response::IntoResponse, routing::get};
|
||||
use crank_artifacts::ArtifactStore;
|
||||
use crank_core::{Workspace, WorkspaceStatus};
|
||||
use crank_registry::{ArtifactSourceId, CreateWorkspaceRequest, RegistryError};
|
||||
use reqwest::multipart::{Form, Part};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
// Serialized by the integration harness at baseline f5f40cb167a82b1e3c1ea2475db5cbaed9d9abfa; this v4 payload preserves the then-current security blocker and digest.
|
||||
const BASELINE_V4_SECURITY_PREVIEW_PAYLOAD: &str = r###"{"dependencies":[],"dependency_snapshots":[],"normalization":{"config":{"external_references_enabled":false,"max_aliases":128,"max_bytes":262144,"max_collection_items":10000,"max_depth":64,"max_expanded_nodes":100000,"max_external_document_bytes":262144,"max_nodes":50000,"max_reference_depth":32,"max_reference_documents":32,"max_references":4096,"max_scalar_bytes":262144,"normalizer_version":"normalized-ir-v4","projection_version":"preview-v4"},"ir_fingerprint":"ae2319de76c13d631b26843623092d966e5deea7cda9e3e40e4acc6fa36a25a8","normalizer_version":"normalized-ir-v4","projection_version":"preview-v4"},"preview":{"findings":[{"code":"unsupported_security_requirement","message":"Требование безопасности должно быть привязано к настроенному Auth Profile перед публикацией этой операции; остальные операции не блокируются.","operation_key":"GET /secure","severity":"error"}],"groups":[{"key":"imported_operation","operations":[{"category":"imported","description":"Выполняет GET /public","draft":{"category":"imported","display_name":"Public","input_mapping":{},"input_schema":{"description":"Входные параметры MCP-инструмента","nullable":false,"required":true,"type":"object"},"name":"public","output_mapping":{"rules":[{"required":true,"source":"$.response.body","target":"$.output"}]},"output_schema":{"description":"Успешный ответ без тела","nullable":false,"required":true,"type":"null"},"target":{"base_url":"https://api.example.test","method":"GET","path_template":"/public","response_contract":[{"schema_variant":0,"status_code":200}]},"tool_description":{"description":"Выполняет GET /public","examples":[{"input":{}}],"title":"Public"},"wizard_state":{}},"findings":[{"code":"missing_summary","message":"У метода нет summary, отображаемое имя будет сгенерировано автоматически.","operation_key":"GET /public","severity":"warning"},{"code":"missing_description","message":"У метода нет description. Перед публикацией лучше описать, когда агенту стоит вызывать этот инструмент.","operation_key":"GET /public","severity":"warning"},{"code":"missing_response_schema","message":"У метода не найдена схема успешного ответа, результат будет описан как общий объект.","operation_key":"GET /public","severity":"warning"},{"code":"no_input_fields","message":"У инструмента нет входных параметров. Это нормально для справочных методов, но проверьте, что агенту не нужно передавать фильтры.","operation_key":"GET /public","severity":"info"},{"code":"empty_output_schema","message":"В ответе не найдено отдельных полей. Перед публикацией проверьте схему ответа и маппинг результата.","operation_key":"GET /public","severity":"warning"},{"code":"weak_tool_description","message":"Описание инструмента слишком короткое или техническое. Перед публикацией добавьте, когда агент должен вызывать инструмент и что будет в успешном ответе.","operation_key":"GET /public","severity":"warning"},{"code":"weak_tool_name","message":"Имя инструмента `public` выглядит слишком общим. Лучше использовать имя с конкретным действием и объектом.","operation_key":"GET /public","severity":"warning"}],"input_fields":0,"key":"GET /public","method":"GET","operation_id":"public","output_fields":0,"path":"/public","server_urls":["https://api.example.test"],"suggested_display_name":"Public","suggested_name":"public"},{"category":"imported","description":"Выполняет GET /secure","draft":{"category":"imported","display_name":"Secure","input_mapping":{},"input_schema":{"description":"Входные параметры MCP-инструмента","nullable":false,"required":true,"type":"object"},"name":"secure","output_mapping":{"rules":[{"required":true,"source":"$.response.body","target":"$.output"}]},"output_schema":{"description":"Успешный ответ без тела","nullable":false,"required":true,"type":"null"},"target":{"base_url":"https://api.example.test","method":"GET","path_template":"/secure","response_contract":[{"schema_variant":0,"status_code":200}]},"tool_description":{"description":"Выполняет GET /secure","examples":[{"input":{}}],"title":"Secure"},"wizard_state":{}},"findings":[{"code":"missing_summary","message":"У мет
Line truncated
|
||||
@@ -43,12 +54,14 @@ async fn external_relative_chain_survives_reversed_builder_order_and_apply_never
|
||||
let origin = format!("http://{address}");
|
||||
|
||||
let registry = test_registry().await;
|
||||
let storage_root = test_storage_root("openapi_import_external_snapshot");
|
||||
let service = test_service_with_external_references(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_external_snapshot"),
|
||||
storage_root.clone(),
|
||||
vec![format!("{origin}/")],
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let foreign_workspace_id = create_workspace(®istry, "ws_external_snapshot_foreign").await;
|
||||
let upload = OpenApiUpload {
|
||||
bytes: format!(
|
||||
r#"
|
||||
@@ -97,6 +110,60 @@ paths:
|
||||
2
|
||||
);
|
||||
|
||||
// The preview response contains only the normalized result. Ownership
|
||||
// envelopes, storage digests, and remote origins stay in the persisted
|
||||
// job payload and are verified through the workspace-scoped registry API.
|
||||
let public_preview = serde_json::to_string(&preview).unwrap();
|
||||
assert!(!public_preview.contains("src_openapi_dep_"));
|
||||
assert!(!public_preview.contains(&origin));
|
||||
let dependencies = job.preview_payload["dependencies"].as_array().unwrap();
|
||||
let store = Arc::new(ArtifactStore::open(&storage_root).unwrap());
|
||||
for dependency in dependencies {
|
||||
let source_id = ArtifactSourceId::new(dependency["source_id"].as_str().unwrap());
|
||||
let digest = dependency["digest"].as_str().unwrap();
|
||||
let canonical_uri = dependency["canonical_uri"].as_str().unwrap();
|
||||
let source = registry
|
||||
.get_artifact_source(&workspace_id, &source_id)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(source.workspace_id, workspace_id);
|
||||
assert_eq!(source.blob.artifact_ref.as_str(), digest);
|
||||
let verified = registry
|
||||
.read_artifact_source(Arc::clone(&store), &workspace_id, &source_id)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(verified.source.blob.artifact_ref.as_str(), digest);
|
||||
let expected_bytes = if canonical_uri.ends_with("/root.yaml") {
|
||||
b"Item: { $ref: './child.yaml#/Item' }".as_slice()
|
||||
} else {
|
||||
assert!(canonical_uri.ends_with("/child.yaml"));
|
||||
b"Item: { type: object, required: [id], properties: { id: { type: string } } }"
|
||||
.as_slice()
|
||||
};
|
||||
assert_eq!(verified.bytes, expected_bytes);
|
||||
|
||||
let foreign_read = registry
|
||||
.read_artifact_source(Arc::clone(&store), &foreign_workspace_id, &source_id)
|
||||
.await
|
||||
.expect_err("foreign workspace must not read an owned snapshot");
|
||||
let unknown_source_id = ArtifactSourceId::new("src_unknown_scope_probe");
|
||||
let unknown_read = registry
|
||||
.read_artifact_source(
|
||||
Arc::clone(&store),
|
||||
&foreign_workspace_id,
|
||||
&unknown_source_id,
|
||||
)
|
||||
.await
|
||||
.expect_err("unknown source must have the same scoped outcome");
|
||||
let foreign_body = source_not_found_body(foreign_read).await;
|
||||
let unknown_body = source_not_found_body(unknown_read).await;
|
||||
assert_eq!(foreign_body, unknown_body);
|
||||
let rendered_body = foreign_body.to_string();
|
||||
assert!(!rendered_body.contains(digest));
|
||||
assert!(!rendered_body.contains(canonical_uri));
|
||||
assert!(!rendered_body.contains(source_id.as_str()));
|
||||
}
|
||||
|
||||
let applied = service
|
||||
.create_openapi_import(
|
||||
&workspace_id,
|
||||
@@ -122,6 +189,59 @@ paths:
|
||||
assert_eq!(active_sources, 0);
|
||||
}
|
||||
|
||||
fn external_upload(origin: &str) -> OpenApiUpload {
|
||||
OpenApiUpload {
|
||||
bytes: format!(
|
||||
r#"
|
||||
openapi: 3.1.0
|
||||
info: {{ title: Scoped external snapshot }}
|
||||
servers: [{{ url: https://api.example.test }}]
|
||||
paths:
|
||||
/items:
|
||||
get:
|
||||
operationId: listItems
|
||||
responses:
|
||||
'200':
|
||||
description: ok
|
||||
content:
|
||||
application/json:
|
||||
schema: {{ $ref: '{origin}/schema.yaml#/Item' }}
|
||||
"#
|
||||
)
|
||||
.into_bytes(),
|
||||
mime_type: "application/yaml".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
}
|
||||
}
|
||||
|
||||
async fn create_workspace(registry: &crank_registry::PostgresRegistry, id: &str) -> WorkspaceId {
|
||||
let workspace_id = WorkspaceId::new(id);
|
||||
let now = OffsetDateTime::now_utc();
|
||||
registry
|
||||
.create_workspace(CreateWorkspaceRequest {
|
||||
workspace: &Workspace {
|
||||
id: workspace_id.clone(),
|
||||
slug: id.replace('_', "-"),
|
||||
display_name: id.to_owned(),
|
||||
status: WorkspaceStatus::Active,
|
||||
settings: serde_json::json!({}),
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
workspace_id
|
||||
}
|
||||
|
||||
async fn source_not_found_body(error: RegistryError) -> serde_json::Value {
|
||||
assert!(matches!(&error, RegistryError::SourceNotFound { .. }));
|
||||
let response = ApiError::from(error).into_response();
|
||||
assert_eq!(response.status(), StatusCode::NOT_FOUND);
|
||||
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||
serde_json::from_slice(&body).unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn external_secret_document_is_rejected_before_blob_registration() {
|
||||
|
||||
@@ -0,0 +1,287 @@
|
||||
use super::*;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::Notify;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn concurrent_external_previews_keep_snapshot_ownership_workspace_scoped() {
|
||||
let fetches = Arc::new(AtomicUsize::new(0));
|
||||
let fetch_count = Arc::clone(&fetches);
|
||||
let app = Router::new().route(
|
||||
"/schema.yaml",
|
||||
get(move || {
|
||||
let fetch_count = Arc::clone(&fetch_count);
|
||||
async move {
|
||||
fetch_count.fetch_add(1, Ordering::SeqCst);
|
||||
"Item: { type: object, properties: { id: { type: string } } }"
|
||||
}
|
||||
}),
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
let origin = format!("http://{address}");
|
||||
let registry = test_registry().await;
|
||||
let storage_root = test_storage_root("openapi_import_external_workspace_isolation");
|
||||
let service = test_service_with_external_references(
|
||||
registry.clone(),
|
||||
storage_root.clone(),
|
||||
vec![format!("{origin}/")],
|
||||
);
|
||||
let workspace_a = create_workspace(®istry, "ws_external_concurrent_a").await;
|
||||
let workspace_b = create_workspace(®istry, "ws_external_concurrent_b").await;
|
||||
|
||||
let (preview_a, preview_b) = tokio::join!(
|
||||
service.preview_openapi_import(&workspace_a, external_upload(&origin)),
|
||||
service.preview_openapi_import(&workspace_b, external_upload(&origin)),
|
||||
);
|
||||
let preview_a = preview_a.unwrap();
|
||||
let preview_b = preview_b.unwrap();
|
||||
server.abort();
|
||||
assert_eq!(
|
||||
fetches.load(Ordering::SeqCst),
|
||||
2,
|
||||
"each workspace fetches its own preview snapshot"
|
||||
);
|
||||
assert_ne!(preview_a.job_id, preview_b.job_id);
|
||||
|
||||
let job_a = registry
|
||||
.get_import_job(&workspace_a, &preview_a.job_id.as_str().into())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let job_b = registry
|
||||
.get_import_job(&workspace_b, &preview_b.job_id.as_str().into())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let dependency_a = &job_a.preview_payload["dependencies"][0];
|
||||
let dependency_b = &job_b.preview_payload["dependencies"][0];
|
||||
let source_a = ArtifactSourceId::new(dependency_a["source_id"].as_str().unwrap());
|
||||
let source_b = ArtifactSourceId::new(dependency_b["source_id"].as_str().unwrap());
|
||||
let digest_a = dependency_a["digest"].as_str().unwrap();
|
||||
let digest_b = dependency_b["digest"].as_str().unwrap();
|
||||
let canonical_uri = dependency_a["canonical_uri"].as_str().unwrap();
|
||||
assert_eq!(
|
||||
digest_a, digest_b,
|
||||
"identical bytes may share the immutable blob"
|
||||
);
|
||||
assert_eq!(dependency_b["canonical_uri"], dependency_a["canonical_uri"]);
|
||||
assert_ne!(
|
||||
source_a, source_b,
|
||||
"each workspace owns a distinct source relation"
|
||||
);
|
||||
|
||||
let public_a = serde_json::to_string(&preview_a).unwrap();
|
||||
let public_b = serde_json::to_string(&preview_b).unwrap();
|
||||
for response in [&public_a, &public_b] {
|
||||
assert!(!response.contains("src_openapi_dep_"));
|
||||
assert!(!response.contains(digest_a));
|
||||
assert!(!response.contains(canonical_uri));
|
||||
}
|
||||
|
||||
let store = Arc::new(ArtifactStore::open(&storage_root).unwrap());
|
||||
for (workspace_id, source_id) in [(&workspace_a, &source_a), (&workspace_b, &source_b)] {
|
||||
let source = registry
|
||||
.get_artifact_source(workspace_id, source_id)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(source.workspace_id, *workspace_id);
|
||||
assert_eq!(source.blob.artifact_ref.as_str(), digest_a);
|
||||
let verified = registry
|
||||
.read_artifact_source(Arc::clone(&store), workspace_id, source_id)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
verified.bytes,
|
||||
b"Item: { type: object, properties: { id: { type: string } } }"
|
||||
);
|
||||
}
|
||||
|
||||
let foreign_body = source_not_found_body(
|
||||
registry
|
||||
.read_artifact_source(Arc::clone(&store), &workspace_b, &source_a)
|
||||
.await
|
||||
.expect_err("workspace B cannot resolve workspace A source"),
|
||||
)
|
||||
.await;
|
||||
let unknown_source = ArtifactSourceId::new("src_unknown_workspace_probe");
|
||||
let unknown_body = source_not_found_body(
|
||||
registry
|
||||
.read_artifact_source(Arc::clone(&store), &workspace_b, &unknown_source)
|
||||
.await
|
||||
.expect_err("unknown source is indistinguishable from a foreign source"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(foreign_body, unknown_body);
|
||||
let response = foreign_body.to_string();
|
||||
assert!(!response.contains(digest_a));
|
||||
assert!(!response.contains(canonical_uri));
|
||||
assert!(!response.contains(source_a.as_str()));
|
||||
assert!(!response.contains("exists"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn existing_foreign_snapshot_does_not_short_circuit_second_workspace_fetch() {
|
||||
let fetches = Arc::new(AtomicUsize::new(0));
|
||||
let fetch_count = Arc::clone(&fetches);
|
||||
let second_fetch_entered = Arc::new(Notify::new());
|
||||
let entered = Arc::clone(&second_fetch_entered);
|
||||
let release_second_fetch = Arc::new(Notify::new());
|
||||
let release = Arc::clone(&release_second_fetch);
|
||||
let app = Router::new().route(
|
||||
"/schema.yaml",
|
||||
get(move || {
|
||||
let fetch_count = Arc::clone(&fetch_count);
|
||||
let entered = Arc::clone(&entered);
|
||||
let release = Arc::clone(&release);
|
||||
async move {
|
||||
let request_number = fetch_count.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
if request_number == 2 {
|
||||
entered.notify_one();
|
||||
release.notified().await;
|
||||
}
|
||||
"Item: { type: object, properties: { id: { type: string } } }"
|
||||
}
|
||||
}),
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
let origin = format!("http://{address}");
|
||||
let registry = test_registry().await;
|
||||
let service = test_service_with_external_references(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_external_fetch_oracle"),
|
||||
vec![format!("{origin}/")],
|
||||
);
|
||||
let workspace_a = create_workspace(®istry, "ws_external_oracle_a").await;
|
||||
let workspace_b = create_workspace(®istry, "ws_external_oracle_b").await;
|
||||
|
||||
let preview_a = service
|
||||
.preview_openapi_import(&workspace_a, external_upload(&origin))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(fetches.load(Ordering::SeqCst), 1);
|
||||
|
||||
let preview_b_origin = origin.clone();
|
||||
let preview_b_workspace = workspace_b.clone();
|
||||
let mut preview_b_task = tokio::spawn(async move {
|
||||
service
|
||||
.preview_openapi_import(&preview_b_workspace, external_upload(&preview_b_origin))
|
||||
.await
|
||||
});
|
||||
tokio::time::timeout(Duration::from_secs(10), second_fetch_entered.notified())
|
||||
.await
|
||||
.expect("the second preview must reach its HTTP fetch");
|
||||
|
||||
// The fixture holds the real HTTP response. Poll the preview once after
|
||||
// observing that fetch; it must remain pending until the fixture releases it.
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut preview_b_task => panic!("second preview bypassed its held fetch: {result:?}"),
|
||||
_ = tokio::task::yield_now() => {}
|
||||
}
|
||||
assert_eq!(fetches.load(Ordering::SeqCst), 2);
|
||||
release_second_fetch.notify_one();
|
||||
let preview_b = tokio::time::timeout(Duration::from_secs(10), &mut preview_b_task)
|
||||
.await
|
||||
.expect("the released second preview should complete")
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
server.abort();
|
||||
|
||||
let job_a = registry
|
||||
.get_import_job(&workspace_a, &preview_a.job_id.as_str().into())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let job_b = registry
|
||||
.get_import_job(&workspace_b, &preview_b.job_id.as_str().into())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let source_a = ArtifactSourceId::new(
|
||||
job_a.preview_payload["dependencies"][0]["source_id"]
|
||||
.as_str()
|
||||
.unwrap(),
|
||||
);
|
||||
let source_b = ArtifactSourceId::new(
|
||||
job_b.preview_payload["dependencies"][0]["source_id"]
|
||||
.as_str()
|
||||
.unwrap(),
|
||||
);
|
||||
assert_ne!(source_a, source_b);
|
||||
assert_eq!(fetches.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn file_origin_and_relative_chain_are_blocked_without_file_or_network_access() {
|
||||
const PRIVATE_FILE_BYTES: &str = "PrivateCanary: file-origin-secret-must-never-be-read";
|
||||
const HYPOTHETICAL_FILE_ROOT: &str = "Item: { $ref: './private/canary.yaml#/Secret' }";
|
||||
let file_fixture_root = test_storage_root("openapi_import_file_origin_fixture");
|
||||
let private_directory = file_fixture_root.join("private");
|
||||
std::fs::create_dir_all(&private_directory).unwrap();
|
||||
std::fs::write(file_fixture_root.join("root.yaml"), HYPOTHETICAL_FILE_ROOT).unwrap();
|
||||
std::fs::write(
|
||||
private_directory.join("canary.yaml"),
|
||||
format!("Secret: {{ type: string, example: '{PRIVATE_FILE_BYTES}' }}"),
|
||||
)
|
||||
.unwrap();
|
||||
let file_origin = url::Url::from_file_path(file_fixture_root.join("root.yaml")).unwrap();
|
||||
let file_origin_for_response = file_origin.clone();
|
||||
let requests = Arc::new(AtomicUsize::new(0));
|
||||
let request_count = Arc::clone(&requests);
|
||||
let app = Router::new().route(
|
||||
"/schema.yaml",
|
||||
get(move || {
|
||||
let request_count = Arc::clone(&request_count);
|
||||
async move {
|
||||
request_count.fetch_add(1, Ordering::SeqCst);
|
||||
format!("Item: {{ $ref: '{file_origin_for_response}#/Item' }}")
|
||||
}
|
||||
}),
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
let origin = format!("http://{address}");
|
||||
let registry = test_registry().await;
|
||||
let service = test_service_with_external_references(
|
||||
registry,
|
||||
test_storage_root("openapi_import_file_origin_blocked"),
|
||||
vec![format!("{origin}/")],
|
||||
);
|
||||
let preview = service
|
||||
.preview_openapi_import(&WorkspaceId::new("ws_default"), external_upload(&origin))
|
||||
.await
|
||||
.unwrap();
|
||||
server.abort();
|
||||
|
||||
assert_eq!(
|
||||
requests.load(Ordering::SeqCst),
|
||||
1,
|
||||
"only the explicitly allowlisted HTTP root is fetched"
|
||||
);
|
||||
let findings = preview
|
||||
.preview
|
||||
.groups
|
||||
.iter()
|
||||
.flat_map(|group| &group.operations)
|
||||
.flat_map(|operation| &operation.findings)
|
||||
.chain(preview.preview.findings.iter())
|
||||
.collect::<Vec<_>>();
|
||||
assert!(
|
||||
findings.iter().any(|finding| {
|
||||
finding.severity == crank_import::rest::ImportFindingSeverity::Error
|
||||
&& finding.code == "reference_target_missing"
|
||||
}),
|
||||
"file origin must produce a blocking unresolved-reference finding"
|
||||
);
|
||||
let report = serde_json::to_string(&preview).unwrap();
|
||||
assert!(!report.contains(file_origin.as_str()));
|
||||
assert!(!report.contains(PRIVATE_FILE_BYTES));
|
||||
assert!(!report.contains(HYPOTHETICAL_FILE_ROOT));
|
||||
}
|
||||
@@ -0,0 +1,603 @@
|
||||
//! F1 transport-parity cases for the Admin external-reference import.
|
||||
//!
|
||||
//! The external materializer stores snapshot keys produced by the URL transport
|
||||
//! (`url::Url`), which collapses a `%2e%2e` path segment and percent-encodes an
|
||||
//! apostrophe in a query (`'` -> `%27`). Because the materializer and the pure
|
||||
//! resolver used different URI keys, both references produced a false
|
||||
//! `external_reference_unavailable` blocker. These cases run the real allowlisted
|
||||
//! fixture server through preview -> apply -> replay (service) and through the
|
||||
//! authenticated multipart route (outer). They are registered from
|
||||
//! `external_references.rs` so the parent file stays within the repository
|
||||
//! file-size budget; shared helpers and imports come from `super`.
|
||||
|
||||
use super::*;
|
||||
|
||||
// F1 acceptance (both cases): the service preview -> apply -> replay path. The
|
||||
// assertions verify the transport-canonical keys resolve, the dependency
|
||||
// bytes/digests verify, apply never refetches, and replay is a stable no-op.
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn transport_canonical_external_uris_resolve_without_false_blocker_or_refetch() {
|
||||
// Distinct bytes so each canonical URI owns a distinct content-addressed
|
||||
// blob; byte-identical documents collapse into a single dependency envelope
|
||||
// (the recorded alias/digest observation) and could not be told apart.
|
||||
const ROOT_ITEM: &str =
|
||||
"Item: { type: object, required: [id], properties: { id: { type: string } } }";
|
||||
const QUERY_ITEM: &str =
|
||||
"Item: { type: object, required: [id], properties: { id: { type: integer } } }";
|
||||
let fetches = Arc::new(AtomicUsize::new(0));
|
||||
let root_fetches = Arc::clone(&fetches);
|
||||
let query_fetches = Arc::clone(&fetches);
|
||||
let app = Router::new()
|
||||
.route(
|
||||
"/root.yaml",
|
||||
get(move || {
|
||||
let fetches = Arc::clone(&root_fetches);
|
||||
async move {
|
||||
fetches.fetch_add(1, Ordering::SeqCst);
|
||||
ROOT_ITEM
|
||||
}
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/schema.json",
|
||||
get(move || {
|
||||
let fetches = Arc::clone(&query_fetches);
|
||||
async move {
|
||||
fetches.fetch_add(1, Ordering::SeqCst);
|
||||
QUERY_ITEM
|
||||
}
|
||||
}),
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let fixture_server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
let origin = format!("http://{address}");
|
||||
|
||||
let registry = test_registry().await;
|
||||
let storage_root = test_storage_root("openapi_import_external_uri_transport_parity");
|
||||
let service = test_service_with_external_references(
|
||||
registry.clone(),
|
||||
storage_root.clone(),
|
||||
vec![format!("{origin}/")],
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let upload = OpenApiUpload {
|
||||
bytes: format!(
|
||||
r##"
|
||||
openapi: 3.1.0
|
||||
info: {{ title: External URI transport parity }}
|
||||
servers: [{{ url: https://api.example.test }}]
|
||||
paths:
|
||||
/dot:
|
||||
get:
|
||||
operationId: encodedDot
|
||||
responses:
|
||||
'200':
|
||||
description: ok
|
||||
content: {{ application/json: {{ schema: {{ $ref: '{origin}/a/%2e%2e/root.yaml#/Item' }} }} }}
|
||||
/query:
|
||||
get:
|
||||
operationId: quotedQuery
|
||||
responses:
|
||||
'200':
|
||||
description: ok
|
||||
content: {{ application/json: {{ schema: {{ $ref: "{origin}/schema.json?filter='x'#/Item" }} }} }}
|
||||
"##
|
||||
)
|
||||
.into_bytes(),
|
||||
mime_type: "application/yaml".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
};
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Materialization first: the external materializer must have downloaded and
|
||||
// stored both snapshots under the transport-canonical keys before resolution
|
||||
// is judged. This separates the F1 resolver key mismatch from a snapshot that
|
||||
// was never fetched at all.
|
||||
let job_id: crank_registry::ImportJobId = preview.job_id.as_str().into();
|
||||
let job = registry
|
||||
.get_import_job(&workspace_id, &job_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let dependencies = job.preview_payload["dependencies"].as_array().unwrap();
|
||||
assert_eq!(dependencies.len(), 2);
|
||||
let canonical_uris = dependencies
|
||||
.iter()
|
||||
.map(|dependency| dependency["canonical_uri"].as_str().unwrap().to_owned())
|
||||
.collect::<std::collections::BTreeSet<_>>();
|
||||
assert_eq!(
|
||||
canonical_uris,
|
||||
std::collections::BTreeSet::from([
|
||||
format!("{origin}/root.yaml"),
|
||||
format!("{origin}/schema.json?filter=%27x%27"),
|
||||
]),
|
||||
"materialized dependency keys must be the transport-canonical URIs"
|
||||
);
|
||||
assert_eq!(
|
||||
fetches.load(Ordering::SeqCst),
|
||||
2,
|
||||
"both external documents must be fetched exactly once during preview"
|
||||
);
|
||||
|
||||
// Dependency bytes and digests verify against the workspace-scoped store.
|
||||
let store = Arc::new(ArtifactStore::open(&storage_root).unwrap());
|
||||
for dependency in dependencies {
|
||||
let source_id = ArtifactSourceId::new(dependency["source_id"].as_str().unwrap());
|
||||
let digest = dependency["digest"].as_str().unwrap();
|
||||
let verified = registry
|
||||
.read_artifact_source(Arc::clone(&store), &workspace_id, &source_id)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(verified.source.blob.artifact_ref.as_str(), digest);
|
||||
let canonical_uri = dependency["canonical_uri"].as_str().unwrap();
|
||||
let expected = if canonical_uri.ends_with("/root.yaml") {
|
||||
ROOT_ITEM
|
||||
} else {
|
||||
QUERY_ITEM
|
||||
};
|
||||
assert_eq!(verified.bytes, expected.as_bytes());
|
||||
}
|
||||
|
||||
// Criterion-defining: neither transport-canonical URI may become a false
|
||||
// blocker. Collected across all operations so one failure reports both.
|
||||
let false_blockers = preview
|
||||
.preview
|
||||
.groups
|
||||
.iter()
|
||||
.flat_map(|group| &group.operations)
|
||||
.flat_map(|operation| {
|
||||
operation
|
||||
.findings
|
||||
.iter()
|
||||
.filter(|finding| finding.code == "external_reference_unavailable")
|
||||
.map(|_| operation.key.clone())
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert!(
|
||||
false_blockers.is_empty(),
|
||||
"both transport-canonical URIs must resolve; false external blockers: {false_blockers:?}"
|
||||
);
|
||||
let resolved = preview
|
||||
.preview
|
||||
.groups
|
||||
.iter()
|
||||
.flat_map(|group| &group.operations)
|
||||
.map(|operation| (operation.key.clone(), operation.output_fields))
|
||||
.collect::<std::collections::BTreeMap<_, _>>();
|
||||
assert_eq!(resolved["GET /dot"], 1, "encoded-dot schema must resolve");
|
||||
assert_eq!(
|
||||
resolved["GET /query"], 1,
|
||||
"quoted-query schema must resolve"
|
||||
);
|
||||
|
||||
// Apply consumes the saved snapshots and must not refetch.
|
||||
let created = service
|
||||
.create_openapi_import(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /dot".to_owned(), "GET /query".to_owned()],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(created.created.len(), 2);
|
||||
assert_eq!(
|
||||
fetches.load(Ordering::SeqCst),
|
||||
2,
|
||||
"apply must reuse the saved dependency snapshots"
|
||||
);
|
||||
let drafts_after_apply = registry.list_operations(&workspace_id).await.unwrap().len();
|
||||
|
||||
// AC-2 replay: re-issue the SAME request key/payload. The import is already
|
||||
// applied, so the service must return the stored application result, create
|
||||
// no extra Draft, and refetch nothing. The fixture server stays alive until
|
||||
// after the replay so the counter would observe any real request.
|
||||
let replay = service
|
||||
.create_openapi_import(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /dot".to_owned(), "GET /query".to_owned()],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
replay.created, created.created,
|
||||
"replay must return the stored application result for the same request key and payload"
|
||||
);
|
||||
assert_eq!(replay.created.len(), 2);
|
||||
assert_eq!(
|
||||
fetches.load(Ordering::SeqCst),
|
||||
2,
|
||||
"replay must not refetch dependency snapshots"
|
||||
);
|
||||
|
||||
fixture_server.abort();
|
||||
let completed = registry
|
||||
.get_import_job(&workspace_id, &job_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(completed.status, ImportJobStatus::Completed);
|
||||
assert_eq!(
|
||||
registry.list_operations(&workspace_id).await.unwrap().len(),
|
||||
drafts_after_apply,
|
||||
"replay must not create extra Drafts"
|
||||
);
|
||||
}
|
||||
|
||||
// F1 outer path: the same references uploaded as authenticated multipart through
|
||||
// the outer router must preview without a false blocker, and the materializer
|
||||
// must have stored both transport-canonical snapshots before resolution is
|
||||
// judged. The run then continues through the real router apply and a replay of
|
||||
// the same payload key while the fixture is still alive: the stored application
|
||||
// result must be returned unchanged, no extra Draft may appear, and the fetch
|
||||
// counter must not grow.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn outer_authenticated_multipart_preview_matches_transport_canonical_uri() {
|
||||
// Distinct bytes so the two canonical URIs cannot collapse into one
|
||||
// dependency envelope; both remain valid resolvable schemas.
|
||||
const ROOT_ITEM: &str =
|
||||
"Item: { type: object, required: [id], properties: { id: { type: string } } }";
|
||||
const QUERY_ITEM: &str =
|
||||
"Item: { type: object, required: [id], properties: { id: { type: integer } } }";
|
||||
let fetches = Arc::new(AtomicUsize::new(0));
|
||||
let root_fetches = Arc::clone(&fetches);
|
||||
let query_fetches = Arc::clone(&fetches);
|
||||
let fixture = Router::new()
|
||||
.route(
|
||||
"/root.yaml",
|
||||
get(move || {
|
||||
let fetches = Arc::clone(&root_fetches);
|
||||
async move {
|
||||
fetches.fetch_add(1, Ordering::SeqCst);
|
||||
ROOT_ITEM
|
||||
}
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/schema.json",
|
||||
get(move || {
|
||||
let fetches = Arc::clone(&query_fetches);
|
||||
async move {
|
||||
fetches.fetch_add(1, Ordering::SeqCst);
|
||||
QUERY_ITEM
|
||||
}
|
||||
}),
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let fixture_server = tokio::spawn(async move { axum::serve(listener, fixture).await.unwrap() });
|
||||
let origin = format!("http://{address}");
|
||||
|
||||
let registry = test_registry().await;
|
||||
let app = build_test_app_with_external_references(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_external_uri_multipart"),
|
||||
vec![format!("{origin}/")],
|
||||
);
|
||||
let server = spawn_admin_api(app).await;
|
||||
let client = authorized_client(&server).await;
|
||||
let document = format!(
|
||||
r##"
|
||||
openapi: 3.1.0
|
||||
info: {{ title: Multipart transport parity }}
|
||||
servers: [{{ url: https://api.example.test }}]
|
||||
paths:
|
||||
/dot:
|
||||
get:
|
||||
operationId: encodedDot
|
||||
responses:
|
||||
'200':
|
||||
description: ok
|
||||
content: {{ application/json: {{ schema: {{ $ref: '{origin}/a/%2e%2e/root.yaml#/Item' }} }} }}
|
||||
/query:
|
||||
get:
|
||||
operationId: quotedQuery
|
||||
responses:
|
||||
'200':
|
||||
description: ok
|
||||
content: {{ application/json: {{ schema: {{ $ref: "{origin}/schema.json?filter='x'#/Item" }} }} }}
|
||||
"##
|
||||
);
|
||||
let response = client
|
||||
.post(format!("{server}/imports/openapi/preview"))
|
||||
.multipart(
|
||||
Form::new().part(
|
||||
"file",
|
||||
Part::bytes(document.into_bytes())
|
||||
.file_name("openapi.yaml".to_owned())
|
||||
.mime_str("application/yaml")
|
||||
.unwrap(),
|
||||
),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let status = response.status();
|
||||
let body = response.json::<serde_json::Value>().await.unwrap();
|
||||
assert_eq!(status, reqwest::StatusCode::OK, "{body}");
|
||||
|
||||
// The materializer must have downloaded both snapshots under the
|
||||
// transport-canonical keys before the blocker check is meaningful.
|
||||
let job_id_str = body["job_id"].as_str().unwrap().to_owned();
|
||||
let job_id: crank_registry::ImportJobId = job_id_str.as_str().into();
|
||||
let job = registry
|
||||
.get_import_job(&WorkspaceId::new("ws_default"), &job_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let canonical_uris = job.preview_payload["dependencies"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|dependency| dependency["canonical_uri"].as_str().unwrap().to_owned())
|
||||
.collect::<std::collections::BTreeSet<_>>();
|
||||
assert_eq!(
|
||||
canonical_uris,
|
||||
std::collections::BTreeSet::from([
|
||||
format!("{origin}/root.yaml"),
|
||||
format!("{origin}/schema.json?filter=%27x%27"),
|
||||
]),
|
||||
"both transport-canonical external URIs must be materialized"
|
||||
);
|
||||
assert_eq!(
|
||||
fetches.load(Ordering::SeqCst),
|
||||
2,
|
||||
"preview must fetch each external document exactly once"
|
||||
);
|
||||
|
||||
assert!(
|
||||
!body.to_string().contains("external_reference_unavailable"),
|
||||
"outer multipart preview must not report a false external blocker: {body}"
|
||||
);
|
||||
let resolved = body["preview"]["groups"][0]["operations"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|operation| {
|
||||
(
|
||||
operation["key"].as_str().unwrap().to_owned(),
|
||||
operation["output_fields"].clone(),
|
||||
)
|
||||
})
|
||||
.collect::<std::collections::BTreeMap<_, _>>();
|
||||
assert_eq!(resolved["GET /dot"], serde_json::json!(1));
|
||||
assert_eq!(resolved["GET /query"], serde_json::json!(1));
|
||||
|
||||
// AC-2: apply through the real authenticated router, then replay the SAME
|
||||
// payload key. The fixture stays alive so a real refetch would move the
|
||||
// counter, and the same application key must not create another Draft.
|
||||
let create_payload = serde_json::json!({
|
||||
"selected_operation_keys": ["GET /dot", "GET /query"],
|
||||
"server_url": null,
|
||||
"conflict_mode": "skip"
|
||||
});
|
||||
let create_response = client
|
||||
.post(format!("{server}/imports/openapi/{job_id_str}/create"))
|
||||
.json(&create_payload)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
create_response.status(),
|
||||
reqwest::StatusCode::OK,
|
||||
"apply through the router must succeed"
|
||||
);
|
||||
let created: serde_json::Value = create_response.json().await.unwrap();
|
||||
assert_eq!(created["created"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(
|
||||
fetches.load(Ordering::SeqCst),
|
||||
2,
|
||||
"apply must reuse the saved dependency snapshots"
|
||||
);
|
||||
let drafts_after_apply = client
|
||||
.get(format!("{server}/operations"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.json::<serde_json::Value>()
|
||||
.await
|
||||
.unwrap()["total"]
|
||||
.clone();
|
||||
assert_eq!(drafts_after_apply, serde_json::json!(2));
|
||||
|
||||
let replay_response = client
|
||||
.post(format!("{server}/imports/openapi/{job_id_str}/create"))
|
||||
.json(&create_payload)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(replay_response.status(), reqwest::StatusCode::OK);
|
||||
let replay: serde_json::Value = replay_response.json().await.unwrap();
|
||||
assert_eq!(
|
||||
replay, created,
|
||||
"replaying the same payload key must return the stored application result"
|
||||
);
|
||||
assert_eq!(
|
||||
fetches.load(Ordering::SeqCst),
|
||||
2,
|
||||
"replay must not refetch dependency snapshots"
|
||||
);
|
||||
let drafts_after_replay = client
|
||||
.get(format!("{server}/operations"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.json::<serde_json::Value>()
|
||||
.await
|
||||
.unwrap()["total"]
|
||||
.clone();
|
||||
assert_eq!(
|
||||
drafts_after_replay, drafts_after_apply,
|
||||
"replay must not create extra Drafts"
|
||||
);
|
||||
|
||||
fixture_server.abort();
|
||||
}
|
||||
|
||||
// AC-3 over real HTTP: the primary document references an encoded-dot root alias
|
||||
// (`/a/%2e%2e/root.yaml`) whose document contains a relative child `$ref`. The
|
||||
// materializer must canonicalize the alias to `/root.yaml`, then join the child
|
||||
// against that real canonical root (not the raw alias), so `/child.yaml` is
|
||||
// fetched exactly once and the derived schema resolves through the chain.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn encoded_dot_root_alias_chain_resolves_relative_child_against_canonical_root_over_http() {
|
||||
const ROOT_ALIAS_DOCUMENT: &str = "Item: { $ref: './child.yaml#/Item' }";
|
||||
const CHILD_ITEM: &str =
|
||||
"Item: { type: object, required: [id], properties: { id: { type: string } } }";
|
||||
let fetches = Arc::new(AtomicUsize::new(0));
|
||||
let root_fetches = Arc::clone(&fetches);
|
||||
let child_fetches = Arc::clone(&fetches);
|
||||
let app = Router::new()
|
||||
.route(
|
||||
"/root.yaml",
|
||||
get(move || {
|
||||
let fetches = Arc::clone(&root_fetches);
|
||||
async move {
|
||||
fetches.fetch_add(1, Ordering::SeqCst);
|
||||
ROOT_ALIAS_DOCUMENT
|
||||
}
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/child.yaml",
|
||||
get(move || {
|
||||
let fetches = Arc::clone(&child_fetches);
|
||||
async move {
|
||||
fetches.fetch_add(1, Ordering::SeqCst);
|
||||
CHILD_ITEM
|
||||
}
|
||||
}),
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let fixture_server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
let origin = format!("http://{address}");
|
||||
|
||||
let registry = test_registry().await;
|
||||
let storage_root = test_storage_root("openapi_import_external_uri_dot_root_chain");
|
||||
let service = test_service_with_external_references(
|
||||
registry.clone(),
|
||||
storage_root.clone(),
|
||||
vec![format!("{origin}/")],
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let upload = OpenApiUpload {
|
||||
bytes: format!(
|
||||
r##"
|
||||
openapi: 3.1.0
|
||||
info: {{ title: Canonical root alias chain }}
|
||||
servers: [{{ url: https://api.example.test }}]
|
||||
paths:
|
||||
/items:
|
||||
get:
|
||||
operationId: listItems
|
||||
responses:
|
||||
'200':
|
||||
description: ok
|
||||
content: {{ application/json: {{ schema: {{ $ref: '{origin}/a/%2e%2e/root.yaml#/Item' }} }} }}
|
||||
"##
|
||||
)
|
||||
.into_bytes(),
|
||||
mime_type: "application/yaml".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
};
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let job_id: crank_registry::ImportJobId = preview.job_id.as_str().into();
|
||||
let job = registry
|
||||
.get_import_job(&workspace_id, &job_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let dependencies = job.preview_payload["dependencies"].as_array().unwrap();
|
||||
assert_eq!(dependencies.len(), 2);
|
||||
let canonical_uris = dependencies
|
||||
.iter()
|
||||
.map(|dependency| dependency["canonical_uri"].as_str().unwrap().to_owned())
|
||||
.collect::<std::collections::BTreeSet<_>>();
|
||||
assert_eq!(
|
||||
canonical_uris,
|
||||
std::collections::BTreeSet::from([
|
||||
format!("{origin}/root.yaml"),
|
||||
format!("{origin}/child.yaml"),
|
||||
]),
|
||||
"the child must be materialized relative to the canonical root, not the raw encoded-dot alias"
|
||||
);
|
||||
assert_eq!(
|
||||
fetches.load(Ordering::SeqCst),
|
||||
2,
|
||||
"the canonical root alias and its relative child must each be fetched exactly once"
|
||||
);
|
||||
|
||||
// Dependency bytes and digests verify against the workspace-scoped store.
|
||||
let store = Arc::new(ArtifactStore::open(&storage_root).unwrap());
|
||||
for dependency in dependencies {
|
||||
let source_id = ArtifactSourceId::new(dependency["source_id"].as_str().unwrap());
|
||||
let digest = dependency["digest"].as_str().unwrap();
|
||||
let verified = registry
|
||||
.read_artifact_source(Arc::clone(&store), &workspace_id, &source_id)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(verified.source.blob.artifact_ref.as_str(), digest);
|
||||
let canonical_uri = dependency["canonical_uri"].as_str().unwrap();
|
||||
let expected = if canonical_uri.ends_with("/root.yaml") {
|
||||
ROOT_ALIAS_DOCUMENT
|
||||
} else {
|
||||
CHILD_ITEM
|
||||
};
|
||||
assert_eq!(verified.bytes, expected.as_bytes());
|
||||
}
|
||||
|
||||
// No false blocker: the chain resolves through the canonical root.
|
||||
let false_blockers = preview
|
||||
.preview
|
||||
.groups
|
||||
.iter()
|
||||
.flat_map(|group| &group.operations)
|
||||
.flat_map(|operation| {
|
||||
operation
|
||||
.findings
|
||||
.iter()
|
||||
.filter(|finding| finding.code == "external_reference_unavailable")
|
||||
.map(|_| operation.key.clone())
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert!(
|
||||
false_blockers.is_empty(),
|
||||
"the encoded-dot root alias chain must resolve; false blockers: {false_blockers:?}"
|
||||
);
|
||||
assert_eq!(preview.preview.groups[0].operations[0].output_fields, 1);
|
||||
|
||||
// The derived schema must be the child object reached through the canonical
|
||||
// root, projected into the persisted preview.
|
||||
let output_schema =
|
||||
&job.preview_payload["preview"]["groups"][0]["operations"][0]["draft"]["output_schema"];
|
||||
assert_eq!(
|
||||
output_schema["type"], "object",
|
||||
"the operation output schema must be the child object derived through the chain: {output_schema}"
|
||||
);
|
||||
assert_eq!(
|
||||
output_schema["fields"]["id"]["type"], "string",
|
||||
"the child `id` property must survive resolution: {output_schema}"
|
||||
);
|
||||
|
||||
fixture_server.abort();
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
{
|
||||
"dependencies": [],
|
||||
"dependency_snapshots": [],
|
||||
"normalization": {
|
||||
"config": {
|
||||
"external_references_enabled": false,
|
||||
"max_aliases": 128,
|
||||
"max_bytes": 262144,
|
||||
"max_collection_items": 10000,
|
||||
"max_depth": 64,
|
||||
"max_expanded_nodes": 100000,
|
||||
"max_external_document_bytes": 262144,
|
||||
"max_nodes": 50000,
|
||||
"max_reference_depth": 32,
|
||||
"max_reference_documents": 32,
|
||||
"max_references": 4096,
|
||||
"max_scalar_bytes": 262144,
|
||||
"normalizer_version": "normalized-ir-v5",
|
||||
"projection_version": "preview-v6"
|
||||
},
|
||||
"ir_fingerprint": "1e7a724e849b657d79d78f494d962ba5ebc164f154902153a8ed0610e0744679",
|
||||
"normalizer_version": "normalized-ir-v5",
|
||||
"projection_version": "preview-v6"
|
||||
},
|
||||
"preview": {
|
||||
"findings": [],
|
||||
"groups": [
|
||||
{
|
||||
"key": "imported_operation",
|
||||
"operations": [
|
||||
{
|
||||
"category": "imported",
|
||||
"description": "Выполняет GET /items",
|
||||
"draft": {
|
||||
"category": "imported",
|
||||
"display_name": "List Items",
|
||||
"input_mapping": {},
|
||||
"input_schema": {
|
||||
"description": "Входные параметры MCP-инструмента",
|
||||
"nullable": false,
|
||||
"required": true,
|
||||
"type": "object"
|
||||
},
|
||||
"name": "list_items",
|
||||
"output_mapping": {
|
||||
"rules": [
|
||||
{
|
||||
"required": true,
|
||||
"source": "$.response.body.id",
|
||||
"target": "$.output.id"
|
||||
}
|
||||
]
|
||||
},
|
||||
"output_schema": {
|
||||
"description": "Ответ API",
|
||||
"fields": {
|
||||
"id": {
|
||||
"nullable": false,
|
||||
"required": true,
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"nullable": false,
|
||||
"required": true,
|
||||
"type": "object"
|
||||
},
|
||||
"target": {
|
||||
"base_url": "https://api.example.test",
|
||||
"method": "GET",
|
||||
"path_template": "/items",
|
||||
"response_contract": [
|
||||
{
|
||||
"media_type": "application/json",
|
||||
"schema_variant": 0,
|
||||
"status_code": 200
|
||||
}
|
||||
]
|
||||
},
|
||||
"tool_description": {
|
||||
"description": "Выполняет GET /items",
|
||||
"examples": [
|
||||
{
|
||||
"input": {}
|
||||
}
|
||||
],
|
||||
"title": "List Items"
|
||||
},
|
||||
"wizard_state": {}
|
||||
},
|
||||
"findings": [
|
||||
{
|
||||
"code": "missing_summary",
|
||||
"message": "У метода нет summary, отображаемое имя будет сгенерировано автоматически.",
|
||||
"operation_key": "GET /items",
|
||||
"severity": "warning",
|
||||
"source_location": {
|
||||
"pointer": "/paths/~1items/get"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": "missing_description",
|
||||
"message": "У метода нет description. Перед публикацией лучше описать, когда агенту стоит вызывать этот инструмент.",
|
||||
"operation_key": "GET /items",
|
||||
"severity": "warning",
|
||||
"source_location": {
|
||||
"pointer": "/paths/~1items/get"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": "no_input_fields",
|
||||
"message": "У инструмента нет входных параметров. Это нормально для справочных методов, но проверьте, что агенту не нужно передавать фильтры.",
|
||||
"operation_key": "GET /items",
|
||||
"severity": "info",
|
||||
"source_location": {
|
||||
"pointer": "/paths/~1items/get"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": "weak_tool_description",
|
||||
"message": "Описание инструмента слишком короткое или техническое. Перед публикацией добавьте, когда агент должен вызывать инструмент и что будет в успешном ответе.",
|
||||
"operation_key": "GET /items",
|
||||
"severity": "warning",
|
||||
"source_location": {
|
||||
"pointer": "/paths/~1items/get"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": "weak_tool_name",
|
||||
"message": "Имя инструмента `list_items` выглядит слишком общим. Лучше использовать имя с конкретным действием и объектом.",
|
||||
"operation_key": "GET /items",
|
||||
"severity": "warning",
|
||||
"source_location": {
|
||||
"pointer": "/paths/~1items/get"
|
||||
}
|
||||
}
|
||||
],
|
||||
"input_fields": 0,
|
||||
"key": "GET /items",
|
||||
"method": "GET",
|
||||
"operation_id": "listItems",
|
||||
"output_fields": 1,
|
||||
"path": "/items",
|
||||
"server_urls": [
|
||||
"https://api.example.test"
|
||||
],
|
||||
"source_location": {
|
||||
"pointer": "/paths/~1items/get"
|
||||
},
|
||||
"suggested_display_name": "List Items",
|
||||
"suggested_name": "list_items"
|
||||
}
|
||||
],
|
||||
"title": "Без группы"
|
||||
}
|
||||
],
|
||||
"source": {
|
||||
"format": "openapi",
|
||||
"servers": [
|
||||
"https://api.example.test"
|
||||
],
|
||||
"title": "URI preview parity",
|
||||
"version": "3.1.0"
|
||||
}
|
||||
},
|
||||
"preview_digest": "ab615bbb932979b3c9d7d78223fc932069e1d7443860a24c682edddc0de11637",
|
||||
"source": {
|
||||
"digest": "sha256:edc9f4ec760d76a6830ae5b9932881d898626faffbc0067162ddb44ebdf8b94c",
|
||||
"source_id": "src_openapi_01a1278095397d018780ab3dafd4b464"
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,9 @@ impl MachineCredentialVerifier for CorpusMcpCredentialVerifier {
|
||||
|
||||
use super::super::common::*;
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
mod crash_recovery;
|
||||
|
||||
const OPENAPI_SINGLE: &str = r#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Apply test }
|
||||
@@ -98,6 +101,7 @@ paths:
|
||||
responses: { '200': { description: ok } }
|
||||
"#;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct CreatedPlan {
|
||||
reference: String,
|
||||
digest: String,
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
//! Kill the actual HTTP-serving process at durable Apply boundaries, then
|
||||
//! restart the same production router against the parent's database/storage.
|
||||
|
||||
use super::*;
|
||||
use crank_artifacts::test_support::{FaultAction, set_checkpoint};
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
process::{Child, Command, Stdio},
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
const CHILD_TEST: &str =
|
||||
"integration::openapi_import::import_plan_apply::crash_recovery::http_apply_crash_child";
|
||||
const CHILD_CONFIG: &str = "CRANK_TEST_APPLY_CRASH_CONFIG";
|
||||
|
||||
struct PrivateConfigGuard(PathBuf);
|
||||
impl Drop for PrivateConfigGuard {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
struct ChildGuard(Child);
|
||||
impl Drop for ChildGuard {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
|
||||
// Child configuration contains only isolated test fixture credentials. Keep it
|
||||
// in a private file and never include it in assertions, stdout or task logs.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn http_apply_crash_child() {
|
||||
let Ok(path) = std::env::var(CHILD_CONFIG) else {
|
||||
return;
|
||||
};
|
||||
let config: Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
|
||||
let registry = crank_registry::PostgresRegistry::connect(config["database"].as_str().unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let root = PathBuf::from(config["storage"].as_str().unwrap());
|
||||
let server = spawn_admin_api(build_test_app(registry, root)).await;
|
||||
set_checkpoint(config["stage"].as_str().unwrap(), FaultAction::Exit);
|
||||
std::fs::write(config["ready"].as_str().unwrap(), server.as_ref()).unwrap();
|
||||
std::future::pending::<()>().await;
|
||||
}
|
||||
|
||||
async fn counts(registry: &crank_registry::PostgresRegistry) -> (i64, i64, i64) {
|
||||
sqlx::query_as(
|
||||
"select (select count(*) from operations),
|
||||
(select count(*) from operation_versions),
|
||||
(select count(*) from import_plan_applications)",
|
||||
)
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn crash_then_restart(stage: &str, committed: bool) {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let (registry, database_url) = test_registry_with_single_connection().await;
|
||||
let root = test_storage_root(stage);
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let server = spawn_admin_api(build_test_app(registry.clone(), root.clone())).await;
|
||||
let client = authorized_client(&server).await;
|
||||
let plan = create_plan(&client, &server, OPENAPI_SINGLE, full_plan()).await;
|
||||
let store = crank_artifacts::ArtifactStore::open(&root).unwrap();
|
||||
let artifact = store.put_registered(OPENAPI_SINGLE.as_bytes()).unwrap();
|
||||
let key = format!("crash-{stage}");
|
||||
assert_eq!(counts(®istry).await, (0, 0, 0));
|
||||
drop(server);
|
||||
|
||||
let ready = root.join("child.ready");
|
||||
let config_path = root.join("child-config.json");
|
||||
let _private_config = PrivateConfigGuard(config_path.clone());
|
||||
{
|
||||
use std::io::Write;
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.mode(0o600)
|
||||
.open(&config_path)
|
||||
.unwrap();
|
||||
let config = json!({"database":database_url,"storage":root,"stage":stage,"ready":ready});
|
||||
file.write_all(&serde_json::to_vec(&config).unwrap())
|
||||
.unwrap();
|
||||
}
|
||||
let mut child = ChildGuard(
|
||||
Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", CHILD_TEST, "--nocapture"])
|
||||
.env(CHILD_CONFIG, &config_path)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.unwrap(),
|
||||
);
|
||||
let start = Instant::now();
|
||||
let child_url = loop {
|
||||
if let Ok(url) = std::fs::read_to_string(&ready) {
|
||||
break url;
|
||||
}
|
||||
assert!(
|
||||
child.0.try_wait().unwrap().is_none(),
|
||||
"child exited before HTTP readiness"
|
||||
);
|
||||
assert!(
|
||||
start.elapsed() < Duration::from_secs(30),
|
||||
"child HTTP readiness deadline"
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
};
|
||||
let response = client
|
||||
.post(format!(
|
||||
"{child_url}/imports/openapi/{}/apply",
|
||||
plan.reference
|
||||
))
|
||||
.json(&json!({"plan_digest":plan.digest,"idempotency_key":key}))
|
||||
.timeout(Duration::from_secs(30))
|
||||
.send()
|
||||
.await;
|
||||
assert!(response.is_err(), "crash must prevent an HTTP response");
|
||||
let status = loop {
|
||||
if let Some(status) = child.0.try_wait().unwrap() {
|
||||
break status;
|
||||
}
|
||||
assert!(
|
||||
start.elapsed() < Duration::from_secs(35),
|
||||
"child crash deadline"
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
};
|
||||
assert_eq!(
|
||||
status.code(),
|
||||
Some(86),
|
||||
"must hit the exact armed commit boundary"
|
||||
);
|
||||
std::fs::remove_file(config_path).unwrap();
|
||||
std::fs::remove_file(ready).unwrap();
|
||||
let expected = if committed { (1, 1, 1) } else { (0, 0, 0) };
|
||||
// An independent connection can observe only fully committed state.
|
||||
assert_eq!(counts(®istry).await, expected);
|
||||
let before: Option<Value> = sqlx::query_scalar(
|
||||
"select report from import_plan_applications where workspace_id='ws_default' and idempotency_key=$1",
|
||||
).bind(&key).fetch_optional(registry.pool()).await.unwrap();
|
||||
assert_eq!(before.is_some(), committed);
|
||||
|
||||
// The source of this nonexpired job remains referenced after process loss;
|
||||
// cleanup cannot make its plan snapshot eligible for orphan deletion.
|
||||
assert_eq!(sqlx::query_scalar::<_, i64>(
|
||||
"select count(*) from artifact_sources where workspace_id='ws_default' and lifecycle='active'",
|
||||
).fetch_one(registry.pool()).await.unwrap(), 1);
|
||||
let cleanup = registry.cleanup_expired_import_jobs(32).await;
|
||||
assert!(cleanup.is_ok());
|
||||
let now = time::OffsetDateTime::now_utc();
|
||||
let claim = registry
|
||||
.claim_artifact_reconciliation(crank_registry::ClaimArtifactReconciliationRequest {
|
||||
artifact: &artifact,
|
||||
token: crank_registry::ArtifactClaimToken::generate(),
|
||||
claimed_at: now,
|
||||
lease_expires_at: now + time::Duration::minutes(5),
|
||||
detached_grace: time::Duration::hours(24),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
claim,
|
||||
crank_registry::ArtifactClaimOutcome::ActiveReference
|
||||
));
|
||||
assert_eq!(
|
||||
store.read(artifact.artifact_ref()).unwrap(),
|
||||
OPENAPI_SINGLE.as_bytes()
|
||||
);
|
||||
assert_eq!(sqlx::query_scalar::<_, i64>(
|
||||
"select count(*) from artifact_sources where workspace_id='ws_default' and lifecycle='active'",
|
||||
).fetch_one(registry.pool()).await.unwrap(), 1);
|
||||
|
||||
let restarted = spawn_admin_api(build_test_app(registry.clone(), root)).await;
|
||||
let (status, report) = apply_plan(&client, &restarted, &plan, &key).await;
|
||||
assert_eq!(status, reqwest::StatusCode::OK);
|
||||
if let Some(before) = before {
|
||||
assert_eq!(
|
||||
report, before,
|
||||
"restart must return the committed immutable report"
|
||||
);
|
||||
}
|
||||
assert_eq!(report["plan_digest"], plan.digest);
|
||||
assert_eq!(report["counts"]["created"], 1);
|
||||
let (status, replay) = apply_plan(&client, &restarted, &plan, &key).await;
|
||||
assert_eq!(status, reqwest::StatusCode::OK);
|
||||
assert_eq!(
|
||||
replay, report,
|
||||
"exact retry must be byte-equivalent structured report"
|
||||
);
|
||||
assert_eq!(counts(®istry).await, (1, 1, 1));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn http_process_crash_before_commit_rolls_back_and_retries_after_restart() {
|
||||
crash_then_restart("apply_before_commit", false).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn http_process_crash_after_commit_before_response_replays_after_restart() {
|
||||
crash_then_restart("apply_after_commit", true).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn concurrent_distinct_overlapping_http_plans_have_one_coherent_commit() {
|
||||
let (seed_registry, database_url) = test_registry_with_single_connection().await;
|
||||
// The ordinary test registry has only one connection and would serialize
|
||||
// both requests before their transactions even start.
|
||||
let registry = crank_registry::PostgresRegistry::connect_with_options_and_pool_config(
|
||||
database_url
|
||||
.parse::<sqlx::postgres::PgConnectOptions>()
|
||||
.unwrap(),
|
||||
crank_registry::PostgresPoolConfig::try_new(4, 0, 5_000, 60_000, 1_800_000).unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
drop(seed_registry);
|
||||
let server = spawn_admin_api(build_test_app(
|
||||
registry.clone(),
|
||||
test_storage_root("distinct-overlap-plans"),
|
||||
))
|
||||
.await;
|
||||
let client = authorized_client(&server).await;
|
||||
let a = create_plan(&client, &server, OPENAPI_SINGLE, full_plan()).await;
|
||||
let b = create_plan(&client, &server, OPENAPI_TWO_OPERATIONS, full_plan()).await;
|
||||
assert_ne!(a.reference, b.reference);
|
||||
assert_ne!(a.digest, b.digest);
|
||||
let a_key = "overlap-distinct-a";
|
||||
let b_key = "overlap-distinct-b";
|
||||
// Hold the production workspace row lock until BOTH independent Apply
|
||||
// transactions are blocked on it. Merely joining requests could otherwise
|
||||
// exercise two sequential transactions.
|
||||
let mut gate = registry.pool().begin().await.unwrap();
|
||||
let gate_pid: i32 = sqlx::query_scalar("select pg_backend_pid()")
|
||||
.fetch_one(&mut *gate)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("select id from workspaces where id = 'ws_default' for update")
|
||||
.fetch_one(&mut *gate)
|
||||
.await
|
||||
.unwrap();
|
||||
let a_task = tokio::spawn({
|
||||
let (client, server, a) = (client.clone(), server.to_string(), a.clone());
|
||||
async move { apply_plan(&client, &server, &a, a_key).await }
|
||||
});
|
||||
let b_task = tokio::spawn({
|
||||
let (client, server, b) = (client.clone(), server.to_string(), b.clone());
|
||||
async move { apply_plan(&client, &server, &b, b_key).await }
|
||||
});
|
||||
let mut observed_waiting = 0;
|
||||
let barrier_result = tokio::time::timeout(Duration::from_secs(15), async {
|
||||
loop {
|
||||
let waiting: i64 = sqlx::query_scalar(
|
||||
"with recursive blocked(pid) as (
|
||||
select pid from pg_catalog.pg_stat_activity
|
||||
where $1 = any(pg_catalog.pg_blocking_pids(pid))
|
||||
union
|
||||
select activity.pid from pg_catalog.pg_stat_activity activity
|
||||
join blocked on blocked.pid = any(pg_catalog.pg_blocking_pids(activity.pid))
|
||||
)
|
||||
select count(distinct pid) from blocked",
|
||||
)
|
||||
.bind(gate_pid)
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
observed_waiting = waiting;
|
||||
if waiting == 2 {
|
||||
break;
|
||||
}
|
||||
assert!(!a_task.is_finished() && !b_task.is_finished());
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await;
|
||||
assert!(
|
||||
barrier_result.is_ok(),
|
||||
"both distinct Apply transactions must reach the workspace lock; observed {observed_waiting}"
|
||||
);
|
||||
gate.commit().await.unwrap();
|
||||
let ((a_status, a_report), (b_status, b_report)) =
|
||||
(a_task.await.unwrap(), b_task.await.unwrap());
|
||||
assert!(
|
||||
a_status.is_success() ^ b_status.is_success(),
|
||||
"exactly one overlapping plan commits: {a_status}/{b_status}"
|
||||
);
|
||||
let (winner, loser_status, loser) = if a_status.is_success() {
|
||||
(&a_report, b_status, &b_report)
|
||||
} else {
|
||||
(&b_report, a_status, &a_report)
|
||||
};
|
||||
assert_eq!(loser_status, reqwest::StatusCode::CONFLICT);
|
||||
let error_code = loser
|
||||
.pointer("/error/context/error_code")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap();
|
||||
assert!(
|
||||
matches!(
|
||||
error_code,
|
||||
"import_plan_fingerprint_stale" | "import_plan_name_conflict"
|
||||
),
|
||||
"loser must get the exact typed catalog/name conflict, got {error_code}"
|
||||
);
|
||||
let expected = winner["counts"]["created"].as_i64().unwrap();
|
||||
assert!(expected == 1 || expected == 2);
|
||||
assert_eq!(
|
||||
counts(®istry).await,
|
||||
(expected, expected, 1),
|
||||
"loser cannot leave partial Operations/versions/application"
|
||||
);
|
||||
let (winning_plan, winning_key) = if a_status.is_success() {
|
||||
(&a, a_key)
|
||||
} else {
|
||||
(&b, b_key)
|
||||
};
|
||||
let (status, replay) = apply_plan(&client, &server, winning_plan, winning_key).await;
|
||||
assert_eq!(status, reqwest::StatusCode::OK);
|
||||
assert_eq!(&replay, winner);
|
||||
assert_eq!(counts(®istry).await, (expected, expected, 1));
|
||||
}
|
||||
+119
-54
@@ -8,9 +8,17 @@ use admin_api::service::{
|
||||
use crank_core::WorkspaceId;
|
||||
use crank_registry::{CreateImportPlanRequest, ImportPlanId};
|
||||
|
||||
fn single_operation_upload() -> OpenApiUpload {
|
||||
OpenApiUpload {
|
||||
bytes: OPENAPI_SINGLE.as_bytes().to_vec(),
|
||||
mime_type: "application/yaml".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn older_v2_support_matrix_rejects_new_apply_but_keeps_plan_auditable() {
|
||||
async fn older_support_matrix_rejects_new_apply_but_keeps_plan_auditable() {
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
@@ -20,14 +28,7 @@ async fn older_v2_support_matrix_rejects_new_apply_but_keeps_plan_auditable() {
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let preview = service
|
||||
.preview_openapi_import(
|
||||
&workspace_id,
|
||||
OpenApiUpload {
|
||||
bytes: OPENAPI_SINGLE.as_bytes().to_vec(),
|
||||
mime_type: "application/yaml".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
},
|
||||
)
|
||||
.preview_openapi_import(&workspace_id, single_operation_upload())
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id = preview.job_id.as_str().into();
|
||||
@@ -51,56 +52,120 @@ async fn older_v2_support_matrix_rejects_new_apply_but_keeps_plan_auditable() {
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
// Model an immutable plan saved under an earlier support matrix. The
|
||||
// registry derives its valid semantic digest from the changed payload.
|
||||
let old_id: ImportPlanId = "plan_older_support_matrix".into();
|
||||
let mut old_payload = original.payload.clone();
|
||||
old_payload["plan_reference"] = json!(old_id.as_str());
|
||||
old_payload["support_matrix_version"] = json!("1.0.2");
|
||||
let older = registry
|
||||
.create_import_plan(CreateImportPlanRequest {
|
||||
id: &old_id,
|
||||
workspace_id: &workspace_id,
|
||||
job_id: &original.job_id,
|
||||
payload: &old_payload,
|
||||
created_at: &original.created_at,
|
||||
expires_at: &original.expires_at,
|
||||
})
|
||||
// 1.0.2 is the historical matrix contract and 1.0.3 the immediate previous
|
||||
// one; against the shipped 1.0.4 matrix both must stay stale and must not
|
||||
// authorize a new Apply, while the original immutable plan stays auditable.
|
||||
for version in ["1.0.2", "1.0.3"] {
|
||||
// Model an immutable plan saved under an earlier support matrix. The
|
||||
// registry derives its valid semantic digest from the changed payload.
|
||||
let old_id: ImportPlanId =
|
||||
format!("plan_older_support_matrix_{}", version.replace('.', "_")).into();
|
||||
let mut old_payload = original.payload.clone();
|
||||
old_payload["plan_reference"] = json!(old_id.as_str());
|
||||
old_payload["support_matrix_version"] = json!(version);
|
||||
let older = registry
|
||||
.create_import_plan(CreateImportPlanRequest {
|
||||
id: &old_id,
|
||||
workspace_id: &workspace_id,
|
||||
job_id: &original.job_id,
|
||||
payload: &old_payload,
|
||||
created_at: &original.created_at,
|
||||
expires_at: &original.expires_at,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_ne!(older.digest, original.digest);
|
||||
|
||||
let audit = service
|
||||
.revalidate_openapi_import_plan(&workspace_id, &old_id)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(audit.revalidation_status, "stale", "{version}");
|
||||
assert!(audit.revalidation_required, "{version}");
|
||||
assert_eq!(
|
||||
audit.reason.as_deref(),
|
||||
Some("importer_version_changed"),
|
||||
"{version}"
|
||||
);
|
||||
|
||||
let error = service
|
||||
.apply_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&old_id,
|
||||
OpenApiImportPlanApplyPayload {
|
||||
plan_digest: older.digest,
|
||||
idempotency_key: format!("old-matrix-{version}"),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect_err("old support matrix must not authorize a new Apply");
|
||||
match error {
|
||||
ApiError::Conflict {
|
||||
context: Some(context),
|
||||
..
|
||||
} => assert_eq!(context["error_code"], "importer_version_changed"),
|
||||
other => panic!("expected typed re-preview conflict, got {other:?}"),
|
||||
}
|
||||
assert!(
|
||||
service
|
||||
.list_operations(&workspace_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty(),
|
||||
"{version} apply must not mutate the workspace"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// The runtime matrix version stamped into a fresh plan must equal the version
|
||||
// recorded in the machine matrix the corpus validates. Reading the machine YAML
|
||||
// (rather than a second literal) keeps an app release honest: it can never
|
||||
// advertise a matrix the repository does not actually ship.
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn fresh_plan_support_matrix_version_matches_machine_matrix() {
|
||||
let machine_text = std::fs::read_to_string(
|
||||
std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../crates/crank-import/tests/support-matrix.yaml"),
|
||||
)
|
||||
.unwrap();
|
||||
let machine: serde_yaml::Value = serde_yaml::from_str(&machine_text).unwrap();
|
||||
let machine_version = machine["matrix_version"].as_str().unwrap().to_owned();
|
||||
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_support_matrix_runtime_version"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, single_operation_upload())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_ne!(older.digest, original.digest);
|
||||
|
||||
let audit = service
|
||||
.revalidate_openapi_import_plan(&workspace_id, &old_id)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(audit.revalidation_status, "stale");
|
||||
assert!(audit.revalidation_required);
|
||||
assert_eq!(audit.reason.as_deref(), Some("importer_version_changed"));
|
||||
|
||||
let error = service
|
||||
.apply_openapi_import_plan(
|
||||
let job_id = preview.job_id.as_str().into();
|
||||
let created = service
|
||||
.create_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&old_id,
|
||||
OpenApiImportPlanApplyPayload {
|
||||
plan_digest: older.digest,
|
||||
idempotency_key: "old-matrix-new-attempt".to_owned(),
|
||||
&job_id,
|
||||
OpenApiImportPlanCreatePayload {
|
||||
selection_mode: "full".to_owned(),
|
||||
selected_operation_keys: Vec::new(),
|
||||
server_url: None,
|
||||
decisions: Vec::new(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect_err("old support matrix must not authorize a new Apply");
|
||||
match error {
|
||||
ApiError::Conflict {
|
||||
context: Some(context),
|
||||
..
|
||||
} => assert_eq!(context["error_code"], "importer_version_changed"),
|
||||
other => panic!("expected typed re-preview conflict, got {other:?}"),
|
||||
}
|
||||
assert!(
|
||||
service
|
||||
.list_operations(&workspace_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
.unwrap();
|
||||
let stored = registry
|
||||
.get_import_plan(&workspace_id, &created.plan_reference.as_str().into())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
stored.payload["support_matrix_version"],
|
||||
json!(machine_version),
|
||||
"the runtime support-matrix version must match the machine matrix"
|
||||
);
|
||||
}
|
||||
@@ -208,7 +208,7 @@ async fn full_plan_is_server_authored_with_bounded_confirmation_and_no_mutation(
|
||||
assert_eq!(stored.digest, plan.plan_digest);
|
||||
assert_eq!(stored.payload["schema_version"], "import-plan-v2");
|
||||
assert_eq!(stored.payload["catalog_revision"], plan.catalog_revision);
|
||||
assert_eq!(stored.payload["support_matrix_version"], "1.0.3");
|
||||
assert_eq!(stored.payload["support_matrix_version"], "1.0.4");
|
||||
assert!(stored.payload["findings"]["document"].is_array());
|
||||
assert!(stored.payload["findings"]["candidates"].is_array());
|
||||
assert_eq!(stored.expires_at, expires_at);
|
||||
|
||||
@@ -91,3 +91,173 @@ async fn exact_v5_contract_replays_saved_preview_without_source_locations() {
|
||||
.unwrap();
|
||||
assert_eq!(completed.status, ImportJobStatus::Completed);
|
||||
}
|
||||
|
||||
// Deterministic baseline source for the v5/v6 replay characterization. It uses
|
||||
// a local reference so the preview is self-contained (no external dependency
|
||||
// or ephemeral fixture port) while still exercising the reference graph.
|
||||
const URI_PREVIEW_DOCUMENT: &str = r#"
|
||||
openapi: 3.1.0
|
||||
info: { title: URI preview parity, version: '1' }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
paths:
|
||||
/items:
|
||||
get:
|
||||
operationId: listItems
|
||||
responses:
|
||||
'200':
|
||||
description: ok
|
||||
content: { application/json: { schema: { $ref: '#/components/schemas/Item' } } }
|
||||
components:
|
||||
schemas:
|
||||
Item: { type: object, required: [id], properties: { id: { type: string } } }
|
||||
"#;
|
||||
|
||||
fn uri_preview_upload() -> OpenApiUpload {
|
||||
OpenApiUpload {
|
||||
bytes: URI_PREVIEW_DOCUMENT.as_bytes().to_vec(),
|
||||
mime_type: "application/yaml".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
}
|
||||
}
|
||||
|
||||
fn v5_v6_fixture_path() -> std::path::PathBuf {
|
||||
std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("tests/integration/openapi_import/fixtures/v5-v6-uri-preview.json")
|
||||
}
|
||||
|
||||
// AC-4 (history): a preview persisted under the historical (v5, v6) contract
|
||||
// must replay unchanged, and a new preview of the same source must use the
|
||||
// current contract. Captured from baseline execution before the URI change.
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn v5_v6_uri_preview_replays_unchanged_and_new_preview_uses_current_contract() {
|
||||
let fixture_text = std::fs::read_to_string(v5_v6_fixture_path())
|
||||
.expect("baseline v5/v6 URI preview fixture must be captured before the change");
|
||||
let fixture: serde_json::Value = serde_json::from_str(&fixture_text).unwrap();
|
||||
assert_eq!(
|
||||
fixture["normalization"]["normalizer_version"],
|
||||
serde_json::json!("normalized-ir-v5")
|
||||
);
|
||||
assert_eq!(
|
||||
fixture["normalization"]["projection_version"],
|
||||
serde_json::json!("preview-v6")
|
||||
);
|
||||
let fixture_preview = fixture["preview"].clone();
|
||||
let fixture_digest = fixture["preview_digest"].clone();
|
||||
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_v5_v6_replay"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
|
||||
// A current preview of the same bytes must use the current contract.
|
||||
let fresh = service
|
||||
.preview_openapi_import(&workspace_id, uri_preview_upload())
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id: crank_registry::ImportJobId = fresh.job_id.as_str().into();
|
||||
let fresh_job = registry
|
||||
.get_import_job(&workspace_id, &job_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
fresh_job.preview_payload["source"]["digest"], fixture["source"]["digest"],
|
||||
"fixture must refer to the exact captured source bytes"
|
||||
);
|
||||
assert_eq!(
|
||||
fresh_job.preview_payload["normalization"]["normalizer_version"],
|
||||
serde_json::json!(crank_import::rest::NORMALIZER_VERSION)
|
||||
);
|
||||
assert_eq!(
|
||||
fresh_job.preview_payload["normalization"]["projection_version"],
|
||||
serde_json::json!(crank_import::rest::PROJECTION_VERSION)
|
||||
);
|
||||
|
||||
// Bind the historical payload to this run's freshly registered source blob.
|
||||
let mut payload = fixture.clone();
|
||||
payload["source"]["source_id"] = fresh_job.preview_payload["source"]["source_id"].clone();
|
||||
sqlx::query("update import_jobs set preview_payload = $1::jsonb where id = $2")
|
||||
.bind(serde_json::to_string(&payload).unwrap())
|
||||
.bind(job_id.as_str())
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let result = service
|
||||
.create_openapi_import(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /items".to_owned()],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result.created.len(), 1);
|
||||
|
||||
// The historical preview is replayed from its saved projection, never
|
||||
// recomputed under the current normalizer.
|
||||
let completed = registry
|
||||
.get_import_job(&workspace_id, &job_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(completed.status, ImportJobStatus::Completed);
|
||||
assert_eq!(completed.preview_payload["preview"], fixture_preview);
|
||||
assert_eq!(
|
||||
completed.preview_payload["normalization"]["normalizer_version"],
|
||||
serde_json::json!("normalized-ir-v5")
|
||||
);
|
||||
assert_eq!(
|
||||
completed.preview_payload["normalization"]["projection_version"],
|
||||
serde_json::json!("preview-v6")
|
||||
);
|
||||
assert_eq!(completed.preview_payload["preview_digest"], fixture_digest);
|
||||
}
|
||||
|
||||
// AC-4 (version RED): a fresh preview of the fixture source must be stamped with
|
||||
// the approved v6 normalizer contract. This is the version RED, distinct from
|
||||
// the URI transport RED: it pins the exact approved literals instead of
|
||||
// following the current `NORMALIZER_VERSION`/`PROJECTION_VERSION` constants,
|
||||
// which do not by themselves prove the approved v6 value. Deliberately no
|
||||
// if-current branch and no skip: the assertion is unconditional and is expected
|
||||
// to fail until the implementation bumps the normalizer to `normalized-ir-v6`.
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn fresh_preview_matches_approved_v6_normalizer_contract() {
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_v5_v6_version_contract"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let fresh = service
|
||||
.preview_openapi_import(&workspace_id, uri_preview_upload())
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id: crank_registry::ImportJobId = fresh.job_id.as_str().into();
|
||||
let fresh_job = registry
|
||||
.get_import_job(&workspace_id, &job_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
fresh_job.preview_payload["normalization"]["normalizer_version"],
|
||||
serde_json::json!("normalized-ir-v6"),
|
||||
"approved normalizer contract is normalized-ir-v6"
|
||||
);
|
||||
assert_eq!(
|
||||
fresh_job.preview_payload["normalization"]["projection_version"],
|
||||
serde_json::json!("preview-v6"),
|
||||
"approved projection contract is preview-v6"
|
||||
);
|
||||
}
|
||||
@@ -53,30 +53,48 @@ RUN --mount=type=cache,id=crank-mcp-cargo-registry,target=/usr/local/cargo/regis
|
||||
SQLX_OFFLINE=true cargo build --release -p mcp-server \
|
||||
&& cp /app/target/release/mcp-server /tmp/mcp-server
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
# Trusted CA bundle source for the package stage. The slim image ships no CA
|
||||
# certificates, so the HTTPS Debian mirror can only be reached after seeding
|
||||
# them; the Rust base image provides the bundle without rebuilding the app.
|
||||
FROM rust:1.96.1-bookworm AS ca-bundle
|
||||
|
||||
RUN test -s /etc/ssl/certs/ca-certificates.crt
|
||||
|
||||
# Package stage: install the security-refreshed Debian packages, then assemble
|
||||
# the minimal runtime rootfs. Kept independent of the Rust builder so it can be
|
||||
# built and reviewed on its own.
|
||||
FROM debian:bookworm-slim AS runtime-rootfs
|
||||
|
||||
ARG CRANK_SECURITY_REFRESH
|
||||
|
||||
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
|
||||
COPY --from=ca-bundle /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
|
||||
COPY scripts/prepare-runtime-rootfs.sh /usr/local/bin/prepare-runtime-rootfs
|
||||
|
||||
RUN sed -i 's|http://deb.debian.org|https://deb.debian.org|g' /etc/apt/sources.list.d/debian.sources \
|
||||
&& apt-get update \
|
||||
&& apt-get install -y --no-install-recommends --only-upgrade libpcre2-8-0 perl-base \
|
||||
&& apt-get install -y --no-install-recommends --only-upgrade \
|
||||
base-files libc6 libgcc-s1 gcc-12-base bash dash libtinfo6 libselinux1 libpcre2-8-0 coreutils \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& dpkg --compare-versions "$(dpkg-query -W -f='${Version}' libpcre2-8-0)" ge '10.42-1+deb12u2' \
|
||||
&& dpkg --compare-versions "$(dpkg-query -W -f='${Version}' perl-base)" ge '5.36.0-7+deb12u4' \
|
||||
&& sh /usr/local/bin/prepare-runtime-rootfs /runtime \
|
||||
&& echo "crank-security-refresh=${CRANK_SECURITY_REFRESH}"
|
||||
|
||||
WORKDIR /app
|
||||
COPY scripts/docker-http-healthcheck.sh /runtime/usr/local/bin/crank-http-healthcheck
|
||||
|
||||
RUN chmod 0755 /runtime/usr/local/bin/crank-http-healthcheck
|
||||
|
||||
FROM scratch
|
||||
|
||||
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
|
||||
COPY --from=runtime-rootfs /runtime /
|
||||
|
||||
COPY --from=builder /tmp/mcp-server /usr/local/bin/mcp-server
|
||||
COPY scripts/docker-http-healthcheck.sh /usr/local/bin/crank-http-healthcheck
|
||||
|
||||
RUN test -s /etc/ssl/certs/ca-certificates.crt \
|
||||
&& chmod 0755 /usr/local/bin/crank-http-healthcheck
|
||||
|
||||
ENV PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
||||
ENV CRANK_MCP_BIND=0.0.0.0:3002
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
EXPOSE 3002
|
||||
|
||||
CMD ["mcp-server"]
|
||||
@@ -10,12 +10,20 @@ const TEST_MASTER_KEY: &str = "test-master-key-00000000000000000000000000000000"
|
||||
const REGISTERED_MASTER_KEY: &str = "registered-master-key-CANARY_SECRET_VALUE-00000000";
|
||||
const WRONG_MASTER_KEY: &str = "wrong-master-key-CANARY_SECRET_VALUE-0000000000000";
|
||||
|
||||
fn isolated_metrics_bind() -> String {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("ephemeral metrics port");
|
||||
let addr = listener.local_addr().unwrap().to_string();
|
||||
drop(listener);
|
||||
addr
|
||||
}
|
||||
|
||||
fn run_with(entries: &[(&str, &str)]) -> String {
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_mcp-server"));
|
||||
for field in crank_config::field_registry() {
|
||||
command.env_remove(field.env_name);
|
||||
}
|
||||
command.env("CRANK_MASTER_KEY", TEST_MASTER_KEY);
|
||||
command.env("CRANK_MCP_METRICS_BIND", isolated_metrics_bind());
|
||||
for (name, value) in entries {
|
||||
command.env(name, value);
|
||||
}
|
||||
|
||||
@@ -2247,6 +2247,7 @@ Object.assign(TRANSLATIONS.en, {
|
||||
'openapi.finding.missing_servers': 'No base URL was found in the document.',
|
||||
'openapi.finding.multiple_servers': 'Several base URLs are available; choose one before creating drafts.',
|
||||
'openapi.finding.unsupported_request_body': 'This request body needs review in the wizard.',
|
||||
'openapi.finding.external_reference_disabled': 'External references are blocked by default. Check the reference at this source location. A server administrator must add trusted addresses to the server allowlist. For offline use, prepare a self-contained OpenAPI file with its referenced schemas included before uploading; this screen accepts one file and does not upload separate reference files.',
|
||||
'openapi.finding.operation_name_renamed': 'The operation name was adjusted to keep it unique.',
|
||||
'openapi.finding.operation_name_conflict': 'An operation with this name already exists.',
|
||||
'openapi.finding.weak_tool_description': 'The tool description is too short.',
|
||||
@@ -2449,6 +2450,7 @@ Object.assign(TRANSLATIONS.ru, {
|
||||
'openapi.finding.missing_servers': 'В документе не найден base URL.',
|
||||
'openapi.finding.multiple_servers': 'В документе несколько base URL; выберите один перед созданием черновиков.',
|
||||
'openapi.finding.unsupported_request_body': 'Тело этого запроса нужно проверить в мастере.',
|
||||
'openapi.finding.external_reference_disabled': 'Внешние ссылки по умолчанию запрещены. Проверьте ссылку по указанному пути. Администратор сервера может добавить доверенные адреса в список разрешённых адресов. Для работы без сети заранее подготовьте самодостаточный OpenAPI-файл, включив в него схемы из внешних ссылок; этот экран принимает один файл и не загружает отдельные файлы зависимостей.',
|
||||
'openapi.finding.operation_name_renamed': 'Имя операции изменено, чтобы сохранить уникальность.',
|
||||
'openapi.finding.operation_name_conflict': 'Операция с таким именем уже существует.',
|
||||
'openapi.finding.weak_tool_description': 'Описание инструмента слишком короткое.',
|
||||
|
||||
@@ -724,6 +724,7 @@
|
||||
multiple_servers: 'openapi.finding.multiple_servers',
|
||||
unsupported_request_body: 'openapi.finding.unsupported_request_body',
|
||||
unsupported_security_scheme: 'openapi.finding.unsupported_security_scheme',
|
||||
external_reference_disabled: 'openapi.finding.external_reference_disabled',
|
||||
unsupported_security_and_requirement: 'openapi.finding.unsupported_security_and_requirement',
|
||||
auth_profile_required: 'openapi.error.auth_profile_required',
|
||||
operation_name_renamed: 'openapi.finding.operation_name_renamed',
|
||||
|
||||
@@ -101,6 +101,7 @@ trap cleanup EXIT
|
||||
trap 'exit 130' INT TERM
|
||||
|
||||
cleanup
|
||||
rm -f "$TMP_DIR/admin-control.request" "$TMP_DIR/admin-control.ack"
|
||||
|
||||
show_startup_log() {
|
||||
local log_file="$1"
|
||||
@@ -235,7 +236,8 @@ chmod 700 "$CRANK_STORAGE_ROOT"
|
||||
|
||||
(
|
||||
cd "$ROOT_DIR/apps/ui"
|
||||
exec node scripts/playwright-http-fixture.js >"$LOG_DIR/http-fixture.log" 2>&1
|
||||
exec env CRANK_E2E_STREAM_FIXTURE_PORT="$STREAM_FIXTURE_PORT" \
|
||||
node scripts/playwright-http-fixture.js >"$LOG_DIR/http-fixture.log" 2>&1
|
||||
) &
|
||||
echo $! > "$TMP_DIR/http-fixture.pid"
|
||||
|
||||
@@ -292,12 +294,27 @@ if ! (
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Launch the built executable directly so the test lifecycle controls the
|
||||
# actual server PID, rather than a Cargo wrapper. This control exists only in
|
||||
# the local Playwright harness and adds no application endpoint/configuration.
|
||||
(
|
||||
cd "$ROOT_DIR"
|
||||
exec env -u CRANK_MCP_BIND -u CRANK_MCP_REFRESH_MS CRANK_DEMO_SEED=true \
|
||||
cargo run -p admin-api --bin admin-api >>"$LOG_DIR/admin-api.log" 2>&1
|
||||
) &
|
||||
echo $! > "$TMP_DIR/admin-api.pid"
|
||||
cargo build -p admin-api --bin admin-api --example e2e_storage_counts >>"$LOG_DIR/admin-api.log" 2>&1
|
||||
)
|
||||
ADMIN_BINARY="${CARGO_TARGET_DIR:-$ROOT_DIR/target}/debug/admin-api"
|
||||
if [[ "$ADMIN_BINARY" != /* ]]; then
|
||||
ADMIN_BINARY="$ROOT_DIR/$ADMIN_BINARY"
|
||||
fi
|
||||
STORAGE_COUNTS_BINARY="$(dirname "$ADMIN_BINARY")/examples/e2e_storage_counts"
|
||||
start_admin() {
|
||||
(
|
||||
cd "$ROOT_DIR"
|
||||
exec env -u CRANK_MCP_BIND -u CRANK_MCP_REFRESH_MS CRANK_DEMO_SEED=true \
|
||||
"$ADMIN_BINARY" >>"$LOG_DIR/admin-api.log" 2>&1
|
||||
) &
|
||||
echo $! > "$TMP_DIR/admin-api.pid"
|
||||
}
|
||||
start_admin
|
||||
|
||||
wait_for_http \
|
||||
"admin-api" \
|
||||
@@ -322,7 +339,9 @@ wait_for_http \
|
||||
|
||||
(
|
||||
cd "$ROOT_DIR/apps/ui"
|
||||
exec node scripts/playwright-ui-server.js >"$LOG_DIR/ui-server.log" 2>&1
|
||||
exec env CRANK_E2E_UI_PORT="$UI_PORT" CRANK_E2E_ADMIN_PORT="$ADMIN_PORT" \
|
||||
CRANK_E2E_MCP_PORT="$MCP_PORT" \
|
||||
node scripts/playwright-ui-server.js >"$LOG_DIR/ui-server.log" 2>&1
|
||||
) &
|
||||
echo $! > "$TMP_DIR/ui-server.pid"
|
||||
|
||||
@@ -335,5 +354,43 @@ wait_for_http \
|
||||
echo "Crank UI e2e stack is ready on http://127.0.0.1:$UI_PORT"
|
||||
|
||||
while true; do
|
||||
if [[ -f "$TMP_DIR/admin-control.request" ]]; then
|
||||
command=""
|
||||
read -r command < "$TMP_DIR/admin-control.request" || true
|
||||
rm -f "$TMP_DIR/admin-control.request"
|
||||
case "$command" in
|
||||
stop)
|
||||
if [[ -f "$TMP_DIR/admin-api.pid" ]]; then
|
||||
admin_pid="$(cat "$TMP_DIR/admin-api.pid")"
|
||||
kill "$admin_pid" 2>/dev/null || true
|
||||
wait "$admin_pid" || true
|
||||
rm -f "$TMP_DIR/admin-api.pid"
|
||||
fi
|
||||
;;
|
||||
start)
|
||||
if [[ ! -f "$TMP_DIR/admin-api.pid" ]] || \
|
||||
! kill -0 "$(cat "$TMP_DIR/admin-api.pid")" 2>/dev/null; then
|
||||
start_admin
|
||||
fi
|
||||
wait_for_http "restarted admin-api" "http://127.0.0.1:$ADMIN_PORT/health" \
|
||||
"$TMP_DIR/admin-api.pid" "$LOG_DIR/admin-api.log" || exit 1
|
||||
;;
|
||||
counts\ *)
|
||||
workspace="${command#counts }"
|
||||
if [[ ! "$workspace" =~ ^[a-zA-Z0-9_-]{1,128}$ ]]; then
|
||||
echo "Invalid local storage observation scope" >&2
|
||||
exit 1
|
||||
fi
|
||||
"$STORAGE_COUNTS_BINARY" "$workspace" > "$TMP_DIR/storage-counts.json.tmp"
|
||||
mv "$TMP_DIR/storage-counts.json.tmp" "$TMP_DIR/storage-counts.json"
|
||||
;;
|
||||
*)
|
||||
echo "Unknown local Admin API test control command" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
printf '%s\n' "$command" > "$TMP_DIR/admin-control.ack.tmp"
|
||||
mv "$TMP_DIR/admin-control.ack.tmp" "$TMP_DIR/admin-control.ack"
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
@@ -292,6 +292,8 @@ test('authentication recovery returns to an incomplete authoritative onboarding
|
||||
});
|
||||
|
||||
await page.goto('/');
|
||||
// Wait for the initial projection and its automatic panel opening before toggling.
|
||||
await expect(page.getByTestId('onboarding-trigger')).toContainText(/3\s*\/\s*7/);
|
||||
if (!await page.getByTestId('onboarding-checklist').isVisible()) {
|
||||
await page.getByTestId('onboarding-trigger').click();
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ function planResponse(prefix) {
|
||||
};
|
||||
}
|
||||
|
||||
async function preparePlanFlow(page, locale) {
|
||||
async function preparePlanFlow(page, locale, reportFixture) {
|
||||
const planCalls = [];
|
||||
const applyCalls = [];
|
||||
const prefix = uniqueName('plan_apply');
|
||||
@@ -98,7 +98,7 @@ async function preparePlanFlow(page, locale) {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
body: JSON.stringify(reportFixture || {
|
||||
plan_digest: 'a'.repeat(64),
|
||||
counts: { selected: 1, excluded: 1, created: 0, versioned: 1 },
|
||||
outcomes: [{ status: 'versioned' }],
|
||||
@@ -196,6 +196,63 @@ test('[P1] AC-13 double-click sends one Apply with the stored reference, digest
|
||||
expect(applyCalls[0].payload.idempotency_key.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
for (const locale of ['en', 'ru']) {
|
||||
test(`[P1] AC-2.13-13 renders every immutable Apply outcome in ${locale}`, async ({ page }) => {
|
||||
const reportFixture = {
|
||||
plan_digest: 'd'.repeat(64),
|
||||
idempotency_key: 'apply-report-full-outcomes',
|
||||
status: 'applied',
|
||||
counts: { selected: 5, excluded: 0, created: 1, versioned: 1, renamed: 1, skipped: 1, rejected: 1 },
|
||||
outcomes: [
|
||||
{ key: 'GET /created', name: 'created_operation', status: 'created', version: 1 },
|
||||
{ key: 'GET /versioned', name: 'versioned_operation', status: 'versioned', version: 2 },
|
||||
{ key: 'GET /renamed', name: 'renamed_operation', status: 'renamed', version: 1 },
|
||||
{ key: 'GET /skipped', name: 'skipped_operation', status: 'skipped', reason: 'not_selected' },
|
||||
{
|
||||
key: 'GET /rejected',
|
||||
name: 'rejected_operation',
|
||||
status: 'rejected',
|
||||
reason: 'unsupported_schema',
|
||||
message: 'raw-report-canary https://report-secret.example.test/internal',
|
||||
},
|
||||
],
|
||||
};
|
||||
const { releaseApplyResponse } = await preparePlanFlow(page, locale, reportFixture);
|
||||
await page.locator('[data-testid="openapi-import-apply-confirmation"]').getByRole('button', {
|
||||
name: localized('Apply import', 'Применить импорт'),
|
||||
}).click();
|
||||
releaseApplyResponse();
|
||||
|
||||
const report = page.locator('[data-testid="openapi-import-apply-result"]');
|
||||
await expect(report).toBeVisible();
|
||||
await expect(report.locator('.openapi-import-plan-summary')).toContainText(
|
||||
localized('Applied: 3; skipped: 1; excluded: 0; rejected: 1.', 'Применено: 3; пропущено: 1; исключено: 0; отклонено: 1.'),
|
||||
);
|
||||
for (const outcome of reportFixture.outcomes) {
|
||||
const row = report.locator(`[data-outcome="${outcome.status}"]`);
|
||||
await expect(row).toHaveCount(1);
|
||||
await expect(row).toContainText(outcome.name);
|
||||
await expect(row).toContainText(outcome.key);
|
||||
if (outcome.version) await expect(row).toContainText(`v${outcome.version}`);
|
||||
if (outcome.reason) {
|
||||
const reason = row.locator('.openapi-import-plan-reason');
|
||||
await expect(reason).toBeVisible();
|
||||
await expect(reason).toContainText(localized(
|
||||
'This imported item needs review in the wizard.',
|
||||
'Этот импортированный элемент нужно проверить в мастере.',
|
||||
));
|
||||
}
|
||||
}
|
||||
await expect(report.locator('[data-outcome="created"]')).toContainText(localized('Created', 'Создано'));
|
||||
await expect(report.locator('[data-outcome="versioned"]')).toContainText(localized('New Draft Version', 'Новая версия черновика'));
|
||||
await expect(report.locator('[data-outcome="renamed"]')).toContainText(localized('Created with confirmed name', 'Создано с подтверждённым именем'));
|
||||
await expect(report.locator('[data-outcome="skipped"]')).toContainText(localized('Skipped', 'Пропущено'));
|
||||
await expect(report.locator('[data-outcome="rejected"]')).toContainText(localized('Rejected', 'Отклонено'));
|
||||
await expect(report).not.toContainText('raw-report-canary');
|
||||
await expect(report).not.toContainText('https://report-secret.example.test/internal');
|
||||
});
|
||||
}
|
||||
|
||||
test('[P1] AC-13 submits the confirmed new_version decision for the exact existing operation', async ({ page }) => {
|
||||
const prefix = uniqueName('plan_version');
|
||||
const targetOperationId = 'op_exact_importplan_target';
|
||||
|
||||
@@ -188,6 +188,44 @@ test('[P1] AC-1 preview renders source locations and stable finding codes for ca
|
||||
await expect(row.locator('[data-testid="openapi-import-conflict-location"]')).toContainText('/operationId');
|
||||
});
|
||||
|
||||
for (const locale of ['en', 'ru']) {
|
||||
test(`[P0] AC-2.8-02 external reference denial gives safe guidance and stays blocked in ${locale}`, async ({ page }) => {
|
||||
const prefix = uniqueName('preview_external_denied');
|
||||
const sourceCanary = 'private-reference-message-canary';
|
||||
const urlCanary = 'https://private.example.test/internal/openapi.yaml';
|
||||
const operations = [candidate(prefix, 'blocked', {
|
||||
status: 'blocked',
|
||||
findings: [{
|
||||
code: 'external_reference_disabled',
|
||||
severity: 'error',
|
||||
message: sourceCanary + ' ' + urlCanary,
|
||||
operation_key: 'GET /' + prefix + '-blocked',
|
||||
source_location: { pointer: '/paths/~1' + prefix + '-blocked/get/schema/$ref' },
|
||||
}],
|
||||
})];
|
||||
const response = previewResponse(prefix, operations);
|
||||
await routeOperationsEmpty(page);
|
||||
await page.route('**/api/admin/workspaces/*/imports/openapi/preview', async (route) => {
|
||||
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(response) });
|
||||
});
|
||||
await openImportModal(page, locale);
|
||||
await uploadAndPreview(page, prefix, [[prefix + '-blocked', prefix + '_blocked']]);
|
||||
|
||||
const row = page.locator('.openapi-import-operation').first();
|
||||
const selection = row.locator('[data-openapi-operation]');
|
||||
await expect(selection).toBeDisabled();
|
||||
await expect(row.locator('[data-testid="openapi-import-operation-readiness"]')).toHaveAttribute('data-state', 'blocked');
|
||||
await expect(page.locator('[data-testid="openapi-import-blockers"]')).toContainText('external_reference_disabled');
|
||||
await row.locator('.openapi-import-findings summary').click();
|
||||
const finding = row.locator('.openapi-import-finding');
|
||||
await expect(finding).toContainText('external_reference_disabled');
|
||||
await expect(finding).toContainText(locale === 'en' ? /server allowlist/i : /список разрешённых адресов/i);
|
||||
await expect(finding).toContainText(locale === 'en' ? /offline/i : /работы без сети/i);
|
||||
await expect(finding).not.toContainText(sourceCanary);
|
||||
await expect(finding).not.toContainText(urlCanary);
|
||||
});
|
||||
}
|
||||
|
||||
// AC-4: duplicate/invalid/taken names must show a deterministic rename
|
||||
// proposal and conflict type, and the snapshot must stay unchanged.
|
||||
test('[P1] AC-4 preview shows conflict type and deterministic rename proposal without mutating the snapshot', async ({ page }) => {
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
const fs = require('node:fs/promises');
|
||||
const path = require('node:path');
|
||||
const { test, expect } = require('@playwright/test');
|
||||
const { getCurrentWorkspace, login, localized, uniqueName } = require('./helpers');
|
||||
|
||||
const controlDirectory = path.resolve(__dirname, '../../../../.tmp/ui-e2e');
|
||||
|
||||
async function dismissOnboardingIfOpen(page) {
|
||||
await page.locator('#crank-onboarding-panel').waitFor({ state: 'attached' });
|
||||
await page.locator('[data-testid="onboarding-dismiss"]').waitFor({ state: 'attached' });
|
||||
await page.evaluate(() => document.querySelector('[data-testid="onboarding-dismiss"]').click());
|
||||
await expect(page.locator('#crank-onboarding-panel')).toBeHidden();
|
||||
}
|
||||
|
||||
function openApiDocument(operationId) {
|
||||
return [
|
||||
'openapi: 3.0.3',
|
||||
`info: { title: '${operationId}', version: '1' }`,
|
||||
'servers: [{ url: https://api.example.test }]',
|
||||
'paths:',
|
||||
` /${operationId}:`,
|
||||
' get:',
|
||||
` operationId: ${operationId}`,
|
||||
' summary: Recovery test operation',
|
||||
' responses:',
|
||||
" '200': { description: OK }",
|
||||
'',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
async function operationSnapshot(page, workspaceId) {
|
||||
return page.evaluate(async (id) => {
|
||||
const response = await window.CrankApi.listOperations(id);
|
||||
if (!response || !Array.isArray(response.items)) throw new Error('Operations API returned no item list');
|
||||
return response.items;
|
||||
}, workspaceId);
|
||||
}
|
||||
|
||||
async function requestAdminControl(command) {
|
||||
const requestFile = path.join(controlDirectory, 'admin-control.request');
|
||||
const ackFile = path.join(controlDirectory, 'admin-control.ack');
|
||||
await fs.mkdir(controlDirectory, { recursive: true });
|
||||
await fs.rm(ackFile, { force: true });
|
||||
const temporaryFile = `${requestFile}.${process.pid}.${Date.now()}.tmp`;
|
||||
await fs.writeFile(temporaryFile, `${command}\n`, { mode: 0o600 });
|
||||
await fs.rename(temporaryFile, requestFile);
|
||||
await expect.poll(async () => {
|
||||
try {
|
||||
return (await fs.readFile(ackFile, 'utf8')).trim();
|
||||
} catch (_error) {
|
||||
return '';
|
||||
}
|
||||
}, { timeout: 30_000, message: `Admin API did not acknowledge ${command}` }).toBe(command);
|
||||
}
|
||||
|
||||
async function adminApiPid() {
|
||||
return (await fs.readFile(path.join(controlDirectory, 'admin-api.pid'), 'utf8')).trim();
|
||||
}
|
||||
|
||||
async function storageCounts(workspaceId) {
|
||||
await requestAdminControl(`counts ${workspaceId}`);
|
||||
return JSON.parse(await fs.readFile(path.join(controlDirectory, 'storage-counts.json'), 'utf8'));
|
||||
}
|
||||
|
||||
async function openImport(page, operationId) {
|
||||
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
|
||||
await page.locator('#openapi-import-file').setInputFiles({
|
||||
name: `${operationId}.yaml`,
|
||||
mimeType: 'application/yaml',
|
||||
buffer: Buffer.from(openApiDocument(operationId)),
|
||||
});
|
||||
const previewResponse = page.waitForResponse((response) =>
|
||||
response.request().method() === 'POST'
|
||||
&& response.url().includes('/imports/openapi/preview'));
|
||||
await page.locator('#openapi-import-preview').click();
|
||||
const response = await previewResponse;
|
||||
expect(response.ok()).toBe(true);
|
||||
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
|
||||
return response;
|
||||
}
|
||||
|
||||
test('[P1] AC03 real invalid preview shows the exact canonical correlation headers', async ({ page }) => {
|
||||
await login(page);
|
||||
await dismissOnboardingIfOpen(page);
|
||||
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
|
||||
await page.locator('#openapi-import-file').setInputFiles({
|
||||
name: 'invalid-openapi.yaml',
|
||||
mimeType: 'application/yaml',
|
||||
buffer: Buffer.from('openapi: [\n'),
|
||||
});
|
||||
|
||||
const rejectedPreview = page.waitForResponse((response) =>
|
||||
response.request().method() === 'POST'
|
||||
&& response.url().includes('/imports/openapi/preview'));
|
||||
await page.locator('#openapi-import-preview').click();
|
||||
const response = await rejectedPreview;
|
||||
expect(response.status()).toBeGreaterThanOrEqual(400);
|
||||
expect(response.status()).toBeLessThan(500);
|
||||
|
||||
const requestId = response.headers()['x-request-id'];
|
||||
const traceId = response.headers()['x-trace-id'];
|
||||
expect(requestId).toBeTruthy();
|
||||
expect(traceId).toMatch(/^[a-f0-9]{32}$/i);
|
||||
const status = page.locator('#openapi-import-status');
|
||||
await expect(status).toBeFocused();
|
||||
await expect(status).toHaveAttribute('role', 'status');
|
||||
await expect(status).toHaveAttribute('aria-live', 'polite');
|
||||
await expect(status).toHaveAttribute('aria-atomic', 'true');
|
||||
await expect(status).toContainText(requestId);
|
||||
await expect(status).toContainText(traceId);
|
||||
await expect(status).toContainText('Request ID:');
|
||||
await expect(status).toContainText('Trace ID:');
|
||||
});
|
||||
|
||||
test('[P1] AC05 real preview and plan do not mutate Operations; reduced-motion Apply replay survives reload and API restart', async ({ page }) => {
|
||||
// This journey includes bounded process stop/start and several database observations.
|
||||
test.setTimeout(120_000);
|
||||
await page.emulateMedia({ reducedMotion: 'reduce' });
|
||||
await login(page);
|
||||
await dismissOnboardingIfOpen(page);
|
||||
expect(await page.evaluate(() => window.matchMedia('(prefers-reduced-motion: reduce)').matches)).toBe(true);
|
||||
|
||||
const workspace = await getCurrentWorkspace(page);
|
||||
expect(workspace && workspace.id).toBeTruthy();
|
||||
const initialOperations = await operationSnapshot(page, workspace.id);
|
||||
const initialCounts = await storageCounts(workspace.id);
|
||||
expect(initialCounts).toMatchObject({
|
||||
sources: expect.any(Number),
|
||||
operations: expect.any(Number),
|
||||
versions: expect.any(Number),
|
||||
});
|
||||
const operationId = uniqueName('recovery_import').replace(/[^a-zA-Z0-9_]/g, '_');
|
||||
const applyRequests = [];
|
||||
const apiRequests = { preview: 0, createPlan: 0, apply: 0 };
|
||||
page.on('request', (request) => {
|
||||
if (request.method() !== 'POST') return;
|
||||
const url = request.url();
|
||||
if (url.includes('/imports/openapi/preview')) apiRequests.preview += 1;
|
||||
if (/\/imports\/openapi\/[^/]+\/plans(?:\?|$)/.test(url)) apiRequests.createPlan += 1;
|
||||
if (/\/imports\/openapi\/[^/]+\/apply(?:\?|$)/.test(url)) apiRequests.apply += 1;
|
||||
});
|
||||
await page.route('**/imports/openapi/*/apply', async (route) => {
|
||||
applyRequests.push({
|
||||
url: route.request().url(),
|
||||
body: route.request().postData(),
|
||||
});
|
||||
if (applyRequests.length === 1) {
|
||||
// Send the real request to Admin API, then lose only its browser response.
|
||||
const response = await route.fetch();
|
||||
expect(response.ok()).toBe(true);
|
||||
await route.abort('connectionreset');
|
||||
return;
|
||||
}
|
||||
await route.continue();
|
||||
});
|
||||
|
||||
await openImport(page, operationId);
|
||||
expect(await operationSnapshot(page, workspace.id)).toEqual(initialOperations);
|
||||
expect(apiRequests.preview).toBe(1);
|
||||
const afterPreviewCounts = await storageCounts(workspace.id);
|
||||
expect(afterPreviewCounts).toEqual({
|
||||
...initialCounts,
|
||||
sources: initialCounts.sources + 1,
|
||||
});
|
||||
const dialogMotion = await page.locator('.openapi-import-dialog').evaluate((node) => getComputedStyle(node).transitionDuration);
|
||||
expect(dialogMotion.split(',').every((duration) => Number.parseFloat(duration) === 0)).toBe(true);
|
||||
await page.locator('#openapi-import-server-custom').fill('https://api.example.test');
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
|
||||
expect(await operationSnapshot(page, workspace.id)).toEqual(initialOperations);
|
||||
expect(apiRequests.createPlan).toBe(1);
|
||||
expect(await storageCounts(workspace.id)).toEqual(afterPreviewCounts);
|
||||
|
||||
await page.locator('#openapi-import-plan-apply').click();
|
||||
await expect.poll(() => applyRequests.length).toBe(1);
|
||||
expect(apiRequests.apply).toBe(1);
|
||||
const applyStatus = page.locator('#openapi-import-status');
|
||||
await expect(applyStatus).toBeFocused();
|
||||
await expect(applyStatus).toHaveAttribute('role', 'status');
|
||||
await expect(applyStatus).toHaveAttribute('aria-live', 'polite');
|
||||
await expect(applyStatus).toHaveAttribute('aria-atomic', 'true');
|
||||
await expect(applyStatus).toContainText(localized('Apply result is unknown', 'Результат применения неизвестен'));
|
||||
await expect(page.locator('#openapi-import-retry')).toBeVisible();
|
||||
const committedOperations = await operationSnapshot(page, workspace.id);
|
||||
expect(committedOperations).toHaveLength(initialOperations.length + 1);
|
||||
expect(committedOperations.some((operation) => operation.name === operationId
|
||||
|| operation.operation_id === operationId)).toBe(true);
|
||||
const committedCounts = await storageCounts(workspace.id);
|
||||
expect(committedCounts).toEqual({
|
||||
...afterPreviewCounts,
|
||||
operations: afterPreviewCounts.operations + 1,
|
||||
versions: afterPreviewCounts.versions + 1,
|
||||
});
|
||||
|
||||
const pidBeforeRestart = await adminApiPid();
|
||||
let adminMayBeStopped = true;
|
||||
try {
|
||||
await requestAdminControl('stop');
|
||||
await requestAdminControl('start');
|
||||
adminMayBeStopped = false;
|
||||
} finally {
|
||||
if (adminMayBeStopped) await requestAdminControl('start');
|
||||
}
|
||||
expect(await adminApiPid()).not.toBe(pidBeforeRestart);
|
||||
expect(await storageCounts(workspace.id)).toEqual(committedCounts);
|
||||
await page.reload();
|
||||
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
|
||||
await expect(page.locator('#openapi-import-retry')).toBeVisible();
|
||||
await expect(page.locator('#openapi-import-status')).toContainText(localized('Apply result is unknown', 'Результат применения неизвестен'));
|
||||
|
||||
const retryResponse = page.waitForResponse((response) =>
|
||||
response.request().method() === 'POST'
|
||||
&& response.url().includes('/imports/openapi/')
|
||||
&& response.url().endsWith('/apply'));
|
||||
await page.locator('#openapi-import-retry').click();
|
||||
const response = await retryResponse;
|
||||
expect(response.status()).toBe(200);
|
||||
await expect(page.locator('#openapi-import-result')).toContainText(operationId);
|
||||
await expect.poll(() => applyRequests.length).toBe(2);
|
||||
expect(applyRequests[1].url).toBe(applyRequests[0].url);
|
||||
expect(applyRequests[1].body).toBe(applyRequests[0].body);
|
||||
expect(apiRequests).toEqual({ preview: 1, createPlan: 1, apply: 2 });
|
||||
|
||||
const finalOperations = await operationSnapshot(page, workspace.id);
|
||||
expect(finalOperations).toHaveLength(initialOperations.length + 1);
|
||||
expect(finalOperations.filter((operation) => operation.name === operationId
|
||||
|| operation.operation_id === operationId)).toHaveLength(1);
|
||||
expect(await storageCounts(workspace.id)).toEqual(committedCounts);
|
||||
});
|
||||
@@ -367,6 +367,8 @@ impl ExternalReferenceFetcher {
|
||||
fn outbound_client(policy: &OutboundHttpPolicy) -> Result<Client, Arc<str>> {
|
||||
let resolver = Arc::new(PolicyDnsResolver {
|
||||
policy: policy.clone(),
|
||||
#[cfg(test)]
|
||||
lookup: None,
|
||||
});
|
||||
Client::builder()
|
||||
.redirect(redirect::Policy::none())
|
||||
@@ -611,23 +613,43 @@ impl OutboundHttpPolicy {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Clone)]
|
||||
struct PolicyDnsResolver {
|
||||
policy: OutboundHttpPolicy,
|
||||
// Test-local DNS answers exercise the actual policy resolver and connector.
|
||||
// Neither this field nor an injection API exists in production builds.
|
||||
#[cfg(test)]
|
||||
lookup: Option<Arc<dyn Resolve>>,
|
||||
}
|
||||
|
||||
impl PolicyDnsResolver {
|
||||
fn lookup(&self, name: Name) -> Resolving {
|
||||
#[cfg(test)]
|
||||
if let Some(lookup) = &self.lookup {
|
||||
return lookup.resolve(name);
|
||||
}
|
||||
let host = normalize_host(name.as_str());
|
||||
Box::pin(async move {
|
||||
let addresses = tokio::net::lookup_host((host.as_str(), 0))
|
||||
.await
|
||||
.map_err(|error| Box::new(error) as Box<dyn std::error::Error + Send + Sync>)?;
|
||||
let addresses: Vec<_> = addresses.collect();
|
||||
Ok(Box::new(addresses.into_iter()) as Addrs)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Resolve for PolicyDnsResolver {
|
||||
fn resolve(&self, name: Name) -> Resolving {
|
||||
let host = normalize_host(name.as_str());
|
||||
let policy = self.policy.clone();
|
||||
let resolver = self.clone();
|
||||
Box::pin(async move {
|
||||
policy
|
||||
.validate_host(&host)
|
||||
.map_err(|error| boxed_io_error(error.to_string()))?;
|
||||
let explicitly_allowed = policy.is_explicitly_allowed(&host);
|
||||
let resolved = tokio::net::lookup_host((host.as_str(), 0))
|
||||
.await
|
||||
.map_err(|error| Box::new(error) as Box<dyn std::error::Error + Send + Sync>)?;
|
||||
let resolved = resolver.lookup(name).await?;
|
||||
let addresses = resolved
|
||||
.filter(|address| {
|
||||
!policy.is_denied_ip(address.ip())
|
||||
@@ -969,3 +991,7 @@ fn to_reqwest_method(method: HttpMethod) -> reqwest::Method {
|
||||
HttpMethod::Options => reqwest::Method::OPTIONS,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "client_dns_tests.rs"]
|
||||
mod dns_tests;
|
||||
@@ -0,0 +1,155 @@
|
||||
//! Use the production policy resolver in reqwest's real connector. DNS can
|
||||
//! change immediately after lookup; only the validated returned addresses may
|
||||
//! be connected to, and a subsequent resolution must enforce policy again.
|
||||
|
||||
use super::*;
|
||||
use axum::{Router, routing::get};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
struct ChangingLookup {
|
||||
calls: AtomicUsize,
|
||||
answers: Vec<Vec<SocketAddr>>,
|
||||
}
|
||||
impl Resolve for ChangingLookup {
|
||||
fn resolve(&self, _: Name) -> Resolving {
|
||||
// Advancing before the connector receives this iterator models a DNS
|
||||
// answer changing between validation and the socket connection.
|
||||
let call = self.calls.fetch_add(1, Ordering::SeqCst);
|
||||
let addresses = self.answers[call.min(self.answers.len() - 1)].clone();
|
||||
Box::pin(async move { Ok(Box::new(addresses.into_iter()) as Addrs) })
|
||||
}
|
||||
}
|
||||
|
||||
struct Listeners(Vec<tokio::task::JoinHandle<()>>);
|
||||
impl Drop for Listeners {
|
||||
fn drop(&mut self) {
|
||||
for handle in &self.0 {
|
||||
handle.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn fixture() -> (u16, Arc<AtomicUsize>, Arc<AtomicUsize>, Listeners) {
|
||||
let allowed = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = allowed.local_addr().unwrap().port();
|
||||
let denied = tokio::net::TcpListener::bind((Ipv4Addr::new(127, 0, 0, 2), port))
|
||||
.await
|
||||
.unwrap();
|
||||
let allowed_count = Arc::new(AtomicUsize::new(0));
|
||||
let denied_count = Arc::new(AtomicUsize::new(0));
|
||||
let mut handles = Vec::new();
|
||||
for (listener, count) in [
|
||||
(allowed, Arc::clone(&allowed_count)),
|
||||
(denied, Arc::clone(&denied_count)),
|
||||
] {
|
||||
handles.push(tokio::spawn(async move {
|
||||
let app = Router::new().route(
|
||||
"/document",
|
||||
get(move || {
|
||||
let count = Arc::clone(&count);
|
||||
async move {
|
||||
count.fetch_add(1, Ordering::SeqCst);
|
||||
"snapshot"
|
||||
}
|
||||
}),
|
||||
);
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
}));
|
||||
}
|
||||
(port, allowed_count, denied_count, Listeners(handles))
|
||||
}
|
||||
|
||||
fn policy_client(lookup: Arc<ChangingLookup>) -> Client {
|
||||
let policy = OutboundHttpPolicy::try_new(
|
||||
vec!["reference.invalid".into()],
|
||||
vec!["127.0.0.2".into()],
|
||||
1024,
|
||||
)
|
||||
.unwrap();
|
||||
Client::builder()
|
||||
.no_proxy()
|
||||
.redirect(redirect::Policy::none())
|
||||
.pool_max_idle_per_host(0)
|
||||
.timeout(Duration::from_secs(3))
|
||||
.dns_resolver(Arc::new(PolicyDnsResolver {
|
||||
policy,
|
||||
lookup: Some(lookup),
|
||||
}))
|
||||
.build()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dns_rebinding_pins_the_validated_connection_then_rejects_changed_denied_answer() {
|
||||
let (port, allowed, denied, _listeners) = fixture().await;
|
||||
let lookup = Arc::new(ChangingLookup {
|
||||
calls: AtomicUsize::new(0),
|
||||
answers: vec![
|
||||
vec!["127.0.0.1:0".parse().unwrap()],
|
||||
vec!["127.0.0.2:0".parse().unwrap()],
|
||||
],
|
||||
});
|
||||
let client = policy_client(Arc::clone(&lookup));
|
||||
let url = format!("http://reference.invalid:{port}/document");
|
||||
let body = client
|
||||
.get(&url)
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.error_for_status()
|
||||
.unwrap()
|
||||
.text()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(body, "snapshot");
|
||||
assert_eq!(
|
||||
lookup.calls.load(Ordering::SeqCst),
|
||||
1,
|
||||
"one validated answer is pinned for this connection"
|
||||
);
|
||||
assert_eq!(allowed.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(denied.load(Ordering::SeqCst), 0);
|
||||
|
||||
// Disable idle pooling above so a new connection really asks for the new
|
||||
// answer; no timing or external DNS configuration is involved.
|
||||
let error = client.get(&url).send().await.unwrap_err();
|
||||
assert!(error.is_connect());
|
||||
assert!(
|
||||
!error.is_timeout(),
|
||||
"must reject the new DNS answer, not merely time out"
|
||||
);
|
||||
assert_eq!(lookup.calls.load(Ordering::SeqCst), 2);
|
||||
assert_eq!(allowed.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(
|
||||
denied.load(Ordering::SeqCst),
|
||||
0,
|
||||
"deny must win over hostname allowlist"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mixed_dns_answers_never_pass_denied_address_to_the_connector() {
|
||||
let (port, allowed, denied, _listeners) = fixture().await;
|
||||
let lookup = Arc::new(ChangingLookup {
|
||||
calls: AtomicUsize::new(0),
|
||||
answers: vec![vec![
|
||||
"127.0.0.2:0".parse().unwrap(),
|
||||
"127.0.0.1:0".parse().unwrap(),
|
||||
]],
|
||||
});
|
||||
let client = policy_client(Arc::clone(&lookup));
|
||||
assert_eq!(
|
||||
client
|
||||
.get(format!("http://reference.invalid:{port}/document"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.text()
|
||||
.await
|
||||
.unwrap(),
|
||||
"snapshot"
|
||||
);
|
||||
assert_eq!(lookup.calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(allowed.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(denied.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
@@ -30,6 +30,18 @@ pub enum FaultAction {
|
||||
Hold,
|
||||
}
|
||||
|
||||
/// Terminates a debug test process at an explicitly armed transaction boundary.
|
||||
/// Release builds contain neither this hook nor its callers. The checkpoint
|
||||
/// is in-memory only; a request or environment variable cannot arm it.
|
||||
#[cfg(debug_assertions)]
|
||||
pub fn crash_if_checkpointed(stage: &str) {
|
||||
if action(stage) == Some(FaultAction::Exit) {
|
||||
// Deliberately skip destructors/atexit, as a lost process would. Test
|
||||
// containers belong to the parent process, not this child.
|
||||
unsafe { libc::_exit(86) }
|
||||
}
|
||||
}
|
||||
|
||||
struct State {
|
||||
checkpoint: Option<(String, FaultAction, usize)>,
|
||||
hits: BTreeMap<String, usize>,
|
||||
|
||||
@@ -643,6 +643,47 @@ fn corrupted_or_symlinked_final_never_returns_bytes() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_published_blob_is_integrity_failure_with_safe_diagnostics() {
|
||||
let root = TestRoot::new("truncated-final");
|
||||
let store = ArtifactStore::open(&root.0).unwrap();
|
||||
let source = b"published blob truncated tail".as_slice();
|
||||
let stored = store.put(source).unwrap();
|
||||
let path = root
|
||||
.0
|
||||
.join("sha256")
|
||||
.join(&stored.artifact_ref.digest_hex()[..2])
|
||||
.join(stored.artifact_ref.digest_hex());
|
||||
assert_eq!(
|
||||
fs::metadata(&path).unwrap().permissions().mode() & 0o777,
|
||||
0o400
|
||||
);
|
||||
|
||||
// Publishing leaves the blob read-only. Reopen it writable only long enough
|
||||
// to truncate the tail, then restore the exact private mode the verified
|
||||
// reader validates before it compares length and digest.
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
|
||||
fs::File::options()
|
||||
.write(true)
|
||||
.open(&path)
|
||||
.unwrap()
|
||||
.set_len(u64::try_from(source.len() - 4).unwrap())
|
||||
.unwrap();
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o400)).unwrap();
|
||||
assert_eq!(
|
||||
fs::metadata(&path).unwrap().permissions().mode() & 0o777,
|
||||
0o400
|
||||
);
|
||||
|
||||
let error = store.read(&stored.artifact_ref).unwrap_err();
|
||||
assert_eq!(error, ArtifactError::Integrity);
|
||||
assert_eq!(error.to_string(), "artifact integrity verification failed");
|
||||
let diagnostic = format!("{error} {error:?}");
|
||||
assert!(!diagnostic.contains(stored.artifact_ref.digest_hex()));
|
||||
assert!(!diagnostic.contains(root.0.to_string_lossy().as_ref()));
|
||||
assert!(!diagnostic.contains("published"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_at_final_digest_is_integrity_failure() {
|
||||
let root = TestRoot::new("directory-final");
|
||||
|
||||
@@ -355,16 +355,19 @@ fn real_process_write_limit_leaves_no_partial_final_blob() {
|
||||
}
|
||||
|
||||
let root = TestRoot::new("real-write-limit");
|
||||
let status = Command::new(std::env::current_exe().unwrap())
|
||||
// Capture the child's stdout/stderr with pipes: the child lowers
|
||||
// RLIMIT_FSIZE to 1 byte, which would otherwise make libtest's own
|
||||
// result write fail with EFBIG against an inherited regular log file.
|
||||
let output = Command::new(std::env::current_exe().unwrap())
|
||||
.args([
|
||||
"--exact",
|
||||
"real_process_write_limit_leaves_no_partial_final_blob",
|
||||
"--nocapture",
|
||||
])
|
||||
.env("CRANK_ARTIFACTS_CHILD_ROOT", &root.0)
|
||||
.status()
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(status.success());
|
||||
assert!(output.status.success(), "child status: {}", output.status);
|
||||
|
||||
let store = ArtifactStore::open(&root.0).unwrap();
|
||||
let expected =
|
||||
|
||||
@@ -27,6 +27,7 @@ mod source_safety;
|
||||
mod strict_decode;
|
||||
mod swagger2;
|
||||
mod swagger2_findings;
|
||||
mod uri;
|
||||
|
||||
pub use model::{
|
||||
ExternalDocumentSnapshot, HISTORICAL_NORMALIZER_VERSION, HISTORICAL_PROJECTION_VERSION,
|
||||
@@ -51,3 +52,4 @@ pub use payload::operation_draft_from_candidate;
|
||||
pub use source_safety::{
|
||||
validate_document_bundle_source_safe, validate_resolved_bundle_source_safe,
|
||||
};
|
||||
pub use uri::canonical_external_document_uri;
|
||||
@@ -9,7 +9,7 @@ use serde_json::Value;
|
||||
/// The immutable contract used to normalize an OpenAPI source. These names
|
||||
/// deliberately travel with an import job: changing either contract must not
|
||||
/// silently reinterpret a pending preview.
|
||||
pub const NORMALIZER_VERSION: &str = "normalized-ir-v5";
|
||||
pub const NORMALIZER_VERSION: &str = "normalized-ir-v6";
|
||||
pub const PROJECTION_VERSION: &str = "preview-v6";
|
||||
pub const HISTORICAL_NORMALIZER_VERSION: &str = "normalized-ir-v4";
|
||||
pub const HISTORICAL_PROJECTION_VERSION: &str = "preview-v4";
|
||||
|
||||
@@ -9,6 +9,7 @@ use crate::rest::model::{
|
||||
};
|
||||
|
||||
use super::reference_budget::{CopyBudget, count_branch_bytes, count_copy_bytes, merge_object};
|
||||
use super::uri::canonical_external_document_uri;
|
||||
use super::{ImportParseError, decode_budget, normalize_coverage::escape_pointer};
|
||||
|
||||
pub(super) struct ResolutionResult {
|
||||
@@ -467,14 +468,11 @@ impl Resolver<'_> {
|
||||
if document.is_empty() {
|
||||
return Ok(Some((current, pointer)));
|
||||
}
|
||||
let canonical = if has_uri_scheme(document) {
|
||||
canonical_absolute_uri(document)
|
||||
} else {
|
||||
let Some(base) = self.documents[current].uri.as_deref() else {
|
||||
return Ok(None);
|
||||
};
|
||||
join_relative(base, document)
|
||||
};
|
||||
// The document part is canonicalized exactly like the Admin URL
|
||||
// transport, so a supplied snapshot key matches its `$ref`. The shared
|
||||
// helper also rejects non-HTTP(S) schemes and userinfo targets.
|
||||
let canonical =
|
||||
canonical_external_document_uri(self.documents[current].uri.as_deref(), document);
|
||||
Ok(canonical.and_then(|canonical| {
|
||||
self.by_uri
|
||||
.get(&canonical)
|
||||
@@ -565,161 +563,6 @@ fn is_oas31(root: &Value) -> bool {
|
||||
.is_some_and(|version| version.starts_with("3.1."))
|
||||
}
|
||||
|
||||
fn join_relative(base: &str, relative: &str) -> Option<String> {
|
||||
let base = UriReference::parse(base)?;
|
||||
let relative = UriReference::parse(relative)?;
|
||||
let scheme = relative.scheme.or(base.scheme)?;
|
||||
let authority = if relative.scheme.is_some() || relative.authority.is_some() {
|
||||
relative.authority
|
||||
} else {
|
||||
base.authority
|
||||
};
|
||||
let (path, query) = if relative.scheme.is_some() || relative.authority.is_some() {
|
||||
(remove_dot_segments(&relative.path), relative.query)
|
||||
} else if relative.path.is_empty() {
|
||||
(base.path, relative.query.or(base.query))
|
||||
} else if relative.path.starts_with('/') {
|
||||
(remove_dot_segments(&relative.path), relative.query)
|
||||
} else {
|
||||
(
|
||||
remove_dot_segments(&merge_paths(
|
||||
&base.path,
|
||||
authority.is_some(),
|
||||
&relative.path,
|
||||
)),
|
||||
relative.query,
|
||||
)
|
||||
};
|
||||
UriReference {
|
||||
scheme: Some(scheme),
|
||||
authority,
|
||||
path,
|
||||
query,
|
||||
}
|
||||
.render()
|
||||
}
|
||||
|
||||
fn canonical_absolute_uri(uri: &str) -> Option<String> {
|
||||
let reference = UriReference::parse(uri)?;
|
||||
let scheme = reference.scheme?;
|
||||
UriReference {
|
||||
scheme: Some(scheme),
|
||||
authority: reference.authority,
|
||||
path: remove_dot_segments(&reference.path),
|
||||
query: reference.query,
|
||||
}
|
||||
.render()
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct UriReference<'a> {
|
||||
scheme: Option<&'a str>,
|
||||
authority: Option<&'a str>,
|
||||
path: String,
|
||||
query: Option<&'a str>,
|
||||
}
|
||||
|
||||
impl<'a> UriReference<'a> {
|
||||
fn parse(value: &'a str) -> Option<Self> {
|
||||
if value.contains('\\') || value.contains('#') {
|
||||
return None;
|
||||
}
|
||||
let (without_query, query) = value
|
||||
.split_once('?')
|
||||
.map_or((value, None), |(path, query)| (path, Some(query)));
|
||||
let (scheme, rest) = if let Some(index) = without_query.find(':') {
|
||||
let candidate = &without_query[..index];
|
||||
if is_uri_scheme(candidate) {
|
||||
(Some(candidate), &without_query[index + 1..])
|
||||
} else {
|
||||
(None, without_query)
|
||||
}
|
||||
} else {
|
||||
(None, without_query)
|
||||
};
|
||||
let (authority, path) = if let Some(rest) = rest.strip_prefix("//") {
|
||||
match rest.find('/') {
|
||||
Some(index) => (Some(&rest[..index]), rest[index..].to_owned()),
|
||||
None => (Some(rest), String::new()),
|
||||
}
|
||||
} else {
|
||||
(None, rest.to_owned())
|
||||
};
|
||||
Some(Self {
|
||||
scheme,
|
||||
authority,
|
||||
path,
|
||||
query,
|
||||
})
|
||||
}
|
||||
|
||||
fn render(&self) -> Option<String> {
|
||||
let scheme = self.scheme?;
|
||||
let scheme = scheme.to_ascii_lowercase();
|
||||
let mut value = format!("{scheme}:");
|
||||
if let Some(authority) = self.authority {
|
||||
value.push_str("//");
|
||||
value.push_str(&canonical_authority(authority, &scheme));
|
||||
}
|
||||
if self.authority.is_some() && self.path.is_empty() {
|
||||
value.push('/');
|
||||
} else {
|
||||
value.push_str(&self.path);
|
||||
}
|
||||
if let Some(query) = self.query {
|
||||
value.push('?');
|
||||
value.push_str(query);
|
||||
}
|
||||
Some(value)
|
||||
}
|
||||
}
|
||||
|
||||
fn canonical_authority(authority: &str, scheme: &str) -> String {
|
||||
let authority = authority.to_ascii_lowercase();
|
||||
let default_port = match scheme {
|
||||
"http" => Some("80"),
|
||||
"https" => Some("443"),
|
||||
_ => None,
|
||||
};
|
||||
let authority = if let Some(default_port) = default_port
|
||||
&& let Some((host, port)) = authority.rsplit_once(':')
|
||||
&& port == default_port
|
||||
&& (!host.contains(':') || host.ends_with(']'))
|
||||
{
|
||||
host.to_owned()
|
||||
} else {
|
||||
authority
|
||||
};
|
||||
punycode_authority(authority, scheme)
|
||||
}
|
||||
|
||||
/// Applies the same IDNA/punycode host identity that the external-snapshot
|
||||
/// materializer gets from `url::Url`, so a Unicode `$ref` and the stored
|
||||
/// punycode `canonical_uri` resolve to the same snapshot. ASCII-only
|
||||
/// authorities (including IPv6 literals) and authorities with userinfo keep the
|
||||
/// previous ASCII-lowercase rendering, preserving RFC 3986 behavior.
|
||||
fn punycode_authority(authority: String, scheme: &str) -> String {
|
||||
if authority.is_ascii() || !matches!(scheme, "http" | "https") || authority.contains('@') {
|
||||
return authority;
|
||||
}
|
||||
let Ok(parsed) = url::Url::parse(&format!("{scheme}://{authority}")) else {
|
||||
return authority;
|
||||
};
|
||||
let Some(host) = parsed.host_str() else {
|
||||
return authority;
|
||||
};
|
||||
match parsed.port() {
|
||||
Some(port) => format!("{host}:{port}"),
|
||||
None => host.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
fn has_uri_scheme(value: &str) -> bool {
|
||||
value
|
||||
.split_once(':')
|
||||
.is_some_and(|(candidate, _)| is_uri_scheme(candidate))
|
||||
}
|
||||
|
||||
/// URI schemes are case-insensitive (RFC 3986 §3.1), so the failed-target
|
||||
/// classification must not depend on the literal case of `http`/`https`.
|
||||
fn is_external_http_scheme(reference: &str) -> bool {
|
||||
@@ -728,47 +571,6 @@ fn is_external_http_scheme(reference: &str) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
fn is_uri_scheme(candidate: &str) -> bool {
|
||||
let Some(first) = candidate.as_bytes().first() else {
|
||||
return false;
|
||||
};
|
||||
first.is_ascii_alphabetic()
|
||||
&& candidate
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'-' | b'.'))
|
||||
}
|
||||
|
||||
fn merge_paths(base_path: &str, has_authority: bool, relative_path: &str) -> String {
|
||||
match base_path.rfind('/') {
|
||||
Some(index) => format!("{}{}", &base_path[..=index], relative_path),
|
||||
None if has_authority => format!("/{relative_path}"),
|
||||
None => relative_path.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_dot_segments(path: &str) -> String {
|
||||
let leading_slash = path.starts_with('/');
|
||||
let trailing_slash = path.ends_with('/');
|
||||
let mut output = Vec::new();
|
||||
for segment in path.split('/') {
|
||||
match segment {
|
||||
"." => {}
|
||||
".." => {
|
||||
output.pop();
|
||||
}
|
||||
_ => output.push(segment),
|
||||
}
|
||||
}
|
||||
let mut result = output.join("/");
|
||||
if leading_slash && !result.starts_with('/') {
|
||||
result.insert(0, '/');
|
||||
}
|
||||
if trailing_slash && !result.ends_with('/') {
|
||||
result.push('/');
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
enum TargetError {
|
||||
MalformedFragment,
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
//! Shared, pure canonical identity for external HTTP(S) document references.
|
||||
//!
|
||||
//! The Admin external-snapshot materializer keys every fetched dependency by the
|
||||
//! URL transport canonical form (`url::Url`, i.e. the WHATWG URL standard).
|
||||
//! The pure reference resolver must derive the exact same key, otherwise a
|
||||
//! supplied snapshot never matches and the reference becomes a false
|
||||
//! `external_reference_unavailable`. Both callers delegate here so the identity
|
||||
//! rule (IDNA punycode host, default-port removal, percent-encoded dot
|
||||
//! segments, WHATWG special-query encoding) lives in one place and stays
|
||||
//! I/O-free.
|
||||
//!
|
||||
//! Semantics deliberately follow `url::Url` rather than a hand-rolled RFC 3986
|
||||
//! renderer: the transport already stores the `url::Url` string, so any other
|
||||
//! renderer would reintroduce the divergent keys this helper removes.
|
||||
|
||||
use url::Url;
|
||||
|
||||
/// Canonical absolute form of an HTTP(S) URI reference.
|
||||
///
|
||||
/// `base` is the already-canonical URI of the document that contains the
|
||||
/// reference; pass `None` for an absolute reference or for the primary document.
|
||||
/// The fragment is always dropped because it addresses a JSON Pointer inside the
|
||||
/// fetched document, not a network resource. Returns `None` when the result is
|
||||
/// not an absolute `http`/`https` URL or when it carries userinfo credentials,
|
||||
/// so a caller can never derive an identity for a disallowed target.
|
||||
pub fn canonical_external_document_uri(base: Option<&str>, reference: &str) -> Option<String> {
|
||||
if reference.starts_with('#') {
|
||||
return None;
|
||||
}
|
||||
let mut url = match base {
|
||||
Some(base) => Url::parse(base).ok()?.join(reference).ok()?,
|
||||
None => Url::parse(reference).ok()?,
|
||||
};
|
||||
if !matches!(url.scheme(), "http" | "https")
|
||||
|| !url.username().is_empty()
|
||||
|| url.password().is_some()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
url.set_fragment(None);
|
||||
Some(url.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::canonical_external_document_uri;
|
||||
|
||||
#[test]
|
||||
fn collapses_percent_encoded_dot_segments_like_the_transport() {
|
||||
assert_eq!(
|
||||
canonical_external_document_uri(
|
||||
None,
|
||||
"https://schemas.example.test/a/%2e%2e/root.yaml#/Item"
|
||||
)
|
||||
.as_deref(),
|
||||
Some("https://schemas.example.test/root.yaml")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn applies_the_special_query_percent_encode_set_like_the_transport() {
|
||||
assert_eq!(
|
||||
canonical_external_document_uri(
|
||||
None,
|
||||
"https://schemas.example.test/schema.json?filter='x'#/Item"
|
||||
)
|
||||
.as_deref(),
|
||||
Some("https://schemas.example.test/schema.json?filter=%27x%27")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joins_relative_references_against_a_canonical_base() {
|
||||
assert_eq!(
|
||||
canonical_external_document_uri(
|
||||
Some("https://schemas.example.test/root.yaml"),
|
||||
"./child.yaml#/Item"
|
||||
)
|
||||
.as_deref(),
|
||||
Some("https://schemas.example.test/child.yaml")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_local_non_http_and_userinfo_references() {
|
||||
assert_eq!(canonical_external_document_uri(None, "#/Item"), None);
|
||||
assert_eq!(
|
||||
canonical_external_document_uri(None, "urn:example:item"),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
canonical_external_document_uri(None, "https://user:pass@host/schema.json"),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,9 @@ use std::{
|
||||
#[path = "corpus/matrix.rs"]
|
||||
mod matrix;
|
||||
|
||||
#[path = "corpus/reference_uri.rs"]
|
||||
mod reference_uri;
|
||||
|
||||
fn tests_root() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests")
|
||||
}
|
||||
@@ -117,8 +120,8 @@ fn normalize(source: &str) -> Result<crank_import::rest::NormalizedIr, ImportPar
|
||||
#[test]
|
||||
fn ac_2_manifest_covers_fifty_provenanced_specs_with_exact_expectations() {
|
||||
let manifest = manifest();
|
||||
assert_eq!(manifest.corpus_version, "1.0.4");
|
||||
assert_eq!(manifest.matrix_version, "1.0.3");
|
||||
assert_eq!(manifest.corpus_version, "1.0.5");
|
||||
assert_eq!(manifest.matrix_version, "1.0.4");
|
||||
assert!(!manifest.compatibility_impact.trim().is_empty());
|
||||
assert!(manifest.documents.len() >= 50);
|
||||
let root = tests_root().join("corpus");
|
||||
@@ -687,6 +690,21 @@ fn ac_2_manifest_covers_fifty_provenanced_specs_with_exact_expectations() {
|
||||
document.file
|
||||
);
|
||||
}
|
||||
"regression-uri-encoded-dot.yaml" | "regression-uri-query-quote.yaml" => {
|
||||
// Default-deny characterization: without a supplied
|
||||
// snapshot the external `$ref` stays blocked at its
|
||||
// source. The positive snapshot oracle lives in
|
||||
// `corpus/reference_uri.rs`.
|
||||
assert!(
|
||||
ir.findings
|
||||
.iter()
|
||||
.chain(ir.operations.iter().flat_map(|operation| &operation.findings))
|
||||
.any(|finding| finding.code == "external_reference_disabled"),
|
||||
"{} must default-deny its external $ref: {:?}",
|
||||
document.file,
|
||||
ir.findings
|
||||
);
|
||||
}
|
||||
_ => unreachable!("hostile fixture must have a dedicated expectation"),
|
||||
}
|
||||
}
|
||||
@@ -713,6 +731,7 @@ fn ac_2_manifest_covers_fifty_provenanced_specs_with_exact_expectations() {
|
||||
.into_iter()
|
||||
.chain(std::iter::once("manifest.json".to_owned()))
|
||||
.chain(std::iter::once("matrix.rs".to_owned()))
|
||||
.chain(std::iter::once("reference_uri.rs".to_owned()))
|
||||
.collect::<std::collections::BTreeSet<_>>();
|
||||
let actual_files = fs::read_dir(&root)
|
||||
.expect("corpus directory exists")
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"corpus_version": "1.0.4",
|
||||
"matrix_version": "1.0.3",
|
||||
"corpus_version": "1.0.5",
|
||||
"matrix_version": "1.0.4",
|
||||
"digest_algorithm": "sha256",
|
||||
"canonical_digest_definition": "SHA-256 of compact JSON with lexicographically ordered keys; null for malformed JSON",
|
||||
"documents": [
|
||||
@@ -14407,7 +14407,29 @@
|
||||
"warning_findings": [],
|
||||
"blocker_findings": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "hostile-13",
|
||||
"file": "regression-uri-encoded-dot.yaml",
|
||||
"sha256": "9c3f73debd2f51449904c6691939e3bb3f8958f9562eac8b105cdf23a92cbc2d",
|
||||
"canonical_digest": null,
|
||||
"origin": "synthetic: Epic 2 external URI transport regression",
|
||||
"license": "CC0-1.0 synthetic; no third-party content",
|
||||
"specification_version": "OpenAPI 3.1",
|
||||
"classification": "hostile",
|
||||
"expected_preview": {}
|
||||
},
|
||||
{
|
||||
"id": "hostile-14",
|
||||
"file": "regression-uri-query-quote.yaml",
|
||||
"sha256": "b1c879285d4f5bfa64004fcc0dced1e115a1423d8a4c3a4c9a0699894e776c8f",
|
||||
"canonical_digest": null,
|
||||
"origin": "synthetic: Epic 2 external URI transport regression",
|
||||
"license": "CC0-1.0 synthetic; no third-party content",
|
||||
"specification_version": "OpenAPI 3.1",
|
||||
"classification": "hostile",
|
||||
"expected_preview": {}
|
||||
}
|
||||
],
|
||||
"compatibility_impact": "Corpus 1.0.4 is a metadata-only SemVer increment aligning its manifest with support matrix 1.0.3; fixture contents and checksums are unchanged. Corpus 1.0.3 added hostile-security-scope.json: a document-level basic requirement remains selectable on the inherited candidate while an explicit security: [] override stays public; malformed or unsupported requirements retain scoped blockers. Support matrix 1.0.3 adds executable blockers for undeclared path placeholders and object/array schema defaults across OpenAPI 3.0, OpenAPI 3.1, and Swagger 2.0 while preserving scalar defaults and previously supported behavior."
|
||||
"compatibility_impact": "Corpus 1.0.5 adds two hostile external-URI regression fixtures (regression-uri-encoded-dot.yaml, regression-uri-query-quote.yaml) and the reference_uri.rs positive-snapshot oracle: an encoded-dot path segment and an apostrophe query now canonicalize to the URL transport identity, so a supplied snapshot resolves while the default-deny pass and all statuses/denominators are unchanged. Support matrix 1.0.4 records the shared external HTTP(S) URI canonicalization contract without changing any construct status. Corpus 1.0.4 was a metadata-only SemVer increment aligning its manifest with support matrix 1.0.3; fixture contents and checksums were unchanged."
|
||||
}
|
||||
@@ -31,7 +31,7 @@ fn ac_1_support_matrix_rows_have_exact_construct_contracts() {
|
||||
let matrix_text = fs::read_to_string(tests_root().join("support-matrix.yaml"))
|
||||
.expect("support matrix exists");
|
||||
let matrix: serde_yaml::Value = serde_yaml::from_str(&matrix_text).expect("valid YAML");
|
||||
assert_eq!(matrix["matrix_version"].as_str(), Some("1.0.3"));
|
||||
assert_eq!(matrix["matrix_version"].as_str(), Some("1.0.4"));
|
||||
assert!(
|
||||
matrix["compatibility_impact"]
|
||||
.as_str()
|
||||
@@ -696,73 +696,100 @@ fn ac_1_support_matrix_rows_have_exact_construct_contracts() {
|
||||
row["specification_version"] == version && row["construct_id"] == construct
|
||||
})
|
||||
.unwrap();
|
||||
let reference = if external {
|
||||
"https://schemas.example.test/root.yaml#/Item"
|
||||
} else if version == "Swagger 2.0" {
|
||||
// The allowlisted-external row must exercise the same transport
|
||||
// canonicalization the materializer keys snapshots with. The
|
||||
// expected keys below are static literals, independent of the
|
||||
// production `canonical_external_document_uri` helper: a
|
||||
// percent-encoded dot segment collapses to its parent path and an
|
||||
// apostrophe in the query is percent-encoded (`%27`).
|
||||
let external_document = "Item: { type: object, properties: { id: { type: string } } }";
|
||||
let external_variants: [(&str, &str); 3] = [
|
||||
(
|
||||
"https://schemas.example.test/root.yaml#/Item",
|
||||
"https://schemas.example.test/root.yaml",
|
||||
),
|
||||
(
|
||||
"https://schemas.example.test/a/%2e%2e/root.yaml#/Item",
|
||||
"https://schemas.example.test/root.yaml",
|
||||
),
|
||||
(
|
||||
"https://schemas.example.test/schema.json?filter='x'#/Item",
|
||||
"https://schemas.example.test/schema.json?filter=%27x%27",
|
||||
),
|
||||
];
|
||||
let local_reference = if version == "Swagger 2.0" {
|
||||
"#/definitions/Item"
|
||||
} else {
|
||||
"#/components/schemas/Item"
|
||||
};
|
||||
let schema = json!({"$ref":reference});
|
||||
let response = if version == "Swagger 2.0" {
|
||||
json!({"description":"ok","schema":schema})
|
||||
let variants = if external {
|
||||
external_variants
|
||||
.iter()
|
||||
.map(|(reference, canonical_uri)| (*reference, Some(*canonical_uri)))
|
||||
.collect::<Vec<_>>()
|
||||
} else {
|
||||
json!({"description":"ok","content":{"application/json":{"schema":schema}}})
|
||||
vec![(local_reference, None)]
|
||||
};
|
||||
let probe = if version == "Swagger 2.0" {
|
||||
let mut root = json!({"swagger":"2.0","info":{"title":"Reference probe","version":"1"},"paths":{"/probe":{"get":{"operationId":"referenceProbe","responses":{"200":response}}}}});
|
||||
if !external {
|
||||
root["definitions"] =
|
||||
json!({"Item":{"type":"object","properties":{"id":{"type":"string"}}}});
|
||||
}
|
||||
root
|
||||
} else {
|
||||
let mut root = json!({"openapi":if version == "OpenAPI 3.0" {"3.0.3"} else {"3.1.0"},
|
||||
"info":{"title":"Reference probe","version":"1"},"servers":[{"url":"https://matrix.example.test"}],"paths":{"/probe":{"get":{"operationId":"referenceProbe","responses":{"200":response}}}}});
|
||||
if !external {
|
||||
root["components"] = json!({"schemas":{"Item":{"type":"object","properties":{"id":{"type":"string"}}}}});
|
||||
}
|
||||
root
|
||||
};
|
||||
let source = serde_json::to_string(&probe).unwrap();
|
||||
let ir = if external {
|
||||
let external_source =
|
||||
"Item: { type: object, properties: { id: { type: string } } }";
|
||||
let snapshot = crank_import::rest::ExternalDocumentSnapshot {
|
||||
canonical_uri: "https://schemas.example.test/root.yaml".to_owned(),
|
||||
digest: SourceDigest::parse(hex(external_source.as_bytes())).unwrap(),
|
||||
document: external_source.to_owned(),
|
||||
for (reference, canonical_uri) in variants {
|
||||
let schema = json!({"$ref":reference});
|
||||
let response = if version == "Swagger 2.0" {
|
||||
json!({"description":"ok","schema":schema})
|
||||
} else {
|
||||
json!({"description":"ok","content":{"application/json":{"schema":schema}}})
|
||||
};
|
||||
let digest = SourceDigest::parse(hex(source.as_bytes())).unwrap();
|
||||
normalize_verified_bundle(
|
||||
&source,
|
||||
digest,
|
||||
&[snapshot],
|
||||
&NormalizationConfig::default(),
|
||||
)
|
||||
.unwrap()
|
||||
} else {
|
||||
normalize(&source).unwrap()
|
||||
};
|
||||
validate_normalized_ir(&ir).unwrap();
|
||||
assert_eq!(row["status"], "supported");
|
||||
assert!(
|
||||
!ir.reference_graph.edges.is_empty(),
|
||||
"{version} {construct} did not resolve through a source-backed edge"
|
||||
);
|
||||
assert!(
|
||||
ir.unresolved_references.is_empty(),
|
||||
"{version} {construct} remains unresolved"
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
ir.operations[0].response_variants[0].schema.as_ref().map(|schema| &schema.kind),
|
||||
Some(NormalizedSchemaKind::Object { properties, .. }) if properties.contains_key("id")
|
||||
),
|
||||
"{version} {construct} resolved schema was not projected into the operation"
|
||||
);
|
||||
assert_actionable(&ir, &format!("{version} {construct}"));
|
||||
assert_eq!(row["expected_finding"], "none");
|
||||
let probe = if version == "Swagger 2.0" {
|
||||
let mut root = json!({"swagger":"2.0","info":{"title":"Reference probe","version":"1"},"paths":{"/probe":{"get":{"operationId":"referenceProbe","responses":{"200":response}}}}});
|
||||
if !external {
|
||||
root["definitions"] =
|
||||
json!({"Item":{"type":"object","properties":{"id":{"type":"string"}}}});
|
||||
}
|
||||
root
|
||||
} else {
|
||||
let mut root = json!({"openapi":if version == "OpenAPI 3.0" {"3.0.3"} else {"3.1.0"},
|
||||
"info":{"title":"Reference probe","version":"1"},"servers":[{"url":"https://matrix.example.test"}],"paths":{"/probe":{"get":{"operationId":"referenceProbe","responses":{"200":response}}}}});
|
||||
if !external {
|
||||
root["components"] = json!({"schemas":{"Item":{"type":"object","properties":{"id":{"type":"string"}}}}});
|
||||
}
|
||||
root
|
||||
};
|
||||
let source = serde_json::to_string(&probe).unwrap();
|
||||
let ir = if let Some(canonical_uri) = canonical_uri {
|
||||
let snapshot = crank_import::rest::ExternalDocumentSnapshot {
|
||||
canonical_uri: canonical_uri.to_owned(),
|
||||
digest: SourceDigest::parse(hex(external_document.as_bytes())).unwrap(),
|
||||
document: external_document.to_owned(),
|
||||
};
|
||||
let digest = SourceDigest::parse(hex(source.as_bytes())).unwrap();
|
||||
normalize_verified_bundle(
|
||||
&source,
|
||||
digest,
|
||||
&[snapshot],
|
||||
&NormalizationConfig::default(),
|
||||
)
|
||||
.unwrap()
|
||||
} else {
|
||||
normalize(&source).unwrap()
|
||||
};
|
||||
validate_normalized_ir(&ir).unwrap();
|
||||
assert_eq!(row["status"], "supported");
|
||||
assert!(
|
||||
!ir.reference_graph.edges.is_empty(),
|
||||
"{version} {construct} did not resolve through a source-backed edge ({reference})"
|
||||
);
|
||||
assert!(
|
||||
ir.unresolved_references.is_empty(),
|
||||
"{version} {construct} remains unresolved ({reference})"
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
ir.operations[0].response_variants[0].schema.as_ref().map(|schema| &schema.kind),
|
||||
Some(NormalizedSchemaKind::Object { properties, .. }) if properties.contains_key("id")
|
||||
),
|
||||
"{version} {construct} resolved schema was not projected into the operation ({reference})"
|
||||
);
|
||||
assert_actionable(&ir, &format!("{version} {construct} {reference}"));
|
||||
assert_eq!(row["expected_finding"], "none");
|
||||
}
|
||||
probed(construct);
|
||||
}
|
||||
for code in 200..300 {
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
//! Positive and default-deny oracle for external HTTP(S) URI transport parity.
|
||||
//!
|
||||
//! These two regression fixtures pin the F1 defect: an encoded-dot path segment
|
||||
//! (`%2e%2e`) and an apostrophe query (`'`). Under the default configuration the
|
||||
//! external `$ref` must stay default-denied (the document-level pass
|
||||
//! `corpus.rs` characterizes); once a snapshot keyed by the URL transport
|
||||
//! canonical form is supplied, the reference must resolve. Keeping the positive
|
||||
//! snapshot oracle here, separate from the default-deny pass, means neither can
|
||||
//! mask the other, and both run the real pure resolver.
|
||||
|
||||
use super::*;
|
||||
use crank_import::rest::{
|
||||
ExternalDocumentSnapshot, NormalizedSchemaKind, SourceDigest, normalize_verified_bundle,
|
||||
};
|
||||
|
||||
struct Case {
|
||||
file: &'static str,
|
||||
/// The raw `$ref` exactly as it appears in the fixture.
|
||||
reference: &'static str,
|
||||
/// The `url::Url` transport canonical form the materializer would store.
|
||||
canonical_uri: &'static str,
|
||||
}
|
||||
|
||||
const CASES: &[Case] = &[
|
||||
Case {
|
||||
file: "regression-uri-encoded-dot.yaml",
|
||||
reference: "https://schemas.example.test/a/%2e%2e/root.yaml#/Item",
|
||||
canonical_uri: "https://schemas.example.test/root.yaml",
|
||||
},
|
||||
Case {
|
||||
file: "regression-uri-query-quote.yaml",
|
||||
reference: "https://schemas.example.test/schema.json?filter='x'#/Item",
|
||||
canonical_uri: "https://schemas.example.test/schema.json?filter=%27x%27",
|
||||
},
|
||||
];
|
||||
|
||||
fn fixture(file: &str) -> String {
|
||||
fs::read_to_string(tests_root().join("corpus").join(file))
|
||||
.unwrap_or_else(|error| panic!("{file}: {error}"))
|
||||
}
|
||||
|
||||
fn digest(byte: char) -> SourceDigest {
|
||||
SourceDigest::parse(byte.to_string().repeat(64)).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_deny_pass_keeps_each_external_uri_blocked_without_snapshots() {
|
||||
for case in CASES {
|
||||
let source = fixture(case.file);
|
||||
assert!(
|
||||
source.contains(case.reference),
|
||||
"{} fixture lost its raw $ref",
|
||||
case.file
|
||||
);
|
||||
let ir = normalize(&source).unwrap_or_else(|error| panic!("{}: {error}", case.file));
|
||||
validate_normalized_ir(&ir).unwrap();
|
||||
assert!(
|
||||
ir.findings
|
||||
.iter()
|
||||
.chain(
|
||||
ir.operations
|
||||
.iter()
|
||||
.flat_map(|operation| &operation.findings)
|
||||
)
|
||||
.any(|finding| finding.code == "external_reference_disabled"),
|
||||
"{} must default-deny its external $ref without a snapshot",
|
||||
case.file
|
||||
);
|
||||
assert!(
|
||||
ir.reference_graph.edges.is_empty(),
|
||||
"{} must not resolve without a supplied snapshot",
|
||||
case.file
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn positive_snapshot_oracle_resolves_each_transport_canonical_uri() {
|
||||
let snapshot_document =
|
||||
"Item: { type: object, required: [id], properties: { id: { type: string } } }";
|
||||
for case in CASES {
|
||||
let source = fixture(case.file);
|
||||
let snapshots = vec![ExternalDocumentSnapshot {
|
||||
canonical_uri: case.canonical_uri.to_owned(),
|
||||
digest: digest('b'),
|
||||
document: snapshot_document.to_owned(),
|
||||
}];
|
||||
let config = NormalizationConfig {
|
||||
external_references_enabled: true,
|
||||
..NormalizationConfig::default()
|
||||
};
|
||||
let ir = normalize_verified_bundle(&source, digest('a'), &snapshots, &config)
|
||||
.unwrap_or_else(|error| panic!("{}: {error}", case.file));
|
||||
assert!(
|
||||
!ir.operations[0]
|
||||
.findings
|
||||
.iter()
|
||||
.any(|finding| finding.code == "external_reference_unavailable"),
|
||||
"{} resolved against the transport key but still reported unavailable: {:?}",
|
||||
case.file,
|
||||
ir.operations[0].findings
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
ir.operations[0]
|
||||
.response_schema
|
||||
.as_ref()
|
||||
.map(|schema| &schema.kind),
|
||||
Some(NormalizedSchemaKind::Object { properties, .. })
|
||||
if properties.contains_key("id")
|
||||
),
|
||||
"{} resolved schema must keep its `id` property",
|
||||
case.file
|
||||
);
|
||||
assert_eq!(ir.reference_graph.edges.len(), 1, "{}", case.file);
|
||||
assert_eq!(
|
||||
ir.reference_graph.edges[0].target.snapshot_digest,
|
||||
digest('b')
|
||||
);
|
||||
assert_eq!(ir.reference_graph.dependency_digests, vec![digest('b')]);
|
||||
assert!(ir.unresolved_references.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
openapi: 3.1.0
|
||||
info: { title: External URI encoded-dot regression, version: '1' }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
paths:
|
||||
/items:
|
||||
get:
|
||||
operationId: encodedDot
|
||||
responses:
|
||||
'200':
|
||||
description: ok
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: 'https://schemas.example.test/a/%2e%2e/root.yaml#/Item' }
|
||||
@@ -0,0 +1,13 @@
|
||||
openapi: 3.1.0
|
||||
info: { title: External URI query-quote regression, version: '1' }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
paths:
|
||||
/items:
|
||||
get:
|
||||
operationId: quotedQuery
|
||||
responses:
|
||||
'200':
|
||||
description: ok
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "https://schemas.example.test/schema.json?filter='x'#/Item" }
|
||||
@@ -4,6 +4,12 @@ use crank_import::rest::{
|
||||
normalize_verified_document, preview_from_ir, reference_uris,
|
||||
};
|
||||
|
||||
// `reference_resolution.rs` is an integration-test crate root, so a nested
|
||||
// module must point at the file explicitly to keep the path
|
||||
// `tests/reference_resolution/uri_transport.rs` (relative to this file's dir).
|
||||
#[path = "reference_resolution/uri_transport.rs"]
|
||||
mod uri_transport;
|
||||
|
||||
fn digest(byte: char) -> SourceDigest {
|
||||
SourceDigest::parse(byte.to_string().repeat(64)).unwrap()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
//! F1 transport-parity cases for the pure resolver.
|
||||
//!
|
||||
//! Each case supplies a snapshot keyed exactly as the Admin URL transport
|
||||
//! (`url::Url`) keys it, then drives `normalize_verified_bundle`. The cases are
|
||||
//! registered from `reference_resolution.rs` so the parent file stays within the
|
||||
//! repository file-size budget; the shared helpers (`digest`, `normalize_*`,
|
||||
//! and the `rest` imports) come from `super` through `use super::*`.
|
||||
|
||||
use super::*;
|
||||
|
||||
// F1 (a): the external materializer derives its snapshot key from the URL
|
||||
// transport (`url::Url`), which collapses a percent-encoded dot segment
|
||||
// (`%2e%2e`) into the parent path. The pure resolver must derive the same
|
||||
// canonical key, otherwise a supplied snapshot becomes a false
|
||||
// `external_reference_unavailable` blocker. RED before the shared URI helper.
|
||||
#[test]
|
||||
fn encoded_dot_path_reference_matches_transport_canonical_snapshot() {
|
||||
let document = r#"
|
||||
openapi: 3.1.0
|
||||
info: { title: Encoded dot transport parity }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
paths:
|
||||
/items:
|
||||
get:
|
||||
operationId: listItems
|
||||
responses:
|
||||
'200':
|
||||
description: ok
|
||||
content: { application/json: { schema: { $ref: 'https://schemas.example.test/a/%2e%2e/root.yaml#/Item' } } }
|
||||
"#;
|
||||
let snapshots = vec![ExternalDocumentSnapshot {
|
||||
// Transport (`url::Url`) canonical form of the same reference.
|
||||
canonical_uri: "https://schemas.example.test/root.yaml".to_owned(),
|
||||
digest: digest('b'),
|
||||
document: "Item: { type: object, required: [id], properties: { id: { type: string } } }"
|
||||
.to_owned(),
|
||||
}];
|
||||
let config = NormalizationConfig {
|
||||
external_references_enabled: true,
|
||||
..NormalizationConfig::default()
|
||||
};
|
||||
let ir = normalize_verified_bundle(document, digest('a'), &snapshots, &config).unwrap();
|
||||
|
||||
assert!(
|
||||
!ir.operations[0]
|
||||
.findings
|
||||
.iter()
|
||||
.any(|finding| finding.code == "external_reference_unavailable"),
|
||||
"encoded-dot $ref must match its transport-canonical snapshot, got: {:?}",
|
||||
ir.operations[0].findings
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
ir.operations[0]
|
||||
.response_schema
|
||||
.as_ref()
|
||||
.map(|schema| &schema.kind),
|
||||
Some(NormalizedSchemaKind::Object { properties, .. }) if properties.contains_key("id")
|
||||
),
|
||||
"resolved schema must preserve its `id` property"
|
||||
);
|
||||
assert_eq!(ir.reference_graph.edges.len(), 1);
|
||||
assert_eq!(
|
||||
ir.reference_graph.edges[0].target.snapshot_digest,
|
||||
digest('b')
|
||||
);
|
||||
assert!(ir.unresolved_references.is_empty());
|
||||
}
|
||||
|
||||
// F1 (b): the URL transport percent-encodes an apostrophe inside a query string
|
||||
// (`'` -> `%27`, the WHATWG special-query percent-encode set for http/https).
|
||||
// The resolver must canonicalize the query the same way or the stored snapshot
|
||||
// key never matches. RED before the shared URI helper.
|
||||
//
|
||||
// The `$ref` sits in a YAML double-quoted scalar: the reference itself contains
|
||||
// an apostrophe, so a single-quoted scalar would terminate early and turn this
|
||||
// into a parser syntax failure instead of the intended resolution RED.
|
||||
#[test]
|
||||
fn quoted_query_reference_matches_transport_canonical_snapshot() {
|
||||
let document = r##"
|
||||
openapi: 3.1.0
|
||||
info: { title: Quoted query transport parity }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
paths:
|
||||
/items:
|
||||
get:
|
||||
operationId: listItems
|
||||
responses:
|
||||
'200':
|
||||
description: ok
|
||||
content: { application/json: { schema: { $ref: "https://schemas.example.test/schema.json?filter='x'#/Item" } } }
|
||||
"##;
|
||||
let snapshots = vec![ExternalDocumentSnapshot {
|
||||
// Transport (`url::Url`) canonical form of the apostrophe query.
|
||||
canonical_uri: "https://schemas.example.test/schema.json?filter=%27x%27".to_owned(),
|
||||
digest: digest('b'),
|
||||
document: "Item: { type: object, required: [id], properties: { id: { type: string } } }"
|
||||
.to_owned(),
|
||||
}];
|
||||
let config = NormalizationConfig {
|
||||
external_references_enabled: true,
|
||||
..NormalizationConfig::default()
|
||||
};
|
||||
let ir = normalize_verified_bundle(document, digest('a'), &snapshots, &config).unwrap();
|
||||
|
||||
assert!(
|
||||
!ir.operations[0]
|
||||
.findings
|
||||
.iter()
|
||||
.any(|finding| finding.code == "external_reference_unavailable"),
|
||||
"quoted-query $ref must match its transport-canonical snapshot, got: {:?}",
|
||||
ir.operations[0].findings
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
ir.operations[0]
|
||||
.response_schema
|
||||
.as_ref()
|
||||
.map(|schema| &schema.kind),
|
||||
Some(NormalizedSchemaKind::Object { properties, .. }) if properties.contains_key("id")
|
||||
),
|
||||
"resolved schema must preserve its `id` property"
|
||||
);
|
||||
assert_eq!(ir.reference_graph.edges.len(), 1);
|
||||
assert_eq!(
|
||||
ir.reference_graph.edges[0].target.snapshot_digest,
|
||||
digest('b')
|
||||
);
|
||||
assert!(ir.unresolved_references.is_empty());
|
||||
}
|
||||
|
||||
// AC-3: after the encoded-dot alias is canonicalized, a relative child must be
|
||||
// joined against the real canonical root, not the raw alias. RED while the
|
||||
// resolver still keys the alias literally.
|
||||
#[test]
|
||||
fn encoded_dot_root_alias_resolves_relative_child_against_canonical_root() {
|
||||
let document = r#"
|
||||
openapi: 3.1.0
|
||||
info: { title: Canonical root alias }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
paths:
|
||||
/items:
|
||||
get:
|
||||
operationId: listItems
|
||||
responses:
|
||||
'200':
|
||||
description: ok
|
||||
content: { application/json: { schema: { $ref: 'https://schemas.example.test/a/%2e%2e/root.yaml#/Item' } } }
|
||||
"#;
|
||||
let snapshots = vec![
|
||||
ExternalDocumentSnapshot {
|
||||
// Transport canonical of the encoded-dot root alias.
|
||||
canonical_uri: "https://schemas.example.test/root.yaml".to_owned(),
|
||||
digest: digest('b'),
|
||||
document: "Item: { $ref: './child.yaml#/Item' }".to_owned(),
|
||||
},
|
||||
ExternalDocumentSnapshot {
|
||||
canonical_uri: "https://schemas.example.test/child.yaml".to_owned(),
|
||||
digest: digest('c'),
|
||||
document:
|
||||
"Item: { type: object, required: [id], properties: { id: { type: string } } }"
|
||||
.to_owned(),
|
||||
},
|
||||
];
|
||||
let config = NormalizationConfig {
|
||||
external_references_enabled: true,
|
||||
..NormalizationConfig::default()
|
||||
};
|
||||
let ir = normalize_verified_bundle(document, digest('a'), &snapshots, &config).unwrap();
|
||||
|
||||
assert!(
|
||||
!ir.operations[0]
|
||||
.findings
|
||||
.iter()
|
||||
.any(|finding| finding.code == "external_reference_unavailable"),
|
||||
"encoded-dot root alias must resolve and join its child against the canonical root, got: {:?}",
|
||||
ir.operations[0].findings
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
ir.operations[0]
|
||||
.response_schema
|
||||
.as_ref()
|
||||
.map(|schema| &schema.kind),
|
||||
Some(NormalizedSchemaKind::Object { properties, .. }) if properties.contains_key("id")
|
||||
),
|
||||
"child schema must resolve through the canonical root"
|
||||
);
|
||||
assert_eq!(
|
||||
ir.reference_graph.dependency_digests,
|
||||
vec![digest('b'), digest('c')]
|
||||
);
|
||||
assert!(ir.unresolved_references.is_empty());
|
||||
}
|
||||
@@ -140,6 +140,51 @@ fn swagger2_projects_basic_and_api_key_header_and_query() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swagger2_cookie_api_key_is_explicitly_unsupported_at_operation_and_preview() {
|
||||
let document = json!({
|
||||
"swagger": "2.0",
|
||||
"info": { "title": "Unsupported Swagger cookie", "version": "1" },
|
||||
"host": "security.example.test",
|
||||
"schemes": ["https"],
|
||||
"securityDefinitions": {
|
||||
"CookieKey": { "type": "apiKey", "in": "cookie", "name": "session" }
|
||||
},
|
||||
"security": [{ "CookieKey": [] }],
|
||||
"paths": { "/private": { "get": {
|
||||
"responses": { "200": { "description": "ok" } }
|
||||
}}}
|
||||
});
|
||||
let ir = normalize(&document);
|
||||
let operation = operation(&ir, "/private");
|
||||
assert!(matches!(
|
||||
ir.security_schemes["CookieKey"].kind,
|
||||
NormalizedSecuritySchemeKind::Unsupported { .. }
|
||||
));
|
||||
assert!(!operation.security_requirements.alternatives[0].supported);
|
||||
assert!(
|
||||
operation
|
||||
.findings
|
||||
.iter()
|
||||
.any(|finding| finding.code == "unsupported_security_scheme")
|
||||
);
|
||||
assert!(
|
||||
operation
|
||||
.findings
|
||||
.iter()
|
||||
.any(|finding| finding.code == "unsupported_security_requirements")
|
||||
);
|
||||
let preview = candidates(&ir);
|
||||
let candidate = candidate(&preview, "GET /private");
|
||||
assert!(
|
||||
candidate
|
||||
.findings
|
||||
.iter()
|
||||
.any(|finding| finding.code == "unsupported_security_requirements")
|
||||
);
|
||||
assert!(candidate.draft.input_mapping.rules.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effective_requirements_inherit_override_and_allow_explicit_no_auth() {
|
||||
let document = json!({
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
matrix_version: 1.0.3
|
||||
compatibility_impact: "1.0.3 adds executable blockers for undeclared path placeholders and object/array schema defaults in OpenAPI 3.0, OpenAPI 3.1, and Swagger 2.0. The 1.0.2 effective-security inheritance/override behavior remains covered; scalar defaults and previously supported importer behavior remain unchanged."
|
||||
matrix_version: 1.0.4
|
||||
compatibility_impact: "1.0.4 records the shared external HTTP(S) URI canonicalization contract (percent-encoded dot segments, WHATWG special-query encoding, IDNA punycode host and default-port removal) now used by both the Admin snapshot materializer and the pure resolver; no construct status or previously supported behavior changes. The 1.0.3 executable blockers for undeclared path placeholders and object/array schema defaults across OpenAPI 3.0, OpenAPI 3.1, and Swagger 2.0 remain covered."
|
||||
constructs:
|
||||
- specification_version: "OpenAPI 3.0"
|
||||
construct_id: "http.method.get"
|
||||
|
||||
@@ -354,7 +354,11 @@ impl PostgresRegistry {
|
||||
let outcome = apply_import_plan_transaction(&mut transaction, request).await;
|
||||
match outcome {
|
||||
Ok((replayed, report)) => {
|
||||
#[cfg(debug_assertions)]
|
||||
crank_artifacts::test_support::crash_if_checkpointed("apply_before_commit");
|
||||
transaction.commit().await?;
|
||||
#[cfg(debug_assertions)]
|
||||
crank_artifacts::test_support::crash_if_checkpointed("apply_after_commit");
|
||||
Ok(ApplyImportPlanResult { replayed, report })
|
||||
}
|
||||
Err(ApplyTxFailure::KeyConflict) => {
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
use super::*;
|
||||
use sqlx::Row;
|
||||
use std::collections::HashMap;
|
||||
|
||||
mod exhaustive_v12;
|
||||
|
||||
#[tokio::test]
|
||||
async fn healthy_v11_upgrades_to_v13_without_rewriting_prior_ledger() {
|
||||
@@ -216,3 +220,523 @@ async fn v13_guard_rejects_wrong_cleanup_index_order_and_predicate() {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const V12_BLOB_COLUMNS: &[&str] = &[
|
||||
"digest",
|
||||
"artifact_ref",
|
||||
"size_bytes",
|
||||
"storage_lifecycle",
|
||||
"claim_token",
|
||||
"claim_expires_at",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
];
|
||||
const V12_SOURCE_COLUMNS: &[&str] = &[
|
||||
"workspace_id",
|
||||
"source_id",
|
||||
"blob_digest",
|
||||
"mime_type",
|
||||
"sensitivity",
|
||||
"lifecycle",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
"detached_at",
|
||||
];
|
||||
const V12_BLOB_DEFAULTS: &[(&str, Option<&str>)] = &[
|
||||
("digest", None),
|
||||
("artifact_ref", None),
|
||||
("size_bytes", None),
|
||||
("storage_lifecycle", Some("'available'::text")),
|
||||
("claim_token", None),
|
||||
("claim_expires_at", None),
|
||||
("created_at", None),
|
||||
("updated_at", None),
|
||||
];
|
||||
const V12_SOURCE_DEFAULTS: &[(&str, Option<&str>)] = &[
|
||||
("workspace_id", None),
|
||||
("source_id", None),
|
||||
("blob_digest", None),
|
||||
("mime_type", None),
|
||||
("sensitivity", None),
|
||||
("lifecycle", Some("'active'::text")),
|
||||
("created_at", None),
|
||||
("updated_at", None),
|
||||
("detached_at", None),
|
||||
];
|
||||
// PostgreSQL normalizes `set default null` into "no default", so each column
|
||||
// that legitimately has no default needs a concrete typed expression to prove
|
||||
// the guard rejects a newly introduced default.
|
||||
const V12_BLOB_NO_DEFAULT_DRIFT: &[(&str, &str)] = &[
|
||||
("digest", "'crank_drift'::text"),
|
||||
("artifact_ref", "'crank_drift'::text"),
|
||||
("size_bytes", "1"),
|
||||
("claim_token", "'crank_drift'::text"),
|
||||
("claim_expires_at", "'2000-01-01 00:00:00+00'::timestamptz"),
|
||||
("created_at", "'2000-01-01 00:00:00+00'::timestamptz"),
|
||||
("updated_at", "'2000-01-01 00:00:00+00'::timestamptz"),
|
||||
];
|
||||
const V12_SOURCE_NO_DEFAULT_DRIFT: &[(&str, &str)] = &[
|
||||
("workspace_id", "'crank_drift'::text"),
|
||||
("source_id", "'crank_drift'::text"),
|
||||
("blob_digest", "'crank_drift'::text"),
|
||||
("mime_type", "'crank_drift'::text"),
|
||||
("sensitivity", "'crank_drift'::text"),
|
||||
("created_at", "'2000-01-01 00:00:00+00'::timestamptz"),
|
||||
("updated_at", "'2000-01-01 00:00:00+00'::timestamptz"),
|
||||
("detached_at", "'2000-01-01 00:00:00+00'::timestamptz"),
|
||||
];
|
||||
const V12_BLOB_CONSTRAINTS: &[&str] = &[
|
||||
"artifact_blobs_artifact_ref_key",
|
||||
"artifact_blobs_claim_shape_check",
|
||||
"artifact_blobs_claim_token_check",
|
||||
"artifact_blobs_digest_check",
|
||||
"artifact_blobs_lifecycle_check",
|
||||
"artifact_blobs_pkey",
|
||||
"artifact_blobs_ref_check",
|
||||
"artifact_blobs_size_check",
|
||||
"artifact_blobs_timestamps_check",
|
||||
];
|
||||
const V12_SOURCE_CONSTRAINTS: &[&str] = &[
|
||||
"artifact_sources_blob_digest_fkey",
|
||||
"artifact_sources_id_check",
|
||||
"artifact_sources_lifecycle_check",
|
||||
"artifact_sources_mime_type_check",
|
||||
"artifact_sources_pkey",
|
||||
"artifact_sources_sensitivity_check",
|
||||
"artifact_sources_state_check",
|
||||
"artifact_sources_timestamps_check",
|
||||
"artifact_sources_workspace_id_fkey",
|
||||
];
|
||||
const V12_OWNED_RELATIONS: &[(&str, &str)] = &[
|
||||
("artifact_blobs", "r"),
|
||||
("artifact_blobs_artifact_ref_key", "i"),
|
||||
("artifact_blobs_expired_claim_idx", "i"),
|
||||
("artifact_blobs_pkey", "i"),
|
||||
("artifact_sources", "r"),
|
||||
("artifact_sources_blob_lifecycle_detached_idx", "i"),
|
||||
("artifact_sources_openapi_dangling_idx", "i"),
|
||||
("artifact_sources_pkey", "i"),
|
||||
("artifact_sources_workspace_created_idx", "i"),
|
||||
];
|
||||
|
||||
fn owned_names(values: &[&str]) -> Vec<String> {
|
||||
values.iter().map(|value| (*value).to_owned()).collect()
|
||||
}
|
||||
|
||||
fn owned_defaults(values: &[(&str, Option<&str>)]) -> Vec<(String, Option<String>)> {
|
||||
values
|
||||
.iter()
|
||||
.map(|(name, default)| ((*name).to_owned(), default.map(str::to_owned)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn catalog_columns(pool: &sqlx::PgPool, table: &str) -> Vec<String> {
|
||||
sqlx::query(
|
||||
"select column_name
|
||||
from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = $1
|
||||
order by ordinal_position",
|
||||
)
|
||||
.bind(table)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|row| row.get::<String, _>("column_name"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn catalog_column_defaults(
|
||||
pool: &sqlx::PgPool,
|
||||
table: &str,
|
||||
) -> Vec<(String, Option<String>)> {
|
||||
sqlx::query(
|
||||
"select column_name, column_default
|
||||
from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = $1
|
||||
order by ordinal_position",
|
||||
)
|
||||
.bind(table)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
(
|
||||
row.get::<String, _>("column_name"),
|
||||
row.get::<Option<String>, _>("column_default"),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn catalog_constraints(pool: &sqlx::PgPool, table: &str) -> Vec<String> {
|
||||
sqlx::query(
|
||||
"select c.conname
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema() and t.relname = $1
|
||||
order by c.conname",
|
||||
)
|
||||
.bind(table)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|row| row.get::<String, _>("conname"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn catalog_indexes(pool: &sqlx::PgPool) -> Vec<String> {
|
||||
sqlx::query(
|
||||
"select idx.relname
|
||||
from pg_catalog.pg_index i
|
||||
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
|
||||
join pg_catalog.pg_class t on t.oid = i.indrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and t.relname in ('artifact_blobs', 'artifact_sources')
|
||||
order by idx.relname",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|row| row.get::<String, _>("relname"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn catalog_owned_relations(pool: &sqlx::PgPool) -> Vec<(String, String)> {
|
||||
sqlx::query(
|
||||
r"select c.relname, c.relkind::text as relkind
|
||||
from pg_catalog.pg_class c
|
||||
join pg_catalog.pg_namespace n on n.oid = c.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and c.relname like 'artifact\_%' escape '\'
|
||||
order by c.relname",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
(
|
||||
row.get::<String, _>("relname"),
|
||||
row.get::<String, _>("relkind"),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn catalog_constraint_definitions(pool: &sqlx::PgPool) -> HashMap<String, String> {
|
||||
sqlx::query(
|
||||
"select c.conname, pg_get_constraintdef(c.oid, true) as definition
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and t.relname in ('artifact_blobs', 'artifact_sources')",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
(
|
||||
row.get::<String, _>("conname"),
|
||||
row.get::<String, _>("definition"),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn assert_v12_drift(pool: &sqlx::PgPool, drift: &str, restore: &str) {
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(drift.to_owned()))
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let error = MigrationAuthority::preflight(pool).await.unwrap_err();
|
||||
assert_eq!(error.code(), "partial_sequence", "drift: {drift}");
|
||||
assert_eq!(error.version(), Some(12), "drift: {drift}");
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(restore.to_owned()))
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 },
|
||||
"restore: {restore}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn v12_guard_rejects_exhaustive_catalog_drift_for_both_tables() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v12_exhaustive_drift").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
|
||||
// Fixed catalog snapshots. These are hard assertions over the complete
|
||||
// matrix, so a disappeared object fails the test instead of silently
|
||||
// dropping out of the drift loop below.
|
||||
assert_eq!(
|
||||
catalog_columns(&pool, "artifact_blobs").await,
|
||||
owned_names(V12_BLOB_COLUMNS)
|
||||
);
|
||||
assert_eq!(
|
||||
catalog_columns(&pool, "artifact_sources").await,
|
||||
owned_names(V12_SOURCE_COLUMNS)
|
||||
);
|
||||
assert_eq!(
|
||||
V12_BLOB_COLUMNS.len() + V12_SOURCE_COLUMNS.len(),
|
||||
17,
|
||||
"the V12 column matrix is exactly seventeen columns"
|
||||
);
|
||||
assert_eq!(
|
||||
catalog_column_defaults(&pool, "artifact_blobs").await,
|
||||
owned_defaults(V12_BLOB_DEFAULTS)
|
||||
);
|
||||
assert_eq!(
|
||||
catalog_column_defaults(&pool, "artifact_sources").await,
|
||||
owned_defaults(V12_SOURCE_DEFAULTS)
|
||||
);
|
||||
assert_eq!(
|
||||
V12_BLOB_DEFAULTS.len() + V12_SOURCE_DEFAULTS.len(),
|
||||
17,
|
||||
"the V12 default matrix is exactly seventeen columns"
|
||||
);
|
||||
assert_eq!(
|
||||
V12_BLOB_DEFAULTS
|
||||
.iter()
|
||||
.chain(V12_SOURCE_DEFAULTS)
|
||||
.filter(|(_, default)| default.is_none())
|
||||
.count(),
|
||||
15,
|
||||
"fifteen V12 columns must declare no default"
|
||||
);
|
||||
assert_eq!(
|
||||
catalog_constraints(&pool, "artifact_blobs").await,
|
||||
owned_names(V12_BLOB_CONSTRAINTS)
|
||||
);
|
||||
assert_eq!(
|
||||
catalog_constraints(&pool, "artifact_sources").await,
|
||||
owned_names(V12_SOURCE_CONSTRAINTS)
|
||||
);
|
||||
assert_eq!(
|
||||
V12_BLOB_CONSTRAINTS.len() + V12_SOURCE_CONSTRAINTS.len(),
|
||||
18,
|
||||
"the V12 constraint matrix is exactly eighteen constraints"
|
||||
);
|
||||
assert_eq!(
|
||||
catalog_indexes(&pool).await,
|
||||
owned_names(&[
|
||||
"artifact_blobs_artifact_ref_key",
|
||||
"artifact_blobs_expired_claim_idx",
|
||||
"artifact_blobs_pkey",
|
||||
"artifact_sources_blob_lifecycle_detached_idx",
|
||||
"artifact_sources_openapi_dangling_idx",
|
||||
"artifact_sources_pkey",
|
||||
"artifact_sources_workspace_created_idx",
|
||||
])
|
||||
);
|
||||
assert_eq!(
|
||||
catalog_owned_relations(&pool).await,
|
||||
V12_OWNED_RELATIONS
|
||||
.iter()
|
||||
.map(|(name, kind)| ((*name).to_owned(), (*kind).to_owned()))
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
|
||||
// Every column of both tables: rename it away and restore the name.
|
||||
for (table, column) in V12_BLOB_COLUMNS
|
||||
.iter()
|
||||
.map(|column| ("artifact_blobs", *column))
|
||||
.chain(
|
||||
V12_SOURCE_COLUMNS
|
||||
.iter()
|
||||
.map(|column| ("artifact_sources", *column)),
|
||||
)
|
||||
{
|
||||
let drift = format!("alter table {table} rename column {column} to {column}_crank_drift;");
|
||||
let restore =
|
||||
format!("alter table {table} rename column {column}_crank_drift to {column};");
|
||||
assert_v12_drift(&pool, &drift, &restore).await;
|
||||
}
|
||||
|
||||
// Every column of both tables: change its type and restore the original,
|
||||
// then toggle nullability and restore it. The primary-key members are a
|
||||
// special case because PostgreSQL rejects dropping their NOT NULL while the
|
||||
// key exists; that rejection is asserted and the nullable shape is reached
|
||||
// through a dropped/restored primary key.
|
||||
exhaustive_v12::assert_column_type_drift(&pool).await;
|
||||
exhaustive_v12::assert_column_nullability_drift(&pool).await;
|
||||
|
||||
// Every declared default: swap in a different typed default, then restore.
|
||||
for (table, column, replacement, original) in [
|
||||
(
|
||||
"artifact_blobs",
|
||||
"storage_lifecycle",
|
||||
"'unavailable'",
|
||||
"'available'",
|
||||
),
|
||||
("artifact_sources", "lifecycle", "'detached'", "'active'"),
|
||||
] {
|
||||
let drift = format!("alter table {table} alter column {column} set default {replacement};");
|
||||
let restore = format!("alter table {table} alter column {column} set default {original};");
|
||||
assert_v12_drift(&pool, &drift, &restore).await;
|
||||
}
|
||||
|
||||
// Every V12 column that declares no default: introduce a concrete typed
|
||||
// default, prove the guard rejects it, then drop the default and prove the
|
||||
// schema returns to Current. A bare `set default null` would be folded back
|
||||
// into "no default" by PostgreSQL, so the drift list is fixed and compared
|
||||
// against the default inventory to keep a missing field from dropping out.
|
||||
assert_eq!(
|
||||
V12_BLOB_NO_DEFAULT_DRIFT
|
||||
.iter()
|
||||
.map(|(column, _)| *column)
|
||||
.collect::<Vec<_>>(),
|
||||
V12_BLOB_DEFAULTS
|
||||
.iter()
|
||||
.filter(|(_, default)| default.is_none())
|
||||
.map(|(column, _)| *column)
|
||||
.collect::<Vec<_>>(),
|
||||
"every defaultless artifact_blobs column must have a drift case"
|
||||
);
|
||||
assert_eq!(
|
||||
V12_SOURCE_NO_DEFAULT_DRIFT
|
||||
.iter()
|
||||
.map(|(column, _)| *column)
|
||||
.collect::<Vec<_>>(),
|
||||
V12_SOURCE_DEFAULTS
|
||||
.iter()
|
||||
.filter(|(_, default)| default.is_none())
|
||||
.map(|(column, _)| *column)
|
||||
.collect::<Vec<_>>(),
|
||||
"every defaultless artifact_sources column must have a drift case"
|
||||
);
|
||||
for (table, column, drift) in V12_BLOB_NO_DEFAULT_DRIFT
|
||||
.iter()
|
||||
.map(|(column, drift)| ("artifact_blobs", *column, *drift))
|
||||
.chain(
|
||||
V12_SOURCE_NO_DEFAULT_DRIFT
|
||||
.iter()
|
||||
.map(|(column, drift)| ("artifact_sources", *column, *drift)),
|
||||
)
|
||||
{
|
||||
let set = format!("alter table {table} alter column {column} set default {drift};");
|
||||
let restore = format!("alter table {table} alter column {column} drop default;");
|
||||
assert_v12_drift(&pool, &set, &restore).await;
|
||||
}
|
||||
|
||||
// Every constraint: drop it, then restore it from its own catalog
|
||||
// definition. The foreign key that depends on the artifact_blobs primary
|
||||
// key is dropped first and restored after it.
|
||||
let definitions = catalog_constraint_definitions(&pool).await;
|
||||
for (table, constraint) in V12_BLOB_CONSTRAINTS
|
||||
.iter()
|
||||
.map(|constraint| ("artifact_blobs", *constraint))
|
||||
.chain(
|
||||
V12_SOURCE_CONSTRAINTS
|
||||
.iter()
|
||||
.map(|constraint| ("artifact_sources", *constraint)),
|
||||
)
|
||||
{
|
||||
let definition = definitions
|
||||
.get(constraint)
|
||||
.unwrap_or_else(|| panic!("missing definition for {constraint}"));
|
||||
if constraint == "artifact_blobs_pkey" {
|
||||
let fk = definitions
|
||||
.get("artifact_sources_blob_digest_fkey")
|
||||
.expect("the dependent foreign key definition must be captured");
|
||||
let drift = "alter table artifact_sources drop constraint artifact_sources_blob_digest_fkey;\n\
|
||||
alter table artifact_blobs drop constraint artifact_blobs_pkey;";
|
||||
let restore = format!(
|
||||
"alter table artifact_blobs add constraint artifact_blobs_pkey {definition};\n\
|
||||
alter table artifact_sources add constraint artifact_sources_blob_digest_fkey {fk};"
|
||||
);
|
||||
assert_v12_drift(&pool, drift, &restore).await;
|
||||
} else {
|
||||
let drift = format!("alter table {table} drop constraint {constraint};");
|
||||
let restore = format!("alter table {table} add constraint {constraint} {definition};");
|
||||
assert_v12_drift(&pool, &drift, &restore).await;
|
||||
}
|
||||
}
|
||||
|
||||
// Every constraint again, this time keeping its name and `contype` while
|
||||
// changing only its definition: same-name `check (true)`, foreign keys with
|
||||
// a different delete action, and primary key/unique constraints with
|
||||
// rewritten members. Each mutation must be rejected before the original
|
||||
// captured definition is replayed.
|
||||
exhaustive_v12::assert_constraint_definition_drift(&pool).await;
|
||||
|
||||
// The standalone V12 index: change its definition, then remove it.
|
||||
let index_definition: String = sqlx::query_scalar(
|
||||
"select pg_get_indexdef(i.indexrelid)
|
||||
from pg_catalog.pg_index i
|
||||
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = idx.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and idx.relname = 'artifact_sources_workspace_created_idx'",
|
||||
)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_v12_drift(
|
||||
&pool,
|
||||
"drop index artifact_sources_workspace_created_idx;
|
||||
create index artifact_sources_workspace_created_idx
|
||||
on artifact_sources(workspace_id, source_id, created_at);",
|
||||
&format!("drop index artifact_sources_workspace_created_idx;\n{index_definition};"),
|
||||
)
|
||||
.await;
|
||||
|
||||
// Every standalone index must be rejected when removed and restorable from
|
||||
// its own catalog definition. The V12 guard validates the whole expanded
|
||||
// name set, so each removal is a version 12 partial sequence.
|
||||
for index in [
|
||||
"artifact_blobs_expired_claim_idx",
|
||||
"artifact_sources_blob_lifecycle_detached_idx",
|
||||
"artifact_sources_openapi_dangling_idx",
|
||||
"artifact_sources_workspace_created_idx",
|
||||
] {
|
||||
let definition: String = sqlx::query_scalar(
|
||||
"select pg_get_indexdef(i.indexrelid)
|
||||
from pg_catalog.pg_index i
|
||||
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = idx.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and idx.relname = $1",
|
||||
)
|
||||
.bind(index)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_v12_drift(
|
||||
&pool,
|
||||
&format!("drop index {index};"),
|
||||
&format!("{definition};"),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
// Extra owned objects of every kind must be rejected by the exact inventory.
|
||||
assert_v12_drift(
|
||||
&pool,
|
||||
"create table artifact_crank_drift_owned(id integer);",
|
||||
"drop table artifact_crank_drift_owned;",
|
||||
)
|
||||
.await;
|
||||
assert_v12_drift(
|
||||
&pool,
|
||||
"create index artifact_crank_drift_owned_idx on artifact_blobs(digest);",
|
||||
"drop index artifact_crank_drift_owned_idx;",
|
||||
)
|
||||
.await;
|
||||
assert_v12_drift(
|
||||
&pool,
|
||||
"create view artifact_crank_drift_owned_view as select digest from artifact_blobs;",
|
||||
"drop view artifact_crank_drift_owned_view;",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
+426
@@ -0,0 +1,426 @@
|
||||
use crank_registry::{MigrationAuthority, MigrationPreflight};
|
||||
|
||||
// V12 changed-type coverage. Every column gets a reachable `alter column ...
|
||||
// type` drift whose `information_schema.data_type` differs from the frozen
|
||||
// guard expectation, plus the exact expression that puts the original type
|
||||
// back. `character varying` is chosen for the text columns and `timestamp`
|
||||
// for the timestamptz columns because both are binary-compatible rewrites:
|
||||
// PostgreSQL applies them even while the primary key, unique, foreign key,
|
||||
// default, check and index objects stay in place, so the guard rejection is
|
||||
// genuinely caused by the type drift and not by a missing dependent object.
|
||||
const COLUMN_TYPE_DRIFT: &[(&str, &str, &str, &str)] = &[
|
||||
("artifact_blobs", "digest", "character varying", "text"),
|
||||
(
|
||||
"artifact_blobs",
|
||||
"artifact_ref",
|
||||
"character varying",
|
||||
"text",
|
||||
),
|
||||
("artifact_blobs", "size_bytes", "integer", "bigint"),
|
||||
(
|
||||
"artifact_blobs",
|
||||
"storage_lifecycle",
|
||||
"character varying",
|
||||
"text",
|
||||
),
|
||||
("artifact_blobs", "claim_token", "character varying", "text"),
|
||||
(
|
||||
"artifact_blobs",
|
||||
"claim_expires_at",
|
||||
"timestamp",
|
||||
"timestamp with time zone",
|
||||
),
|
||||
(
|
||||
"artifact_blobs",
|
||||
"created_at",
|
||||
"timestamp",
|
||||
"timestamp with time zone",
|
||||
),
|
||||
(
|
||||
"artifact_blobs",
|
||||
"updated_at",
|
||||
"timestamp",
|
||||
"timestamp with time zone",
|
||||
),
|
||||
(
|
||||
"artifact_sources",
|
||||
"workspace_id",
|
||||
"character varying",
|
||||
"text",
|
||||
),
|
||||
("artifact_sources", "source_id", "character varying", "text"),
|
||||
(
|
||||
"artifact_sources",
|
||||
"blob_digest",
|
||||
"character varying",
|
||||
"text",
|
||||
),
|
||||
("artifact_sources", "mime_type", "character varying", "text"),
|
||||
(
|
||||
"artifact_sources",
|
||||
"sensitivity",
|
||||
"character varying",
|
||||
"text",
|
||||
),
|
||||
("artifact_sources", "lifecycle", "character varying", "text"),
|
||||
(
|
||||
"artifact_sources",
|
||||
"created_at",
|
||||
"timestamp",
|
||||
"timestamp with time zone",
|
||||
),
|
||||
(
|
||||
"artifact_sources",
|
||||
"updated_at",
|
||||
"timestamp",
|
||||
"timestamp with time zone",
|
||||
),
|
||||
(
|
||||
"artifact_sources",
|
||||
"detached_at",
|
||||
"timestamp",
|
||||
"timestamp with time zone",
|
||||
),
|
||||
];
|
||||
|
||||
// Columns that legitimately carry `null` in V12. The remaining non-primary-key
|
||||
// columns are `not null`, and the primary-key members cannot have `not null`
|
||||
// dropped while the key exists.
|
||||
const V12_NULLABLE_COLUMNS: &[(&str, &str)] = &[
|
||||
("artifact_blobs", "claim_token"),
|
||||
("artifact_blobs", "claim_expires_at"),
|
||||
("artifact_sources", "detached_at"),
|
||||
];
|
||||
|
||||
const V12_PRIMARY_KEY_COLUMNS: &[(&str, &str)] = &[
|
||||
("artifact_blobs", "digest"),
|
||||
("artifact_sources", "workspace_id"),
|
||||
("artifact_sources", "source_id"),
|
||||
];
|
||||
|
||||
// V12 changed-definition coverage. Each entry keeps the original constraint
|
||||
// name and `pg_constraint.contype` and only changes the definition: every
|
||||
// check becomes `check (true)`, both foreign keys change their delete action,
|
||||
// and the primary key/unique members are rewritten while staying the same
|
||||
// kind. The original definition is captured from the catalog and replayed to
|
||||
// restore the exact prior shape.
|
||||
const CONSTRAINT_DEFINITION_DRIFT: &[(&str, &str, &str)] = &[
|
||||
(
|
||||
"artifact_blobs",
|
||||
"artifact_blobs_artifact_ref_key",
|
||||
"unique (digest)",
|
||||
),
|
||||
(
|
||||
"artifact_blobs",
|
||||
"artifact_blobs_claim_shape_check",
|
||||
"check (true)",
|
||||
),
|
||||
(
|
||||
"artifact_blobs",
|
||||
"artifact_blobs_claim_token_check",
|
||||
"check (true)",
|
||||
),
|
||||
(
|
||||
"artifact_blobs",
|
||||
"artifact_blobs_digest_check",
|
||||
"check (true)",
|
||||
),
|
||||
(
|
||||
"artifact_blobs",
|
||||
"artifact_blobs_lifecycle_check",
|
||||
"check (true)",
|
||||
),
|
||||
(
|
||||
"artifact_blobs",
|
||||
"artifact_blobs_pkey",
|
||||
"primary key (digest) include (artifact_ref)",
|
||||
),
|
||||
("artifact_blobs", "artifact_blobs_ref_check", "check (true)"),
|
||||
(
|
||||
"artifact_blobs",
|
||||
"artifact_blobs_size_check",
|
||||
"check (true)",
|
||||
),
|
||||
(
|
||||
"artifact_blobs",
|
||||
"artifact_blobs_timestamps_check",
|
||||
"check (true)",
|
||||
),
|
||||
(
|
||||
"artifact_sources",
|
||||
"artifact_sources_blob_digest_fkey",
|
||||
"foreign key (blob_digest) references artifact_blobs(digest) on delete cascade",
|
||||
),
|
||||
(
|
||||
"artifact_sources",
|
||||
"artifact_sources_id_check",
|
||||
"check (true)",
|
||||
),
|
||||
(
|
||||
"artifact_sources",
|
||||
"artifact_sources_lifecycle_check",
|
||||
"check (true)",
|
||||
),
|
||||
(
|
||||
"artifact_sources",
|
||||
"artifact_sources_mime_type_check",
|
||||
"check (true)",
|
||||
),
|
||||
(
|
||||
"artifact_sources",
|
||||
"artifact_sources_pkey",
|
||||
"primary key (source_id, workspace_id)",
|
||||
),
|
||||
(
|
||||
"artifact_sources",
|
||||
"artifact_sources_sensitivity_check",
|
||||
"check (true)",
|
||||
),
|
||||
(
|
||||
"artifact_sources",
|
||||
"artifact_sources_state_check",
|
||||
"check (true)",
|
||||
),
|
||||
(
|
||||
"artifact_sources",
|
||||
"artifact_sources_timestamps_check",
|
||||
"check (true)",
|
||||
),
|
||||
(
|
||||
"artifact_sources",
|
||||
"artifact_sources_workspace_id_fkey",
|
||||
"foreign key (workspace_id) references workspaces(id) on delete restrict",
|
||||
),
|
||||
];
|
||||
|
||||
async fn catalog_nullable(pool: &sqlx::PgPool, table: &str, column: &str) -> bool {
|
||||
sqlx::query_scalar::<_, String>(
|
||||
"select is_nullable
|
||||
from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = $1 and column_name = $2",
|
||||
)
|
||||
.bind(table)
|
||||
.bind(column)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
== "YES"
|
||||
}
|
||||
|
||||
pub(super) async fn assert_column_type_drift(pool: &sqlx::PgPool) {
|
||||
assert_eq!(
|
||||
COLUMN_TYPE_DRIFT.len(),
|
||||
17,
|
||||
"every V12 column needs a changed-type drift case"
|
||||
);
|
||||
for (table, column, drift_type, restore_type) in COLUMN_TYPE_DRIFT {
|
||||
let drift = format!("alter table {table} alter column {column} type {drift_type};");
|
||||
let restore = format!("alter table {table} alter column {column} type {restore_type};");
|
||||
super::assert_v12_drift(pool, &drift, &restore).await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn assert_column_nullability_drift(pool: &sqlx::PgPool) {
|
||||
let mut covered = 0usize;
|
||||
for (table, column) in super::V12_BLOB_COLUMNS
|
||||
.iter()
|
||||
.map(|column| ("artifact_blobs", *column))
|
||||
.chain(
|
||||
super::V12_SOURCE_COLUMNS
|
||||
.iter()
|
||||
.map(|column| ("artifact_sources", *column)),
|
||||
)
|
||||
{
|
||||
covered += 1;
|
||||
let nullable = catalog_nullable(pool, table, column).await;
|
||||
let expected_nullable = V12_NULLABLE_COLUMNS.contains(&(table, column));
|
||||
assert_eq!(
|
||||
nullable, expected_nullable,
|
||||
"nullability inventory drift for {table}.{column}"
|
||||
);
|
||||
if V12_PRIMARY_KEY_COLUMNS.contains(&(table, column)) {
|
||||
assert_primary_key_nullability(pool, table, column).await;
|
||||
} else if nullable {
|
||||
let drift = format!("alter table {table} alter column {column} set not null;");
|
||||
let restore = format!("alter table {table} alter column {column} drop not null;");
|
||||
super::assert_v12_drift(pool, &drift, &restore).await;
|
||||
} else {
|
||||
let drift = format!("alter table {table} alter column {column} drop not null;");
|
||||
let restore = format!("alter table {table} alter column {column} set not null;");
|
||||
super::assert_v12_drift(pool, &drift, &restore).await;
|
||||
}
|
||||
}
|
||||
assert_eq!(covered, 17, "every V12 column needs a nullability case");
|
||||
assert_eq!(
|
||||
V12_PRIMARY_KEY_COLUMNS.len() + V12_NULLABLE_COLUMNS.len(),
|
||||
6,
|
||||
"the V12 nullability exceptions are exactly the three primary-key members and three nullable columns"
|
||||
);
|
||||
}
|
||||
|
||||
// PostgreSQL refuses `drop not null` on a primary-key member outright, so this
|
||||
// case cannot be reached with the key in place. The rejection is asserted
|
||||
// explicitly instead of being skipped, then the nullable shape is reached by
|
||||
// dropping the primary key (and the dependent foreign key for artifact_blobs),
|
||||
// toggling nullability, and replaying the captured definitions in dependency
|
||||
// order.
|
||||
async fn assert_primary_key_nullability(pool: &sqlx::PgPool, table: &str, column: &str) {
|
||||
let direct = format!("alter table {table} alter column {column} drop not null;");
|
||||
let error = sqlx::raw_sql(sqlx::AssertSqlSafe(direct))
|
||||
.execute(pool)
|
||||
.await
|
||||
.expect_err("PostgreSQL must reject dropping NOT NULL on a primary key member");
|
||||
assert!(
|
||||
error.to_string().contains("is in a primary key"),
|
||||
"unexpected rejection for {table}.{column}: {error}"
|
||||
);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 },
|
||||
"a rejected primary-key nullability change must leave the schema current"
|
||||
);
|
||||
|
||||
let definitions = super::catalog_constraint_definitions(pool).await;
|
||||
let (drift, restore) = if table == "artifact_blobs" {
|
||||
let pkey = definitions
|
||||
.get("artifact_blobs_pkey")
|
||||
.expect("artifact_blobs primary key definition must be captured");
|
||||
let fk = definitions
|
||||
.get("artifact_sources_blob_digest_fkey")
|
||||
.expect("the foreign key that depends on artifact_blobs_pkey must be captured");
|
||||
(
|
||||
"alter table artifact_sources drop constraint artifact_sources_blob_digest_fkey;\n\
|
||||
alter table artifact_blobs drop constraint artifact_blobs_pkey;\n\
|
||||
alter table artifact_blobs alter column digest drop not null;"
|
||||
.to_owned(),
|
||||
format!(
|
||||
"alter table artifact_blobs alter column digest set not null;\n\
|
||||
alter table artifact_blobs add constraint artifact_blobs_pkey {pkey};\n\
|
||||
alter table artifact_sources add constraint artifact_sources_blob_digest_fkey {fk};"
|
||||
),
|
||||
)
|
||||
} else {
|
||||
let pkey = definitions
|
||||
.get("artifact_sources_pkey")
|
||||
.expect("artifact_sources primary key definition must be captured");
|
||||
(
|
||||
format!(
|
||||
"alter table artifact_sources drop constraint artifact_sources_pkey;\n\
|
||||
alter table artifact_sources alter column {column} drop not null;"
|
||||
),
|
||||
format!(
|
||||
"alter table artifact_sources alter column {column} set not null;\n\
|
||||
alter table artifact_sources add constraint artifact_sources_pkey {pkey};"
|
||||
),
|
||||
)
|
||||
};
|
||||
super::assert_v12_drift(pool, &drift, &restore).await;
|
||||
}
|
||||
|
||||
pub(super) async fn assert_constraint_definition_drift(pool: &sqlx::PgPool) {
|
||||
assert_eq!(
|
||||
CONSTRAINT_DEFINITION_DRIFT.len(),
|
||||
18,
|
||||
"every V12 constraint needs a same-name/kind changed-definition case"
|
||||
);
|
||||
let definitions = super::catalog_constraint_definitions(pool).await;
|
||||
for (table, constraint, drift_definition) in CONSTRAINT_DEFINITION_DRIFT {
|
||||
let original = definitions
|
||||
.get(*constraint)
|
||||
.unwrap_or_else(|| panic!("missing original definition for {constraint}"));
|
||||
if *constraint == "artifact_blobs_pkey" {
|
||||
let fk = definitions
|
||||
.get("artifact_sources_blob_digest_fkey")
|
||||
.expect("the foreign key that depends on artifact_blobs_pkey must be captured");
|
||||
let drift = format!(
|
||||
"alter table artifact_sources drop constraint artifact_sources_blob_digest_fkey;\n\
|
||||
alter table artifact_blobs drop constraint artifact_blobs_pkey;\n\
|
||||
alter table artifact_blobs add constraint artifact_blobs_pkey {drift_definition};\n\
|
||||
alter table artifact_sources add constraint artifact_sources_blob_digest_fkey {fk};"
|
||||
);
|
||||
let restore = format!(
|
||||
"alter table artifact_sources drop constraint artifact_sources_blob_digest_fkey;\n\
|
||||
alter table artifact_blobs drop constraint artifact_blobs_pkey;\n\
|
||||
alter table artifact_blobs add constraint artifact_blobs_pkey {original};\n\
|
||||
alter table artifact_sources add constraint artifact_sources_blob_digest_fkey {fk};"
|
||||
);
|
||||
assert_definition_only_drift(pool, constraint, &drift, &restore).await;
|
||||
} else {
|
||||
let drift = format!(
|
||||
"alter table {table} drop constraint {constraint};\n\
|
||||
alter table {table} add constraint {constraint} {drift_definition};"
|
||||
);
|
||||
let restore = format!(
|
||||
"alter table {table} drop constraint {constraint};\n\
|
||||
alter table {table} add constraint {constraint} {original};"
|
||||
);
|
||||
assert_definition_only_drift(pool, constraint, &drift, &restore).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A definition test must not pass merely because a dependent constraint went
|
||||
// missing. Assert that exactly the named definition changed, with the complete
|
||||
// name/kind inventory preserved, before asking the production guard to reject it.
|
||||
async fn assert_definition_only_drift(
|
||||
pool: &sqlx::PgPool,
|
||||
changed: &str,
|
||||
drift: &str,
|
||||
restore: &str,
|
||||
) {
|
||||
let before = super::catalog_constraint_definitions(pool).await;
|
||||
let kinds = constraint_kinds(pool).await;
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(drift.to_owned()))
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let after = super::catalog_constraint_definitions(pool).await;
|
||||
assert_eq!(
|
||||
constraint_kinds(pool).await,
|
||||
kinds,
|
||||
"all constraint names and kinds must survive: {changed}"
|
||||
);
|
||||
assert_ne!(
|
||||
after.get(changed),
|
||||
before.get(changed),
|
||||
"definition must actually change: {changed}"
|
||||
);
|
||||
for (name, definition) in &before {
|
||||
if name != changed {
|
||||
assert_eq!(
|
||||
after.get(name),
|
||||
Some(definition),
|
||||
"unrelated definition changed: {name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
let error = MigrationAuthority::preflight(pool).await.unwrap_err();
|
||||
assert_eq!(
|
||||
error.code(),
|
||||
"partial_sequence",
|
||||
"definition drift: {changed}"
|
||||
);
|
||||
assert_eq!(error.version(), Some(12), "definition drift: {changed}");
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(restore.to_owned()))
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(super::catalog_constraint_definitions(pool).await, before);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
);
|
||||
}
|
||||
|
||||
async fn constraint_kinds(pool: &sqlx::PgPool) -> Vec<(String, String)> {
|
||||
sqlx::query_as(
|
||||
"select c.conname::text, c.contype::text from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and t.relname in ('artifact_blobs', 'artifact_sources') order by c.conname",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
@@ -57,8 +57,8 @@ services:
|
||||
|
||||
artifact-storage-init:
|
||||
image: ${CRANK_ADMIN_API_IMAGE:-git.itexp.me/bsodfather/crank-community-admin-api:main}
|
||||
entrypoint: ["/bin/sh", "-ec"]
|
||||
command: ["install -d -m 700 -- \"$${CRANK_STORAGE_ROOT}\""]
|
||||
entrypoint: ["/usr/local/bin/crank-admin-entrypoint"]
|
||||
command: ["crank-storage-init"]
|
||||
restart: "no"
|
||||
environment:
|
||||
CRANK_STORAGE_ROOT: ${CRANK_STORAGE_ROOT:-/var/lib/crank/storage}
|
||||
|
||||
@@ -61,8 +61,8 @@ services:
|
||||
build:
|
||||
context: ../..
|
||||
dockerfile: apps/admin-api/Dockerfile
|
||||
entrypoint: ["/bin/sh", "-ec"]
|
||||
command: ["install -d -m 700 -- \"$${CRANK_STORAGE_ROOT}\""]
|
||||
entrypoint: ["/usr/local/bin/crank-admin-entrypoint"]
|
||||
command: ["crank-storage-init"]
|
||||
restart: "no"
|
||||
environment:
|
||||
CRANK_STORAGE_ROOT: ${CRANK_STORAGE_ROOT:-/var/lib/crank/storage}
|
||||
|
||||
+2
-2
@@ -44,8 +44,8 @@ services:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: apps/admin-api/Dockerfile
|
||||
entrypoint: ["/bin/sh", "-ec"]
|
||||
command: ["install -d -m 700 -- \"$${CRANK_STORAGE_ROOT}\""]
|
||||
entrypoint: ["/usr/local/bin/crank-admin-entrypoint"]
|
||||
command: ["crank-storage-init"]
|
||||
restart: "no"
|
||||
environment:
|
||||
CRANK_STORAGE_ROOT: ${CRANK_STORAGE_ROOT:-/var/lib/crank/storage}
|
||||
|
||||
@@ -784,7 +784,7 @@ Explicit зависимости Epic 8: `8.1 → 8.2`; `8.3,8.4,8.5,8.7,8.8` з
|
||||
|
||||
| Case ID | Проверка (Given / When / Then) | Expected evidence | PASS criterion |
|
||||
|---|---|---|---|
|
||||
| `AT-2.10-01` | **Given** OpenAPI 3.x `components.securitySchemes` или Swagger 2.0 `securityDefinitions`<br>**When** importer анализирует schemes<br>**Then** bearer HTTP, basic HTTP и API key в header/query/cookie преобразуются в typed security metadata<br>**And** source names, locations и применимые format hints сохраняются без credential values. | Отчёт AT-2.10-01: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | bearer HTTP, basic HTTP и API key в header/query/cookie преобразуются в typed security metadata; source names, locations и применимые format hints сохраняются без credential values. |
|
||||
| `AT-2.10-01` | **Given** OpenAPI 3.x `components.securitySchemes` или Swagger 2.0 `securityDefinitions`<br>**When** importer анализирует schemes<br>**Then** OpenAPI 3.x bearer/basic и API key в header/query/cookie, а Swagger 2.0 basic и API key в header/query преобразуются в typed security metadata; Swagger 2.0 cookie явно отклоняется как unsupported<br>**And** source names, locations и применимые format hints сохраняются без credential values. | Отчёт AT-2.10-01: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | OpenAPI 3.x bearer/basic и API key в header/query/cookie, а Swagger 2.0 basic и API key в header/query преобразуются в typed security metadata; Swagger 2.0 cookie явно отклоняется как unsupported; source names, locations и применимые format hints сохраняются без credential values. |
|
||||
| `AT-2.10-02` | **Given** global security requirement<br>**When** Operation не задаёт собственный override<br>**Then** candidate наследует global requirement согласно specification semantics<br>**And** operation-level requirement или explicit no-auth корректно заменяет global rule. | Отчёт AT-2.10-02: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | candidate наследует global requirement согласно specification semantics; operation-level requirement или explicit no-auth корректно заменяет global rule. |
|
||||
| `AT-2.10-03` | **Given** security requirement с несколькими alternatives<br>**When** source определяет OR-семантику<br>**Then** preview сохраняет все допустимые alternatives и позволяет выбрать поддерживаемый вариант<br>**And** importer не объединяет alternatives в ложное обязательное AND. | Отчёт AT-2.10-03: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | preview сохраняет все допустимые alternatives и позволяет выбрать поддерживаемый вариант; importer не объединяет alternatives в ложное обязательное AND. |
|
||||
| `AT-2.10-04` | **Given** security requirement, требующий несколько schemes одновременно<br>**When** source определяет AND-семантику<br>**Then** candidate сохраняет составное требование, если runtime contract его поддерживает<br>**And** иначе affected Operation получает blocker finding с перечислением несохраняемой semantics. | Отчёт AT-2.10-04: фактический результат указанного When и наблюдения/значения для каждого Then/And; процедура, revision/config/environment, исполнитель/дата и bounded артефакты с digest. Для мутации/отказа — состояние до/после и число side effects. | candidate сохраняет составное требование, если runtime contract его поддерживает; иначе affected Operation получает blocker finding с перечислением несохраняемой semantics. |
|
||||
@@ -2996,3 +2996,7 @@ Protocol-кейсы (вне построчного AC-реестра): `AT-PROTO
|
||||
---
|
||||
|
||||
_Конец плана._
|
||||
|
||||
### Уточнение AT-2.10-01 — 2026-10-10
|
||||
|
||||
Разделены возможности двух форматов без изменения импортёра: в [OAS 2.0 Security Scheme Object](https://spec.openapis.org/oas/v2.0.html#security-scheme-object) для `apiKey.in` допустимы только `header` и `query`. Cookie поддерживает OpenAPI 3.x; неподдерживаемая Swagger-схема должна оставаться явным blocker, без создания Draft с ослабленной безопасностью. Предыдущее обобщение header/query/cookie на оба формата было ошибкой требований.
|
||||
@@ -0,0 +1,128 @@
|
||||
# Хранение и восстановление исходных документов OpenAPI
|
||||
|
||||
Эта инструкция описывает текущую реализацию Community. Контракт HTTP см.
|
||||
в [Admin API](admin-api.md#openapi-preview-upload), параметры — в
|
||||
[runtime-config.md](runtime-config.md), обновление схемы — в [migrations.md](migrations.md).
|
||||
|
||||
## Корень и ограничения
|
||||
|
||||
`CRANK_STORAGE_ROOT` — абсолютный путь, по умолчанию `/var/lib/crank/storage`.
|
||||
Admin API открывает его при запуске и закрепляет файловый дескриптор. Корень
|
||||
и внутренние каталоги должны принадлежать пользователю процесса и иметь права
|
||||
`0700`; опубликованные blobs — `0400`. Символьные ссылки, чужие владельцы,
|
||||
небезопасные права и hard links отклоняются. В Compose именованный том
|
||||
`artifact_storage` монтируется в этот путь, а `artifact-storage-init`
|
||||
подготавливает права. Не заменяйте root symlink и не исправляйте проблему
|
||||
прав рекурсивным `chmod 777`.
|
||||
|
||||
Production upload — `multipart/form-data` с единственным полем `file`, UTF-8
|
||||
YAML/JSON, непустой файл до 262144 bytes включительно. Расширение и MIME
|
||||
должны согласовываться; для YAML/JSON допустим `application/octet-stream`.
|
||||
Это фиксированный предел текущего импортёра, не отдельная переменная окружения.
|
||||
Дополнительные лимиты normalizer и external reference chain описаны в
|
||||
[openapi-import.md](openapi-import.md). Увеличение HTTP proxy body limit
|
||||
не увеличивает предел импортёра. Не передавайте документ через JSON `{document}`.
|
||||
|
||||
Физический blob адресуется только SHA-256: `sha256/<первые 2 hex>/<digest>`.
|
||||
Запись использует private temp, file fsync, публикацию без перезаписи и
|
||||
fsync каталога. Чтение проверяет digest до возврата bytes. PostgreSQL хранит
|
||||
workspace-scoped ownership и references; один физический digest может
|
||||
принадлежать нескольким workspace. Наличие файла не предоставляет права
|
||||
другому workspace. Preview не создаёт Operations; Apply создаёт их одной
|
||||
транзакцией и сохраняет неизменяемый результат для точного повторного запроса.
|
||||
|
||||
## Резервное копирование и восстановление
|
||||
|
||||
Сохраняйте согласованный комплект PostgreSQL, **всего** artifact storage,
|
||||
Compose, runtime configuration и используемой ревизии образов. Дамп БД
|
||||
без тома не восстанавливает исходники и snapshots; отдельно взятый том
|
||||
не восстанавливает ownership и immutable plans. Конфигурация и исходники
|
||||
могут содержать секретные данные: закрытые права, шифрование копии и ограниченный доступ.
|
||||
|
||||
Перед ручным снимком остановите mutating traffic и процессы `admin-api`/
|
||||
`mcp-server`, включая фоновые reconciliation workers; затем получите дамп
|
||||
PostgreSQL и архив тома. Не удаляйте named volume. Копируйте комплект на другой
|
||||
хост и проверяйте SHA256SUMS. Возобновляйте процессы после получения снимка.
|
||||
|
||||
`scripts/deploy-community.sh` создаёт комплект `backups/<UTC>/` из
|
||||
`postgres.dump`, `artifacts.tar.gz`, `runtime.env`, `docker-compose.yml`,
|
||||
`SHA256SUMS` и проверяет миграцию копии перед обновлением. Дамп и архив
|
||||
получаются последовательно; при продолжающихся записях это **не** доказательство
|
||||
атомарного снимка БД+файлов. Для строгой согласованности оператор должен
|
||||
организовать окно без записей. Скрипт сохраняет пять последних локальных
|
||||
комплектов, поэтому внешняя копия обязательна до следующего обновления.
|
||||
|
||||
Проверяйте восстановление на изолированном стенде с matching image revision,
|
||||
БД и томом: контрольные суммы, compatibility check, `/ready`, чтение
|
||||
сохранённого source, повтор Apply с прежним ключом и отсутствие дубликатов.
|
||||
Существующая команда восстановления изменяет данные назначения:
|
||||
|
||||
```sh
|
||||
CRANK_RESTORE_CONFIRM=restore ./scripts/restore-community.sh DEPLOY_DIR BACKUP_DIR
|
||||
```
|
||||
|
||||
Перед её выполнением сохраните текущее состояние и убедитесь, что выбрано
|
||||
нужное назначение. Не откатывайте только приложение после миграции схемы:
|
||||
используйте совместимый forward image либо проверенное восстановление комплекта.
|
||||
|
||||
## Очистка и восстановление claims
|
||||
|
||||
Координатор запускается в Admin API, проходит Recovery до Sweep и ограничивает
|
||||
каждый тик: 4096 traversal syscalls, 32 candidates, 32 mutation attempts,
|
||||
deadline 30 секунд. Период — 15 минут. Grace финальных/detached blobs — 24 часа,
|
||||
lease claim — 5 минут; cleanup temp — после часа с отдельными лимитами
|
||||
512 scans / 16 deletes. Это константы текущей версии, не конфигурационные ручки.
|
||||
|
||||
Referenced source действующего ImportPlan не является orphan. Старые upload jobs
|
||||
и detached references очищаются по жизненному циклу; нельзя освобождать место
|
||||
ручным удалением digest из storage, пока БД ссылается на него.
|
||||
Sweep сначала помещает eligible blob в quarantine. Recovery проверяет обе
|
||||
канонические локации и только после подтверждённого отсутствия переводит БД
|
||||
в `unavailable`. Неопределённая мутация/fsync/commit сохраняет claim для
|
||||
повторной попытки; перезапуск начинает bounded cycle заново. Старый worker
|
||||
не может финализировать новый fencing token. При сбое диска/БД восстановите
|
||||
ресурс, затем наблюдайте последующие тики; не сбрасывайте claim вручную в idle.
|
||||
|
||||
Legacy read — только из явно настроенного доверенного корня с проверками
|
||||
containment и digest. Это read compatibility, не автоматическая миграция,
|
||||
перезапись или удаление старых файлов. URL документа не выбирает корень.
|
||||
|
||||
## Диагностика и границы доказательств
|
||||
|
||||
Используйте canonical `X-Request-ID` и `X-Trace-ID` из ответа для сопоставления
|
||||
с диагностикой. Ошибки не должны включать raw source, credentials или пути.
|
||||
Reconciliation пишет фиксированные classification counters в события
|
||||
`admin.artifact_reconciliation.tick` / `failed`; это безопасные категории,
|
||||
а не реестр digest/workspace/token. `/ready` проверяет доступность PostgreSQL,
|
||||
но не подтверждает целостность каждого blob: verified read проверяет конкретный файл.
|
||||
|
||||
Для проверки фоновой очистки смотрите последовательность событий
|
||||
`admin.artifact_reconciliation.tick`: `cycle_completed=true` означает завершённый
|
||||
проход, `recovery_completed=false` — Recovery ещё продолжается. Несколько тиков
|
||||
с `retryable=true`, ростом `recovery_retryable`, `registration_retryable` или
|
||||
`mutation_retryable` требуют проверки доступности БД, свободного места и ошибок
|
||||
fsync/permissions. Событие `admin.artifact_reconciliation.failed` содержит
|
||||
категорию `backend` или `deadline`; сопоставьте её с журналами БД и хоста.
|
||||
После восстановления ресурса убедитесь, что следующие тики завершают цикл без
|
||||
retryable. Предел candidates/mutation attempts может означать продолжение
|
||||
ограниченного прохода, а не сбой.
|
||||
|
||||
В текущей версии эти значения — поля структурированных событий, а не
|
||||
Prometheus gauge размера очереди. Runtime не публикует точное число оставшихся
|
||||
blobs: не считайте один незавершённый тик доказательством утечки. Для Compose
|
||||
отберите события из журнала Admin API командой
|
||||
`docker compose logs --since 2h admin-api`; фильтруйте по фиксированным именам
|
||||
событий. Не включайте raw source или digest в диагностические выгрузки.
|
||||
|
||||
Внешние ссылки выключены по умолчанию. Разрешение задаёт оператор allowlist;
|
||||
автономный комплект требует подготовки и согласованной поддержки загрузки,
|
||||
а не произвольного доступа к файловой системе. Документ не может разрешить
|
||||
себе сеть. Изменённое удалённое содержимое требует нового preview.
|
||||
|
||||
Автоматические проверки находятся в `crank-artifacts/tests`, registry
|
||||
`artifact_sources`/`artifact_reconciliation`, Admin API `reconciliation/tests`
|
||||
и `openapi_import`, UI `openapi*.spec.js`. Они проверяют конкретные сбои и
|
||||
состояния; успешный CI не доказывает отсутствие любых аппаратных сбоев,
|
||||
потерь данных при произвольном порядке backup или утечек по времени.
|
||||
Reference performance, длительная эксплуатация и человеческая приёмка
|
||||
выполняются отдельно по [acceptance-test-plan.md](acceptance-test-plan.md).
|
||||
@@ -176,6 +176,9 @@ curl -I http://127.0.0.1:3000/
|
||||
|
||||
## Эксплуатация
|
||||
|
||||
Хранение OpenAPI sources, ограничения загрузки, согласованное резервирование
|
||||
и восстановление claims описаны в [операторской инструкции](artifact-storage-operations.md).
|
||||
|
||||
- `/health` проверяет, что процесс жив; `/ready` дополнительно проверяет доступность PostgreSQL и используется Docker Compose.
|
||||
- CD перед каждым обновлением создаёт согласованный комплект в `backups/<UTC-время>`: дамп PostgreSQL, том артефактов, окружение, Compose и контрольные суммы. Хранятся последние пять локальных комплектов.
|
||||
- Копируйте комплекты резервных копий на отдельный хост или в объектное хранилище.
|
||||
|
||||
@@ -212,7 +212,7 @@ Semantic loss получает blocker с source location: такой candidate
|
||||
|
||||
Один endpoint с несколькими request formats остаётся одним Tool. Поля `content_type` и `body` выбирают одну schema и соответствующую сериализацию; неизвестный selector или body другой ветви отклоняются до отправки запроса. Для единственного формата selector не нужен. Подробный inline-file contract описан в [REST](protocols/rest.md).
|
||||
|
||||
Новые imports используют `normalized-ir-v5` / `preview-v6`: source-derived candidate, finding и naming conflict включают безопасный RFC 6901 `source_location`; typed findings сохраняют стабильный `code`. Схемы и маппинги принадлежат candidate с его source pointer и проверяемой provenance в IR/reference graph. Производные группы, counts и summary связаны с исходником через membership candidates; единственный pointer или finding code для такой агрегации был бы ложной provenance. Исторические v2/v3/v4/v5 jobs воспроизводят сохранённый preview, а legacy-v1 использует отдельную историческую projection. Обновление importer не меняет inputs существующих jobs.
|
||||
Новые imports используют `normalized-ir-v6` / `preview-v6`: source-derived candidate, finding и naming conflict включают безопасный RFC 6901 `source_location`; typed findings сохраняют стабильный `code`. Схемы и маппинги принадлежат candidate с его source pointer и проверяемой provenance в IR/reference graph. Производные группы, counts и summary связаны с исходником через membership candidates; единственный pointer или finding code для такой агрегации был бы ложной provenance. Общая pure HTTP(S) URI identity (`url::Url`) появилась в `normalized-ir-v6`: materializer и resolver больше не расходятся на percent-encoded dot segments и special-query символах. Исторические v2/v3/v4/v5 jobs, включая прежнюю пару `normalized-ir-v5`/`preview-v6`, воспроизводят сохранённый preview без повторного разбора, а legacy-v1 использует отдельную историческую projection. Обновление importer не меняет inputs существующих jobs.
|
||||
|
||||
Другие форматы спецификаций и протоколов в Community-импорт не входят.
|
||||
|
||||
@@ -256,7 +256,7 @@ Harness отправляет реальный `openapi.yaml` с 2 000 operations
|
||||
|
||||
## Нормативная матрица и regression corpus
|
||||
|
||||
Машинная матрица версии `1.0.3` хранится в [`crates/crank-import/tests/support-matrix.yaml`](../crates/crank-import/tests/support-matrix.yaml); corpus version — `1.0.4`. Матрица фиксирует контракт отдельно для OpenAPI 3.0, OpenAPI 3.1 и Swagger 2.0. Acceptance test запускает нормализатор на отдельном probe для каждой строки, включая все 100 успешных кодов в каждом формате, и сверяет сохранённую semantics или точный blocker; выполненные probes списываются со всех строк версии, поэтому неподвергнутая проверкой строка матрицы падает gate. Corpus version `1.0.4` — metadata-only SemVer increment для согласования manifest с неизменной matrix `1.0.3`; fixture contents и checksums не менялись. Предыдущий corpus release `1.0.3` добавил hostile fixture `hostile-security-scope.json`: document-level требование безопасности применяется только к унаследовавшему его secured candidate (`GET /secure`, location `/security/0`), а операция с явным `security: []` (`GET /public`) остаётся actionable без глобального blocker; oversized hostile JSON остаётся тем же canonical JSON с ожидаемым parser rejection.
|
||||
Машинная матрица версии `1.0.4` хранится в [`crates/crank-import/tests/support-matrix.yaml`](../crates/crank-import/tests/support-matrix.yaml); corpus version — `1.0.5`. Матрица фиксирует контракт отдельно для OpenAPI 3.0, OpenAPI 3.1 и Swagger 2.0. Acceptance test запускает нормализатор на отдельном probe для каждой строки, включая все 100 успешных кодов в каждом формате, и сверяет сохранённую semantics или точный blocker; выполненные probes списываются со всех строк версии, поэтому неподвергнутая проверкой строка матрицы падает gate. Corpus version `1.0.5` добавляет два hostile external-URI regression fixture (`regression-uri-encoded-dot.yaml`, `regression-uri-query-quote.yaml`) и модуль `reference_uri.rs`: encoded-dot path segment и апостроф в query канонизируются в URL transport identity, поэтому поставленный snapshot разрешается, а default-deny pass, statuses и denominators не ослабляются. Matrix `1.0.4` фиксирует общий external HTTP(S) URI canonicalization contract без изменения statuses. Предыдущий corpus release `1.0.4` был metadata-only SemVer increment; `1.0.3` добавил hostile fixture `hostile-security-scope.json`: document-level требование безопасности применяется только к унаследовавшему его secured candidate (`GET /secure`, location `/security/0`), а операция с явным `security: []` (`GET /public`) остаётся actionable без глобального blocker.
|
||||
|
||||
| Конструкция | OpenAPI 3.0/3.1 | Swagger 2.0 | Сохраняемый контракт или finding |
|
||||
|---|---|---|---|
|
||||
@@ -276,6 +276,6 @@ Harness отправляет реальный `openapi.yaml` с 2 000 operations
|
||||
| Микс public/secured operations | Поддерживается | Подвергается проверке | Blocker принадлежит только затронутому candidate; global blocker не создаётся для требований одного operation |
|
||||
| XML, `TRACE`, `CONNECT` | Unsupported | Unsupported | Source-located finding; blocker не становится actionable Draft |
|
||||
|
||||
Матрица `1.0.3` добавляет исполняемые probes обоих blockers во всех трёх форматах; coverage validation отвергает неподтверждённые source findings. Новые primary документы и external snapshots отвергают повторённые JSON/YAML mapping keys вместо last-key-wins; корректный YAML flow syntax сохраняется. HTTP(S) scheme регистронезависима, а Unicode hostname сопоставляется с punycode snapshot identity. Historical legacy v1 decoder и уже сохранённые completed reports не переписываются; новый preview с изменившейся semantics требует нового подтверждённого плана.
|
||||
Матрица `1.0.4` фиксирует общий pure HTTP(S) URI canonicalization contract во всех трёх форматах; matrix `1.0.3` добавила исполняемые probes обоих blockers во всех трёх форматах; coverage validation отвергает неподтверждённые source findings. Новые primary документы и external snapshots отвергают повторённые JSON/YAML mapping keys вместо last-key-wins; корректный YAML flow syntax сохраняется. HTTP(S) scheme регистронезависима, percent-encoded dot segments и special-query символы приводятся к `url::Url` identity, а Unicode hostname сопоставляется с punycode snapshot identity. Historical legacy v1 decoder и уже сохранённые completed reports не переписываются; новый preview с изменившейся semantics требует нового подтверждённого плана.
|
||||
|
||||
Offline corpus в `crates/crank-import/tests/corpus/` содержит 50 synthetic representative документов и hostile subset. Manifest фиксирует SHA-256 исходных файлов, canonical digest JSON, происхождение и лицензию; для representative документов он также фиксирует полный canonical preview и frozen candidates (schemas, mappings, actionable/blocker), а для hostile — ожидаемые отказы и findings. Команда `just openapi-corpus` прогоняет настоящий normalizer, сравнивает независимо перечисленные raw source pointers с canonical source tree и coverage ledger, проверяет порог 95% actionable от всех representative Operations и отдельно нулевой silent loss. Evidence связывает digest manifest и matrix, включает content digest и создаётся без перезаписи; конфликт содержимого для того же identity останавливает gate. CI прикладывает `crates/crank-import/target/openapi-corpus/evidence-<identity>.json`. Artifact не содержит загруженный исходник или значения secret-like examples.
|
||||
@@ -0,0 +1,159 @@
|
||||
# Сканирование образов и минимальный runtime
|
||||
|
||||
Документ описывает, как устроены конечные серверные образы Crank, как
|
||||
сокращён состав окружения и как CI блокирует неподтверждённые результаты проверки.
|
||||
Он относится к одной конкретной проблеме безопасности и **не закрывает
|
||||
оставшиеся NFR-риски**: это только часть работы, а не полное подтверждение
|
||||
соответствия NFR.
|
||||
|
||||
## Минимальный runtime
|
||||
|
||||
`admin-api` и `mcp-server` собираются `FROM scratch`: в финальный слой попадает
|
||||
не Debian slim, а заранее собранный минимальный rootfs. Его формирует
|
||||
`scripts/prepare-runtime-rootfs.sh` во время package stage Dockerfile
|
||||
(`apps/admin-api/Dockerfile`, `apps/mcp-server/Dockerfile`).
|
||||
|
||||
В rootfs переносятся только файлы явного allowlist-набора из **десяти** Debian
|
||||
пакетов:
|
||||
|
||||
```text
|
||||
base-files libc6 libgcc-s1 gcc-12-base bash dash libtinfo6 libselinux1 libpcre2-8-0 coreutils
|
||||
```
|
||||
|
||||
- `gcc-12-base` добавлен, чтобы copyright-файл, на который ссылается
|
||||
`libgcc-s1`, существовал вместе со своим пакетом-владельцем.
|
||||
- От `coreutils` переносятся только `mkdir`, `chmod`, `env` и их copyright.
|
||||
Полный GNU coreutils, `apt`, `libacl`, GNU `gzip`, `util-linux`, `infocmp` и
|
||||
BusyBox сознательно не попадают в образ.
|
||||
- Сохраняются Rust 1.96.1/glibc, CA-сертификаты, мигратор, порты, readiness,
|
||||
shell healthcheck, cold storage-init с правами 0700 и проверки путей.
|
||||
|
||||
### Учёт файлов и лицензии
|
||||
|
||||
Вместе с файлами rootfs создаётся проверяемая опись:
|
||||
|
||||
- `/usr/share/crank/runtime-inventory.tsv` — TSV из трёх колонок:
|
||||
`package<TAB>normalized absolute path<TAB>sha256` для обычного файла либо
|
||||
target симлинка. Сгенерированные самим helper-ом файлы (`/etc/passwd`,
|
||||
`/etc/group`, `/etc/nsswitch.conf`) помечены синтетическим пакетом
|
||||
`runtime-generated`. Путь фиксирован и не настраивается.
|
||||
- `/var/lib/dpkg/status` — десять параграфов с реальными версиями пакетов.
|
||||
Сам файл и inventory в TSV намеренно не перечисляются.
|
||||
- Лицензии ориентируются на фактические `copyright`-файлы перенесённых
|
||||
пакетов; версия каждого пакета берётся из dpkg, а не из внешнего списка.
|
||||
|
||||
Инвентарь содержит около 355 записей и проверяется не по декларации, а по
|
||||
реальному immutable образу (см. ниже).
|
||||
|
||||
## Что делает обёртка сканирования
|
||||
|
||||
`scripts/scan-images.sh IMAGE [IMAGE ...]` — единственная точка входа для CI:
|
||||
|
||||
1. Однократно скачивает и проверяет по SHA256 зафиксированную версию Trivy 0.70.0
|
||||
(`8b4376d5d6befe5c24d503f10ff136d9e0c49f9127a4279fd110b727929a5aa9`).
|
||||
2. Однократно скачивает свежую vulnerability DB в изолированный cache.
|
||||
3. Для каждого образа получает immutable id через `docker image inspect` и
|
||||
сканирует **именно id**, а не тег.
|
||||
4. Завершает каждый скан вызовом checker:
|
||||
`scripts/check-image-scan.py --report ... --image-id ... --db-metadata ... --decision ...`.
|
||||
|
||||
Политика сканирования жёстко зашита и не читает локальную конфигурацию:
|
||||
|
||||
```text
|
||||
--image-src docker --config /dev/null --ignorefile /dev/null
|
||||
--ignore-unfixed=false --list-all-pkgs=true
|
||||
--severity UNKNOWN,LOW,MEDIUM,HIGH,CRITICAL --scanners vuln
|
||||
--format json --exit-code 0 --skip-db-update
|
||||
--cache-dir <isolated> --no-progress --skip-version-check
|
||||
```
|
||||
|
||||
Перед запуском Trivy обёртка удаляет все унаследованные переменные `TRIVY_*`
|
||||
(имена читаются, значения не логируются), поэтому окружение не может подменить
|
||||
severity, config, ignorefile, skip-files или VEX. Наследуемые Docker context и
|
||||
proxy-переменные сохраняются.
|
||||
|
||||
## Артефакты и коды выхода
|
||||
|
||||
Результаты каждого запуска сохраняются в отдельном каталоге `.tmp/image-scan-evidence/run.XXXXXX` (расположение можно
|
||||
изменить только переменной `CRANK_IMAGE_SCAN_OUTPUT_DIR`, не фильтрами) и
|
||||
**сохраняются даже при красном результате**:
|
||||
|
||||
```text
|
||||
db/metadata.json копия фактических метаданных Trivy DB
|
||||
db-download.log лог загрузки базы
|
||||
scanner.json версия сканера и применённая политика
|
||||
<NN-slug>.json сырой JSON-отчёт Trivy по образу
|
||||
<NN-slug>.scan.log лог сканирования
|
||||
<NN-slug>.gate.log вывод checker
|
||||
<NN-slug>.decision.json решение checker по образу
|
||||
receipt.json агрегированная квитанция tag<->immutable id<->raw<->decision
|
||||
```
|
||||
|
||||
Сырой отчёт никогда не перезаписывается решением. Коды выхода:
|
||||
|
||||
- `0` — PASS: все образы прошли, неразрешённых High/Critical нет.
|
||||
- `1` — BLOCKED: есть High/Critical без точечного обоснованного исключения.
|
||||
- `2` — ERROR: bootstrap/скан/evidence неполны, испорчены, просрочены или
|
||||
не совпадают с реальным образом.
|
||||
|
||||
Обёртка не останавливается на красном образе и обрабатывает оставшиеся;
|
||||
итоговый код ненулевой, если хотя бы один образ не PASS. Сбой загрузки сканера
|
||||
или базы также даёт ненулевой код и error-квитанцию для каждого запрошенного
|
||||
образа.
|
||||
|
||||
## Единственное исключение
|
||||
|
||||
Проверяющий скрипт допускает только одну конкретную неприменимую находку и только при одновременном выполнении всех
|
||||
условий:
|
||||
|
||||
- CVE — `CVE-2025-69720`;
|
||||
- пакет — `libtinfo6`, `InstalledVersion == 6.4-4`;
|
||||
- дистрибутив — Debian 12;
|
||||
- реальная версия `libtinfo6` в dpkg/status — `6.4-4`;
|
||||
- `infocmp` отсутствует среди **всех** basename экспортированного образа;
|
||||
- `ncurses-bin` отсутствует в dpkg/status.
|
||||
|
||||
Уязвимость относится к front-end `infocmp` из ncurses, поэтому проверяется не
|
||||
только имя/версия из отчёта Trivy, но и фактическая файловая система и
|
||||
dpkg/status реального immutable образа. Любое другое имя, версия, дистрибутив
|
||||
или наличие `infocmp`/`ncurses-bin` запрещает исключение и блокирует сборку.
|
||||
Исходная находка остаётся в отчёте; в decision попадают `justification` и `image_id`.
|
||||
|
||||
Первичный источник: Debian Security Tracker —
|
||||
<https://security-tracker.debian.org/tracker/CVE-2025-69720>.
|
||||
|
||||
Предыдущий разбор применимости CVE и доказательства сохранены в
|
||||
[задаче Gitea #92](https://git.itexp.me/bsodfather/crank/issues/92).
|
||||
|
||||
## Почему fail-closed
|
||||
|
||||
- Отсутствие `Results`, `Packages` или целого отчёта не считается «пустым
|
||||
корректным» результатом: это ошибка evidence, а не PASS.
|
||||
- `Metadata.ImageID` обязан точно совпадать с immutable id, а OS, DB `UpdatedAt`
|
||||
и версии пакетов сверяются с реальностью.
|
||||
- DB старше 24 часов или из будущего более чем на 5 минут отклоняется.
|
||||
- Отсутствие `infocmp` берётся из реального экспорта, а не из самого Trivy
|
||||
отчёта: отчёту нельзя доверять в этом вопросе.
|
||||
- Любая ошибка docker/tar/IO трактуется как отказ.
|
||||
|
||||
## Повторная проверка
|
||||
|
||||
Воспроизвести контроль локально:
|
||||
|
||||
```sh
|
||||
scripts/scan-images.sh crank/admin-api:ci crank/mcp-server:ci crank/ui:ci
|
||||
python3 -m unittest discover -s tests/unit -p 'test_scan_images.py'
|
||||
python3 -m unittest discover -s tests/unit -p 'test_check_image_scan.py'
|
||||
```
|
||||
|
||||
Решение по каждому образу — в `<NN-slug>.decision.json`, агрегированный итог и
|
||||
связь тега с immutable id и артефактивами — в `receipt.json`. В CI полные
|
||||
результаты публикуются отдельными artifact-ами даже при красном gate
|
||||
(`image-scan-evidence` в Community Image Smoke и `deploy-image-scan-evidence` в
|
||||
Deploy).
|
||||
|
||||
## Границы
|
||||
|
||||
Документ не утверждает, что все NFR выполнены. Остальные CONCERNS, не
|
||||
относящиеся к перечню уязвимых компонентов и скрывающему фильтру CI, остаются
|
||||
открытыми и проверяются отдельно.
|
||||
Executable
+790
@@ -0,0 +1,790 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Strict evidence gate over a raw Trivy image scan and the real image.
|
||||
|
||||
The scanner wrapper (``scripts/scan-images.sh``) produces one raw Trivy JSON
|
||||
report per image and a copy of the Trivy DB metadata. This gate never rewrites
|
||||
those raw artifacts; it reads them, validates their schema and provenance, then
|
||||
cross-checks the findings against the immutable Docker image itself.
|
||||
|
||||
Exit codes:
|
||||
0 PASS - evidence is consistent and no unresolved High/Critical remains.
|
||||
1 BLOCKED- at least one High/Critical finding is not narrowly excepted.
|
||||
2 ERROR - the evidence (report, DB metadata, manifest or image export) is
|
||||
missing, malformed, stale or inconsistent.
|
||||
|
||||
The raw report is never modified. The evaluation result is written separately to
|
||||
the ``--decision`` path. The only allowed High/Critical exception is the
|
||||
CVE-2025-69720 false positive on the Debian 12 ``libtinfo6:6.4-4`` shared
|
||||
library when the ``infocmp`` front-end tool (``ncurses-bin``) is genuinely
|
||||
absent from the image; that absence is proven from the exported image, not from
|
||||
the scan report.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import posixpath
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import threading
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
# Packages that make up the Debian 12 server runtime rootfs. They must appear in
|
||||
# both the dpkg status database and the Trivy OS package inventory.
|
||||
EXPECTED_PACKAGES = (
|
||||
"base-files",
|
||||
"libc6",
|
||||
"libgcc-s1",
|
||||
"gcc-12-base",
|
||||
"bash",
|
||||
"dash",
|
||||
"libtinfo6",
|
||||
"libselinux1",
|
||||
"libpcre2-8-0",
|
||||
"coreutils",
|
||||
)
|
||||
|
||||
# Fixed, non-overridable runtime inventory location (see prepare-runtime-rootfs).
|
||||
RUNTIME_MANIFEST_PATH = "/usr/share/crank/runtime-inventory.tsv"
|
||||
DPKG_STATUS_PATH = "/var/lib/dpkg/status"
|
||||
SYNTHETIC_PACKAGE = "runtime-generated"
|
||||
CAPTURED_PATHS = frozenset({RUNTIME_MANIFEST_PATH, DPKG_STATUS_PATH})
|
||||
POST_PACKAGE_FILES = frozenset({
|
||||
RUNTIME_MANIFEST_PATH, DPKG_STATUS_PATH,
|
||||
"/etc/ssl/certs/ca-certificates.crt",
|
||||
"/usr/local/bin/admin-api", "/usr/local/bin/crank-migrate",
|
||||
"/usr/local/bin/mcp-server", "/usr/local/bin/crank-admin-entrypoint",
|
||||
"/usr/local/bin/crank-http-healthcheck",
|
||||
# Docker adds these container files; they are not Debian package contents.
|
||||
"/.dockerenv", "/dev/console", "/etc/hostname", "/etc/hosts",
|
||||
"/etc/mtab", "/etc/resolv.conf",
|
||||
})
|
||||
|
||||
RUNTIME_OS_FAMILY = "debian"
|
||||
RUNTIME_OS_NAME_PREFIX = "12"
|
||||
|
||||
ALLOWED_SEVERITIES = frozenset({"UNKNOWN", "LOW", "MEDIUM", "HIGH", "CRITICAL"})
|
||||
BLOCKING_SEVERITIES = frozenset({"HIGH", "CRITICAL"})
|
||||
|
||||
EXPECTED_CVE = "CVE-2025-69720"
|
||||
EXCEPTED_PACKAGE = "libtinfo6"
|
||||
EXCEPTED_VERSION = "6.4-4"
|
||||
EXCEPTION_JUSTIFICATION = (
|
||||
"CVE-2025-69720 describes the infocmp ncurses front-end. The runtime image "
|
||||
"ships only the libtinfo6:6.4-4 shared library from Debian 12 and does not "
|
||||
"contain /usr/bin/infocmp or the ncurses-bin package, so the vulnerable "
|
||||
"code path is unreachable. Proven against the exported immutable image, not "
|
||||
"the scan report."
|
||||
)
|
||||
|
||||
ALLOWED_MANIFEST_PACKAGES = frozenset(EXPECTED_PACKAGES) | {SYNTHETIC_PACKAGE}
|
||||
|
||||
DB_MAX_AGE = timedelta(hours=24)
|
||||
DB_MAX_FUTURE = timedelta(minutes=5)
|
||||
|
||||
MAX_REPORT_BYTES = 256 * 1024 * 1024
|
||||
MAX_DB_METADATA_BYTES = 1024 * 1024
|
||||
MAX_SPECIAL_FILE_BYTES = 4 * 1024 * 1024
|
||||
MAX_EXPORT_ENTRIES = 200_000
|
||||
MAX_EXPORT_BYTES = 512 * 1024 * 1024
|
||||
DOCKER_TIMEOUT_SECONDS = 600
|
||||
READ_CHUNK_BYTES = 64 * 1024
|
||||
|
||||
SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
|
||||
IMAGE_ID_RE = re.compile(r"^sha256:[0-9a-f]{64}$")
|
||||
CONTAINER_ID_RE = re.compile(r"^[0-9a-f]{12,64}$")
|
||||
TIMESTAMP_RE = re.compile(
|
||||
r"^(\d{4})-(\d{2})-(\d{2})[Tt ](\d{2}):(\d{2}):(\d{2})"
|
||||
r"(?:\.(\d+))?(Z|z|[+-]\d{2}:?\d{2})?$"
|
||||
)
|
||||
|
||||
|
||||
class EvidenceError(Exception):
|
||||
"""Raised when scan evidence is missing, malformed or inconsistent."""
|
||||
|
||||
|
||||
def parse_args(argv) -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Fail closed on unresolved High/Critical image findings."
|
||||
)
|
||||
parser.add_argument("--report", required=True, help="raw Trivy JSON report")
|
||||
parser.add_argument("--image-id", required=True, help="immutable image ID")
|
||||
parser.add_argument("--db-metadata", required=True, help="Trivy DB metadata")
|
||||
parser.add_argument("--decision", required=True, help="decision output JSON")
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def unique_json_object(pairs):
|
||||
result = {}
|
||||
for key, value in pairs:
|
||||
if key in result:
|
||||
raise EvidenceError(f"duplicate JSON key: {key}")
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
|
||||
def load_json(path: Path, max_bytes: int, label: str) -> dict:
|
||||
try:
|
||||
if not path.is_file():
|
||||
raise EvidenceError(f"{label} is not a regular file")
|
||||
with path.open("rb") as stream:
|
||||
raw = stream.read(max_bytes + 1)
|
||||
except OSError as error:
|
||||
raise EvidenceError(f"{label} cannot be read: {error}") from error
|
||||
if len(raw) > max_bytes:
|
||||
raise EvidenceError(f"{label} exceeds the size budget")
|
||||
if not raw.strip():
|
||||
raise EvidenceError(f"{label} is empty")
|
||||
try:
|
||||
payload = json.loads(raw, object_pairs_hook=unique_json_object)
|
||||
except (json.JSONDecodeError, UnicodeDecodeError) as error:
|
||||
raise EvidenceError(f"{label} is not valid JSON: {error}") from error
|
||||
if not isinstance(payload, dict):
|
||||
raise EvidenceError(f"{label} must be a JSON object")
|
||||
return payload
|
||||
|
||||
|
||||
def parse_timestamp(value, label: str) -> datetime:
|
||||
if not isinstance(value, str):
|
||||
raise EvidenceError(f"{label} must be a string timestamp")
|
||||
match = TIMESTAMP_RE.match(value.strip())
|
||||
if not match or not match.group(8):
|
||||
raise EvidenceError(f"{label} is not an RFC3339 timestamp: {value!r}")
|
||||
text = value.strip()
|
||||
if text.endswith(("Z", "z")):
|
||||
text = text[:-1] + "+00:00"
|
||||
try:
|
||||
return datetime.fromisoformat(text)
|
||||
except ValueError as error:
|
||||
raise EvidenceError(f"{label} is not a valid timestamp: {value!r}") from error
|
||||
|
||||
|
||||
def load_db_metadata(path: Path, now: datetime) -> dict:
|
||||
payload = load_json(path, MAX_DB_METADATA_BYTES, "Trivy DB metadata")
|
||||
if type(payload.get("Version")) is not int or payload["Version"] != 2:
|
||||
raise EvidenceError("unsupported or missing Trivy DB schema version")
|
||||
updated_at = parse_timestamp(payload.get("UpdatedAt"), "Trivy DB UpdatedAt")
|
||||
age = now - updated_at
|
||||
if age > DB_MAX_AGE:
|
||||
raise EvidenceError(
|
||||
f"Trivy DB is stale: updated {int(age.total_seconds())}s ago "
|
||||
f"(limit {int(DB_MAX_AGE.total_seconds())}s)"
|
||||
)
|
||||
if updated_at - now > DB_MAX_FUTURE:
|
||||
raise EvidenceError("Trivy DB UpdatedAt is too far in the future")
|
||||
return {
|
||||
"path": str(path),
|
||||
"updated_at": updated_at.isoformat(),
|
||||
"age_seconds": max(0, int(age.total_seconds())),
|
||||
"max_age_seconds": int(DB_MAX_AGE.total_seconds()),
|
||||
}
|
||||
|
||||
|
||||
def validate_vulnerability(vuln, result_index: int, vuln_index: int) -> None:
|
||||
prefix = f"report result {result_index} vulnerability {vuln_index}"
|
||||
if not isinstance(vuln, dict):
|
||||
raise EvidenceError(f"{prefix} is not a JSON object")
|
||||
for field in ("VulnerabilityID", "PkgName", "InstalledVersion", "Severity"):
|
||||
value = vuln.get(field)
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
raise EvidenceError(f"{prefix} is missing a non-empty {field}")
|
||||
severity = vuln["Severity"].strip().upper()
|
||||
if severity not in ALLOWED_SEVERITIES:
|
||||
raise EvidenceError(f"{prefix} has an unknown severity {vuln['Severity']!r}")
|
||||
fixed = vuln.get("FixedVersion")
|
||||
if fixed is not None and not isinstance(fixed, str):
|
||||
raise EvidenceError(f"{prefix} has an invalid FixedVersion")
|
||||
status = vuln.get("Status")
|
||||
if status is not None and not isinstance(status, str):
|
||||
raise EvidenceError(f"{prefix} has an invalid Status")
|
||||
|
||||
|
||||
def validate_report(report: dict, expected_image_id: str):
|
||||
if type(report.get("SchemaVersion")) is not int or report["SchemaVersion"] != 2:
|
||||
raise EvidenceError("unsupported or missing Trivy SchemaVersion")
|
||||
if not IMAGE_ID_RE.fullmatch(expected_image_id):
|
||||
raise EvidenceError("--image-id must be an immutable sha256 image id")
|
||||
if report.get("ArtifactType") != "container_image":
|
||||
raise EvidenceError("scan report ArtifactType is not container_image")
|
||||
metadata = report.get("Metadata")
|
||||
if not isinstance(metadata, dict):
|
||||
raise EvidenceError("scan report Metadata is missing")
|
||||
if metadata.get("ImageID") != expected_image_id:
|
||||
raise EvidenceError(
|
||||
f"scan report image id {metadata.get('ImageID')!r} does not match "
|
||||
f"the expected {expected_image_id!r}"
|
||||
)
|
||||
os_meta = metadata.get("OS")
|
||||
if not isinstance(os_meta, dict):
|
||||
raise EvidenceError("scan report Metadata.OS is missing")
|
||||
family = os_meta.get("Family")
|
||||
if not isinstance(family, str) or not family.strip():
|
||||
raise EvidenceError("scan report OS family is missing")
|
||||
name = os_meta.get("Name")
|
||||
if not isinstance(name, str) or not name.strip():
|
||||
raise EvidenceError("scan report is missing the OS version name")
|
||||
|
||||
results = report.get("Results")
|
||||
if not isinstance(results, list) or not results:
|
||||
raise EvidenceError("scan report Results is missing or empty")
|
||||
|
||||
trivy_packages: dict[str, str] = {}
|
||||
os_packages_result = None
|
||||
for index, result in enumerate(results):
|
||||
if not isinstance(result, dict):
|
||||
raise EvidenceError(f"report result {index} is not a JSON object")
|
||||
packages = result.get("Packages")
|
||||
if not isinstance(packages, list):
|
||||
raise EvidenceError(f"report result {index} is missing the Packages list")
|
||||
for package in packages:
|
||||
if not isinstance(package, dict):
|
||||
raise EvidenceError(f"report result {index} has a malformed package")
|
||||
for field in ("Name", "Version"):
|
||||
if not isinstance(package.get(field), str) or not package[field].strip():
|
||||
raise EvidenceError(f"report result {index} package lacks {field}")
|
||||
vulnerabilities = result.get("Vulnerabilities")
|
||||
if vulnerabilities is None:
|
||||
if not packages:
|
||||
raise EvidenceError(
|
||||
f"report result {index} has neither packages nor vulnerabilities"
|
||||
)
|
||||
elif not isinstance(vulnerabilities, list):
|
||||
raise EvidenceError(
|
||||
f"report result {index} has an invalid Vulnerabilities list"
|
||||
)
|
||||
else:
|
||||
for vuln_index, vuln in enumerate(vulnerabilities):
|
||||
validate_vulnerability(vuln, index, vuln_index)
|
||||
if str(result.get("Class", "")).strip().lower() == "os-pkgs" and packages:
|
||||
if result.get("Type") != family.strip().lower():
|
||||
raise EvidenceError("OS package result does not match the reported OS")
|
||||
os_packages_result = result
|
||||
for package in packages:
|
||||
package_name = package["Name"]
|
||||
release = package.get("Release", "")
|
||||
epoch = package.get("Epoch", 0)
|
||||
if not isinstance(release, str) or type(epoch) is not int or epoch < 0:
|
||||
raise EvidenceError(f"invalid package version fields for {package_name}")
|
||||
version = package["Version"]
|
||||
if release:
|
||||
version += "-" + release
|
||||
if epoch:
|
||||
version = str(epoch) + ":" + version
|
||||
if package_name in trivy_packages:
|
||||
raise EvidenceError(f"duplicate OS package: {package_name}")
|
||||
trivy_packages[package_name] = version
|
||||
if os_packages_result is None:
|
||||
raise EvidenceError("scan report has no non-empty OS package inventory")
|
||||
|
||||
os_info = {
|
||||
"family": family.strip().lower(),
|
||||
"name": name.strip() if isinstance(name, str) else "",
|
||||
}
|
||||
return os_info, results, trivy_packages
|
||||
|
||||
|
||||
def is_runtime_os(os_info: dict) -> bool:
|
||||
return (
|
||||
os_info.get("family") == RUNTIME_OS_FAMILY
|
||||
and re.fullmatch(r"12(?:\.\d+)*", str(os_info.get("name", ""))) is not None
|
||||
)
|
||||
|
||||
|
||||
def normalize_tar_path(name: str):
|
||||
text = str(name).replace("\\", "/").lstrip("/")
|
||||
while text.startswith("./"):
|
||||
text = text[2:]
|
||||
# Go's tar writer (used by `docker export`) marks directories with a
|
||||
# trailing slash; strip it before splitting so directory entries normalize.
|
||||
text = text.rstrip("/")
|
||||
if text in ("", "."):
|
||||
return None
|
||||
parts = text.split("/")
|
||||
if any(part in ("", ".", "..") for part in parts):
|
||||
raise EvidenceError(f"docker export contains an unsafe path: {name!r}")
|
||||
return "/" + "/".join(parts)
|
||||
|
||||
|
||||
def validate_manifest_path(path: str, line_number: int) -> None:
|
||||
if not path.startswith("/"):
|
||||
raise EvidenceError(
|
||||
f"manifest line {line_number} path must be absolute: {path!r}"
|
||||
)
|
||||
if "\\" in path or "\x00" in path:
|
||||
raise EvidenceError(f"manifest line {line_number} path is invalid: {path!r}")
|
||||
if path == "/" or posixpath.normpath(path) != path:
|
||||
raise EvidenceError(
|
||||
f"manifest line {line_number} path is not normalized: {path!r}"
|
||||
)
|
||||
for segment in path.split("/")[1:]:
|
||||
if segment in ("", ".", ".."):
|
||||
raise EvidenceError(
|
||||
f"manifest line {line_number} path is not normalized: {path!r}"
|
||||
)
|
||||
|
||||
|
||||
def parse_manifest(text: str):
|
||||
entries = []
|
||||
seen: set[str] = set()
|
||||
for line_number, raw in enumerate(text.splitlines(), 1):
|
||||
if raw == "":
|
||||
continue
|
||||
fields = raw.split("\t")
|
||||
if len(fields) != 3:
|
||||
raise EvidenceError(
|
||||
f"manifest line {line_number} must have three tab-separated fields"
|
||||
)
|
||||
package, path, digest = fields
|
||||
if not package:
|
||||
raise EvidenceError(f"manifest line {line_number} has an empty package label")
|
||||
if package not in ALLOWED_MANIFEST_PACKAGES:
|
||||
raise EvidenceError(
|
||||
f"manifest line {line_number} has an unexpected package label "
|
||||
f"{package!r}"
|
||||
)
|
||||
validate_manifest_path(path, line_number)
|
||||
if path in seen:
|
||||
raise EvidenceError(f"manifest lists the path more than once: {path}")
|
||||
seen.add(path)
|
||||
if not digest:
|
||||
raise EvidenceError(f"manifest line {line_number} has an empty digest")
|
||||
entries.append((package, path, digest, SHA256_RE.fullmatch(digest) is not None))
|
||||
if not entries:
|
||||
raise EvidenceError("runtime manifest is empty")
|
||||
if RUNTIME_MANIFEST_PATH in seen:
|
||||
raise EvidenceError("runtime manifest must not list its own path")
|
||||
if DPKG_STATUS_PATH in seen:
|
||||
raise EvidenceError("runtime manifest must not list the dpkg status file")
|
||||
return entries
|
||||
|
||||
|
||||
def parse_dpkg_status(text: str) -> dict:
|
||||
packages: dict[str, str] = {}
|
||||
for block in text.split("\n\n"):
|
||||
fields: dict[str, str] = {}
|
||||
for line in block.splitlines():
|
||||
if not line or line[0] in " \t":
|
||||
continue
|
||||
key, separator, value = line.partition(":")
|
||||
if not separator:
|
||||
continue
|
||||
fields[key.strip()] = value.strip()
|
||||
name = fields.get("Package")
|
||||
if name:
|
||||
if name in packages:
|
||||
raise EvidenceError(f"dpkg status lists {name} more than once")
|
||||
if fields.get("Status") != "install ok installed" or not fields.get("Version"):
|
||||
raise EvidenceError(f"dpkg status has invalid installed metadata for {name}")
|
||||
packages[name] = fields["Version"]
|
||||
return packages
|
||||
|
||||
|
||||
def _docker_create(image_id: str) -> str:
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["docker", "create", "--entrypoint", "/bin/sh", image_id],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=DOCKER_TIMEOUT_SECONDS,
|
||||
)
|
||||
except (OSError, subprocess.SubprocessError) as error:
|
||||
raise EvidenceError(f"docker create could not run: {error}") from error
|
||||
if result.returncode != 0:
|
||||
detail = result.stderr.strip() or f"exit {result.returncode}"
|
||||
raise EvidenceError(f"docker create failed for {image_id}: {detail}")
|
||||
container_id = result.stdout.strip()
|
||||
if not CONTAINER_ID_RE.fullmatch(container_id):
|
||||
raise EvidenceError("docker create returned an unexpected container id")
|
||||
return container_id
|
||||
|
||||
|
||||
def _docker_remove(container_id: str) -> None:
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["docker", "rm", container_id],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=DOCKER_TIMEOUT_SECONDS,
|
||||
)
|
||||
except (OSError, subprocess.SubprocessError) as error:
|
||||
raise EvidenceError(f"owned export container cleanup failed: {error}") from error
|
||||
if result.returncode != 0:
|
||||
raise EvidenceError("owned export container cleanup failed: " + result.stderr.strip())
|
||||
|
||||
|
||||
def _consume_member(member, archive, entries, contents, basenames, counters) -> None:
|
||||
path = normalize_tar_path(member.name)
|
||||
if path is None:
|
||||
return
|
||||
counters["entries"] += 1
|
||||
if counters["entries"] > MAX_EXPORT_ENTRIES:
|
||||
raise EvidenceError("docker export exceeds the entry budget")
|
||||
basenames.add(posixpath.basename(path))
|
||||
if path in entries:
|
||||
raise EvidenceError(f"docker export contains a duplicate path: {path}")
|
||||
if member.isdir():
|
||||
entries[path] = ("dir", None)
|
||||
return
|
||||
if member.issym():
|
||||
entries[path] = ("symlink", member.linkname)
|
||||
return
|
||||
if member.islnk():
|
||||
target = normalize_tar_path(member.linkname)
|
||||
linked = entries.get(target) if target else None
|
||||
if linked is not None and linked[0] == "file":
|
||||
entries[path] = ("file", linked[1])
|
||||
else:
|
||||
entries[path] = ("hardlink", member.linkname)
|
||||
return
|
||||
if not member.isfile():
|
||||
entries[path] = ("other", None)
|
||||
return
|
||||
counters["bytes"] += member.size
|
||||
if counters["bytes"] > MAX_EXPORT_BYTES:
|
||||
raise EvidenceError("docker export exceeds the size budget")
|
||||
hasher = hashlib.sha256()
|
||||
capture = bytearray() if path in CAPTURED_PATHS else None
|
||||
stream = archive.extractfile(member)
|
||||
if stream is None:
|
||||
raise EvidenceError(f"docker export could not read {path}")
|
||||
remaining = member.size
|
||||
with stream:
|
||||
while remaining > 0:
|
||||
chunk = stream.read(min(READ_CHUNK_BYTES, remaining))
|
||||
if not chunk:
|
||||
raise EvidenceError(f"docker export truncated while reading {path}")
|
||||
hasher.update(chunk)
|
||||
remaining -= len(chunk)
|
||||
if capture is not None:
|
||||
capture.extend(chunk)
|
||||
if len(capture) > MAX_SPECIAL_FILE_BYTES:
|
||||
raise EvidenceError(f"captured file exceeds budget: {path}")
|
||||
entries[path] = ("file", hasher.hexdigest())
|
||||
if capture is not None:
|
||||
contents[path] = bytes(capture)
|
||||
|
||||
|
||||
def _docker_export(container_id: str):
|
||||
# A file avoids stderr pipe backpressure while the tar stream is consumed.
|
||||
with tempfile.TemporaryFile() as stderr_file:
|
||||
try:
|
||||
process = subprocess.Popen(
|
||||
["docker", "export", container_id],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=stderr_file,
|
||||
)
|
||||
except OSError as error:
|
||||
raise EvidenceError(f"docker export could not run: {error}") from error
|
||||
|
||||
timed_out = threading.Event()
|
||||
|
||||
def expire():
|
||||
if process.poll() is None:
|
||||
timed_out.set()
|
||||
try:
|
||||
process.kill()
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
|
||||
deadline = threading.Timer(DOCKER_TIMEOUT_SECONDS, expire)
|
||||
deadline.daemon = True
|
||||
deadline.start()
|
||||
entries: dict[str, tuple] = {}
|
||||
contents: dict[str, bytes] = {}
|
||||
basenames: set[str] = set()
|
||||
counters = {"entries": 0, "bytes": 0}
|
||||
failure = None
|
||||
try:
|
||||
if process.stdout is None:
|
||||
raise EvidenceError("docker export has no output stream")
|
||||
try:
|
||||
with tarfile.open(fileobj=process.stdout, mode="r|") as archive:
|
||||
for member in archive:
|
||||
_consume_member(member, archive, entries, contents, basenames, counters)
|
||||
except tarfile.TarError as error:
|
||||
raise EvidenceError(f"docker export produced an unreadable archive: {error}") from error
|
||||
except EvidenceError as error:
|
||||
failure = error
|
||||
finally:
|
||||
if process.stdout is not None:
|
||||
process.stdout.close()
|
||||
if failure is not None and process.poll() is None:
|
||||
process.kill()
|
||||
return_code = process.wait()
|
||||
deadline.cancel()
|
||||
deadline.join()
|
||||
if timed_out.is_set():
|
||||
raise EvidenceError("docker export timed out")
|
||||
if failure is not None:
|
||||
raise failure
|
||||
if return_code != 0:
|
||||
stderr_file.seek(0)
|
||||
detail = stderr_file.read(READ_CHUNK_BYTES).decode("utf-8", "replace").strip()
|
||||
raise EvidenceError(f"docker export failed for {container_id}: {detail or f'exit {return_code}'}")
|
||||
return entries, contents, basenames
|
||||
|
||||
|
||||
def read_image(image_id: str):
|
||||
container_id = _docker_create(image_id)
|
||||
try:
|
||||
return _docker_export(container_id)
|
||||
finally:
|
||||
_docker_remove(container_id)
|
||||
|
||||
|
||||
def verify_runtime(entries, contents, trivy_packages):
|
||||
manifest_bytes = contents.get(RUNTIME_MANIFEST_PATH)
|
||||
if manifest_bytes is None:
|
||||
raise EvidenceError(f"runtime manifest {RUNTIME_MANIFEST_PATH} is missing")
|
||||
status_bytes = contents.get(DPKG_STATUS_PATH)
|
||||
if status_bytes is None:
|
||||
raise EvidenceError(f"package status {DPKG_STATUS_PATH} is missing")
|
||||
try:
|
||||
manifest = parse_manifest(manifest_bytes.decode("utf-8"))
|
||||
dpkg_packages = parse_dpkg_status(status_bytes.decode("utf-8"))
|
||||
except UnicodeDecodeError as error:
|
||||
raise EvidenceError("runtime inventory is not valid UTF-8") from error
|
||||
|
||||
unexpected_dpkg = set(dpkg_packages) - set(EXPECTED_PACKAGES)
|
||||
unexpected_trivy = set(trivy_packages) - set(EXPECTED_PACKAGES)
|
||||
if unexpected_dpkg or unexpected_trivy:
|
||||
raise EvidenceError("unexpected runtime packages: " + ", ".join(sorted(unexpected_dpkg | unexpected_trivy)))
|
||||
for package in EXPECTED_PACKAGES:
|
||||
if package not in dpkg_packages:
|
||||
raise EvidenceError(f"dpkg status is missing package {package}")
|
||||
missing_trivy = [name for name in EXPECTED_PACKAGES if name not in trivy_packages]
|
||||
if missing_trivy:
|
||||
raise EvidenceError(
|
||||
"Trivy OS package inventory is missing: " + ", ".join(missing_trivy)
|
||||
)
|
||||
for package in EXPECTED_PACKAGES:
|
||||
if dpkg_packages[package] != trivy_packages[package]:
|
||||
raise EvidenceError(f"Trivy/dpkg version mismatch for {package}")
|
||||
|
||||
for package, path, digest, is_hash in manifest:
|
||||
actual = entries.get(path)
|
||||
if actual is None:
|
||||
raise EvidenceError(f"manifest file is missing from the image: {path}")
|
||||
kind, value = actual
|
||||
if is_hash:
|
||||
if kind != "file" or value != digest:
|
||||
raise EvidenceError(f"manifest hash mismatch for {path}")
|
||||
elif kind != "symlink" or value != digest:
|
||||
raise EvidenceError(f"manifest symlink mismatch for {path}")
|
||||
|
||||
declared = {path for _, path, _, _ in manifest}
|
||||
undeclared = sorted(path for path, (kind, _) in entries.items()
|
||||
if kind != "dir" and path not in declared and path not in POST_PACKAGE_FILES)
|
||||
if undeclared:
|
||||
raise EvidenceError("undeclared runtime files: " + ", ".join(undeclared[:10]))
|
||||
|
||||
return {
|
||||
"manifest_entries": len(manifest),
|
||||
"manifest_packages": sorted({entry[0] for entry in manifest}),
|
||||
"dpkg_packages": len(dpkg_packages),
|
||||
"trivy_packages": len(trivy_packages),
|
||||
"manifest_verified": True,
|
||||
}, dpkg_packages
|
||||
|
||||
|
||||
def _is_excepted(vuln, os_info, infocmp_present, ncurses_bin_present, actual_version) -> bool:
|
||||
if vuln["VulnerabilityID"] != EXPECTED_CVE:
|
||||
return False
|
||||
if vuln["PkgName"] != EXCEPTED_PACKAGE:
|
||||
return False
|
||||
if vuln["InstalledVersion"] != EXCEPTED_VERSION:
|
||||
return False
|
||||
if actual_version != EXCEPTED_VERSION:
|
||||
return False
|
||||
if not is_runtime_os(os_info):
|
||||
return False
|
||||
if infocmp_present is not False:
|
||||
return False
|
||||
if ncurses_bin_present is not False:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def evaluate_findings(results, os_info, basenames, dpkg_packages, image_id):
|
||||
counts = {severity: 0 for severity in ALLOWED_SEVERITIES}
|
||||
high_critical = []
|
||||
blocking = []
|
||||
exceptions = []
|
||||
infocmp_present = "infocmp" in basenames if basenames is not None else None
|
||||
ncurses_bin_present = (
|
||||
"ncurses-bin" in dpkg_packages if dpkg_packages is not None else None
|
||||
)
|
||||
for result in results:
|
||||
target = result.get("Target", "")
|
||||
for vuln in result.get("Vulnerabilities", []) or []:
|
||||
severity = vuln["Severity"].strip().upper()
|
||||
counts[severity] += 1
|
||||
if severity not in BLOCKING_SEVERITIES:
|
||||
continue
|
||||
record = {
|
||||
"vulnerability_id": vuln["VulnerabilityID"],
|
||||
"package": vuln["PkgName"],
|
||||
"installed_version": vuln["InstalledVersion"],
|
||||
"fixed_version": vuln.get("FixedVersion") or None,
|
||||
"severity": severity,
|
||||
"status": vuln.get("Status") or None,
|
||||
"target": target,
|
||||
}
|
||||
actual_version = dpkg_packages.get(EXCEPTED_PACKAGE) if dpkg_packages else None
|
||||
if _is_excepted(vuln, os_info, infocmp_present, ncurses_bin_present, actual_version):
|
||||
record["disposition"] = "excepted"
|
||||
high_critical.append(record)
|
||||
exceptions.append(
|
||||
{
|
||||
"vulnerability_id": vuln["VulnerabilityID"],
|
||||
"package": vuln["PkgName"],
|
||||
"installed_version": vuln["InstalledVersion"],
|
||||
"severity": severity,
|
||||
"image_id": image_id,
|
||||
"justification": EXCEPTION_JUSTIFICATION,
|
||||
}
|
||||
)
|
||||
else:
|
||||
record["disposition"] = "blocked"
|
||||
high_critical.append(record)
|
||||
blocking.append(record)
|
||||
return {
|
||||
"severity_counts": {severity: counts[severity] for severity in sorted(counts)},
|
||||
"high_critical": high_critical,
|
||||
"blocking": blocking,
|
||||
"exceptions": exceptions,
|
||||
}
|
||||
|
||||
|
||||
def _sha256_file(path: Path) -> str:
|
||||
hasher = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
while True:
|
||||
chunk = stream.read(READ_CHUNK_BYTES)
|
||||
if not chunk:
|
||||
break
|
||||
hasher.update(chunk)
|
||||
return hasher.hexdigest()
|
||||
|
||||
|
||||
def _assert_distinct(decision_path: Path, report_path: Path, db_path: Path) -> None:
|
||||
protected = {report_path.resolve(), db_path.resolve()}
|
||||
if decision_path.resolve() in protected:
|
||||
raise EvidenceError(
|
||||
"--decision must not overwrite the raw report or DB metadata"
|
||||
)
|
||||
|
||||
|
||||
def compute(decision: dict, args: argparse.Namespace) -> None:
|
||||
report_path = Path(args.report)
|
||||
db_path = Path(args.db_metadata)
|
||||
decision_path = Path(args.decision)
|
||||
_assert_distinct(decision_path, report_path, db_path)
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
decision["db_metadata"] = load_db_metadata(db_path, now)
|
||||
report = load_json(report_path, MAX_REPORT_BYTES, "scan report")
|
||||
decision["report_sha256"] = _sha256_file(report_path)
|
||||
os_info, results, trivy_packages = validate_report(report, args.image_id)
|
||||
decision["os"] = os_info
|
||||
decision["artifact_type"] = "container_image"
|
||||
|
||||
basenames = None
|
||||
dpkg_packages = None
|
||||
if is_runtime_os(os_info):
|
||||
entries, contents, basenames = read_image(args.image_id)
|
||||
runtime_summary, dpkg_packages = verify_runtime(
|
||||
entries, contents, trivy_packages
|
||||
)
|
||||
runtime_summary["image_files"] = len(entries)
|
||||
decision["runtime_inventory"] = runtime_summary
|
||||
decision.update(
|
||||
evaluate_findings(results, os_info, basenames, dpkg_packages, args.image_id)
|
||||
)
|
||||
|
||||
|
||||
def write_decision(path: Path, decision: dict) -> None:
|
||||
payload = json.dumps(decision, indent=2, sort_keys=True) + "\n"
|
||||
directory = str(path.parent) if str(path.parent) else "."
|
||||
descriptor, temporary = tempfile.mkstemp(prefix=".decision-", dir=directory)
|
||||
try:
|
||||
with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
|
||||
stream.write(payload)
|
||||
os.replace(temporary, path)
|
||||
except OSError:
|
||||
try:
|
||||
os.unlink(temporary)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
def base_decision(args: argparse.Namespace) -> dict:
|
||||
return {
|
||||
"schema": "crank.image-scan.decision.v1",
|
||||
"image_id": args.image_id,
|
||||
"report_path": str(args.report),
|
||||
"db_metadata_path": str(args.db_metadata),
|
||||
"status": "error",
|
||||
"exit_code": 2,
|
||||
"errors": [],
|
||||
}
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
args = parse_args(sys.argv[1:] if argv is None else argv)
|
||||
# An unsafe output path must be rejected before any error receipt is written.
|
||||
try:
|
||||
_assert_distinct(Path(args.decision), Path(args.report), Path(args.db_metadata))
|
||||
except EvidenceError as error:
|
||||
print(f"image scan gate: evidence failure: {error}", file=sys.stderr)
|
||||
return 2
|
||||
decision = base_decision(args)
|
||||
try:
|
||||
compute(decision, args)
|
||||
except EvidenceError as error:
|
||||
decision["status"] = "error"
|
||||
decision["exit_code"] = 2
|
||||
decision["errors"].append(str(error))
|
||||
try:
|
||||
write_decision(Path(args.decision), decision)
|
||||
except OSError as write_error:
|
||||
print(
|
||||
f"image scan gate: cannot write decision: {write_error}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 2
|
||||
print(f"image scan gate: evidence failure: {error}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
blocking = decision.get("blocking", [])
|
||||
if blocking:
|
||||
decision["status"] = "blocked"
|
||||
decision["exit_code"] = 1
|
||||
else:
|
||||
decision["status"] = "pass"
|
||||
decision["exit_code"] = 0
|
||||
try:
|
||||
write_decision(Path(args.decision), decision)
|
||||
except OSError as error:
|
||||
print(f"image scan gate: cannot write decision: {error}", file=sys.stderr)
|
||||
return 2
|
||||
print(
|
||||
"image scan gate: {status} ({blocked} blocking, {excepted} excepted)".format(
|
||||
status=decision["status"],
|
||||
blocked=len(blocking),
|
||||
excepted=len(decision.get("exceptions", [])),
|
||||
)
|
||||
)
|
||||
return decision["exit_code"]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Executable
+169
@@ -0,0 +1,169 @@
|
||||
#!/bin/sh
|
||||
# Assemble the minimal Debian runtime rootfs used by the Crank server images.
|
||||
#
|
||||
# The final admin-api and mcp-server images are built `FROM scratch`; this
|
||||
# script runs inside the Debian package stage before the rootfs is copied into
|
||||
# the scratch image. It transfers only the files owned by an explicit package
|
||||
# allowlist plus three GNU coreutils programs and their copyright. No apt,
|
||||
# libacl, GNU gzip, infocmp, util-linux or BusyBox files are copied.
|
||||
#
|
||||
# Merged-/usr: Debian exposes /bin, /sbin and /lib as symlinks into /usr. The
|
||||
# package file lists still name the legacy paths (for example /bin/bash or
|
||||
# /lib/x86_64-linux-gnu/libc.so.6). Before every copy the parent directory is
|
||||
# resolved through those symlinks (readlink -f on the dirname only), so regular
|
||||
# files and library symlinks land in their real /usr locations while the
|
||||
# top-level directory symlinks (/bin -> usr/bin, /lib -> usr/lib,
|
||||
# /lib64 -> usr/lib64) and file symlinks (for example /usr/bin/sh -> dash) are
|
||||
# preserved unchanged.
|
||||
#
|
||||
# Inventory: /usr/share/crank/runtime-inventory.tsv is a tab-separated manifest
|
||||
# with one row per file placed in the rootfs by this script:
|
||||
#
|
||||
# package<TAB>normalized absolute path<TAB>sha256 for regular files or the
|
||||
# symlink target for symlinks
|
||||
#
|
||||
# Files generated here instead of shipped by a package use the synthetic
|
||||
# package label `runtime-generated`. The scan stage cross-checks this manifest
|
||||
# against the real image instead of trusting Trivy alone. The manifest path is
|
||||
# fixed and cannot be overridden.
|
||||
set -eu
|
||||
|
||||
dest="${1:-/runtime}"
|
||||
|
||||
case "$dest" in
|
||||
/*) ;;
|
||||
*)
|
||||
echo "runtime rootfs destination must be an absolute path: $dest" >&2
|
||||
exit 64
|
||||
;;
|
||||
esac
|
||||
|
||||
# Packages kept in the runtime image. Versions are recorded in dpkg/status.
|
||||
# gcc-12-base supplies the copyright target of libgcc-s1; retaining its
|
||||
# package-owned documentation preserves the license and its source version.
|
||||
packages="base-files libc6 libgcc-s1 gcc-12-base bash dash libtinfo6 libselinux1 libpcre2-8-0 coreutils"
|
||||
|
||||
# shellcheck disable=SC2086
|
||||
set -- $packages
|
||||
expected_packages="$#"
|
||||
set --
|
||||
|
||||
# GNU coreutils is installed only so apt resolves dependencies honestly; of the
|
||||
# whole package just these files are transferred. install/cp/mv are deliberately
|
||||
# left out because they pull in libacl.
|
||||
coreutils_files="/bin/mkdir /bin/chmod /usr/bin/env /usr/share/doc/coreutils/copyright"
|
||||
|
||||
mkdir -p \
|
||||
"$dest/usr/local/bin" \
|
||||
"$dest/var/lib/dpkg" \
|
||||
"$dest/etc" \
|
||||
"$dest/tmp" \
|
||||
"$dest/run/lock" \
|
||||
"$dest/usr/share/crank"
|
||||
|
||||
# A world-writable sticky /tmp and the run-state directories match the FHS and
|
||||
# the previous slim image. /run and /run/lock also give the base-files
|
||||
# /var/run and /var/lock symlinks valid targets.
|
||||
chmod 1777 "$dest/tmp"
|
||||
chmod 0755 "$dest/run"
|
||||
chmod 1777 "$dest/run/lock"
|
||||
|
||||
status="$dest/var/lib/dpkg/status"
|
||||
inventory="$dest/usr/share/crank/runtime-inventory.tsv"
|
||||
: > "$status"
|
||||
: > "$inventory"
|
||||
|
||||
for package in $packages; do
|
||||
version="$(dpkg-query -W -f='${Version}' "$package")"
|
||||
printf 'runtime-package: %s %s\n' "$package" "$version"
|
||||
|
||||
# dpkg/status paragraph, separated from the next one by a blank line.
|
||||
dpkg-query -s "$package" >> "$status"
|
||||
printf '\n' >> "$status"
|
||||
|
||||
# shellcheck disable=SC2086
|
||||
for source in $(dpkg-query -L "$package"); do
|
||||
if [ "$package" = "coreutils" ]; then
|
||||
allowed=0
|
||||
# shellcheck disable=SC2086
|
||||
for candidate in $coreutils_files; do
|
||||
if [ "$source" = "$candidate" ]; then
|
||||
allowed=1
|
||||
break
|
||||
fi
|
||||
done
|
||||
[ "$allowed" -eq 1 ] || continue
|
||||
fi
|
||||
|
||||
if [ ! -f "$source" ] && [ ! -L "$source" ]; then
|
||||
continue
|
||||
fi
|
||||
|
||||
directory="$(readlink -f "$(dirname -- "$source")")"
|
||||
base="$(basename -- "$source")"
|
||||
if [ "$directory" = "/" ]; then
|
||||
path="/$base"
|
||||
parent="$dest"
|
||||
else
|
||||
path="$directory/$base"
|
||||
parent="$dest$directory"
|
||||
fi
|
||||
|
||||
# Several packages list the same merged-/usr symlink; keep the first
|
||||
# copy and skip duplicates so the manifest has one row per path.
|
||||
if [ -e "$dest$path" ] || [ -L "$dest$path" ]; then
|
||||
continue
|
||||
fi
|
||||
|
||||
mkdir -p "$parent"
|
||||
cp -a --no-target-directory -- "$source" "$dest$path"
|
||||
|
||||
if [ -L "$source" ]; then
|
||||
digest="$(readlink -- "$source")"
|
||||
else
|
||||
digest="$(sha256sum -- "$source")"
|
||||
digest="${digest%% *}"
|
||||
fi
|
||||
printf '%s\t%s\t%s\n' "$package" "$path" "$digest" >> "$inventory"
|
||||
done
|
||||
done
|
||||
|
||||
# Docker mounts /etc/hosts and /etc/resolv.conf, but the image still needs the
|
||||
# root account and a name-service switch policy. `hosts: files dns` is required
|
||||
# for getaddrinfo to fall back to DNS for outbound requests.
|
||||
printf 'root:x:0:0:root:/root:/bin/sh\n' > "$dest/etc/passwd"
|
||||
printf 'root:x:0:\n' > "$dest/etc/group"
|
||||
printf 'passwd: files\ngroup: files\nhosts: files dns\n' > "$dest/etc/nsswitch.conf"
|
||||
|
||||
for generated in /etc/passwd /etc/group /etc/nsswitch.conf; do
|
||||
digest="$(sha256sum -- "$dest$generated")"
|
||||
digest="${digest%% *}"
|
||||
printf 'runtime-generated\t%s\t%s\n' "$generated" "$digest" >> "$inventory"
|
||||
done
|
||||
|
||||
count="$(grep -c '^Package: ' "$status")"
|
||||
if [ "$count" -ne "$expected_packages" ]; then
|
||||
echo "dpkg status holds $count packages, expected $expected_packages" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Merged-/usr and shell-entrypoint contracts must hold in the assembled rootfs.
|
||||
for link in bin lib lib64 sbin; do
|
||||
if [ ! -L "$dest/$link" ]; then
|
||||
echo "merged-/usr symlink /$link missing from runtime rootfs" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
for exe in usr/bin/sh usr/bin/mkdir usr/bin/chmod usr/bin/env usr/bin/bash; do
|
||||
if [ ! -x "$dest/$exe" ]; then
|
||||
echo "runtime shell or coreutils subset missing: /$exe" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$(grep -c . "$inventory")" -eq 0 ]; then
|
||||
echo "runtime inventory is empty" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
printf 'runtime-inventory: %s files\n' "$(grep -c . "$inventory")"
|
||||
+289
-11
@@ -1,4 +1,30 @@
|
||||
#!/bin/sh
|
||||
# Scan the built Crank server images with a pinned Trivy and fail closed.
|
||||
#
|
||||
# The wrapper downloads and checksum-verifies one fixed Trivy release, downloads
|
||||
# one fresh vulnerability database, then scans every requested image by its
|
||||
# immutable Docker id with a fully pinned policy. It never trusts a local
|
||||
# trivy.yaml, .trivyignore, VEX file or skip list: --config and --ignorefile
|
||||
# point at /dev/null and every inherited TRIVY_* variable is removed before
|
||||
# Trivy runs. Docker context and proxy variables are preserved.
|
||||
#
|
||||
# Artifacts are written to the evidence directory (default
|
||||
# .tmp/image-scan-evidence, relocatable only through CRANK_IMAGE_SCAN_OUTPUT_DIR)
|
||||
# and are kept even when the gate is red:
|
||||
#
|
||||
# db/metadata.json copy of the actual downloaded Trivy DB metadata
|
||||
# db-download.log database download log
|
||||
# scanner.json pinned scanner version and scan policy receipt
|
||||
# <NN-slug>.json raw Trivy JSON report per image
|
||||
# <NN-slug>.scan.log Trivy scan log per image
|
||||
# <NN-slug>.gate.log checker output per image
|
||||
# <NN-slug>.decision.json checker decision per image
|
||||
# receipt.json aggregate tag<->immutable id<->raw<->decision receipt
|
||||
#
|
||||
# Every scan is finished by the accepted checker (scripts/check-image-scan.py),
|
||||
# which owns the PASS/BLOCKED/ERROR decision and the DB-age check. The wrapper
|
||||
# exits 0 only when every image passed, 1 when at least one image is blocked and
|
||||
# 2 on any bootstrap, scan or evidence error.
|
||||
set -eu
|
||||
|
||||
if [ "$#" -eq 0 ]; then
|
||||
@@ -6,24 +32,276 @@ if [ "$#" -eq 0 ]; then
|
||||
exit 2
|
||||
fi
|
||||
|
||||
# Strip inherited TRIVY_* overrides so neither the environment nor a local Trivy
|
||||
# config can loosen the policy. Only names are read; no values are logged.
|
||||
for name in $(env | sed -n 's/^\(TRIVY_[A-Za-z0-9_]*\)=.*/\1/p'); do
|
||||
unset "$name"
|
||||
done
|
||||
|
||||
script_dir="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
|
||||
checker="$script_dir/check-image-scan.py"
|
||||
|
||||
trivy_version="0.70.0"
|
||||
archive="trivy_${trivy_version}_Linux-64bit.tar.gz"
|
||||
expected_sha256="8b4376d5d6befe5c24d503f10ff136d9e0c49f9127a4279fd110b727929a5aa9"
|
||||
download_url="https://github.com/aquasecurity/trivy/releases/download/v${trivy_version}/${archive}"
|
||||
|
||||
output_dir="${CRANK_IMAGE_SCAN_OUTPUT_DIR:-.tmp/image-scan-evidence}"
|
||||
if ! mkdir -p "$output_dir"; then
|
||||
echo "scan-images: cannot create evidence directory $output_dir" >&2
|
||||
exit 2
|
||||
fi
|
||||
if ! output_dir="$(CDPATH= cd -- "$output_dir" && pwd)"; then
|
||||
echo "scan-images: cannot resolve evidence directory $output_dir" >&2
|
||||
exit 2
|
||||
fi
|
||||
# Each invocation owns a fresh artifact directory. An absent new report can
|
||||
# never be mistaken for a successful report left by a previous invocation.
|
||||
if ! output_dir="$(mktemp -d "$output_dir/run.XXXXXX")"; then
|
||||
echo "scan-images: cannot create a fresh evidence run directory" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
temp_dir="$(mktemp -d)"
|
||||
trap 'rm -rf "$temp_dir"' EXIT HUP INT TERM
|
||||
cache_dir="$temp_dir/trivy-cache"
|
||||
mkdir -p "$cache_dir"
|
||||
cleanup() { rm -rf "$temp_dir"; }
|
||||
trap cleanup EXIT HUP INT TERM
|
||||
|
||||
curl --fail --silent --show-error --location \
|
||||
"https://github.com/aquasecurity/trivy/releases/download/v${trivy_version}/${archive}" \
|
||||
--output "$temp_dir/$archive"
|
||||
printf '%s %s\n' "$expected_sha256" "$temp_dir/$archive" | sha256sum --check --status
|
||||
tar -C "$temp_dir" -xzf "$temp_dir/$archive" trivy
|
||||
requested="$temp_dir/requested-images.txt"
|
||||
printf '%s\n' "$@" > "$requested"
|
||||
records="$temp_dir/records.jsonl"
|
||||
: > "$records"
|
||||
|
||||
# Bootstrap failures still produce a receipt naming every requested image.
|
||||
fail_all() {
|
||||
reason="$1"
|
||||
python3 - "$output_dir/receipt.json" "$reason" "$requested" <<'PY'
|
||||
import json
|
||||
import sys
|
||||
|
||||
receipt_path, reason, requested_path = sys.argv[1:4]
|
||||
with open(requested_path, encoding="utf-8") as stream:
|
||||
images = [line for line in stream.read().splitlines() if line]
|
||||
receipt = {
|
||||
"schema": "crank.image-scan.receipt.v1",
|
||||
"error": reason,
|
||||
"overall": {"status": "error", "exit_code": 2},
|
||||
"images": [
|
||||
{"index": index + 1, "tag": tag, "status": "error", "error": reason}
|
||||
for index, tag in enumerate(images)
|
||||
],
|
||||
}
|
||||
with open(receipt_path, "w", encoding="utf-8") as stream:
|
||||
json.dump(receipt, stream, indent=2, sort_keys=True)
|
||||
stream.write("\n")
|
||||
PY
|
||||
echo "scan-images: $reason" >&2
|
||||
exit 2
|
||||
}
|
||||
|
||||
# Download and checksum-verify the pinned scanner exactly once.
|
||||
if ! curl --fail --silent --show-error --location --max-time 300 \
|
||||
"$download_url" --output "$temp_dir/$archive" \
|
||||
>"$output_dir/scanner-download.log" 2>&1; then
|
||||
fail_all "could not download pinned Trivy ${trivy_version}"
|
||||
fi
|
||||
if ! printf '%s %s\n' "$expected_sha256" "$temp_dir/$archive" \
|
||||
| sha256sum --check --status; then
|
||||
fail_all "pinned Trivy archive checksum mismatch"
|
||||
fi
|
||||
trivy_bin="$temp_dir/trivy"
|
||||
if ! tar -C "$temp_dir" -xzf "$temp_dir/$archive" trivy; then
|
||||
fail_all "could not extract the pinned Trivy archive"
|
||||
fi
|
||||
if [ ! -x "$trivy_bin" ]; then
|
||||
fail_all "pinned Trivy executable is missing after extraction"
|
||||
fi
|
||||
|
||||
# Download one fresh vulnerability database; every scan reuses it read-only.
|
||||
if ! "$trivy_bin" image --config /dev/null --download-db-only --cache-dir "$cache_dir" \
|
||||
--no-progress --skip-version-check \
|
||||
>"$output_dir/db-download.log" 2>&1; then
|
||||
fail_all "could not download the Trivy vulnerability database"
|
||||
fi
|
||||
db_metadata="$output_dir/db/metadata.json"
|
||||
mkdir -p "$output_dir/db"
|
||||
if ! cp "$cache_dir/db/metadata.json" "$db_metadata"; then
|
||||
fail_all "Trivy database metadata was not produced"
|
||||
fi
|
||||
|
||||
if ! version_output="$("$trivy_bin" --config /dev/null --cache-dir "$cache_dir" --version 2>&1)"; then
|
||||
fail_all "could not read pinned Trivy version"
|
||||
fi
|
||||
reported_version="$(printf '%s\n' "$version_output" | sed -n 's/^Version:[[:space:]]*//p' | head -n 1)"
|
||||
if [ "$reported_version" != "$trivy_version" ]; then
|
||||
fail_all "pinned Trivy reported an unexpected version"
|
||||
fi
|
||||
python3 - "$output_dir/scanner.json" "$trivy_version" "$expected_sha256" \
|
||||
"$archive" "$version_output" <<'PY'
|
||||
import json
|
||||
import sys
|
||||
|
||||
path, expected, digest, archive, reported = sys.argv[1:6]
|
||||
reported_version = next(
|
||||
(line.strip() for line in reported.splitlines() if line.strip()), ""
|
||||
)
|
||||
payload = {
|
||||
"schema": "crank.image-scan.scanner.v1",
|
||||
"expected_version": expected,
|
||||
"reported_version": reported_version,
|
||||
"archive": archive,
|
||||
"archive_sha256": digest,
|
||||
"policy": {
|
||||
"image_source": "docker",
|
||||
"config": "/dev/null",
|
||||
"ignorefile": "/dev/null",
|
||||
"ignore_unfixed": False,
|
||||
"list_all_pkgs": True,
|
||||
"severities": ["UNKNOWN", "LOW", "MEDIUM", "HIGH", "CRITICAL"],
|
||||
"scanners": ["vuln"],
|
||||
"skip_db_update": True,
|
||||
"skip_version_check": True,
|
||||
},
|
||||
}
|
||||
with open(path, "w", encoding="utf-8") as stream:
|
||||
json.dump(payload, stream, indent=2, sort_keys=True)
|
||||
stream.write("\n")
|
||||
PY
|
||||
|
||||
overall_rc=0
|
||||
index=0
|
||||
for image in "$@"; do
|
||||
"$temp_dir/trivy" image \
|
||||
--exit-code 1 \
|
||||
--ignore-unfixed \
|
||||
--severity HIGH,CRITICAL \
|
||||
index=$((index + 1))
|
||||
slug="$(printf '%s' "$image" \
|
||||
| sed 's/[^A-Za-z0-9._-]/_/g; s/^[.-]*//; s/[.-]*$//' \
|
||||
| cut -c1-80)"
|
||||
[ -n "$slug" ] || slug="image"
|
||||
base="$(printf '%02d' "$index")-$slug"
|
||||
raw="$output_dir/$base.json"
|
||||
scan_log="$output_dir/$base.scan.log"
|
||||
gate_log="$output_dir/$base.gate.log"
|
||||
decision="$output_dir/$base.decision.json"
|
||||
|
||||
image_id="$(docker image inspect --format '{{.Id}}' "$image" \
|
||||
2>"$output_dir/$base.inspect.log" || true)"
|
||||
image_id="$(printf '%s' "$image_id" | tr -d '[:space:]')"
|
||||
|
||||
scan_rc=0
|
||||
if [ -z "$image_id" ]; then
|
||||
scan_rc=2
|
||||
printf 'scan-images: cannot resolve an immutable id for %s\n' "$image" >&2
|
||||
elif "$trivy_bin" image \
|
||||
--image-src docker \
|
||||
--config /dev/null \
|
||||
--ignorefile /dev/null \
|
||||
--ignore-unfixed=false \
|
||||
--list-all-pkgs=true \
|
||||
--severity UNKNOWN,LOW,MEDIUM,HIGH,CRITICAL \
|
||||
--scanners vuln \
|
||||
--format json \
|
||||
--exit-code 0 \
|
||||
--skip-db-update \
|
||||
--cache-dir "$cache_dir" \
|
||||
--no-progress \
|
||||
"$image"
|
||||
--skip-version-check \
|
||||
--output "$raw" \
|
||||
"$image_id" >"$scan_log" 2>&1; then
|
||||
scan_rc=0
|
||||
else
|
||||
scan_rc=$?
|
||||
fi
|
||||
|
||||
# The checker is always invoked so every image gets a decision artifact,
|
||||
# even when the scan itself failed. Missing or malformed evidence is
|
||||
# reported by the checker itself with exit code 2.
|
||||
if gate_output="$(python3 "$checker" \
|
||||
--report "$raw" \
|
||||
--image-id "$image_id" \
|
||||
--db-metadata "$db_metadata" \
|
||||
--decision "$decision" 2>&1)"; then
|
||||
gate_rc=0
|
||||
else
|
||||
gate_rc=$?
|
||||
fi
|
||||
printf '%s\n' "$gate_output" >"$gate_log"
|
||||
printf '%s\n' "$gate_output"
|
||||
|
||||
effective_rc="$gate_rc"
|
||||
if [ "$scan_rc" -ne 0 ] && [ "$effective_rc" -lt 2 ]; then
|
||||
effective_rc=2
|
||||
fi
|
||||
if [ "$effective_rc" -gt "$overall_rc" ]; then
|
||||
overall_rc="$effective_rc"
|
||||
fi
|
||||
|
||||
case "$effective_rc" in
|
||||
0) status="pass" ;;
|
||||
1) status="blocked" ;;
|
||||
*) status="error" ;;
|
||||
esac
|
||||
|
||||
python3 - "$records" "$index" "$image" "$image_id" "$raw" "$scan_log" \
|
||||
"$gate_log" "$decision" "$scan_rc" "$gate_rc" "$status" <<'PY'
|
||||
import json
|
||||
import sys
|
||||
|
||||
(
|
||||
records_path, index, tag, image_id, raw, scan_log, gate_log, decision,
|
||||
scan_exit, gate_exit, status,
|
||||
) = sys.argv[1:12]
|
||||
record = {
|
||||
"index": int(index),
|
||||
"tag": tag,
|
||||
"image_id": image_id or None,
|
||||
"raw": raw,
|
||||
"scan_log": scan_log,
|
||||
"gate_log": gate_log,
|
||||
"decision": decision,
|
||||
"scan_exit": int(scan_exit),
|
||||
"gate_exit": int(gate_exit),
|
||||
"status": status,
|
||||
}
|
||||
with open(records_path, "a", encoding="utf-8") as stream:
|
||||
stream.write(json.dumps(record) + "\n")
|
||||
PY
|
||||
done
|
||||
|
||||
case "$overall_rc" in
|
||||
0) overall_status="pass" ;;
|
||||
1) overall_status="blocked" ;;
|
||||
*) overall_status="error" ;;
|
||||
esac
|
||||
|
||||
python3 - "$records" "$output_dir/receipt.json" "$db_metadata" \
|
||||
"$output_dir/scanner.json" "$overall_rc" "$overall_status" "$output_dir" <<'PY'
|
||||
import json
|
||||
import sys
|
||||
|
||||
records_path, receipt_path, db_path, scanner_path, exit_code, status, out_dir = (
|
||||
sys.argv[1:8]
|
||||
)
|
||||
with open(records_path, encoding="utf-8") as stream:
|
||||
images = [json.loads(line) for line in stream if line.strip()]
|
||||
with open(scanner_path, encoding="utf-8") as stream:
|
||||
scanner = json.load(stream)
|
||||
with open(db_path, encoding="utf-8") as stream:
|
||||
db_metadata = json.load(stream)
|
||||
receipt = {
|
||||
"schema": "crank.image-scan.receipt.v1",
|
||||
"output_dir": out_dir,
|
||||
"scanner": scanner,
|
||||
"database": {
|
||||
"metadata_path": db_path,
|
||||
"updated_at": db_metadata.get("UpdatedAt"),
|
||||
},
|
||||
"overall": {"status": status, "exit_code": int(exit_code)},
|
||||
"images": images,
|
||||
}
|
||||
with open(receipt_path, "w", encoding="utf-8") as stream:
|
||||
json.dump(receipt, stream, indent=2, sort_keys=True)
|
||||
stream.write("\n")
|
||||
PY
|
||||
|
||||
printf 'scan-images: %s (%s/receipt.json)\n' "$overall_status" "$output_dir"
|
||||
exit "$overall_rc"
|
||||
@@ -0,0 +1,777 @@
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
SCRIPT = Path(__file__).parents[2] / "scripts" / "check-image-scan.py"
|
||||
|
||||
|
||||
def load_checker():
|
||||
spec = importlib.util.spec_from_file_location("check_image_scan", SCRIPT)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
IMAGE_ID = "sha256:" + "a" * 64
|
||||
CID = "0123456789ab"
|
||||
|
||||
EXPECTED_PACKAGES = (
|
||||
"base-files",
|
||||
"libc6",
|
||||
"libgcc-s1",
|
||||
"gcc-12-base",
|
||||
"bash",
|
||||
"dash",
|
||||
"libtinfo6",
|
||||
"libselinux1",
|
||||
"libpcre2-8-0",
|
||||
"coreutils",
|
||||
)
|
||||
|
||||
MANIFEST_PATH = "/usr/share/crank/runtime-inventory.tsv"
|
||||
DPKG_STATUS_PATH = "/var/lib/dpkg/status"
|
||||
|
||||
FAKE_DOCKER = '''#!/usr/bin/env python3
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
args = sys.argv[1:]
|
||||
log = os.environ.get("FAKE_DOCKER_LOG")
|
||||
if log:
|
||||
with open(log, "a", encoding="utf-8") as stream:
|
||||
stream.write(json.dumps(args) + "\\n")
|
||||
if not args:
|
||||
sys.exit(2)
|
||||
command = args[0]
|
||||
if command == "create":
|
||||
rc = int(os.environ.get("FAKE_DOCKER_CREATE_RC", "0"))
|
||||
if rc != 0:
|
||||
sys.stderr.write("create failed\\n")
|
||||
sys.exit(rc)
|
||||
sys.stdout.write(os.environ.get("FAKE_DOCKER_CID", "deadbeefcafe") + "\\n")
|
||||
sys.exit(0)
|
||||
if command == "export":
|
||||
rc = int(os.environ.get("FAKE_DOCKER_EXPORT_RC", "0"))
|
||||
if rc != 0:
|
||||
sys.stderr.write("export failed\\n")
|
||||
sys.exit(rc)
|
||||
with open(os.environ["FAKE_DOCKER_TAR"], "rb") as stream:
|
||||
sys.stdout.buffer.write(stream.read())
|
||||
sys.exit(0)
|
||||
if command == "rm":
|
||||
sys.exit(0)
|
||||
sys.exit(2)
|
||||
'''
|
||||
|
||||
|
||||
def sha256(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def build_tar(entries) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
with tarfile.open(fileobj=buffer, mode="w") as archive:
|
||||
for kind, path, value in entries:
|
||||
info = tarfile.TarInfo(path.lstrip("/"))
|
||||
info.mode = 0o644
|
||||
info.uid = 0
|
||||
info.gid = 0
|
||||
if kind == "file":
|
||||
data = value if isinstance(value, bytes) else value.encode("utf-8")
|
||||
info.type = tarfile.REGTYPE
|
||||
info.size = len(data)
|
||||
archive.addfile(info, io.BytesIO(data))
|
||||
elif kind == "symlink":
|
||||
info.type = tarfile.SYMTYPE
|
||||
info.linkname = value
|
||||
info.size = 0
|
||||
archive.addfile(info)
|
||||
elif kind == "dir":
|
||||
# Emulate Go's tar writer, which marks directories with a slash.
|
||||
info.name = path.lstrip("/") + "/"
|
||||
info.type = tarfile.DIRTYPE
|
||||
info.size = 0
|
||||
archive.addfile(info)
|
||||
else:
|
||||
raise AssertionError(f"unknown entry kind {kind}")
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def build_status(packages, versions=None) -> str:
|
||||
versions = versions or {}
|
||||
blocks = []
|
||||
for name in packages:
|
||||
blocks.append(
|
||||
"Package: {name}\n"
|
||||
"Status: install ok installed\n"
|
||||
"Architecture: amd64\n"
|
||||
"Version: {version}\n"
|
||||
"Description: test package\n".format(
|
||||
name=name, version=versions.get(name, "6.4-4" if name == "libtinfo6" else "1.2.3-1")
|
||||
)
|
||||
)
|
||||
return "\n".join(blocks)
|
||||
|
||||
|
||||
def runtime_image(
|
||||
*,
|
||||
manifest_text=None,
|
||||
status_text=None,
|
||||
extra_entries=(),
|
||||
drop_manifest=False,
|
||||
drop_status=False,
|
||||
drop_files=(),
|
||||
):
|
||||
entries = []
|
||||
manifest_lines = []
|
||||
for package in EXPECTED_PACKAGES:
|
||||
path = f"/usr/share/crank/{package}.payload"
|
||||
data = f"{package} payload\n".encode("utf-8")
|
||||
entries.append(("file", path, data))
|
||||
manifest_lines.append(f"{package}\t{path}\t{sha256(data)}")
|
||||
entries.append(("symlink", "/usr/bin/sh", "dash"))
|
||||
manifest_lines.append("dash\t/usr/bin/sh\tdash")
|
||||
entries.append(("dir", "/usr/bin", None))
|
||||
entries.append(("dir", "/usr/share/crank", None))
|
||||
for path in ("/etc/passwd", "/etc/group", "/etc/nsswitch.conf"):
|
||||
data = f"{path} generated\n".encode("utf-8")
|
||||
entries.append(("file", path, data))
|
||||
manifest_lines.append(f"runtime-generated\t{path}\t{sha256(data)}")
|
||||
entries.extend(tuple(extra_entries))
|
||||
if manifest_text is None:
|
||||
manifest_text = "".join(line + "\n" for line in manifest_lines)
|
||||
if not drop_manifest:
|
||||
entries.append(("file", MANIFEST_PATH, manifest_text.encode("utf-8")))
|
||||
if status_text is None:
|
||||
status_text = build_status(EXPECTED_PACKAGES)
|
||||
if not drop_status:
|
||||
entries.append(("file", DPKG_STATUS_PATH, status_text.encode("utf-8")))
|
||||
kept = set(drop_files)
|
||||
return [entry for entry in entries if entry[1] not in kept]
|
||||
|
||||
|
||||
def vulnerability(
|
||||
vulnerability_id="CVE-2024-9999",
|
||||
package="libc6",
|
||||
installed="1.2.3-1",
|
||||
severity="HIGH",
|
||||
fixed=None,
|
||||
status="affected",
|
||||
):
|
||||
record = {
|
||||
"VulnerabilityID": vulnerability_id,
|
||||
"PkgName": package,
|
||||
"InstalledVersion": installed,
|
||||
"Severity": severity,
|
||||
"Status": status,
|
||||
"Title": "test finding",
|
||||
}
|
||||
if fixed is not None:
|
||||
record["FixedVersion"] = fixed
|
||||
return record
|
||||
|
||||
|
||||
def make_report(
|
||||
*,
|
||||
image_id=IMAGE_ID,
|
||||
artifact_type="container_image",
|
||||
os_family="debian",
|
||||
os_name="12.11",
|
||||
include_os=True,
|
||||
include_metadata=True,
|
||||
include_results=True,
|
||||
packages=None,
|
||||
vulnerabilities=None,
|
||||
results=None,
|
||||
):
|
||||
if packages is None:
|
||||
packages = [
|
||||
{"ID": f"{name}@1.2.3-1", "Name": name, "Version": "6.4-4" if name == "libtinfo6" else "1.2.3-1", "Arch": "amd64"}
|
||||
for name in EXPECTED_PACKAGES
|
||||
]
|
||||
result = {
|
||||
"Target": "crank/test",
|
||||
"Class": "os-pkgs",
|
||||
"Type": os_family,
|
||||
"Packages": packages,
|
||||
}
|
||||
if vulnerabilities is not None:
|
||||
result["Vulnerabilities"] = vulnerabilities
|
||||
report = {
|
||||
"SchemaVersion": 2,
|
||||
"ArtifactName": "crank/test",
|
||||
"ArtifactType": artifact_type,
|
||||
}
|
||||
if include_metadata:
|
||||
metadata = {"ImageID": image_id, "RepoTags": ["crank/test:ci"]}
|
||||
if include_os:
|
||||
metadata["OS"] = {"Family": os_family, "Name": os_name}
|
||||
report["Metadata"] = metadata
|
||||
if include_results:
|
||||
report["Results"] = [result] if results is None else results
|
||||
return report
|
||||
|
||||
|
||||
class ImageScanCheckerTests(unittest.TestCase):
|
||||
def run_check(
|
||||
self,
|
||||
*,
|
||||
report=None,
|
||||
report_raw=None,
|
||||
db_updated=None,
|
||||
db_raw=None,
|
||||
tar_bytes=None,
|
||||
image_id=IMAGE_ID,
|
||||
extra_env=None,
|
||||
decision_alias=None,
|
||||
):
|
||||
root = Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, root, ignore_errors=True)
|
||||
|
||||
report_path = root / "report.json"
|
||||
if report_raw is not None:
|
||||
report_path.write_text(report_raw, encoding="utf-8")
|
||||
else:
|
||||
report_path.write_text(json.dumps(report), encoding="utf-8")
|
||||
|
||||
db_path = root / "db.json"
|
||||
if db_raw is not None:
|
||||
db_path.write_text(db_raw, encoding="utf-8")
|
||||
else:
|
||||
updated = db_updated if db_updated is not None else datetime.now(timezone.utc)
|
||||
db_path.write_text(
|
||||
json.dumps({"Version": 2, "UpdatedAt": updated.isoformat()}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
tar_path = root / "image.tar"
|
||||
if tar_bytes is None:
|
||||
tar_bytes = build_tar(runtime_image())
|
||||
tar_path.write_bytes(tar_bytes)
|
||||
|
||||
bin_dir = root / "bin"
|
||||
bin_dir.mkdir()
|
||||
docker = bin_dir / "docker"
|
||||
docker.write_text(FAKE_DOCKER, encoding="utf-8")
|
||||
docker.chmod(0o755)
|
||||
|
||||
log = root / "docker.jsonl"
|
||||
env = os.environ.copy()
|
||||
env["PATH"] = f"{bin_dir}:{env['PATH']}"
|
||||
env["FAKE_DOCKER_TAR"] = str(tar_path)
|
||||
env["FAKE_DOCKER_CID"] = CID
|
||||
env["FAKE_DOCKER_LOG"] = str(log)
|
||||
if extra_env:
|
||||
env.update(extra_env)
|
||||
|
||||
decision_path = root / "decision.json"
|
||||
if decision_alias == "report":
|
||||
decision_path = report_path
|
||||
elif decision_alias == "db":
|
||||
decision_path = db_path
|
||||
elif decision_alias == "symlink":
|
||||
decision_path.symlink_to(report_path)
|
||||
result = subprocess.run(
|
||||
[
|
||||
"python3",
|
||||
str(SCRIPT),
|
||||
"--report",
|
||||
str(report_path),
|
||||
"--image-id",
|
||||
image_id,
|
||||
"--db-metadata",
|
||||
str(db_path),
|
||||
"--decision",
|
||||
str(decision_path),
|
||||
],
|
||||
text=True,
|
||||
capture_output=True,
|
||||
env=env,
|
||||
check=False,
|
||||
)
|
||||
decision = None
|
||||
if decision_path.exists():
|
||||
decision = json.loads(decision_path.read_text(encoding="utf-8"))
|
||||
calls = []
|
||||
if log.exists():
|
||||
calls = [
|
||||
json.loads(line)
|
||||
for line in log.read_text(encoding="utf-8").splitlines()
|
||||
if line.strip()
|
||||
]
|
||||
return result, decision, root, calls
|
||||
|
||||
# ------------------------------------------------------------------ pass
|
||||
def test_decision_alias_never_changes_protected_input(self):
|
||||
report = make_report()
|
||||
for alias in ("report", "db", "symlink"):
|
||||
with self.subTest(alias=alias):
|
||||
result, _, root, _ = self.run_check(report=report, decision_alias=alias)
|
||||
self.assertEqual(result.returncode, 2)
|
||||
self.assertEqual(json.loads((root / "report.json").read_text()), report)
|
||||
self.assertEqual(json.loads((root / "db.json").read_text())["Version"], 2)
|
||||
|
||||
def test_malformed_package_records_are_evidence_errors(self):
|
||||
for package in (None, {}, {"Name": ""}, {"Name": "bash"}, {"Name": "bash", "Version": 3}):
|
||||
with self.subTest(package=package):
|
||||
result, decision, _, _ = self.run_check(report=make_report(os_family="alpine", os_name="3.23", packages=[package]))
|
||||
self.assertEqual(result.returncode, 2)
|
||||
self.assertEqual(decision["status"], "error")
|
||||
|
||||
def test_package_versions_must_match_exported_status(self):
|
||||
report = make_report()
|
||||
report["Results"][0]["Packages"][0]["Version"] = "999.0"
|
||||
result, decision, _, _ = self.run_check(report=report)
|
||||
self.assertEqual(result.returncode, 2)
|
||||
self.assertEqual(decision["status"], "error")
|
||||
|
||||
def test_exception_requires_actual_libtinfo_version(self):
|
||||
report = make_report(vulnerabilities=[vulnerability(vulnerability_id="CVE-2025-69720", package="libtinfo6", installed="6.4-4")])
|
||||
report["Results"][0]["Packages"] = [dict(p, Version="9.9") if p["Name"] == "libtinfo6" else p for p in report["Results"][0]["Packages"]]
|
||||
tar = build_tar(runtime_image(status_text=build_status(EXPECTED_PACKAGES, {"libtinfo6": "9.9"})))
|
||||
result, decision, _, _ = self.run_check(report=report, tar_bytes=tar)
|
||||
self.assertEqual(result.returncode, 1)
|
||||
self.assertEqual(decision["exceptions"], [])
|
||||
|
||||
def test_debian_129_is_not_the_debian12_exception(self):
|
||||
report = make_report(os_name="129", vulnerabilities=[vulnerability(vulnerability_id="CVE-2025-69720", package="libtinfo6", installed="6.4-4")])
|
||||
result, decision, _, _ = self.run_check(report=report)
|
||||
self.assertEqual(result.returncode, 1)
|
||||
self.assertEqual(decision["exceptions"], [])
|
||||
|
||||
def test_duplicate_json_keys_are_evidence_errors(self):
|
||||
payload = json.dumps(make_report())
|
||||
payload = payload[:-1] + ',"ArtifactType":"container_image"}'
|
||||
result, decision, _, _ = self.run_check(report_raw=payload)
|
||||
self.assertEqual(result.returncode, 2)
|
||||
self.assertEqual(decision["status"], "error")
|
||||
|
||||
def test_invalid_timezone_produces_error_decision(self):
|
||||
result, decision, _, _ = self.run_check(report=make_report(), db_raw='{"Version":2,"UpdatedAt":"2026-10-10T00:00:00+99:99"}')
|
||||
self.assertEqual(result.returncode, 2)
|
||||
self.assertEqual(decision["status"], "error")
|
||||
|
||||
def test_unsupported_db_schema_is_evidence_error(self):
|
||||
for version in (None, True, "2", 3):
|
||||
with self.subTest(version=version):
|
||||
metadata = {"Version": version, "UpdatedAt": datetime.now(timezone.utc).isoformat()}
|
||||
result, decision, _, _ = self.run_check(report=make_report(), db_raw=json.dumps(metadata))
|
||||
self.assertEqual(result.returncode, 2)
|
||||
self.assertEqual(decision["status"], "error")
|
||||
|
||||
def test_manifest_cannot_omit_a_transferred_file(self):
|
||||
entries = runtime_image()
|
||||
changed = []
|
||||
for kind, path, value in entries:
|
||||
if path == MANIFEST_PATH:
|
||||
value = "\n".join(value.decode().splitlines()[1:]).encode() + b"\n"
|
||||
changed.append((kind, path, value))
|
||||
result, decision, _, _ = self.run_check(report=make_report(), tar_bytes=build_tar(changed))
|
||||
self.assertEqual(result.returncode, 2)
|
||||
self.assertEqual(decision["status"], "error")
|
||||
|
||||
def test_undeclared_runtime_file_is_evidence_error(self):
|
||||
tar = build_tar(runtime_image(extra_entries=[("file", "/usr/lib/undeclared.so", b"file")]))
|
||||
result, decision, _, _ = self.run_check(report=make_report(), tar_bytes=tar)
|
||||
self.assertEqual(result.returncode, 2)
|
||||
self.assertEqual(decision["status"], "error")
|
||||
|
||||
def test_unexpected_dpkg_package_is_evidence_error(self):
|
||||
tar = build_tar(runtime_image(status_text=build_status(EXPECTED_PACKAGES + ("unexpected",))))
|
||||
result, decision, _, _ = self.run_check(report=make_report(), tar_bytes=tar)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
self.assertEqual(decision["status"], "error")
|
||||
|
||||
def test_unexpected_trivy_package_is_evidence_error(self):
|
||||
report = make_report()
|
||||
report["Results"][0]["Packages"].append({"Name": "unexpected", "Version": "1"})
|
||||
result, decision, _, _ = self.run_check(report=report)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
self.assertEqual(decision["status"], "error")
|
||||
|
||||
def test_stalled_export_has_a_deadline(self):
|
||||
module = load_checker()
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
docker = Path(directory) / "docker"
|
||||
docker.write_text("#!/usr/bin/env python3\nimport time\ntime.sleep(2)\n")
|
||||
docker.chmod(0o755)
|
||||
with mock.patch.dict(os.environ, {"PATH": directory + ":" + os.environ["PATH"]}), \
|
||||
mock.patch.object(module, "DOCKER_TIMEOUT_SECONDS", 0.1):
|
||||
with self.assertRaisesRegex(module.EvidenceError, "timed out"):
|
||||
module._docker_export(CID)
|
||||
|
||||
def test_clean_runtime_image_passes_and_verifies_real_files(self):
|
||||
result, decision, _, calls = self.run_check(report=make_report())
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(decision["status"], "pass")
|
||||
self.assertEqual(decision["exit_code"], 0)
|
||||
self.assertIn(["create", "--entrypoint", "/bin/sh", IMAGE_ID], calls)
|
||||
self.assertIn(["export", CID], calls)
|
||||
self.assertIn(["rm", CID], calls)
|
||||
self.assertGreater(decision["runtime_inventory"]["manifest_entries"], 0)
|
||||
|
||||
def test_narrow_libtinfo_exception_passes_with_image_bound_justification(self):
|
||||
report = make_report(
|
||||
vulnerabilities=[
|
||||
vulnerability(
|
||||
vulnerability_id="CVE-2025-69720",
|
||||
package="libtinfo6",
|
||||
installed="6.4-4",
|
||||
severity="HIGH",
|
||||
)
|
||||
]
|
||||
)
|
||||
result, decision, _, _ = self.run_check(report=report)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(decision["status"], "pass")
|
||||
self.assertEqual(len(decision["exceptions"]), 1)
|
||||
exception = decision["exceptions"][0]
|
||||
self.assertEqual(exception["vulnerability_id"], "CVE-2025-69720")
|
||||
self.assertEqual(exception["image_id"], IMAGE_ID)
|
||||
self.assertTrue(exception["justification"])
|
||||
self.assertEqual(decision["high_critical"][0]["disposition"], "excepted")
|
||||
|
||||
def test_absent_vulnerabilities_with_packages_is_a_valid_empty_result(self):
|
||||
result, decision, _, _ = self.run_check(report=make_report())
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(decision["severity_counts"]["HIGH"], 0)
|
||||
|
||||
def test_only_medium_low_unknown_findings_pass_and_are_counted(self):
|
||||
report = make_report(
|
||||
vulnerabilities=[
|
||||
vulnerability(package="libc6", severity="MEDIUM"),
|
||||
vulnerability(package="bash", severity="LOW"),
|
||||
vulnerability(package="dash", severity="UNKNOWN"),
|
||||
]
|
||||
)
|
||||
result, decision, _, _ = self.run_check(report=report)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(decision["severity_counts"]["MEDIUM"], 1)
|
||||
self.assertEqual(decision["severity_counts"]["LOW"], 1)
|
||||
self.assertEqual(decision["severity_counts"]["UNKNOWN"], 1)
|
||||
self.assertEqual(decision["blocking"], [])
|
||||
|
||||
def test_non_debian_image_skips_runtime_manifest(self):
|
||||
report = make_report(
|
||||
os_family="alpine",
|
||||
os_name="3.24",
|
||||
packages=[{"ID": "musl@1.2", "Name": "musl", "Version": "1.2"}],
|
||||
)
|
||||
result, decision, _, calls = self.run_check(
|
||||
report=report, tar_bytes=build_tar([("file", "/bin/sh", b"busybox")])
|
||||
)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(calls, [])
|
||||
|
||||
# --------------------------------------------------------------- blocked
|
||||
def test_unfixed_high_is_blocked(self):
|
||||
report = make_report(
|
||||
vulnerabilities=[
|
||||
vulnerability(
|
||||
vulnerability_id="CVE-2024-0001",
|
||||
package="libc6",
|
||||
severity="HIGH",
|
||||
fixed=None,
|
||||
)
|
||||
]
|
||||
)
|
||||
result, decision, _, _ = self.run_check(report=report)
|
||||
self.assertEqual(result.returncode, 1)
|
||||
self.assertEqual(decision["status"], "blocked")
|
||||
self.assertEqual(len(decision["blocking"]), 1)
|
||||
self.assertEqual(decision["blocking"][0]["vulnerability_id"], "CVE-2024-0001")
|
||||
|
||||
def test_critical_is_blocked(self):
|
||||
report = make_report(
|
||||
vulnerabilities=[vulnerability(package="bash", severity="CRITICAL")]
|
||||
)
|
||||
result, decision, _, _ = self.run_check(report=report)
|
||||
self.assertEqual(result.returncode, 1)
|
||||
self.assertEqual(decision["status"], "blocked")
|
||||
|
||||
def test_libtinfo_exception_is_guarded_by_version_package_and_state(self):
|
||||
guarded_reports = {
|
||||
"wrong_version": make_report(
|
||||
vulnerabilities=[
|
||||
vulnerability(
|
||||
vulnerability_id="CVE-2025-69720",
|
||||
package="libtinfo6",
|
||||
installed="6.4-3",
|
||||
severity="HIGH",
|
||||
)
|
||||
]
|
||||
),
|
||||
"wrong_package": make_report(
|
||||
vulnerabilities=[
|
||||
vulnerability(
|
||||
vulnerability_id="CVE-2025-69720",
|
||||
package="libselinux1",
|
||||
installed="6.4-4",
|
||||
severity="HIGH",
|
||||
)
|
||||
]
|
||||
),
|
||||
"wrong_distribution": make_report(
|
||||
os_name="11.9",
|
||||
vulnerabilities=[
|
||||
vulnerability(
|
||||
vulnerability_id="CVE-2025-69720",
|
||||
package="libtinfo6",
|
||||
installed="6.4-4",
|
||||
severity="HIGH",
|
||||
)
|
||||
]
|
||||
),
|
||||
}
|
||||
for label, report in guarded_reports.items():
|
||||
with self.subTest(label=label):
|
||||
result, decision, _, _ = self.run_check(report=report)
|
||||
self.assertEqual(result.returncode, 1, result.stderr)
|
||||
self.assertEqual(decision["exceptions"], [])
|
||||
|
||||
def test_libtinfo_exception_blocked_when_ncurses_bin_present(self):
|
||||
report = make_report(
|
||||
vulnerabilities=[
|
||||
vulnerability(
|
||||
vulnerability_id="CVE-2025-69720",
|
||||
package="libtinfo6",
|
||||
installed="6.4-4",
|
||||
severity="HIGH",
|
||||
)
|
||||
]
|
||||
)
|
||||
tar = build_tar(
|
||||
runtime_image(status_text=build_status(EXPECTED_PACKAGES + ("ncurses-bin",)))
|
||||
)
|
||||
result, decision, _, _ = self.run_check(report=report, tar_bytes=tar)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
self.assertEqual(decision["status"], "error")
|
||||
|
||||
def test_libtinfo_exception_blocked_when_infocmp_present(self):
|
||||
report = make_report(
|
||||
vulnerabilities=[
|
||||
vulnerability(
|
||||
vulnerability_id="CVE-2025-69720",
|
||||
package="libtinfo6",
|
||||
installed="6.4-4",
|
||||
severity="HIGH",
|
||||
)
|
||||
]
|
||||
)
|
||||
tar = build_tar(
|
||||
runtime_image(extra_entries=[("file", "/usr/bin/infocmp", b"infocmp\n")])
|
||||
)
|
||||
result, decision, _, _ = self.run_check(report=report, tar_bytes=tar)
|
||||
self.assertIn(result.returncode, (1, 2), result.stderr)
|
||||
self.assertEqual(decision.get("exceptions", []), [])
|
||||
|
||||
def test_exception_not_trusted_from_trivy_report_alone(self):
|
||||
report = make_report(
|
||||
vulnerabilities=[
|
||||
vulnerability(
|
||||
vulnerability_id="CVE-2025-69720",
|
||||
package="libtinfo6",
|
||||
installed="6.4-4",
|
||||
severity="HIGH",
|
||||
)
|
||||
]
|
||||
)
|
||||
tar = build_tar(
|
||||
runtime_image(extra_entries=[("file", "/usr/bin/infocmp", b"infocmp\n")])
|
||||
)
|
||||
result, _, _, _ = self.run_check(report=report, tar_bytes=tar)
|
||||
self.assertIn(result.returncode, (1, 2), result.stderr)
|
||||
|
||||
# ------------------------------------------------------- evidence errors
|
||||
def test_wrong_image_id_is_evidence_error(self):
|
||||
report = make_report(image_id="sha256:" + "b" * 64)
|
||||
result, decision, _, _ = self.run_check(report=report)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
self.assertEqual(decision["status"], "error")
|
||||
|
||||
def test_wrong_artifact_type_is_evidence_error(self):
|
||||
result, _, _, _ = self.run_check(report=make_report(artifact_type="filesystem"))
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
|
||||
def test_malformed_report_is_evidence_error(self):
|
||||
result, _, _, _ = self.run_check(report_raw="{not json")
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
|
||||
def test_missing_results_is_evidence_error(self):
|
||||
result, _, _, _ = self.run_check(
|
||||
report=make_report(include_results=False)
|
||||
)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
|
||||
def test_empty_results_is_evidence_error(self):
|
||||
result, _, _, _ = self.run_check(report=make_report(results=[]))
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
|
||||
def test_missing_os_is_evidence_error(self):
|
||||
result, _, _, _ = self.run_check(
|
||||
report=make_report(include_os=False)
|
||||
)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
|
||||
def test_empty_packages_without_vulnerabilities_is_evidence_error(self):
|
||||
result, _, _, _ = self.run_check(
|
||||
report=make_report(packages=[], vulnerabilities=None)
|
||||
)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
|
||||
def test_missing_packages_key_is_evidence_error(self):
|
||||
report = make_report()
|
||||
del report["Results"][0]["Packages"]
|
||||
result, _, _, _ = self.run_check(report=report)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
|
||||
def test_unknown_severity_is_evidence_error(self):
|
||||
result, _, _, _ = self.run_check(
|
||||
report=make_report(vulnerabilities=[vulnerability(severity="MODERATE")])
|
||||
)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
|
||||
def test_stale_db_is_evidence_error(self):
|
||||
updated = datetime.now(timezone.utc) - timedelta(hours=26)
|
||||
result, _, _, _ = self.run_check(
|
||||
report=make_report(), db_updated=updated
|
||||
)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
|
||||
def test_future_db_is_evidence_error(self):
|
||||
updated = datetime.now(timezone.utc) + timedelta(minutes=10)
|
||||
result, _, _, _ = self.run_check(
|
||||
report=make_report(), db_updated=updated
|
||||
)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
|
||||
def test_malformed_db_metadata_is_evidence_error(self):
|
||||
result, _, _, _ = self.run_check(report=make_report(), db_raw="{")
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
|
||||
def test_missing_manifest_is_evidence_error(self):
|
||||
tar = build_tar(runtime_image(drop_manifest=True))
|
||||
result, _, _, _ = self.run_check(report=make_report(), tar_bytes=tar)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
|
||||
def test_missing_dpkg_status_is_evidence_error(self):
|
||||
tar = build_tar(runtime_image(drop_status=True))
|
||||
result, _, _, _ = self.run_check(report=make_report(), tar_bytes=tar)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
|
||||
def test_manifest_hash_mismatch_is_evidence_error(self):
|
||||
manifest = (
|
||||
"base-files\t/usr/share/crank/base-files.payload\t" + "0" * 64 + "\n"
|
||||
)
|
||||
tar = build_tar(runtime_image(manifest_text=manifest))
|
||||
result, _, _, _ = self.run_check(report=make_report(), tar_bytes=tar)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
|
||||
def test_manifest_missing_image_file_is_evidence_error(self):
|
||||
tar = build_tar(runtime_image(drop_files=["/usr/share/crank/bash.payload"]))
|
||||
result, _, _, _ = self.run_check(report=make_report(), tar_bytes=tar)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
|
||||
def test_manifest_duplicate_or_unnormalized_paths_are_evidence_errors(self):
|
||||
base = (
|
||||
"base-files\t/etc/passwd\t" + sha256(b"/etc/passwd generated\n") + "\n"
|
||||
)
|
||||
cases = {
|
||||
"duplicate": base + base,
|
||||
"unnormalized": "base-files\t/etc/../etc/passwd\t" + "0" * 64 + "\n",
|
||||
"relative": "base-files\tetc/passwd\t" + "0" * 64 + "\n",
|
||||
}
|
||||
for label, manifest in cases.items():
|
||||
with self.subTest(label=label):
|
||||
tar = build_tar(runtime_image(manifest_text=manifest))
|
||||
result, _, _, _ = self.run_check(report=make_report(), tar_bytes=tar)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
|
||||
def test_manifest_with_unexpected_package_label_is_evidence_error(self):
|
||||
manifest = "linux-image\t/usr/bin/bash\t" + "0" * 64 + "\n"
|
||||
tar = build_tar(runtime_image(manifest_text=manifest))
|
||||
result, _, _, _ = self.run_check(report=make_report(), tar_bytes=tar)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
|
||||
def test_manifest_listing_its_own_path_is_evidence_error(self):
|
||||
manifest = f"runtime-generated\t{MANIFEST_PATH}\t{'0' * 64}\n"
|
||||
tar = build_tar(runtime_image(manifest_text=manifest))
|
||||
result, _, _, _ = self.run_check(report=make_report(), tar_bytes=tar)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
|
||||
def test_missing_expected_package_in_dpkg_is_evidence_error(self):
|
||||
status = build_status(
|
||||
[name for name in EXPECTED_PACKAGES if name != "libgcc-s1"]
|
||||
)
|
||||
tar = build_tar(runtime_image(status_text=status))
|
||||
result, _, _, _ = self.run_check(report=make_report(), tar_bytes=tar)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
|
||||
def test_missing_expected_package_in_trivy_report_is_evidence_error(self):
|
||||
packages = [
|
||||
{"ID": f"{name}@1.2.3-1", "Name": name, "Version": "1.2.3-1"}
|
||||
for name in EXPECTED_PACKAGES
|
||||
if name != "coreutils"
|
||||
]
|
||||
result, _, _, _ = self.run_check(report=make_report(packages=packages))
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
|
||||
def test_docker_create_failure_is_evidence_error(self):
|
||||
result, decision, _, _ = self.run_check(
|
||||
report=make_report(), extra_env={"FAKE_DOCKER_CREATE_RC": "1"}
|
||||
)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
self.assertEqual(decision["status"], "error")
|
||||
|
||||
def test_docker_export_failure_is_evidence_error(self):
|
||||
result, _, _, _ = self.run_check(
|
||||
report=make_report(), extra_env={"FAKE_DOCKER_EXPORT_RC": "1"}
|
||||
)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
|
||||
def test_docker_export_malformed_archive_is_evidence_error(self):
|
||||
result, _, _, _ = self.run_check(
|
||||
report=make_report(), tar_bytes=b"not a tar archive"
|
||||
)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
|
||||
# ------------------------------------------------------------ assurance
|
||||
def test_tar_path_normalization_handles_directory_slashes_and_traversal(self):
|
||||
module = load_checker()
|
||||
self.assertEqual(module.normalize_tar_path("usr/bin/"), "/usr/bin")
|
||||
self.assertEqual(module.normalize_tar_path("./etc/passwd"), "/etc/passwd")
|
||||
self.assertEqual(module.normalize_tar_path("/lib64"), "/lib64")
|
||||
self.assertIsNone(module.normalize_tar_path("./"))
|
||||
self.assertIsNone(module.normalize_tar_path("/"))
|
||||
for unsafe in ("etc/../../etc/passwd", "usr//bin", "a/./b"):
|
||||
with self.assertRaises(module.EvidenceError):
|
||||
module.normalize_tar_path(unsafe)
|
||||
|
||||
def test_raw_report_is_not_modified_by_the_gate(self):
|
||||
report = make_report()
|
||||
payload = json.dumps(report)
|
||||
result, _, root, _ = self.run_check(report_raw=payload)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual((root / "report.json").read_text(encoding="utf-8"), payload)
|
||||
|
||||
def test_decision_written_separately_on_error(self):
|
||||
result, decision, root, _ = self.run_check(report_raw="{broken")
|
||||
self.assertEqual(result.returncode, 2)
|
||||
self.assertTrue((root / "decision.json").exists())
|
||||
self.assertEqual(decision["status"], "error")
|
||||
self.assertTrue(decision["errors"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,462 @@
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
WRAPPER = ROOT / "scripts" / "scan-images.sh"
|
||||
CHECKER = ROOT / "scripts" / "check-image-scan.py"
|
||||
|
||||
VULN_ID = "sha256:" + "1" * 64
|
||||
CLEAN_ID = "sha256:" + "2" * 64
|
||||
|
||||
VULN_TAG = "crank/vuln:ci"
|
||||
CLEAN_TAG = "crank/clean:ci"
|
||||
|
||||
FAKE_CURL = """#!/usr/bin/env python3
|
||||
import os
|
||||
import sys
|
||||
|
||||
args = sys.argv[1:]
|
||||
if os.environ.get("FAKE_CURL_FAIL") == "1":
|
||||
sys.stderr.write("curl: (7) failed to connect\\n")
|
||||
sys.exit(7)
|
||||
output = None
|
||||
for index, value in enumerate(args):
|
||||
if value in ("--output", "-o"):
|
||||
output = args[index + 1]
|
||||
if output is None:
|
||||
sys.stderr.write("curl: missing --output\\n")
|
||||
sys.exit(2)
|
||||
with open(os.environ["FAKE_CURL_ARCHIVE"], "rb") as source:
|
||||
payload = source.read()
|
||||
with open(output, "wb") as target:
|
||||
target.write(payload)
|
||||
sys.exit(0)
|
||||
"""
|
||||
|
||||
FAKE_DOCKER = """#!/usr/bin/env python3
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
args = sys.argv[1:]
|
||||
with open(os.environ["FAKE_DOCKER_LOG"], "a", encoding="utf-8") as stream:
|
||||
stream.write(json.dumps(args) + "\\n")
|
||||
if args[:2] == ["image", "inspect"]:
|
||||
with open(os.environ["FAKE_IMAGE_MAP"], encoding="utf-8") as source:
|
||||
mapping = json.load(source)
|
||||
entry = mapping.get(args[-1])
|
||||
if entry is None:
|
||||
sys.stderr.write("docker: no such image " + args[-1] + "\\n")
|
||||
sys.exit(1)
|
||||
sys.stdout.write(entry["id"] + "\\n")
|
||||
sys.exit(0)
|
||||
sys.stderr.write("docker: unexpected command\\n")
|
||||
sys.exit(2)
|
||||
"""
|
||||
|
||||
# Fake Trivy shipped inside the stub scanner archive. It records every
|
||||
# invocation and any inherited TRIVY_* variable so the test can prove the
|
||||
# wrapper both pinned the flags and scrubbed the environment.
|
||||
FAKE_TRIVY = """#!/usr/bin/env python3
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
args = sys.argv[1:]
|
||||
log = os.environ.get("FAKE_TRIVY_LOG")
|
||||
if log:
|
||||
record = {
|
||||
"args": args,
|
||||
"trivy_env": sorted(name for name in os.environ if name.startswith("TRIVY_")),
|
||||
}
|
||||
with open(log, "a", encoding="utf-8") as stream:
|
||||
stream.write(json.dumps(record) + "\\n")
|
||||
if "--version" in args:
|
||||
if os.environ.get("FAKE_TRIVY_VERSION_FAIL"):
|
||||
sys.exit(7)
|
||||
sys.stdout.write("Version: 0.70.0\\n")
|
||||
sys.exit(0)
|
||||
if "--download-db-only" in args:
|
||||
cache = args[args.index("--cache-dir") + 1]
|
||||
db_dir = os.path.join(cache, "db")
|
||||
os.makedirs(db_dir, exist_ok=True)
|
||||
with open(os.path.join(db_dir, "trivy.db"), "w", encoding="utf-8") as stream:
|
||||
stream.write("fixture-db\\n")
|
||||
now = datetime.now(timezone.utc)
|
||||
metadata = {
|
||||
"Version": 2,
|
||||
"UpdatedAt": now.isoformat().replace("+00:00", "Z"),
|
||||
"NextUpdate": (now + timedelta(hours=24)).isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
with open(os.path.join(db_dir, "metadata.json"), "w", encoding="utf-8") as stream:
|
||||
json.dump(metadata, stream)
|
||||
sys.exit(0)
|
||||
target = args[-1]
|
||||
if os.environ.get("FAKE_TRIVY_NO_OUTPUT_ID") == target:
|
||||
sys.exit(0)
|
||||
if os.environ.get("FAKE_TRIVY_FAIL_ID") == target:
|
||||
sys.stderr.write("trivy: fixture scan failure for " + target + "\\n")
|
||||
sys.exit(1)
|
||||
output = args[args.index("--output") + 1]
|
||||
source = os.path.join(os.environ["FAKE_REPORT_DIR"], target.replace(":", "_") + ".json")
|
||||
if not os.path.exists(source):
|
||||
sys.stderr.write("trivy: no report fixture for " + target + "\\n")
|
||||
sys.exit(1)
|
||||
with open(source, encoding="utf-8") as stream:
|
||||
report = json.load(stream)
|
||||
report["Metadata"]["ImageID"] = target
|
||||
with open(output, "w", encoding="utf-8") as stream:
|
||||
json.dump(report, stream)
|
||||
sys.exit(0)
|
||||
"""
|
||||
|
||||
|
||||
def build_archive(script: str) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
with tarfile.open(fileobj=buffer, mode="w:gz") as archive:
|
||||
data = script.encode("utf-8")
|
||||
info = tarfile.TarInfo("trivy")
|
||||
info.size = len(data)
|
||||
info.mode = 0o755
|
||||
info.type = tarfile.REGTYPE
|
||||
archive.addfile(info, io.BytesIO(data))
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def alpine_report(image_id: str, vulnerabilities=None) -> dict:
|
||||
result = {
|
||||
"Target": "fixture:latest (alpine 3.24)",
|
||||
"Class": "os-pkgs",
|
||||
"Type": "alpine",
|
||||
"Packages": [
|
||||
{"ID": "musl@1.2.5-r0", "Name": "musl", "Version": "1.2.5-r0"}
|
||||
],
|
||||
}
|
||||
if vulnerabilities is not None:
|
||||
result["Vulnerabilities"] = vulnerabilities
|
||||
return {
|
||||
"SchemaVersion": 2,
|
||||
"ArtifactName": "fixture:latest",
|
||||
"ArtifactType": "container_image",
|
||||
"Metadata": {
|
||||
"ImageID": image_id,
|
||||
"OS": {"Family": "alpine", "Name": "3.24"},
|
||||
},
|
||||
"Results": [result],
|
||||
}
|
||||
|
||||
|
||||
def unfixed_high() -> dict:
|
||||
return {
|
||||
"VulnerabilityID": "CVE-2024-0001",
|
||||
"PkgName": "musl",
|
||||
"InstalledVersion": "1.2.5-r0",
|
||||
"Severity": "HIGH",
|
||||
"Status": "affected",
|
||||
"Title": "fixture unfixed high",
|
||||
}
|
||||
|
||||
|
||||
class ScanImagesWrapperTests(unittest.TestCase):
|
||||
def run_scan(
|
||||
self,
|
||||
*,
|
||||
images=(VULN_TAG, CLEAN_TAG),
|
||||
trivy_fail_id=None,
|
||||
curl_fail=False,
|
||||
extra_env=None,
|
||||
workdir_files=None,
|
||||
run_in_workdir=False,
|
||||
repeat_without_output=False,
|
||||
):
|
||||
temporary = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temporary.cleanup)
|
||||
root = Path(temporary.name)
|
||||
|
||||
bin_dir = root / "bin"
|
||||
bin_dir.mkdir()
|
||||
for name, contents in (("curl", FAKE_CURL), ("docker", FAKE_DOCKER)):
|
||||
path = bin_dir / name
|
||||
path.write_text(contents, encoding="utf-8")
|
||||
path.chmod(0o755)
|
||||
|
||||
wrappers = root / "wrappers"
|
||||
wrappers.mkdir()
|
||||
fixture_archive = build_archive(FAKE_TRIVY)
|
||||
production = WRAPPER.read_text(encoding="utf-8")
|
||||
fixture_hash = hashlib.sha256(fixture_archive).hexdigest()
|
||||
# Replace only the pinned archive hash in the test copy; the production
|
||||
# wrapper is never modified and there is no bypass environment variable.
|
||||
patched, replacements = re.subn(
|
||||
r'expected_sha256="[0-9a-f]{64}"',
|
||||
f'expected_sha256="{fixture_hash}"',
|
||||
production,
|
||||
count=1,
|
||||
)
|
||||
self.assertEqual(replacements, 1)
|
||||
self.assertIn('expected_sha256="8b4376d5d6befe5c24d503f10ff136d9e0c49f9127a4279fd110b727929a5aa9"', production)
|
||||
wrapper_copy = wrappers / "scan-images.sh"
|
||||
wrapper_copy.write_text(patched, encoding="utf-8")
|
||||
wrapper_copy.chmod(0o755)
|
||||
shutil.copy2(CHECKER, wrappers / "check-image-scan.py")
|
||||
|
||||
archive_path = root / "trivy-fixture.tar.gz"
|
||||
archive_path.write_bytes(fixture_archive)
|
||||
|
||||
reports = root / "reports"
|
||||
reports.mkdir()
|
||||
(reports / (VULN_ID.replace(":", "_") + ".json")).write_text(
|
||||
json.dumps(alpine_report(VULN_ID, [unfixed_high()])), encoding="utf-8"
|
||||
)
|
||||
(reports / (CLEAN_ID.replace(":", "_") + ".json")).write_text(
|
||||
json.dumps(alpine_report(CLEAN_ID)), encoding="utf-8"
|
||||
)
|
||||
|
||||
image_map = root / "images.json"
|
||||
image_map.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
VULN_TAG: {"id": VULN_ID},
|
||||
CLEAN_TAG: {"id": CLEAN_ID},
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
evidence = root / "evidence"
|
||||
docker_log = root / "docker.jsonl"
|
||||
trivy_log = root / "trivy.jsonl"
|
||||
|
||||
for name, contents in (workdir_files or {}).items():
|
||||
(root / name).write_text(contents, encoding="utf-8")
|
||||
|
||||
env = os.environ.copy()
|
||||
env.update(
|
||||
{
|
||||
"PATH": f"{bin_dir}:{env['PATH']}",
|
||||
"CRANK_IMAGE_SCAN_OUTPUT_DIR": str(evidence),
|
||||
"FAKE_CURL_ARCHIVE": str(archive_path),
|
||||
"FAKE_IMAGE_MAP": str(image_map),
|
||||
"FAKE_REPORT_DIR": str(reports),
|
||||
"FAKE_DOCKER_LOG": str(docker_log),
|
||||
"FAKE_TRIVY_LOG": str(trivy_log),
|
||||
}
|
||||
)
|
||||
if trivy_fail_id is not None:
|
||||
env["FAKE_TRIVY_FAIL_ID"] = trivy_fail_id
|
||||
if curl_fail:
|
||||
env["FAKE_CURL_FAIL"] = "1"
|
||||
if extra_env:
|
||||
env.update(extra_env)
|
||||
|
||||
result = subprocess.run(
|
||||
["sh", str(wrapper_copy), *images],
|
||||
text=True,
|
||||
capture_output=True,
|
||||
env=env,
|
||||
cwd=str(root) if run_in_workdir else None,
|
||||
check=False,
|
||||
)
|
||||
if repeat_without_output:
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
env["FAKE_TRIVY_NO_OUTPUT_ID"] = CLEAN_ID
|
||||
result = subprocess.run(["sh", str(wrapper_copy), *images], text=True, capture_output=True,
|
||||
env=env, cwd=str(root) if run_in_workdir else None, check=False)
|
||||
|
||||
docker_calls = []
|
||||
if docker_log.exists():
|
||||
docker_calls = [
|
||||
json.loads(line)
|
||||
for line in docker_log.read_text(encoding="utf-8").splitlines()
|
||||
if line.strip()
|
||||
]
|
||||
trivy_calls = []
|
||||
if trivy_log.exists():
|
||||
trivy_calls = [
|
||||
json.loads(line)
|
||||
for line in trivy_log.read_text(encoding="utf-8").splitlines()
|
||||
if line.strip()
|
||||
]
|
||||
receipt = None
|
||||
runs = sorted(evidence.glob("run.*"), key=lambda path: path.stat().st_mtime_ns)
|
||||
if runs:
|
||||
evidence = runs[-1]
|
||||
receipt_path = evidence / "receipt.json"
|
||||
if receipt_path.exists():
|
||||
receipt = json.loads(receipt_path.read_text(encoding="utf-8"))
|
||||
return result, root, evidence, receipt, docker_calls, trivy_calls
|
||||
|
||||
@staticmethod
|
||||
def scan_calls(trivy_calls):
|
||||
return [call for call in trivy_calls if call["args"][:1] == ["image"] and "--output" in call["args"]]
|
||||
|
||||
@staticmethod
|
||||
def target_of(call):
|
||||
return call["args"][-1]
|
||||
|
||||
def test_unfixed_high_blocks_overall_but_both_images_scanned(self):
|
||||
result, _, evidence, receipt, docker_calls, trivy_calls = self.run_scan()
|
||||
self.assertEqual(result.returncode, 1, result.stderr)
|
||||
|
||||
scans = self.scan_calls(trivy_calls)
|
||||
self.assertEqual({self.target_of(call) for call in scans}, {VULN_ID, CLEAN_ID})
|
||||
self.assertEqual(
|
||||
{call[-1] for call in docker_calls if call[:2] == ["image", "inspect"]},
|
||||
{VULN_TAG, CLEAN_TAG},
|
||||
)
|
||||
|
||||
self.assertIsNotNone(receipt)
|
||||
self.assertEqual(receipt["overall"]["exit_code"], 1)
|
||||
self.assertEqual(receipt["overall"]["status"], "blocked")
|
||||
self.assertEqual(len(receipt["images"]), 2)
|
||||
self.assertEqual({entry["tag"] for entry in receipt["images"]}, {VULN_TAG, CLEAN_TAG})
|
||||
self.assertIn(VULN_ID, {entry["image_id"] for entry in receipt["images"]})
|
||||
|
||||
by_tag = {entry["tag"]: entry for entry in receipt["images"]}
|
||||
for entry in receipt["images"]:
|
||||
self.assertTrue(Path(entry["raw"]).is_file(), entry["raw"])
|
||||
self.assertTrue(Path(entry["decision"]).is_file(), entry["decision"])
|
||||
self.assertTrue(Path(entry["scan_log"]).is_file(), entry["scan_log"])
|
||||
self.assertEqual(by_tag[VULN_TAG]["status"], "blocked")
|
||||
self.assertEqual(by_tag[CLEAN_TAG]["status"], "pass")
|
||||
|
||||
vuln_raw = json.loads(Path(by_tag[VULN_TAG]["raw"]).read_text(encoding="utf-8"))
|
||||
clean_raw = json.loads(Path(by_tag[CLEAN_TAG]["raw"]).read_text(encoding="utf-8"))
|
||||
self.assertEqual(vuln_raw["Metadata"]["ImageID"], VULN_ID)
|
||||
self.assertEqual(clean_raw["Metadata"]["ImageID"], CLEAN_ID)
|
||||
|
||||
vuln_decision = json.loads(Path(by_tag[VULN_TAG]["decision"]).read_text(encoding="utf-8"))
|
||||
clean_decision = json.loads(Path(by_tag[CLEAN_TAG]["decision"]).read_text(encoding="utf-8"))
|
||||
self.assertEqual(vuln_decision["status"], "blocked")
|
||||
self.assertEqual(vuln_decision["blocking"][0]["vulnerability_id"], "CVE-2024-0001")
|
||||
self.assertEqual(clean_decision["status"], "pass")
|
||||
|
||||
def test_pinned_flags_survive_hidden_trivy_overrides(self):
|
||||
hostile = {
|
||||
"TRIVY_SEVERITY": "LOW",
|
||||
"TRIVY_IGNORE_UNFIXED": "true",
|
||||
"TRIVY_CONFIG": "/dev/null",
|
||||
"TRIVY_SKIP_FILES": "usr/bin/infocmp",
|
||||
"TRIVY_VEX": "vex.json",
|
||||
"TRIVY_IGNORE_POLICY": "policy.rego",
|
||||
}
|
||||
result, _, _, _, _, trivy_calls = self.run_scan(
|
||||
extra_env=hostile,
|
||||
workdir_files={"trivy.yaml": "severity: LOW\nignore-unfixed: true\n"},
|
||||
run_in_workdir=True,
|
||||
)
|
||||
self.assertEqual(result.returncode, 1, result.stderr)
|
||||
for call in trivy_calls:
|
||||
args = call["args"]
|
||||
self.assertIn("--config", args)
|
||||
self.assertEqual(args[args.index("--config") + 1], "/dev/null")
|
||||
|
||||
scans = self.scan_calls(trivy_calls)
|
||||
self.assertTrue(scans)
|
||||
for call in scans:
|
||||
args = call["args"]
|
||||
self.assertEqual(call["trivy_env"], [])
|
||||
self.assertIn("--image-src", args)
|
||||
self.assertEqual(args[args.index("--image-src") + 1], "docker")
|
||||
self.assertEqual(args[args.index("--config") + 1], "/dev/null")
|
||||
self.assertEqual(args[args.index("--ignorefile") + 1], "/dev/null")
|
||||
self.assertIn("--ignore-unfixed=false", args)
|
||||
self.assertIn("--list-all-pkgs=true", args)
|
||||
self.assertIn("--skip-db-update", args)
|
||||
self.assertIn("--skip-version-check", args)
|
||||
self.assertIn("--no-progress", args)
|
||||
self.assertEqual(args[args.index("--exit-code") + 1], "0")
|
||||
self.assertEqual(args[args.index("--scanners") + 1], "vuln")
|
||||
self.assertEqual(args[args.index("--format") + 1], "json")
|
||||
self.assertEqual(
|
||||
args[args.index("--severity") + 1],
|
||||
"UNKNOWN,LOW,MEDIUM,HIGH,CRITICAL",
|
||||
)
|
||||
|
||||
def test_scan_error_on_first_image_does_not_stop_the_second(self):
|
||||
result, _, _, receipt, _, trivy_calls = self.run_scan(trivy_fail_id=VULN_ID)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
|
||||
scans = self.scan_calls(trivy_calls)
|
||||
self.assertEqual({self.target_of(call) for call in scans}, {VULN_ID, CLEAN_ID})
|
||||
|
||||
self.assertIsNotNone(receipt)
|
||||
self.assertEqual(receipt["overall"]["exit_code"], 2)
|
||||
self.assertEqual(receipt["overall"]["status"], "error")
|
||||
by_tag = {entry["tag"]: entry for entry in receipt["images"]}
|
||||
self.assertEqual(by_tag[VULN_TAG]["status"], "error")
|
||||
self.assertEqual(by_tag[CLEAN_TAG]["status"], "pass")
|
||||
clean_decision = json.loads(
|
||||
Path(by_tag[CLEAN_TAG]["decision"]).read_text(encoding="utf-8")
|
||||
)
|
||||
self.assertEqual(clean_decision["status"], "pass")
|
||||
vuln_decision = json.loads(
|
||||
Path(by_tag[VULN_TAG]["decision"]).read_text(encoding="utf-8")
|
||||
)
|
||||
self.assertEqual(vuln_decision["status"], "error")
|
||||
|
||||
def test_scanner_version_failure_is_a_bootstrap_error(self):
|
||||
result, _, _, receipt, _, _ = self.run_scan(extra_env={"FAKE_TRIVY_VERSION_FAIL": "1"})
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
self.assertEqual(receipt["overall"]["status"], "error")
|
||||
|
||||
def test_rerun_cannot_reuse_an_old_successful_raw_report(self):
|
||||
result, _, evidence, receipt, _, _ = self.run_scan(images=(CLEAN_TAG,), repeat_without_output=True)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
self.assertEqual(receipt["overall"]["status"], "error")
|
||||
self.assertEqual(receipt["images"][0]["status"], "error")
|
||||
|
||||
def test_bootstrap_failure_writes_error_receipt_for_each_image(self):
|
||||
result, _, _, receipt, docker_calls, trivy_calls = self.run_scan(curl_fail=True)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
self.assertIsNotNone(receipt)
|
||||
self.assertEqual(receipt["overall"]["status"], "error")
|
||||
self.assertEqual(receipt["overall"]["exit_code"], 2)
|
||||
self.assertEqual(len(receipt["images"]), 2)
|
||||
self.assertTrue(all(entry["status"] == "error" for entry in receipt["images"]))
|
||||
self.assertEqual({entry["tag"] for entry in receipt["images"]}, {VULN_TAG, CLEAN_TAG})
|
||||
self.assertEqual(docker_calls, [])
|
||||
self.assertEqual(trivy_calls, [])
|
||||
|
||||
def test_unknown_image_is_error_and_is_never_scanned(self):
|
||||
missing = "crank/missing:ci"
|
||||
result, _, _, receipt, _, trivy_calls = self.run_scan(images=(missing, CLEAN_TAG))
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
by_tag = {entry["tag"]: entry for entry in receipt["images"]}
|
||||
self.assertEqual(by_tag[missing]["status"], "error")
|
||||
self.assertEqual(by_tag[CLEAN_TAG]["status"], "pass")
|
||||
self.assertEqual([self.target_of(call) for call in self.scan_calls(trivy_calls)], [CLEAN_ID])
|
||||
decision = json.loads(Path(by_tag[missing]["decision"]).read_text())
|
||||
self.assertEqual(decision["status"], "error")
|
||||
|
||||
def test_download_error_log_is_retained(self):
|
||||
result, _, evidence, receipt, _, _ = self.run_scan(curl_fail=True)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
self.assertEqual(receipt["overall"]["status"], "error")
|
||||
self.assertIn("failed to connect", (evidence / "scanner-download.log").read_text())
|
||||
|
||||
def test_evidence_kept_even_when_gate_is_red(self):
|
||||
_, _, evidence, receipt, _, _ = self.run_scan()
|
||||
self.assertTrue((evidence / "receipt.json").is_file())
|
||||
self.assertTrue((evidence / "scanner.json").is_file())
|
||||
self.assertTrue((evidence / "db" / "metadata.json").is_file())
|
||||
scanner = json.loads((evidence / "scanner.json").read_text(encoding="utf-8"))
|
||||
self.assertEqual(scanner["expected_version"], "0.70.0")
|
||||
self.assertEqual(scanner["policy"]["ignore_unfixed"], False)
|
||||
self.assertIsNotNone(receipt)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user