feat: enforce TLS service identities

This commit is contained in:
2026-11-04 23:05:11 +03:00
parent cb51354889
commit 951e554e06
46 changed files with 681 additions and 165 deletions
+22 -3
View File
@@ -2,6 +2,8 @@ package main
import ( import (
"bytes" "bytes"
"crypto/tls"
"crypto/x509"
"encoding/json" "encoding/json"
"flag" "flag"
"fmt" "fmt"
@@ -19,6 +21,7 @@ import (
type apiClient struct { type apiClient struct {
baseURL string baseURL string
client *http.Client client *http.Client
transport *http.Transport
token string token string
userID string userID string
} }
@@ -32,9 +35,23 @@ func main() {
} }
func run() error { func run() error {
baseURL := flag.String("base-url", "http://localhost:8080", "API base URL") baseURL := flag.String("base-url", "https://localhost:8443", "API base URL")
caFile := flag.String("ca-file", ".runtime/security/public-ca/ca.crt", "trusted CA certificate")
flag.Parse() flag.Parse()
client := &apiClient{baseURL: *baseURL, client: &http.Client{Timeout: 10 * time.Second}} caPEM, err := os.ReadFile(*caFile)
if err != nil {
return fmt.Errorf("read trusted CA: %w", err)
}
roots := x509.NewCertPool()
if !roots.AppendCertsFromPEM(caPEM) {
return fmt.Errorf("trusted CA does not contain a certificate")
}
transport := &http.Transport{TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12, RootCAs: roots}}
defer transport.CloseIdleConnections()
client := &apiClient{
baseURL: *baseURL, client: &http.Client{Transport: transport, Timeout: 10 * time.Second},
transport: transport,
}
if err := client.registerAndLogin(); err != nil { if err := client.registerAndLogin(); err != nil {
return err return err
} }
@@ -130,7 +147,9 @@ func (c *apiClient) verifyConcurrentIdempotency() error {
instances = make(map[string]struct{}) instances = make(map[string]struct{})
messageID string messageID string
) )
transport := &http.Transport{DisableKeepAlives: true, MaxConnsPerHost: workers} transport := c.transport.Clone()
transport.DisableKeepAlives = true
transport.MaxConnsPerHost = workers
client := &http.Client{Transport: transport, Timeout: 10 * time.Second} client := &http.Client{Transport: transport, Timeout: 10 * time.Second}
defer transport.CloseIdleConnections() defer transport.CloseIdleConnections()
+32 -6
View File
@@ -3,6 +3,8 @@ package main
import ( import (
"bytes" "bytes"
"context" "context"
"crypto/tls"
"crypto/x509"
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"errors" "errors"
@@ -12,16 +14,18 @@ import (
_ "image/jpeg" _ "image/jpeg"
"io" "io"
"net/http" "net/http"
"os"
"strings" "strings"
"time" "time"
"github.com/google/uuid" "github.com/google/uuid"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
type apiState struct { type apiState struct {
BaseURL string `json:"base_url"` BaseURL string `json:"base_url"`
CAFile string `json:"ca_file"`
Token string `json:"token"` Token string `json:"token"`
AttachmentID string `json:"attachment_id"` AttachmentID string `json:"attachment_id"`
} }
@@ -41,11 +45,15 @@ type apiChat struct {
func runAPIProduce(arguments []string, output io.Writer) error { func runAPIProduce(arguments []string, output io.Writer) error {
flags := flag.NewFlagSet("api-produce", flag.ContinueOnError) flags := flag.NewFlagSet("api-produce", flag.ContinueOnError)
flags.SetOutput(io.Discard) flags.SetOutput(io.Discard)
baseURL := flags.String("base-url", "http://nginx:8080", "messenger base URL") baseURL := flags.String("base-url", "https://nginx:8443", "messenger base URL")
caFile := flags.String("ca-file", "/run/security/public-ca/ca.crt", "trusted CA certificate")
if err := flags.Parse(arguments); err != nil || flags.NArg() != 0 { if err := flags.Parse(arguments); err != nil || flags.NArg() != 0 {
return errors.New("usage: lab5experiment api-produce [-base-url URL]") return errors.New("usage: lab5experiment api-produce [-base-url URL] [-ca-file PATH]")
}
client, err := newAPIClient(*caFile)
if err != nil {
return err
} }
client := &http.Client{Timeout: 10 * time.Second}
suffix := strings.ReplaceAll(uuid.NewString(), "-", "")[:12] suffix := strings.ReplaceAll(uuid.NewString(), "-", "")[:12]
password := "Lab5-" + uuid.NewString() password := "Lab5-" + uuid.NewString()
owner, err := registerAPIUser(client, *baseURL, "qa_"+suffix, password) owner, err := registerAPIUser(client, *baseURL, "qa_"+suffix, password)
@@ -102,7 +110,9 @@ func runAPIProduce(arguments []string, output io.Writer) error {
if response.StatusCode != http.StatusConflict { if response.StatusCode != http.StatusConflict {
return fmt.Errorf("queued content returned %d, expected 409", response.StatusCode) return fmt.Errorf("queued content returned %d, expected 409", response.StatusCode)
} }
return json.NewEncoder(output).Encode(apiState{BaseURL: *baseURL, Token: token, AttachmentID: attachment.ID}) return json.NewEncoder(output).Encode(apiState{
BaseURL: *baseURL, CAFile: *caFile, Token: token, AttachmentID: attachment.ID,
})
} }
func runAPIVerify(arguments []string, input io.Reader, output io.Writer) error { func runAPIVerify(arguments []string, input io.Reader, output io.Writer) error {
@@ -116,7 +126,10 @@ func runAPIVerify(arguments []string, input io.Reader, output io.Writer) error {
if err := json.NewDecoder(input).Decode(&state); err != nil { if err := json.NewDecoder(input).Decode(&state); err != nil {
return fmt.Errorf("decode API scenario state: %w", err) return fmt.Errorf("decode API scenario state: %w", err)
} }
client := &http.Client{Timeout: 10 * time.Second} client, err := newAPIClient(state.CAFile)
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), *waitTimeout) ctx, cancel := context.WithTimeout(context.Background(), *waitTimeout)
defer cancel() defer cancel()
var attachment model.Attachment var attachment model.Attachment
@@ -176,6 +189,19 @@ func runAPIVerify(arguments []string, input io.Reader, output io.Writer) error {
}) })
} }
func newAPIClient(caFile string) (*http.Client, error) {
caPEM, err := os.ReadFile(caFile)
if err != nil {
return nil, fmt.Errorf("read trusted CA: %w", err)
}
roots := x509.NewCertPool()
if !roots.AppendCertsFromPEM(caPEM) {
return nil, errors.New("trusted CA does not contain a certificate")
}
transport := &http.Transport{TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12, RootCAs: roots}}
return &http.Client{Transport: transport, Timeout: 10 * time.Second}, nil
}
func registerAPIUser(client *http.Client, baseURL, username, password string) (apiUser, error) { func registerAPIUser(client *http.Client, baseURL, username, password string) (apiUser, error) {
body, err := json.Marshal(map[string]string{ body, err := json.Marshal(map[string]string{
"username": username, "display_name": username, "password": password, "username": username, "display_name": username, "password": password,
+9 -9
View File
@@ -21,15 +21,15 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/broker/redisstream" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/broker/redisstream"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/config" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/config"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/database" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/database"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment/transform" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment/transform"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment/worker" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment/worker"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/objectstore" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/objectstore"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/outbox" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/outbox"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/postgres" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/postgres"
) )
const ( const (
+2 -2
View File
@@ -5,8 +5,8 @@ import (
"log/slog" "log/slog"
"os" "os"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/bootstrap" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/bootstrap"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/logger" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/logger"
) )
func main() { func main() {
+1 -1
View File
@@ -1,4 +1,4 @@
module gitea.privcloud.tech/dizi/mtusi2026lab6 module gitea.privcloud.tech/dizi/mtusi2026lab7
go 1.26.0 go 1.26.0
+2 -2
View File
@@ -3,8 +3,8 @@ package bootstrap
import ( import (
"context" "context"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/config" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/config"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/database" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/database"
) )
func RunMigrations() error { func RunMigrations() error {
+10 -10
View File
@@ -14,16 +14,16 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/broker/redisstream" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/broker/redisstream"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/config" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/config"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/database" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/database"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment/pipeline" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment/pipeline"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment/transform" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment/transform"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment/worker" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment/worker"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/objectstore" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/objectstore"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/outbox" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/outbox"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/postgres" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/postgres"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry"
) )
func RunDispatcher(logger *slog.Logger) error { func RunDispatcher(logger *slog.Logger) error {
+5 -5
View File
@@ -10,11 +10,11 @@ import (
"syscall" "syscall"
"time" "time"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/config" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/config"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/database" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/database"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/objectstore" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/objectstore"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/postgres" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/postgres"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/reconcile" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/reconcile"
) )
type reconciliationOutput struct { type reconciliationOutput struct {
+3 -3
View File
@@ -6,9 +6,9 @@ import (
"fmt" "fmt"
"io" "io"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/config" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/config"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/database" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/database"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/postgres" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/postgres"
) )
func RunAttachmentReplay(arguments []string, output io.Writer) error { func RunAttachmentReplay(arguments []string, output io.Writer) error {
+87 -20
View File
@@ -2,6 +2,9 @@ package bootstrap
import ( import (
"context" "context"
"crypto/tls"
"errors"
"fmt"
"log/slog" "log/slog"
"net" "net"
"net/http" "net/http"
@@ -9,22 +12,42 @@ import (
"os/signal" "os/signal"
"syscall" "syscall"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/config" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/config"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/database" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/database"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/httpapi" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/httpapi"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/objectstore" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/objectstore"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/password" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/password"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/postgres" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/postgres"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/session" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/security/tlsconfig"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/session"
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry"
) )
type serverResult struct {
name string
err error
}
func RunServer(logger *slog.Logger) error { func RunServer(logger *slog.Logger) error {
settings, err := config.LoadServer() settings, err := config.LoadServer()
if err != nil { if err != nil {
return err return err
} }
apiTLSConfiguration, err := tlsconfig.LoadServer(tlsconfig.ServerConfig{
CAPath: settings.TLSCAPath, CertificatePath: settings.TLSCertificatePath,
PrivateKeyPath: settings.TLSPrivateKeyPath, AllowedClientURI: settings.TLSAllowedClientURI,
})
if err != nil {
return err
}
metricsTLSConfiguration, err := tlsconfig.LoadServer(tlsconfig.ServerConfig{
CAPath: settings.TLSCAPath, CertificatePath: settings.TLSCertificatePath,
PrivateKeyPath: settings.TLSPrivateKeyPath, AllowedClientURI: settings.TLSAllowedMetricsClientURI,
})
if err != nil {
return err
}
instanceID, err := os.Hostname() instanceID, err := os.Hostname()
if err != nil { if err != nil {
return err return err
@@ -76,34 +99,78 @@ func RunServer(logger *slog.Logger) error {
SessionTTL: settings.SessionTTL, IdempotencyTTL: settings.IdempotencyTTL, SessionTTL: settings.SessionTTL, IdempotencyTTL: settings.IdempotencyTTL,
RequestTTL: settings.RequestTimeout, InstanceID: instanceID, SwaggerPort: settings.SwaggerPort, RequestTTL: settings.RequestTimeout, InstanceID: instanceID, SwaggerPort: settings.SwaggerPort,
}) })
server := &http.Server{ apiServer := &http.Server{
Addr: settings.Address, Handler: app.Handler(), ReadHeaderTimeout: settings.HTTPReadHeaderTimeout, Addr: settings.Address, Handler: app.Handler(), ReadHeaderTimeout: settings.HTTPReadHeaderTimeout,
ReadTimeout: settings.HTTPReadTimeout, WriteTimeout: settings.HTTPWriteTimeout, ReadTimeout: settings.HTTPReadTimeout, WriteTimeout: settings.HTTPWriteTimeout,
IdleTimeout: settings.HTTPIdleTimeout, IdleTimeout: settings.HTTPIdleTimeout, TLSConfig: apiTLSConfiguration,
} }
listener, err := net.Listen("tcp", server.Addr) healthServer := &http.Server{
Addr: settings.HealthAddress, Handler: app.HealthHandler(),
ReadHeaderTimeout: settings.HTTPReadHeaderTimeout, ReadTimeout: settings.HTTPReadTimeout,
WriteTimeout: settings.HTTPWriteTimeout, IdleTimeout: settings.HTTPIdleTimeout,
}
metricsServer := &http.Server{
Addr: settings.MetricsAddress, Handler: app.MetricsHandler(),
ReadHeaderTimeout: settings.HTTPReadHeaderTimeout, ReadTimeout: settings.HTTPReadTimeout,
WriteTimeout: settings.HTTPWriteTimeout, IdleTimeout: settings.HTTPIdleTimeout,
TLSConfig: metricsTLSConfiguration,
}
apiListener, err := net.Listen("tcp", apiServer.Addr)
if err != nil { if err != nil {
return err return err
} }
serveResult := make(chan error, 1) healthListener, err := net.Listen("tcp", healthServer.Addr)
go func() { serveResult <- server.Serve(listener) }() if err != nil {
logger.Info("server started", "address", server.Addr) _ = apiListener.Close()
return err
}
metricsListener, err := net.Listen("tcp", metricsServer.Addr)
if err != nil {
_ = apiListener.Close()
_ = healthListener.Close()
return err
}
serveResults := make(chan serverResult, 3)
go serveHTTP(serveResults, "api", apiServer, tls.NewListener(apiListener, apiTLSConfiguration))
go serveHTTP(serveResults, "health", healthServer, healthListener)
go serveHTTP(serveResults, "metrics", metricsServer, tls.NewListener(metricsListener, metricsTLSConfiguration))
logger.Info("servers started", "api_address", apiServer.Addr, "health_address", healthServer.Addr, "metrics_address", metricsServer.Addr)
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop() defer stop()
var serveErr error
select { select {
case err := <-serveResult: case result := <-serveResults:
return err serveErr = fmt.Errorf("%s server stopped: %w", result.name, result.err)
case <-ctx.Done(): case <-ctx.Done():
logger.Info("shutdown requested") logger.Info("shutdown requested")
}
app.SetReady(false) app.SetReady(false)
shutdownCtx, cancel := context.WithTimeout(context.Background(), settings.HTTPShutdownTimeout) shutdownCtx, cancel := context.WithTimeout(context.Background(), settings.HTTPShutdownTimeout)
defer cancel() defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil { shutdownErr := shutdownServers(shutdownCtx, apiServer, healthServer, metricsServer)
_ = server.Close() return errors.Join(serveErr, shutdownErr)
return err }
func serveHTTP(results chan<- serverResult, name string, server *http.Server, listener net.Listener) {
results <- serverResult{name: name, err: server.Serve(listener)}
}
func shutdownServers(ctx context.Context, servers ...*http.Server) error {
results := make(chan error, len(servers))
for _, server := range servers {
go func() { results <- server.Shutdown(ctx) }()
} }
var shutdownErr error
for range servers {
shutdownErr = errors.Join(shutdownErr, <-results)
}
if shutdownErr == nil {
return nil return nil
} }
for _, server := range servers {
_ = server.Close()
}
return shutdownErr
} }
func databaseConfig(settings config.ServerConfig) database.Config { func databaseConfig(settings config.ServerConfig) database.Config {
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"log/slog" "log/slog"
"time" "time"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry"
) )
func startTelemetry(serviceName, instanceID string) (*telemetry.Runtime, *slog.Logger, error) { func startTelemetry(serviceName, instanceID string) (*telemetry.Runtime, *slog.Logger, error) {
+1 -1
View File
@@ -16,7 +16,7 @@ import (
"go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/trace"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/outbox" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/outbox"
) )
const ( const (
+73 -1
View File
@@ -13,6 +13,13 @@ import (
type ServerConfig struct { type ServerConfig struct {
Address string Address string
HealthAddress string
MetricsAddress string
TLSCAPath string
TLSCertificatePath string
TLSPrivateKeyPath string
TLSAllowedClientURI string
TLSAllowedMetricsClientURI string
DatabaseURL string DatabaseURL string
CacheURL string CacheURL string
SessionTTL time.Duration SessionTTL time.Duration
@@ -111,6 +118,34 @@ func LoadServer() (ServerConfig, error) {
if err != nil { if err != nil {
return ServerConfig{}, err return ServerConfig{}, err
} }
healthAddress, err := loopbackAddress(values, "server.health_address")
if err != nil {
return ServerConfig{}, err
}
metricsAddress, err := nonLoopbackAddress(values, "server.metrics_address")
if err != nil {
return ServerConfig{}, err
}
tlsCAPath, err := requiredString(values, "server.tls.ca_path")
if err != nil {
return ServerConfig{}, err
}
tlsCertificatePath, err := requiredString(values, "server.tls.certificate_path")
if err != nil {
return ServerConfig{}, err
}
tlsPrivateKeyPath, err := requiredString(values, "server.tls.private_key_path")
if err != nil {
return ServerConfig{}, err
}
tlsAllowedClientURI, err := requiredString(values, "server.tls.allowed_client_uri")
if err != nil {
return ServerConfig{}, err
}
tlsAllowedMetricsClientURI, err := requiredString(values, "server.tls.allowed_metrics_client_uri")
if err != nil {
return ServerConfig{}, err
}
database, err := loadDatabaseConfig(values) database, err := loadDatabaseConfig(values)
if err != nil { if err != nil {
return ServerConfig{}, err return ServerConfig{}, err
@@ -216,7 +251,11 @@ func LoadServer() (ServerConfig, error) {
} }
return ServerConfig{ return ServerConfig{
Address: net.JoinHostPort(host, port), DatabaseURL: database.url, CacheURL: cacheURL, Address: net.JoinHostPort(host, port), HealthAddress: healthAddress, MetricsAddress: metricsAddress,
TLSCAPath: tlsCAPath, TLSCertificatePath: tlsCertificatePath,
TLSPrivateKeyPath: tlsPrivateKeyPath, TLSAllowedClientURI: tlsAllowedClientURI,
TLSAllowedMetricsClientURI: tlsAllowedMetricsClientURI,
DatabaseURL: database.url, CacheURL: cacheURL,
SessionTTL: sessionTTL, IdempotencyTTL: idempotencyTTL, SessionTTL: sessionTTL, IdempotencyTTL: idempotencyTTL,
DBMaxConns: int32(database.maxConns), DBMinConns: int32(database.minConns), DBMaxConns: int32(database.maxConns), DBMinConns: int32(database.minConns),
DBMaxConnectionAge: database.maxConnectionAge, DBMaxConnectionIdle: database.maxConnectionIdle, DBMaxConnectionAge: database.maxConnectionAge, DBMaxConnectionIdle: database.maxConnectionIdle,
@@ -371,6 +410,39 @@ func requiredPort(values *viper.Viper, name string) (string, error) {
return value, nil return value, nil
} }
func loopbackAddress(values *viper.Viper, name string) (string, error) {
value, err := requiredString(values, name)
if err != nil {
return "", err
}
host, port, err := net.SplitHostPort(value)
if err != nil || host != "127.0.0.1" {
return "", fmt.Errorf("%s: must use 127.0.0.1 with an explicit port", name)
}
if _, err := integerValue(port, 1, 65535); err != nil {
return "", fmt.Errorf("%s: %w", name, err)
}
return net.JoinHostPort(host, port), nil
}
func nonLoopbackAddress(values *viper.Viper, name string) (string, error) {
value, err := requiredString(values, name)
if err != nil {
return "", err
}
host, port, err := net.SplitHostPort(value)
if err != nil || host == "" || strings.EqualFold(host, "localhost") {
return "", fmt.Errorf("%s: must use a non-loopback host with an explicit port", name)
}
if address := net.ParseIP(host); address != nil && address.IsLoopback() {
return "", fmt.Errorf("%s: must use a non-loopback host with an explicit port", name)
}
if _, err := integerValue(port, 1, 65535); err != nil {
return "", fmt.Errorf("%s: %w", name, err)
}
return net.JoinHostPort(host, port), nil
}
func duration(values *viper.Viper, name string, minimum, maximum time.Duration) (time.Duration, error) { func duration(values *viper.Viper, name string, minimum, maximum time.Duration) (time.Duration, error) {
value, err := requiredString(values, name) value, err := requiredString(values, name)
if err != nil { if err != nil {
+36
View File
@@ -46,6 +46,34 @@ func TestLoadValuesRejectsUnknownVersion(t *testing.T) {
require.ErrorContains(t, err, "version: must be 1") require.ErrorContains(t, err, "version: must be 1")
} }
func TestLoadServerLoadsTLSAndHealthSettings(t *testing.T) {
setConfigEnvironment(t, validTestConfig)
settings, err := LoadServer()
require.NoError(t, err)
require.Equal(t, "127.0.0.1:8082", settings.HealthAddress)
require.Equal(t, "0.0.0.0:9091", settings.MetricsAddress)
require.Equal(t, "/run/security/internal-ca/ca.crt", settings.TLSCAPath)
require.Equal(t, "spiffe://mtusi/lab7/load-balancer", settings.TLSAllowedClientURI)
require.Equal(t, "spiffe://mtusi/lab7/prometheus", settings.TLSAllowedMetricsClientURI)
}
func TestLoadServerRejectsNonLoopbackHealthAddress(t *testing.T) {
content := strings.Replace(validTestConfig, "health_address: 127.0.0.1:8082", "health_address: 0.0.0.0:8082", 1)
setConfigEnvironment(t, content)
_, err := LoadServer()
require.ErrorContains(t, err, "server.health_address: must use 127.0.0.1")
}
func TestLoadServerRejectsLoopbackMetricsAddress(t *testing.T) {
content := strings.Replace(validTestConfig, "metrics_address: 0.0.0.0:9091", "metrics_address: 127.0.0.1:9091", 1)
setConfigEnvironment(t, content)
_, err := LoadServer()
require.ErrorContains(t, err, "server.metrics_address: must use a non-loopback host")
}
func setConfigEnvironment(t *testing.T, content string) { func setConfigEnvironment(t *testing.T, content string) {
t.Helper() t.Helper()
path := filepath.Join(t.TempDir(), "messenger.yaml") path := filepath.Join(t.TempDir(), "messenger.yaml")
@@ -64,6 +92,14 @@ func setConfigEnvironment(t *testing.T, content string) {
const validTestConfig = `version: 1 const validTestConfig = `version: 1
server: server:
health_address: 127.0.0.1:8082
metrics_address: 0.0.0.0:9091
tls:
ca_path: /run/security/internal-ca/ca.crt
certificate_path: /run/security/api/tls.crt
private_key_path: /run/security/api/tls.key
allowed_client_uri: spiffe://mtusi/lab7/load-balancer
allowed_metrics_client_uri: spiffe://mtusi/lab7/prometheus
session_store: valkey session_store: valkey
session_ttl: 1h session_ttl: 1h
idempotency_ttl: 24h idempotency_ttl: 24h
+7
View File
@@ -14,6 +14,13 @@ const supportedConfigVersion = 1
var environmentKeys = map[string]string{ var environmentKeys = map[string]string{
"server.host": "APP_HOST", "server.host": "APP_HOST",
"server.port": "APP_PORT", "server.port": "APP_PORT",
"server.health_address": "APP_HEALTH_ADDRESS",
"server.metrics_address": "APP_METRICS_ADDRESS",
"server.tls.ca_path": "APP_TLS_CA_PATH",
"server.tls.certificate_path": "APP_TLS_CERTIFICATE_PATH",
"server.tls.private_key_path": "APP_TLS_PRIVATE_KEY_PATH",
"server.tls.allowed_client_uri": "APP_TLS_ALLOWED_CLIENT_URI",
"server.tls.allowed_metrics_client_uri": "APP_TLS_ALLOWED_METRICS_CLIENT_URI",
"server.swagger_port": "SWAGGER_PORT", "server.swagger_port": "SWAGGER_PORT",
"database.url": "DATABASE_URL", "database.url": "DATABASE_URL",
"cache.url": "CACHE_URL", "cache.url": "CACHE_URL",
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"gitea.privcloud.tech/dizi/mtusi2026lab6/migrations" "gitea.privcloud.tech/dizi/mtusi2026lab7/migrations"
) )
var ( var (
+2 -2
View File
@@ -19,8 +19,8 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"golang.org/x/sync/semaphore" "golang.org/x/sync/semaphore"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry"
) )
type Repository interface { type Repository interface {
@@ -15,7 +15,7 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
func TestUploadLifecycle(t *testing.T) { func TestUploadLifecycle(t *testing.T) {
@@ -23,11 +23,11 @@ import (
"go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/trace"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/broker/redisstream" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/broker/redisstream"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment/transform" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment/transform"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/objectstore" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/objectstore"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry"
) )
type Repository interface { type Repository interface {
@@ -9,9 +9,9 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment/transform" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment/transform"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/objectstore" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/objectstore"
) )
func TestConfigRequiresEnoughMemoryForMaximumImage(t *testing.T) { func TestConfigRequiresEnoughMemoryForMaximumImage(t *testing.T) {
+3 -3
View File
@@ -16,9 +16,9 @@ import (
"go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric" "go.opentelemetry.io/otel/metric"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry"
) )
func (s *Server) uploadAttachment(w http.ResponseWriter, r *http.Request) *apiError { func (s *Server) uploadAttachment(w http.ResponseWriter, r *http.Request) *apiError {
+1 -1
View File
@@ -6,7 +6,7 @@ import (
"net/http" "net/http"
"strings" "strings"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError { func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError {
+1 -1
View File
@@ -9,7 +9,7 @@ import (
"time" "time"
"unicode/utf8" "unicode/utf8"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
@@ -4,8 +4,8 @@ import (
"context" "context"
"time" "time"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
type UserRepository interface { type UserRepository interface {
+1 -1
View File
@@ -1,7 +1,7 @@
package httpapi package httpapi
import ( import (
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
"github.com/google/uuid" "github.com/google/uuid"
) )
-3
View File
@@ -14,9 +14,6 @@ func (s *Server) route(w http.ResponseWriter, r *http.Request) *apiError {
handler = s.live handler = s.live
case "/health/ready": case "/health/ready":
handler = s.readiness handler = s.readiness
case "/metrics":
s.metrics.handler.ServeHTTP(w, r)
return nil
case "/api/v1/users": case "/api/v1/users":
handler = s.users handler = s.users
case "/api/v1/users/me": case "/api/v1/users/me":
+24 -1
View File
@@ -15,7 +15,7 @@ import (
semconv "go.opentelemetry.io/otel/semconv/v1.34.0" semconv "go.opentelemetry.io/otel/semconv/v1.34.0"
"go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/trace"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry"
) )
type Dependencies struct { type Dependencies struct {
@@ -94,6 +94,29 @@ func (s *Server) Handler() http.Handler {
return http.HandlerFunc(s.serve) return http.HandlerFunc(s.serve)
} }
func (s *Server) HealthHandler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/health/live", func(w http.ResponseWriter, r *http.Request) {
s.serveHealth(w, r, s.live)
})
mux.HandleFunc("/health/ready", func(w http.ResponseWriter, r *http.Request) {
s.serveHealth(w, r, s.readiness)
})
return mux
}
func (s *Server) MetricsHandler() http.Handler {
mux := http.NewServeMux()
mux.Handle("/metrics", s.metrics.handler)
return mux
}
func (s *Server) serveHealth(w http.ResponseWriter, r *http.Request, handler requestHandler) {
if err := handler(w, r); err != nil {
writeError(w, "", err)
}
}
func (s *Server) serve(w http.ResponseWriter, r *http.Request) { func (s *Server) serve(w http.ResponseWriter, r *http.Request) {
requestContext := telemetry.Extract(r.Context(), propagation.HeaderCarrier(r.Header)) requestContext := telemetry.Extract(r.Context(), propagation.HeaderCarrier(r.Header))
tracer := otel.Tracer("messenger-api/http") tracer := otel.Tracer("messenger-api/http")
+33 -3
View File
@@ -14,8 +14,8 @@ import (
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
var errDependency = errors.New("dependency unavailable") var errDependency = errors.New("dependency unavailable")
@@ -135,7 +135,7 @@ func (s *MessengerSuite) TestReadinessReturnsUnavailableForDependencyFailure() {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
server := s.server(tt.store, tt.sessions, passwordsStub{}, tt.objects, attachmentServiceStub{}) server := s.server(tt.store, tt.sessions, passwordsStub{}, tt.objects, attachmentServiceStub{})
response := serveRequest(server, http.MethodGet, "/health/ready", "") response := serveHealthRequest(server, http.MethodGet, "/health/ready")
if response.Code != http.StatusServiceUnavailable { if response.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want %d", response.Code, http.StatusServiceUnavailable) t.Fatalf("status = %d, want %d", response.Code, http.StatusServiceUnavailable)
} }
@@ -143,6 +143,29 @@ func (s *MessengerSuite) TestReadinessReturnsUnavailableForDependencyFailure() {
} }
} }
func (s *MessengerSuite) TestHealthHandlerDoesNotExposeBusinessAPI() {
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
response := serveHealthRequest(server, http.MethodGet, "/api/v1/users/me")
s.Equal(http.StatusNotFound, response.Code)
}
func (s *MessengerSuite) TestMetricsHandlerOnlyExposesMetrics() {
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
server.metrics.handler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNoContent)
})
metrics := httptest.NewRecorder()
server.MetricsHandler().ServeHTTP(metrics, httptest.NewRequest(http.MethodGet, "/metrics", nil))
s.Equal(http.StatusNoContent, metrics.Code)
for _, path := range []string{"/health/ready", "/api/v1/users/me"} {
response := httptest.NewRecorder()
server.MetricsHandler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, path, nil))
s.Equal(http.StatusNotFound, response.Code, path)
}
s.Equal(http.StatusNotFound, serveRequest(server, http.MethodGet, "/metrics", "").Code)
}
func (s *MessengerSuite) TestBusinessRequestReturnsUnavailableForDependencyFailure() { func (s *MessengerSuite) TestBusinessRequestReturnsUnavailableForDependencyFailure() {
t := s.T() t := s.T()
tests := []struct { tests := []struct {
@@ -376,3 +399,10 @@ func serveRequest(server *Server, method, path, body string) *httptest.ResponseR
server.Handler().ServeHTTP(response, request) server.Handler().ServeHTTP(response, request)
return response return response
} }
func serveHealthRequest(server *Server, method, path string) *httptest.ResponseRecorder {
request := httptest.NewRequest(method, path, nil)
response := httptest.NewRecorder()
server.HealthHandler().ServeHTTP(response, request)
return response
}
+1 -1
View File
@@ -18,7 +18,7 @@ import (
"go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/trace"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
var ErrNotFound = errors.New("object not found") var ErrNotFound = errors.New("object not found")
+2 -2
View File
@@ -11,8 +11,8 @@ import (
"go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/trace"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry"
) )
var errLeaseLost = errors.New("outbox lease lost") var errLeaseLost = errors.New("outbox lease lost")
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"testing" "testing"
"time" "time"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
+1 -1
View File
@@ -10,7 +10,7 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
const attachmentJobTopic = "attachment.jobs" const attachmentJobTopic = "attachment.jobs"
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"fmt" "fmt"
"time" "time"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
func (s *Store) RenewAttachmentJobLease( func (s *Store) RenewAttachmentJobLease(
+1 -1
View File
@@ -9,7 +9,7 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
func (s *Store) RecoverExpiredAttachmentJobs( func (s *Store) RecoverExpiredAttachmentJobs(
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
const attachmentColumns = ` const attachmentColumns = `
+1 -1
View File
@@ -1,6 +1,6 @@
package postgres package postgres
import "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" import "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
var ( var (
ErrConflict = model.ErrConflict ErrConflict = model.ErrConflict
+1 -1
View File
@@ -12,7 +12,7 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
const expiredIdempotencyCleanupBatch = 100 const expiredIdempotencyCleanupBatch = 100
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
func (s *Store) ClaimOutboxEvents( func (s *Store) ClaimOutboxEvents(
+1 -1
View File
@@ -10,7 +10,7 @@ import (
"github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
type Store struct { type Store struct {
+4 -4
View File
@@ -15,10 +15,10 @@ import (
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/database" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/database"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/postgres" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/postgres"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/reconcile" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/reconcile"
) )
type PostgresSuite struct { type PostgresSuite struct {
+1 -1
View File
@@ -6,7 +6,7 @@ import (
"fmt" "fmt"
"time" "time"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
type MetadataStore interface { type MetadataStore interface {
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
func TestReconcilerLifecycleAndRepeat(t *testing.T) { func TestReconcilerLifecycleAndRepeat(t *testing.T) {
+54
View File
@@ -0,0 +1,54 @@
package tlsconfig
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"net/url"
"os"
)
type ServerConfig struct {
CAPath string
CertificatePath string
PrivateKeyPath string
AllowedClientURI string
}
func LoadServer(config ServerConfig) (*tls.Config, error) {
allowedURI, err := url.Parse(config.AllowedClientURI)
if err != nil || allowedURI.Scheme == "" || allowedURI.Host == "" || allowedURI.String() != config.AllowedClientURI {
return nil, errors.New("allowed client URI must be an absolute canonical URI")
}
caPEM, err := os.ReadFile(config.CAPath)
if err != nil {
return nil, fmt.Errorf("read client CA: %w", err)
}
clientCAs := x509.NewCertPool()
if !clientCAs.AppendCertsFromPEM(caPEM) {
return nil, errors.New("client CA does not contain a certificate")
}
certificate, err := tls.LoadX509KeyPair(config.CertificatePath, config.PrivateKeyPath)
if err != nil {
return nil, fmt.Errorf("load server certificate: %w", err)
}
return &tls.Config{
MinVersion: tls.VersionTLS13,
Certificates: []tls.Certificate{certificate},
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: clientCAs,
VerifyConnection: func(state tls.ConnectionState) error {
if len(state.PeerCertificates) == 0 {
return errors.New("client certificate is required")
}
for _, identity := range state.PeerCertificates[0].URIs {
if identity.String() == config.AllowedClientURI {
return nil
}
}
return fmt.Errorf("client certificate URI SAN is not allowed: want %s", config.AllowedClientURI)
},
}, nil
}
+185
View File
@@ -0,0 +1,185 @@
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 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
}
+1 -1
View File
@@ -14,7 +14,7 @@ import (
"github.com/valkey-io/valkey-go" "github.com/valkey-io/valkey-go"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
) )
const ( const (
+1 -1
View File
@@ -11,7 +11,7 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/session" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/session"
) )
type SessionSuite struct { type SessionSuite struct {