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

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

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

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

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

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

122 lines
5.1 KiB
Go

// Package chrunner is the tenant-scoped implementation of api's
// querylang/executor.SQLRunner interface -- the piece
// /docs/security/threat-model.md's headline finding says was missing:
// until this package, api/cmd/api/main.go opened exactly one shared
// ClickHouse connection for every tenant, no matter how many
// tenant_memberships/Tenant CRs existed. This package requires
// importing api/querylang/executor and api/authz directly (see
// enterprise/go.mod's replace directive) -- implementing
// executor.SQLRunner structurally requires it (its RunSQL method
// returns *executor.Result, a type only that package defines), and
// that's the allowed import direction: enterprise -> api, never the
// reverse (hack/check-tenant-boundary.sh enforces that direction only).
//
// Design, per /docs/phase-4-isolation-design.md's ClickHouse section:
// Registry holds one fully separate *executor.ChRunner (and the
// driver.Conn under it) per tenant, built once at construction from an
// immutable map -- never a shared pool with session-level `USE`, which
// is a classic concurrency bug (a connection recycled between tenants
// mid-flight can interleave one tenant's session state into another's
// query). RunSQL resolves which tenant's runner to use from the
// request's authz.Identity (attached to ctx by
// api/authz.RequireRole/RequireRoleOrService), never from any
// caller-suppliable parameter -- there is no code path in this package
// that accepts a tenant ID as an argument to a query-executing method.
package chrunner
import (
"context"
"fmt"
"github.com/ClickHouse/clickhouse-go/v2"
"github.com/cairnobs/cairnobs/api/authz"
"github.com/cairnobs/cairnobs/api/querylang/executor"
)
// DataSource is the minimal shape Registry needs to open one tenant's
// connection -- deliberately not enterprise/internal/rbacstore.DataSource
// itself, so this package doesn't need to import rbacstore just to
// describe "an address and a credential." Callers (enterprise-api's
// main.go) adapt rbacstore rows into this.
type DataSource struct {
TenantID string
Database string
Username string
Password string
}
// Registry implements executor.SQLRunner by routing each call to the
// caller's tenant-specific connection. Immutable after New returns --
// see this file's doc comment on why that's load-bearing, not just a
// style choice.
type Registry struct {
runners map[string]*executor.ChRunner
closers []func()
}
// New opens one real ClickHouse connection per DataSource (same native
// address for all of them -- tenants sharing a physical ClickHouse
// server today, per-tenant *pinning* to dedicated cluster nodes is
// named as later, non-schema-changing work in
// /docs/phase-4-isolation-design.md, not something this constructor
// does). Fails closed: if any one tenant's connection can't be opened
// or doesn't ping successfully, the whole Registry fails to construct
// rather than silently running with a partial tenant set -- a tenant
// missing from the map is a clear, loud "unknown tenant" error at query
// time (see RunSQL), not a connection nobody noticed never came up.
func New(ctx context.Context, addr string, sources []DataSource) (*Registry, error) {
reg := &Registry{runners: make(map[string]*executor.ChRunner, len(sources))}
for _, src := range sources {
conn, err := clickhouse.Open(&clickhouse.Options{
Addr: []string{addr},
Auth: clickhouse.Auth{
Database: src.Database,
Username: src.Username,
Password: src.Password,
},
})
if err != nil {
reg.Close()
return nil, fmt.Errorf("chrunner: opening connection for tenant %q: %w", src.TenantID, err)
}
if err := conn.Ping(ctx); err != nil {
_ = conn.Close()
reg.Close()
return nil, fmt.Errorf("chrunner: pinging connection for tenant %q: %w", src.TenantID, err)
}
reg.runners[src.TenantID] = executor.NewChRunner(conn)
reg.closers = append(reg.closers, func() { _ = conn.Close() })
}
return reg, nil
}
// Close releases every underlying connection -- call once at process
// shutdown, same lifecycle as the single conn.Close() api/cmd/api/main.go
// defers today, just fanned out over N connections.
func (r *Registry) Close() {
for _, c := range r.closers {
c()
}
}
// RunSQL implements executor.SQLRunner. Resolves the caller's tenant
// from ctx (never a parameter -- see this file's doc comment) and fails
// closed on every ambiguous case: no identity, an identity with no
// tenant (RoleService, or a misconfigured authorizer), or a tenant with
// no provisioned connection all return an error, never a fallback to
// some other tenant's connection or an arbitrarily-chosen default.
func (r *Registry) RunSQL(ctx context.Context, sql string) (*executor.Result, error) {
identity, ok := authz.IdentityFromContext(ctx)
if !ok {
return nil, fmt.Errorf("chrunner: no authenticated identity in context, refusing to run query")
}
if identity.TenantID == "" {
return nil, fmt.Errorf("chrunner: authenticated identity %q has no tenant, refusing to run query", identity.Role)
}
runner, ok := r.runners[identity.TenantID]
if !ok {
return nil, fmt.Errorf("chrunner: tenant %q has no provisioned ClickHouse connection", identity.TenantID)
}
return runner.RunSQL(ctx, sql)
}