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
@@ -4,6 +4,7 @@ use tracing::warn;
|
||||
|
||||
pub(super) struct MaterializedDependencies {
|
||||
pub(super) snapshots: Vec<crank_import::rest::ExternalDocumentSnapshot>,
|
||||
pub(super) secret_literal_rejected: bool,
|
||||
envelopes: Vec<ImportJobSourceEnvelope>,
|
||||
canonical_uris: Vec<String>,
|
||||
guards: Vec<SourceDetachGuard>,
|
||||
@@ -21,6 +22,7 @@ impl MaterializedDependencies {
|
||||
fn empty() -> Self {
|
||||
Self {
|
||||
snapshots: Vec::new(),
|
||||
secret_literal_rejected: false,
|
||||
envelopes: Vec::new(),
|
||||
canonical_uris: Vec::new(),
|
||||
guards: Vec::new(),
|
||||
@@ -207,6 +209,26 @@ impl AdminService {
|
||||
);
|
||||
continue;
|
||||
};
|
||||
match crank_import::rest::scan_secret_literals(&bytes) {
|
||||
Ok(findings) if !findings.is_empty() => {
|
||||
materialization_failure(
|
||||
"security_scan",
|
||||
"literal_credentials_rejected",
|
||||
result.snapshots.len(),
|
||||
);
|
||||
result.secret_literal_rejected = true;
|
||||
break;
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(_) => {
|
||||
materialization_failure(
|
||||
"security_scan",
|
||||
"invalid_document",
|
||||
result.snapshots.len(),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let Ok(references) = crank_import::rest::external_reference_uris(
|
||||
&document,
|
||||
&self.external_reference_normalization,
|
||||
@@ -368,6 +390,14 @@ impl AdminService {
|
||||
}
|
||||
let document = String::from_utf8(verified.bytes)
|
||||
.map_err(|_| ApiError::openapi_upload(locale, "source_integrity"))?;
|
||||
let findings = crank_import::rest::scan_secret_literals(document.as_bytes())
|
||||
.map_err(|_| ApiError::openapi_upload(locale, "source_integrity"))?;
|
||||
if !findings.is_empty() {
|
||||
return Err(ApiError::openapi_upload(
|
||||
locale,
|
||||
"literal_credentials_rejected",
|
||||
));
|
||||
}
|
||||
let digest =
|
||||
crank_import::rest::SourceDigest::parse(dependency.digest.digest_hex().to_owned())
|
||||
.map_err(|_| ApiError::openapi_upload(locale, "source_integrity"))?;
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
use super::*;
|
||||
use crate::service::{OpenApiAuthProfileChoice, OpenApiAuthProfileOption};
|
||||
use crank_core::{AuthConfig, AuthProfile, AuthProfileId};
|
||||
|
||||
impl AdminService {
|
||||
pub(super) async fn openapi_auth_profile_choices(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
preview: &crank_import::rest::ImportPreview,
|
||||
) -> Result<Vec<OpenApiAuthProfileChoice>, ApiError> {
|
||||
let mut profiles = self
|
||||
.registry
|
||||
.list_auth_profiles(workspace_id)
|
||||
.await?
|
||||
.into_iter()
|
||||
.filter(|profile| profile.kind == profile.config.kind())
|
||||
.collect::<Vec<_>>();
|
||||
let mut available_profiles = Vec::with_capacity(profiles.len());
|
||||
for profile in profiles.drain(..) {
|
||||
if auth_profile_is_available(&self.registry, workspace_id, &profile).await? {
|
||||
available_profiles.push(profile);
|
||||
}
|
||||
}
|
||||
let mut choices = Vec::new();
|
||||
for operation in preview
|
||||
.groups
|
||||
.iter()
|
||||
.flat_map(|group| group.operations.iter())
|
||||
{
|
||||
for (alternative_index, alternative) in operation
|
||||
.security_requirements
|
||||
.alternatives
|
||||
.iter()
|
||||
.enumerate()
|
||||
{
|
||||
let scheme = (alternative.schemes.len() == 1)
|
||||
.then(|| operation.security_schemes.get(&alternative.schemes[0]))
|
||||
.flatten();
|
||||
let requirement = scheme.and_then(import_auth_requirement);
|
||||
let supported = alternative.supported
|
||||
&& (alternative.schemes.is_empty() || requirement.is_some());
|
||||
let options = requirement
|
||||
.as_ref()
|
||||
.map(|requirement| {
|
||||
available_profiles
|
||||
.iter()
|
||||
.filter(|profile| auth_profile_matches(profile, requirement))
|
||||
.map(|profile| OpenApiAuthProfileOption {
|
||||
id: profile.id.as_str().to_owned(),
|
||||
name: profile.name.clone(),
|
||||
kind: profile.kind,
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
choices.push(OpenApiAuthProfileChoice {
|
||||
operation_key: operation.key.clone(),
|
||||
alternative_index,
|
||||
scheme_names: alternative.schemes.clone(),
|
||||
supported,
|
||||
profiles: options,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(choices)
|
||||
}
|
||||
|
||||
pub(super) async fn resolve_openapi_auth_binding(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
candidate: &ImportOperationCandidate,
|
||||
mapping: Option<&OpenApiAuthMapping>,
|
||||
locale: OpenApiUploadLocale,
|
||||
) -> Result<(Option<AuthProfileId>, Option<ImportAuthRequirement>), ApiError> {
|
||||
let alternatives = &candidate.security_requirements.alternatives;
|
||||
if alternatives.is_empty() {
|
||||
return if mapping.is_none() {
|
||||
Ok((None, None))
|
||||
} else {
|
||||
Err(ApiError::openapi_upload(locale, "auth_mapping_invalid"))
|
||||
};
|
||||
}
|
||||
let mapping =
|
||||
mapping.ok_or_else(|| ApiError::openapi_upload(locale, "auth_mapping_required"))?;
|
||||
let alternative = alternatives
|
||||
.get(mapping.alternative_index)
|
||||
.ok_or_else(|| ApiError::openapi_upload(locale, "auth_mapping_invalid"))?;
|
||||
if !alternative.supported {
|
||||
return Err(ApiError::openapi_upload(locale, "auth_mapping_unsupported"));
|
||||
}
|
||||
if alternative.schemes.is_empty() {
|
||||
return if mapping.auth_profile_id.is_none() {
|
||||
Ok((None, None))
|
||||
} else {
|
||||
Err(ApiError::openapi_upload(locale, "auth_mapping_invalid"))
|
||||
};
|
||||
}
|
||||
if alternative.schemes.len() != 1 {
|
||||
return Err(ApiError::openapi_upload(locale, "auth_mapping_unsupported"));
|
||||
}
|
||||
let scheme = candidate
|
||||
.security_schemes
|
||||
.get(&alternative.schemes[0])
|
||||
.ok_or_else(|| ApiError::openapi_upload(locale, "auth_mapping_unsupported"))?;
|
||||
let requirement = import_auth_requirement(scheme)
|
||||
.ok_or_else(|| ApiError::openapi_upload(locale, "auth_mapping_unsupported"))?;
|
||||
let profile_id = mapping
|
||||
.auth_profile_id
|
||||
.as_deref()
|
||||
.filter(|value| !value.is_empty())
|
||||
.ok_or_else(|| ApiError::openapi_upload(locale, "auth_mapping_required"))?;
|
||||
let profile_id = AuthProfileId::new(profile_id.to_owned());
|
||||
let profile = self
|
||||
.registry
|
||||
.get_auth_profile(workspace_id, &profile_id)
|
||||
.await?
|
||||
.ok_or_else(|| ApiError::openapi_auth_binding_unavailable(locale))?;
|
||||
if !auth_profile_matches(&profile, &requirement)
|
||||
|| !auth_profile_is_available(&self.registry, workspace_id, &profile).await?
|
||||
{
|
||||
return Err(ApiError::openapi_auth_binding_unavailable(locale));
|
||||
}
|
||||
Ok((Some(profile_id), Some(requirement)))
|
||||
}
|
||||
}
|
||||
|
||||
fn import_auth_requirement(
|
||||
scheme: &crank_import::rest::NormalizedSecurityScheme,
|
||||
) -> Option<ImportAuthRequirement> {
|
||||
use crank_import::rest::{NormalizedSecuritySchemeKind, SecurityParameterLocation};
|
||||
|
||||
match &scheme.kind {
|
||||
NormalizedSecuritySchemeKind::Http { scheme, .. }
|
||||
if scheme.eq_ignore_ascii_case("bearer") =>
|
||||
{
|
||||
Some(ImportAuthRequirement::Bearer)
|
||||
}
|
||||
NormalizedSecuritySchemeKind::Http { scheme, .. }
|
||||
if scheme.eq_ignore_ascii_case("basic") =>
|
||||
{
|
||||
Some(ImportAuthRequirement::Basic)
|
||||
}
|
||||
NormalizedSecuritySchemeKind::ApiKey {
|
||||
location: SecurityParameterLocation::Header,
|
||||
parameter_name,
|
||||
..
|
||||
} => Some(ImportAuthRequirement::ApiKeyHeader {
|
||||
parameter_name: parameter_name.clone(),
|
||||
}),
|
||||
NormalizedSecuritySchemeKind::ApiKey {
|
||||
location: SecurityParameterLocation::Query,
|
||||
parameter_name,
|
||||
..
|
||||
} => Some(ImportAuthRequirement::ApiKeyQuery {
|
||||
parameter_name: parameter_name.clone(),
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn auth_profile_matches(profile: &AuthProfile, requirement: &ImportAuthRequirement) -> bool {
|
||||
if profile.kind != profile.config.kind() {
|
||||
return false;
|
||||
}
|
||||
match (requirement, &profile.config) {
|
||||
(ImportAuthRequirement::Bearer, AuthConfig::Bearer(_))
|
||||
| (ImportAuthRequirement::Basic, AuthConfig::Basic(_)) => true,
|
||||
(
|
||||
ImportAuthRequirement::ApiKeyHeader { parameter_name },
|
||||
AuthConfig::ApiKeyHeader(config),
|
||||
) => config.header_name.eq_ignore_ascii_case(parameter_name),
|
||||
(
|
||||
ImportAuthRequirement::ApiKeyQuery { parameter_name },
|
||||
AuthConfig::ApiKeyQuery(config),
|
||||
) => config.param_name == *parameter_name,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
async fn auth_profile_is_available(
|
||||
registry: &crank_registry::PostgresRegistry,
|
||||
workspace_id: &WorkspaceId,
|
||||
profile: &AuthProfile,
|
||||
) -> Result<bool, ApiError> {
|
||||
for secret_id in profile.config.secret_ids() {
|
||||
if registry
|
||||
.get_current_secret_version(workspace_id, secret_id)
|
||||
.await?
|
||||
.is_none()
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
Reference in new issue
Block a user