helm-rs 0.1.2

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! A tiny HTTP server for the success paths: it serves fixed bodies and, when given credentials,
//! answers `401` with `WWW-Authenticate: Basic` until the request carries them. It records every
//! request so a test can see which `Authorization` header reached it.

use std::collections::HashMap;
use std::io::{BufRead, BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};

/// One request the server saw: its path and `Authorization` header.
pub type Seen = (String, Option<String>);

/// A running stub server; it stops when dropped.
pub struct Server {
    /// The `host:port` it listens on.
    pub host: String,
    seen: Arc<Mutex<Vec<Seen>>>,
    stop: Arc<AtomicBool>,
    thread: Option<JoinHandle<()>>,
}

/// The `Authorization` header value for HTTP basic auth.
pub fn basic(user: &str, password: &str) -> String {
    const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let bytes = format!("{user}:{password}").into_bytes();
    let mut out = String::from("Basic ");

    for chunk in bytes.chunks(3) {
        let n = chunk
            .iter()
            .enumerate()
            .fold(0u32, |acc, (i, b)| acc | (u32::from(*b) << (16 - 8 * i)));

        for i in 0..4 {
            if i <= chunk.len() {
                out.push(char::from(ALPHABET[((n >> (18 - 6 * i)) & 63) as usize]));
            } else {
                out.push('=');
            }
        }
    }

    out
}

fn handle(
    stream: &TcpStream,
    routes: &HashMap<String, Vec<u8>>,
    want: Option<&str>,
    seen: &Mutex<Vec<Seen>>,
) {
    let mut reader = BufReader::new(stream);
    let mut line = String::new();
    let mut auth = None;

    if reader.read_line(&mut line).is_err() {
        return;
    }

    let path = line.split_whitespace().nth(1).unwrap_or("/").to_owned();

    loop {
        let mut header = String::new();

        if reader.read_line(&mut header).unwrap_or(0) <= 2 {
            break;
        }

        if let Some((name, value)) = header.trim_end().split_once(':')
            && name.eq_ignore_ascii_case("authorization")
        {
            auth = Some(value.trim().to_owned());
        }
    }

    seen.lock()
        .expect("seen lock")
        .push((path.clone(), auth.clone()));

    let response = match routes.get(&path) {
        Some(body) if want.is_none() || want == auth.as_deref() => {
            let head = format!(
                "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                body.len()
            );

            [head.into_bytes(), body.clone()].concat()
        }
        Some(_) => b"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Basic realm=\"stub\"\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_vec(),
        None => b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_vec(),
    };

    let mut stream = stream;

    stream.write_all(&response).expect("write response");
}

impl Server {
    /// Serves `routes` (path to body); with `want`, only requests carrying that `Authorization`
    /// header get the body.
    pub fn start(routes: HashMap<String, Vec<u8>>, want: Option<String>) -> Self {
        let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
        let host = listener.local_addr().expect("addr").to_string();
        let seen = Arc::new(Mutex::new(Vec::new()));
        let stop = Arc::new(AtomicBool::new(false));
        let thread = {
            let (seen, stop) = (Arc::clone(&seen), Arc::clone(&stop));
            let (routes, want) = (Arc::new(routes), Arc::new(want));

            thread::spawn(move || {
                for stream in listener.incoming() {
                    if stop.load(Ordering::SeqCst) {
                        break;
                    }

                    let Ok(stream) = stream else { continue };
                    let (routes, want, seen) =
                        (Arc::clone(&routes), Arc::clone(&want), Arc::clone(&seen));

                    thread::spawn(move || handle(&stream, &routes, want.as_deref(), &seen));
                }
            })
        };

        Self {
            host,
            seen,
            stop,
            thread: Some(thread),
        }
    }

    /// The `Authorization` header of every request to `path`, in order.
    pub fn authorizations(&self, path: &str) -> Vec<Option<String>> {
        self.seen
            .lock()
            .expect("seen lock")
            .iter()
            .filter(|(p, _)| p == path)
            .map(|(_, a)| a.clone())
            .collect()
    }
}

impl Drop for Server {
    fn drop(&mut self) {
        self.stop.store(true, Ordering::SeqCst);

        if TcpStream::connect(&self.host).is_ok()
            && let Some(thread) = self.thread.take()
        {
            thread.join().expect("server thread");
        }
    }
}