Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ and listed with their assets on the

- **A shared machine keeps the GPUs its owner wants.** The share switch
takes a GPU cap (`max_gpus`, the agent's `--max-gpus`): the most GPUs
other members' lanes hold here, `0` none. A GPU whose memory is more than
a quarter used by processes on the machine is not offered either; the
other members' lanes hold here, `0` none; a lane gets any free GPU that
fits, as long as the cap allows. A GPU whose memory is more than a
quarter used by processes on the machine is not offered either; the
pool shows it as "in use on the machine" (ADR-0115).
- **A lane shows its GPUs.** A lane on a node that holds GPUs gets a GPU
tile on its card and usage page: load, its last ten minutes, and memory
Expand All @@ -25,9 +26,11 @@ and listed with their assets on the
shows under Admin in the pool area now ("Asks to run lanes", with what it
offers and a Grant button), counts in the pool's badge, is marked in
Machines, and an admin's hub notifies the desktop when one starts asking
(`machine_asks`, on by default). A second member entry of the same machine
(the same address, or a name such as `<name>-wsl`) is pointed out
(ADR-0116, #599).
(`machine_asks`, on by default; at most once in half an hour per
machine). Another member entry with the same address, or a similar name
such as `<name>-wsl`, is pointed out with its id (a name is not checked).
A machine's name keeps no invisible characters (bidi overrides,
zero-width marks) (ADR-0116, #599).

### Fixed

Expand Down Expand Up @@ -63,8 +66,12 @@ and listed with their assets on the
keep their connections to a service (#556, #559). A service that ties its
login to the connection (Windows Negotiate or NTLM, Kestrel's and
HTTP.sys's default) took the next visitor's request on such a connection
as the first visitor's. A connection whose request or answer carries
Negotiate or NTLM is closed after its answer now, as YARP does (#569).
as the first visitor's. A connection whose request or answer carries a
Windows login (Negotiate, NTLM, Kerberos, CredSSP) now stays with the
visitor's connection, for the handshake and what follows, and is never
given to anyone else, as YARP does; it closes with the visitor's
connection. A visitor's `Proxy-Authorization` no longer reaches the
service (#569).

## [0.51.0] - 2026-11-19

Expand Down
118 changes: 113 additions & 5 deletions crates/devstack-daemon/src/proxy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
//! request), and hop-by-hop headers stay on their hop (RFC 9110 §7.6.1).

use bytes::Bytes;
use devstack_node::connpool::Pool;
use devstack_node::connpool::{Bound, Pool};
use http_body_util::{BodyExt, Full, StreamBody, combinators::BoxBody};
use hyper::body::{Frame, Incoming};
use hyper::{Request, Response, StatusCode};
Expand Down Expand Up @@ -158,8 +158,12 @@ impl Proxy {
continue;
};
let sh = sh.clone();
// The upstream connection a login binds to this client's (#569).
let client = Arc::new(Bound::default());
tokio::spawn(async move {
let service = hyper::service::service_fn(move |r| handle(sh.clone(), r));
let service = hyper::service::service_fn(move |r| {
handle(sh.clone(), client.clone(), r)
});
let _ = hyper::server::conn::http1::Builder::new()
.serve_connection(TokioIo::new(stream), service)
.with_upgrades()
Expand Down Expand Up @@ -312,9 +316,13 @@ pub fn strip_hop_by_hop(h: &mut hyper::HeaderMap, upgrade: bool) {
h.remove(n);
}
}
// The proxy login headers are this hop's too: a visitor's never reaches
// the service (review before 0.52.0).
for n in [
"keep-alive",
"proxy-connection",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailer",
"transfer-encoding",
Expand Down Expand Up @@ -355,7 +363,11 @@ async fn connect(port: u16) -> std::io::Result<TcpStream> {
Ok(s)
}

async fn handle(sh: Arc<Shared>, mut req: Request<Incoming>) -> Result<Response<Body>, Infallible> {
async fn handle(
sh: Arc<Shared>,
client: Arc<Bound<u16, Body>>,
mut req: Request<Incoming>,
) -> Result<Response<Body>, Infallible> {
let up = match wait_upstream(&sh).await {
Ok(u) => u,
Err((state, reason)) => {
Expand Down Expand Up @@ -387,7 +399,9 @@ async fn handle(sh: Arc<Shared>, mut req: Request<Incoming>) -> Result<Response<
// goes out once more on a new one where that is safe (`connpool`).
let (sender, mut resp) = match sh
.pool
.send(&up.port, req.map(BodyExt::boxed), || sender(up.port))
.send(&up.port, &client, req.map(BodyExt::boxed), || {
sender(up.port)
})
.await
{
Ok(r) => r,
Expand Down Expand Up @@ -517,7 +531,17 @@ mod tests {

/// One request on a kept-alive connection; returns (status, headers, body).
fn get(conn: &mut std::net::TcpStream, path: &str) -> (u16, String, String) {
write!(conn, "GET {path} HTTP/1.1\r\nHost: x\r\n\r\n").unwrap();
get_as(conn, path, None)
}

/// The same, with an `Authorization` header.
fn get_as(
conn: &mut std::net::TcpStream,
path: &str,
auth: Option<&str>,
) -> (u16, String, String) {
let auth = auth.map_or(String::new(), |a| format!("Authorization: {a}\r\n"));
write!(conn, "GET {path} HTTP/1.1\r\nHost: x\r\n{auth}\r\n").unwrap();
let mut r = BufReader::new(conn.try_clone().unwrap());
let mut head = String::new();
loop {
Expand Down Expand Up @@ -586,6 +610,90 @@ mod tests {
);
}

/// An upstream that logs a connection in as Kestrel does with NTLM:
/// `NTLM t1` gets the challenge `NTLM t2`, `NTLM t3` on the same
/// connection after it logs the connection in, and a logged-in
/// connection answers 200 without credentials; anything else is 401.
fn ntlm_upstream(rt: &tokio::runtime::Runtime) -> u16 {
use std::sync::atomic::AtomicU8;
let l = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
let port = l.local_addr().unwrap().port();
l.set_nonblocking(true).unwrap();
rt.spawn(async move {
let l = tokio::net::TcpListener::from_std(l).unwrap();
loop {
let (s, _) = l.accept().await.unwrap();
let login = Arc::new(AtomicU8::new(0));
tokio::spawn(async move {
let svc = hyper::service::service_fn(move |r: Request<Incoming>| {
let login = login.clone();
async move {
let auth = r
.headers()
.get("authorization")
.and_then(|v| v.to_str().ok())
.unwrap_or("")
.to_string();
let (status, challenge) = match auth.as_str() {
"NTLM t1" => {
login.store(1, Ordering::SeqCst);
(401, Some("NTLM t2"))
}
"NTLM t3" if login.load(Ordering::SeqCst) == 1 => {
login.store(2, Ordering::SeqCst);
(200, None)
}
"" if login.load(Ordering::SeqCst) == 2 => (200, None),
_ => (401, Some("NTLM")),
};
let mut resp = Response::new(Full::new(Bytes::from("ok")).boxed());
*resp.status_mut() = StatusCode::from_u16(status).unwrap();
if let Some(c) = challenge {
resp.headers_mut()
.insert("www-authenticate", c.parse().unwrap());
}
Ok::<_, Infallible>(resp)
}
});
let _ = hyper::server::conn::http1::Builder::new()
.serve_connection(TokioIo::new(s), svc)
.await;
});
}
});
port
}

/// #569 and the review before 0.52.0, through the proxy: a client
/// connection logs in over its handshake and stays logged in; another
/// client connection is not.
#[test]
fn a_windows_login_through_the_proxy_stays_with_its_client() {
let rt = tokio::runtime::Runtime::new().unwrap();
let up = ntlm_upstream(&rt);
let port = free_port();
let p = Proxy::bind("api", port, rt.handle()).unwrap();
p.set_upstream(Some(Upstream {
port: up,
build: None,
}));
let mut anna = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap();
assert_eq!(get_as(&mut anna, "/", Some("NTLM t1")).0, 401);
assert_eq!(
get_as(&mut anna, "/", Some("NTLM t3")).0,
200,
"the handshake did not stay on one connection"
);
assert_eq!(
get(&mut anna, "/").0,
200,
"anna's connection is not logged in"
);
let mut ben = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap();
assert_eq!(get(&mut ben, "/").0, 401, "ben got anna's login");
assert_eq!(get(&mut anna, "/").0, 200);
}

#[test]
fn hop_by_hop_headers_stay_on_their_hop() {
let mut h = hyper::HeaderMap::new();
Expand Down
47 changes: 40 additions & 7 deletions crates/devstack-daemon/src/staticsrv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,38 @@ fn percent_decode(s: &str) -> String {
String::from_utf8_lossy(&out).into_owned()
}

use devstack_node::connpool::{GiveBack, IDLE_MAX, Pool};
use devstack_node::connpool::{Bound, GiveBack, IDLE_MAX, Pool};

/// One client connection: where it comes from, and the connection to each
/// forward's target a login bound to it (#569). axum makes one per
/// connection it accepts and hands a copy to each of its requests.
#[derive(Clone)]
struct Client {
peer: SocketAddr,
bound: Arc<std::sync::Mutex<Bindings>>,
}

/// A client connection's bindings, by the port of the forward's target.
type Bindings = std::collections::HashMap<u16, Arc<Bound<(), Body>>>;

impl Client {
/// Its binding to the target on `port` (one per forward).
fn to(&self, port: u16) -> Arc<Bound<(), Body>> {
self.bound.lock().unwrap().entry(port).or_default().clone()
}
}

impl
axum::extract::connect_info::Connected<axum::serve::IncomingStream<'_, tokio::net::TcpListener>>
for Client
{
fn connect_info(stream: axum::serve::IncomingStream<'_, tokio::net::TcpListener>) -> Self {
Client {
peer: *stream.remote_addr(),
bound: Arc::default(),
}
}
}

/// Where a forward sends its requests: `http://host:port`, with the
/// connections to it that are idle now. They are reused, as a reverse proxy
Expand Down Expand Up @@ -156,7 +187,7 @@ pub fn serve(root: PathBuf, port: u16, spa: bool, forward: &[String]) -> Result<
.map_err(|e| format!("port {port}: {e}"))?;
axum::serve(
listener,
app(root, spa, forwards).into_make_service_with_connect_info::<SocketAddr>(),
app(root, spa, forwards).into_make_service_with_connect_info::<Client>(),
)
.await
.map_err(|e| e.to_string())
Expand All @@ -166,13 +197,13 @@ pub fn serve(root: PathBuf, port: u16, spa: bool, forward: &[String]) -> Result<
fn app(root: PathBuf, spa: bool, forwards: Vec<(String, Target)>) -> axum::Router {
let forwards = Arc::new(forwards);
axum::Router::new().fallback(
move |ConnectInfo(peer): ConnectInfo<SocketAddr>, req: Request| {
move |ConnectInfo(client): ConnectInfo<Client>, req: Request| {
let root = root.clone();
let forwards = forwards.clone();
async move {
// A forwarded prefix never falls back to a file.
if let Some((_, to)) = devstack_config::forward::pick(&forwards, req.uri().path()) {
return pass(to, peer, req).await;
return pass(to, &client, req).await;
}
let tag = req
.headers()
Expand All @@ -191,7 +222,8 @@ fn app(root: PathBuf, spa: bool, forwards: Vec<(String, Target)>) -> axum::Route
/// their hop, the answer streamed (SSE, a download) and an upgrade
/// (WebSocket) joined. An unreachable target is a 502 at once: nothing here
/// knows whether it is starting.
async fn pass(to: &Target, peer: SocketAddr, mut req: Request) -> Response<Body> {
async fn pass(to: &Target, client: &Client, mut req: Request) -> Response<Body> {
let peer = client.peer;
let fail = |e: String| {
Response::builder()
.status(StatusCode::BAD_GATEWAY)
Expand Down Expand Up @@ -238,7 +270,8 @@ async fn pass(to: &Target, peer: SocketAddr, mut req: Request) -> Response<Body>
*req.uri_mut() = path.parse().unwrap_or_else(|_| Uri::from_static("/"));
*req.version_mut() = Version::HTTP_11;

let (sender, mut resp) = match to.pool.send(&(), req, || to.connect()).await {
let bound = client.to(to.port);
let (sender, mut resp) = match to.pool.send(&(), &bound, req, || to.connect()).await {
Ok(r) => r,
Err(e) => return fail(e),
};
Expand Down Expand Up @@ -454,7 +487,7 @@ mod tests {
let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = l.local_addr().unwrap().port();
tokio::spawn(async move {
axum::serve(l, app.into_make_service_with_connect_info::<SocketAddr>()).await
axum::serve(l, app.into_make_service_with_connect_info::<Client>()).await
});
port
}
Expand Down
13 changes: 12 additions & 1 deletion crates/devstack-daemon/src/watch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -247,15 +247,26 @@ const RELIST_AFTER: std::time::Duration = std::time::Duration::from_millis(200);
/// directory is listed again [`RELIST_AFTER`] later, on a thread of its own
/// that ends with the watcher; what it finds again is delivered again,
/// which costs nothing (a candidate or a restart waits for its debounce).
/// The directories that came while it waited are listed with it, each once
/// (a burst of new directories is one more listing, not one per event).
fn feed(repo: PathBuf, deliver: Deliver) -> impl FnMut(notify::Event) + Send + 'static {
let (tx, rx) = std::sync::mpsc::channel::<(Instant, Vec<PathBuf>)>();
if LIST_NEW_DIRS {
let (repo, deliver) = (repo.clone(), deliver.clone());
let _ = std::thread::Builder::new()
.name("watch-relist".into())
.spawn(move || {
while let Ok((due, dirs)) = rx.recv() {
while let Ok((mut due, mut dirs)) = rx.recv() {
std::thread::sleep(due.saturating_duration_since(Instant::now()));
// What came meanwhile, its own wait included (each one
// only once its directory's watch is surely in place).
while let Ok((d, more)) = rx.try_recv() {
due = due.max(d);
dirs.extend(more);
}
std::thread::sleep(due.saturating_duration_since(Instant::now()));
dirs.sort();
dirs.dedup();
let ev = dirs.into_iter().fold(
notify::Event::new(EventKind::Create(notify::event::CreateKind::Folder)),
notify::Event::add_path,
Expand Down
Loading
Loading