package security import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "os" "strings" "sync/atomic" "time" ) var validUntil atomic.Int64 func Valid() bool { return os.Getenv("BAO_ROLE") == "" || time.Now().Unix() < validUntil.Load() } // Certificates are locally bootstrapped, scoped, expiring identities. No root or // permanent bootstrap token is ever mounted in an application container. func LoadSecrets(ctx context.Context) error { role := os.Getenv("BAO_ROLE") if role == "" { return nil } if !strings.HasPrefix(os.Getenv("BAO_ADDR"), "https://") { return fmt.Errorf("secret authority must use HTTPS") } tlsConfig, e := ClientTLS() if e != nil { return e } client := &http.Client{Transport: &http.Transport{TLSClientConfig: tlsConfig}, Timeout: 3 * time.Second} call := func(ctx context.Context, method, path, token string, body any, out any) error { b, _ := json.Marshal(body) req, e := http.NewRequestWithContext(ctx, method, os.Getenv("BAO_ADDR")+"/v1/"+path, bytes.NewReader(b)) if e != nil { return e } req.Header.Set("Content-Type", "application/json") if token != "" { req.Header.Set("X-Vault-Token", token) } res, e := client.Do(req) if e != nil { return fmt.Errorf("secret authority unavailable") } defer res.Body.Close() if res.StatusCode >= 300 { return fmt.Errorf("secret authority rejected request") } if out != nil { return json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(out) } return nil } refresh := func() error { c, cancel := context.WithTimeout(context.Background(), 6*time.Second) defer cancel() var auth struct { Auth struct { Token string `json:"client_token"` TTL int64 `json:"lease_duration"` } `json:"auth"` } if e := call(c, "POST", "auth/cert/login", "", map[string]string{"name": role}, &auth); e != nil { return e } var secret struct { Data map[string]string `json:"data"` } if e := call(c, "GET", "secret/"+role, auth.Auth.Token, nil, &secret); e != nil { return e } // Credentials are immutable during this process lifetime; rotation recreates // only affected services, never images. Refresh validates scoped auth/lease. if validUntil.Load() == 0 { for k, v := range secret.Data { if e := os.Setenv(k, v); e != nil { return e } } } validUntil.Store(time.Now().Unix() + auth.Auth.TTL) return nil } if e := refresh(); e != nil { return e } go func() { ticker := time.NewTicker(20 * time.Second) defer ticker.Stop() for range ticker.C { _ = refresh() if !Valid() && !strings.HasPrefix(role, "api") { os.Exit(75) } } }() return nil }