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 }