guard_agent_rs/lib.rs
1//! guard-agent-rs: telemetry and monitoring agent for the Guard ecosystem.
2//!
3//! This crate is the Rust counterpart of the Python [`guard-agent`] and
4//! TypeScript [`guardagent`] telemetry agents. It ships security events,
5//! metrics, and agent status to the Guard ingestion API
6//! (`POST /api/v1/events`, `/api/v1/metrics`, `/api/v1/status`) with the same
7//! reliability semantics:
8//!
9//! - bounded per-kind buffers with `drop` (evict oldest), `block`, and
10//! `raise` overflow policies;
11//! - flush triggers on buffer high watermark and on a fixed interval;
12//! - at-least-once flush handshake: drain, send, confirm (delete persisted
13//! records) or requeue in original order;
14//! - transport retries with exponential backoff, honoring `Retry-After` on
15//! 429;
16//! - 413 split-or-drop with binary halving and a singleton drop threshold;
17//! - permanent rejection (400, 404, 422) drops the batch without retrying;
18//! - per-kind failure streaks with capped backoff and a computed degraded
19//! state;
20//! - optional Redis persistence with TTL and startup reload.
21//!
22//! Telemetry failures never propagate into the caller's request path:
23//! [`GuardAgent::send_event`] and [`GuardAgent::send_metric`] cannot fail,
24//! and every error is observable through [`GuardAgent::get_stats`], the
25//! computed [`AgentStatus`], logs, and the optional `on_error` hook.
26//!
27//! # Usage
28//!
29//! ```rust
30//! use guard_agent_rs::{AgentConfig, GuardAgent, SecurityEvent};
31//!
32//! # async fn example() {
33//! let mut config = AgentConfig::new("your-api-key-at-least-10-chars");
34//! config.endpoint = "https://api.guard-core.com".to_owned();
35//! config.install_id = Some("6f0a2880-1a2b-4c3d-9e4f-aabbccddeeff".to_owned());
36//! let agent = GuardAgent::new(config).expect("valid configuration");
37//!
38//! agent
39//! .send_event(
40//! SecurityEvent::new("rate_limited")
41//! .with_ip_address("10.0.0.1")
42//! .with_endpoint("/api/users")
43//! .with_action_taken("blocked"),
44//! )
45//! .await;
46//!
47//! let stats = agent.get_stats().await;
48//! assert_eq!(stats.events_buffered, 1);
49//! # }
50//! ```
51//!
52//! See the repository README for the full reliability contract and the
53//! `persistence` feature documentation for Redis-backed buffering.
54//!
55//! [`guard-agent`]: https://pypi.org/project/guard-agent/
56//! [`guardagent`]: https://github.com/Guard-Core/guard-agent-ts
57
58#![cfg_attr(docsrs, feature(doc_cfg))]
59
60pub mod agent;
61#[cfg(feature = "guard-core")]
62#[cfg_attr(docsrs, doc(cfg(feature = "guard-core")))]
63pub mod bridge;
64pub mod circuit_breaker;
65pub mod config;
66pub mod encryption;
67pub mod error;
68pub mod install_id;
69pub mod logging_utils;
70pub mod models;
71pub mod persistence;
72pub mod rate_limiter;
73pub mod signing;
74pub mod transport;
75pub mod utils;
76
77pub use agent::{AgentStats, GuardAgent, LoopFailures};
78#[cfg(feature = "guard-core")]
79#[cfg_attr(docsrs, doc(cfg(feature = "guard-core")))]
80pub use bridge::GuardAgentTelemetry;
81pub use circuit_breaker::CircuitBreakerState;
82pub use config::{
83 AgentConfig, BufferOverflowPolicy, DEFAULT_BACKOFF_FACTOR, DEFAULT_BUFFER_SIZE,
84 DEFAULT_COMPRESSION_THRESHOLD, DEFAULT_DYNAMIC_RULE_INTERVAL_SECS, DEFAULT_ENDPOINT,
85 DEFAULT_FLUSH_INTERVAL_SECS, DEFAULT_HIGH_WATERMARK_RATIO, DEFAULT_MAX_PAYLOAD_SIZE,
86 DEFAULT_RETRY_ATTEMPTS, DEFAULT_SENSITIVE_HEADERS, DEFAULT_STATUS_INTERVAL_SECS,
87 DEFAULT_TIMEOUT_SECS, MIN_API_KEY_LEN, MIN_DYNAMIC_RULE_INTERVAL_SECS,
88 MIN_STATUS_INTERVAL_SECS,
89};
90#[cfg(feature = "persistence")]
91#[cfg_attr(docsrs, doc(cfg(feature = "persistence")))]
92pub use config::{DEFAULT_REDIS_KEY_PREFIX, RedisConfig};
93pub use encryption::{PayloadEncryptor, canonical_json, urlsafe_base64_encode};
94pub use error::{ConfigError, ErrorStage, GuardAgentError};
95pub use models::{
96 AgentHealth, AgentStatus, DynamicRules, KNOWN_EVENT_TYPES, MetricType, SecurityEvent,
97 SecurityMetric,
98};
99#[cfg(feature = "persistence")]
100#[cfg_attr(docsrs, doc(cfg(feature = "persistence")))]
101pub use persistence::RedisClientHandler;
102pub use persistence::{
103 InMemoryRedisStore, NAMESPACE_EVENTS, NAMESPACE_METRICS, PERSIST_TTL_SECONDS, RedisHandler,
104};
105pub use rate_limiter::RateLimiter;
106pub use utils::{hash_ip, truncate_payload};
107
108/// Version of this agent, reported in batch payloads and the User-Agent.
109pub const AGENT_VERSION: &str = env!("CARGO_PKG_VERSION");
110
111/// Test-only support shared by the unit-test modules of this crate.
112///
113/// The unit test binary installs no logger by default, and the `log` facade
114/// skips a record's argument evaluation entirely when the level filter is
115/// lower than the record, so every `warn!`/`info!` branch whose interior
116/// regions are part of the coverage surface needs a trace-level logger
117/// installed before the branch fires. The installer is idempotent.
118#[cfg(test)]
119pub(crate) mod test_support {
120 /// A logger that swallows every record (the tests only need the argument
121 /// evaluation side effect of an installed, fully-enabled logger).
122 struct TraceLogger;
123
124 impl log::Log for TraceLogger {
125 fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
126 metadata.level() <= log::max_level()
127 }
128
129 fn log(&self, _record: &log::Record<'_>) {}
130
131 fn flush(&self) {}
132 }
133
134 /// Installs the trace logger exactly once. Every test that depends on
135 /// log-argument evaluation calls this first; `log` admits a single
136 /// logger per process, so later calls are no-ops.
137 pub fn install_trace_logger() {
138 static SETUP: std::sync::Once = std::sync::Once::new();
139 SETUP.call_once(|| {
140 let _ = log::set_boxed_logger(Box::new(TraceLogger));
141 log::set_max_level(log::LevelFilter::Trace);
142 });
143 }
144
145 #[test]
146 fn trace_logger_contract_holds() {
147 install_trace_logger();
148 let logger = TraceLogger;
149 let metadata = log::Metadata::builder().level(log::Level::Warn).build();
150 assert!(
151 log::Log::enabled(&logger, &metadata),
152 "trace level admits warnings"
153 );
154 let record = log::Record::builder()
155 .args(format_args!("test record"))
156 .level(log::Level::Warn)
157 .target(module_path!())
158 .build();
159 log::Log::log(&logger, &record);
160 log::Log::flush(&logger);
161 }
162}