package security import ( "bytes" "context" "encoding/json" "fmt" "io" "log/slog" "net/http" "os" "os/exec" "reflect" "strings" "syscall" "time" ) func baoRequest(ctx context.Context, client *http.Client, method, path, token string, body any) (map[string]any, error) { if !strings.HasPrefix(os.Getenv("BAO_ADDR"), "https://") { return nil, fmt.Errorf("secret service requires HTTPS") } b, _ := json.Marshal(body) r, e := http.NewRequestWithContext(ctx, method, os.Getenv("BAO_ADDR")+"/v1/"+path, bytes.NewReader(b)) if e != nil { return nil, fmt.Errorf("invalid secret endpoint") } r.Header.Set("Content-Type", "application/json") if token != "" { r.Header.Set("X-Vault-Token", token) } resp, e := client.Do(r) if e != nil { return nil, fmt.Errorf("secret service unavailable") } defer resp.Body.Close() if resp.StatusCode != 200 { return nil, fmt.Errorf("secret service denied or sealed") } var out map[string]any if json.NewDecoder(io.LimitReader(resp.Body, 65536)).Decode(&out) != nil { return nil, fmt.Errorf("invalid secret response") } return out, nil } // Short-lived certificate auth replaces a permanent bootstrap token. Values // live only in this process and a tmpfs snapshot consumed by the child. func fetch(ctx context.Context) (map[string]string, time.Time, error) { tc, e := ClientTLS() if e != nil { return nil, time.Time{}, e } transport := &http.Transport{TLSClientConfig: tc} defer transport.CloseIdleConnections() client := &http.Client{Transport: transport, Timeout: 3 * time.Second} login, e := baoRequest(ctx, client, "POST", "auth/cert/login", "", map[string]string{"name": os.Getenv("SERVICE_ID")}) if e != nil { return nil, time.Time{}, e } auth, ok := login["auth"].(map[string]any) if !ok { return nil, time.Time{}, fmt.Errorf("missing service auth") } token, _ := auth["client_token"].(string) ttl, _ := auth["lease_duration"].(float64) if ttl <= 0 || ttl > 120 { return nil, time.Time{}, fmt.Errorf("invalid service TTL") } defer baoRequest(context.WithoutCancel(ctx), client, "POST", "auth/token/revoke-self", token, map[string]any{}) data, e := baoRequest(ctx, client, "GET", "kv/data/"+os.Getenv("SERVICE_ID"), token, nil) if e != nil { return nil, time.Time{}, e } outer, _ := data["data"].(map[string]any) raw, _ := outer["data"].(map[string]any) values := map[string]string{} for k, v := range raw { if s, ok := v.(string); ok { values[k] = s } } if values["database_url"] == "" { return nil, time.Time{}, fmt.Errorf("incomplete service secrets") } return values, time.Now().Add(time.Duration(ttl) * time.Second), nil } func stopChild(cmd *exec.Cmd, done <-chan error) { cmd.Process.Signal(syscall.SIGTERM) select { case <-done: case <-time.After(6 * time.Second): cmd.Process.Kill() <-done } } func Supervise(ctx context.Context, args []string) error { var values map[string]string var expiry time.Time var child *exec.Cmd var done chan error ticker := time.NewTicker(5 * time.Second) defer ticker.Stop() defer func() { if child != nil { stopChild(child, done) } }() for { fresh, until, e := fetch(ctx) if e == nil { expiry = until if child == nil || !reflect.DeepEqual(values, fresh) { if child != nil { stopChild(child, done) child = nil } values = fresh b, _ := json.Marshal(values) if e = os.WriteFile("/run/runtime/active.json", b, 0600); e != nil { return fmt.Errorf("runtime secret storage unavailable") } executable, _ := os.Executable() child = exec.Command(executable, args...) child.Env = append(os.Environ(), "RUNTIME_SECRET_FILE=/run/runtime/active.json") child.Stdout = os.Stdout child.Stderr = os.Stderr if e = child.Start(); e != nil { return fmt.Errorf("child unavailable") } done = make(chan error, 1) go func(c *exec.Cmd, ch chan error) { ch <- c.Wait() }(child, done) slog.Info("service credentials installed", "event", "credentials_installed") } } else if child != nil && !time.Now().Before(expiry) { stopChild(child, done) child = nil os.Remove("/run/runtime/active.json") slog.Warn("service authorization expired", "event", "authorization_expired") } if child != nil { select { case <-done: child = nil default: } } select { case <-ctx.Done(): return nil case <-ticker.C: } } } func RuntimeSecret(name string) (string, bool) { path := os.Getenv("RUNTIME_SECRET_FILE") if path == "" { return "", false } b, e := os.ReadFile(path) if e != nil { return "", true } var data map[string]string if json.Unmarshal(b, &data) != nil { return "", true } key := map[string]string{"DATABASE_URL_FILE": "database_url", "CACHE_URL_FILE": "cache_url", "BROKER_URL_FILE": "broker_url", "CURSOR_KEY_FILE": "cursor_key", "S3_ACCESS_KEY_ID_FILE": "s3_access_key_id", "S3_SECRET_ACCESS_KEY_FILE": "s3_secret_access_key"}[name] return data[key], true }