Phase 4: real per-tenant ClickHouse isolation via a new enterprise-api binary

Closes the threat model's headline finding for the SQL query path:
enterprise/internal/tenantprovision does real CREATE DATABASE/USER/GRANT
against ClickHouse, and enterprise/internal/chrunner is a per-tenant
connection registry implementing api's SQLRunner interface, resolving
the tenant from the authenticated request identity -- never a
caller-suppliable parameter. Both are wired into a new binary,
enterprise/cmd/enterprise-api, alongside the unchanged single-tenant
api/cmd/api, since AGPL core can never import enterprise/ and Go's own
internal/ package visibility rules meant enterprise/ couldn't implement
core's SQLRunner interface without importing the package that defines
it. That required moving api/internal/{authz,queryapi,dashboards,
querylang/executor,searchclient,httpserver} out of internal/ -- the
minimal set enterprise-api needs to import; querylang's compiler
internals (planner/lexer/parser/ast/ir) and api's own config stay
internal, since nothing outside api needs them directly.

Also finally wires enterprise/internal/audit into queryapi.AuditLogger
(nil since Phase 4 task 4) via a new adapter, and adds live-ClickHouse
integration tests for two of the four adversarial probes named in
docs/phase-4-isolation-design.md's verification plan.

Corrected several overclaims in the docs while writing this up: an
earlier claim that rbacstore's CRUD was "verified against a live
Postgres" was never actually true in this environment (only
internal/audit was, earlier in this phase, before Docker access was
lost) -- threat-model.md, phase-4-runbook.md, CLAUDE.md, and
enterprise/README.md all now distinguish "a real integration test
exists" from "this was confirmed against a live database."

