forked from mtusi2026/mtusi2026lab7
feat: secure service connections and login
This commit is contained in:
@@ -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 {
|
||||
|
||||
@@ -2,6 +2,7 @@ package bootstrap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net"
|
||||
@@ -14,16 +15,17 @@ 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/security/tlsconfig"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry"
|
||||
)
|
||||
|
||||
func RunDispatcher(logger *slog.Logger) error {
|
||||
@@ -48,7 +50,11 @@ func RunDispatcher(logger *slog.Logger) error {
|
||||
if err := telemetry.ObserveDatabasePool(observability.MeterProvider().Meter("messenger-dispatcher/database"), pool); err != nil {
|
||||
return err
|
||||
}
|
||||
client, err := newRedisClient(settings.BrokerURL)
|
||||
brokerTLSConfiguration, err := loadClientTLS(settings.BrokerTLS)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
client, err := newRedisClient(settings.BrokerURL, brokerTLSConfiguration)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -61,9 +67,6 @@ func RunDispatcher(logger *slog.Logger) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := broker.Ensure(context.Background()); err != nil {
|
||||
return err
|
||||
}
|
||||
metrics := pipeline.NewMetrics(observability.MeterProvider().Meter("messenger-dispatcher"), observability.MetricsHandler(), 0)
|
||||
dispatcher, err := outbox.New(postgres.New(pool), broker, metrics, outbox.Config{
|
||||
BatchSize: settings.BatchSize, LeaseDuration: settings.LeaseDuration,
|
||||
@@ -74,8 +77,14 @@ func RunDispatcher(logger *slog.Logger) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
metricsTLSConfiguration, err := loadServerTLS(settings.MetricsTLS)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Info("outbox dispatcher started", "stream", settings.Stream)
|
||||
return runPipelineProcess(logger, settings.MetricsAddress, metrics.Handler(), dispatcher.Run)
|
||||
return runPipelineProcess(
|
||||
logger, settings.MetricsAddress, settings.HealthAddress, metricsTLSConfiguration, metrics.Handler(), dispatcher.Run,
|
||||
)
|
||||
}
|
||||
|
||||
func RunWorker(logger *slog.Logger) error {
|
||||
@@ -103,12 +112,16 @@ func RunWorker(logger *slog.Logger) error {
|
||||
objects, err := objectstore.New(objectstore.Config{
|
||||
Endpoint: settings.S3Endpoint, Region: settings.S3Region, Bucket: settings.S3Bucket,
|
||||
AccessKey: settings.S3AccessKey, SecretKey: settings.S3SecretKey,
|
||||
UseTLS: settings.S3UseTLS, Timeout: settings.S3Timeout,
|
||||
UseTLS: settings.S3UseTLS, CAPath: settings.S3CAPath, Timeout: settings.S3Timeout,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
client, err := newRedisClient(settings.BrokerURL)
|
||||
brokerTLSConfiguration, err := loadClientTLS(settings.BrokerTLS)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
client, err := newRedisClient(settings.BrokerURL, brokerTLSConfiguration)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -144,15 +157,36 @@ func RunWorker(logger *slog.Logger) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
metricsTLSConfiguration, err := loadServerTLS(settings.MetricsTLS)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
logger.Info("attachment worker started", "consumer", consumer, "concurrency", settings.Concurrency)
|
||||
return runPipelineProcess(logger, settings.MetricsAddress, metrics.Handler(), processorWorker.Run)
|
||||
return runPipelineProcess(
|
||||
logger, settings.MetricsAddress, settings.HealthAddress, metricsTLSConfiguration, metrics.Handler(), processorWorker.Run,
|
||||
)
|
||||
}
|
||||
|
||||
func newRedisClient(rawURL string) (*redis.Client, error) {
|
||||
func loadClientTLS(config config.ClientTLSConfig) (*tls.Config, error) {
|
||||
return tlsconfig.LoadClient(tlsconfig.ClientConfig{
|
||||
CAPath: config.CAPath, CertificatePath: config.CertificatePath,
|
||||
PrivateKeyPath: config.PrivateKeyPath, ServerName: config.ServerName,
|
||||
})
|
||||
}
|
||||
|
||||
func loadServerTLS(config config.ServerTLSConfig) (*tls.Config, error) {
|
||||
return tlsconfig.LoadServer(tlsconfig.ServerConfig{
|
||||
CAPath: config.CAPath, CertificatePath: config.CertificatePath,
|
||||
PrivateKeyPath: config.PrivateKeyPath, AllowedClientURI: config.AllowedClientURI,
|
||||
})
|
||||
}
|
||||
|
||||
func newRedisClient(rawURL string, tlsConfiguration *tls.Config) (*redis.Client, error) {
|
||||
options, err := redis.ParseURL(rawURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
options.TLSConfig = tlsConfiguration.Clone()
|
||||
client := redis.NewClient(options)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
@@ -166,19 +200,32 @@ func newRedisClient(rawURL string) (*redis.Client, error) {
|
||||
func runPipelineProcess(
|
||||
logger *slog.Logger,
|
||||
metricsAddress string,
|
||||
healthAddress string,
|
||||
metricsTLSConfiguration *tls.Config,
|
||||
metricsHandler http.Handler,
|
||||
run func(context.Context) error,
|
||||
) error {
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("/metrics", metricsHandler)
|
||||
mux.HandleFunc("/health/live", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) })
|
||||
server := &http.Server{Addr: metricsAddress, Handler: mux, ReadHeaderTimeout: 5 * time.Second}
|
||||
listener, err := net.Listen("tcp", metricsAddress)
|
||||
metricsMux := http.NewServeMux()
|
||||
metricsMux.Handle("/metrics", metricsHandler)
|
||||
metricsServer := &http.Server{
|
||||
Addr: metricsAddress, Handler: metricsMux, ReadHeaderTimeout: 5 * time.Second,
|
||||
TLSConfig: metricsTLSConfiguration,
|
||||
}
|
||||
healthMux := http.NewServeMux()
|
||||
healthMux.HandleFunc("/health/live", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) })
|
||||
healthServer := &http.Server{Addr: healthAddress, Handler: healthMux, ReadHeaderTimeout: 5 * time.Second}
|
||||
metricsListener, err := net.Listen("tcp", metricsAddress)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
serveResult := make(chan error, 1)
|
||||
go func() { serveResult <- server.Serve(listener) }()
|
||||
healthListener, err := net.Listen("tcp", healthAddress)
|
||||
if err != nil {
|
||||
_ = metricsListener.Close()
|
||||
return err
|
||||
}
|
||||
serveResult := make(chan error, 2)
|
||||
go func() { serveResult <- metricsServer.Serve(tls.NewListener(metricsListener, metricsTLSConfiguration)) }()
|
||||
go func() { serveResult <- healthServer.Serve(healthListener) }()
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
@@ -195,8 +242,10 @@ func runPipelineProcess(
|
||||
}
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := server.Shutdown(shutdownCtx); err != nil && result == nil {
|
||||
result = err
|
||||
for _, server := range []*http.Server{metricsServer, healthServer} {
|
||||
if err := server.Shutdown(shutdownCtx); err != nil && result == nil {
|
||||
result = err
|
||||
}
|
||||
}
|
||||
if errors.Is(result, http.ErrServerClosed) || errors.Is(result, context.Canceled) {
|
||||
return nil
|
||||
|
||||
@@ -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 {
|
||||
@@ -57,7 +57,7 @@ func RunReconciliation(arguments []string, output io.Writer) error {
|
||||
objects, err := objectstore.New(objectstore.Config{
|
||||
Endpoint: settings.S3Endpoint, Region: settings.S3Region, Bucket: settings.S3Bucket,
|
||||
AccessKey: settings.S3AccessKey, SecretKey: settings.S3SecretKey,
|
||||
UseTLS: settings.S3UseTLS, Timeout: settings.S3Timeout,
|
||||
UseTLS: settings.S3UseTLS, CAPath: settings.S3CAPath, Timeout: settings.S3Timeout,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+112
-27
@@ -2,6 +2,9 @@ package bootstrap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
@@ -9,22 +12,43 @@ 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/loginlimit"
|
||||
"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
|
||||
@@ -42,11 +66,27 @@ func RunServer(logger *slog.Logger) error {
|
||||
if err := telemetry.ObserveDatabasePool(observability.MeterProvider().Meter("messenger-api/database"), pool); err != nil {
|
||||
return err
|
||||
}
|
||||
sessions, err := session.New(settings.CacheURL)
|
||||
cacheTLSConfiguration, err := tlsconfig.LoadClient(tlsconfig.ClientConfig{
|
||||
CAPath: settings.CacheTLS.CAPath, CertificatePath: settings.CacheTLS.CertificatePath,
|
||||
PrivateKeyPath: settings.CacheTLS.PrivateKeyPath, ServerName: settings.CacheTLS.ServerName,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sessions, err := session.New(settings.CacheURL, cacheTLSConfiguration)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = sessions.Close() }()
|
||||
loginLimiter, err := loginlimit.New(settings.CacheURL, loginlimit.Config{
|
||||
AccountAttempts: int64(settings.LoginRateLimitAccountAttempts),
|
||||
SourceAttempts: int64(settings.LoginRateLimitSourceAttempts),
|
||||
Window: settings.LoginRateLimitWindow,
|
||||
}, cacheTLSConfiguration)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = loginLimiter.Close() }()
|
||||
passwords, err := password.New(password.Config{
|
||||
MemoryKiB: settings.PasswordMemoryKiB, Iterations: settings.PasswordIterations,
|
||||
Parallelism: settings.PasswordParallelism, SaltLength: settings.PasswordSaltLength,
|
||||
@@ -70,40 +110,85 @@ func RunServer(logger *slog.Logger) error {
|
||||
}
|
||||
app := httpapi.NewServer(logger, httpapi.Dependencies{
|
||||
Users: repository, Chats: repository, Messages: repository, Attachments: attachments,
|
||||
Sessions: sessions, Passwords: passwords, Database: repository, Objects: objects,
|
||||
Sessions: sessions, Passwords: passwords, LoginLimiter: loginLimiter,
|
||||
Database: repository, Objects: objects,
|
||||
Meter: observability.MeterProvider().Meter("messenger-api"), Metrics: observability.MetricsHandler(),
|
||||
}, httpapi.Config{
|
||||
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 {
|
||||
@@ -118,6 +203,6 @@ func objectStoreConfig(settings config.ServerConfig) objectstore.Config {
|
||||
return objectstore.Config{
|
||||
Endpoint: settings.S3Endpoint, Region: settings.S3Region, Bucket: settings.S3Bucket,
|
||||
AccessKey: settings.S3AccessKey, SecretKey: settings.S3SecretKey,
|
||||
UseTLS: settings.S3UseTLS, Timeout: settings.S3Timeout,
|
||||
UseTLS: settings.S3UseTLS, CAPath: settings.S3CAPath, Timeout: settings.S3Timeout,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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 (
|
||||
|
||||
+179
-40
@@ -12,41 +12,53 @@ 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
|
||||
CacheTLS ClientTLSConfig
|
||||
SessionTTL time.Duration
|
||||
IdempotencyTTL time.Duration
|
||||
LoginRateLimitAccountAttempts int
|
||||
LoginRateLimitSourceAttempts int
|
||||
LoginRateLimitWindow 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
|
||||
S3CAPath string
|
||||
S3Timeout time.Duration
|
||||
AttachmentMaxBytes int64
|
||||
AttachmentMaxPixels int64
|
||||
AttachmentBodyMemory int64
|
||||
AttachmentDecodeMemory int64
|
||||
PipelineVersion int
|
||||
}
|
||||
|
||||
type MigrationConfig struct {
|
||||
@@ -74,6 +86,7 @@ type ReconciliationConfig struct {
|
||||
S3AccessKey string
|
||||
S3SecretKey string
|
||||
S3UseTLS bool
|
||||
S3CAPath string
|
||||
S3Timeout time.Duration
|
||||
}
|
||||
|
||||
@@ -94,9 +107,24 @@ type objectStorageConfig struct {
|
||||
accessKey string
|
||||
secretKey string
|
||||
useTLS bool
|
||||
caPath string
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
type ClientTLSConfig struct {
|
||||
CAPath string
|
||||
CertificatePath string
|
||||
PrivateKeyPath string
|
||||
ServerName string
|
||||
}
|
||||
|
||||
type ServerTLSConfig struct {
|
||||
CAPath string
|
||||
CertificatePath string
|
||||
PrivateKeyPath string
|
||||
AllowedClientURI string
|
||||
}
|
||||
|
||||
func LoadServer() (ServerConfig, error) {
|
||||
values, err := loadValues()
|
||||
if err != nil {
|
||||
@@ -111,6 +139,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
|
||||
@@ -119,6 +175,10 @@ func LoadServer() (ServerConfig, error) {
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
cacheTLS, err := loadClientTLSConfig(values, "cache.tls")
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
store, err := requiredString(values, "server.session_store")
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
@@ -135,6 +195,18 @@ func LoadServer() (ServerConfig, error) {
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
loginRateLimitAccountAttempts, err := integer(values, "server.login_rate_limit.account_attempts", 1, 1_000_000)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
loginRateLimitSourceAttempts, err := integer(values, "server.login_rate_limit.source_attempts", 1, 1_000_000)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
loginRateLimitWindow, err := duration(values, "server.login_rate_limit.window", time.Second, 24*time.Hour)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
requestTimeout, err := duration(values, "server.request_timeout", time.Second, 5*time.Minute)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
@@ -216,9 +288,16 @@ 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, CacheTLS: cacheTLS,
|
||||
SessionTTL: sessionTTL, IdempotencyTTL: idempotencyTTL,
|
||||
DBMaxConns: int32(database.maxConns), DBMinConns: int32(database.minConns),
|
||||
LoginRateLimitAccountAttempts: loginRateLimitAccountAttempts,
|
||||
LoginRateLimitSourceAttempts: loginRateLimitSourceAttempts,
|
||||
LoginRateLimitWindow: loginRateLimitWindow,
|
||||
DBMaxConns: int32(database.maxConns), DBMinConns: int32(database.minConns),
|
||||
DBMaxConnectionAge: database.maxConnectionAge, DBMaxConnectionIdle: database.maxConnectionIdle,
|
||||
DBHealthCheckPeriod: database.healthCheckPeriod, DependencyTimeout: database.dependencyTimeout,
|
||||
RequestTimeout: requestTimeout,
|
||||
@@ -229,7 +308,7 @@ func LoadServer() (ServerConfig, error) {
|
||||
PasswordSaltLength: uint32(passwordSaltLength), PasswordKeyLength: uint32(passwordKeyLength),
|
||||
SwaggerPort: swaggerPort, S3Endpoint: storage.endpoint, S3Region: storage.region, S3Bucket: storage.bucket,
|
||||
S3AccessKey: storage.accessKey, S3SecretKey: storage.secretKey,
|
||||
S3UseTLS: storage.useTLS, S3Timeout: storage.timeout,
|
||||
S3UseTLS: storage.useTLS, S3CAPath: storage.caPath, S3Timeout: storage.timeout,
|
||||
AttachmentMaxBytes: int64(attachmentMaxBytes), AttachmentMaxPixels: int64(attachmentMaxPixels),
|
||||
AttachmentBodyMemory: int64(attachmentBodyMemory),
|
||||
AttachmentDecodeMemory: int64(attachmentDecodeMemory),
|
||||
@@ -277,7 +356,7 @@ func LoadReconciliation() (ReconciliationConfig, error) {
|
||||
DBHealthCheckPeriod: database.healthCheckPeriod, DependencyTimeout: database.dependencyTimeout,
|
||||
S3Endpoint: storage.endpoint, S3Region: storage.region, S3Bucket: storage.bucket,
|
||||
S3AccessKey: storage.accessKey, S3SecretKey: storage.secretKey,
|
||||
S3UseTLS: storage.useTLS, S3Timeout: storage.timeout,
|
||||
S3UseTLS: storage.useTLS, S3CAPath: storage.caPath, S3Timeout: storage.timeout,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -306,13 +385,40 @@ func loadObjectStorageConfig(values *viper.Viper) (objectStorageConfig, error) {
|
||||
if err != nil {
|
||||
return objectStorageConfig{}, err
|
||||
}
|
||||
caPath, err := requiredString(values, "object_storage.ca_path")
|
||||
if err != nil {
|
||||
return objectStorageConfig{}, err
|
||||
}
|
||||
timeout, err := duration(values, "object_storage.timeout", time.Second, 5*time.Minute)
|
||||
if err != nil {
|
||||
return objectStorageConfig{}, err
|
||||
}
|
||||
return objectStorageConfig{
|
||||
endpoint: endpoint, region: region, bucket: bucket, accessKey: accessKey,
|
||||
secretKey: secretKey, useTLS: useTLS, timeout: timeout,
|
||||
secretKey: secretKey, useTLS: useTLS, caPath: caPath, timeout: timeout,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func loadClientTLSConfig(values *viper.Viper, prefix string) (ClientTLSConfig, error) {
|
||||
caPath, err := requiredString(values, prefix+".ca_path")
|
||||
if err != nil {
|
||||
return ClientTLSConfig{}, err
|
||||
}
|
||||
certificatePath, err := requiredString(values, prefix+".certificate_path")
|
||||
if err != nil {
|
||||
return ClientTLSConfig{}, err
|
||||
}
|
||||
privateKeyPath, err := requiredString(values, prefix+".private_key_path")
|
||||
if err != nil {
|
||||
return ClientTLSConfig{}, err
|
||||
}
|
||||
serverName, err := requiredString(values, prefix+".server_name")
|
||||
if err != nil {
|
||||
return ClientTLSConfig{}, err
|
||||
}
|
||||
return ClientTLSConfig{
|
||||
CAPath: caPath, CertificatePath: certificatePath,
|
||||
PrivateKeyPath: privateKeyPath, ServerName: serverName,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -371,6 +477,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 {
|
||||
|
||||
@@ -46,6 +46,66 @@ 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)
|
||||
require.Equal(t, 5, settings.LoginRateLimitAccountAttempts)
|
||||
require.Equal(t, 20, settings.LoginRateLimitSourceAttempts)
|
||||
require.Equal(t, time.Minute, settings.LoginRateLimitWindow)
|
||||
}
|
||||
|
||||
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 TestLoadServerUsesRenderedOpenBaoSecrets(t *testing.T) {
|
||||
setConfigEnvironment(t, validTestConfig)
|
||||
path := filepath.Join(t.TempDir(), "secrets.json")
|
||||
require.NoError(t, os.WriteFile(path, []byte(`{
|
||||
"database_url":"postgres://openbao/database",
|
||||
"cache_url":"rediss://openbao/cache",
|
||||
"s3_access_key":"openbao-api",
|
||||
"s3_secret_key":"openbao-secret"
|
||||
}`), 0o600))
|
||||
t.Setenv("MESSENGER_SECRETS_FILE", path)
|
||||
|
||||
settings, err := LoadServer()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "postgres://openbao/database", settings.DatabaseURL)
|
||||
require.Equal(t, "rediss://openbao/cache", settings.CacheURL)
|
||||
require.Equal(t, "openbao-api", settings.S3AccessKey)
|
||||
require.Equal(t, "openbao-secret", settings.S3SecretKey)
|
||||
}
|
||||
|
||||
func TestLoadServerRejectsUnknownOpenBaoSecret(t *testing.T) {
|
||||
setConfigEnvironment(t, validTestConfig)
|
||||
path := filepath.Join(t.TempDir(), "secrets.json")
|
||||
require.NoError(t, os.WriteFile(path, []byte(`{"root_token":"forbidden"}`), 0o600))
|
||||
t.Setenv("MESSENGER_SECRETS_FILE", path)
|
||||
|
||||
_, err := LoadServer()
|
||||
require.ErrorContains(t, err, "unsupported field root_token")
|
||||
}
|
||||
|
||||
func setConfigEnvironment(t *testing.T, content string) {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "messenger.yaml")
|
||||
@@ -64,9 +124,21 @@ 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
|
||||
login_rate_limit:
|
||||
account_attempts: 5
|
||||
source_attempts: 20
|
||||
window: 1m
|
||||
request_timeout: 5s
|
||||
http:
|
||||
read_header_timeout: 5s
|
||||
@@ -87,10 +159,17 @@ database:
|
||||
max_connection_idle: 1m
|
||||
health_check_period: 30s
|
||||
dependency_timeout: 5s
|
||||
cache:
|
||||
tls:
|
||||
ca_path: /run/security/internal-ca/ca.crt
|
||||
certificate_path: /run/security/client/tls.crt
|
||||
private_key_path: /run/security/client/tls.key
|
||||
server_name: redis-gateway
|
||||
migration:
|
||||
timeout: 30s
|
||||
object_storage:
|
||||
use_tls: false
|
||||
ca_path: /run/security/internal-ca/ca.crt
|
||||
timeout: 5s
|
||||
attachments:
|
||||
max_bytes: 10485760
|
||||
@@ -100,6 +179,11 @@ attachments:
|
||||
pipeline:
|
||||
version: 1
|
||||
broker:
|
||||
tls:
|
||||
ca_path: /run/security/internal-ca/ca.crt
|
||||
certificate_path: /run/security/client/tls.crt
|
||||
private_key_path: /run/security/client/tls.key
|
||||
server_name: redis-gateway
|
||||
stream: attachment-jobs
|
||||
consumer_group: attachment-workers
|
||||
failed_stream: attachment-jobs-failed
|
||||
@@ -128,4 +212,10 @@ worker:
|
||||
memory_bytes: 738197504
|
||||
monitoring:
|
||||
metrics_address: 0.0.0.0:9091
|
||||
health_address: 127.0.0.1:9092
|
||||
tls:
|
||||
ca_path: /run/security/internal-ca/ca.crt
|
||||
certificate_path: /run/security/metrics/tls.crt
|
||||
private_key_path: /run/security/metrics/tls.key
|
||||
allowed_client_uri: spiffe://mtusi/lab7/prometheus
|
||||
`
|
||||
|
||||
+63
-11
@@ -1,8 +1,10 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
@@ -12,17 +14,32 @@ 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",
|
||||
}
|
||||
|
||||
var secretKeys = map[string]string{
|
||||
"database_url": "database.url",
|
||||
"cache_url": "cache.url",
|
||||
"broker_url": "broker.url",
|
||||
"s3_access_key": "object_storage.access_key",
|
||||
"s3_secret_key": "object_storage.secret_key",
|
||||
}
|
||||
|
||||
func loadValues() (*viper.Viper, error) {
|
||||
@@ -43,5 +60,40 @@ func loadValues() (*viper.Viper, error) {
|
||||
return nil, fmt.Errorf("bind %s: %w", name, err)
|
||||
}
|
||||
}
|
||||
if err := loadSecretFile(values, strings.TrimSpace(os.Getenv("MESSENGER_SECRETS_FILE"))); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
func loadSecretFile(values *viper.Viper, path string) error {
|
||||
if path == "" {
|
||||
return nil
|
||||
}
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open messenger secrets: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
decoder := json.NewDecoder(io.LimitReader(file, 64<<10))
|
||||
var secrets map[string]string
|
||||
if err := decoder.Decode(&secrets); err != nil {
|
||||
return fmt.Errorf("decode messenger secrets: %w", err)
|
||||
}
|
||||
var trailing any
|
||||
if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) {
|
||||
return errors.New("decode messenger secrets: trailing JSON value")
|
||||
}
|
||||
for name, value := range secrets {
|
||||
key, ok := secretKeys[name]
|
||||
if !ok {
|
||||
return fmt.Errorf("messenger secrets: unsupported field %s", name)
|
||||
}
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return fmt.Errorf("messenger secrets: %s is empty", name)
|
||||
}
|
||||
values.Set(key, value)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ type DispatcherConfig struct {
|
||||
DBHealthCheckPeriod time.Duration
|
||||
DependencyTimeout time.Duration
|
||||
BrokerURL string
|
||||
BrokerTLS ClientTLSConfig
|
||||
Stream string
|
||||
ConsumerGroup string
|
||||
FailedStream string
|
||||
@@ -31,6 +32,8 @@ type DispatcherConfig struct {
|
||||
CleanupInterval time.Duration
|
||||
CleanupBatchSize int
|
||||
MetricsAddress string
|
||||
HealthAddress string
|
||||
MetricsTLS ServerTLSConfig
|
||||
}
|
||||
|
||||
type WorkerConfig struct {
|
||||
@@ -47,8 +50,10 @@ type WorkerConfig struct {
|
||||
S3AccessKey string
|
||||
S3SecretKey string
|
||||
S3UseTLS bool
|
||||
S3CAPath string
|
||||
S3Timeout time.Duration
|
||||
BrokerURL string
|
||||
BrokerTLS ClientTLSConfig
|
||||
Stream string
|
||||
ConsumerGroup string
|
||||
FailedStream string
|
||||
@@ -67,6 +72,8 @@ type WorkerConfig struct {
|
||||
AttachmentMaxPixels int64
|
||||
MemoryBytes int64
|
||||
MetricsAddress string
|
||||
HealthAddress string
|
||||
MetricsTLS ServerTLSConfig
|
||||
}
|
||||
|
||||
type JobAdminConfig struct {
|
||||
@@ -116,6 +123,10 @@ func LoadDispatcher() (DispatcherConfig, error) {
|
||||
if err != nil {
|
||||
return DispatcherConfig{}, err
|
||||
}
|
||||
brokerTLS, err := loadClientTLSConfig(values, "broker.tls")
|
||||
if err != nil {
|
||||
return DispatcherConfig{}, err
|
||||
}
|
||||
batchSize, err := integer(values, "outbox.batch_size", 1, 1000)
|
||||
if err != nil {
|
||||
return DispatcherConfig{}, err
|
||||
@@ -152,16 +163,24 @@ func LoadDispatcher() (DispatcherConfig, error) {
|
||||
if err != nil {
|
||||
return DispatcherConfig{}, err
|
||||
}
|
||||
healthAddress, err := loopbackAddress(values, "monitoring.health_address")
|
||||
if err != nil {
|
||||
return DispatcherConfig{}, err
|
||||
}
|
||||
metricsTLS, err := loadServerTLSConfig(values, "monitoring.tls")
|
||||
if err != nil {
|
||||
return DispatcherConfig{}, err
|
||||
}
|
||||
return DispatcherConfig{
|
||||
DatabaseURL: database.url, DBMaxConns: int32(database.maxConns), DBMinConns: int32(database.minConns),
|
||||
DBMaxConnectionAge: database.maxConnectionAge, DBMaxConnectionIdle: database.maxConnectionIdle,
|
||||
DBHealthCheckPeriod: database.healthCheckPeriod, DependencyTimeout: database.dependencyTimeout,
|
||||
BrokerURL: broker.url, Stream: broker.stream, ConsumerGroup: broker.consumerGroup,
|
||||
BrokerURL: broker.url, BrokerTLS: brokerTLS, Stream: broker.stream, ConsumerGroup: broker.consumerGroup,
|
||||
FailedStream: broker.failedStream, FailedStreamMaxLength: int64(broker.failedStreamMaxLength),
|
||||
BatchSize: batchSize, LeaseDuration: leaseDuration, PollInterval: pollInterval,
|
||||
RecoveryInterval: recoveryInterval, RetryDelay: retryDelay,
|
||||
Retention: retention, CleanupInterval: cleanupInterval, CleanupBatchSize: cleanupBatchSize,
|
||||
MetricsAddress: metricsAddress,
|
||||
MetricsAddress: metricsAddress, HealthAddress: healthAddress, MetricsTLS: metricsTLS,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -182,6 +201,10 @@ func LoadWorker() (WorkerConfig, error) {
|
||||
if err != nil {
|
||||
return WorkerConfig{}, err
|
||||
}
|
||||
brokerTLS, err := loadClientTLSConfig(values, "broker.tls")
|
||||
if err != nil {
|
||||
return WorkerConfig{}, err
|
||||
}
|
||||
concurrency, err := integer(values, "worker.concurrency", 1, 64)
|
||||
if err != nil {
|
||||
return WorkerConfig{}, err
|
||||
@@ -247,13 +270,22 @@ func LoadWorker() (WorkerConfig, error) {
|
||||
if err != nil {
|
||||
return WorkerConfig{}, err
|
||||
}
|
||||
healthAddress, err := loopbackAddress(values, "monitoring.health_address")
|
||||
if err != nil {
|
||||
return WorkerConfig{}, err
|
||||
}
|
||||
metricsTLS, err := loadServerTLSConfig(values, "monitoring.tls")
|
||||
if err != nil {
|
||||
return WorkerConfig{}, err
|
||||
}
|
||||
return WorkerConfig{
|
||||
DatabaseURL: database.url, DBMaxConns: int32(database.maxConns), DBMinConns: int32(database.minConns),
|
||||
DBMaxConnectionAge: database.maxConnectionAge, DBMaxConnectionIdle: database.maxConnectionIdle,
|
||||
DBHealthCheckPeriod: database.healthCheckPeriod, DependencyTimeout: database.dependencyTimeout,
|
||||
S3Endpoint: storage.endpoint, S3Region: storage.region, S3Bucket: storage.bucket,
|
||||
S3AccessKey: storage.accessKey, S3SecretKey: storage.secretKey, S3UseTLS: storage.useTLS,
|
||||
S3Timeout: storage.timeout, BrokerURL: broker.url, Stream: broker.stream,
|
||||
S3CAPath: storage.caPath, S3Timeout: storage.timeout,
|
||||
BrokerURL: broker.url, BrokerTLS: brokerTLS, Stream: broker.stream,
|
||||
ConsumerGroup: broker.consumerGroup, FailedStream: broker.failedStream,
|
||||
FailedStreamMaxLength: int64(broker.failedStreamMaxLength),
|
||||
Concurrency: concurrency, Prefetch: prefetch, LeaseDuration: leaseDuration,
|
||||
@@ -261,6 +293,7 @@ func LoadWorker() (WorkerConfig, error) {
|
||||
ReclaimInterval: reclaimInterval, MaxAttempts: maxAttempts, RetryBase: retryBase, RetryMax: retryMax,
|
||||
AttachmentMaxBytes: int64(attachmentMaxBytes), AttachmentMaxPixels: int64(attachmentMaxPixels),
|
||||
MemoryBytes: int64(memoryBytes), MetricsAddress: metricsAddress,
|
||||
HealthAddress: healthAddress, MetricsTLS: metricsTLS,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -279,6 +312,29 @@ func metricsAddress(values *viper.Viper) (string, error) {
|
||||
return address, nil
|
||||
}
|
||||
|
||||
func loadServerTLSConfig(values *viper.Viper, prefix string) (ServerTLSConfig, error) {
|
||||
caPath, err := requiredString(values, prefix+".ca_path")
|
||||
if err != nil {
|
||||
return ServerTLSConfig{}, err
|
||||
}
|
||||
certificatePath, err := requiredString(values, prefix+".certificate_path")
|
||||
if err != nil {
|
||||
return ServerTLSConfig{}, err
|
||||
}
|
||||
privateKeyPath, err := requiredString(values, prefix+".private_key_path")
|
||||
if err != nil {
|
||||
return ServerTLSConfig{}, err
|
||||
}
|
||||
allowedClientURI, err := requiredString(values, prefix+".allowed_client_uri")
|
||||
if err != nil {
|
||||
return ServerTLSConfig{}, err
|
||||
}
|
||||
return ServerTLSConfig{
|
||||
CAPath: caPath, CertificatePath: certificatePath,
|
||||
PrivateKeyPath: privateKeyPath, AllowedClientURI: allowedClientURI,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func loadBrokerConfig(values *viper.Viper) (brokerConfig, error) {
|
||||
url, err := requiredString(values, "broker.url")
|
||||
if err != nil {
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/migrations"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/migrations"
|
||||
)
|
||||
|
||||
var (
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
package loginlimit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/valkey-io/valkey-go"
|
||||
)
|
||||
|
||||
const keyPrefix = "login-rate:{login}:"
|
||||
|
||||
var (
|
||||
ErrInvalidConfig = errors.New("invalid login rate limit configuration")
|
||||
ErrStore = errors.New("login rate limit store unavailable")
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
AccountAttempts int64
|
||||
SourceAttempts int64
|
||||
Window time.Duration
|
||||
}
|
||||
|
||||
type Limiter struct {
|
||||
client valkey.Client
|
||||
script *valkey.Lua
|
||||
config Config
|
||||
}
|
||||
|
||||
func New(rawURL string, config Config, tlsConfiguration ...*tls.Config) (*Limiter, error) {
|
||||
if config.AccountAttempts < 1 || config.SourceAttempts < 1 || config.Window < time.Second {
|
||||
return nil, ErrInvalidConfig
|
||||
}
|
||||
option, err := valkey.ParseURL(rawURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: parse Valkey URL: %w", ErrStore, err)
|
||||
}
|
||||
if len(tlsConfiguration) > 0 && tlsConfiguration[0] != nil {
|
||||
option.TLSConfig = tlsConfiguration[0].Clone()
|
||||
}
|
||||
option.DisableCache = true
|
||||
client, err := valkey.NewClient(option)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: create Valkey client: %w", ErrStore, err)
|
||||
}
|
||||
return &Limiter{client: client, script: valkey.NewLuaScript(limitScript), config: config}, nil
|
||||
}
|
||||
|
||||
func (l *Limiter) Allow(ctx context.Context, username, source string) (bool, time.Duration, error) {
|
||||
result, err := l.script.Exec(ctx, l.client,
|
||||
[]string{key("account", username), key("source", source)},
|
||||
[]string{
|
||||
strconv.FormatInt(l.config.Window.Milliseconds(), 10),
|
||||
strconv.FormatInt(l.config.AccountAttempts, 10),
|
||||
strconv.FormatInt(l.config.SourceAttempts, 10),
|
||||
},
|
||||
).AsIntSlice()
|
||||
if err != nil {
|
||||
return false, 0, fmt.Errorf("%w: account login attempt: %w", ErrStore, err)
|
||||
}
|
||||
if len(result) != 2 {
|
||||
return false, 0, fmt.Errorf("%w: unexpected script result", ErrStore)
|
||||
}
|
||||
return result[0] == 1, time.Duration(result[1]) * time.Millisecond, nil
|
||||
}
|
||||
|
||||
func (l *Limiter) Close() error {
|
||||
l.client.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
func key(scope, value string) string {
|
||||
digest := sha256.Sum256([]byte(value))
|
||||
return keyPrefix + scope + ":" + hex.EncodeToString(digest[:])
|
||||
}
|
||||
|
||||
const limitScript = `
|
||||
local function increment(key, window)
|
||||
local count = redis.call('INCR', key)
|
||||
if count == 1 then
|
||||
redis.call('PEXPIRE', key, window)
|
||||
end
|
||||
local ttl = redis.call('PTTL', key)
|
||||
if ttl < 1 then
|
||||
redis.call('PEXPIRE', key, window)
|
||||
ttl = window
|
||||
end
|
||||
return count, ttl
|
||||
end
|
||||
|
||||
local window = tonumber(ARGV[1])
|
||||
local account_count, account_ttl = increment(KEYS[1], window)
|
||||
local source_count, source_ttl = increment(KEYS[2], window)
|
||||
local retry_after = 0
|
||||
|
||||
if account_count > tonumber(ARGV[2]) then
|
||||
retry_after = account_ttl
|
||||
end
|
||||
if source_count > tonumber(ARGV[3]) and source_ttl > retry_after then
|
||||
retry_after = source_ttl
|
||||
end
|
||||
if retry_after > 0 then
|
||||
return {0, retry_after}
|
||||
end
|
||||
return {1, 0}
|
||||
`
|
||||
@@ -0,0 +1,111 @@
|
||||
package loginlimit_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/loginlimit"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/security/tlsconfig"
|
||||
)
|
||||
|
||||
func TestLimitIsSharedByInstances(t *testing.T) {
|
||||
rawURL := testCacheURL(t)
|
||||
tlsConfiguration := testCacheTLS(t)
|
||||
config := loginlimit.Config{AccountAttempts: 5, SourceAttempts: 20, Window: time.Minute}
|
||||
first, err := loginlimit.New(rawURL, config, tlsConfiguration)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { require.NoError(t, first.Close()) })
|
||||
second, err := loginlimit.New(rawURL, config, tlsConfiguration)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { require.NoError(t, second.Close()) })
|
||||
|
||||
username := "rate_" + uuid.NewString()
|
||||
limiters := []*loginlimit.Limiter{first, second}
|
||||
results := make(chan bool, 16)
|
||||
errors := make(chan error, 16)
|
||||
var group sync.WaitGroup
|
||||
for i := range 16 {
|
||||
group.Add(1)
|
||||
go func() {
|
||||
defer group.Done()
|
||||
allowed, retryAfter, err := limiters[i%len(limiters)].Allow(context.Background(), username, "192.0.2.10")
|
||||
if err != nil {
|
||||
errors <- err
|
||||
return
|
||||
}
|
||||
if !allowed && retryAfter <= 0 {
|
||||
errors <- loginlimit.ErrStore
|
||||
return
|
||||
}
|
||||
results <- allowed
|
||||
}()
|
||||
}
|
||||
group.Wait()
|
||||
close(results)
|
||||
close(errors)
|
||||
for err := range errors {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
var allowed int
|
||||
for result := range results {
|
||||
if result {
|
||||
allowed++
|
||||
}
|
||||
}
|
||||
require.Equal(t, int(config.AccountAttempts), allowed)
|
||||
}
|
||||
|
||||
func TestSourceLimitCoversDifferentAccounts(t *testing.T) {
|
||||
limiter, err := loginlimit.New(testCacheURL(t), loginlimit.Config{
|
||||
AccountAttempts: 10,
|
||||
SourceAttempts: 2,
|
||||
Window: time.Minute,
|
||||
}, testCacheTLS(t))
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { require.NoError(t, limiter.Close()) })
|
||||
|
||||
suffix := uuid.NewString()
|
||||
for i, expected := range []bool{true, true, false} {
|
||||
allowed, retryAfter, err := limiter.Allow(context.Background(), suffix+string(rune('a'+i)), "198.51.100.20")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, expected, allowed)
|
||||
if !allowed {
|
||||
require.Positive(t, retryAfter)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testCacheTLS(t *testing.T) *tls.Config {
|
||||
t.Helper()
|
||||
configuration, err := tlsconfig.LoadClient(tlsconfig.ClientConfig{
|
||||
CAPath: os.Getenv("TEST_CACHE_TLS_CA_PATH"),
|
||||
CertificatePath: os.Getenv("TEST_CACHE_TLS_CERTIFICATE_PATH"),
|
||||
PrivateKeyPath: os.Getenv("TEST_CACHE_TLS_PRIVATE_KEY_PATH"),
|
||||
ServerName: os.Getenv("TEST_CACHE_TLS_SERVER_NAME"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return configuration
|
||||
}
|
||||
|
||||
func testCacheURL(t *testing.T) string {
|
||||
t.Helper()
|
||||
rawURL := strings.TrimSpace(os.Getenv("TEST_CACHE_URL"))
|
||||
if rawURL != "" {
|
||||
return rawURL
|
||||
}
|
||||
path := strings.TrimSpace(os.Getenv("TEST_CACHE_URL_FILE"))
|
||||
if path == "" {
|
||||
t.Skip("set TEST_CACHE_URL or TEST_CACHE_URL_FILE to run integration tests")
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
require.NoError(t, err)
|
||||
return strings.TrimSpace(string(data))
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"math"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"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 {
|
||||
@@ -21,6 +25,15 @@ func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError
|
||||
if !ok {
|
||||
return unauthorized()
|
||||
}
|
||||
allowed, retryAfter, err := s.loginLimiter.Allow(r.Context(), username, loginSource(r))
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
if !allowed {
|
||||
retrySeconds := max(int64(1), int64(math.Ceil(retryAfter.Seconds())))
|
||||
w.Header().Set("Retry-After", strconv.FormatInt(retrySeconds, 10))
|
||||
return rateLimited()
|
||||
}
|
||||
credentials, err := s.userRepository.UserByUsername(r.Context(), username)
|
||||
if errors.Is(err, model.ErrNotFound) {
|
||||
if _, verifyErr := s.passwords.Verify(passwordValue, s.passwords.DummyHash()); verifyErr != nil {
|
||||
@@ -38,6 +51,9 @@ func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError
|
||||
if !verified {
|
||||
return unauthorized()
|
||||
}
|
||||
if rehashErr := s.rehashPassword(r.Context(), credentials, passwordValue); rehashErr != nil {
|
||||
return rehashErr
|
||||
}
|
||||
token, expiresAt, err := s.sessions.Create(r.Context(), credentials.ID, s.sessionTTL)
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
@@ -51,6 +67,57 @@ func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) rehashPassword(ctx context.Context, credentials model.UserCredentials, passwordValue string) *apiError {
|
||||
needsRehash, err := s.passwords.NeedsRehash(credentials.PasswordHash)
|
||||
if err != nil {
|
||||
return internalError()
|
||||
}
|
||||
if !needsRehash {
|
||||
return nil
|
||||
}
|
||||
passwordHash, err := s.passwords.Hash(passwordValue)
|
||||
if err != nil {
|
||||
return internalError()
|
||||
}
|
||||
updated, err := s.userRepository.UpdatePasswordHash(ctx, credentials.ID, credentials.PasswordHash, passwordHash)
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
if updated {
|
||||
return nil
|
||||
}
|
||||
current, err := s.userRepository.UserByUsername(ctx, credentials.Username)
|
||||
if errors.Is(err, model.ErrNotFound) {
|
||||
return unauthorized()
|
||||
}
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
verified, err := s.passwords.Verify(passwordValue, current.PasswordHash)
|
||||
if err != nil {
|
||||
return internalError()
|
||||
}
|
||||
if !verified {
|
||||
return unauthorized()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func loginSource(r *http.Request) string {
|
||||
forwarded := strings.Split(r.Header.Get("X-Forwarded-For"), ",")
|
||||
// Nginx appends the address it observed last, so preceding client-supplied entries are not trusted.
|
||||
if address := net.ParseIP(strings.TrimSpace(forwarded[len(forwarded)-1])); address != nil {
|
||||
return address.String()
|
||||
}
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err == nil {
|
||||
if address := net.ParseIP(host); address != nil {
|
||||
return address.String()
|
||||
}
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
func singleBasicAuth(r *http.Request) (string, string, bool) {
|
||||
if len(r.Header.Values("Authorization")) != 1 {
|
||||
return "", "", false
|
||||
|
||||
@@ -36,6 +36,10 @@ func unauthorized() *apiError {
|
||||
return &apiError{http.StatusUnauthorized, errorCodeUnauthorized, "authentication required"}
|
||||
}
|
||||
|
||||
func rateLimited() *apiError {
|
||||
return &apiError{http.StatusTooManyRequests, errorCodeRateLimited, "too many requests"}
|
||||
}
|
||||
|
||||
func notFound() *apiError {
|
||||
return &apiError{http.StatusNotFound, errorCodeNotFound, "resource not found"}
|
||||
}
|
||||
|
||||
@@ -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}$`)
|
||||
@@ -32,12 +32,15 @@ func (s *Server) readiness(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
if err := s.database.Ping(ctx); err != nil {
|
||||
s.logger.ErrorContext(ctx, "readiness dependency failed", "dependency", "postgres", "error", err)
|
||||
return unavailable()
|
||||
}
|
||||
if err := s.sessions.Ping(ctx); err != nil {
|
||||
s.logger.ErrorContext(ctx, "readiness dependency failed", "dependency", "valkey", "error", err)
|
||||
return unavailable()
|
||||
}
|
||||
if err := s.objects.Ping(ctx); err != nil {
|
||||
s.logger.ErrorContext(ctx, "readiness dependency failed", "dependency", "s3", "error", err)
|
||||
return unavailable()
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
|
||||
@@ -4,14 +4,15 @@ 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 {
|
||||
CreateUser(context.Context, string, string, string) (model.User, error)
|
||||
UserByID(context.Context, string) (model.User, error)
|
||||
UserByUsername(context.Context, string) (model.UserCredentials, error)
|
||||
UpdatePasswordHash(context.Context, string, string, string) (bool, error)
|
||||
}
|
||||
|
||||
type ChatRepository interface {
|
||||
@@ -45,5 +46,10 @@ type SessionStore interface {
|
||||
type PasswordService interface {
|
||||
Hash(string) (string, error)
|
||||
Verify(string, string) (bool, error)
|
||||
NeedsRehash(string) (bool, error)
|
||||
DummyHash() string
|
||||
}
|
||||
|
||||
type LoginLimiter interface {
|
||||
Allow(context.Context, string, string) (bool, time.Duration, error)
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
)
|
||||
|
||||
|
||||
@@ -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":
|
||||
|
||||
@@ -15,20 +15,21 @@ 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 {
|
||||
Users UserRepository
|
||||
Chats ChatRepository
|
||||
Messages MessageRepository
|
||||
Attachments AttachmentService
|
||||
Sessions SessionStore
|
||||
Passwords PasswordService
|
||||
Database HealthChecker
|
||||
Objects HealthChecker
|
||||
Meter metric.Meter
|
||||
Metrics http.Handler
|
||||
Users UserRepository
|
||||
Chats ChatRepository
|
||||
Messages MessageRepository
|
||||
Attachments AttachmentService
|
||||
Sessions SessionStore
|
||||
Passwords PasswordService
|
||||
LoginLimiter LoginLimiter
|
||||
Database HealthChecker
|
||||
Objects HealthChecker
|
||||
Meter metric.Meter
|
||||
Metrics http.Handler
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
@@ -46,6 +47,7 @@ type Server struct {
|
||||
attachments AttachmentService
|
||||
sessions SessionStore
|
||||
passwords PasswordService
|
||||
loginLimiter LoginLimiter
|
||||
database HealthChecker
|
||||
objects HealthChecker
|
||||
sessionTTL time.Duration
|
||||
@@ -77,7 +79,8 @@ func NewServer(
|
||||
userRepository: dependencies.Users, chatRepository: dependencies.Chats,
|
||||
messageRepository: dependencies.Messages,
|
||||
attachments: dependencies.Attachments, sessions: dependencies.Sessions,
|
||||
passwords: dependencies.Passwords, database: dependencies.Database, objects: dependencies.Objects,
|
||||
passwords: dependencies.Passwords, loginLimiter: dependencies.LoginLimiter,
|
||||
database: dependencies.Database, objects: dependencies.Objects,
|
||||
sessionTTL: config.SessionTTL, idempotencyTTL: config.IdempotencyTTL, requestTTL: config.RequestTTL,
|
||||
instanceID: config.InstanceID, logger: logger, swaggerPort: config.SwaggerPort,
|
||||
metrics: newMetrics(dependencies.Meter, dependencies.Metrics),
|
||||
@@ -94,6 +97,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")
|
||||
|
||||
@@ -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")
|
||||
@@ -34,14 +34,15 @@ func (s *MessengerSuite) SetupTest() {
|
||||
}
|
||||
|
||||
type messengerStoreStub struct {
|
||||
pingErr error
|
||||
userByID model.User
|
||||
userByIDErr error
|
||||
credentials model.UserCredentials
|
||||
credentialsErr error
|
||||
message model.Message
|
||||
messageReplay bool
|
||||
messageErr error
|
||||
pingErr error
|
||||
userByID model.User
|
||||
userByIDErr error
|
||||
credentials model.UserCredentials
|
||||
credentialsErr error
|
||||
message model.Message
|
||||
messageReplay bool
|
||||
messageErr error
|
||||
updatePasswordHash func(context.Context, string, string, string) (bool, error)
|
||||
}
|
||||
|
||||
func (s messengerStoreStub) Ping(context.Context) error { return s.pingErr }
|
||||
@@ -54,6 +55,12 @@ func (s messengerStoreStub) UserByID(context.Context, string) (model.User, error
|
||||
func (s messengerStoreStub) UserByUsername(context.Context, string) (model.UserCredentials, error) {
|
||||
return s.credentials, s.credentialsErr
|
||||
}
|
||||
func (s messengerStoreStub) UpdatePasswordHash(ctx context.Context, userID, previousHash, passwordHash string) (bool, error) {
|
||||
if s.updatePasswordHash == nil {
|
||||
return false, nil
|
||||
}
|
||||
return s.updatePasswordHash(ctx, userID, previousHash, passwordHash)
|
||||
}
|
||||
func (messengerStoreStub) CreateChat(context.Context, string, []string, string) (model.Chat, error) {
|
||||
return model.Chat{}, nil
|
||||
}
|
||||
@@ -109,15 +116,37 @@ func (s sessionStub) UserID(context.Context, string) (string, error) { return s.
|
||||
func (sessionStub) Delete(context.Context, string) error { return nil }
|
||||
|
||||
type passwordsStub struct {
|
||||
verified bool
|
||||
err error
|
||||
verified bool
|
||||
err error
|
||||
hash string
|
||||
hashErr error
|
||||
needsRehash bool
|
||||
needsRehashErr error
|
||||
}
|
||||
|
||||
func (passwordsStub) Hash(string) (string, error) { return "hash", nil }
|
||||
func (passwordsStub) DummyHash() string { return "hash" }
|
||||
func (s passwordsStub) Hash(string) (string, error) {
|
||||
if s.hash == "" {
|
||||
return "hash", s.hashErr
|
||||
}
|
||||
return s.hash, s.hashErr
|
||||
}
|
||||
func (passwordsStub) DummyHash() string { return "hash" }
|
||||
func (s passwordsStub) Verify(string, string) (bool, error) {
|
||||
return s.verified, s.err
|
||||
}
|
||||
func (s passwordsStub) NeedsRehash(string) (bool, error) {
|
||||
return s.needsRehash, s.needsRehashErr
|
||||
}
|
||||
|
||||
type loginLimiterStub struct {
|
||||
allowed bool
|
||||
retryAfter time.Duration
|
||||
err error
|
||||
}
|
||||
|
||||
func (s loginLimiterStub) Allow(context.Context, string, string) (bool, time.Duration, error) {
|
||||
return s.allowed, s.retryAfter, s.err
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestReadinessReturnsUnavailableForDependencyFailure() {
|
||||
t := s.T()
|
||||
@@ -135,7 +164,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 +172,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 {
|
||||
@@ -187,6 +239,48 @@ func (s *MessengerSuite) TestAuthenticationChallenges() {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestSessionCreationReturnsRateLimitWithRetryAfter() {
|
||||
server := s.serverWithLoginLimiter(
|
||||
messengerStoreStub{}, sessionStub{}, passwordsStub{},
|
||||
loginLimiterStub{retryAfter: 1500 * time.Millisecond},
|
||||
)
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
|
||||
request.SetBasicAuth("student", "T3st-password-123")
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
|
||||
s.Equal(http.StatusTooManyRequests, response.Code)
|
||||
s.Equal("2", response.Header().Get("Retry-After"))
|
||||
s.Contains(response.Body.String(), `"code":"rate_limited"`)
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestSessionCreationRehashesPasswordWithCompareAndSwap() {
|
||||
var updated []string
|
||||
store := messengerStoreStub{
|
||||
credentials: model.UserCredentials{User: model.User{ID: "user-id"}, PasswordHash: "old-hash"},
|
||||
updatePasswordHash: func(_ context.Context, userID, previousHash, passwordHash string) (bool, error) {
|
||||
updated = []string{userID, previousHash, passwordHash}
|
||||
return true, nil
|
||||
},
|
||||
}
|
||||
server := s.newTestServer(store, sessionStub{}, passwordsStub{
|
||||
verified: true, needsRehash: true, hash: "new-hash",
|
||||
})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
|
||||
request.SetBasicAuth("student", "T3st-password-123")
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
|
||||
s.Equal(http.StatusCreated, response.Code)
|
||||
s.Equal([]string{"user-id", "old-hash", "new-hash"}, updated)
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestLoginSourceUsesAddressAppendedByIngress() {
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
|
||||
request.Header.Set("X-Forwarded-For", "203.0.113.9, 198.51.100.7")
|
||||
s.Equal("198.51.100.7", loginSource(request))
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestAttachmentContentAuthenticatesBeforeVariantValidation() {
|
||||
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
|
||||
response := serveRequest(
|
||||
@@ -357,10 +451,34 @@ func (s *MessengerSuite) server(
|
||||
passwords PasswordService,
|
||||
objects objectStoreStub,
|
||||
attachments AttachmentService,
|
||||
) *Server {
|
||||
return s.serverWithDependencies(
|
||||
store, sessions, passwords, loginLimiterStub{allowed: true}, objects, attachments,
|
||||
)
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) serverWithLoginLimiter(
|
||||
store messengerStoreStub,
|
||||
sessions SessionStore,
|
||||
passwords PasswordService,
|
||||
limiter LoginLimiter,
|
||||
) *Server {
|
||||
return s.serverWithDependencies(
|
||||
store, sessions, passwords, limiter, objectStoreStub{}, attachmentServiceStub{},
|
||||
)
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) serverWithDependencies(
|
||||
store messengerStoreStub,
|
||||
sessions SessionStore,
|
||||
passwords PasswordService,
|
||||
limiter LoginLimiter,
|
||||
objects objectStoreStub,
|
||||
attachments AttachmentService,
|
||||
) *Server {
|
||||
return NewServer(s.logger, Dependencies{
|
||||
Users: store, Chats: store, Messages: store, Attachments: attachments,
|
||||
Sessions: sessions, Passwords: passwords, Database: store, Objects: objects,
|
||||
Sessions: sessions, Passwords: passwords, LoginLimiter: limiter, Database: store, Objects: objects,
|
||||
}, Config{
|
||||
SessionTTL: time.Hour, IdempotencyTTL: 24 * time.Hour, RequestTTL: time.Second,
|
||||
InstanceID: "test-instance", SwaggerPort: "8081",
|
||||
@@ -376,3 +494,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
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -18,7 +20,8 @@ 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"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/security/tlsconfig"
|
||||
)
|
||||
|
||||
var ErrNotFound = errors.New("object not found")
|
||||
@@ -30,6 +33,7 @@ type Config struct {
|
||||
AccessKey string
|
||||
SecretKey string
|
||||
UseTLS bool
|
||||
CAPath string
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
@@ -47,11 +51,27 @@ func New(config Config) (*Store, error) {
|
||||
if strings.TrimSpace(config.Bucket) == "" || config.Timeout <= 0 {
|
||||
return nil, errors.New("invalid object store configuration")
|
||||
}
|
||||
client, err := minio.New(endpoint, &minio.Options{
|
||||
options := &minio.Options{
|
||||
Creds: credentials.NewStaticV4(config.AccessKey, config.SecretKey, ""),
|
||||
Secure: config.UseTLS,
|
||||
Region: config.Region,
|
||||
})
|
||||
}
|
||||
if config.UseTLS {
|
||||
host, _, err := net.SplitHostPort(endpoint)
|
||||
if err != nil {
|
||||
return nil, errors.New("S3 endpoint must include a port")
|
||||
}
|
||||
tlsConfiguration, err := tlsconfig.LoadClient(tlsconfig.ClientConfig{
|
||||
CAPath: config.CAPath, ServerName: host,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load S3 TLS configuration: %w", err)
|
||||
}
|
||||
transport := http.DefaultTransport.(*http.Transport).Clone()
|
||||
transport.TLSClientConfig = tlsConfiguration
|
||||
options.Transport = transport
|
||||
}
|
||||
client, err := minio.New(endpoint, options)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create S3 client: %w", err)
|
||||
}
|
||||
@@ -79,12 +99,8 @@ func endpointHost(value string, useTLS bool) (string, error) {
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
exists, err := s.client.BucketExists(ctx, s.bucket)
|
||||
if err != nil {
|
||||
return fmt.Errorf("check S3 bucket: %w", err)
|
||||
}
|
||||
if !exists {
|
||||
return errors.New("S3 bucket does not exist")
|
||||
if _, err := s.client.GetBucketLocation(ctx, s.bucket); err != nil {
|
||||
return fmt.Errorf("check S3 bucket location: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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"
|
||||
)
|
||||
|
||||
|
||||
@@ -68,6 +68,14 @@ func (h *Hasher) Verify(value, encodedHash string) (bool, error) {
|
||||
return subtle.ConstantTimeCompare(actual, digest) == 1, nil
|
||||
}
|
||||
|
||||
func (h *Hasher) NeedsRehash(encodedHash string) (bool, error) {
|
||||
config, _, _, err := decode(encodedHash)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return config != h.config, nil
|
||||
}
|
||||
|
||||
func (h *Hasher) DummyHash() string {
|
||||
return h.dummyHash
|
||||
}
|
||||
|
||||
@@ -39,6 +39,61 @@ func (s *PasswordSuite) TestVerifyRejectsMalformedHash() {
|
||||
s.Error(err)
|
||||
}
|
||||
|
||||
func (s *PasswordSuite) TestNeedsRehashDetectsChangedParameters() {
|
||||
currentHash, err := s.hasher.Hash("T3st-password-123")
|
||||
s.Require().NoError(err)
|
||||
needsRehash, err := s.hasher.NeedsRehash(currentHash)
|
||||
s.Require().NoError(err)
|
||||
s.False(needsRehash)
|
||||
|
||||
legacyConfig := testConfig()
|
||||
legacyConfig.KeyLength = 16
|
||||
legacy, err := New(legacyConfig)
|
||||
s.Require().NoError(err)
|
||||
legacyHash, err := legacy.Hash("T3st-password-123")
|
||||
s.Require().NoError(err)
|
||||
needsRehash, err = s.hasher.NeedsRehash(legacyHash)
|
||||
s.Require().NoError(err)
|
||||
s.True(needsRehash)
|
||||
}
|
||||
|
||||
func testConfig() Config {
|
||||
return Config{MemoryKiB: 8 * 1024, Iterations: 1, Parallelism: 1, SaltLength: 16, KeyLength: 32}
|
||||
}
|
||||
|
||||
func BenchmarkArgon2idHash(b *testing.B) {
|
||||
hasher, err := New(productionConfig())
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for range b.N {
|
||||
if _, err := hasher.Hash("T3st-password-123"); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkArgon2idVerify(b *testing.B) {
|
||||
hasher, err := New(productionConfig())
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
hash, err := hasher.Hash("T3st-password-123")
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for range b.N {
|
||||
verified, err := hasher.Verify("T3st-password-123", hash)
|
||||
if err != nil || !verified {
|
||||
b.Fatalf("verify: result=%v error=%v", verified, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func productionConfig() Config {
|
||||
return Config{MemoryKiB: 64 * 1024, Iterations: 3, Parallelism: 2, SaltLength: 16, KeyLength: 32}
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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 = `
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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 {
|
||||
@@ -100,6 +100,19 @@ func (s *Store) UserByUsername(ctx context.Context, username string) (model.User
|
||||
return credentials, nil
|
||||
}
|
||||
|
||||
func (s *Store) UpdatePasswordHash(ctx context.Context, userID, previousHash, passwordHash string) (bool, error) {
|
||||
const query = `
|
||||
UPDATE users
|
||||
SET password_hash = $1
|
||||
WHERE id = $2 AND password_hash = $3`
|
||||
|
||||
result, err := s.pool.Exec(ctx, query, passwordHash, userID, previousHash)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("update password hash: %w", err)
|
||||
}
|
||||
return result.RowsAffected() == 1, nil
|
||||
}
|
||||
|
||||
func (s *Store) CreateChat(
|
||||
ctx context.Context,
|
||||
title string,
|
||||
|
||||
@@ -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 {
|
||||
@@ -77,6 +77,27 @@ func (s *PostgresSuite) TestConcurrentUsernameCreation() {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TestPasswordHashUpdateUsesCompareAndSwap() {
|
||||
username := uniqueUsername()
|
||||
user, err := s.store.CreateUser(context.Background(), username, "Password user", "old-hash")
|
||||
s.Require().NoError(err)
|
||||
|
||||
updated, err := s.store.UpdatePasswordHash(context.Background(), user.ID, "other-hash", "new-hash")
|
||||
s.Require().NoError(err)
|
||||
s.False(updated)
|
||||
|
||||
updated, err = s.store.UpdatePasswordHash(context.Background(), user.ID, "old-hash", "new-hash")
|
||||
s.Require().NoError(err)
|
||||
s.True(updated)
|
||||
updated, err = s.store.UpdatePasswordHash(context.Background(), user.ID, "old-hash", "stale-hash")
|
||||
s.Require().NoError(err)
|
||||
s.False(updated)
|
||||
|
||||
credentials, err := s.store.UserByUsername(context.Background(), username)
|
||||
s.Require().NoError(err)
|
||||
s.Equal("new-hash", credentials.PasswordHash)
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TestCreateChatRollsBackForUnknownMember() {
|
||||
t := s.T()
|
||||
pool := s.pool
|
||||
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
|
||||
)
|
||||
|
||||
type MetadataStore interface {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package mtlsproxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/security/tlsconfig"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
ListenAddress string
|
||||
TargetAddress string
|
||||
CAPath string
|
||||
CertificatePath string
|
||||
PrivateKeyPath string
|
||||
AllowedClientURI string
|
||||
ALPNProtocols []string
|
||||
DialTimeout time.Duration
|
||||
}
|
||||
|
||||
func Run(ctx context.Context, config Config) error {
|
||||
if config.ListenAddress == "" || config.TargetAddress == "" || config.DialTimeout <= 0 {
|
||||
return errors.New("invalid mTLS proxy configuration")
|
||||
}
|
||||
tlsConfiguration, err := tlsconfig.LoadServer(tlsconfig.ServerConfig{
|
||||
CAPath: config.CAPath, CertificatePath: config.CertificatePath,
|
||||
PrivateKeyPath: config.PrivateKeyPath, AllowedClientURI: config.AllowedClientURI,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tlsConfiguration.NextProtos = config.ALPNProtocols
|
||||
listener, err := net.Listen("tcp", config.ListenAddress)
|
||||
if err != nil {
|
||||
return fmt.Errorf("listen: %w", err)
|
||||
}
|
||||
defer listener.Close()
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
_ = listener.Close()
|
||||
}()
|
||||
|
||||
var connections sync.WaitGroup
|
||||
defer connections.Wait()
|
||||
for {
|
||||
connection, err := listener.Accept()
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("accept: %w", err)
|
||||
}
|
||||
connections.Add(1)
|
||||
go func() {
|
||||
defer connections.Done()
|
||||
serve(ctx, connection, config, tlsConfiguration)
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
func serve(ctx context.Context, connection net.Conn, config Config, tlsConfiguration *tls.Config) {
|
||||
client := tls.Server(connection, tlsConfiguration)
|
||||
defer client.Close()
|
||||
handshakeCtx, cancel := context.WithTimeout(ctx, config.DialTimeout)
|
||||
defer cancel()
|
||||
if err := client.HandshakeContext(handshakeCtx); err != nil {
|
||||
return
|
||||
}
|
||||
target, err := (&net.Dialer{Timeout: config.DialTimeout}).DialContext(ctx, "tcp", config.TargetAddress)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer target.Close()
|
||||
|
||||
result := make(chan struct{}, 2)
|
||||
copyConnection := func(destination, source net.Conn) {
|
||||
_, _ = io.Copy(destination, source)
|
||||
if writer, ok := destination.(interface{ CloseWrite() error }); ok {
|
||||
_ = writer.CloseWrite()
|
||||
}
|
||||
result <- struct{}{}
|
||||
}
|
||||
go copyConnection(target, client)
|
||||
go copyConnection(client, target)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-result:
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package tlsconfig
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type ClientConfig struct {
|
||||
CAPath string
|
||||
CertificatePath string
|
||||
PrivateKeyPath string
|
||||
ServerName string
|
||||
}
|
||||
|
||||
func LoadClient(config ClientConfig) (*tls.Config, error) {
|
||||
if strings.TrimSpace(config.ServerName) == "" {
|
||||
return nil, errors.New("TLS server name is required")
|
||||
}
|
||||
caPEM, err := os.ReadFile(config.CAPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read server CA: %w", err)
|
||||
}
|
||||
roots := x509.NewCertPool()
|
||||
if !roots.AppendCertsFromPEM(caPEM) {
|
||||
return nil, errors.New("server CA does not contain a certificate")
|
||||
}
|
||||
|
||||
var certificates []tls.Certificate
|
||||
if config.CertificatePath != "" || config.PrivateKeyPath != "" {
|
||||
if config.CertificatePath == "" || config.PrivateKeyPath == "" {
|
||||
return nil, errors.New("TLS client certificate and private key must be configured together")
|
||||
}
|
||||
certificate, err := tls.LoadX509KeyPair(config.CertificatePath, config.PrivateKeyPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load client certificate: %w", err)
|
||||
}
|
||||
certificates = []tls.Certificate{certificate}
|
||||
}
|
||||
|
||||
return &tls.Config{
|
||||
MinVersion: tls.VersionTLS13,
|
||||
RootCAs: roots,
|
||||
Certificates: certificates,
|
||||
ServerName: config.ServerName,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package tlsconfig
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"math/big"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestLoadClientLoadsTrustAndIdentity(t *testing.T) {
|
||||
caPath, certificatePath, keyPath := writeClientCertificate(t)
|
||||
|
||||
configuration, err := LoadClient(ClientConfig{
|
||||
CAPath: caPath, CertificatePath: certificatePath, PrivateKeyPath: keyPath, ServerName: "collector",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, uint16(0x0304), configuration.MinVersion)
|
||||
require.Equal(t, "collector", configuration.ServerName)
|
||||
require.Len(t, configuration.Certificates, 1)
|
||||
require.NotNil(t, configuration.RootCAs)
|
||||
}
|
||||
|
||||
func TestLoadClientRejectsPartialIdentity(t *testing.T) {
|
||||
caPath, certificatePath, _ := writeClientCertificate(t)
|
||||
|
||||
_, err := LoadClient(ClientConfig{CAPath: caPath, CertificatePath: certificatePath, ServerName: "collector"})
|
||||
require.ErrorContains(t, err, "configured together")
|
||||
}
|
||||
|
||||
func writeClientCertificate(t *testing.T) (string, string, string) {
|
||||
t.Helper()
|
||||
directory := t.TempDir()
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
require.NoError(t, err)
|
||||
template := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "test"},
|
||||
NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour),
|
||||
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
|
||||
BasicConstraintsValid: true, IsCA: true,
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
|
||||
require.NoError(t, err)
|
||||
certificate := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
|
||||
privateKey := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
|
||||
caPath := filepath.Join(directory, "ca.crt")
|
||||
certificatePath := filepath.Join(directory, "tls.crt")
|
||||
keyPath := filepath.Join(directory, "tls.key")
|
||||
require.NoError(t, os.WriteFile(caPath, certificate, 0o600))
|
||||
require.NoError(t, os.WriteFile(certificatePath, certificate, 0o600))
|
||||
require.NoError(t, os.WriteFile(keyPath, privateKey, 0o600))
|
||||
return caPath, certificatePath, keyPath
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
@@ -14,7 +15,7 @@ import (
|
||||
|
||||
"github.com/valkey-io/valkey-go"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -40,11 +41,15 @@ type Store struct {
|
||||
client valkey.Client
|
||||
}
|
||||
|
||||
func New(rawURL string) (*Store, error) {
|
||||
func New(rawURL string, tlsConfiguration ...*tls.Config) (*Store, error) {
|
||||
option, err := valkey.ParseURL(rawURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: parse Valkey URL: %w", ErrStore, err)
|
||||
}
|
||||
if len(tlsConfiguration) > 0 && tlsConfiguration[0] != nil {
|
||||
option.TLSConfig = tlsConfiguration[0].Clone()
|
||||
}
|
||||
option.DisableCache = true
|
||||
|
||||
client, err := valkey.NewClient(option)
|
||||
if err != nil {
|
||||
|
||||
@@ -11,7 +11,8 @@ import (
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/session"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/security/tlsconfig"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/session"
|
||||
)
|
||||
|
||||
type SessionSuite struct {
|
||||
@@ -34,7 +35,14 @@ func (s *SessionSuite) SetupSuite() {
|
||||
s.Require().NoError(err)
|
||||
rawURL = strings.TrimSpace(string(data))
|
||||
}
|
||||
store, err := session.New(rawURL)
|
||||
tlsConfiguration, err := tlsconfig.LoadClient(tlsconfig.ClientConfig{
|
||||
CAPath: os.Getenv("TEST_CACHE_TLS_CA_PATH"),
|
||||
CertificatePath: os.Getenv("TEST_CACHE_TLS_CERTIFICATE_PATH"),
|
||||
PrivateKeyPath: os.Getenv("TEST_CACHE_TLS_PRIVATE_KEY_PATH"),
|
||||
ServerName: os.Getenv("TEST_CACHE_TLS_SERVER_NAME"),
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
store, err := session.New(rawURL, tlsConfiguration)
|
||||
s.Require().NoError(err)
|
||||
s.store = store
|
||||
}
|
||||
|
||||
@@ -26,6 +26,9 @@ import (
|
||||
"go.opentelemetry.io/otel/sdk/resource"
|
||||
"go.opentelemetry.io/otel/sdk/trace"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.34.0"
|
||||
"google.golang.org/grpc/credentials"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/security/tlsconfig"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -34,13 +37,17 @@ const (
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
ServiceName string
|
||||
Version string
|
||||
InstanceID string
|
||||
Endpoint string
|
||||
Environment string
|
||||
Namespace string
|
||||
Insecure bool
|
||||
ServiceName string
|
||||
Version string
|
||||
InstanceID string
|
||||
Endpoint string
|
||||
Environment string
|
||||
Namespace string
|
||||
Insecure bool
|
||||
TLSCAPath string
|
||||
TLSCertificatePath string
|
||||
TLSPrivateKeyPath string
|
||||
TLSServerName string
|
||||
}
|
||||
|
||||
type Runtime struct {
|
||||
@@ -54,13 +61,17 @@ type Runtime struct {
|
||||
func ConfigFromEnvironment(serviceName, instanceID string) Config {
|
||||
resourceAttributes := parseResourceAttributes(os.Getenv("OTEL_RESOURCE_ATTRIBUTES"))
|
||||
return Config{
|
||||
ServiceName: serviceName,
|
||||
Version: firstValue(os.Getenv("SERVICE_VERSION"), resourceAttributes["service.version"], "dev"),
|
||||
InstanceID: instanceID,
|
||||
Endpoint: strings.TrimSpace(os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT")),
|
||||
Environment: firstValue(os.Getenv("DEPLOYMENT_ENVIRONMENT"), resourceAttributes["deployment.environment.name"], defaultEnvironment),
|
||||
Namespace: firstValue(os.Getenv("SERVICE_NAMESPACE"), resourceAttributes["service.namespace"], defaultNamespace),
|
||||
Insecure: true,
|
||||
ServiceName: serviceName,
|
||||
Version: firstValue(os.Getenv("SERVICE_VERSION"), resourceAttributes["service.version"], "dev"),
|
||||
InstanceID: instanceID,
|
||||
Endpoint: strings.TrimSpace(os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT")),
|
||||
Environment: firstValue(os.Getenv("DEPLOYMENT_ENVIRONMENT"), resourceAttributes["deployment.environment.name"], defaultEnvironment),
|
||||
Namespace: firstValue(os.Getenv("SERVICE_NAMESPACE"), resourceAttributes["service.namespace"], defaultNamespace),
|
||||
Insecure: strings.EqualFold(strings.TrimSpace(os.Getenv("OTEL_EXPORTER_OTLP_INSECURE")), "true"),
|
||||
TLSCAPath: strings.TrimSpace(os.Getenv("OTEL_EXPORTER_OTLP_CERTIFICATE")),
|
||||
TLSCertificatePath: strings.TrimSpace(os.Getenv("OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE")),
|
||||
TLSPrivateKeyPath: strings.TrimSpace(os.Getenv("OTEL_EXPORTER_OTLP_CLIENT_KEY")),
|
||||
TLSServerName: strings.TrimSpace(os.Getenv("OTEL_EXPORTER_OTLP_SERVER_NAME")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -187,6 +198,12 @@ func newTraceExporter(ctx context.Context, config Config) (trace.SpanExporter, e
|
||||
}
|
||||
if config.Insecure {
|
||||
options = append(options, otlptracegrpc.WithInsecure())
|
||||
} else {
|
||||
transportCredentials, err := telemetryCredentials(config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
options = append(options, otlptracegrpc.WithTLSCredentials(transportCredentials))
|
||||
}
|
||||
exporter, err := otlptracegrpc.New(ctx, options...)
|
||||
if err != nil {
|
||||
@@ -204,6 +221,12 @@ func newMetricExporter(ctx context.Context, config Config) (*otlpmetricgrpc.Expo
|
||||
}
|
||||
if config.Insecure {
|
||||
options = append(options, otlpmetricgrpc.WithInsecure())
|
||||
} else {
|
||||
transportCredentials, err := telemetryCredentials(config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
options = append(options, otlpmetricgrpc.WithTLSCredentials(transportCredentials))
|
||||
}
|
||||
exporter, err := otlpmetricgrpc.New(ctx, options...)
|
||||
if err != nil {
|
||||
@@ -221,6 +244,12 @@ func newLogExporter(ctx context.Context, config Config) (*otlploggrpc.Exporter,
|
||||
}
|
||||
if config.Insecure {
|
||||
options = append(options, otlploggrpc.WithInsecure())
|
||||
} else {
|
||||
transportCredentials, err := telemetryCredentials(config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
options = append(options, otlploggrpc.WithTLSCredentials(transportCredentials))
|
||||
}
|
||||
exporter, err := otlploggrpc.New(ctx, options...)
|
||||
if err != nil {
|
||||
@@ -229,6 +258,17 @@ func newLogExporter(ctx context.Context, config Config) (*otlploggrpc.Exporter,
|
||||
return exporter, nil
|
||||
}
|
||||
|
||||
func telemetryCredentials(config Config) (credentials.TransportCredentials, error) {
|
||||
tlsConfiguration, err := tlsconfig.LoadClient(tlsconfig.ClientConfig{
|
||||
CAPath: config.TLSCAPath, CertificatePath: config.TLSCertificatePath,
|
||||
PrivateKeyPath: config.TLSPrivateKeyPath, ServerName: config.TLSServerName,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load OTLP TLS configuration: %w", err)
|
||||
}
|
||||
return credentials.NewTLS(tlsConfiguration), nil
|
||||
}
|
||||
|
||||
func (r *Runtime) Logger() *slog.Logger {
|
||||
return r.logger
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user