Source identity
| Field | Recorded value |
|---|---|
| Source type | GitHub source |
| Original record | Janady13/missionmatch / internal/platform/tenant/tenant.go |
| Date | Not specified in source |
| Repository | Janady13/missionmatch |
| Revision | 720d47fae476b0d38477ae4401697d372b1ea2bc |
| Branch | feature/opportunity-to-outcome |
| Path or archive member | internal/platform/tenant/tenant.go |
| Original SHA-256 | 8fae437384e03150e691b32f94288ec17703e875936b53c0a92fbc923c60b509 |
| Git blob SHA | 16d1e11f6ed6ac1b50b2bee3fa663496cb1a251d |
| Reading-copy SHA-256 | 8fae437384e03150e691b32f94288ec17703e875936b53c0a92fbc923c60b509 |
Every recorded occurrence
These 2 records contain identical original source bytes. Their paths and revisions remain part of the archive.
| Original record | Branch or archive | Revision / identifier | Original location |
|---|---|---|---|
| Janady13/missionmatch / internal/platform/tenant/tenant.go | feature/opportunity-to-outcome | 720d47fae476b0d38477ae4401697d372b1ea2bc | Open original |
| Janady13/missionmatch / internal/platform/tenant/tenant.go | feature/aioe-upgrade | 2178e7298d0e5d9af83afa12402fd587f0ba6ed8 | Open original |
Recovered source transcript
Download complete source text ↓216 lines · 9.5 KB
// Package tenant is the multi-tenancy correctness boundary.
//
// Tenant isolation is enforced by Postgres Row-Level Security, NOT by Go WHERE clauses. Every
// tenant-scoped request runs inside a transaction whose `app.current_org_id` GUC is set
// transaction-locally, so Postgres discards it at COMMIT/ROLLBACK and it can never leak to the next
// request that reuses a pooled connection (the pgx-pool gotcha, see docs/STACK_DECISIONS.md §2).
//
// Two safeguards stack here:
// - Go side: no validated org in context => RunInTenantTx refuses to run (fail closed).
// - DB side: an unset GUC makes current_setting(...,true) NULL, so the RLS policy matches zero
// rows (default deny).
//
// The org id MUST originate from a verified session/JWT claim resolved by auth middleware, never
// from a client-supplied body, header, or query parameter.
package tenant
import (
"context"
"errors"
"fmt"
"net/http"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// ErrNoTenant is returned when tenant-scoped DB work is attempted without a validated organization.
var ErrNoTenant = errors.New("tenant: no organization_id in context (refusing to run unscoped query)")
// ctxKey is an unexported context key so a client cannot spoof the org via a context-key collision.
type ctxKey struct{}
var orgKey = ctxKey{}
// WithOrg stores the validated org id in ctx. Call this ONLY from auth middleware, with a value
// taken from verified claims.
func WithOrg(ctx context.Context, orgID string) context.Context {
return context.WithValue(ctx, orgKey, orgID)
}
// OrgFromContext returns the validated org id and whether a non-empty one is present.
func OrgFromContext(ctx context.Context) (string, bool) {
v, ok := ctx.Value(orgKey).(string)
return v, ok && v != ""
}
// principalCtxKey is a SEPARATE key type from ctxKey. Reusing ctxKey for the user would collide with
// orgKey, because every empty struct value of the same type is equal, so the two context lookups
// would return each other's value. A distinct type keeps the org and the principal independent.
type principalCtxKey struct{}
var principalKey = principalCtxKey{}
// Principal is the authenticated actor resolved from a validated session: the user id and the role
// used for authorization. Like the org, it MUST originate from auth middleware reading verified
// session state, never a client supplied value.
type Principal struct {
UserID string
Role string
// Tools is the granted product set (missionmatch, screenmatch, slatematch, recruitmatch) resolved
// with the session. It rides on the principal so the per tool API gate is a context read rather than
// a database round trip on every request, and so a change to entitlement takes effect on the next
// session resolve rather than being cached indefinitely.
//
// Empty means entitled to nothing, which is the intended fail closed default; it is never a signal
// that the set was simply not loaded.
Tools []string
}
// WithUser stores the validated principal in ctx. Call this ONLY from auth middleware.
func WithUser(ctx context.Context, p Principal) context.Context {
return context.WithValue(ctx, principalKey, p)
}
// UserFromContext returns the validated principal and whether one with a non-empty user id is
// present.
func UserFromContext(ctx context.Context) (Principal, bool) {
p, ok := ctx.Value(principalKey).(Principal)
return p, ok && p.UserID != ""
}
// Router resolves the leaf tenant DB for an organization under the database per tenant model: it
// acquires that tenant's own pool plus a release the caller must invoke. The per tenant pool manager
// satisfies it. A DB with a nil router is shared mode, where every request uses the one static Pool and
// isolation rests entirely on Row Level Security. With a router the DB is per tenant mode, where each
// request physically routes to its own tenant's database and RLS becomes defense in depth.
type Router interface {
Acquire(ctx context.Context, org uuid.UUID) (*DB, func(), error)
}
// DB wraps either a single pgxpool.Pool (shared mode, authenticating as the NOBYPASSRLS application
// role) or a Router (per tenant mode) that resolves the request's tenant pool. Pool is nil in per
// tenant mode.
type DB struct {
Pool *pgxpool.Pool
router Router
}
// New wraps a pool as a tenant-scoped DB: shared mode, or a leaf tenant DB the manager hands back.
func New(pool *pgxpool.Pool) *DB { return &DB{Pool: pool} }
// NewRouting builds a routing DB with no static pool: every access resolves the caller's tenant
// database from the router using the validated org in context. This is how per tenant mode reaches
// tenant data while leaving every handler and every RunInTenantTx call site unchanged.
func NewRouting(r Router) *DB { return &DB{router: r} }
// Ready reports whether this DB can reach a database at all. It is the ONLY correct way for a service to
// ask "am I configured", and services must not test Pool themselves.
//
// Pool is nil BY DESIGN in per tenant mode, where the database is resolved per request through the
// router. Roughly twenty services were written against `db.Pool == nil` as a stand in for "no database
// configured" and returned 503 before ever calling RunInTenantTx, which would have routed correctly. The
// effect was that enabling per tenant routing permanently disabled the audit trail, adverse impact
// reporting, governance, alerts, sourcing, awards, wages, and both opportunity surfaces, while the boot
// log cheerfully reported the routed compliance pool as active. The routing layer worked; the guard in
// front of it did not know routing existed.
func (db *DB) Ready() bool { return db != nil && (db.Pool != nil || db.router != nil) }
// Close releases the underlying pool. It is a no op for a routing DB, because the manager owns the
// tenant pools and closing one here would pull it out from under other in flight requests.
func (db *DB) Close() {
if db.Pool != nil {
db.Pool.Close()
}
}
// resolveLeaf returns the DB to actually run against for this request plus a release the caller MUST
// invoke. In shared mode that is the DB itself with a no op release. In per tenant mode it acquires the
// tenant's leaf DB by the validated org in context, failing closed when there is no validated org so a
// request without one still reaches zero data rather than an arbitrary tenant.
func (db *DB) resolveLeaf(ctx context.Context) (*DB, func(), error) {
if db.router == nil {
return db, func() {}, nil
}
orgStr, ok := OrgFromContext(ctx)
if !ok {
return nil, nil, ErrNoTenant
}
org, err := uuid.Parse(orgStr)
if err != nil {
return nil, nil, ErrNoTenant
}
return db.router.Acquire(ctx, org)
}
// Acquire exposes the request's leaf DB, and a release the caller MUST invoke, for the readers that
// touch a pool directly rather than going through RunInTenantTx: the global reference catalog reads and
// the stored skill matcher. In shared mode it is a no op wrapper over the single pool; in per tenant
// mode it routes to the tenant's own database.
func (db *DB) Acquire(ctx context.Context) (*DB, func(), error) { return db.resolveLeaf(ctx) }
// RunInTenantTx is THE correctness boundary. It:
// 1. requires a validated org id (fail-closed: no org => no query, before the pool is touched),
// 2. opens a transaction on a single pooled connection,
// 3. sets app.current_org_id transaction-locally via set_config(..., is_local=true) so it
// auto-resets at COMMIT/ROLLBACK and cannot leak across the pool,
// 4. runs fn against that same tx, then commits (rolling back on any error).
//
// All tenant-scoped repository work MUST go through this method.
func (db *DB) RunInTenantTx(ctx context.Context, fn func(ctx context.Context, tx pgx.Tx) error) (err error) {
orgID, ok := OrgFromContext(ctx)
if !ok {
return ErrNoTenant
}
// In per tenant mode this routes to the org's own database, and refuses without a validated org. In
// shared mode leaf is this DB and release is a no op. The org GUC is still set below either way, so
// RLS stays armed inside the tenant database as defense in depth rather than as the only barrier.
leaf, release, err := db.resolveLeaf(ctx)
if err != nil {
return err
}
defer release()
if leaf.Pool == nil {
return ErrNoTenant
}
tx, err := leaf.Pool.Begin(ctx)
if err != nil {
return fmt.Errorf("begin tenant tx: %w", err)
}
// Rollback is a no-op once Commit succeeds; this guarantees the connection is released on every path.
defer func() { _ = tx.Rollback(ctx) }()
// Transaction-local GUC, parameterized (no SQL-injection surface). is_local=true is what makes
// this safe on a pooled connection.
if _, err = tx.Exec(ctx, "SELECT set_config('app.current_org_id', $1, true)", orgID); err != nil {
return fmt.Errorf("set tenant guc: %w", err)
}
if err = fn(ctx, tx); err != nil {
return err // defer rolls back
}
if err = tx.Commit(ctx); err != nil {
return fmt.Errorf("commit tenant tx: %w", err)
}
return nil
}
// Middleware resolves the org id from an already-validated request and stores it in context.
// resolveOrg MUST read verified session/JWT claims, never a raw client value. A request whose org
// cannot be resolved is rejected with 403 before any downstream handler runs.
func Middleware(resolveOrg func(*http.Request) (string, bool)) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
orgID, ok := resolveOrg(r)
if !ok {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
next.ServeHTTP(w, r.WithContext(WithOrg(r.Context(), orgID)))
})
}
}