Files
mtusi2026lab7/infra/tls/gateway_test.go
T

215 lines
6.7 KiB
Go

package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/json"
"encoding/pem"
"io"
"math/big"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
type countedBody struct {
io.ReadCloser
bytes *atomic.Int64
release <-chan struct{}
}
func (b *countedBody) Close() error {
if b.release != nil {
<-b.release
}
return b.ReadCloser.Close()
}
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)
}
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
release := make(chan struct{})
var released sync.Once
unhold := func() { released.Do(func() { close(release) }) }
director := proxy.Director
proxy.Director = func(r *http.Request) {
director(r)
body := &countedBody{ReadCloser: r.Body, bytes: &forwarded}
if reject {
body.release = release
}
r.Body = body
}
frontend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Connection", "close")
proxy.ServeHTTP(w, r)
}))
defer frontend.Close()
defer unhold()
payload := strings.Repeat("x", 10*1024*1024+1)
client := &http.Client{Timeout: 5 * time.Second}
request, _ := http.NewRequest("POST", frontend.URL, strings.NewReader(payload))
request.Header.Set("Content-Type", "image/png")
request.Close = true
response, err := client.Do(request)
if err != nil {
unhold()
t.Fatal(err)
}
defer response.Body.Close()
body, err := io.ReadAll(response.Body)
unhold()
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")
}
}