Files
crank/apps/admin-api/tests/integration/openapi_import/security.rs
T

660 lines
21 KiB
Rust

use super::*;
#[tokio::test]
#[serial]
async fn literal_credential_is_rejected_before_any_import_artifact_or_job_is_created() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_literal_credential_rejected"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let canary = "atdd-secret-canary-2-10-api";
let upload = OpenApiUpload {
bytes: format!(
r#"
openapi: 3.0.3
info: {{ title: Secret canary }}
paths:
/items:
get:
responses:
'200': {{ description: ok }}
x-api-key: {canary}
"#
)
.into_bytes(),
mime_type: "application/yaml".to_owned(),
locale: OpenApiUploadLocale::En,
};
let error = service
.preview_openapi_import(&workspace_id, upload)
.await
.unwrap_err();
assert!(!format!("{error:?}").contains(canary));
let import_jobs: i64 =
sqlx::query_scalar("select count(*) from import_jobs where workspace_id = $1")
.bind(workspace_id.as_str())
.fetch_one(registry.pool())
.await
.unwrap();
let artifact_sources: i64 =
sqlx::query_scalar("select count(*) from artifact_sources where workspace_id = $1")
.bind(workspace_id.as_str())
.fetch_one(registry.pool())
.await
.unwrap();
assert_eq!(import_jobs, 0);
assert_eq!(artifact_sources, 0);
}
#[tokio::test]
#[serial]
async fn auth_profiles_are_workspace_scoped_revalidated_and_shared_secret_availability_is_current()
{
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_auth_profile_binding"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let secret = service
.create_secret(
&workspace_id,
None,
SecretPayload {
name: "shared-openapi-token".to_owned(),
kind: SecretKind::Token,
value: json!("integration-secret-canary"),
},
None,
)
.await
.unwrap();
let ciphertext = registry
.get_current_secret_version(&workspace_id, &secret.id)
.await
.unwrap()
.unwrap()
.secret_version
.ciphertext;
let secret_hash = format!("{:x}", sha2::Sha256::digest(b"integration-secret-canary"));
let profile_a = create_bearer_profile(&service, &workspace_id, "profile-a", &secret.id).await;
let profile_b = create_bearer_profile(&service, &workspace_id, "profile-b", &secret.id).await;
let preview = service
.preview_openapi_import(&workspace_id, two_protected_operations_upload())
.await
.unwrap();
assert_eq!(preview.auth_profile_choices.len(), 2);
for choice in &preview.auth_profile_choices {
assert!(choice.supported);
assert_eq!(choice.profiles.len(), 2);
}
let response = serde_json::to_string(&preview).unwrap();
assert!(!response.contains("integration-secret-canary"));
let applied = service
.create_openapi_import(
&workspace_id,
&preview.job_id.as_str().into(),
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /a".to_owned(), "GET /b".to_owned()],
auth_mappings: vec![
OpenApiAuthMapping {
operation_key: "GET /a".to_owned(),
alternative_index: 0,
auth_profile_id: Some(profile_a.id.as_str().to_owned()),
},
OpenApiAuthMapping {
operation_key: "GET /b".to_owned(),
alternative_index: 0,
auth_profile_id: Some(profile_b.id.as_str().to_owned()),
},
],
server_url: None,
conflict_mode: "skip".to_owned(),
},
)
.await
.unwrap();
assert_eq!(applied.created.len(), 2);
for created in &applied.created {
let version = service
.get_operation_version(
&workspace_id,
&created.operation_id.as_str().into(),
created.version,
)
.await
.unwrap();
let profile_ref = version
.snapshot
.execution_config
.auth_profile_ref
.as_ref()
.unwrap();
let serialized_operation = serde_json::to_string(&version.snapshot).unwrap();
assert!(serialized_operation.contains(profile_ref.as_str()));
assert!(!serialized_operation.contains("integration-secret-canary"));
assert!(!serialized_operation.contains(&ciphertext));
assert!(!serialized_operation.contains(&secret_hash));
}
let changed_mapping_replay = service
.create_openapi_import(
&workspace_id,
&preview.job_id.as_str().into(),
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /a".to_owned(), "GET /b".to_owned()],
auth_mappings: vec![
OpenApiAuthMapping {
operation_key: "GET /a".to_owned(),
alternative_index: 0,
auth_profile_id: Some(profile_b.id.as_str().to_owned()),
},
OpenApiAuthMapping {
operation_key: "GET /b".to_owned(),
alternative_index: 0,
auth_profile_id: Some(profile_a.id.as_str().to_owned()),
},
],
server_url: None,
conflict_mode: "skip".to_owned(),
},
)
.await;
assert!(changed_mapping_replay.is_err());
assert_eq!(
service.list_operations(&workspace_id).await.unwrap().len(),
2
);
let now = time::OffsetDateTime::now_utc();
let foreign_workspace_id = WorkspaceId::new("ws_openapi_auth_foreign");
let foreign_workspace = Workspace {
id: foreign_workspace_id.clone(),
slug: "openapi-auth-foreign".to_owned(),
display_name: "OpenAPI Auth Foreign".to_owned(),
status: WorkspaceStatus::Active,
settings: json!({}),
created_at: now,
updated_at: now,
};
registry
.create_workspace(CreateWorkspaceRequest {
workspace: &foreign_workspace,
})
.await
.unwrap();
let foreign_secret = service
.create_secret(
&foreign_workspace_id,
None,
SecretPayload {
name: "foreign-token".to_owned(),
kind: SecretKind::Token,
value: json!("foreign-secret-canary"),
},
None,
)
.await
.unwrap();
let foreign_profile = create_bearer_profile(
&service,
&foreign_workspace_id,
"foreign-profile",
&foreign_secret.id,
)
.await;
let choices_preview = service
.preview_openapi_import(&workspace_id, two_protected_operations_upload())
.await
.unwrap();
assert!(
choices_preview
.auth_profile_choices
.iter()
.flat_map(|choice| &choice.profiles)
.all(|profile| profile.id != foreign_profile.id.as_str())
);
let missing_error =
apply_first_protected_mapping(&service, &workspace_id, "auth_missing_profile")
.await
.unwrap_err();
let foreign_error =
apply_first_protected_mapping(&service, &workspace_id, foreign_profile.id.as_str())
.await
.unwrap_err();
assert_eq!(format!("{missing_error:?}"), format!("{foreign_error:?}"));
assert!(!format!("{foreign_error:?}").contains(foreign_profile.id.as_str()));
sqlx::query("update secrets set status = 'disabled' where workspace_id = $1 and id = $2")
.bind(workspace_id.as_str())
.bind(secret.id.as_str())
.execute(registry.pool())
.await
.unwrap();
let disabled_preview = service
.preview_openapi_import(&workspace_id, two_protected_operations_upload())
.await
.unwrap();
assert!(
disabled_preview
.auth_profile_choices
.iter()
.all(|choice| choice.profiles.is_empty())
);
let before_disabled_apply = service.list_operations(&workspace_id).await.unwrap().len();
let disabled_error = service
.create_openapi_import_with_locale(
&workspace_id,
&disabled_preview.job_id.as_str().into(),
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /a".to_owned()],
auth_mappings: vec![OpenApiAuthMapping {
operation_key: "GET /a".to_owned(),
alternative_index: 0,
auth_profile_id: Some(profile_a.id.as_str().to_owned()),
}],
server_url: None,
conflict_mode: "skip".to_owned(),
},
OpenApiUploadLocale::Ru,
)
.await
.unwrap_err();
match &disabled_error {
admin_api::error::ApiError::Unprocessable { message, context } => {
assert_eq!(
message,
"выбранный профиль аутентификации недоступен для этого импорта"
);
assert_eq!(
context.as_ref().unwrap()["error_code"],
"openapi_auth_binding_unavailable"
);
}
other => panic!("expected localized auth binding error, got {other:?}"),
}
let disabled_shared_profile_error =
apply_first_protected_mapping(&service, &workspace_id, profile_b.id.as_str())
.await
.unwrap_err();
assert_eq!(
format!("{disabled_shared_profile_error:?}"),
format!("{missing_error:?}")
);
assert_eq!(
service.list_operations(&workspace_id).await.unwrap().len(),
before_disabled_apply
);
}
#[tokio::test]
#[serial]
async fn selected_supported_or_and_explicit_no_auth_alternatives_apply_without_collapsing_semantics()
{
let registry = test_registry().await;
let service = test_service(
registry,
test_storage_root("openapi_import_auth_alternatives"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let secret = service
.create_secret(
&workspace_id,
None,
SecretPayload {
name: "or-token".to_owned(),
kind: SecretKind::Token,
value: json!("or-profile-secret"),
},
None,
)
.await
.unwrap();
let profile = create_bearer_profile(&service, &workspace_id, "or-bearer", &secret.id).await;
let preview = service
.preview_openapi_import(&workspace_id, security_alternatives_upload())
.await
.unwrap();
let choices = preview
.auth_profile_choices
.iter()
.filter(|choice| choice.operation_key == "GET /choice")
.collect::<Vec<_>>();
assert_eq!(choices.len(), 2);
assert!(choices[0].supported);
assert_eq!(choices[0].profiles.len(), 1);
assert!(!choices[1].supported);
let either = preview
.auth_profile_choices
.iter()
.filter(|choice| choice.operation_key == "GET /either")
.collect::<Vec<_>>();
assert_eq!(either.len(), 2);
assert!(either[1].supported);
let applied = service
.create_openapi_import(
&workspace_id,
&preview.job_id.as_str().into(),
OpenApiImportCreatePayload {
selected_operation_keys: vec![
"GET /choice".to_owned(),
"GET /either".to_owned(),
"GET /public".to_owned(),
],
auth_mappings: vec![
OpenApiAuthMapping {
operation_key: "GET /choice".to_owned(),
alternative_index: 0,
auth_profile_id: Some(profile.id.as_str().to_owned()),
},
OpenApiAuthMapping {
operation_key: "GET /either".to_owned(),
alternative_index: 1,
auth_profile_id: None,
},
],
server_url: None,
conflict_mode: "skip".to_owned(),
},
)
.await
.unwrap();
assert_eq!(applied.created.len(), 3);
for created in &applied.created {
let version = service
.get_operation_version(
&workspace_id,
&created.operation_id.as_str().into(),
created.version,
)
.await
.unwrap();
let auth_profile_ref = version.snapshot.execution_config.auth_profile_ref;
match created.operation_key.as_str() {
"GET /choice" => assert_eq!(auth_profile_ref, Some(profile.id.clone())),
"GET /either" | "GET /public" => assert!(auth_profile_ref.is_none()),
other => panic!("unexpected operation {other}"),
}
}
}
#[tokio::test]
#[serial]
async fn changed_security_scheme_after_preview_fails_digest_check_without_draft_mutation() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_security_scheme_drift"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let secret = service
.create_secret(
&workspace_id,
None,
SecretPayload {
name: "drift-test-token".to_owned(),
kind: SecretKind::Token,
value: json!("scheme-drift-profile-secret"),
},
None,
)
.await
.unwrap();
let profile =
create_bearer_profile(&service, &workspace_id, "drift-test-profile", &secret.id).await;
let bearer_preview = service
.preview_openapi_import(&workspace_id, security_scheme_upload(false))
.await
.unwrap();
let api_key_preview = service
.preview_openapi_import(&workspace_id, security_scheme_upload(true))
.await
.unwrap();
let bearer_job: crank_registry::ImportJobId = bearer_preview.job_id.as_str().into();
let api_key_job: crank_registry::ImportJobId = api_key_preview.job_id.as_str().into();
let api_key_source = registry
.get_import_job(&workspace_id, &api_key_job)
.await
.unwrap()
.unwrap()
.preview_payload["source"]
.clone();
sqlx::query(
"update import_jobs
set preview_payload = jsonb_set(
jsonb_set(preview_payload, '{source,source_id}', $1, false),
'{source,digest}', $2, false
)
where workspace_id = $3 and id = $4",
)
.bind(&api_key_source["source_id"])
.bind(&api_key_source["digest"])
.bind(workspace_id.as_str())
.bind(bearer_job.as_str())
.execute(registry.pool())
.await
.unwrap();
let error = service
.create_openapi_import(
&workspace_id,
&bearer_job,
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /secure".to_owned()],
auth_mappings: vec![OpenApiAuthMapping {
operation_key: "GET /secure".to_owned(),
alternative_index: 0,
auth_profile_id: Some(profile.id.as_str().to_owned()),
}],
server_url: None,
conflict_mode: "skip".to_owned(),
},
)
.await
.unwrap_err();
match error {
admin_api::error::ApiError::Unprocessable { context, .. } => assert_eq!(
context.unwrap()["error_code"],
"openapi_upload.source_integrity"
),
other => panic!("expected source integrity error, got {other:?}"),
}
let job = registry
.get_import_job(&workspace_id, &bearer_job)
.await
.unwrap()
.unwrap();
assert_eq!(
job.error_text.as_deref(),
Some("import_replay_verification_failed")
);
assert!(
service
.list_operations(&workspace_id)
.await
.unwrap()
.is_empty()
);
}
#[tokio::test]
#[serial]
async fn auth_mapping_for_unselected_operation_is_rejected_without_draft_mutation() {
let registry = test_registry().await;
let service = test_service(
registry,
test_storage_root("openapi_import_unselected_auth_mapping"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace_id, two_protected_operations_upload())
.await
.unwrap();
assert!(
service
.create_openapi_import(
&workspace_id,
&preview.job_id.as_str().into(),
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /a".to_owned()],
auth_mappings: vec![OpenApiAuthMapping {
operation_key: "GET /b".to_owned(),
alternative_index: 0,
auth_profile_id: None,
}],
server_url: None,
conflict_mode: "skip".to_owned(),
},
)
.await
.is_err()
);
assert!(
service
.list_operations(&workspace_id)
.await
.unwrap()
.is_empty()
);
}
fn two_protected_operations_upload() -> OpenApiUpload {
OpenApiUpload {
bytes: br#"
openapi: 3.0.3
info: { title: Protected API }
servers: [{ url: https://api.example.test }]
components:
securitySchemes:
bearerAuth: { type: http, scheme: bearer }
security:
- bearerAuth: []
paths:
/a:
get:
responses: { '200': { description: ok } }
/b:
get:
responses: { '200': { description: ok } }
"#
.to_vec(),
mime_type: "application/yaml".to_owned(),
locale: OpenApiUploadLocale::En,
}
}
fn security_alternatives_upload() -> OpenApiUpload {
OpenApiUpload {
bytes: br#"
openapi: 3.0.3
info: { title: Security alternatives }
servers: [{ url: https://api.example.test }]
components:
securitySchemes:
bearerAuth: { type: http, scheme: bearer }
oauth: { type: oauth2, flows: { implicit: { authorizationUrl: https://auth.example.test, scopes: {} } } }
security:
- bearerAuth: []
- oauth: []
paths:
/choice:
get:
responses: { '200': { description: ok } }
/either:
get:
security:
- bearerAuth: []
- {}
responses: { '200': { description: ok } }
/public:
get:
security: []
responses: { '200': { description: ok } }
"#
.to_vec(),
mime_type: "application/yaml".to_owned(),
locale: OpenApiUploadLocale::En,
}
}
fn security_scheme_upload(api_key: bool) -> OpenApiUpload {
let security_scheme = if api_key {
"auth: { type: apiKey, in: header, name: X-Token }"
} else {
"auth: { type: http, scheme: bearer }"
};
OpenApiUpload {
bytes: format!(
"openapi: 3.0.3\ninfo: {{ title: Scheme drift }}\nservers: [{{ url: https://api.example.test }}]\ncomponents:\n securitySchemes:\n {security_scheme}\nsecurity:\n - auth: []\npaths:\n /secure:\n get:\n responses: {{ '200': {{ description: ok }} }}\n"
)
.into_bytes(),
mime_type: "application/yaml".to_owned(),
locale: OpenApiUploadLocale::En,
}
}
async fn create_bearer_profile(
service: &admin_api::service::AdminService,
workspace_id: &WorkspaceId,
name: &str,
secret_id: &SecretId,
) -> crank_core::AuthProfile {
service
.create_auth_profile(
workspace_id,
AuthProfilePayload {
name: name.to_owned(),
kind: AuthKind::Bearer,
config: AuthConfig::Bearer(BearerAuthConfig {
header_name: "Authorization".to_owned(),
secret_id: secret_id.clone(),
}),
},
None,
)
.await
.unwrap()
}
async fn apply_first_protected_mapping(
service: &admin_api::service::AdminService,
workspace_id: &WorkspaceId,
auth_profile_id: &str,
) -> Result<OpenApiImportCreateResponse, admin_api::error::ApiError> {
let preview = service
.preview_openapi_import(workspace_id, two_protected_operations_upload())
.await?;
service
.create_openapi_import(
workspace_id,
&preview.job_id.as_str().into(),
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /a".to_owned()],
auth_mappings: vec![OpenApiAuthMapping {
operation_key: "GET /a".to_owned(),
alternative_index: 0,
auth_profile_id: Some(auth_profile_id.to_owned()),
}],
server_url: None,
conflict_mode: "skip".to_owned(),
},
)
.await
}