feat: complete Epic 1 production foundation

This commit is contained in:
bsodfather committed 2026-08-25 01:24:11 +03:00
1 parent 767428436d
commit 182bde8ac0
298 files changed
+35711 -5291

No files matched your search

+155 -69
View File
@@ -5,11 +5,13 @@ use crank_core::{
ToolAccessMode, ToolSelectionPolicy, UsagePeriod, WorkspaceId, search_tool_catalog,
};
use crank_registry::{
AgentVersionRecord, CreateAgentDraftVersionRequest, CreateAgentRequest, PublishAgentRequest,
SaveAgentBindingsRequest, SaveAgentCatalogConfigRequest, UsageBucket, UsageQuery,
AgentStateExpectation, AgentVersionRecord, CreateAgentDraftVersionRequest, CreateAgentRequest,
PublishAgentRequest, SaveAgentCatalogConfigRequest, UpdateAgentSummaryRequest, UsageBucket,
UsageQuery,
};
use serde_json::json;
use time::OffsetDateTime;
use sha2::{Digest, Sha256};
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use tracing::{info, instrument};
use crate::{
@@ -17,12 +19,50 @@ use crate::{
service::{
AdminService, AgentCatalogPayload, AgentMutationResult, AgentPayload, AgentSummaryView,
CreatedAgentResponse, PublishAgentResponse, ToolSearchPreviewPayload, UpdateAgentPayload,
agent_mcp_endpoint, format_timestamp, map_agent_summary_view, new_prefixed_id,
agent_mcp_endpoint, format_timestamp, map_agent_summary_view, new_prefixed_id, now_string,
today_start_utc,
},
};
impl AdminService {
pub fn agent_state_etag(agent: &AgentSummaryView) -> String {
let policy =
serde_json::to_string(&agent.tool_selection_policy).unwrap_or_else(|_| "{}".to_owned());
let operation_ids = agent.operation_ids.join(",");
let material = format!(
"agent-state-v2\0{}\0{}\0{}\0{}\0{}\0{}\0{}\0{:?}\0{:?}\0{}\0{}\0{}\0{}\0{}",
agent.workspace_id,
agent.id,
agent.slug,
agent.display_name,
agent.description,
agent.updated_at,
agent.current_draft_version,
agent.status,
agent.latest_published_version,
agent.catalog_revision,
agent.operation_count,
operation_ids,
policy,
agent.key_count
);
format!("\"{:x}\"", Sha256::digest(material.as_bytes()))
}
pub fn agent_state_expectation(
agent: &AgentSummaryView,
) -> Result<AgentStateExpectation, ApiError> {
let updated_at = OffsetDateTime::parse(&agent.updated_at, &Rfc3339)
.map_err(|_| ApiError::internal("invalid agent state timestamp"))?;
Ok(AgentStateExpectation {
status: agent.status,
current_draft_version: agent.current_draft_version,
latest_published_version: agent.latest_published_version,
catalog_revision: agent.catalog_revision,
updated_at,
})
}
#[instrument(skip(self, payload), fields(workspace_id = %workspace_id.as_str()))]
pub async fn preview_tool_search(
&self,
@@ -110,13 +150,16 @@ impl AdminService {
self.ensure_workspace_exists(workspace_id).await?;
let workspace = self.get_workspace(workspace_id).await?;
let summaries = self.registry.list_agents(workspace_id).await?;
let usage_start = today_start_utc()?;
let usage_end = now_string()?;
let usage = self
.registry
.list_usage_by_agent(UsageQuery {
workspace_id,
period: UsagePeriod::Last24Hours,
source: None,
created_after: &today_start_utc()?,
created_after: &usage_start,
created_before: &usage_end,
bucket: UsageBucket::Hour,
})
.await?;
@@ -189,6 +232,8 @@ impl AdminService {
.iter()
.map(|binding| binding.operation_id.as_str().to_owned())
.collect::<Vec<_>>();
let usage_start = today_start_utc()?;
let usage_end = now_string()?;
let usage = self
.registry
.get_usage_for_agent(
@@ -196,7 +241,8 @@ impl AdminService {
workspace_id,
period: UsagePeriod::Last24Hours,
source: None,
created_after: &today_start_utc()?,
created_after: &usage_start,
created_before: &usage_end,
bucket: UsageBucket::Hour,
},
agent_id,
@@ -317,6 +363,7 @@ impl AdminService {
workspace_id: &WorkspaceId,
agent_id: &AgentId,
payload: UpdateAgentPayload,
expected_state: Option<&AgentStateExpectation>,
) -> Result<AgentMutationResult, ApiError> {
let existing = self
.registry
@@ -328,6 +375,20 @@ impl AdminService {
json!({ "agent_id": agent_id.as_str() }),
)
})?;
if existing.status == AgentStatus::Published
&& (payload.slug != existing.slug
|| payload.display_name != existing.display_name
|| payload.description != existing.description)
{
return Err(ApiError::conflict_with_context(
"published Agent summary is immutable; unpublish before editing",
json!({
"agent_id": agent_id.as_str(),
"error_code": "agent_published_summary_immutable",
"recovery": "unpublish_edit_publish"
}),
));
}
if payload.slug != existing.slug
&& self
@@ -346,10 +407,13 @@ impl AdminService {
.update_agent_summary(
workspace_id,
agent_id,
&payload.slug,
&payload.display_name,
&payload.description,
&updated_at,
UpdateAgentSummaryRequest {
slug: &payload.slug,
display_name: &payload.display_name,
description: &payload.description,
updated_at: &updated_at,
expected_state,
},
)
.await?;
@@ -365,6 +429,7 @@ impl AdminService {
&self,
workspace_id: &WorkspaceId,
agent_id: &AgentId,
expected_state: Option<&AgentStateExpectation>,
) -> Result<AgentMutationResult, ApiError> {
let existing = self
.registry
@@ -376,8 +441,20 @@ impl AdminService {
json!({ "agent_id": agent_id.as_str() }),
)
})?;
if existing.latest_published_version.is_some() {
return Err(ApiError::conflict_with_context(
"published Agent cannot be deleted; archive or unpublish it instead",
json!({
"agent_id": agent_id.as_str(),
"error_code": "agent_delete_forbidden",
"recovery": "archive_or_unpublish"
}),
));
}
self.registry.delete_agent(workspace_id, agent_id).await?;
self.registry
.delete_agent(workspace_id, agent_id, expected_state)
.await?;
Ok(AgentMutationResult {
agent_id: agent_id.as_str().to_owned(),
@@ -392,6 +469,7 @@ impl AdminService {
workspace_id: &WorkspaceId,
agent_id: &AgentId,
payload: AgentCatalogPayload,
expected_state: Option<&AgentStateExpectation>,
) -> Result<AgentVersionRecord, ApiError> {
let current_version = self
.ensure_editable_agent_version(workspace_id, agent_id)
@@ -408,6 +486,8 @@ impl AdminService {
enabled: binding.enabled,
})
.collect::<Vec<_>>();
self.validate_exact_published_agent_bindings(workspace_id, &bindings)
.await?;
let tool_selection_policy = requested_policy
.unwrap_or_else(|| current_version.snapshot.tool_selection_policy.clone());
validate_tool_selection_policy(&tool_selection_policy, &bindings)?;
@@ -419,6 +499,7 @@ impl AdminService {
agent_version: current_version.version,
bindings: &bindings,
tool_selection_policy: &tool_selection_policy,
expected_state,
})
.await?;
info!(
@@ -474,19 +555,23 @@ impl AdminService {
workspace_id: &WorkspaceId,
agent_id: &AgentId,
version: u32,
expected_state: Option<&AgentStateExpectation>,
) -> Result<PublishAgentResponse, ApiError> {
let agent_version = self
.get_agent_version(workspace_id, agent_id, version)
.await?;
let published_bindings = self
.published_agent_bindings(workspace_id, &agent_version.bindings)
.await?;
validate_tool_selection_policy(
&agent_version.snapshot.tool_selection_policy,
&published_bindings,
&agent_version.bindings,
)?;
if published_bindings.is_empty() {
if agent_version
.bindings
.iter()
.filter(|binding| binding.enabled)
.count()
== 0
{
return Err(ApiError::conflict_with_context(
"agent cannot be published without published enabled tools",
json!({
@@ -497,36 +582,10 @@ impl AdminService {
));
}
self.validate_exact_published_agent_bindings(workspace_id, &agent_version.bindings)
.await?;
let published_at = OffsetDateTime::now_utc();
if published_bindings != agent_version.bindings {
let draft_version = AgentVersion {
agent_id: agent_id.clone(),
version: agent_version.version + 1,
status: AgentStatus::Draft,
instructions: agent_version.snapshot.instructions.clone(),
tool_selection_policy: agent_version.snapshot.tool_selection_policy.clone(),
created_at: published_at,
};
self.registry
.create_agent_draft_version(CreateAgentDraftVersionRequest {
workspace_id,
agent_id,
version: &draft_version,
bindings: &agent_version.bindings,
updated_at: &published_at,
})
.await?;
self.registry
.save_agent_bindings(SaveAgentBindingsRequest {
workspace_id,
agent_id,
agent_version: agent_version.version,
bindings: &published_bindings,
})
.await?;
}
self.registry
.publish_agent(PublishAgentRequest {
@@ -535,6 +594,7 @@ impl AdminService {
version,
published_at: &published_at,
published_by: None,
expected_state,
})
.await?;
info!(
@@ -552,41 +612,65 @@ impl AdminService {
})
}
async fn published_agent_bindings(
async fn validate_exact_published_agent_bindings(
&self,
workspace_id: &WorkspaceId,
bindings: &[AgentOperationBinding],
) -> Result<Vec<AgentOperationBinding>, ApiError> {
let mut published = Vec::new();
) -> Result<(), ApiError> {
for binding in bindings {
if !binding.enabled {
continue;
}
let Some(summary) = self
.registry
.get_operation_summary(workspace_id, &binding.operation_id)
.await?
else {
continue;
return Err(ApiError::not_found_with_context(
"operation was not found for Agent binding",
json!({
"error_code": "agent_binding_scope_denied",
"operation_id": binding.operation_id.as_str()
}),
));
};
if summary.status == crank_core::OperationStatus::Archived {
return Err(ApiError::unprocessable_with_context(
"archived operation cannot be added to an Agent binding",
json!({
"error_code": "agent_binding_archived_operation",
"operation_id": binding.operation_id.as_str()
}),
));
}
let Some(operation_version) = summary.latest_published_version else {
continue;
let Some(version) = self
.registry
.get_operation_version(
workspace_id,
&binding.operation_id,
binding.operation_version,
)
.await?
else {
return Err(ApiError::unprocessable_with_context(
"operation version is not published for Agent binding",
json!({
"error_code": "agent_binding_not_published",
"operation_id": binding.operation_id.as_str(),
"operation_version": binding.operation_version
}),
));
};
published.push(AgentOperationBinding {
operation_id: summary.id,
operation_version,
tool_name: binding.tool_name.clone(),
tool_title: binding.tool_title.clone(),
tool_description_override: binding.tool_description_override.clone(),
enabled: true,
});
if !version.snapshot.is_published() {
return Err(ApiError::unprocessable_with_context(
"operation version is not published for Agent binding",
json!({
"error_code": "agent_binding_not_published",
"operation_id": binding.operation_id.as_str(),
"operation_version": binding.operation_version
}),
));
}
}
Ok(published)
Ok(())
}
#[instrument(skip(self), fields(workspace_id = %workspace_id.as_str(), agent_id = %agent_id.as_str()))]
@@ -594,11 +678,12 @@ impl AdminService {
&self,
workspace_id: &WorkspaceId,
agent_id: &AgentId,
expected_state: Option<&AgentStateExpectation>,
) -> Result<AgentMutationResult, ApiError> {
self.ensure_workspace_exists(workspace_id).await?;
let updated_at = OffsetDateTime::now_utc();
self.registry
.unpublish_agent(workspace_id, agent_id, &updated_at)
.unpublish_agent(workspace_id, agent_id, &updated_at, expected_state)
.await?;
info!(
name: "admin.agent.unpublished",
@@ -618,11 +703,12 @@ impl AdminService {
&self,
workspace_id: &WorkspaceId,
agent_id: &AgentId,
expected_state: Option<&AgentStateExpectation>,
) -> Result<AgentMutationResult, ApiError> {
self.ensure_workspace_exists(workspace_id).await?;
let updated_at = OffsetDateTime::now_utc();
self.registry
.archive_agent(workspace_id, agent_id, &updated_at)
.archive_agent(workspace_id, agent_id, &updated_at, expected_state)
.await?;
info!(
name: "admin.agent.archived",
+300 -28
View File
@@ -6,12 +6,14 @@ use crank_registry::{CreatePlatformApiKeyRequest, PlatformApiKeyRecord};
use serde_json::json;
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use tracing::instrument;
use url::Url;
use crate::{
error::ApiError,
service::{
AdminService, CreatedPlatformApiKeyResponse, PlatformApiKeyPayload, generate_access_secret,
hash_access_secret, new_prefixed_id,
AdminAuditContext, AdminService, CreatedPlatformApiKeyResponse, CredentialAuditRecord,
EphemeralMcpClientConfig, EphemeralMcpConnection, PlatformApiKeyPayload,
generate_access_secret, hash_access_secret, new_prefixed_id,
},
};
@@ -38,32 +40,84 @@ impl AdminService {
.await?)
}
#[instrument(skip(self, payload), fields(workspace_id = %workspace_id.as_str(), agent_id = %agent_id.as_str(), key_name = %payload.name))]
#[instrument(skip(self, payload, audit_context), fields(workspace_id = %workspace_id.as_str(), agent_id = %agent_id.as_str(), key_name = %payload.name))]
pub async fn create_agent_platform_api_key(
&self,
workspace_id: &WorkspaceId,
agent_id: &AgentId,
payload: PlatformApiKeyPayload,
mut payload: PlatformApiKeyPayload,
audit_context: Option<&AdminAuditContext>,
) -> Result<CreatedPlatformApiKeyResponse, ApiError> {
self.ensure_workspace_exists(workspace_id).await?;
self.registry
let workspace = match self.get_workspace(workspace_id).await {
Ok(workspace) => workspace,
Err(error) => {
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.platform_api_key.create_failed",
target_kind: crank_core::AuditTargetKind::PlatformApiKey,
workspace_id,
target_id: "pending",
credential_type: "platform_api_key",
outcome: "failure",
reason: error.code(),
},
)
.await;
return Err(error);
}
};
let agent_result = match self
.registry
.get_agent_summary(workspace_id, agent_id)
.await?
.ok_or_else(|| {
.await
{
Ok(agent) => agent.ok_or_else(|| {
ApiError::not_found_with_context(
format!("agent {} was not found", agent_id.as_str()),
json!({ "agent_id": agent_id.as_str() }),
)
})?;
}),
Err(error) => Err(ApiError::from(error)),
};
let agent = match agent_result {
Ok(agent) => agent,
Err(error) => {
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.platform_api_key.create_failed",
target_kind: crank_core::AuditTargetKind::PlatformApiKey,
workspace_id,
target_id: "pending",
credential_type: "platform_api_key",
outcome: "failure",
reason: error.code(),
},
)
.await;
return Err(error);
}
};
validate_platform_api_key_payload(&payload)?;
let expires_at = match payload.expires_at.as_deref() {
Some(value) => Some(
OffsetDateTime::parse(value, &Rfc3339)
.map_err(|_| ApiError::validation("expires_at must be RFC3339 timestamp"))?,
),
None => None,
let expires_at = match validate_platform_api_key_payload(&mut payload) {
Ok(expires_at) => expires_at,
Err(error) => {
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.platform_api_key.create_failed",
target_kind: crank_core::AuditTargetKind::PlatformApiKey,
workspace_id,
target_id: "pending",
credential_type: payload.key_kind.audit_credential_type(),
outcome: "failure",
reason: error.code(),
},
)
.await;
return Err(error);
}
};
let secret = generate_access_secret(payload.key_kind.secret_marker());
let api_key = PlatformApiKeyRecord {
@@ -83,55 +137,213 @@ impl AdminService {
},
};
self.registry
if let Err(error) = self
.registry
.create_platform_api_key(CreatePlatformApiKeyRequest {
api_key: &api_key.api_key,
secret_hash: &hash_access_secret(&secret),
})
.await?;
.await
{
let error = ApiError::from(error);
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.platform_api_key.create_failed",
target_kind: crank_core::AuditTargetKind::PlatformApiKey,
workspace_id,
target_id: api_key.api_key.id.as_str(),
credential_type: api_key.api_key.key_kind.audit_credential_type(),
outcome: "failure",
reason: error.code(),
},
)
.await;
return Err(error);
}
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.platform_api_key.created",
target_kind: crank_core::AuditTargetKind::PlatformApiKey,
workspace_id,
target_id: api_key.api_key.id.as_str(),
credential_type: api_key.api_key.key_kind.audit_credential_type(),
outcome: "success",
reason: "credential_created",
},
)
.await;
Ok(CreatedPlatformApiKeyResponse { api_key, secret })
let connection = (api_key.api_key.key_kind == PlatformApiKeyKind::McpClient).then(|| {
let endpoint = self.public_agent_mcp_endpoint(&workspace.workspace.slug, &agent.slug);
EphemeralMcpConnection {
endpoint: endpoint.clone(),
clients: ephemeral_client_configs(&endpoint, &secret),
secret_display: "once",
}
});
Ok(CreatedPlatformApiKeyResponse {
api_key,
secret,
connection,
})
}
#[instrument(skip(self), fields(workspace_id = %workspace_id.as_str(), agent_id = %agent_id.as_str(), key_id = %key_id.as_str()))]
#[instrument(skip(self, audit_context), fields(workspace_id = %workspace_id.as_str(), agent_id = %agent_id.as_str(), key_id = %key_id.as_str()))]
pub async fn revoke_agent_platform_api_key(
&self,
workspace_id: &WorkspaceId,
agent_id: &AgentId,
key_id: &PlatformApiKeyId,
audit_context: Option<&AdminAuditContext>,
) -> Result<(), ApiError> {
self.registry
if let Err(error) = self
.registry
.revoke_platform_api_key_for_agent(
workspace_id,
agent_id,
key_id,
&OffsetDateTime::now_utc(),
)
.await?;
.await
{
let error = ApiError::from(error);
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.platform_api_key.revoke_failed",
target_kind: crank_core::AuditTargetKind::PlatformApiKey,
workspace_id,
target_id: key_id.as_str(),
credential_type: "platform_api_key",
outcome: "failure",
reason: error.code(),
},
)
.await;
return Err(error);
}
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.platform_api_key.revoked",
target_kind: crank_core::AuditTargetKind::PlatformApiKey,
workspace_id,
target_id: key_id.as_str(),
credential_type: "platform_api_key",
outcome: "success",
reason: "credential_revoked",
},
)
.await;
Ok(())
}
#[instrument(skip(self), fields(workspace_id = %workspace_id.as_str(), agent_id = %agent_id.as_str(), key_id = %key_id.as_str()))]
#[instrument(skip(self, audit_context), fields(workspace_id = %workspace_id.as_str(), agent_id = %agent_id.as_str(), key_id = %key_id.as_str()))]
pub async fn delete_agent_platform_api_key(
&self,
workspace_id: &WorkspaceId,
agent_id: &AgentId,
key_id: &PlatformApiKeyId,
audit_context: Option<&AdminAuditContext>,
) -> Result<(), ApiError> {
self.registry
if let Err(error) = self
.registry
.delete_platform_api_key_for_agent(workspace_id, agent_id, key_id)
.await?;
.await
{
let error = ApiError::from(error);
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.platform_api_key.delete_failed",
target_kind: crank_core::AuditTargetKind::PlatformApiKey,
workspace_id,
target_id: key_id.as_str(),
credential_type: "platform_api_key",
outcome: "failure",
reason: error.code(),
},
)
.await;
return Err(error);
}
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.platform_api_key.deleted",
target_kind: crank_core::AuditTargetKind::PlatformApiKey,
workspace_id,
target_id: key_id.as_str(),
credential_type: "platform_api_key",
outcome: "success",
reason: "credential_deleted",
},
)
.await;
Ok(())
}
}
fn validate_platform_api_key_payload(payload: &PlatformApiKeyPayload) -> Result<(), ApiError> {
fn ephemeral_client_configs(endpoint: &str, secret: &str) -> Vec<EphemeralMcpClientConfig> {
["claude_desktop", "cursor", "vscode"]
.into_iter()
.map(|client| EphemeralMcpClientConfig {
client: client.to_owned(),
config: json!({
"transport": "streamable_http",
"url": endpoint,
"headers": {"Authorization": format!("Bearer {secret}")}
}),
})
.collect()
}
trait PlatformApiKeyKindAuditExt {
fn audit_credential_type(self) -> &'static str;
}
impl PlatformApiKeyKindAuditExt for PlatformApiKeyKind {
fn audit_credential_type(self) -> &'static str {
match self {
PlatformApiKeyKind::McpClient => "mcp_client_key",
PlatformApiKeyKind::Approval => "approval_key",
}
}
}
fn validate_platform_api_key_payload(
payload: &mut PlatformApiKeyPayload,
) -> Result<Option<OffsetDateTime>, ApiError> {
const MAX_KEY_NAME_CHARS: usize = 128;
const MAX_SCOPES: usize = 8;
payload.name = payload.name.trim().to_owned();
if payload.name.trim().is_empty() {
return Err(ApiError::validation("key name is required"));
}
if payload.name.chars().count() > MAX_KEY_NAME_CHARS {
return Err(ApiError::validation(
"key name must be at most 128 characters",
));
}
if payload.scopes.is_empty() {
return Err(ApiError::validation("at least one key scope is required"));
}
if payload.scopes.len() > MAX_SCOPES {
return Err(ApiError::validation("too many key scopes"));
}
if payload
.scopes
.iter()
.enumerate()
.any(|(index, scope)| payload.scopes[..index].contains(scope))
{
return Err(ApiError::validation(
"key scopes must not contain duplicates",
));
}
let valid = payload.scopes.iter().all(|scope| match payload.key_kind {
PlatformApiKeyKind::McpClient => matches!(
@@ -156,6 +368,66 @@ fn validate_platform_api_key_payload(payload: &PlatformApiKeyPayload) -> Result<
"approval key can contain at most 20 allowed origins",
));
}
if payload.key_kind == PlatformApiKeyKind::Approval {
let mut normalized_origins = Vec::with_capacity(payload.allowed_origins.len());
for origin in &payload.allowed_origins {
normalized_origins.push(validate_approval_origin(origin)?);
}
if normalized_origins
.iter()
.enumerate()
.any(|(index, origin)| normalized_origins[..index].contains(origin))
{
return Err(ApiError::validation(
"allowed origins must not contain duplicates",
));
}
payload.allowed_origins = normalized_origins;
} else if !payload.allowed_origins.is_empty() {
return Err(ApiError::validation(
"allowed origins are only supported for approval keys",
));
}
Ok(())
let expires_at = payload
.expires_at
.as_deref()
.map(|value| {
OffsetDateTime::parse(value, &Rfc3339)
.map_err(|_| ApiError::validation("expires_at must be RFC3339 timestamp"))
})
.transpose()?;
if expires_at.is_some_and(|value| value <= OffsetDateTime::now_utc()) {
return Err(ApiError::validation("expires_at must be in the future"));
}
Ok(expires_at)
}
fn validate_approval_origin(origin: &str) -> Result<String, ApiError> {
const MAX_ORIGIN_LEN: usize = 2048;
if origin.is_empty() || origin.len() > MAX_ORIGIN_LEN {
return Err(ApiError::validation("allowed origin is invalid"));
}
if origin
.bytes()
.any(|byte| byte.is_ascii_control() || byte.is_ascii_whitespace())
{
return Err(ApiError::validation("allowed origin is invalid"));
}
let parsed =
Url::parse(origin).map_err(|_| ApiError::validation("allowed origin is invalid"))?;
if !matches!(parsed.scheme(), "http" | "https")
|| parsed.host_str().is_none()
|| !parsed.username().is_empty()
|| parsed.password().is_some()
|| parsed.path() != "/"
|| parsed.query().is_some()
|| parsed.fragment().is_some()
{
return Err(ApiError::validation("allowed origin is invalid"));
}
Ok(parsed.origin().ascii_serialization())
}
+238 -40
View File
@@ -1,20 +1,101 @@
use crank_core::{LoginOutcome, MembershipRole, UserSessionId, WorkspaceId};
use crank_core::{
LoginOutcome, MembershipRole, User, UserId, UserSessionId, UserStatus, WorkspaceId,
};
use crank_registry::{AdminSecurityAuditRequest, ConsumeAdminBootstrapContractRequest};
use serde_json::json;
use time::OffsetDateTime;
use tracing::instrument;
use crate::{
auth::{
AuthenticatedSession, SessionCookie, create_session_cookie, hash_password,
hash_session_secret, verify_password,
AuthenticatedSession, SessionCookie, create_csrf_token_value, create_session_cookie,
hash_csrf_token, hash_password, hash_session_secret, verify_password,
},
error::ApiError,
service::{
AdminService, ChangePasswordPayload, LoginPayload, SessionResponse, UpdateProfilePayload,
map_identity_error, validate_profile_display_name, validate_profile_email,
AdminService, BootstrapStatusResponse, ChangePasswordPayload, CompleteBootstrapPayload,
LoginPayload, SessionResponse, UpdateProfilePayload, hash_access_secret,
map_identity_error, new_prefixed_id, validate_profile_display_name, validate_profile_email,
},
};
impl AdminService {
pub async fn bootstrap_status(&self) -> Result<BootstrapStatusResponse, ApiError> {
Ok(BootstrapStatusResponse {
bootstrap_required: !self.registry.has_password_admin().await?,
})
}
pub async fn complete_bootstrap(
&self,
payload: CompleteBootstrapPayload,
) -> Result<(SessionCookie, SessionResponse), ApiError> {
if payload.token.len() < 32 || payload.token.len() > 256 {
self.record_admin_security_audit(None, "bootstrap_rejected", "rejected", "bootstrap")
.await;
return Err(Self::constant_bootstrap_error());
}
if payload.password.len() < 12 || payload.password.len() > 256 {
self.record_admin_security_audit(None, "bootstrap_rejected", "rejected", "bootstrap")
.await;
return Err(Self::constant_bootstrap_error());
}
let now = OffsetDateTime::now_utc();
let bootstrap_token_hash = hash_access_secret(&format!("bootstrap:{}", payload.token));
if !self
.registry
.admin_bootstrap_contract_is_consumable(&bootstrap_token_hash, &now)
.await?
{
self.record_admin_security_audit(None, "bootstrap_rejected", "rejected", "bootstrap")
.await;
return Err(Self::constant_bootstrap_error());
}
let password_hash = hash_password(&payload.password, &self.auth_settings.password_pepper)?;
let user_id = self
.registry
.consume_admin_bootstrap_contract(ConsumeAdminBootstrapContractRequest {
token_hash: &bootstrap_token_hash,
password_hash: &password_hash,
now: &now,
})
.await
.map_err(|_| Self::constant_bootstrap_error());
let user_id = match user_id {
Ok(user_id) => user_id,
Err(error) => {
self.record_admin_security_audit(
None,
"bootstrap_rejected",
"rejected",
"bootstrap",
)
.await;
return Err(error);
}
};
self.record_admin_security_audit(
Some(&user_id),
"bootstrap_completed",
"success",
"bootstrap",
)
.await;
let user = self
.registry
.get_auth_user_by_id(&user_id)
.await?
.ok_or_else(|| ApiError::internal("bootstrap user was not found"))?
.user;
self.create_session_for_user(user).await
}
fn constant_bootstrap_error() -> ApiError {
ApiError::unauthorized("bootstrap request is invalid or expired")
}
pub async fn bootstrap_admin_user(&self) -> Result<(), ApiError> {
let password_hash = hash_password(
&self.auth_settings.bootstrap_admin.password,
@@ -83,36 +164,99 @@ impl AdminService {
Ok(())
}
pub async fn verify_session_csrf(
&self,
session_id: &UserSessionId,
csrf_hash: &str,
) -> Result<bool, ApiError> {
Ok(self
.registry
.verify_session_csrf(session_id, csrf_hash)
.await?)
}
pub async fn login(
&self,
payload: LoginPayload,
) -> Result<(SessionCookie, SessionResponse), ApiError> {
let authenticated = self.authenticate_login(&payload).await?;
self.login_with_client_bucket(payload, "anonymous").await
}
pub async fn login_with_client_bucket(
&self,
payload: LoginPayload,
client_bucket: &str,
) -> Result<(SessionCookie, SessionResponse), ApiError> {
let scope_hash = hash_access_secret(&format!(
"login:{}:{}",
client_bucket,
payload.email.trim().to_ascii_lowercase()
));
if let Some(locked_until) = self
.registry
.login_backoff_locked_until(&scope_hash)
.await?
{
let retry_after_ms = (locked_until - OffsetDateTime::now_utc())
.whole_milliseconds()
.clamp(1, 300_000);
return Err(ApiError::rate_limited_with_context(
"login temporarily unavailable",
json!({
"retry_after_ms": retry_after_ms,
"error_code": "login_throttled",
"recovery": "retry_after_delay"
}),
));
}
let authenticated = match self.authenticate_login(&payload).await {
Ok(authenticated) => authenticated,
Err(error) => {
let _ = self
.registry
.record_login_failure(&scope_hash, &OffsetDateTime::now_utc())
.await;
self.record_admin_security_audit(None, "login_rejected", "rejected", "login")
.await;
return Err(error);
}
};
self.registry.reset_login_backoff(&scope_hash).await?;
self.record_admin_security_audit(
Some(&authenticated.user.id),
"login_succeeded",
"success",
"login",
)
.await;
self.create_session_for_user(authenticated.user).await
}
async fn create_session_for_user(
&self,
user: User,
) -> Result<(SessionCookie, SessionResponse), ApiError> {
let session_cookie = create_session_cookie(&self.auth_settings)?;
let csrf_token = create_csrf_token_value();
let secret_hash = hash_session_secret(
&session_cookie.session_id,
&session_cookie.value,
&self.auth_settings.session_secret,
);
let memberships = self
.registry
.list_workspaces_for_user(&authenticated.user.id)
.await?;
let csrf_hash = hash_csrf_token(
&session_cookie.session_id,
&csrf_token,
&self.auth_settings.session_secret,
);
let memberships = self.registry.list_workspaces_for_user(&user.id).await?;
let default_workspace_id = memberships
.iter()
.find(|membership| membership.workspace.id.as_str() == "ws_default")
.map(|membership| membership.workspace.id.as_str().to_owned());
let current_workspace_id = default_workspace_id.or_else(|| {
authenticated
.current_workspace_id
.as_ref()
.map(|workspace_id| workspace_id.as_str().to_owned())
.or_else(|| {
memberships
.first()
.map(|membership| membership.workspace.id.as_str().to_owned())
})
memberships
.first()
.map(|membership| membership.workspace.id.as_str().to_owned())
});
let current_workspace_ref = current_workspace_id
.as_ref()
@@ -120,9 +264,10 @@ impl AdminService {
self.registry
.create_user_session(
&session_cookie.session_id,
&authenticated.user.id,
&user.id,
current_workspace_ref.as_ref(),
&secret_hash,
Some(&csrf_hash),
&session_cookie.expires_at,
)
.await?;
@@ -130,9 +275,10 @@ impl AdminService {
Ok((
session_cookie,
SessionResponse {
user: authenticated.user,
user,
memberships,
current_workspace_id,
csrf_token,
},
))
}
@@ -158,7 +304,19 @@ impl AdminService {
.registry
.get_auth_user_by_email(&payload.email)
.await?
.ok_or_else(|| ApiError::unauthorized("invalid email or password"))?;
.ok_or_else(|| {
let _ = hash_password(&payload.password, &self.auth_settings.password_pepper);
ApiError::unauthorized("invalid email or password")
})?;
if user.user.status != UserStatus::Active {
let _ = verify_password(
&payload.password,
&self.auth_settings.password_pepper,
&user.password_hash,
);
return Err(ApiError::unauthorized("invalid email or password"));
}
if !verify_password(
&payload.password,
@@ -181,6 +339,8 @@ impl AdminService {
_session_value: &str,
) -> Result<(), ApiError> {
self.registry.revoke_user_session(session_id).await?;
self.record_admin_security_audit(None, "logout", "success", "session")
.await;
Ok(())
}
@@ -190,21 +350,23 @@ impl AdminService {
session_id: &UserSessionId,
session_value: &str,
) -> Result<Option<SessionResponse>, ApiError> {
Ok(self
.get_session(session_id, session_value)
.await?
.map(|session| SessionResponse {
user: session.user,
memberships: session.memberships,
current_workspace_id: session
.current_workspace_id
.map(|id| id.as_str().to_owned()),
}))
let Some(session) = self.get_session(session_id, session_value).await? else {
return Ok(None);
};
Ok(Some(SessionResponse {
user: session.user,
memberships: session.memberships,
current_workspace_id: session
.current_workspace_id
.map(|id| id.as_str().to_owned()),
csrf_token: String::new(),
}))
}
pub async fn update_profile(
&self,
user_id: &crank_core::UserId,
session_id: &UserSessionId,
current_workspace_id: Option<&WorkspaceId>,
payload: UpdateProfilePayload,
) -> Result<SessionResponse, ApiError> {
@@ -221,18 +383,19 @@ impl AdminService {
user,
memberships,
current_workspace_id: current_workspace_id.map(|id| id.as_str().to_owned()),
csrf_token: self.rotate_session_csrf_token(session_id).await?,
})
}
pub async fn change_password(
&self,
user_id: &crank_core::UserId,
current_session_id: &UserSessionId,
_current_session_id: &UserSessionId,
payload: ChangePasswordPayload,
) -> Result<(), ApiError> {
if payload.new_password.len() < 12 {
if payload.new_password.len() < 12 || payload.new_password.len() > 256 {
return Err(ApiError::validation(
"new password must be at least 12 characters long",
"new password must be between 12 and 256 characters long",
));
}
@@ -258,13 +421,48 @@ impl AdminService {
let password_hash =
hash_password(&payload.new_password, &self.auth_settings.password_pepper)?;
self.registry
.update_user_password_and_revoke_other_sessions(
user_id,
current_session_id,
&password_hash,
)
.update_user_password_and_revoke_all_sessions(user_id, &password_hash)
.await?;
self.record_admin_security_audit(Some(user_id), "password_rotated", "success", "password")
.await;
Ok(())
}
async fn record_admin_security_audit(
&self,
actor_user_id: Option<&UserId>,
action: &'static str,
outcome: &'static str,
source: &'static str,
) {
let (request_id, trace_id) = crank_observability::current_request_correlation();
let audit_id = new_prefixed_id("audit");
let _ = self
.registry
.record_admin_security_audit(AdminSecurityAuditRequest {
id: &audit_id,
action,
outcome,
actor_user_id,
session_id: None,
request_id: request_id.as_deref(),
trace_id: trace_id.as_deref(),
source,
})
.await;
}
pub async fn rotate_session_csrf_token(
&self,
session_id: &UserSessionId,
) -> Result<String, ApiError> {
let csrf_token = create_csrf_token_value();
let csrf_hash =
hash_csrf_token(session_id, &csrf_token, &self.auth_settings.session_secret);
self.registry
.update_user_session_csrf(session_id, &csrf_hash)
.await?;
Ok(csrf_token)
}
}
+61 -11
View File
@@ -1,9 +1,9 @@
use std::collections::BTreeMap;
use crank_core::{
AgentId, InvocationLevel, InvocationSource, InvocationStatus, MembershipRole, OperationId,
OperationSecurityLevel, PlatformApiKeyKind, PlatformApiKeyScope, PlatformApiKeyStatus,
Protocol, Target, WizardState, WorkspaceId,
AgentId, AgentOperationBinding, InvocationLevel, InvocationSource, InvocationStatus,
MembershipRole, OperationId, OperationSecurityLevel, PlatformApiKeyKind, PlatformApiKeyScope,
PlatformApiKeyStatus, Protocol, Target, WizardState, WorkspaceId,
};
use crank_mapping::{JsonPathRoot, infer_mapping_from_samples};
use crank_mapping::{MappingRule, MappingSet};
@@ -87,8 +87,12 @@ impl AdminService {
async fn cleanup_legacy_demo_assets(&self, workspace_id: &WorkspaceId) -> Result<(), ApiError> {
for slug in ["revops-copilot", "support-triage"] {
if let Some(agent) = self.find_agent_by_slug(workspace_id, slug).await? {
self.delete_agent(workspace_id, &AgentId::new(agent.id.as_str().to_owned()))
.await?;
self.delete_agent(
workspace_id,
&AgentId::new(agent.id.as_str().to_owned()),
None,
)
.await?;
}
}
@@ -129,7 +133,10 @@ impl AdminService {
.await
{
Ok(()) => Ok(()),
Err(RegistryError::OperationHasPublishedAgentBindings { .. }) => {
Err(
RegistryError::OperationHasPublishedAgentBindings { .. }
| RegistryError::OperationDeleteForbidden { .. },
) => {
tracing::warn!(
name: "admin.demo_operation.cleanup_skipped",
operation_id = %operation_id.as_str(),
@@ -168,6 +175,7 @@ impl AdminService {
expires_at: None,
allowed_origins: Vec::new(),
},
None,
)
.await?
.api_key
@@ -175,7 +183,7 @@ impl AdminService {
};
if revoke && key.api_key.status != PlatformApiKeyStatus::Revoked {
self.revoke_agent_platform_api_key(workspace_id, agent_id, &key.api_key.id)
self.revoke_agent_platform_api_key(workspace_id, agent_id, &key.api_key.id, None)
.await?;
}
@@ -210,8 +218,17 @@ impl AdminService {
return Ok(());
}
self.publish_operation(workspace_id, &summary.id, summary.current_draft_version)
.await?;
self.publish_operation(
workspace_id,
&summary.id,
summary.current_draft_version,
&crank_registry::OperationStateExpectation {
current_draft_version: summary.current_draft_version,
status: summary.status,
latest_published_version: summary.latest_published_version,
},
)
.await?;
Ok(())
}
@@ -273,10 +290,15 @@ impl AdminService {
publish: bool,
) -> Result<(), ApiError> {
let summary = self.get_agent(workspace_id, agent_id).await?;
self.save_agent_bindings(workspace_id, agent_id, bindings.into())
let current = self
.get_agent_version(workspace_id, agent_id, summary.current_draft_version)
.await?;
if !demo_agent_bindings_match(&current.bindings, &bindings) {
self.save_agent_bindings(workspace_id, agent_id, bindings.into(), None)
.await?;
}
if publish && summary.latest_published_version.is_none() {
self.publish_agent(workspace_id, agent_id, summary.current_draft_version)
self.publish_agent(workspace_id, agent_id, summary.current_draft_version, None)
.await?;
}
@@ -294,11 +316,16 @@ impl AdminService {
.list_invocation_logs(ListInvocationLogsQuery {
workspace_id,
level: None,
status: None,
outcome_group: None,
search_text: None,
source: None,
operation_id: None,
agent_id: None,
created_after: None,
created_before: None,
cursor_created_at: None,
cursor_id: None,
limit: 1,
})
.await?
@@ -329,6 +356,10 @@ impl AdminService {
message: "Frankfurter returned latest exchange rate".to_owned(),
status_code: Some(200),
error_kind: None,
execution_stage: Some(crank_core::ExecutionStage::Runtime),
execution_error_code: None,
retryability: Some(crank_core::Retryability::Never),
outcome_certainty: Some(crank_core::OutcomeCertainty::Certain),
duration_ms: 124,
request_preview: json!({
"path": {},
@@ -343,6 +374,25 @@ impl AdminService {
}
}
fn demo_agent_bindings_match(
existing: &[AgentOperationBinding],
desired: &[AgentBindingPayload],
) -> bool {
if existing.len() != desired.len() {
return false;
}
let mut desired = desired.iter().collect::<Vec<_>>();
desired.sort_by(|left, right| left.tool_name.cmp(&right.tool_name));
existing.iter().zip(desired).all(|(existing, desired)| {
existing.operation_id.as_str() == desired.operation_id
&& existing.operation_version == desired.operation_version
&& existing.tool_name == desired.tool_name
&& existing.tool_title == desired.tool_title
&& existing.tool_description_override == desired.tool_description_override
&& existing.enabled == desired.enabled
})
}
fn demo_currency_agent_payload() -> AgentPayload {
AgentPayload {
slug: "currency-rates".to_owned(),
+497 -45
View File
@@ -1,16 +1,26 @@
use crank_core::{ConfigExport, WorkspaceId};
use crank_registry::RegistryOperation;
use crank_core::{OperationStatus, Target, WorkspaceId};
use crank_registry::OperationStateExpectation;
use serde::de::{self, Deserialize, Deserializer, MapAccess, SeqAccess, Visitor};
use serde_yaml::Value as YamlValue;
use std::fmt;
use tracing::{info, instrument};
use crate::{
error::ApiError,
import_guidance::import_guidance_warnings,
service::{
AdminService, ExportQuery, ImportMode, ImportQuery, ImportResponse, NewVersionPayload,
OperationPayload, YamlOperationDocument,
AdminService, ExportQuery, ImportMode, ImportQuery, ImportResponse,
LegacyYamlOperationDocument, NewVersionPayload, OperationPayload, PortableOperation,
YamlOperationDocument,
},
};
const MAX_YAML_BYTES: usize = 256 * 1024;
const MAX_YAML_LINE_OR_SCALAR_BYTES: usize = 64 * 1024;
const MAX_YAML_DEPTH: usize = 64;
const MAX_YAML_NODES: usize = 20_000;
const MAX_YAML_COLLECTION_ITEMS: usize = 4_096;
impl AdminService {
#[instrument(skip(self), fields(operation_id = %operation_id.as_str(), version = query.version.unwrap_or_default(), mode = ?query.mode))]
pub async fn export_operation(
@@ -30,19 +40,30 @@ impl AdminService {
let record = self
.get_operation_version(workspace_id, operation_id, version)
.await?;
let document = YamlOperationDocument {
format_version: "1".to_owned(),
kind: "operation".to_owned(),
operation: RegistryOperation {
config_export: Some(ConfigExport {
format_version: "1".to_owned(),
export_mode: query.mode,
let aggregate = self.get_operation(workspace_id, operation_id).await?;
let exportable = record.status == OperationStatus::Published
|| (aggregate.status != OperationStatus::Archived
&& record.status == OperationStatus::Draft
&& aggregate.current_draft_version == version);
if !exportable {
return Err(ApiError::conflict_with_context(
"only the active current Draft or a Published Version can be exported",
serde_json::json!({
"error_code": "operation_invalid_transition",
"version": version
}),
..record.snapshot
},
));
}
let operation = PortableOperation::from_registry(&record.snapshot);
reject_credential_material(&operation)?;
let document = YamlOperationDocument {
format_version: "2".to_owned(),
kind: "operation".to_owned(),
operation,
};
serde_yaml::to_string(&document).map_err(|error| ApiError::internal(error.to_string()))
serde_yaml::to_string(&document)
.map_err(|_| ApiError::internal("portable yaml serialization failed"))
}
#[instrument(skip(self, yaml_document), fields(mode = ?query.mode))]
@@ -51,29 +72,41 @@ impl AdminService {
workspace_id: &WorkspaceId,
query: ImportQuery,
yaml_document: &str,
if_match: Option<&str>,
) -> Result<ImportResponse, ApiError> {
let document: YamlOperationDocument = serde_yaml::from_str(yaml_document)
.map_err(|error| ApiError::validation(error.to_string()))?;
if document.kind != "operation" {
return Err(ApiError::validation("yaml kind must be operation"));
}
reject_yaml_anchors_and_aliases(yaml_document)?;
let parsed = parse_bounded_yaml(yaml_document)?;
let format_version = parsed
.as_mapping()
.and_then(|mapping| mapping.get(YamlValue::String("format_version".to_owned())))
.and_then(YamlValue::as_str)
.ok_or_else(yaml_invalid)?;
let payload = OperationPayload {
name: document.operation.name.clone(),
display_name: document.operation.display_name.clone(),
category: document.operation.category.clone(),
protocol: document.operation.protocol,
security_level: document.operation.security_level,
target: document.operation.target.clone(),
input_schema: document.operation.input_schema.clone(),
output_schema: document.operation.output_schema.clone(),
input_mapping: document.operation.input_mapping.clone(),
output_mapping: document.operation.output_mapping.clone(),
execution_config: document.operation.execution_config.clone(),
tool_description: document.operation.tool_description.clone(),
wizard_state: document.operation.wizard_state.clone(),
let (operation, warnings) = match format_version {
"2" => {
let document: YamlOperationDocument =
serde_yaml::from_value(parsed).map_err(|_| yaml_invalid())?;
if document.kind != "operation" || document.format_version != "2" {
return Err(yaml_unsupported());
}
(document.operation, Vec::new())
}
"1" => {
let document: LegacyYamlOperationDocument =
serde_yaml::from_value(parsed).map_err(|_| yaml_invalid())?;
if document.kind != "operation" || document.format_version != "1" {
return Err(yaml_unsupported());
}
let warnings = import_guidance_warnings(&document.operation);
(
PortableOperation::from_registry(&document.operation),
warnings,
)
}
_ => return Err(yaml_unsupported()),
};
let warnings = import_guidance_warnings(&document.operation);
reject_credential_material(&operation)?;
let payload = operation.to_payload();
match query.mode {
ImportMode::Create => {
@@ -88,9 +121,66 @@ impl AdminService {
}
ImportMode::Upsert => {
if let Some(existing) = self
.find_operation_by_name(workspace_id, &document.operation.name)
.find_operation_by_name(workspace_id, &operation.name)
.await?
{
if existing.status == OperationStatus::Archived {
return Err(crank_registry::RegistryError::OperationArchived {
operation_id: existing.id.as_str().to_owned(),
}
.into());
}
let current = self
.get_operation_version(
workspace_id,
&existing.id,
existing.current_draft_version,
)
.await?;
if operation.matches_registry(&current.snapshot) {
let expected_state = OperationStateExpectation {
current_draft_version: existing.current_draft_version,
status: existing.status,
latest_published_version: existing.latest_published_version,
};
self.registry
.verify_operation_state(workspace_id, &existing.id, &expected_state)
.await?;
return Ok(ImportResponse {
operation_id: existing.id.as_str().to_owned(),
workspace_id: workspace_id.as_str().to_owned(),
version: existing.current_draft_version,
import_mode: ImportMode::Upsert,
warnings,
});
}
let current_detail = self.get_operation(workspace_id, &existing.id).await?;
let expected_state = OperationStateExpectation {
current_draft_version: current_detail.current_draft_version,
status: current_detail.status,
latest_published_version: current_detail.latest_published_version,
};
let expected_etag = Self::operation_state_etag(&current_detail);
let provided_etag = if_match.ok_or_else(|| {
ApiError::precondition_required_with_context(
"If-Match is required when YAML upsert changes an existing Operation",
serde_json::json!({
"error_code": "operation_precondition_required",
"current_version": existing.current_draft_version,
"recovery": "reload"
}),
)
})?;
if provided_etag != expected_etag {
return Err(ApiError::conflict_with_context(
"Operation state changed; reload before retrying YAML upsert",
serde_json::json!({
"error_code": "operation_stale_version",
"current_version": existing.current_draft_version,
"recovery": "reload"
}),
));
}
let created = self
.create_version(
workspace_id,
@@ -99,9 +189,9 @@ impl AdminService {
operation: payload,
change_note: Some("yaml upsert".to_owned()),
},
&expected_state,
)
.await?;
let response = ImportResponse {
operation_id: created.operation_id,
workspace_id: created.workspace_id,
@@ -118,22 +208,384 @@ impl AdminService {
Ok(response)
} else {
let created = self.create_operation(workspace_id, payload).await?;
let response = ImportResponse {
Ok(ImportResponse {
operation_id: created.operation_id,
workspace_id: created.workspace_id,
version: created.version,
import_mode: ImportMode::Upsert,
warnings,
};
info!(
name: "admin.operation.imported",
operation_id = %response.operation_id,
version = response.version,
"operation imported by upsert"
);
Ok(response)
})
}
}
}
}
}
impl PortableOperation {
fn from_registry(operation: &crank_registry::RegistryOperation) -> Self {
Self {
name: operation.name.clone(),
display_name: operation.display_name.clone(),
category: operation.category.clone(),
protocol: operation.protocol,
security_level: operation.security_level,
target: operation.target.clone(),
input_schema: operation.input_schema.clone(),
output_schema: operation.output_schema.clone(),
input_mapping: operation.input_mapping.clone(),
output_mapping: operation.output_mapping.clone(),
execution_config: operation.execution_config.clone(),
tool_description: operation.tool_description.clone(),
}
}
fn to_payload(&self) -> OperationPayload {
OperationPayload {
name: self.name.clone(),
display_name: self.display_name.clone(),
category: self.category.clone(),
protocol: self.protocol,
security_level: self.security_level,
target: self.target.clone(),
input_schema: self.input_schema.clone(),
output_schema: self.output_schema.clone(),
input_mapping: self.input_mapping.clone(),
output_mapping: self.output_mapping.clone(),
execution_config: self.execution_config.clone(),
tool_description: self.tool_description.clone(),
wizard_state: None,
}
}
fn matches_registry(&self, operation: &crank_registry::RegistryOperation) -> bool {
self.name == operation.name
&& self.display_name == operation.display_name
&& self.category == operation.category
&& self.protocol == operation.protocol
&& self.security_level == operation.security_level
&& self.target == operation.target
&& self.input_schema == operation.input_schema
&& self.output_schema == operation.output_schema
&& self.input_mapping == operation.input_mapping
&& self.output_mapping == operation.output_mapping
&& self.execution_config == operation.execution_config
&& self.tool_description == operation.tool_description
}
}
fn parse_bounded_yaml(document: &str) -> Result<YamlValue, ApiError> {
if document.is_empty() {
return Err(yaml_invalid());
}
if document.len() > MAX_YAML_BYTES {
return Err(ApiError::payload_too_large_with_context(
"operation yaml exceeds the 256 KiB limit",
serde_json::json!({ "error_code": "operation_yaml_too_large" }),
));
}
if document
.lines()
.any(|line| line.len() > MAX_YAML_LINE_OR_SCALAR_BYTES)
{
return Err(yaml_unsupported());
}
let separators = document.lines().filter(|line| line.trim() == "---").count();
if separators > 1 || document.lines().any(|line| line.trim() == "...") {
return Err(yaml_unsupported());
}
DuplicateChecked::deserialize(serde_yaml::Deserializer::from_str(document))
.map_err(|_| yaml_invalid())?;
let parsed: YamlValue = serde_yaml::from_str(document).map_err(|_| yaml_invalid())?;
let mut nodes = 0;
validate_yaml_value(&parsed, 0, &mut nodes)?;
Ok(parsed)
}
/// A bounded preflight pass which rejects duplicate mapping keys before
/// `serde_yaml::Value` can collapse them. Values are deliberately discarded:
/// the authoritative typed parse follows only after this structural check.
struct DuplicateChecked;
impl<'de> Deserialize<'de> for DuplicateChecked {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_any(DuplicateCheckedVisitor)
}
}
struct DuplicateCheckedVisitor;
impl<'de> Visitor<'de> for DuplicateCheckedVisitor {
type Value = DuplicateChecked;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a YAML value without duplicate mapping keys")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut keys = Vec::<YamlValue>::new();
while let Some(key) = map.next_key::<YamlValue>()? {
if keys.iter().any(|existing| existing == &key) {
return Err(de::Error::custom("duplicate mapping key"));
}
keys.push(key);
map.next_value::<DuplicateChecked>()?;
}
Ok(DuplicateChecked)
}
fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
while sequence.next_element::<DuplicateChecked>()?.is_some() {}
Ok(DuplicateChecked)
}
fn visit_bool<E>(self, _: bool) -> Result<Self::Value, E> {
Ok(DuplicateChecked)
}
fn visit_i64<E>(self, _: i64) -> Result<Self::Value, E> {
Ok(DuplicateChecked)
}
fn visit_u64<E>(self, _: u64) -> Result<Self::Value, E> {
Ok(DuplicateChecked)
}
fn visit_f64<E>(self, _: f64) -> Result<Self::Value, E> {
Ok(DuplicateChecked)
}
fn visit_str<E>(self, _: &str) -> Result<Self::Value, E> {
Ok(DuplicateChecked)
}
fn visit_string<E>(self, _: String) -> Result<Self::Value, E> {
Ok(DuplicateChecked)
}
fn visit_none<E>(self) -> Result<Self::Value, E> {
Ok(DuplicateChecked)
}
fn visit_unit<E>(self) -> Result<Self::Value, E> {
Ok(DuplicateChecked)
}
fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
DuplicateChecked::deserialize(deserializer)
}
fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
DuplicateChecked::deserialize(deserializer)
}
}
fn validate_yaml_value(value: &YamlValue, depth: usize, nodes: &mut usize) -> Result<(), ApiError> {
if depth > MAX_YAML_DEPTH {
return Err(yaml_unsupported());
}
*nodes = nodes.saturating_add(1);
if *nodes > MAX_YAML_NODES {
return Err(yaml_unsupported());
}
match value {
YamlValue::Sequence(values) => {
if values.len() > MAX_YAML_COLLECTION_ITEMS {
return Err(yaml_unsupported());
}
for value in values {
validate_yaml_value(value, depth + 1, nodes)?;
}
}
YamlValue::Mapping(values) => {
if values.len() > MAX_YAML_COLLECTION_ITEMS {
return Err(yaml_unsupported());
}
for (key, value) in values {
validate_yaml_value(key, depth + 1, nodes)?;
validate_yaml_value(value, depth + 1, nodes)?;
}
}
YamlValue::String(value) if value.len() > MAX_YAML_LINE_OR_SCALAR_BYTES => {
return Err(yaml_unsupported());
}
YamlValue::Tagged(_) => return Err(yaml_unsupported()),
_ => {}
}
Ok(())
}
fn reject_credential_material(operation: &PortableOperation) -> Result<(), ApiError> {
let sensitive_name = |name: &str| {
let normalized = name.to_ascii_lowercase();
let segments = normalized.split(['-', '_', '.']).collect::<Vec<_>>();
matches!(
normalized.as_str(),
"authorization" | "proxy-authorization" | "cookie" | "set-cookie"
) || segments
.iter()
.any(|segment| matches!(*segment, "auth" | "token" | "secret" | "cookie"))
|| segments.windows(2).any(|parts| parts == ["api", "key"])
};
let sensitive_value = |value: &str| {
let normalized = value.trim().to_ascii_lowercase();
normalized.starts_with("bearer ")
|| normalized.starts_with("basic ")
|| normalized.starts_with("digest ")
|| normalized.contains("api_key=")
|| normalized.contains("access_token=")
};
let target_headers = match &operation.target {
Target::Rest(target) => &target.static_headers,
};
if target_headers
.iter()
.any(|(name, value)| sensitive_name(name) || sensitive_value(value))
|| operation
.execution_config
.headers
.iter()
.any(|(name, value)| sensitive_name(name) || sensitive_value(value))
{
return Err(ApiError::unprocessable_with_context(
"portable yaml contains credential-bearing headers",
serde_json::json!({ "error_code": "operation_yaml_invalid" }),
));
}
Ok(())
}
fn reject_yaml_anchors_and_aliases(document: &str) -> Result<(), ApiError> {
let mut single_quote = false;
let mut double_quote = false;
let mut escaped = false;
let mut comment = false;
let mut previous = '\n';
let chars = document.chars().collect::<Vec<_>>();
for (index, character) in chars.iter().copied().enumerate() {
if character == '\n' {
comment = false;
previous = character;
continue;
}
if comment {
previous = character;
continue;
}
if double_quote {
if escaped {
escaped = false;
} else if character == '\\' {
escaped = true;
} else if character == '"' {
double_quote = false;
}
previous = character;
continue;
}
if single_quote {
if character == '\'' {
single_quote = false;
}
previous = character;
continue;
}
match character {
'#' => comment = true,
'"' => double_quote = true,
'\'' => single_quote = true,
'&' | '*'
if (previous.is_whitespace() || matches!(previous, ':' | '[' | '{' | ','))
&& chars.get(index + 1).is_some_and(|next| {
next.is_ascii_alphanumeric() || matches!(next, '_' | '-')
}) =>
{
return Err(yaml_unsupported());
}
_ => {}
}
previous = character;
}
Ok(())
}
fn yaml_invalid() -> ApiError {
ApiError::unprocessable_with_context(
"operation yaml is invalid",
serde_json::json!({ "error_code": "operation_yaml_invalid" }),
)
}
fn yaml_unsupported() -> ApiError {
ApiError::unprocessable_with_context(
"operation yaml uses an unsupported construct",
serde_json::json!({ "error_code": "operation_yaml_unsupported" }),
)
}
#[cfg(test)]
mod tests {
use super::parse_bounded_yaml;
use serde_json::Value;
#[test]
fn portable_v2_schema_freezes_the_closed_top_level_contract() {
let schema: Value = serde_json::from_str(include_str!(
"../../../../docs/schemas/operation-export-v2.schema.json"
))
.unwrap();
assert_eq!(schema["properties"]["format_version"]["const"], "2");
assert_eq!(schema["properties"]["kind"]["const"], "operation");
assert_eq!(schema["additionalProperties"], false);
assert_eq!(
schema["$defs"]["portable_operation"]["additionalProperties"],
false
);
assert_eq!(
schema["$defs"]["portable_operation"]["properties"]["security_level"]["enum"],
serde_json::json!(["standard"])
);
for name in [
"rest_target",
"schema",
"mapping_set",
"mapping_rule",
"execution_config",
"tool_description",
] {
assert_eq!(schema["$defs"][name]["additionalProperties"], false);
}
assert_eq!(
schema["$defs"]["portable_operation"]["properties"]["target"]["$ref"],
"#/$defs/rest_target"
);
}
#[test]
fn bounded_yaml_rejects_duplicate_keys_before_typed_parsing() {
let document =
"format_version: '2'\nkind: operation\nkind: attacker_override\noperation: {}\n";
let error = parse_bounded_yaml(document).expect_err("duplicate key must fail closed");
match error {
crate::error::ApiError::Unprocessable { context, .. } => assert_eq!(
context.and_then(|value| value["error_code"].as_str().map(str::to_owned)),
Some("operation_yaml_invalid".to_owned())
),
other => panic!("unexpected error: {other:?}"),
}
}
}
+466 -21
View File
@@ -1,28 +1,52 @@
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use crank_core::{
AgentId, ApprovalRequestId, ApprovalRequestStatus, InvocationLogId, OperationId, UsagePeriod,
WorkspaceId,
};
use crank_registry::{
ApprovalRequestRecord, ExpireApprovalRequest, InvocationLogRecord, ListApprovalRequestsQuery,
ListInvocationLogsQuery, UsageQuery, UsageRollupRecord,
ApprovalRequestRecord, DecideApprovalRequest, ExpireApprovalRequest, InvocationLogRecord,
InvocationRetentionOutcome, ListApprovalRequestsQuery, ListInvocationLogsQuery, UsageQuery,
UsageRollupRecord,
};
use serde_json::json;
use time::OffsetDateTime;
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use tracing::instrument;
use crate::{
error::ApiError,
service::{
AdminService, ApprovalsQuery, LogsQuery, UsageOverviewResponse, UsageRequestQuery,
usage_window,
AdminService, ApprovalDecisionPayload, ApprovalsQuery, LogsListResponse, LogsQuery,
UsageOverviewResponse, UsageRequestQuery, usage_window,
},
};
const LOG_LIST_DEFAULT_LIMIT: u32 = 100;
const LOG_LIST_MAX_LIMIT: u32 = 200;
const LOG_CSV_MAX_ROWS: u32 = 1_000;
const MAX_EXPLICIT_USAGE_WINDOW_DAYS: i64 = 90;
#[derive(serde::Serialize, serde::Deserialize)]
struct LogsCursor {
created_at: String,
id: String,
}
fn safe_approval_record(mut record: ApprovalRequestRecord) -> ApprovalRequestRecord {
record.approval.request_payload =
crank_core::sanitize_invocation_preview(&record.approval.request_payload);
record.approval.response_payload = record
.approval
.response_payload
.as_ref()
.map(crank_core::sanitize_invocation_preview);
record
}
impl AdminService {
pub async fn cleanup_invocation_logs_before(
&self,
cutoff: OffsetDateTime,
) -> Result<u64, ApiError> {
) -> Result<InvocationRetentionOutcome, ApiError> {
self.registry
.delete_invocation_logs_before(cutoff)
.await
@@ -34,25 +58,45 @@ impl AdminService {
&self,
workspace_id: &WorkspaceId,
query: LogsQuery,
) -> Result<Vec<InvocationLogRecord>, ApiError> {
) -> Result<LogsListResponse, ApiError> {
self.ensure_workspace_exists(workspace_id).await?;
let operation_id = query.operation_id.as_deref().map(OperationId::new);
let agent_id = query.agent_id.as_deref().map(AgentId::new);
let (_, created_after, _) = usage_window(query.period.unwrap_or(UsagePeriod::Last7Days))?;
let (_, created_after, created_before, _) =
resolve_usage_window(query.period.unwrap_or(UsagePeriod::Last7Days), &query)?;
let (cursor_created_at, cursor_id) = decode_logs_cursor(query.cursor.as_deref())?;
let limit = query
.limit
.unwrap_or(LOG_LIST_DEFAULT_LIMIT)
.clamp(1, LOG_LIST_MAX_LIMIT);
self.registry
let mut items = self
.registry
.list_invocation_logs(ListInvocationLogsQuery {
workspace_id,
level: query.level,
status: query.status,
outcome_group: query.outcome_group,
search_text: query.search.as_deref(),
source: query.source,
operation_id: operation_id.as_ref(),
agent_id: agent_id.as_ref(),
created_after: Some(&created_after),
limit: query.limit.unwrap_or(100),
created_before: Some(&created_before),
cursor_created_at: cursor_created_at.as_deref(),
cursor_id: cursor_id.as_ref(),
limit: limit.saturating_add(1),
})
.await
.map_err(ApiError::from)
.await?;
let next_cursor = if items.len() > limit as usize {
items.truncate(limit as usize);
items.last().map(encode_logs_cursor).transpose()?
} else {
None
};
Ok(LogsListResponse { items, next_cursor })
}
#[instrument(skip(self))]
@@ -72,6 +116,69 @@ impl AdminService {
})
}
#[instrument(skip(self))]
pub async fn export_logs_csv(
&self,
workspace_id: &WorkspaceId,
mut query: LogsQuery,
) -> Result<String, ApiError> {
query.limit = Some(
query
.limit
.unwrap_or(LOG_CSV_MAX_ROWS)
.clamp(1, LOG_CSV_MAX_ROWS),
);
query.cursor = None;
let page = self.list_logs(workspace_id, query).await?;
let mut csv = String::from(
"created_at,level,status,source,agent,operation,operation_version,duration_ms,request_id,trace_id,stage,error_code,message,request_preview,response_preview\n",
);
for record in page.items {
let log = record.log;
let row = [
log.created_at
.format(&Rfc3339)
.map_err(|error| ApiError::internal(error.to_string()))?,
serialize_csv_text(log.level)?,
serialize_csv_text(log.status)?,
serialize_csv_text(log.source)?,
record
.agent_display_name
.or(record.agent_slug)
.unwrap_or_default(),
record.operation_display_name,
log.operation_version
.map(|value| value.to_string())
.unwrap_or_default(),
log.duration_ms.to_string(),
log.request_id.unwrap_or_default(),
log.trace_id.unwrap_or_default(),
log.execution_stage
.map(serialize_csv_text)
.transpose()?
.unwrap_or_default(),
log.execution_error_code
.map(serialize_csv_text)
.transpose()?
.unwrap_or_default(),
log.message,
serde_json::to_string(&log.request_preview)
.map_err(|error| ApiError::internal(error.to_string()))?,
serde_json::to_string(&log.response_preview)
.map_err(|error| ApiError::internal(error.to_string()))?,
];
csv.push_str(&row.into_iter().map(csv_cell).collect::<Vec<_>>().join(","));
csv.push('\n');
if csv.len() > 1_048_576 {
return Err(ApiError::unprocessable_with_context(
"logs CSV export exceeded the bounded response size",
json!({ "error_code": "logs_csv_too_large" }),
));
}
}
Ok(csv)
}
#[instrument(skip(self))]
pub async fn list_approvals(
&self,
@@ -92,7 +199,7 @@ impl AdminService {
for record in records {
let record = self.normalize_approval_record(record).await?;
if query.status.is_none() || record.approval.status == query.status.unwrap() {
normalized.push(record);
normalized.push(safe_approval_record(record));
}
}
@@ -117,7 +224,114 @@ impl AdminService {
)
})?;
self.normalize_approval_record(record).await
self.normalize_approval_record(record)
.await
.map(safe_approval_record)
}
#[instrument(skip(self, payload))]
pub async fn approve_approval(
&self,
workspace_id: &WorkspaceId,
approval_id: &ApprovalRequestId,
payload: ApprovalDecisionPayload,
) -> Result<ApprovalRequestRecord, ApiError> {
if !payload.approve.eq_ignore_ascii_case("yes") {
return Err(ApiError::unprocessable_with_context(
"approve must be yes for approval confirmation",
json!({ "error_code": "invalid_decision_payload" }),
));
}
self.decide_admin_approval(
workspace_id,
approval_id,
ApprovalRequestStatus::Approved,
Some(json!({"approve": "yes"})),
payload.note.as_deref(),
)
.await
}
#[instrument(skip(self, payload))]
pub async fn deny_approval(
&self,
workspace_id: &WorkspaceId,
approval_id: &ApprovalRequestId,
payload: ApprovalDecisionPayload,
) -> Result<ApprovalRequestRecord, ApiError> {
if !payload.approve.eq_ignore_ascii_case("no") {
return Err(ApiError::unprocessable_with_context(
"approve must be no for approval denial",
json!({ "error_code": "invalid_decision_payload" }),
));
}
self.decide_admin_approval(
workspace_id,
approval_id,
ApprovalRequestStatus::Denied,
Some(json!({"approve": "no"})),
payload.note.as_deref(),
)
.await
}
async fn decide_admin_approval(
&self,
workspace_id: &WorkspaceId,
approval_id: &ApprovalRequestId,
status: ApprovalRequestStatus,
response_payload: Option<serde_json::Value>,
decision_note: Option<&str>,
) -> Result<ApprovalRequestRecord, ApiError> {
self.ensure_workspace_exists(workspace_id).await?;
let current = self
.registry
.get_approval_request(workspace_id, approval_id)
.await?
.ok_or_else(|| {
ApiError::not_found_with_context(
format!("approval request {} was not found", approval_id.as_str()),
json!({ "approval_id": approval_id.as_str() }),
)
})?;
let normalized = self.normalize_approval_record(current).await?;
if normalized.approval.status != ApprovalRequestStatus::Pending {
return Err(ApiError::conflict_with_context(
"approval request is not pending",
json!({
"approval_id": approval_id.as_str(),
"status": normalized.approval.status,
"error_code": "approval_state_conflict"
}),
));
}
let decided = self
.registry
.decide_approval_request(DecideApprovalRequest {
workspace_id,
agent_id: &normalized.approval.agent_id,
approval_id,
operation_id: &normalized.approval.operation_id,
operation_version: normalized.approval.operation_version,
request_payload: &normalized.approval.request_payload,
status,
decided_at: OffsetDateTime::now_utc(),
decided_by_key_id: None,
response_payload,
decision_note,
})
.await?
.ok_or_else(|| {
ApiError::conflict_with_context(
"approval request state changed before decision was recorded",
json!({
"approval_id": approval_id.as_str(),
"error_code": "approval_state_conflict"
}),
)
})?;
Ok(safe_approval_record(decided))
}
async fn normalize_approval_record(
@@ -149,13 +363,14 @@ impl AdminService {
query: UsageRequestQuery,
) -> Result<UsageOverviewResponse, ApiError> {
self.ensure_workspace_exists(workspace_id).await?;
let (period, created_after, bucket) =
usage_window(query.period.unwrap_or(UsagePeriod::Last7Days))?;
let (period, created_after, created_before, bucket) =
resolve_usage_request_window(query.period.unwrap_or(UsagePeriod::Last7Days), &query)?;
let usage_query = UsageQuery {
workspace_id,
period,
source: query.source,
created_after: &created_after,
created_before: &created_before,
bucket,
};
@@ -168,16 +383,104 @@ impl AdminService {
.registry
.list_usage_by_operation(usage_query.clone())
.await?;
let agents = self.registry.list_usage_by_agent(usage_query).await?;
let agents = self
.registry
.list_usage_by_agent(usage_query.clone())
.await?;
let outcomes = self.registry.list_usage_outcomes(usage_query).await?;
Ok(UsageOverviewResponse {
summary,
timeline,
operations,
agents,
outcomes,
})
}
#[instrument(skip(self))]
pub async fn export_usage_csv(
&self,
workspace_id: &WorkspaceId,
query: UsageRequestQuery,
) -> Result<String, ApiError> {
let usage = self.get_usage_overview(workspace_id, query).await?;
let mut csv = String::from(
"kind,name,group,error_code,calls_total,calls_error,p50_ms,p95_ms,p99_ms\n",
);
for operation in usage.operations {
csv.push_str(
&[
"operation".to_owned(),
operation.operation_display_name,
String::new(),
String::new(),
operation.calls_total.to_string(),
operation.calls_error.to_string(),
operation.p50_ms.to_string(),
operation.p95_ms.to_string(),
operation.p99_ms.to_string(),
]
.into_iter()
.map(csv_cell)
.collect::<Vec<_>>()
.join(","),
);
csv.push('\n');
}
for agent in usage.agents {
csv.push_str(
&[
"agent".to_owned(),
agent.agent_display_name,
String::new(),
String::new(),
agent.calls_total.to_string(),
agent.calls_error.to_string(),
agent.p50_ms.to_string(),
agent.p95_ms.to_string(),
agent.p99_ms.to_string(),
]
.into_iter()
.map(csv_cell)
.collect::<Vec<_>>()
.join(","),
);
csv.push('\n');
}
for outcome in usage.outcomes {
csv.push_str(
&[
"outcome".to_owned(),
String::new(),
serialize_csv_text(outcome.group)?,
outcome
.execution_error_code
.map(serialize_csv_text)
.transpose()?
.unwrap_or_default(),
outcome.calls_total.to_string(),
String::new(),
outcome.p50_ms.to_string(),
outcome.p95_ms.to_string(),
outcome.p99_ms.to_string(),
]
.into_iter()
.map(csv_cell)
.collect::<Vec<_>>()
.join(","),
);
csv.push('\n');
}
if csv.len() > 1_048_576 {
return Err(ApiError::unprocessable_with_context(
"usage CSV export exceeded the bounded response size",
json!({ "error_code": "usage_csv_too_large" }),
));
}
Ok(csv)
}
#[instrument(skip(self))]
pub async fn get_operation_usage(
&self,
@@ -186,8 +489,8 @@ impl AdminService {
query: UsageRequestQuery,
) -> Result<UsageRollupRecord, ApiError> {
self.get_operation(workspace_id, operation_id).await?;
let (period, created_after, bucket) =
usage_window(query.period.unwrap_or(UsagePeriod::Last7Days))?;
let (period, created_after, created_before, bucket) =
resolve_usage_request_window(query.period.unwrap_or(UsagePeriod::Last7Days), &query)?;
self.registry
.get_usage_for_operation(
@@ -196,6 +499,7 @@ impl AdminService {
period,
source: query.source,
created_after: &created_after,
created_before: &created_before,
bucket,
},
operation_id,
@@ -220,8 +524,8 @@ impl AdminService {
query: UsageRequestQuery,
) -> Result<UsageRollupRecord, ApiError> {
self.get_agent(workspace_id, agent_id).await?;
let (period, created_after, bucket) =
usage_window(query.period.unwrap_or(UsagePeriod::Last7Days))?;
let (period, created_after, created_before, bucket) =
resolve_usage_request_window(query.period.unwrap_or(UsagePeriod::Last7Days), &query)?;
self.registry
.get_usage_for_agent(
@@ -230,6 +534,7 @@ impl AdminService {
period,
source: query.source,
created_after: &created_after,
created_before: &created_before,
bucket,
},
agent_id,
@@ -243,3 +548,143 @@ impl AdminService {
})
}
}
fn resolve_usage_window(
period: UsagePeriod,
query: &LogsQuery,
) -> Result<(UsagePeriod, String, String, crank_registry::UsageBucket), ApiError> {
resolve_explicit_or_period_window(
period,
query.created_after.as_deref(),
query.created_before.as_deref(),
)
}
fn resolve_usage_request_window(
period: UsagePeriod,
query: &UsageRequestQuery,
) -> Result<(UsagePeriod, String, String, crank_registry::UsageBucket), ApiError> {
resolve_explicit_or_period_window(
period,
query.created_after.as_deref(),
query.created_before.as_deref(),
)
}
fn resolve_explicit_or_period_window(
period: UsagePeriod,
created_after: Option<&str>,
created_before: Option<&str>,
) -> Result<(UsagePeriod, String, String, crank_registry::UsageBucket), ApiError> {
match (created_after, created_before) {
(None, None) => usage_window(period),
(Some(_), None) | (None, Some(_)) => Err(invalid_usage_window(
"usage window requires both created_after and created_before",
)),
(Some(after), Some(before)) => {
let after = OffsetDateTime::parse(after, &Rfc3339)
.map_err(|_| invalid_usage_window("created_after must be RFC3339 UTC"))?;
let before = OffsetDateTime::parse(before, &Rfc3339)
.map_err(|_| invalid_usage_window("created_before must be RFC3339 UTC"))?;
if after >= before {
return Err(invalid_usage_window(
"created_after must be before created_before",
));
}
let duration = before - after;
if duration > time::Duration::days(MAX_EXPLICIT_USAGE_WINDOW_DAYS) {
return Err(invalid_usage_window("usage window exceeds maximum range"));
}
let bucket = if duration <= time::Duration::days(1) {
crank_registry::UsageBucket::Hour
} else if duration <= time::Duration::days(14) {
crank_registry::UsageBucket::Day
} else if duration <= time::Duration::days(45) {
crank_registry::UsageBucket::Week
} else {
crank_registry::UsageBucket::Month
};
Ok((
period,
after
.format(&Rfc3339)
.map_err(|error| ApiError::internal(error.to_string()))?,
before
.format(&Rfc3339)
.map_err(|error| ApiError::internal(error.to_string()))?,
bucket,
))
}
}
}
fn invalid_usage_window(message: &'static str) -> ApiError {
ApiError::unprocessable_with_context(message, json!({ "error_code": "usage_window_invalid" }))
}
fn decode_logs_cursor(
cursor: Option<&str>,
) -> Result<(Option<String>, Option<InvocationLogId>), ApiError> {
let Some(cursor) = cursor else {
return Ok((None, None));
};
if cursor.len() > 512 {
return Err(invalid_logs_cursor());
}
let bytes = URL_SAFE_NO_PAD
.decode(cursor)
.map_err(|_| invalid_logs_cursor())?;
let decoded: LogsCursor = serde_json::from_slice(&bytes).map_err(|_| invalid_logs_cursor())?;
OffsetDateTime::parse(&decoded.created_at, &Rfc3339).map_err(|_| invalid_logs_cursor())?;
if decoded.id.is_empty()
|| decoded.id.len() > 128
|| decoded.id.contains(';')
|| decoded.id.contains(',')
{
return Err(invalid_logs_cursor());
}
Ok((
Some(decoded.created_at),
Some(InvocationLogId::new(decoded.id)),
))
}
fn encode_logs_cursor(record: &InvocationLogRecord) -> Result<String, ApiError> {
let cursor = LogsCursor {
created_at: record
.log
.created_at
.format(&Rfc3339)
.map_err(|error| ApiError::internal(error.to_string()))?,
id: record.log.id.as_str().to_owned(),
};
let encoded =
serde_json::to_vec(&cursor).map_err(|error| ApiError::internal(error.to_string()))?;
Ok(URL_SAFE_NO_PAD.encode(encoded))
}
fn invalid_logs_cursor() -> ApiError {
ApiError::unprocessable_with_context(
"logs cursor is invalid",
json!({ "error_code": "logs_cursor_invalid" }),
)
}
fn serialize_csv_text<T: serde::Serialize>(value: T) -> Result<String, ApiError> {
serde_json::to_value(value)
.map_err(|error| ApiError::internal(error.to_string()))?
.as_str()
.map(ToOwned::to_owned)
.ok_or_else(|| ApiError::internal("failed to serialize CSV enum value"))
}
fn csv_cell(mut value: String) -> String {
if value
.chars()
.next()
.is_some_and(|ch| matches!(ch, '=' | '+' | '-' | '@' | '\t' | '\r' | '\n'))
{
value.insert(0, '\'');
}
format!("\"{}\"", value.replace('"', "\"\""))
}
+268
View File
@@ -0,0 +1,268 @@
use crank_core::{
OnboardingProjection, OnboardingStepId, ProductEventId, ProductEventKind, WorkspaceId,
};
use crank_registry::{
OnboardingPresentationMilestone, RecordOnboardingMilestoneRequest, RegistryError,
};
use serde_json::json;
use time::OffsetDateTime;
use crate::{
error::ApiError,
service::{
AdminService, OnboardingEventPayload, OnboardingEventResponse, OnboardingFirstCallEvidence,
OnboardingResponse, OnboardingStepView, ResetOnboardingSelectionResponse, format_timestamp,
new_prefixed_id,
},
};
impl AdminService {
pub async fn get_onboarding(
&self,
workspace_id: &WorkspaceId,
) -> Result<OnboardingResponse, ApiError> {
self.ensure_workspace_exists(workspace_id).await?;
let projection = self
.registry
.ensure_onboarding_eligibility(workspace_id, OffsetDateTime::now_utc())
.await?;
self.map_onboarding_response(projection).await
}
pub async fn record_onboarding_event(
&self,
workspace_id: &WorkspaceId,
payload: OnboardingEventPayload,
) -> Result<OnboardingEventResponse, ApiError> {
self.ensure_workspace_exists(workspace_id).await?;
if payload.completed_steps.is_some() || payload.event == "completed" {
return Err(onboarding_event_not_allowed());
}
if payload.idempotency_key.is_empty() || payload.idempotency_key.len() > 256 {
return Err(ApiError::validation(
"idempotency_key must contain 1..256 bytes",
));
}
if payload.idempotency_key.starts_with("onboarding:") {
return Err(onboarding_event_not_allowed());
}
let (milestone, event_kind) = match payload.event.as_str() {
"started" => (
OnboardingPresentationMilestone::Started,
ProductEventKind::OnboardingStarted,
),
"resumed" => (
OnboardingPresentationMilestone::Resumed,
ProductEventKind::OnboardingResumed,
),
"dismissed" => (
OnboardingPresentationMilestone::Dismissed,
ProductEventKind::OnboardingDismissed,
),
"abandoned" => (
OnboardingPresentationMilestone::Abandoned,
ProductEventKind::OnboardingAbandoned,
),
_ => return Err(onboarding_event_not_allowed()),
};
// Presentation events must never exist outside the server-owned cohort,
// including a direct API call before the first UI snapshot GET.
let current = self
.registry
.ensure_onboarding_eligibility(workspace_id, OffsetDateTime::now_utc())
.await?;
let outcome = self
.registry
.record_onboarding_milestone(RecordOnboardingMilestoneRequest {
workspace_id,
event_id: &ProductEventId::new(new_prefixed_id("pe")),
milestone,
idempotency_key: &payload.idempotency_key,
expected_revision: payload.expected_revision,
occurred_at: OffsetDateTime::now_utc(),
eligible_since: None,
})
.await;
let outcome = match outcome {
Ok(outcome) => outcome,
Err(RegistryError::OnboardingStaleRevision) => {
let replay = self
.registry
.get_product_event_by_idempotency_key(workspace_id, &payload.idempotency_key)
.await?;
if replay
.as_ref()
.is_some_and(|record| record.event.kind == event_kind)
{
return Ok(OnboardingEventResponse {
accepted: false,
onboarding: self.map_onboarding_response(current).await?,
});
}
if replay.is_some() {
return Err(ApiError::conflict_with_context(
"idempotency key was already used for another onboarding event",
json!({"error_code":"onboarding_idempotency_conflict","recovery":"use_original_event"}),
));
}
return Err(ApiError::conflict_with_context(
"onboarding state changed; reload before retrying",
json!({"error_code":"onboarding_stale_revision","recovery":"reload"}),
));
}
Err(RegistryError::InvalidExecutionRecord {
field: "product_event.idempotency_conflict",
}) => {
return Err(ApiError::conflict_with_context(
"idempotency key was already used for another onboarding event",
json!({"error_code":"onboarding_idempotency_conflict","recovery":"use_original_event"}),
));
}
Err(other) => return Err(other.into()),
};
Ok(OnboardingEventResponse {
accepted: outcome.accepted,
onboarding: self.map_onboarding_response(outcome.projection).await?,
})
}
pub async fn reset_onboarding_selection(
&self,
workspace_id: &WorkspaceId,
expected_revision: i64,
) -> Result<ResetOnboardingSelectionResponse, ApiError> {
self.ensure_workspace_exists(workspace_id).await?;
let projection = self
.registry
.reset_onboarding_selection(workspace_id, expected_revision, OffsetDateTime::now_utc())
.await
.map_err(|error| match error {
RegistryError::OnboardingStaleRevision => ApiError::conflict_with_context(
"onboarding state changed; reload before resetting the selection",
json!({"error_code":"onboarding_stale_revision","recovery":"reload"}),
),
other => ApiError::from(other),
})?;
Ok(ResetOnboardingSelectionResponse {
selection_reset: true,
onboarding: self.map_onboarding_response(projection).await?,
})
}
async fn map_onboarding_response(
&self,
projection: OnboardingProjection,
) -> Result<OnboardingResponse, ApiError> {
let endpoint = if let Some(agent_id) = projection.agent_id.as_ref() {
let workspace = self.get_workspace(&projection.workspace_id).await?;
let agent = self
.registry
.get_agent_summary(&projection.workspace_id, agent_id)
.await?
.ok_or_else(|| ApiError::internal("onboarding agent disappeared"))?;
Some(self.public_agent_mcp_endpoint(&workspace.workspace.slug, &agent.slug))
} else {
None
};
let first_call = match (
projection.first_call_log_id.as_ref(),
projection.agent_id.as_ref(),
projection.platform_api_key_id.as_ref(),
projection.operation_id.as_ref(),
projection.operation_version,
projection.first_call_tool_name.as_ref(),
projection.first_call_at,
) {
(
Some(log_id),
Some(agent_id),
Some(key_id),
Some(operation_id),
Some(operation_version),
Some(tool_name),
Some(occurred_at),
) => Some(OnboardingFirstCallEvidence {
log_id: log_id.as_str().to_owned(),
agent_id: agent_id.as_str().to_owned(),
key_id: key_id.as_str().to_owned(),
operation_id: operation_id.as_str().to_owned(),
operation_version,
tool_name: tool_name.clone(),
occurred_at: format_timestamp(occurred_at),
request_id: projection.first_call_request_id.clone(),
trace_id: projection.first_call_trace_id.clone(),
}),
_ => None,
};
let first_incomplete = projection.steps.iter().position(|step| !step.completed);
Ok(OnboardingResponse {
schema_version: 1,
workspace_id: projection.workspace_id.as_str().to_owned(),
revision: projection.revision,
status: if projection.completed {
"complete".to_owned()
} else {
"in_progress".to_owned()
},
completed: projection.completed,
eligible_since: projection.eligible_since.map(format_timestamp),
steps: projection
.steps
.iter()
.enumerate()
.map(|(index, step)| {
let status = if step.completed {
"complete"
} else if projection.was_completed {
"regressed"
} else if Some(index) == first_incomplete {
"current"
} else {
"pending"
};
let reason_code = match status {
"complete" => "authoritative_evidence_present",
"regressed" => "authoritative_evidence_regressed",
"current" => "authoritative_evidence_missing",
_ => "prerequisite_incomplete",
};
OnboardingStepView {
id: step.id,
completed: step.completed,
status: status.to_owned(),
action_code: action_code(step.id).to_owned(),
reason_code: reason_code.to_owned(),
}
})
.collect(),
operation_id: projection.operation_id.map(|id| id.as_str().to_owned()),
operation_version: projection.operation_version,
agent_id: projection.agent_id.map(|id| id.as_str().to_owned()),
catalog_revision: projection.catalog_revision,
platform_api_key_id: projection
.platform_api_key_id
.map(|id| id.as_str().to_owned()),
mcp_endpoint: endpoint,
first_call,
})
}
}
fn action_code(step: OnboardingStepId) -> &'static str {
match step {
OnboardingStepId::Operation => "create_operation",
OnboardingStepId::Test => "test_operation",
OnboardingStepId::PublishOperation => "publish_operation",
OnboardingStepId::Agent => "publish_agent",
OnboardingStepId::Key => "create_mcp_key",
OnboardingStepId::McpConnection => "connect_mcp_client",
OnboardingStepId::FirstCall => "call_tool",
}
}
fn onboarding_event_not_allowed() -> ApiError {
ApiError::unprocessable_with_context(
"client cannot complete authoritative onboarding steps",
json!({"error_code":"onboarding_event_not_allowed"}),
)
}
+247 -97
View File
@@ -1,14 +1,17 @@
use crank_core::{
ConfigExport, ExecutionMode, ExportMode, InvocationLevel, InvocationSource, InvocationStatus,
OperationId, OperationStatus, Samples, WorkspaceId,
ConfigExport, ExecutionMode, ExecutionOrigin, ExportMode, InvocationLevel, InvocationSource,
InvocationStatus, OperationAvailability, OperationId, OperationStatus, OperationVersionState,
Samples, WorkspaceId,
};
use crank_registry::{
CreateVersionRequest, OperationVersionRecord, PublishRequest, RegistryOperation,
CreateVersionRequest, OperationStateExpectation, OperationVersionRecord, PublishRequest,
RegistryOperation,
};
use crank_runtime::{
RuntimeError, RuntimeExecutionRequest, RuntimeOperation, RuntimeRequestContext,
ExecutionAuthorization, RuntimeExecutionRequest, RuntimeOperation, RuntimeRequestContext,
};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use time::OffsetDateTime;
use tracing::{info, instrument};
@@ -18,13 +21,33 @@ use crate::{
AdminService, CreatedOperationResponse, InvocationRecordRequest, NewVersionPayload,
OperationDetailView, OperationMutationResult, OperationPayload, OperationSummaryView,
PublishResponse, TestRunPayload, TestRunResult, UpdateOperationPayload, VersionRef,
agent_ref_map, build_request_preview, default_usage_summary, enrich_operation_summary,
format_timestamp, new_prefixed_id, now_string, runtime_error_code, today_start_utc,
tool_quality_mapping_set, tool_quality_schema_node, usage_map,
agent_ref_map, default_usage_summary, enrich_operation_summary, format_timestamp,
new_prefixed_id, now_string, today_start_utc, tool_quality_mapping_set,
tool_quality_schema_node, usage_map,
},
};
impl AdminService {
pub fn operation_state_etag(detail: &OperationDetailView) -> String {
let material = format!(
"operation-state-v2\0{}\0{}\0{}\0{:?}\0{:?}",
detail.workspace_id,
detail.id,
detail.current_draft_version,
detail.status,
detail.latest_published_version
);
format!("\"{:x}\"", Sha256::digest(material.as_bytes()))
}
pub fn operation_version_etag(record: &OperationVersionRecord) -> Result<String, ApiError> {
let bytes = serde_json::to_vec(&record.snapshot)
.map_err(|_| ApiError::internal("operation version serialization failed"))?;
let mut digest = Sha256::new();
digest.update(b"operation-version-v2\0");
digest.update(bytes);
Ok(format!("\"{:x}\"", digest.finalize()))
}
pub async fn list_operations(
&self,
workspace_id: &WorkspaceId,
@@ -84,6 +107,11 @@ impl AdminService {
let refs = agent_ref_map(agent_refs)
.remove(operation_id.as_str())
.unwrap_or_default();
let current_version = self
.registry
.get_operation_version(workspace_id, operation_id, summary.current_draft_version)
.await?
.ok_or_else(|| ApiError::internal("current operation version is unavailable"))?;
Ok(OperationDetailView {
id: summary.id.as_str().to_owned(),
@@ -94,6 +122,11 @@ impl AdminService {
protocol: summary.protocol,
security_level: summary.security_level,
status: summary.status,
availability: if summary.status == OperationStatus::Archived {
OperationAvailability::Archived
} else {
OperationAvailability::Active
},
current_draft_version: summary.current_draft_version,
latest_published_version: summary.latest_published_version,
created_at: format_timestamp(summary.created_at),
@@ -101,11 +134,15 @@ impl AdminService {
published_at: summary.published_at.map(format_timestamp),
draft_version_ref: VersionRef {
version: summary.current_draft_version,
status: summary.status,
status: if current_version.status == OperationStatus::Published {
OperationVersionState::Published
} else {
OperationVersionState::Draft
},
},
published_version_ref: summary.latest_published_version.map(|version| VersionRef {
version,
status: OperationStatus::Published,
status: OperationVersionState::Published,
}),
agent_refs: refs,
})
@@ -155,6 +192,8 @@ impl AdminService {
}
let snapshot = self.new_operation_snapshot(payload)?;
self.validate_registry_operation_in_workspace(workspace_id, &snapshot)
.await?;
let operation_id = snapshot.id.clone();
self.registry
@@ -240,6 +279,7 @@ impl AdminService {
workspace_id: &WorkspaceId,
operation_id: &OperationId,
payload: NewVersionPayload,
expected_state: &OperationStateExpectation,
) -> Result<CreatedOperationResponse, ApiError> {
self.validate_operation_payload(&payload.operation)?;
@@ -254,7 +294,27 @@ impl AdminService {
)
})?;
let now = OffsetDateTime::now_utc();
let version = summary.current_draft_version + 1;
if summary.current_draft_version != expected_state.current_draft_version
|| summary.status != expected_state.status
|| summary.latest_published_version != expected_state.latest_published_version
{
return Err(crank_registry::RegistryError::OperationStaleVersion {
operation_id: operation_id.as_str().to_owned(),
expected: expected_state.current_draft_version,
actual: summary.current_draft_version,
}
.into());
}
let version = summary
.current_draft_version
.checked_add(1)
.filter(|value| i32::try_from(*value).is_ok())
.ok_or_else(|| {
ApiError::conflict_with_context(
"operation revision limit reached",
json!({ "error_code": "operation_revision_exhausted" }),
)
})?;
let snapshot = RegistryOperation {
id: operation_id.clone(),
name: payload.operation.name,
@@ -283,13 +343,19 @@ impl AdminService {
published_at: None,
};
self.validate_registry_operation_in_workspace(workspace_id, &snapshot)
.await?;
self.registry
.create_version(CreateVersionRequest {
workspace_id,
snapshot: &snapshot,
change_note: payload.change_note.as_deref(),
created_by: None,
})
.create_version_cas(
CreateVersionRequest {
workspace_id,
snapshot: &snapshot,
change_note: payload.change_note.as_deref(),
created_by: None,
},
expected_state,
)
.await?;
info!(
name: "admin.operation.version_created",
@@ -313,21 +379,20 @@ impl AdminService {
workspace_id: &WorkspaceId,
operation_id: &OperationId,
payload: UpdateOperationPayload,
expected_state: &OperationStateExpectation,
) -> Result<OperationMutationResult, ApiError> {
let existing = self
.get_operation_version(
workspace_id,
operation_id,
self.get_operation(workspace_id, operation_id)
.await?
.current_draft_version,
expected_state.current_draft_version,
)
.await?;
let updated_at = OffsetDateTime::now_utc();
let snapshot = RegistryOperation {
id: operation_id.clone(),
name: existing.snapshot.name,
name: existing.snapshot.name.clone(),
display_name: payload.display_name,
category: payload.category,
protocol: existing.snapshot.protocol,
@@ -341,24 +406,39 @@ impl AdminService {
output_mapping: payload.output_mapping,
execution_config: payload.execution_config,
tool_description: payload.tool_description,
samples: existing.snapshot.samples,
generated_draft: existing.snapshot.generated_draft,
config_export: existing.snapshot.config_export,
samples: existing.snapshot.samples.clone(),
generated_draft: existing.snapshot.generated_draft.clone(),
config_export: existing.snapshot.config_export.clone(),
wizard_state: payload.wizard_state,
created_at: existing.snapshot.created_at,
updated_at,
published_at: existing.snapshot.published_at,
};
self.validate_registry_operation(&snapshot)?;
self.validate_registry_operation_in_workspace(workspace_id, &snapshot)
.await?;
if existing.snapshot.portable_semantically_eq(&snapshot)
&& existing.snapshot.wizard_state == snapshot.wizard_state
{
self.registry
.verify_operation_state(workspace_id, operation_id, expected_state)
.await?;
return Ok(OperationMutationResult {
operation_id: operation_id.as_str().to_owned(),
workspace_id: workspace_id.as_str().to_owned(),
version: existing.version,
status: existing.status,
updated_at: format_timestamp(existing.snapshot.updated_at),
});
}
self.registry
.update_operation_draft(workspace_id, &snapshot)
.update_operation_draft_cas(workspace_id, &snapshot, expected_state)
.await?;
Ok(OperationMutationResult {
operation_id: operation_id.as_str().to_owned(),
workspace_id: workspace_id.as_str().to_owned(),
version: snapshot.version,
version: snapshot.version.saturating_add(1),
status: snapshot.status,
updated_at: format_timestamp(updated_at),
})
@@ -370,16 +450,56 @@ impl AdminService {
workspace_id: &WorkspaceId,
operation_id: &OperationId,
version: u32,
expected_state: &OperationStateExpectation,
) -> Result<PublishResponse, ApiError> {
let record = self
.get_operation_version(workspace_id, operation_id, version)
.await?;
self.validate_registry_operation_in_workspace(workspace_id, &record.snapshot)
.await?;
let mut findings = crank_core::analyze_tool_identity_quality(
&record.snapshot.name,
&record.snapshot.tool_description,
)
.findings;
findings.extend(
crank_core::analyze_tool_schema_quality(
"input_schema",
&tool_quality_schema_node(&record.snapshot.input_schema),
)
.findings,
);
findings.extend(
crank_core::analyze_tool_response_projection_quality(&tool_quality_mapping_set(
&record.snapshot.output_mapping,
))
.findings,
);
let report = crank_core::ToolQualityReport::new(findings);
if report.blocking {
return Err(ApiError::unprocessable_with_context(
"operation publish is blocked by quality findings",
json!({
"error_code": "operation_publish_blocked",
"findings": report.findings
}),
));
}
let published_at = OffsetDateTime::now_utc();
self.registry
.publish_operation(PublishRequest {
workspace_id,
operation_id,
version,
published_at: &published_at,
published_by: None,
})
.publish_operation_cas(
PublishRequest {
workspace_id,
operation_id,
version,
published_at: &published_at,
published_by: None,
},
expected_state,
)
.await?;
let authoritative = self
.get_operation_version(workspace_id, operation_id, version)
.await?;
info!(
name: "admin.operation.published",
@@ -392,7 +512,11 @@ impl AdminService {
operation_id: operation_id.as_str().to_owned(),
workspace_id: workspace_id.as_str().to_owned(),
published_version: version,
published_at: format_timestamp(published_at),
published_at: authoritative
.snapshot
.published_at
.map(format_timestamp)
.unwrap_or_else(|| format_timestamp(published_at)),
})
}
@@ -401,19 +525,21 @@ impl AdminService {
&self,
workspace_id: &WorkspaceId,
operation_id: &OperationId,
expected_state: &OperationStateExpectation,
) -> Result<OperationMutationResult, ApiError> {
let summary = self.get_operation(workspace_id, operation_id).await?;
let updated_at = OffsetDateTime::now_utc();
self.registry
.archive_operation(workspace_id, operation_id, &updated_at)
.archive_operation_cas(workspace_id, operation_id, &updated_at, expected_state)
.await?;
let authoritative = self.get_operation(workspace_id, operation_id).await?;
Ok(OperationMutationResult {
operation_id: operation_id.as_str().to_owned(),
workspace_id: workspace_id.as_str().to_owned(),
version: summary.current_draft_version,
status: OperationStatus::Archived,
updated_at: format_timestamp(updated_at),
updated_at: authoritative.updated_at,
})
}
@@ -422,11 +548,12 @@ impl AdminService {
&self,
workspace_id: &WorkspaceId,
operation_id: &OperationId,
expected_state: &OperationStateExpectation,
) -> Result<OperationMutationResult, ApiError> {
let summary = self.get_operation(workspace_id, operation_id).await?;
let updated_at = now_string()?;
self.registry
.delete_operation(workspace_id, operation_id)
.delete_operation_cas(workspace_id, operation_id, expected_state)
.await?;
Ok(OperationMutationResult {
@@ -448,70 +575,77 @@ impl AdminService {
) -> Result<TestRunResult, ApiError> {
let request_id = correlation.request_id().as_str();
let trace_id = correlation.trace_id().as_str();
let runtime_request_context = RuntimeRequestContext::from_correlation(correlation)
let mut runtime_request_context = RuntimeRequestContext::from_correlation(correlation)
.with_metering_context(workspace_id.clone(), None, InvocationSource::AdminTestRun);
if let Some(token) = payload.confirmation_token.as_deref() {
runtime_request_context = runtime_request_context.with_confirmation_token(token);
}
let locale = payload
.locale
.as_deref()
.filter(|value| {
value.eq_ignore_ascii_case("ru") || value.to_ascii_lowercase().starts_with("ru-")
})
.map_or(crank_core::ExecutionLocale::En, |_| {
crank_core::ExecutionLocale::Ru
});
let record = self
.get_operation_version(workspace_id, operation_id, payload.version)
.await?;
let summary = self.get_operation(workspace_id, operation_id).await?;
if summary.status == OperationStatus::Archived
|| record.status != OperationStatus::Draft
|| summary.current_draft_version != payload.version
{
return Err(ApiError::conflict_with_context(
"only the current saved Draft can be tested",
json!({
"operation_id": operation_id.as_str(),
"current_version": summary.current_draft_version,
"tested_version": payload.version,
"error_code": "operation_invalid_transition"
}),
));
}
let runtime = RuntimeOperation::from(record.snapshot.clone());
let mode = ExecutionMode::Unary;
let preview_span = crank_trace::Stage::RuntimeArgumentsMap.span();
let preview_result = preview_span
.in_scope(|| build_request_preview(&record.snapshot.input_mapping, &payload.input));
let request_preview = match preview_result {
Ok(preview) => preview,
Err(error) => {
crank_trace::StageOutcome::Error.record(&preview_span);
crank_trace::ErrorCategory::Mapping.record(&preview_span);
drop(preview_span);
self.record_invocation(InvocationRecordRequest {
workspace_id,
agent_id: None,
operation: &record.snapshot,
request_id: Some(request_id),
trace_id: Some(trace_id),
source: InvocationSource::AdminTestRun,
level: InvocationLevel::Error,
status: InvocationStatus::Error,
message: "mapping preview failed".to_owned(),
status_code: None,
error_kind: Some("mapping".to_owned()),
duration_ms: 0,
request_preview: Value::Null,
response_preview: Value::Null,
})
.await;
return Ok(TestRunResult {
ok: false,
mode,
request_preview: Value::Null,
response_preview: Value::Null,
errors: vec![crate::error::runtime_test_failure(&RuntimeError::Mapping(
error,
))],
});
}
};
crank_trace::StageOutcome::Success.record(&preview_span);
drop(preview_span);
let resolved_auth = self
.resolve_operation_auth(workspace_id, &runtime.execution_config)
.resolve_operation_auth(workspace_id, &runtime.execution_config, None)
.await;
let started_at = std::time::Instant::now();
match match resolved_auth {
let correlation = crank_core::CorrelationContext::new(
runtime_request_context.request_id.clone(),
runtime_request_context.trace_context.clone(),
);
let execution_result = match resolved_auth {
Ok(resolved_auth) => {
self.runtime
.execute_request(
RuntimeExecutionRequest::new(&runtime, &payload.input)
.with_optional_auth(resolved_auth.as_ref())
.with_context(&runtime_request_context),
)
.await
match RuntimeExecutionRequest::try_new(
workspace_id,
ExecutionOrigin::AdminDraft,
None,
&runtime,
&payload.input,
ExecutionAuthorization::Authorized,
resolved_auth.as_ref(),
&runtime_request_context,
std::time::Instant::now()
+ std::time::Duration::from_millis(
runtime.execution_config.timeout_ms.max(1),
),
) {
Ok(request) => self.runtime.execute_outcome(request).await,
Err(_) => Err(crank_core::ExecutionFailure::new(
crank_core::ExecutionErrorCode::RuntimeInternal,
correlation.clone(),
)),
}
}
Err(error) => Err(error),
} {
Ok(response_preview) => {
Err(error) => Err(crank_runtime::normalize_runtime_error(&error, &correlation)),
};
match execution_result {
Ok(success) => {
let response_preview = crank_core::sanitize_invocation_preview(&success.output);
let request_preview = success.request_preview;
let duration_ms =
u64::try_from(started_at.elapsed().as_millis()).unwrap_or(u64::MAX);
self.record_invocation(InvocationRecordRequest {
@@ -526,6 +660,10 @@ impl AdminService {
message: "admin test run completed".to_owned(),
status_code: None,
error_kind: None,
execution_stage: Some(crank_core::ExecutionStage::Runtime),
execution_error_code: None,
retryability: Some(crank_core::Retryability::Never),
outcome_certainty: Some(crank_core::OutcomeCertainty::Certain),
duration_ms,
request_preview: request_preview.clone(),
response_preview: response_preview.clone(),
@@ -534,12 +672,15 @@ impl AdminService {
Ok(TestRunResult {
ok: true,
mode,
tested_version: payload.version,
request_id: request_id.to_owned(),
trace_id: trace_id.to_owned(),
request_preview,
response_preview,
errors: Vec::new(),
})
}
Err(error) => {
Err(failure) => {
let duration_ms =
u64::try_from(started_at.elapsed().as_millis()).unwrap_or(u64::MAX);
self.record_invocation(InvocationRecordRequest {
@@ -551,20 +692,29 @@ impl AdminService {
source: InvocationSource::AdminTestRun,
level: InvocationLevel::Error,
status: InvocationStatus::Error,
message: error.to_string(),
status_code: None,
error_kind: Some(runtime_error_code(&error).to_owned()),
message: "runtime execution failed".to_owned(),
status_code: failure.upstream_status(),
error_kind: Some(failure.error_code().as_str().to_owned()),
execution_stage: Some(failure.stage()),
execution_error_code: Some(failure.error_code()),
retryability: Some(failure.retryability()),
outcome_certainty: Some(failure.outcome_certainty()),
duration_ms,
request_preview: request_preview.clone(),
request_preview: Value::Null,
response_preview: Value::Null,
})
.await;
Ok(TestRunResult {
ok: false,
mode,
request_preview,
tested_version: payload.version,
request_id: request_id.to_owned(),
trace_id: trace_id.to_owned(),
request_preview: Value::Null,
response_preview: Value::Null,
errors: vec![crate::error::runtime_test_failure(&error)],
errors: vec![crate::error::execution_test_failure_localized(
&failure, locale,
)],
})
}
}
+542 -34
View File
@@ -12,7 +12,8 @@ use tracing::{info, instrument};
use crate::{
error::ApiError,
service::{
AdminService, AuthProfilePayload, RotateSecretPayload, SecretPayload, new_prefixed_id,
AdminAuditContext, AdminService, AuthProfilePayload, CredentialAuditRecord,
RotateSecretPayload, SecretPayload, new_prefixed_id,
},
};
@@ -57,15 +58,46 @@ impl AdminService {
})
}
#[instrument(skip(self, payload), fields(workspace_id = %workspace_id.as_str(), secret_name = %payload.name))]
#[instrument(skip(self, created_by, payload, audit_context), fields(workspace_id = %workspace_id.as_str(), secret_name = %payload.name))]
pub async fn create_secret(
&self,
workspace_id: &WorkspaceId,
created_by: Option<&UserId>,
payload: SecretPayload,
audit_context: Option<&AdminAuditContext>,
) -> Result<Secret, ApiError> {
self.ensure_workspace_exists(workspace_id).await?;
validate_secret_payload(&payload)?;
if let Err(error) = self.ensure_workspace_exists(workspace_id).await {
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.secret.create_failed",
target_kind: crank_core::AuditTargetKind::Secret,
workspace_id,
target_id: "pending",
credential_type: "secret",
outcome: "failure",
reason: error.code(),
},
)
.await;
return Err(error);
}
if let Err(error) = validate_secret_payload(&payload) {
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.secret.create_failed",
target_kind: crank_core::AuditTargetKind::Secret,
workspace_id,
target_id: "pending",
credential_type: "secret",
outcome: "failure",
reason: error.code(),
},
)
.await;
return Err(error);
}
let now = OffsetDateTime::now_utc();
let secret = Secret {
@@ -82,89 +114,322 @@ impl AdminService {
let ciphertext = self
.secret_crypto
.encrypt(&payload.value)
.map_err(|error| ApiError::internal(error.to_string()))?;
.map_err(|error| ApiError::internal(error.to_string()));
let ciphertext = match ciphertext {
Ok(ciphertext) => ciphertext,
Err(error) => {
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.secret.create_failed",
target_kind: crank_core::AuditTargetKind::Secret,
workspace_id,
target_id: secret.id.as_str(),
credential_type: "secret",
outcome: "failure",
reason: error.code(),
},
)
.await;
return Err(error);
}
};
self.registry
if let Err(error) = self
.registry
.create_secret(CreateSecretRequest {
secret: &secret,
ciphertext: &ciphertext,
key_version: self.secret_crypto.key_version(),
master_key_epoch: self.secret_crypto.master_key_epoch(),
created_by,
})
.await?;
.await
{
let error = ApiError::from(error);
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.secret.create_failed",
target_kind: crank_core::AuditTargetKind::Secret,
workspace_id,
target_id: secret.id.as_str(),
credential_type: "secret",
outcome: "failure",
reason: error.code(),
},
)
.await;
return Err(error);
}
info!(
name: "admin.secret.created",
secret_id = %secret.id.as_str(),
"secret created"
);
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.secret.created",
target_kind: crank_core::AuditTargetKind::Secret,
workspace_id,
target_id: secret.id.as_str(),
credential_type: "secret",
outcome: "success",
reason: "credential_created",
},
)
.await;
Ok(secret)
}
#[instrument(skip(self, payload), fields(workspace_id = %workspace_id.as_str(), secret_id = %secret_id.as_str()))]
#[instrument(skip(self, created_by, payload, audit_context), fields(workspace_id = %workspace_id.as_str(), secret_id = %secret_id.as_str()))]
pub async fn rotate_secret(
&self,
workspace_id: &WorkspaceId,
secret_id: &SecretId,
created_by: Option<&UserId>,
payload: RotateSecretPayload,
audit_context: Option<&AdminAuditContext>,
) -> Result<Secret, ApiError> {
self.ensure_workspace_exists(workspace_id).await?;
if payload.value.is_null() {
return Err(ApiError::validation("secret value must not be null"));
if let Err(error) = self.ensure_workspace_exists(workspace_id).await {
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.secret.rotate_failed",
target_kind: crank_core::AuditTargetKind::Secret,
workspace_id,
target_id: secret_id.as_str(),
credential_type: "secret",
outcome: "failure",
reason: error.code(),
},
)
.await;
return Err(error);
}
let existing = match self.get_secret(workspace_id, secret_id).await {
Ok(secret) => secret,
Err(error) => {
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.secret.rotate_failed",
target_kind: crank_core::AuditTargetKind::Secret,
workspace_id,
target_id: secret_id.as_str(),
credential_type: "secret",
outcome: "failure",
reason: error.code(),
},
)
.await;
return Err(error);
}
};
if let Err(error) = validate_secret_value(existing.kind, &payload.value) {
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.secret.rotate_failed",
target_kind: crank_core::AuditTargetKind::Secret,
workspace_id,
target_id: secret_id.as_str(),
credential_type: "secret",
outcome: "failure",
reason: error.code(),
},
)
.await;
return Err(error);
}
let now = OffsetDateTime::now_utc();
let ciphertext = self
.secret_crypto
.encrypt(&payload.value)
.map_err(|error| ApiError::internal(error.to_string()))?;
self.registry
.map_err(|error| ApiError::internal(error.to_string()));
let ciphertext = match ciphertext {
Ok(ciphertext) => ciphertext,
Err(error) => {
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.secret.rotate_failed",
target_kind: crank_core::AuditTargetKind::Secret,
workspace_id,
target_id: secret_id.as_str(),
credential_type: "secret",
outcome: "failure",
reason: error.code(),
},
)
.await;
return Err(error);
}
};
let version = match self
.registry
.rotate_secret(RotateSecretRequest {
workspace_id,
secret_id,
ciphertext: &ciphertext,
key_version: self.secret_crypto.key_version(),
master_key_epoch: self.secret_crypto.master_key_epoch(),
created_at: &now,
updated_at: &now,
created_by,
})
.await?;
.await
{
Ok(version) => version,
Err(error) => {
let error = ApiError::from(error);
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.secret.rotate_failed",
target_kind: crank_core::AuditTargetKind::Secret,
workspace_id,
target_id: secret_id.as_str(),
credential_type: "secret",
outcome: "failure",
reason: error.code(),
},
)
.await;
return Err(error);
}
};
info!(
name: "admin.secret.rotated",
secret_id = %secret_id.as_str(),
"secret rotated"
);
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.secret.rotated",
target_kind: crank_core::AuditTargetKind::Secret,
workspace_id,
target_id: secret_id.as_str(),
credential_type: "secret",
outcome: "success",
reason: "credential_rotated",
},
)
.await;
self.get_secret(workspace_id, secret_id).await
Ok(Secret {
current_version: version.secret_version.version,
updated_at: now,
..existing
})
}
#[instrument(skip(self), fields(workspace_id = %workspace_id.as_str(), secret_id = %secret_id.as_str()))]
#[instrument(skip(self, audit_context), fields(workspace_id = %workspace_id.as_str(), secret_id = %secret_id.as_str()))]
pub async fn delete_secret(
&self,
workspace_id: &WorkspaceId,
secret_id: &SecretId,
audit_context: Option<&AdminAuditContext>,
) -> Result<(), ApiError> {
self.ensure_workspace_exists(workspace_id).await?;
if let Some(profile) = self
if let Err(error) = self.ensure_workspace_exists(workspace_id).await {
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.secret.delete_failed",
target_kind: crank_core::AuditTargetKind::Secret,
workspace_id,
target_id: secret_id.as_str(),
credential_type: "secret",
outcome: "failure",
reason: error.code(),
},
)
.await;
return Err(error);
}
let referencing_profiles = match self
.registry
.list_auth_profiles_referencing_secret(workspace_id, secret_id)
.await?
.into_iter()
.next()
.await
{
Ok(profiles) => profiles,
Err(error) => {
let error = ApiError::from(error);
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.secret.delete_failed",
target_kind: crank_core::AuditTargetKind::Secret,
workspace_id,
target_id: secret_id.as_str(),
credential_type: "secret",
outcome: "failure",
reason: error.code(),
},
)
.await;
return Err(error);
}
};
if let Some(profile) = referencing_profiles.into_iter().next() {
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.secret.delete_denied",
target_kind: crank_core::AuditTargetKind::Secret,
workspace_id,
target_id: secret_id.as_str(),
credential_type: "secret",
outcome: "denied",
reason: "secret_referenced_by_auth_profile",
},
)
.await;
return Err(RegistryError::SecretReferencedByAuthProfile {
secret_id: secret_id.as_str().to_owned(),
auth_profile_id: profile.id.as_str().to_owned(),
}
.into());
}
self.registry.delete_secret(workspace_id, secret_id).await?;
if let Err(error) = self.registry.delete_secret(workspace_id, secret_id).await {
let error = ApiError::from(error);
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.secret.delete_failed",
target_kind: crank_core::AuditTargetKind::Secret,
workspace_id,
target_id: secret_id.as_str(),
credential_type: "secret",
outcome: "failure",
reason: error.code(),
},
)
.await;
return Err(error);
}
info!(
name: "admin.secret.deleted",
secret_id = %secret_id.as_str(),
"secret deleted"
);
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.secret.deleted",
target_kind: crank_core::AuditTargetKind::Secret,
workspace_id,
target_id: secret_id.as_str(),
credential_type: "secret",
outcome: "success",
reason: "credential_deleted",
},
)
.await;
Ok(())
}
@@ -185,39 +450,118 @@ impl AdminService {
})
}
#[instrument(skip(self, payload), fields(auth_profile_name = %payload.name, auth_kind = ?payload.kind))]
#[instrument(skip(self, payload, audit_context), fields(auth_profile_name = %payload.name, auth_kind = ?payload.kind))]
pub async fn create_auth_profile(
&self,
workspace_id: &WorkspaceId,
payload: AuthProfilePayload,
audit_context: Option<&AdminAuditContext>,
) -> Result<AuthProfile, ApiError> {
validate_auth_profile_kind(payload.kind, &payload.config)?;
self.ensure_workspace_exists(workspace_id).await?;
self.validate_auth_profile_secret_ids(workspace_id, &payload.config)
.await?;
if let Err(error) = validate_auth_profile_payload(&payload) {
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.auth_profile.create_failed",
target_kind: crank_core::AuditTargetKind::AuthProfile,
workspace_id,
target_id: "pending",
credential_type: "auth_profile",
outcome: "failure",
reason: error.code(),
},
)
.await;
return Err(error);
}
if let Err(error) = self.ensure_workspace_exists(workspace_id).await {
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.auth_profile.create_failed",
target_kind: crank_core::AuditTargetKind::AuthProfile,
workspace_id,
target_id: "pending",
credential_type: "auth_profile",
outcome: "failure",
reason: error.code(),
},
)
.await;
return Err(error);
}
if let Err(error) = self
.validate_auth_profile_secret_ids(workspace_id, &payload.config)
.await
{
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.auth_profile.create_failed",
target_kind: crank_core::AuditTargetKind::AuthProfile,
workspace_id,
target_id: "pending",
credential_type: "auth_profile",
outcome: "failure",
reason: error.code(),
},
)
.await;
return Err(error);
}
let now = OffsetDateTime::now_utc();
let profile = AuthProfile {
id: AuthProfileId::new(new_prefixed_id("auth")),
workspace_id: workspace_id.clone(),
name: payload.name,
name: payload.name.trim().to_owned(),
kind: payload.kind,
config: payload.config,
created_at: now,
updated_at: now,
};
self.registry
if let Err(error) = self
.registry
.save_auth_profile(SaveAuthProfileRequest {
workspace_id,
profile: &profile,
})
.await?;
.await
{
let error = ApiError::from(error);
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.auth_profile.create_failed",
target_kind: crank_core::AuditTargetKind::AuthProfile,
workspace_id,
target_id: profile.id.as_str(),
credential_type: "auth_profile",
outcome: "failure",
reason: error.code(),
},
)
.await;
return Err(error);
}
info!(
name: "admin.auth_profile.created",
auth_profile_id = %profile.id.as_str(),
"auth profile created"
);
self.record_credential_audit(
audit_context,
CredentialAuditRecord {
action: "credential.auth_profile.created",
target_kind: crank_core::AuditTargetKind::AuthProfile,
workspace_id,
target_id: profile.id.as_str(),
credential_type: "auth_profile",
outcome: "success",
reason: "credential_created",
},
)
.await;
Ok(profile)
}
@@ -228,13 +572,45 @@ impl AdminService {
config: &AuthConfig,
) -> Result<(), ApiError> {
for secret_id in config.secret_ids() {
self.get_secret(workspace_id, secret_id).await?;
let secret = self.get_secret(workspace_id, secret_id).await?;
if secret.status != SecretStatus::Active {
return Err(RegistryError::SecretInactive {
secret_id: secret_id.as_str().to_owned(),
}
.into());
}
}
Ok(())
}
}
fn validate_auth_profile_payload(payload: &AuthProfilePayload) -> Result<(), ApiError> {
const MAX_PROFILE_NAME_CHARS: usize = 128;
let profile_name = payload.name.trim();
if profile_name.is_empty() || profile_name.chars().count() > MAX_PROFILE_NAME_CHARS {
return Err(ApiError::validation(
"auth profile name must contain 1 to 128 characters",
));
}
if profile_name.chars().any(char::is_control) {
return Err(ApiError::validation(
"auth profile name contains unsupported characters",
));
}
validate_auth_profile_kind(payload.kind, &payload.config)?;
match &payload.config {
AuthConfig::Bearer(config) => validate_auth_header_name(&config.header_name)?,
AuthConfig::Basic(_) => {}
AuthConfig::ApiKeyHeader(config) => validate_auth_header_name(&config.header_name)?,
AuthConfig::ApiKeyQuery(config) => validate_auth_query_name(&config.param_name)?,
}
Ok(())
}
fn validate_auth_profile_kind(kind: AuthKind, config: &AuthConfig) -> Result<(), ApiError> {
let is_match = matches!(
(kind, config),
@@ -252,13 +628,145 @@ fn validate_auth_profile_kind(kind: AuthKind, config: &AuthConfig) -> Result<(),
}
fn validate_secret_payload(payload: &SecretPayload) -> Result<(), ApiError> {
if payload.name.trim().is_empty() {
return Err(ApiError::validation("secret name must not be empty"));
const MAX_SECRET_NAME_CHARS: usize = 128;
let name = payload.name.trim();
if name.is_empty() || name.chars().count() > MAX_SECRET_NAME_CHARS {
return Err(ApiError::validation(
"secret name must contain 1 to 128 characters",
));
}
if name.chars().any(char::is_control) {
return Err(ApiError::validation(
"secret name contains unsupported characters",
));
}
if payload.value.is_null() {
validate_secret_value(payload.kind, &payload.value)
}
fn validate_secret_value(
kind: crank_core::SecretKind,
value: &serde_json::Value,
) -> Result<(), ApiError> {
const MAX_SECRET_VALUE_BYTES: usize = 65_536;
const MAX_SECRET_STRING_BYTES: usize = 16_384;
if value.is_null() {
return Err(ApiError::validation("secret value must not be null"));
}
let encoded = serde_json::to_vec(value)
.map_err(|_| ApiError::validation("secret value must be valid JSON"))?;
if encoded.len() > MAX_SECRET_VALUE_BYTES {
return Err(ApiError::validation("secret value is too large"));
}
match kind {
crank_core::SecretKind::Token | crank_core::SecretKind::Header => {
if value.is_string() {
validate_non_empty_secret_string(value, "secret value", MAX_SECRET_STRING_BYTES)?;
} else {
let object = value.as_object().ok_or_else(|| {
ApiError::validation(
"token/header secret must be a string or a single token/value field",
)
})?;
let field = object
.get("token")
.or_else(|| object.get("value"))
.filter(|_| object.len() == 1)
.ok_or_else(|| {
ApiError::validation("token/header secret must contain only token or value")
})?;
validate_non_empty_secret_string(field, "secret value", MAX_SECRET_STRING_BYTES)?;
}
}
crank_core::SecretKind::UsernamePassword => {
let object = value.as_object().ok_or_else(|| {
ApiError::validation("username_password secret must contain username and password")
})?;
if object.len() != 2
|| !object.contains_key("username")
|| !object.contains_key("password")
{
return Err(ApiError::validation(
"username_password secret must contain only username and password",
));
}
validate_non_empty_secret_string(
&object["username"],
"secret username",
MAX_SECRET_STRING_BYTES,
)?;
validate_non_empty_secret_string(
&object["password"],
"secret password",
MAX_SECRET_STRING_BYTES,
)?;
}
crank_core::SecretKind::Generic => {}
}
Ok(())
}
fn validate_non_empty_secret_string(
value: &serde_json::Value,
field: &str,
max_bytes: usize,
) -> Result<(), ApiError> {
let value = value
.as_str()
.ok_or_else(|| ApiError::validation(format!("{field} must be a string")))?;
if value.is_empty() {
return Err(ApiError::validation(format!("{field} must not be empty")));
}
if value.len() > max_bytes {
return Err(ApiError::validation(format!("{field} is too large")));
}
Ok(())
}
fn validate_auth_header_name(value: &str) -> Result<(), ApiError> {
const MAX_HEADER_NAME_BYTES: usize = 128;
if value.is_empty()
|| value.len() > MAX_HEADER_NAME_BYTES
|| !value.bytes().all(|byte| {
byte.is_ascii_alphanumeric()
|| matches!(
byte,
b'!' | b'#'
| b'$'
| b'%'
| b'&'
| b'\''
| b'*'
| b'+'
| b'-'
| b'.'
| b'^'
| b'_'
| b'`'
| b'|'
| b'~'
)
})
{
return Err(ApiError::validation("auth header name is invalid"));
}
Ok(())
}
fn validate_auth_query_name(value: &str) -> Result<(), ApiError> {
const MAX_QUERY_NAME_BYTES: usize = 128;
if value.is_empty()
|| value.len() > MAX_QUERY_NAME_BYTES
|| !value.bytes().all(|byte| {
byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.' | b'[' | b']')
})
{
return Err(ApiError::validation("auth query parameter name is invalid"));
}
Ok(())
}
+1
View File
@@ -97,6 +97,7 @@ impl AdminService {
user,
memberships,
current_workspace_id: Some(workspace_id.as_str().to_owned()),
csrf_token: self.rotate_session_csrf_token(session_id).await?,
})
}