authz

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Overview

Package authz wires the authz service: the fragment-loaded engine, the transactional grant store, the effective-access decision, and their HTTP surface. This file holds the real (non-faked) Deps implementations — small HTTP clients against identity/registry's existing internal endpoints, following org's internal/org/identityclient.go pattern (validates over HTTP, not by trusting input). Every request-body value that lands in a URL path is url.PathEscape'd, so a companyId of "x/state?y" is one path segment, never a different endpoint.

Platform-role grant/revoke: the tuple `system:platform#superadmin @ user:<subjectId>` is the platform role's ONLY record, so authz owns its mutation. Both routes are superadmin-gated by the same global-scope decision every AdminAuthorizer in the platform asks (the gateway's RequireSuperadmin guard asks it too, before proxying here), write the tuple through the grant ledger and the audit row in ONE transaction, and hold an advisory lock so two concurrent revokes can never leave the platform with zero superadmins.

The EffectiveAccessSummary composition (the effective-access "Summary contract").

This composes each field from data the system genuinely has today, never inventing a new storage surface (no new deps, no decision caching):

  • featureKeys: re-derives "is this ALLOWED" per feature via the SAME decision.Decider every enforcement call already uses (never a separate, potentially-drifting answer) — the one feature key actually wired into this codebase today (auth.platform_administration.access, mirrored from gateway's platform_admin.go/registry's adminauthz.go) plus one synthesized "<moduleKey>.access" feature per registry-known+enabled module, evaluated at company scope when a companyId is given. There is no feature/manifest catalog yet, so this is the honest ceiling of what "featureKeys" can mean right now.
  • roleBindings: the platform role (DB-backed, same PlatformRoleSource every decision uses) plus, when a companyId is given, the company type's own declared non-system relations (internal/authz/harness/model.fga: "admin", "viewer") checked directly against the engine — there is no grantable-relations catalog yet either, so these two are the full honest set.
  • objectAccess: every DIRECT tuple naming the subject (internal/authz/store. ListDirectTuplesForSubject), grouped by object.
  • rowScopes / fieldPolicies: empty arrays. Segment-rule compilation and field-policy evaluation are not built yet.

Index

Constants

This section is empty.

Variables

View Source
var ErrTokenInvalid = errors.New("authz: bearer token invalid")

ErrTokenInvalid covers any bearer validation failure.

Functions

func CheckMigrationsApplied

func CheckMigrationsApplied(ctx context.Context, pool *pgxpool.Pool) error

CheckMigrationsApplied verifies migrations have been run — it never runs them itself (ARCH-004: no runtime DDL, ever; migrations are applied out-of-band by `make migrate-authz`, as the kiban owner role). Same pattern as internal/org/store.go and internal/registry/store.go.

Types

type Claims

type Claims struct {
	Subject  string
	ClientID string
}

Claims is the verified identity a bearer carries: the subject (kcSub) and the client the token was issued to (`azp`). Identity only, never authority.

type IdentityClient

type IdentityClient struct {
	HTTP    *http.Client
	BaseURL string
}

IdentityClient calls identity's GET /internal/identity/users/{kcSub}/state. It answers BOTH decision.SubjectSource (step 1/3: lifecycle) and decision.KeycloakSource (step 2: kcEnabled), since both ride the same response. The platform role is NOT identity's to answer (enginePlatformRoleSource below).

func NewIdentityClient

func NewIdentityClient(client *http.Client, baseURL string) *IdentityClient

func (*IdentityClient) Enabled

func (c *IdentityClient) Enabled(ctx context.Context, subjectID string) (decision.KCState, error)

Enabled implements decision.KeycloakSource (step 2). identity's kcEnabled is itself a tri-state string ("true"/"false"/"unknown" — see internal/identity/state.go); never defaulted to enabled on ambiguity.

func (*IdentityClient) Lookup

func (c *IdentityClient) Lookup(ctx context.Context, subjectID string) (decision.SubjectResult, error)

Lookup implements decision.SubjectSource (step 1/3).

