forked from mtusi2026/mtusi2026lab7
212 lines
6.2 KiB
Go
212 lines
6.2 KiB
Go
// Package openbao obtains process-scoped credentials using a short-lived client certificate.
|
|
// Secrets are materialized only in the container tmpfs. Renewal never falls back to local credentials.
|
|
package openbao
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"gitea.privcloud.tech/mtusi2026/internal/pkg/transportsecurity"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
type response struct {
|
|
Auth struct {
|
|
ClientToken string `json:"client_token"`
|
|
LeaseDuration int `json:"lease_duration"`
|
|
} `json:"auth"`
|
|
Data map[string]json.RawMessage `json:"data"`
|
|
LeaseID string `json:"lease_id"`
|
|
LeaseDuration int `json:"lease_duration"`
|
|
}
|
|
type client struct {
|
|
http *http.Client
|
|
addr, token string
|
|
}
|
|
|
|
func (c *client) call(ctx context.Context, method, path string, body any) (response, error) {
|
|
var out response
|
|
b, err := json.Marshal(body)
|
|
if err != nil {
|
|
return out, err
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, method, c.addr+"/v1/"+path, bytes.NewReader(b))
|
|
if err != nil {
|
|
return out, errors.New("invalid OpenBao endpoint")
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
if c.token != "" {
|
|
req.Header.Set("X-Vault-Token", c.token)
|
|
}
|
|
r, err := c.http.Do(req)
|
|
if err != nil {
|
|
return out, errors.New("OpenBao transport unavailable")
|
|
}
|
|
defer r.Body.Close()
|
|
if r.StatusCode < 200 || r.StatusCode >= 300 {
|
|
return out, errors.New("OpenBao operation denied or unavailable")
|
|
}
|
|
err = json.NewDecoder(r.Body).Decode(&out)
|
|
return out, err
|
|
}
|
|
func str(m map[string]json.RawMessage, k string) string {
|
|
var s string
|
|
_ = json.Unmarshal(m[k], &s)
|
|
return s
|
|
}
|
|
|
|
// Start is used by short-lived operator probes.
|
|
func Start(ctx context.Context) (func(), error) { _, close, err := Connect(ctx); return close, err }
|
|
|
|
// Connect returns the lifetime shared by every request and background operation.
|
|
func Connect(ctx context.Context) (context.Context, func(), error) {
|
|
addr := os.Getenv("BAO_ADDR")
|
|
if addr == "" {
|
|
return ctx, func() {}, nil
|
|
}
|
|
if !strings.HasPrefix(addr, "https://") {
|
|
return nil, nil, errors.New("OpenBao HTTPS required")
|
|
}
|
|
tlsConfig, err := transportsecurity.Client()
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
c := &client{http: &http.Client{Timeout: 3 * time.Second, Transport: &http.Transport{TLSClientConfig: tlsConfig}}, addr: addr}
|
|
role := os.Getenv("SERVICE_ROLE")
|
|
if role != "api" && role != "worker" && role != "dispatcher" {
|
|
return nil, nil, errors.New("invalid service role")
|
|
}
|
|
login := func() (time.Time, error) {
|
|
issuedAt := time.Now()
|
|
r, e := c.call(ctx, "POST", "auth/cert/login", map[string]string{"name": role})
|
|
if e != nil {
|
|
return time.Time{}, e
|
|
}
|
|
if r.Auth.ClientToken == "" || r.Auth.LeaseDuration < 1 {
|
|
return time.Time{}, errors.New("invalid scoped token")
|
|
}
|
|
c.token = r.Auth.ClientToken
|
|
return issuedAt.Add(time.Duration(r.Auth.LeaseDuration) * time.Second), nil
|
|
}
|
|
tokenExpiry, err := login()
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
kv, err := c.call(ctx, "GET", "secret/data/"+role, nil)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
var secrets map[string]string
|
|
if err = json.Unmarshal(kv.Data["data"], &secrets); err != nil {
|
|
return nil, nil, err
|
|
}
|
|
dbIssuedAt := time.Now()
|
|
db, err := c.call(ctx, "GET", "database/creds/"+role, nil)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
if db.LeaseDuration < 1 || db.LeaseID == "" {
|
|
return nil, nil, errors.New("invalid DB lease")
|
|
}
|
|
dbExpiry := dbIssuedAt.Add(time.Duration(db.LeaseDuration) * time.Second)
|
|
directory := "/run/credentials"
|
|
if err = os.MkdirAll(directory, 0700); err != nil {
|
|
return nil, nil, err
|
|
}
|
|
for key, value := range secrets {
|
|
env := map[string]string{"s3_access": "S3_ACCESS_KEY_ID_FILE", "s3_secret": "S3_SECRET_ACCESS_KEY_FILE", "redis_password": "REDIS_PASSWORD_FILE"}[key]
|
|
if env == "" {
|
|
continue
|
|
}
|
|
p := filepath.Join(directory, key)
|
|
if err = os.WriteFile(p, []byte(value), 0600); err != nil {
|
|
return nil, nil, err
|
|
}
|
|
os.Setenv(env, p)
|
|
}
|
|
os.Setenv("POSTGRES_USER", str(db.Data, "username"))
|
|
os.Setenv("POSTGRES_PASSWORD", str(db.Data, "password"))
|
|
os.Unsetenv("POSTGRES_PASSWORD_FILE")
|
|
ctx, cancel := context.WithCancel(ctx)
|
|
certExpiry := tlsConfig.Certificates[0].Leaf.NotAfter
|
|
expiryUpdates := make(chan time.Time)
|
|
deadline := func() time.Time { return minTime(tokenExpiry, dbExpiry, certExpiry).Add(-3 * time.Second) }
|
|
initialDeadline := deadline()
|
|
// This independent watchdog still fires while a renewal HTTP request is blocked.
|
|
go func() {
|
|
timer := time.NewTimer(max(time.Until(initialDeadline), 0))
|
|
defer timer.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-timer.C:
|
|
cancel()
|
|
return
|
|
case at := <-expiryUpdates:
|
|
timer.Reset(max(time.Until(at), 0))
|
|
}
|
|
}
|
|
}()
|
|
go func() {
|
|
tick := time.NewTicker(15 * time.Second)
|
|
defer tick.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-tick.C:
|
|
renewedAt := time.Now()
|
|
renewed, e := c.call(ctx, "POST", "auth/token/renew-self", map[string]int{"increment": 300})
|
|
if e == nil && renewed.Auth.LeaseDuration > 0 {
|
|
tokenExpiry = renewedAt.Add(time.Duration(renewed.Auth.LeaseDuration) * time.Second)
|
|
}
|
|
leaseAt := time.Now()
|
|
lease, e := c.call(ctx, "PUT", "sys/leases/renew", map[string]string{"lease_id": db.LeaseID, "increment": "600"})
|
|
if e == nil && lease.LeaseDuration > 0 {
|
|
dbExpiry = leaseAt.Add(time.Duration(lease.LeaseDuration) * time.Second)
|
|
}
|
|
current, e := c.call(ctx, "GET", "secret/data/"+role, nil)
|
|
if e == nil {
|
|
var next map[string]string
|
|
if json.Unmarshal(current.Data["data"], &next) == nil {
|
|
a, _ := json.Marshal(secrets)
|
|
b, _ := json.Marshal(next)
|
|
if !bytes.Equal(a, b) {
|
|
cancel()
|
|
return
|
|
}
|
|
}
|
|
}
|
|
// Re-authenticate before the renewable token reaches its max TTL.
|
|
if time.Until(tokenExpiry) < 45*time.Second {
|
|
if expiry, e := login(); e == nil {
|
|
tokenExpiry = expiry
|
|
}
|
|
}
|
|
select {
|
|
case expiryUpdates <- deadline():
|
|
case <-ctx.Done():
|
|
return
|
|
}
|
|
}
|
|
}
|
|
}()
|
|
return ctx, cancel, nil
|
|
}
|
|
|
|
func minTime(values ...time.Time) time.Time {
|
|
result := values[0]
|
|
for _, value := range values[1:] {
|
|
if value.Before(result) {
|
|
result = value
|
|
}
|
|
}
|
|
return result
|
|
}
|