Files
crank/apps/admin-api/tests/integration/prompts.rs
T
bsodfather 54ce770682
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s
feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.

Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
  Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
  3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
  revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
  version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
  dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
  resources/list admission fix for bound template publications.

Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
  `just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
  a real MCP Inspector 2.12.0 client smoke.

Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
  runs only on main), story events run the changed packages, the full workspace suite
  stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
  release entry of the tag instead of dying with the runner workspace.

Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.

Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
2026-10-25 09:08:22 +00:00

630 lines
23 KiB
Rust

use super::common::{
authorized_client, build_test_app, spawn_admin_api, test_auth_settings, test_registry,
test_storage_root,
};
use crank_core::{MembershipRole, Workspace, WorkspaceId, WorkspaceStatus};
use crank_registry::{CreateWorkspaceRequest, PostgresRegistry};
use reqwest::StatusCode;
use serde_json::{Value, json};
use serial_test::serial;
use time::OffsetDateTime;
const DEFAULT_WORKSPACE_ID: &str = "ws_default";
const TEST_AUTH_EMAIL: &str = "owner@crank.local";
const TEST_AUTH_PASSWORD: &str = "test-password";
fn payload(name: &str) -> Value {
json!({
"name": name,
"description": "typed prompt",
"sensitivity": "internal",
"arguments": [{"name":"count","schema":{"type":"integer"},"required":true}],
"messages": [{"role":"system","content":"Safe"},{"role":"user","content":"Count={{count}}"}]
})
}
async fn create_prompt(client: &reqwest::Client, base: &str, body: &Value) -> Value {
let response = client
.post(format!("{base}/prompts"))
.json(body)
.send()
.await
.expect("create request completes");
let status = response.status();
let text = response.text().await.unwrap_or_default();
assert_eq!(status, StatusCode::CREATED, "create must succeed: {text}");
serde_json::from_str(&text).expect("created prompt is JSON")
}
async fn create_workspace(
registry: &PostgresRegistry,
suffix: &str,
with_membership: bool,
) -> WorkspaceId {
let now = OffsetDateTime::now_utc();
let workspace_id = WorkspaceId::new(format!("ws_story312_{suffix}"));
registry
.create_workspace(CreateWorkspaceRequest {
workspace: &Workspace {
id: workspace_id.clone(),
slug: format!("story312-{suffix}"),
display_name: format!("Story 3.12 {suffix}"),
status: WorkspaceStatus::Active,
settings: json!({}),
created_at: now,
updated_at: now,
},
})
.await
.expect("synthetic workspace creates");
if with_membership {
let password_hash = admin_api::auth::hash_password(
TEST_AUTH_PASSWORD,
&test_auth_settings().password_pepper,
)
.expect("owner password hash");
let owner_id = registry
.upsert_bootstrap_user(TEST_AUTH_EMAIL, "Test Owner", &password_hash)
.await
.expect("owner account");
registry
.ensure_membership(&workspace_id, &owner_id, MembershipRole::Owner)
.await
.expect("owner membership");
}
workspace_id
}
fn workspace_base(server: &str, workspace: &WorkspaceId) -> String {
server.replace(DEFAULT_WORKSPACE_ID, workspace.as_str())
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story312_http_draft_preview_and_invalid_arguments_return_no_partial_messages() {
let registry = test_registry().await;
let server = spawn_admin_api(build_test_app(
registry,
test_storage_root("story312_prompts"),
))
.await;
let client = authorized_client(&server).await;
let base = server.as_ref();
let prompt = create_prompt(
&client,
base,
&json!({
"name":"HTTP preview fixture",
"description":"typed prompt",
"sensitivity":"internal",
"arguments":[
{"name":"count","schema":{"type":"integer"},"required":true},
{"name":"tone","schema":{"type":"string","enum":["warm","plain"]},"required":false,"default":"warm"}
],
"messages":[{"role":"system","content":"Safe"},{"role":"user","content":"Count={{count}}, tone {{tone}}"}]
}),
)
.await;
let prompt_id = prompt["prompt_id"].as_str().expect("prompt id returned");
let preview = client
.post(format!("{base}/prompts/{prompt_id}/preview"))
.json(&json!({"arguments":{"count":7}}))
.send()
.await
.expect("preview request completes");
assert_eq!(preview.status(), StatusCode::OK);
let preview: Value = preview.json().await.expect("preview is JSON");
assert_eq!(preview["status"], "draft");
assert_eq!(preview["messages"][1]["content"], "Count=7, tone warm");
for (label, arguments, expected_field, expected_code) in [
(
"invalid value",
json!({"count":"seven"}),
"count",
"prompt_invalid_argument",
),
(
"unsupported enum value",
json!({"count":7,"tone":"loud"}),
"tone",
"prompt_invalid_argument",
),
(
"missing required value",
json!({"tone":"plain"}),
"count",
"prompt_missing_argument",
),
(
"unknown value",
json!({"count":7,"extra":true}),
"extra",
"prompt_unknown_argument",
),
] {
let rejected = client
.post(format!("{base}/prompts/{prompt_id}/preview"))
.json(&json!({"arguments": arguments}))
.send()
.await
.unwrap_or_else(|error| panic!("{label} preview completes: {error}"));
let status = rejected.status();
let body: Value = rejected.json().await.expect("structured error response");
assert_eq!(status, StatusCode::BAD_REQUEST, "{label}: {body}");
assert_eq!(body["error"]["code"], expected_code, "{label}: {body}");
assert_eq!(
body["error"]["context"]["field"], expected_field,
"{label}: {body}"
);
assert!(
body.get("messages").is_none(),
"{label}: invalid values must not return partial messages"
);
}
let stored = client
.get(format!("{base}/prompts/{prompt_id}"))
.send()
.await
.expect("read request completes");
let stored: Value = stored.json().await.expect("stored prompt is JSON");
assert_eq!(
stored["version"], 1,
"rejected previews must not change the Draft"
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story312_http_update_roundtrip_and_stale_conflict_keep_the_last_version() {
let registry = test_registry().await;
let server = spawn_admin_api(build_test_app(
registry,
test_storage_root("story312_prompts_update"),
))
.await;
let client = authorized_client(&server).await;
let base = server.as_ref();
let created = create_prompt(
&client,
base,
&json!({
"name":"Before update",
"description":"first description",
"sensitivity":"internal",
"arguments":[{"name":"tone","schema":{"type":"string","enum":["warm","plain"]},"required":false,"default":"warm"}],
"messages":[{"role":"user","content":"Tone {{tone}}"}]
}),
)
.await;
let prompt_id = created["prompt_id"].as_str().expect("prompt id returned");
let updated = client
.put(format!("{base}/prompts/{prompt_id}"))
.json(&json!({
"name":"After update",
"description":"second description",
"sensitivity":"secret",
"expected_updated_at": created["updated_at"],
"arguments":[{"name":"tone","schema":{"type":"string","enum":["warm","plain","formal"]},"required":false,"default":"formal"}],
"messages":[{"role":"system","content":"Be {{tone}}."},{"role":"user","content":"Hello"}]
}))
.send()
.await
.expect("update request completes");
let status = updated.status();
let body: Value = updated.json().await.expect("updated prompt is JSON");
assert_eq!(status, StatusCode::OK, "update must succeed: {body}");
assert_eq!(body["version"], 2);
assert_eq!(body["name"], "After update");
assert_eq!(body["description"], "second description");
assert_eq!(body["sensitivity"], "secret");
assert_eq!(body["definition"]["arguments"][0]["default"], "formal");
assert_eq!(
body["definition"]["arguments"][0]["schema"]["enum"],
json!(["warm", "plain", "formal"])
);
assert_eq!(body["definition"]["messages"][0]["content"], "Be {{tone}}.");
assert_eq!(body["definition"]["messages"][1]["role"], "user");
let fetched = client
.get(format!("{base}/prompts/{prompt_id}"))
.send()
.await
.expect("read request completes");
let fetched: Value = fetched.json().await.expect("stored prompt is JSON");
assert_eq!(fetched["version"], 2);
assert_eq!(fetched["name"], "After update");
assert_eq!(fetched["description"], "second description");
assert_eq!(fetched["sensitivity"], "secret");
assert_eq!(fetched["definition"], body["definition"]);
let stale = client
.put(format!("{base}/prompts/{prompt_id}"))
.json(&json!({
"name":"Stale edit",
"description":"stale",
"sensitivity":"public",
"expected_updated_at": created["updated_at"],
"arguments":[{"name":"tone","schema":{"type":"string"},"required":false,"default":"warm"}],
"messages":[{"role":"user","content":"Stale"}]
}))
.send()
.await
.expect("stale update request completes");
let status = stale.status();
let body: Value = stale.json().await.expect("stale error is JSON");
assert_eq!(
status,
StatusCode::CONFLICT,
"stale update must conflict: {body}"
);
assert_eq!(body["error"]["code"], "prompt_stale_revision");
let preserved = client
.get(format!("{base}/prompts/{prompt_id}"))
.send()
.await
.expect("read request completes");
let preserved: Value = preserved.json().await.expect("stored prompt is JSON");
assert_eq!(
preserved["version"], 2,
"a conflicting update must not create a revision"
);
assert_eq!(preserved["name"], "After update");
assert_eq!(
preserved["definition"]["messages"][0]["content"],
"Be {{tone}}."
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story312_http_default_value_boundary_is_rejected_before_storage() {
let registry = test_registry().await;
let server = spawn_admin_api(build_test_app(
registry,
test_storage_root("story312_prompts_bounds"),
))
.await;
let client = authorized_client(&server).await;
let base = server.as_ref();
let at_limit = "a".repeat(16_382);
let prompt = create_prompt(
&client,
base,
&json!({
"name":"Boundary fixture",
"description":"default boundary",
"sensitivity":"internal",
"arguments":[{"name":"text","schema":{"type":"string"},"required":false,"default": at_limit}],
"messages":[{"role":"user","content":"{{text}}"}]
}),
)
.await;
let prompt_id = prompt["prompt_id"].as_str().expect("prompt id returned");
assert_eq!(prompt["definition"]["arguments"][0]["default"], at_limit);
let rendered = client
.post(format!("{base}/prompts/{prompt_id}/preview"))
.json(&json!({"arguments":{}}))
.send()
.await
.expect("preview request completes");
assert_eq!(rendered.status(), StatusCode::OK);
let rendered: Value = rendered.json().await.expect("preview is JSON");
assert_eq!(rendered["messages"][0]["content"], at_limit);
let too_large = "a".repeat(16_383);
let rejected = client
.post(format!("{base}/prompts"))
.json(&json!({
"name":"Over boundary fixture",
"description":"default boundary",
"sensitivity":"internal",
"arguments":[{"name":"text","schema":{"type":"string"},"required":false,"default": too_large}],
"messages":[{"role":"user","content":"{{text}}"}]
}))
.send()
.await
.expect("over-boundary create completes");
let status = rejected.status();
let body: Value = rejected.json().await.expect("rejection is JSON");
assert_eq!(
status,
StatusCode::BAD_REQUEST,
"an oversized default needs a structured 4xx: {body}"
);
assert_eq!(body["error"]["code"], "prompt_invalid_definition");
let listed = client
.get(format!("{base}/prompts"))
.send()
.await
.expect("list request completes");
let listed: Value = listed.json().await.expect("list is JSON");
assert_eq!(
listed["items"].as_array().map(Vec::len),
Some(1),
"a rejected default must not create a partial Draft"
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story312_http_scope_isolates_two_existing_workspaces() {
let registry = test_registry().await;
let owned = create_workspace(&registry, "scope_owned", true).await;
let foreign = create_workspace(&registry, "scope_foreign", false).await;
let server = spawn_admin_api(build_test_app(
registry,
test_storage_root("story312_prompts_scope"),
))
.await;
// Memberships belong to the authenticated session, so log in after granting them.
let client = authorized_client(&server).await;
let base = server.as_ref();
let owned_base = workspace_base(base, &owned);
let foreign_base = workspace_base(base, &foreign);
let local = create_prompt(&client, base, &payload("Local prompt")).await;
let remote = create_prompt(&client, &owned_base, &payload("Owned workspace prompt")).await;
let local_id = local["prompt_id"].as_str().expect("local prompt id");
let remote_id = remote["prompt_id"].as_str().expect("remote prompt id");
for (label, request) in [
("read", client.get(format!("{base}/prompts/{remote_id}"))),
(
"preview",
client
.post(format!("{base}/prompts/{remote_id}/preview"))
.json(&json!({"arguments":{"count":1}})),
),
(
"update",
client
.put(format!("{base}/prompts/{remote_id}"))
.json(&json!({
"name":"Hijacked",
"description":"hijacked",
"sensitivity":"public",
"expected_updated_at": remote["updated_at"],
"arguments":[{"name":"count","schema":{"type":"integer"},"required":true}],
"messages":[{"role":"user","content":"Hijacked"}]
})),
),
] {
let response = request.send().await.expect("foreign request completes");
let status = response.status();
let body: Value = response.json().await.unwrap_or(Value::Null);
assert_eq!(
status,
StatusCode::NOT_FOUND,
"{label} of another workspace's prompt must stay hidden: {body}"
);
}
let mirrored = client
.get(format!("{owned_base}/prompts/{local_id}"))
.send()
.await
.expect("cross read completes");
assert_eq!(
mirrored.status(),
StatusCode::NOT_FOUND,
"the other workspace must not read the local prompt"
);
let unchanged = client
.get(format!("{owned_base}/prompts/{remote_id}"))
.send()
.await
.expect("owned read completes");
let unchanged: Value = unchanged.json().await.expect("owned prompt is JSON");
assert_eq!(unchanged["version"], 1);
assert_eq!(unchanged["name"], "Owned workspace prompt");
let denied_list = client
.get(format!("{foreign_base}/prompts"))
.send()
.await
.expect("foreign list completes");
assert_eq!(
denied_list.status(),
StatusCode::FORBIDDEN,
"a workspace without membership must be refused"
);
let denied_create = client
.post(format!("{foreign_base}/prompts"))
.json(&payload("Foreign prompt"))
.send()
.await
.expect("foreign create completes");
assert_eq!(
denied_create.status(),
StatusCode::FORBIDDEN,
"a workspace without membership must not accept writes"
);
let listed = client
.get(format!("{base}/prompts"))
.send()
.await
.expect("own list completes");
assert_eq!(listed.status(), StatusCode::OK);
let listed: Value = listed.json().await.expect("list is JSON");
assert_eq!(listed["items"].as_array().map(Vec::len), Some(1));
assert_eq!(listed["items"][0]["prompt_id"], local_id);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story312_http_stores_multiline_defaults_and_rejects_nul_before_storage() {
let registry = test_registry().await;
let server = spawn_admin_api(build_test_app(
registry,
test_storage_root("story312_prompts_escapes"),
))
.await;
let client = authorized_client(&server).await;
let base = server.as_ref();
let lines = "\n".repeat(3_000);
let tabs = "\t".repeat(3_000);
// PostgreSQL stores LF/TAB as two-byte escapes, so these defaults fit the guard.
let prompt = create_prompt(
&client,
base,
&json!({
"name":"Multiline fixture",
"description":"multiline defaults",
"sensitivity":"internal",
"arguments":[
{"name":"lines","schema":{"type":"string"},"required":false,"default": lines},
{"name":"tabs","schema":{"type":"string"},"required":false,"default": tabs}
],
"messages":[{"role":"user","content":"{{lines}}|{{tabs}}"}]
}),
)
.await;
let prompt_id = prompt["prompt_id"]
.as_str()
.expect("prompt id returned")
.to_owned();
assert_eq!(prompt["definition"]["arguments"][0]["default"], lines);
assert_eq!(prompt["definition"]["arguments"][1]["default"], tabs);
let read = client
.get(format!("{base}/prompts/{prompt_id}"))
.send()
.await
.expect("read request completes");
assert_eq!(read.status(), StatusCode::OK);
let read: Value = read.json().await.expect("read prompt is JSON");
assert_eq!(read["definition"]["arguments"][0]["default"], lines);
assert_eq!(read["definition"]["arguments"][1]["default"], tabs);
let previewed = client
.post(format!("{base}/prompts/{prompt_id}/preview"))
.json(&json!({"arguments":{}}))
.send()
.await
.expect("preview request completes");
assert_eq!(previewed.status(), StatusCode::OK);
let previewed: Value = previewed.json().await.expect("preview is JSON");
assert_eq!(
previewed["messages"][0]["content"],
format!("{lines}|{tabs}"),
"the preview must return the stored multiline text unchanged"
);
// PostgreSQL refuses U+0000 in jsonb and text, so it must stop at the API boundary.
for (label, body) in [
(
"default",
json!({
"name":"NUL default",
"description":"nul default",
"sensitivity":"internal",
"arguments":[{"name":"text","schema":{"type":"string"},"required":false,"default":"a\u{0}b"}],
"messages":[{"role":"user","content":"{{text}}"}]
}),
),
(
"enum",
json!({
"name":"NUL enum",
"description":"nul enum",
"sensitivity":"internal",
"arguments":[{"name":"text","schema":{"type":"string","enum":["ok","a\u{0}b"]},"required":false,"default":"ok"}],
"messages":[{"role":"user","content":"{{text}}"}]
}),
),
(
"name",
json!({
"name":"NUL \u{0} name",
"description":"nul name",
"sensitivity":"internal",
"arguments":[{"name":"text","schema":{"type":"string"},"required":true}],
"messages":[{"role":"user","content":"{{text}}"}]
}),
),
(
"message",
json!({
"name":"NUL message",
"description":"nul message",
"sensitivity":"internal",
"arguments":[{"name":"text","schema":{"type":"string"},"required":true}],
"messages":[{"role":"user","content":"before\u{0}after {{text}}"}]
}),
),
] {
let rejected = client
.post(format!("{base}/prompts"))
.json(&body)
.send()
.await
.expect("NUL create request completes");
let status = rejected.status();
let body: Value = rejected.json().await.expect("NUL rejection is JSON");
assert_eq!(
status,
StatusCode::BAD_REQUEST,
"U+0000 in {label} needs a structured 4xx, not a storage failure: {body}"
);
assert_eq!(body["error"]["code"], "prompt_invalid_definition");
assert_eq!(body["error"]["context"]["field"], "definition");
}
// A rejected update must not create a new version or change the stored text.
let rejected_update = client
.put(format!("{base}/prompts/{prompt_id}"))
.json(&json!({
"name":"Multiline fixture",
"description":"multiline defaults",
"sensitivity":"internal",
"expected_updated_at": prompt["updated_at"],
"arguments":[
{"name":"lines","schema":{"type":"string"},"required":false,"default":"a\u{0}b"},
{"name":"tabs","schema":{"type":"string"},"required":false,"default": tabs}
],
"messages":[{"role":"user","content":"{{lines}}|{{tabs}}"}]
}))
.send()
.await
.expect("NUL update request completes");
let status = rejected_update.status();
let body: Value = rejected_update
.json()
.await
.expect("NUL update rejection is JSON");
assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
assert_eq!(body["error"]["code"], "prompt_invalid_definition");
let unchanged = client
.get(format!("{base}/prompts/{prompt_id}"))
.send()
.await
.expect("read after rejected update completes");
let unchanged: Value = unchanged.json().await.expect("prompt is JSON");
assert_eq!(
unchanged["version"], 1,
"a rejected update must not version"
);
assert_eq!(unchanged["definition"]["arguments"][0]["default"], lines);
let listed = client
.get(format!("{base}/prompts"))
.send()
.await
.expect("list request completes");
let listed: Value = listed.json().await.expect("list is JSON");
assert_eq!(
listed["items"].as_array().map(Vec::len),
Some(1),
"rejected NUL drafts must not be persisted"
);
assert_eq!(listed["items"][0]["prompt_id"], prompt_id);
}