type OrgClient

type OrgClient struct {
	HTTP    *http.Client
	BaseURL string
}

OrgClient calls org's internal company-facts endpoints — implements decision.CompanySource and decision.MembershipSource end-to-end. Both endpoints are open internal reads (no bearer required org-side, same shape as identity's own GET /internal/identity/users/{kcSub}/state) since they answer pure facts, not user-facing data; the effective-access endpoint itself is the bearer-gated boundary.

func NewOrgClient

func NewOrgClient(client *http.Client, baseURL string) *OrgClient

func (*OrgClient) Membership

func (c *OrgClient) Membership(ctx context.Context, companyID, subjectID string) (decision.MembershipState, error)

Membership implements decision.MembershipSource (step 5) via GET /internal/org/companies/{companyID}/members/by-kcsub/{subjectID}. Membership is real (a linked member row exists); Blocked = COMPANY_ACCESS_BLOCKED's v1 source, `member.is_active = false` on an existing membership — never derived any other way.

func (*OrgClient) State

func (c *OrgClient) State(ctx context.Context, companyID string) (decision.CompanyState, error)

State implements decision.CompanySource (step 5) via GET /internal/org/companies/{companyID}/state. Any transport/decode failure or non-200 status is a genuine dependency failure (⇒ DEPENDENCY_UNAVAILABLE) — never defaulted to exists/isActive=true.

type RegistryClient

type RegistryClient struct {
	HTTP    *http.Client
	BaseURL string
}

RegistryClient calls registry's GET /api/platform/capabilities/{module} for decision.ModuleStateSource (step 6).

func NewRegistryClient

func NewRegistryClient(client *http.Client, baseURL string) *RegistryClient

func (*RegistryClient) AppFeatures

func (c *RegistryClient) AppFeatures(ctx context.Context) (map[string]map[string]bool, error)

AppFeatures returns, for every registered app and every built-in module that declares feature keys, the set it declares. A module declaring none is absent and unrestricted.

func (*RegistryClient) AppOwners

func (c *RegistryClient) AppOwners(ctx context.Context) (map[string]string, error)

AppOwners returns module_key -> service client id for every registered app (a module with no service client is absent).

func (*RegistryClient) Enabled

func (c *RegistryClient) Enabled(ctx context.Context, moduleKey string) (bool, error)

Enabled implements decision.ModuleStateSource.

func (*RegistryClient) KnownEnabled

func (c *RegistryClient) KnownEnabled(ctx context.Context) (map[string]bool, error)

KnownEnabled calls registry's GET /api/platform/capabilities to build the module_key -> true set fragment.Load needs (only registry-known, enabled modules' fragments merge into the effective model).

type Service

type Service struct {
	Pool         *pgxpool.Pool
	Audit        *audit.Writer
	KnownEnabled func(ctx context.Context) (map[string]bool, error) // registry-known+enabled module keys, for fragment.Load
	// AppOwners maps a registered app's module key to its service client id (the verified
	// `azp` its backend's token carries). Nil means "no apps": the grants owner rule never
	// fires.
	AppOwners func(ctx context.Context) (map[string]string, error)
	// AppFeatures maps a module key (a registered app, or a built-in module that declares
	// features) to its declared feature keys; /can and /batch-can refuse (422) any other key for
	// that module, except "<key>.access". Nil means no restriction anywhere.
	AppFeatures func(ctx context.Context) (map[string]map[string]bool, error)
	Verifier    *TokenVerifier
	DebugCheck  bool

	Identity *IdentityClient
	Registry *RegistryClient
	Org      *OrgClient

	// Metrics records kiban_authz_decisions_total{reason} + kiban_authz_decision_duration_seconds
	// for the two real enforcement endpoints (/effective-access/can, /batch-can) —
	// deliberately NOT the /effective-access/summary endpoint's own internal decider.Evaluate
	// calls (summary.go), which compose a display read across every feature/module rather than
	// answer one real enforcement question; counting those under the same metric would make
	// "DENY reason spiking" alerts fire on ordinary nav-summary reads instead of real access
	// checks. A nil Metrics (e.g. tests that don't wire it) makes recordDecision/
	// recordBatchDecisions no-ops via *metrics.Registry's own nil-receiver safety.
	Metrics *metrics.Registry
}

