api! and some more wicked ahh sql shi 100% made by codex

This commit is contained in:
lda
2026-04-27 04:22:36 +07:00 Verified
parent 4efa70c228
commit 23656cd6d7
11 changed files with 351 additions and 10 deletions
+64 -2
View File
@@ -8,8 +8,8 @@ use tracing::{info, warn};
use crate::api::json_error;
use crate::runtime::{AppState, SessionEvent};
use crate::state::{
AgentDeviceObservationInput, AgentDeviceObservationView, AuditEventInput,
DeviceIdentifierInput, KnownDeviceInput,
AgentDeviceObservationEvent, AgentDeviceObservationInput, AgentDeviceObservationView,
AuditEventInput, DeviceIdentifierInput, KnownDeviceInput,
};
#[derive(Debug, Deserialize)]
@@ -152,6 +152,16 @@ pub struct ListObservationsQuery {
pub limit: Option<usize>,
}
#[derive(Debug, Deserialize)]
pub struct ListObservationHistoryQuery {
pub agent_id: Option<String>,
pub kind: Option<String>,
pub mac: Option<String>,
pub ip: Option<String>,
pub observation_key: Option<String>,
pub limit: Option<usize>,
}
pub async fn healthz() -> &'static str {
"ok"
}
@@ -703,6 +713,46 @@ pub async fn list_agent_observations(
}
}
pub async fn list_agent_observation_history(
State(state): State<AppState>,
Query(query): Query<ListObservationHistoryQuery>,
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
let kind = normalized_query_value(query.kind).map(|value| value.to_ascii_lowercase());
let mac = normalized_query_value(query.mac).map(|value| value.to_ascii_lowercase());
let ip = normalized_query_value(query.ip);
let observation_key = normalized_query_value(query.observation_key);
match state
.store
.list_agent_observation_events(
query.agent_id.as_deref(),
kind.as_deref(),
mac.as_deref(),
ip.as_deref(),
observation_key.as_deref(),
query.limit.unwrap_or(500),
)
.await
{
Ok(events) => Ok((
StatusCode::OK,
Json(
events
.into_iter()
.map(agent_observation_event_response) // no-op premium
.collect::<Vec<_>>(),
),
)),
Err(err) => {
warn!(error = %err, "failed to list agent observation history");
Err(json_error(
StatusCode::INTERNAL_SERVER_ERROR,
"list_observation_history_failed",
&err.to_string(),
))
}
}
}
pub async fn state_stats(
State(state): State<AppState>,
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
@@ -734,6 +784,18 @@ fn agent_observation_response(
observation
}
fn agent_observation_event_response(
event: AgentDeviceObservationEvent,
) -> AgentDeviceObservationEvent {
event
}
fn normalized_query_value(value: Option<String>) -> Option<String> {
value
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
}
fn known_device_response(device: crate::state::KnownDevice) -> KnownDeviceResponse {
KnownDeviceResponse {
device_id: device.device_id,
+3 -2
View File
@@ -13,8 +13,9 @@ pub use control::{
EnrollTokenStatus, IssueEnrollTokenResponse, RevokeAgentResponse, RevokeEnrollTokenResponse,
StateStatsResponse, attach_device_identifier, attach_observation_identifier,
create_known_device, enroll, forget_known_device, healthz, issue_enroll_token,
list_agent_observations, list_enroll_tokens, list_known_devices, revoke_agent,
revoke_enroll_token, set_agent_nickname, state_stats, upload_agent_observations,
list_agent_observation_history, list_agent_observations, list_enroll_tokens,
list_known_devices, revoke_agent, revoke_enroll_token, set_agent_nickname, state_stats,
upload_agent_observations,
};
pub fn json_error(
+4
View File
@@ -97,6 +97,10 @@ fn control_api_routes() -> Router<AppState> {
"/api/v1/control/observations",
get(api::list_agent_observations),
)
.route(
"/api/v1/control/observations/history",
get(api::list_agent_observation_history),
)
.route(
"/api/v1/control/devices",
get(api::list_known_devices).post(api::create_known_device),
+3 -2
View File
@@ -3,6 +3,7 @@ mod types;
pub use store::Store;
pub use types::{
AgentDeviceObservationInput, AgentDeviceObservationView, AlertState, AuditEvent,
AuditEventFilter, AuditEventInput, DeviceIdentifierInput, KnownDevice, KnownDeviceInput,
AgentDeviceObservationEvent, AgentDeviceObservationInput, AgentDeviceObservationView,
AlertState, AuditEvent, AuditEventFilter, AuditEventInput, DeviceIdentifierInput, KnownDevice,
KnownDeviceInput,
};
+38 -4
View File
@@ -8,10 +8,10 @@ use tracing::{info, warn};
use uuid::Uuid;
use crate::state::types::{
AgentDeviceObservation, AgentDeviceObservationInput, AgentDeviceObservationView, AlertState,
AlertTransition, AuditEvent, AuditEventFilter, AuditEventInput, DeviceIdentifier,
DeviceIdentifierInput, EnrollTokenInfo, IssuedAgent, IssuedEnrollToken, KnownDevice,
KnownDeviceInput, KnownDeviceSummary, StateStats,
AgentDeviceObservation, AgentDeviceObservationEvent, AgentDeviceObservationInput,
AgentDeviceObservationView, AlertState, AlertTransition, AuditEvent, AuditEventFilter,
AuditEventInput, DeviceIdentifier, DeviceIdentifierInput, EnrollTokenInfo, IssuedAgent,
IssuedEnrollToken, KnownDevice, KnownDeviceInput, KnownDeviceSummary, StateStats,
};
pub struct Store {
@@ -397,6 +397,40 @@ mod tests {
.expect("event count should read");
assert_eq!(event_count, 1);
store
.upsert_agent_observations(
"agent-a",
vec![crate::state::AgentDeviceObservationInput {
kind: "dhcp".into(),
action: "remove".into(),
mac: Some("AA:BB:CC:DD:EE:FF".into()),
ip: Some("192.168.1.10".into()),
hostname: Some("lda".into()),
first_seen_unix: 10,
last_seen_unix: 30,
}],
)
.await
.expect("changed observation upsert should succeed");
let events = store
.list_agent_observation_events(
Some("agent-a"),
None,
Some("aa:bb:cc:dd:ee:ff"),
None,
None,
10,
)
.await
.expect("observation events should list");
assert_eq!(events.len(), 2);
assert_eq!(events[0].action, "remove");
assert_eq!(
events[0].observation_key,
"agent:agent-a:dhcp:mac:aa:bb:cc:dd:ee:ff"
);
cleanup_dir(&dir);
}
@@ -365,3 +365,29 @@ pub(in crate::state::store) fn agent_observation_view_from_row(
known_device,
})
}
pub(in crate::state::store) fn agent_observation_event_from_row(
row: AgentObservationEventRow,
) -> Result<AgentDeviceObservationEvent> {
let known_device = match (row.device_id, row.display_name, row.pinned) {
(Some(device_id), Some(display_name), Some(pinned)) => Some(KnownDeviceSummary {
device_id,
display_name,
pinned: pinned != 0,
}),
_ => None,
};
Ok(AgentDeviceObservationEvent {
event_id: row.event_id,
observation_key: row.observation_key,
agent_id: row.agent_id,
kind: row.kind,
action: row.action,
mac: row.mac,
ip: row.ip,
hostname: row.hostname,
ts_unix: u64::try_from(row.ts_unix)
.context("negative observation event timestamp in state db")?,
known_device,
})
}
@@ -53,6 +53,21 @@ pub(in crate::state::store) struct AgentObservationViewRow {
pub(in crate::state::store) pinned: Option<i64>,
}
pub(in crate::state::store) struct AgentObservationEventRow {
pub(in crate::state::store) event_id: String,
pub(in crate::state::store) observation_key: String,
pub(in crate::state::store) agent_id: String,
pub(in crate::state::store) kind: String,
pub(in crate::state::store) action: String,
pub(in crate::state::store) mac: Option<String>,
pub(in crate::state::store) ip: Option<String>,
pub(in crate::state::store) hostname: Option<String>,
pub(in crate::state::store) ts_unix: i64,
pub(in crate::state::store) device_id: Option<String>,
pub(in crate::state::store) display_name: Option<String>,
pub(in crate::state::store) pinned: Option<i64>,
}
pub(in crate::state::store) struct ObservationIdentifierRow {
pub(in crate::state::store) mac: Option<String>,
pub(in crate::state::store) ip: Option<String>,
@@ -194,4 +194,69 @@ impl Store {
.map(agent_observation_view_from_row)
.collect()
}
pub async fn list_agent_observation_events(
&self,
agent_id: Option<&str>,
kind: Option<&str>,
mac: Option<&str>,
ip: Option<&str>,
observation_key: Option<&str>,
limit: usize,
) -> Result<Vec<AgentDeviceObservationEvent>> {
let limit = limit.clamp(1, 1000);
let limit = i64::try_from(limit).context("observation event limit overflow")?;
let rows = sqlx::query_as!(
AgentObservationEventRow,
r#"SELECT events.event_id as "event_id!",
('agent:' || events.agent_id || ':' || events.kind || ':' ||
CASE
WHEN events.mac IS NOT NULL THEN 'mac:' || events.mac
WHEN events.ip IS NOT NULL THEN 'ip:' || events.ip
ELSE ''
END) as "observation_key!",
events.agent_id as "agent_id!",
events.kind as "kind!",
events.action as "action!",
events.mac,
events.ip,
events.hostname,
events.ts_unix,
known_devices.device_id,
known_devices.display_name,
known_devices.pinned
FROM agent_device_observation_events events
LEFT JOIN device_identifiers identifiers
ON identifiers.identifier_key =
CASE
WHEN events.mac IS NOT NULL THEN 'mac:' || events.mac
WHEN events.ip IS NOT NULL THEN 'ip:' || events.ip
END
LEFT JOIN known_devices ON known_devices.device_id = identifiers.device_id
WHERE (?1 IS NULL OR events.agent_id = ?1)
AND (?2 IS NULL OR events.kind = ?2)
AND (?3 IS NULL OR events.mac = ?3)
AND (?4 IS NULL OR events.ip = ?4)
AND (?5 IS NULL OR ('agent:' || events.agent_id || ':' || events.kind || ':' ||
CASE
WHEN events.mac IS NOT NULL THEN 'mac:' || events.mac
WHEN events.ip IS NOT NULL THEN 'ip:' || events.ip
ELSE ''
END) = ?5)
ORDER BY events.ts_unix DESC
LIMIT ?6"#,
agent_id,
kind,
mac,
ip,
observation_key,
limit
)
.fetch_all(&self.pool)
.await
.context("failed listing agent observation events")?;
rows.into_iter()
.map(agent_observation_event_from_row)
.collect()
}
}
+14
View File
@@ -91,6 +91,20 @@ pub struct AgentDeviceObservationView {
pub known_device: Option<KnownDeviceSummary>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentDeviceObservationEvent {
pub event_id: String,
pub observation_key: String,
pub agent_id: String,
pub kind: String,
pub action: String,
pub mac: Option<String>,
pub ip: Option<String>,
pub hostname: Option<String>,
pub ts_unix: u64,
pub known_device: Option<KnownDeviceSummary>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KnownDeviceSummary {
pub device_id: String,