This commit is contained in:
@@ -0,0 +1,123 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
S3Endpoint string
|
||||
S3Bucket string
|
||||
S3AccessKey string
|
||||
S3SecretKey string
|
||||
S3UseSSL bool
|
||||
Port string
|
||||
PostgresHost string
|
||||
PostgresPort uint16
|
||||
PostgresUser string
|
||||
PostgresDatabase string
|
||||
PostgresPassword string
|
||||
PostgresMaxConns int32
|
||||
RedisAddr string
|
||||
RedisPassword string
|
||||
secure bool
|
||||
SessionTTL time.Duration
|
||||
QueryTimeout time.Duration
|
||||
CursorKey [32]byte
|
||||
}
|
||||
|
||||
func value(name, fallback string) string {
|
||||
if v := os.Getenv(name); v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
func positive(name string, fallback, max int) (int, error) {
|
||||
n, err := strconv.Atoi(value(name, strconv.Itoa(fallback)))
|
||||
if err != nil || n < 1 || n > max {
|
||||
return 0, fmt.Errorf("invalid %s", name)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
func secret(name string) (string, error) {
|
||||
if file := os.Getenv(name + "_FILE"); file != "" {
|
||||
data, err := os.ReadFile(file)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("cannot read %s_FILE", name)
|
||||
}
|
||||
if s := strings.TrimSpace(string(data)); s != "" {
|
||||
return s, nil
|
||||
}
|
||||
}
|
||||
if s := os.Getenv(name); s != "" {
|
||||
return s, nil
|
||||
}
|
||||
return "", fmt.Errorf("%s or %s_FILE is required", name, name)
|
||||
}
|
||||
|
||||
func Load() (Config, error) { return load(secret) }
|
||||
|
||||
func load(secret func(string) (string, error)) (Config, error) {
|
||||
var c Config
|
||||
port, err := positive("PORT", 8080, 65535)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
c.Port = strconv.Itoa(port)
|
||||
pgPort, err := positive("POSTGRES_PORT", 5432, 65535)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
c.PostgresPort = uint16(pgPort)
|
||||
max, err := positive("POSTGRES_MAX_CONNS", 10, 100)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
c.PostgresMaxConns = int32(max)
|
||||
ttl, err := positive("SESSION_TTL_SECONDS", 3600, 86400*30)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
c.SessionTTL = time.Duration(ttl) * time.Second
|
||||
timeout, err := positive("QUERY_TIMEOUT_MS", 2000, 10000)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
c.QueryTimeout = time.Duration(timeout) * time.Millisecond
|
||||
c.PostgresHost = value("POSTGRES_HOST", "localhost")
|
||||
c.PostgresUser = value("POSTGRES_USER", "messenger")
|
||||
c.PostgresDatabase = value("POSTGRES_DB", "messenger")
|
||||
c.RedisAddr = value("REDIS_ADDR", "localhost:6379")
|
||||
c.PostgresPassword, err = secret("POSTGRES_PASSWORD")
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
key, err := secret("CURSOR_KEY")
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
decoded, err := hex.DecodeString(key)
|
||||
if err != nil || len(decoded) != 32 {
|
||||
return c, fmt.Errorf("CURSOR_KEY must be 32 random bytes encoded as hex")
|
||||
}
|
||||
copy(c.CursorKey[:], decoded)
|
||||
c.S3Endpoint = value("S3_ENDPOINT", "minio:9000")
|
||||
c.S3Bucket = value("S3_BUCKET", "attachments")
|
||||
c.S3UseSSL, err = strconv.ParseBool(value("S3_USE_SSL", "false"))
|
||||
if err != nil {
|
||||
return c, fmt.Errorf("invalid S3_USE_SSL")
|
||||
}
|
||||
c.S3AccessKey, err = secret("S3_ACCESS_KEY")
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
c.S3SecretKey, err = secret("S3_SECRET_KEY")
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"reflect"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/trust"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
const caFile = "/trust/ca.crt"
|
||||
|
||||
func LoadService() (Config, error) {
|
||||
role := os.Getenv("SERVICE_ROLE")
|
||||
if role != "api" && role != "worker" && role != "operator" {
|
||||
return Config{}, errors.New("invalid service role")
|
||||
}
|
||||
tlsConfig, err := trust.Client(caFile, "/identity/tls.crt", "/identity/tls.key")
|
||||
if err != nil {
|
||||
return Config{}, errors.New("cannot load service identity")
|
||||
}
|
||||
client := &http.Client{
|
||||
Timeout: 3 * time.Second,
|
||||
Transport: &http.Transport{TLSClientConfig: tlsConfig, DisableKeepAlives: true},
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
||||
}
|
||||
query := func(method, path, token string, out any) error {
|
||||
req, err := http.NewRequest(method, "https://openbao:8200/v1/"+path, bytes.NewReader([]byte("{}")))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if token != "" {
|
||||
req.Header.Set("X-Vault-Token", token)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return errors.New("OpenBao unreachable")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode/100 != 2 {
|
||||
return errors.New("OpenBao authorization or availability failure")
|
||||
}
|
||||
if out != nil {
|
||||
return json.NewDecoder(io.LimitReader(resp.Body, 65536)).Decode(out)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
read := func() (map[string]string, error) {
|
||||
var session struct {
|
||||
Auth struct {
|
||||
Token string `json:"client_token"`
|
||||
}
|
||||
}
|
||||
if err := query("POST", "auth/cert/login", "", &session); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var response struct {
|
||||
Data struct {
|
||||
Data map[string]string
|
||||
}
|
||||
}
|
||||
err := query("GET", "lab/data/"+role, session.Auth.Token, &response)
|
||||
_ = query("POST", "auth/token/revoke-self", session.Auth.Token, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, key := range []string{"POSTGRES_PASSWORD", "S3_ACCESS_KEY", "S3_SECRET_KEY", "REDIS_PASSWORD", "CURSOR_KEY"} {
|
||||
if response.Data.Data[key] == "" {
|
||||
return nil, errors.New("OpenBao role data incomplete")
|
||||
}
|
||||
}
|
||||
return response.Data.Data, nil
|
||||
}
|
||||
initial, err := read()
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
cfg, err := load(func(name string) (string, error) {
|
||||
return initial[name], nil
|
||||
})
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if !cfg.S3UseSSL {
|
||||
return Config{}, errors.New("service S3 connection requires TLS")
|
||||
}
|
||||
cfg.RedisPassword = initial["REDIS_PASSWORD"]
|
||||
cfg.secure = true
|
||||
if role != "operator" {
|
||||
go func() {
|
||||
ticker := time.NewTicker(10 * time.Second)
|
||||
defer ticker.Stop()
|
||||
last := time.Now()
|
||||
for range ticker.C {
|
||||
next, err := read()
|
||||
if err == nil {
|
||||
if !reflect.DeepEqual(initial, next) {
|
||||
log.Print("service credentials changed; restarting with fresh credentials")
|
||||
_ = syscall.Kill(os.Getpid(), syscall.SIGTERM)
|
||||
return
|
||||
}
|
||||
last = time.Now()
|
||||
} else if time.Since(last) >= 35*time.Second {
|
||||
log.Print("service credential lease lost; terminating")
|
||||
_ = syscall.Kill(os.Getpid(), syscall.SIGTERM)
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (c Config) PostgresConfig() (*pgxpool.Config, error) {
|
||||
if c.secure {
|
||||
return pgxpool.ParseConfig("host=" + c.PostgresHost + " sslmode=verify-full sslrootcert=" + caFile)
|
||||
}
|
||||
return pgxpool.ParseConfig("sslmode=disable")
|
||||
}
|
||||
|
||||
func (c Config) RedisOptions() (*redis.Options, error) {
|
||||
o := &redis.Options{
|
||||
Addr: c.RedisAddr, Username: os.Getenv("REDIS_USER"), Password: c.RedisPassword,
|
||||
PoolSize: 10, MaxActiveConns: 10, PoolTimeout: c.QueryTimeout,
|
||||
// Retire pooled connections before the mTLS proxy enforces its 90-second limit.
|
||||
ConnMaxLifetime: time.Minute, ConnMaxIdleTime: 20 * time.Second,
|
||||
DialTimeout: c.QueryTimeout, ReadTimeout: c.QueryTimeout, WriteTimeout: c.QueryTimeout,
|
||||
MaxRetries: -1, ContextTimeoutEnabled: true, Protocol: 2, DisableIdentity: true,
|
||||
}
|
||||
if c.secure {
|
||||
var err error
|
||||
o.TLSConfig, err = trust.Client(caFile, "/identity/tls.crt", "/identity/tls.key")
|
||||
return o, err
|
||||
}
|
||||
return o, nil
|
||||
}
|
||||
Reference in New Issue
Block a user