Service wires the engine, fragment loader, store and decision behind the HTTP surface. DebugCheck, when true, exposes the raw diagnostics-only `check` endpoint.

func (*Service) Routes

func (svc *Service) Routes() http.Handler

Routes builds authz's HTTP handler. Every effective-access/grants endpoint requires a validated bearer (never an actor from a request body); `check` is diagnostics-only, wired only when Service.DebugCheck is true. The `summary` endpoint is the one deliberate exception to the bearer rule: it takes kcSub as a query param, the same "internal, unauthenticated read, caller supplies the identity" shape org's own internal facts endpoints use — the gateway is the bearer-validating boundary for it, injecting the caller's own kcSub, never trusting a client-supplied one.

type TokenVerifier

type TokenVerifier struct {
	// contains filtered or unexported fields
}

TokenVerifier is authz's own copy of identity's bearer verifier (same lestrrat-go/jwx/v3 pattern, duplicated locally rather than importing internal/identity as a library — each service owns its own small infra helpers in this codebase, same as every dbtest_env.go). Actor identity for effective-access requests is ALWAYS this validated bearer subject (Forbidden: never accept an actor from a request body).

func NewTokenVerifier

func NewTokenVerifier(ctx context.Context, jwksURL, issuer, audience string) (*TokenVerifier, error)

func (*TokenVerifier) Refresh

func (v *TokenVerifier) Refresh(ctx context.Context) error

func (*TokenVerifier) Verify

func (v *TokenVerifier) Verify(ctx context.Context, bearerToken string) (string, error)

Verify returns the validated subject (kcSub). azp is never treated as an audience fallback.

func (*TokenVerifier) VerifyClaims

func (v *TokenVerifier) VerifyClaims(ctx context.Context, bearerToken string) (Claims, error)

VerifyClaims is Verify plus the token's `azp`.

Directories

Path Synopsis
Package client is the shared "is this caller the platform superadmin" AdminAuthorizer implementation, used by org, identity, registry and the gateway's superadmin guard.
Package client is the shared "is this caller the platform superadmin" AdminAuthorizer implementation, used by org, identity, registry and the gateway's superadmin guard.
Package decision implements the effective-access decision EXACTLY: the ordered 8-step, fail-closed effective-access decision, the 13-reason enum (OPENFGA_DENIED is named ENGINE_DENIED here — the engine is not OpenFGA), and evidence/batchCan semantics.
Package decision implements the effective-access decision EXACTLY: the ordered 8-step, fail-closed effective-access decision, the 13-reason enum (OPENFGA_DENIED is named ENGINE_DENIED here — the engine is not OpenFGA), and evidence/batchCan semantics.
Package engine is the evaluator for the supported Zanzibar subset (this, computedUserset, tupleToUserset, union, intersection).
Package engine is the evaluator for the supported Zanzibar subset (this, computedUserset, tupleToUserset, union, intersection).
Package fragment loads module authz fragments (a module's authz.fragment.json "relations" JSON) into the effective engine.Model, subset-walled and inert for modules the registry doesn't know about or has disabled: an unknown/disabled module's fragment contributes NOTHING to the effective model, and — the property this package exists to prove — a check against an object type that belongs ONLY to such a fragment answers false, never errors, never allows.
Package fragment loads module authz fragments (a module's authz.fragment.json "relations" JSON) into the effective engine.Model, subset-walled and inert for modules the registry doesn't know about or has disabled: an unknown/disabled module's fragment contributes NOTHING to the effective model, and — the property this package exists to prove — a check against an object type that belongs ONLY to such a fragment answers false, never errors, never allows.
The default module-access tuple writer.
The default module-access tuple writer.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL