Files
dizi a8edaf058d
CI / verify (pull_request) Successful in 14m53s
chore: finalize lab7 security verification
2026-11-06 22:00:42 +03:00

186 lines
6.2 KiB
Go

package tlsconfig
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"net"
"net/url"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/require"
)
const allowedClientURI = "spiffe://mtusi/lab7/load-balancer"
func TestServerRequiresAllowedClientIdentity(t *testing.T) {
files := issueTestCertificates(t)
serverConfig, err := LoadServer(ServerConfig{
CAPath: files.caPath, CertificatePath: files.serverCertificatePath,
PrivateKeyPath: files.serverPrivateKeyPath, AllowedClientURI: allowedClientURI,
})
require.NoError(t, err)
tests := []struct {
name string
certificatePath string
privateKeyPath string
wantServerError bool
}{
{name: "allowed identity", certificatePath: files.allowedCertificatePath, privateKeyPath: files.allowedPrivateKeyPath},
{name: "other identity from trusted CA", certificatePath: files.otherCertificatePath, privateKeyPath: files.otherPrivateKeyPath, wantServerError: true},
{name: "missing certificate", wantServerError: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
clientConfig := &tls.Config{RootCAs: files.caPool, ServerName: "api.internal", MinVersion: tls.VersionTLS13}
if tt.certificatePath != "" {
certificate, loadErr := tls.LoadX509KeyPair(tt.certificatePath, tt.privateKeyPath)
require.NoError(t, loadErr)
clientConfig.Certificates = []tls.Certificate{certificate}
}
serverErr, clientErr := handshake(serverConfig, clientConfig)
if tt.wantServerError {
require.Error(t, serverErr)
return
}
require.NoError(t, serverErr)
require.NoError(t, clientErr)
})
}
}
func TestLoadServerRejectsInvalidClientCA(t *testing.T) {
directory := t.TempDir()
caPath := filepath.Join(directory, "ca.pem")
require.NoError(t, os.WriteFile(caPath, []byte("not a certificate"), 0o600))
_, err := LoadServer(ServerConfig{CAPath: caPath, AllowedClientURI: allowedClientURI})
require.ErrorContains(t, err, "client CA does not contain a certificate")
}
func handshake(serverConfig, clientConfig *tls.Config) (error, error) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return err, err
}
defer func() { _ = listener.Close() }()
serverResult := make(chan error, 1)
go func() {
connection, acceptErr := listener.Accept()
if acceptErr != nil {
serverResult <- acceptErr
return
}
server := tls.Server(connection, serverConfig)
serverResult <- server.Handshake()
_ = server.Close()
}()
client, clientErr := tls.Dial("tcp", listener.Addr().String(), clientConfig)
if client != nil {
_ = client.Close()
}
serverErr := <-serverResult
return serverErr, clientErr
}
type testCertificateFiles struct {
caPath string
serverCertificatePath string
serverPrivateKeyPath string
allowedCertificatePath string
allowedPrivateKeyPath string
otherCertificatePath string
otherPrivateKeyPath string
caPool *x509.CertPool
}
func issueTestCertificates(t *testing.T) testCertificateFiles {
t.Helper()
directory := t.TempDir()
caCertificate, caKey := issueCA(t)
caPath := filepath.Join(directory, "ca.pem")
writeCertificate(t, caPath, caCertificate.Raw)
caPool := x509.NewCertPool()
caPool.AddCert(caCertificate)
serverCertificatePath, serverPrivateKeyPath := issueLeaf(t, directory, caCertificate, caKey, "server", nil, []string{"api.internal"}, x509.ExtKeyUsageServerAuth)
allowed := mustParseURI(t, allowedClientURI)
allowedCertificatePath, allowedPrivateKeyPath := issueLeaf(t, directory, caCertificate, caKey, "allowed", []*url.URL{allowed}, nil, x509.ExtKeyUsageClientAuth)
other := mustParseURI(t, "spiffe://mtusi/lab7/worker")
otherCertificatePath, otherPrivateKeyPath := issueLeaf(t, directory, caCertificate, caKey, "other", []*url.URL{other}, nil, x509.ExtKeyUsageClientAuth)
return testCertificateFiles{
caPath: caPath, serverCertificatePath: serverCertificatePath, serverPrivateKeyPath: serverPrivateKeyPath,
allowedCertificatePath: allowedCertificatePath, allowedPrivateKeyPath: allowedPrivateKeyPath,
otherCertificatePath: otherCertificatePath, otherPrivateKeyPath: otherPrivateKeyPath, caPool: caPool,
}
}
func issueCA(t *testing.T) (*x509.Certificate, *ecdsa.PrivateKey) {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
template := &x509.Certificate{
SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "test CA"},
NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour),
IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign,
}
der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
require.NoError(t, err)
certificate, err := x509.ParseCertificate(der)
require.NoError(t, err)
return certificate, key
}
func issueLeaf(
t *testing.T,
directory string,
ca *x509.Certificate,
caKey *ecdsa.PrivateKey,
name string,
identities []*url.URL,
dnsNames []string,
usage x509.ExtKeyUsage,
) (string, string) {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
template := &x509.Certificate{
SerialNumber: big.NewInt(time.Now().UnixNano()), Subject: pkix.Name{CommonName: name},
NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{usage},
URIs: identities, DNSNames: dnsNames,
}
der, err := x509.CreateCertificate(rand.Reader, template, ca, &key.PublicKey, caKey)
require.NoError(t, err)
certificatePath := filepath.Join(directory, name+".crt")
privateKeyPath := filepath.Join(directory, name+".key")
writeCertificate(t, certificatePath, der)
keyDER, err := x509.MarshalPKCS8PrivateKey(key)
require.NoError(t, err)
require.NoError(t, os.WriteFile(privateKeyPath, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER}), 0o600))
return certificatePath, privateKeyPath
}
func writeCertificate(t *testing.T, path string, der []byte) {
t.Helper()
require.NoError(t, os.WriteFile(path, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o600))
}
func mustParseURI(t *testing.T, value string) *url.URL {
t.Helper()
identity, err := url.Parse(value)
require.NoError(t, err)
return identity
}