fix(fermata): an unknown config field is an error someone sees; a broken layer costs only that layer
deny_unknown_fields on every config struct. [enforcement] mode, EnforcementMode and mask-entire-file are gone, and on_parse_error defaults to allow. New settings on_unparsed_read and on_mask_write, default deny, read by later blocks. SecretsConfig::load stays strict for the channel filter. load_or_default skips only the layers that fail, so a typo keeps the other layers and the default list. Hooks note the broken layer and any skipped() secret file beside output that shows text, not beside every Write (shows_text). Under deny the refusal is unchanged. fermata check exits 2 with the line number. A non-UTF-8 layer counts as a failed layer; a layer whose bytes cannot be read stays silent, as pinned.
This commit is contained in:
+38
-16
@@ -66,6 +66,14 @@ fn run_check(op: Op, json: bool, paths: &[PathBuf]) -> ExitCode {
|
|||||||
Some(r) => r,
|
Some(r) => r,
|
||||||
None => continue,
|
None => continue,
|
||||||
};
|
};
|
||||||
|
// `Policy::load` goes on without a broken layer; a check says so instead.
|
||||||
|
let (_, errors) = SecretsConfig::load_or_default(&root);
|
||||||
|
if !errors.is_empty() {
|
||||||
|
for e in &errors {
|
||||||
|
eprintln!("fermata: secrets config: {e}");
|
||||||
|
}
|
||||||
|
return ExitCode::from(2);
|
||||||
|
}
|
||||||
let policy = match Policy::load(&root) {
|
let policy = match Policy::load(&root) {
|
||||||
Ok(p) => p,
|
Ok(p) => p,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
@@ -147,8 +155,8 @@ fn gate_failure(root: &Path, what: &str) -> Decision {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The project's policy, or the decision to give without one. `Policy::load`
|
/// The project's policy, or the decision to give without one. `Policy::load` goes on
|
||||||
/// treats a broken config as no rules, which a project under `deny` did not ask for.
|
/// without a broken layer's rules, which a project under `deny` did not ask for.
|
||||||
fn gate_policy(root: &Path) -> Result<Policy, Decision> {
|
fn gate_policy(root: &Path) -> Result<Policy, Decision> {
|
||||||
if let Err(e) = SecretsConfig::load(root) {
|
if let Err(e) = SecretsConfig::load(root) {
|
||||||
let refused = gate_failure(root, &format!("{} cannot be loaded,", shown_path(e.path(), root)));
|
let refused = gate_failure(root, &format!("{} cannot be loaded,", shown_path(e.path(), root)));
|
||||||
@@ -230,11 +238,10 @@ fn run_pre_tool_use(
|
|||||||
|
|
||||||
/// Handle a PostToolUse hook event (output redaction).
|
/// Handle a PostToolUse hook event (output redaction).
|
||||||
///
|
///
|
||||||
/// Fail-open: an error results in `{}` on stdout and exit 0, so the harness
|
/// Fail-open: an error costs only what failed, and output that shows text gets a note
|
||||||
/// continues with the original output. Two exceptions replace the output with a
|
/// saying so. Two exceptions replace the output with a refusal: `on_parse_error = "deny"`
|
||||||
/// refusal: `on_parse_error = "deny"` when the secrets cannot be loaded, and, under
|
/// when the secrets cannot be loaded, and, under every setting, a secret that sits where
|
||||||
/// every setting, a secret that sits where it cannot be masked. Nothing printed
|
/// it cannot be masked. Nothing printed here quotes a file or a value.
|
||||||
/// here quotes a file or a value.
|
|
||||||
fn run_post_tool_use(
|
fn run_post_tool_use(
|
||||||
adapter: &dyn dirigent_fermata::harness::HarnessAdapter,
|
adapter: &dyn dirigent_fermata::harness::HarnessAdapter,
|
||||||
buf: &[u8],
|
buf: &[u8],
|
||||||
@@ -276,7 +283,18 @@ fn run_post_tool_use(
|
|||||||
ExitCode::from(0)
|
ExitCode::from(0)
|
||||||
};
|
};
|
||||||
|
|
||||||
// Load secrets config; fail-open if missing or broken, unless it says `deny`.
|
let answer = |updated: Option<&serde_json::Value>, notes: &[String]| {
|
||||||
|
let context = (!notes.is_empty()).then(|| notes.join("\n"));
|
||||||
|
let out = adapter
|
||||||
|
.render_post_tool_use(&payload, updated, context.as_deref())
|
||||||
|
.unwrap_or_else(|_| b"{}".to_vec());
|
||||||
|
let _ = std::io::stdout().lock().write_all(&out);
|
||||||
|
ExitCode::from(0)
|
||||||
|
};
|
||||||
|
let shows_text = adapter.shows_text(&payload);
|
||||||
|
let mut notes = Vec::new();
|
||||||
|
|
||||||
|
// Load secrets config; a broken layer costs that layer, unless it says `deny`.
|
||||||
let config = match SecretsConfig::load(&root) {
|
let config = match SecretsConfig::load(&root) {
|
||||||
Ok(c) => c,
|
Ok(c) => c,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
@@ -284,7 +302,11 @@ fn run_post_tool_use(
|
|||||||
if SecretsConfig::denies_on_failure(&root) {
|
if SecretsConfig::denies_on_failure(&root) {
|
||||||
return withhold(format!("{} cannot be loaded, {FIX_OR_CHANGE}", shown_path(e.path(), &root)));
|
return withhold(format!("{} cannot be loaded, {FIX_OR_CHANGE}", shown_path(e.path(), &root)));
|
||||||
}
|
}
|
||||||
return pass_through();
|
let (config, errors) = SecretsConfig::load_or_default(&root);
|
||||||
|
if shows_text {
|
||||||
|
notes.extend(errors.iter().map(|e| format!("[fermata] {e}. That layer's rules are off.")));
|
||||||
|
}
|
||||||
|
config
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let deny = config.enforcement.on_parse_error == ParseErrorAction::Deny;
|
let deny = config.enforcement.on_parse_error == ParseErrorAction::Deny;
|
||||||
@@ -300,9 +322,13 @@ fn run_post_tool_use(
|
|||||||
None => format!("the [files] patterns in .botsecrets cannot be used, {FIX_OR_CHANGE}"),
|
None => format!("the [files] patterns in .botsecrets cannot be used, {FIX_OR_CHANGE}"),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return pass_through();
|
return answer(None, ¬es);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
if shows_text && !manifest.skipped().is_empty() {
|
||||||
|
let files: Vec<String> = manifest.skipped().iter().map(|path| shown_path(path, &root)).collect();
|
||||||
|
notes.push(format!("[fermata] {} cannot be parsed, so its values are not masked here.", files.join(", ")));
|
||||||
|
}
|
||||||
|
|
||||||
// Redact the response in its own shape.
|
// Redact the response in its own shape.
|
||||||
let redactor = Redactor::new(&manifest, config.redaction.style);
|
let redactor = Redactor::new(&manifest, config.redaction.style);
|
||||||
@@ -324,13 +350,9 @@ fn run_post_tool_use(
|
|||||||
|
|
||||||
// Scan what is left, so that known secrets are not flagged again.
|
// Scan what is left, so that known secrets are not flagged again.
|
||||||
let output = updated.as_ref().unwrap_or(&payload.tool_response);
|
let output = updated.as_ref().unwrap_or(&payload.tool_response);
|
||||||
let warning = heuristic_warning(&config, &adapter.output_text(&payload, output));
|
notes.extend(heuristic_warning(&config, &adapter.output_text(&payload, output)));
|
||||||
|
|
||||||
let out = adapter
|
answer(updated.as_ref(), ¬es)
|
||||||
.render_post_tool_use(&payload, updated.as_ref(), warning.as_deref())
|
|
||||||
.unwrap_or_else(|_| b"{}".to_vec());
|
|
||||||
let _ = std::io::stdout().lock().write_all(&out);
|
|
||||||
ExitCode::from(0)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Run the heuristic scanner if enabled. `report` logs to stderr and changes
|
/// Run the heuristic scanner if enabled. `report` logs to stderr and changes
|
||||||
|
|||||||
+2
-5
@@ -28,11 +28,8 @@ impl Policy {
|
|||||||
let botignore = BotignoreSet::load(root)?;
|
let botignore = BotignoreSet::load(root)?;
|
||||||
|
|
||||||
// Load policy from .botsecrets (or fermata.toml fallback).
|
// Load policy from .botsecrets (or fermata.toml fallback).
|
||||||
// If SecretsConfig::load() fails, use empty defaults (fail-open).
|
// A layer that fails costs only its own rules (fail-open).
|
||||||
let policy = SecretsConfig::load(root)
|
let policy = SecretsConfig::load_or_default(root).0.policy.unwrap_or_default();
|
||||||
.ok()
|
|
||||||
.and_then(|s| s.policy)
|
|
||||||
.unwrap_or_default();
|
|
||||||
|
|
||||||
let (read_globs, read_patterns) = compile_globs(
|
let (read_globs, read_patterns) = compile_globs(
|
||||||
policy.read.as_ref().map(|r| r.patterns.as_slice()).unwrap_or(&[]),
|
policy.read.as_ref().map(|r| r.patterns.as_slice()).unwrap_or(&[]),
|
||||||
|
|||||||
+65
-24
@@ -49,6 +49,7 @@ impl SecretsConfigError {
|
|||||||
///
|
///
|
||||||
/// When present, this provides file-access and bash policy rules.
|
/// When present, this provides file-access and bash policy rules.
|
||||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
pub struct PolicyConfig {
|
pub struct PolicyConfig {
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub read: Option<OpRules>,
|
pub read: Option<OpRules>,
|
||||||
@@ -59,12 +60,14 @@ pub struct PolicyConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Default, Clone, Deserialize, Serialize)]
|
#[derive(Debug, Default, Clone, Deserialize, Serialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
pub struct OpRules {
|
pub struct OpRules {
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub patterns: Vec<String>,
|
pub patterns: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Default, Clone, Deserialize, Serialize)]
|
#[derive(Debug, Default, Clone, Deserialize, Serialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
pub struct BashRules {
|
pub struct BashRules {
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub deny: Vec<String>,
|
pub deny: Vec<String>,
|
||||||
@@ -79,6 +82,7 @@ pub struct BashRules {
|
|||||||
|
|
||||||
/// Top-level `.botsecrets` configuration.
|
/// Top-level `.botsecrets` configuration.
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
pub struct SecretsConfig {
|
pub struct SecretsConfig {
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub files: FilesConfig,
|
pub files: FilesConfig,
|
||||||
@@ -97,12 +101,14 @@ pub struct SecretsConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
pub struct FilesConfig {
|
pub struct FilesConfig {
|
||||||
#[serde(default = "default_file_patterns")]
|
#[serde(default = "default_file_patterns")]
|
||||||
pub patterns: Vec<String>,
|
pub patterns: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
pub struct KeysConfig {
|
pub struct KeysConfig {
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub include: Vec<String>,
|
pub include: Vec<String>,
|
||||||
@@ -120,6 +126,7 @@ pub enum RedactionStyle {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
pub struct RedactionConfig {
|
pub struct RedactionConfig {
|
||||||
#[serde(default = "default_redaction_style")]
|
#[serde(default = "default_redaction_style")]
|
||||||
pub style: RedactionStyle,
|
pub style: RedactionStyle,
|
||||||
@@ -134,6 +141,7 @@ pub enum HeuristicMode {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
pub struct HeuristicConfig {
|
pub struct HeuristicConfig {
|
||||||
#[serde(default = "default_true")]
|
#[serde(default = "default_true")]
|
||||||
pub enabled: bool,
|
pub enabled: bool,
|
||||||
@@ -143,31 +151,36 @@ pub struct HeuristicConfig {
|
|||||||
pub patterns: Vec<String>,
|
pub patterns: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
|
|
||||||
#[serde(rename_all = "kebab-case")]
|
|
||||||
pub enum EnforcementMode {
|
|
||||||
Strict,
|
|
||||||
Permissive,
|
|
||||||
Audit,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
|
||||||
#[serde(rename_all = "kebab-case")]
|
#[serde(rename_all = "kebab-case")]
|
||||||
pub enum ParseErrorAction {
|
pub enum ParseErrorAction {
|
||||||
MaskEntireFile,
|
|
||||||
Allow,
|
Allow,
|
||||||
Deny,
|
Deny,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
/// What a guard does with a call it would stop.
|
||||||
pub struct EnforcementConfig {
|
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
|
||||||
#[serde(default = "default_enforcement_mode")]
|
#[serde(rename_all = "kebab-case")]
|
||||||
pub mode: EnforcementMode,
|
pub enum GuardAction {
|
||||||
#[serde(default = "default_parse_error_action")]
|
Deny,
|
||||||
pub on_parse_error: ParseErrorAction,
|
Allow,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct EnforcementConfig {
|
||||||
|
#[serde(default = "default_parse_error_action")]
|
||||||
|
pub on_parse_error: ParseErrorAction,
|
||||||
|
/// A Read of a file on the secret list that fermata cannot mask.
|
||||||
|
#[serde(default = "default_guard_action")]
|
||||||
|
pub on_unparsed_read: GuardAction,
|
||||||
|
/// A Write or Edit that adds a mask to a file.
|
||||||
|
#[serde(default = "default_guard_action")]
|
||||||
|
pub on_mask_write: GuardAction,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
pub struct FileOverride {
|
pub struct FileOverride {
|
||||||
pub path: String,
|
pub path: String,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
@@ -272,12 +285,12 @@ fn default_true() -> bool {
|
|||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_enforcement_mode() -> EnforcementMode {
|
fn default_parse_error_action() -> ParseErrorAction {
|
||||||
EnforcementMode::Permissive
|
ParseErrorAction::Allow
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_parse_error_action() -> ParseErrorAction {
|
fn default_guard_action() -> GuardAction {
|
||||||
ParseErrorAction::MaskEntireFile
|
GuardAction::Deny
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
@@ -336,8 +349,9 @@ impl Default for HeuristicConfig {
|
|||||||
impl Default for EnforcementConfig {
|
impl Default for EnforcementConfig {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
mode: default_enforcement_mode(),
|
|
||||||
on_parse_error: default_parse_error_action(),
|
on_parse_error: default_parse_error_action(),
|
||||||
|
on_unparsed_read: default_guard_action(),
|
||||||
|
on_mask_write: default_guard_action(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -349,6 +363,7 @@ impl Default for EnforcementConfig {
|
|||||||
/// A partially-specified config layer parsed from a single `.botsecrets` file.
|
/// A partially-specified config layer parsed from a single `.botsecrets` file.
|
||||||
/// `Option`-wrapped fields distinguish "absent" from "explicitly set".
|
/// `Option`-wrapped fields distinguish "absent" from "explicitly set".
|
||||||
#[derive(Debug, Clone, Default, Deserialize)]
|
#[derive(Debug, Clone, Default, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
struct PartialSecretsConfig {
|
struct PartialSecretsConfig {
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
files: Option<PartialFilesConfig>,
|
files: Option<PartialFilesConfig>,
|
||||||
@@ -367,22 +382,26 @@ struct PartialSecretsConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default, Deserialize)]
|
#[derive(Debug, Clone, Default, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
struct PartialFilesConfig {
|
struct PartialFilesConfig {
|
||||||
patterns: Option<Vec<String>>,
|
patterns: Option<Vec<String>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default, Deserialize)]
|
#[derive(Debug, Clone, Default, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
struct PartialKeysConfig {
|
struct PartialKeysConfig {
|
||||||
include: Option<Vec<String>>,
|
include: Option<Vec<String>>,
|
||||||
exclude: Option<Vec<String>>,
|
exclude: Option<Vec<String>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default, Deserialize)]
|
#[derive(Debug, Clone, Default, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
struct PartialRedactionConfig {
|
struct PartialRedactionConfig {
|
||||||
style: Option<RedactionStyle>,
|
style: Option<RedactionStyle>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default, Deserialize)]
|
#[derive(Debug, Clone, Default, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
struct PartialHeuristicConfig {
|
struct PartialHeuristicConfig {
|
||||||
enabled: Option<bool>,
|
enabled: Option<bool>,
|
||||||
mode: Option<HeuristicMode>,
|
mode: Option<HeuristicMode>,
|
||||||
@@ -390,9 +409,11 @@ struct PartialHeuristicConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default, Deserialize)]
|
#[derive(Debug, Clone, Default, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
struct PartialEnforcementConfig {
|
struct PartialEnforcementConfig {
|
||||||
mode: Option<EnforcementMode>,
|
|
||||||
on_parse_error: Option<ParseErrorAction>,
|
on_parse_error: Option<ParseErrorAction>,
|
||||||
|
on_unparsed_read: Option<GuardAction>,
|
||||||
|
on_mask_write: Option<GuardAction>,
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
@@ -446,12 +467,15 @@ impl SecretsConfig {
|
|||||||
|
|
||||||
// enforcement
|
// enforcement
|
||||||
if let Some(e) = layer.enforcement {
|
if let Some(e) = layer.enforcement {
|
||||||
if let Some(mode) = e.mode {
|
|
||||||
self.enforcement.mode = mode;
|
|
||||||
}
|
|
||||||
if let Some(action) = e.on_parse_error {
|
if let Some(action) = e.on_parse_error {
|
||||||
self.enforcement.on_parse_error = action;
|
self.enforcement.on_parse_error = action;
|
||||||
}
|
}
|
||||||
|
if let Some(action) = e.on_unparsed_read {
|
||||||
|
self.enforcement.on_unparsed_read = action;
|
||||||
|
}
|
||||||
|
if let Some(action) = e.on_mask_write {
|
||||||
|
self.enforcement.on_mask_write = action;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// file overrides (replace)
|
// file overrides (replace)
|
||||||
@@ -506,6 +530,23 @@ impl SecretsConfig {
|
|||||||
Ok(config)
|
Ok(config)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// [`Self::load`] for a hook that goes on without a broken layer: skips only the
|
||||||
|
/// layers that fail and returns their errors. A typo must not cost the other layers.
|
||||||
|
/// A layer whose bytes cannot be read is no error here, as in
|
||||||
|
/// [`Self::denies_on_failure`]; bytes that are not UTF-8 were read, and are one.
|
||||||
|
pub fn load_or_default(root: &Path) -> (Self, Vec<SecretsConfigError>) {
|
||||||
|
let mut config = Self::default();
|
||||||
|
let mut errors = Vec::new();
|
||||||
|
for file in Self::layer_files(root) {
|
||||||
|
match Self::read_partial(&file) {
|
||||||
|
Ok(layer) => config.merge_layer(layer),
|
||||||
|
Err(SecretsConfigError::Io { source, .. }) if source.kind() != std::io::ErrorKind::InvalidData => {}
|
||||||
|
Err(e) => errors.push(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(config, errors)
|
||||||
|
}
|
||||||
|
|
||||||
/// The layer files that exist for `root`, least specific first.
|
/// The layer files that exist for `root`, least specific first.
|
||||||
fn layer_files(root: &Path) -> Vec<PathBuf> {
|
fn layer_files(root: &Path) -> Vec<PathBuf> {
|
||||||
let mut files = Vec::new();
|
let mut files = Vec::new();
|
||||||
|
|||||||
@@ -47,6 +47,8 @@ impl ManifestError {
|
|||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct Manifest {
|
pub struct Manifest {
|
||||||
entries: Vec<SecretEntry>,
|
entries: Vec<SecretEntry>,
|
||||||
|
/// Secret files left out because they cannot be parsed, editor files aside.
|
||||||
|
skipped: Vec<PathBuf>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Minimum secret value length to keep. Anything shorter risks false-positive
|
/// Minimum secret value length to keep. Anything shorter risks false-positive
|
||||||
@@ -157,6 +159,7 @@ impl Manifest {
|
|||||||
/// `root`.
|
/// `root`.
|
||||||
pub fn build(config: &SecretsConfig, root: &Path) -> Result<Self, ManifestError> {
|
pub fn build(config: &SecretsConfig, root: &Path) -> Result<Self, ManifestError> {
|
||||||
let mut entries = Vec::new();
|
let mut entries = Vec::new();
|
||||||
|
let mut skipped = Vec::new();
|
||||||
|
|
||||||
// 1. Discover files matching `config.files.patterns`.
|
// 1. Discover files matching `config.files.patterns`.
|
||||||
let discovered = discover_files(&config.files.patterns, root)?;
|
let discovered = discover_files(&config.files.patterns, root)?;
|
||||||
@@ -173,20 +176,11 @@ impl Manifest {
|
|||||||
path.display(),
|
path.display(),
|
||||||
e
|
e
|
||||||
);
|
);
|
||||||
|
skipped.push(path.clone());
|
||||||
}
|
}
|
||||||
ParseErrorAction::Deny => {
|
ParseErrorAction::Deny => {
|
||||||
return Err(e.into());
|
return Err(e.into());
|
||||||
}
|
}
|
||||||
ParseErrorAction::MaskEntireFile => {
|
|
||||||
// We cannot extract individual secrets — the redactor
|
|
||||||
// may choose to mask the entire file content if it
|
|
||||||
// appears in output. For now we log and continue.
|
|
||||||
eprintln!(
|
|
||||||
"fermata: warning: cannot parse {}: {}",
|
|
||||||
path.display(),
|
|
||||||
e
|
|
||||||
);
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -224,12 +218,13 @@ impl Manifest {
|
|||||||
override_path.display(),
|
override_path.display(),
|
||||||
e
|
e
|
||||||
);
|
);
|
||||||
|
skipped.push(override_path);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5. Every spelling, deduplicated, longest first.
|
// 5. Every spelling, deduplicated, longest first.
|
||||||
Ok(Self { entries: finish(entries) })
|
Ok(Self { entries: finish(entries), skipped })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Build a manifest from a pre-built list of secret entries.
|
/// Build a manifest from a pre-built list of secret entries.
|
||||||
@@ -243,13 +238,14 @@ impl Manifest {
|
|||||||
/// Useful for testing and for library consumers that obtain secrets
|
/// Useful for testing and for library consumers that obtain secrets
|
||||||
/// from sources other than filesystem discovery.
|
/// from sources other than filesystem discovery.
|
||||||
pub fn from_entries(entries: Vec<SecretEntry>) -> Self {
|
pub fn from_entries(entries: Vec<SecretEntry>) -> Self {
|
||||||
Self { entries: finish(entries) }
|
Self { entries: finish(entries), skipped: Vec::new() }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Build an empty manifest (no secrets known).
|
/// Build an empty manifest (no secrets known).
|
||||||
pub fn empty() -> Self {
|
pub fn empty() -> Self {
|
||||||
Self {
|
Self {
|
||||||
entries: Vec::new(),
|
entries: Vec::new(),
|
||||||
|
skipped: Vec::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -258,6 +254,11 @@ impl Manifest {
|
|||||||
&self.entries
|
&self.entries
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Secret files whose values are not in this manifest, because they cannot be parsed.
|
||||||
|
pub fn skipped(&self) -> &[PathBuf] {
|
||||||
|
&self.skipped
|
||||||
|
}
|
||||||
|
|
||||||
/// Returns `true` if the manifest contains no secrets.
|
/// Returns `true` if the manifest contains no secrets.
|
||||||
pub fn is_empty(&self) -> bool {
|
pub fn is_empty(&self) -> bool {
|
||||||
self.entries.is_empty()
|
self.entries.is_empty()
|
||||||
|
|||||||
@@ -102,6 +102,10 @@ impl HarnessAdapter for ClaudeAdapter {
|
|||||||
text
|
text
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn shows_text(&self, payload: &PostToolUsePayload) -> bool {
|
||||||
|
is_mcp(payload) || matches!(payload.tool_name.as_str(), "Read" | "Bash" | "PowerShell" | "Grep")
|
||||||
|
}
|
||||||
|
|
||||||
fn render_post_tool_use(
|
fn render_post_tool_use(
|
||||||
&self,
|
&self,
|
||||||
_payload: &PostToolUsePayload,
|
_payload: &PostToolUsePayload,
|
||||||
|
|||||||
@@ -122,6 +122,10 @@ pub trait HarnessAdapter {
|
|||||||
/// The strings of `output` that are text, for the heuristic scanner.
|
/// The strings of `output` that are text, for the heuristic scanner.
|
||||||
fn output_text<'a>(&self, payload: &PostToolUsePayload, output: &'a serde_json::Value) -> Vec<&'a str>;
|
fn output_text<'a>(&self, payload: &PostToolUsePayload, output: &'a serde_json::Value) -> Vec<&'a str>;
|
||||||
|
|
||||||
|
/// Whether this output shows file or command text, so that a note about what is not
|
||||||
|
/// masked belongs beside it. A session of many Writes must not pay for it each time.
|
||||||
|
fn shows_text(&self, payload: &PostToolUsePayload) -> bool;
|
||||||
|
|
||||||
/// Render a PostToolUse response: the replacement output if there is one, and
|
/// Render a PostToolUse response: the replacement output if there is one, and
|
||||||
/// a note to show beside the result. Neither means the original stands.
|
/// a note to show beside the result. Neither means the original stands.
|
||||||
fn render_post_tool_use(
|
fn render_post_tool_use(
|
||||||
|
|||||||
@@ -50,3 +50,22 @@ fn check_emits_json_with_flag() {
|
|||||||
let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
|
let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
|
||||||
assert_eq!(v["kind"], "deny");
|
assert_eq!(v["kind"], "deny");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn check_exits_2_and_names_the_line_of_a_broken_config() {
|
||||||
|
for (config, line) in [("[polcy]\nread = 1\n", 1), ("[files]\n[polcy]\nread = 1\n", 2), ("[enforcement]\nmode = \"strict\"\n", 2)] {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let home = tempfile::tempdir().unwrap();
|
||||||
|
fs::write(tmp.path().join(".botsecrets"), config).unwrap();
|
||||||
|
let target = tmp.path().join("a.txt");
|
||||||
|
fs::write(&target, "").unwrap();
|
||||||
|
|
||||||
|
Command::cargo_bin("fermata")
|
||||||
|
.unwrap()
|
||||||
|
.args(["check", "--op", "read", target.to_str().unwrap()])
|
||||||
|
.env("HOME", home.path())
|
||||||
|
.assert()
|
||||||
|
.code(2)
|
||||||
|
.stderr(predicate::str::contains(".botsecrets").and(predicate::str::contains(format!("line {line}"))));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -111,10 +111,12 @@ fn a_file_override_that_cannot_be_parsed_withholds_the_output_under_deny() {
|
|||||||
/// and shape against its schema: `tests/cli_hook_redaction.rs`.
|
/// and shape against its schema: `tests/cli_hook_redaction.rs`.
|
||||||
#[test]
|
#[test]
|
||||||
fn an_object_response_is_withheld_in_its_own_shape_under_deny() {
|
fn an_object_response_is_withheld_in_its_own_shape_under_deny() {
|
||||||
// The control: without `deny` the output goes on, with this file's values unknown.
|
// The control: without `deny` the output goes on, with this file's values unknown,
|
||||||
|
// and a note says which file.
|
||||||
let p = project(&[("secrets.toml", BROKEN_TOML)]);
|
let p = project(&[("secrets.toml", BROKEN_TOML)]);
|
||||||
let (out, stderr) = p.post(json!({"stdout": RESPONSE}));
|
let (out, stderr) = p.post(json!({"stdout": RESPONSE}));
|
||||||
assert_eq!(out, json!({}));
|
assert!(out["hookSpecificOutput"].get("updatedToolOutput").is_none(), "{out}");
|
||||||
|
assert!(note(&out).contains("secrets.toml") && !note(&out).contains(VALUE), "{out}");
|
||||||
assert!(stderr.contains("secrets.toml"), "{stderr}");
|
assert!(stderr.contains("secrets.toml"), "{stderr}");
|
||||||
|
|
||||||
let p = project(&[(".botsecrets", DENY), ("secrets.toml", BROKEN_TOML)]);
|
let p = project(&[(".botsecrets", DENY), ("secrets.toml", BROKEN_TOML)]);
|
||||||
@@ -210,19 +212,145 @@ fn a_broken_config_with_a_multi_line_string_deny_withholds_the_output() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A broken config that does not say `deny` stays open, as it always has. Only the
|
/// A broken config that does not say `deny` stays open: the default list still masks,
|
||||||
/// message changes.
|
/// and a note names the file and the line.
|
||||||
#[test]
|
#[test]
|
||||||
fn a_broken_config_without_deny_stays_open_and_quotes_nothing() {
|
fn a_broken_config_without_deny_stays_open_and_quotes_nothing() {
|
||||||
for broken in [BROKEN_TOML.to_string(), format!("# on_parse_error = \"deny\"\n{BROKEN_TOML}")] {
|
for broken in [BROKEN_TOML.to_string(), format!("# on_parse_error = \"deny\"\n{BROKEN_TOML}")] {
|
||||||
let p = project(&[(".botsecrets", &broken)]);
|
let p = project(&[(".botsecrets", &broken), (".env", &format!("API_TOKEN={VALUE}\n"))]);
|
||||||
let (out, stderr) = p.post(json!(RESPONSE));
|
let (out, stderr) = p.post(json!(RESPONSE));
|
||||||
assert_eq!(out, json!({}));
|
let text = out["hookSpecificOutput"]["updatedToolOutput"].as_str().unwrap_or_else(|| panic!("not masked: {out}"));
|
||||||
|
assert!(text.starts_with("output of the tool") && !out.to_string().contains(VALUE), "{out}");
|
||||||
|
assert!(note(&out).contains(".botsecrets") && note(&out).contains("line "), "{out}");
|
||||||
assert!(stderr.contains(".botsecrets") && stderr.contains("line "), "{stderr}");
|
assert!(stderr.contains(".botsecrets") && stderr.contains("line "), "{stderr}");
|
||||||
assert_silent(&p.pre_bash());
|
assert_silent(&p.pre_bash());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// A layer that cannot be loaded costs only that layer
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
const TYPO: &str = "[polcy]\nread = 1\n";
|
||||||
|
const GLOBAL_VALUE: &str = "fake-value-of-the-global-key";
|
||||||
|
const LOCAL_VALUE: &str = "fake-value-of-the-local-key";
|
||||||
|
|
||||||
|
fn note(out: &Value) -> &str {
|
||||||
|
out["hookSpecificOutput"]["additionalContext"].as_str().unwrap_or_else(|| panic!("no note: {out}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tool_output(p: &Project, tool: &str, text: &str) -> Value {
|
||||||
|
let (input, response) = match tool {
|
||||||
|
"Read" => (
|
||||||
|
json!({"file_path": "/p/f"}),
|
||||||
|
json!({"type": "text", "file": {"filePath": "/p/f", "content": text, "numLines": 1, "startLine": 1, "totalLines": 1}}),
|
||||||
|
),
|
||||||
|
"Write" => (
|
||||||
|
json!({"file_path": "/p/f", "content": text}),
|
||||||
|
json!({"type": "create", "filePath": "/p/f", "content": text, "structuredPatch": [], "originalFile": null}),
|
||||||
|
),
|
||||||
|
"Grep" => (json!({"pattern": "x"}), json!({"mode": "content", "numFiles": 1, "filenames": [], "content": text, "numLines": 1})),
|
||||||
|
"Bash" | "PowerShell" => (json!({"command": "x"}), json!({"stdout": text, "stderr": "", "interrupted": false})),
|
||||||
|
_ => (json!({}), json!([{"type": "text", "text": text}])),
|
||||||
|
};
|
||||||
|
p.hook("post-tool-use", json!({"tool_name": tool, "tool_input": input, "tool_response": response})).0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Output that shows file or command text gets the note, and only that (A-11).
|
||||||
|
const TEXT_TOOLS: &[&str] = &["Read", "Bash", "PowerShell", "Grep", "mcp__srv__tool"];
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_typo_in_botsecrets_keeps_the_other_layers_and_the_default_list() {
|
||||||
|
let env = format!("API_TOKEN={VALUE}\nMY_GLOBAL={GLOBAL_VALUE}\nMY_LOCAL={LOCAL_VALUE}\n");
|
||||||
|
let p = project(&[(".botsecrets", TYPO), (".botsecrets.local", "[keys]\ninclude = [\"MY_LOCAL\"]\n"), (".env", &env)]);
|
||||||
|
let global = p.home.path().join(".config/fermata");
|
||||||
|
fs::create_dir_all(&global).unwrap();
|
||||||
|
fs::write(global.join(".botsecrets"), "[keys]\ninclude = [\"MY_GLOBAL\"]\n").unwrap();
|
||||||
|
|
||||||
|
let text = format!("{VALUE} {GLOBAL_VALUE} {LOCAL_VALUE}");
|
||||||
|
for tool in TEXT_TOOLS {
|
||||||
|
let out = tool_output(&p, tool, &text);
|
||||||
|
for value in [VALUE, GLOBAL_VALUE, LOCAL_VALUE] {
|
||||||
|
assert!(!out.to_string().contains(value), "{tool}: {out}");
|
||||||
|
}
|
||||||
|
let note = note(&out);
|
||||||
|
assert!(note.contains(".botsecrets") && note.contains("line 1") && note.contains("rules are off"), "{tool}: {note}");
|
||||||
|
assert!(!note.contains("polcy"), "{tool}: {note}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// A Write costs the session no line for it, masked or not.
|
||||||
|
assert_eq!(tool_output(&p, "Write", "clean"), json!({}));
|
||||||
|
let out = tool_output(&p, "Write", VALUE);
|
||||||
|
assert!(!out.to_string().contains(VALUE), "{out}");
|
||||||
|
assert!(out["hookSpecificOutput"].get("additionalContext").is_none(), "{out}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A broken user-global layer: the project's own rules stand.
|
||||||
|
#[test]
|
||||||
|
fn a_typo_in_the_user_global_layer_keeps_the_project_layer() {
|
||||||
|
let p = project(&[(".botsecrets", "[keys]\ninclude = [\"MY_LOCAL\"]\n"), (".env", &format!("MY_LOCAL={LOCAL_VALUE}\n"))]);
|
||||||
|
let global = p.home.path().join(".config/fermata");
|
||||||
|
fs::create_dir_all(&global).unwrap();
|
||||||
|
fs::write(global.join(".botsecrets"), TYPO).unwrap();
|
||||||
|
let out = tool_output(&p, "Read", LOCAL_VALUE);
|
||||||
|
assert!(!out.to_string().contains(LOCAL_VALUE), "{out}");
|
||||||
|
assert!(note(&out).contains("fermata/.botsecrets"), "{out}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The gate keeps the rules of the layers that load, and says nothing of the others.
|
||||||
|
#[test]
|
||||||
|
fn the_gate_keeps_the_rules_of_the_layers_that_load() {
|
||||||
|
let local = "[policy.read]\npatterns = [\"blocked.txt\"]\n";
|
||||||
|
let p = project(&[(".botsecrets", TYPO), (".botsecrets.local", local), ("blocked.txt", ""), ("safe.txt", "")]);
|
||||||
|
assert!(deny_reason(&p.pre_read("blocked.txt")).contains("blocked.txt"));
|
||||||
|
assert_silent(&p.pre_read("safe.txt"));
|
||||||
|
assert_silent(&p.pre_bash());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_layer_that_is_not_utf8_is_a_broken_layer() {
|
||||||
|
let p = project(&[(".env", &format!("API_TOKEN={VALUE}\n"))]);
|
||||||
|
fs::write(p.dir.path().join(".botsecrets"), [0xff, 0xfe, 0x00]).unwrap();
|
||||||
|
let out = tool_output(&p, "Read", VALUE);
|
||||||
|
assert!(!out.to_string().contains(VALUE), "{out}");
|
||||||
|
assert!(note(&out).contains(".botsecrets") && note(&out).contains("rules are off"), "{out}");
|
||||||
|
assert_eq!(tool_output(&p, "Write", "clean"), json!({}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An unknown field under `deny` is the broken config it always was.
|
||||||
|
#[test]
|
||||||
|
fn an_unknown_field_refuses_under_deny() {
|
||||||
|
for config in [format!("{DENY}{TYPO}"), "[enforcement]\nmode = \"strict\"\non_parse_error = \"deny\"\n".to_string()] {
|
||||||
|
let p = project(&[(".botsecrets", &config), ("safe.txt", "")]);
|
||||||
|
assert!(refusal(&p.post(json!(RESPONSE)).0).contains(".botsecrets"), "{config}");
|
||||||
|
assert!(deny_reason(&p.pre_read("safe.txt")).contains(".botsecrets"), "{config}");
|
||||||
|
assert!(deny_reason(&p.pre_bash()).contains(".botsecrets"), "{config}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `skipped()`: a secret file that cannot be parsed, named beside text output only.
|
||||||
|
#[test]
|
||||||
|
fn a_file_that_cannot_be_parsed_is_named_beside_text_output_only() {
|
||||||
|
let config = "[[file]]\npath = \"conf.toml\"\n";
|
||||||
|
let p = project(&[(".botsecrets", config), ("secrets.toml", BROKEN_TOML), ("conf.toml", BROKEN_TOML), (".env", "API_TOKEN=fake-value-that-still-masks\n")]);
|
||||||
|
for tool in TEXT_TOOLS {
|
||||||
|
let out = tool_output(&p, tool, "fake-value-that-still-masks");
|
||||||
|
assert!(!out.to_string().contains("fake-value-that-still-masks"), "{tool}: {out}");
|
||||||
|
let note = note(&out);
|
||||||
|
assert!(note.contains("secrets.toml") && note.contains("conf.toml"), "{tool}: {note}");
|
||||||
|
assert!(!note.contains(VALUE), "{tool}: {note}");
|
||||||
|
}
|
||||||
|
assert_eq!(tool_output(&p, "Write", "clean"), json!({}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An editor's file was never a secret file that failed: no note.
|
||||||
|
#[test]
|
||||||
|
fn an_editors_swap_file_gets_no_note() {
|
||||||
|
let p = project(&[]);
|
||||||
|
fs::write(p.dir.path().join(".env.swp"), b"b0VIM \xff\xfe\x00\x01").unwrap();
|
||||||
|
assert_eq!(tool_output(&p, "Read", "clean"), json!({}));
|
||||||
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// PostToolUse, other settings
|
// PostToolUse, other settings
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
@@ -230,12 +358,14 @@ fn a_broken_config_without_deny_stays_open_and_quotes_nothing() {
|
|||||||
/// `hook` itself asserts that stderr quotes nothing.
|
/// `hook` itself asserts that stderr quotes nothing.
|
||||||
#[test]
|
#[test]
|
||||||
fn other_settings_stay_open_and_quote_nothing() {
|
fn other_settings_stay_open_and_quote_nothing() {
|
||||||
for setting in ["", "[enforcement]\non_parse_error = \"allow\"\n", "[enforcement]\non_parse_error = \"mask-entire-file\"\n"] {
|
for setting in ["", "[enforcement]\non_parse_error = \"allow\"\n"] {
|
||||||
// A discovered file, and a `[[file]]` override.
|
// A discovered file, and a `[[file]]` override.
|
||||||
let config = format!("{setting}[[file]]\npath = \"conf.toml\"\n");
|
let config = format!("{setting}[[file]]\npath = \"conf.toml\"\n");
|
||||||
let p = project(&[(".botsecrets", &config), ("secrets.toml", BROKEN_TOML), ("conf.toml", BROKEN_TOML)]);
|
let p = project(&[(".botsecrets", &config), ("secrets.toml", BROKEN_TOML), ("conf.toml", BROKEN_TOML)]);
|
||||||
let (out, stderr) = p.post(json!("no secrets here"));
|
let (out, stderr) = p.post(json!("no secrets here"));
|
||||||
assert_eq!(out, json!({}), "setting {setting:?}");
|
assert!(out["hookSpecificOutput"].get("updatedToolOutput").is_none(), "setting {setting:?}: {out}");
|
||||||
|
assert!(note(&out).contains("secrets.toml") && note(&out).contains("conf.toml"), "setting {setting:?}: {out}");
|
||||||
|
assert!(!out.to_string().contains(VALUE), "setting {setting:?}: {out}");
|
||||||
assert!(stderr.contains("secrets.toml") && stderr.contains("conf.toml"), "{stderr}");
|
assert!(stderr.contains("secrets.toml") && stderr.contains("conf.toml"), "{stderr}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use dirigent_fermata::core::secrets::config::{
|
use dirigent_fermata::core::secrets::config::{
|
||||||
EnforcementMode, HeuristicMode, ParseErrorAction, RedactionStyle, SecretsConfig,
|
GuardAction, HeuristicMode, ParseErrorAction, RedactionStyle, SecretsConfig,
|
||||||
BUILTIN_KEY_PATTERNS,
|
BUILTIN_KEY_PATTERNS,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -15,7 +15,9 @@ patterns = [".env", ".env.*"]
|
|||||||
assert_eq!(cfg.files.patterns, vec![".env", ".env.*"]);
|
assert_eq!(cfg.files.patterns, vec![".env", ".env.*"]);
|
||||||
// Other sections use defaults
|
// Other sections use defaults
|
||||||
assert_eq!(cfg.redaction.style, RedactionStyle::Masked);
|
assert_eq!(cfg.redaction.style, RedactionStyle::Masked);
|
||||||
assert_eq!(cfg.enforcement.mode, EnforcementMode::Permissive);
|
assert_eq!(cfg.enforcement.on_parse_error, ParseErrorAction::Allow);
|
||||||
|
assert_eq!(cfg.enforcement.on_unparsed_read, GuardAction::Deny);
|
||||||
|
assert_eq!(cfg.enforcement.on_mask_write, GuardAction::Deny);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -38,8 +40,9 @@ mode = "report"
|
|||||||
patterns = ['AKIA[A-Z2-7]{16}']
|
patterns = ['AKIA[A-Z2-7]{16}']
|
||||||
|
|
||||||
[enforcement]
|
[enforcement]
|
||||||
mode = "strict"
|
|
||||||
on_parse_error = "deny"
|
on_parse_error = "deny"
|
||||||
|
on_unparsed_read = "allow"
|
||||||
|
on_mask_write = "allow"
|
||||||
|
|
||||||
[[file]]
|
[[file]]
|
||||||
path = "settings.py"
|
path = "settings.py"
|
||||||
@@ -56,8 +59,9 @@ keys = ["SECRET_KEY", "DATABASES.*.PASSWORD"]
|
|||||||
assert!(!cfg.heuristic.enabled);
|
assert!(!cfg.heuristic.enabled);
|
||||||
assert_eq!(cfg.heuristic.mode, HeuristicMode::Report);
|
assert_eq!(cfg.heuristic.mode, HeuristicMode::Report);
|
||||||
assert_eq!(cfg.heuristic.patterns, vec!["AKIA[A-Z2-7]{16}"]);
|
assert_eq!(cfg.heuristic.patterns, vec!["AKIA[A-Z2-7]{16}"]);
|
||||||
assert_eq!(cfg.enforcement.mode, EnforcementMode::Strict);
|
|
||||||
assert_eq!(cfg.enforcement.on_parse_error, ParseErrorAction::Deny);
|
assert_eq!(cfg.enforcement.on_parse_error, ParseErrorAction::Deny);
|
||||||
|
assert_eq!(cfg.enforcement.on_unparsed_read, GuardAction::Allow);
|
||||||
|
assert_eq!(cfg.enforcement.on_mask_write, GuardAction::Allow);
|
||||||
assert_eq!(cfg.file_overrides.len(), 1);
|
assert_eq!(cfg.file_overrides.len(), 1);
|
||||||
assert_eq!(cfg.file_overrides[0].path, "settings.py");
|
assert_eq!(cfg.file_overrides[0].path, "settings.py");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -78,11 +82,9 @@ fn empty_toml_returns_defaults() {
|
|||||||
assert_eq!(cfg.redaction.style, RedactionStyle::Masked);
|
assert_eq!(cfg.redaction.style, RedactionStyle::Masked);
|
||||||
assert!(cfg.heuristic.enabled);
|
assert!(cfg.heuristic.enabled);
|
||||||
assert_eq!(cfg.heuristic.mode, HeuristicMode::Enforce);
|
assert_eq!(cfg.heuristic.mode, HeuristicMode::Enforce);
|
||||||
assert_eq!(cfg.enforcement.mode, EnforcementMode::Permissive);
|
assert_eq!(cfg.enforcement.on_parse_error, ParseErrorAction::Allow);
|
||||||
assert_eq!(
|
assert_eq!(cfg.enforcement.on_unparsed_read, GuardAction::Deny);
|
||||||
cfg.enforcement.on_parse_error,
|
assert_eq!(cfg.enforcement.on_mask_write, GuardAction::Deny);
|
||||||
ParseErrorAction::MaskEntireFile
|
|
||||||
);
|
|
||||||
assert!(cfg.file_overrides.is_empty());
|
assert!(cfg.file_overrides.is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -245,7 +247,7 @@ fn load_local_overrides_project() {
|
|||||||
[redaction]
|
[redaction]
|
||||||
style = "named"
|
style = "named"
|
||||||
[enforcement]
|
[enforcement]
|
||||||
mode = "strict"
|
on_parse_error = "deny"
|
||||||
"#,
|
"#,
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -262,7 +264,7 @@ style = "absent"
|
|||||||
// .local overrides .botsecrets for redaction style
|
// .local overrides .botsecrets for redaction style
|
||||||
assert_eq!(cfg.redaction.style, RedactionStyle::Absent);
|
assert_eq!(cfg.redaction.style, RedactionStyle::Absent);
|
||||||
// enforcement from .botsecrets is preserved (not in .local)
|
// enforcement from .botsecrets is preserved (not in .local)
|
||||||
assert_eq!(cfg.enforcement.mode, EnforcementMode::Strict);
|
assert_eq!(cfg.enforcement.on_parse_error, ParseErrorAction::Deny);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -337,15 +339,16 @@ fn all_redaction_styles_parse() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn all_enforcement_modes_parse() {
|
fn all_enforcement_settings_parse() {
|
||||||
for (input, expected) in [
|
for (input, parse_error, guard) in [
|
||||||
("strict", EnforcementMode::Strict),
|
("allow", ParseErrorAction::Allow, GuardAction::Allow),
|
||||||
("permissive", EnforcementMode::Permissive),
|
("deny", ParseErrorAction::Deny, GuardAction::Deny),
|
||||||
("audit", EnforcementMode::Audit),
|
|
||||||
] {
|
] {
|
||||||
let toml_str = format!("[enforcement]\nmode = \"{input}\"");
|
let toml_str = format!("[enforcement]\non_parse_error = \"{input}\"\non_unparsed_read = \"{input}\"\non_mask_write = \"{input}\"");
|
||||||
let cfg = SecretsConfig::from_toml(&toml_str).unwrap();
|
let cfg = SecretsConfig::from_toml(&toml_str).unwrap();
|
||||||
assert_eq!(cfg.enforcement.mode, expected, "failed for: {input}");
|
assert_eq!(cfg.enforcement.on_parse_error, parse_error, "failed for: {input}");
|
||||||
|
assert_eq!(cfg.enforcement.on_unparsed_read, guard, "failed for: {input}");
|
||||||
|
assert_eq!(cfg.enforcement.on_mask_write, guard, "failed for: {input}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -371,8 +374,8 @@ patterns = [".env"]
|
|||||||
[redaction]
|
[redaction]
|
||||||
style = "typed"
|
style = "typed"
|
||||||
[enforcement]
|
[enforcement]
|
||||||
mode = "audit"
|
|
||||||
on_parse_error = "allow"
|
on_parse_error = "allow"
|
||||||
|
on_unparsed_read = "allow"
|
||||||
"#,
|
"#,
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -380,13 +383,72 @@ on_parse_error = "allow"
|
|||||||
let serialized = toml::to_string(&cfg).unwrap();
|
let serialized = toml::to_string(&cfg).unwrap();
|
||||||
let deserialized: SecretsConfig = toml::from_str(&serialized).unwrap();
|
let deserialized: SecretsConfig = toml::from_str(&serialized).unwrap();
|
||||||
assert_eq!(deserialized.redaction.style, RedactionStyle::Typed);
|
assert_eq!(deserialized.redaction.style, RedactionStyle::Typed);
|
||||||
assert_eq!(deserialized.enforcement.mode, EnforcementMode::Audit);
|
assert_eq!(deserialized.enforcement.on_unparsed_read, GuardAction::Allow);
|
||||||
|
assert_eq!(deserialized.enforcement.on_mask_write, GuardAction::Deny);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
deserialized.enforcement.on_parse_error,
|
deserialized.enforcement.on_parse_error,
|
||||||
ParseErrorAction::Allow
|
ParseErrorAction::Allow
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Every section refuses a field it does not know, with the field's line.
|
||||||
|
const UNKNOWN_FIELDS: &[(&str, usize)] = &[
|
||||||
|
("nonsense = 1\n", 1),
|
||||||
|
("[polcy]\nread = 1\n", 1),
|
||||||
|
("[files]\npattern = []\n", 2),
|
||||||
|
("[keys]\nexclude = []\ninclud = []\n", 3),
|
||||||
|
("[redaction]\nstile = \"named\"\n", 2),
|
||||||
|
("[heuristic]\nenable = false\n", 2),
|
||||||
|
("[enforcement]\nmode = \"strict\"\n", 2),
|
||||||
|
("[enforcement]\non_parse_error = \"mask-entire-file\"\n", 2),
|
||||||
|
("[enforcement]\non_unparsed_read = \"ask\"\n", 2),
|
||||||
|
("[enforcement]\non_mask_write = \"ask\"\n", 2),
|
||||||
|
("[[file]]\npath = \"x\"\nkey = []\n", 3),
|
||||||
|
("[policy]\nreads = []\n", 2),
|
||||||
|
("[policy.read]\ndeny = [\"x\"]\n", 2),
|
||||||
|
("[policy.write]\ndeny = [\"x\"]\n", 2),
|
||||||
|
("[policy.bash]\nallow = [\"x\"]\n", 2),
|
||||||
|
];
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_unknown_field_fails_load_with_its_line() {
|
||||||
|
for (config, line) in UNKNOWN_FIELDS {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
std::fs::write(dir.path().join(".botsecrets"), config).unwrap();
|
||||||
|
let text = SecretsConfig::load(dir.path()).err().unwrap_or_else(|| panic!("loaded: {config}")).to_string();
|
||||||
|
assert!(text.ends_with(&format!("invalid TOML at line {line}")) && text.contains(".botsecrets"), "{config}: {text}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_unknown_field_fails_from_toml() {
|
||||||
|
for (config, _) in UNKNOWN_FIELDS {
|
||||||
|
assert!(SecretsConfig::from_toml(config).is_err(), "{config}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A broken layer costs that layer. A layer whose bytes cannot be read is no error, one
|
||||||
|
/// that is not UTF-8 is: `cli_hook_fail_closed.rs` has the first, in a home of its own.
|
||||||
|
#[test]
|
||||||
|
fn load_or_default_skips_only_the_layer_that_fails() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
std::fs::write(dir.path().join(".botsecrets"), "[polcy]\nread = 1\n").unwrap();
|
||||||
|
std::fs::write(dir.path().join(".botsecrets.local"), "[keys]\ninclude = [\"FROM_LOCAL\"]\n").unwrap();
|
||||||
|
assert!(SecretsConfig::load(dir.path()).is_err(), "`load` stays strict");
|
||||||
|
let (cfg, errors) = SecretsConfig::load_or_default(dir.path());
|
||||||
|
assert_eq!(cfg.keys.include, vec!["FROM_LOCAL"]);
|
||||||
|
assert_eq!(cfg.files.patterns, SecretsConfig::default().files.patterns);
|
||||||
|
assert_eq!(errors.len(), 1);
|
||||||
|
assert_eq!(errors[0].path(), dir.path().join(".botsecrets"));
|
||||||
|
assert!(errors[0].to_string().ends_with("invalid TOML at line 1"), "{}", errors[0]);
|
||||||
|
|
||||||
|
std::fs::write(dir.path().join(".botsecrets"), [0xff, 0xfe, 0x00]).unwrap();
|
||||||
|
let (cfg, errors) = SecretsConfig::load_or_default(dir.path());
|
||||||
|
assert_eq!(cfg.keys.include, vec!["FROM_LOCAL"]);
|
||||||
|
assert_eq!(errors.len(), 1);
|
||||||
|
assert_eq!(errors[0].path(), dir.path().join(".botsecrets"));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_broken_layer_names_its_line_and_never_quotes_it() {
|
fn a_broken_layer_names_its_line_and_never_quotes_it() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
|||||||
Reference in New Issue
Block a user