use std::{
borrow::Cow,
cmp::Ordering,
collections::{BTreeMap, BTreeSet},
fmt,
hash::Hash,
path::Path,
str::FromStr,
sync::{LazyLock, OnceLock},
};
use anyhow::{Context, Result, anyhow};
use liquid::{ParserBuilder, model::Value, object};
use regex::Regex;
use schemars::{JsonSchema, Schema, SchemaGenerator};
use serde::{Deserialize, Serialize};
use tracing::debug;
use xxhash_rust::xxh3::xxh3_64;
use crate::liquid_filters;
fn default_false() -> bool {
false
}
fn default_true() -> bool {
true
}
#[derive(
Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Default,
)]
#[serde(rename_all = "lowercase")]
pub enum TlsMode {
#[default]
Strict,
Lax,
Off,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
#[serde(tag = "type", content = "content")]
pub enum Validation {
Assumed,
AWS,
AzureStorage,
Coinbase,
GCP,
MongoDB,
MySQL,
Postgres,
Jdbc,
CredentialUri,
JWT,
Ethereum(EthereumValidation),
Raw(String),
Betterleaks(BetterleaksValidation),
Http(HttpValidation),
Grpc(GrpcValidation),
}
impl Validation {
pub fn redacted_for_inspection(&self) -> Self {
let mut inspected = self.clone();
if let Self::Http(http) = &mut inspected {
redact_http_auth(http);
}
inspected
}
}
fn redact_http_auth(http: &mut HttpValidation) {
if let Some(auth) = &mut http.auth {
let credentials = &mut auth.oauth2.ropc;
for value in
[&mut credentials.username, &mut credentials.password, &mut credentials.client_secret]
.into_iter()
.flatten()
{
*value = "[REDACTED]".into();
}
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct BetterleaksValidation {
#[cfg(debug_assertions)]
#[serde(default)]
pub source: String,
#[serde(deserialize_with = "deserialize_betterleaks_expression")]
pub expression: BetterleaksExpr,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "deserialize_optional_betterleaks_expression"
)]
pub analyze: Option<BetterleaksExpr>,
#[serde(default)]
pub components: BTreeMap<String, String>,
#[serde(default)]
pub capabilities: BetterleaksCapabilities,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Default)]
pub struct BetterleaksCapabilities {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub access_map: Option<BetterleaksAccessMap>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub revocation_bindings: Option<BetterleaksRevocationBindings>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct BetterleaksAccessMap {
pub handler: BetterleaksAccessMapHandler,
#[serde(default)]
pub inputs: BTreeMap<String, String>,
#[serde(default)]
pub reachable_2xx: bool,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum BetterleaksAccessMapHandler {
Aws,
Gcp,
GcpApiKey,
AzureClientSecret,
AzureStorage,
Algolia,
Alibaba,
Artifactory,
Salesforce,
Airtable,
Anthropic,
Auth0,
Buildkite,
Circleci,
Fastly,
Github,
Gitlab,
Harness,
Huggingface,
IbmCloud,
Monday,
Openai,
Paypal,
Pinecone,
Sendinblue,
Stripe,
WeightsAndBiases,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct BetterleaksRevocationBindings {
#[serde(default = "default_finding_secret_source")]
pub secret: String,
#[serde(default)]
pub variables: BTreeMap<String, String>,
}
fn default_finding_secret_source() -> String {
"finding.secret".to_string()
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum BetterleaksExpr {
Nil,
Identifier {
value: String,
},
Integer {
value: i64,
},
Float {
value: String,
},
Bool {
value: bool,
},
String {
value: String,
},
Unary {
operator: String,
node: Box<BetterleaksExpr>,
},
Binary {
operator: String,
left: Box<BetterleaksExpr>,
right: Box<BetterleaksExpr>,
},
Chain {
node: Box<BetterleaksExpr>,
},
Member {
node: Box<BetterleaksExpr>,
property: Box<BetterleaksExpr>,
#[serde(default)]
optional: bool,
#[serde(default)]
method: bool,
},
Slice {
node: Box<BetterleaksExpr>,
from: Box<BetterleaksExpr>,
to: Box<BetterleaksExpr>,
},
Call {
callee: Box<BetterleaksExpr>,
#[serde(default)]
arguments: Vec<BetterleaksExpr>,
},
Builtin {
name: String,
#[serde(default)]
arguments: Vec<BetterleaksExpr>,
},
Conditional {
cond: Box<BetterleaksExpr>,
exp1: Box<BetterleaksExpr>,
exp2: Box<BetterleaksExpr>,
},
VariableDeclarator {
name: String,
value: Box<BetterleaksExpr>,
expr: Box<BetterleaksExpr>,
},
Sequence {
#[serde(default)]
nodes: Vec<BetterleaksExpr>,
},
Array {
#[serde(default)]
nodes: Vec<BetterleaksExpr>,
},
Map {
#[serde(default)]
pairs: Vec<BetterleaksExpr>,
},
Pair {
key: Box<BetterleaksExpr>,
value: Box<BetterleaksExpr>,
},
Predicate {
node: Box<BetterleaksExpr>,
},
Pointer {
name: String,
},
}
impl BetterleaksExpr {
pub fn env_input_vars(&self) -> BTreeSet<String> {
let mut vars = BTreeSet::new();
let mut nodes = vec![self];
while let Some(node) = nodes.pop() {
match node {
Self::Call { callee, arguments } => {
if let Self::Member { node, property, .. } = callee.as_ref()
&& matches!(node.as_ref(), Self::Identifier { value } if value == "env")
&& matches!(property.as_ref(), Self::String { value } if value == "get")
&& let [Self::String { value }] = arguments.as_slice()
{
vars.insert(value.clone());
}
nodes.push(callee);
nodes.extend(arguments);
}
Self::Unary { node, .. } | Self::Chain { node } | Self::Predicate { node } => {
nodes.push(node);
}
Self::Binary { left, right, .. } => {
nodes.extend([left.as_ref(), right.as_ref()]);
}
Self::Member { node, property, .. } => {
nodes.extend([node.as_ref(), property.as_ref()]);
}
Self::Slice { node, from, to } => {
nodes.extend([node.as_ref(), from.as_ref(), to.as_ref()]);
}
Self::Builtin { arguments, .. } => nodes.extend(arguments),
Self::Conditional { cond, exp1, exp2 } => {
nodes.extend([cond.as_ref(), exp1.as_ref(), exp2.as_ref()]);
}
Self::VariableDeclarator { value, expr, .. } => {
nodes.extend([value.as_ref(), expr.as_ref()]);
}
Self::Sequence { nodes: children }
| Self::Array { nodes: children }
| Self::Map { pairs: children } => nodes.extend(children),
Self::Pair { key, value } => {
nodes.extend([key.as_ref(), value.as_ref()]);
}
Self::Nil
| Self::Identifier { .. }
| Self::Integer { .. }
| Self::Float { .. }
| Self::Bool { .. }
| Self::String { .. }
| Self::Pointer { .. } => {}
}
}
vars
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum EthereumValidation {
PrivateKey,
PublicKey,
Mnemonic,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
#[serde(tag = "type", content = "content")]
pub enum Revocation {
AWS,
GCP,
Betterleaks(BetterleaksValidation),
Http(#[serde(deserialize_with = "deserialize_http_revocation")] HttpValidation),
HttpMultiStep(HttpMultiStepRevocation),
}
impl Revocation {
pub fn redacted_for_inspection(&self) -> Self {
let mut inspected = self.clone();
if let Self::Http(http) = &mut inspected {
redact_http_auth(http);
}
inspected
}
}
fn deserialize_betterleaks_expression<'de, D>(
deserializer: D,
) -> std::result::Result<BetterleaksExpr, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum Expression {
Ast(BetterleaksExpr),
Source(String),
}
match Expression::deserialize(deserializer)? {
Expression::Ast(expression) => Ok(expression),
Expression::Source(source) => {
let expression = crate::betterleaks::parse_custom_expression(&source)
.map_err(serde::de::Error::custom)?;
serde_json::from_value(expression).map_err(serde::de::Error::custom)
}
}
}
fn deserialize_optional_betterleaks_expression<'de, D>(
deserializer: D,
) -> std::result::Result<Option<BetterleaksExpr>, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
struct Expression(
#[serde(deserialize_with = "deserialize_betterleaks_expression")] BetterleaksExpr,
);
Option::<Expression>::deserialize(deserializer).map(|value| value.map(|value| value.0))
}
fn deserialize_http_revocation<'de, D>(
deserializer: D,
) -> std::result::Result<HttpValidation, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
struct HttpRevocation {
request: HttpRequest,
multipart: Option<MultipartConfig>,
#[serde(default)]
auth: Option<serde::de::IgnoredAny>,
}
let http = HttpRevocation::deserialize(deserializer)?;
if http.auth.is_some() {
return Err(serde::de::Error::custom("OAuth2 auth is supported for validation only"));
}
Ok(HttpValidation { request: http.request, multipart: http.multipart, auth: None })
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct HttpMultiStepRevocation {
pub steps: Vec<RevocationStep>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct RevocationStep {
#[serde(default)]
pub name: Option<String>,
pub request: HttpRequest,
#[serde(default)]
pub multipart: Option<MultipartConfig>,
#[serde(default)]
pub extract: Option<BTreeMap<String, ResponseExtractor>>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
#[serde(tag = "type")]
pub enum ResponseExtractor {
JsonPath { path: String },
Regex { pattern: String },
Header { name: String },
Body,
StatusCode,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct DependsOnRule {
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub verify_candidates: bool,
pub rule_id: String,
pub variable: String,
#[serde(default)]
pub optional: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub within: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct PatternRequirements {
#[serde(default)]
pub min_digits: Option<usize>,
#[serde(default)]
pub min_uppercase: Option<usize>,
#[serde(default)]
pub min_lowercase: Option<usize>,
#[serde(default)]
pub min_special_chars: Option<usize>,
#[serde(default)]
pub special_chars: Option<String>,
#[serde(default)]
pub ignore_if_contains: Option<Vec<String>>,
#[serde(default)]
pub checksum: Option<ChecksumRequirement>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct ChecksumRequirement {
pub actual: ChecksumActual,
pub expected: String,
#[serde(default)]
pub skip_if_missing: bool,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct ChecksumActual {
pub template: String,
#[serde(default)]
pub requires_capture: Option<String>,
}
#[derive(Clone, Copy)]
pub struct PatternRequirementContext<'a> {
pub regex: &'a regex::bytes::Regex,
pub captures: &'a regex::bytes::Captures<'a>,
pub full_match: &'a [u8],
}
impl PatternRequirements {
const DEFAULT_SPECIAL_CHARS: &'static str = "!@#$%^&*()_+-=[]{}|;:'\",.<>?/\\`~";
pub fn validate(
&self,
input: &[u8],
context: Option<PatternRequirementContext<'_>>,
respect_ignore_if_contains: bool,
) -> PatternValidationResult {
let s = String::from_utf8_lossy(input);
if let Some(min_digits) = self.min_digits {
let digit_count = s.chars().filter(|c| c.is_ascii_digit()).count();
if digit_count < min_digits {
return PatternValidationResult::Failed;
}
}
if let Some(min_uppercase) = self.min_uppercase {
let uppercase_count = s.chars().filter(|c| c.is_ascii_uppercase()).count();
if uppercase_count < min_uppercase {
return PatternValidationResult::Failed;
}
}
if let Some(min_lowercase) = self.min_lowercase {
let lowercase_count = s.chars().filter(|c| c.is_ascii_lowercase()).count();
if lowercase_count < min_lowercase {
return PatternValidationResult::Failed;
}
}
if let Some(min_special) = self.min_special_chars {
let special_chars =
self.special_chars.as_deref().unwrap_or(Self::DEFAULT_SPECIAL_CHARS);
let special_count = s.chars().filter(|c| special_chars.contains(*c)).count();
if special_count < min_special {
return PatternValidationResult::Failed;
}
}
if respect_ignore_if_contains && let Some(ignore_terms) = self.ignore_if_contains.as_ref() {
let lowercase_input = s.to_lowercase();
if let Some(matched_term) = ignore_terms
.iter()
.filter_map(|term| {
let trimmed = term.trim();
if trimmed.is_empty() { None } else { Some((trimmed, trimmed.to_lowercase())) }
})
.find_map(|(original, lowered)| {
if lowercase_input.contains(&lowered) {
Some(original.to_string())
} else {
None
}
})
{
return PatternValidationResult::IgnoredBySubstring { matched_term };
}
}
if let Some(checksum) = &self.checksum {
let Some(ctx) = context else {
return if checksum.skip_if_missing {
PatternValidationResult::Passed
} else {
PatternValidationResult::Failed
};
};
if let Some(required) = checksum.actual.requires_capture.as_deref()
&& ctx.captures.name(required).is_none()
{
return if checksum.skip_if_missing {
PatternValidationResult::Passed
} else {
PatternValidationResult::Failed
};
}
let mut globals = object!({
"MATCH": s.to_string(),
"FULL_MATCH": String::from_utf8_lossy(ctx.full_match).to_string(),
});
for name in ctx.regex.capture_names().flatten() {
if let Some(capture) = ctx.captures.name(name) {
let value = String::from_utf8_lossy(capture.as_bytes()).to_string();
globals.insert(name.to_owned().into(), Value::scalar(value.clone()));
globals.insert(name.to_ascii_uppercase().into(), Value::scalar(value));
}
}
let actual =
match render_pattern_requirement_template(&checksum.actual.template, &globals) {
Ok(rendered) => rendered,
Err(err) => {
debug!(
"Failed to render checksum actual template '{}': {}",
checksum.actual.template, err
);
return PatternValidationResult::Failed;
}
};
let expected = match render_pattern_requirement_template(&checksum.expected, &globals) {
Ok(rendered) => rendered,
Err(err) => {
debug!(
"Failed to render checksum expected template '{}': {}",
checksum.expected, err
);
return PatternValidationResult::Failed;
}
};
if actual != expected {
let actual_len = actual.chars().count();
let expected_len = expected.chars().count();
return PatternValidationResult::FailedChecksum { actual_len, expected_len };
}
}
PatternValidationResult::Passed
}
}
fn render_pattern_requirement_template(
template: &str,
globals: &liquid::Object,
) -> Result<String, String> {
PATTERN_REQUIREMENTS_TEMPLATE_PARSER
.parse(template)
.map_err(|e| e.to_string())
.and_then(|parsed| parsed.render(globals).map_err(|e| e.to_string()))
}
#[derive(Debug, PartialEq, Eq)]
pub enum PatternValidationResult {
Passed,
Failed,
FailedChecksum { actual_len: usize, expected_len: usize },
IgnoredBySubstring { matched_term: String },
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct HttpValidation {
pub request: HttpRequest,
pub multipart: Option<MultipartConfig>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub auth: Option<Box<HttpValidationAuth>>,
}
pub const MAX_HTTP_FALLBACKS: usize = 2;
#[derive(Debug, Serialize, Deserialize, PartialEq, PartialOrd, Clone)]
#[serde(deny_unknown_fields)]
pub struct HttpFallback {
pub id: String,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub reuse_primary_validation_logic: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub validation: Option<Validation>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub reuse_primary_revocation_logic: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub revocation_url: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub revocation_urls: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub revocation: Option<Revocation>,
}
impl HttpFallback {
fn resolved_revocation<'a>(
&'a self,
primary: Option<&Revocation>,
) -> Result<Option<Cow<'a, Revocation>>> {
use anyhow::{bail, ensure};
if !self.reuse_primary_revocation_logic {
ensure!(
self.revocation_url.is_none() && self.revocation_urls.is_empty(),
"Revocation URL overrides require reuse_primary_revocation_logic: true"
);
return Ok(self.revocation.as_ref().map(Cow::Borrowed));
}
ensure!(
self.revocation.is_none(),
"reuse_primary_revocation_logic: true cannot include revocation"
);
let mut action = primary
.context("reuse_primary_revocation_logic: true requires primary revocation")?
.clone();
match &mut action {
Revocation::Http(http) => {
ensure!(
self.revocation_urls.is_empty(),
"Single-request revocation logic reuse requires revocation_url, not revocation_urls"
);
http.request.url = self
.revocation_url
.as_ref()
.filter(|url| !url.trim().is_empty())
.context(
"Single-request revocation logic reuse requires a nonblank revocation_url",
)?
.clone();
http.request.fallback_urls.clear();
}
Revocation::HttpMultiStep(multi) => {
ensure!(
self.revocation_url.is_none(),
"Multi-step revocation logic reuse requires revocation_urls, not revocation_url"
);
ensure!(
(1..=2).contains(&multi.steps.len())
&& self.revocation_urls.len() == multi.steps.len()
&& self.revocation_urls.iter().all(|url| !url.trim().is_empty()),
"Multi-step revocation logic reuse requires one nonblank revocation_urls entry per step (one or two steps)"
);
for (step, url) in multi.steps.iter_mut().zip(&self.revocation_urls) {
step.request.url = url.clone();
step.request.fallback_urls.clear();
}
}
_ => bail!(
"Primary revocation logic reuse supports only HTTP and HTTP multi-step actions"
),
}
Ok(Some(Cow::Owned(action)))
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
#[serde(deny_unknown_fields)]
pub struct HttpValidationAuth {
pub oauth2: OAuth2Config,
}
#[derive(Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
#[serde(deny_unknown_fields)]
pub struct OAuth2Config {
pub token_endpoint: String,
#[serde(default = "default_token_header")]
pub token_header: String,
pub ropc: OAuth2PasswordCredentials,
}
fn default_token_header() -> String {
"Authorization".into()
}
#[derive(Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
#[serde(deny_unknown_fields)]
pub struct OAuth2PasswordCredentials {
#[serde(default)]
pub username: Option<String>,
#[serde(default)]
pub username_env: Option<String>,
#[serde(default)]
pub password: Option<String>,
#[serde(default)]
pub password_env: Option<String>,
pub client_id: String,
#[serde(default)]
pub client_secret: Option<String>,
#[serde(default)]
pub client_secret_env: Option<String>,
#[serde(default)]
pub scope: Option<String>,
}
impl fmt::Debug for OAuth2Config {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OAuth2Config").finish_non_exhaustive()
}
}
impl fmt::Debug for OAuth2PasswordCredentials {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OAuth2PasswordCredentials").finish_non_exhaustive()
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct GrpcValidation {
pub request: GrpcRequest,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct GrpcRequest {
pub url: String,
#[serde(default)]
pub headers: BTreeMap<String, String>,
#[serde(default)]
pub body: Option<String>,
#[serde(default)]
pub response_matcher: Option<Vec<ResponseMatcher>>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
#[serde(try_from = "HttpRequestDefinition", into = "HttpRequestDefinition")]
pub struct HttpRequest {
pub method: String,
pub url: String,
pub fallback_urls: Vec<String>,
pub headers: BTreeMap<String, String>,
pub body: Option<String>,
pub response_matcher: Option<Vec<ResponseMatcher>>,
pub multipart: Option<MultipartConfig>,
pub response_is_html: bool,
}
impl HttpRequest {
pub fn urls(&self) -> impl Iterator<Item = &str> {
std::iter::once(self.url.as_str()).chain(self.fallback_urls.iter().map(String::as_str))
}
}
#[derive(Serialize, Deserialize)]
#[serde(untagged)]
enum HttpRequestUrls {
Single(String),
Multiple(Vec<String>),
}
#[derive(Serialize, Deserialize)]
struct HttpRequestDefinition {
method: String,
url: HttpRequestUrls,
#[serde(default)]
headers: BTreeMap<String, String>,
#[serde(default)]
body: Option<String>,
#[serde(default)]
response_matcher: Option<Vec<ResponseMatcher>>,
#[serde(default)]
multipart: Option<MultipartConfig>,
#[serde(default = "default_false")]
response_is_html: bool,
}
impl TryFrom<HttpRequestDefinition> for HttpRequest {
type Error = &'static str;
fn try_from(definition: HttpRequestDefinition) -> std::result::Result<Self, Self::Error> {
let (url, fallback_urls) = match definition.url {
HttpRequestUrls::Single(url) => (url, Vec::new()),
HttpRequestUrls::Multiple(mut urls) => {
if urls.is_empty() {
return Err("HTTP url list must contain at least one endpoint");
}
if urls.iter().any(|url| url.trim().is_empty()) {
return Err("HTTP url list cannot contain an empty endpoint");
}
let url = urls.remove(0);
(url, urls)
}
};
Ok(Self {
method: definition.method,
url,
fallback_urls,
headers: definition.headers,
body: definition.body,
response_matcher: definition.response_matcher,
multipart: definition.multipart,
response_is_html: definition.response_is_html,
})
}
}
impl From<HttpRequest> for HttpRequestDefinition {
fn from(request: HttpRequest) -> Self {
let url = if request.fallback_urls.is_empty() {
HttpRequestUrls::Single(request.url)
} else {
HttpRequestUrls::Multiple(
std::iter::once(request.url).chain(request.fallback_urls).collect(),
)
};
Self {
method: request.method,
url,
headers: request.headers,
body: request.body,
response_matcher: request.response_matcher,
multipart: request.multipart,
response_is_html: request.response_is_html,
}
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct MultipartConfig {
pub parts: Vec<MultipartPart>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct MultipartPart {
pub name: String,
#[serde(rename = "type")]
pub part_type: String,
pub content: String,
#[serde(default)]
pub content_type: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
#[serde(deny_unknown_fields)]
pub struct ReportResponseData {
#[serde(default = "default_true")]
report_response: bool,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
#[serde(untagged)]
pub enum ResponseMatcher {
WordMatch {
r#type: String,
words: Vec<String>,
#[serde(default = "default_false")]
match_all_words: bool,
#[serde(default = "default_false")]
negative: bool, },
StatusMatch {
r#type: String,
status: Vec<u16>,
#[serde(default = "default_false")]
match_all_status: bool,
#[serde(default = "default_false")]
negative: bool, },
HeaderMatch {
r#type: String, header: String, expected: Vec<String>, #[serde(default = "default_false")]
match_all_values: bool,
},
JsonValid {
r#type: String,
},
XmlValid {
r#type: String,
},
ReportResponse(ReportResponseData),
}
#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy, Default)]
pub enum Confidence {
Low,
#[default]
Medium,
High,
}
impl PartialOrd for Confidence {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Confidence {
fn cmp(&self, other: &Self) -> Ordering {
match (self, other) {
(Confidence::Low, Confidence::Low) => Ordering::Equal,
(Confidence::Low, _) => Ordering::Less,
(Confidence::Medium, Confidence::Low) => Ordering::Greater,
(Confidence::Medium, Confidence::Medium) => Ordering::Equal,
(Confidence::Medium, Confidence::High) => Ordering::Less,
(Confidence::High, Confidence::High) => Ordering::Equal,
(Confidence::High, _) => Ordering::Greater,
}
}
}
impl Confidence {
pub fn is_at_least(&self, other: &Confidence) -> bool {
self >= other
}
}
impl fmt::Display for Confidence {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
Confidence::Low => "low",
Confidence::Medium => "medium",
Confidence::High => "high",
};
write!(f, "{}", s)
}
}
impl FromStr for Confidence {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"low" => Ok(Confidence::Low),
"medium" => Ok(Confidence::Medium),
"high" => Ok(Confidence::High),
_ => Err(anyhow!("Invalid confidence level: {}", s)),
}
}
}
impl JsonSchema for Confidence {
fn schema_name() -> Cow<'static, str> {
"Confidence".into()
}
fn json_schema(_gen: &mut SchemaGenerator) -> Schema {
schemars::json_schema!({
"enum": ["Low", "Medium", "High"]
})
}
}
impl Serialize for Confidence {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(&self.to_string())
}
}
impl<'de> Deserialize<'de> for Confidence {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
s.parse().map_err(serde::de::Error::custom)
}
}
#[derive(Serialize, Deserialize, Debug, PartialEq, PartialOrd, Clone)]
pub struct RuleSyntax {
pub name: String,
pub id: String,
pub pattern: String,
#[serde(default)]
pub specificity: i64,
#[serde(default)]
pub tags: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub keywords: Vec<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub betterleaks_path_only: bool,
#[serde(default)]
pub path: Option<String>,
#[serde(default)]
pub betterleaks_filter: Option<BetterleaksExpr>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub betterleaks_secret_group: Option<usize>,
#[serde(default = "default_true")]
pub authoritative: bool,
#[serde(default = "default_true")]
pub vectorscan_compatible: bool,
#[serde(default)]
pub min_entropy: f32,
#[serde(default)]
pub confidence: Confidence,
#[serde(default = "default_true")]
pub visible: bool,
#[serde(default)]
pub examples: Vec<String>,
#[serde(default)]
pub negative_examples: Vec<String>,
#[serde(default)]
pub references: Vec<String>,
#[serde(default)]
pub validation: Option<Validation>,
#[serde(default)]
pub revocation: Option<Revocation>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub fallbacks: Vec<HttpFallback>,
#[serde(default)]
pub depends_on_rule: Vec<Option<DependsOnRule>>,
#[serde(default)]
pub pattern_requirements: Option<PatternRequirements>,
#[serde(default)]
pub tls_mode: Option<TlsMode>,
}
pub static RULE_COMMENTS_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"(?m)(\(\?#[^)]*\))|(\s\#[\sa-zA-Z]*$)")
.expect("comment-stripping regex should compile")
});
static PATTERN_REQUIREMENTS_TEMPLATE_PARSER: LazyLock<liquid::Parser> = LazyLock::new(|| {
liquid_filters::register_all(ParserBuilder::with_stdlib())
.build()
.expect("pattern requirement template parser should compile")
});
impl RuleSyntax {
pub fn redacted_for_inspection(&self) -> Self {
let mut inspected = self.clone();
inspected.validation =
inspected.validation.as_ref().map(Validation::redacted_for_inspection);
inspected.revocation =
inspected.revocation.as_ref().map(Revocation::redacted_for_inspection);
for fallback in &mut inspected.fallbacks {
fallback.validation =
fallback.validation.as_ref().map(Validation::redacted_for_inspection);
fallback.revocation =
fallback.revocation.as_ref().map(Revocation::redacted_for_inspection);
}
inspected
}
pub fn new(id: impl Into<String>, name: impl Into<String>, pattern: impl Into<String>) -> Self {
Self {
id: id.into(),
name: name.into(),
pattern: pattern.into(),
specificity: 0,
tags: Vec::new(),
keywords: Vec::new(),
betterleaks_path_only: false,
path: None,
betterleaks_filter: None,
betterleaks_secret_group: None,
authoritative: true,
vectorscan_compatible: true,
min_entropy: 0.0,
confidence: Confidence::default(),
visible: true,
examples: Vec::new(),
negative_examples: Vec::new(),
references: Vec::new(),
validation: None,
revocation: None,
fallbacks: Vec::new(),
depends_on_rule: Vec::new(),
pattern_requirements: None,
tls_mode: None,
}
}
pub fn check_http_fallbacks(&self) -> Result<()> {
use anyhow::{bail, ensure};
if self.fallbacks.is_empty() {
return Ok(());
}
ensure!(
self.fallbacks.len() <= MAX_HTTP_FALLBACKS,
"At most two HTTP fallbacks are allowed"
);
let Some(Validation::Http(primary)) = &self.validation else {
bail!("HTTP fallbacks require primary HTTP validation");
};
ensure!(
primary.request.fallback_urls.is_empty(),
"Do not mix named fallbacks with legacy URL lists"
);
let mut ids = std::collections::BTreeSet::new();
for fallback in &self.fallbacks {
ensure!(
!fallback.id.is_empty()
&& fallback.id != "primary"
&& fallback
.id
.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"_.-".contains(&c))
&& ids.insert(&fallback.id),
"Fallback IDs must be unique, nonempty identifiers other than primary"
);
if fallback.reuse_primary_validation_logic {
ensure!(
fallback.validation.is_none(),
"reuse_primary_validation_logic: true cannot include validation"
);
ensure!(
fallback.url.as_ref().is_some_and(|url| !url.trim().is_empty()),
"reuse_primary_validation_logic: true requires a nonblank url (only the logic is reused)"
);
} else {
ensure!(
fallback.url.is_none(),
"Fallback url requires reuse_primary_validation_logic: true"
);
let Some(Validation::Http(http)) = &fallback.validation else {
bail!(
"reuse_primary_validation_logic defaults to false and requires complete HTTP validation"
);
};
ensure!(
http.request.fallback_urls.is_empty() && !http.request.url.trim().is_empty(),
"Fallback validation must have one nonblank scalar URL"
);
ensure!(
http.request.response_matcher.as_ref().is_some_and(|m| !m.is_empty()),
"Fallback HTTP validation requires response_matcher"
);
}
if let Some(action) = fallback.resolved_revocation(self.revocation.as_ref())? {
let requests: Vec<_> = match action.as_ref() {
Revocation::Http(http) => vec![&http.request],
Revocation::HttpMultiStep(multi) => {
ensure!(
(1..=2).contains(&multi.steps.len()),
"Fallback revocation requires one or two steps"
);
multi.steps.iter().map(|step| &step.request).collect()
}
_ => bail!("Fallback revocation must be HTTP or HTTP multi-step"),
};
ensure!(
requests.iter().all(|r| r.fallback_urls.is_empty()),
"Named fallback revocation must use scalar URLs"
);
ensure!(
requests.last().is_some_and(|r| r
.response_matcher
.as_ref()
.is_some_and(|m| !m.is_empty())),
"Fallback revocation requires a final response_matcher"
);
}
}
Ok(())
}
pub fn http_validations(&self, enabled: bool) -> Result<Vec<(Option<&str>, HttpValidation)>> {
self.check_http_fallbacks()?;
let Some(Validation::Http(primary)) = &self.validation else { return Ok(Vec::new()) };
let mut first = primary.clone();
first.request.fallback_urls.clear();
let mut configurations = vec![(None, first)];
if !enabled {
return Ok(configurations);
}
if self.fallbacks.is_empty() {
if primary.request.fallback_urls.len() > MAX_HTTP_FALLBACKS {
static WARN_LEGACY_URL_LIMIT: std::sync::Once = std::sync::Once::new();
WARN_LEGACY_URL_LIMIT.call_once(|| {
tracing::warn!("HTTP validation uses only the first three URLs in legacy URL lists (primary and two fallbacks); additional URLs are ignored");
});
}
for url in primary.request.fallback_urls.iter().take(MAX_HTTP_FALLBACKS) {
let mut http = primary.clone();
http.request.url = url.clone();
http.request.fallback_urls.clear();
configurations.push((None, http));
}
} else {
for fallback in &self.fallbacks {
let mut http = if fallback.reuse_primary_validation_logic {
primary.clone()
} else if let Some(Validation::Http(http)) = &fallback.validation {
http.clone()
} else {
unreachable!("checked HTTP fallback")
};
if fallback.reuse_primary_validation_logic {
http.request.url = fallback.url.clone().expect("checked fallback URL");
}
configurations.push((Some(fallback.id.as_str()), http));
}
}
Ok(configurations)
}
pub fn selected_revocation(
&self,
fallback_id: Option<&str>,
) -> Result<Option<Cow<'_, Revocation>>> {
match fallback_id {
None => Ok(self.revocation.as_ref().map(Cow::Borrowed)),
Some(id) => self
.fallbacks
.iter()
.find(|fallback| fallback.id == id)
.ok_or_else(|| anyhow!("Unknown validated fallback ID"))?
.resolved_revocation(self.revocation.as_ref()),
}
}
const REGEX_SIZE_LIMIT: usize = 16 * 1024 * 1024;
pub fn uncommented_pattern(&self) -> Cow<'_, str> {
RULE_COMMENTS_PATTERN.replace_all(&self.pattern, "")
}
fn build_regex(pattern: &str) -> Result<regex::bytes::Regex> {
regex::bytes::RegexBuilder::new(pattern)
.unicode(false)
.size_limit(Self::REGEX_SIZE_LIMIT)
.build()
.context("Failed to build regex")
}
pub fn as_regex(&self) -> Result<regex::bytes::Regex> {
Self::build_regex(&self.uncommented_pattern())
}
pub fn matches_path(&self, path: &str) -> bool {
self.path
.as_deref()
.is_none_or(|pattern| Regex::new(pattern).is_ok_and(|regex| regex.is_match(path)))
}
pub fn betterleaks_filter(&self) -> Option<&BetterleaksExpr> {
self.betterleaks_filter.as_ref()
}
pub fn betterleaks_secret_group(&self) -> Option<usize> {
self.betterleaks_secret_group
}
pub fn is_authoritative(&self) -> bool {
self.authoritative
}
pub fn vectorscan_compatible(&self) -> bool {
true
}
pub fn as_anchored_regex(&self) -> Result<regex::bytes::Regex> {
Self::build_regex(&format!("{}$", self.uncommented_pattern()))
}
pub fn as_endpoint_regex(&self) -> Result<regex::bytes::Regex> {
Self::build_regex(&format!(r"(?:{})\z", self.uncommented_pattern()))
}
pub fn finding_sha1_fingerprint(&self) -> String {
let hash = xxh3_64(self.pattern.as_bytes());
format!("{:x}", hash)
}
pub fn to_json(&self) -> String {
serde_json::to_string(self).expect("Serialization of rule syntax should succeed")
}
pub fn from_yaml_file<P: AsRef<Path>>(path: P) -> Result<Vec<Self>> {
let path = path.as_ref();
let contents = std::fs::read_to_string(path)
.with_context(|| format!("Failed to read file: {}", path.display()))?;
#[derive(Deserialize)]
#[serde(untagged)]
enum RuleSyntaxDocument {
Sequence(Vec<RuleSyntax>),
Mapped { rules: Vec<RuleSyntax> },
}
let parsed: RuleSyntaxDocument = yaml_serde::from_str(&contents).map_err(|e| {
let context = e.location().map_or(String::new(), |loc| {
format!(" at line {} column {}", loc.line(), loc.column())
});
anyhow!("Failed to parse YAML from {}{}: {}", path.display(), context, e)
})?;
Ok(match parsed {
RuleSyntaxDocument::Sequence(rules) => rules,
RuleSyntaxDocument::Mapped { rules } => rules,
})
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Rule {
pub syntax: RuleSyntax,
finding_sha1_fingerprint: String,
min_entropy: f32,
visible: bool,
#[serde(skip, default = "default_runtime_minimum_confidence")]
runtime_minimum_confidence: Confidence,
#[serde(skip)]
runtime_dependency_helper: bool,
#[serde(skip)]
runtime_helper_visibility: Option<(bool, bool)>,
#[serde(skip)]
path_regex: OnceLock<(String, Option<Regex>)>,
#[serde(skip)]
keyword_regex: OnceLock<(Vec<String>, Option<regex::bytes::Regex>)>,
}
impl PartialEq for Rule {
fn eq(&self, other: &Self) -> bool {
self.syntax == other.syntax
&& self.finding_sha1_fingerprint == other.finding_sha1_fingerprint
&& self.min_entropy == other.min_entropy
&& self.visible == other.visible
&& self.runtime_minimum_confidence == other.runtime_minimum_confidence
&& self.runtime_dependency_helper == other.runtime_dependency_helper
&& self.runtime_helper_visibility == other.runtime_helper_visibility
}
}
fn default_runtime_minimum_confidence() -> Confidence {
Confidence::Low
}
impl Rule {
pub fn new(syntax: RuleSyntax) -> Self {
Self {
finding_sha1_fingerprint: syntax.finding_sha1_fingerprint(),
min_entropy: syntax.min_entropy,
visible: syntax.visible,
runtime_minimum_confidence: Confidence::Low,
runtime_dependency_helper: false,
runtime_helper_visibility: None,
path_regex: OnceLock::new(),
keyword_regex: OnceLock::new(),
syntax,
}
}
pub fn syntax(&self) -> &RuleSyntax {
&self.syntax
}
pub fn matches_keywords(&self, bytes: &[u8]) -> bool {
if bytes.len() <= 256 || self.syntax.keywords.is_empty() {
return self.matches_keywords_uncached(bytes);
}
let (keywords, ascii_regex) = self.keyword_regex.get_or_init(|| {
let patterns = self
.syntax
.keywords
.iter()
.filter(|keyword| keyword.is_ascii())
.map(|keyword| regex::escape(keyword))
.collect::<Vec<_>>();
let compiled = (!patterns.is_empty())
.then(|| {
regex::bytes::RegexBuilder::new(&patterns.join("|"))
.case_insensitive(true)
.unicode(false)
.build()
.ok()
})
.flatten();
(self.syntax.keywords.clone(), compiled)
});
if keywords == &self.syntax.keywords
&& let Some(regex) = ascii_regex
{
return regex.is_match(bytes)
|| keywords.iter().filter(|keyword| !keyword.is_ascii()).any(|keyword| {
String::from_utf8_lossy(bytes).to_lowercase().contains(&keyword.to_lowercase())
});
}
self.matches_keywords_uncached(bytes)
}
fn matches_keywords_uncached(&self, bytes: &[u8]) -> bool {
self.syntax.keywords.is_empty()
|| self.syntax.keywords.iter().any(|keyword| {
if keyword.is_empty() {
return true;
}
if keyword.is_ascii() {
bytes
.windows(keyword.len())
.any(|window| window.eq_ignore_ascii_case(keyword.as_bytes()))
} else {
String::from_utf8_lossy(bytes).to_lowercase().contains(&keyword.to_lowercase())
}
})
}
pub fn json_syntax(&self) -> String {
self.syntax.to_json()
}
pub fn finding_sha1_fingerprint(&self) -> &str {
&self.finding_sha1_fingerprint
}
pub fn name(&self) -> &str {
&self.syntax.name
}
pub fn id(&self) -> &str {
&self.syntax.id
}
pub fn min_entropy(&self) -> f32 {
self.min_entropy
}
pub fn set_entropy(&mut self, new_entropy: f32) -> Result<()> {
if new_entropy < 0.0 {
return Err(anyhow!("Entropy value cannot be negative"));
}
self.min_entropy = new_entropy;
self.syntax.min_entropy = new_entropy;
Ok(())
}
pub fn visible(&self) -> bool {
self.visible
}
pub fn confidence(&self) -> Confidence {
self.syntax.confidence
}
pub fn set_runtime_confidence_filter(
&mut self,
minimum_confidence: Confidence,
dependency_helper: bool,
) {
if let Some((visible, syntax_visible)) = self.runtime_helper_visibility.take() {
self.visible = visible;
self.syntax.visible = syntax_visible;
}
self.runtime_minimum_confidence = minimum_confidence;
self.runtime_dependency_helper = dependency_helper;
if dependency_helper && !self.confidence().is_at_least(&minimum_confidence) {
self.runtime_helper_visibility = Some((self.visible, self.syntax.visible));
self.visible = false;
self.syntax.visible = false;
}
}
#[deprecated(
note = "Confidence is static; use confidence(), runtime_minimum_confidence(), and is_runtime_dependency_helper()"
)]
pub fn accepts_effective_confidence(&self, _confidence: Confidence) -> bool {
self.runtime_dependency_helper
|| self.confidence().is_at_least(&self.runtime_minimum_confidence)
}
#[deprecated(
note = "Confidence is static; compare confidence() with runtime_minimum_confidence()"
)]
pub fn reports_effective_confidence(&self, _confidence: Confidence) -> bool {
self.confidence().is_at_least(&self.runtime_minimum_confidence)
}
pub fn is_runtime_dependency_helper(&self) -> bool {
self.runtime_dependency_helper
}
pub fn runtime_minimum_confidence(&self) -> Confidence {
self.runtime_minimum_confidence
}
pub fn suppress_runtime_reporting(&mut self) {
self.runtime_helper_visibility = None;
self.visible = false;
self.syntax.visible = false;
}
pub fn pattern_requirements(&self) -> Option<&PatternRequirements> {
self.syntax.pattern_requirements.as_ref()
}
pub fn matches_path(&self, path: &str) -> bool {
let Some(pattern) = self.syntax.path.as_deref() else {
return true;
};
let (cached_pattern, regex) =
self.path_regex.get_or_init(|| (pattern.to_owned(), Regex::new(pattern).ok()));
if cached_pattern != pattern {
return self.syntax.matches_path(path);
}
regex.as_ref().is_some_and(|regex| regex.is_match(path))
}
pub fn betterleaks_filter(&self) -> Option<&BetterleaksExpr> {
self.syntax.betterleaks_filter()
}
pub fn betterleaks_secret_group(&self) -> Option<usize> {
self.syntax.betterleaks_secret_group()
}
pub fn vectorscan_compatible(&self) -> bool {
self.syntax.vectorscan_compatible()
}
pub fn tls_mode(&self) -> Option<TlsMode> {
self.syntax.tls_mode
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[allow(deprecated, reason = "the compatibility wrappers must remain callable")]
fn legacy_confidence_wrappers_use_only_configured_confidence() {
for configured in [Confidence::Low, Confidence::Medium, Confidence::High] {
let mut syntax = RuleSyntax::new("acme.static", "Static confidence fixture", "token");
syntax.confidence = configured;
let mut rule = Rule::new(syntax);
rule.set_runtime_confidence_filter(Confidence::Medium, false);
for legacy in [Confidence::Low, Confidence::Medium, Confidence::High] {
let selected = configured.is_at_least(&Confidence::Medium);
assert_eq!(rule.accepts_effective_confidence(legacy), selected);
assert_eq!(rule.reports_effective_confidence(legacy), selected);
assert_eq!(rule.confidence(), configured);
}
}
}
#[test]
fn below_threshold_helpers_are_hidden_without_changing_configured_confidence() {
let mut syntax = RuleSyntax::new("acme.helper", "Helper fixture", "token");
syntax.confidence = Confidence::Low;
let mut rule = Rule::new(syntax);
rule.set_runtime_confidence_filter(Confidence::Medium, true);
assert_eq!(rule.confidence(), Confidence::Low);
assert_eq!(rule.runtime_minimum_confidence(), Confidence::Medium);
assert!(rule.is_runtime_dependency_helper());
assert!(!rule.visible());
assert!(!rule.syntax().visible);
assert!(!rule.confidence().is_at_least(&rule.runtime_minimum_confidence()));
assert_eq!(rule.clone(), rule);
}
#[test]
fn reportable_helpers_keep_their_configured_visibility() {
for visible in [false, true] {
let mut syntax = RuleSyntax::new("acme.helper", "Helper fixture", "token");
syntax.confidence = Confidence::High;
syntax.visible = visible;
let mut rule = Rule::new(syntax);
rule.set_runtime_confidence_filter(Confidence::High, true);
assert_eq!(rule.visible(), visible);
assert_eq!(rule.syntax().visible, visible);
assert_eq!(rule.confidence(), Confidence::High);
assert!(rule.confidence().is_at_least(&rule.runtime_minimum_confidence()));
}
}
#[test]
fn helper_reconfiguration_restores_both_original_visibility_flags() {
for visible in [false, true] {
for syntax_visible in [false, true] {
let mut syntax = RuleSyntax::new("acme.helper", "Helper fixture", "token");
syntax.confidence = Confidence::Low;
syntax.visible = visible;
let mut original = Rule::new(syntax);
original.syntax.visible = syntax_visible;
for (minimum, helper) in
[(Confidence::Low, false), (Confidence::Low, true), (Confidence::High, false)]
{
let mut rule = original.clone();
rule.set_runtime_confidence_filter(Confidence::High, true);
assert!(!rule.visible());
assert!(!rule.syntax().visible);
rule.set_runtime_confidence_filter(minimum, helper);
assert_eq!(rule.visible(), visible);
assert_eq!(rule.syntax().visible, syntax_visible);
assert_eq!(rule.confidence(), Confidence::Low);
assert_eq!(rule.runtime_minimum_confidence(), minimum);
assert_eq!(rule.is_runtime_dependency_helper(), helper);
assert!(rule.runtime_helper_visibility.is_none());
}
}
}
}
#[test]
fn repeated_helper_configuration_preserves_original_visibility() {
let mut syntax = RuleSyntax::new("acme.helper", "Helper fixture", "token");
syntax.confidence = Confidence::Low;
let mut rule = Rule::new(syntax);
let original = rule.clone();
for minimum in [Confidence::High, Confidence::Medium, Confidence::Medium, Confidence::High]
{
rule.set_runtime_confidence_filter(minimum, true);
assert!(!rule.visible());
assert!(!rule.syntax().visible);
}
rule.set_runtime_confidence_filter(Confidence::Low, false);
assert_eq!(rule, original);
assert!(rule.visible());
assert!(rule.syntax().visible);
}
#[test]
fn permanent_suppression_survives_helper_reconfiguration() {
for helper_first in [false, true] {
let mut syntax = RuleSyntax::new("acme.helper", "Helper fixture", "token");
syntax.confidence = Confidence::Low;
let mut rule = Rule::new(syntax);
if helper_first {
rule.set_runtime_confidence_filter(Confidence::High, true);
}
rule.suppress_runtime_reporting();
assert!(rule.runtime_helper_visibility.is_none());
for (minimum, helper) in
[(Confidence::Low, false), (Confidence::High, true), (Confidence::Low, false)]
{
rule.set_runtime_confidence_filter(minimum, helper);
assert!(!rule.visible());
assert!(!rule.syntax().visible);
}
}
}
#[test]
fn cloned_hidden_helpers_restore_visibility_independently() {
let mut syntax = RuleSyntax::new("acme.helper", "Helper fixture", "token");
syntax.confidence = Confidence::Low;
let mut rule = Rule::new(syntax);
rule.set_runtime_confidence_filter(Confidence::High, true);
let mut cloned = rule.clone();
assert_eq!(rule, cloned);
cloned.set_runtime_confidence_filter(Confidence::Low, false);
assert!(cloned.visible());
assert!(cloned.syntax().visible);
assert!(!rule.visible());
assert!(!rule.syntax().visible);
assert!(rule.is_runtime_dependency_helper());
cloned.suppress_runtime_reporting();
rule.set_runtime_confidence_filter(Confidence::Low, false);
assert!(rule.visible());
assert!(rule.syntax().visible);
assert!(!cloned.visible());
assert!(!cloned.syntax().visible);
}
#[test]
fn helper_visibility_snapshot_affects_equality_but_not_serialization() {
let mut syntax = RuleSyntax::new("acme.helper", "Helper fixture", "token");
syntax.confidence = Confidence::Low;
let original = Rule::new(syntax);
assert!(original.runtime_helper_visibility.is_none());
let mut temporary = original.clone();
temporary.set_runtime_confidence_filter(Confidence::High, true);
let mut permanent = original.clone();
permanent.suppress_runtime_reporting();
permanent.set_runtime_confidence_filter(Confidence::High, true);
assert_eq!(temporary.syntax(), permanent.syntax());
assert_eq!(temporary.visible(), permanent.visible());
assert_ne!(temporary, permanent);
let serialized = serde_json::to_value(&temporary).unwrap();
assert_eq!(serialized, serde_json::to_value(&permanent).unwrap());
assert!(serialized.get("runtime_helper_visibility").is_none());
let mut restored: Rule = serde_json::from_value(serialized).unwrap();
assert!(restored.runtime_helper_visibility.is_none());
let mut expected = original;
expected.suppress_runtime_reporting();
assert_eq!(restored, expected);
restored.set_runtime_confidence_filter(Confidence::Low, false);
assert!(!restored.visible());
assert!(!restored.syntax().visible);
}
#[test]
fn runtime_path_regex_is_cached_without_changing_serialization_or_equality() {
let mut syntax = RuleSyntax::new("acme.path", "Path fixture", "token");
syntax.path = Some(r"(?i)\.pem$".into());
let rule = Rule::new(syntax);
let cold = rule.clone();
let serialized = serde_json::to_value(&rule).unwrap();
assert!(rule.path_regex.get().is_none());
for _ in 0..1000 {
assert!(rule.matches_path("private.PEM"));
assert!(!rule.matches_path("source.rs"));
}
let (pattern, compiled) = rule.path_regex.get().expect("path regex was cached");
assert_eq!(pattern, r"(?i)\.pem$");
assert!(compiled.is_some());
assert_eq!(rule, cold);
assert_eq!(rule, rule.clone());
assert_eq!(serde_json::to_value(&rule).unwrap(), serialized);
let restored: Rule = serde_json::from_value(serialized).unwrap();
assert_eq!(rule, restored);
assert!(restored.path_regex.get().is_none());
assert!(restored.matches_path("private.pem"));
}
#[test]
fn runtime_path_cache_preserves_invalid_and_mutated_path_restrictions() {
let mut rule = Rule::new(RuleSyntax::new("acme.path", "Path fixture", "token"));
assert!(rule.matches_path("anywhere"));
assert!(rule.path_regex.get().is_none());
rule.syntax.path = Some("[".into());
assert!(!rule.matches_path("anywhere"));
assert!(!rule.matches_path("another"));
assert!(rule.path_regex.get().unwrap().1.is_none());
rule.syntax.path = Some(r"\.key$".into());
assert!(rule.matches_path("private.key"));
assert!(!rule.matches_path("source.rs"));
rule.syntax.path = None;
assert!(rule.matches_path("anywhere"));
}
#[test]
fn candidate_keywords_support_ascii_and_unicode_case_folding() {
let mut syntax = RuleSyntax::new("acme.keyword", "Keyword", "token");
assert!(Rule::new(syntax.clone()).matches_keywords(b""));
syntax.keywords = vec!["Provider".into(), "CAFÉ".into()];
let rule = Rule::new(syntax);
assert!(rule.matches_keywords(b"pRoViDeR"));
assert!(rule.matches_keywords("café".as_bytes()));
assert!(!rule.matches_keywords(b"unrelated"));
}
#[test]
fn large_source_keyword_search_preserves_literal_and_case_folding_semantics() {
for keywords in [
vec!["Provider", "CAFÉ"],
vec!["[literal]+.*", "k"],
vec!["�", "ASCII"],
vec![""],
vec!["CAFÉ"],
] {
let mut syntax = RuleSyntax::new("acme.keyword", "Keyword", "token");
syntax.keywords = keywords.into_iter().map(str::to_owned).collect();
let rule = Rule::new(syntax);
for value in [
b"pRoViDeR".as_slice(),
"café".as_bytes(),
b"[LITERAL]+.*",
b"LITERALxxxxx",
"K".as_bytes(),
b"\xffASCII",
b"\xff",
b"unrelated",
] {
let bytes = [vec![b' '; 4096], value.to_vec()].concat();
assert_eq!(rule.matches_keywords(&bytes), rule.matches_keywords_uncached(&bytes));
}
}
}
#[test]
fn runtime_keyword_cache_preserves_serialization_equality_and_mutated_keywords() {
let mut syntax = RuleSyntax::new("acme.keyword", "Keyword", "token");
syntax.keywords = vec!["provider".into()];
let mut rule = Rule::new(syntax);
let cold = rule.clone();
let serialized = serde_json::to_value(&rule).unwrap();
let bytes = [vec![b' '; 4096], b"PROVIDER".to_vec()].concat();
assert!(rule.matches_keywords(&bytes));
assert!(rule.keyword_regex.get().unwrap().1.is_some());
assert_eq!(rule, cold);
assert_eq!(rule, rule.clone());
assert_eq!(serde_json::to_value(&rule).unwrap(), serialized);
let restored: Rule = serde_json::from_value(serialized).unwrap();
assert!(restored.keyword_regex.get().is_none());
assert!(restored.matches_keywords(&bytes));
rule.syntax.keywords = vec!["replacement".into()];
assert!(!rule.matches_keywords(&bytes));
let replacement = [vec![b' '; 4096], b"REPLACEMENT".to_vec()].concat();
assert!(rule.matches_keywords(&replacement));
rule.syntax.keywords.clear();
assert!(rule.matches_keywords(&bytes));
}
#[test]
fn betterleaks_env_inputs_collect_only_literal_get_calls() {
let program: BetterleaksValidation = serde_json::from_value(serde_json::json!({
"expression": r#"
let dynamic = "DYNAMIC";
[env.get("Z_ADMIN"), env.get("A_ID"), env.get("Z_ADMIN"),
env.get(dynamic), env.get("COMPUTED" + "_NAME"),
env.getOrDefault("OPTIONAL", "fallback"), other.get("OTHER"),
"env.get(\"STRING_ONLY\")", false ? env.get("BRANCH_INPUT") : ""]
"#,
"analyze": "env.get('ANALYZE_ONLY')"
}))
.unwrap();
assert_eq!(
program.expression.env_input_vars().into_iter().collect::<Vec<_>>(),
["A_ID", "BRANCH_INPUT", "Z_ADMIN"]
);
}
#[test]
fn betterleaks_env_inputs_traverse_nested_expression_nodes() {
let cases: &[(&str, &[&str])] = &[
(
"let admin = env.get('LET'); !env.get('UNARY') && (env.get('COND') ? env.get('YES') : env.get('NO'))",
&["COND", "LET", "NO", "UNARY", "YES"],
),
("{'entry': [env.get('ARRAY')]}[env.get('MEMBER')]", &["ARRAY", "MEMBER"]),
("env.get('NODE')[env.get('FROM'):env.get('TO')]", &["FROM", "NODE", "TO"]),
("map([1], env.get('PREDICATE'))", &["PREDICATE"]),
("http.get(env.get('CALL_ARGUMENT'))", &["CALL_ARGUMENT"]),
("env.get(env.get('DYNAMIC_ARGUMENT'))", &["DYNAMIC_ARGUMENT"]),
("env.get('CHAIN')?.field", &["CHAIN"]),
];
for (source, expected) in cases {
let program: BetterleaksValidation =
serde_json::from_value(serde_json::json!({"expression": source})).unwrap();
assert_eq!(
program.expression.env_input_vars().into_iter().collect::<Vec<_>>(),
*expected,
"{source}"
);
}
}
#[test]
fn custom_yaml_betterleaks_programs_accept_source_and_round_trip_as_ast() {
let yaml = r#"
type: Betterleaks
content:
expression: 'let r = http.get("https://example.invalid"); r.status == 200 ? {"result": "valid"} : validate.unknown(r)'
analyze: 'analysis.capabilities({"read": true})'
"#;
let validation: Validation = yaml_serde::from_str(yaml).unwrap();
let Validation::Betterleaks(program) = &validation else { panic!("wrong validator") };
assert!(matches!(program.expression, BetterleaksExpr::VariableDeclarator { .. }));
assert!(program.analyze.is_some());
let ast_yaml = yaml_serde::to_string(&validation).unwrap();
assert_eq!(yaml_serde::from_str::<Validation>(&ast_yaml).unwrap(), validation);
let revocation: Revocation = yaml_serde::from_str("type: Betterleaks\ncontent:\n expression: 'let r = http.delete(\"https://example.invalid\"); r.status == 204 ? {\"result\": \"revoked\"} : revoke.unknown(r)'\n").unwrap();
assert!(matches!(revocation, Revocation::Betterleaks(_)));
assert!(
yaml_serde::from_str::<Validation>(
"type: Betterleaks\ncontent:\n expression: 'let broken ='\n"
)
.is_err()
);
}
#[test]
fn http_url_strings_and_fallback_lists_round_trip_without_changing_other_request_fields() {
for url in [
serde_json::json!("https://primary.example/identity"),
serde_json::json!([
"https://primary.example/identity",
"https://secondary.example/identity",
"{{ THIRD_ENDPOINT }}/identity"
]),
] {
let definition = serde_json::json!({
"method": "POST", "url": url,
"headers": {"Authorization": "Bearer {{ TOKEN }}"},
"body": "{{ TOKEN }}", "multipart": null,
"response_matcher": [{"type": "StatusMatch", "status": [200],
"match_all_status": false, "negative": false}],
"response_is_html": true
});
let request: HttpRequest = serde_json::from_value(definition.clone()).unwrap();
assert_eq!(serde_json::to_value(&request).unwrap(), definition);
let yaml = yaml_serde::to_string(&request).unwrap();
assert_eq!(yaml_serde::from_str::<HttpRequest>(&yaml).unwrap(), request);
}
}
#[test]
fn http_url_lists_reject_empty_non_string_and_blank_endpoints() {
for url in [
serde_json::json!([]),
serde_json::json!(["https://primary.example", " "]),
serde_json::json!(["https://primary.example", 42]),
] {
assert!(
serde_json::from_value::<HttpRequest>(serde_json::json!({
"method": "GET", "url": url
}))
.is_err()
);
}
}
#[test]
fn http_url_list_with_one_endpoint_preserves_scalar_request_behavior() {
let request: HttpRequest =
yaml_serde::from_str("method: GET\nurl:\n - https://primary.example/identity\n")
.unwrap();
assert_eq!(request.url, "https://primary.example/identity");
assert!(request.fallback_urls.is_empty());
assert_eq!(request.urls().collect::<Vec<_>>(), ["https://primary.example/identity"]);
assert!(serde_json::to_value(&request).unwrap()["url"].is_string());
}
use regex::bytes::Regex as BytesRegex;
#[test]
fn http_revocation_rejects_oauth2_auth_during_deserialization() {
let password = "operator-password-secret";
let client_secret = "operator-client-secret";
for auth in [
serde_json::json!({"oauth2": {
"token_endpoint": "https://idp.example.com/token",
"ropc": {"username": "operator", "password": password,
"client_id": "scanner", "client_secret": client_secret}
}}),
serde_json::json!({"oauth2": {"ropc": {
"password": [password], "client_secret": {"secret": client_secret}
}}}),
] {
let definition = serde_json::json!({"type": "Http", "content": {
"auth": auth,
"request": {"method": "DELETE", "url": "https://api.example.com/token",
"response_matcher": [{"type": "StatusMatch", "status": [204]}]}
}});
let json_error = serde_json::from_value::<Revocation>(definition.clone()).unwrap_err();
let yaml = yaml_serde::to_string(&definition).unwrap();
let yaml_error = yaml_serde::from_str::<Revocation>(&yaml).unwrap_err();
for error in [json_error.to_string(), yaml_error.to_string()] {
assert!(error.contains("OAuth2 auth is supported for validation only"));
assert!(!error.contains(password));
assert!(!error.contains(client_secret));
}
let document = serde_json::json!({"rules": [{
"id": "acme.revocation-auth", "name": "Revocation auth fixture",
"pattern": "(synthetic-secret)", "revocation": definition
}]});
let yaml = yaml_serde::to_string(&document).unwrap();
let error = crate::Rules::from_paths_and_contents(
[(Path::new("revocation-auth.yml"), yaml.as_bytes())],
Confidence::Low,
)
.err()
.expect("unsupported auth must fail during rule loading");
assert!(!error.to_string().contains(password));
assert!(!error.to_string().contains(client_secret));
}
}
#[test]
fn supported_revocation_definitions_preserve_defaults_and_round_trip() {
for definition in [
serde_json::json!({"type": "AWS"}),
serde_json::json!({"type": "GCP"}),
serde_json::json!({"type": "Http", "content": {
"request": {"method": "DELETE", "url": "https://api.example.com/token"}
}}),
serde_json::json!({"type": "Http", "content": {
"auth": null,
"request": {"method": "DELETE", "url": "https://api.example.com/token"}
}}),
serde_json::json!({"type": "HttpMultiStep", "content": {"steps": [{
"request": {"method": "DELETE", "url": "https://api.example.com/token"}
}]}}),
] {
let revocation: Revocation = serde_json::from_value(definition).unwrap();
let serialized = serde_json::to_value(&revocation).unwrap();
assert_eq!(serde_json::from_value::<Revocation>(serialized).unwrap(), revocation);
let yaml = yaml_serde::to_string(&revocation).unwrap();
assert_eq!(yaml_serde::from_str::<Revocation>(&yaml).unwrap(), revocation);
if let Revocation::Http(http) = revocation {
assert!(http.auth.is_none());
assert!(http.multipart.is_none());
assert!(http.request.headers.is_empty());
assert!(!http.request.response_is_html);
}
}
}
#[test]
fn oauth2_inspection_redacts_literals_without_changing_lossless_serialization() {
for credentials in [
serde_json::json!({"username": "operator-user-secret", "password": "operator-password-secret",
"client_id": "scanner", "client_secret": "operator-client-secret"}),
serde_json::json!({"username_env": "KF_OPERATOR_USERNAME", "password_env": "KF_OPERATOR_PASSWORD",
"client_id": "scanner", "client_secret_env": "KF_OPERATOR_CLIENT_SECRET"}),
] {
let validation: Validation = serde_json::from_value(serde_json::json!({
"type": "Http", "content": {
"auth": {"oauth2": {"token_endpoint": "https://idp.example.com/token", "ropc": credentials}},
"request": {"method": "GET", "url": "https://verifier.example.com/verify"}
}
})).unwrap();
let original = serde_json::to_value(&validation).unwrap();
let inspected = validation.redacted_for_inspection();
let redacted = serde_json::to_value(&inspected).unwrap();
let credentials = &redacted["content"]["auth"]["oauth2"]["ropc"];
for field in ["username", "password", "client_secret"] {
let expected = if original["content"]["auth"]["oauth2"]["ropc"][field].is_null() {
serde_json::Value::Null
} else {
serde_json::json!("[REDACTED]")
};
assert_eq!(credentials[field], expected);
}
for field in ["username_env", "password_env", "client_secret_env", "client_id", "scope"]
{
assert_eq!(
credentials[field],
original["content"]["auth"]["oauth2"]["ropc"][field]
);
}
assert_eq!(redacted["content"]["auth"]["oauth2"]["token_header"], "Authorization");
assert_eq!(serde_json::to_value(&validation).unwrap(), original);
assert_eq!(serde_json::from_value::<Validation>(original).unwrap(), validation);
}
}
#[test]
fn test_pattern_requirements_digits() {
let reqs = PatternRequirements {
min_digits: Some(2),
min_uppercase: None,
min_lowercase: None,
min_special_chars: None,
special_chars: None,
ignore_if_contains: None,
checksum: None,
};
assert!(matches!(reqs.validate(b"abc123def", None, true), PatternValidationResult::Passed));
assert!(matches!(reqs.validate(b"abc1def", None, true), PatternValidationResult::Failed));
assert!(matches!(reqs.validate(b"abcdef", None, true), PatternValidationResult::Failed));
}
#[test]
fn test_pattern_requirements_checksum() {
let reqs = PatternRequirements {
min_digits: None,
min_uppercase: None,
min_lowercase: None,
min_special_chars: None,
special_chars: None,
ignore_if_contains: None,
checksum: Some(ChecksumRequirement {
actual: ChecksumActual {
template: "{{ MATCH | suffix: 6 }}".to_string(),
requires_capture: Some("checksum".to_string()),
},
expected: "{{ BODY | crc32 | base62: 6 }}".to_string(),
skip_if_missing: true,
}),
};
let token = b"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";
let regex =
BytesRegex::new(r"(?x) ghp_(?P<body>[A-Za-z0-9]{30})(?P<checksum>[A-Za-z0-9]{6})")
.unwrap();
let captures = regex.captures(token).expect("token should match");
assert!(matches!(
reqs.validate(
token,
Some(PatternRequirementContext {
regex: ®ex,
captures: &captures,
full_match: token
}),
true
),
PatternValidationResult::Passed
));
let mut invalid = token.to_vec();
*invalid.last_mut().unwrap() = b'0';
let captures_invalid =
regex.captures(&invalid).expect("invalid token should still match pattern");
assert!(matches!(
reqs.validate(
&invalid,
Some(PatternRequirementContext {
regex: ®ex,
captures: &captures_invalid,
full_match: &invalid,
}),
true
),
PatternValidationResult::FailedChecksum { .. }
));
let legacy = b"ghp_legacy_token";
assert!(matches!(reqs.validate(legacy, None, true), PatternValidationResult::Passed));
}
#[test]
fn test_pattern_requirements_uppercase() {
let reqs = PatternRequirements {
min_digits: None,
min_uppercase: Some(2),
min_lowercase: None,
min_special_chars: None,
special_chars: None,
ignore_if_contains: None,
checksum: None,
};
assert!(matches!(reqs.validate(b"ABCdef", None, true), PatternValidationResult::Passed));
assert!(matches!(reqs.validate(b"Adef", None, true), PatternValidationResult::Failed));
assert!(matches!(reqs.validate(b"abcdef", None, true), PatternValidationResult::Failed));
}
#[test]
fn test_pattern_requirements_lowercase() {
let reqs = PatternRequirements {
min_digits: None,
min_uppercase: None,
min_lowercase: Some(2),
min_special_chars: None,
special_chars: None,
ignore_if_contains: None,
checksum: None,
};
assert!(matches!(reqs.validate(b"ABCdef", None, true), PatternValidationResult::Passed));
assert!(matches!(reqs.validate(b"ABCd", None, true), PatternValidationResult::Failed));
assert!(matches!(reqs.validate(b"ABC123", None, true), PatternValidationResult::Failed));
}
#[test]
fn test_pattern_requirements_special_chars() {
let reqs = PatternRequirements {
min_digits: None,
min_uppercase: None,
min_lowercase: None,
min_special_chars: Some(2),
special_chars: None, ignore_if_contains: None,
checksum: None,
};
assert!(matches!(reqs.validate(b"abc!@def", None, true), PatternValidationResult::Passed));
assert!(matches!(reqs.validate(b"abc!def", None, true), PatternValidationResult::Failed));
assert!(matches!(reqs.validate(b"abcdef", None, true), PatternValidationResult::Failed));
}
#[test]
fn test_pattern_requirements_custom_special_chars() {
let reqs = PatternRequirements {
min_digits: None,
min_uppercase: None,
min_lowercase: None,
min_special_chars: Some(2),
special_chars: Some("$%^".to_string()),
ignore_if_contains: None,
checksum: None,
};
assert!(matches!(reqs.validate(b"abc$%def", None, true), PatternValidationResult::Passed));
assert!(matches!(reqs.validate(b"abc!@def", None, true), PatternValidationResult::Failed));
assert!(matches!(reqs.validate(b"abc$def", None, true), PatternValidationResult::Failed));
}
#[test]
fn test_pattern_requirements_combined() {
let reqs = PatternRequirements {
min_digits: Some(1),
min_uppercase: Some(1),
min_lowercase: Some(1),
min_special_chars: Some(1),
special_chars: None,
ignore_if_contains: None,
checksum: None,
};
assert!(matches!(reqs.validate(b"Abc1!", None, true), PatternValidationResult::Passed));
assert!(matches!(reqs.validate(b"Abc!", None, true), PatternValidationResult::Failed));
assert!(matches!(reqs.validate(b"abc1!", None, true), PatternValidationResult::Failed));
assert!(matches!(reqs.validate(b"ABC1!", None, true), PatternValidationResult::Failed));
assert!(matches!(reqs.validate(b"Abc1", None, true), PatternValidationResult::Failed));
}
#[test]
fn test_pattern_requirements_ignore_if_contains() {
let reqs = PatternRequirements {
min_digits: None,
min_uppercase: None,
min_lowercase: None,
min_special_chars: None,
special_chars: None,
ignore_if_contains: Some(vec!["test".to_string(), "Demo".to_string()]),
checksum: None,
};
assert!(matches!(
reqs.validate(b"MyTestToken", None, true),
PatternValidationResult::IgnoredBySubstring { .. }
));
assert!(matches!(
reqs.validate(b"example-demo-value", None, true),
PatternValidationResult::IgnoredBySubstring { .. }
));
assert!(matches!(
reqs.validate(b"example-value", None, true),
PatternValidationResult::Passed
));
}
#[test]
fn test_pattern_requirements_ignore_if_contains_ignores_empty_entries() {
let reqs = PatternRequirements {
min_digits: None,
min_uppercase: None,
min_lowercase: None,
min_special_chars: None,
special_chars: None,
ignore_if_contains: Some(vec![" ".to_string(), "".to_string(), "BLOCK".to_string()]),
checksum: None,
};
assert!(matches!(
reqs.validate(b"needs-blocking", None, true),
PatternValidationResult::IgnoredBySubstring { .. }
));
assert!(matches!(reqs.validate(b"allowed", None, true), PatternValidationResult::Passed));
}
#[test]
fn test_pattern_requirements_ignore_if_contains_can_be_disabled() {
let reqs = PatternRequirements {
min_digits: None,
min_uppercase: None,
min_lowercase: None,
min_special_chars: None,
special_chars: None,
ignore_if_contains: Some(vec!["ignoreme".to_string()]),
checksum: None,
};
assert!(matches!(
reqs.validate(b"value-ignoreme", None, true),
PatternValidationResult::IgnoredBySubstring { .. }
));
assert!(matches!(
reqs.validate(b"value-ignoreme", None, false),
PatternValidationResult::Passed
));
}
#[test]
fn test_pattern_requirements_none() {
let reqs = PatternRequirements {
min_digits: None,
min_uppercase: None,
min_lowercase: None,
min_special_chars: None,
special_chars: None,
ignore_if_contains: None,
checksum: None,
};
assert!(matches!(reqs.validate(b"anything", None, true), PatternValidationResult::Passed));
assert!(matches!(reqs.validate(b"123", None, true), PatternValidationResult::Passed));
assert!(matches!(reqs.validate(b"!@#", None, true), PatternValidationResult::Passed));
}
}