summaryrefslogtreecommitdiffstats
path: root/src/http/mod.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/http/mod.rs')
-rw-r--r--src/http/mod.rs41
1 files changed, 0 insertions, 41 deletions
diff --git a/src/http/mod.rs b/src/http/mod.rs
index 11ea107..7beeff4 100644
--- a/src/http/mod.rs
+++ b/src/http/mod.rs
@@ -9,13 +9,11 @@ use std::sync::Arc;
use crate::config::Config;
use crate::db::Db;
-/// Shared state every handler needs.
pub struct State {
pub cfg: Config,
pub db: Db,
}
-/// A request that has been decoded enough to route on.
pub struct Req {
pub method: String,
pub path: String,
@@ -23,11 +21,7 @@ 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) — 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.
pub accept_gzip: bool,
}
@@ -46,18 +40,12 @@ impl Req {
}
}
-/// What a handler produced.
pub struct Res {
pub status: u16,
pub content_type: String,
pub body: Vec<u8>,
pub headers: Vec<(String, String)>,
- /// 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.
pub stream_len: Option<usize>,
}
@@ -68,9 +56,6 @@ impl Res {
pub fn text(status: u16, body: String) -> Self {
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, 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,
@@ -99,8 +84,6 @@ impl Res {
}
}
-/// Start the HTTP server. Returns the accept-loop handle and the address it
-/// actually bound, which matters for `:0` in tests.
pub struct Server {
pub handle: std::thread::JoinHandle<()>,
pub addr: String,
@@ -115,8 +98,6 @@ pub fn spawn(cfg: Config, db: Db) -> std::io::Result<Server> {
let handle = std::thread::Builder::new()
.name("http-accept".into())
.spawn(move || {
- // `tiny_http` hands each connection to its own worker internally;
- // the accept loop just blocks on `recv` and hands off.
for request in server.incoming_requests() {
let state = state.clone();
std::thread::Builder::new()
@@ -152,7 +133,6 @@ fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result<
.find(|h| h.field.equiv("Accept-Encoding"))
.map(|h| h.value.as_str().contains("gzip"))
.unwrap_or(false);
- // Parsed once, here, rather than per `form_get` call (n-3).
let form_pairs = forms::parse(&body);
let req = Req {
method: request.method().as_str().to_string(),
@@ -166,7 +146,6 @@ fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result<
};
let mut res = dispatch(&state, &req);
- // Attach the session cookie if the handler minted one.
if let Some(sid) = res.headers.iter().find(|(k, _)| k == "X-New-Session").map(|(_, v)| v.clone()) {
res.headers.retain(|(k, _)| k != "X-New-Session");
res.header("Set-Cookie", &format!("sid={sid}; Path=/; HttpOnly; SameSite=Strict"));
@@ -180,8 +159,6 @@ fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result<
headers.push(h);
}
}
- // A streamed response is chunked and stays open until the reader returns
- // EOF; that is the whole point for the log tail.
if let Some(reader) = res.stream.take() {
let mut resp = tiny_http::Response::new(
tiny_http::StatusCode(res.status),
@@ -190,9 +167,6 @@ fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result<
res.stream_len,
None,
);
- // tiny_http switches to chunked above 32 KB by default. For a file whose
- // length we know, a Content-Length is what a browser wants; the log tail
- // has no known length and stays chunked, which is what it needs.
if res.stream_len.is_some() {
resp = resp.with_chunked_threshold(usize::MAX);
}
@@ -206,34 +180,23 @@ fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result<
request.respond(builder)
}
-/// 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";
- // Static assets and the login page are reachable without a session.
match (req.method.as_str(), seg.as_slice()) {
("GET", ["static", name]) => return render::static_asset(name, req.accept_gzip),
("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, 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 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() {
Some(s) => (s, true),
- // No system RNG means no unguessable session id. Refuse rather than
- // hand out a token someone else could compute.
None => return Res::text(500, "500: could not mint a session\n".into()),
},
};
@@ -245,7 +208,6 @@ fn dispatch(state: &State, req: &Req) -> Res {
return finish(state, req, res, &sid, new_session);
}
- // CSRF: every state-changing request must carry the token for its session.
if !is_get {
let token = req.form_get("csrf").or_else(|| req.query_get("csrf")).unwrap_or_default();
if !auth::csrf_ok(&sid, &token) {
@@ -261,14 +223,11 @@ fn dispatch(state: &State, req: &Req) -> Res {
}
fn finish(_state: &State, _req: &Req, mut res: Res, _sid: &str, _new: bool) -> Res {
- // A tiny security posture for a tool that serves a package index.
res.header("X-Content-Type-Options", "nosniff");
res.header("Referrer-Policy", "same-origin");
res
}
-/// Percent-decode a path segment. Enough for package names and ids, which is
-/// all that ever needs it here.
fn percent_decode(s: &str) -> String {
let bytes = s.as_bytes();
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());