369 lines
12 KiB
Rust
369 lines
12 KiB
Rust
use crank_core::{Protocol, ResponseCachePolicy, Target};
|
|
use serde_json::json;
|
|
|
|
use crate::error::ApiError;
|
|
|
|
const MAX_OPERATION_TIMEOUT_MS: u64 = 300_000;
|
|
|
|
pub(super) fn validate_protocol_target(
|
|
protocol: Protocol,
|
|
target: &Target,
|
|
) -> Result<(), ApiError> {
|
|
let is_match = matches!((protocol, target), (Protocol::Rest, Target::Rest(_)));
|
|
|
|
if is_match {
|
|
return Ok(());
|
|
}
|
|
|
|
Err(ApiError::validation("protocol and target kind must match"))
|
|
}
|
|
|
|
pub(super) fn validate_execution_timeout(
|
|
execution_config: &crank_core::ExecutionConfig,
|
|
) -> Result<(), ApiError> {
|
|
if !(1..=MAX_OPERATION_TIMEOUT_MS).contains(&execution_config.timeout_ms) {
|
|
return Err(ApiError::validation_with_context(
|
|
format!("operation timeout must be between 1 and {MAX_OPERATION_TIMEOUT_MS} ms"),
|
|
json!({ "field": "execution_config.timeout_ms" }),
|
|
));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub(super) fn validate_response_cache_policy(
|
|
target: &Target,
|
|
execution_config: &crank_core::ExecutionConfig,
|
|
) -> Result<(), ApiError> {
|
|
let Some(ResponseCachePolicy { ttl_ms }) = execution_config.response_cache.as_ref() else {
|
|
return Ok(());
|
|
};
|
|
|
|
if *ttl_ms == 0 {
|
|
return Err(ApiError::validation_with_context(
|
|
"response cache ttl must be greater than zero".to_owned(),
|
|
json!({
|
|
"field": "execution_config.response_cache.ttl_ms",
|
|
}),
|
|
));
|
|
}
|
|
|
|
match target {
|
|
Target::Rest(rest_target) if rest_target.method == crank_core::HttpMethod::Get => {}
|
|
_ => {
|
|
return Err(ApiError::validation_with_context(
|
|
"response cache is supported only for REST GET operations".to_owned(),
|
|
json!({
|
|
"field": "execution_config.response_cache",
|
|
}),
|
|
));
|
|
}
|
|
}
|
|
|
|
if execution_config.auth_profile_ref.is_some() {
|
|
return Err(ApiError::validation_with_context(
|
|
"response cache is not supported for operations with auth_profile_ref".to_owned(),
|
|
json!({
|
|
"field": "execution_config.auth_profile_ref",
|
|
}),
|
|
));
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
pub(super) fn validate_idempotency_policy(
|
|
target: &Target,
|
|
execution_config: &crank_core::ExecutionConfig,
|
|
) -> Result<(), ApiError> {
|
|
let Some(policy) = execution_config.idempotency.as_ref() else {
|
|
return Ok(());
|
|
};
|
|
|
|
if policy.mode == crank_core::IdempotencyMode::Disabled {
|
|
return Ok(());
|
|
}
|
|
|
|
if policy.ttl_ms == 0 {
|
|
return Err(ApiError::validation_with_context(
|
|
"idempotency ttl must be greater than zero".to_owned(),
|
|
json!({
|
|
"field": "execution_config.idempotency.ttl_ms",
|
|
}),
|
|
));
|
|
}
|
|
|
|
match target {
|
|
Target::Rest(rest_target)
|
|
if matches!(
|
|
rest_target.method,
|
|
crank_core::HttpMethod::Post
|
|
| crank_core::HttpMethod::Put
|
|
| crank_core::HttpMethod::Patch
|
|
| crank_core::HttpMethod::Delete
|
|
) => {}
|
|
_ => {
|
|
return Err(ApiError::validation_with_context(
|
|
"idempotency is supported only for mutating REST operations".to_owned(),
|
|
json!({
|
|
"field": "execution_config.idempotency",
|
|
}),
|
|
));
|
|
}
|
|
}
|
|
|
|
if policy.mode == crank_core::IdempotencyMode::Required
|
|
&& policy.input_field.as_deref().is_none_or(str::is_empty)
|
|
&& policy.header_name.as_deref().is_none_or(str::is_empty)
|
|
{
|
|
return Err(ApiError::validation_with_context(
|
|
"required idempotency needs input_field or header_name".to_owned(),
|
|
json!({
|
|
"field": "execution_config.idempotency",
|
|
}),
|
|
));
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
pub(super) fn validate_approval_policy(
|
|
execution_config: &crank_core::ExecutionConfig,
|
|
) -> Result<(), ApiError> {
|
|
let Some(policy) = execution_config.approval_policy.as_ref() else {
|
|
return Ok(());
|
|
};
|
|
|
|
if !policy.required {
|
|
return Ok(());
|
|
}
|
|
|
|
if policy.ttl_seconds == 0 || policy.ttl_seconds > 300 {
|
|
return Err(ApiError::validation_with_context(
|
|
"approval ttl must be between 1 and 300 seconds".to_owned(),
|
|
json!({
|
|
"field": "execution_config.approval_policy.ttl_seconds",
|
|
}),
|
|
));
|
|
}
|
|
|
|
if let Some(message) = policy.elicitation_message.as_ref()
|
|
&& message.chars().count() > 240
|
|
{
|
|
return Err(ApiError::validation_with_context(
|
|
"approval elicitation message must be at most 240 characters".to_owned(),
|
|
json!({
|
|
"field": "execution_config.approval_policy.elicitation_message",
|
|
}),
|
|
));
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use std::collections::BTreeMap;
|
|
|
|
use crank_core::{
|
|
ExecutionConfig, HttpMethod, IdempotencyMode, IdempotencyPolicy, OperationApprovalMode,
|
|
OperationApprovalPayloadPreviewMode, OperationApprovalPolicy, OperationApprovalRiskLevel,
|
|
ResponseCachePolicy, RestTarget, Target,
|
|
};
|
|
|
|
use super::{
|
|
validate_approval_policy, validate_execution_timeout, validate_idempotency_policy,
|
|
validate_response_cache_policy,
|
|
};
|
|
|
|
fn cacheable_execution_config() -> ExecutionConfig {
|
|
ExecutionConfig {
|
|
timeout_ms: 1_000,
|
|
retry_policy: None,
|
|
response_cache: Some(ResponseCachePolicy { ttl_ms: 5_000 }),
|
|
idempotency: None,
|
|
safety: None,
|
|
approval_policy: None,
|
|
auth_profile_ref: None,
|
|
headers: BTreeMap::new(),
|
|
}
|
|
}
|
|
|
|
fn idempotent_execution_config(mode: IdempotencyMode) -> ExecutionConfig {
|
|
ExecutionConfig {
|
|
timeout_ms: 1_000,
|
|
retry_policy: None,
|
|
response_cache: None,
|
|
idempotency: Some(IdempotencyPolicy {
|
|
mode,
|
|
ttl_ms: 5_000,
|
|
input_field: Some("request_id".to_owned()),
|
|
header_name: Some("Idempotency-Key".to_owned()),
|
|
}),
|
|
safety: None,
|
|
approval_policy: None,
|
|
auth_profile_ref: None,
|
|
headers: BTreeMap::new(),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn accepts_response_cache_for_rest_get() {
|
|
let target = Target::Rest(RestTarget {
|
|
base_url: "http://example.invalid".to_owned(),
|
|
method: HttpMethod::Get,
|
|
path_template: "/catalog".to_owned(),
|
|
static_headers: BTreeMap::new(),
|
|
request_contract: None,
|
|
response_contract: Vec::new(),
|
|
multipart_field_mime_types: BTreeMap::new(),
|
|
});
|
|
|
|
let result = validate_response_cache_policy(&target, &cacheable_execution_config());
|
|
|
|
assert!(result.is_ok());
|
|
}
|
|
|
|
#[test]
|
|
fn rejects_zero_and_excessive_execution_timeouts() {
|
|
let mut config = cacheable_execution_config();
|
|
config.timeout_ms = 0;
|
|
assert!(validate_execution_timeout(&config).is_err());
|
|
|
|
config.timeout_ms = 300_001;
|
|
assert!(validate_execution_timeout(&config).is_err());
|
|
|
|
config.timeout_ms = 300_000;
|
|
assert!(validate_execution_timeout(&config).is_ok());
|
|
}
|
|
|
|
#[test]
|
|
fn rejects_response_cache_for_non_get_rest_operation() {
|
|
let target = Target::Rest(RestTarget {
|
|
base_url: "http://example.invalid".to_owned(),
|
|
method: HttpMethod::Post,
|
|
path_template: "/catalog".to_owned(),
|
|
static_headers: BTreeMap::new(),
|
|
request_contract: None,
|
|
response_contract: Vec::new(),
|
|
multipart_field_mime_types: BTreeMap::new(),
|
|
});
|
|
|
|
let error =
|
|
validate_response_cache_policy(&target, &cacheable_execution_config()).unwrap_err();
|
|
|
|
assert!(matches!(error, crate::error::ApiError::Validation { .. }));
|
|
assert_eq!(
|
|
error.to_string(),
|
|
"response cache is supported only for REST GET operations"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn accepts_idempotency_for_mutating_rest_operation() {
|
|
let target = Target::Rest(RestTarget {
|
|
base_url: "http://example.invalid".to_owned(),
|
|
method: HttpMethod::Post,
|
|
path_template: "/orders".to_owned(),
|
|
static_headers: BTreeMap::new(),
|
|
request_contract: None,
|
|
response_contract: Vec::new(),
|
|
multipart_field_mime_types: BTreeMap::new(),
|
|
});
|
|
|
|
let result = validate_idempotency_policy(
|
|
&target,
|
|
&idempotent_execution_config(IdempotencyMode::Required),
|
|
);
|
|
|
|
assert!(result.is_ok());
|
|
}
|
|
|
|
#[test]
|
|
fn rejects_idempotency_for_rest_get() {
|
|
let target = Target::Rest(RestTarget {
|
|
base_url: "http://example.invalid".to_owned(),
|
|
method: HttpMethod::Get,
|
|
path_template: "/orders".to_owned(),
|
|
static_headers: BTreeMap::new(),
|
|
request_contract: None,
|
|
response_contract: Vec::new(),
|
|
multipart_field_mime_types: BTreeMap::new(),
|
|
});
|
|
|
|
let error = validate_idempotency_policy(
|
|
&target,
|
|
&idempotent_execution_config(IdempotencyMode::Optional),
|
|
)
|
|
.unwrap_err();
|
|
|
|
assert!(matches!(error, crate::error::ApiError::Validation { .. }));
|
|
assert_eq!(
|
|
error.to_string(),
|
|
"idempotency is supported only for mutating REST operations"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn rejects_required_idempotency_without_key_source() {
|
|
let target = Target::Rest(RestTarget {
|
|
base_url: "http://example.invalid".to_owned(),
|
|
method: HttpMethod::Post,
|
|
path_template: "/orders".to_owned(),
|
|
static_headers: BTreeMap::new(),
|
|
request_contract: None,
|
|
response_contract: Vec::new(),
|
|
multipart_field_mime_types: BTreeMap::new(),
|
|
});
|
|
let mut config = idempotent_execution_config(IdempotencyMode::Required);
|
|
let policy = config.idempotency.as_mut().unwrap();
|
|
policy.input_field = None;
|
|
policy.header_name = None;
|
|
|
|
let error = validate_idempotency_policy(&target, &config).unwrap_err();
|
|
|
|
assert!(matches!(error, crate::error::ApiError::Validation { .. }));
|
|
assert_eq!(
|
|
error.to_string(),
|
|
"required idempotency needs input_field or header_name"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn accepts_valid_approval_policy() {
|
|
let mut config = cacheable_execution_config();
|
|
config.approval_policy = Some(OperationApprovalPolicy {
|
|
required: true,
|
|
mode: OperationApprovalMode::Custom,
|
|
risk_level: OperationApprovalRiskLevel::Dangerous,
|
|
ttl_seconds: 300,
|
|
show_payload_preview: true,
|
|
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
|
|
elicitation_message: None,
|
|
});
|
|
|
|
validate_approval_policy(&config).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn rejects_invalid_approval_policy() {
|
|
let mut config = cacheable_execution_config();
|
|
config.approval_policy = Some(OperationApprovalPolicy {
|
|
required: true,
|
|
mode: OperationApprovalMode::Custom,
|
|
risk_level: OperationApprovalRiskLevel::Dangerous,
|
|
ttl_seconds: 0,
|
|
show_payload_preview: true,
|
|
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
|
|
elicitation_message: None,
|
|
});
|
|
|
|
let error = validate_approval_policy(&config).unwrap_err();
|
|
|
|
assert!(matches!(error, crate::error::ApiError::Validation { .. }));
|
|
assert_eq!(
|
|
error.to_string(),
|
|
"approval ttl must be between 1 and 300 seconds"
|
|
);
|
|
}
|
|
}
|