Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/protocol.md
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,10 @@ without domain logic.
}
```

`collected_at` is an RFC 3339 timestamp with a UTC offset (`Z` or `±hh:mm`), the same
form as `log.at`. The server drops a `telemetry` frame whose `collected_at` is anything
else and keeps the connection open.

A `telemetry_collect` **request** (see tool catalog) returns the *same* snapshot
shape inside `response.result`, optionally restricted to `args.sections`.

Expand Down
3 changes: 3 additions & 0 deletions docs/telemetry.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ wire shape see [`protocol.md`](protocol.md).
default **every 15 minutes** (`KENNY_TELEMETRY_INTERVAL_SECS`, default `900`), plus an
**immediate first push** right after it connects, so a freshly onboarded PC appears with
real data at once. The on-demand `telemetry_collect` tool forces a "refresh now".
- Every snapshot carries the instant it was collected (`collected_at`, an RFC 3339
timestamp with a UTC offset). The server **drops** a pushed snapshot without one and
keeps the connection open; see [`protocol.md`](protocol.md).
- The server **persists** every snapshot in SQLite — the latest plus roughly **30 days of
per-agent history** for the health trend and heatmaps.
- A **daily rollup** distils the hardware-health signals (disk wear and error counters,
Expand Down
9 changes: 7 additions & 2 deletions kenny-agent/src/handlers/agent_update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -814,7 +814,12 @@ mod tests {
if !src.exists() {
return; // No `sleep` on this host; skip rather than fail.
}
let target = std::env::temp_dir().join(format!("kenny-wait-test-{}", std::process::id()));
// The copy keeps the file name `sleep` inside a private directory: where
// `sleep` is an applet of a multi-call binary (uutils, busybox), the binary
// picks the applet by the name it is run as and exits at once under any other.
let dir = std::env::temp_dir().join(format!("kenny-wait-test-{}", std::process::id()));
std::fs::create_dir_all(&dir).expect("create private dir");
let target = dir.join("sleep");
std::fs::copy(src, &target).expect("copy sleep binary");
// Make the copy executable for hosts that don't preserve the mode bit.
#[cfg(unix)]
Expand All @@ -838,7 +843,7 @@ mod tests {

let _ = child.kill();
let _ = child.wait();
let _ = std::fs::remove_file(&target);
let _ = std::fs::remove_dir_all(&dir);

assert!(
!freed,
Expand Down
6 changes: 3 additions & 3 deletions kenny-agent/src/handlers/cleanup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1022,7 +1022,7 @@ fn walk<O: Ops>(
match ops.remove_file(dir, &name, &meta, s.commit()) {
Ok(()) => {
s.files += 1;
s.bytes += meta.size;
s.bytes = s.bytes.saturating_add(meta.size);
s.deletions += 1;
}
Err(FsError::NotFound) => {}
Expand Down Expand Up @@ -1221,7 +1221,7 @@ fn sweep_recycle_user<O: Ops>(
match ops.remove_file(dir, &payload, &m, s.commit()) {
Ok(()) => {
s.files += 1;
s.bytes += m.size;
s.bytes = s.bytes.saturating_add(m.size);
s.deletions += 1;
true
}
Expand Down Expand Up @@ -1273,7 +1273,7 @@ fn sweep_recycle_user<O: Ops>(
match ops.remove_file(dir, &name, &info, s.commit()) {
Ok(()) => {
s.files += 1;
s.bytes += info.size;
s.bytes = s.bytes.saturating_add(info.size);
s.deletions += 1;
}
Err(FsError::NotFound) => {}
Expand Down
26 changes: 26 additions & 0 deletions kenny-agent/src/handlers/cleanup/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -711,6 +711,32 @@ mod linux_only {
use super::*;
use std::os::unix::fs::symlink;

/// Sizes are the file system's word, and a sparse file can claim 8 EiB: three of
/// them exceed `u64`. Needs a file system that allows such a length (tmpfs).
#[test]
fn reclaimed_bytes_saturate_on_huge_sparse_files() {
let root = PathBuf::from(format!(
"/dev/shm/kenny-cleanup-sparse-{}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&root);
if std::fs::create_dir_all(&root).is_err() {
return;
}
for i in 0..3 {
let f = std::fs::File::create(root.join(format!("f{i}"))).unwrap();
if f.set_len(i64::MAX as u64).is_err() {
let _ = std::fs::remove_dir_all(&root);
return;
}
}
let clock = TestClock::ahead(1);
let s = sweep(&root, &tmp_rules(0), true, &clock, unlimited());
let _ = std::fs::remove_dir_all(&root);
assert_eq!(s.files, 3);
assert_eq!(s.bytes, u64::MAX);
}

#[test]
fn symlinked_file_and_dir_are_never_followed() {
let t = Tree::new("links");
Expand Down
72 changes: 64 additions & 8 deletions kenny-agent/src/handlers/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,19 +77,40 @@ pub fn search(args: Value) -> Result<Value, (ErrorCode, String)> {
Ok(json!({ "matches": matches }))
}

/// `fs_read` — read a file, truncating at [`READ_CAP`] bytes.
/// `fs_read` — read a regular file, truncating at [`READ_CAP`] bytes.
///
/// Reads at most one byte past the cap, so the size of the file never decides how
/// much memory the call takes. Anything that is not a regular file is refused: a FIFO
/// blocks until someone writes to it and a character device such as `/dev/zero` never
/// ends.
pub fn read(args: Value) -> Result<Value, (ErrorCode, String)> {
use std::io::Read as _;

let args: PathArg = serde_json::from_value(args)
.map_err(|e| (ErrorCode::BadArgs, format!("invalid fs_read args: {e}")))?;
let bytes = std::fs::read(&args.path).map_err(map_io)?;
let truncated = bytes.len() > READ_CAP;
let slice = if truncated {
&bytes[..READ_CAP]
} else {
&bytes[..]
let not_regular = || {
(
ErrorCode::BadArgs,
format!("fs_read needs a regular file: {}", args.path),
)
};
// Checked before the open (opening a FIFO already blocks) and again on the open
// handle (the path may have been swapped in between).
if !std::fs::metadata(&args.path).map_err(map_io)?.is_file() {
return Err(not_regular());
}
let file = std::fs::File::open(&args.path).map_err(map_io)?;
if !file.metadata().map_err(map_io)?.is_file() {
return Err(not_regular());
}
let mut bytes = Vec::new();
file.take(READ_CAP as u64 + 1)
.read_to_end(&mut bytes)
.map_err(map_io)?;
let truncated = bytes.len() > READ_CAP;
bytes.truncate(READ_CAP);
Ok(json!({
"content": String::from_utf8_lossy(slice),
"content": String::from_utf8_lossy(&bytes),
"truncated": truncated,
}))
}
Expand All @@ -111,6 +132,41 @@ fn map_io(e: std::io::Error) -> (ErrorCode, String) {
mod tests {
use super::*;

#[test]
fn read_stops_at_the_cap_whatever_the_file_size() {
let dir = std::env::temp_dir().join(format!("kenny-fs-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
let big = dir.join("big.bin");
// Sparse: 8 GiB of length, no blocks. Reading it whole would need 8 GiB.
std::fs::File::create(&big)
.unwrap()
.set_len(8 << 30)
.unwrap();
let out = read(json!({"path": big.to_string_lossy()})).unwrap();
assert_eq!(out["truncated"], true);
assert_eq!(out["content"].as_str().unwrap().len(), READ_CAP);

let exact = dir.join("exact.bin");
std::fs::write(&exact, vec![b'a'; READ_CAP]).unwrap();
let out = read(json!({"path": exact.to_string_lossy()})).unwrap();
assert_eq!(out["truncated"], false);
assert_eq!(out["content"].as_str().unwrap().len(), READ_CAP);
std::fs::remove_dir_all(&dir).ok();
}

#[test]
fn read_refuses_a_directory() {
let err = read(json!({"path": std::env::temp_dir().to_string_lossy()})).unwrap_err();
assert_eq!(err.0, ErrorCode::BadArgs);
}

#[cfg(unix)]
#[test]
fn read_refuses_a_device_that_never_ends() {
let err = read(json!({"path": "/dev/zero"})).unwrap_err();
assert_eq!(err.0, ErrorCode::BadArgs);
}

#[test]
fn list_and_read_round_trip() {
let dir = std::env::temp_dir().join(format!("kenny-fs-{}", uuid::Uuid::new_v4()));
Expand Down
16 changes: 15 additions & 1 deletion kenny-agent/src/telemetry/collectors/web_activity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ pub mod core {
if obs.last_seen > existing.last_seen {
existing.last_seen = obs.last_seen;
}
existing.hits += obs.hits;
existing.hits = existing.hits.saturating_add(obs.hits);
for s in obs.sources {
if !existing.sources.contains(&s) {
existing.sources.push(s);
Expand Down Expand Up @@ -560,6 +560,20 @@ pub mod core {
assert_eq!(merged[1].domain, "b.example");
}

/// `visit_count` comes from a database the monitored user can write.
#[test]
fn merged_hits_saturate() {
let seen = |hits| Observation {
domain: "a.example.com".into(),
first_seen: "2026-06-04T18:00:00Z".into(),
last_seen: "2026-06-04T18:00:00Z".into(),
hits,
sources: vec!["browser_history".into()],
};
let (merged, _) = merge_observations(vec![seen(u64::MAX), seen(1)]);
assert_eq!(merged[0].hits, u64::MAX);
}

#[test]
fn merge_caps_at_250_and_flags_truncated() {
let mut obs = Vec::new();
Expand Down
13 changes: 12 additions & 1 deletion kenny-server/kenny_server/availability.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,17 @@ def _parse(value: TimeLike) -> datetime:
return parsed.astimezone(timezone.utc)


def _parses(value: Any) -> bool:
"""Whether a stored timestamp is usable. A snapshot's ``collected_at`` is the
agent's own string, so a stored row may hold one that is not an instant."""

try:
_parse(value)
except (TypeError, ValueError, OverflowError):
return False
return True


def _dt(value: TimeLike) -> datetime:
# Whole seconds: every boundary on one grid, so no segment is shorter than
# the precision it is reported at.
Expand Down Expand Up @@ -358,7 +369,7 @@ async def load_many(
first_sessions.get(agent_id),
agent_pushes[0] if agent_pushes else None,
)
if v
if v and _parses(v)
]
out[agent_id] = compute(
sessions=sessions.get(agent_id, []),
Expand Down
4 changes: 4 additions & 0 deletions kenny-server/kenny_server/health_rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -2021,6 +2021,10 @@ def evaluate_snapshot(
"""

now = now or datetime.now(timezone.utc)
if now.tzinfo is None:
# A stored ``collected_at`` without an offset is read as UTC; the rules
# subtract offset-aware instants from ``now``.
now = now.replace(tzinfo=timezone.utc)
is_windows = _is_windows(agent_os)
sections: dict[str, Any] = {}
for name, payload in snapshot.items():
Expand Down
24 changes: 23 additions & 1 deletion kenny-server/kenny_server/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@

from __future__ import annotations

from datetime import datetime, timezone
from typing import Annotated, Any, Literal, Union

from pydantic import BaseModel, ConfigDict, Field, TypeAdapter
from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, field_validator

# ---------------------------------------------------------------------------
# Shared / leaf types
Expand Down Expand Up @@ -148,6 +149,27 @@ class Telemetry(BaseModel):
collected_at: str
snapshot: dict[str, Section]

@field_validator("collected_at")
@classmethod
def _collected_at_is_an_instant(cls, value: str) -> str:
"""Refuse a ``collected_at`` that is not an RFC 3339 instant.

The stored value orders a host's snapshots, is the "as of" instant its
history is scored at and feeds the availability record; one that does
not parse, or names no offset, breaks those reads for the whole fleet.
"""

try:
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
if parsed.tzinfo is None:
raise ValueError("no UTC offset")
parsed.astimezone(timezone.utc)
except (ValueError, OverflowError):
raise ValueError(
"collected_at must be an RFC 3339 timestamp with a UTC offset"
) from None
return value


class Log(BaseModel):
"""``log`` frame: agent -> server, a structured log line."""
Expand Down
32 changes: 27 additions & 5 deletions kenny-server/kenny_server/tunnel.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,22 @@ def _token_auth_enabled() -> bool:
return os.environ.get("KENNY_ALLOW_TOKEN_AUTH", "1") not in ("0", "false", "")


async def _receive_text(websocket: WebSocket) -> str | None:
"""The next frame's text, or ``None`` for a binary frame.

Every kenny frame is a JSON text message (``docs/protocol.md`` § Transport).
Starlette's ``receive_text`` assumes one and raises ``KeyError`` on a binary
message, which anyone who can open a socket to ``/agent/ws`` can send, before
authenticating. Callers treat ``None`` like any other frame that is not a
known shape.
"""

try:
return await websocket.receive_text()
except KeyError:
return None


class ToolError(Exception):
"""Raised when a forwarded tool returns an error response or times out."""

Expand Down Expand Up @@ -441,9 +457,11 @@ async def _handshake_conn(self, websocket: WebSocket) -> tuple[str, int] | None:
reconnects while the policy frame is being re-sent.
"""

raw = await websocket.receive_text()
raw = await _receive_text(websocket)
try:
frame = parse_frame(raw)
# A binary first frame (``None``) fails validation like any other
# non-frame.
frame = parse_frame(raw if raw is not None else "")
except ValidationError:
# Malformed JSON or a frame that doesn't match any known shape
# (pydantic wraps JSON decode errors into ValidationError too, since
Expand Down Expand Up @@ -559,15 +577,15 @@ async def _handshake_signed(
# A stalled handshake must not pin the socket indefinitely.
try:
reply_raw = await asyncio.wait_for(
websocket.receive_text(), timeout=HANDSHAKE_TIMEOUT_S
_receive_text(websocket), timeout=HANDSHAKE_TIMEOUT_S
)
except asyncio.TimeoutError:
logger.warning("auth timeout for agent %s; closing 4401", frame.agent_id)
await websocket.close(code=4401)
return False

try:
auth = parse_frame(reply_raw)
auth = parse_frame(reply_raw) if reply_raw is not None else None
except Exception: # noqa: BLE001 - malformed frame
auth = None
if not isinstance(auth, Auth):
Expand Down Expand Up @@ -624,7 +642,7 @@ async def _serve(self, websocket: WebSocket, agent_id: str) -> str:
while True:
try:
raw = await asyncio.wait_for(
websocket.receive_text(), timeout=HEARTBEAT_TIMEOUT_SECS
_receive_text(websocket), timeout=HEARTBEAT_TIMEOUT_SECS
)
except asyncio.TimeoutError:
logger.info(
Expand All @@ -638,6 +656,10 @@ async def _serve(self, websocket: WebSocket, agent_id: str) -> str:
except Exception: # noqa: BLE001 - the peer is gone; closing is best-effort
logger.debug("closing a timed-out socket for %s failed", agent_id)
return "heartbeat_timeout"
if raw is None:
# Not a kenny frame at all; drop it like an unparseable one.
logger.warning("dropping binary frame from %s", agent_id)
continue
# Absolute ceiling: reject any frame too large to safely parse, before
# parsing/persisting it, so a compromised agent can't exhaust server
# memory (CWE-400/770). The strict per-kind caps for unsolicited pushes
Expand Down
Loading