From 4af4f2c28030cc56b3a15d3899052bf443be1e8b Mon Sep 17 00:00:00 2001 From: Amir Husayn Panahifar Date: Fri, 4 Dec 2026 16:42:50 +0330 Subject: [PATCH] feat(prom): auth, TLS and custom headers for the Prometheus datasource Add --prom-bearer-file, --prom-basic-auth-user/--prom-basic-auth-password-file, --prom-ca-file and repeatable --prom-header to grom run, backed by a new prom.NewWithOptions. Secrets are read from files only and re-read per request. With no new flags the existing prom.New path is used unchanged. Standard library only; go.mod is unchanged. Refs #2 --- README.md | 24 +++ cmd/grom/promflags.go | 81 +++++++++ cmd/grom/promflags_test.go | 57 +++++++ cmd/grom/run.go | 7 +- internal/datasource/prom/options.go | 146 ++++++++++++++++ internal/datasource/prom/options_test.go | 205 +++++++++++++++++++++++ 6 files changed, 516 insertions(+), 4 deletions(-) create mode 100644 cmd/grom/promflags.go create mode 100644 cmd/grom/promflags_test.go create mode 100644 internal/datasource/prom/options.go create mode 100644 internal/datasource/prom/options_test.go diff --git a/README.md b/README.md index 246d99c..3089648 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,30 @@ grom import --check my-dashboard.json # non-zero exit on any warning (CI) grom run -c dashboard.yaml --prom http://localhost:9090 --once ``` +## Authentication, TLS and tenants + +For a Prometheus behind auth, a private CA or a multi-tenant backend +(Mimir, Cortex, Thanos), pass connection options to `grom run`. Secrets are +read from files only — never from flags — and are re-read on every request, +so rotated credentials are picked up without a restart. + +| Flag | Effect | +|---|---| +| `--prom-bearer-file PATH` | `Authorization: Bearer ` | +| `--prom-basic-auth-user USER` + `--prom-basic-auth-password-file PATH` | HTTP basic auth | +| `--prom-ca-file PATH` | verify the server with this PEM CA bundle | +| `--prom-header "Name: value"` | extra header on every request (repeatable) | + +```bash +# Behind an authenticating reverse proxy, internal CA +grom run -c dashboard.yaml --prom https://prometheus.example.com \ + --prom-bearer-file ~/.config/grom/token --prom-ca-file ~/.config/grom/ca.pem + +# Multi-tenant backend: select the tenant with X-Scope-OrgID +grom run -c dashboard.yaml --prom https://mimir.example.com/prometheus \ + --prom-header "X-Scope-OrgID: team-a" +``` + ## Keys | Key | Action | diff --git a/cmd/grom/promflags.go b/cmd/grom/promflags.go new file mode 100644 index 0000000..deaeb8b --- /dev/null +++ b/cmd/grom/promflags.go @@ -0,0 +1,81 @@ +package main + +import ( + "fmt" + "net/http" + "strings" + + "github.com/spf13/cobra" + + "github.com/qf-studio/grom/internal/datasource/prom" +) + +// promFlags holds the connection options for the Prometheus datasource. +// Secrets are only accepted by file path so they never land in shell history +// or `ps` output. +type promFlags struct { + addr string + bearerFile string + basicUser string + basicPasswordFile string + caFile string + headers []string +} + +func (f *promFlags) register(cmd *cobra.Command) { + fl := cmd.Flags() + fl.StringVar(&f.addr, "prom", "http://localhost:9090", "Prometheus base URL") + fl.StringVar(&f.bearerFile, "prom-bearer-file", "", "file holding a bearer token for Prometheus") + fl.StringVar(&f.basicUser, "prom-basic-auth-user", "", "basic auth username for Prometheus") + fl.StringVar(&f.basicPasswordFile, "prom-basic-auth-password-file", "", "file holding the basic auth password") + fl.StringVar(&f.caFile, "prom-ca-file", "", "PEM CA bundle to verify the Prometheus server certificate") + fl.StringArrayVar(&f.headers, "prom-header", nil, + `extra request header as "Name: value", repeatable (e.g. "X-Scope-OrgID: team-a")`) +} + +// options translates the flags into datasource options. +func (f *promFlags) options() (prom.Options, error) { + h, err := parseHeaders(f.headers) + if err != nil { + return prom.Options{}, err + } + return prom.Options{ + BearerTokenFile: f.bearerFile, + BasicAuthUser: f.basicUser, + BasicAuthPasswordFile: f.basicPasswordFile, + CAFile: f.caFile, + Headers: h, + }, nil +} + +// client builds the datasource. With no connection options it uses the plain +// client exactly as before, so existing invocations are unaffected. +func (f *promFlags) client() (*prom.Client, error) { + o, err := f.options() + if err != nil { + return nil, err + } + if o.BearerTokenFile == "" && o.BasicAuthUser == "" && o.BasicAuthPasswordFile == "" && + o.CAFile == "" && len(o.Headers) == 0 { + return prom.New(f.addr) + } + return prom.NewWithOptions(f.addr, o) +} + +// parseHeaders turns repeated "Name: value" flags into an http.Header. +// Repeating a name adds another value. +func parseHeaders(raw []string) (http.Header, error) { + if len(raw) == 0 { + return nil, nil + } + h := http.Header{} + for _, r := range raw { + name, value, ok := strings.Cut(r, ":") + name, value = strings.TrimSpace(name), strings.TrimSpace(value) + if !ok || name == "" { + return nil, fmt.Errorf(`--prom-header %q: want "Name: value"`, r) + } + h.Add(name, value) + } + return h, nil +} diff --git a/cmd/grom/promflags_test.go b/cmd/grom/promflags_test.go new file mode 100644 index 0000000..f282f26 --- /dev/null +++ b/cmd/grom/promflags_test.go @@ -0,0 +1,57 @@ +package main + +import ( + "strings" + "testing" +) + +func TestParseHeaders(t *testing.T) { + tests := []struct { + name string + in []string + want map[string]string // canonical name -> comma-joined values + wantErr bool + }{ + {name: "none", in: nil, want: map[string]string{}}, + {name: "tenant", in: []string{"X-Scope-OrgID: team-a"}, want: map[string]string{"X-Scope-Orgid": "team-a"}}, + {name: "trims spaces", in: []string{" X-Foo : bar "}, want: map[string]string{"X-Foo": "bar"}}, + {name: "value with colon", in: []string{"X-Url: http://a:1"}, want: map[string]string{"X-Url": "http://a:1"}}, + {name: "repeated name adds value", in: []string{"X-A: 1", "x-a: 2"}, want: map[string]string{"X-A": "1,2"}}, + {name: "empty value allowed", in: []string{"X-Empty:"}, want: map[string]string{"X-Empty": ""}}, + {name: "missing colon", in: []string{"X-Scope-OrgID team-a"}, wantErr: true}, + {name: "empty name", in: []string{": v"}, wantErr: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + h, err := parseHeaders(tt.in) + if tt.wantErr { + if err == nil { + t.Fatal("want error, got nil") + } + return + } + if err != nil { + t.Fatalf("parseHeaders: %v", err) + } + if len(h) != len(tt.want) { + t.Fatalf("got %d headers %v, want %d", len(h), h, len(tt.want)) + } + for k, v := range tt.want { + if got := strings.Join(h.Values(k), ","); got != v { + t.Errorf("%s = %q, want %q", k, got, v) + } + } + }) + } +} + +func TestPromFlagsPlainClientWhenNoOptions(t *testing.T) { + f := promFlags{addr: "http://localhost:9090"} + if _, err := f.client(); err != nil { + t.Fatalf("client: %v", err) + } + f.basicUser = "only-user" + if _, err := f.client(); err == nil { + t.Fatal("want error for user without password file") + } +} diff --git a/cmd/grom/run.go b/cmd/grom/run.go index eca3cb7..0b995d5 100644 --- a/cmd/grom/run.go +++ b/cmd/grom/run.go @@ -10,7 +10,6 @@ import ( "github.com/qf-studio/grom/internal/app" "github.com/qf-studio/grom/internal/config" - "github.com/qf-studio/grom/internal/datasource/prom" "github.com/qf-studio/grom/internal/grafana" "github.com/qf-studio/grom/pkg/tui/theme" "github.com/qf-studio/grom/pkg/tui/widget" @@ -20,7 +19,7 @@ func runCmd() *cobra.Command { var ( cfgPath string grafanaPath string - promAddr string + pf promFlags themeName string ascii bool once bool @@ -34,7 +33,7 @@ func runCmd() *cobra.Command { if err != nil { return err } - ds, err := prom.New(promAddr) + ds, err := pf.client() if err != nil { return err } @@ -67,7 +66,7 @@ func runCmd() *cobra.Command { cmd.Flags().StringVarP(&cfgPath, "config", "c", "", "dashboard YAML config") cmd.Flags().StringVar(&grafanaPath, "grafana-json", "", "import a Grafana dashboard JSON instead of a YAML config") - cmd.Flags().StringVar(&promAddr, "prom", "http://localhost:9090", "Prometheus base URL") + pf.register(cmd) cmd.Flags().StringVar(&themeName, "theme", "", "override theme (default: config theme)") cmd.Flags().BoolVar(&ascii, "ascii", false, "block-character charts instead of braille") cmd.Flags().BoolVar(&once, "once", false, "render a single static frame and exit (no TUI)") diff --git a/internal/datasource/prom/options.go b/internal/datasource/prom/options.go new file mode 100644 index 0000000..e91cd07 --- /dev/null +++ b/internal/datasource/prom/options.go @@ -0,0 +1,146 @@ +package prom + +import ( + "crypto/tls" + "crypto/x509" + "errors" + "fmt" + "net/http" + "os" + "strings" + + promapi "github.com/prometheus/client_golang/api" + promv1 "github.com/prometheus/client_golang/api/prometheus/v1" +) + +// Options configures how the client authenticates to and verifies the +// Prometheus server. The zero value behaves exactly like New. +// +// Secrets are only taken from files. They are re-read on every request, so a +// rotated token or password is picked up without restarting grom. +type Options struct { + // BearerTokenFile holds a token sent as "Authorization: Bearer ". + BearerTokenFile string + // BasicAuthUser and BasicAuthPasswordFile enable HTTP basic auth. Both + // must be set together; they are mutually exclusive with BearerTokenFile. + BasicAuthUser string + BasicAuthPasswordFile string + // CAFile is a PEM bundle used instead of the system roots to verify the + // server certificate. + CAFile string + // Headers are added to every request, e.g. X-Scope-OrgID for + // multi-tenant backends such as Mimir, Cortex or Thanos. + Headers http.Header +} + +// NewWithOptions creates a client for addr using the auth, TLS and header +// settings in o. Credential files are checked once up front so a typo fails +// at startup rather than on the first refresh. +func NewWithOptions(addr string, o Options) (*Client, error) { + if err := o.validate(); err != nil { + return nil, err + } + rt, err := o.roundTripper() + if err != nil { + return nil, err + } + c, err := promapi.NewClient(promapi.Config{Address: addr, RoundTripper: rt}) + if err != nil { + return nil, fmt.Errorf("prometheus client %q: %w", addr, err) + } + return &Client{api: promv1.NewAPI(c)}, nil +} + +func (o Options) validate() error { + basic := o.BasicAuthUser != "" || o.BasicAuthPasswordFile != "" + if o.BearerTokenFile != "" && basic { + return errors.New("bearer token and basic auth are mutually exclusive") + } + if basic && (o.BasicAuthUser == "" || o.BasicAuthPasswordFile == "") { + return errors.New("basic auth needs both a user and a password file") + } + for name := range o.Headers { + if name == "" || strings.ContainsAny(name, " \t\r\n:") { + return fmt.Errorf("invalid header name %q", name) + } + if o.hasAuth() && http.CanonicalHeaderKey(name) == "Authorization" { + return errors.New("an authorization header conflicts with the bearer/basic auth options") + } + } + for _, f := range []string{o.BearerTokenFile, o.BasicAuthPasswordFile} { + if f == "" { + continue + } + if _, err := readSecret(f); err != nil { + return err + } + } + return nil +} + +func (o Options) hasAuth() bool { return o.BearerTokenFile != "" || o.BasicAuthUser != "" } + +func (o Options) roundTripper() (http.RoundTripper, error) { + base, ok := http.DefaultTransport.(*http.Transport) + if !ok { + return nil, errors.New("unexpected http.DefaultTransport type") + } + tr := base.Clone() + if o.CAFile != "" { + pem, err := os.ReadFile(o.CAFile) + if err != nil { + return nil, fmt.Errorf("read CA file: %w", err) + } + pool := x509.NewCertPool() + if !pool.AppendCertsFromPEM(pem) { + return nil, fmt.Errorf("CA file %q: no PEM certificates found", o.CAFile) + } + tr.TLSClientConfig = &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12} + } + return &authTransport{opts: o, next: tr}, nil +} + +// authTransport injects headers and credentials into each request. +type authTransport struct { + opts Options + next http.RoundTripper +} + +func (t *authTransport) RoundTrip(req *http.Request) (*http.Response, error) { + req = req.Clone(req.Context()) // RoundTrippers must not mutate the caller's request + for name, vals := range t.opts.Headers { + req.Header.Del(name) + for _, v := range vals { + req.Header.Add(name, v) + } + } + switch { + case t.opts.BearerTokenFile != "": + tok, err := readSecret(t.opts.BearerTokenFile) + if err != nil { + return nil, err + } + req.Header.Set("Authorization", "Bearer "+tok) + case t.opts.BasicAuthUser != "": + pw, err := readSecret(t.opts.BasicAuthPasswordFile) + if err != nil { + return nil, err + } + req.SetBasicAuth(t.opts.BasicAuthUser, pw) + } + return t.next.RoundTrip(req) +} + +// readSecret returns the trimmed contents of a credential file. The error +// names the file but never includes its contents. +func readSecret(path string) (string, error) { + b, err := os.ReadFile(path) + if err != nil { + return "", fmt.Errorf("read credential file: %w", err) + } + s := strings.TrimSpace(string(b)) + if s == "" { + return "", fmt.Errorf("credential file %q is empty", path) + } + return s, nil +} diff --git a/internal/datasource/prom/options_test.go b/internal/datasource/prom/options_test.go new file mode 100644 index 0000000..02969d5 --- /dev/null +++ b/internal/datasource/prom/options_test.go @@ -0,0 +1,205 @@ +package prom + +import ( + "context" + "encoding/pem" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + + "github.com/qf-studio/grom/internal/datasource" +) + +const emptyVector = `{"status":"success","data":{"resultType":"vector","result":[]}}` + +// headerRecorder is a Prometheus-shaped server that records the headers of +// the last request it saw. +type headerRecorder struct { + mu sync.Mutex + last http.Header +} + +func (h *headerRecorder) handler(w http.ResponseWriter, r *http.Request) { + h.mu.Lock() + h.last = r.Header.Clone() + h.mu.Unlock() + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(emptyVector)) +} + +func (h *headerRecorder) get() http.Header { + h.mu.Lock() + defer h.mu.Unlock() + return h.last +} + +func writeFile(t *testing.T, name, content string) string { + t.Helper() + p := filepath.Join(t.TempDir(), name) + if err := os.WriteFile(p, []byte(content), 0o600); err != nil { + t.Fatal(err) + } + return p +} + +func query(t *testing.T, c *Client) error { + t.Helper() + _, err := c.QueryInstant(context.Background(), datasource.Instant{Expr: "up"}) + return err +} + +func TestNewWithOptionsSendsCredentialsAndHeaders(t *testing.T) { + token := writeFile(t, "token", "s3cr3t-token\n") // trailing newline is trimmed + pass := writeFile(t, "pass", "hunter2") + + tests := []struct { + name string + opts Options + want map[string][]string + }{ + { + name: "bearer token from file", + opts: Options{BearerTokenFile: token}, + want: map[string][]string{"Authorization": {"Bearer s3cr3t-token"}}, + }, + { + name: "basic auth", + opts: Options{BasicAuthUser: "grom", BasicAuthPasswordFile: pass}, + // base64("grom:hunter2") + want: map[string][]string{"Authorization": {"Basic Z3JvbTpodW50ZXIy"}}, + }, + { + name: "tenant header", + opts: Options{Headers: http.Header{"X-Scope-Orgid": {"team-a"}}}, + want: map[string][]string{"X-Scope-Orgid": {"team-a"}}, + }, + { + name: "multi-value header plus bearer", + opts: Options{ + BearerTokenFile: token, + Headers: http.Header{"X-Scope-Orgid": {"team-a", "team-b"}}, + }, + want: map[string][]string{ + "Authorization": {"Bearer s3cr3t-token"}, + "X-Scope-Orgid": {"team-a", "team-b"}, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + rec := &headerRecorder{} + srv := httptest.NewServer(http.HandlerFunc(rec.handler)) + defer srv.Close() + + c, err := NewWithOptions(srv.URL, tt.opts) + if err != nil { + t.Fatalf("NewWithOptions: %v", err) + } + if err := query(t, c); err != nil { + t.Fatalf("query: %v", err) + } + got := rec.get() + for k, want := range tt.want { + if g := got.Values(k); strings.Join(g, ",") != strings.Join(want, ",") { + t.Errorf("header %s = %q, want %q", k, g, want) + } + } + }) + } +} + +func TestNewWithOptionsRereadsRotatedToken(t *testing.T) { + rec := &headerRecorder{} + srv := httptest.NewServer(http.HandlerFunc(rec.handler)) + defer srv.Close() + + token := writeFile(t, "token", "old") + c, err := NewWithOptions(srv.URL, Options{BearerTokenFile: token}) + if err != nil { + t.Fatalf("NewWithOptions: %v", err) + } + if err := query(t, c); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(token, []byte("new"), 0o600); err != nil { + t.Fatal(err) + } + if err := query(t, c); err != nil { + t.Fatal(err) + } + if got := rec.get().Get("Authorization"); got != "Bearer new" { + t.Errorf("after rotation Authorization = %q, want %q", got, "Bearer new") + } +} + +func TestNewWithOptionsCAFile(t *testing.T) { + srv := httptest.NewTLSServer(http.HandlerFunc((&headerRecorder{}).handler)) + defer srv.Close() + + // Without the CA the self-signed test cert must be rejected. + c, err := NewWithOptions(srv.URL, Options{}) + if err != nil { + t.Fatalf("NewWithOptions: %v", err) + } + if err := query(t, c); err == nil { + t.Fatal("query without CA: want certificate error, got nil") + } + + caPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw}) + c, err = NewWithOptions(srv.URL, Options{CAFile: writeFile(t, "ca.pem", string(caPEM))}) + if err != nil { + t.Fatalf("NewWithOptions with CA: %v", err) + } + if err := query(t, c); err != nil { + t.Fatalf("query with CA: %v", err) + } +} + +func TestNewWithOptionsErrors(t *testing.T) { + token := writeFile(t, "token", "x") + empty := writeFile(t, "empty", " \n") + notPEM := writeFile(t, "ca.pem", "not a certificate") + missing := filepath.Join(t.TempDir(), "missing") + + tests := []struct { + name string + opts Options + wantErr string + }{ + {"bearer and basic", Options{BearerTokenFile: token, BasicAuthUser: "u", BasicAuthPasswordFile: token}, "mutually exclusive"}, + {"user without password", Options{BasicAuthUser: "u"}, "both a user and a password file"}, + {"password without user", Options{BasicAuthPasswordFile: token}, "both a user and a password file"}, + {"missing token file", Options{BearerTokenFile: missing}, "read credential file"}, + {"empty token file", Options{BearerTokenFile: empty}, "is empty"}, + {"bad CA file", Options{CAFile: notPEM}, "no PEM certificates"}, + {"missing CA file", Options{CAFile: missing}, "read CA file"}, + {"bad header name", Options{Headers: http.Header{"Bad Name": {"v"}}}, "invalid header name"}, + {"authorization header with auth", Options{BearerTokenFile: token, Headers: http.Header{"Authorization": {"x"}}}, "conflicts"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := NewWithOptions("http://localhost:9090", tt.opts) + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("err = %v, want containing %q", err, tt.wantErr) + } + }) + } +} + +func TestCredentialErrorsDoNotLeakSecrets(t *testing.T) { + // A file that exists but is empty after trimming must not echo its content; + // a readable secret must never appear in any error we return. + secret := "do-not-print-me" + p := writeFile(t, "token", secret) + _, err := NewWithOptions("http://localhost:9090", Options{BearerTokenFile: p, BasicAuthUser: "u", BasicAuthPasswordFile: p}) + if err == nil { + t.Fatal("want error") + } + if strings.Contains(err.Error(), secret) { + t.Fatalf("error leaks secret: %v", err) + } +}