From 46d2b5ceaedbe6dce5856cf3e707ae673b7b7a86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=B6nke=20Liebau?= Date: Fri, 20 Nov 2026 17:50:49 +0000 Subject: [PATCH 1/5] Replace chrono with jiff chrono is unmaintained (RUSTSEC-2026-0543) and easybill-xero was its only user in the dependency tree. jiff reads and writes the same RFC 3339 timestamps, so existing state files keep loading (covered by a test). Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 150 +++++++++++++----------------------------- Cargo.toml | 2 +- src/cli.rs | 28 ++++---- src/main.rs | 8 +-- src/state.rs | 37 +++++++---- src/sync/all.rs | 2 +- src/sync/customers.rs | 18 ++--- src/sync/documents.rs | 8 +-- src/sync/report.rs | 10 +-- src/xero/auth.rs | 6 +- src/xero/token.rs | 4 +- 11 files changed, 112 insertions(+), 161 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7e6001f..5f389e1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11,15 +11,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "android_system_properties" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" -dependencies = [ - "libc", -] - [[package]] name = "anstream" version = "1.0.0" @@ -186,18 +177,6 @@ dependencies = [ "rand_core 0.10.1", ] -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "num-traits", - "serde", - "windows-link", -] - [[package]] name = "clap" version = "4.6.7" @@ -244,12 +223,6 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" -[[package]] -name = "core-foundation-sys" -version = "0.8.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" - [[package]] name = "cpufeatures" version = "0.3.1" @@ -289,10 +262,10 @@ dependencies = [ "async-trait", "base64", "bytes", - "chrono", "clap", "easybill", "http", + "jiff", "opentelemetry", "opentelemetry-http", "opentelemetry-otlp", @@ -557,30 +530,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - [[package]] name = "icu_collections" version = "2.3.0" @@ -722,6 +671,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 = "js-sys" version = "0.3.105" @@ -905,6 +889,15 @@ 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.6" @@ -1899,65 +1892,12 @@ dependencies = [ "rustls-pki-types", ] -[[package]] -name = "windows-core" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-link", - "windows-result", - "windows-strings", -] - -[[package]] -name = "windows-implement" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-interface" -version = "0.59.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" -[[package]] -name = "windows-result" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-strings" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" -dependencies = [ - "windows-link", -] - [[package]] name = "windows-sys" version = "0.52.0" diff --git a/Cargo.toml b/Cargo.toml index 1e51773..94310ba 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,7 +32,7 @@ opentelemetry-http = { version = "0.33", default-features = false } async-trait = "0.1" bytes = "1" http = "1" -chrono = { version = "0.4", default-features = false, features = ["clock", "serde"] } +jiff = { version = "0.2", default-features = false, features = ["std", "serde"] } base64 = "0.22" url = "2" rand = "0.8" diff --git a/src/cli.rs b/src/cli.rs index e7b7fd0..44939ea 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -2,8 +2,8 @@ use std::path::PathBuf; -use chrono::{NaiveDate, NaiveDateTime}; use clap::{Args, Parser, Subcommand}; +use jiff::civil; use crate::xero::token::AuthMode; @@ -99,16 +99,16 @@ pub struct SyncAllArgs { /// Only sync customers modified on or after this point in easybill's local /// time: `YYYY-MM-DD` or `YYYY-MM-DD HH:MM:SS` (or `T` instead of the space). #[arg(long, value_parser = parse_since)] - pub since: Option, + pub since: Option, /// Inclusive start of the document-date window (`YYYY-MM-DD`). #[arg(long)] - pub from: NaiveDate, + pub from: civil::Date, /// Inclusive end of the document-date window (`YYYY-MM-DD`); open-ended if /// omitted. #[arg(long)] - pub to: Option, + pub to: Option, /// Print the Xero payloads instead of sending them (no API writes). #[arg(long)] @@ -124,12 +124,12 @@ pub struct SyncAllArgs { pub struct SyncDocumentsArgs { /// Inclusive start of the document-date window (`YYYY-MM-DD`). #[arg(long)] - pub from: NaiveDate, + pub from: civil::Date, /// Inclusive end of the document-date window (`YYYY-MM-DD`); open-ended if /// omitted. #[arg(long)] - pub to: Option, + pub to: Option, /// Print the Xero payloads instead of sending them (no API writes). #[arg(long)] @@ -146,7 +146,7 @@ pub struct SyncCustomersArgs { /// Only sync customers modified on or after this point in easybill's local /// time: `YYYY-MM-DD` or `YYYY-MM-DD HH:MM:SS` (or `T` instead of the space). #[arg(long, value_parser = parse_since)] - pub since: Option, + pub since: Option, /// Print the Xero payloads instead of sending them (no API writes). #[arg(long)] @@ -178,12 +178,12 @@ pub struct CheckArgs { /// all customers, and list every tax key in use with its `[tax]` mapping. /// Needs `EASYBILL_API_TOKEN`. #[arg(long)] - pub from: Option, + pub from: Option, /// Inclusive end of the scanned document-date window (`YYYY-MM-DD`); /// open-ended if omitted. #[arg(long, requires = "from")] - pub to: Option, + pub to: Option, /// Also list every scanned document line (document number, line, VAT /// rate, tax key and TaxType, booking account and AccountCode), flagging @@ -209,15 +209,15 @@ pub struct LoginArgs { /// Parses `--since`: a date (midnight) or a date and time, without an offset /// (easybill timestamps are local time). -fn parse_since(value: &str) -> Result { +fn parse_since(value: &str) -> Result { let value = value.trim(); ["%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S"] .iter() - .find_map(|format| NaiveDateTime::parse_from_str(value, format).ok()) + .find_map(|format| civil::DateTime::strptime(format, value).ok()) .or_else(|| { - NaiveDate::parse_from_str(value, "%Y-%m-%d") + civil::Date::strptime("%Y-%m-%d", value) .ok() - .and_then(|d| d.and_hms_opt(0, 0, 0)) + .map(|d| d.to_datetime(civil::Time::midnight())) }) .ok_or_else(|| { String::from( @@ -273,7 +273,7 @@ mod tests { #[test] fn since_accepts_date_or_datetime_without_offset() { let midnight = parse_since("2026-06-01").expect("date"); - assert_eq!(midnight.to_string(), "2026-06-01 00:00:00"); + assert_eq!(midnight, civil::date(2026, 6, 1).at(0, 0, 0, 0)); assert_eq!( parse_since("2026-06-01T09:30:00").expect("datetime"), parse_since("2026-06-01 09:30:00").expect("datetime") diff --git a/src/main.rs b/src/main.rs index d9218a3..0c23247 100644 --- a/src/main.rs +++ b/src/main.rs @@ -44,8 +44,8 @@ enum Error { /// `--to` is before `--from`. #[snafu(display("--to {to} is before --from {from}"))] InvalidWindow { - from: chrono::NaiveDate, - to: chrono::NaiveDate, + from: jiff::civil::Date, + to: jiff::civil::Date, }, /// The configuration file could not be loaded. @@ -240,8 +240,8 @@ async fn run(cli: Cli) -> Result<(), Error> { /// Rejects a date window whose end is before its start. fn check_window( - from: Option, - to: Option, + from: Option, + to: Option, ) -> Result<(), Error> { match (from, to) { (Some(from), Some(to)) if to < from => InvalidWindowSnafu { from, to }.fail(), diff --git a/src/state.rs b/src/state.rs index b97ef95..b20c47b 100644 --- a/src/state.rs +++ b/src/state.rs @@ -13,7 +13,7 @@ use std::collections::BTreeMap; use std::path::{Path, PathBuf}; -use chrono::{DateTime, Utc}; +use jiff::Timestamp; use serde::{Deserialize, Serialize}; use snafu::{IntoError, OptionExt, ResultExt, Snafu}; @@ -162,7 +162,7 @@ pub struct DocumentRecord { pub status: DocumentStatus, /// When the document entered this status (kept while it doesn't change). - pub since: DateTime, + pub since: Timestamp, /// The easybill document number. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -218,14 +218,14 @@ pub struct CustomerRecord { pub status: CustomerStatus, /// When the customer entered this status (kept while it doesn't change). - pub since: DateTime, + pub since: Timestamp, } /// When a sync command last ran. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RunRecord { /// When it last finished, successfully or not. - pub last_run: DateTime, + pub last_run: Timestamp, /// Whether that run finished without a run-level error (failed items /// don't count). @@ -233,16 +233,16 @@ pub struct RunRecord { /// When it last finished without a run-level error. #[serde(default, skip_serializing_if = "Option::is_none")] - pub last_success: Option>, + pub last_success: Option, } /// The `since` for a status: kept from `previous` while the status is /// unchanged, else `now`. pub fn status_since( - previous: Option<(S, DateTime)>, + previous: Option<(S, Timestamp)>, status: S, - now: DateTime, -) -> DateTime { + now: Timestamp, +) -> Timestamp { match previous { Some((old, since)) if old == status => since, _ => now, @@ -273,7 +273,7 @@ pub struct DocumentMapping { pub pdf_uploaded: bool, /// When this document was last synced (ISO 8601). - pub synced_at: DateTime, + pub synced_at: Timestamp, } /// The persisted Xero authentication state. `Debug` redacts the token. @@ -286,7 +286,7 @@ pub struct XeroState { pub tenant_id: String, /// When this refresh token was obtained. - pub obtained_at: DateTime, + pub obtained_at: Timestamp, } impl std::fmt::Debug for XeroState { @@ -454,6 +454,17 @@ mod tests { std::fs::remove_file(&path).ok(); } + #[test] + fn loads_timestamps_written_by_chrono() { + // State files written before the switch to jiff carry chrono's RFC 3339 + // format, with nanoseconds where the clock provided them. + let json = r#"{"xero":{"refresh_token":"rt","tenant_id":"t","obtained_at":"2026-11-20T10:21:33.123456789Z"}}"#; + let state: State = serde_json::from_str(json).expect("chrono timestamps should load"); + let obtained_at = state.xero.expect("xero should be present").obtained_at; + assert_eq!(obtained_at.as_second(), 1_795_170_093); + assert_eq!(obtained_at.subsec_nanosecond(), 123_456_789); + } + #[test] fn update_keeps_changes_made_since_load() { let path = temp_path("update"); @@ -478,7 +489,7 @@ mod tests { xero_id: "x".to_owned(), kind: DocumentKind::Invoice, pdf_uploaded: false, - synced_at: Utc::now(), + synced_at: Timestamp::now(), }, ); }) @@ -492,8 +503,8 @@ mod tests { #[test] fn status_since_is_kept_while_unchanged() { - let then: DateTime = "2026-11-01T00:00:00Z".parse().expect("valid timestamp"); - let now: DateTime = "2026-11-11T08:00:00Z".parse().expect("valid timestamp"); + let then: Timestamp = "2026-11-01T00:00:00Z".parse().expect("valid timestamp"); + let now: Timestamp = "2026-11-11T08:00:00Z".parse().expect("valid timestamp"); let failing = Some((DocumentStatus::FailedConfig, then)); assert_eq!( status_since(failing, DocumentStatus::FailedConfig, now), diff --git a/src/sync/all.rs b/src/sync/all.rs index 95bc9ad..90968bc 100644 --- a/src/sync/all.rs +++ b/src/sync/all.rs @@ -17,7 +17,7 @@ use crate::xero::token::AuthMode; #[derive(Debug, Clone)] pub struct Options { /// `--since` passed to the customer phase. - pub since: Option, + pub since: Option, /// `--from` passed to the document phase. pub from: String, diff --git a/src/sync/customers.rs b/src/sync/customers.rs index d9a2df3..a9eff24 100644 --- a/src/sync/customers.rs +++ b/src/sync/customers.rs @@ -13,7 +13,7 @@ use std::collections::{HashMap, HashSet}; use std::path::Path; -use chrono::{NaiveDateTime, Utc}; +use jiff::{civil, Timestamp}; use snafu::{OptionExt, ResultExt}; use tracing::Instrument as _; @@ -36,7 +36,7 @@ use easybill::models::Customer; pub struct Options { /// Only sync customers whose easybill `updated_at` is `>=` this value /// (easybill local time); `None` syncs all. - pub since: Option, + pub since: Option, /// If `true`, print the payloads that would be sent and make no API writes. pub dry_run: bool, @@ -261,7 +261,7 @@ fn record_statuses( statuses: &[(i64, CustomerStatus)], ) -> Result<()> { let path = state::resolve_path(state_override).context(StateSnafu)?; - let now = Utc::now(); + let now = Timestamp::now(); State::update(&path, |s| { for &(id, status) in statuses { let key = id.to_string(); @@ -277,7 +277,7 @@ fn record_statuses( /// Whether a customer's `updated_at` is `>= since`. A customer whose /// `updated_at` is missing or unparseable counts as modified: syncing it again /// is harmless, skipping it silently is not. -fn modified_since(customer: &Customer, since: Option) -> bool { +fn modified_since(customer: &Customer, since: Option) -> bool { let Some(since) = since else { return true; }; @@ -293,7 +293,7 @@ fn modified_since(customer: &Customer, since: Option) -> bool { /// then keeps the customers modified since `since`. fn plan_selected<'a>( customers: &'a [Customer], - since: Option, + since: Option, config: &Config, existing: &ExistingIndex<'_>, ) -> Vec> { @@ -304,10 +304,10 @@ fn plan_selected<'a>( } /// Parses an easybill timestamp (`"2025-01-15 14:20:41"`, local time). -fn parse_easybill_timestamp(ts: &str) -> Option { +fn parse_easybill_timestamp(ts: &str) -> Option { let ts = ts.trim(); - NaiveDateTime::parse_from_str(ts, "%Y-%m-%d %H:%M:%S") - .or_else(|_| NaiveDateTime::parse_from_str(ts, "%Y-%m-%dT%H:%M:%S")) + civil::DateTime::strptime("%Y-%m-%d %H:%M:%S", ts) + .or_else(|_| civil::DateTime::strptime("%Y-%m-%dT%H:%M:%S", ts)) .ok() } @@ -578,7 +578,7 @@ mod tests { assert_eq!(ids, vec![2, 3, 4]); } - fn at(ts: &str) -> NaiveDateTime { + fn at(ts: &str) -> civil::DateTime { parse_easybill_timestamp(ts).expect("valid timestamp") } diff --git a/src/sync/documents.rs b/src/sync/documents.rs index ba29562..ae1f29c 100644 --- a/src/sync/documents.rs +++ b/src/sync/documents.rs @@ -16,7 +16,7 @@ use std::path::Path; -use chrono::Utc; +use jiff::Timestamp; use snafu::{OptionExt, ResultExt}; use tracing::Instrument as _; @@ -411,7 +411,7 @@ async fn sync_one( xero_id, kind, pdf_uploaded: false, - synced_at: Utc::now(), + synced_at: Timestamp::now(), }; if let Some(existing) = &existing { @@ -618,7 +618,7 @@ fn record_status(state: &mut State, document: &Document, status: DocumentStatus) }; let record = DocumentRecord { status, - since: status_since(previous, status, Utc::now()), + since: status_since(previous, status, Timestamp::now()), number: document.number.clone(), customer_id: document.customer_id, amount_cents, @@ -726,7 +726,7 @@ mod tests { xero_id: "guid-7".to_owned(), kind: DocumentKind::Invoice, pdf_uploaded: false, - synced_at: Utc::now(), + synced_at: Timestamp::now(), }, ); assert_eq!(known_id(&state, 7), Some("guid-7")); diff --git a/src/sync/report.rs b/src/sync/report.rs index 24dc877..ed9eb7f 100644 --- a/src/sync/report.rs +++ b/src/sync/report.rs @@ -16,7 +16,7 @@ use std::path::Path; -use chrono::{DateTime, Utc}; +use jiff::Timestamp; use opentelemetry::KeyValue; use snafu::ResultExt; @@ -130,7 +130,7 @@ pub fn publish(state_override: Option<&Path>, command: &'static str, run_ok: boo /// Records the run in state and returns the updated state. fn record_run(state_override: Option<&Path>, command: &str, run_ok: bool) -> Result { let path = state::resolve_path(state_override).context(StateSnafu)?; - let now = Utc::now(); + let now = Timestamp::now(); State::update(&path, |s| { let last_success = s.runs.get(command).and_then(|r| r.last_success); s.runs.insert( @@ -269,8 +269,8 @@ fn export(points: &[Point]) { } /// A timestamp as Unix seconds. -fn seconds(at: DateTime) -> f64 { - at.timestamp() as f64 +fn seconds(at: Timestamp) -> f64 { + at.as_second() as f64 } #[cfg(test)] @@ -278,7 +278,7 @@ mod tests { use super::*; use crate::state::{CustomerRecord, DocumentRecord}; - fn at(s: &str) -> DateTime { + fn at(s: &str) -> Timestamp { s.parse().expect("valid timestamp") } diff --git a/src/xero/auth.rs b/src/xero/auth.rs index 0c92143..17e374f 100644 --- a/src/xero/auth.rs +++ b/src/xero/auth.rs @@ -7,7 +7,7 @@ use std::path::Path; use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; use base64::Engine as _; -use chrono::Utc; +use jiff::Timestamp; use reqwest::header::ACCEPT; use serde::de::DeserializeOwned; use snafu::{OptionExt, ResultExt, Snafu}; @@ -148,7 +148,7 @@ pub async fn login(state_override: Option<&Path>, port: u16, tenant: Option<&str current.xero = Some(XeroState { refresh_token: token.refresh_token.clone(), tenant_id: selected.tenant_id.clone(), - obtained_at: Utc::now(), + obtained_at: Timestamp::now(), }); current.save(&path).context(StateSnafu)?; @@ -188,7 +188,7 @@ pub async fn refresh(state_override: Option<&Path>) -> Result<()> { current.xero = Some(XeroState { refresh_token: token.refresh_token.clone(), tenant_id: existing.tenant_id.clone(), - obtained_at: Utc::now(), + obtained_at: Timestamp::now(), }); current.save(&path).context(StateSnafu)?; tracing::debug!("rotated refresh token persisted"); diff --git a/src/xero/token.rs b/src/xero/token.rs index 7728ecf..c643291 100644 --- a/src/xero/token.rs +++ b/src/xero/token.rs @@ -15,7 +15,7 @@ use std::path::{Path, PathBuf}; -use chrono::Utc; +use jiff::Timestamp; use snafu::{ResultExt, Snafu}; use crate::state::{self, State, XeroState}; @@ -197,7 +197,7 @@ impl TokenManager { s.xero = Some(XeroState { refresh_token: token.refresh_token.clone(), tenant_id: existing.tenant_id.clone(), - obtained_at: Utc::now(), + obtained_at: Timestamp::now(), }); }) .context(PersistRotatedSnafu)?; From dbfac6eacec02fe54ffd379b8e91b3827fcf3faf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=B6nke=20Liebau?= Date: Fri, 20 Nov 2026 17:51:04 +0000 Subject: [PATCH 2/5] Adopt the operators' rustfmt config and reformat Same rustfmt.toml as the operators (nightly-only import grouping and granularity). Formatting only, no functional change. Co-Authored-By: Claude Opus 5.5 --- easybill/src/client.rs | 6 ++++-- rustfmt.toml | 11 +++++++++++ src/cli.rs | 12 ++++-------- src/config.rs | 6 ++++-- src/main.rs | 9 +++------ src/state.rs | 9 +++++---- src/sync/all.rs | 8 +++++--- src/sync/customers.rs | 34 +++++++++++++++++++--------------- src/sync/documents.rs | 37 ++++++++++++++++++++----------------- src/sync/report.rs | 18 +++++++++--------- src/telemetry.rs | 14 ++++++++------ src/xero/auth.rs | 12 ++++++++---- src/xero/check.rs | 36 +++++++++++++++++++++++------------- src/xero/client.rs | 25 +++++++++++++++---------- src/xero/contact.rs | 7 +++++-- src/xero/document.rs | 16 +++++++++------- src/xero/token.rs | 10 +++++++--- 17 files changed, 159 insertions(+), 111 deletions(-) create mode 100644 rustfmt.toml diff --git a/easybill/src/client.rs b/easybill/src/client.rs index ebd4e73..dda26c5 100644 --- a/easybill/src/client.rs +++ b/easybill/src/client.rs @@ -8,8 +8,10 @@ use std::time::Duration; -use reqwest::header::{ACCEPT, RETRY_AFTER}; -use reqwest::StatusCode; +use reqwest::{ + StatusCode, + header::{ACCEPT, RETRY_AFTER}, +}; use serde::de::DeserializeOwned; use snafu::{ResultExt, Snafu}; diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..d988426 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,11 @@ +# Taken from stackabletech/operator-templating, keep in sync. + +# This file includes unstable features, so you need to run "cargo +nightly fmt" to format your code. +# It's also ok to use the stable toolchain by simple running "cargo fmt", but using the nightly formatter is preferred. + +# https://doc.rust-lang.org/nightly/edition-guide/rust-2024/rustfmt-style-edition.html +style_edition = "2024" +imports_granularity = "Crate" +group_imports = "StdExternalCrate" +reorder_impl_items = true +use_field_init_shorthand = true diff --git a/src/cli.rs b/src/cli.rs index 44939ea..16b45f0 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -260,14 +260,10 @@ mod tests { Cli::try_parse_from(["easybill-xero", "sync", "documents", "--from", "yesterday"]) .is_err() ); - assert!(Cli::try_parse_from([ - "easybill-xero", - "sync", - "documents", - "--from", - "2026-02-30" - ]) - .is_err()); + assert!( + Cli::try_parse_from(["easybill-xero", "sync", "documents", "--from", "2026-02-30"]) + .is_err() + ); } #[test] diff --git a/src/config.rs b/src/config.rs index 6ed93a7..f12c3c1 100644 --- a/src/config.rs +++ b/src/config.rs @@ -22,8 +22,10 @@ //! # covers lines without one //! ``` -use std::collections::BTreeMap; -use std::path::{Path, PathBuf}; +use std::{ + collections::BTreeMap, + path::{Path, PathBuf}, +}; use serde::Deserialize; use snafu::{OptionExt, ResultExt, Snafu}; diff --git a/src/main.rs b/src/main.rs index 0c23247..6decc04 100644 --- a/src/main.rs +++ b/src/main.rs @@ -16,16 +16,13 @@ mod sync; mod telemetry; mod xero; -use std::error::Error as _; -use std::path::PathBuf; -use std::process::ExitCode; +use std::{error::Error as _, path::PathBuf, process::ExitCode}; use clap::Parser; -use snafu::{ResultExt, Snafu}; -use tracing::Instrument as _; - use cli::{Cli, Command, LogFormat, SyncCommand, XeroCommand}; use config::Config; +use snafu::{ResultExt, Snafu}; +use tracing::Instrument as _; use xero::token::AuthMode; /// Top-level binary error wrapping each subsystem's module-local error. diff --git a/src/state.rs b/src/state.rs index b20c47b..a25ed18 100644 --- a/src/state.rs +++ b/src/state.rs @@ -10,8 +10,10 @@ //! Secrets other than the refresh token (client id/secret, easybill API key) //! never live here — they come from environment variables. -use std::collections::BTreeMap; -use std::path::{Path, PathBuf}; +use std::{ + collections::BTreeMap, + path::{Path, PathBuf}, +}; use jiff::Timestamp; use serde::{Deserialize, Serialize}; @@ -330,8 +332,7 @@ impl State { /// Returns [`Error::CreateDir`], [`Error::Serialise`], [`Error::WriteTemp`], /// or [`Error::Persist`] on the corresponding failure. pub fn save(&self, path: impl AsRef) -> Result<()> { - use std::io::Write; - use std::os::unix::fs::OpenOptionsExt; + use std::{io::Write, os::unix::fs::OpenOptionsExt}; let path = path.as_ref(); if let Some(parent) = path.parent() { diff --git a/src/sync/all.rs b/src/sync/all.rs index 90968bc..4366b2b 100644 --- a/src/sync/all.rs +++ b/src/sync/all.rs @@ -9,9 +9,11 @@ use std::path::Path; -use crate::config::Config; -use crate::sync::{customers, documents, Error, ItemsFailedSnafu, Result}; -use crate::xero::token::AuthMode; +use crate::{ + config::Config, + sync::{Error, ItemsFailedSnafu, Result, customers, documents}, + xero::token::AuthMode, +}; /// Options for a `sync all` run. #[derive(Debug, Clone)] diff --git a/src/sync/customers.rs b/src/sync/customers.rs index a9eff24..2f2caca 100644 --- a/src/sync/customers.rs +++ b/src/sync/customers.rs @@ -10,26 +10,30 @@ //! The durable link is the contact's `ContactNumber` (the easybill id), which //! the upsert sets and which `sync documents` uses to resolve contacts. -use std::collections::{HashMap, HashSet}; -use std::path::Path; - -use jiff::{civil, Timestamp}; +use std::{ + collections::{HashMap, HashSet}, + path::Path, +}; +use easybill::{client::EasybillClient, models::Customer}; +use jiff::{Timestamp, civil}; use snafu::{OptionExt, ResultExt}; use tracing::Instrument as _; -use crate::config::Config; -use crate::state::{self, status_since, CustomerRecord, CustomerStatus, State}; -use crate::sync::{ - ClientSnafu, EasybillSnafu, EmptyResponseSnafu, ItemsFailedSnafu, Result, StateSnafu, - TokenSnafu, +use crate::{ + config::Config, + state::{self, CustomerRecord, CustomerStatus, State, status_since}, + sync::{ + ClientSnafu, EasybillSnafu, EmptyResponseSnafu, ItemsFailedSnafu, Result, StateSnafu, + TokenSnafu, + }, + xero::{ + client::ApiClient, + contact::{map_customer, name_with_number_suffix}, + models::{Contact, ContactResult, ContactsRequest}, + token::{AuthMode, TokenManager}, + }, }; -use crate::xero::client::ApiClient; -use crate::xero::contact::{map_customer, name_with_number_suffix}; -use crate::xero::models::{Contact, ContactResult, ContactsRequest}; -use crate::xero::token::{AuthMode, TokenManager}; -use easybill::client::EasybillClient; -use easybill::models::Customer; /// Options for a `sync customers` run. #[derive(Debug, Clone, Default)] diff --git a/src/sync/documents.rs b/src/sync/documents.rs index ae1f29c..488f93c 100644 --- a/src/sync/documents.rs +++ b/src/sync/documents.rs @@ -16,28 +16,31 @@ use std::path::Path; +use easybill::{client::EasybillClient, models::Document}; use jiff::Timestamp; use snafu::{OptionExt, ResultExt}; use tracing::Instrument as _; -use crate::config::Config; -use crate::state::{ - self, status_since, DocumentKind, DocumentMapping, DocumentRecord, DocumentStatus, State, -}; -use crate::sync::{ - ClientSnafu, EasybillSnafu, EmptyResponseSnafu, Error, ItemsFailedSnafu, Result, StateSnafu, - TokenSnafu, -}; -use crate::xero::attachment::{attachment_filename, attachment_path, Resource}; -use crate::xero::client::ApiClient; -use crate::xero::document::{map_document, verify_total, Mapped}; -use crate::xero::models::{ - CreditNoteResult, CreditNotesRequest, CreditNotesResponse, InvoiceResult, InvoicesRequest, - InvoicesResponse, +use crate::{ + config::Config, + state::{ + self, DocumentKind, DocumentMapping, DocumentRecord, DocumentStatus, State, status_since, + }, + sync::{ + ClientSnafu, EasybillSnafu, EmptyResponseSnafu, Error, ItemsFailedSnafu, Result, + StateSnafu, TokenSnafu, + }, + xero::{ + attachment::{Resource, attachment_filename, attachment_path}, + client::ApiClient, + document::{Mapped, map_document, verify_total}, + models::{ + CreditNoteResult, CreditNotesRequest, CreditNotesResponse, InvoiceResult, + InvoicesRequest, InvoicesResponse, + }, + token::{AuthMode, TokenManager}, + }, }; -use crate::xero::token::{AuthMode, TokenManager}; -use easybill::client::EasybillClient; -use easybill::models::Document; /// Xero type of a sales invoice. const TYPE_ACCREC: &str = "ACCREC"; diff --git a/src/sync/report.rs b/src/sync/report.rs index ed9eb7f..30e9369 100644 --- a/src/sync/report.rs +++ b/src/sync/report.rs @@ -20,8 +20,10 @@ use jiff::Timestamp; use opentelemetry::KeyValue; use snafu::ResultExt; -use crate::state::{self, CustomerStatus, DocumentStatus, RunRecord, State}; -use crate::sync::{Result, StateSnafu}; +use crate::{ + state::{self, CustomerStatus, DocumentStatus, RunRecord, State}, + sync::{Result, StateSnafu}, +}; /// One gauge of the snapshot. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -80,19 +82,17 @@ impl Metric { Self::LastRunSuccess => { "Whether a sync command's last run finished without a run-level error (1) or not (0)." } - Self::LastSuccess => "Unix time a sync command last finished without a run-level error.", + Self::LastSuccess => { + "Unix time a sync command last finished without a run-level error." + } Self::Documents => "Known easybill documents by sync status.", Self::Customers => "Known easybill customers by sync status.", - Self::DocumentIssueSince => { - "Unix time a document entered its current problem status." - } + Self::DocumentIssueSince => "Unix time a document entered its current problem status.", Self::DocumentIssueAmount => "Gross amount of a problem document, in its currency.", Self::DocumentIssueReportedAt => { "Unix time of the run that reported this document problem." } - Self::CustomerIssueSince => { - "Unix time a customer entered its current problem status." - } + Self::CustomerIssueSince => "Unix time a customer entered its current problem status.", Self::CustomerIssueReportedAt => { "Unix time of the run that reported this customer problem." } diff --git a/src/telemetry.rs b/src/telemetry.rs index 4dd01d1..3f6d853 100644 --- a/src/telemetry.rs +++ b/src/telemetry.rs @@ -20,14 +20,16 @@ use std::time::Duration; use opentelemetry::trace::{TraceContextExt as _, TracerProvider as _}; use opentelemetry_otlp::{WithExportConfig as _, WithHttpConfig as _}; -use opentelemetry_sdk::metrics::{PeriodicReader, SdkMeterProvider}; -use opentelemetry_sdk::trace::SdkTracerProvider; -use opentelemetry_sdk::Resource; +use opentelemetry_sdk::{ + Resource, + metrics::{PeriodicReader, SdkMeterProvider}, + trace::SdkTracerProvider, +}; use snafu::{ResultExt, Snafu}; use tracing_opentelemetry::OpenTelemetrySpanExt as _; -use tracing_subscriber::layer::SubscriberExt as _; -use tracing_subscriber::util::SubscriberInitExt as _; -use tracing_subscriber::{fmt, EnvFilter, Layer as _}; +use tracing_subscriber::{ + EnvFilter, Layer as _, fmt, layer::SubscriberExt as _, util::SubscriberInitExt as _, +}; use crate::cli::LogFormat; diff --git a/src/xero/auth.rs b/src/xero/auth.rs index 17e374f..b35130b 100644 --- a/src/xero/auth.rs +++ b/src/xero/auth.rs @@ -5,16 +5,20 @@ use std::path::Path; -use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; -use base64::Engine as _; +use base64::{ + Engine as _, + engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}, +}; use jiff::Timestamp; use reqwest::header::ACCEPT; use serde::de::DeserializeOwned; use snafu::{OptionExt, ResultExt, Snafu}; use url::Url; -use crate::state::{self, State, XeroState}; -use crate::xero::models::{Connection, OrganisationsResponse, TokenResponse}; +use crate::{ + state::{self, State, XeroState}, + xero::models::{Connection, OrganisationsResponse, TokenResponse}, +}; const AUTHORIZE_URL: &str = "https://login.xero.com/identity/connect/authorize"; const TOKEN_URL: &str = "https://identity.xero.com/connect/token"; diff --git a/src/xero/check.rs b/src/xero/check.rs index c74bea0..dc8460e 100644 --- a/src/xero/check.rs +++ b/src/xero/check.rs @@ -12,18 +12,26 @@ //! with the Xero `AccountCode` it resolves to; one that is missing or inactive //! in the org is a problem, since Xero would reject the document. -use std::collections::{BTreeMap, BTreeSet}; -use std::path::Path; - +use std::{ + collections::{BTreeMap, BTreeSet}, + path::Path, +}; + +use easybill::{ + client::EasybillClient, + models::{Customer, Document}, +}; use snafu::{ResultExt, Snafu}; -use crate::config::Config; -use crate::sync::documents::{document_filters, without_skipped}; -use crate::xero::client::{self, ApiClient}; -use crate::xero::models::{Account, TaxRate}; -use crate::xero::token::{self, AuthMode, TokenManager}; -use easybill::client::EasybillClient; -use easybill::models::{Customer, Document}; +use crate::{ + config::Config, + sync::documents::{document_filters, without_skipped}, + xero::{ + client::{self, ApiClient}, + models::{Account, TaxRate}, + token::{self, AuthMode, TokenManager}, + }, +}; /// Errors arising from `xero check`. #[derive(Debug, Snafu)] @@ -916,9 +924,11 @@ default = "200" // Without a scan: no counts, plus a hint. let report = tax_keys_report(&config(), None); - assert!(report_lines(&report) - .iter() - .any(|l| l == "null/20 -> OUTPUT2")); + assert!( + report_lines(&report) + .iter() + .any(|l| l == "null/20 -> OUTPUT2") + ); assert!(report.contains("pass --from")); } diff --git a/src/xero/client.rs b/src/xero/client.rs index 72e57ea..0552f4b 100644 --- a/src/xero/client.rs +++ b/src/xero/client.rs @@ -11,20 +11,25 @@ //! validation responses echo the whole invoice or contact, which must not end //! up in logs. -use std::sync::Mutex; -use std::time::{Duration, Instant}; +use std::{ + sync::Mutex, + time::{Duration, Instant}, +}; -use reqwest::header::{ACCEPT, RETRY_AFTER}; -use reqwest::{Method, StatusCode}; -use serde::de::DeserializeOwned; -use serde::Serialize; +use reqwest::{ + Method, StatusCode, + header::{ACCEPT, RETRY_AFTER}, +}; +use serde::{Serialize, de::DeserializeOwned}; use snafu::{ResultExt, Snafu}; -use crate::xero::models::{ - AccountsResponse, ContactResult, ContactsRequest, ContactsResponse, CreditNotesRequest, - CreditNotesResponse, InvoicesRequest, InvoicesResponse, TaxRatesResponse, +use crate::xero::{ + models::{ + AccountsResponse, ContactResult, ContactsRequest, ContactsResponse, CreditNotesRequest, + CreditNotesResponse, InvoicesRequest, InvoicesResponse, TaxRatesResponse, + }, + token::{self, AccessContext, TokenManager}, }; -use crate::xero::token::{self, AccessContext, TokenManager}; /// The Accounting API base URL (trailing slash so paths join cleanly). const API_BASE: &str = "https://api.xero.com/api.xro/2.0/"; diff --git a/src/xero/contact.rs b/src/xero/contact.rs index 2ca5715..6ef850b 100644 --- a/src/xero/contact.rs +++ b/src/xero/contact.rs @@ -5,10 +5,13 @@ //! ISO country code is translated to an English country name (Xero expects the //! name, not the code). -use crate::config::Config; -use crate::xero::models::{Address, Contact, ContactPerson, PaymentTerm, PaymentTerms, Phone}; use easybill::models::Customer; +use crate::{ + config::Config, + xero::models::{Address, Contact, ContactPerson, PaymentTerm, PaymentTerms, Phone}, +}; + /// The Xero payment-term basis matching easybill's `due_in_days`. const DAYS_AFTER_BILL_DATE: &str = "DAYSAFTERBILLDATE"; diff --git a/src/xero/document.rs b/src/xero/document.rs index 1a7a55a..ed8637b 100644 --- a/src/xero/document.rs +++ b/src/xero/document.rs @@ -8,13 +8,14 @@ //! missing mapping fails the *document* (returned as an error) rather than //! silently producing a wrong invoice. -use rust_decimal::prelude::FromPrimitive; -use rust_decimal::{Decimal, RoundingStrategy}; +use easybill::models::{Document, DocumentItem}; +use rust_decimal::{Decimal, RoundingStrategy, prelude::FromPrimitive}; use snafu::{OptionExt, ResultExt, Snafu}; -use crate::config::{self, Config}; -use crate::xero::models::{ContactRef, CreditNote, Invoice, LineItem}; -use easybill::models::{Document, DocumentItem}; +use crate::{ + config::{self, Config}, + xero::models::{ContactRef, CreditNote, Invoice, LineItem}, +}; /// The easybill document type for invoices. const TYPE_INVOICE: &str = "INVOICE"; @@ -355,9 +356,10 @@ pub struct TotalMismatch { #[cfg(test)] mod tests { - use super::*; use rust_decimal_macros::dec; + use super::*; + fn config() -> Config { toml::from_str( r#" @@ -439,7 +441,7 @@ default = "200" let second = &inv.line_items[1]; assert_eq!(second.description, "License"); assert_eq!(second.account_code, "200"); // no booking account -> default - // 10% of 16000.00, taken from easybill's line total. + // 10% of 16000.00, taken from easybill's line total. assert_eq!(second.discount_amount, Some(dec!(1600))); } diff --git a/src/xero/token.rs b/src/xero/token.rs index c643291..25eadaf 100644 --- a/src/xero/token.rs +++ b/src/xero/token.rs @@ -18,9 +18,13 @@ use std::path::{Path, PathBuf}; use jiff::Timestamp; use snafu::{ResultExt, Snafu}; -use crate::state::{self, State, XeroState}; -use crate::xero::auth; -use crate::xero::models::{ClientCredentialsToken, TokenResponse}; +use crate::{ + state::{self, State, XeroState}, + xero::{ + auth, + models::{ClientCredentialsToken, TokenResponse}, + }, +}; /// How the tool authenticates against Xero. #[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)] From 68db208a849089747b8faa798721e63a394480c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=B6nke=20Liebau?= Date: Fri, 20 Nov 2026 17:52:10 +0000 Subject: [PATCH 3/5] Update rustls, rustls-webpki, webpki-roots, tokio and yoke-derive Fixes RUSTSEC-2026-0346, -0347, -0348, -0349 (rustls), -0381 (webpki-roots), -0382 (rustls-webpki) and -0386 (tokio), and replaces the yanked yoke-derive 0.8.3. Found by cargo-deny. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5f389e1..b9dad4b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1223,9 +1223,9 @@ checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" [[package]] name = "rustls" -version = "0.23.45" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "once_cell", "ring", @@ -1247,9 +1247,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.103.15" +version = "0.103.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" dependencies = [ "ring", "rustls-pki-types", @@ -1497,9 +1497,9 @@ checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] name = "tokio" -version = "1.53.1" +version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ "bytes", "libc", @@ -1885,9 +1885,9 @@ dependencies = [ [[package]] name = "webpki-roots" -version = "1.0.9" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" dependencies = [ "rustls-pki-types", ] @@ -2023,9 +2023,9 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", From ac1ab2e77ac53873e771deb5b4f5f189e8be4c54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=B6nke=20Liebau?= Date: Fri, 20 Nov 2026 17:57:20 +0000 Subject: [PATCH 4/5] Add the operators' CI checks prek runs the hooks from .pre-commit-config.yaml on pull requests (typos, cargo-deny, yamllint, markdownlint, actionlint, hadolint, cargo doc, nightly rustfmt, clippy, tests), build.yaml gains a cargo-udeps job, and a daily job runs cargo-audit. deny.toml, rustfmt.toml and the lint configs are copied from stackabletech/operator-templating. Also fixes what the new checks found (private doc links, typos, Markdown style) and the Harbor secret name in the docs. Co-Authored-By: Claude Opus 5.5 --- .git-blame-ignore-revs | 5 + .github/workflows/build.yaml | 53 +++---- .github/workflows/general_daily_security.yml | 32 +++++ .github/workflows/pr_prek.yaml | 32 +++++ .hadolint.yaml | 12 ++ .markdownlint.yaml | 28 ++++ .pre-commit-config.yaml | 87 ++++++++++++ .yamllint.yaml | 17 +++ AGENTS.md | 32 +++-- README.md | 65 ++++++--- TODO.md | 21 ++- deny.toml | 141 +++++++++++++++++++ easybill/src/client.rs | 12 +- rust-toolchain.toml | 4 + src/sync/customers.rs | 2 +- src/xero/client.rs | 2 +- 16 files changed, 482 insertions(+), 63 deletions(-) create mode 100644 .git-blame-ignore-revs create mode 100644 .github/workflows/general_daily_security.yml create mode 100644 .github/workflows/pr_prek.yaml create mode 100644 .hadolint.yaml create mode 100644 .markdownlint.yaml create mode 100644 .pre-commit-config.yaml create mode 100644 .yamllint.yaml create mode 100644 deny.toml create mode 100644 rust-toolchain.toml diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 0000000..183246c --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,5 @@ +# Formatting-only commits, skipped by `git blame` (GitHub picks this file up; +# locally: `git config blame.ignoreRevsFile .git-blame-ignore-revs`). + +# Adopt the operators' rustfmt config and reformat +dbfac6eacec02fe54ffd379b8e91b3827fcf3faf diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 440bec0..8920b97 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -3,11 +3,12 @@ # # - a tag `vX.Y.Z` publishes `X.Y.Z` (the tag must match the Cargo.toml version) # - a push to `main` publishes `0.0.0-dev` (floating) and `0.0.0-dev-` -# - a pull request only runs the checks and a test build (nothing is pushed) +# - a pull request only runs a test build (nothing is pushed) and cargo-udeps; +# the other checks are in pr_prek.yaml # # Repository settings needed: # - variable `REGISTRY_NAMESPACE`: the Harbor project on oci.stackable.tech -# - secret `HARBOR_ROBOT_SECRET`: the secret of the robot account +# - secret `HARBOR_ROBOT_STACKABLE_GITHUB_ACTION_BUILD_SECRET`: the secret of the robot account # `robot$+github-action-build` name: Build @@ -26,46 +27,34 @@ concurrency: env: REGISTRY: oci.stackable.tech IMAGE_NAME: easybill-xero - # Keep in sync with the builder image in the Dockerfile. - RUST_TOOLCHAIN: 1.99.1 jobs: - check: - name: Check + cargo-udeps: + name: Run cargo-udeps runs-on: ubuntu-latest permissions: contents: read + env: + # cargo-udeps needs nightly features; this unlocks them on the stable + # toolchain from rust-toolchain.toml, as the operators do. + RUSTC_BOOTSTRAP: 1 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master - with: - toolchain: ${{ env.RUST_TOOLCHAIN }} - components: clippy, rustfmt - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + key: udeps - - run: cargo fmt --all --check - - run: cargo clippy --workspace --all-targets --locked -- -D warnings - - run: cargo test --workspace --locked + - uses: stackabletech/cargo-install-action@e3e2dcf8d0f0e5bdbc619bf6ee7560dd68152d3c + with: + crate: cargo-udeps - - name: Check that the tag matches the Cargo.toml version - if: startsWith(github.ref, 'refs/tags/v') - env: - TAG: ${{ github.ref_name }} - run: | - version="$(cargo metadata --no-deps --format-version 1 --locked \ - | jq -r '.packages[] | select(.name == "easybill-xero") | .version')" - if [ "${TAG#v}" != "$version" ]; then - echo "Tag $TAG does not match the Cargo.toml version $version" >&2 - exit 1 - fi + - run: cargo udeps --workspace --all-targets --locked build: name: Build/Publish Image - needs: check runs-on: ubuntu-latest permissions: contents: read @@ -78,6 +67,18 @@ jobs: with: persist-credentials: false + - name: Check that the tag matches the Cargo.toml version + if: startsWith(github.ref, 'refs/tags/v') + env: + TAG: ${{ github.ref_name }} + run: | + version="$(cargo metadata --no-deps --format-version 1 --locked \ + | jq -r '.packages[] | select(.name == "easybill-xero") | .version')" + if [ "${TAG#v}" != "$version" ]; then + echo "Tag $TAG does not match the Cargo.toml version $version" >&2 + exit 1 + fi + - name: Check repository settings if: env.PUBLISH == 'true' env: diff --git a/.github/workflows/general_daily_security.yml b/.github/workflows/general_daily_security.yml new file mode 100644 index 0000000..67124b2 --- /dev/null +++ b/.github/workflows/general_daily_security.yml @@ -0,0 +1,32 @@ +--- +# Checks the dependencies against the RustSec advisory database every day, +# so new advisories show up even when no pull request touches Cargo.lock. +# Taken from stackabletech/operator-templating. +name: Daily Security Audit + +on: + schedule: + - cron: "15 4 * * *" + workflow_dispatch: + +permissions: {} + +jobs: + audit: + runs-on: ubuntu-latest + permissions: + contents: read + # rustsec/audit-check publishes its results as a Check run, which requires this scope + checks: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: rustsec/audit-check@69366f33c96575abad1ee0dba8212993eecbe998 # v2.0.0 + # Build against stable because cargo-audit sometimes depends on things + # that require a newer Rust version than our pinned toolchain. This does + # not influence the result, so it should be safe. + env: + RUSTUP_TOOLCHAIN: stable + with: + token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/pr_prek.yaml b/.github/workflows/pr_prek.yaml new file mode 100644 index 0000000..314d608 --- /dev/null +++ b/.github/workflows/pr_prek.yaml @@ -0,0 +1,32 @@ +--- +# Runs the hooks in .pre-commit-config.yaml on the files a pull request +# changes (lints, cargo-deny, rustfmt, clippy, tests). Modelled after +# stackabletech/operator-templating. +name: prek + +on: + pull_request: + +permissions: {} + +env: + CARGO_TERM_COLOR: always + # Keep in sync with the cargo-rustfmt hook in .pre-commit-config.yaml. The + # stable toolchain comes from rust-toolchain.toml. + RUST_NIGHTLY_TOOLCHAIN_VERSION: "nightly-2026-11-02" + HADOLINT_VERSION: "v2.15.1" + +jobs: + prek: + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + fetch-depth: 0 + - uses: stackabletech/actions/run-prek@d5c85b3cef351617f19de803812b42b839e20168 # v0.18.4 + with: + rust: ${{ env.RUST_NIGHTLY_TOOLCHAIN_VERSION }} + hadolint: ${{ env.HADOLINT_VERSION }} diff --git a/.hadolint.yaml b/.hadolint.yaml new file mode 100644 index 0000000..affffa3 --- /dev/null +++ b/.hadolint.yaml @@ -0,0 +1,12 @@ +# Taken from stackabletech/operator-templating, keep in sync. +--- +ignored: + # Warning: Use the -y switch to avoid manual input dnf install -y + # https://github.com/hadolint/hadolint/wiki/DL3038 + # Reason: We set `assumeyes=True` in dnf.conf in our base image + - DL3038 + + # Warning: Specify version with dnf install -y - + # https://github.com/hadolint/hadolint/wiki/DL3041 + # Reason: It's good advice, but we're not set up to pin versions just yet + - DL3041 diff --git a/.markdownlint.yaml b/.markdownlint.yaml new file mode 100644 index 0000000..699a203 --- /dev/null +++ b/.markdownlint.yaml @@ -0,0 +1,28 @@ +# Taken from stackabletech/operator-templating, keep in sync. +--- +# All defaults or options can be checked here: +# https://github.com/DavidAnson/markdownlint/blob/main/schema/.markdownlint.yaml + +# Default state for all rules +default: true + +# MD013/line-length - Line length +MD013: + # Number of characters + line_length: 9999 + # Number of characters for headings + heading_line_length: 9999 + # Number of characters for code blocks + code_block_line_length: 9999 + +# MD033/no-inline-html +MD033: + allowed_elements: [h1, img, p] + +# MD024/no-duplicate-heading/no-duplicate-header - Multiple headings with the same content +MD024: + # Only check sibling headings + siblings_only: true + +# MD041/first-line-heading/first-line-h1 First line in a file should be a top-level heading +MD041: false # Github issues and PRs already have titles, and H1 is enormous in the description box. diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..ecdfacc --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,87 @@ +# Modelled after stackabletech/operator-templating; the hook versions are kept +# in sync with it. Hooks for Helm, Nix, Python and README rendering are left +# out, as this repo has none of those. +--- +repos: + - repo: https://github.com/crate-ci/typos + rev: 7f9d0819ca1c008ade73f4b41fa9d258d48f605b # v1.51.1 + hooks: + - id: typos + # Drop the upstream default `--write-changes` so the hook only + # reports failures instead of writing changes. + args: ["--force-exclude"] + + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: 3e8a8703264a2f4a69428a0aa4dcb512790b2c8c # 6.0.0 + hooks: + - id: trailing-whitespace + - id: end-of-file-fixer + - id: detect-aws-credentials + args: ["--allow-missing-credentials"] + - id: detect-private-key + + - repo: https://github.com/EmbarkStudios/cargo-deny + rev: 1c9ca2b643ee15722178c1350501aabb024dd6f3 # 0.19.9 + hooks: + - id: cargo-deny + args: ["--all-features", "check", "advisories", "bans", "licenses", "sources"] + + - repo: https://github.com/adrienverge/yamllint + rev: 79a6b2b1392eaf49cdd32ac4f14be1a809bbd8f7 # 1.37.1 + hooks: + - id: yamllint + args: ["--strict"] + + - repo: https://github.com/igorshubovych/markdownlint-cli + rev: cbcdc463be5464e25e3e955a511599a67b9b987f # 0.50.0 + hooks: + - id: markdownlint + types: [text] + files: \.md$ + + - repo: https://github.com/rhysd/actionlint + rev: 914e7df21a07ef503a81201c76d2b11c789d3fca # 1.7.12 + hooks: + - id: actionlint + + - repo: https://github.com/hadolint/hadolint + rev: 2eece55955ced00200be9729e9728cb7dacca505 # 2.15.1 + hooks: + - id: hadolint + + - repo: local + hooks: + - id: cargo-doc + name: cargo-doc + language: system + env: + RUSTDOCFLAGS: "-D warnings" + entry: cargo doc --workspace --no-deps --document-private-items --locked + stages: [pre-commit, pre-merge-commit] + pass_filenames: false + files: \.rs$|Cargo\.(toml|lock) + + - id: cargo-test + name: cargo-test + language: system + entry: cargo test --workspace --locked + stages: [pre-commit, pre-merge-commit] + pass_filenames: false + files: \.rs$|Cargo\.(toml|lock) + + - id: cargo-rustfmt + name: cargo-rustfmt + language: system + # Keep the nightly version in sync with .github/workflows/pr_prek.yaml. + entry: cargo +nightly-2026-11-02 fmt --all -- --check + stages: [pre-commit, pre-merge-commit] + pass_filenames: false + files: \.rs$ + + - id: cargo-clippy + name: cargo-clippy + language: system + entry: cargo clippy --workspace --all-targets --locked -- -D warnings + stages: [pre-commit, pre-merge-commit] + pass_filenames: false + files: \.rs$|Cargo\.(toml|lock) diff --git a/.yamllint.yaml b/.yamllint.yaml new file mode 100644 index 0000000..a86b5bf --- /dev/null +++ b/.yamllint.yaml @@ -0,0 +1,17 @@ +# Taken from stackabletech/operator-templating (without the Helm ignore), +# keep in sync. +--- +extends: default + +rules: + line-length: disable + truthy: + check-keys: false + comments: + min-spaces-from-content: 1 # Needed due to https://github.com/adrienverge/yamllint/issues/443 + indentation: + indent-sequences: consistent + comments-indentation: disable # This is generally useless and interferes with commented example values + braces: + max-spaces-inside: 1 + max-spaces-inside-empty: 0 diff --git a/AGENTS.md b/AGENTS.md index 1406a13..b46c1d9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,14 +26,24 @@ grafana/ dashboard for the monitoring snapshot ## Before you finish a change -CI runs exactly these, all must pass: +CI runs the hooks in `.pre-commit-config.yaml` (through prek) and +`cargo-udeps`; all must pass. The Rust part of it: ```sh -cargo fmt --all --check +cargo +nightly-2026-11-02 fmt --all --check cargo clippy --workspace --all-targets --locked -- -D warnings cargo test --workspace --locked +RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps --document-private-items --locked +cargo deny --all-features check advisories bans licenses sources +RUSTC_BOOTSTRAP=1 cargo udeps --workspace --all-targets --locked ``` +`prek run --all-files` runs everything except `cargo-udeps`, including the +YAML, Markdown, Dockerfile and spelling lints. Formatting needs the nightly +toolchain (unstable options in `rustfmt.toml`). `deny.toml`, `rustfmt.toml` +and the lint configs are copied from stackabletech/operator-templating; keep +them in sync rather than editing them here. + Update `README.md` when behaviour, options, environment variables or metrics change. @@ -109,7 +119,8 @@ the README table and the dashboard legend panel. This repo follows the Stackable Rust style guide; the points that matter most, and where this repo differs: -**Errors** +### Errors + - `snafu` only (no `thiserror`, no `anyhow`). One `Error` enum per module, explicit `.context(…Snafu)` at every call site; never `#[snafu(context(false))]`. @@ -121,19 +132,22 @@ most, and where this repo differs: - Use `crate::sync::error_chain` to log an error with its full source chain on one line. -**Panics** +### Panics + - No `unwrap()`, also not in tests. `unwrap_or*` are fine. - `expect("…")` only where failure is impossible; the message states the invariant (`must` in production code, `should` in tests). -**Types and signatures** +### Types and signatures + - No sentinel values (empty string, `-1`) for "nothing": use `Option`. - Take owned values when you need ownership, instead of cloning a reference inside. - `Option` variables carry no `maybe_` / `opt_` prefix. Use full words for names, except in closures. -**Formatting and docs** +### Formatting and docs + - `format!`/`println!` with three or more substitutions use named arguments. Some older code still uses positional ones; fix them when you touch it. - Every item gets a doc comment (summary sentence ending in a full stop); @@ -143,7 +157,8 @@ most, and where this repo differs: - Enum variants and struct fields with doc comments or attributes are separated by blank lines. -**Tests** +### Tests + - Unit tests live in a `#[cfg(test)] mod tests` in the same file. - Names describe what is verified, without a `test_` prefix. - Prefer `assert_eq!` over `assert!`. For several inputs the guide asks for @@ -152,7 +167,8 @@ most, and where this repo differs: - No network in tests. Keep mapping and classification logic pure so it can be tested without the APIs (see `snapshot` in `src/sync/report.rs`). -**Dependencies** +### Dependencies + - Check the licence before adding a crate: it must be compatible with Apache-2.0, the project's licence. - Keep the binary statically linkable: avoid crates with C dependencies, and diff --git a/README.md b/README.md index a77dc65..e0428b6 100644 --- a/README.md +++ b/README.md @@ -147,7 +147,8 @@ easybill customer number. A linked contact is updated in place and gets `ContactNumber` set, so later runs link by that. Otherwise a new contact is created. -Colliding display names get a ` ()` suffix (Xero requires unique names). +Colliding display names get a numbered suffix such as `Acme (2)` (Xero requires +unique names). A customer is **blocked** instead when its `AccountNumber` matches several unlinked contacts, or when it would get a new contact whose name matches an existing contact that isn't linked to any easybill customer (most likely the @@ -198,13 +199,13 @@ and an expiring access token is renewed during long runs. Every log line carries the context it was logged in, as `tracing` spans: -| Span | Fields | -|--------------------------------------|---------------------------------------------------------| -| `run` | `run_id`, `command` | -| `sync_customers` / `sync_documents` | the command's options | -| `customer` | `customer_id`, `contact_id` | -| `document` | `document_id`, `number`, `xero_id`, `outcome` | -| `xero_request` / `easybill_request` | `context` (e.g. `PUT /Invoices`), `http.response.status_code` | +| Span | Fields | +|-------------------------------------|---------------------------------------------------------------| +| `run` | `run_id`, `command` | +| `sync_customers` / `sync_documents` | the command's options | +| `customer` | `customer_id`, `contact_id` | +| `document` | `document_id`, `number`, `xero_id`, `outcome` | +| `xero_request` / `easybill_request` | `context` (e.g. `PUT /Invoices`), `http.response.status_code` | In JSON, `span` is the innermost span and `spans` the whole stack, so every line can be filtered by `run_id` or `document_id`. In JSON mode the final @@ -234,17 +235,17 @@ Document statuses: `synced`, `approved_in_xero`, `skipped` (fine), and `ok`, `blocked`, `failed`. A document failing for a reason other than its own data counts as `failed_customer` if its customer's last sync failed. -| Metric | Labels | -|----------------------------------------------------------------|----------------------------------------------------------------| -| `easybill_xero_last_run_timestamp_seconds` | `command` | -| `easybill_xero_last_run_success` (1/0, failed items don't count) | `command` | -| `easybill_xero_last_success_timestamp_seconds` | `command` | -| `easybill_xero_documents` / `easybill_xero_customers` (counts) | `status` | -| `easybill_xero_document_issue_since_timestamp_seconds` | `document_id`, `number`, `status`, `customer_id`, `currency` | -| `easybill_xero_document_issue_amount` (gross, credit notes negative) | same | -| `easybill_xero_document_issue_reported_at_timestamp_seconds` | same | -| `easybill_xero_customer_issue_since_timestamp_seconds` | `customer_id`, `status` | -| `easybill_xero_customer_issue_reported_at_timestamp_seconds` | `customer_id`, `status` | +| Metric | Labels | +|----------------------------------------------------------------------|--------------------------------------------------------------| +| `easybill_xero_last_run_timestamp_seconds` | `command` | +| `easybill_xero_last_run_success` (1/0, failed items don't count) | `command` | +| `easybill_xero_last_success_timestamp_seconds` | `command` | +| `easybill_xero_documents` / `easybill_xero_customers` (counts) | `status` | +| `easybill_xero_document_issue_since_timestamp_seconds` | `document_id`, `number`, `status`, `customer_id`, `currency` | +| `easybill_xero_document_issue_amount` (gross, credit notes negative) | same | +| `easybill_xero_document_issue_reported_at_timestamp_seconds` | same | +| `easybill_xero_customer_issue_since_timestamp_seconds` | `customer_id`, `status` | +| `easybill_xero_customer_issue_reported_at_timestamp_seconds` | `customer_id`, `status` | The values are written once per run, so between runs Prometheus has no current sample: query with `last_over_time(…[25h])` (longer than the @@ -284,19 +285,37 @@ The entrypoint is the binary; pass the command as arguments. It runs as uid ## CI -[`.github/workflows/build.yaml`](./.github/workflows/build.yaml) runs -`cargo fmt`, `clippy` and the tests, then builds the image: +Pull requests run these checks; all are meant to be required before merging: + +| Check | Workflow | What it runs | +|-----------------------|----------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `prek` | [`pr_prek.yaml`](./.github/workflows/pr_prek.yaml) | the hooks in [`.pre-commit-config.yaml`](./.pre-commit-config.yaml): typos, cargo-deny, yamllint, markdownlint, actionlint, hadolint, `cargo doc`, nightly `rustfmt`, clippy, tests | +| `Run cargo-udeps` | [`build.yaml`](./.github/workflows/build.yaml) | unused dependencies | +| `Build/Publish Image` | [`build.yaml`](./.github/workflows/build.yaml) | a test build of the image | + +prek only runs the hooks whose files a pull request changes. To run them +locally, install [prek](https://github.com/j178/prek), cargo-deny, hadolint and +the nightly toolchain named in `pr_prek.yaml`, then `prek install` (on every +commit) or `prek run --all-files`. A daily job +([`general_daily_security.yml`](./.github/workflows/general_daily_security.yml)) +checks the dependencies against the RustSec advisory database, so new +advisories show up without a pull request. The setup follows the Stackable +operators; `deny.toml`, `rustfmt.toml` and the lint configs are copies of +theirs. + +[`build.yaml`](./.github/workflows/build.yaml) publishes the image: | Trigger | Published tags | |-----------------|--------------------------------------------------------| | tag `vX.Y.Z` | `X.Y.Z` (the tag must match the `Cargo.toml` version) | | push to `main` | `0.0.0-dev` (floating) and `0.0.0-dev-` | -| pull request | none (checks and a test build only) | +| pull request | none (test build only) | Images are published for `linux/amd64` to `oci.stackable.tech//easybill-xero`, where `` is the Harbor project set in the repository variable `REGISTRY_NAMESPACE`; the robot account's -secret is the repository secret `HARBOR_ROBOT_SECRET`. Published images are +secret is the repository secret +`HARBOR_ROBOT_STACKABLE_GITHUB_ACTION_BUILD_SECRET`. Published images are signed with cosign (keyless, via the workflow's GitHub identity): ```bash diff --git a/TODO.md b/TODO.md index a357bf0..168593c 100644 --- a/TODO.md +++ b/TODO.md @@ -57,7 +57,26 @@ commit if it isn't obvious. and hand-made state files, not in a real sync. - [ ] **Container build.** The OpenTelemetry dependencies haven't been built with the static Dockerfile yet (no C dependencies were added, so no problems - are expected). + are expected). The `Build/Publish Image` check on the first pull request + will show it; remove this item once that is green. - [ ] **Dev shell with Nix and direnv.** The credential loading in `shell.nix` was only tested as plain bash; `nix-shell` and `direnv allow` with the committed `.envrc` haven't been run. + +## CI + +- [ ] **Make the checks required.** `prek`, `Run cargo-udeps` and + `Build/Publish Image` only block merges once they are required in the + branch protection (or a ruleset) for `main`. That's a repository setting, + not part of the code. +- [ ] **Dev shell tooling.** `shell.nix` takes Rust from nixpkgs (not the + 1.99.1 in `rust-toolchain.toml`) and has no rustup, so the + `cargo +nightly-…` rustfmt hook fails in the Nix shell. prek, cargo-deny, + cargo-udeps and hadolint aren't in it either. Without them, `prek run` + doesn't work locally and CI is the first place the lints run. +- [ ] **Keep the copied configs in sync.** `deny.toml`, `rustfmt.toml`, + `.yamllint.yaml`, `.hadolint.yaml`, `.markdownlint.yaml` and the hook + versions in `.pre-commit-config.yaml` are copies from + stackabletech/operator-templating. Nothing updates them automatically; + without that, new advisory ignores or licence decisions there won't reach + this repo. diff --git a/deny.toml b/deny.toml new file mode 100644 index 0000000..30e53b1 --- /dev/null +++ b/deny.toml @@ -0,0 +1,141 @@ +# Taken from stackabletech/operator-templating, keep in sync. +# +# This file is the source of truth for all our repos! +# This includes repos not templated by operator-templating, please copy/paste the file for this repos. +# +# TIP: Use "cargo deny check" to check if everything is fine + +[graph] +targets = [ + { triple = "x86_64-unknown-linux-gnu" }, + { triple = "aarch64-unknown-linux-gnu" }, + { triple = "x86_64-unknown-linux-musl" }, + { triple = "aarch64-apple-darwin" }, + { triple = "x86_64-apple-darwin" }, +] + +[advisories] +yanked = "deny" +ignore = [ + # https://rustsec.org/advisories/RUSTSEC-2023-0071 + # "rsa" crate: Marvin Attack: potential key recovery through timing sidechannel + # + # No patch is yet available, however work is underway to migrate to a fully constant-time implementation. + # So we need to accept this, as of SDP 26.3 we are "only" using the crate to create private + + # public key pairs used by webhooks, such as conversion or mutating webhooks. + # + # https://github.com/RustCrypto/RSA/issues/19 is the tracking issue + "RUSTSEC-2023-0071", + + # https://rustsec.org/advisories/RUSTSEC-2024-0436 + # The "paste" crate is no longer maintained because the owner states that the implementation is + # finished. There are at least two (forked) alternatives which state to be maintained. They'd + # need to be vetted before a potential switch. Additionally, they'd need to be in a maintained + # state for a couple of years to provide any benefit over using "paste". + # + # This crate is only used in a single place in the xtask package inside the declarative + # "write_crd" macro. The impact of vulnerabilities, if any, should be fairly minimal. + # + # See thread: https://users.rust-lang.org/t/paste-alternatives/126787/4 + # + # This can only be removed again if we decide to use a different crate. + "RUSTSEC-2024-0436", + + # https://rustsec.org/advisories/RUSTSEC-2026-0097 + # rand 0.8.5 is unsound when log+thread_rng features are enabled and a custom logger calls rand::rng(). + # + # This version is pulled in transitively via num-bigint-dig -> rsa -> stackable-certs and cannot be + # updated until the upstream rsa crate bumps its rand dependency. + "RUSTSEC-2026-0097", + + # https://rustsec.org/advisories/RUSTSEC-2026-0173 + # The author of `proc-macro-error2` has [confirmed](https://github.com/GnomedDev/proc-macro-error-2/issues/17#issuecomment-4643215473) + # that the crate is no longer maintained and recommends that users migrate away from it. + # + # There currently is no way for us to negate this advisory, because that crate is not used + # directly by us. We need to wait for new versions of oci-spec and getset. See the following + # issue which tracks moving to a newer getset version: https://github.com/youki-dev/oci-spec-rs/issues/340 + # + # proc-macro-error2 v2.0.1 + # └── getset v0.1.6 + # └── oci-spec v0.9.0 + # └── boil v0.2.1 + # + # Alternate crates are: + # + # - https://crates.io/crates/manyhow + # - https://github.com/SergioBenitez/proc-macro2-diagnostics + "RUSTSEC-2026-0173", + + # https://rustsec.org/advisories/RUSTSEC-2026-0543 + # The chrono crate is unmaintained; all versions are affected. + # + # chrono v0.4.45 + # └── built v0.8.1 + # + # We already use jiff in a couple of places, but chrono comes in through an indirect dependency. + # Ideally upstream should switch to jiff (or time, which is also a valid alternative). + "RUSTSEC-2026-0543", + + # https://rustsec.org/advisories/RUSTSEC-2026-0542 + # Because chrono is now unmaintained and humantime wraps chrono, it is also unmaintained; all + # versions are affected. + # + # humantime v2.4.0 + # └── stackable-webhook v0.11.0 + # └── stackable-operator v0.122.0 + # + # humantime is only used in a single place to format timestamps according to RFC 3339. We + # already switched to jiff in https://github.com/stackabletech/operator-rs/pull/1335, + # but this change needs to be rolled out across all operators. + "RUSTSEC-2026-0542", +] + +[bans] +multiple-versions = "allow" + +[licenses] +unused-allowed-license = "allow" +confidence-threshold = 1.0 +allow = [ + "Apache-2.0", + "BSD-2-Clause", + "BSD-3-Clause", + "CC0-1.0", + "ISC", + "LicenseRef-ring", + "LicenseRef-webpki", + "MIT", + "MPL-2.0", + "OpenSSL", # Needed for the ring and/or aws-lc-sys crate. See https://github.com/stackabletech/operator-templating/pull/464 for details + "Unicode-3.0", + "Unicode-DFS-2016", + "Zlib", + "Unlicense", + "Apache-2.0 WITH LLVM-exception", # Needed for ar_archive_writer crate (transitive dependency) +] +private = { ignore = true } + +[[licenses.clarify]] +name = "ring" +expression = "LicenseRef-ring" +license-files = [ + { path = "LICENSE", hash = 0xbd0eed23 }, +] + +[[licenses.clarify]] +name = "webpki" +expression = "LicenseRef-webpki" +license-files = [ + { path = "LICENSE", hash = 0x001c7e6c }, +] + +[sources] +unknown-registry = "deny" +unknown-git = "deny" +allow-git = [ + "https://github.com/kube-rs/kube-rs", +] + +[sources.allow-org] +github = ["stackabletech"] diff --git a/easybill/src/client.rs b/easybill/src/client.rs index dda26c5..df26156 100644 --- a/easybill/src/client.rs +++ b/easybill/src/client.rs @@ -191,7 +191,9 @@ impl EasybillClient { /// /// # Errors /// - /// See [`Self::get_json`]. + /// Returns [`Error::Http`] if the request fails, [`Error::Api`] if + /// easybill answers with an error status and [`Error::Parse`] if the + /// response can't be deserialised. pub async fn customers_page(&self, page: u32, limit: u32) -> Result> { self.get_json( "customers", @@ -228,7 +230,9 @@ impl EasybillClient { /// /// # Errors /// - /// See [`Self::get_json`]. + /// Returns [`Error::Http`] if the request fails, [`Error::Api`] if + /// easybill answers with an error status and [`Error::Parse`] if the + /// response can't be deserialised. pub async fn customer(&self, id: i64) -> Result { self.get_json( &format!("customers/{id}"), @@ -243,7 +247,9 @@ impl EasybillClient { /// /// # Errors /// - /// See [`Self::get_json`]. + /// Returns [`Error::Http`] if the request fails, [`Error::Api`] if + /// easybill answers with an error status and [`Error::Parse`] if the + /// response can't be deserialised. pub async fn documents_page( &self, page: u32, diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 0000000..ead7997 --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,4 @@ +# Keep in sync with the builder image in the Dockerfile. +[toolchain] +channel = "1.99.1" +profile = "default" diff --git a/src/sync/customers.rs b/src/sync/customers.rs index 2f2caca..06de6b2 100644 --- a/src/sync/customers.rs +++ b/src/sync/customers.rs @@ -279,7 +279,7 @@ fn record_statuses( } /// Whether a customer's `updated_at` is `>= since`. A customer whose -/// `updated_at` is missing or unparseable counts as modified: syncing it again +/// `updated_at` is missing or unparsable counts as modified: syncing it again /// is harmless, skipping it silently is not. fn modified_since(customer: &Customer, since: Option) -> bool { let Some(since) = since else { diff --git a/src/xero/client.rs b/src/xero/client.rs index 0552f4b..ffa6d73 100644 --- a/src/xero/client.rs +++ b/src/xero/client.rs @@ -638,7 +638,7 @@ mod tests { } #[test] - fn retry_after_defaults_when_unparseable() { + fn retry_after_defaults_when_unparsable() { let mut headers = reqwest::header::HeaderMap::new(); headers.insert( RETRY_AFTER, From 3e6192aca261a1d57bd7dd0b928bc67191dccb93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=B6nke=20Liebau?= Date: Fri, 20 Nov 2026 17:59:27 +0000 Subject: [PATCH 5/5] Use the system CA certificates instead of webpki-roots webpki-roots is licensed CDLA-Permissive-2.0, which the shared deny.toml doesn't allow. The runtime image ships CA certificates, so reqwest now loads those (rustls-tls-native-roots), and trusted roots follow base image updates. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 79 ++++++++++++++++++++++++++++++++++++++------- Cargo.toml | 2 +- Dockerfile | 3 +- TODO.md | 4 ++- easybill/Cargo.toml | 2 +- 5 files changed, 75 insertions(+), 15 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b9dad4b..3e2c3b7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -223,6 +223,22 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + [[package]] name = "cpufeatures" version = "0.3.1" @@ -501,10 +517,10 @@ dependencies = [ "hyper", "hyper-util", "rustls", + "rustls-native-certs", "tokio", "tokio-rustls", "tower-service", - "webpki-roots", ] [[package]] @@ -803,6 +819,12 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + [[package]] name = "opentelemetry" version = "0.33.1" @@ -1157,6 +1179,7 @@ dependencies = [ "pin-project-lite", "quinn", "rustls", + "rustls-native-certs", "rustls-pki-types", "serde", "serde_json", @@ -1171,7 +1194,6 @@ dependencies = [ "wasm-bindgen", "wasm-bindgen-futures", "web-sys", - "webpki-roots", ] [[package]] @@ -1235,6 +1257,18 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + [[package]] name = "rustls-pki-types" version = "1.15.1" @@ -1268,6 +1302,38 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "serde" version = "1.0.229" @@ -1883,15 +1949,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "webpki-roots" -version = "1.0.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" -dependencies = [ - "rustls-pki-types", -] - [[package]] name = "windows-link" version = "0.2.1" diff --git a/Cargo.toml b/Cargo.toml index 94310ba..bc81484 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,7 +17,7 @@ path = "src/main.rs" [dependencies] easybill = { path = "easybill" } tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util", "time"] } -reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "json"] } +reqwest = { version = "0.12", default-features = false, features = ["rustls-tls-native-roots", "json"] } serde = { version = "1", features = ["derive"] } serde_json = "1" clap = { version = "4", features = ["derive", "env"] } diff --git a/Dockerfile b/Dockerfile index 2e7d05a..03168fb 100644 --- a/Dockerfile +++ b/Dockerfile @@ -13,7 +13,8 @@ # # DNS works without NSS modules: static glibc (>= 2.34) has the `files` and # `dns` lookups built in and reads /etc/hosts and /etc/resolv.conf. TLS roots -# are compiled into the binary (webpki-roots). +# come from the image's CA certificates (rustls-native-certs), so they follow +# base image updates. # # Find the latest version: diff --git a/TODO.md b/TODO.md index 168593c..47a24a6 100644 --- a/TODO.md +++ b/TODO.md @@ -58,7 +58,9 @@ commit if it isn't obvious. - [ ] **Container build.** The OpenTelemetry dependencies haven't been built with the static Dockerfile yet (no C dependencies were added, so no problems are expected). The `Build/Publish Image` check on the first pull request - will show it; remove this item once that is green. + will show whether it builds. Also run the image once against Xero and + easybill: TLS roots now come from the image's CA bundle + (`rustls-native-certs`), and that hasn't been tried in `hi/static` yet. - [ ] **Dev shell with Nix and direnv.** The credential loading in `shell.nix` was only tested as plain bash; `nix-shell` and `direnv allow` with the committed `.envrc` haven't been run. diff --git a/easybill/Cargo.toml b/easybill/Cargo.toml index c8d6389..bc15bd6 100644 --- a/easybill/Cargo.toml +++ b/easybill/Cargo.toml @@ -7,7 +7,7 @@ license = "Apache-2.0" publish = false [dependencies] -reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "json"] } +reqwest = { version = "0.12", default-features = false, features = ["rustls-tls-native-roots", "json"] } serde = { version = "1", features = ["derive"] } serde_json = "1" snafu = "0.8"