diff --git a/cmd/dependencycheck/main.go b/cmd/dependencycheck/main.go index eaa3d64..57fe0ef 100644 --- a/cmd/dependencycheck/main.go +++ b/cmd/dependencycheck/main.go @@ -2,6 +2,8 @@ package main import ( "bytes" + "crypto/tls" + "crypto/x509" "encoding/json" "flag" "fmt" @@ -17,10 +19,11 @@ import ( ) type apiClient struct { - baseURL string - client *http.Client - token string - userID string + baseURL string + client *http.Client + transport *http.Transport + token string + userID string } func main() { @@ -32,9 +35,23 @@ func main() { } 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() - 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 { return err } @@ -130,7 +147,9 @@ func (c *apiClient) verifyConcurrentIdempotency() error { instances = make(map[string]struct{}) 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} defer transport.CloseIdleConnections() diff --git a/cmd/lab5experiment/api_scenario.go b/cmd/lab5experiment/api_scenario.go index 048a121..e238e09 100644 --- a/cmd/lab5experiment/api_scenario.go +++ b/cmd/lab5experiment/api_scenario.go @@ -3,6 +3,8 @@ package main import ( "bytes" "context" + "crypto/tls" + "crypto/x509" "encoding/base64" "encoding/json" "errors" @@ -12,16 +14,18 @@ import ( _ "image/jpeg" "io" "net/http" + "os" "strings" "time" "github.com/google/uuid" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model" ) type apiState struct { BaseURL string `json:"base_url"` + CAFile string `json:"ca_file"` Token string `json:"token"` AttachmentID string `json:"attachment_id"` } @@ -41,11 +45,15 @@ type apiChat struct { func runAPIProduce(arguments []string, output io.Writer) error { flags := flag.NewFlagSet("api-produce", flag.ContinueOnError) 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 { - 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] password := "Lab5-" + uuid.NewString() 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 { 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 { @@ -116,7 +126,10 @@ func runAPIVerify(arguments []string, input io.Reader, output io.Writer) error { if err := json.NewDecoder(input).Decode(&state); err != nil { 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) defer cancel() 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) { body, err := json.Marshal(map[string]string{ "username": username, "display_name": username, "password": password, diff --git a/cmd/lab5experiment/main.go b/cmd/lab5experiment/main.go index 35c5241..420a23d 100644 --- a/cmd/lab5experiment/main.go +++ b/cmd/lab5experiment/main.go @@ -21,15 +21,15 @@ import ( "github.com/google/uuid" "github.com/redis/go-redis/v9" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/broker/redisstream" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/config" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/database" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment/transform" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment/worker" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/objectstore" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/outbox" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/postgres" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/broker/redisstream" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/config" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/database" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment/transform" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment/worker" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/objectstore" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/outbox" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/postgres" ) const ( diff --git a/cmd/messenger/main.go b/cmd/messenger/main.go index c2c6c96..39bd0bd 100644 --- a/cmd/messenger/main.go +++ b/cmd/messenger/main.go @@ -5,8 +5,8 @@ import ( "log/slog" "os" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/bootstrap" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/logger" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/bootstrap" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/logger" ) func main() { diff --git a/go.mod b/go.mod index 37c0a6e..7989475 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module gitea.privcloud.tech/dizi/mtusi2026lab6 +module gitea.privcloud.tech/dizi/mtusi2026lab7 go 1.26.0 diff --git a/internal/bootstrap/migration.go b/internal/bootstrap/migration.go index 0e7dd49..3ce60ec 100644 --- a/internal/bootstrap/migration.go +++ b/internal/bootstrap/migration.go @@ -3,8 +3,8 @@ package bootstrap import ( "context" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/config" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/database" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/config" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/database" ) func RunMigrations() error { diff --git a/internal/bootstrap/pipeline.go b/internal/bootstrap/pipeline.go index 1539107..4637314 100644 --- a/internal/bootstrap/pipeline.go +++ b/internal/bootstrap/pipeline.go @@ -14,16 +14,16 @@ import ( "github.com/google/uuid" "github.com/redis/go-redis/v9" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/broker/redisstream" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/config" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/database" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment/pipeline" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment/transform" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment/worker" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/objectstore" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/outbox" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/postgres" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/broker/redisstream" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/config" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/database" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment/pipeline" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment/transform" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment/worker" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/objectstore" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/outbox" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/postgres" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry" ) func RunDispatcher(logger *slog.Logger) error { diff --git a/internal/bootstrap/reconciliation.go b/internal/bootstrap/reconciliation.go index 3f09a3f..09515e1 100644 --- a/internal/bootstrap/reconciliation.go +++ b/internal/bootstrap/reconciliation.go @@ -10,11 +10,11 @@ import ( "syscall" "time" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/config" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/database" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/objectstore" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/postgres" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/reconcile" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/config" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/database" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/objectstore" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/postgres" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/reconcile" ) type reconciliationOutput struct { diff --git a/internal/bootstrap/replay.go b/internal/bootstrap/replay.go index 70cc3e8..3c59e70 100644 --- a/internal/bootstrap/replay.go +++ b/internal/bootstrap/replay.go @@ -6,9 +6,9 @@ import ( "fmt" "io" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/config" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/database" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/postgres" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/config" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/database" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/postgres" ) func RunAttachmentReplay(arguments []string, output io.Writer) error { diff --git a/internal/bootstrap/server.go b/internal/bootstrap/server.go index 473c0b7..c4d2d19 100644 --- a/internal/bootstrap/server.go +++ b/internal/bootstrap/server.go @@ -2,6 +2,9 @@ package bootstrap import ( "context" + "crypto/tls" + "errors" + "fmt" "log/slog" "net" "net/http" @@ -9,22 +12,42 @@ import ( "os/signal" "syscall" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/config" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/database" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/httpapi" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/objectstore" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/password" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/postgres" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/session" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/config" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/database" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/httpapi" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/objectstore" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/password" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/postgres" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/security/tlsconfig" + "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 { settings, err := config.LoadServer() if err != nil { 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() if err != nil { return err @@ -76,34 +99,78 @@ func RunServer(logger *slog.Logger) error { SessionTTL: settings.SessionTTL, IdempotencyTTL: settings.IdempotencyTTL, RequestTTL: settings.RequestTimeout, InstanceID: instanceID, SwaggerPort: settings.SwaggerPort, }) - server := &http.Server{ + apiServer := &http.Server{ Addr: settings.Address, Handler: app.Handler(), ReadHeaderTimeout: settings.HTTPReadHeaderTimeout, 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 { return err } - serveResult := make(chan error, 1) - go func() { serveResult <- server.Serve(listener) }() - logger.Info("server started", "address", server.Addr) + healthListener, err := net.Listen("tcp", healthServer.Addr) + if err != nil { + _ = 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) defer stop() + var serveErr error select { - case err := <-serveResult: - return err + case result := <-serveResults: + serveErr = fmt.Errorf("%s server stopped: %w", result.name, result.err) case <-ctx.Done(): logger.Info("shutdown requested") - app.SetReady(false) - shutdownCtx, cancel := context.WithTimeout(context.Background(), settings.HTTPShutdownTimeout) - defer cancel() - if err := server.Shutdown(shutdownCtx); err != nil { - _ = server.Close() - return err - } + } + app.SetReady(false) + shutdownCtx, cancel := context.WithTimeout(context.Background(), settings.HTTPShutdownTimeout) + defer cancel() + shutdownErr := shutdownServers(shutdownCtx, apiServer, healthServer, metricsServer) + return errors.Join(serveErr, shutdownErr) +} + +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 } + for _, server := range servers { + _ = server.Close() + } + return shutdownErr } func databaseConfig(settings config.ServerConfig) database.Config { diff --git a/internal/bootstrap/telemetry.go b/internal/bootstrap/telemetry.go index bb1dcd9..e055263 100644 --- a/internal/bootstrap/telemetry.go +++ b/internal/bootstrap/telemetry.go @@ -5,7 +5,7 @@ import ( "log/slog" "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) { diff --git a/internal/broker/redisstream/broker.go b/internal/broker/redisstream/broker.go index 0788997..45fa60a 100644 --- a/internal/broker/redisstream/broker.go +++ b/internal/broker/redisstream/broker.go @@ -16,7 +16,7 @@ import ( "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/trace" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/outbox" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/outbox" ) const ( diff --git a/internal/config/config.go b/internal/config/config.go index 977abc5..9baf139 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -12,41 +12,48 @@ import ( ) type ServerConfig struct { - Address string - DatabaseURL string - CacheURL string - SessionTTL time.Duration - IdempotencyTTL time.Duration - DBMaxConns int32 - DBMinConns int32 - DBMaxConnectionAge time.Duration - DBMaxConnectionIdle time.Duration - DBHealthCheckPeriod time.Duration - DependencyTimeout time.Duration - RequestTimeout time.Duration - HTTPReadHeaderTimeout time.Duration - HTTPReadTimeout time.Duration - HTTPWriteTimeout time.Duration - HTTPIdleTimeout time.Duration - HTTPShutdownTimeout time.Duration - PasswordMemoryKiB uint32 - PasswordIterations uint32 - PasswordParallelism uint8 - PasswordSaltLength uint32 - PasswordKeyLength uint32 - SwaggerPort string - S3Endpoint string - S3Region string - S3Bucket string - S3AccessKey string - S3SecretKey string - S3UseTLS bool - S3Timeout time.Duration - AttachmentMaxBytes int64 - AttachmentMaxPixels int64 - AttachmentBodyMemory int64 - AttachmentDecodeMemory int64 - PipelineVersion int + Address string + HealthAddress string + MetricsAddress string + TLSCAPath string + TLSCertificatePath string + TLSPrivateKeyPath string + TLSAllowedClientURI string + TLSAllowedMetricsClientURI string + DatabaseURL string + CacheURL string + SessionTTL time.Duration + IdempotencyTTL time.Duration + DBMaxConns int32 + DBMinConns int32 + DBMaxConnectionAge time.Duration + DBMaxConnectionIdle time.Duration + DBHealthCheckPeriod time.Duration + DependencyTimeout time.Duration + RequestTimeout time.Duration + HTTPReadHeaderTimeout time.Duration + HTTPReadTimeout time.Duration + HTTPWriteTimeout time.Duration + HTTPIdleTimeout time.Duration + HTTPShutdownTimeout time.Duration + PasswordMemoryKiB uint32 + PasswordIterations uint32 + PasswordParallelism uint8 + PasswordSaltLength uint32 + PasswordKeyLength uint32 + SwaggerPort string + S3Endpoint string + S3Region string + S3Bucket string + S3AccessKey string + S3SecretKey string + S3UseTLS bool + S3Timeout time.Duration + AttachmentMaxBytes int64 + AttachmentMaxPixels int64 + AttachmentBodyMemory int64 + AttachmentDecodeMemory int64 + PipelineVersion int } type MigrationConfig struct { @@ -111,6 +118,34 @@ func LoadServer() (ServerConfig, error) { if err != nil { 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) if err != nil { return ServerConfig{}, err @@ -216,7 +251,11 @@ func LoadServer() (ServerConfig, error) { } 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, DBMaxConns: int32(database.maxConns), DBMinConns: int32(database.minConns), DBMaxConnectionAge: database.maxConnectionAge, DBMaxConnectionIdle: database.maxConnectionIdle, @@ -371,6 +410,39 @@ func requiredPort(values *viper.Viper, name string) (string, error) { 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) { value, err := requiredString(values, name) if err != nil { diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 80d2216..7d53cbb 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -46,6 +46,34 @@ func TestLoadValuesRejectsUnknownVersion(t *testing.T) { 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) { t.Helper() path := filepath.Join(t.TempDir(), "messenger.yaml") @@ -64,6 +92,14 @@ func setConfigEnvironment(t *testing.T, content string) { const validTestConfig = `version: 1 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_ttl: 1h idempotency_ttl: 24h diff --git a/internal/config/loader.go b/internal/config/loader.go index 6cd115c..0abbf59 100644 --- a/internal/config/loader.go +++ b/internal/config/loader.go @@ -12,17 +12,24 @@ import ( const supportedConfigVersion = 1 var environmentKeys = map[string]string{ - "server.host": "APP_HOST", - "server.port": "APP_PORT", - "server.swagger_port": "SWAGGER_PORT", - "database.url": "DATABASE_URL", - "cache.url": "CACHE_URL", - "object_storage.endpoint": "S3_ENDPOINT", - "object_storage.region": "S3_REGION", - "object_storage.bucket": "S3_BUCKET", - "object_storage.access_key": "S3_ACCESS_KEY", - "object_storage.secret_key": "S3_SECRET_KEY", - "broker.url": "BROKER_URL", + "server.host": "APP_HOST", + "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", + "database.url": "DATABASE_URL", + "cache.url": "CACHE_URL", + "object_storage.endpoint": "S3_ENDPOINT", + "object_storage.region": "S3_REGION", + "object_storage.bucket": "S3_BUCKET", + "object_storage.access_key": "S3_ACCESS_KEY", + "object_storage.secret_key": "S3_SECRET_KEY", + "broker.url": "BROKER_URL", } func loadValues() (*viper.Viper, error) { diff --git a/internal/database/database.go b/internal/database/database.go index c631b06..0a00149 100644 --- a/internal/database/database.go +++ b/internal/database/database.go @@ -8,7 +8,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" - "gitea.privcloud.tech/dizi/mtusi2026lab6/migrations" + "gitea.privcloud.tech/dizi/mtusi2026lab7/migrations" ) var ( diff --git a/internal/messenger/attachment/service.go b/internal/messenger/attachment/service.go index 38e5bdc..3054d5f 100644 --- a/internal/messenger/attachment/service.go +++ b/internal/messenger/attachment/service.go @@ -19,8 +19,8 @@ import ( "github.com/google/uuid" "golang.org/x/sync/semaphore" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry" ) type Repository interface { diff --git a/internal/messenger/attachment/service_test.go b/internal/messenger/attachment/service_test.go index 296f283..448c4ac 100644 --- a/internal/messenger/attachment/service_test.go +++ b/internal/messenger/attachment/service_test.go @@ -15,7 +15,7 @@ import ( "github.com/stretchr/testify/require" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model" ) func TestUploadLifecycle(t *testing.T) { diff --git a/internal/messenger/attachment/worker/worker.go b/internal/messenger/attachment/worker/worker.go index 45ff600..6ef0db2 100644 --- a/internal/messenger/attachment/worker/worker.go +++ b/internal/messenger/attachment/worker/worker.go @@ -23,11 +23,11 @@ import ( "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/trace" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/broker/redisstream" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment/transform" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/objectstore" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/broker/redisstream" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment/transform" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/objectstore" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry" ) type Repository interface { diff --git a/internal/messenger/attachment/worker/worker_test.go b/internal/messenger/attachment/worker/worker_test.go index c2ca384..05d1cdd 100644 --- a/internal/messenger/attachment/worker/worker_test.go +++ b/internal/messenger/attachment/worker/worker_test.go @@ -9,9 +9,9 @@ import ( "github.com/stretchr/testify/require" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment/transform" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/objectstore" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment/transform" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/objectstore" ) func TestConfigRequiresEnoughMemoryForMaximumImage(t *testing.T) { diff --git a/internal/messenger/httpapi/attachments.go b/internal/messenger/httpapi/attachments.go index 2e832d6..84b6a79 100644 --- a/internal/messenger/httpapi/attachments.go +++ b/internal/messenger/httpapi/attachments.go @@ -16,9 +16,9 @@ import ( "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/metric" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry" ) func (s *Server) uploadAttachment(w http.ResponseWriter, r *http.Request) *apiError { diff --git a/internal/messenger/httpapi/auth.go b/internal/messenger/httpapi/auth.go index 29419a1..8827532 100644 --- a/internal/messenger/httpapi/auth.go +++ b/internal/messenger/httpapi/auth.go @@ -6,7 +6,7 @@ import ( "net/http" "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 { diff --git a/internal/messenger/httpapi/handlers.go b/internal/messenger/httpapi/handlers.go index 9084d13..036c500 100644 --- a/internal/messenger/httpapi/handlers.go +++ b/internal/messenger/httpapi/handlers.go @@ -9,7 +9,7 @@ import ( "time" "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}$`) diff --git a/internal/messenger/httpapi/messenger_interface.go b/internal/messenger/httpapi/messenger_interface.go index 9844c25..418ddbf 100644 --- a/internal/messenger/httpapi/messenger_interface.go +++ b/internal/messenger/httpapi/messenger_interface.go @@ -4,8 +4,8 @@ import ( "context" "time" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model" ) type UserRepository interface { diff --git a/internal/messenger/httpapi/model.go b/internal/messenger/httpapi/model.go index 7f3f6dc..366c128 100644 --- a/internal/messenger/httpapi/model.go +++ b/internal/messenger/httpapi/model.go @@ -1,7 +1,7 @@ package httpapi import ( - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model" "github.com/google/uuid" ) diff --git a/internal/messenger/httpapi/routes.go b/internal/messenger/httpapi/routes.go index f272767..6912660 100644 --- a/internal/messenger/httpapi/routes.go +++ b/internal/messenger/httpapi/routes.go @@ -14,9 +14,6 @@ func (s *Server) route(w http.ResponseWriter, r *http.Request) *apiError { handler = s.live case "/health/ready": handler = s.readiness - case "/metrics": - s.metrics.handler.ServeHTTP(w, r) - return nil case "/api/v1/users": handler = s.users case "/api/v1/users/me": diff --git a/internal/messenger/httpapi/server.go b/internal/messenger/httpapi/server.go index fcc18bf..0be6957 100644 --- a/internal/messenger/httpapi/server.go +++ b/internal/messenger/httpapi/server.go @@ -15,7 +15,7 @@ import ( semconv "go.opentelemetry.io/otel/semconv/v1.34.0" "go.opentelemetry.io/otel/trace" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry" ) type Dependencies struct { @@ -94,6 +94,29 @@ func (s *Server) Handler() http.Handler { 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) { requestContext := telemetry.Extract(r.Context(), propagation.HeaderCarrier(r.Header)) tracer := otel.Tracer("messenger-api/http") diff --git a/internal/messenger/httpapi/server_test.go b/internal/messenger/httpapi/server_test.go index c1bf91d..73b341d 100644 --- a/internal/messenger/httpapi/server_test.go +++ b/internal/messenger/httpapi/server_test.go @@ -14,8 +14,8 @@ import ( "github.com/stretchr/testify/suite" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model" ) var errDependency = errors.New("dependency unavailable") @@ -135,7 +135,7 @@ func (s *MessengerSuite) TestReadinessReturnsUnavailableForDependencyFailure() { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { 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 { 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() { t := s.T() tests := []struct { @@ -376,3 +399,10 @@ func serveRequest(server *Server, method, path, body string) *httptest.ResponseR server.Handler().ServeHTTP(response, request) 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 +} diff --git a/internal/objectstore/store.go b/internal/objectstore/store.go index e2d6ded..e9f7b62 100644 --- a/internal/objectstore/store.go +++ b/internal/objectstore/store.go @@ -18,7 +18,7 @@ import ( "go.opentelemetry.io/otel/codes" "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") diff --git a/internal/outbox/dispatcher.go b/internal/outbox/dispatcher.go index ea74f61..5b76b75 100644 --- a/internal/outbox/dispatcher.go +++ b/internal/outbox/dispatcher.go @@ -11,8 +11,8 @@ import ( "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/trace" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry" ) var errLeaseLost = errors.New("outbox lease lost") diff --git a/internal/outbox/dispatcher_test.go b/internal/outbox/dispatcher_test.go index b9d792c..51c4145 100644 --- a/internal/outbox/dispatcher_test.go +++ b/internal/outbox/dispatcher_test.go @@ -8,7 +8,7 @@ import ( "testing" "time" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model" "github.com/stretchr/testify/require" ) diff --git a/internal/postgres/attachment_jobs.go b/internal/postgres/attachment_jobs.go index 6c959de..314e7fc 100644 --- a/internal/postgres/attachment_jobs.go +++ b/internal/postgres/attachment_jobs.go @@ -10,7 +10,7 @@ import ( "github.com/google/uuid" "github.com/jackc/pgx/v5" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model" ) const attachmentJobTopic = "attachment.jobs" diff --git a/internal/postgres/attachment_lease.go b/internal/postgres/attachment_lease.go index 9e631a9..261f3b9 100644 --- a/internal/postgres/attachment_lease.go +++ b/internal/postgres/attachment_lease.go @@ -5,7 +5,7 @@ import ( "fmt" "time" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model" ) func (s *Store) RenewAttachmentJobLease( diff --git a/internal/postgres/attachment_recovery.go b/internal/postgres/attachment_recovery.go index e305a79..4774764 100644 --- a/internal/postgres/attachment_recovery.go +++ b/internal/postgres/attachment_recovery.go @@ -9,7 +9,7 @@ import ( "github.com/google/uuid" "github.com/jackc/pgx/v5" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model" ) func (s *Store) RecoverExpiredAttachmentJobs( diff --git a/internal/postgres/attachments.go b/internal/postgres/attachments.go index 2765eda..2a5d759 100644 --- a/internal/postgres/attachments.go +++ b/internal/postgres/attachments.go @@ -8,7 +8,7 @@ import ( "github.com/jackc/pgx/v5" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model" ) const attachmentColumns = ` diff --git a/internal/postgres/errors.go b/internal/postgres/errors.go index 39509ad..8c13bb9 100644 --- a/internal/postgres/errors.go +++ b/internal/postgres/errors.go @@ -1,6 +1,6 @@ package postgres -import "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" +import "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model" var ( ErrConflict = model.ErrConflict diff --git a/internal/postgres/idempotency.go b/internal/postgres/idempotency.go index 4bbb95b..3261e66 100644 --- a/internal/postgres/idempotency.go +++ b/internal/postgres/idempotency.go @@ -12,7 +12,7 @@ import ( "github.com/google/uuid" "github.com/jackc/pgx/v5" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model" ) const expiredIdempotencyCleanupBatch = 100 diff --git a/internal/postgres/outbox.go b/internal/postgres/outbox.go index 0817f7c..b6b056a 100644 --- a/internal/postgres/outbox.go +++ b/internal/postgres/outbox.go @@ -8,7 +8,7 @@ import ( "github.com/google/uuid" "github.com/jackc/pgx/v5" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model" ) func (s *Store) ClaimOutboxEvents( diff --git a/internal/postgres/store.go b/internal/postgres/store.go index 44980b7..3d72658 100644 --- a/internal/postgres/store.go +++ b/internal/postgres/store.go @@ -10,7 +10,7 @@ import ( "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgxpool" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model" ) type Store struct { diff --git a/internal/postgres/store_integration_test.go b/internal/postgres/store_integration_test.go index e4184db..2e025bd 100644 --- a/internal/postgres/store_integration_test.go +++ b/internal/postgres/store_integration_test.go @@ -15,10 +15,10 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "github.com/stretchr/testify/suite" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/database" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/postgres" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/reconcile" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/database" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/postgres" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/reconcile" ) type PostgresSuite struct { diff --git a/internal/reconcile/reconcile.go b/internal/reconcile/reconcile.go index 15607f8..4c04575 100644 --- a/internal/reconcile/reconcile.go +++ b/internal/reconcile/reconcile.go @@ -6,7 +6,7 @@ import ( "fmt" "time" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model" ) type MetadataStore interface { diff --git a/internal/reconcile/reconcile_test.go b/internal/reconcile/reconcile_test.go index 36a2955..2236ab8 100644 --- a/internal/reconcile/reconcile_test.go +++ b/internal/reconcile/reconcile_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/require" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model" ) func TestReconcilerLifecycleAndRepeat(t *testing.T) { diff --git a/internal/security/tlsconfig/server.go b/internal/security/tlsconfig/server.go new file mode 100644 index 0000000..c767c26 --- /dev/null +++ b/internal/security/tlsconfig/server.go @@ -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 +} diff --git a/internal/security/tlsconfig/server_test.go b/internal/security/tlsconfig/server_test.go new file mode 100644 index 0000000..3183b4f --- /dev/null +++ b/internal/security/tlsconfig/server_test.go @@ -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 +} diff --git a/internal/session/session.go b/internal/session/session.go index a7df4b9..e4763a0 100644 --- a/internal/session/session.go +++ b/internal/session/session.go @@ -14,7 +14,7 @@ import ( "github.com/valkey-io/valkey-go" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model" ) const ( diff --git a/internal/session/session_integration_test.go b/internal/session/session_integration_test.go index a82e5eb..1fd3784 100644 --- a/internal/session/session_integration_test.go +++ b/internal/session/session_integration_test.go @@ -11,7 +11,7 @@ import ( "github.com/google/uuid" "github.com/stretchr/testify/suite" - "gitea.privcloud.tech/dizi/mtusi2026lab6/internal/session" + "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/session" ) type SessionSuite struct {