~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

The host keeps its logs and counts its use, for its operators

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:host/admin-logs-stats
crates/group-host/src/admin.rsnew+108−0
@@ -0,0 +1,108 @@
//! What the host's operators, the accounts `HOST_ADMINS` names, may read
//! of it: the lines it logged (`fyi.opensocial.getLogs`) and how it is
//! used (`fyi.opensocial.getStats`); and the writing of both, as it
//! serves.
use crate::Host;
use crate::group_api::signed_in;
use crate::logs::Asked;
use crate::rbac::NS;
use crate::space_api::forbidden;
use crate::xrpc::XrpcError;
use axum::Json;
use axum::extract::{Query, State};
use axum::http::HeaderMap;
use serde::Deserialize;
use serde_json::{Value, json};
use std::sync::Arc;
use std::time::{Duration, Instant};
type Answer = Result<Json<Value>, XrpcError>;
/// How often the lines logged and the counts are written.
pub const FLUSH: Duration = Duration::from_secs(1);
/// How often the oldest lines are let go.
const PRUNE: Duration = Duration::from_secs(60);
/// The caller of `lxm`, who must be one of the host's operators.
async fn operator(host: &Host, headers: &HeaderMap, lxm: &str) -> Result<String, XrpcError> {
let who = signed_in(host, headers, lxm).await?;
if !host.config.host_admins.contains(&who) {
return Err(forbidden("only this host's operators may read this"));
}
Ok(who)
}
/// The lines `asked` names, oldest first. The read is itself logged,
/// `logs read`, with who asked and for what.
pub async fn get_logs(
State(host): State<Arc<Host>>,
headers: HeaderMap,
Query(asked): Query<Asked>,
) -> Answer {
let did = operator(&host, &headers, &format!("{NS}.getLogs")).await?;
tracing::info!(did, asked = asked.said(), "logs read");
// What was logged up to now, this read's own line with it.
let read = host.logs.flush().and_then(|()| host.logs.read(&asked));
let lines = read.map_err(XrpcError::internal)?;
let lines: Vec<Value> = lines
.into_iter()
.map(|line| json!({"line": line}))
.collect();
Ok(Json(json!({ "lines": lines })))
}
#[derive(Deserialize)]
pub struct StatsAsked {
days: Option<u32>,
}
/// How the host was used over the last `days` days (7 unless asked),
/// and what it holds.
pub async fn get_stats(
State(host): State<Arc<Host>>,
headers: HeaderMap,
Query(asked): Query<StatsAsked>,
) -> Answer {
operator(&host, &headers, &format!("{NS}.getStats")).await?;
let counted = host.stats.flush().map_err(anyhow::Error::from);
let days = asked.days.unwrap_or(7);
let now = crate::time::now_millis();
let report = counted.and_then(|()| host.stats.report(&host.store, days, now));
Ok(Json(report.map_err(XrpcError::internal)?))
}
/// Writes the lines logged and the counts every `every`, and lets go of
/// the oldest lines every [`PRUNE`], at once the first time.
pub async fn keeping(host: Arc<Host>, every: Duration) {
let mut pruned: Option<Instant> = None;
loop {
wrote("logs", host.logs.flush());
wrote("stats", host.stats.flush());
if pruned.is_none_or(|t| t.elapsed() >= PRUNE) {
wrote("logs", host.logs.prune());
pruned = Some(Instant::now());
}
tokio::time::sleep(every).await;
}
}
/// Says, to stderr alone, why `what` was not written: it is written
/// with the next.
pub fn wrote(what: &str, done: rusqlite::Result<()>) {
if let Err(err) = done {
eprintln!("{what} not kept: {err:#}");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn says_what_was_not_kept() {
wrote("logs", Ok(()));
wrote("logs", Err(rusqlite::Error::InvalidQuery));
}
}
crates/group-host/src/config.rs+15−0
@@ -58,6 +58,12 @@ pub struct Config {
/// trailing slash: the PDS the console's "Create one" signs them up at,
/// by its authorization server's sign-up (`prompt=create`).
pub signup_pds: String,
/// Who runs this host, `HOST_ADMINS`, comma-separated DIDs: the
/// accounts that may read its logs and stats. None unless set.
pub host_admins: Vec<String>,
/// How many of the lines it logs at info and below it keeps to read
/// back, `LOGS_KEEP`; any line is kept 30 days at most.
pub logs_keep: u64,
}
/// The service that finds anyone on the network by what is typed.
@@ -144,6 +150,13 @@ impl Config {
if reqwest::Url::parse(&signup_pds).is_err() {
bail!("SIGNUP_PDS is no URL: {signup_pds}");
}
let host_admins = list("HOST_ADMINS");
let logs_keep = match var("LOGS_KEEP") {
Some(n) => n
.parse()
.with_context(|| format!("LOGS_KEEP is no number of lines: {n}"))?,
None => crate::logs::KEEP,
};
Ok(Config {
port,
public_url,
@@ -161,6 +174,8 @@ impl Config {
favicons,
actor_search,
signup_pds,
host_admins,
logs_keep,
})
}
crates/group-host/src/lexicons.rs+2−0
@@ -65,7 +65,9 @@ pub const FILES: &[&str] = &[
lexicon!("fyi/opensocial/getGroup"),
lexicon!("fyi/opensocial/getGroupAuth"),
lexicon!("fyi/opensocial/getJoinRequest"),
lexicon!("fyi/opensocial/getLogs"),
lexicon!("fyi/opensocial/getSpaceBlob"),
lexicon!("fyi/opensocial/getStats"),
lexicon!("fyi/opensocial/getSubjectHistory"),
lexicon!("fyi/opensocial/getViewer"),
lexicon!("fyi/opensocial/importAccount"),
crates/group-host/src/lib.rs+33−3
@@ -6,6 +6,7 @@
pub mod account_move;
pub mod actor_search;
pub mod actors;
pub mod admin;
pub mod api;
pub mod app_passwords;
pub mod authority;
@@ -32,6 +33,7 @@ pub mod index;
pub mod index_api;
pub mod lexicons;
pub mod lifecycle;
pub mod logs;
pub mod mcp;
pub mod member_writes;
pub mod migration;
@@ -43,6 +45,7 @@ pub mod oauth_dpop;
pub mod oauth_resource;
pub mod oauth_scope;
pub mod oauth_store;
pub mod observe;
pub mod plc;
pub mod provision;
pub mod rbac;
@@ -53,6 +56,7 @@ pub mod secrets;
pub mod sites;
pub mod space;
pub mod space_api;
pub mod stats;
pub mod store;
pub mod time;
pub mod token_writes;
@@ -91,6 +95,10 @@ pub struct Host {
pub(crate) clients: oauth_clients::Clients,
/// The handles the directory names, as last read for a search.
pub(crate) handles: actor_search::Handles,
/// The lines it logged, kept for its operators.
pub logs: Arc<logs::Logs>,
/// How it is used, counted for its operators.
pub stats: stats::Stats,
}
impl Host {
@@ -99,6 +107,8 @@ impl Host {
std::fs::create_dir_all(&config.data_dir)?;
let store = store::Store::open(&config.data_dir.join("host.sqlite"))?;
let secrets = secrets::Secrets::load(&config.data_dir)?;
let logs = logs::Logs::open(&config.data_dir.join("logs.sqlite"), config.logs_keep)?;
let stats = stats::Stats::open(&config.data_dir.join("stats.sqlite"))?;
let plc = plc::Directory::new(&config.plc_url);
let identity = identity::Resolver::new(&config.plc_url, &config.did_web_scheme);
// A clock id of its own, so two hosts' revisions never collide.
@@ -118,6 +128,8 @@ impl Host {
index_wake: Default::default(),
clients: Default::default(),
handles: Default::default(),
logs: Arc::new(logs),
stats,
})
}
}
@@ -132,8 +144,16 @@ pub fn client() -> reqwest::Client {
built.expect("a client with a timeout builds")
}
/// The host's routes.
/// The host's routes, each request logged and counted
/// ([`observe`]).
pub fn router(host: Arc<Host>) -> Router {
let observing = axum::middleware::from_fn_with_state(host.clone(), observe::observe);
routes(host).layer(observing)
}
/// The host's routes, as the MCP server calls them for a tool, within
/// the request that called it.
pub(crate) fn routes(host: Arc<Host>) -> Router {
// A site is published whole, its files in one body: as large as one
// upload may be, as the lexicons' check reads it.
let site_limit = usize::try_from(host.config.blob_upload_limit).unwrap_or(usize::MAX);
@@ -411,6 +431,8 @@ pub fn router(host: Arc<Host>) -> Router {
"/xrpc/fyi.opensocial.completeImport",
post(import::complete_import),
)
.route("/xrpc/fyi.opensocial.getLogs", get(admin::get_logs))
.route("/xrpc/fyi.opensocial.getStats", get(admin::get_stats))
.route(
"/xrpc/fyi.opensocial.importAccountSpace",
post(import_space::import_account_space),
@@ -618,6 +640,11 @@ pub async fn run(args: &[String], config: Config) -> anyhow::Result<()> {
pub async fn serve(config: Config) -> anyhow::Result<()> {
let listener = TcpListener::bind(("0.0.0.0", config.port)).await?;
println!("listening on {}", listener.local_addr()?);
let host = Arc::new(Host::open(config)?);
// Every line from here kept for the operators too, written as it goes.
logs::sink(&host.logs);
tokio::spawn(admin::keeping(host.clone(), admin::FLUSH));
let config = &host.config;
tracing::info!(
public_url = %config.public_url,
did = %config.service_did,
@@ -625,7 +652,6 @@ pub async fn serve(config: Config) -> anyhow::Result<()> {
commit = COMMIT,
"serving"
);
let host = Arc::new(Host::open(config)?);
// Uploads no record took, moves kept a day, and invites lapsed, swept
// now and each hour after.
let sweeping = host.clone();
@@ -660,11 +686,15 @@ pub async fn serve(config: Config) -> anyhow::Result<()> {
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
}
});
let app = router(host);
let app = router(host.clone());
axum::serve(listener, app)
.with_graceful_shutdown(stopped())
.await?;
tracing::info!("stopped");
// What was logged and counted since the last write, kept before it
// goes.
admin::wrote("logs", host.logs.flush());
admin::wrote("stats", host.stats.flush());
Ok(())
}
crates/group-host/src/logs.rsnew+442−0
442 lines changed: not loaded until asked for.
crates/group-host/src/main.rs+1−0
@@ -7,6 +7,7 @@ async fn main() -> anyhow::Result<()> {
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()),
)
.with_writer(group_host::logs::Tee::default)
.init();
let args: Vec<String> = std::env::args().skip(1).collect();
group_host::run(&args, group_host::config::Config::from_env()?).await
crates/group-host/src/mcp.rs+9−2
@@ -849,7 +849,7 @@ impl Host {
let mut request = request.expect("a request of a path and a body");
let value = cookie.parse().expect("a cookie is a header's value");
request.headers_mut().insert(header::COOKIE, value);
let res = crate::router(self.clone()).oneshot(request).await;
let res = crate::routes(self.clone()).oneshot(request).await;
let res = res.expect("the router answers every request");
let status = res.status();
let bytes = axum::body::to_bytes(res.into_body(), usize::MAX).await;
@@ -874,7 +874,14 @@ impl Host {
args: Value,
) -> Result<Value, String> {
let planned = group_host_mcp::plan(&tool, &args, &iso(now_millis()));
self.carry_out(who, planned?).await
let done = match planned {
Ok(planned) => self.carry_out(who, planned).await,
Err(why) => Err(why),
};
let ok = done.is_ok();
tracing::info!(tool = tool.name, ok, "mcp tool");
self.stats.tool(&tool.name, ok);
done
}
}
crates/group-host/src/migration.rs+1−1
@@ -409,7 +409,7 @@ pub(crate) async fn take_in(
let empty = host.sign(&account, &Tree::build(&BTreeMap::new()));
let made = host
.store
.create_account(&account, &empty, now_millis(), &[]);
.create_account(&account, &empty, now_millis() / 1000, &[]);
if !made.map_err(XrpcError::internal)? {
return Err(refused(
"HandleNotAvailable",
crates/group-host/src/observe.rsnew+93−0
@@ -0,0 +1,93 @@
//! What the host logs and counts of each request: a line, `request`,
//! with its method, route, path (never its query), status and duration,
//! in a trace of its own or the one its `traceparent` names, which every
//! line logged while answering it carries and the answer gives back as
//! `x-trace-id`; and a count in [`crate::stats`]. A trace is the
//! caller's to name, so one may name another's and have its lines read
//! with them. The health checks, asked every few seconds, are logged at
//! debug and not counted.
use crate::Host;
use axum::extract::{MatchedPath, Request, State};
use axum::http::{HeaderValue, Method};
use axum::middleware::Next;
use axum::response::Response;
use std::sync::Arc;
use std::time::Instant;
use tracing::Instrument;
/// The health checks' route.
const HEALTH: &str = "/xrpc/_health";
/// The routes that stream for as long as their reader stays.
const STREAMS: [&str; 1] = ["/xrpc/com.atproto.sync.subscribeRepos"];
/// What a request no route matched is counted as.
pub const UNMATCHED: &str = "(unmatched)";
/// A request's method as counted: one of HTTP's own, or any other as
/// `OTHER`, so a client sending methods of its making makes no more
/// counts.
pub fn method_of(method: &Method) -> &str {
const KNOWN: [Method; 7] = [
Method::GET,
Method::POST,
Method::PUT,
Method::DELETE,
Method::PATCH,
Method::HEAD,
Method::OPTIONS,
];
if KNOWN.contains(method) {
method.as_str()
} else {
"OTHER"
}
}
/// The trace `traceparent` names, if it is one (W3C Trace Context:
/// `00-<32 hex>-<16 hex>-<2 hex>`, its trace not all zeros); else a new
/// one.
pub fn trace_from(traceparent: Option<&str>) -> String {
let named = traceparent.and_then(|t| {
let parts: Vec<&str> = t.trim().split('-').collect();
let hex = |s: &str, n: usize| s.len() == n && s.bytes().all(|b| b.is_ascii_hexdigit());
let ok = matches!(parts.as_slice(), [v, trace, span, flags]
if hex(v, 2) && hex(trace, 32) && hex(span, 16) && hex(flags, 2)
&& trace.bytes().any(|b| b != b'0'));
ok.then(|| parts[1].to_ascii_lowercase())
});
named.unwrap_or_else(|| {
let mut bytes = [0u8; 16];
rand_core::RngCore::fill_bytes(&mut rand_core::OsRng, &mut bytes);
bytes.iter().map(|b| format!("{b:02x}")).collect()
})
}
/// Logs and counts the request, answered in its trace.
pub async fn observe(State(host): State<Arc<Host>>, req: Request, next: Next) -> Response {
let started = Instant::now();
let matched = req.extensions().get::<MatchedPath>();
let route = matched.map_or(UNMATCHED, MatchedPath::as_str).to_string();
let method = method_of(req.method()).to_string();
let path = req.uri().path().to_string();
let parent = req.headers().get("traceparent");
let trace = trace_from(parent.and_then(|v| v.to_str().ok()));
let span = tracing::info_span!("request", trace = %trace);
let mut res = next.run(req).instrument(span.clone()).await;
let took = started.elapsed();
let status = res.status().as_u16();
let id = HeaderValue::try_from(trace.as_str()).expect("hex is a header's value");
res.headers_mut().insert("x-trace-id", id);
let duration_ms = u64::try_from(took.as_millis()).unwrap_or(u64::MAX);
span.in_scope(|| {
if route == HEALTH {
tracing::debug!(method, route, path, status, duration_ms, "request");
return;
}
tracing::info!(method, route, path, status, duration_ms, "request");
let streams = STREAMS.contains(&route.as_str());
host.stats.served(&route, &method, status, took, streams);
});
res
}
crates/group-host/src/stats.rsnew+441−0
441 lines changed: not loaded until asked for.
crates/group-host/src/store.rs+5−0
@@ -421,6 +421,11 @@ pub const MIGRATIONS: &[&str] = &[
ALTER TABLE assistant_grant RENAME TO mcp_grant;
DROP INDEX IF EXISTS assistant_grant_member;
CREATE INDEX IF NOT EXISTS mcp_grant_member ON mcp_grant (grp, member);
",
// An account is made at a time in seconds, as a space is: those moved
// here were kept in milliseconds.
"
UPDATE account SET created_at = created_at / 1000 WHERE created_at > 100000000000;
",
];
crates/group-host/tests/admin.rsnew+147−0
@@ -0,0 +1,147 @@
//! What the host's operators read of it: the lines it logged, and how it
//! is used.
mod common;
use common::groups::*;
use common::{Running, start};
use serde_json::{Value as Json, json};
const LOGS: &str = "fyi.opensocial.getLogs";
const STATS: &str = "fyi.opensocial.getStats";
/// A host whose operator is the first of three people, who sign in at a
/// directory the host reads: the people, and the host.
async fn operated() -> ([common::spaces::Authority; 3], Running) {
let directory = start(&[], false).await;
let people = people(&directory).await;
let plc = directory.host.config.plc_url.clone();
let h = start(&[("PLC_URL", &plc), ("HOST_ADMINS", &people[0].did)], false).await;
(people, h)
}
/// A line as the host logs one, in `trace`.
fn line(message: &str, trace: &str) -> Vec<u8> {
let v = json!({"level": "INFO", "fields": {"message": message},
"spans": [{"name": "request", "trace": trace}]});
format!("{v}\n").into_bytes()
}
#[tokio::test]
async fn only_its_operators_read_its_logs_and_stats() {
let ([alice, bob, _], h) = operated().await;
for lxm in [LOGS, STATS] {
let (status, said) = get(&h, lxm, "", &[]).await;
assert_eq!((status, said["error"].as_str()), (401, Some("AuthMissing")));
let (status, said) = get(&h, lxm, "", &[auth(&h, &bob, lxm)]).await;
assert_eq!((status, said["error"].as_str()), (403, Some("Forbidden")));
let (status, said) = get(&h, lxm, "", &[auth(&h, &alice, lxm)]).await;
assert_eq!(status, 200, "{said}");
}
}
#[tokio::test]
async fn reads_one_requests_lines_by_its_trace() {
let ([alice, _, _], h) = operated().await;
h.host.logs.keep(&line("request", "aaaa"));
h.host.logs.keep(&line("indexed", "aaaa"));
h.host.logs.keep(&line("request", "bbbb"));
let (status, said) = get(&h, LOGS, "trace=aaaa", &[auth(&h, &alice, LOGS)]).await;
assert_eq!(status, 200, "{said}");
let messages: Vec<&Json> = said["lines"]
.as_array()
.unwrap()
.iter()
.map(|l| &l["line"]["fields"]["message"])
.collect();
assert_eq!(messages, ["request", "indexed"]);
let asked = "message=request&level=info&limit=1";
let (_, said) = get(&h, LOGS, asked, &[auth(&h, &alice, LOGS)]).await;
assert_eq!(said["lines"].as_array().unwrap().len(), 1);
// A read asking what the lexicon does not take is refused before it.
let (status, said) = get(&h, LOGS, "limit=501", &[auth(&h, &alice, LOGS)]).await;
assert_eq!(
(status, said["error"].as_str()),
(400, Some("InvalidRequest"))
);
}
#[tokio::test]
async fn counts_each_request_by_its_route_and_what_the_host_holds() {
let ([alice, _, _], h) = operated().await;
start_group(
&h,
&alice,
json!({"handle": "riders.groups.test", "displayName": "Riders"}),
)
.await;
// The health checks are not counted; a path no route answers is.
let traced = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01";
let res = h
.http
.get(format!("{}/xrpc/_health", h.url))
.header("traceparent", traced)
.send()
.await
.unwrap();
// The trace a request names is the one it is answered in.
assert_eq!(
res.headers()["x-trace-id"],
"0af7651916cd43dd8448eb211c80319c"
);
let (status, _) = h.get_path("/nowhere").await;
assert_eq!(status, 404);
// A method of the client's making is counted as one, whatever it is.
for method in ["BREW", "WHEN"] {
let method = reqwest::Method::from_bytes(method.as_bytes()).unwrap();
let asked = h
.http
.request(method, format!("{}/xrpc/fyi.opensocial.getGroup", h.url));
asked.send().await.unwrap();
}
let (status, said) = get(&h, STATS, "days=2", &[auth(&h, &alice, STATS)]).await;
assert_eq!(status, 200, "{said}");
assert_eq!(said["host"]["groups"], 1);
assert_eq!(said["host"]["spaces"], 2);
let today = &said["days"][1];
assert_eq!(today["groupsMade"], 1);
assert_eq!(today["spacesMade"], 2);
let routes = said["routes"].as_array().unwrap();
let route = |r: &str| routes.iter().find(|x| x["route"] == r).cloned();
let made = route("/xrpc/fyi.opensocial.createGroup").unwrap();
assert_eq!(
(made["method"].as_str(), made["requests"].as_i64()),
(Some("POST"), Some(1))
);
let unmatched = route("(unmatched)").unwrap();
assert_eq!(unmatched["refused"], 1);
let others: Vec<&Json> = routes.iter().filter(|x| x["method"] == "OTHER").collect();
assert_eq!(others.len(), 1, "{routes:?}");
assert_eq!(others[0]["requests"], 2);
assert_eq!(others[0]["route"], "/xrpc/fyi.opensocial.getGroup");
assert_eq!(route("/xrpc/_health"), None);
// A week unless asked.
let (_, said) = get(&h, STATS, "", &[auth(&h, &alice, STATS)]).await;
assert_eq!(said["days"].as_array().unwrap().len(), 7);
}
/// The lines and counts are written as the host serves, and the oldest
/// lines let go.
#[tokio::test]
async fn keeps_what_it_logs_and_counts_as_it_goes() {
let h = start(&[("LOGS_KEEP", "1")], false).await;
h.host.logs.keep(&line("first", "cccc"));
h.host.logs.keep(&line("second", "cccc"));
h.host.stats.tool("group_show", true);
let every = std::time::Duration::from_millis(10);
let going = tokio::spawn(group_host::admin::keeping(h.host.clone(), every));
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
going.abort();
let asked = group_host::logs::Asked::default();
let kept = h.host.logs.read(&asked).unwrap();
assert_eq!(kept.len(), 1, "{kept:?}");
let now = group_host::time::now_millis();
let report = h.host.stats.report(&h.host.store, 1, now).unwrap();
assert_eq!(report["days"][0]["toolCalls"], 1);
}
crates/group-host/tests/config.rs+16−0
crates/group-host/tests/mcp.rs+10−0
crates/group-host/tests/serve.rs+54−1
crates/opensocial/src/lib.rs+87−2
crates/opensocial/tests/commands.rs+66−1
docs/design/README.md+1−0
docs/reference/api.md+17−0
docs/reference/cli.md+15−3
docs/reference/config.md+6−3
docs/reference/mcp.md+2−1
docs/deploying.md+9−1
lexicons/fyi/opensocial/getLogs.jsonnew+78−0
lexicons/fyi/opensocial/getStats.jsonnew+200−0
AGENTS.md+3−2