feat: secure service connections and login
This commit is contained in:
@@ -2,6 +2,8 @@ package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
@@ -17,10 +19,11 @@ import (
|
||||
)
|
||||
|
||||
type apiClient struct {
|
||||
baseURL string
|
||||
client *http.Client
|
||||
token string
|
||||
userID string
|
||||
baseURL string
|
||||
client *http.Client
|
||||
transport *http.Transport
|
||||
token string
|
||||
userID string
|
||||
}
|
||||
|
||||
func main() {
|
||||
@@ -32,9 +35,23 @@ func main() {
|
||||
}
|
||||
|
||||
func run() error {
|
||||
baseURL := flag.String("base-url", "http://localhost:8080", "API base URL")
|
||||
baseURL := flag.String("base-url", "https://localhost:8443", "API base URL")
|
||||
caFile := flag.String("ca-file", ".runtime/security/public-ca/ca.crt", "trusted CA certificate")
|
||||
flag.Parse()
|
||||
client := &apiClient{baseURL: *baseURL, client: &http.Client{Timeout: 10 * time.Second}}
|
||||
caPEM, err := os.ReadFile(*caFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read trusted CA: %w", err)
|
||||
}
|
||||
roots := x509.NewCertPool()
|
||||
if !roots.AppendCertsFromPEM(caPEM) {
|
||||
return fmt.Errorf("trusted CA does not contain a certificate")
|
||||
}
|
||||
transport := &http.Transport{TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12, RootCAs: roots}}
|
||||
defer transport.CloseIdleConnections()
|
||||
client := &apiClient{
|
||||
baseURL: *baseURL, client: &http.Client{Transport: transport, Timeout: 10 * time.Second},
|
||||
transport: transport,
|
||||
}
|
||||
if err := client.registerAndLogin(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -130,7 +147,9 @@ func (c *apiClient) verifyConcurrentIdempotency() error {
|
||||
instances = make(map[string]struct{})
|
||||
messageID string
|
||||
)
|
||||
transport := &http.Transport{DisableKeepAlives: true, MaxConnsPerHost: workers}
|
||||
transport := c.transport.Clone()
|
||||
transport.DisableKeepAlives = true
|
||||
transport.MaxConnsPerHost = workers
|
||||
client := &http.Client{Transport: transport, Timeout: 10 * time.Second}
|
||||
defer transport.CloseIdleConnections()
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ package main
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -12,16 +14,18 @@ import (
|
||||
_ "image/jpeg"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
|
||||
)
|
||||
|
||||
type apiState struct {
|
||||
BaseURL string `json:"base_url"`
|
||||
CAFile string `json:"ca_file"`
|
||||
Token string `json:"token"`
|
||||
AttachmentID string `json:"attachment_id"`
|
||||
}
|
||||
@@ -41,11 +45,15 @@ type apiChat struct {
|
||||
func runAPIProduce(arguments []string, output io.Writer) error {
|
||||
flags := flag.NewFlagSet("api-produce", flag.ContinueOnError)
|
||||
flags.SetOutput(io.Discard)
|
||||
baseURL := flags.String("base-url", "http://nginx:8080", "messenger base URL")
|
||||
baseURL := flags.String("base-url", "https://nginx:8443", "messenger base URL")
|
||||
caFile := flags.String("ca-file", "/run/security/public-ca/ca.crt", "trusted CA certificate")
|
||||
if err := flags.Parse(arguments); err != nil || flags.NArg() != 0 {
|
||||
return errors.New("usage: lab5experiment api-produce [-base-url URL]")
|
||||
return errors.New("usage: lab5experiment api-produce [-base-url URL] [-ca-file PATH]")
|
||||
}
|
||||
client, err := newAPIClient(*caFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
suffix := strings.ReplaceAll(uuid.NewString(), "-", "")[:12]
|
||||
password := "Lab5-" + uuid.NewString()
|
||||
owner, err := registerAPIUser(client, *baseURL, "qa_"+suffix, password)
|
||||
@@ -102,7 +110,9 @@ func runAPIProduce(arguments []string, output io.Writer) error {
|
||||
if response.StatusCode != http.StatusConflict {
|
||||
return fmt.Errorf("queued content returned %d, expected 409", response.StatusCode)
|
||||
}
|
||||
return json.NewEncoder(output).Encode(apiState{BaseURL: *baseURL, Token: token, AttachmentID: attachment.ID})
|
||||
return json.NewEncoder(output).Encode(apiState{
|
||||
BaseURL: *baseURL, CAFile: *caFile, Token: token, AttachmentID: attachment.ID,
|
||||
})
|
||||
}
|
||||
|
||||
func runAPIVerify(arguments []string, input io.Reader, output io.Writer) error {
|
||||
@@ -116,7 +126,10 @@ func runAPIVerify(arguments []string, input io.Reader, output io.Writer) error {
|
||||
if err := json.NewDecoder(input).Decode(&state); err != nil {
|
||||
return fmt.Errorf("decode API scenario state: %w", err)
|
||||
}
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
client, err := newAPIClient(state.CAFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), *waitTimeout)
|
||||
defer cancel()
|
||||
var attachment model.Attachment
|
||||
@@ -176,6 +189,19 @@ func runAPIVerify(arguments []string, input io.Reader, output io.Writer) error {
|
||||
})
|
||||
}
|
||||
|
||||
func newAPIClient(caFile string) (*http.Client, error) {
|
||||
caPEM, err := os.ReadFile(caFile)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read trusted CA: %w", err)
|
||||
}
|
||||
roots := x509.NewCertPool()
|
||||
if !roots.AppendCertsFromPEM(caPEM) {
|
||||
return nil, errors.New("trusted CA does not contain a certificate")
|
||||
}
|
||||
transport := &http.Transport{TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12, RootCAs: roots}}
|
||||
return &http.Client{Transport: transport, Timeout: 10 * time.Second}, nil
|
||||
}
|
||||
|
||||
func registerAPIUser(client *http.Client, baseURL, username, password string) (apiUser, error) {
|
||||
body, err := json.Marshal(map[string]string{
|
||||
"username": username, "display_name": username, "password": password,
|
||||
|
||||
+20
-10
@@ -21,15 +21,16 @@ import (
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/broker/redisstream"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/config"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/database"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment/transform"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment/worker"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/objectstore"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/outbox"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/postgres"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/broker/redisstream"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/config"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/database"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment/transform"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment/worker"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/objectstore"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/outbox"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/postgres"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/security/tlsconfig"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -132,7 +133,7 @@ func newExperiment(ctx context.Context) (*experiment, func(), 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 {
|
||||
pool.Close()
|
||||
@@ -143,6 +144,15 @@ func newExperiment(ctx context.Context) (*experiment, func(), error) {
|
||||
pool.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
brokerTLS, err := tlsconfig.LoadClient(tlsconfig.ClientConfig{
|
||||
CAPath: settings.BrokerTLS.CAPath, CertificatePath: settings.BrokerTLS.CertificatePath,
|
||||
PrivateKeyPath: settings.BrokerTLS.PrivateKeyPath, ServerName: settings.BrokerTLS.ServerName,
|
||||
})
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
redisOptions.TLSConfig = brokerTLS
|
||||
client := redis.NewClient(redisOptions)
|
||||
if err := client.Ping(ctx).Err(); err != nil {
|
||||
pool.Close()
|
||||
|
||||
@@ -5,8 +5,8 @@ import (
|
||||
"log/slog"
|
||||
"os"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/bootstrap"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/logger"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/bootstrap"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/logger"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/security/mtlsproxy"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := run(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run() error {
|
||||
config := mtlsproxy.Config{
|
||||
ListenAddress: required("PROXY_LISTEN_ADDRESS"), TargetAddress: required("PROXY_TARGET_ADDRESS"),
|
||||
CAPath: required("PROXY_TLS_CA_PATH"), CertificatePath: required("PROXY_TLS_CERTIFICATE_PATH"),
|
||||
PrivateKeyPath: required("PROXY_TLS_PRIVATE_KEY_PATH"), AllowedClientURI: required("PROXY_ALLOWED_CLIENT_URI"),
|
||||
ALPNProtocols: strings.Split(required("PROXY_ALPN_PROTOCOLS"), ","),
|
||||
DialTimeout: 5 * time.Second,
|
||||
}
|
||||
if config.ListenAddress == "" || config.TargetAddress == "" || config.CAPath == "" ||
|
||||
config.CertificatePath == "" || config.PrivateKeyPath == "" || config.AllowedClientURI == "" ||
|
||||
len(config.ALPNProtocols) == 0 || config.ALPNProtocols[0] == "" {
|
||||
return errors.New("mTLS proxy environment is incomplete")
|
||||
}
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
return mtlsproxy.Run(ctx, config)
|
||||
}
|
||||
|
||||
func required(name string) string {
|
||||
return os.Getenv(name)
|
||||
}
|
||||
+32
-1
@@ -1,9 +1,21 @@
|
||||
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
|
||||
@@ -26,11 +38,19 @@ database:
|
||||
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
|
||||
use_tls: true
|
||||
ca_path: /run/security/internal-ca/ca.crt
|
||||
timeout: 5s
|
||||
|
||||
attachments:
|
||||
@@ -43,6 +63,11 @@ 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
|
||||
@@ -74,3 +99,9 @@ worker:
|
||||
|
||||
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
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
module gitea.privcloud.tech/dizi/mtusi2026lab6
|
||||
module gitea.privcloud.tech/dizi/mtusi2026lab7
|
||||
|
||||
go 1.26.0
|
||||
|
||||
toolchain go1.26.10
|
||||
|
||||
require (
|
||||
github.com/deepteams/webp v1.2.8
|
||||
github.com/google/uuid v1.6.0
|
||||
@@ -12,20 +14,21 @@ require (
|
||||
github.com/spf13/viper v1.21.0
|
||||
github.com/stretchr/testify v1.11.1
|
||||
github.com/valkey-io/valkey-go v1.0.78
|
||||
go.opentelemetry.io/contrib/bridges/otelslog v0.13.0
|
||||
go.opentelemetry.io/contrib/bridges/otelslog v0.20.0
|
||||
go.opentelemetry.io/contrib/instrumentation/runtime v0.60.0
|
||||
go.opentelemetry.io/otel v1.38.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.14.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.38.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.38.0
|
||||
go.opentelemetry.io/otel v1.45.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.21.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.45.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0
|
||||
go.opentelemetry.io/otel/exporters/prometheus v0.60.0
|
||||
go.opentelemetry.io/otel/metric v1.38.0
|
||||
go.opentelemetry.io/otel/sdk v1.38.0
|
||||
go.opentelemetry.io/otel/sdk/log v0.14.0
|
||||
go.opentelemetry.io/otel/sdk/metric v1.38.0
|
||||
go.opentelemetry.io/otel/trace v1.38.0
|
||||
go.opentelemetry.io/otel/metric v1.45.0
|
||||
go.opentelemetry.io/otel/sdk v1.45.0
|
||||
go.opentelemetry.io/otel/sdk/log v0.21.0
|
||||
go.opentelemetry.io/otel/sdk/metric v1.45.0
|
||||
go.opentelemetry.io/otel/trace v1.45.0
|
||||
golang.org/x/crypto v0.57.0
|
||||
golang.org/x/sync v0.23.0
|
||||
google.golang.org/grpc v1.83.2
|
||||
)
|
||||
|
||||
require (
|
||||
@@ -37,15 +40,15 @@ require (
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||
github.com/go-ini/ini v1.67.0 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/go-logr/logr v1.4.4 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
|
||||
github.com/grafana/regexp v0.0.0-20240518133315-a468a5bfb3bc // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/klauspost/compress v1.18.2 // indirect
|
||||
github.com/klauspost/compress v1.18.7 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.11 // indirect
|
||||
github.com/klauspost/crc32 v1.3.0 // indirect
|
||||
github.com/minio/crc64nvme v1.1.1 // indirect
|
||||
@@ -66,18 +69,17 @@ require (
|
||||
github.com/spf13/pflag v1.0.10 // indirect
|
||||
github.com/subosito/gotenv v1.6.0 // indirect
|
||||
github.com/tinylib/msgp v1.6.1 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.1.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0 // indirect
|
||||
go.opentelemetry.io/otel/log v0.14.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.7.1 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0 // indirect
|
||||
go.opentelemetry.io/otel/log v0.21.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.11.0 // indirect
|
||||
go.yaml.in/yaml/v2 v2.4.2 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
golang.org/x/net v0.58.0 // indirect
|
||||
golang.org/x/net v0.60.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250825161204-c5933d9347a5 // indirect
|
||||
google.golang.org/grpc v1.75.0 // indirect
|
||||
google.golang.org/protobuf v1.36.8 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
||||
@@ -24,8 +24,8 @@ github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8
|
||||
github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A=
|
||||
github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
|
||||
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
|
||||
@@ -38,8 +38,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/grafana/regexp v0.0.0-20240518133315-a468a5bfb3bc h1:GN2Lv3MGO7AS6PrRoT6yV5+wkrOpcszoIsO4+4ds248=
|
||||
github.com/grafana/regexp v0.0.0-20240518133315-a468a5bfb3bc/go.mod h1:+JKpmjMGhpgPL+rXZ5nsZieVzvarn86asRlBg4uNGnk=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 h1:8Tjv8EJ+pM1xP8mK6egEbD1OgnVTyacbefKhmbLhIhU=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2/go.mod h1:pkJQ2tZHJ0aFOVEEot6oZmaVEZcRme73eIFmhiVuRWs=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF28c5ZQfqCBQ5g2xfk=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
@@ -48,8 +48,8 @@ github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg=
|
||||
github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/klauspost/compress v1.18.2 h1:iiPHWW0YrcFgpBYhsA6D1+fqHssJscY/Tm/y2Uqnapk=
|
||||
github.com/klauspost/compress v1.18.2/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
|
||||
github.com/klauspost/compress v1.18.7 h1:aUyZsS4kH3QTKurYhAOwAHxllVPnOthb3vPfnF1Ehjw=
|
||||
github.com/klauspost/compress v1.18.7/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.11 h1:0OwqZRYI2rFrjS4kvkDnqJkKHdHaRnCm68/DY4OxRzU=
|
||||
github.com/klauspost/cpuid/v2 v2.2.11/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
@@ -89,8 +89,8 @@ github.com/prometheus/procfs v0.17.0 h1:FuLQ+05u4ZI+SS/w9+BWEM2TXiHKsUQ9TADiRH7D
|
||||
github.com/prometheus/procfs v0.17.0/go.mod h1:oPQLaDAMRbA+u8H5Pbfq+dl3VDAvHxMUOVhe0wYB2zw=
|
||||
github.com/redis/go-redis/v9 v9.17.2 h1:P2EGsA4qVIM3Pp+aPocCJ7DguDHhqrXNhVcEp4ViluI=
|
||||
github.com/redis/go-redis/v9 v9.17.2/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370=
|
||||
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
|
||||
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
|
||||
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
|
||||
github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc=
|
||||
@@ -116,40 +116,42 @@ github.com/tinylib/msgp v1.6.1 h1:ESRv8eL3u+DNHUoSAAQRE50Hm162zqAnBoGv9PzScPY=
|
||||
github.com/tinylib/msgp v1.6.1/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA=
|
||||
github.com/valkey-io/valkey-go v1.0.78 h1:1Ce8hRaaNXpKfqmqZQRhnbVh1eW8MGR873pdXVvE4y8=
|
||||
github.com/valkey-io/valkey-go v1.0.78/go.mod h1:gvC/r2m3eW4Hbj0YnjogTzNtFdPSM/D+NCqen+5OABM=
|
||||
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
|
||||
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
|
||||
go.opentelemetry.io/contrib/bridges/otelslog v0.13.0 h1:bwnLpizECbPr1RrQ27waeY2SPIPeccCx/xLuoYADZ9s=
|
||||
go.opentelemetry.io/contrib/bridges/otelslog v0.13.0/go.mod h1:3nWlOiiqA9UtUnrcNk82mYasNxD8ehOspL0gOfEo6Y4=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/bridges/otelslog v0.20.0 h1:oEl2Pw/i4OQwhAuda2pAHFAcOMivA+Xa+iTccBfab/g=
|
||||
go.opentelemetry.io/contrib/bridges/otelslog v0.20.0/go.mod h1:yMSQaiiq5dpfrSJCYLBcqFeJkFFI67seT4ngvx6jfVo=
|
||||
go.opentelemetry.io/contrib/instrumentation/runtime v0.60.0 h1:0NgN/3SYkqYJ9NBlDfl/2lzVlwos/YQLvi8sUrzJRBE=
|
||||
go.opentelemetry.io/contrib/instrumentation/runtime v0.60.0/go.mod h1:oxpUfhTkhgQaYIjtBt3T3w135dLoxq//qo3WPlPIKkE=
|
||||
go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8=
|
||||
go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.14.0 h1:OMqPldHt79PqWKOMYIAQs3CxAi7RLgPxwfFSwr4ZxtM=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.14.0/go.mod h1:1biG4qiqTxKiUCtoWDPpL3fB3KxVwCiGw81j3nKMuHE=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.38.0 h1:vl9obrcoWVKp/lwl8tRE33853I8Xru9HFbw/skNeLs8=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.38.0/go.mod h1:GAXRxmLJcVM3u22IjTg74zWBrRCKq8BnOqUVLodpcpw=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0 h1:GqRJVj7UmLjCVyVJ3ZFLdPRmhDUp2zFmQe3RHIOsw24=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0/go.mod h1:ri3aaHSmCTVYu2AWv44YMauwAQc0aqI9gHKIcSbI1pU=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.38.0 h1:lwI4Dc5leUqENgGuQImwLo4WnuXFPetmPpkLi2IrX54=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.38.0/go.mod h1:Kz/oCE7z5wuyhPxsXDuaPteSWqjSBD5YaSdbxZYGbGk=
|
||||
go.opentelemetry.io/otel v1.45.0 h1:pdrWmLHofpubmArBv1LgFSv1Z0Ie/ppdZzu+kUN5EeU=
|
||||
go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.21.0 h1:WseeVYf5dJZTsyPiyW5L14k5qsSibqXAMTSiFEDiWr0=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.21.0/go.mod h1:SiLZnQS6Qk2eCpvr2CH/XMAOa64TWGXxEZJZCpD2Lmc=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.45.0 h1:klTViGcsvLCd1xN3rZzfZ12NslC/OimbmR+k+A006RI=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.45.0/go.mod h1:jRsK04CWmXuY8A0O+wMpSf+t90RHZ53o5Qmxn2PQPfk=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0 h1:QRefszxJmfPdjXUUm3j6iDzY03mTPXMjqErFqQ67vUg=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0/go.mod h1:Tiz03lTBVBrm7eWZBOidzEaYaJa8tjwGUGv6d8mlTyk=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0 h1:fG5MCxGz8+2VtrN/WgqSpJFctVz24gpxj8CxkKmc8Ww=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0/go.mod h1:BmAYTn+3ysbRe+IU2msxmf5Rx3g6DHvex+tWI3LdhYI=
|
||||
go.opentelemetry.io/otel/exporters/prometheus v0.60.0 h1:cGtQxGvZbnrWdC2GyjZi0PDKVSLWP/Jocix3QWfXtbo=
|
||||
go.opentelemetry.io/otel/exporters/prometheus v0.60.0/go.mod h1:hkd1EekxNo69PTV4OWFGZcKQiIqg0RfuWExcPKFvepk=
|
||||
go.opentelemetry.io/otel/log v0.14.0 h1:2rzJ+pOAZ8qmZ3DDHg73NEKzSZkhkGIua9gXtxNGgrM=
|
||||
go.opentelemetry.io/otel/log v0.14.0/go.mod h1:5jRG92fEAgx0SU/vFPxmJvhIuDU9E1SUnEQrMlJpOno=
|
||||
go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA=
|
||||
go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI=
|
||||
go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E=
|
||||
go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg=
|
||||
go.opentelemetry.io/otel/sdk/log v0.14.0 h1:JU/U3O7N6fsAXj0+CXz21Czg532dW2V4gG1HE/e8Zrg=
|
||||
go.opentelemetry.io/otel/sdk/log v0.14.0/go.mod h1:imQvII+0ZylXfKU7/wtOND8Hn4OpT3YUoIgqJVksUkM=
|
||||
go.opentelemetry.io/otel/sdk/log/logtest v0.14.0 h1:Ijbtz+JKXl8T2MngiwqBlPaHqc4YCaP/i13Qrow6gAM=
|
||||
go.opentelemetry.io/otel/sdk/log/logtest v0.14.0/go.mod h1:dCU8aEL6q+L9cYTqcVOk8rM9Tp8WdnHOPLiBgp0SGOA=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA=
|
||||
go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE=
|
||||
go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs=
|
||||
go.opentelemetry.io/proto/otlp v1.7.1 h1:gTOMpGDb0WTBOP8JaO72iL3auEZhVmAQg4ipjOVAtj4=
|
||||
go.opentelemetry.io/proto/otlp v1.7.1/go.mod h1:b2rVh6rfI/s2pHWNlB7ILJcRALpcNDzKhACevjI+ZnE=
|
||||
go.opentelemetry.io/otel/log v0.21.0 h1:SLsVDGmtyBrdw8/a2Z0bOIxou/+bN4z56GebH7T0LvA=
|
||||
go.opentelemetry.io/otel/log v0.21.0/go.mod h1:iReetQrZL9Wyg84cCkOoCmqDHS5RCFfyxC7J+r8fn8g=
|
||||
go.opentelemetry.io/otel/metric v1.45.0 h1:7Eg1uH7CJ5cXv9is6tnBe1FI6rj1nwUdbFypRm3br/M=
|
||||
go.opentelemetry.io/otel/metric v1.45.0/go.mod h1:HAPbm1nd3p1PmFH7v2dR+6BjXxw+Lq4a2+pndMAm08s=
|
||||
go.opentelemetry.io/otel/metric/x v0.67.0 h1:PcicCNZFkZ4bXfSooXdo3WN7RBOVOtjVdo1wD358Uns=
|
||||
go.opentelemetry.io/otel/metric/x v0.67.0/go.mod h1:FBjCWZe6wgcqxcMtjdGiClDKXb2YxxXii0CXftE4QtI=
|
||||
go.opentelemetry.io/otel/sdk v1.45.0 h1:4VVSMgQ83dUgW2aoX5f6JgLvHwIvzcuLnF9lUdCSpCw=
|
||||
go.opentelemetry.io/otel/sdk v1.45.0/go.mod h1:Sr40LgXV7DsKMMJMKOhUWOgMWTfAaqvm2kF0g7ilwuA=
|
||||
go.opentelemetry.io/otel/sdk/log v0.21.0 h1:QsE7XSR0ktQdKmRKGnR+f1ObGF32WG+7MER/P9KgmYc=
|
||||
go.opentelemetry.io/otel/sdk/log v0.21.0/go.mod h1:m9mApjCoD2/1QuKCAptjv+BrG9WKOvQLVdNx+iBldTo=
|
||||
go.opentelemetry.io/otel/sdk/log/logtest v0.21.0 h1:X+JBBgKlswCGYsmgL0CnoUUtlE//VB345c84jYAYkdQ=
|
||||
go.opentelemetry.io/otel/sdk/log/logtest v0.21.0/go.mod h1:HD1575K8e6sIFBBDd5tZB3t9DlMytWXq9FuR+Y4rfjE=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.45.0 h1:oVFszMfyj1Am6s24Vtc7wBb8BKLcwepJjNEYILuiE3o=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.45.0/go.mod h1:vUWUxDZvu1WVRj8JA8S0AdhsPrZoDpA2DdZauIh4mDA=
|
||||
go.opentelemetry.io/otel/trace v1.45.0 h1:l/mP6Uv7oNO7/TblbhpbgMidxhq1uO/rPsikOyVhxag=
|
||||
go.opentelemetry.io/otel/trace v1.45.0/go.mod h1:qoJJA2xNMnxRrdISU/kLtfUH2wNeQbiv+jhs/CxI8bc=
|
||||
go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk=
|
||||
go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI=
|
||||
@@ -158,24 +160,24 @@ go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
|
||||
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
|
||||
golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU=
|
||||
golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
||||
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5 h1:BIRfGDEjiHRrk0QKZe3Xv2ieMhtgRGeLcZQ0mIVn4EY=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5/go.mod h1:j3QtIyytwqGr1JUDtYXwtMXWPKsEa5LtzIFN1Wn5WvE=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250825161204-c5933d9347a5 h1:eaY8u2EuxbRv7c3NiGK0/NedzVsCcV6hDuU5qPX5EGE=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250825161204-c5933d9347a5/go.mod h1:M4/wBTSeyLxupu3W3tJtOgB14jILAS/XWPSSa3TAlJc=
|
||||
google.golang.org/grpc v1.75.0 h1:+TW+dqTd2Biwe6KKfhE5JpiYIBWq865PhKGSXiivqt4=
|
||||
google.golang.org/grpc v1.75.0/go.mod h1:JtPAzKiq4v1xcAB2hydNlWI2RnF85XXcV0mhKXr2ecQ=
|
||||
google.golang.org/protobuf v1.36.8 h1:xHScyCOEuuwZEc6UtSOvPbAT4zRh0xcNRYekJwfqyMc=
|
||||
google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
|
||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d h1:FarXi840EJWSHYTN3ERkADbPWjl307+FGrA22KAVjjc=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d/go.mod h1:K/+WGbmBY7aNW1HDw1fJnKYo10i0DkAX6pows00dLig=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d h1:IL4hdHzcUv2l/gcg98/Rj3FbtE6axwqslOW8SW0C+S0=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU=
|
||||
google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
|
||||
@@ -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