feat(metering): the quota, Prüftage, the daily limit and the cap (t72) (#928)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 4m52s
CI / Deploy Dashboard (push) Failing after 5m54s
CI / Deploy Agent (push) Failing after 7m45s

This commit was merged in pull request #928.
This commit is contained in:
sharang committed 2026-11-06 14:48:07 +00:00
1 parent ce786b716b
commit a7355ffdc8
12 files changed
+838 -64

No files matched your search

Generated
+44 -15
View File
@@ -526,6 +526,16 @@ dependencies = [
"windows-link",
]
[[package]]
name = "chrono-tz"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6139a8597ed92cf816dfb33f5dd6cf0bb93a6adc938f11039f371bc5bcd26c3"
dependencies = [
"chrono",
"phf 0.12.1",
]
[[package]]
name = "ciborium"
version = "0.2.2"
@@ -596,6 +606,7 @@ dependencies = [
"axum",
"base64 0.22.1",
"chrono",
"chrono-tz",
"compliance-core",
"compliance-dast",
"compliance-graph",
@@ -1114,7 +1125,7 @@ dependencies = [
"cssparser-macros",
"dtoa-short",
"itoa",
"phf",
"phf 0.13.1",
"smallvec",
]
@@ -2116,7 +2127,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -3864,7 +3875,7 @@ version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -4284,6 +4295,15 @@ dependencies = [
"indexmap",
]
[[package]]
name = "phf"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "913273894cec178f401a31ec4b656318d95473527be05c0752cc41cdc32be8b7"
dependencies = [
"phf_shared 0.12.1",
]
[[package]]
name = "phf"
version = "0.13.1"
@@ -4291,7 +4311,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"
dependencies = [
"phf_macros",
"phf_shared",
"phf_shared 0.13.1",
"serde",
]
@@ -4302,7 +4322,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1"
dependencies = [
"phf_generator",
"phf_shared",
"phf_shared 0.13.1",
]
[[package]]
@@ -4312,7 +4332,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"
dependencies = [
"fastrand",
"phf_shared",
"phf_shared 0.13.1",
]
[[package]]
@@ -4322,12 +4342,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef"
dependencies = [
"phf_generator",
"phf_shared",
"phf_shared 0.13.1",
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "phf_shared"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06005508882fb681fd97892ecff4b7fd0fee13ef1aa569f8695dae7ab9099981"
dependencies = [
"siphasher",
]
[[package]]
name = "phf_shared"
version = "0.13.1"
@@ -4590,7 +4619,7 @@ dependencies = [
"once_cell",
"socket2 0.6.2",
"tracing",
"windows-sys 0.59.0",
"windows-sys 0.60.2",
]
[[package]]
@@ -4957,7 +4986,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -5129,7 +5158,7 @@ dependencies = [
"derive_more",
"log",
"new_debug_unreachable",
"phf",
"phf 0.13.1",
"phf_codegen",
"precomputed-hash",
"rustc-hash 2.1.1",
@@ -5577,7 +5606,7 @@ checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901"
dependencies = [
"new_debug_unreachable",
"parking_lot",
"phf_shared",
"phf_shared 0.13.1",
"precomputed-hash",
]
@@ -5588,7 +5617,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "585635e46db231059f76c5849798146164652513eb9e8ab2685939dd90f29b69"
dependencies = [
"phf_generator",
"phf_shared",
"phf_shared 0.13.1",
"proc-macro2",
"quote",
]
@@ -5897,7 +5926,7 @@ dependencies = [
"getrandom 0.4.1",
"once_cell",
"rustix",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -6996,7 +7025,7 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57a9779e9f04d2ac1ce317aee707aa2f6b773afba7b931222bff6983843b1576"
dependencies = [
"phf",
"phf 0.13.1",
"phf_codegen",
"string_cache",
"string_cache_codegen",
@@ -7067,7 +7096,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
+2
View File
@@ -33,6 +33,8 @@ tokio = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
chrono = { workspace = true }
# Calendar days and months of metering in Europe/Berlin (t72).
chrono-tz = "0.10"
mongodb = { workspace = true }
reqwest = { workspace = true }
thiserror = { workspace = true }
+60 -17
View File
@@ -13,6 +13,12 @@ use crate::registry::RegistryClient;
use crate::scan_gate::{Admission, HeldTarget, ScanGate};
use crate::secrets::SecretBox;
/// A target whose billing changed, with its new billing (t72).
pub type BillingChange = (
mongodb::bson::oid::ObjectId,
compliance_core::models::TargetBilling,
);
/// Default maximum concurrent pentest sessions.
const DEFAULT_MAX_CONCURRENT_SESSIONS: usize = 5;
@@ -165,20 +171,44 @@ impl ComplianceAgent {
&self,
tenant_id: &str,
db: &crate::database::Database,
) -> Vec<(
mongodb::bson::oid::ObjectId,
compliance_core::models::TargetBilling,
)> {
let included = match &self.registry {
None => None,
Some(registry) => match registry.check_entitlement(tenant_id, None, None).await {
Ok(check) => check.included_targets(),
Err(e) => {
tracing::warn!(tenant_id, "plan not read, target billing kept: {e}");
return Vec::new();
}
},
) -> Vec<BillingChange> {
match self.plan(tenant_id).await {
Some(plan) => {
self.assign_billing(tenant_id, db, plan.included_targets)
.await
}
None => Vec::new(),
}
}
/// The tenant's plan for metering (t72), from its entitlement; without
/// a registry, no limits at all. `None` when the registry did not
/// answer: then the stored billing stays, and counted Prüfungen are
/// neither checked nor charged.
pub async fn plan(&self, tenant_id: &str) -> Option<crate::metering::Plan> {
let Some(registry) = &self.registry else {
return Some(crate::metering::Plan::default());
};
match registry.check_entitlement(tenant_id, None, None).await {
Ok(check) => Some(crate::metering::Plan {
included_targets: check.included_targets(),
limits: check.plan_limits(),
}),
Err(e) => {
tracing::warn!(tenant_id, "plan not read, metering waits: {e}");
None
}
}
}
/// Store the billing of the tenant's targets for a plan that includes
/// `included` targets; best-effort.
async fn assign_billing(
&self,
tenant_id: &str,
db: &crate::database::Database,
included: Option<u32>,
) -> Vec<BillingChange> {
match crate::metering::assign_billing(db, included).await {
Ok(changes) => {
if !changes.is_empty() {
@@ -273,14 +303,19 @@ impl ComplianceAgent {
trigger: compliance_core::models::ScanTrigger,
) -> Result<(), crate::error::AgentError> {
let db = self.db_pool.for_tenant_id(tenant_id).await?;
// Whether this target is included or extra decides whether its scan
// counts, and the plan's limits whether a counted one may run (t72).
let plan = self.plan(tenant_id).await;
if let Some(plan) = &plan {
self.assign_billing(tenant_id, &db, plan.included_targets)
.await;
}
let orchestrator =
PipelineOrchestrator::new(self.config.clone(), tenant_id, db.clone(), self.llm.clone())
.with_nuget_license_cache(self.nuget_license_cache.clone())
.with_exploit_cache(self.exploit_cache.clone())
.with_advisory_index(self.advisory_index.clone());
// Whether this target is included or extra decides whether its scan
// counts (t72).
self.refresh_billing(tenant_id, &db).await;
.with_advisory_index(self.advisory_index.clone())
.with_plan_limits(plan.map(|p| p.limits));
let started = chrono::Utc::now();
let outcome = orchestrator.run_target(target_id, trigger.clone()).await?;
// Support's scans are ours, not the customer's usage; a scheduled scan
@@ -298,6 +333,14 @@ impl ComplianceAgent {
}),
);
}
if let Some(day) = &outcome.booked_prueftag {
self.emit_usage(
tenant_id,
"prueftag.booked",
format!("prueftag:{tenant_id}:{target_id}:{day}"),
serde_json::json!({ "target_id": target_id, "day": day }),
);
}
self.notify_new_findings(tenant_id, target_id, &db, started);
Ok(())
}
+6
View File
@@ -42,6 +42,11 @@ pub enum AgentError {
#[error("the archive password set on the target does not open it")]
ArchivePasswordWrong,
/// A counted Prüfung the plan does not allow now (t72): not an error of
/// the scan, which ends without scanning.
#[error("not run: {0:?}")]
NotAdmitted(compliance_core::models::Refusal),
#[error("{0}")]
Other(String),
}
@@ -73,6 +78,7 @@ impl AgentError {
| Self::Config(_)
| Self::Secret(_)
| Self::Exec(_)
| Self::NotAdmitted(_)
| Self::Other(_) => (
RunErrorCode::Internal,
"the scan stopped because of an internal error",
+209 -7
View File
@@ -1,10 +1,17 @@
//! Which of a tenant's targets are the plan's included ones (t72).
//! Metering of a tenant's Prüfungen (t72).
//!
//! The oldest active targets are included, up to the plan's
//! `included_targets`; every other active target is extra. The split is
//! stored on each target ([`OnboardedTarget::billing`]) and brought up to
//! date before each scan and when a target is created, so archiving an
//! included target moves the oldest extra one up.
//! **Included and extra targets.** The oldest active targets are included,
//! up to the plan's `included_targets`; every other active target is extra.
//! The split is stored on each target ([`OnboardedTarget::billing`]) and
//! brought up to date before each scan and when a target is created, so
//! archiving an included target moves the oldest extra one up.
//!
//! **Counters.** A counted Prüfung is checked against the plan when it
//! starts ([`usage`] and [`compliance_core::models::admit`]) and charged
//! when it completes ([`charge`]): to the month's quota, else to the
//! target's Prüftag for the day, booking one if none is. Months and days
//! are calendar ones in Europe/Berlin. A run that fails because of us is
//! never charged, so nothing is refunded.
//!
//! [`OnboardedTarget::billing`]: compliance_core::models::OnboardedTarget::billing
@@ -12,7 +19,9 @@ use chrono::{DateTime, Utc};
use futures_util::TryStreamExt;
use mongodb::bson::{doc, oid::ObjectId, Document};
use compliance_core::models::{split_included, BillableTarget, TargetBilling};
use compliance_core::models::{
split_included, BillableTarget, DayUsage, MonthUsage, PlanLimits, RunCharge, TargetBilling,
};
use crate::database::Database;
use crate::error::AgentError;
@@ -84,9 +93,202 @@ fn billable(target: &Document) -> Option<BillableTarget<ObjectId>> {
})
}
/// The tenant's plan as metering reads it from the registry.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Plan {
/// How many targets the plan includes; `None` is unlimited.
pub included_targets: Option<u32>,
/// The quota and the customer's Prüftag cap.
pub limits: PlanLimits,
}
/// The tenant's counted Prüfungen and booked Prüftage per month.
const MONTHS: &str = "metering_months";
/// Each target's Prüftag per day, once the quota was used up.
const DAYS: &str = "metering_days";
/// The calendar month and day of `at` in Europe/Berlin, as `YYYY-MM` and
/// `YYYY-MM-DD`: the periods the contract counts in.
pub fn berlin_period(at: DateTime<Utc>) -> (String, String) {
let local = at.with_timezone(&chrono_tz::Europe::Berlin);
(
local.format("%Y-%m").to_string(),
local.format("%Y-%m-%d").to_string(),
)
}
/// The id of a target's counter for one day.
fn day_id(target_id: &str, day: &str) -> String {
format!("{target_id}:{day}")
}
/// A stored counter as a `u32`; missing or negative reads as 0.
fn count(document: Option<&Document>, field: &str) -> u32 {
document
.and_then(|d| d.get(field))
.and_then(mongodb::bson::Bson::as_i64)
.or_else(|| document.and_then(|d| d.get_i32(field).ok()).map(i64::from))
.and_then(|n| u32::try_from(n).ok())
.unwrap_or(0)
}
/// What the tenant used this month and `target_id` today, at `at`.
///
/// # Errors
///
/// Returns an error if the counters cannot be read.
pub async fn usage(
db: &Database,
target_id: &str,
at: DateTime<Utc>,
) -> Result<(MonthUsage, DayUsage), AgentError> {
let (month, day) = berlin_period(at);
let month_doc = db
.raw_collection(MONTHS)
.find_one(doc! { "_id": &month })
.await?;
let day_doc = db
.raw_collection(DAYS)
.find_one(doc! { "_id": day_id(target_id, &day) })
.await?;
Ok((
MonthUsage {
pruefungen: count(month_doc.as_ref(), "pruefungen"),
prueftage: count(month_doc.as_ref(), "prueftage"),
},
DayUsage {
prueftag_booked: day_doc
.as_ref()
.and_then(|d| d.get_bool("prueftag_booked").ok())
.unwrap_or(false),
prueftag_pruefungen: count(day_doc.as_ref(), "prueftag_pruefungen"),
},
))
}
/// What [`charge`] charged a completed Prüfung to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Charged {
/// The quota or the target's Prüftag.
pub charge: RunCharge,
/// The Berlin day (`YYYY-MM-DD`) of a Prüftag this Prüfung booked; it
/// goes to the registry as `prueftag.booked`.
pub booked_prueftag: Option<String>,
}
/// Charge one completed, counted Prüfung on `target_id` at `at`: to the
/// month's quota while it lasts, else to the target's Prüftag that day,
/// booking it if none is. The start of the run checked the limits, so this
/// never refuses; scans of several targets finishing at once can take the
/// quota or a Prüftag over by the ones that raced.
///
/// # Errors
///
/// Returns an error if the counters cannot be written.
pub async fn charge(
db: &Database,
target_id: &str,
limits: PlanLimits,
at: DateTime<Utc>,
) -> Result<Charged, AgentError> {
let (month, day) = berlin_period(at);
let months = db.raw_collection(MONTHS);
months
.update_one(
doc! { "_id": &month },
doc! { "$setOnInsert": { "pruefungen": 0_i64, "prueftage": 0_i64 } },
)
.upsert(true)
.await?;
let quota_filter = match limits.monthly_pruefungen {
Some(quota) => doc! { "_id": &month, "pruefungen": { "$lt": i64::from(quota) } },
None => doc! { "_id": &month },
};
let in_quota = months
.update_one(quota_filter, doc! { "$inc": { "pruefungen": 1_i64 } })
.await?;
if in_quota.matched_count == 1 {
return Ok(Charged {
charge: RunCharge::Quota,
booked_prueftag: None,
});
}
let days = db.raw_collection(DAYS);
let id = day_id(target_id, &day);
days.update_one(
doc! { "_id": &id },
doc! { "$setOnInsert": {
"target_id": target_id,
"day": &day,
"month": &month,
"prueftag_booked": false,
"prueftag_pruefungen": 0_i64,
} },
)
.upsert(true)
.await?;
let booked = days
.update_one(
doc! { "_id": &id, "prueftag_booked": false },
doc! { "$set": { "prueftag_booked": true, "prueftag_pruefungen": 1_i64 } },
)
.await?;
if booked.matched_count == 1 {
months
.update_one(
doc! { "_id": &month },
doc! { "$inc": { "prueftage": 1_i64 } },
)
.await?;
return Ok(Charged {
charge: RunCharge::Prueftag,
booked_prueftag: Some(day),
});
}
days.update_one(
doc! { "_id": &id },
doc! { "$inc": { "prueftag_pruefungen": 1_i64 } },
)
.await?;
Ok(Charged {
charge: RunCharge::Prueftag,
booked_prueftag: None,
})
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::TimeZone;
#[test]
fn periods_are_calendar_ones_in_berlin() {
let at = |y, m, d, h, min| {
Utc.with_ymd_and_hms(y, m, d, h, min, 0)
.single()
.expect("valid")
};
// 23:30 UTC on 31 Oct is already 1 Nov in Berlin (CET, UTC+1).
assert_eq!(
berlin_period(at(2026, 10, 31, 23, 30)),
("2026-11".to_string(), "2026-11-01".to_string())
);
// In summer (CEST, UTC+2) the day turns at 22:00 UTC.
assert_eq!(berlin_period(at(2026, 7, 14, 21, 59)).1, "2026-07-14");
assert_eq!(berlin_period(at(2026, 7, 14, 22, 0)).1, "2026-07-15");
}
#[test]
fn a_counter_reads_as_zero_when_missing() {
let stored = doc! { "pruefungen": 7_i64, "small": 3_i32, "negative": -1_i64 };
assert_eq!(count(Some(&stored), "pruefungen"), 7);
assert_eq!(count(Some(&stored), "small"), 3);
assert_eq!(count(Some(&stored), "negative"), 0);
assert_eq!(count(Some(&stored), "absent"), 0);
assert_eq!(count(None, "pruefungen"), 0);
}
#[test]
fn a_stored_target_reads_with_defaults_for_what_it_lacks() {
+182 -22
View File
@@ -37,15 +37,18 @@ pub struct GraphContext {
pub impacts: Vec<compliance_core::models::graph::ImpactAnalysis>,
}
/// How a scan of an onboarded target went, for its usage event (t72).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// How a scan of an onboarded target went, for its usage events (t72).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TargetScanOutcome {
/// `false` when it was skipped because nothing changed (#465).
/// `false` when it was skipped because nothing changed (#465), or the
/// plan did not allow it now.
pub scanned: bool,
/// Why it ran; `None` when it was skipped.
pub attribution: Option<ScanAttribution>,
/// Whether it counts toward the customer's usage.
pub chargeable: bool,
/// The Berlin day (`YYYY-MM-DD`) of a Prüftag this scan booked.
pub booked_prueftag: Option<String>,
}
/// What a scan left out of its working copy before the first stage, as
@@ -76,6 +79,9 @@ pub struct PipelineOrchestrator {
pub(super) exploit_cache: Option<Arc<dyn ExploitCache>>,
/// The vendor CSAF advisories (#515); none in tests.
pub(super) advisory_index: Option<Arc<dyn crate::pipeline::csaf_match::AdvisoryIndex>>,
/// The tenant's plan limits for metering (t72); `None` when not known,
/// and then counted Prüfungen are neither checked nor charged.
pub(super) plan_limits: Option<PlanLimits>,
}
impl PipelineOrchestrator {
@@ -92,9 +98,16 @@ impl PipelineOrchestrator {
nuget_license_cache: None,
exploit_cache: None,
advisory_index: None,
plan_limits: None,
}
}
/// Check and charge counted Prüfungen against `limits` (t72).
pub(crate) fn with_plan_limits(mut self, limits: Option<PlanLimits>) -> Self {
self.plan_limits = limits;
self
}
/// Cache the NuGet licenses looked up on nuget.org in `cache` (#467).
pub(crate) fn with_nuget_license_cache(mut self, cache: Arc<dyn LicenseCache>) -> Self {
self.nuget_license_cache = Some(cache);
@@ -209,10 +222,11 @@ impl PipelineOrchestrator {
}
self.attribute_run(
scan_run_id,
&repo_id,
ScanAttribution::detected(trigger, new_commits || repo.changed_besides_commits),
repo.billing,
)
.await;
.await?;
}
// Submodules are part of what the product ships (a HAL, an RTOS).
@@ -1180,9 +1194,20 @@ impl PipelineOrchestrator {
.map(|id| id.to_hex())
.unwrap_or_default();
let result = self
.run_target_pipeline(&target, &scan_run_id, &trigger)
.await;
// A counted Prüfung a person started is checked against the plan
// before anything runs (t72).
let admitted = if scan_run.chargeable {
self.admit_run(&scan_run_id, target_id).await
} else {
Ok(())
};
let result = match admitted {
Ok(()) => {
self.run_target_pipeline(&target, &scan_run_id, &trigger)
.await
}
Err(e) => Err(e),
};
match &result {
Ok(count) => {
let mut completed = doc! {
@@ -1233,6 +1258,23 @@ impl PipelineOrchestrator {
)
.await?;
}
// The plan does not allow it now: the run ends without scanning,
// and the target keeps what its last scan read, so the change is
// scanned once it may be.
Err(AgentError::NotAdmitted(refusal)) => {
tracing::info!(target_id, ?refusal, "counted Prüfung not run");
self.db
.scan_runs()
.update_one(
doc! { "_id": &insert.inserted_id },
doc! { "$set": {
"status": "completed",
"current_phase": "completed",
"completed_at": mongodb::bson::DateTime::now(),
} },
)
.await?;
}
Err(e) => {
tracing::error!(target_id, error = %e, "Unified scan pipeline failed");
let (code, message) = e.run_failure();
@@ -1250,32 +1292,149 @@ impl PipelineOrchestrator {
.await?;
}
}
result?;
let refused = matches!(result, Err(AgentError::NotAdmitted(_)));
let invalid_input = matches!(
result,
Err(AgentError::ArchivePasswordRequired | AgentError::ArchivePasswordWrong)
);
// Read back without hiding the scan's own error behind a failed read.
let run = self
.db
.scan_runs()
.find_one(doc! { "_id": &insert.inserted_id })
.await?
.ok_or_else(|| AgentError::Other(format!("scan run of {target_id} not found")))?;
Ok(TargetScanOutcome {
scanned: !run
.skipped_stages
.await
.ok()
.flatten();
let unchanged = run.as_ref().is_some_and(|r| {
r.skipped_stages
.iter()
.any(|s| s.stage == "change_detection"),
attribution: run.attribution,
chargeable: run.chargeable,
.any(|s| s.stage == "change_detection")
});
let chargeable = run.as_ref().is_some_and(|r| r.chargeable);
let attribution = run.and_then(|r| r.attribution);
// A counted Prüfung is charged when it completed, or when it failed on
// the customer's input; a failure of ours never is (t72).
let charged = if chargeable && ((result.is_ok() && !unchanged) || invalid_input) {
self.charge_run(&insert.inserted_id, target_id).await
} else {
None
};
if !refused {
result?;
}
Ok(TargetScanOutcome {
scanned: !refused && !unchanged,
attribution,
chargeable,
booked_prueftag: charged.and_then(|c| c.booked_prueftag),
})
}
/// Record why the run `scan_run_id` runs and whether it counts, on a
/// target billed as `billing` (t72). A run with several code artifacts
/// is attributed once per artifact; a change found in any of them wins
/// over our rescan. Best-effort, like [`Self::skip_stage`].
/// Check a counted Prüfung against the plan before it scans (t72):
/// the quota, today's Prüftag on the target, the customer's cap. It runs
/// when the plan's limits or the usage are not known.
///
/// # Errors
///
/// [`AgentError::NotAdmitted`] when the plan does not allow it now; why
/// is recorded on the run.
async fn admit_run(&self, scan_run_id: &str, target_id: &str) -> Result<(), AgentError> {
let Some(limits) = self.plan_limits else {
return Ok(());
};
let (month, day) =
match crate::metering::usage(&self.db, target_id, chrono::Utc::now()).await {
Ok(usage) => usage,
Err(e) => {
tracing::warn!(target_id, "usage not read, the Prüfung runs: {e}");
return Ok(());
}
};
let Admission::Refused(refusal) = admit(limits, month, day) else {
return Ok(());
};
let (code, reason) = match refusal {
Refusal::DailyLimit => (
SkipCode::PrueftagLimitReached,
"the quota is used up and today's Prüftag on the target has had its Prüfungen",
),
Refusal::PrueftagCap => (
SkipCode::PrueftagCapReached,
"the quota is used up and the customer's Prüftag limit is reached",
),
};
self.skip_stage(scan_run_id, SkippedStage::new("metering", code, reason))
.await;
Err(AgentError::NotAdmitted(refusal))
}
/// Charge the completed, counted run `run_id` on `target_id` and record
/// what it was charged to (t72). Nothing is charged when the plan's
/// limits are not known. Best-effort: a counter that cannot be written is
/// logged.
async fn charge_run(
&self,
run_id: &mongodb::bson::Bson,
target_id: &str,
) -> Option<crate::metering::Charged> {
let limits = self.plan_limits?;
match crate::metering::charge(&self.db, target_id, limits, chrono::Utc::now()).await {
Ok(charged) => {
if let Ok(value) = mongodb::bson::to_bson(&charged.charge) {
if let Err(e) = self
.db
.scan_runs()
.update_one(
doc! { "_id": run_id.clone() },
doc! { "$set": { "charge": value } },
)
.await
{
tracing::warn!(target_id, "charge not recorded on the run: {e}");
}
}
Some(charged)
}
Err(e) => {
tracing::warn!(target_id, "Prüfung not charged: {e}");
None
}
}
}
/// Record why the run `scan_run_id` on `target_id` runs and whether it
/// counts, on a target billed as `billing`, and check a counted one
/// against the plan (t72). A run with several code artifacts is
/// attributed once per artifact; a change found in any of them wins over
/// our rescan. The record is best-effort, like [`Self::skip_stage`].
///
/// # Errors
///
/// [`AgentError::NotAdmitted`] when the plan does not allow a counted
/// Prüfung now.
async fn attribute_run(
&self,
scan_run_id: &str,
target_id: &str,
attribution: ScanAttribution,
billing: TargetBilling,
) -> Result<(), AgentError> {
let chargeable = attribution.chargeable(billing);
self.record_attribution(scan_run_id, attribution, chargeable)
.await;
if chargeable {
self.admit_run(scan_run_id, target_id).await?;
}
Ok(())
}
/// Store `attribution` and `chargeable` on the run, unless it already
/// reads as a change.
async fn record_attribution(
&self,
scan_run_id: &str,
attribution: ScanAttribution,
chargeable: bool,
) {
let Ok(oid) = mongodb::bson::oid::ObjectId::parse_str(scan_run_id) else {
return;
@@ -1291,7 +1450,7 @@ impl PipelineOrchestrator {
doc! { "_id": oid, "attribution": { "$ne": change } },
doc! { "$set": {
"attribution": value,
"chargeable": attribution.chargeable(billing),
"chargeable": chargeable,
} },
)
.await
@@ -1346,13 +1505,14 @@ impl PipelineOrchestrator {
if !trigger.started_by_person() && !has_git {
self.attribute_run(
scan_run_id,
&target_id,
ScanAttribution::detected(
trigger,
crate::pipeline::change::content_changed(target),
),
target.billing,
)
.await;
.await?;
}
let plan = build_scan_plan(target);
// An attached artifact nothing analyses is recorded, never passed over:
+37 -1
View File
@@ -68,7 +68,22 @@ impl EntitlementCheck {
/// `limits.included_targets`. `None` when the plan sets no limit (no
/// limits, the key missing or null), so every target is included.
pub fn included_targets(&self) -> Option<u32> {
let n = self.limits.as_ref()?.get("included_targets")?.as_u64()?;
self.limit("included_targets")
}
/// The plan's monthly quota and the customer's Prüftag cap (t72), from
/// `limits.monthly_pruefungen` and `limits.prueftag_cap`; a missing or
/// null key is no limit.
pub fn plan_limits(&self) -> compliance_core::models::PlanLimits {
compliance_core::models::PlanLimits {
monthly_pruefungen: self.limit("monthly_pruefungen"),
prueftag_cap: self.limit("prueftag_cap"),
}
}
/// The whole-number limit `key`; `None` when absent or null.
fn limit(&self, key: &str) -> Option<u32> {
let n = self.limits.as_ref()?.get(key)?.as_u64()?;
// A count beyond u32 is no limit in practice.
Some(u32::try_from(n).unwrap_or(u32::MAX))
}
@@ -662,6 +677,27 @@ mod tests {
assert_eq!(check(serde_json::Value::Null).included_targets(), None);
}
#[test]
fn the_plan_sets_the_quota_and_the_cap() {
let check: EntitlementCheck = serde_json::from_value(serde_json::json!({
"allowed": true,
"limits": { "included_targets": 5, "monthly_pruefungen": 100, "prueftag_cap": 0 },
}))
.expect("an entitlement answer");
assert_eq!(
check.plan_limits(),
compliance_core::models::PlanLimits {
monthly_pruefungen: Some(100),
prueftag_cap: Some(0),
}
);
assert_eq!(
EntitlementCheck::default().plan_limits(),
compliance_core::models::PlanLimits::default(),
"Enterprise: no limits"
);
}
#[test]
fn ladder_filter() {
for s in ["active", "trial", "demo", "warning", ""] {
@@ -0,0 +1,83 @@
//! Counted Prüfungen go to the month's quota first; once it is used up, the
//! first one on a target that day books a Prüftag that allows six (t72).
//! Runs against a live Mongo (`TEST_MONGODB_URI`) and skips cleanly without
//! one.
#![allow(clippy::expect_used, clippy::unwrap_used)]
use chrono::{TimeZone, Utc};
use compliance_agent::database::DatabasePool;
use compliance_agent::metering::{charge, usage};
use compliance_core::models::{
admit, Admission, PlanLimits, Refusal, RunCharge, PRUEFUNGEN_PER_PRUEFTAG,
};
const TENANT: &str = "metering-counters";
#[tokio::test]
async fn the_quota_then_a_prueftag_of_six_then_nothing() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!(
"metering_{}",
&uuid::Uuid::new_v4().simple().to_string()[..10]
);
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP metering_counters: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id(TENANT).await.unwrap();
// Arrange: a quota of two and a cap of one Prüftag, on 6 Nov in Berlin.
let plan = PlanLimits {
monthly_pruefungen: Some(2),
prueftag_cap: Some(1),
};
let at = Utc.with_ymd_and_hms(2026, 11, 6, 9, 0, 0).single().unwrap();
let admitted = |target: &'static str| {
let db = db.clone();
async move {
let (month, day) = usage(&db, target, at).await.unwrap();
admit(plan, month, day)
}
};
// Act / Assert: the quota first.
for _ in 0..2 {
assert_eq!(admitted("a").await, Admission::Quota);
let charged = charge(&db, "a", plan, at).await.unwrap();
assert_eq!(charged.charge, RunCharge::Quota);
assert_eq!(charged.booked_prueftag, None);
}
// The quota is used up: the next one books target a's Prüftag.
assert_eq!(admitted("a").await, Admission::BookPrueftag);
let booked = charge(&db, "a", plan, at).await.unwrap();
assert_eq!(booked.charge, RunCharge::Prueftag);
assert_eq!(booked.booked_prueftag.as_deref(), Some("2026-11-06"));
// It allows six in all; the seventh that day does not run.
for _ in 1..PRUEFUNGEN_PER_PRUEFTAG {
assert_eq!(admitted("a").await, Admission::Prueftag);
let charged = charge(&db, "a", plan, at).await.unwrap();
assert_eq!(charged.booked_prueftag, None, "no second booking");
}
assert_eq!(admitted("a").await, Admission::Refused(Refusal::DailyLimit));
// Another target would need a second Prüftag, over the cap of one.
assert_eq!(
admitted("b").await,
Admission::Refused(Refusal::PrueftagCap)
);
// The next calendar day in Berlin is a new day for target a.
let tomorrow = Utc
.with_ymd_and_hms(2026, 11, 6, 23, 30, 0)
.single()
.unwrap();
let (month, day) = usage(&db, "a", tomorrow).await.unwrap();
assert!(!day.prueftag_booked, "7 Nov in Berlin");
assert_eq!(month.prueftage, 1);
assert_eq!(month.pruefungen, 2);
pool.drop_tenant(TENANT).await.ok();
}
+173
View File
@@ -90,6 +90,102 @@ impl ScanAttribution {
}
}
/// How many counted Prüfungen one Prüftag allows on its target that day.
pub const PRUEFUNGEN_PER_PRUEFTAG: u32 = 6;
/// What the tenant's plan allows per calendar month (Europe/Berlin).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PlanLimits {
/// Counted Prüfungen in the quota; `None` is unlimited (no Prüftage).
pub monthly_pruefungen: Option<u32>,
/// Prüftage the customer allows; `None` is no cap, `Some(0)` none.
pub prueftag_cap: Option<u32>,
}
/// What the tenant used so far this month.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct MonthUsage {
/// Counted Prüfungen charged to the quota.
pub pruefungen: u32,
/// Prüftage booked.
pub prueftage: u32,
}
/// What one target used today, once the quota was used up.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct DayUsage {
/// Whether a Prüftag is booked for the target today.
pub prueftag_booked: bool,
/// Counted Prüfungen charged to that Prüftag.
pub prueftag_pruefungen: u32,
}
/// What a counted Prüfung was charged to.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum RunCharge {
/// The month's quota.
Quota,
/// The target's Prüftag for that day.
Prueftag,
}
/// Whether a counted Prüfung may run, and what it is charged to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Admission {
/// Within the month's quota.
Quota,
/// On the target's Prüftag already booked today.
Prueftag,
/// The quota is used up: this Prüfung books today's Prüftag.
BookPrueftag,
/// It does not run.
Refused(Refusal),
}
/// Why a counted Prüfung does not run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Refusal {
/// Today's Prüftag on the target is used up; there is no second one.
DailyLimit,
/// The quota is used up and the customer's Prüftag cap is reached.
PrueftagCap,
}
/// Whether one more counted Prüfung on a target may run, by the contract
/// (LB Prüfwerk §2 Abs. 5): the quota first; once it is used up, the first
/// counted Prüfung on a target that day books a Prüftag (unless the cap is
/// reached), which allows [`PRUEFUNGEN_PER_PRUEFTAG`] from then on.
///
/// # Examples
///
/// ```
/// use compliance_core::models::{admit, Admission, DayUsage, MonthUsage, PlanLimits};
///
/// let plan = PlanLimits { monthly_pruefungen: Some(100), prueftag_cap: None };
/// let used_up = MonthUsage { pruefungen: 100, prueftage: 0 };
/// assert_eq!(admit(plan, used_up, DayUsage::default()), Admission::BookPrueftag);
/// ```
pub fn admit(limits: PlanLimits, month: MonthUsage, day: DayUsage) -> Admission {
let Some(quota) = limits.monthly_pruefungen else {
return Admission::Quota;
};
if month.pruefungen < quota {
return Admission::Quota;
}
if day.prueftag_booked {
return if day.prueftag_pruefungen < PRUEFUNGEN_PER_PRUEFTAG {
Admission::Prueftag
} else {
Admission::Refused(Refusal::DailyLimit)
};
}
match limits.prueftag_cap {
Some(cap) if month.prueftage >= cap => Admission::Refused(Refusal::PrueftagCap),
_ => Admission::BookPrueftag,
}
}
/// One active target as [`split_included`] sees it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BillableTarget<Id> {
@@ -248,6 +344,83 @@ mod tests {
);
}
const PLAN: PlanLimits = PlanLimits {
monthly_pruefungen: Some(100),
prueftag_cap: Some(2),
};
#[test]
fn the_quota_comes_first() {
let month = MonthUsage {
pruefungen: 99,
prueftage: 0,
};
assert_eq!(admit(PLAN, month, DayUsage::default()), Admission::Quota);
}
#[test]
fn a_used_up_quota_books_a_prueftag_that_allows_six() {
let month = MonthUsage {
pruefungen: 100,
prueftage: 1,
};
assert_eq!(
admit(PLAN, month, DayUsage::default()),
Admission::BookPrueftag
);
let booked = |used| DayUsage {
prueftag_booked: true,
prueftag_pruefungen: used,
};
assert_eq!(admit(PLAN, month, booked(5)), Admission::Prueftag);
assert_eq!(
admit(PLAN, month, booked(PRUEFUNGEN_PER_PRUEFTAG)),
Admission::Refused(Refusal::DailyLimit)
);
}
#[test]
fn the_cap_stops_new_prueftage_but_not_a_booked_one() {
let month = MonthUsage {
pruefungen: 100,
prueftage: 2,
};
assert_eq!(
admit(PLAN, month, DayUsage::default()),
Admission::Refused(Refusal::PrueftagCap)
);
let booked = DayUsage {
prueftag_booked: true,
prueftag_pruefungen: 1,
};
assert_eq!(admit(PLAN, month, booked), Admission::Prueftag);
let none_allowed = PlanLimits {
prueftag_cap: Some(0),
..PLAN
};
let nothing_booked = MonthUsage {
pruefungen: 100,
prueftage: 0,
};
assert_eq!(
admit(none_allowed, nothing_booked, DayUsage::default()),
Admission::Refused(Refusal::PrueftagCap)
);
}
#[test]
fn without_a_quota_everything_runs() {
let unlimited = PlanLimits::default();
let month = MonthUsage {
pruefungen: 10_000,
prueftage: 0,
};
assert_eq!(
admit(unlimited, month, DayUsage::default()),
Admission::Quota
);
}
#[test]
fn stored_names_are_snake_case() {
assert_eq!(
+4 -1
View File
@@ -58,7 +58,10 @@ pub use license_policy::{
};
pub use mcp::{McpServerConfig, McpServerStatus, McpTransport};
pub use mcp_token::{McpToken, McpTokenView};
pub use metering::{split_included, BillableTarget, ScanAttribution, TargetBilling};
pub use metering::{
admit, split_included, Admission, BillableTarget, DayUsage, MonthUsage, PlanLimits, Refusal,
RunCharge, ScanAttribution, TargetBilling, PRUEFUNGEN_PER_PRUEFTAG,
};
pub use notification::{CveNotification, NotificationSeverity, NotificationStatus};
pub use onboarding::{
default_compliance_profile, Artifact, ArtifactAuth, ArtifactKind, Classification,
+16 -1
View File
@@ -194,6 +194,10 @@ pub struct ScanRun {
/// billing when it was attributed).
#[serde(default)]
pub chargeable: bool,
/// What the run was charged to once it counted; `None` while it runs,
/// and for a run that did not count.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub charge: Option<super::metering::RunCharge>,
}
/// Why a stage was skipped, or what a run note is about
@@ -280,6 +284,12 @@ pub enum SkipCode {
/// layer pins or `LAYERSERIES_COMPAT`, so its support period was not
/// checked.
ReleaseUnknown,
/// The month's quota is used up and today's Prüftag on the target has
/// had its Prüfungen, so this counted Prüfung did not run (t72).
PrueftagLimitReached,
/// The month's quota is used up and the Prüftag limit the customer set
/// is reached, so this counted Prüfung did not run (t72).
PrueftagCapReached,
}
impl SkipCode {
@@ -314,7 +324,9 @@ impl SkipCode {
| Self::PlatformProjectGenerated
| Self::UploadUnchanged
| Self::TooLargeToScan
| Self::ReleaseUnknown => false,
| Self::ReleaseUnknown
| Self::PrueftagLimitReached
| Self::PrueftagCapReached => false,
}
}
}
@@ -422,6 +434,7 @@ impl ScanRun {
sbom_quality: None,
attribution: None,
chargeable: false,
charge: None,
}
}
}
@@ -486,6 +499,8 @@ mod skipped_stage_tests {
SkipCode::PlatformProjectGenerated,
SkipCode::UploadUnchanged,
SkipCode::TooLargeToScan,
SkipCode::PrueftagLimitReached,
SkipCode::PrueftagCapReached,
];
assert!(notes.iter().all(|c| c.is_informational()));
assert!(skips.iter().all(|c| !c.is_informational()));
+22
View File
@@ -713,6 +713,28 @@ pub mod scans {
so it was not scanned again. \"Run scan\" always scans in full."
.into()
}
(SkipCode::PrueftagLimitReached, Lang::De) => {
"Nicht geprüft: Das Monatskontingent ist aufgebraucht, und der heutige Prüftag \
für dieses Prüfobjekt hat seine Prüfungen bereits erreicht. Morgen ist wieder \
eine Prüfung möglich."
.into()
}
(SkipCode::PrueftagLimitReached, Lang::En) => {
"Not scanned: the monthly quota is used up and today's Prüftag for this target \
has had all its scans. It can be scanned again tomorrow."
.into()
}
(SkipCode::PrueftagCapReached, Lang::De) => {
"Nicht geprüft: Das Monatskontingent ist aufgebraucht, und Ihr Limit für \
Prüftage ist erreicht. Gezählte Prüfungen laufen wieder ab dem nächsten Monat \
oder nach einer Erhöhung des Limits im Portal."
.into()
}
(SkipCode::PrueftagCapReached, Lang::En) => {
"Not scanned: the monthly quota is used up and your Prüftag limit is reached. \
Counted scans run again next month, or once you raise the limit in the portal."
.into()
}
(SkipCode::TooLargeToScan, Lang::De) => {
format!("Zu groß für die Suche nach Schadsoftware, nicht geprüft: {subject}")
}