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:
@@ -0,0 +1,186 @@
|
||||
// Package queryapi is Sentry's query API: a single POST /query endpoint
|
||||
// accepting either the pipe syntax or raw SQL, compiled by
|
||||
// querylang/planner and executed by querylang/executor. Replaces Phase
|
||||
// 0/1's two separate placeholder endpoints (raw-SQL-only /query,
|
||||
// free-text-only /search) -- see /docs/query-language-design.md.
|
||||
//
|
||||
// Still plain net/http, not the pinned gRPC+REST-gateway pattern, for
|
||||
// the same reason as Phase 0/1: this is one endpoint, and the
|
||||
// proto/annotations/codegen machinery doesn't buy much at that size.
|
||||
// `/api` does speak gRPC internally (to /search) — this simplification
|
||||
// is about the public-facing surface only.
|
||||
package queryapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/sentry/sentry/api/authz"
|
||||
"github.com/sentry/sentry/api/internal/querylang/planner"
|
||||
"github.com/sentry/sentry/api/querylang/executor"
|
||||
)
|
||||
|
||||
// AuditLogger is core's extension point for query audit logging --
|
||||
// deliberately minimal and tenant-agnostic, since core has no concept of
|
||||
// tenants (see /docs/phase-4-isolation-design.md: that mechanism lives
|
||||
// entirely in enterprise/). enterprise/internal/audit implements this
|
||||
// against the real hash-chained, append-only store; a nil AuditLogger
|
||||
// (the default for a single-tenant deployment without enterprise/
|
||||
// configured) means no audit logging happens and core behaves exactly
|
||||
// as it did in Phases 0-3.
|
||||
//
|
||||
// Tenant/user identity is deliberately NOT a field on QueryAuditEntry --
|
||||
// once Phase 4 task 5's auth middleware wraps this handler, it attaches
|
||||
// that identity to the request's context.Context via
|
||||
// enterprise/internal/tenant, and LogQuery's ctx parameter is the same
|
||||
// context the request carried, so an enterprise-side implementation
|
||||
// reads identity from ctx rather than this interface growing
|
||||
// tenant-awareness. Per /docs/phase-4-isolation-design.md's audit
|
||||
// section, this is a fail-open path: a LogQuery error is logged but
|
||||
// never fails the HTTP response for a routine read query.
|
||||
type AuditLogger interface {
|
||||
LogQuery(ctx context.Context, entry QueryAuditEntry) error
|
||||
}
|
||||
|
||||
type QueryAuditEntry struct {
|
||||
Query string
|
||||
Language string
|
||||
RowCount int
|
||||
Duration time.Duration
|
||||
Success bool
|
||||
Error string
|
||||
}
|
||||
|
||||
type Handler struct {
|
||||
logger *slog.Logger
|
||||
sqlRunner executor.SQLRunner
|
||||
search executor.SearchClient
|
||||
queryTimeout time.Duration
|
||||
audit AuditLogger
|
||||
authorizer authz.Authorizer
|
||||
}
|
||||
|
||||
// audit and authorizer may both be nil -- see AuditLogger's doc comment
|
||||
// and authz.RequireRoleOrService's nil-safety. /query allows RoleViewer
|
||||
// (human sessions) or the alerting service identity (RoleService) --
|
||||
// it's the one endpoint /alerting's evaluator legitimately calls, per
|
||||
// /docs/phase-4-isolation-design.md's alerting service-identity design.
|
||||
func NewHandler(logger *slog.Logger, sqlRunner executor.SQLRunner, search executor.SearchClient, queryTimeout time.Duration, audit AuditLogger, authorizer authz.Authorizer) *Handler {
|
||||
return &Handler{logger: logger, sqlRunner: sqlRunner, search: search, queryTimeout: queryTimeout, audit: audit, authorizer: authorizer}
|
||||
}
|
||||
|
||||
// RegisterRoutes adds this handler's routes onto a shared mux. Phase 3
|
||||
// introduced a second handler package (dashboards), so CORS is
|
||||
// now applied once, by main.go, around the fully-assembled mux rather
|
||||
// than by each handler wrapping itself individually -- see
|
||||
// httpserver.WithCORS.
|
||||
func (h *Handler) RegisterRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("POST /query", authz.RequireRoleOrService(h.authorizer, authz.RoleViewer, h.handleQuery))
|
||||
mux.HandleFunc("GET /healthz", h.handleHealthz)
|
||||
}
|
||||
|
||||
func (h *Handler) handleHealthz(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
type queryRequest struct {
|
||||
Query string `json:"query"`
|
||||
// Language overrides auto-detection ("" / omitted). "sql" or "spl" --
|
||||
// see planner.Language and /docs/query-language-design.md's
|
||||
// "Detection" section for why this exists: the rare case a pipe
|
||||
// query legitimately starts with the literal word "select".
|
||||
Language string `json:"language"`
|
||||
}
|
||||
|
||||
type queryResponse struct {
|
||||
Columns []string `json:"columns"`
|
||||
Rows [][]any `json:"rows"`
|
||||
}
|
||||
|
||||
type errorResponse struct {
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
// maxBodyBytes caps the request body: a query string has no legitimate
|
||||
// reason to be larger than this.
|
||||
const maxBodyBytes = 1 << 20 // 1 MiB
|
||||
|
||||
func (h *Handler) handleQuery(w http.ResponseWriter, r *http.Request) {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxBodyBytes)
|
||||
|
||||
var req queryRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid JSON body: "+err.Error())
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(req.Query) == "" {
|
||||
writeError(w, http.StatusBadRequest, "query must not be empty")
|
||||
return
|
||||
}
|
||||
|
||||
lang := planner.Language(req.Language)
|
||||
if lang != planner.Auto && lang != planner.SQL && lang != planner.SPL {
|
||||
writeError(w, http.StatusBadRequest, `language must be "sql", "spl", or omitted`)
|
||||
return
|
||||
}
|
||||
|
||||
plan, err := planner.Compile(req.Query, lang, time.Now())
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(r.Context(), h.queryTimeout)
|
||||
defer cancel()
|
||||
|
||||
start := time.Now()
|
||||
result, err := executor.Execute(ctx, plan, h.sqlRunner, h.search)
|
||||
duration := time.Since(start)
|
||||
|
||||
if err != nil {
|
||||
h.logger.Error("query execution failed", "query", req.Query, "error", err)
|
||||
h.logAudit(r.Context(), req, 0, duration, err)
|
||||
writeError(w, http.StatusBadGateway, "query failed: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
h.logAudit(r.Context(), req, len(result.Rows), duration, nil)
|
||||
writeJSON(w, queryResponse{Columns: result.Columns, Rows: result.Rows})
|
||||
}
|
||||
|
||||
// logAudit is fail-open by design (see AuditLogger's doc comment): a
|
||||
// write failure here is logged and otherwise ignored, never surfaced to
|
||||
// the HTTP caller. Uses r.Context() (the original request context, not
|
||||
// the query-execution one with its own deadline) so a slow/cancelled
|
||||
// query's context.WithTimeout expiring doesn't also cancel the audit
|
||||
// write for it.
|
||||
func (h *Handler) logAudit(ctx context.Context, req queryRequest, rowCount int, duration time.Duration, execErr error) {
|
||||
if h.audit == nil {
|
||||
return
|
||||
}
|
||||
entry := QueryAuditEntry{
|
||||
Query: req.Query, Language: req.Language, RowCount: rowCount,
|
||||
Duration: duration, Success: execErr == nil,
|
||||
}
|
||||
if execErr != nil {
|
||||
entry.Error = execErr.Error()
|
||||
}
|
||||
if err := h.audit.LogQuery(ctx, entry); err != nil {
|
||||
h.logger.Error("audit log write failed", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
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})
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
package queryapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/sentry/sentry/api/authz"
|
||||
"github.com/sentry/sentry/api/querylang/executor"
|
||||
)
|
||||
|
||||
type fakeSQLRunner struct {
|
||||
result *executor.Result
|
||||
err error
|
||||
gotSQL string
|
||||
}
|
||||
|
||||
func (f *fakeSQLRunner) RunSQL(_ context.Context, sql string) (*executor.Result, error) {
|
||||
f.gotSQL = sql
|
||||
if f.err != nil {
|
||||
return nil, f.err
|
||||
}
|
||||
if f.result != nil {
|
||||
return f.result, nil
|
||||
}
|
||||
return &executor.Result{Columns: []string{}, Rows: [][]any{}}, nil
|
||||
}
|
||||
|
||||
type fakeSearchClient struct {
|
||||
recordIDs []string
|
||||
err error
|
||||
gotQuery string
|
||||
}
|
||||
|
||||
func (f *fakeSearchClient) Search(_ context.Context, query string, _ uint32) ([]string, error) {
|
||||
f.gotQuery = query
|
||||
if f.err != nil {
|
||||
return nil, f.err
|
||||
}
|
||||
return f.recordIDs, nil
|
||||
}
|
||||
|
||||
func newTestHandler(sqlRunner *fakeSQLRunner, search *fakeSearchClient) *Handler {
|
||||
if search == nil {
|
||||
search = &fakeSearchClient{}
|
||||
}
|
||||
return NewHandler(slog.New(slog.NewTextHandler(io.Discard, nil)), sqlRunner, search, time.Second, nil, nil)
|
||||
}
|
||||
|
||||
type fakeAuditLogger struct {
|
||||
entries []QueryAuditEntry
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeAuditLogger) LogQuery(_ context.Context, entry QueryAuditEntry) error {
|
||||
f.entries = append(f.entries, entry)
|
||||
return f.err
|
||||
}
|
||||
|
||||
func newTestHandlerWithAudit(sqlRunner *fakeSQLRunner, audit *fakeAuditLogger) *Handler {
|
||||
return NewHandler(slog.New(slog.NewTextHandler(io.Discard, nil)), sqlRunner, &fakeSearchClient{}, time.Second, audit, nil)
|
||||
}
|
||||
|
||||
func newTestMux(h *Handler) *http.ServeMux {
|
||||
mux := http.NewServeMux()
|
||||
h.RegisterRoutes(mux)
|
||||
return mux
|
||||
}
|
||||
|
||||
func postQuery(t *testing.T, h *Handler, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodPost, "/query", strings.NewReader(body))
|
||||
rec := httptest.NewRecorder()
|
||||
newTestMux(h).ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
func TestHandleQuerySQLSuccess(t *testing.T) {
|
||||
sr := &fakeSQLRunner{result: &executor.Result{
|
||||
Columns: []string{"host", "count"},
|
||||
Rows: [][]any{{"h1", 3}},
|
||||
}}
|
||||
h := newTestHandler(sr, nil)
|
||||
|
||||
rec := postQuery(t, h, `{"query": "SELECT host, count(*) FROM logs GROUP BY host"}`)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var got queryResponse
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decoding response: %v", err)
|
||||
}
|
||||
if len(got.Columns) != 2 || len(got.Rows) != 1 {
|
||||
t.Fatalf("unexpected result: %+v", got)
|
||||
}
|
||||
if sr.gotSQL != "SELECT host, count(*) FROM logs GROUP BY host" {
|
||||
t.Fatalf("unexpected SQL passed through: %q", sr.gotSQL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleQueryPipeSyntaxSuccess(t *testing.T) {
|
||||
sr := &fakeSQLRunner{result: &executor.Result{
|
||||
Columns: []string{"host"},
|
||||
Rows: [][]any{{"api"}},
|
||||
}}
|
||||
h := newTestHandler(sr, nil)
|
||||
|
||||
rec := postQuery(t, h, `{"query": "service=api"}`)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if !strings.Contains(sr.gotSQL, "`service` = 'api'") {
|
||||
t.Fatalf("expected compiled SQL to filter on service, got: %s", sr.gotSQL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleQueryTextSearchRoutesThroughSearchClient(t *testing.T) {
|
||||
sr := &fakeSQLRunner{}
|
||||
fs := &fakeSearchClient{recordIDs: []string{"id-1"}}
|
||||
h := newTestHandler(sr, fs)
|
||||
|
||||
rec := postQuery(t, h, `{"query": "message:\"connection refused\""}`)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if fs.gotQuery != `"connection refused"` {
|
||||
t.Fatalf("search query = %q", fs.gotQuery)
|
||||
}
|
||||
if !strings.Contains(sr.gotSQL, "record_id IN ('id-1')") {
|
||||
t.Fatalf("expected the search prefilter in the generated SQL, got: %s", sr.gotSQL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleQueryRejectsEmptyQuery(t *testing.T) {
|
||||
h := newTestHandler(&fakeSQLRunner{}, nil)
|
||||
rec := postQuery(t, h, `{"query": " "}`)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleQueryRejectsInvalidJSON(t *testing.T) {
|
||||
h := newTestHandler(&fakeSQLRunner{}, nil)
|
||||
rec := postQuery(t, h, `not json`)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleQueryRejectsCompileError(t *testing.T) {
|
||||
h := newTestHandler(&fakeSQLRunner{}, nil)
|
||||
rec := postQuery(t, h, `{"query": "service=api | bogus"}`)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400; body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleQueryRejectsNonSelectSQL(t *testing.T) {
|
||||
h := newTestHandler(&fakeSQLRunner{}, nil)
|
||||
rec := postQuery(t, h, `{"query": "DELETE FROM logs", "language": "sql"}`)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleQueryRejectsInvalidLanguage(t *testing.T) {
|
||||
h := newTestHandler(&fakeSQLRunner{}, nil)
|
||||
rec := postQuery(t, h, `{"query": "service=api", "language": "cobol"}`)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleQueryExplicitLanguageOverridesAutoDetect(t *testing.T) {
|
||||
sr := &fakeSQLRunner{}
|
||||
fs := &fakeSearchClient{recordIDs: []string{"id-1"}}
|
||||
h := newTestHandler(sr, fs)
|
||||
|
||||
// "select" alone would auto-detect as (nonsensical but
|
||||
// syntactically-valid-looking) SQL without the override -- the
|
||||
// override forces pipe-syntax parsing instead, where a bare word
|
||||
// with no comparator is a free-text search term.
|
||||
rec := postQuery(t, h, `{"query": "select", "language": "spl"}`)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if fs.gotQuery != "select" {
|
||||
t.Fatalf("expected 'select' to be treated as a free-text search term, got query=%q", fs.gotQuery)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleQueryExecutorErrorReturnsBadGateway(t *testing.T) {
|
||||
sr := &fakeSQLRunner{err: errors.New("boom")}
|
||||
h := newTestHandler(sr, nil)
|
||||
|
||||
rec := postQuery(t, h, `{"query": "SELECT 1"}`)
|
||||
|
||||
if rec.Code != http.StatusBadGateway {
|
||||
t.Fatalf("status = %d, want 502", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleHealthz(t *testing.T) {
|
||||
h := newTestHandler(&fakeSQLRunner{}, nil)
|
||||
req := httptest.NewRequest(http.MethodGet, "/healthz", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
newTestMux(h).ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleQueryLogsAuditEntryOnSuccess(t *testing.T) {
|
||||
sr := &fakeSQLRunner{result: &executor.Result{Columns: []string{"host"}, Rows: [][]any{{"h1"}, {"h2"}}}}
|
||||
audit := &fakeAuditLogger{}
|
||||
h := newTestHandlerWithAudit(sr, audit)
|
||||
|
||||
rec := postQuery(t, h, `{"query": "SELECT host FROM logs"}`)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
if len(audit.entries) != 1 {
|
||||
t.Fatalf("expected 1 audit entry, got %d", len(audit.entries))
|
||||
}
|
||||
entry := audit.entries[0]
|
||||
if entry.Query != "SELECT host FROM logs" || !entry.Success || entry.RowCount != 2 || entry.Error != "" {
|
||||
t.Fatalf("unexpected audit entry: %+v", entry)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleQueryLogsAuditEntryOnFailure(t *testing.T) {
|
||||
sr := &fakeSQLRunner{err: errors.New("boom")}
|
||||
audit := &fakeAuditLogger{}
|
||||
h := newTestHandlerWithAudit(sr, audit)
|
||||
|
||||
rec := postQuery(t, h, `{"query": "SELECT 1"}`)
|
||||
if rec.Code != http.StatusBadGateway {
|
||||
t.Fatalf("status = %d, want 502", rec.Code)
|
||||
}
|
||||
|
||||
if len(audit.entries) != 1 {
|
||||
t.Fatalf("expected 1 audit entry even on failure, got %d", len(audit.entries))
|
||||
}
|
||||
entry := audit.entries[0]
|
||||
if entry.Success || entry.Error == "" {
|
||||
t.Fatalf("expected a failed audit entry with an error message, got %+v", entry)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleQueryAuditWriteFailureDoesNotFailRequest proves the
|
||||
// fail-open design: a request still succeeds even when the audit
|
||||
// logger itself errors -- per queryapi.AuditLogger's doc comment and
|
||||
// /docs/phase-4-isolation-design.md's audit fail-open/fail-closed policy.
|
||||
func TestHandleQueryAuditWriteFailureDoesNotFailRequest(t *testing.T) {
|
||||
sr := &fakeSQLRunner{result: &executor.Result{Columns: []string{}, Rows: [][]any{}}}
|
||||
audit := &fakeAuditLogger{err: errors.New("audit backend unreachable")}
|
||||
h := newTestHandlerWithAudit(sr, audit)
|
||||
|
||||
rec := postQuery(t, h, `{"query": "SELECT 1"}`)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200 -- an audit write failure must not fail the request", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleQueryNilAuditLoggerIsNoOp(t *testing.T) {
|
||||
sr := &fakeSQLRunner{result: &executor.Result{Columns: []string{}, Rows: [][]any{}}}
|
||||
h := newTestHandler(sr, nil) // audit is nil here
|
||||
|
||||
rec := postQuery(t, h, `{"query": "SELECT 1"}`)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// fakeAuthorizer resolves every request to a fixed identity/error --
|
||||
// task 5 wired authz.RequireRoleOrService into RegisterRoutes but every
|
||||
// existing test above passes a nil authorizer (a deliberate no-op), so
|
||||
// none of them actually exercise the wiring with a real authorizer
|
||||
// present. Phase 4 task 8 (adversarial tests) closes that gap: these
|
||||
// prove /query's authz boundary holds when a real Authorizer is wired
|
||||
// in, not just that the middleware function works in isolation
|
||||
// (authz/middleware_test.go already covers that).
|
||||
type fakeAuthorizer struct {
|
||||
identity authz.Identity
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeAuthorizer) Authorize(*http.Request) (authz.Identity, error) {
|
||||
return f.identity, f.err
|
||||
}
|
||||
|
||||
func newTestHandlerWithAuthorizer(sqlRunner *fakeSQLRunner, authorizer authz.Authorizer) *Handler {
|
||||
return NewHandler(slog.New(slog.NewTextHandler(io.Discard, nil)), sqlRunner, &fakeSearchClient{}, time.Second, nil, authorizer)
|
||||
}
|
||||
|
||||
func TestHandleQueryRejectsUnauthenticatedWhenAuthorizerConfigured(t *testing.T) {
|
||||
sr := &fakeSQLRunner{result: &executor.Result{Columns: []string{}, Rows: [][]any{}}}
|
||||
h := newTestHandlerWithAuthorizer(sr, &fakeAuthorizer{err: errors.New("no session")})
|
||||
|
||||
rec := postQuery(t, h, `{"query": "SELECT 1"}`)
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status = %d, want 401", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleQueryAllowsViewer(t *testing.T) {
|
||||
sr := &fakeSQLRunner{result: &executor.Result{Columns: []string{}, Rows: [][]any{}}}
|
||||
h := newTestHandlerWithAuthorizer(sr, &fakeAuthorizer{identity: authz.Identity{TenantID: "acme", Role: authz.RoleViewer}})
|
||||
|
||||
rec := postQuery(t, h, `{"query": "SELECT 1"}`)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleQueryAllowsServiceIdentity is the other half of the
|
||||
// alerting<->api gap's fix (/docs/phase-4-isolation-design.md) --
|
||||
// /alerting's evaluator must be able to call POST /query with its
|
||||
// RoleService credential even though it's not a human session.
|
||||
func TestHandleQueryAllowsServiceIdentity(t *testing.T) {
|
||||
sr := &fakeSQLRunner{result: &executor.Result{Columns: []string{}, Rows: [][]any{}}}
|
||||
h := newTestHandlerWithAuthorizer(sr, &fakeAuthorizer{identity: authz.Identity{Role: authz.RoleService}})
|
||||
|
||||
rec := postQuery(t, h, `{"query": "SELECT 1"}`)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200 -- RoleService must be allowed on /query; body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// This file is a checklist, not a fully passing test suite -- it exists
|
||||
// so the four adversarial probes /docs/phase-4-isolation-design.md's
|
||||
// "Verification plan for this design specifically" section names for
|
||||
// Phase 4 task 8 have a permanent, grep-able home in the test tree.
|
||||
//
|
||||
// Item 1 (fully-qualified cross-tenant raw SQL) is no longer blocked:
|
||||
// enterprise/internal/tenantprovision and enterprise/internal/chrunner
|
||||
// now exist, and both have real, passing (when run against a live
|
||||
// ClickHouse) tests for exactly this probe --
|
||||
// enterprise/internal/tenantprovision/tenantprovision_test.go's
|
||||
// TestProvisionedUserCannotReadOtherTenantDatabase (at the raw
|
||||
// ClickHouse-user layer) and enterprise/internal/chrunner/
|
||||
// chrunner_test.go's TestRegistryTenantCannotReadOtherTenantEvenViaRawSQL
|
||||
// (through the actual query-execution code path api/queryapi.Handler
|
||||
// calls in production, when fronted by enterprise/cmd/enterprise-api
|
||||
// instead of plain api/cmd/api). Nothing to assert here anymore for
|
||||
// item 1 -- see those two tests instead.
|
||||
//
|
||||
// Items 2-4 remain blocked, for the reasons each Skip below states.
|
||||
// Note the scope boundary this leaves: even with chrunner wired in,
|
||||
// there is still exactly one shared Tantivy index for every tenant
|
||||
// (enterprise/internal/searchclient, the Tantivy-side equivalent of
|
||||
// chrunner, is unbuilt) -- see /docs/security/threat-model.md.
|
||||
package queryapi
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestAdversarial_ClickHouseUserCannotReadSystemTables(t *testing.T) {
|
||||
t.Skip("BLOCKED on enterprise/internal/tenantprovision: needs a real per-tenant " +
|
||||
"ClickHouse user to attempt `SELECT * FROM system.query_log`, " +
|
||||
"`system.tables`, `SHOW DATABASES` against, and confirm system.* " +
|
||||
"access was actually revoked (not just assumed from ClickHouse's " +
|
||||
"default template -- task 2's finding was that this is " +
|
||||
"version-dependent and must be checked live, not read from docs). " +
|
||||
"See /docs/phase-4-isolation-design.md's verification plan, item 2.")
|
||||
}
|
||||
|
||||
func TestAdversarial_TantivySearchExcludesOtherTenantsMatchingResults(t *testing.T) {
|
||||
t.Skip("BLOCKED on enterprise/internal/searchclient: needs two real " +
|
||||
"per-tenant Tantivy indices, one seeded with a term, to confirm a " +
|
||||
"search scoped to the other tenant returns zero hits for that term " +
|
||||
"even though the term exists in the other index. See " +
|
||||
"/docs/phase-4-isolation-design.md's verification plan, item 3.")
|
||||
}
|
||||
|
||||
func TestAdversarial_EvaluatorTickMidProvisioningIsRefusedNotServed(t *testing.T) {
|
||||
t.Skip("BLOCKED on enterprise/internal/tenantprovision's ordered " +
|
||||
"provisioning state machine (CREATE USER -> GRANT -> mark active): " +
|
||||
"needs a tenant row that exists but hasn't reached the active gate " +
|
||||
"yet, and a simulated /alerting evaluator tick against it, to " +
|
||||
"confirm every tenant-resolution path actually checks tenant " +
|
||||
"status server-side rather than inferring readiness from ambient " +
|
||||
"connection success. See /docs/phase-4-isolation-design.md's " +
|
||||
"verification plan, item 4, and its provisioning-gate requirement.")
|
||||
}
|
||||
Reference in New Issue
Block a user