242 lines
8.2 KiB
Go
242 lines
8.2 KiB
Go
// Package platform собирает клиентов зависимостей lab7 по trust matrix:
|
||
//
|
||
// PostgreSQL TLS verify-full (CA стенда, имя postgres), роль и пароль сервиса из OpenBao;
|
||
// пароль берётся при КАЖДОМ новом соединении (BeforeConnect) — ротация
|
||
// не требует рестарта, старые соединения закрываются по lifetime/отзыву
|
||
// Redis TLS (проверка сервера), ACL-пользователь сервиса из OpenBao (CredentialsProvider)
|
||
// S3 (MinIO) TLS (CA стенда), ключ сервиса из OpenBao; при смене версии секрета minio-go
|
||
// перечитывает ключ (credentials.Provider.IsExpired)
|
||
// RabbitMQ TLS + mTLS, SASL EXTERNAL: пользователь = CN клиентского сертификата
|
||
// OpenBao TLS + cert auth тем же клиентским сертификатом сервиса
|
||
//
|
||
// Без BAO_ADDR (локальные тесты) — прежнее поведение lab6: URL и ключи из файлов.
|
||
package platform
|
||
|
||
import (
|
||
"context"
|
||
"crypto/tls"
|
||
"crypto/x509"
|
||
"fmt"
|
||
"io"
|
||
"log/slog"
|
||
"net/url"
|
||
"os"
|
||
"strings"
|
||
"sync"
|
||
"time"
|
||
|
||
"github.com/jackc/pgx/v5"
|
||
"github.com/jackc/pgx/v5/pgxpool"
|
||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||
"github.com/redis/go-redis/v9"
|
||
|
||
"github.com/charawein/mtusi2026lab7/internal/config"
|
||
"github.com/charawein/mtusi2026lab7/internal/repository/postgres"
|
||
redisrepo "github.com/charawein/mtusi2026lab7/internal/repository/redis"
|
||
"github.com/charawein/mtusi2026lab7/internal/secrets"
|
||
"github.com/charawein/mtusi2026lab7/internal/storage"
|
||
"github.com/charawein/mtusi2026lab7/internal/tlsutil"
|
||
)
|
||
|
||
type Platform struct {
|
||
Cfg config.Config
|
||
Secrets *secrets.Manager // nil — режим без OpenBao
|
||
KP *tlsutil.KeyPair // клиентский сертификат сервиса
|
||
}
|
||
|
||
func env(k, def string) string {
|
||
if v := os.Getenv(k); v != "" {
|
||
return v
|
||
}
|
||
return def
|
||
}
|
||
|
||
// New: сертификат сервиса + вход в OpenBao (cert auth, роль = BAO_ROLE).
|
||
func New(ctx context.Context, cfg config.Config) (*Platform, error) {
|
||
p := &Platform{Cfg: cfg}
|
||
if cfg.TLSCertFile != "" {
|
||
kp, err := tlsutil.NewKeyPair(cfg.TLSCertFile, cfg.TLSKeyFile)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("service certificate: %w", err)
|
||
}
|
||
p.KP = kp
|
||
}
|
||
if cfg.BaoAddr == "" {
|
||
return p, nil
|
||
}
|
||
if p.KP == nil {
|
||
return nil, fmt.Errorf("BAO_ADDR set but no service certificate for cert auth")
|
||
}
|
||
tc, err := tlsutil.Client(cfg.BaoCACert, p.KP, "")
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
p.Secrets = secrets.New(secrets.Config{Addr: cfg.BaoAddr, Role: cfg.BaoRole, Path: cfg.BaoKVPath, TLS: tc,
|
||
Refresh: cfg.SecretsRefresh})
|
||
if err := p.Secrets.Start(ctx); err != nil {
|
||
return nil, fmt.Errorf("openbao: %w", err)
|
||
}
|
||
return p, nil
|
||
}
|
||
|
||
// PG — пул с TLS verify-full и динамическими credentials.
|
||
func (p *Platform) PG(ctx context.Context, maxConns int32) (*pgxpool.Pool, error) {
|
||
if p.Secrets == nil {
|
||
return postgres.NewPool(ctx, p.Cfg.DatabaseURL, maxConns)
|
||
}
|
||
dsn := fmt.Sprintf("postgres://%s:%s/%s?sslmode=verify-full&sslrootcert=%s",
|
||
env("DATABASE_HOST", "postgres"), env("DATABASE_PORT", "5432"), env("DATABASE_NAME", "messenger"),
|
||
url.QueryEscape(p.Cfg.TLSCAFile))
|
||
pc, err := pgxpool.ParseConfig(dsn)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
pc.MaxConnLifetime = 10 * time.Minute // после ротации старые соединения уходят за ≤ 10 мин
|
||
pc.BeforeConnect = func(_ context.Context, cc *pgx.ConnConfig) error {
|
||
cc.User, cc.Password = p.Secrets.Get("db_user"), p.Secrets.Get("db_password")
|
||
return nil
|
||
}
|
||
return postgres.NewPoolFromConfig(ctx, pc, maxConns)
|
||
}
|
||
|
||
// Redis — TLS + ACL-пользователь сервиса.
|
||
func (p *Platform) Redis(ctx context.Context) (*redis.Client, error) {
|
||
if p.Secrets == nil {
|
||
return redisrepo.NewClient(ctx, p.Cfg.CacheURL)
|
||
}
|
||
tc, err := tlsutil.Client(p.Cfg.TLSCAFile, nil, "redis")
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
return redisrepo.NewClientFromOptions(ctx, &redis.Options{
|
||
Addr: env("REDIS_ADDR", "redis:6379"),
|
||
TLSConfig: tc,
|
||
CredentialsProvider: func() (string, string) {
|
||
return p.Secrets.Get("redis_user"), p.Secrets.Get("redis_password")
|
||
},
|
||
})
|
||
}
|
||
|
||
// S3 — TLS к MinIO, ключ сервиса из OpenBao.
|
||
func (p *Platform) S3() (storage.Store, error) {
|
||
if p.Secrets == nil {
|
||
return storage.NewS3(p.Cfg.S3Endpoint, p.Cfg.S3Region, p.Cfg.S3Bucket, p.Cfg.S3AccessKey, p.Cfg.S3SecretKey)
|
||
}
|
||
pool, err := tlsutil.Pool(p.Cfg.TLSCAFile)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
st, err := storage.NewS3WithCreds(p.Cfg.S3Endpoint, p.Cfg.S3Region, p.Cfg.S3Bucket,
|
||
credentials.New(&s3Provider{m: p.Secrets}), pool)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
return authRetryStore{Store: st, m: p.Secrets}, nil
|
||
}
|
||
|
||
// BrokerTLS — mTLS к RabbitMQ (пользователь = CN сертификата, SASL EXTERNAL).
|
||
func (p *Platform) BrokerTLS() (*tls.Config, error) {
|
||
if p.KP == nil || !strings.HasPrefix(p.Cfg.BrokerURL, "amqps://") {
|
||
return nil, nil
|
||
}
|
||
return tlsutil.Client(p.Cfg.TLSCAFile, p.KP, "")
|
||
}
|
||
|
||
// CAPool — для проверок в других местах.
|
||
func (p *Platform) CAPool() (*x509.CertPool, error) { return tlsutil.Pool(p.Cfg.TLSCAFile) }
|
||
|
||
type s3Provider struct {
|
||
m *secrets.Manager
|
||
mu sync.Mutex
|
||
ver int
|
||
}
|
||
|
||
func (s *s3Provider) Retrieve() (credentials.Value, error) {
|
||
s.mu.Lock()
|
||
defer s.mu.Unlock()
|
||
s.ver = s.m.Version()
|
||
return credentials.Value{AccessKeyID: s.m.Get("s3_access_key"), SecretAccessKey: s.m.Get("s3_secret_key"),
|
||
SignerType: credentials.SignatureV4}, nil
|
||
}
|
||
|
||
func (s *s3Provider) RetrieveWithCredContext(*credentials.CredContext) (credentials.Value, error) {
|
||
return s.Retrieve()
|
||
}
|
||
|
||
// IsExpired — после ротации (новая версия KV) minio-go запросит ключ заново.
|
||
func (s *s3Provider) IsExpired() bool {
|
||
s.mu.Lock()
|
||
defer s.mu.Unlock()
|
||
return s.m.Version() != s.ver
|
||
}
|
||
|
||
// authRetryStore: S3 отверг ключ (InvalidAccessKeyId/SignatureDoesNotMatch) →
|
||
// внеочередное чтение секрета из OpenBao и один повтор, если версия сменилась.
|
||
// Так ротация/отзыв ключа S3 (сначала MinIO, затем KV) не сжигает попытки работ
|
||
// в окне до планового обновления секретов (SECRETS_REFRESH).
|
||
type authRetryStore struct {
|
||
storage.Store
|
||
m *secrets.Manager
|
||
}
|
||
|
||
func (s authRetryStore) retry(ctx context.Context, err error) bool {
|
||
if err == nil || !storage.IsAuthError(err) {
|
||
return false
|
||
}
|
||
changed := s.m.SyncNow(ctx)
|
||
if changed {
|
||
slog.Info("s3 credentials refreshed after auth error", "event", "secrets.s3_auth_retry", "version", s.m.Version())
|
||
}
|
||
return changed
|
||
}
|
||
|
||
func (s authRetryStore) Put(ctx context.Context, key string, r io.Reader, size int64, ct string) error {
|
||
err := s.Store.Put(ctx, key, r, size, ct)
|
||
if sk, ok := r.(io.Seeker); ok && s.retry(ctx, err) {
|
||
if _, serr := sk.Seek(0, io.SeekStart); serr == nil {
|
||
return s.Store.Put(ctx, key, r, size, ct)
|
||
}
|
||
}
|
||
return err
|
||
}
|
||
|
||
func (s authRetryStore) Get(ctx context.Context, key string) (io.ReadCloser, int64, error) {
|
||
rc, n, err := s.Store.Get(ctx, key)
|
||
if s.retry(ctx, err) {
|
||
return s.Store.Get(ctx, key)
|
||
}
|
||
return rc, n, err
|
||
}
|
||
|
||
func (s authRetryStore) Stat(ctx context.Context, key string) (storage.Object, error) {
|
||
o, err := s.Store.Stat(ctx, key)
|
||
if s.retry(ctx, err) {
|
||
return s.Store.Stat(ctx, key)
|
||
}
|
||
return o, err
|
||
}
|
||
|
||
func (s authRetryStore) Delete(ctx context.Context, key string) error {
|
||
err := s.Store.Delete(ctx, key)
|
||
if s.retry(ctx, err) {
|
||
return s.Store.Delete(ctx, key)
|
||
}
|
||
return err
|
||
}
|
||
|
||
func (s authRetryStore) Copy(ctx context.Context, src, dst string) error {
|
||
err := s.Store.Copy(ctx, src, dst)
|
||
if s.retry(ctx, err) {
|
||
return s.Store.Copy(ctx, src, dst)
|
||
}
|
||
return err
|
||
}
|
||
|
||
func (s authRetryStore) List(ctx context.Context, prefix string, fn func(storage.Object) error) error {
|
||
err := s.Store.List(ctx, prefix, fn)
|
||
if s.retry(ctx, err) {
|
||
return s.Store.List(ctx, prefix, fn)
|
||
}
|
||
return err
|
||
}
|