// SPDX-License-Identifier: GPL-3.0-or-later // Package fleet is the read-only client for the Security Hub fleet API (scripts/fleet_api.py). // // Structure for later views (RS07-E: stats, alerts, logs, trace, releases): Client.Get is the single transport // function. A view is a route string plus a rendering function; it needs no new transport, auth or error code. package fleet import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "os" "strings" "time" ) // Exit codes, identical to scripts/fleetctl.py. const ( ExitOK = 0 ExitDrift = 1 // drift or stale snapshot ExitConfig = 2 ExitTransport = 3 ) const ( MaxResponseBytes = 2 * 1024 * 1024 DefaultTimeout = 10 * time.Second ) // ConfigError maps to exit 2 (bad token, bad URL, 401, unreadable repo file). type ConfigError struct{ Msg string } func (e *ConfigError) Error() string { return e.Msg } // TransportError maps to exit 3 (cannot reach the server, non-401 HTTP error, bad body). type TransportError struct{ Msg string } func (e *TransportError) Error() string { return e.Msg } // ExitCodeFor returns the process exit code for an error; nil is ExitOK. func ExitCodeFor(err error) int { var ce *ConfigError var te *TransportError switch { case err == nil: return ExitOK case errors.As(err, &ce): return ExitConfig case errors.As(err, &te): return ExitTransport default: return ExitConfig } } // Envelope is the common shape of every /v1 response. Data stays raw so each view decodes what it needs. type Envelope struct { GeneratedAt string `json:"generated_at"` SnapshotAgeSeconds json.Number `json:"snapshot_age_seconds"` Stale bool `json:"stale"` CoverageComplete *bool `json:"coverage_complete"` SilentHosts []string `json:"silent_hosts"` // forward compatible: accepted-but-silent minions Data json.RawMessage `json:"data"` Raw map[string]any `json:"-"` // the whole body, numbers kept as written } // Client talks to one fleet API. The token is held only here and only sent in the Authorization header. type Client struct { BaseURL string token string HTTP *http.Client } // New validates the URL and returns a client. Redirects are never followed (a redirect must not carry the token). func New(baseURL, token string) (*Client, error) { u, err := url.Parse(baseURL) if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { return nil, &ConfigError{"url must be http or https"} } return &Client{ BaseURL: strings.TrimRight(baseURL, "/"), token: token, HTTP: &http.Client{ Timeout: DefaultTimeout, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, }, }, nil } // LoadToken mirrors fleetctl.load_token: SECURITY_HUB_FLEET_TOKEN wins (set but blank is an error), else the // token file (regular, no group/other permission bits). Errors never contain the token. func LoadToken(lookup func(string) (string, bool), tokenFile string) (string, error) { if v, set := lookup("SECURITY_HUB_FLEET_TOKEN"); set { token := strings.TrimSpace(v) if token == "" { return "", &ConfigError{"token is empty"} } return token, nil } st, err := os.Stat(tokenFile) if err != nil { return "", &ConfigError{"token file unreadable"} } if !st.Mode().IsRegular() || st.Mode().Perm()&0o077 != 0 { return "", &ConfigError{"token file must be mode 0600"} } raw, err := os.ReadFile(tokenFile) if err != nil { return "", &ConfigError{"token file unreadable"} } token := strings.TrimSpace(string(raw)) if token == "" { return "", &ConfigError{"token is empty"} } return token, nil } // Get performs GET path?params and decodes the JSON object body into an Envelope. params with empty values are // skipped. Errors are *ConfigError (401) or *TransportError, never containing the token. func (c *Client) Get(ctx context.Context, path string, params url.Values) (*Envelope, error) { target := c.BaseURL + path if q := cleanParams(params); len(q) > 0 { target += "?" + q.Encode() } req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil) if err != nil { return nil, &ConfigError{"url must be http or https"} } req.Header.Set("Authorization", "Bearer "+c.token) req.Header.Set("Accept", "application/json") resp, err := c.HTTP.Do(req) if err != nil { return nil, transportFailure(err) } defer resp.Body.Close() raw, err := io.ReadAll(io.LimitReader(resp.Body, MaxResponseBytes+1)) if resp.StatusCode == http.StatusUnauthorized { return nil, &ConfigError{"unauthorized"} } if resp.StatusCode < 200 || resp.StatusCode > 299 { return nil, &TransportError{fmt.Sprintf("HTTP %d", resp.StatusCode)} } if err != nil { return nil, &TransportError{"transport failure: read error"} } if len(raw) > MaxResponseBytes { return nil, &TransportError{"response too large"} } return decodeEnvelope(raw) } func decodeEnvelope(raw []byte) (*Envelope, error) { dec := json.NewDecoder(bytes.NewReader(raw)) dec.UseNumber() var generic any if err := dec.Decode(&generic); err != nil { return nil, &TransportError{"response is not valid JSON"} } if dec.More() { return nil, &TransportError{"response is not valid JSON"} } obj, ok := generic.(map[string]any) if !ok { return nil, &TransportError{"response is not a JSON object"} } var env Envelope if err := json.Unmarshal(raw, &env); err != nil { // Typed fields disagreed with the body (for example stale as a string): keep going with defaults. env = Envelope{} env.GeneratedAt, _ = obj["generated_at"].(string) env.Stale, _ = obj["stale"].(bool) if d, ok := obj["data"]; ok { env.Data, _ = json.Marshal(d) } } env.Raw = obj return &env, nil } func cleanParams(p url.Values) url.Values { out := url.Values{} for k, vs := range p { for _, v := range vs { if v != "" { out.Add(k, v) } } } return out } func transportFailure(err error) error { var uerr *url.Error if errors.As(err, &uerr) { if uerr.Timeout() { return &TransportError{"cannot reach server: timed out"} } return &TransportError{"cannot reach server: " + uerr.Err.Error()} } return &TransportError{"transport failure"} } // Typed views over the routes fleetctl uses today. RS07-E adds Stats, Alerts, Logs, Trace, Releases here. // Summary is GET /v1/summary. func (c *Client) Summary(ctx context.Context) (*Envelope, error) { return c.Get(ctx, "/v1/summary", nil) } // Modules is GET /v1/modules. func (c *Client) Modules(ctx context.Context) (*Envelope, error) { return c.Get(ctx, "/v1/modules", nil) } // Jobs is GET /v1/jobs?host=&fun=&limit=. func (c *Client) Jobs(ctx context.Context, host, fun string, limit int) (*Envelope, error) { q := url.Values{"host": {host}, "fun": {fun}} if limit > 0 { q.Set("limit", fmt.Sprint(limit)) } return c.Get(ctx, "/v1/jobs", q) } // Backups is GET /v1/backups. An older controller answers 404; that becomes a clear transport error. func (c *Client) Backups(ctx context.Context) (*Envelope, error) { env, err := c.Get(ctx, "/v1/backups", nil) var te *TransportError if errors.As(err, &te) && te.Msg == "HTTP 404" { return nil, &TransportError{"backups: the fleet API does not have /v1/backups yet (update the controller)"} } return env, err }