feat(import): bind OpenAPI security schemes safely
This commit is contained in:
1 parent
c562d5368d
commit
41a0e46110
38 files changed
+4651
-590
No files matched your search
@@ -1,6 +1,8 @@
|
||||
use super::*;
|
||||
use crate::{ArtifactSourceId, ImportJobSourceEnvelope};
|
||||
use crank_artifacts::ArtifactRef;
|
||||
use crank_core::{AuthConfig, AuthProfile, AuthProfileId, SecretId};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
const APPLICATION_RESULT_KEY: &str = "_crank_application_result";
|
||||
const IMPORT_JOB_CLEANUP_BATCH: u32 = 128;
|
||||
@@ -388,6 +390,10 @@ async fn apply_import_job_transaction(
|
||||
}
|
||||
}
|
||||
|
||||
// Validate the complete binding set before the first Operation insert.
|
||||
// This transaction-level check closes the gap between preview and Apply.
|
||||
validate_import_auth_bindings(tx, request.workspace_id, request.operations).await?;
|
||||
|
||||
let mut result = ImportJobApplyResult {
|
||||
application_key: request.application_key.to_owned(),
|
||||
skipped: request.pre_skipped.to_vec(),
|
||||
@@ -485,6 +491,190 @@ async fn apply_import_job_transaction(
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
async fn validate_import_auth_bindings(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
operations: &[crate::ImportOperationDraft],
|
||||
) -> Result<(), RegistryError> {
|
||||
let mut requirements_by_profile = BTreeMap::<String, Vec<&crate::ImportAuthRequirement>>::new();
|
||||
for draft in operations {
|
||||
match (
|
||||
draft.auth_requirement.as_ref(),
|
||||
draft.operation.execution_config.auth_profile_ref.as_ref(),
|
||||
) {
|
||||
(None, None) => {}
|
||||
(Some(requirement), Some(profile_id)) => requirements_by_profile
|
||||
.entry(profile_id.as_str().to_owned())
|
||||
.or_default()
|
||||
.push(requirement),
|
||||
_ => return Err(RegistryError::ImportAuthBindingUnavailable),
|
||||
}
|
||||
}
|
||||
if requirements_by_profile.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Read the current workspace's profile config first to discover Secret
|
||||
// references. Secret rows are locked in stable order before profile rows,
|
||||
// matching save_auth_profile's secret-then-profile write order.
|
||||
let mut observed_profiles = BTreeMap::<String, AuthProfile>::new();
|
||||
let mut secret_ids = BTreeMap::<String, SecretId>::new();
|
||||
for profile_id in requirements_by_profile.keys() {
|
||||
let profile = read_import_auth_profile(tx, workspace_id, profile_id, false)
|
||||
.await?
|
||||
.ok_or(RegistryError::ImportAuthBindingUnavailable)?;
|
||||
let requirements = &requirements_by_profile[profile_id];
|
||||
if !requirements
|
||||
.iter()
|
||||
.all(|requirement| auth_profile_matches(profile_id, &profile, requirement))
|
||||
{
|
||||
return Err(RegistryError::ImportAuthBindingUnavailable);
|
||||
}
|
||||
for secret_id in profile.config.secret_ids() {
|
||||
secret_ids
|
||||
.entry(secret_id.as_str().to_owned())
|
||||
.or_insert_with(|| secret_id.clone());
|
||||
}
|
||||
observed_profiles.insert(profile_id.clone(), profile);
|
||||
}
|
||||
|
||||
for secret_id in secret_ids.values() {
|
||||
let row = sqlx::query(
|
||||
"select s.status,
|
||||
exists (
|
||||
select 1 from secret_versions sv
|
||||
where sv.secret_id = s.id and sv.version = s.current_version
|
||||
) as has_current_version
|
||||
from secrets s
|
||||
where s.workspace_id = $1 and s.id = $2
|
||||
for update of s",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(secret_id.as_str())
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?;
|
||||
let Some(row) = row else {
|
||||
return Err(RegistryError::ImportAuthBindingUnavailable);
|
||||
};
|
||||
if row.try_get::<String, _>("status")? != "active"
|
||||
|| !row.try_get::<bool, _>("has_current_version")?
|
||||
{
|
||||
return Err(RegistryError::ImportAuthBindingUnavailable);
|
||||
}
|
||||
}
|
||||
|
||||
// The profile may have changed while its former Secret rows were being
|
||||
// locked. Lock profile rows only after Secrets (the order used by profile
|
||||
// updates), then compare the binding config and revalidate compatibility.
|
||||
for (profile_id, observed) in &observed_profiles {
|
||||
let current = read_import_auth_profile(tx, workspace_id, profile_id, true)
|
||||
.await?
|
||||
.ok_or(RegistryError::ImportAuthBindingUnavailable)?;
|
||||
if current.id != observed.id
|
||||
|| current.workspace_id != observed.workspace_id
|
||||
|| current.kind != observed.kind
|
||||
|| current.config != observed.config
|
||||
|| !requirements_by_profile[profile_id]
|
||||
.iter()
|
||||
.all(|requirement| auth_profile_matches(profile_id, ¤t, requirement))
|
||||
{
|
||||
return Err(RegistryError::ImportAuthBindingUnavailable);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn read_import_auth_profile(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
profile_id: &str,
|
||||
lock: bool,
|
||||
) -> Result<Option<AuthProfile>, RegistryError> {
|
||||
let query = if lock {
|
||||
"select id, workspace_id, name, kind, config_json, created_at, updated_at
|
||||
from auth_profiles
|
||||
where workspace_id = $1 and id = $2
|
||||
for update"
|
||||
} else {
|
||||
"select id, workspace_id, name, kind, config_json, created_at, updated_at
|
||||
from auth_profiles
|
||||
where workspace_id = $1 and id = $2"
|
||||
};
|
||||
let row = sqlx::query(query)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(profile_id)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?;
|
||||
row.map(|row| {
|
||||
super::build_auth_profile(
|
||||
row.try_get("id")?,
|
||||
row.try_get("workspace_id")?,
|
||||
row.try_get("name")?,
|
||||
row.try_get("kind")?,
|
||||
row.try_get("config_json")?,
|
||||
row.try_get("created_at")?,
|
||||
row.try_get("updated_at")?,
|
||||
)
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn auth_profile_matches(
|
||||
expected_profile_id: &str,
|
||||
profile: &AuthProfile,
|
||||
requirement: &crate::ImportAuthRequirement,
|
||||
) -> bool {
|
||||
if profile.id != AuthProfileId::new(expected_profile_id)
|
||||
|| profile.kind != profile.config.kind()
|
||||
|| profile.kind != requirement.kind()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
match (requirement, &profile.config) {
|
||||
(crate::ImportAuthRequirement::Bearer, AuthConfig::Bearer(_))
|
||||
| (crate::ImportAuthRequirement::Basic, AuthConfig::Basic(_)) => true,
|
||||
(
|
||||
crate::ImportAuthRequirement::ApiKeyHeader { parameter_name },
|
||||
AuthConfig::ApiKeyHeader(config),
|
||||
) => {
|
||||
is_valid_auth_header_name(&config.header_name)
|
||||
&& is_valid_auth_header_name(parameter_name)
|
||||
&& config.header_name.eq_ignore_ascii_case(parameter_name)
|
||||
}
|
||||
(
|
||||
crate::ImportAuthRequirement::ApiKeyQuery { parameter_name },
|
||||
AuthConfig::ApiKeyQuery(config),
|
||||
) => config.param_name == *parameter_name,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_valid_auth_header_name(value: &str) -> bool {
|
||||
value.len() <= 128
|
||||
&& !value.is_empty()
|
||||
&& 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'~'
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn validate_source_envelope(
|
||||
source: &ImportJobSourceEnvelope,
|
||||
preview_payload: &Value,
|
||||
|
||||
Reference in new issue
Block a user