Files
pruefwerk/compliance-core/src/config.rs
T
sharang 6611c5b691
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Successful in 1m8s
CI / Deploy MCP (push) Successful in 3m52s
CI / Deploy Dashboard (push) Successful in 5m38s
CI / Deploy Agent (push) Successful in 7m6s
feat(security): seal tenant credentials at rest, never return them (#260) (#302)
2026-09-21 16:28:54 +00:00

506 lines
20 KiB
Rust

use secrecy::SecretString;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug)]
pub struct AgentConfig {
pub mongodb_uri: String,
pub mongodb_database: String,
pub litellm_url: String,
pub litellm_api_key: SecretString,
pub litellm_model: String,
pub litellm_embed_model: String,
pub github_token: Option<SecretString>,
pub github_webhook_secret: Option<SecretString>,
pub gitlab_url: Option<String>,
pub gitlab_token: Option<SecretString>,
pub gitlab_webhook_secret: Option<SecretString>,
pub jira_url: Option<String>,
pub jira_email: Option<String>,
pub jira_api_token: Option<SecretString>,
pub jira_project_key: Option<String>,
pub searxng_url: Option<String>,
pub nvd_api_key: Option<SecretString>,
pub agent_port: u16,
/// Port of the separate webhook listener (`WEBHOOK_PORT`, default 3002).
pub webhook_port: u16,
/// Most scans (and PR reviews) running at once across all tenants and
/// targets (`SCAN_CONCURRENCY`, default 2). Each is a clone plus semgrep and
/// syft, so this is what keeps a burst from exhausting the node's memory.
pub scan_concurrency: usize,
pub scan_schedule: String,
pub cve_monitor_schedule: String,
pub git_clone_base_path: String,
/// Base directory for content-addressed artifact blobs and per-run working
/// dirs (`<base>/blobs/<sha[0:2]>/<sha>`, `<base>/work/<target>/<artifact>/`).
pub artifact_store_base_path: String,
pub keycloak_url: Option<String>,
pub keycloak_realm: Option<String>,
pub keycloak_admin_username: Option<String>,
pub keycloak_admin_password: Option<SecretString>,
// Pentest defaults
pub pentest_verification_email: Option<String>,
pub pentest_imap_host: Option<String>,
pub pentest_imap_port: Option<u16>,
/// Use implicit TLS (IMAPS, port 993) instead of plain IMAP.
pub pentest_imap_tls: bool,
pub pentest_imap_username: Option<String>,
pub pentest_imap_password: Option<SecretString>,
/// Static bearer for the cross-tenant admin endpoints under
/// `/api/v1/admin/*`. When `None`, those endpoints are not
/// mounted at all (defense-in-depth: ops endpoints never reach
/// any auth path if no operator has explicitly opted in).
pub admin_api_token: Option<SecretString>,
/// Hex-encoded 32-byte AES-256-GCM key that seals tenant credentials at
/// rest (`SECRETS_ENCRYPTION_KEY`). Without it the agent refuses to store
/// a credential instead of writing it in plain text.
pub secrets_encryption_key: Option<SecretString>,
/// Live tenant-registry URL the scheduler consults for the list
/// of tenants to iterate. When `None` or unreachable, scheduler
/// falls back to `SCHEDULER_TENANT_IDS` env (M7.2-C).
pub tenant_registry_url: Option<String>,
/// Ephemeral soft-PLC provisioning for dynamic PLC testing (#183). Off by
/// default: it needs Docker access in the agent's runtime, which is a
/// deployment opt-in.
pub plc_runtime: PlcRuntimeConfig,
/// Static bearer for the Werkbank runner endpoints
/// (`/api/v1/werkbank/jobs/*`). Machine auth for runners leasing/completing
/// jobs — NOT a Keycloak JWT, since a runner acts across tenants. When
/// `None`, those endpoints are not mounted at all.
pub werkbank_runner_token: Option<SecretString>,
/// Source for the OSCAL control catalog pulled from breakpilot-compliance
/// (drives the [`crate::traits::ControlsProvider`]). Disabled when
/// `base_url` is `None`.
pub breakpilot: BreakpilotConfig,
// ── Platform integration (PRODUCT_INTEGRATION_SPEC 2.0, M-MIG-6) ──
/// Catalog key of this product in the tenant-registry (`pruefwerk`).
pub product_key: String,
/// Expected `aud` of user JWTs (the realm's `<product>-audience` scope).
/// `None` skips audience validation (dev only; logged).
pub keycloak_audience: Option<String>,
/// Service-account client used for registry calls (client_credentials
/// against `keycloak_url`/`keycloak_realm`). Optional in dev.
pub tenant_registry_client_id: Option<String>,
pub tenant_registry_client_secret: Option<SecretString>,
/// Browser origins allowed by CORS. Empty ⇒ permissive (dev only; logged).
pub cors_allowed_origins: Vec<String>,
/// Keycloak clients (JWT `azp`) allowed to call `/api/v1/platform/*`.
pub platform_allowed_clients: Vec<String>,
/// Deployment feature flags (`PW_FEATURES`, comma list). Exposed on the
/// public `/api/v1/platform/version` handshake so the dashboard reads the
/// same set the agent enforces.
pub features: Features,
/// Which environment this process serves (`APP_ENV`). Everything but
/// [`AppEnv::Dev`] is *hardened*: the auth, CORS and registry settings
/// below stop being optional and a missing one fails startup instead of
/// silently disabling the check.
pub app_env: AppEnv,
}
/// Deployment environment (`APP_ENV`).
///
/// The scanner used to degrade quietly when auth configuration was absent:
/// no Keycloak meant no JWT check and a synthetic `dev` tenant, no
/// `CORS_ALLOWED_ORIGINS` meant permissive CORS, no registry meant no
/// entitlement check. That is convenient on a laptop and unacceptable
/// anywhere with customer data, so those degradations now exist only in
/// [`AppEnv::Dev`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AppEnv {
/// Laptop / CI. Auth may be absent; requests fall back to the dev tenant.
#[default]
Dev,
/// `bp-platform-stage`. Real tenants, real Keycloak — hardened.
Staging,
/// `bp-platform-prod`. Hardened.
Production,
}
impl AppEnv {
/// Parse `APP_ENV`. Empty or unset is [`AppEnv::Dev`]; an unrecognised
/// value is an error rather than a silent downgrade to dev.
pub fn parse(raw: &str) -> Result<Self, String> {
match raw.trim().to_ascii_lowercase().as_str() {
"" | "dev" | "development" | "local" | "test" => Ok(Self::Dev),
"stage" | "staging" => Ok(Self::Staging),
"prod" | "production" => Ok(Self::Production),
other => Err(format!(
"unknown APP_ENV '{other}' (expected dev, staging or production)"
)),
}
}
/// Whether the fail-closed rules apply.
pub fn is_hardened(self) -> bool {
!matches!(self, Self::Dev)
}
pub fn as_str(self) -> &'static str {
match self {
Self::Dev => "dev",
Self::Staging => "staging",
Self::Production => "production",
}
}
}
impl AgentConfig {
/// Check that a hardened deployment has everything it needs to enforce
/// authentication, tenancy and entitlements. Returns every problem at
/// once so an operator fixes one deploy instead of five.
///
/// In [`AppEnv::Dev`] this is always `Ok`.
pub fn validate_deployment(&self) -> Result<(), Vec<String>> {
if !self.app_env.is_hardened() {
return Ok(());
}
let mut problems = Vec::new();
let mut require = |present: bool, var: &str, why: &str| {
if !present {
problems.push(format!(
"{var} is required in {} — {why}",
self.app_env.as_str()
));
}
};
require(
self.keycloak_url.is_some(),
"KEYCLOAK_URL",
"without it every request runs unauthenticated as the dev tenant",
);
require(
self.keycloak_realm.is_some(),
"KEYCLOAK_REALM",
"without it every request runs unauthenticated as the dev tenant",
);
require(
self.keycloak_audience.is_some(),
"KEYCLOAK_AUDIENCE",
"an empty audience disables `aud` validation, so any realm token is accepted",
);
require(
!self.cors_allowed_origins.is_empty(),
"CORS_ALLOWED_ORIGINS",
"an empty allowlist falls back to permissive CORS",
);
require(
self.tenant_registry_url.is_some(),
"TENANT_REGISTRY_URL",
"without it entitlements are never checked and the scheduler has no tenant list",
);
require(
self.tenant_registry_client_id.is_some(),
"TENANT_REGISTRY_CLIENT_ID",
"registry calls would go out unauthenticated",
);
require(
self.tenant_registry_client_secret.is_some(),
"TENANT_REGISTRY_CLIENT_SECRET",
"registry calls would go out unauthenticated",
);
require(
self.secrets_encryption_key.is_some(),
"SECRETS_ENCRYPTION_KEY",
"without it no tenant credential (git or tracker token) can be stored",
);
require(
!self.platform_allowed_clients.is_empty(),
"PLATFORM_ALLOWED_CLIENTS",
"the platform lifecycle endpoints would accept any service client",
);
if problems.is_empty() {
Ok(())
} else {
Err(problems)
}
}
}
/// Dev-shaped defaults, mirroring what the agent's loader falls back to when
/// an optional variable is unset. Handy for tests and for the few places that
/// build a config without the environment: `AgentConfig { mongodb_uri: uri,
/// ..Default::default() }`.
impl Default for AgentConfig {
fn default() -> Self {
Self {
mongodb_uri: "mongodb://localhost:27017".to_string(),
mongodb_database: "compliance_scanner".to_string(),
litellm_url: "http://localhost:4000".to_string(),
litellm_api_key: SecretString::from(String::new()),
litellm_model: "gpt-4o".to_string(),
litellm_embed_model: "text-embedding-3-small".to_string(),
github_token: None,
github_webhook_secret: None,
gitlab_url: None,
gitlab_token: None,
gitlab_webhook_secret: None,
jira_url: None,
jira_email: None,
jira_api_token: None,
jira_project_key: None,
searxng_url: None,
nvd_api_key: None,
agent_port: 3001,
webhook_port: 3002,
scan_concurrency: 2,
scan_schedule: "0 0 */6 * * *".to_string(),
cve_monitor_schedule: "0 0 * * * *".to_string(),
git_clone_base_path: "/tmp/compliance-scanner/repos".to_string(),
artifact_store_base_path: "/data/compliance-scanner/artifacts".to_string(),
keycloak_url: None,
keycloak_realm: None,
keycloak_admin_username: None,
keycloak_admin_password: None,
pentest_verification_email: None,
pentest_imap_host: None,
pentest_imap_port: None,
pentest_imap_tls: true,
pentest_imap_username: None,
pentest_imap_password: None,
admin_api_token: None,
secrets_encryption_key: None,
tenant_registry_url: None,
plc_runtime: PlcRuntimeConfig::default(),
werkbank_runner_token: None,
breakpilot: BreakpilotConfig::default(),
product_key: "pruefwerk".to_string(),
keycloak_audience: Some("pruefwerk".to_string()),
tenant_registry_client_id: None,
tenant_registry_client_secret: None,
cors_allowed_origins: Vec::new(),
platform_allowed_clients: Vec::new(),
features: Features::default(),
app_env: AppEnv::Dev,
}
}
}
#[cfg(test)]
mod app_env_tests {
use super::{AgentConfig, AppEnv};
#[test]
fn parses_known_environments_and_rejects_typos() {
assert_eq!(AppEnv::parse("").unwrap(), AppEnv::Dev);
assert_eq!(AppEnv::parse(" Dev ").unwrap(), AppEnv::Dev);
assert_eq!(AppEnv::parse("staging").unwrap(), AppEnv::Staging);
assert_eq!(AppEnv::parse("PROD").unwrap(), AppEnv::Production);
assert!(AppEnv::parse("produciton").is_err());
assert!(!AppEnv::Dev.is_hardened());
assert!(AppEnv::Staging.is_hardened());
assert!(AppEnv::Production.is_hardened());
}
#[test]
fn dev_needs_nothing() {
assert!(AgentConfig::default().validate_deployment().is_ok());
}
#[test]
fn hardened_reports_every_missing_setting_at_once() {
let cfg = AgentConfig {
app_env: AppEnv::Production,
keycloak_audience: None,
..Default::default()
};
let problems = cfg.validate_deployment().unwrap_err();
for var in [
"KEYCLOAK_URL",
"KEYCLOAK_REALM",
"KEYCLOAK_AUDIENCE",
"CORS_ALLOWED_ORIGINS",
"TENANT_REGISTRY_URL",
"TENANT_REGISTRY_CLIENT_ID",
"TENANT_REGISTRY_CLIENT_SECRET",
"SECRETS_ENCRYPTION_KEY",
"PLATFORM_ALLOWED_CLIENTS",
] {
assert!(
problems.iter().any(|p| p.contains(var)),
"{var} missing from {problems:?}"
);
}
}
#[test]
fn fully_configured_staging_passes() {
let cfg = AgentConfig {
app_env: AppEnv::Staging,
keycloak_url: Some("https://auth.breakpilot.com".to_string()),
keycloak_realm: Some("breakpilot-stage".to_string()),
keycloak_audience: Some("pruefwerk".to_string()),
cors_allowed_origins: vec!["https://pruefwerk-stage.breakpilot.com".to_string()],
tenant_registry_url: Some("https://registry-stage.breakpilot.com".to_string()),
tenant_registry_client_id: Some("pruefwerk-svc-stage".to_string()),
tenant_registry_client_secret: Some(secrecy::SecretString::from("s3cret".to_string())),
platform_allowed_clients: vec!["tenant-registry-svc-stage".to_string()],
secrets_encryption_key: Some(secrecy::SecretString::from("00".repeat(32))),
..Default::default()
};
assert!(cfg.validate_deployment().is_ok());
}
}
/// Deployment feature flags (`PW_FEATURES`).
///
/// Flags are free-form lowercase tokens; the ones the agent acts on are the
/// associated constants below. Unknown tokens are kept (and reported on the
/// handshake) so a dashboard-only flag needs no agent release.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Features {
flags: Vec<String>,
}
impl Features {
/// Static-analysis only: the scan pipeline skips every stage that needs
/// live infrastructure (DAST, pentest, ICS probe, ephemeral PLC runtime)
/// and records them as `skipped` on the scan run instead of failing.
pub const SOURCE_ONLY: &'static str = "source_only";
/// Parse a comma-separated flag list. Tokens are trimmed and lowercased;
/// empty tokens are dropped; duplicates collapse.
pub fn parse(csv: &str) -> Self {
let mut flags: Vec<String> = Vec::new();
for raw in csv.split(',') {
let f = raw.trim().to_ascii_lowercase();
if !f.is_empty() && !flags.contains(&f) {
flags.push(f);
}
}
Self { flags }
}
/// Whether `flag` is set.
pub fn has(&self, flag: &str) -> bool {
self.flags.iter().any(|f| f == flag)
}
/// Shorthand for [`Self::has`] with [`Self::SOURCE_ONLY`].
pub fn source_only(&self) -> bool {
self.has(Self::SOURCE_ONLY)
}
/// All set flags, in `PW_FEATURES` order.
pub fn flags(&self) -> &[String] {
&self.flags
}
}
#[cfg(test)]
mod features_tests {
use super::Features;
#[test]
fn parse_trims_lowercases_and_dedups() {
let f = Features::parse(" Source_Only ,, foo,foo ");
assert_eq!(f.flags(), ["source_only", "foo"]);
assert!(f.source_only());
assert!(f.has("foo"));
assert!(!f.has("bar"));
}
#[test]
fn empty_means_no_flags() {
let f = Features::parse("");
assert!(f.flags().is_empty());
assert!(!f.source_only());
assert_eq!(f, Features::default());
}
}
/// Where to pull the OSCAL control catalog from breakpilot-compliance, and where
/// to snapshot it for deterministic / offline reuse.
#[derive(Debug, Clone)]
pub struct BreakpilotConfig {
/// Backend base URL (e.g. `http://backend-compliance:8002`). `None` disables
/// the OSCAL controls provider.
pub base_url: Option<String>,
/// Optional bearer token for the catalog endpoint.
pub token: Option<SecretString>,
/// Directory for catalog snapshots.
pub snapshot_dir: String,
/// Enable the master-controls **semantic** mapping pass (embed regions,
/// Enable the master-controls **semantic** mapping pass (embed regions,
/// retrieve nearest controls, grounded-judge). On by default — validated live
/// against the deployed master-controls catalog. Still a no-op unless
/// `base_url` is set and the catalog is reachable.
pub semantic_mapping: bool,
/// Enable the **grounded surface** pass for absence-based controls (retrieve
/// the code surface a control governs, judge whether it holds). On by default
/// — validated live; it covers the 8 absence-based CRA controls that no
/// syntactic rule can.
pub grounded_control_checks: bool,
}
impl Default for BreakpilotConfig {
fn default() -> Self {
Self {
base_url: None,
token: None,
snapshot_dir: "/data/compliance-scanner/oscal".to_string(),
semantic_mapping: true,
grounded_control_checks: true,
}
}
}
/// Configuration for the ephemeral soft-PLC "provision-and-test" path (#183).
///
/// When a PLC/SPS target ships control logic but no reachable live device, the
/// agent can instantiate that logic itself: spin up a throwaway soft-PLC
/// (OpenPLC) container in-cluster, load the program, start the runtime, probe it
/// over industrial protocols, then tear it down. This struct carries the knobs
/// for that container's lifecycle and the OpenPLC web-UI credentials used to
/// upload the program.
#[derive(Clone, Debug)]
pub struct PlcRuntimeConfig {
/// Master switch. Provision-and-test does nothing unless this is set — it
/// shells out to `docker`, which requires the agent container to have Docker
/// access (socket mount), an explicit deployment decision.
pub enabled: bool,
/// Container image for the ephemeral soft-PLC (OpenPLC).
pub image: String,
/// Docker network the instance joins. Must be the agent's own network so it
/// is reachable in-cluster by container name and never published to the host.
pub network: String,
/// Memory cap passed to `docker run --memory` (e.g. `512m`).
pub memory: String,
/// CPU cap passed to `docker run --cpus` (e.g. `0.5`).
pub cpus: String,
/// Hard ceiling on a provisioned instance's lifetime. Teardown is guaranteed
/// no later than this even if a load/probe step hangs.
pub max_lifetime_secs: u64,
/// OpenPLC web-UI username for the program upload (image default `openplc`).
pub openplc_user: String,
/// OpenPLC web-UI password (image default `openplc`).
pub openplc_password: SecretString,
}
impl Default for PlcRuntimeConfig {
fn default() -> Self {
Self {
enabled: false,
image: "repo.breakpilot.com/pruefwerk/openplc:latest".to_string(),
network: "certifai".to_string(),
memory: "512m".to_string(),
cpus: "0.5".to_string(),
max_lifetime_secs: 180,
openplc_user: "openplc".to_string(),
openplc_password: SecretString::from("openplc".to_string()),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DashboardConfig {
pub mongodb_uri: String,
pub mongodb_database: String,
pub agent_api_url: String,
pub dashboard_port: u16,
pub mcp_endpoint_url: Option<String>,
}