story 2-10-security-schemes-secrets: implemented and reviewed via bmad-loop
This commit is contained in:
1 parent
f5f40cb167
commit
ecfb4e788f
45 files changed
+6025
-829
No files matched your search
@@ -1,70 +1,444 @@
|
||||
use serde_json::Value;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use crate::rest::{
|
||||
model::{ImportFinding, SourceLocation},
|
||||
recommendations::document_finding,
|
||||
};
|
||||
|
||||
pub(super) fn collect_secret_like_examples(
|
||||
value: &Value,
|
||||
pub(super) const REDACTED_LITERAL: &str = "[REDACTED]";
|
||||
|
||||
/// Redacts credential-like literals before they enter the normalized tree,
|
||||
/// while retaining stable source locations for review findings.
|
||||
pub(super) fn redact_secret_like_literals(
|
||||
value: &mut Value,
|
||||
pointer: &str,
|
||||
inside_example: bool,
|
||||
findings: &mut Vec<ImportFinding>,
|
||||
locations: &mut Vec<Option<SourceLocation>>,
|
||||
) {
|
||||
let declared_names = credential_names(std::iter::once(&*value));
|
||||
redact_secret_like_literals_with_names(value, pointer, &declared_names, findings, locations);
|
||||
}
|
||||
|
||||
pub(super) fn redact_secret_like_literals_with_names(
|
||||
value: &mut Value,
|
||||
pointer: &str,
|
||||
declared_names: &CredentialNames,
|
||||
findings: &mut Vec<ImportFinding>,
|
||||
locations: &mut Vec<Option<SourceLocation>>,
|
||||
) {
|
||||
visit(
|
||||
value,
|
||||
pointer,
|
||||
VisitContext {
|
||||
in_secret_example: false,
|
||||
sensitive_parameter_schema: false,
|
||||
force_redact: false,
|
||||
declared_names,
|
||||
},
|
||||
findings,
|
||||
locations,
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct CredentialNames {
|
||||
header: BTreeSet<String>,
|
||||
query: BTreeSet<String>,
|
||||
cookie: BTreeSet<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct VisitContext<'a> {
|
||||
in_secret_example: bool,
|
||||
sensitive_parameter_schema: bool,
|
||||
force_redact: bool,
|
||||
declared_names: &'a CredentialNames,
|
||||
}
|
||||
|
||||
impl CredentialNames {
|
||||
fn contains(&self, location: &str, name: &str) -> bool {
|
||||
let names = match location.to_ascii_lowercase().as_str() {
|
||||
"header" => &self.header,
|
||||
"query" => &self.query,
|
||||
"cookie" => &self.cookie,
|
||||
_ => return false,
|
||||
};
|
||||
names.contains(&name.to_ascii_lowercase())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn credential_names<'a>(roots: impl IntoIterator<Item = &'a Value>) -> CredentialNames {
|
||||
let mut names = CredentialNames::default();
|
||||
for root in roots {
|
||||
collect_credential_names(root, &mut names);
|
||||
}
|
||||
names
|
||||
}
|
||||
|
||||
fn collect_credential_names(value: &Value, names: &mut CredentialNames) {
|
||||
match value {
|
||||
Value::Object(fields) => {
|
||||
if fields.get("type").and_then(Value::as_str) == Some("apiKey")
|
||||
&& let (Some(location), Some(name)) = (
|
||||
fields.get("in").and_then(Value::as_str),
|
||||
fields.get("name").and_then(Value::as_str),
|
||||
)
|
||||
{
|
||||
let destination = match location.to_ascii_lowercase().as_str() {
|
||||
"header" => Some(&mut names.header),
|
||||
"query" => Some(&mut names.query),
|
||||
"cookie" => Some(&mut names.cookie),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(destination) = destination {
|
||||
destination.insert(name.to_ascii_lowercase());
|
||||
}
|
||||
}
|
||||
for child in fields.values() {
|
||||
collect_credential_names(child, names);
|
||||
}
|
||||
}
|
||||
Value::Array(items) => {
|
||||
for child in items {
|
||||
collect_credential_names(child, names);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn visit(
|
||||
value: &mut Value,
|
||||
pointer: &str,
|
||||
context: VisitContext<'_>,
|
||||
findings: &mut Vec<ImportFinding>,
|
||||
locations: &mut Vec<Option<SourceLocation>>,
|
||||
) {
|
||||
if context.force_redact
|
||||
|| value
|
||||
.as_str()
|
||||
.is_some_and(|text| url_has_secret_named(text, context.declared_names))
|
||||
|| (context.in_secret_example && value.as_str() == Some(REDACTED_LITERAL))
|
||||
|| (context.in_secret_example && scalar_looks_secret(value))
|
||||
{
|
||||
redact(value, context.force_redact, context.declared_names);
|
||||
findings.push(document_finding(
|
||||
"secret_like_example",
|
||||
"В исходном документе обнаружено значение, похожее на секрет; оно удалено из импортируемых данных.",
|
||||
));
|
||||
locations.push(Some(SourceLocation {
|
||||
pointer: pointer.to_owned(),
|
||||
}));
|
||||
return;
|
||||
}
|
||||
|
||||
match value {
|
||||
Value::Object(fields) => {
|
||||
let sensitive_parameter =
|
||||
fields
|
||||
.get("in")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|location| {
|
||||
["header", "query", "cookie"]
|
||||
.iter()
|
||||
.any(|allowed| location.eq_ignore_ascii_case(allowed))
|
||||
})
|
||||
&& fields
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|name| {
|
||||
is_sensitive_name(name)
|
||||
|| fields.get("in").and_then(Value::as_str).is_some_and(
|
||||
|location| context.declared_names.contains(location, name),
|
||||
)
|
||||
});
|
||||
for (key, child) in fields {
|
||||
let child_pointer = format!(
|
||||
"{pointer}/{}",
|
||||
super::normalize_coverage::escape_pointer(key)
|
||||
);
|
||||
collect_secret_like_examples(
|
||||
let key_lower = key.to_ascii_lowercase();
|
||||
let in_example = context.in_secret_example
|
||||
|| matches!(
|
||||
key_lower.as_str(),
|
||||
"default"
|
||||
| "example"
|
||||
| "examples"
|
||||
| "x-example"
|
||||
| "x-examples"
|
||||
| "bearerformat"
|
||||
| "x-format-hint"
|
||||
);
|
||||
let sensitive_header_definition = pointer.ends_with("/headers")
|
||||
&& (is_sensitive_name(key) || context.declared_names.contains("header", key));
|
||||
let parameter_value = (sensitive_parameter || sensitive_header_definition)
|
||||
&& matches!(
|
||||
key_lower.as_str(),
|
||||
"example" | "examples" | "x-example" | "x-examples"
|
||||
);
|
||||
let parameter_schema = context.sensitive_parameter_schema
|
||||
|| sensitive_header_definition
|
||||
|| (sensitive_parameter && key_lower == "schema");
|
||||
let parent_is_secret_property =
|
||||
pointer.rsplit('/').next().is_some_and(is_sensitive_name);
|
||||
// Names in schema/scheme maps and security requirements are
|
||||
// identifiers, not credential values. Traverse their metadata
|
||||
// and redact the actual defaults/examples instead.
|
||||
let identifier_map = (child.is_object()
|
||||
&& (pointer.ends_with("/properties")
|
||||
|| pointer.ends_with("/headers")
|
||||
|| pointer == "/components/schemas"
|
||||
|| pointer == "/definitions"
|
||||
|| pointer == "/components/securitySchemes"
|
||||
|| pointer == "/securityDefinitions"))
|
||||
|| (child.is_array()
|
||||
&& pointer.rsplit_once('/').is_some_and(|(parent, index)| {
|
||||
parent.ends_with("/security") && index.parse::<usize>().is_ok()
|
||||
}));
|
||||
let force_child = (is_sensitive_name(key) && !identifier_map)
|
||||
|| (matches!(key_lower.as_str(), "default" | "example" | "examples")
|
||||
&& parent_is_secret_property)
|
||||
|| parameter_value
|
||||
|| (sensitive_parameter
|
||||
&& matches!(key_lower.as_str(), "default" | "example" | "examples"))
|
||||
|| (parameter_schema
|
||||
&& matches!(key_lower.as_str(), "default" | "example" | "examples"));
|
||||
visit(
|
||||
child,
|
||||
&child_pointer,
|
||||
inside_example || matches!(key.as_str(), "example" | "examples"),
|
||||
VisitContext {
|
||||
in_secret_example: in_example,
|
||||
sensitive_parameter_schema: parameter_schema,
|
||||
force_redact: force_child,
|
||||
..context
|
||||
},
|
||||
findings,
|
||||
locations,
|
||||
);
|
||||
}
|
||||
}
|
||||
Value::Array(items) => {
|
||||
for (index, child) in items.iter().enumerate() {
|
||||
collect_secret_like_examples(
|
||||
for (index, child) in items.iter_mut().enumerate() {
|
||||
visit(
|
||||
child,
|
||||
&format!("{pointer}/{index}"),
|
||||
inside_example,
|
||||
VisitContext {
|
||||
force_redact: false,
|
||||
..context
|
||||
},
|
||||
findings,
|
||||
locations,
|
||||
);
|
||||
}
|
||||
}
|
||||
Value::String(value) if inside_example && looks_secret_like(pointer, value) => {
|
||||
findings.push(document_finding(
|
||||
"secret_like_example",
|
||||
"Example содержит значение, похожее на секрет, и не включается в executable contract.",
|
||||
));
|
||||
locations.push(Some(SourceLocation {
|
||||
pointer: pointer.to_owned(),
|
||||
}));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn looks_secret_like(pointer: &str, value: &str) -> bool {
|
||||
let pointer = pointer.to_ascii_lowercase();
|
||||
fn is_sensitive_name(name: &str) -> bool {
|
||||
let lower = name.to_ascii_lowercase();
|
||||
if lower.starts_with('/')
|
||||
|| matches!(
|
||||
lower.as_str(),
|
||||
"url"
|
||||
| "tokenurl"
|
||||
| "authorizationurl"
|
||||
| "refreshurl"
|
||||
| "openidconnecturl"
|
||||
| "clientcredentials"
|
||||
| "authorizationcode"
|
||||
)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let compact = lower.replace(['-', '_'], "");
|
||||
[
|
||||
"token",
|
||||
"secret",
|
||||
"password",
|
||||
"credential",
|
||||
"authorization",
|
||||
"apikey",
|
||||
"accesskey",
|
||||
"ciphertext",
|
||||
"privatekey",
|
||||
"passwd",
|
||||
]
|
||||
.iter()
|
||||
.any(|marker| compact.contains(marker))
|
||||
}
|
||||
|
||||
fn scalar_looks_secret(value: &Value) -> bool {
|
||||
let Value::String(value) = value else {
|
||||
return false;
|
||||
};
|
||||
let value = value.to_ascii_lowercase();
|
||||
[
|
||||
"token",
|
||||
"secret",
|
||||
"password",
|
||||
"credential",
|
||||
"authorization",
|
||||
"api_key",
|
||||
"apikey",
|
||||
"authorization",
|
||||
]
|
||||
.iter()
|
||||
.any(|marker| pointer.contains(marker) || value.contains(marker))
|
||||
.any(|marker| value.contains(marker))
|
||||
|| value.starts_with("bearer ")
|
||||
|| value.starts_with("sk-")
|
||||
|| looks_like_jwt(&value)
|
||||
}
|
||||
|
||||
fn looks_like_jwt(value: &str) -> bool {
|
||||
let mut segments = value.split('.');
|
||||
let (Some(header), Some(payload), Some(signature), None) = (
|
||||
segments.next(),
|
||||
segments.next(),
|
||||
segments.next(),
|
||||
segments.next(),
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
header.starts_with("eyj")
|
||||
&& !payload.is_empty()
|
||||
&& signature.len() >= 8
|
||||
&& [header, payload, signature].iter().all(|segment| {
|
||||
segment
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn url_has_secret(value: &str) -> bool {
|
||||
url_has_secret_named(value, &CredentialNames::default())
|
||||
}
|
||||
|
||||
fn url_has_secret_named(value: &str, declared_names: &CredentialNames) -> bool {
|
||||
url_userinfo(value).is_some()
|
||||
|| query_has_secret_parameter(value, &declared_names.query)
|
||||
|| fragment_has_secret_parameter(value)
|
||||
}
|
||||
|
||||
fn fragment_has_secret_parameter(value: &str) -> bool {
|
||||
let Some((_, fragment)) = value.split_once('#') else {
|
||||
return false;
|
||||
};
|
||||
if fragment.starts_with('/') {
|
||||
return false;
|
||||
}
|
||||
url::form_urlencoded::parse(fragment.as_bytes()).any(|(name, _)| is_sensitive_name(&name))
|
||||
}
|
||||
|
||||
fn redact_url_fragment(value: &str) -> String {
|
||||
let Some((base, fragment)) = value.split_once('#') else {
|
||||
return value.to_owned();
|
||||
};
|
||||
if fragment.starts_with('/') || !fragment.contains('=') {
|
||||
return value.to_owned();
|
||||
}
|
||||
let redacted = fragment
|
||||
.split('&')
|
||||
.map(|pair| {
|
||||
let (name, parameter_value) = pair.split_once('=').unwrap_or((pair, ""));
|
||||
let decoded_name = url::form_urlencoded::parse(format!("{name}=").as_bytes())
|
||||
.next()
|
||||
.map(|(name, _)| name.into_owned())
|
||||
.unwrap_or_default();
|
||||
if is_sensitive_name(&decoded_name) {
|
||||
format!("{name}={REDACTED_LITERAL}")
|
||||
} else if pair.contains('=') {
|
||||
format!("{name}={parameter_value}")
|
||||
} else {
|
||||
name.to_owned()
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("&");
|
||||
format!("{base}#{redacted}")
|
||||
}
|
||||
|
||||
fn url_userinfo(value: &str) -> Option<(&str, &str, &str)> {
|
||||
let (scheme, rest) = value
|
||||
.split_once("://")
|
||||
.or_else(|| value.strip_prefix("//").map(|rest| ("", rest)))?;
|
||||
let (authority, suffix) = rest
|
||||
.find(['/', '?', '#'])
|
||||
.map_or((rest, ""), |index| (&rest[..index], &rest[index..]));
|
||||
let (userinfo, host) = authority.split_once('@')?;
|
||||
if userinfo.is_empty() || host.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some((scheme, host, suffix))
|
||||
}
|
||||
|
||||
fn query_has_secret_parameter(value: &str, declared_query_names: &BTreeSet<String>) -> bool {
|
||||
let Some((_, query)) = value.split_once('?') else {
|
||||
return false;
|
||||
};
|
||||
let query = query.split('#').next().unwrap_or(query);
|
||||
url::form_urlencoded::parse(query.as_bytes()).any(|(name, _)| {
|
||||
is_sensitive_name(&name) || declared_query_names.contains(&name.to_ascii_lowercase())
|
||||
})
|
||||
}
|
||||
|
||||
fn redact(value: &mut Value, force: bool, declared_names: &CredentialNames) {
|
||||
if force
|
||||
|| !value
|
||||
.as_str()
|
||||
.is_some_and(|text| url_has_secret_named(text, declared_names))
|
||||
{
|
||||
*value = Value::String(REDACTED_LITERAL.to_owned());
|
||||
return;
|
||||
}
|
||||
if let Value::String(text) = value {
|
||||
if force {
|
||||
*text = REDACTED_LITERAL.to_owned();
|
||||
return;
|
||||
}
|
||||
let mut sanitized = text.clone();
|
||||
if let Some((scheme, host, suffix)) = url_userinfo(&sanitized) {
|
||||
sanitized = if scheme.is_empty() {
|
||||
format!("//{host}{suffix}")
|
||||
} else {
|
||||
format!("{scheme}://{host}{suffix}")
|
||||
};
|
||||
}
|
||||
if query_has_secret_parameter(&sanitized, &declared_names.query)
|
||||
&& let Some((base, query)) = sanitized.split_once('?')
|
||||
{
|
||||
let (query, fragment) = query
|
||||
.split_once('#')
|
||||
.map_or((query, None), |(query, fragment)| (query, Some(fragment)));
|
||||
let redacted = query
|
||||
.split('&')
|
||||
.map(|pair| {
|
||||
let (name, value) = pair.split_once('=').unwrap_or((pair, ""));
|
||||
let decoded_name = url::form_urlencoded::parse(format!("{name}=").as_bytes())
|
||||
.next()
|
||||
.map(|(name, _)| name.into_owned())
|
||||
.unwrap_or_default();
|
||||
if is_sensitive_name(&decoded_name)
|
||||
|| declared_names
|
||||
.query
|
||||
.contains(&decoded_name.to_ascii_lowercase())
|
||||
{
|
||||
format!("{name}={REDACTED_LITERAL}")
|
||||
} else if pair.contains('=') {
|
||||
format!("{name}={value}")
|
||||
} else {
|
||||
name.to_owned()
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("&");
|
||||
sanitized = match fragment {
|
||||
Some(fragment) => format!("{base}?{redacted}#{fragment}"),
|
||||
None => format!("{base}?{redacted}"),
|
||||
};
|
||||
}
|
||||
*text = redact_url_fragment(&sanitized);
|
||||
} else {
|
||||
*value = Value::String(REDACTED_LITERAL.to_owned());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user