feat(archie): add container runtime, migrate command, secret files, and proxy egress

This commit is contained in:
sam committed 2026-11-27 20:36:52 +11:00
1 parent 7630a14705
commit 86b89a5957
13 files changed
+803 -61

No files matched your search

+123 -9
View File
@@ -3,13 +3,18 @@
package egress
import (
"bufio"
"context"
"crypto/tls"
"encoding/base64"
"fmt"
"io"
"net"
"net/http"
"net/http/httputil"
"net/url"
"strconv"
"strings"
"sync"
)
@@ -18,8 +23,9 @@ import (
// are forwarded. Extensions get it rather than Proxy because they carry their
// own credentials and never trust the daemon CA.
type Tunnel struct {
rules rules
dial func(ctx context.Context, network, addr string) (net.Conn, error)
rules rules
dial func(ctx context.Context, network, addr string) (net.Conn, error)
proxyFunc func(*http.Request) (*url.URL, error)
}
// NewTunnel admits the hosts allow names, in network-policy@1 form. A host
@@ -27,19 +33,23 @@ type Tunnel struct {
// it (a LAN forge); a wildcard match may not. Loopback is refused whatever
// is named: it would reach archie's own services.
func NewTunnel(allow []string) *Tunnel {
t := &Tunnel{rules: rules{allow: compilePatterns(allow)}}
t := &Tunnel{
rules: rules{allow: compilePatterns(allow)},
proxyFunc: http.ProxyFromEnvironment,
}
t.dial = t.dialGuarded
return t
}
func (t *Tunnel) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defaultPort, hostport := 443, r.Host
scheme := "https"
if r.Method != http.MethodConnect {
if !r.URL.IsAbs() || r.URL.Scheme != "http" {
http.Error(w, "only CONNECT and absolute-form http requests are proxied", http.StatusBadRequest)
return
}
defaultPort, hostport = 80, r.URL.Host
defaultPort, hostport, scheme = 80, r.URL.Host, r.URL.Scheme
}
host, port, err := splitTarget(hostport, defaultPort)
if err != nil {
@@ -51,12 +61,31 @@ func (t *Tunnel) ServeHTTP(w http.ResponseWriter, r *http.Request) {
deny(w, r, "egress to "+target+" is not allowed")
return
}
if r.Method == http.MethodConnect {
t.splice(w, r, target)
proxyURL, err := t.proxyFor(scheme, target)
if err != nil {
http.Error(w, "proxy lookup: "+err.Error(), http.StatusBadGateway)
return
}
if proxyURL != nil && isLocalTarget(host) {
deny(w, r, "egress to "+target+" is not allowed")
return
}
if r.Method == http.MethodConnect {
dialFn := t.dial
if proxyURL != nil {
dialFn = func(ctx context.Context, _, addr string) (net.Conn, error) {
return dialViaProxy(ctx, addr, proxyURL)
}
}
t.splice(w, r, target, dialFn)
return
}
transport := &http.Transport{DialContext: t.dial}
if proxyURL != nil {
transport = &http.Transport{Proxy: http.ProxyURL(proxyURL)}
}
rp := &httputil.ReverseProxy{
Transport: &http.Transport{DialContext: t.dial},
Transport: transport,
FlushInterval: -1,
Rewrite: func(pr *httputil.ProxyRequest) {
pr.Out.URL.Host = target
@@ -69,8 +98,93 @@ func (t *Tunnel) ServeHTTP(w http.ResponseWriter, r *http.Request) {
rp.ServeHTTP(w, r)
}
func (t *Tunnel) splice(w http.ResponseWriter, r *http.Request, target string) {
upstream, err := t.dial(r.Context(), "tcp", target)
func (t *Tunnel) proxyFor(scheme, target string) (*url.URL, error) {
if t.proxyFunc == nil {
return nil, nil
}
return t.proxyFunc(&http.Request{URL: &url.URL{Scheme: scheme, Host: target}})
}
func isLocalTarget(host string) bool {
norm := normalizeHost(host)
if norm == "localhost" || strings.HasSuffix(norm, ".localhost") {
return true
}
ip := net.ParseIP(norm)
return ip != nil && (ip.IsLoopback() || ip.IsUnspecified())
}
func dialViaProxy(ctx context.Context, target string, proxyURL *url.URL) (net.Conn, error) {
if proxyURL.Scheme != "http" && proxyURL.Scheme != "https" {
return nil, fmt.Errorf("unsupported proxy scheme %q", proxyURL.Scheme)
}
defaultPort := 80
if proxyURL.Scheme == "https" {
defaultPort = 443
}
host, port, err := splitTarget(proxyURL.Host, defaultPort)
if err != nil {
return nil, fmt.Errorf("proxy host: %w", err)
}
proxyAddr := net.JoinHostPort(host, strconv.Itoa(port))
dialer := &net.Dialer{Timeout: handshakeTimeout}
conn, err := dialer.DialContext(ctx, "tcp", proxyAddr)
if err != nil {
return nil, fmt.Errorf("dial proxy %s: %w", proxyAddr, err)
}
if proxyURL.Scheme == "https" {
tlsConn := tls.Client(conn, &tls.Config{ServerName: host, MinVersion: tls.VersionTLS12})
if err := tlsConn.HandshakeContext(ctx); err != nil {
_ = conn.Close()
return nil, fmt.Errorf("proxy tls handshake: %w", err)
}
conn = tlsConn
}
req := &http.Request{
Method: http.MethodConnect,
URL: &url.URL{Opaque: target},
Host: target,
Header: make(http.Header),
}
if proxyURL.User != nil {
creds := proxyURL.User.String()
req.Header.Set("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(creds)))
}
if err := req.Write(conn); err != nil {
_ = conn.Close()
return nil, fmt.Errorf("write proxy CONNECT: %w", err)
}
br := bufio.NewReader(conn)
resp, err := http.ReadResponse(br, req)
if resp != nil {
_ = resp.Body.Close()
}
if err != nil {
_ = conn.Close()
return nil, fmt.Errorf("read proxy CONNECT response: %w", err)
}
if resp.StatusCode != http.StatusOK {
_ = conn.Close()
return nil, fmt.Errorf("proxy CONNECT %s returned %s", target, resp.Status)
}
if br.Buffered() > 0 {
return &bufferedConn{Conn: conn, r: io.MultiReader(br, conn)}, nil
}
return conn, nil
}
type bufferedConn struct {
net.Conn
r io.Reader
}
func (b *bufferedConn) Read(p []byte) (int, error) {
return b.r.Read(p)
}
func (t *Tunnel) splice(w http.ResponseWriter, r *http.Request, target string, dialFn func(context.Context, string, string) (net.Conn, error)) {
upstream, err := dialFn(r.Context(), "tcp", target)
if err != nil {
http.Error(w, "upstream "+target+": "+err.Error(), http.StatusBadGateway)
return
@@ -0,0 +1,164 @@
package egress
import (
"context"
"encoding/base64"
"io"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync/atomic"
"testing"
"time"
)
// TestTunnelEnforcesAllowListBeforeCorporateProxy guards that disallowed hosts
// and loopback targets are denied before dialing any corporate proxy, while
// allowed hosts chain CONNECT with Proxy-Authorization end-to-end.
func TestTunnelEnforcesAllowListBeforeCorporateProxy(t *testing.T) {
var proxyHits atomic.Int32
var seenAuth atomic.Value
var seenTarget atomic.Value
// Upstream echo server connected to by the corporate proxy.
var lc net.ListenConfig
echoLn, err := lc.Listen(context.Background(), "tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer func() { _ = echoLn.Close() }()
go func() {
for {
c, err := echoLn.Accept()
if err != nil {
return
}
go func(conn net.Conn) {
defer func() { _ = conn.Close() }()
_, _ = io.Copy(conn, conn)
}(c)
}
}()
// Local test corporate HTTP CONNECT proxy.
corpProxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
proxyHits.Add(1)
seenAuth.Store(r.Header.Get("Proxy-Authorization"))
seenTarget.Store(r.Host)
if r.Method != http.MethodConnect {
http.Error(w, "want CONNECT", http.StatusMethodNotAllowed)
return
}
up, err := (&net.Dialer{Timeout: time.Second}).DialContext(r.Context(), "tcp", echoLn.Addr().String())
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
hj, ok := w.(http.Hijacker)
if !ok {
_ = up.Close()
return
}
cli, brw, err := hj.Hijack()
if err != nil {
_ = up.Close()
return
}
defer func() { _ = cli.Close(); _ = up.Close() }()
_, _ = cli.Write([]byte("HTTP/1.1 200 Connection Established\r\n\r\n"))
go func() { _, _ = io.Copy(up, brw); closeWrite(up) }()
_, _ = io.Copy(cli, up)
}))
defer corpProxy.Close()
proxyURL, err := url.Parse(corpProxy.URL)
if err != nil {
t.Fatal(err)
}
proxyURL.User = url.UserPassword("svc", "s3cr3t") //nolint:gosec // test fixture for Proxy-Authorization header
tun := NewTunnel([]string{"api.example.com:443", "127.0.0.1:443"})
tun.proxyFunc = func(req *http.Request) (*url.URL, error) {
if strings.HasPrefix(req.URL.Host, "direct.example.com:") {
return nil, nil
}
return proxyURL, nil
}
srv := httptest.NewServer(tun)
defer srv.Close()
srvURL, _ := url.Parse(srv.URL)
// 1. Disallowed host must fail with 403 and never touch the corporate proxy.
res, err := sendConnect(srvURL.Host, "blocked.example.com:443")
if err != nil {
t.Fatalf("blocked CONNECT: %v", err)
}
if !strings.HasPrefix(res, "HTTP/1.1 403 ") {
t.Fatalf("blocked CONNECT status = %q, want 403", res)
}
if proxyHits.Load() != 0 {
t.Fatalf("corporate proxy was contacted %d times for disallowed host", proxyHits.Load())
}
// 2. Loopback host must fail with 403 even if named in allow-list.
res, err = sendConnect(srvURL.Host, "127.0.0.1:443")
if err != nil {
t.Fatalf("loopback CONNECT: %v", err)
}
if !strings.HasPrefix(res, "HTTP/1.1 403 ") {
t.Fatalf("loopback CONNECT status = %q, want 403", res)
}
if proxyHits.Load() != 0 {
t.Fatalf("corporate proxy was contacted %d times for loopback host", proxyHits.Load())
}
// 3. Allowed host chains CONNECT through the corporate proxy with Basic auth.
conn, err := (&net.Dialer{Timeout: time.Second}).DialContext(context.Background(), "tcp", srvURL.Host)
if err != nil {
t.Fatal(err)
}
defer func() { _ = conn.Close() }()
_, _ = io.WriteString(conn, "CONNECT api.example.com:443 HTTP/1.1\r\nHost: api.example.com:443\r\n\r\n")
buf := make([]byte, 128)
n, err := conn.Read(buf)
if err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(string(buf[:n]), "HTTP/1.1 200 ") {
t.Fatalf("allowed CONNECT = %q, want 200", string(buf[:n]))
}
_, _ = io.WriteString(conn, "ping")
n, err = conn.Read(buf)
if err != nil {
t.Fatal(err)
}
if string(buf[:n]) != "ping" {
t.Fatalf("echoed = %q, want ping", string(buf[:n]))
}
wantAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte("svc:s3cr3t"))
if got, _ := seenAuth.Load().(string); got != wantAuth {
t.Fatalf("Proxy-Authorization = %q, want %q", got, wantAuth)
}
if got, _ := seenTarget.Load().(string); got != "api.example.com:443" {
t.Fatalf("proxied target = %q, want api.example.com:443", got)
}
}
func sendConnect(proxyAddr, target string) (string, error) {
conn, err := (&net.Dialer{Timeout: time.Second}).DialContext(context.Background(), "tcp", proxyAddr)
if err != nil {
return "", err
}
defer func() { _ = conn.Close() }()
if _, err := io.WriteString(conn, "CONNECT "+target+" HTTP/1.1\r\nHost: "+target+"\r\n\r\n"); err != nil {
return "", err
}
buf := make([]byte, 256)
n, err := conn.Read(buf)
if err != nil && n == 0 {
return "", err
}
return string(buf[:n]), nil
}
+8 -2
View File
@@ -193,8 +193,14 @@ func openVerified(path string, sum []byte) (*os.File, error) {
}
func passEnv(names []string) []string {
env := make([]string, 0, len(names)+2)
for _, name := range append([]string{"PATH", "HOME"}, names...) {
defaults := []string{"PATH", "HOME", "SSL_CERT_FILE", "SSL_CERT_DIR"}
env := make([]string, 0, len(names)+len(defaults))
seen := make(map[string]struct{}, len(names)+len(defaults))
for _, name := range append(defaults, names...) {
if _, dup := seen[name]; dup {
continue
}
seen[name] = struct{}{}
if value, ok := os.LookupEnv(name); ok {
env = append(env, name+"="+value)
}