1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
// Copyright 2026 Paolo Vella
// SPDX-License-Identifier: MPL-2.0
//! Centralized audit store types — query parameters, results, and backend selection.
//!
//! Phase 43: These types define the query interface for structured audit log search.
//! They live in `vellaveto-types` (leaf crate) so both `vellaveto-audit` and
//! `vellaveto-server` can reference them without circular dependencies.
use serde::{Deserialize, Serialize};
/// Maximum number of entries returned per query (prevents OOM on large result sets).
pub const MAX_QUERY_LIMIT: u64 = 1_000;
/// Maximum text search length (bytes) to prevent ReDoS / excessive scan time.
pub const MAX_TEXT_SEARCH_LEN: usize = 512;
/// Maximum length of agent_id / tool filter strings.
pub const MAX_FILTER_STRING_LEN: usize = 256;
/// Maximum query offset to prevent DoS via astronomical skip values.
pub const MAX_QUERY_OFFSET: u64 = 1_000_000;
/// Maximum length of `tenant_id` filter string (bytes).
///
/// SECURITY (FIND-R203-003): Named constant replaces magic number 64 in validate().
pub const MAX_TENANT_ID_LEN: usize = 64;
/// Supported audit store backends.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum AuditStoreBackend {
/// Local JSONL file (default, always active).
#[default]
File,
/// PostgreSQL database (requires `postgres-store` feature).
Postgres,
}
/// Verdict filter for audit queries.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum VerdictFilter {
Allow,
Deny,
RequireApproval,
}
/// Query parameters for searching audit entries.
///
/// All fields are optional — omitted fields are not filtered.
/// `limit` is capped at [`MAX_QUERY_LIMIT`].
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AuditQueryParams {
/// ISO 8601 start time (inclusive).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub since: Option<String>,
/// ISO 8601 end time (exclusive).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub until: Option<String>,
/// Filter by agent ID (exact match on metadata.agent_id).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub agent_id: Option<String>,
/// Filter by tool name (exact match on action.tool).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tool: Option<String>,
/// Filter by verdict type.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub verdict: Option<VerdictFilter>,
/// Substring text search across tool, function, and metadata.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub text_search: Option<String>,
/// Minimum sequence number (inclusive).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub from_sequence: Option<u64>,
/// Maximum sequence number (inclusive).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub to_sequence: Option<u64>,
/// Maximum number of entries to return (default 100, max 1000).
#[serde(default = "default_limit")]
pub limit: u64,
/// Number of entries to skip for pagination.
#[serde(default)]
pub offset: u64,
/// Filter by tenant ID (exact match on entry.tenant_id). Phase 44.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tenant_id: Option<String>,
}
fn default_limit() -> u64 {
100
}
impl Default for AuditQueryParams {
fn default() -> Self {
Self {
since: None,
until: None,
agent_id: None,
tool: None,
verdict: None,
text_search: None,
from_sequence: None,
to_sequence: None,
limit: default_limit(),
offset: 0,
tenant_id: None,
}
}
}
impl AuditQueryParams {
/// Validate query parameters. Returns an error describing the first violation.
pub fn validate(&self) -> Result<(), String> {
// Cap limit
if self.limit > MAX_QUERY_LIMIT {
return Err(format!(
"limit {} exceeds maximum {}",
self.limit, MAX_QUERY_LIMIT
));
}
if self.limit == 0 {
return Err("limit must be > 0".to_string());
}
// SECURITY (FIND-R200-004): Cap offset to prevent DoS via astronomical skip values
// that force the backend to scan/skip huge numbers of rows.
if self.offset > MAX_QUERY_OFFSET {
return Err(format!(
"offset {} exceeds maximum {}",
self.offset, MAX_QUERY_OFFSET
));
}
// Validate filter string lengths
if let Some(ref agent_id) = self.agent_id {
// SECURITY (IMP-R198-013): Reject empty filter strings — they are
// semantically meaningless and likely caller errors.
if agent_id.is_empty() {
return Err("agent_id filter must not be empty".to_string());
}
if agent_id.len() > MAX_FILTER_STRING_LEN {
return Err(format!(
"agent_id length {} exceeds maximum {}",
agent_id.len(),
MAX_FILTER_STRING_LEN
));
}
if crate::has_dangerous_chars(agent_id) {
return Err("agent_id contains control or format characters".to_string());
}
}
if let Some(ref tool) = self.tool {
// SECURITY (IMP-R198-013): Reject empty filter strings.
if tool.is_empty() {
return Err("tool filter must not be empty".to_string());
}
if tool.len() > MAX_FILTER_STRING_LEN {
return Err(format!(
"tool length {} exceeds maximum {}",
tool.len(),
MAX_FILTER_STRING_LEN
));
}
if crate::has_dangerous_chars(tool) {
return Err("tool contains control or format characters".to_string());
}
}
if let Some(ref text_search) = self.text_search {
if text_search.is_empty() {
return Err("text_search must not be empty".to_string());
}
if text_search.len() > MAX_TEXT_SEARCH_LEN {
return Err(format!(
"text_search length {} exceeds maximum {}",
text_search.len(),
MAX_TEXT_SEARCH_LEN
));
}
if crate::has_dangerous_chars(text_search) {
return Err("text_search contains control or format characters".to_string());
}
// SECURITY (FIND-R198-007): Reject text_search consisting solely of
// SQL LIKE wildcards (% and _). Such patterns match everything and
// could be used for data exfiltration or DoS via full-table scan.
if text_search.chars().all(|c| c == '%' || c == '_') {
return Err(
"text_search must not consist solely of SQL wildcard characters".to_string(),
);
}
}
// Phase 44: Validate tenant_id filter
if let Some(ref tenant_id) = self.tenant_id {
if tenant_id.is_empty() {
return Err("tenant_id filter must not be empty".to_string());
}
// SECURITY (FIND-R203-003): Use named constant instead of magic number 64.
if tenant_id.len() > MAX_TENANT_ID_LEN {
return Err(format!(
"tenant_id length {} exceeds maximum {}",
tenant_id.len(),
MAX_TENANT_ID_LEN
));
}
if crate::has_dangerous_chars(tenant_id) {
return Err("tenant_id contains control or format characters".to_string());
}
}
// Validate sequence range ordering
if let (Some(from), Some(to)) = (self.from_sequence, self.to_sequence) {
if from > to {
return Err(format!(
"from_sequence ({from}) must be <= to_sequence ({to})"
));
}
}
// SECURITY (FIND-R198-006): Validate timestamps with full ISO 8601 parsing
// at validation time rather than deferring to query time. Malformed timestamps
// could bypass time-range filters or cause unexpected query behavior.
if let Some(ref since) = self.since {
if since.len() > 64 {
return Err("since timestamp too long".to_string());
}
if crate::has_dangerous_chars(since) {
return Err("since contains control or format characters".to_string());
}
crate::time_util::parse_iso8601_secs(since)
.map_err(|e| format!("since is not valid ISO 8601: {e}"))?;
}
if let Some(ref until) = self.until {
if until.len() > 64 {
return Err("until timestamp too long".to_string());
}
if crate::has_dangerous_chars(until) {
return Err("until contains control or format characters".to_string());
}
crate::time_util::parse_iso8601_secs(until)
.map_err(|e| format!("until is not valid ISO 8601: {e}"))?;
}
// SECURITY (FIND-R200-005, FIND-R202-001): Validate temporal ordering using parsed
// epoch seconds, not lexicographic string comparison. Lexicographic ordering can
// disagree with chronological ordering on edge cases (sub-second precision, timezone
// suffixes). Both timestamps were already parsed above, so re-parse is infallible.
if let (Some(ref since), Some(ref until)) = (&self.since, &self.until) {
let since_epoch = crate::time_util::parse_iso8601_secs(since)
.map_err(|e| format!("since is not valid ISO 8601: {e}"))?;
let until_epoch = crate::time_util::parse_iso8601_secs(until)
.map_err(|e| format!("until is not valid ISO 8601: {e}"))?;
if since_epoch >= until_epoch {
return Err(format!("since ({since}) must be before until ({until})"));
}
}
Ok(())
}
}
/// Result of an audit query.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AuditQueryResult {
/// Matching entries for this page.
pub entries: Vec<serde_json::Value>,
/// Total number of matching entries (across all pages).
pub total: u64,
/// Current offset.
pub offset: u64,
/// Page size used.
pub limit: u64,
}
impl AuditQueryResult {
/// Validate structural invariants on deserialized query results.
///
/// SECURITY (FIND-R224-005): Prevents oversized result sets from untrusted
/// deserialized payloads and ensures total >= entries.len() invariant.
pub fn validate(&self) -> Result<(), String> {
if u64::try_from(self.entries.len()).unwrap_or(u64::MAX) > MAX_QUERY_LIMIT {
return Err(format!(
"AuditQueryResult entries count {} exceeds MAX_QUERY_LIMIT {}",
self.entries.len(),
MAX_QUERY_LIMIT
));
}
if (u64::try_from(self.entries.len()).unwrap_or(u64::MAX)) > self.total {
return Err(format!(
"AuditQueryResult entries count ({}) exceeds total ({})",
self.entries.len(),
self.total
));
}
Ok(())
}
}
/// Status of the audit store backend.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AuditStoreStatus {
/// Which backend is active.
pub backend: AuditStoreBackend,
/// Whether the centralized store is enabled.
pub enabled: bool,
/// Whether the sink is healthy (for dual-write backends).
pub sink_healthy: bool,
/// Number of entries pending flush to the centralized store.
pub pending_count: usize,
}