From 1551f7d156849b9ef944f4d5ed9e5514a9bec4e8 Mon Sep 17 00:00:00 2001 From: Martin Pluskal Date: Tue, 17 Nov 2026 14:48:06 +0100 Subject: [PATCH 1/2] fix(policy): reject negative day counts at load A negative `younger_than_days` or `min_bug_age_days` loaded without complaint. For the matcher it asks for a cutoff in the future: the rule matched nothing, until the count was large enough for the date arithmetic to overflow, and from there it matched every bug, because an unrepresentable cutoff reads as "every bug is young". Where that flip happens depends on the date library's range, so the meaning of such a value is not something the policy file controls. A negative `min_bug_age_days` was inert; it is refused so that one sign rule covers both. Policy::validate now refuses them, naming the rule or the global key. Zero stays legal in both places. A policy file that carried a negative count stops the server from starting until the value is changed, and the README says what each rewrite means. --- README.md | 13 +++-- crates/bugwarden-core/src/policy.rs | 78 ++++++++++++++++++++++++++++- docs/DESIGN.md | 23 +++++++-- 3 files changed, 104 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index a37a785..77ed49f 100644 --- a/README.md +++ b/README.md @@ -789,7 +789,14 @@ warning at startup if the policy file is group- or other-writable. this one from starting at all — if it names a rule `default`, `min_bug_age_days` or `unavailable`, ends a name with `:unreadable-metadata`, leaves a name blank, or uses one name twice. The error names the offending -rule; rename it and the file loads unchanged. Nothing else about the file's +rule; rename it and the file loads unchanged. A negative `min_bug_age_days` +or `younger_than_days` is refused the same way. For `min_bug_age_days` write +`0` or remove the key; a negative value was already inert. For +`younger_than_days` the two are not the same: `0` keeps the rule from +matching anything but a bug dated in the future, much as a small negative +count did, while removing the key makes the rule match on its other +criteria, or every bug if it has none. +Decide which was meant, or delete the rule. Nothing else about the file's meaning changed. A complete, commented example ships in @@ -805,7 +812,7 @@ A complete, commented example ships in | Key | Type | Default | Description | |-----|------|---------|-------------| -| `min_bug_age_days` | integer | `0` (disabled) | Bugs created less than N days ago are **invisible** — treated exactly like nonexistent bugs, evaluated before any rule. A bug whose `creation_time` is missing or unparsable is denied (fail closed) | +| `min_bug_age_days` | integer | `0` (disabled) | Bugs created less than N days ago are **invisible** — treated exactly like nonexistent bugs, evaluated before any rule. A bug whose `creation_time` is missing or unparsable is denied (fail closed). A negative value is refused at startup | | `allow_private_comments` | boolean | `false` | Master switch for **all** private content: comments, attachment metadata, and attachment downloads. Even when `true`, each call must also pass `include_private = true`. On an attachment download a *missing* privacy flag counts as private | | `read_only` | boolean | `false` | Strip write capabilities from every grant and remove write tools from the tool listing. The `--read-only` flag ORs into this | | `disabled_tools` | array of strings | `[]` | Tool names to remove from the tool listing entirely | @@ -854,7 +861,7 @@ write two consecutive rules. | `whiteboard_contains` | array of strings | case-insensitive substring search in the whiteboard | | `summary_contains` | array of strings | case-insensitive substring search in the bug's one-line summary | | `group_restricted` | boolean | `true` matches bugs readable only through at least one Bugzilla group, `false` matches world-readable bugs | -| `younger_than_days` | integer | matches bugs created within the last N days | +| `younger_than_days` | integer | matches bugs created within the last N days; a negative N is refused at startup | | `created_by_me` | boolean | whether the caller's account authored the bug, compared case-insensitively to the bug's creator. `true` matches the caller's own reports, `false` everyone else's. How the caller's login is resolved depends on `global.identity_source` (default `whoami`): see the source × custody table below. Either source costs at most one lookup per tool call — `whoami` a fresh `GET /rest/whoami`, `declared` zero HTTP requests, since it was verified once at startup — and none at all under a policy without an access-covering `created_by_me` rule (a rule scoped to `operations = ["create"]` alone never triggers one). An unresolvable identity makes the criterion **unknown**, which denies (see Unreadable metadata); a policy that consults this criterion therefore denies everything it reaches while identity cannot be resolved. In the create gate the prospective bug always counts as created by the caller — no lookup happens there (a `create_bug` whose custom fields name Bug ID targets resolves the caller once, for those existing bugs only). Older bugwarden versions reject a policy using this key, or `global.identity_source`/`global.identity_login`, at startup (strict parsing fails closed) | Identity resolution by source and API-key custody: diff --git a/crates/bugwarden-core/src/policy.rs b/crates/bugwarden-core/src/policy.rs index 6a30602..9104e0f 100644 --- a/crates/bugwarden-core/src/policy.rs +++ b/crates/bugwarden-core/src/policy.rs @@ -284,7 +284,8 @@ pub struct Matcher { /// /// A bug with a missing/unparsable `creation_time` has no age to /// compare, so the criterion is undecidable and resolves fail-closed - /// (I4), exactly like every other unreadable field. + /// (I4), exactly like every other unreadable field. A negative count + /// is refused when the policy loads. #[serde(default)] pub younger_than_days: Option, } @@ -561,7 +562,8 @@ pub enum IdentitySource { pub struct GlobalGuards { /// Deny every bug younger than this many days; `0` disables the gate. /// This runs BEFORE any rule, and a missing `creation_time` while the - /// gate is active means Denied (fail closed, I4). + /// gate is active means Denied (fail closed, I4). A negative count is + /// refused when the policy loads. #[serde(default)] pub min_bug_age_days: i64, /// Whether private comments may ever be returned. Even when `true` a @@ -706,6 +708,8 @@ impl Policy { /// - `allow`/`deny` rules carry no capabilities (a capability list on /// them would be dead configuration masking operator intent); /// - `default_action` is not `restrict`; + /// - neither day count is negative: `global.min_bug_age_days` and every + /// rule's `younger_than_days`; /// - `operations`, when written, is non-empty (`operations = []` would /// apply the rule to no operation at all); /// - a `restrict` rule scoped to ONLY the `create` operation grants @@ -781,6 +785,13 @@ impl Policy { } _ => {} } + if self.global.min_bug_age_days < 0 { + anyhow::bail!( + "global.min_bug_age_days = {} is negative; it counts days back \ + from now and must be 0 or more (0 disables the quarantine)", + self.global.min_bug_age_days + ); + } // A rule name has to identify exactly one thing: it is the only // field in an audit record saying what decided an assessment, and I3 // keeps that fact out of the client's reach entirely, so the stream @@ -851,6 +862,14 @@ impl Policy { } _ => {} } + if let Some(days) = rule.matcher.younger_than_days.filter(|d| *d < 0) { + anyhow::bail!( + "rule \"{}\": younger_than_days = {} is negative; it counts \ + days back from now and must be 0 or more", + rule.name, + days + ); + } if let Some(ops) = &rule.operations { if ops.is_empty() { anyhow::bail!( @@ -1933,6 +1952,61 @@ products = ["SUSE*"] assert!(Policy::from_toml_str(s).is_err()); } + #[test] + fn reject_negative_younger_than_days() { + // Under each action and scope, on the first rule and on a later + // one: the check is per rule, whatever else the rule says. + let shapes = [ + "action = \"deny\"\n", + "action = \"allow\"\n", + "action = \"restrict\"\ncapabilities = [\"summary\"]\n", + "action = \"deny\"\noperations = [\"access\"]\n", + "action = \"deny\"\noperations = [\"create\"]\n", + ]; + for (shape, first) in shapes.into_iter().flat_map(|s| [(s, true), (s, false)]) { + let policy = |days: i64| { + let plain = "[[rule]]\nname = \"plain\"\naction = \"deny\"\n"; + let fresh = format!( + "[[rule]]\nname = \"fresh\"\n{shape}\ + [rule.match]\nyounger_than_days = {days}\n" + ); + if first { + fresh + plain + } else { + plain.to_string() + &fresh + } + }; + for days in [-1, -2_912_428, -95_005_769, i64::MIN] { + let msg = format!("{:#}", Policy::from_toml_str(&policy(days)).unwrap_err()); + let want = format!("rule \"fresh\": younger_than_days = {days} is negative"); + assert!(msg.contains(&want), "unexpected error: {msg}"); + } + // Zero is the edge of the window, not a sign error. + Policy::from_toml_str(&policy(0)).unwrap(); + } + } + + #[test] + fn reject_negative_min_bug_age_days() { + for days in [-1, -2_912_428, -95_005_769, i64::MIN] { + let s = format!("[global]\nmin_bug_age_days = {days}\n"); + let msg = format!("{:#}", Policy::from_toml_str(&s).unwrap_err()); + let want = format!("global.min_bug_age_days = {days} is negative"); + assert!(msg.contains(&want), "unexpected error: {msg}"); + } + Policy::from_toml_str("[global]\nmin_bug_age_days = 0\n").unwrap(); + // Built past the loader, a negative count leaves the gate off: an + // active gate would deny a bug whose age it cannot read. + for days in [-1, i64::MIN] { + let mut p = Policy::default(); + p.global.min_bug_age_days = days; + let mut bug = meta(); + bug.creation_time = None; + let access = p.classify(&bug, now(), Operation::Access); + assert!(access.allows(Capability::Read), "{days}: {access:?}"); + } + } + #[test] fn reject_restrict_without_capabilities() { let s = "[[rule]]\nname = \"r\"\naction = \"restrict\"\n"; diff --git a/docs/DESIGN.md b/docs/DESIGN.md index a8698a1..1ec0de2 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -336,7 +336,7 @@ pub struct Matcher { #[serde(default)] pub whiteboard_contains: Vec,// case-insensitive substrings #[serde(default)] pub summary_contains: Vec, // case-insensitive substrings in the one-line summary #[serde(default)] pub group_restricted: Option, // true: readable only via >=1 Bugzilla group; false: world-readable - #[serde(default)] pub younger_than_days: Option, // creation_time newer than now-N days + #[serde(default)] pub younger_than_days: Option, // creation_time newer than now-N days; N < 0 is refused at load // The one identity-relative criterion: true selects bugs AUTHORED by the // requesting account, false everyone else's (see "Identity resolution"). // TOML spelling `created_by_me = true|false`; absent = not consulted. @@ -397,7 +397,7 @@ impl Rule { #[derive(Debug, Clone, serde::Deserialize)] #[serde(deny_unknown_fields)] pub struct GlobalGuards { - #[serde(default)] pub min_bug_age_days: i64, // 0 = disabled + #[serde(default)] pub min_bug_age_days: i64, // 0 = disabled; negative is refused at load #[serde(default)] pub allow_private_comments: bool, // default false #[serde(default)] pub read_only: bool, #[serde(default)] pub disabled_tools: Vec, @@ -425,8 +425,10 @@ impl Policy { // comparisons are exact, so "Default" and " default" stay legal, while // the blank check trims; Restrict rules need >=1 capability; Allow/Deny // rules must have empty capabilities; default_action must not be - // Restrict; a written `operations = []` is an error (a rule applying to - // no operation is dead configuration); a Restrict rule scoped to ONLY + // Restrict; neither day count (global.min_bug_age_days, a rule's + // younger_than_days) may be negative; a written `operations = []` is + // an error (a rule applying to no operation is dead configuration); a + // Restrict rule scoped to ONLY // `create` must grant exactly the `create` capability (without it the // rule could grant nothing reachable, and any other capability it named // would be dead — the create gate consults only `create`); a Restrict @@ -2479,6 +2481,16 @@ pinned by the in-crate capture test under "Testing". create_bug's single `warn` this stream must not err in. Recorded on `RequestInfo::id`: records are per-ATTEMPT, and `request.id` is a client-chosen correlation hint and never an identity. +- **Day counts must not be negative.** `Policy::validate` rejects a negative + `global.min_bug_age_days`, and a negative `younger_than_days` on any rule, + which the error names. A negative `younger_than_days` asks for a cutoff in + the future, so the rule matched nothing, until the count was large enough + for the subtraction to overflow: the matcher read an unrepresentable + cutoff as "every bug is young", and the rule then matched every bug. Where + that happened was set by the date library's range. A negative + `min_bug_age_days` was inert, because the gate only runs for a positive + count, and is refused so that one sign rule covers both. Refusing the sign + at load leaves no such value to interpret. - **Rule names the operator may not take (issue #84).** `Policy::validate` rejects a rule named `"default"`, `"min_bug_age_days"` or `"unavailable"`, a rule whose name ends in `":unreadable-metadata"`, a @@ -3871,7 +3883,8 @@ wired, `server.rs` and `main.rs` are the reference. - Unit tests (#[cfg(test)] in policy.rs/guard.rs): glob matching; first-match ordering; embargo group deny; min_bug_age_days incl. missing creation_time - (fail closed); younger_than_days matcher; restrict caps; read-implies-summary; + (fail closed); younger_than_days matcher; a negative day count in either + refused at load, zero accepted; restrict caps; read-implies-summary; read_only strips write caps — create and attach named explicitly, and a restrict grant of comment grants neither; default deny; summary redaction; comment filtering; validation errors (unknown TOML keys, restrict without From 576875b4d3780b90d30203d8074695280cf77608 Mon Sep 17 00:00:00 2001 From: Martin Pluskal Date: Tue, 17 Nov 2026 14:58:55 +0100 Subject: [PATCH 2/2] build(deps): replace chrono with jiff chrono is unmaintained (RUSTSEC-2026-0543), and deny.toml fails on an unmaintained crate that a workspace crate depends on directly. Both crates did, for one type and three operations: an instant, parsing it, subtracting days from it and formatting it. jiff 0.2 covers those with its defaults switched off, so no time zone database comes along, and schemars emits the same `date-time` schema for jiff::Timestamp as for chrono's DateTime: `initialize` and `tools/list` are served byte-identical. Measured against chrono 0.4.45 with jiff 0.2.46, over 64 timestamp strings, a grid of day counts and 20,012 instants: - Parsing follows jiff's ISO 8601 grammar. It accepts strings chrono refused (no seconds, `+02`, a bracketed zone name) and refuses some chrono accepted (ten or more fractional digits, a Unicode minus, the last hours of year 9999; on the tool parameters also surrounding whitespace and unpadded fields). A second 60 reads as 59. Bugzilla's own shape reads as the same instant, and an unparsable `creation_time` is still unknown and fails closed (I4). - `age_cutoff` gives the same cutoff wherever both can represent it. jiff stops at year -9999 where chrono went some 262,000 years back; for a cutoff before that, both criteria reach the verdict they reached with chrono. A cutoff after year 9999 takes a negative count, which the loader now refuses; built past it, the matcher matches nothing. - The audit `ts` is byte-identical. So is the query string sent to Bugzilla from year 0000 on; before it jiff writes `-001` where chrono wrote `-0001`. - The reply to an unusable `new_since` or `changed_since` carries jiff's wording, which quotes the unparsed rest of the client's own string, escaped. At the default log level none of it is logged; under debug rmcp's `response message` line carries it, as it does for every parameter error. The two parameters' own log fields print fractions without trailing zeros. chrono stays in the dependency tree through rmcp, which depends on it and enables schemars' chrono04. bugwarden-core's public API takes jiff::Timestamp where it took chrono::DateTime, a breaking change for that crate: its next release has to be 0.8.0. --- Cargo.lock | 57 +++++++- crates/bugwarden-core/Cargo.toml | 2 +- crates/bugwarden-core/benches/guard.rs | 16 +- crates/bugwarden-core/src/client.rs | 22 +-- crates/bugwarden-core/src/guard.rs | 42 +++--- crates/bugwarden-core/src/policy.rs | 137 +++++++++++++++--- crates/bugwarden-core/tests/guard_wiremock.rs | 5 +- crates/bugwarden/Cargo.toml | 4 +- crates/bugwarden/src/audit.rs | 2 +- crates/bugwarden/src/server.rs | 8 +- docs/DESIGN.md | 48 ++++-- 11 files changed, 255 insertions(+), 88 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 355c79d..427eaf1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -223,12 +223,12 @@ dependencies = [ "axum", "base64 0.23.1", "bugwarden-core", - "chrono", "clap", "clap_complete", "clap_mangen", "futures-core", "http", + "jiff", "prost", "reqwest", "rmcp", @@ -253,8 +253,8 @@ name = "bugwarden-core" version = "0.7.1" dependencies = [ "anyhow", - "chrono", "iai-callgrind", + "jiff", "reqwest", "serde", "serde_json", @@ -318,10 +318,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" dependencies = [ "iana-time-zone", - "js-sys", "num-traits", "serde", - "wasm-bindgen", "windows-link", ] @@ -1097,6 +1095,41 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jiff" +version = "0.2.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175dc66334db3b9ab9985bf8b61cfed50dc16d20964bb47f9e479adcae984a7f" +dependencies = [ + "jiff-core", + "jiff-static", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", +] + +[[package]] +name = "jiff-core" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e599b80292e597019b8b3e392de3f4bea2959ddfb8c7dff60e035e9e311a2c1b" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-static" +version = "0.2.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7b1af7547d47354bc438d797e3854601bde8f8d185780c5ba4ab27afa54f1ba" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "jni" version = "0.22.4" @@ -1311,6 +1344,21 @@ version = "0.3.33" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + [[package]] name = "potential_utf" version = "0.1.5" @@ -1771,6 +1819,7 @@ checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" dependencies = [ "chrono", "dyn-clone", + "jiff", "ref-cast", "schemars_derive", "serde", diff --git a/crates/bugwarden-core/Cargo.toml b/crates/bugwarden-core/Cargo.toml index a1b0ceb..0402413 100644 --- a/crates/bugwarden-core/Cargo.toml +++ b/crates/bugwarden-core/Cargo.toml @@ -16,7 +16,7 @@ workspace = true [dependencies] anyhow = "1" -chrono = { version = "0.4.34", features = ["serde"] } +jiff = { version = "0.2.46", default-features = false, features = ["std"] } serde = { version = "1", features = ["derive"] } serde_json = "1" tokio = { version = "1", features = ["rt"] } diff --git a/crates/bugwarden-core/benches/guard.rs b/crates/bugwarden-core/benches/guard.rs index d39d232..8e4e18b 100644 --- a/crates/bugwarden-core/benches/guard.rs +++ b/crates/bugwarden-core/benches/guard.rs @@ -10,10 +10,10 @@ use std::hint::black_box; use bugwarden_core::guard::Guard; use bugwarden_core::policy::{BugMeta, Operation, Policy}; -use chrono::{DateTime, Utc}; use iai_callgrind::{ library_benchmark, library_benchmark_group, main, Callgrind, EventKind, LibraryBenchmarkConfig, }; +use jiff::Timestamp; use serde_json::{json, Value}; const POLICY: &str = r#" @@ -33,10 +33,8 @@ capabilities = ["summary"] products = ["SUSE*"] "#; -fn now() -> DateTime { - DateTime::parse_from_rfc3339("2026-01-15T00:00:00Z") - .expect("fixed instant") - .with_timezone(&Utc) +fn now() -> Timestamp { + "2026-01-15T00:00:00Z".parse().expect("fixed instant") } fn meta(product: Option<&str>, groups: Option<&[&str]>, creation: Option<&str>) -> BugMeta { @@ -51,11 +49,7 @@ fn meta(product: Option<&str>, groups: Option<&[&str]>, creation: Option<&str>) keywords: Some(vec![]), groups: groups.map(|g| g.iter().map(|s| (*s).to_owned()).collect()), whiteboard: Some(String::new()), - creation_time: creation.map(|s| { - DateTime::parse_from_rfc3339(s) - .expect("fixture time") - .with_timezone(&Utc) - }), + creation_time: creation.map(|s| s.parse().expect("fixture time")), created_by_me: Some(false), } } @@ -63,7 +57,7 @@ fn meta(product: Option<&str>, groups: Option<&[&str]>, creation: Option<&str>) struct ClassifyFix { policy: Policy, bug: BugMeta, - now: DateTime, + now: Timestamp, } fn classify_allow() -> ClassifyFix { diff --git a/crates/bugwarden-core/src/client.rs b/crates/bugwarden-core/src/client.rs index 86bb7c2..910f538 100644 --- a/crates/bugwarden-core/src/client.rs +++ b/crates/bugwarden-core/src/client.rs @@ -20,7 +20,7 @@ use std::sync::Arc; use std::time::{Duration, Instant}; use anyhow::{anyhow, bail, Result}; -use chrono::{DateTime, Utc}; +use jiff::Timestamp; use serde_json::Value; tokio::task_local! { @@ -351,12 +351,12 @@ impl BugzillaClient { &self, key: &str, id: u64, - new_since: Option>, + new_since: Option, ) -> Result { let path = format!("/bug/{id}/history"); let mut query: Vec<(&str, String)> = Vec::new(); if let Some(ts) = new_since { - query.push(("new_since", ts.format(TIMESTAMP_FORMAT).to_string())); + query.push(("new_since", ts.strftime(TIMESTAMP_FORMAT).to_string())); } let v = self.get_json(key, &path, &query).await?; Ok(v.get("bugs") @@ -374,12 +374,12 @@ impl BugzillaClient { &self, key: &str, id: u64, - new_since: Option>, + new_since: Option, ) -> Result> { let path = format!("/bug/{id}/comment"); let mut query: Vec<(&str, String)> = Vec::new(); if let Some(ts) = new_since { - query.push(("new_since", ts.format(TIMESTAMP_FORMAT).to_string())); + query.push(("new_since", ts.strftime(TIMESTAMP_FORMAT).to_string())); } let v = self.get_json(key, &path, &query).await?; let id_key = id.to_string(); @@ -422,7 +422,7 @@ impl BugzillaClient { include_fields: &str, limit: u32, offset: u32, - changed_since: Option>, + changed_since: Option, ) -> Result { let quicksearch = if status.is_empty() { query.to_string() @@ -437,7 +437,10 @@ impl BugzillaClient { ("order", "relevance".to_string()), ]; if let Some(ts) = changed_since { - params.push(("last_change_time", ts.format(TIMESTAMP_FORMAT).to_string())); + params.push(( + "last_change_time", + ts.strftime(TIMESTAMP_FORMAT).to_string(), + )); } self.get_json(key, "/bug", ¶ms).await } @@ -852,7 +855,6 @@ fn parse_response(status: reqwest::StatusCode, body: &str) -> Result { #[cfg(test)] mod tests { use super::*; - use chrono::TimeZone; use reqwest::StatusCode; /// Stands in for a real program's identity, naming neither this crate @@ -903,9 +905,9 @@ mod tests { #[test] fn timestamp_format_renders_utc_z() { - let ts = Utc.with_ymd_and_hms(2024, 1, 2, 3, 4, 5).unwrap(); + let ts: Timestamp = "2024-01-02T05:04:05.999+02:00".parse().unwrap(); assert_eq!( - ts.format(TIMESTAMP_FORMAT).to_string(), + ts.strftime(TIMESTAMP_FORMAT).to_string(), "2024-01-02T03:04:05Z" ); } diff --git a/crates/bugwarden-core/src/guard.rs b/crates/bugwarden-core/src/guard.rs index f795e87..72d5928 100644 --- a/crates/bugwarden-core/src/guard.rs +++ b/crates/bugwarden-core/src/guard.rs @@ -18,7 +18,7 @@ use std::collections::{BTreeMap, BTreeSet}; -use chrono::{DateTime, Utc}; +use jiff::Timestamp; use serde_json::{Map, Value}; use crate::client::{BugzillaClient, CLASSIFY_FIELDS}; @@ -85,7 +85,7 @@ pub struct SearchRequest<'a> { /// How many visible bugs to skip. pub offset: u32, /// Only bugs changed since then; narrows upstream rows. - pub changed_since: Option>, + pub changed_since: Option, } /// What one [`Guard::quicksearch_window`] scan produced: the window the @@ -175,7 +175,7 @@ impl Guard { if ids.is_empty() { return out; } - let now = Utc::now(); + let now = Timestamp::now(); // Classification objects fetched from Bugzilla, keyed by the id the // SERVER reported. Requested ids are only trusted when the response @@ -468,7 +468,7 @@ impl Guard { ids: &BTreeSet, caller: Option<&str>, ) -> BTreeSet { - let now = Utc::now(); + let now = Timestamp::now(); // Bug id 0 never exists, so an empty candidate set still costs one // request: otherwise "this bug has no links" and "every link is // hidden" would be told apart by the clock (I2). @@ -1264,7 +1264,7 @@ impl Guard { pub fn may_create(&self, requested: &mut Value) -> bool { normalize_create_request(requested); let mut meta = BugMeta::from_json(requested, None); - meta.creation_time = Some(Utc::now()); + meta.creation_time = Some(Timestamp::now()); // Bugzilla augments the group list server-side on creation; the // request's claim about it is not knowledge (see above). meta.groups = None; @@ -1283,7 +1283,7 @@ impl Guard { // Every other field the request does not mention is unknown, not // empty, and classification fails closed on it (I4). self.policy - .classify(&meta, Utc::now(), Operation::Create) + .classify(&meta, Timestamp::now(), Operation::Create) .allows(Capability::Create) } @@ -1394,7 +1394,7 @@ impl Guard { bugs: Vec, caller: Option<&str>, ) -> (Vec, Vec) { - let now = Utc::now(); + let now = Timestamp::now(); let mut kept = Vec::new(); let mut dropped = Vec::new(); for bug in bugs { @@ -3306,7 +3306,7 @@ products = ["NoView*"] ); assert!( g.policy - .classify(&public, Utc::now(), Operation::Access) + .classify(&public, Timestamp::now(), Operation::Access) .allows(Capability::Read), "existing desktop bugs must stay fully readable" ); @@ -3329,7 +3329,7 @@ products = ["NoView*"] assert!( matches!( g.policy - .classify(&restricted, Utc::now(), Operation::Access), + .classify(&restricted, Timestamp::now(), Operation::Access), Access::Denied { .. } ), "group-restricted desktop bugs must stay denied" @@ -3350,7 +3350,7 @@ products = ["NoView*"] assert!( matches!( g.policy - .classify(&own_restricted, Utc::now(), Operation::Access), + .classify(&own_restricted, Timestamp::now(), Operation::Access), Access::Denied { .. } ), "shipped policy denies the caller's own group-restricted bug too: \ @@ -3408,7 +3408,7 @@ products = ["NoView*"] assert!( matches!( g.policy - .classify(&restricted, Utc::now(), Operation::Access), + .classify(&restricted, Timestamp::now(), Operation::Access), Access::Denied { .. } ), "group-restricted bugs someone else filed must stay denied" @@ -3422,7 +3422,7 @@ products = ["NoView*"] let own_restricted = BugMeta::from_json(&own_restricted_json, caller); let own_access = g .policy - .classify(&own_restricted, Utc::now(), Operation::Access); + .classify(&own_restricted, Timestamp::now(), Operation::Access); for cap in [ Capability::Read, Capability::Comments, @@ -3463,7 +3463,8 @@ products = ["NoView*"] let unknown = BugMeta::from_json(bug_json, None); assert!( matches!( - g.policy.classify(&unknown, Utc::now(), Operation::Access), + g.policy + .classify(&unknown, Timestamp::now(), Operation::Access), Access::Denied { .. } ), "identity-unknown must deny (blackout), bug {}", @@ -3510,7 +3511,7 @@ products = ["NoView*"] let full = policy(&toml); assert!( matches!( - full.classify(&bug, Utc::now(), Operation::Access), + full.classify(&bug, Timestamp::now(), Operation::Access), Access::Denied { .. } ), "shipped policy must deny a security-group bug" @@ -3528,7 +3529,7 @@ products = ["NoView*"] .find("[[rule]]") .expect("a rule must follow the broad rule"); let narrowed = policy(&format!("{}{}", &toml[..start], &toml[end..])); - match narrowed.classify(&bug, Utc::now(), Operation::Access) { + match narrowed.classify(&bug, Timestamp::now(), Operation::Access) { Access::Denied { rule } => assert_eq!( rule, "security-groups", "the named-group rule itself must be the one denying" @@ -3560,14 +3561,14 @@ products = ["NoView*"] ); assert!( matches!( - full.classify(&partner, Utc::now(), Operation::Access), + full.classify(&partner, Timestamp::now(), Operation::Access), Access::Denied { .. } ), "shipped policy hides every restricted bug" ); assert!( matches!( - narrowed.classify(&partner, Utc::now(), Operation::Access), + narrowed.classify(&partner, Timestamp::now(), Operation::Access), Access::Granted { .. } ), "narrowing is meant to expose non-security restricted bugs" @@ -3925,7 +3926,10 @@ group_restricted = true }), None, ); - match g.policy.classify(&public, Utc::now(), Operation::Access) { + match g + .policy + .classify(&public, Timestamp::now(), Operation::Access) + { Access::Granted { rule, .. } => assert_eq!(rule, "default"), other => panic!("non-restricted bug must stay readable, got {other:?}"), } @@ -3945,7 +3949,7 @@ group_restricted = true ); match g .policy - .classify(&restricted, Utc::now(), Operation::Access) + .classify(&restricted, Timestamp::now(), Operation::Access) { Access::Denied { rule } => assert_eq!(rule, "group-restricted"), other => panic!("group-restricted bug must stay denied, got {other:?}"), diff --git a/crates/bugwarden-core/src/policy.rs b/crates/bugwarden-core/src/policy.rs index 9104e0f..d971e8f 100644 --- a/crates/bugwarden-core/src/policy.rs +++ b/crates/bugwarden-core/src/policy.rs @@ -49,7 +49,7 @@ use std::collections::BTreeSet; use std::path::Path; use anyhow::Context as _; -use chrono::{DateTime, Duration, Utc}; +use jiff::{SignedDuration, Timestamp}; use serde_json::Value; /// A capability a policy grant can carry. @@ -198,12 +198,13 @@ fn contains_any(needles: &[String], haystack: &str) -> bool { needles.iter().any(|n| hay.contains(&n.to_lowercase())) } -/// `now - days`, or `None` when the subtraction is not representable. +/// `now - days`, or `None` when that is outside representable time. /// -/// Callers must treat `None` as "the cutoff cannot be computed" and fail -/// closed (I4). -fn age_cutoff(now: DateTime, days: i64) -> Option> { - Duration::try_days(days).and_then(|d| now.checked_sub_signed(d)) +/// What `None` means is the caller's to say: the age quarantine denies +/// (I4), the matcher reads the sign of `days`. +fn age_cutoff(now: Timestamp, days: i64) -> Option { + let secs = days.checked_mul(86_400)?; + now.checked_sub(SignedDuration::from_secs(secs)).ok() } /// Bug-matching criteria of a rule. @@ -325,7 +326,7 @@ impl Matcher { /// be evaluated and yields [`MatchOutcome::Unknown`], unless some other /// criterion already ruled the bug out (a definitive `No` wins, because /// then the unreadable field cannot change the answer). - pub fn evaluate(&self, bug: &BugMeta, now: DateTime) -> MatchOutcome { + pub fn evaluate(&self, bug: &BugMeta, now: Timestamp) -> MatchOutcome { let mut unknown = false; // Globs against a single value. @@ -414,12 +415,15 @@ impl Matcher { match (bug.creation_time, age_cutoff(now, days)) { // Age unreadable: undecidable like any other missing field. (None, _) => unknown = true, - // Cutoff not representable: the window covers all of - // representable time, so every bug counts as young. + // Cutoff after all representable time, which takes a + // negative count: no bug is younger than that. + (Some(_), None) if days.is_negative() => return MatchOutcome::No, + // Cutoff before all representable time: the window covers + // all of it, so every bug counts as young. (Some(_), None) => {} (Some(ct), Some(cutoff)) => { if ct <= cutoff { - // Strictly older than N days => not "younger than". + // N days old or older => not "younger than". return MatchOutcome::No; } } @@ -946,7 +950,7 @@ impl Policy { /// /// Every grant — from a rule or from the default — has write capabilities /// stripped when `global.read_only` is set. - pub fn classify(&self, bug: &BugMeta, now: DateTime, op: Operation) -> Access { + pub fn classify(&self, bug: &BugMeta, now: Timestamp, op: Operation) -> Access { if self.global.min_bug_age_days > 0 { let too_young = match ( bug.creation_time, @@ -1079,7 +1083,7 @@ pub struct BugMeta { /// Whiteboard text. pub whiteboard: Option, /// Creation time; `None` when absent or unparsable. - pub creation_time: Option>, + pub creation_time: Option, /// Whether the requesting account authored this bug. `Some(true/false)` /// is an established relationship; `None` means it cannot be known — /// the bug's `creator` was unreadable, OR the caller's identity was not @@ -1170,8 +1174,7 @@ impl BugMeta { creation_time: v .get("creation_time") .and_then(Value::as_str) - .and_then(|s| DateTime::parse_from_rfc3339(s).ok()) - .map(|dt| dt.with_timezone(&Utc)), + .and_then(|s| s.parse::().ok()), created_by_me: match (caller, str_field(v, "creator")) { (Some(login), Some(creator)) => { Some(login.to_lowercase() == creator.to_lowercase()) @@ -1229,12 +1232,12 @@ mod tests { use super::*; use serde_json::json; - fn t(s: &str) -> DateTime { - DateTime::parse_from_rfc3339(s).unwrap().with_timezone(&Utc) + fn t(s: &str) -> Timestamp { + s.parse().unwrap() } /// Fixed "now" so age arithmetic is deterministic. - fn now() -> DateTime { + fn now() -> Timestamp { t("2026-01-15T12:00:00Z") } @@ -1817,13 +1820,74 @@ mod tests { } #[test] - fn matcher_younger_than_days_huge_value_fails_closed() { - // Unrepresentable cutoff => every bug counts as young. - let m = Matcher { - younger_than_days: Some(i64::MAX), + fn matcher_younger_than_days_before_all_time_matches_every_bug() { + // A cutoff before representable time, by subtraction or by seconds + // that overflow an i64: every bug with an age counts as young. + for days in [4_392_055, 5_000_000, i64::MAX] { + let m = Matcher { + younger_than_days: Some(days), + ..Default::default() + }; + let mut bug = meta(); + for ct in [t("2025-06-01T00:00:00Z"), Timestamp::MIN] { + bug.creation_time = Some(ct); + assert!(m.evaluate(&bug, now()).is_yes(), "{days}"); + } + } + } + + #[test] + fn matcher_negative_younger_than_days_matches_only_past_its_cutoff() { + // No policy file gets here (validate refuses the sign); the public + // struct does. The cutoff then lies in the future. + let matcher = |days| Matcher { + younger_than_days: Some(days), ..Default::default() }; - assert!(m.evaluate(&meta(), now()).is_yes()); + let mut bug = meta(); + assert_eq!(matcher(-1).evaluate(&bug, now()), MatchOutcome::No); + bug.creation_time = Some(t("2026-01-17T12:00:00Z")); + assert!(matcher(-1).evaluate(&bug, now()).is_yes()); + bug.creation_time = None; + assert_eq!(matcher(-1).evaluate(&bug, now()), MatchOutcome::Unknown); + // Past representable time nothing is younger, not everything. + for days in [-5_000_000, i64::MIN] { + bug.creation_time = Some(Timestamp::MAX); + assert_eq!(matcher(days).evaluate(&bug, now()), MatchOutcome::No); + bug.creation_time = None; + assert_eq!(matcher(days).evaluate(&bug, now()), MatchOutcome::Unknown); + } + } + + #[test] + fn age_cutoff_is_none_outside_representable_time() { + assert_eq!(age_cutoff(now(), 0), Some(now())); + assert_eq!(age_cutoff(now(), 7), Some(t("2026-01-08T12:00:00Z"))); + assert_eq!(age_cutoff(now(), -1), Some(t("2026-01-16T12:00:00Z"))); + let half = t("2026-01-15T12:00:00.5Z"); + assert_eq!(age_cutoff(half, 7), Some(t("2026-01-08T12:00:00.5Z"))); + // The last count that can still be subtracted from this `now`, one + // more, and one whose seconds overflow an i64; then the future. + assert!(age_cutoff(now(), 4_392_054).is_some()); + for days in [4_392_055, i64::MAX, -5_000_000, i64::MIN] { + assert_eq!(age_cutoff(now(), days), None, "{days}"); + } + } + + #[test] + fn classify_min_bug_age_unrepresentable_cutoff_fails_closed() { + for days in [4_392_055, 5_000_000, i64::MAX] { + let toml = format!("[global]\nmin_bug_age_days = {days}\n"); + let p = Policy::from_toml_str(&toml).unwrap(); + let mut bug = meta(); + for ct in [t("2025-01-01T00:00:00Z"), Timestamp::MIN] { + bug.creation_time = Some(ct); + match p.classify(&bug, now(), Operation::Access) { + Access::Denied { rule } => assert_eq!(rule, "min_bug_age_days"), + other => panic!("no cutoff must deny (I4), got {other:?} for {days}"), + } + } + } } // ---------- Policy parsing + validation ---------- @@ -3434,6 +3498,35 @@ capabilities = ["summary", "create", "attach"] assert!(m.creation_time.is_none()); } + #[test] + fn bugmeta_creation_time_is_the_instant_or_nothing() { + let read = |s: &str| BugMeta::from_json(&json!({"creation_time": s}), None).creation_time; + // Bugzilla's own shape, checked against the epoch and not the parser. + let filed = Timestamp::from_second(1_411_499_537).unwrap(); + assert_eq!(read("2014-09-23T19:12:17Z"), Some(filed)); + assert_eq!(read("2014-09-23T21:12:17+02:00"), Some(filed)); + assert_eq!(read("2014-09-23T17:12:17-02:00"), Some(filed)); + let half = Timestamp::new(1_411_499_537, 500_000_000).unwrap(); + assert_eq!(read("2014-09-23T19:12:17.5Z"), Some(half)); + // jiff has no leap second: a second 60 reads as the 59th. + let last = Timestamp::from_second(1_411_499_579).unwrap(); + assert_eq!(read("2014-09-23T19:12:60Z"), Some(last)); + // No instant without an offset, a time or a clean string, and none + // from another notation. + for s in [ + "2014-09-23T19:12:17", + "2014-09-23", + "2014-09-23T19:12:17Z ", + " 2014-09-23T19:12:17Z", + "", + "Tue, 23 Sep 2014 19:12:17 GMT", + "2014-266T19:12:17Z", + "2014-W39-2T19:12:17Z", + ] { + assert_eq!(read(s), None, "{s:?}"); + } + } + #[test] fn bugmeta_status_whiteboard_fallback() { let m = BugMeta::from_json(&json!({"status_whiteboard": "legacy"}), None); diff --git a/crates/bugwarden-core/tests/guard_wiremock.rs b/crates/bugwarden-core/tests/guard_wiremock.rs index 2e043f7..5e6ccbf 100644 --- a/crates/bugwarden-core/tests/guard_wiremock.rs +++ b/crates/bugwarden-core/tests/guard_wiremock.rs @@ -130,9 +130,8 @@ groups = ["*security*", "*embargo*"] #[tokio::test] async fn assess_min_bug_age_denies_young_and_missing_creation_time() { let server = MockServer::start().await; - let now = chrono::Utc::now(); - let young = (now - chrono::Duration::days(1)) - .format("%Y-%m-%dT%H:%M:%SZ") + let young = (jiff::Timestamp::now() - jiff::SignedDuration::from_hours(24)) + .strftime("%Y-%m-%dT%H:%M:%SZ") .to_string(); Mock::given(method("GET")) .and(path("/rest/bug")) diff --git a/crates/bugwarden/Cargo.toml b/crates/bugwarden/Cargo.toml index d1e8100..317307d 100644 --- a/crates/bugwarden/Cargo.toml +++ b/crates/bugwarden/Cargo.toml @@ -69,8 +69,8 @@ serde_json = "1" # Attachment windowing decodes the base64 Bugzilla serves. Already in the # lock file through rmcp; this makes the dependency the one it is used as. base64 = "0.23.1" -schemars = { version = "1", features = ["chrono04"] } -chrono = { version = "0.4", features = ["serde"] } +schemars = { version = "1", features = ["jiff02"] } +jiff = { version = "0.2.46", default-features = false, features = ["std", "serde"] } sha2 = "0.11" # Constant-time byte comparison for the HTTP bearer tokens. Already in the # lock file through rustls; this makes the dependency the one it is used as. diff --git a/crates/bugwarden/src/audit.rs b/crates/bugwarden/src/audit.rs index e45c74d..2dea999 100644 --- a/crates/bugwarden/src/audit.rs +++ b/crates/bugwarden/src/audit.rs @@ -1440,7 +1440,7 @@ impl AuditSink { let seq = state.seq + 1; let event = AuditEvent { v: SCHEMA_VERSION, - ts: chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true), + ts: format!("{:.3}", jiff::Timestamp::now()), seq, session, kind, diff --git a/crates/bugwarden/src/server.rs b/crates/bugwarden/src/server.rs index 12508a1..95eefa6 100644 --- a/crates/bugwarden/src/server.rs +++ b/crates/bugwarden/src/server.rs @@ -23,7 +23,7 @@ use bugwarden_core::custom_fields::{ use bugwarden_core::guard::{Guard, SearchRequest, SearchWindow}; use bugwarden_core::policy::{Access, Action, Capability, IdentitySource}; use bugwarden_core::quoted::QuotedError; -use chrono::{DateTime, Utc}; +use jiff::Timestamp; use rmcp::{ handler::server::{router::tool::ToolRouter, tool::ToolCallContext, wrapper::Parameters}, model::*, @@ -2794,7 +2794,7 @@ pub struct BugHistoryParams { pub id: u64, /// Only return history newer than this date. #[serde(default)] - pub new_since: Option>, + pub new_since: Option, /// Keep only the first N history entries. #[serde(default)] pub head: Option, @@ -2812,7 +2812,7 @@ pub struct BugCommentsParams { pub include_private: bool, /// Only return comments newer than this date. #[serde(default)] - pub new_since: Option>, + pub new_since: Option, /// Keep the first N comments (comment 0 is the report — keep it in /// the window on large threads). #[serde(default)] @@ -2858,7 +2858,7 @@ pub struct QuicksearchParams { pub offset: u32, /// Only return bugs changed since this date. #[serde(default)] - pub changed_since: Option>, + pub changed_since: Option, /// Optional comma-separated list of fields to group the results by: /// product, component, status, resolution, severity, priority. Omit it /// (or send an empty string) for a flat `{"bugs": [...]}` response. diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 1ec0de2..9e05b89 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -354,7 +354,7 @@ impl Matcher { // rule (allow, or restrict under a denying default) may neither grant nor // be skipped, since skipping would fall through to a later granting rule // or an allowing default. "Present but empty" is knowledge, not Unknown. - pub fn evaluate(&self, bug: &BugMeta, now: chrono::DateTime) -> MatchOutcome; + pub fn evaluate(&self, bug: &BugMeta, now: jiff::Timestamp) -> MatchOutcome; } #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)] @@ -437,7 +437,7 @@ impl Policy { // otherwise silently lose both the intended filing grant and the reads // the capability list withholds). Unknown operation names are rejected // by serde. - pub fn classify(&self, bug: &BugMeta, now: chrono::DateTime, op: Operation) -> Access; + pub fn classify(&self, bug: &BugMeta, now: jiff::Timestamp, op: Operation) -> Access; // Whether any rule consulted for Operation::Access carries a // created_by_me criterion — the laziness gate for whoami (see // "Identity resolution"). A rule scoped to ONLY `create` does not @@ -472,7 +472,7 @@ pub struct BugMeta { pub keywords: Option>, pub groups: Option>, // group names; Some(vec![]) = world-readable pub whiteboard: Option, // "whiteboard", falling back to "status_whiteboard" - pub creation_time: Option>, + pub creation_time: Option, // Some(true/false) = established bug–caller relationship; None = it // cannot be known (creator unreadable OR caller identity unresolved). pub created_by_me: Option, @@ -537,7 +537,7 @@ impl Guard { // SearchWindow together with the scan's accounting (issue #29) — // server-side only (I3), for the audit record; the client response is // built from `bugs` alone. - pub struct SearchRequest<'a> { query, status, include_fields: &'a str, limit, offset: u32, changed_since: Option> } + pub struct SearchRequest<'a> { query, status, include_fields: &'a str, limit, offset: u32, changed_since: Option } pub struct SearchWindow { bugs: Vec, scanned: u32, dropped: Vec } pub const MAX_SEARCH_WINDOW: u32; @@ -761,12 +761,12 @@ impl BugzillaClient { pub async fn valid_login(&self, key: &str, login: &str) -> anyhow::Result; // {"result": bool} or bare bool; any other shape = error, never false pub async fn server_info(&self, key: &str) -> anyhow::Result; pub async fn get_bugs(&self, key: &str, ids: &[u64], include_fields: Option<&str>) -> anyhow::Result; - pub async fn bug_history(&self, key: &str, id: u64, new_since: Option>) -> anyhow::Result; - pub async fn bug_comments(&self, key: &str, id: u64, new_since: Option>) -> anyhow::Result>; + pub async fn bug_history(&self, key: &str, id: u64, new_since: Option) -> anyhow::Result; + pub async fn bug_comments(&self, key: &str, id: u64, new_since: Option) -> anyhow::Result>; pub async fn add_comment(&self, key: &str, id: u64, comment: &str, is_private: bool) -> anyhow::Result; pub async fn create_bug(&self, key: &str, payload: serde_json::Value) -> anyhow::Result; pub async fn add_attachment(&self, key: &str, id: u64, payload: serde_json::Value) -> anyhow::Result; - pub async fn quicksearch(&self, key: &str, query: &str, status: &str, include_fields: &str, limit: u32, offset: u32, changed_since: Option>) -> anyhow::Result; + pub async fn quicksearch(&self, key: &str, query: &str, status: &str, include_fields: &str, limit: u32, offset: u32, changed_since: Option) -> anyhow::Result; pub async fn update_bug(&self, key: &str, id: u64, payload: serde_json::Value) -> anyhow::Result; pub async fn attachments(&self, key: &str, id: u64) -> anyhow::Result; pub async fn quicksearch_syntax_html(&self) -> anyhow::Result; @@ -1362,9 +1362,9 @@ constraints the model must know. | tool | params (schemars struct) | guard capability | notes | |---|---|---|---| | bug_info | bug_ids: Vec, include_fields?: String (comma-separated; `id` is always included), detail?: bool — mutually exclusive | per-id: Read => full, else Summary => redacted, else restricted entry | envelope `{"bugs":[..], "restricted":[{"id":N,"note":denial(N)}]}`; full fetch only for Read-granted ids. Every fetched body is RE-CLASSIFIED before it is served (assemble_bug_info): the verdict came from the classification fetch and the body from a later request, so a bug embargoed in between must not be served on the stale verdict (TOCTOU; same reason download_attachment re-checks). Costs no request — the body is a superset of CLASSIFY_FIELDS — and a body that now earns only summary is served as the summary view, one that earns nothing becomes the uniform restricted entry. A failed body fetch is logged server-side ONLY and leaves those ids restricted: Bugzilla's message names the bug and says whether it exists, so forwarding it would undo I2. The optional projection (`include_fields` via project_fields, `_redacted`-preserving; or `detail=false` dropping every `*_detail` key, which duplicate the plain account fields with real_name/id/email expanded — measured 44-48% of a full bug's serialized size — and `comment_count` dropped on every path, projected or full (I5)) is the LAST step before serving, applied to the re-checked bodies after the verdict (I4/I8) and before link scrubbing: a field not served is never assessed, and the `restricted` entries are never projected (I2) | -| bug_history | id, new_since?: DateTime, head?: u32, tail?: u32 | history | a history recording a change to a `cf_` field first learns those fields' kinds (`FieldTypeCache::kinds`, cache-first, with no request when the history names no `cf_` field — see "Custom field types") so a Bug ID custom field change is scrubbed like a `depends_on` one and a free-text field's digits are left alone (I14; a failed lookup reads the field leniently, which only narrows what is served); head/tail window the SCRUBBED history (first/last N entries; head + tail >= the entry count keeps everything): with either set the response is an envelope `{"history": [...], "truncation": {"omitted_entries": N, "shown_entries": M}}` instead of the bare array; a window that actually omits entries is audited as a `history_window` redaction, which PRESERVES the granting rule (the client asked for less; no rule decided it — see "The `guard.rule` encoding"). The window runs on the post-scrub (I14) list — `omitted_entries` counts only entries the client may see, so a scrub-dropped entry cannot leak by arithmetic (I3). `head: 0` / `tail: 0` omit everything; a zero is a window of zero entries, never "no limit" (absent is the only "no limit"). Documented exception: a non-array `history` from upstream is served unchanged and WITHOUT the envelope — a presentation control must not drop an odd shape; `Guard::scrub_history` likewise early-returns on a non-array, so that shape is unscrubbed (pre-existing) | +| bug_history | id, new_since?: jiff::Timestamp, head?: u32, tail?: u32 | history | a history recording a change to a `cf_` field first learns those fields' kinds (`FieldTypeCache::kinds`, cache-first, with no request when the history names no `cf_` field — see "Custom field types") so a Bug ID custom field change is scrubbed like a `depends_on` one and a free-text field's digits are left alone (I14; a failed lookup reads the field leniently, which only narrows what is served); head/tail window the SCRUBBED history (first/last N entries; head + tail >= the entry count keeps everything): with either set the response is an envelope `{"history": [...], "truncation": {"omitted_entries": N, "shown_entries": M}}` instead of the bare array; a window that actually omits entries is audited as a `history_window` redaction, which PRESERVES the granting rule (the client asked for less; no rule decided it — see "The `guard.rule` encoding"). The window runs on the post-scrub (I14) list — `omitted_entries` counts only entries the client may see, so a scrub-dropped entry cannot leak by arithmetic (I3). `head: 0` / `tail: 0` omit everything; a zero is a window of zero entries, never "no limit" (absent is the only "no limit"). Documented exception: a non-array `history` from upstream is served unchanged and WITHOUT the envelope — a presentation control must not drop an odd shape; `Guard::scrub_history` likewise early-returns on a non-array, so that shape is unscrubbed (pre-existing) | | bug_comments | id, include_private: bool = false, new_since?, head?: u32, tail?: u32, max_comment_chars?: u32 | comments | filter_comments applied (I5). Optional windowing: with ANY of head/tail/max_comment_chars set the response is an envelope `{"comments":[..], "truncation":{"omitted_comments":N,"shown_comments":M}}`, else the bare array it always was. Windowing runs LAST, on the post-filter (I5), post-duplicate-marker-scrub (I14) list — `omitted_comments` counts only comments the client may see, so private-comment existence cannot leak by arithmetic. head keeps the first N (comment 0 is the report), tail the last N; overlap keeps everything and omits nothing. A comment capped by max_comment_chars carries a sibling `text_truncated: {"shown_chars","total_chars"}` — never an in-text marker, which free-form comment text would absorb. The name is max_comment_chars, not download_attachment's max_chars, on purpose: same unit, different scope — this caps EACH comment, that caps the WHOLE response — so do not converge the two into one name. summarize_bug is deliberately NOT windowed (its prompt needs every comment). Audit: `note_redacted_client_window("comments_window")` when omission or a cap actually fired — that note PRESERVES the granting rule, unlike the I5 suppression noted beside it (see "The `guard.rule` encoding") | -| bugs_quicksearch | query, status: String = "ALL", include_fields: String = "id,product,component,assigned_to,status,resolution,summary,last_change_time", limit: u32 = 50, offset: u32 = 0, changed_since?: DateTime, group_by?: String | post-filter | fetch include_fields = requested ∪ CLASSIFY_FIELDS; optional `changed_since` narrows upstream rows to bugs changed since then (Bugzilla `last_change_time`), so an unchanged watch costs exactly one scan request and classifies zero rows while the guard still classifies every returned row with no counts leaving the server (#315); after filter, project kept bugs to requested fields (keep `_redacted` marker; `comment_count` always dropped, I5); envelope `{"bugs":[..]}` — or `{"groups":[..]}` under `group_by`, see below — only (I3), except an advisory `note` when the query is nothing but bug ids (comma/whitespace-separated, optional `#` per id) steering exact id sets to bug_info — the note is a pure function of the CLIENT'S REQUEST (the query and status strings), never of results, verdicts, or anything upstream said (no new oracle), and the `bugs` array is byte-identical with or without it (the query is still searched, never rerouted); its wording tracks the request: a non-empty status is prefixed to the query so upstream content-matches the whole expression, while an empty status sends the query bare and Bugzilla routes a bare all-number query to an exact id lookup (bug_id + anyexact) — on that path the note drops the content-matching claim — and a query naming more distinct ids than MAX_ASSESS_IDS steers to batched bug_info calls (the cap is already public in the too_many_ids refusal text) instead of straight into that refusal | **limit/offset address the bugs the client may SEE, not upstream rows** (Guard::quicksearch_window): filtering an already-paginated page left a hole exactly where a hidden bug sat — a short page the next offset contradicted — and since quicksearch matches summary text that hole was a probe for the hidden title, one word at a time. The guard now scans upstream from row 0 in 200-row chunks, classifies each, and fills the window from the survivors; rows are deduped on the server-reported id (relevance order is not stable between calls) and an id-less row is dropped (I4). A short page is NOT read as end-of-results — Bugzilla is free to cap a page below the requested chunk size (an admin-configured `max_search_results`, for instance), and that cap looks identical to a short page at the genuine end of a result set; only an empty page ends the scan early. Bounds, independent of each other: MAX_SEARCH_WINDOW=1000 addressable, 2000 rows scanned, and 10 sequential requests; hitting any of the three truncates, which looks exactly like the end of results. `limit` is honoured up to MAX_SEARCH_WINDOW and silently clamped above; prefer one call with a large `limit` and a lean `include_fields` over an offset walk — the walk re-scans from row zero, so one large call costs the server no more than the last page of the walk and the client one turn instead of N+1; a page short of `limit` is not the end of results. The objects returned are the ones classified. The scan target is quantised to whole chunks so the stopping point does not track the client's `limit`; without that, `limit` could be binary-searched against the clock to recover each block's exact hidden count. Residual, accepted: filling a window of VISIBLE bugs needs more rows when bugs are hidden, so a stopwatch still learns one bit per scanned block ("not entirely visible"). Removing that would mean scanning the worst case on every search, or letting pages go short again. Search failure returns a bare "Search failed"; the upstream text is logged server-side only (it can name a bug and say whether it exists). The scan's accounting — rows examined, verdict-dropped ids — goes to the audit record only (`guard.scan` plus the suppressed-ids machinery, issue #29); the response is byte-identical with or without drops. Optional `group_by` (issue #143): a comma-separated subset of GROUP_BY_FIELDS = product, component, status, resolution, severity, priority, deduped, unknown name refused BEFORE the upstream call (a silently ungrouped typo looks like a broken feature; the text quotes only what the client sent, so it is no oracle) while a spec naming NOTHING (`""`, bare commas) means "no grouping" rather than an error — that is what a client filling in every declared param sends, and the sibling `include_fields` reads an empty segment the same way. The response becomes `{"groups":[{"bugs":[..], :, ..}]}` and each grouped field is reported once per group instead of once per bug. Header key order is NOT caller order and is not promised anywhere client-facing: serde_json is built without `preserve_order`, so its Map is a BTreeMap and a header serializes with keys sorted, `bugs` first — `group_by=status,product` and `product,status` return identical bytes. GROUP_BY_FIELDS is a HAND-PICKED subset of the CLASSIFY_FIELDS ∩ SUMMARY_FIELDS intersection (which is all ten SUMMARY_FIELDS), restricted to low-cardinality enum-ish values; that membership is what makes grouping free of policy consequences — no extra upstream field is pulled, and a summary-redacted row carries all six so it buckets like any other row instead of needing one of its own. Membership is NOT the I14 argument: the same intersection holds `summary`, which routinely reads "regression from bug 12345". What keeps a header clean is ORDERING — a grouped field is FORCED into `requested` the way `id` is, so grouping runs on the served, link-scrubbed projection, a value can only reach a header by the same path that would have put it on the bug, and grouping never surfaces a field the projection dropped. Group order and within-group order are first appearance in the served window, so grouping cannot reorder by verdict, and a group exists only where a served bug put it: no empty buckets, no header naming a hidden bug's product (I3). It runs LAST, after the audit block has read the flat projection, so a call's record is identical whether or not the client asked for groups; `group_by` is in PARAM_ALLOWLIST (a vocabulary field, not free text) so the record carries it verbatim. The envelope key is `groups`, deliberately the same word as Bugzilla's per-bug `groups` security-group list which a client may project into the bugs nested inside it — parallel to `bugs` at the same level, and depth disambiguates; do not rename one to "fix" the collision without also moving the other. Predicate gate (#337): after group_by validation and before any request the query and the status prefix are tokenized quote-aware (double quotes always, single quotes only at word boundaries, backslash escapes; unbalanced refuses; split on Perl whitespace including vertical tab and form feed): bare terms, quoted phrases, `#`-id lists with `#` optional per comma piece, `P`-shorthands and exact (never prefix) predicates over product, component, status, resolution, severity, priority, summary (`short_desc` spelling included) pass — a field name in parens groups rather than names, so surrounding parens trim before the allowlist — everything else is refused with a fixed per-class text at zero requests — link (`depends_on`/`blocked`/`dupe`/`see_also`/`cf_*`), content (`comment`/`description`/`longdesc`), attachment, visibility (`group`/`flag`/`requestee`/`setter`), `# : @ [ ! ?` shortcuts (one leading `-` negates one comma piece, judged after the strip), mapping aliases of refused targets, unknown names and unbalanced quotes. A pseudo-quoted predicate is not a phrase. Masking allocation rides the transport body cap, so no separate query length cap. A pure request function, so hidden rows cannot move it; assignee-ish fields, keywords and whiteboard stay out because summary rows do not carry them | +| bugs_quicksearch | query, status: String = "ALL", include_fields: String = "id,product,component,assigned_to,status,resolution,summary,last_change_time", limit: u32 = 50, offset: u32 = 0, changed_since?: jiff::Timestamp, group_by?: String | post-filter | fetch include_fields = requested ∪ CLASSIFY_FIELDS; optional `changed_since` narrows upstream rows to bugs changed since then (Bugzilla `last_change_time`), so an unchanged watch costs exactly one scan request and classifies zero rows while the guard still classifies every returned row with no counts leaving the server (#315); after filter, project kept bugs to requested fields (keep `_redacted` marker; `comment_count` always dropped, I5); envelope `{"bugs":[..]}` — or `{"groups":[..]}` under `group_by`, see below — only (I3), except an advisory `note` when the query is nothing but bug ids (comma/whitespace-separated, optional `#` per id) steering exact id sets to bug_info — the note is a pure function of the CLIENT'S REQUEST (the query and status strings), never of results, verdicts, or anything upstream said (no new oracle), and the `bugs` array is byte-identical with or without it (the query is still searched, never rerouted); its wording tracks the request: a non-empty status is prefixed to the query so upstream content-matches the whole expression, while an empty status sends the query bare and Bugzilla routes a bare all-number query to an exact id lookup (bug_id + anyexact) — on that path the note drops the content-matching claim — and a query naming more distinct ids than MAX_ASSESS_IDS steers to batched bug_info calls (the cap is already public in the too_many_ids refusal text) instead of straight into that refusal | **limit/offset address the bugs the client may SEE, not upstream rows** (Guard::quicksearch_window): filtering an already-paginated page left a hole exactly where a hidden bug sat — a short page the next offset contradicted — and since quicksearch matches summary text that hole was a probe for the hidden title, one word at a time. The guard now scans upstream from row 0 in 200-row chunks, classifies each, and fills the window from the survivors; rows are deduped on the server-reported id (relevance order is not stable between calls) and an id-less row is dropped (I4). A short page is NOT read as end-of-results — Bugzilla is free to cap a page below the requested chunk size (an admin-configured `max_search_results`, for instance), and that cap looks identical to a short page at the genuine end of a result set; only an empty page ends the scan early. Bounds, independent of each other: MAX_SEARCH_WINDOW=1000 addressable, 2000 rows scanned, and 10 sequential requests; hitting any of the three truncates, which looks exactly like the end of results. `limit` is honoured up to MAX_SEARCH_WINDOW and silently clamped above; prefer one call with a large `limit` and a lean `include_fields` over an offset walk — the walk re-scans from row zero, so one large call costs the server no more than the last page of the walk and the client one turn instead of N+1; a page short of `limit` is not the end of results. The objects returned are the ones classified. The scan target is quantised to whole chunks so the stopping point does not track the client's `limit`; without that, `limit` could be binary-searched against the clock to recover each block's exact hidden count. Residual, accepted: filling a window of VISIBLE bugs needs more rows when bugs are hidden, so a stopwatch still learns one bit per scanned block ("not entirely visible"). Removing that would mean scanning the worst case on every search, or letting pages go short again. Search failure returns a bare "Search failed"; the upstream text is logged server-side only (it can name a bug and say whether it exists). The scan's accounting — rows examined, verdict-dropped ids — goes to the audit record only (`guard.scan` plus the suppressed-ids machinery, issue #29); the response is byte-identical with or without drops. Optional `group_by` (issue #143): a comma-separated subset of GROUP_BY_FIELDS = product, component, status, resolution, severity, priority, deduped, unknown name refused BEFORE the upstream call (a silently ungrouped typo looks like a broken feature; the text quotes only what the client sent, so it is no oracle) while a spec naming NOTHING (`""`, bare commas) means "no grouping" rather than an error — that is what a client filling in every declared param sends, and the sibling `include_fields` reads an empty segment the same way. The response becomes `{"groups":[{"bugs":[..], :, ..}]}` and each grouped field is reported once per group instead of once per bug. Header key order is NOT caller order and is not promised anywhere client-facing: serde_json is built without `preserve_order`, so its Map is a BTreeMap and a header serializes with keys sorted, `bugs` first — `group_by=status,product` and `product,status` return identical bytes. GROUP_BY_FIELDS is a HAND-PICKED subset of the CLASSIFY_FIELDS ∩ SUMMARY_FIELDS intersection (which is all ten SUMMARY_FIELDS), restricted to low-cardinality enum-ish values; that membership is what makes grouping free of policy consequences — no extra upstream field is pulled, and a summary-redacted row carries all six so it buckets like any other row instead of needing one of its own. Membership is NOT the I14 argument: the same intersection holds `summary`, which routinely reads "regression from bug 12345". What keeps a header clean is ORDERING — a grouped field is FORCED into `requested` the way `id` is, so grouping runs on the served, link-scrubbed projection, a value can only reach a header by the same path that would have put it on the bug, and grouping never surfaces a field the projection dropped. Group order and within-group order are first appearance in the served window, so grouping cannot reorder by verdict, and a group exists only where a served bug put it: no empty buckets, no header naming a hidden bug's product (I3). It runs LAST, after the audit block has read the flat projection, so a call's record is identical whether or not the client asked for groups; `group_by` is in PARAM_ALLOWLIST (a vocabulary field, not free text) so the record carries it verbatim. The envelope key is `groups`, deliberately the same word as Bugzilla's per-bug `groups` security-group list which a client may project into the bugs nested inside it — parallel to `bugs` at the same level, and depth disambiguates; do not rename one to "fix" the collision without also moving the other. Predicate gate (#337): after group_by validation and before any request the query and the status prefix are tokenized quote-aware (double quotes always, single quotes only at word boundaries, backslash escapes; unbalanced refuses; split on Perl whitespace including vertical tab and form feed): bare terms, quoted phrases, `#`-id lists with `#` optional per comma piece, `P`-shorthands and exact (never prefix) predicates over product, component, status, resolution, severity, priority, summary (`short_desc` spelling included) pass — a field name in parens groups rather than names, so surrounding parens trim before the allowlist — everything else is refused with a fixed per-class text at zero requests — link (`depends_on`/`blocked`/`dupe`/`see_also`/`cf_*`), content (`comment`/`description`/`longdesc`), attachment, visibility (`group`/`flag`/`requestee`/`setter`), `# : @ [ ! ?` shortcuts (one leading `-` negates one comma piece, judged after the strip), mapping aliases of refused targets, unknown names and unbalanced quotes. A pseudo-quoted predicate is not a phrase. Masking allocation rides the transport body cap, so no separate query length cap. A pure request function, so hidden rows cannot move it; assignee-ish fields, keywords and whiteboard stay out because summary rows do not carry them | | create_bug | product, component, summary, version, description = "", severity?, priority?, op_sys?, platform?, keywords?: Vec, groups?: Vec, custom_fields?: JsonObject | create (write), judged on the prospective bug AS IT WILL BE FILED (Guard::may_create) | there is no bug id to assess, so the request itself is classified BEFORE any upstream call (I8): the rules that hide a product by name refuse filing into it, a field the request omits fails closed (I4), and a client-claimed `groups` list is never trusted — Bugzilla unions the product's mandatory groups in server-side, so may_create forces groups to unknown, which means a group-consulting rule refuses every create request that REACHES it — creation is possible only where an earlier rule covering the create operation grants it (a rule carrying `operations = ["create"]`, placed ahead of the group-consulting rules, is how an operator permits filing without that grant shadowing reads of existing bugs — issue #26), and a policy with no such grant refuses all creation. **Judged is filed.** Bugzilla rewrites a create request before it resolves anything: it trims names (Perl `\s`), turns every run of ASCII control characters in the summary into one space and trims it (`clean_text`), and skips a keyword that is `""` or `"0"` — testing that falsiness on the RAW element, before the trim it applies to the ones it goes on to resolve. Judged raw, `product: " Security Response"` walked past a `products = ["Security*"]` deny rule into the grant behind it and was filed into Security Response all the same. So `may_create` rewrites the payload the same way IN PLACE, classifies the rewrite, and create_bug POSTs that very object — the rewritten names are ones Bugzilla's own trim leaves alone, so the name Bugzilla looks up is the name that was judged; which object that lookup returns, and whether the priority survives, are the two limits below. The NAME trim is deliberately a SUPERSET of Bugzilla's: Unicode White_Space plus U+180E, which Perl counted as `\s` until 5.20 and Rust's `is_whitespace` does not — that arm is load-bearing, not decoration. A superset is safe only because the POST carries the trimmed value and a name resolves to its stored spelling anyway; trimming less is the bug. The SUMMARY is stored as sent, so it is trimmed with White_Space alone and nothing Bugzilla keeps is dropped: an edge U+180E stays in what is judged and POSTed, a Perl before 5.20 strips it itself and a later one keeps it, so on every Perl the stored summary is the one the raw request would have produced. The judged summary therefore contains the stored one, and `summary_contains` is a positive substring test, so every needle the filed summary carries the judged one carries too. WHICH fields are rewritten is a rule rather than a list: every field create_bug sends that a Matcher reads (product, component, summary, severity, priority, keywords). Bugzilla also trims version, op_sys and platform, which no criterion reads — rewriting them would decide nothing, and a new criterion over such a field must extend the rewrite with it or reopen this bug. Evidence also needs the SHAPE create_bug sends: BugMeta reads component and keywords leniently (a lone string, an array, `{"name": ..}` objects) where Bugzilla splits a keyword string, resolves such objects itself, and refuses a list where it wants a name — so a non-string component is unknown, a keyword element the trim would turn false stays exactly as it came for Bugzilla to resolve or refuse, and a list holding one is unknown as a whole (a partly rewritten list reads as a shorter one). A list Bugzilla would skip entirely is dropped, as create_bug drops an empty one. A rewritten field that came out empty is still POSTed, so the upstream refusal answers it — `require_summary`, `require_component`, and `object_not_specified` for product, severity and (with `letsubmitterchoosepriority` on; off, the second limit below applies) priority — behind the same refusal text at the same cost. The audit record keeps the client's RAW arguments while the POST carries the rewrite: audited is what was asked, filed is what was judged. Two known limits remain, both about what the filed bug ends up carrying. First, the lookup compares under the DATABASE's collation, which can treat two spellings as equal — or a character as weightless — where a glob cannot: measured on MariaDB 10.6, the stored `Security Response` is matched by `"Śecurity Response"` under `utf8mb3_general_ci`, and under the UCA `utf8mb4_unicode_ci` by its decomposed spelling and by a leading zero-width space, BOM, word joiner or RLO; this gate judges each of those as a different product and POSTs it verbatim. ASCII-only product names are therefore no protection either, and a name glob is not a boundary on such an instance. Components, keywords, severities and priorities are looked up by name through the same comparison (`Bugzilla::Object` via `sql_istrcmp`; a component by `name = ?`, which MySQL also compares under the collation), so by reading the code, not by measurement, the limit covers their criteria too. What narrows it is an allowlist-shaped create grant ahead of a rule refusing every other create request, as the shipped example does: a spelling the allowlist does not match is refused, which leaves only products whose names the database equates with a name the allowlist does match. A create-scoped grant on exact product names ahead of a default deny narrows it furthest: an equivalent spelling can then only be refused, never admitted — a denylist create rule, by contrast, stays bypassable by such a spelling. Issue #330 carried the measurements and the options; the steering rule above is its resolution: stripping or refusing such characters was rejected because it would change what the reporter filed, so nothing here closes the limit (PostgreSQL's `LOWER()` against Rust's `to_lowercase` is the same class, by reasoning, not measurement). Second, with `letsubmitterchoosepriority` off Bugzilla replaces the requested priority with `defaultpriority`, so a `priorities` criterion judges a priority the filed bug may not carry. **Every refusal is one refusal**: a policy refusal, a refused Bug ID custom field target, an unassessable custom field value and an upstream failure all return the same fixed create_denial text after the same upstream request count — the refused path burns one classify call against bug id 0 (never a valid id, creates nothing; download_attachment's padding precedent) instead of the POST. That count is a function of the request and the field kinds as learned (a failed lookup reads every field as Unknown, so a number anywhere becomes a target): `N = [one type lookup, when custom_fields is non-empty — at most 50 keys, the cap refusing more at zero requests] + [one whoami, when there are Bug ID targets and the policy consults identity through whoami] + [one classify per distinct target] + 1 (the POST, or the pad)`. No term depends on `may_create`'s verdict, on a target's verdict or existence, or on the POST's outcome — the targets are assessed even when the gate already refused, and a hidden target answers with create_denial, never with that bug's own uniform denial. Two texts, or differing counts, would be a free policy-enumeration oracle: send a guaranteed-invalid `version` plus a probe product and read the policy off which refusal (or which latency) comes back, with nothing created. Residual, accepted: a SUCCESSFUL create still confirms the product is allowed — that is the tool doing its job, and it costs a real, attributable bug; and the padding equalizes request count, not the upstream handler's exact latency (GET classify vs rejected POST). Bugzilla's failure message is logged server-side only (it can say whether a product/component exists). `custom_fields` keys must start with `cf_` (I7): the gate runs before `may_create` and errors with ZERO upstream requests on a non-`cf_` key — distinguishable from the padded create refusal on purpose, since it decides nothing about policy or Bugzilla; the 25-id cap over the custom field values that could name a bug and the 50-key cap on `custom_fields` refuse at zero requests the same way (I7). The caller is resolved for the targets only, never for the gate (see "Identity resolution"). No Matcher criterion reads `cf_*`, so a custom field cannot move a prospective bug between rules the way `product`/`component` do, and `may_create`'s rewrite never touches a `cf_*` value. `custom_fields` is not in `PARAM_ALLOWLIST`, so the audit stream records it as `_len`, same as the updater | | add_attachment | bug_id, data (base64), file_name, summary, content_type, comment = "", is_private = false, is_patch = false | attach (write) on bug_id | guard assessment before the upload (I8), uniform denial (I2); then global.max_attachment_bytes caps the DECODED size of `data` (0 = no cap) — the ceiling the operator set on downloads binds uploads through the same server too, measured after base64 expansion is stripped so encoding overhead cannot shrink it. The refusal names neither the payload's size nor the cap value (max_attachment_bytes is not I1-disclosable, exactly as on the download path). Over http that non-disclosure is partial and knowingly so: the transport's POST body cap is derived from this same value (#52), so its 413 boundary is probeable once the cap exceeds ~2.25 MiB decoded — accepted, with the reasoning, under "rmcp 3.10 usage notes" below. Nothing here changes: this refusal still names neither size nor cap. `comment` travels as a PLAIN string — Bug.add_attachment documents it so; the `{"comment": {"body": ..}}` shape belongs to Bug.update only | | add_comment | bug_id, comment, is_private: bool = false | comment (write) | an upstream refusal is the fixed line plus at most one code-selected hint — see "Upstream failures of the write tools". Success serves the envelope with id-bearing `changes` scrubbed to the assessed bug (I14); the comment id itself names no bug | @@ -2491,6 +2491,23 @@ pinned by the in-crate capture test under "Testing". create_bug's single `warn` `min_bug_age_days` was inert, because the gate only runs for a positive count, and is refused so that one sign rule covers both. Refusing the sign at load leaves no such value to interpret. +- **Instants are `jiff::Timestamp` (#432).** chrono, which this replaced, is + unmaintained (RUSTSEC-2026-0543) and stays in the dependency tree only + through rmcp. These properties are relied on. Parsing: `creation_time` and + the `new_since` / `changed_since` parameters go through jiff's ISO 8601 + parser, which requires an offset. Against chrono it is laxer in places (a + missing seconds field, `+02`, a bracketed zone name) and stricter in + others (more than nine fractional digits; on the parameters also + surrounding whitespace and unpadded fields), and it reads second 60 as + 59. Bugzilla's `2014-09-23T19:12:17Z` is the shape that matters, and a + `creation_time` that does not parse is unknown (I4). Range: years -9999 + to 9999, so `age_cutoff` is `None` for a cutoff outside it. Before the + range the age quarantine denies and the matcher counts every bug as + young; after it, which takes a negative count the loader refuses, the + matcher matches nothing. Formats: the audit `ts` is `{:.3}` of the + timestamp, which truncates to milliseconds and always prints three + digits, and the query string sent to Bugzilla is unchanged from year 0000 + on (before it jiff's `%Y` writes `-001` where chrono wrote `-0001`). - **Rule names the operator may not take (issue #84).** `Policy::validate` rejects a rule named `"default"`, `"min_bug_age_days"` or `"unavailable"`, a rule whose name ends in `":unreadable-metadata"`, a @@ -3851,7 +3868,7 @@ wired, `server.rs` and `main.rs` are the reference. `sse_retry` set response framing and SSE liveness — client-visible timing, with no guard or operator-visible limit riding on them. - axum MUST be 0.8 (rmcp's version — extension extraction breaks otherwise); - schemars 1.x with feature `chrono04`; tokio 1; tokio-util 0.7. + schemars 1.x with feature `jiff02`; tokio 1; tokio-util 0.7. - Server struct: `#[derive(Clone)] pub struct BugWarden { cfg: Arc, guard: Arc, bz: Arc, tool_router: ToolRouter, key_custody: KeyCustody, audit: Option> }` - `BugWarden::new` builds `Self::tool_router()` then `remove_route` for write tools when read-only and for every `global.disabled_tools` entry (I13). @@ -3884,7 +3901,16 @@ wired, `server.rs` and `main.rs` are the reference. - Unit tests (#[cfg(test)] in policy.rs/guard.rs): glob matching; first-match ordering; embargo group deny; min_bug_age_days incl. missing creation_time (fail closed); younger_than_days matcher; a negative day count in either - refused at load, zero accepted; restrict caps; read-implies-summary; + refused at load on any rule and at any size, zero accepted; built past + the loader, a negative min_bug_age_days leaves the gate off and a negative + younger_than_days matches only a bug dated past its cutoff, nothing once + that cutoff is unrepresentable, and stays unknown for an unreadable age; + age_cutoff None outside representable time, where the quarantine denies + and, before that time, the matcher counts every bug as young; + creation_time read as Bugzilla's instant (checked against the epoch, with + `Z`, either offset sign and a fraction, second 60 as the 59th) and None + without an offset or a time, with padding, when empty, and for an + RFC 2822, ordinal or week date; restrict caps; read-implies-summary; read_only strips write caps — create and attach named explicitly, and a restrict grant of comment grants neither; default deny; summary redaction; comment filtering; validation errors (unknown TOML keys, restrict without