summaryrefslogtreecommitdiffstats
path: root/src/http
diff options
context:
space:
mode:
Diffstat (limited to 'src/http')
-rw-r--r--src/http/auth.rs45
-rw-r--r--src/http/forms.rs5
-rw-r--r--src/http/mod.rs44
-rw-r--r--src/http/render.rs14
-rw-r--r--src/http/routes/mod.rs6
-rw-r--r--src/http/routes/mutations.rs3
-rw-r--r--src/http/routes/pages.rs9
-rw-r--r--src/http/sse.rs12
8 files changed, 31 insertions, 107 deletions
diff --git a/src/http/auth.rs b/src/http/auth.rs
index 8c56c1f..9689fd8 100644
--- a/src/http/auth.rs
+++ b/src/http/auth.rs
@@ -1,26 +1,11 @@
-//! Session and CSRF (§12: "form posts are plain `<form method=post>` with a
-//! CSRF token").
-//!
-//! One operator, one shared credential, no user table (§14). A session is an
-//! opaque random id held in memory; the CSRF token is derived from it, so a
-//! cross-site form cannot produce one it has not seen, and there is no token
-//! table to keep in step with the sessions.
-//!
-//! **The sid is the credential.** A sid is minted for anonymous visitors too,
-//! because the CSRF token has to be derivable before anyone has typed a
-//! password; what the password buys is the `authenticated` flag on one sid.
-//! Nothing else in the request proves who you are, which is why there is no
-//! separate "logged in" cookie to forge.
-
use std::collections::HashMap;
use std::sync::Mutex;
use std::sync::OnceLock;
use crate::hash;
-/// Live sids and whether each has passed the password gate. One map, so the
-/// two facts cannot drift apart: dropping a session removes its authentication
-/// with it.
+/// Live sids and whether each has passed the password gate. One map, so
+/// dropping a session removes its authentication with it.
static SESSIONS: OnceLock<Mutex<HashMap<String, bool>>> = OnceLock::new();
fn sessions() -> &'static Mutex<HashMap<String, bool>> {
@@ -28,19 +13,14 @@ fn sessions() -> &'static Mutex<HashMap<String, bool>> {
}
/// Random hex token from the system RNG, or `None` when there is no usable one.
-///
-/// The old version read `/dev/urandom` into a zeroed buffer, ignored every
-/// error, and hashed the result anyway (§6 m-13): a failed read produced a
-/// session id derived from a buffer of zeros plus the clock and a counter,
-/// which is guessable by anyone who can guess roughly when the process started
-/// — and nothing anywhere said the RNG had failed. A session id is the whole
-/// credential now (C-1), so "no RNG" is a refusal, not a weaker token.
+/// A session id is the whole credential (C-1), so "no RNG" is a refusal rather
+/// than a weaker, guessable token.
fn random_hex() -> Option<String> {
use std::io::Read;
let mut buf = [0u8; 32];
let mut f = std::fs::File::open("/dev/urandom").ok()?;
f.read_exact(&mut buf).ok()?;
- // Mixed in regardless, so two calls in the same instant still differ.
+ // Mixed in so two calls in the same instant still differ.
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
@@ -68,8 +48,7 @@ pub fn is_valid_session(sid: &str) -> bool {
sessions().lock().map(|s| s.contains_key(sid)).unwrap_or(false)
}
-/// Mark a session as having passed the password gate. Only ever called with a
-/// sid this process minted, and it cannot mint one: an unknown sid stays
+/// Mark a session as having passed the password gate. An unknown sid stays
/// unknown rather than being inserted as a side effect of a login attempt.
pub fn authenticate(sid: &str) {
if let Ok(mut s) = sessions().lock() {
@@ -79,8 +58,8 @@ pub fn authenticate(sid: &str) {
}
}
-/// The gate's whole question: is this sid one we issued *and* did someone type
-/// the password into a form on this session?
+/// The gate's whole question: is this sid one we issued, and did someone type
+/// the password into a form on it?
pub fn is_authenticated(sid: &str) -> bool {
sessions().lock().map(|s| s.get(sid).copied().unwrap_or(false)).unwrap_or(false)
}
@@ -91,8 +70,8 @@ pub fn drop_session(sid: &str) {
}
}
-/// The CSRF token for a session. Derived rather than stored: it cannot drift
-/// out of sync with the session, and it is cheap to recompute per request.
+/// The CSRF token for a session. Derived rather than stored, so it cannot drift
+/// out of sync with the session.
pub fn csrf_token(sid: &str) -> String {
hash::hex(format!("csrf|{sid}").as_bytes())[..32].to_string()
}
@@ -125,8 +104,8 @@ pub fn parse_cookies(header: &str) -> Vec<(String, String)> {
.collect()
}
-/// Check the shared password. Empty password means the UI is open, which is the
-// default on loopback; the CSRF gate still applies.
+/// An empty password means the UI is open, which is the default on loopback;
+/// the CSRF gate still applies.
pub fn password_ok(cfg: &crate::config::Config, given: &str) -> bool {
cfg.password.is_empty() || constant_time_eq(&cfg.password, given)
}
diff --git a/src/http/forms.rs b/src/http/forms.rs
index 6e36e38..03da7b8 100644
--- a/src/http/forms.rs
+++ b/src/http/forms.rs
@@ -1,8 +1,3 @@
-//! `application/x-www-form-urlencoded` parsing and HTML escaping.
-//!
-//! Deliberately tiny: the only forms in this application are ours, so we need
-//! decoding for names, versions and hashes — not a general MIME parser.
-
/// Percent-decode one token (`+` means space in a form body).
pub fn decode(s: &str) -> String {
let bytes = s.as_bytes();
diff --git a/src/http/mod.rs b/src/http/mod.rs
index 81c526c..11ea107 100644
--- a/src/http/mod.rs
+++ b/src/http/mod.rs
@@ -1,16 +1,3 @@
-//! The web surface (§12).
-//!
-//! `tiny_http`, thread-per-connection, blocking. Handlers **read** through the
-//! thread-local read-only connections and never touch the write connection;
-//! mutations are handed to the writer actor as a transaction request. That is
-//! what keeps a slow browser from ever holding the database lock.
-//!
-//! Two guards on every POST: a session id, and a CSRF token that must match
-//! it. The session id is the only credential the browser holds, and it counts
-//! as authentication only if someone typed the password into a form on that
-//! exact session (§12). Forms are plain `<form method=post>`, so the whole
-//! approval flow works with JavaScript switched off.
-
mod auth;
mod forms;
mod render;
@@ -36,10 +23,8 @@ pub struct Req {
pub body: String,
pub cookies: Vec<(String, String)>,
pub query_pairs: Vec<(String, String)>,
- /// The body's form pairs, parsed once when the request is decoded (n-3).
- /// `form_get` used to re-parse the whole body on every call, and a single
- /// handler — approve, with its two hashes, its note and its CSRF token —
- /// asks five times.
+ /// The body's form pairs, parsed once when the request is decoded (n-3) — a
+ /// single handler asks for five of them.
pub form_pairs: Vec<(String, String)>,
/// Whether the client said it can take gzip. Used to decide whether to hand
/// out the precompressed static asset.
@@ -67,9 +52,9 @@ pub struct Res {
pub content_type: String,
pub body: Vec<u8>,
pub headers: Vec<(String, String)>,
- /// When set, the response body is produced by reading this to EOF instead of
- /// `body`. Used for the log tail (§13), which must stream bytes as a build
- /// appends them rather than buffering a response that never finishes.
+ /// When set, the body is produced by reading this to EOF instead of `body`.
+ /// Used for the log tail (§13), which must stream bytes as a build appends
+ /// them rather than buffering a response that never finishes.
pub stream: Option<Box<dyn std::io::Read + Send>>,
/// Length of `stream` when it is known up front, so the response can carry a
/// Content-Length instead of chunked transfer encoding.
@@ -84,8 +69,8 @@ impl Res {
Self { status, content_type: "text/plain; charset=utf-8".into(), body: body.into_bytes(), headers: Vec::new(), stream: None, stream_len: None }
}
/// A streamed response. `known_len` lets a static file be sent with a
- /// Content-Length instead of chunked, which is what a browser wants for a
- /// file it already knows the size of.
+ /// Content-Length, which is what a browser wants for a file whose size it
+ /// already knows.
pub fn stream(content_type: &str, reader: impl std::io::Read + Send + 'static, known_len: Option<usize>) -> Self {
Self {
status: 200,
@@ -221,8 +206,8 @@ fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result<
request.respond(builder)
}
-/// Route table (§12). Everything is one flat match: there is no middleware
-/// stack, just the session gate and then a path.
+/// Route table (§12). One flat match: no middleware stack, just the session gate
+/// and then a path.
fn dispatch(state: &State, req: &Req) -> Res {
let seg: Vec<&str> = req.path.trim_matches('/').split('/').filter(|s| !s.is_empty()).collect();
let is_get = req.method == "GET";
@@ -233,17 +218,16 @@ fn dispatch(state: &State, req: &Req) -> Res {
("GET", ["login"]) => return routes::login_form(state, req),
("POST", ["login"]) => return routes::login(state, req),
("GET", ["healthz"]) => return Res::text(200, "ok\n".into()),
- // Metrics are counts only — no package names, no versions, no audit
- // detail — and a Prometheus scraper has no session to present. Serving
- // them unauthenticated is what makes them scrapeable at all; the bind
- // address is loopback by default, which is where that is safe.
+ // Metrics are counts only — no package names, versions, or audit detail
+ // — and a Prometheus scraper has no session to present. The bind address
+ // is loopback by default, which is where this is safe.
("GET", ["metrics"]) => return routes::metrics(state),
_ => {}
}
// Session gate: mint a session for anonymous visitors so the CSRF token
- // exists even before anyone logs in. It is not a login — `gate` only lets
- // through a sid that a successful login marked authenticated.
+ // exists before anyone logs in. It is not a login — `gate` only lets through
+ // a sid that a successful login marked authenticated.
let (sid, new_session) = match req.cookie("sid") {
Some(s) if auth::is_valid_session(&s) => (s, false),
_ => match auth::new_session() {
diff --git a/src/http/render.rs b/src/http/render.rs
index ca3ba51..f049a25 100644
--- a/src/http/render.rs
+++ b/src/http/render.rs
@@ -1,9 +1,3 @@
-//! Template contexts (§12, §13).
-//!
-//! Askama compiles every template into Rust at build time, so a missing field
-//! is a compile error rather than a blank page at 2am. Contexts are built from
-//! live DB state; nothing here writes.
-
use askama::Template;
/// Everything the shared chrome needs. Embedded in each page context because
@@ -293,8 +287,7 @@ pub struct Builds {
pub recent: Vec<BuildRow>,
}
-/// The same table on its own, for the htmx fragment refresh. Same fields, so
-/// the include in builds.html and this standalone render cannot drift apart.
+/// The same table on its own, for the htmx fragment refresh.
#[derive(Template)]
#[template(path = "builds_table.html")]
pub struct BuildsTable {
@@ -386,13 +379,10 @@ pub struct SettingRow {
pub value: String,
}
-/// Vendored static assets. htmx arrives in P3; until then this serves the
-/// favicon and refuses everything else rather than walking the filesystem.
/// Static assets. Two files, both vendored, both served from `include_bytes!`
/// so the binary is self-contained and there is no install step and no bundler
/// (§13). htmx is the only JavaScript this app ships; it is served precompressed
-/// because the raw file is 48 KB and the gzip is 15 KB, and the budget that
-/// matters is what a browser actually downloads.
+/// because the budget that matters is what a browser actually downloads.
pub fn static_asset(name: &str, accept_gzip: bool) -> crate::http::Res {
use crate::http::Res;
match name {
diff --git a/src/http/routes/mod.rs b/src/http/routes/mod.rs
index e78cc74..0dfed52 100644
--- a/src/http/routes/mod.rs
+++ b/src/http/routes/mod.rs
@@ -1,9 +1,3 @@
-//! Route handlers (§12).
-//!
-//! Every handler reads through `db.read` — the thread-local read-only
-//! connection — and hands mutations to the writer actor. A slow client can
-//! therefore never hold the write lock, which is the whole point of the split.
-
use crate::db::{self, builds, model::*};
use crate::review::candidates;
use crate::time;
diff --git a/src/http/routes/mutations.rs b/src/http/routes/mutations.rs
index 133d491..79089b2 100644
--- a/src/http/routes/mutations.rs
+++ b/src/http/routes/mutations.rs
@@ -1,6 +1,3 @@
-//! The write side of the UI: every handler that changes something, and the flash
-//! it answers with.
-
use crate::db::{self, builds};
use crate::review::{approve as ap, candidates};
use crate::pipeline;
diff --git a/src/http/routes/pages.rs b/src/http/routes/pages.rs
index dea7de0..f1f3ef8 100644
--- a/src/http/routes/pages.rs
+++ b/src/http/routes/pages.rs
@@ -1,5 +1,3 @@
-//! The read side of the UI: pages that only ever go through `db.read`.
-
use crate::db::{self, builds, Db};
use crate::review::{candidates, diff, risk};
use crate::ops;
@@ -554,10 +552,9 @@ pub(crate) fn audit(state: &State, req: &Req) -> Res {
/// `GET /metrics` in Prometheus text exposition format (§12, §15).
///
-/// Everything here is computed from live state on every scrape. There are no
-/// counters incremented at event sites, because a counter that has to be
-/// maintained by every code path is a counter that quietly drifts the first time
-/// a path is added; a query cannot drift.
+/// Everything here is computed from live state on every scrape. There are no counters
+/// incremented at event sites: a counter every code path has to maintain quietly
+/// drifts the first time a path is added; a query cannot drift.
pub fn metrics(state: &State) -> Res {
match ops::metrics(&state.cfg, &state.db) {
Ok(m) => {
diff --git a/src/http/sse.rs b/src/http/sse.rs
index 5bfb75b..561de33 100644
--- a/src/http/sse.rs
+++ b/src/http/sse.rs
@@ -1,15 +1,3 @@
-//! The live log tail (§13): `GET /builds/:id/log.stream` as server-sent events.
-//!
-//! This is a blocking `std::io::Read` polled by the connection's thread, which is
-//! exactly the shape §14 asks for — no async runtime, no timer wheel. The
-//! pipeline appends to a plain file, so "streaming the log" means noticing that
-//! the file grew and forwarding the new bytes. Nothing in the build path knows
-//! this reader exists, which is what makes it safe to have at all: a client that
-//! disconnects, hangs or never connects cannot slow a build by a microsecond.
-//!
-//! The stream ends when the build reaches a terminal state and the file has no
-//! more bytes, so a browser tab does not hold a connection open forever.
-
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};