Files
cairnobs/cli/cmd/cairnobsctl/httpclient.go
jcoffey-dev 13cf9a30cb Rebrand: Sentry -> Cairn OBS
Full rebrand across cosmetic branding, code identifiers, and
infrastructure/data-plane naming, using the supplied Cairn OBS logo
package. Cosmetic: favicon/logo swap (also closes a stale license-audit
finding -- the old favicon was SvelteKit's unreplaced scaffold logo),
new centered welcome landing page, larger/legible sidebar logo, page
titles, CLAUDE.md/README/docs prose.

Code identifiers: Go module path github.com/sentry/sentry ->
github.com/cairnobs/cairnobs across all 13 modules and ~91 files (protoc
regenerated); Rust crates sentry-agent/sentry-parser/sentry-search ->
cairnobs-*; CLI sentryctl -> cairnobsctl; Terraform provider fully
renamed (sentry_dashboard etc. -> cairnobs_dashboard, provider type,
env vars); every session/auth cookie name; agent config paths and
Windows service identity.

Deliberately preserved: the gRPC wire protocol's protobuf packages
(sentry.logs.v1, sentry.agent.v1) and their Go import directory
(proto/sentry/...) -- renaming the wire-level package would break every
currently-deployed agent binary (confirmed two real hosts, including
mail.inbuxa.com, are actively streaming through this exact contract)
until rebuilt and redeployed in lockstep with an ingest cutover. Only
the Go module path wrapping the generated code changes.

Infrastructure: every docker-compose container name (root and three
component-level compose files); the Helm chart (directory, Chart.yaml,
named-template helpers, all templates, values.yaml image repos);
Kubernetes Operator (CRD group sentry.io -> cairnobs.io, both CRD YAML
files, Go identifiers, RBAC markers); the coupled enterprise/tenantcrd
package. Caught and fixed real path-coupling bugs along the way: the
Helm chart's search/ingest volume mounts and the dev-only-credential
detection constant vs. docker-compose.yml's literal values had to move
together or a security warning would have silently stopped firing.

Data plane: Postgres database sentry_metadata -> cairnobs_metadata and
role sentry -> cairnobs; ClickHouse database sentry -> cairnobs; Kafka
topic sentry.logs.raw -> cairnobs.logs.raw and its consumer groups.
Source-level defaults, docker-compose.yml, and every migrate.sh/
provision script default updated together; already-applied migration
files left untouched per this repo's immutable-migration convention.

Verified at every layer: all 13 Go modules build/vet/test clean, both
Rust workspaces (agent, search) build/clippy/test clean, npm run check/
build clean, docker compose config validates on all four compose files.
Live-verified against a real docker stack multiple times through this
work, including a final fresh-volume run confirming the actual renamed
Postgres database/role, ClickHouse database, and Kafka topic all work
end to end with a real login and query, zero console errors.
2026-08-21 20:53:32 -07:00

169 lines
5.5 KiB
Go

package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
)
var httpClient = &http.Client{Timeout: 30 * time.Second}
// setAuth attaches CAIRNOBSCTL_TOKEN (see resolveToken) as a Bearer
// credential, a no-op when token is empty -- matches every backend's
// nil-authorizer no-op default (see api/internal/authz.RequireRole*).
func setAuth(req *http.Request, token string) {
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
}
// httpGetJSON GETs path and prints the pretty-printed JSON response to
// stdout, or the error body/status to stderr. Shared by dashboards/alerts
// list and get, which otherwise differ only in path and resource name.
func httpGetJSON(baseURL, path, token string, stdout, stderr io.Writer) int {
req, err := http.NewRequest(http.MethodGet, baseURL+path, nil)
if err != nil {
fmt.Fprintf(stderr, "building request: %v\n", err)
return 1
}
setAuth(req, token)
resp, err := httpClient.Do(req)
if err != nil {
fmt.Fprintf(stderr, "request failed: %v\n", err)
return 1
}
defer resp.Body.Close()
return printJSONResponse(resp, stdout, stderr)
}
// httpPostFileJSON reads file (a JSON document, e.g. an exported
// dashboard or a rule definition) and POSTs it to path as-is -- no
// reshaping, since the file's shape already matches what the endpoint
// expects (the same JSON the web UI's export button and POST /rules
// produce/accept respectively). This is what makes "apply" the seed of a
// future Terraform provider: one JSON contract, multiple callers.
func httpPostFileJSON(baseURL, path, token, file string, stdout, stderr io.Writer) int {
body, err := os.ReadFile(file)
if err != nil {
fmt.Fprintf(stderr, "reading %s: %v\n", file, err)
return 1
}
req, err := http.NewRequest(http.MethodPost, baseURL+path, bytes.NewReader(body))
if err != nil {
fmt.Fprintf(stderr, "building request: %v\n", err)
return 1
}
req.Header.Set("Content-Type", "application/json")
setAuth(req, token)
resp, err := httpClient.Do(req)
if err != nil {
fmt.Fprintf(stderr, "request failed: %v\n", err)
return 1
}
defer resp.Body.Close()
return printJSONResponse(resp, stdout, stderr)
}
// httpMutateNoBody sends method to path with an optional JSON body
// ("" for none, e.g. DELETE) and expects a 2xx with no meaningful
// response body -- PUT/DELETE /dashboards/{id}/permissions/{userId}
// both respond 204 No Content, so there's nothing for printJSONResponse
// to pretty-print here. Prints successMsg to stdout on success, the
// same {"error": "..."} parsing every other helper in this file uses
// otherwise.
func httpMutateNoBody(method, baseURL, path, token, body, successMsg string, stdout, stderr io.Writer) int {
var reqBody io.Reader
if body != "" {
reqBody = strings.NewReader(body)
}
req, err := http.NewRequest(method, baseURL+path, reqBody)
if err != nil {
fmt.Fprintf(stderr, "building request: %v\n", err)
return 1
}
if body != "" {
req.Header.Set("Content-Type", "application/json")
}
setAuth(req, token)
resp, err := httpClient.Do(req)
if err != nil {
fmt.Fprintf(stderr, "request failed: %v\n", err)
return 1
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
respBody, _ := io.ReadAll(resp.Body)
var errResp errorResponseBody
if json.Unmarshal(respBody, &errResp) == nil && errResp.Error != "" {
fmt.Fprintf(stderr, "request failed: %s\n", errResp.Error)
} else {
fmt.Fprintf(stderr, "request failed: status %d\n", resp.StatusCode)
}
return 1
}
fmt.Fprintln(stdout, successMsg)
return 0
}
// httpPutJSON PUTs body (already-encoded JSON) to path and prints the
// pretty-printed JSON response -- same shape as httpPostFileJSON, but
// for callers that construct the body themselves rather than reading it
// from a file (agents config set, agents restart).
func httpPutJSON(baseURL, path, token, body string, stdout, stderr io.Writer) int {
return httpSendJSON(http.MethodPut, baseURL, path, token, body, stdout, stderr)
}
// httpPostJSON is httpPutJSON's POST sibling -- for callers creating a
// resource from a body they built themselves rather than reading it
// from a file (users create, users reset-password).
func httpPostJSON(baseURL, path, token, body string, stdout, stderr io.Writer) int {
return httpSendJSON(http.MethodPost, baseURL, path, token, body, stdout, stderr)
}
func httpSendJSON(method, baseURL, path, token, body string, stdout, stderr io.Writer) int {
req, err := http.NewRequest(method, baseURL+path, strings.NewReader(body))
if err != nil {
fmt.Fprintf(stderr, "building request: %v\n", err)
return 1
}
req.Header.Set("Content-Type", "application/json")
setAuth(req, token)
resp, err := httpClient.Do(req)
if err != nil {
fmt.Fprintf(stderr, "request failed: %v\n", err)
return 1
}
defer resp.Body.Close()
return printJSONResponse(resp, stdout, stderr)
}
func printJSONResponse(resp *http.Response, stdout, stderr io.Writer) int {
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Fprintf(stderr, "reading response: %v\n", err)
return 1
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
var errResp errorResponseBody
if json.Unmarshal(body, &errResp) == nil && errResp.Error != "" {
fmt.Fprintf(stderr, "request failed: %s\n", errResp.Error)
} else {
fmt.Fprintf(stderr, "request failed: status %d\n", resp.StatusCode)
}
return 1
}
var pretty bytes.Buffer
if json.Indent(&pretty, body, "", " ") == nil {
stdout.Write(pretty.Bytes())
} else {
stdout.Write(body)
}
fmt.Fprintln(stdout)
return 0
}