Files
deploy-felhom-compose/controller/internal/cloudflare/client.go
T
admin 8b8c04a487 fix: P0+P1 critical bug fixes across controller (24 files)
Concurrency fixes:
- Deep-copy stacks in GetStack/GetStacks to prevent shared state mutation (C04)
- Add per-state mutex to watchdog pathProbeState (C05)
- Guard MetricsCollector.Start() with sync.Once against double-start (C06)
- Hold diskJobMu across entire raw mount operation (C07)
- Add mutex to SetEncryptionKey (C08), MigrateEncryption write lock (H03)
- Use sync.Once for sync.Stop() channel close (H08)
- Set syncing=true before releasing lock in TriggerSync (H09)
- Deep-copy lastDBDump/lastBackup in GetFullStatus (H11)
- Add WaitGroup for stderr goroutine in MigrateDrive (H19)
- Add mutex to SetBackupRunningCheck (M18)

Security fixes:
- Validate Bearer token against Hub API key in CSRF middleware (H16)
- Validate backup paths start with expected prefix in RemoveStack (M12)
- Guard uuid[:8] slice with length check (H20)
- Parse fstab fields exactly for mount target matching (H21)

Bug fixes:
- Use decrypted env vars for compose deploy (C01)
- Log decrypt failures in DecryptMap instead of swallowing (C02)
- Move Deployed=false inside lock in runComposeDeploy (C03)
- Fix activeDrives() to skip disconnected drives (H02)
- Fix Snapshot() stderr extraction from exec.ExitError (H01)
- Check unlockCmd.Run() error in restic (H01)
- Buffer template rendering via bytes.Buffer (H07)
- Thread context.Context through cloudflare client (H10)
- Fix leaf-name collision detection in cross-drive backup (H15)
- Add nil check for crossDriveRunner (H17)
- Use strings.TrimSpace instead of slice on command output (H18)
- Make SaveAppConfig atomic with write-to-tmp+rename (H04)
- Pass encKey on deploy failure SaveAppConfig (H05)
- Fix IPv6 address format in TCP health probe

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 13:39:45 +01:00

115 lines
2.7 KiB
Go

package cloudflare
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"time"
)
const apiBase = "https://api.cloudflare.com/client/v4"
// Client handles Cloudflare API calls.
type Client struct {
apiToken string
httpClient *http.Client
logger *log.Logger
debug bool
}
// New creates a Cloudflare API client.
func New(apiToken string, logger *log.Logger, debug bool) *Client {
return &Client{
apiToken: apiToken,
httpClient: &http.Client{Timeout: 15 * time.Second},
logger: logger,
debug: debug,
}
}
// IsConfigured returns true if a CF API token is set.
func (c *Client) IsConfigured() bool {
return c.apiToken != ""
}
// apiResponse is the generic Cloudflare API response wrapper.
type apiResponse struct {
Success bool `json:"success"`
Errors []apiError `json:"errors"`
Messages []apiMessage `json:"messages"`
Result json.RawMessage `json:"result"`
}
type apiError struct {
Code int `json:"code"`
Message string `json:"message"`
}
type apiMessage struct {
Code int `json:"code"`
Message string `json:"message"`
}
// do performs an HTTP request to the Cloudflare API and decodes the response.
func (c *Client) do(ctx context.Context, method, path string, body interface{}) (*apiResponse, error) {
var bodyReader io.Reader
if body != nil {
data, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("marshal request: %w", err)
}
bodyReader = bytes.NewReader(data)
if c.debug {
c.logger.Printf("[CF-DEBUG] %s %s body=%s", method, path, string(data))
}
} else if c.debug {
c.logger.Printf("[CF-DEBUG] %s %s", method, path)
}
url := apiBase + path
req, err := http.NewRequestWithContext(ctx, method, url, bodyReader)
if err != nil {
return nil, fmt.Errorf("create request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+c.apiToken)
req.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("http request: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("read response: %w", err)
}
if c.debug {
c.logger.Printf("[CF-DEBUG] Response %d: %s", resp.StatusCode, string(respBody))
}
var apiResp apiResponse
if err := json.Unmarshal(respBody, &apiResp); err != nil {
return nil, fmt.Errorf("decode response (status %d): %w", resp.StatusCode, err)
}
if !apiResp.Success {
msg := "unknown error"
if len(apiResp.Errors) > 0 {
msg = apiResp.Errors[0].Message
for _, e := range apiResp.Errors[1:] {
msg += "; " + e.Message
}
}
return &apiResp, fmt.Errorf("cloudflare API error (status %d): %s", resp.StatusCode, msg)
}
return &apiResp, nil
}