Files
mtusi2026lab7/infra/tls/gateway_test.go
T

305 lines
9.6 KiB
Go

package main
import (
"bufio"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"math/big"
"net"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
)
type countedBody struct {
io.ReadCloser
bytes *atomic.Int64
}
func (b *countedBody) Read(data []byte) (int, error) {
n, err := b.ReadCloser.Read(data)
b.bytes.Add(int64(n))
return n, err
}
func TestEarlyRejectionDoesNotForwardBodyAndAcceptedBodyStillStreams(t *testing.T) {
for _, reject := range []bool{true, false} {
t.Run(map[bool]string{true: "early_413", false: "accepted_stream"}[reject], func(t *testing.T) {
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Instance-Id", "synthetic-api")
if reject {
w.WriteHeader(413)
io.WriteString(w, `{"error":"payload_too_large"}`)
return
}
data, err := io.ReadAll(r.Body)
if err != nil {
t.Error(err)
}
// Request-body cleanup must not cancel legitimate processing.
time.Sleep(2200 * time.Millisecond)
w.Write(data)
}))
defer backend.Close()
target, _ := url.Parse(backend.URL)
proxy := loopbackProxy(Config{Role: "api"}, target)
defer proxy.Transport.(*http.Transport).CloseIdleConnections()
var forwarded atomic.Int64
director := proxy.Director
proxy.Director = func(r *http.Request) {
director(r)
r.Body = &countedBody{ReadCloser: r.Body, bytes: &forwarded}
}
frontend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Connection", "close")
serveLoopbackProxy(Config{Role: "api"}, proxy, w, r)
}))
defer frontend.Close()
payload := strings.Repeat("x", 10*1024*1024+1)
conn, err := net.DialTimeout("tcp", frontend.Listener.Addr().String(), time.Second)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
_ = conn.SetDeadline(time.Now().Add(5 * time.Second))
connection := "keep-alive"
if reject {
connection = "close"
}
fmt.Fprintf(conn, "POST / HTTP/1.1\r\nHost: synthetic\r\nConnection: %s\r\nContent-Type: image/png\r\nContent-Length: %d\r\n\r\n", connection, len(payload))
// A load balancer can finish writing before reading the early reply.
if _, err := io.WriteString(conn, payload); err != nil {
t.Fatal(err)
}
reader := bufio.NewReader(conn)
var response *http.Response
for {
response, err = http.ReadResponse(reader, &http.Request{Method: "POST"})
if err != nil {
t.Fatal(err)
}
if response.StatusCode >= 200 {
break
}
response.Body.Close()
}
defer response.Body.Close()
body, err := io.ReadAll(response.Body)
if err != nil || response.Header.Get("X-Instance-Id") != "synthetic-api" {
t.Fatalf("incomplete application response: %v", err)
}
if reject {
if response.StatusCode != 413 || string(body) != `{"error":"payload_too_large"}` || forwarded.Load() != 0 {
t.Fatalf("early rejection lost: status=%d forwarded=%d", response.StatusCode, forwarded.Load())
}
} else if response.StatusCode != 200 || string(body) != payload || forwarded.Load() != int64(len(payload)) {
t.Fatal("accepted body was not streamed intact")
}
})
}
}
type authority struct {
cert *x509.Certificate
key *ecdsa.PrivateKey
pem []byte
}
func root(t *testing.T) authority {
t.Helper()
key, e := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if e != nil {
t.Fatal(e)
}
template := &x509.Certificate{SerialNumber: big.NewInt(time.Now().UnixNano()), Subject: pkix.Name{CommonName: "Synthetic test CA"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign}
der, e := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
if e != nil {
t.Fatal(e)
}
cert, e := x509.ParseCertificate(der)
if e != nil {
t.Fatal(e)
}
return authority{cert, key, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})}
}
func client(t *testing.T, ca authority, role string, expired bool) *x509.Certificate {
t.Helper()
key, e := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if e != nil {
t.Fatal(e)
}
identity, _ := url.Parse("spiffe://messenger/" + role)
expiry := time.Now().Add(time.Minute)
if expired {
expiry = time.Now().Add(-time.Minute)
}
template := &x509.Certificate{SerialNumber: big.NewInt(time.Now().UnixNano()), Subject: pkix.Name{CommonName: role}, NotBefore: time.Now().Add(-time.Hour), NotAfter: expiry, URIs: []*url.URL{identity}, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, KeyUsage: x509.KeyUsageDigitalSignature}
der, e := x509.CreateCertificate(rand.Reader, template, ca.cert, &key.PublicKey, ca.key)
if e != nil {
t.Fatal(e)
}
cert, e := x509.ParseCertificate(der)
if e != nil {
t.Fatal(e)
}
return cert
}
func TestClientAuthorizationUsesCurrentChainIdentityExpiryAndRevocation(t *testing.T) {
ca := root(t)
foreign := root(t)
directory := t.TempDir()
conf := Config{Trust: filepath.Join(directory, "ca.pem"), Revoked: filepath.Join(directory, "revoked.json")}
if e := os.WriteFile(conf.Trust, ca.pem, 0600); e != nil {
t.Fatal(e)
}
if e := os.WriteFile(conf.Revoked, []byte(`{}`), 0600); e != nil {
t.Fatal(e)
}
boundary := Boundary{Allow: map[string][]string{"spiffe://messenger/lb": {"* /"}}}
good := client(t, ca, "lb", false)
state := func(leaf *x509.Certificate, issuer authority) tls.ConnectionState {
return tls.ConnectionState{PeerCertificates: []*x509.Certificate{leaf, issuer.cert}, VerifiedChains: [][]*x509.Certificate{{leaf, issuer.cert}}}
}
cases := []struct {
name string
state tls.ConnectionState
allowed bool
}{
{"authorized", state(good, ca), true},
{"no_certificate", tls.ConnectionState{}, false},
{"trusted_but_wrong_role", state(client(t, ca, "worker", false), ca), false},
{"foreign_authority", state(client(t, foreign, "lb", false), foreign), false},
{"expired", state(client(t, ca, "lb", true), ca), false},
}
for _, test := range cases {
t.Run(test.name, func(t *testing.T) {
_, e := peer(conf, test.state, boundary)
if (e == nil) != test.allowed {
t.Fatalf("authorization mismatch: allowed=%v error=%v", test.allowed, e)
}
})
}
raw, _ := json.Marshal(map[string]bool{good.SerialNumber.Text(16): true})
if e := os.WriteFile(conf.Revoked, raw, 0600); e != nil {
t.Fatal(e)
}
if _, e := peer(conf, state(good, ca), boundary); e == nil {
t.Fatal("revoked client accepted on previously authenticated connection")
}
if e := os.WriteFile(conf.Revoked, []byte(`{}`), 0600); e != nil {
t.Fatal(e)
}
if e := os.WriteFile(conf.Trust, foreign.pem, 0600); e != nil {
t.Fatal(e)
}
if _, e := peer(conf, state(good, ca), boundary); e == nil {
t.Fatal("retired authority accepted from cached verified chain")
}
if e := os.Remove(conf.Revoked); e != nil {
t.Fatal(e)
}
if _, e := peer(conf, state(good, ca), boundary); e == nil {
t.Fatal("missing revocation policy did not fail closed")
}
}
// A failed native commit must be reported and aborted so the agent retries;
// persisting a new PEM alone does not prove that the native process uses it.
func TestHAProxyCertificateTransaction(t *testing.T) {
for _, success := range []bool{true, false} {
t.Run(fmt.Sprint(success), func(t *testing.T) {
ca := root(t)
key, err := x509.MarshalECPrivateKey(ca.key)
if err != nil {
t.Fatal(err)
}
directory, err := os.MkdirTemp("", "lb-")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.RemoveAll(directory) })
current := filepath.Join(directory, "current")
if err = os.Mkdir(current, 0700); err != nil {
t.Fatal(err)
}
bundle := filepath.Join(current, "bundle.pem")
raw := append(ca.pem, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: key})...)
if err = os.WriteFile(bundle, raw, 0600); err != nil {
t.Fatal(err)
}
socket := filepath.Join(directory, "admin.sock")
listener, err := net.Listen("unix", socket)
if err != nil {
t.Fatal(err)
}
defer listener.Close()
done := make(chan error, 1)
go func() {
commands := []string{"set ssl cert ", "commit ssl cert "}
if !success {
commands = append(commands, "abort ssl cert ")
}
for _, prefix := range commands {
conn, e := listener.Accept()
if e != nil {
done <- e
return
}
conn.SetDeadline(time.Now().Add(3 * time.Second))
request, e := io.ReadAll(conn)
if e != nil {
conn.Close()
done <- e
return
}
if !strings.HasPrefix(string(request), prefix+bundle) {
conn.Close()
done <- fmt.Errorf("unexpected command prefix")
return
}
reply := "Transaction created for certificate\n"
if strings.HasPrefix(prefix, "set") && (!strings.HasSuffix(string(request), "\n\n") || !strings.Contains(string(request), "-----BEGIN EC PRIVATE KEY-----")) {
conn.Close()
done <- fmt.Errorf("missing bounded PEM payload")
return
}
if strings.HasPrefix(prefix, "commit") {
reply = "Success!\n"
if !success {
reply = "synthetic failure contains PRIVATE response\n"
}
}
io.WriteString(conn, reply)
conn.Close()
}
done <- nil
}()
err = installHAProxyCertificate(socket, bundle)
if (err == nil) != success {
t.Fatal("native commit result was ignored")
}
if err != nil && strings.Contains(err.Error(), "PRIVATE") {
t.Fatal("native response leaked")
}
if e := <-done; e != nil {
t.Fatal(e)
}
})
}
}