Cleanup pass: one home for duplicated logic, stale comments out

Nothing behavioral except two status codes; mostly removing places where
the same rule was written down more than once and could drift.

- server/src/private.rs: the owner-only create/write helpers, which
  config.rs, certs.rs, and the session dirs each had their own copy of
  (certs.rs even duplicated the explanatory comment). One module owns the
  modes now, so the "nothing this server writes is readable by anyone
  else" property is checkable in one place.
- server/src/media.rs: the image media-type/extension table, which the
  four places that have to agree on it each spelled out separately --
  storing an upload, serving it back, building a content block, saving a
  produced image. The differing *defaults* stay at the call sites with
  the reasoning, since they genuinely differ by direction.
- routes.rs: a missing file was a 400 and an unreadable one a 400 with a
  hand-rolled log line; they are now 404 and Internal respectively.
  UnknownSession became NotFound, since it was the only 404-with-message.
- main.rs: xdg_dir takes the variable's value instead of reading the
  environment, which drops the unsafe set_var from its test and lets the
  test actually assert the relative-path rule.
- echo.rs had its own 4-byte hex generator beside session::random_hex.
- claude.rs: the two impl Translator blocks were one type's methods.
- Stale comments: phase-2 markers on shipped work, a permission-mode list
  that had drifted from the CLI's, "dev-updater" as the leaf certificate's
  fallback common name, a half-written sentence in build-apk.sh.
- App: the JSONArray walk written out in four fetchers, the four
  near-identical BackHandlers in AppRoot, and SessionScreen's inline
  fully-qualified names where the file otherwise imports.
- server/wg-test.log was committed by accident; *.log is ignored now, and
  the gitignore comments describe where state actually lives.
- PLAN.md's backend layout gains the new modules and drops hosts.rs for
  the ssh.rs that was built instead.

Verified: 35 server tests, clippy clean, app compiles warning-free, and a
scratch server driven over curl -- attachment upload/serve round-trip with
both a known and an unknown content type, the new 404s, transcript and
session-dir deletion, plus a real claude-cli session answering a prompt.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017xn8nHw1tw1R6PtiY1eEtw
This commit is contained in:
irisandClaude Opus 5 committed 2026-08-25 16:10:33 -04:00
1 parent d4a4ee7808
commit 99bcc341c1
18 files changed
+295 -241

No files matched your search

+9 -32
View File
@@ -25,7 +25,6 @@
//! which is exactly the attack pinning exists to stop.
use std::net::IpAddr;
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
@@ -33,6 +32,8 @@ use rcgen::{
BasicConstraints, CertificateParams, DnType, IsCa, Issuer, KeyPair, KeyUsagePurpose, SanType,
};
use crate::private;
/// Where the leaf lives, for handing to the TLS listener.
pub struct Certificates {
pub leaf_cert: PathBuf,
@@ -45,17 +46,7 @@ pub struct Certificates {
/// Ensures `dir` holds a CA and a leaf covering `addresses`, creating what
/// is missing. Safe to call on every start.
pub fn ensure(dir: &Path, addresses: &[IpAddr]) -> Result<Certificates> {
std::fs::DirBuilder::new()
.recursive(true)
.mode(0o700)
.create(dir)
.with_context(|| format!("create {}", dir.display()))?;
// Set explicitly as well: `mode` applies only when the directory is
// created, so a directory that already existed -- made by hand, or by
// an older version -- would otherwise keep whatever permissions it had
// while holding a private key.
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
.with_context(|| format!("restrict {}", dir.display()))?;
private::create_dir(dir)?;
let ca_cert_path = dir.join("ca.pem");
let ca_key_path = dir.join("ca-key.pem");
@@ -63,8 +54,8 @@ pub fn ensure(dir: &Path, addresses: &[IpAddr]) -> Result<Certificates> {
let (ca_pem, ca_key_pem) = if ca_is_new {
let (pem, key) = generate_ca()?;
write_private(&ca_key_path, &key)?;
write_private(&ca_cert_path, &pem)?;
private::write_file(&ca_key_path, key.as_bytes())?;
private::write_file(&ca_cert_path, pem.as_bytes())?;
tracing::info!("generated a new CA in {}", dir.display());
(pem, key)
} else {
@@ -79,8 +70,8 @@ pub fn ensure(dir: &Path, addresses: &[IpAddr]) -> Result<Certificates> {
let (leaf_pem, leaf_key_pem) = generate_leaf(&ca_pem, &ca_key_pem, addresses)?;
let leaf_cert = dir.join("leaf.pem");
let leaf_key = dir.join("leaf-key.pem");
write_private(&leaf_key, &leaf_key_pem)?;
write_private(&leaf_cert, &leaf_pem)?;
private::write_file(&leaf_key, leaf_key_pem.as_bytes())?;
private::write_file(&leaf_cert, leaf_pem.as_bytes())?;
Ok(Certificates { leaf_cert, leaf_key, ca_is_new })
}
@@ -111,7 +102,7 @@ fn generate_leaf(
params.distinguished_name.push(DnType::OrganizationName, "ai-app dev");
params.distinguished_name.push(
DnType::CommonName,
addresses.first().map(|a| a.to_string()).unwrap_or_else(|| "dev-updater".to_string()),
addresses.first().map(|a| a.to_string()).unwrap_or_else(|| "ai-app".to_string()),
);
params.subject_alt_names = addresses.iter().map(|a| SanType::IpAddress(*a)).collect();
params.is_ca = IsCa::ExplicitNoCa;
@@ -121,24 +112,10 @@ fn generate_leaf(
Ok((certificate.pem(), key.serialize_pem()))
}
/// Writes owner-readable only, from the moment the file exists rather than
/// a `chmod` afterwards.
fn write_private(path: &Path, contents: &str) -> Result<()> {
use std::io::Write;
let mut file = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o600)
.open(path)
.with_context(|| format!("write {}", path.display()))?;
file.write_all(contents.as_bytes())
.with_context(|| format!("write {}", path.display()))
}
#[cfg(test)]
mod tests {
use super::*;
use std::os::unix::fs::PermissionsExt;
fn addresses() -> Vec<IpAddr> {
vec!["10.66.0.1".parse().unwrap(), "127.0.0.1".parse().unwrap()]