Still not built: Tantivy/free-text tenant isolation
(enterprise/internal/searchclient), and any deployment-topology
mechanism that actually routes traffic to enterprise-api instead of
plain api -- both binaries exist side by side today with nothing
enforcing or flagging which one a deployment runs.
This commit is contained in:
2026-08-13 22:48:38 -07:00
parent 3eb0f4c589
commit 1d57e697b1
49 changed files with 2003 additions and 237 deletions
+246
View File
@@ -0,0 +1,246 @@
package dashboards
import (
"context"
"encoding/json"
"errors"
"log/slog"
"net/http"
"github.com/sentry/sentry/api/authz"
)
// store is the narrow interface Handler depends on -- *Store (store.go)
// is the production implementation; tests use a fake, same pattern as
// queryapi's SQLRunner/SearchClient. Every method except Create/Import
// takes a tenantID -- see store.go's doc comment for why.
type store interface {
CreateDashboard(ctx context.Context, d *Dashboard) error
ListDashboards(ctx context.Context, tenantID string) ([]Dashboard, error)
GetDashboard(ctx context.Context, tenantID, id string) (*Dashboard, error)
UpdateDashboard(ctx context.Context, tenantID string, d *Dashboard) error
DeleteDashboard(ctx context.Context, tenantID, id string) error
AddPanel(ctx context.Context, tenantID, dashboardID string, p *Panel) error
UpdatePanel(ctx context.Context, tenantID string, p *Panel) error
DeletePanel(ctx context.Context, tenantID, dashboardID, panelID string) error
ImportDashboard(ctx context.Context, tenantID string, d *Dashboard) (*Dashboard, error)
}
type Handler struct {
logger *slog.Logger
store store
authorizer authz.Authorizer
}
func NewHandler(logger *slog.Logger, store store, authorizer authz.Authorizer) *Handler {
return &Handler{logger: logger, store: store, authorizer: authorizer}
}
// RegisterRoutes wires the RBAC minimum-role bar from
// /docs/phase-4-rbac-design.md's matrix. Note what's NOT enforced here
// yet: the matrix's "(own/granted)" qualifier for Editor create/edit/
// delete requires the dashboard_permissions/ownership lookup that
// enterprise/internal/rbacstore hasn't been built yet -- until then,
// RoleEditor is necessary but not sufficient per the matrix, and every
// Editor can act on every dashboard *within their own tenant* (tenant
// scoping itself -- a different, more basic property than the
// per-resource "(own/granted)" qualifier -- is enforced, via tenantID
// below and store.go's WHERE tenant_id = ... filtering). Tracked as
// follow-up, not silently dropped.
func (h *Handler) RegisterRoutes(mux *http.ServeMux) {
mux.HandleFunc("POST /dashboards", authz.RequireRole(h.authorizer, authz.RoleEditor, h.handleCreate))
mux.HandleFunc("GET /dashboards", authz.RequireRole(h.authorizer, authz.RoleViewer, h.handleList))
mux.HandleFunc("POST /dashboards/import", authz.RequireRole(h.authorizer, authz.RoleEditor, h.handleImport))
mux.HandleFunc("GET /dashboards/{id}", authz.RequireRole(h.authorizer, authz.RoleViewer, h.handleGet))
mux.HandleFunc("PUT /dashboards/{id}", authz.RequireRole(h.authorizer, authz.RoleEditor, h.handleUpdate))
mux.HandleFunc("DELETE /dashboards/{id}", authz.RequireRole(h.authorizer, authz.RoleEditor, h.handleDelete))
mux.HandleFunc("GET /dashboards/{id}/export", authz.RequireRole(h.authorizer, authz.RoleViewer, h.handleExport))
mux.HandleFunc("POST /dashboards/{id}/panels", authz.RequireRole(h.authorizer, authz.RoleEditor, h.handleAddPanel))
mux.HandleFunc("PUT /dashboards/{id}/panels/{panelId}", authz.RequireRole(h.authorizer, authz.RoleEditor, h.handleUpdatePanel))
mux.HandleFunc("DELETE /dashboards/{id}/panels/{panelId}", authz.RequireRole(h.authorizer, authz.RoleEditor, h.handleDeletePanel))
}
const maxBodyBytes = 1 << 20 // 1 MiB, same cap as queryapi
// tenantID resolves the tenant to scope a request's store calls to --
// from the authenticated identity RequireRole attached to the request
// context, never from a client-supplied field (a Dashboard JSON body
// can set "tenant_id" to anything; store.go's methods only ever see the
// value this function returns, not that field). Falls back to
// "default" when no identity is present (nil authorizer -- matches
// every other nil-authorizer-is-Phase-0-3-single-tenant default in this
// codebase) or when a resolved identity somehow carries no tenant (only
// RoleService identities can, per authz.Identity's doc comment, and
// RequireRole -- unlike RequireRoleOrService -- never admits RoleService,
// so this branch is a defensive fallback, not an expected path).
func (h *Handler) tenantID(r *http.Request) string {
if id, ok := authz.IdentityFromContext(r.Context()); ok && id.TenantID != "" {
return id.TenantID
}
return "default"
}
func (h *Handler) handleCreate(w http.ResponseWriter, r *http.Request) {
var d Dashboard
if !decodeJSON(w, r, &d) {
return
}
if d.Name == "" {
writeError(w, http.StatusBadRequest, "name must not be empty")
return
}
// Overrides any client-supplied tenant_id -- see tenantID's doc comment.
d.TenantID = h.tenantID(r)
if err := h.store.CreateDashboard(r.Context(), &d); err != nil {
h.logger.Error("creating dashboard", "error", err)
writeError(w, http.StatusInternalServerError, "creating dashboard failed")
return
}
writeJSON(w, http.StatusCreated, d)
}
func (h *Handler) handleList(w http.ResponseWriter, r *http.Request) {
list, err := h.store.ListDashboards(r.Context(), h.tenantID(r))
if err != nil {
h.logger.Error("listing dashboards", "error", err)
writeError(w, http.StatusInternalServerError, "listing dashboards failed")
return
}
writeJSON(w, http.StatusOK, list)
}
func (h *Handler) handleGet(w http.ResponseWriter, r *http.Request) {
d, err := h.store.GetDashboard(r.Context(), h.tenantID(r), r.PathValue("id"))
if err != nil {
h.writeStoreErr(w, err, "fetching dashboard")
return
}
writeJSON(w, http.StatusOK, d)
}
func (h *Handler) handleExport(w http.ResponseWriter, r *http.Request) {
// Export is the same document GET /dashboards/{id} returns -- the
// import endpoint below consumes exactly this shape, and so does
// `sentryctl dashboards apply`, so there's one JSON contract used
// from every call site rather than a bespoke export format.
h.handleGet(w, r)
}
func (h *Handler) handleImport(w http.ResponseWriter, r *http.Request) {
var d Dashboard
if !decodeJSON(w, r, &d) {
return
}
if d.Name == "" {
writeError(w, http.StatusBadRequest, "name must not be empty")
return
}
imported, err := h.store.ImportDashboard(r.Context(), h.tenantID(r), &d)
if err != nil {
h.logger.Error("importing dashboard", "error", err)
writeError(w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, http.StatusCreated, imported)
}
func (h *Handler) handleUpdate(w http.ResponseWriter, r *http.Request) {
var d Dashboard
if !decodeJSON(w, r, &d) {
return
}
if d.Name == "" {
writeError(w, http.StatusBadRequest, "name must not be empty")
return
}
d.ID = r.PathValue("id")
if err := h.store.UpdateDashboard(r.Context(), h.tenantID(r), &d); err != nil {
h.writeStoreErr(w, err, "updating dashboard")
return
}
writeJSON(w, http.StatusOK, d)
}
func (h *Handler) handleDelete(w http.ResponseWriter, r *http.Request) {
if err := h.store.DeleteDashboard(r.Context(), h.tenantID(r), r.PathValue("id")); err != nil {
h.writeStoreErr(w, err, "deleting dashboard")
return
}
w.WriteHeader(http.StatusNoContent)
}
func (h *Handler) handleAddPanel(w http.ResponseWriter, r *http.Request) {
var p Panel
if !decodeJSON(w, r, &p) {
return
}
if err := validatePanel(&p); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if err := h.store.AddPanel(r.Context(), h.tenantID(r), r.PathValue("id"), &p); err != nil {
h.writeStoreErr(w, err, "adding panel")
return
}
writeJSON(w, http.StatusCreated, p)
}
func (h *Handler) handleUpdatePanel(w http.ResponseWriter, r *http.Request) {
var p Panel
if !decodeJSON(w, r, &p) {
return
}
if err := validatePanel(&p); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
p.ID = r.PathValue("panelId")
p.DashboardID = r.PathValue("id")
if err := h.store.UpdatePanel(r.Context(), h.tenantID(r), &p); err != nil {
h.writeStoreErr(w, err, "updating panel")
return
}
writeJSON(w, http.StatusOK, p)
}
func (h *Handler) handleDeletePanel(w http.ResponseWriter, r *http.Request) {
if err := h.store.DeletePanel(r.Context(), h.tenantID(r), r.PathValue("id"), r.PathValue("panelId")); err != nil {
h.writeStoreErr(w, err, "deleting panel")
return
}
w.WriteHeader(http.StatusNoContent)
}
func (h *Handler) writeStoreErr(w http.ResponseWriter, err error, action string) {
if errors.Is(err, ErrNotFound) {
writeError(w, http.StatusNotFound, "not found")
return
}
h.logger.Error(action, "error", err)
writeError(w, http.StatusInternalServerError, action+" failed")
}
func decodeJSON(w http.ResponseWriter, r *http.Request, v any) bool {
r.Body = http.MaxBytesReader(w, r.Body, maxBodyBytes)
if err := json.NewDecoder(r.Body).Decode(v); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body: "+err.Error())
return false
}
return true
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
type errorResponse struct {
Error string `json:"error"`
}
func writeError(w http.ResponseWriter, status int, msg string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(errorResponse{Error: msg})
}
+464
View File
@@ -0,0 +1,464 @@
package dashboards
import (
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/sentry/sentry/api/authz"
)
// fakeStore enforces tenant scoping the same way store.go's real
// pgx-backed Store does (a mismatched tenantID behaves exactly like a
// missing ID -- ErrNotFound, never a distinguishable "found but wrong
// tenant" error) so handler_test.go's cross-tenant tests exercise real
// behavior, not a fake that happens to always agree.
type fakeStore struct {
dashboards map[string]*Dashboard
createErr error
importErr error
}
func newFakeStore() *fakeStore {
return &fakeStore{dashboards: map[string]*Dashboard{}}
}
func (f *fakeStore) CreateDashboard(_ context.Context, d *Dashboard) error {
if f.createErr != nil {
return f.createErr
}
d.ID = "dash-1"
f.dashboards[d.ID] = d
return nil
}
func (f *fakeStore) ListDashboards(_ context.Context, tenantID string) ([]Dashboard, error) {
var out []Dashboard
for _, d := range f.dashboards {
if d.TenantID == tenantID {
out = append(out, *d)
}
}
return out, nil
}
func (f *fakeStore) GetDashboard(_ context.Context, tenantID, id string) (*Dashboard, error) {
d, ok := f.dashboards[id]
if !ok || d.TenantID != tenantID {
return nil, ErrNotFound
}
return d, nil
}
func (f *fakeStore) UpdateDashboard(_ context.Context, tenantID string, d *Dashboard) error {
existing, ok := f.dashboards[d.ID]
if !ok || existing.TenantID != tenantID {
return ErrNotFound
}
panels := existing.Panels
*existing = *d
existing.TenantID = tenantID
existing.Panels = panels
return nil
}
func (f *fakeStore) DeleteDashboard(_ context.Context, tenantID, id string) error {
d, ok := f.dashboards[id]
if !ok || d.TenantID != tenantID {
return ErrNotFound
}
delete(f.dashboards, id)
return nil
}
func (f *fakeStore) AddPanel(_ context.Context, tenantID, dashboardID string, p *Panel) error {
d, ok := f.dashboards[dashboardID]
if !ok || d.TenantID != tenantID {
return ErrNotFound
}
p.ID = "panel-1"
p.DashboardID = dashboardID
d.Panels = append(d.Panels, *p)
return nil
}
func (f *fakeStore) UpdatePanel(_ context.Context, tenantID string, p *Panel) error {
d, ok := f.dashboards[p.DashboardID]
if !ok || d.TenantID != tenantID {
return ErrNotFound
}
for i := range d.Panels {
if d.Panels[i].ID == p.ID {
d.Panels[i] = *p
return nil
}
}
return ErrNotFound
}
func (f *fakeStore) DeletePanel(_ context.Context, tenantID, dashboardID, panelID string) error {
d, ok := f.dashboards[dashboardID]
if !ok || d.TenantID != tenantID {
return ErrNotFound
}
for i := range d.Panels {
if d.Panels[i].ID == panelID {
d.Panels = append(d.Panels[:i], d.Panels[i+1:]...)
return nil
}
}
return ErrNotFound
}
func (f *fakeStore) ImportDashboard(_ context.Context, tenantID string, d *Dashboard) (*Dashboard, error) {
if f.importErr != nil {
return nil, f.importErr
}
imported := *d
imported.ID = "dash-imported"
imported.TenantID = tenantID
f.dashboards[imported.ID] = &imported
return &imported, nil
}
func newTestMux(fs *fakeStore) *http.ServeMux {
h := NewHandler(slog.New(slog.NewTextHandler(io.Discard, nil)), fs, nil)
mux := http.NewServeMux()
h.RegisterRoutes(mux)
return mux
}
// fakeAuthorizer resolves every request to a fixed identity -- used by
// the cross-tenant tests below, which need a real (non-nil) authorizer
// so tenantID(r) reads from the resolved identity instead of falling
// back to "default" for every request.
type fakeAuthorizer struct {
identity authz.Identity
}
func (f *fakeAuthorizer) Authorize(*http.Request) (authz.Identity, error) {
return f.identity, nil
}
func newTestMuxWithTenant(fs *fakeStore, tenantID string) *http.ServeMux {
h := NewHandler(slog.New(slog.NewTextHandler(io.Discard, nil)), fs,
&fakeAuthorizer{identity: authz.Identity{TenantID: tenantID, Role: authz.RoleOwner}})
mux := http.NewServeMux()
h.RegisterRoutes(mux)
return mux
}
func doRequest(t *testing.T, mux *http.ServeMux, method, path, body string) *httptest.ResponseRecorder {
t.Helper()
var r io.Reader
if body != "" {
r = strings.NewReader(body)
}
req := httptest.NewRequest(method, path, r)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
return rec
}
func TestCreateDashboard(t *testing.T) {
mux := newTestMux(newFakeStore())
rec := doRequest(t, mux, http.MethodPost, "/dashboards", `{"name": "Overview"}`)
if rec.Code != http.StatusCreated {
t.Fatalf("status = %d, want 201; body=%s", rec.Code, rec.Body.String())
}
var got Dashboard
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
t.Fatalf("decoding response: %v", err)
}
if got.ID == "" {
t.Fatalf("expected an assigned ID, got empty")
}
}
// TestCreateDashboardIgnoresClientSuppliedTenantID is the regression
// test for the tenant-spoofing gap found during Phase 4 task 7 (see
// /docs/security/threat-model.md's "application-layer tenant scoping"
// section): Dashboard.TenantID has a `json:"tenant_id"` tag, so a
// request body can set it to anything. The handler must always
// overwrite it from the authenticated identity, never trust the body.
func TestCreateDashboardIgnoresClientSuppliedTenantID(t *testing.T) {
fs := newFakeStore()
mux := newTestMuxWithTenant(fs, "acme")
rec := doRequest(t, mux, http.MethodPost, "/dashboards", `{"name": "Overview", "tenant_id": "globex"}`)
if rec.Code != http.StatusCreated {
t.Fatalf("status = %d, want 201; body=%s", rec.Code, rec.Body.String())
}
if fs.dashboards["dash-1"].TenantID != "acme" {
t.Fatalf("stored TenantID = %q, want %q (the authenticated identity's tenant, not the client-supplied value)", fs.dashboards["dash-1"].TenantID, "acme")
}
}
func TestCreateDashboardRejectsEmptyName(t *testing.T) {
mux := newTestMux(newFakeStore())
rec := doRequest(t, mux, http.MethodPost, "/dashboards", `{"name": ""}`)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400", rec.Code)
}
}
func TestGetDashboardNotFound(t *testing.T) {
mux := newTestMux(newFakeStore())
rec := doRequest(t, mux, http.MethodGet, "/dashboards/nope", "")
if rec.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404", rec.Code)
}
}
// TestCrossTenantGetIsNotFound is the core adversarial case: a request
// authenticated as tenant "globex" must not be able to read a dashboard
// that belongs to tenant "acme" -- and the response must be a plain 404
// (not a 403, which would confirm the ID exists under a different
// tenant).
func TestCrossTenantGetIsNotFound(t *testing.T) {
fs := newFakeStore()
fs.dashboards["dash-1"] = &Dashboard{ID: "dash-1", TenantID: "acme", Name: "Acme's dashboard"}
mux := newTestMuxWithTenant(fs, "globex")
rec := doRequest(t, mux, http.MethodGet, "/dashboards/dash-1", "")
if rec.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404 (cross-tenant read must not succeed or leak existence via a different status)", rec.Code)
}
}
func TestCrossTenantListDoesNotLeakOtherTenants(t *testing.T) {
fs := newFakeStore()
fs.dashboards["dash-1"] = &Dashboard{ID: "dash-1", TenantID: "acme", Name: "Acme's dashboard"}
fs.dashboards["dash-2"] = &Dashboard{ID: "dash-2", TenantID: "globex", Name: "Globex's dashboard"}
mux := newTestMuxWithTenant(fs, "globex")
rec := doRequest(t, mux, http.MethodGet, "/dashboards", "")
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
}
var got []Dashboard
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
t.Fatalf("decoding response: %v", err)
}
if len(got) != 1 || got[0].ID != "dash-2" {
t.Fatalf("expected only globex's own dashboard, got %+v", got)
}
}
func TestCrossTenantUpdateIsNotFound(t *testing.T) {
fs := newFakeStore()
fs.dashboards["dash-1"] = &Dashboard{ID: "dash-1", TenantID: "acme", Name: "Acme's dashboard"}
mux := newTestMuxWithTenant(fs, "globex")
rec := doRequest(t, mux, http.MethodPut, "/dashboards/dash-1", `{"name": "Hijacked"}`)
if rec.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404", rec.Code)
}
if fs.dashboards["dash-1"].Name != "Acme's dashboard" {
t.Fatalf("cross-tenant update must not modify the row, got Name = %q", fs.dashboards["dash-1"].Name)
}
}
func TestCrossTenantDeleteIsNotFound(t *testing.T) {
fs := newFakeStore()
fs.dashboards["dash-1"] = &Dashboard{ID: "dash-1", TenantID: "acme", Name: "Acme's dashboard"}
mux := newTestMuxWithTenant(fs, "globex")
rec := doRequest(t, mux, http.MethodDelete, "/dashboards/dash-1", "")
if rec.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404", rec.Code)
}
if _, ok := fs.dashboards["dash-1"]; !ok {
t.Fatalf("cross-tenant delete must not remove the row")
}
}
func TestCrossTenantAddPanelIsNotFound(t *testing.T) {
fs := newFakeStore()
fs.dashboards["dash-1"] = &Dashboard{ID: "dash-1", TenantID: "acme", Name: "Acme's dashboard"}
mux := newTestMuxWithTenant(fs, "globex")
rec := doRequest(t, mux, http.MethodPost, "/dashboards/dash-1/panels",
`{"query": "service=api", "viz_type": "table"}`)
if rec.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404; body=%s", rec.Code, rec.Body.String())
}
if len(fs.dashboards["dash-1"].Panels) != 0 {
t.Fatalf("cross-tenant AddPanel must not attach a panel to the other tenant's dashboard")
}
}
func TestAddPanelRejectsRawSQL(t *testing.T) {
fs := newFakeStore()
fs.dashboards["dash-1"] = &Dashboard{ID: "dash-1", TenantID: "default", Name: "Overview"}
mux := newTestMux(fs)
rec := doRequest(t, mux, http.MethodPost, "/dashboards/dash-1/panels",
`{"query": "SELECT 1", "query_language": "sql", "viz_type": "table"}`)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400; body=%s", rec.Code, rec.Body.String())
}
}
func TestAddPanelRejectsInvalidVizType(t *testing.T) {
fs := newFakeStore()
fs.dashboards["dash-1"] = &Dashboard{ID: "dash-1", TenantID: "default", Name: "Overview"}
mux := newTestMux(fs)
rec := doRequest(t, mux, http.MethodPost, "/dashboards/dash-1/panels",
`{"query": "service=api", "viz_type": "pie"}`)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400; body=%s", rec.Code, rec.Body.String())
}
}
func TestAddPanelSuccess(t *testing.T) {
fs := newFakeStore()
fs.dashboards["dash-1"] = &Dashboard{ID: "dash-1", TenantID: "default", Name: "Overview"}
mux := newTestMux(fs)
rec := doRequest(t, mux, http.MethodPost, "/dashboards/dash-1/panels",
`{"title": "Errors", "query": "service=api | stats count by host", "viz_type": "line", "width": 6, "height": 4}`)
if rec.Code != http.StatusCreated {
t.Fatalf("status = %d, want 201; body=%s", rec.Code, rec.Body.String())
}
if len(fs.dashboards["dash-1"].Panels) != 1 {
t.Fatalf("expected 1 panel stored, got %d", len(fs.dashboards["dash-1"].Panels))
}
}
func TestUpdateDashboardChangesTimeRange(t *testing.T) {
fs := newFakeStore()
fs.dashboards["dash-1"] = &Dashboard{ID: "dash-1", TenantID: "default", Name: "Overview", DefaultEarliest: "-1h", DefaultLatest: "now"}
mux := newTestMux(fs)
rec := doRequest(t, mux, http.MethodPut, "/dashboards/dash-1",
`{"name": "Overview", "default_earliest": "-24h", "default_latest": "now"}`)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
}
if fs.dashboards["dash-1"].DefaultEarliest != "-24h" {
t.Fatalf("expected default_earliest to be updated, got %q", fs.dashboards["dash-1"].DefaultEarliest)
}
}
func TestUpdateDashboardNotFound(t *testing.T) {
mux := newTestMux(newFakeStore())
rec := doRequest(t, mux, http.MethodPut, "/dashboards/nope", `{"name": "Overview"}`)
if rec.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404", rec.Code)
}
}
func TestDeleteDashboard(t *testing.T) {
fs := newFakeStore()
fs.dashboards["dash-1"] = &Dashboard{ID: "dash-1", TenantID: "default", Name: "Overview"}
mux := newTestMux(fs)
rec := doRequest(t, mux, http.MethodDelete, "/dashboards/dash-1", "")
if rec.Code != http.StatusNoContent {
t.Fatalf("status = %d, want 204", rec.Code)
}
if _, ok := fs.dashboards["dash-1"]; ok {
t.Fatalf("expected dashboard to be deleted")
}
}
func TestExportThenImportRoundTrips(t *testing.T) {
fs := newFakeStore()
fs.dashboards["dash-1"] = &Dashboard{
ID: "dash-1", TenantID: "default", Name: "Overview",
Panels: []Panel{{ID: "panel-1", DashboardID: "dash-1", Query: "service=api", VizType: VizTable}},
}
mux := newTestMux(fs)
exportRec := doRequest(t, mux, http.MethodGet, "/dashboards/dash-1/export", "")
if exportRec.Code != http.StatusOK {
t.Fatalf("export status = %d, want 200", exportRec.Code)
}
importRec := doRequest(t, mux, http.MethodPost, "/dashboards/import", exportRec.Body.String())
if importRec.Code != http.StatusCreated {
t.Fatalf("import status = %d, want 201; body=%s", importRec.Code, importRec.Body.String())
}
var imported Dashboard
if err := json.Unmarshal(importRec.Body.Bytes(), &imported); err != nil {
t.Fatalf("decoding import response: %v", err)
}
if imported.ID == "dash-1" {
t.Fatalf("expected import to assign a fresh ID, got the source ID back")
}
}
// TestImportIgnoresExportedTenantID: an exported dashboard JSON file
// carries whatever tenant_id it was exported from -- importing it into
// a different tenant's session must assign it to the *importing*
// tenant, never silently move it to the tenant named in the file.
func TestImportIgnoresExportedTenantID(t *testing.T) {
fs := newFakeStore()
mux := newTestMuxWithTenant(fs, "globex")
rec := doRequest(t, mux, http.MethodPost, "/dashboards/import",
`{"name": "Imported", "tenant_id": "acme"}`)
if rec.Code != http.StatusCreated {
t.Fatalf("status = %d, want 201; body=%s", rec.Code, rec.Body.String())
}
var imported Dashboard
if err := json.Unmarshal(rec.Body.Bytes(), &imported); err != nil {
t.Fatalf("decoding response: %v", err)
}
if imported.TenantID != "globex" {
t.Fatalf("imported TenantID = %q, want %q (the importing identity's tenant)", imported.TenantID, "globex")
}
}
func TestCreateDashboardStoreErrorReturns500(t *testing.T) {
fs := newFakeStore()
fs.createErr = errors.New("boom")
mux := newTestMux(fs)
rec := doRequest(t, mux, http.MethodPost, "/dashboards", `{"name": "Overview"}`)
if rec.Code != http.StatusInternalServerError {
t.Fatalf("status = %d, want 500", rec.Code)
}
}
// TestServiceIdentityCannotAccessDashboards is the other half of the
// service-identity boundary (the /query half is
// api/queryapi's own tests) -- api/authz's own tests
// already prove RequireRole rejects RoleService in isolation
// (TestRequireRolePlainDoesNotAllowService); this proves it holds
// through the real dashboards handler, wired the way it's actually
// deployed, not just the middleware function in isolation. A defect
// here would mean /alerting's service token -- meant only for POST
// /query -- could also read/write dashboards, which was never the
// intent (dashboards uses plain RequireRole, not RequireRoleOrService,
// specifically to keep this door shut).
func TestServiceIdentityCannotAccessDashboards(t *testing.T) {
fs := newFakeStore()
fs.dashboards["dash-1"] = &Dashboard{ID: "dash-1", TenantID: "default", Name: "Overview"}
h := NewHandler(slog.New(slog.NewTextHandler(io.Discard, nil)), fs,
&fakeAuthorizer{identity: authz.Identity{Role: authz.RoleService}})
mux := http.NewServeMux()
h.RegisterRoutes(mux)
for _, tt := range []struct {
method, path, body string
}{
{http.MethodGet, "/dashboards", ""},
{http.MethodGet, "/dashboards/dash-1", ""},
{http.MethodPost, "/dashboards", `{"name": "New"}`},
{http.MethodDelete, "/dashboards/dash-1", ""},
} {
rec := doRequest(t, mux, tt.method, tt.path, tt.body)
if rec.Code != http.StatusForbidden {
t.Errorf("%s %s: status = %d, want 403 (RoleService must never access dashboards)", tt.method, tt.path, rec.Code)
}
}
}
+316
View File
@@ -0,0 +1,316 @@
package dashboards
import (
"context"
"errors"
"fmt"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// ErrNotFound is returned by Get/Delete when the id doesn't exist --
// including when it exists but belongs to a different tenant (see this
// file's tenant-scoping comment below): a 404 either way, never a 403
// that would confirm cross-tenant existence.
var ErrNotFound = errors.New("not found")
// Store is the pgx-backed CRUD implementation. IDs are assigned
// server-side (google/uuid), matching how /ingest assigns record_id --
// one place (Go) generates IDs, not split between the app and the
// database via a Postgres extension.
//
// Every method below except CreateDashboard/ImportDashboard takes a
// tenantID and filters by it (`WHERE ... AND tenant_id = $N`, or a join
// through dashboards for the panel methods, since dashboard_panels has
// no tenant_id column of its own). This is Phase 4 task 5/8 tenant
// scoping, added after the authz RBAC wiring shipped without it -- see
// /docs/security/threat-model.md's "application-layer tenant scoping"
// section for why that gap mattered even with RBAC live: a role check
// alone answers "is this identity allowed to edit *some* dashboard,"
// not "is this identity allowed to touch *this* dashboard." The
// handler (handler.go) resolves tenantID from the authenticated
// identity (authz.IdentityFromContext) -- never from a client-supplied
// request field, since Dashboard.TenantID is a JSON field a request
// body can set arbitrarily.
type Store struct {
pool *pgxpool.Pool
}
func NewStore(pool *pgxpool.Pool) *Store {
return &Store{pool: pool}
}
// CreateDashboard trusts d.TenantID -- callers (handler.go) must set it
// from the authenticated identity before calling, never from client
// input. Not itself tenant-scoped (there's nothing to scope against
// yet; the row doesn't exist).
func (s *Store) CreateDashboard(ctx context.Context, d *Dashboard) error {
d.ID = uuid.NewString()
if d.TenantID == "" {
d.TenantID = "default"
}
if d.CreatedBy == "" {
d.CreatedBy = "anonymous"
}
if d.DefaultEarliest == "" {
d.DefaultEarliest = "-1h"
}
if d.DefaultLatest == "" {
d.DefaultLatest = "now"
}
row := s.pool.QueryRow(ctx, `
INSERT INTO dashboards (id, tenant_id, name, description, default_earliest, default_latest, created_by)
VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING created_at, updated_at`,
d.ID, d.TenantID, d.Name, d.Description, d.DefaultEarliest, d.DefaultLatest, d.CreatedBy)
return row.Scan(&d.CreatedAt, &d.UpdatedAt)
}
func (s *Store) ListDashboards(ctx context.Context, tenantID string) ([]Dashboard, error) {
rows, err := s.pool.Query(ctx, `
SELECT id, tenant_id, name, description, default_earliest, default_latest, created_by, created_at, updated_at
FROM dashboards WHERE tenant_id = $1 ORDER BY created_at DESC`, tenantID)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Dashboard
for rows.Next() {
var d Dashboard
if err := rows.Scan(&d.ID, &d.TenantID, &d.Name, &d.Description, &d.DefaultEarliest, &d.DefaultLatest, &d.CreatedBy, &d.CreatedAt, &d.UpdatedAt); err != nil {
return nil, err
}
out = append(out, d)
}
return out, rows.Err()
}
func (s *Store) GetDashboard(ctx context.Context, tenantID, id string) (*Dashboard, error) {
var d Dashboard
row := s.pool.QueryRow(ctx, `
SELECT id, tenant_id, name, description, default_earliest, default_latest, created_by, created_at, updated_at
FROM dashboards WHERE id = $1 AND tenant_id = $2`, id, tenantID)
if err := row.Scan(&d.ID, &d.TenantID, &d.Name, &d.Description, &d.DefaultEarliest, &d.DefaultLatest, &d.CreatedBy, &d.CreatedAt, &d.UpdatedAt); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
return nil, err
}
panels, err := s.listPanels(ctx, id)
if err != nil {
return nil, err
}
d.Panels = panels
return &d, nil
}
// listPanels doesn't itself take a tenantID -- every call site first
// resolves the owning dashboard via a tenant-scoped query (GetDashboard
// above, or dashboardTenantMatches below), so by the time this runs,
// dashboardID is already known to belong to the caller's tenant.
func (s *Store) listPanels(ctx context.Context, dashboardID string) ([]Panel, error) {
rows, err := s.pool.Query(ctx, `
SELECT id, dashboard_id, title, query, query_language, viz_type, viz_config,
position_x, position_y, width, height, earliest_override, latest_override,
sort_order, created_at, updated_at
FROM dashboard_panels WHERE dashboard_id = $1 ORDER BY sort_order, created_at`, dashboardID)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Panel
for rows.Next() {
var p Panel
if err := rows.Scan(&p.ID, &p.DashboardID, &p.Title, &p.Query, &p.QueryLanguage, &p.VizType, &p.VizConfig,
&p.PositionX, &p.PositionY, &p.Width, &p.Height, &p.EarliestOverride, &p.LatestOverride,
&p.SortOrder, &p.CreatedAt, &p.UpdatedAt); err != nil {
return nil, err
}
out = append(out, p)
}
return out, rows.Err()
}
// dashboardTenantMatches is the join every panel-mutating method below
// uses in place of a tenant_id column dashboard_panels doesn't have --
// "does this dashboard exist AND belong to this tenant." A plain
// EXISTS query, not a full row fetch: the panel methods that call this
// only need a yes/no gate, not the dashboard's data.
func (s *Store) dashboardTenantMatches(ctx context.Context, tenantID, dashboardID string) (bool, error) {
var exists bool
err := s.pool.QueryRow(ctx,
`SELECT EXISTS(SELECT 1 FROM dashboards WHERE id = $1 AND tenant_id = $2)`,
dashboardID, tenantID,
).Scan(&exists)
return exists, err
}
func (s *Store) UpdateDashboard(ctx context.Context, tenantID string, d *Dashboard) error {
if d.DefaultEarliest == "" {
d.DefaultEarliest = "-1h"
}
if d.DefaultLatest == "" {
d.DefaultLatest = "now"
}
row := s.pool.QueryRow(ctx, `
UPDATE dashboards SET name = $1, description = $2, default_earliest = $3, default_latest = $4, updated_at = now()
WHERE id = $5 AND tenant_id = $6
RETURNING tenant_id, created_by, created_at, updated_at`,
d.Name, d.Description, d.DefaultEarliest, d.DefaultLatest, d.ID, tenantID)
if err := row.Scan(&d.TenantID, &d.CreatedBy, &d.CreatedAt, &d.UpdatedAt); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return ErrNotFound
}
return err
}
return nil
}
func (s *Store) DeleteDashboard(ctx context.Context, tenantID, id string) error {
tag, err := s.pool.Exec(ctx, `DELETE FROM dashboards WHERE id = $1 AND tenant_id = $2`, id, tenantID)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrNotFound
}
return nil
}
func (s *Store) AddPanel(ctx context.Context, tenantID, dashboardID string, p *Panel) error {
ok, err := s.dashboardTenantMatches(ctx, tenantID, dashboardID)
if err != nil {
return err
}
if !ok {
return ErrNotFound
}
p.ID = uuid.NewString()
p.DashboardID = dashboardID
row := s.pool.QueryRow(ctx, `
INSERT INTO dashboard_panels (id, dashboard_id, title, query, query_language, viz_type, viz_config,
position_x, position_y, width, height, earliest_override, latest_override, sort_order)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
RETURNING created_at, updated_at`,
p.ID, p.DashboardID, p.Title, p.Query, p.QueryLanguage, p.VizType, p.VizConfig,
p.PositionX, p.PositionY, p.Width, p.Height, p.EarliestOverride, p.LatestOverride, p.SortOrder)
return row.Scan(&p.CreatedAt, &p.UpdatedAt)
}
func (s *Store) UpdatePanel(ctx context.Context, tenantID string, p *Panel) error {
ok, err := s.dashboardTenantMatches(ctx, tenantID, p.DashboardID)
if err != nil {
return err
}
if !ok {
return ErrNotFound
}
tag, err := s.pool.Exec(ctx, `
UPDATE dashboard_panels SET
title = $1, query = $2, query_language = $3, viz_type = $4, viz_config = $5,
position_x = $6, position_y = $7, width = $8, height = $9,
earliest_override = $10, latest_override = $11, sort_order = $12, updated_at = now()
WHERE id = $13 AND dashboard_id = $14`,
p.Title, p.Query, p.QueryLanguage, p.VizType, p.VizConfig,
p.PositionX, p.PositionY, p.Width, p.Height,
p.EarliestOverride, p.LatestOverride, p.SortOrder, p.ID, p.DashboardID)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrNotFound
}
return nil
}
func (s *Store) DeletePanel(ctx context.Context, tenantID, dashboardID, panelID string) error {
ok, err := s.dashboardTenantMatches(ctx, tenantID, dashboardID)
if err != nil {
return err
}
if !ok {
return ErrNotFound
}
tag, err := s.pool.Exec(ctx, `DELETE FROM dashboard_panels WHERE id = $1 AND dashboard_id = $2`, panelID, dashboardID)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrNotFound
}
return nil
}
// ImportDashboard creates a new dashboard and all its panels from an
// exported Dashboard document, assigning fresh IDs throughout -- so
// importing an exported dashboard into a different environment (or
// re-importing into the same one) never collides with the source IDs.
// Runs in one transaction: either the whole dashboard lands, or none of
// it does. tenantID comes from the caller (the authenticated identity),
// never from d.TenantID -- an exported dashboard JSON file carries
// whatever tenant_id it was exported from, and importing it must not
// let that value silently re-assign the dashboard to a different
// tenant than the importing user's own.
func (s *Store) ImportDashboard(ctx context.Context, tenantID string, d *Dashboard) (*Dashboard, error) {
tx, err := s.pool.Begin(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback(ctx)
id := uuid.NewString()
createdBy := d.CreatedBy
if createdBy == "" {
createdBy = "anonymous"
}
earliest := d.DefaultEarliest
if earliest == "" {
earliest = "-1h"
}
latest := d.DefaultLatest
if latest == "" {
latest = "now"
}
var out Dashboard
out.ID, out.TenantID, out.Name, out.Description = id, tenantID, d.Name, d.Description
out.DefaultEarliest, out.DefaultLatest, out.CreatedBy = earliest, latest, createdBy
row := tx.QueryRow(ctx, `
INSERT INTO dashboards (id, tenant_id, name, description, default_earliest, default_latest, created_by)
VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING created_at, updated_at`,
out.ID, out.TenantID, out.Name, out.Description, out.DefaultEarliest, out.DefaultLatest, out.CreatedBy)
if err := row.Scan(&out.CreatedAt, &out.UpdatedAt); err != nil {
return nil, err
}
for _, p := range d.Panels {
if err := validatePanel(&p); err != nil {
return nil, fmt.Errorf("panel %q: %w", p.Title, err)
}
p.ID = uuid.NewString()
p.DashboardID = out.ID
prow := tx.QueryRow(ctx, `
INSERT INTO dashboard_panels (id, dashboard_id, title, query, query_language, viz_type, viz_config,
position_x, position_y, width, height, earliest_override, latest_override, sort_order)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
RETURNING created_at, updated_at`,
p.ID, p.DashboardID, p.Title, p.Query, p.QueryLanguage, p.VizType, p.VizConfig,
p.PositionX, p.PositionY, p.Width, p.Height, p.EarliestOverride, p.LatestOverride, p.SortOrder)
if err := prow.Scan(&p.CreatedAt, &p.UpdatedAt); err != nil {
return nil, err
}
out.Panels = append(out.Panels, p)
}
if err := tx.Commit(ctx); err != nil {
return nil, err
}
return &out, nil
}
+192
View File
@@ -0,0 +1,192 @@
// Adversarial cross-tenant isolation tests against a real Postgres --
// Phase 4 task 8. handler_test.go's TestCrossTenant* tests already cover
// this against fakeStore (which is hand-written to mimic the real SQL's
// tenant filtering); these tests exercise the actual parameterized SQL
// in store.go, including the tenant_id foreign key constraint added in
// metadata/migrations/0027_add_dashboards_tenant_fk.sql -- a real gap a
// fake store literally cannot catch (e.g. a typo in a WHERE clause, or
// forgetting to update every method when the schema changes).
//
// Skipped unless DASHBOARDS_TEST_POSTGRES_ADDR is set; run via:
//
// docker run --rm --network sentry_default -v $(pwd)/../../..:/src -w /src/api \
// -e DASHBOARDS_TEST_POSTGRES_ADDR=metadata-postgres:5432 \
// -e DASHBOARDS_TEST_POSTGRES_PASSWORD=sentry-dev-only \
// golang:1.25-alpine go test ./dashboards/... -run Integration -v
package dashboards
import (
"context"
"fmt"
"os"
"testing"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
)
func integrationStore(t *testing.T) (*Store, *pgxpool.Pool) {
t.Helper()
addr := os.Getenv("DASHBOARDS_TEST_POSTGRES_ADDR")
if addr == "" {
t.Skip("DASHBOARDS_TEST_POSTGRES_ADDR not set -- skipping live-Postgres integration test")
}
password := os.Getenv("DASHBOARDS_TEST_POSTGRES_PASSWORD")
dsn := fmt.Sprintf("postgres://sentry:%s@%s/sentry_metadata", password, addr)
pool, err := pgxpool.New(context.Background(), dsn)
if err != nil {
t.Fatalf("opening pool: %v", err)
}
t.Cleanup(pool.Close)
return NewStore(pool), pool
}
// createTestTenant inserts directly into the tenants table (owned by
// metadata/migrations/0017-0019, not this package) -- dashboards.tenant_id
// has had a real foreign-key constraint since
// metadata/migrations/0027_add_dashboards_tenant_fk.sql, so a dashboard
// row for a tenant that doesn't exist in `tenants` is rejected by
// Postgres itself, not just application logic. Uses a unique suffix so
// repeated test runs against a persistent dev Postgres don't collide.
func createTestTenant(t *testing.T, pool *pgxpool.Pool) string {
t.Helper()
id := "test-tenant-" + uuid.NewString()[:8]
_, err := pool.Exec(context.Background(),
`INSERT INTO tenants (id, display_name, status) VALUES ($1, $1, 'active')`, id)
if err != nil {
t.Fatalf("creating test tenant: %v", err)
}
return id
}
func TestIntegrationCrossTenantGetIsNotFound(t *testing.T) {
store, pool := integrationStore(t)
ctx := context.Background()
tenantA := createTestTenant(t, pool)
tenantB := createTestTenant(t, pool)
d := &Dashboard{TenantID: tenantA, Name: "Acme's dashboard"}
if err := store.CreateDashboard(ctx, d); err != nil {
t.Fatalf("CreateDashboard: %v", err)
}
// Same tenant: found.
if _, err := store.GetDashboard(ctx, tenantA, d.ID); err != nil {
t.Fatalf("GetDashboard (same tenant): %v", err)
}
// Different tenant: not found, not a data leak.
if _, err := store.GetDashboard(ctx, tenantB, d.ID); err != ErrNotFound {
t.Fatalf("GetDashboard (cross-tenant) error = %v, want ErrNotFound", err)
}
}
func TestIntegrationCrossTenantListDoesNotLeak(t *testing.T) {
store, pool := integrationStore(t)
ctx := context.Background()
tenantA := createTestTenant(t, pool)
tenantB := createTestTenant(t, pool)
da := &Dashboard{TenantID: tenantA, Name: "A's dashboard"}
db := &Dashboard{TenantID: tenantB, Name: "B's dashboard"}
if err := store.CreateDashboard(ctx, da); err != nil {
t.Fatalf("CreateDashboard A: %v", err)
}
if err := store.CreateDashboard(ctx, db); err != nil {
t.Fatalf("CreateDashboard B: %v", err)
}
listA, err := store.ListDashboards(ctx, tenantA)
if err != nil {
t.Fatalf("ListDashboards A: %v", err)
}
for _, d := range listA {
if d.TenantID != tenantA {
t.Fatalf("tenant A's list leaked a dashboard from tenant %q", d.TenantID)
}
}
found := false
for _, d := range listA {
if d.ID == da.ID {
found = true
}
if d.ID == db.ID {
t.Fatalf("tenant A's list included tenant B's dashboard %q", db.ID)
}
}
if !found {
t.Fatal("tenant A's list did not include tenant A's own dashboard")
}
}
func TestIntegrationCrossTenantUpdateAndDeleteAreNotFound(t *testing.T) {
store, pool := integrationStore(t)
ctx := context.Background()
tenantA := createTestTenant(t, pool)
tenantB := createTestTenant(t, pool)
d := &Dashboard{TenantID: tenantA, Name: "Original"}
if err := store.CreateDashboard(ctx, d); err != nil {
t.Fatalf("CreateDashboard: %v", err)
}
hijack := &Dashboard{ID: d.ID, Name: "Hijacked"}
if err := store.UpdateDashboard(ctx, tenantB, hijack); err != ErrNotFound {
t.Fatalf("cross-tenant UpdateDashboard error = %v, want ErrNotFound", err)
}
got, err := store.GetDashboard(ctx, tenantA, d.ID)
if err != nil {
t.Fatalf("GetDashboard after attempted cross-tenant update: %v", err)
}
if got.Name != "Original" {
t.Fatalf("cross-tenant update mutated the row: Name = %q", got.Name)
}
if err := store.DeleteDashboard(ctx, tenantB, d.ID); err != ErrNotFound {
t.Fatalf("cross-tenant DeleteDashboard error = %v, want ErrNotFound", err)
}
if _, err := store.GetDashboard(ctx, tenantA, d.ID); err != nil {
t.Fatalf("expected the dashboard to still exist after a failed cross-tenant delete: %v", err)
}
}
func TestIntegrationCrossTenantPanelMutationIsNotFound(t *testing.T) {
store, pool := integrationStore(t)
ctx := context.Background()
tenantA := createTestTenant(t, pool)
tenantB := createTestTenant(t, pool)
d := &Dashboard{TenantID: tenantA, Name: "Has panels"}
if err := store.CreateDashboard(ctx, d); err != nil {
t.Fatalf("CreateDashboard: %v", err)
}
p := &Panel{Query: "service=api", VizType: VizTable, Width: 6, Height: 4}
if err := store.AddPanel(ctx, tenantB, d.ID, p); err != ErrNotFound {
t.Fatalf("cross-tenant AddPanel error = %v, want ErrNotFound", err)
}
// Add it for real (tenant A), then confirm tenant B can't update/delete it either.
if err := store.AddPanel(ctx, tenantA, d.ID, p); err != nil {
t.Fatalf("AddPanel (same tenant): %v", err)
}
p.Title = "Hijacked"
if err := store.UpdatePanel(ctx, tenantB, p); err != ErrNotFound {
t.Fatalf("cross-tenant UpdatePanel error = %v, want ErrNotFound", err)
}
if err := store.DeletePanel(ctx, tenantB, d.ID, p.ID); err != ErrNotFound {
t.Fatalf("cross-tenant DeletePanel error = %v, want ErrNotFound", err)
}
}
// TestIntegrationDashboardTenantForeignKeyRejectsUnknownTenant proves
// the database itself, not just application code, refuses a dashboard
// for a tenant that was never provisioned -- defense in depth
// independent of the Go-level tenant scoping above (see
// metadata/migrations/0027_add_dashboards_tenant_fk.sql).
func TestIntegrationDashboardTenantForeignKeyRejectsUnknownTenant(t *testing.T) {
store, _ := integrationStore(t)
d := &Dashboard{TenantID: "does-not-exist-" + uuid.NewString()[:8], Name: "Orphan"}
if err := store.CreateDashboard(context.Background(), d); err == nil {
t.Fatal("expected CreateDashboard to fail for a tenant_id with no matching tenants row")
}
}
+86
View File
@@ -0,0 +1,86 @@
// Package dashboards implements CRUD for saved, multi-panel dashboards
// -- see /docs/phase-3-dashboard-design.md. Deliberately pure CRUD: panel
// *query execution* happens client-side (the web UI calls the existing
// POST /query per panel), so this package never touches querylang.
package dashboards
import (
"encoding/json"
"fmt"
"time"
)
// VizType is one of the panel visualization kinds. "top_n" renders
// through the same path as "table" -- the query itself already did the
// sort/limit -- so there's no execution-side difference, only UI framing.
type VizType string
const (
VizTable VizType = "table"
VizLine VizType = "line"
VizBar VizType = "bar"
VizSingleStat VizType = "single_stat"
VizTopN VizType = "top_n"
)
func validVizType(v VizType) bool {
switch v {
case VizTable, VizLine, VizBar, VizSingleStat, VizTopN:
return true
default:
return false
}
}
type Dashboard struct {
ID string `json:"id"`
TenantID string `json:"tenant_id"`
Name string `json:"name"`
Description string `json:"description"`
DefaultEarliest string `json:"default_earliest"`
DefaultLatest string `json:"default_latest"`
CreatedBy string `json:"created_by"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Panels []Panel `json:"panels,omitempty"`
}
type Panel struct {
ID string `json:"id"`
DashboardID string `json:"dashboard_id"`
Title string `json:"title"`
Query string `json:"query"`
QueryLanguage string `json:"query_language"`
VizType VizType `json:"viz_type"`
VizConfig json.RawMessage `json:"viz_config,omitempty"`
PositionX int `json:"position_x"`
PositionY int `json:"position_y"`
Width int `json:"width"`
Height int `json:"height"`
EarliestOverride *string `json:"earliest_override,omitempty"`
LatestOverride *string `json:"latest_override,omitempty"`
SortOrder int `json:"sort_order"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// validatePanel enforces the two rules /docs/phase-3-dashboard-design.md
// states as disclosed non-goals rather than silent gaps: raw-SQL panels
// aren't supported (time-range injection has no reliable splice point
// into arbitrary SQL), and viz_type must be one this API knows how to
// store/render.
func validatePanel(p *Panel) error {
if p.Query == "" {
return fmt.Errorf("query must not be empty")
}
if p.QueryLanguage == "sql" {
return fmt.Errorf("raw-SQL panels are not supported -- dashboards only support pipe-syntax queries, since the dashboard time-range picker is injected as leading query terms")
}
if !validVizType(p.VizType) {
return fmt.Errorf("viz_type must be one of table, line, bar, single_stat, top_n, got %q", p.VizType)
}
if len(p.VizConfig) == 0 {
p.VizConfig = json.RawMessage(`{}`)
}
return nil
}