Files
iam/internal/authz/scope_test.go
zeekay ef2f42a2ec Decide SuperAdmin on the row's own org
schema.User.SuperAdmin is the one predicate: a person whose row's owner
is the admin org. The Guard sets Principal.Sudo from it when it loads
the caller, and assume/release, device approval, unlink, the bootstrap
credential freeze and the registry push gate ask the row directly.
store.IsSuperAdmin, which also admitted a membership of the admin org,
is gone. A brand org's user added to the admin org is an ordinary
member of their own org, and a service account or program in the admin
org is never SuperAdmin.

hanzoai/authz v1.10.42 reads the same rule off a token (Claims.Sudo on
orgs[0]) and lets a membership of the admin org open nothing, so such a
member no longer reads or edits the admin org's registry row either.
The token IAM mints is unchanged: orgs still opens with the row's
owner.

Two protective gates keep the whole admin org, machines and unheld
names included: no secret key names an account there
(store.SuperAdminKey), and only a SuperAdmin writes one
(users.Authorize). Both read the owner as written, so neither reads the
store.

Every request the Guard admits for a SuperAdmin is recorded as a
superadmin audit row, PlatformWritten, with its method, address, answer
and client address; so is a SuperAdmin's unlink of someone else's
sign-in method and a device approval into another org.

TestEverySuperAdminGateAdmitsTheAdminOrgsPeopleOnly drives ten
SuperAdmin-only requests through the router as two SuperAdmins, a brand
admin holding an admin-org membership and two admin-org machines, and
reads the trail row each one leaves.

Claude-Session: https://claude.ai/code/session_01HuMDfgFssPUptYUzgZ6Cp8
2026-09-27 19:24:51 -07:00

764 lines
30 KiB
Go

// Copyright 2026 Hanzo AI, Inc.
// SPDX-License-Identifier: MIT OR Apache-2.0
package authz_test
// AN ORG-SCOPED REQUEST IS HONOURED OR REFUSED, NEVER SILENTLY REINTERPRETED.
//
// A listing that quietly drops the ?owner= filter answers 200 with the caller's
// own rows whatever org was asked for, so a fabricated org is indistinguishable
// from a real one AND from the caller's own. Nothing in the status code, the
// `status` field, the message or the count carries the difference — the caller
// holds tenant A believing it holds tenant B, and then filters and writes.
//
// A status code is therefore NOT the contract here. Every case asserts on the
// RECORDS that crossed the wire, because "200 with somebody else's rows" is the
// exact answer these tests exist to make impossible.
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http/httptest"
"testing"
"github.com/hanzoai/orm"
"github.com/hanzoai/iam/pkg/schema"
"github.com/hanzoai/iam/internal/testhttp"
)
// The two spellings an unauthorized caller must not be able to tell apart: a
// FOREIGN-BUT-REAL tenant, and a name no tenant has ever had. If these two
// answers differ in any byte, the refusal is an org-existence oracle.
const (
foreignRealOrg = "lux"
fabricatedOrg = "nonexistent-org-xyz"
// reservedOrg is the organization whose membership IS SuperAdmin, spelled here
// because these tests are the package's outside view (authz_test) and the
// constant is unexported. store.IsSuperAdmin holds the same word.
reservedOrg = "admin"
)
// ---- request helpers -------------------------------------------------------
// reply is one response reduced to what a client can actually observe.
type reply struct {
status int
body string
}
// row is the only part of a listed record these assertions read: which tenant it
// belongs to.
type row struct {
Owner string `json:"owner"`
}
// records returns the rows that actually crossed the wire. A collection names its
// own array — users, projects, organizations — so the key is READ from the body
// instead of assumed, and one decoder serves every listing. A refusal carries no
// array at all, which is the point.
func (r reply) records(t *testing.T) []row {
t.Helper()
var body map[string]json.RawMessage
if err := json.Unmarshal([]byte(r.body), &body); err != nil {
return nil
}
var out []row
for _, raw := range body {
var rows []row
if json.Unmarshal(raw, &rows) == nil {
out = append(out, rows...)
}
}
return out
}
// owners returns the DISTINCT owners present in a listing — the misattribution
// assertion: a request for org X must never answer with rows owned by Y.
func (r reply) owners(t *testing.T) map[string]int {
t.Helper()
got := map[string]int{}
for _, u := range r.records(t) {
if u.Owner != "" {
got[u.Owner]++
}
}
return got
}
// send issues one request through the REAL registered router and returns
// everything a client sees. auth is applied verbatim as the Authorization value.
func (h *harness) send(t *testing.T, method, path, auth string, body any) reply {
t.Helper()
var r io.Reader
if body != nil {
b, _ := json.Marshal(body)
r = bytes.NewReader(b)
}
req := httptest.NewRequest(method, path, r)
req.Host = "hanzo.id"
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if auth != "" {
req.Header.Set("Authorization", auth)
}
resp, err := testhttp.Do(h.app, req)
if err != nil {
t.Fatalf("%s %s: %v", method, path, err)
}
b, _ := io.ReadAll(resp.Body)
_ = resp.Body.Close()
return reply{status: resp.StatusCode, body: string(b)}
}
// asApp is the client_secret_basic header a confidential client sends — the
// exact transport the hanzo-console credential used in the production repro.
func asApp(clientID, secret string) string {
return "Basic " + base64.StdEncoding.EncodeToString([]byte(clientID+":"+secret))
}
// asUser is the bearer header a human carries.
func asUser(tok string) string { return "Bearer " + tok }
// ---- fixtures --------------------------------------------------------------
// seedScopeFixture builds the production shape: a foreign-but-real tenant `lux`
// with its own users and projects alongside hanzo's, plus the admin-owned
// hanzo-console application whose capability allowlist admits it to the users
// entity. That capability is what carries the request PAST the Guard and into
// principal.Scope — without it the Guard refuses first and the silent discard is
// never reached, which is why a unit test on authorize() alone proves nothing
// here.
func seedScopeFixture(t *testing.T, h *harness) {
t.Helper()
t.Setenv("IAM_USER_ADMIN_APPS", "hanzo-console")
t.Setenv("IAM_ORG_ADMIN_APPS", "hanzo-console")
seedAppRow(t, h.db, "admin", "hanzo-console", "s3cret", signingKid)
// The foreign-but-real tenant. Its org row exists, its users exist — so a
// refusal that consulted the store COULD tell it apart from a fabrication.
seedOrgRow(t, h.db, foreignRealOrg)
seedUser(t, h.db, foreignRealOrg, "lux-alice", true, false, false)
seedUser(t, h.db, foreignRealOrg, "lux-bob", false, false, false)
seedProjectRow(t, h.db, foreignRealOrg, "lux-secret-project")
seedOrgRow(t, h.db, "hanzo")
seedProjectRow(t, h.db, "hanzo", "hanzo-project")
}
// seedOrgRow registers a tenant in the org registry, which is admin-owned: the
// org's identity is its NAME, not its owner.
func seedOrgRow(t *testing.T, db orm.DB, name string) {
t.Helper()
o := orm.New[schema.Organization](db)
o.Owner, o.Name = "admin", name
o.SetId("admin/" + name)
if err := o.CreateCtx(context.Background()); err != nil {
t.Fatalf("seed org %s: %v", name, err)
}
}
// seedProjectRow adds one project under a tenant.
func seedProjectRow(t *testing.T, db orm.DB, owner, name string) {
t.Helper()
p := orm.New[schema.Project](db)
p.Owner, p.Name = owner, name
p.SetId(owner + "/" + name)
if err := p.CreateCtx(context.Background()); err != nil {
t.Fatalf("seed project %s/%s: %v", owner, name, err)
}
}
// ---- the bug ---------------------------------------------------------------
// THE PRODUCTION REPRO. A non-super principal asking for an org that is not its
// own must be REFUSED — not answered with its own org's rows under the foreign
// org's name.
func TestScope_ForeignOrgIsRefusedNotSilentlyReinterpreted(t *testing.T) {
h := newHarness(t)
seedScopeFixture(t, h)
auth := asApp("hanzo-console", "s3cret")
// Own org: unchanged, and it is what makes the foreign case meaningful —
// there ARE hanzo rows to be misattributed.
own := h.send(t, "GET", "/v1/iam/projects?owner=hanzo", auth, nil)
if own.status != 200 {
t.Fatalf("own-org listing = %d, want 200 (unchanged): %s", own.status, own.body)
}
if len(own.records(t)) == 0 {
t.Fatal("own-org listing returned no rows; the fixture cannot prove misattribution")
}
for _, org := range []string{foreignRealOrg, fabricatedOrg} {
t.Run(org, func(t *testing.T) {
got := h.send(t, "GET", "/v1/iam/projects?owner="+org, auth, nil)
// (1) The refusal must be EXPLICIT.
if got.status != 403 {
t.Errorf("GET projects?owner=%s = %d, want 403 — an org-scoped request "+
"is honoured or refused, never silently reinterpreted: %s",
org, got.status, got.body)
}
// (2) And it must carry NOTHING. A 403 that still ships rows, or a
// 200 carrying the caller's own rows under another org's name, is
// the misattribution this closes.
if owners := got.owners(t); len(owners) > 0 {
t.Errorf("GET projects?owner=%s returned rows owned by %v — the caller "+
"asked for %s and was handed somebody else's tenant", org, owners, org)
}
})
}
}
// The refusal must not become an ORG-EXISTENCE ORACLE. A foreign-but-real tenant
// and a name no tenant has ever had must be answered IDENTICALLY, byte for byte,
// or an unauthorized caller enumerates the customer list one guess at a time.
//
// The property is structural, not cosmetic: the decision is taken from the
// verified principal alone and never touches the store, so there is no lookup
// whose outcome could differ. This test is what keeps it that way.
func TestScope_ForeignAndFabricatedOrgsAreIndistinguishable(t *testing.T) {
h := newHarness(t)
seedScopeFixture(t, h)
auth := asApp("hanzo-console", "s3cret")
for _, path := range []string{
"/v1/iam/organizations?owner=",
"/v1/iam/projects?owner=",
"/v1/iam/workspaces?owner=",
"/v1/iam/scim/v2/Users?owner=",
} {
t.Run(path, func(t *testing.T) {
real := h.send(t, "GET", path+foreignRealOrg, auth, nil)
fake := h.send(t, "GET", path+fabricatedOrg, auth, nil)
if real.status != fake.status {
t.Errorf("%s: real org -> %d, fabricated org -> %d: the STATUS distinguishes "+
"a tenant that exists from one that does not", path, real.status, fake.status)
}
if real.body != fake.body {
t.Errorf("%s: the BODY distinguishes a real tenant from a fabricated one\n"+
" real (%s): %s\n fake (%s): %s",
path, foreignRealOrg, real.body, fabricatedOrg, fake.body)
}
})
}
}
// A SuperAdmin's cross-tenant reach is the ONE cross-tenant scope and is
// unchanged: it asks for lux and it gets LUX, not hanzo.
func TestScope_SuperAdminCrossOrgReadIsUnchanged(t *testing.T) {
h := newHarness(t)
seedScopeFixture(t, h)
root := asUser(h.token(t, "admin/root"))
got := h.send(t, "GET", "/v1/iam/users?owner="+foreignRealOrg, root, nil)
if got.status != 200 {
t.Fatalf("SuperAdmin cross-org listing = %d, want 200: %s", got.status, got.body)
}
owners := got.owners(t)
if owners[foreignRealOrg] == 0 {
t.Errorf("SuperAdmin asked for %s and got %v — cross-tenant reach regressed",
foreignRealOrg, owners)
}
if len(owners) != 1 {
t.Errorf("SuperAdmin asked for %s and got rows from %v — the owner filter was dropped",
foreignRealOrg, owners)
}
}
// Own-org access is untouched for a HUMAN too, on the endpoints the Guard does
// not pre-authorize (their target rides in ?organization=, so principal.Scope is the
// only gate they have).
func TestScope_OwnOrgReadIsUnchangedForAHuman(t *testing.T) {
h := newHarness(t)
seedScopeFixture(t, h)
boss := asUser(h.token(t, "hanzo/boss"))
got := h.send(t, "GET", "/v1/iam/projects?owner=hanzo", boss, nil)
if got.status != 200 {
t.Fatalf("own-org project list = %d, want 200 (unchanged): %s", got.status, got.body)
}
if len(got.records(t)) == 0 {
t.Errorf("own-org project list came back empty: %s", got.body)
}
}
// The SAME silent discard, reachable by an ORDINARY HUMAN — no client credential
// needed. get-organization-projects and get-organization-workspaces are
// handler-authorized (their target rides in ?organization=, which the Guard does
// not inspect), so principal.Scope is the whole gate, and it rewrote the parameter.
// An org admin asking for lux's projects got HANZO's, labelled lux.
func TestScope_HandlerAuthorizedReadsAreNotSilentlyRewritten(t *testing.T) {
h := newHarness(t)
seedScopeFixture(t, h)
boss := asUser(h.token(t, "hanzo/boss"))
for _, path := range []string{
"/v1/iam/projects?owner=" + foreignRealOrg,
"/v1/iam/workspaces?owner=" + foreignRealOrg,
} {
t.Run(path, func(t *testing.T) {
got := h.send(t, "GET", path, boss, nil)
if got.status != 403 {
t.Errorf("GET %s = %d, want 403: %s", path, got.status, got.body)
}
var env struct {
Data []map[string]any `json:"data"`
}
_ = json.Unmarshal([]byte(got.body), &env)
for _, row := range env.Data {
t.Errorf("GET %s returned a row owned by %v — a hanzo row answering a "+
"request for %s is the misattribution, not a leak", path, row["owner"], foreignRealOrg)
}
})
}
}
// THE WORST SHAPE OF THE BUG: a path-targeted SCIM read. `/Users/lux/alice`
// named a specific row in a specific tenant; Scope rewrote the owner half and
// the handler answered with hanzo/alice — a DIFFERENT HUMAN, under the requested
// identity's URL. A caller that then acts on that record acts on the wrong
// person in the wrong tenant.
func TestScope_SCIMPathTargetIsNeverRewrittenToAnotherTenant(t *testing.T) {
h := newHarness(t)
seedScopeFixture(t, h)
boss := asUser(h.token(t, "hanzo/boss"))
got := h.send(t, "GET", "/v1/iam/scim/v2/Users/"+foreignRealOrg+"/alice", boss, nil)
if got.status == 200 {
t.Errorf("GET /Users/%s/alice = 200 — it resolved SOMEBODY, and hanzo/alice is "+
"the only alice there is: %s", foreignRealOrg, got.body)
}
if got.status != 403 {
t.Errorf("GET /Users/%s/alice = %d, want 403: %s", foreignRealOrg, got.status, got.body)
}
}
// A WRITE misattribution is worse than a read one: a SCIM provisioning call that
// named tenant `lux` created the account inside `hanzo`. Assert the refusal AND
// that nothing was persisted anywhere — the real security property, not the
// status code.
func TestScope_SCIMProvisioningNeverLandsInTheWrongTenant(t *testing.T) {
h := newHarness(t)
seedScopeFixture(t, h)
boss := asUser(h.token(t, "hanzo/boss"))
body := map[string]any{
"schemas": []string{"urn:ietf:params:scim:schemas:core:2.0:User"},
"userName": "misfiled",
"urn:ietf:params:scim:schemas:extension:hanzo:2.0:User": map[string]any{
"owner": foreignRealOrg,
},
}
got := h.send(t, "POST", "/v1/iam/scim/v2/Users", boss, body)
if got.status == 201 {
t.Errorf("SCIM create naming owner=%s succeeded (%d): %s", foreignRealOrg, got.status, got.body)
}
if h.userExists(t, "hanzo", "misfiled") {
t.Errorf("a create that NAMED tenant %s persisted the account under hanzo — "+
"the caller believes it provisioned %s", foreignRealOrg, foreignRealOrg)
}
if h.userExists(t, foreignRealOrg, "misfiled") {
t.Errorf("a hanzo admin provisioned an account inside %s", foreignRealOrg)
}
}
// get-users AND get-organization must give the SAME answer to "may this
// principal see another tenant's org?" — for every principal that holds no
// cross-tenant grant. A human org-admin is the case that carries a secret, and on
// both verbs a foreign-but-real org and a fabricated one are the identical
// existence-independent refusal. Answering one of them differently would make the
// pair an org-existence oracle no matter how carefully the other was written.
func TestScope_GetUsersAndGetOrganizationAgreeForAnUngrantedPrincipal(t *testing.T) {
h := newHarness(t)
seedScopeFixture(t, h)
boss := asUser(h.token(t, "hanzo/boss")) // org-admin of hanzo, no capability, not super
for _, verb := range []struct{ name, pattern string }{
{"get-users", "/v1/iam/users?owner=%s"},
{"get-organization", "/v1/iam/organizations/admin/%s"},
} {
t.Run(verb.name, func(t *testing.T) {
real := h.send(t, "GET", fmt.Sprintf(verb.pattern, foreignRealOrg), boss, nil)
fake := h.send(t, "GET", fmt.Sprintf(verb.pattern, fabricatedOrg), boss, nil)
if real.status == 200 || fake.status == 200 {
t.Errorf("%s admitted a foreign org: real=%d fake=%d", verb.name, real.status, fake.status)
}
if real.status != fake.status || real.body != fake.body {
t.Errorf("%s distinguishes a real tenant from a fabricated one — that pair IS "+
"the org-existence oracle\n real: %d %s\n fake: %d %s",
verb.name, real.status, real.body, fake.status, fake.body)
}
})
}
}
// The other half of the coherent policy: where a cross-tenant grant DOES exist,
// it HONOURS the org the request names. CapOrgAdmin is the brand consoles'
// registry authority — they create customer orgs during onboarding and read
// Organization.Founder to resume a partial one — so a grant holder asking for lux
// gets LUX's row. Correctly attributed is the whole requirement; substituting
// hanzo's row here would be the same misattribution wearing a capability.
func TestScope_AGrantHonoursTheOrgItNamesAndNeverSubstitutes(t *testing.T) {
h := newHarness(t)
seedScopeFixture(t, h)
got := h.send(t, "GET", "/v1/iam/organizations/admin/"+foreignRealOrg,
asApp("hanzo-console", "s3cret"), nil)
if got.status != 200 {
t.Fatalf("CapOrgAdmin registry read = %d, want 200 — onboarding reads Founder "+
"through this: %s", got.status, got.body)
}
var org struct {
Owner string `json:"owner"`
Name string `json:"name"`
}
if err := json.Unmarshal([]byte(got.body), &org); err != nil {
t.Fatalf("decode %s: %v", got.body, err)
}
if org.Name != foreignRealOrg {
t.Errorf("asked for org %q, got %q — a grant must return the org it was asked for, "+
"never another", foreignRealOrg, org.Name)
}
}
// An UNSTATED scope is not a reinterpreted one. Omitting ?owner= has always
// meant "my own org" and still does — the rule is about a request that NAMES an
// org it may not have, not about one that names none.
func TestScope_UnstatedOwnerStillMeansOwnOrg(t *testing.T) {
h := newHarness(t)
seedScopeFixture(t, h)
got := h.send(t, "GET", "/v1/iam/projects", asApp("hanzo-console", "s3cret"), nil)
if got.status != 200 {
t.Fatalf("project list with no owner = %d, want 200 (unchanged): %s", got.status, got.body)
}
owners := got.owners(t)
if owners["hanzo"] == 0 || len(owners) != 1 {
t.Errorf("project list with no owner returned %v, want hanzo only", owners)
}
}
// seedMembership grants a user the right to act in an org that is not their
// home. It is the shape a real console user has: one account, several orgs.
func seedMembership(t *testing.T, db orm.DB, user, org, role string) {
t.Helper()
m := orm.New[schema.Membership](db)
m.Owner, m.Name = org, user+"@"+org
m.User, m.Org, m.Role = user, org, role
m.SetId(org + "/" + user)
if err := m.CreateCtx(context.Background()); err != nil {
t.Fatalf("seed membership %s in %s: %v", user, org, err)
}
}
// THE PRODUCTION BUG, and its exact repro. [email protected] administers several orgs;
// the console's switcher listed them and clicking one did nothing, because
// get-organization-projects?organization=<other> answered 403 and the switcher
// swallowed it. The account's HOME org was the only org it could read — the
// membership set, which IAM itself mints into the token's `orgs` claim to
// authorize exactly this switch, was ignored on IAM's own surface.
func TestScopeRead_AnOrgYouBelongToOpens(t *testing.T) {
h := newHarness(t)
seedScopeFixture(t, h)
// A hanzo account that ADMINISTERS the other tenant, the way a real operator does.
seedUser(t, h.db, "hanzo", "crossorg", false, false, false)
seedMembership(t, h.db, "hanzo/crossorg", foreignRealOrg, "admin")
crossorg := asUser(h.token(t, "hanzo/crossorg"))
for _, path := range []string{
"/v1/iam/projects?owner=" + foreignRealOrg,
"/v1/iam/workspaces?owner=" + foreignRealOrg,
} {
t.Run(path, func(t *testing.T) {
got := h.send(t, "GET", path, crossorg, nil)
if got.status != 200 {
t.Fatalf("GET %s = %d, want 200 — a member of %s cannot read it: %s",
path, got.status, foreignRealOrg, got.body)
}
// It must answer for the org ASKED FOR, never quietly for the home org.
var env struct {
Data []map[string]any `json:"data"`
}
_ = json.Unmarshal([]byte(got.body), &env)
for _, row := range env.Data {
if row["owner"] != foreignRealOrg {
t.Errorf("GET %s returned a row owned by %v — answering for the home org "+
"is the misattribution the strict clause existed to prevent", path, row["owner"])
}
}
})
}
}
// The other half, and the reason this is a separate entry point: belonging to an
// org is permission to SEE it. A stranger is still refused, byte-identically.
func TestScopeRead_AStrangerIsStillRefused(t *testing.T) {
h := newHarness(t)
seedScopeFixture(t, h)
boss := asUser(h.token(t, "hanzo/boss")) // no membership anywhere but hanzo
got := h.send(t, "GET", "/v1/iam/projects?owner="+foreignRealOrg, boss, nil)
if got.status != 403 {
t.Fatalf("a non-member read of %s = %d, want 403: %s", foreignRealOrg, got.status, got.body)
}
}
// A SuperAdmin is a person whose own org is the reserved one, and that reaches
// every tenant. A brand org's person holding a membership IN the reserved org is
// not one, and reaches no tenant but their own. This asks it on `users`
// deliberately: users is the STRICT clause, the one ordinary membership never
// opens, so a 200 here can only come from Super.
func TestSuper_OnlyTheReservedOrgsOwnPeopleReachEveryTenant(t *testing.T) {
h := newHarness(t)
seedScopeFixture(t, h)
seedUser(t, h.db, "hanzo", "operator", true, false, false)
seedMembership(t, h.db, "hanzo/operator", reservedOrg, "admin")
for _, owner := range []string{foreignRealOrg, reservedOrg} {
got := h.send(t, "GET", "/v1/iam/users?owner="+owner, asUser(h.token(t, "hanzo/operator")), nil)
if got.status != 403 {
t.Fatalf("GET users?owner=%s as hanzo/operator, a member of %q = %d, want 403: %s",
owner, reservedOrg, got.status, got.body)
}
}
got := h.send(t, "GET", "/v1/iam/users?owner="+foreignRealOrg, asUser(h.token(t, "admin/root")), nil)
if got.status != 200 {
t.Fatalf("GET users?owner=%s as admin/root = %d, want 200: %s", foreignRealOrg, got.status, got.body)
}
// And it answers for the tenant ASKED FOR — masquerade, not a home-org read.
owners := got.owners(t)
if owners[foreignRealOrg] == 0 {
t.Fatalf("GET users?owner=%s returned no %s rows (owners=%v); a SuperAdmin must be "+
"handed the tenant it named, not its own", foreignRealOrg, foreignRealOrg, owners)
}
for owner := range owners {
if owner != foreignRealOrg {
t.Errorf("GET users?owner=%s returned a row owned by %q — masquerade answers "+
"for the tenant asked for and nothing else", foreignRealOrg, owner)
}
}
}
// The other half, and the reason the reserved org is named rather than membership
// in general: ordinary membership is never platform authority. An owner or admin
// membership makes you that one tenant's admin; it never reaches a third tenant or
// the reserved org, and an unscoped page stays your own.
func TestSuper_OrdinaryMembershipIsNotSudo(t *testing.T) {
h := newHarness(t)
seedScopeFixture(t, h)
seedUser(t, h.db, "hanzo", "member", false, false, false)
seedMembership(t, h.db, "hanzo/member", foreignRealOrg, "admin")
member := asUser(h.token(t, "hanzo/member"))
// Administering lux makes it lux's admin, which reads lux's people...
got := h.send(t, "GET", "/v1/iam/users?owner="+foreignRealOrg, member, nil)
if got.status != 200 {
t.Fatalf("GET users?owner=%s as an ADMIN of %s = %d, want 200: %s",
foreignRealOrg, foreignRealOrg, got.status, got.body)
}
if owners := got.owners(t); len(owners) != 1 || owners[foreignRealOrg] == 0 {
t.Errorf("lux's admin was answered rows owned by %v", owners)
}
// ...and is not platform sudo: no other tenant, no reserved org, and naming no
// org answers its own rather than every tenant's.
for _, owner := range []string{reservedOrg, fabricatedOrg} {
if got := h.send(t, "GET", "/v1/iam/users?owner="+owner, member, nil); got.status != 403 {
t.Errorf("GET users?owner=%s as an admin of %s = %d, want 403: %s", owner, foreignRealOrg, got.status, got.body)
}
}
got = h.send(t, "GET", "/v1/iam/users", member, nil)
if owners := got.owners(t); owners[foreignRealOrg] != 0 || owners[reservedOrg] != 0 {
t.Errorf("an unscoped page for lux's admin spanned tenants: %v", owners)
}
}
// seedEmail seeds a user carrying an address, which seedUser leaves empty. The
// global page narrows by address across the WHOLE table, so proving that needs
// one address present in more than one tenant.
func seedEmail(t *testing.T, db orm.DB, owner, name, email string) {
t.Helper()
u := orm.New[schema.User](db)
u.Owner, u.Name, u.Email = owner, name, email
u.SetId(owner + "/" + name)
if err := u.CreateCtx(context.Background()); err != nil {
t.Fatalf("seed user %s/%s: %v", owner, name, err)
}
}
// A caller whose scope spans tenants and names none gets the page its scope
// allows: every tenant. This is the read the gone table's get-global-users points
// at, and the reason the owner cannot be a required field — required refuses this
// caller before the handler resolves anything.
func TestScope_SuperAdminGlobalUserPageSpansTenants(t *testing.T) {
h := newHarness(t)
seedScopeFixture(t, h)
got := h.send(t, "GET", "/v1/iam/users", asUser(h.token(t, "admin/root")), nil)
if got.status != 200 {
t.Fatalf("SuperAdmin global user page = %d, want 200: %s", got.status, got.body)
}
owners := got.owners(t)
if len(owners) < 2 {
t.Errorf("SuperAdmin named no owner and got rows from %v — a scope that spans "+
"tenants must answer across them, not fall back to one", owners)
}
if owners[foreignRealOrg] == 0 {
t.Errorf("the global page carries no %s rows (owners=%v)", foreignRealOrg, owners)
}
}
// THE LEAK GUARD. Naming no owner means "the tenant my credential is scoped to",
// and for a credential scoped to ONE tenant that is one tenant — never the table.
//
// hanzo-console is the shape that makes this reachable and the shape that made it
// dangerous: an admin-owned confidential client holding the users capability. That
// capability carries a request with NO owner named PAST the Guard and PAST the op
// seam, because both read an unnamed target as "nothing named to refuse" and hand
// it on. The handler is the only place left that holds the credential and the
// query at once, so the tenant is decided there or it is not decided at all.
func TestScope_GlobalUserPageNeverLeaksAnotherTenant(t *testing.T) {
h := newHarness(t)
seedScopeFixture(t, h)
// The human is the second half: an org admin is refused outright here, before
// the handler, so the two together say an unstated owner never widens for a
// non-super whether it carries a capability or not.
for _, c := range []struct {
who string
auth string
}{
{"hanzo-console", asApp("hanzo-console", "s3cret")},
{"hanzo/boss", asUser(h.token(t, "hanzo/boss"))},
} {
t.Run(c.who, func(t *testing.T) {
got := h.send(t, "GET", "/v1/iam/users", c.auth, nil)
owners := got.owners(t)
for owner := range owners {
if owner != "hanzo" {
t.Errorf("LEAK: %s listed users naming no owner and received %q's rows "+
"(owners=%v, status=%d).\nA credential scoped to hanzo reads hanzo or is "+
"refused; every other tenant's roster is a customer list.\nbody: %s",
c.who, owner, owners, got.status, got.body)
}
}
if got.status == 200 && owners["hanzo"] == 0 {
t.Errorf("%s got a 200 carrying no hanzo rows (owners=%v) — the assertion above "+
"cannot fail against an empty page: %s", c.who, owners, got.body)
}
})
}
// hanzo-console's own page still answers, so the guard cannot be satisfied by
// an endpoint that simply stopped working.
own := h.send(t, "GET", "/v1/iam/users", asApp("hanzo-console", "s3cret"), nil)
if own.status != 200 || own.owners(t)["hanzo"] == 0 {
t.Errorf("hanzo-console's own user page = %d owners=%v, want 200 carrying hanzo: %s",
own.status, own.owners(t), own.body)
}
}
// The address narrowing applies to the tenant-spanning page too, and the count is
// narrowed with it — a page of 2 reported as "2 of 40" is a caller paging forever
// through rows it filtered out.
func TestScope_GlobalUserPageNarrowsByEmail(t *testing.T) {
h := newHarness(t)
seedScopeFixture(t, h)
seedEmail(t, h.db, "hanzo", "pat", "[email protected]")
seedEmail(t, h.db, foreignRealOrg, "pat", "[email protected]")
seedEmail(t, h.db, "hanzo", "sam", "[email protected]")
got := h.send(t, "GET", "/v1/iam/[email protected]",
asUser(h.token(t, "admin/root")), nil)
if got.status != 200 {
t.Fatalf("global page narrowed by address = %d, want 200: %s", got.status, got.body)
}
var page struct {
Users []struct{ Owner, Name, Email string } `json:"users"`
Total int `json:"total"`
}
if err := json.Unmarshal([]byte(got.body), &page); err != nil {
t.Fatalf("decode %s: %v", got.body, err)
}
if len(page.Users) != 2 || page.Total != 2 {
t.Fatalf("address narrowing returned %d rows and a total of %d, want 2 and 2 — "+
"the page and the count must go through the same narrowing: %s",
len(page.Users), page.Total, got.body)
}
for _, u := range page.Users {
if u.Email != "[email protected]" {
t.Errorf("a row for %s survived the address narrowing: %+v", u.Email, u)
}
}
if page.Users[0].Owner == page.Users[1].Owner {
t.Errorf("both rows came from %s — the narrowing collapsed to one tenant instead of "+
"applying across the page the scope allows", page.Users[0].Owner)
}
}
// seedKey adds one API key under a tenant. A key row carries the publishable
// half and the scope it may reach, so which tenant a page comes from is the
// whole question.
func seedKey(t *testing.T, db orm.DB, owner, name string) {
t.Helper()
k := orm.New[schema.Key](db)
k.Owner, k.Name = owner, name
k.AccessKey, k.State = "pk-"+owner+"-"+name, "Active"
k.SetId(owner + "/" + name)
if err := k.CreateCtx(context.Background()); err != nil {
t.Fatalf("seed key %s/%s: %v", owner, name, err)
}
}
// A capability admits a confidential client to a COLLECTION; it never names the
// tenant, and it is not read as one. hanzo-console holds the users and keys
// capabilities and serves hanzo, so on both collections it reads hanzo — whether
// it names another tenant, or names none.
//
// The two capabilities differ in what a page discloses and agree in what decides
// it: the roster is the tenant's people, the key set is its integrations, and
// both are pinned in the handler because that is the only place holding the
// credential and the query at once.
func TestScope_ACapabilityNamesACollectionNotATenant(t *testing.T) {
h := newHarness(t)
seedScopeFixture(t, h)
t.Setenv("IAM_KEY_MINT_ALLOWED_APPS", "hanzo-console")
seedKey(t, h.db, foreignRealOrg, "lux-secret-key")
seedKey(t, h.db, "hanzo", "hanzo-key")
auth := asApp("hanzo-console", "s3cret")
for _, collection := range []string{"users", "keys"} {
t.Run(collection, func(t *testing.T) {
named := h.send(t, "GET", "/v1/iam/"+collection+"?owner="+foreignRealOrg, auth, nil)
if named.status != 403 {
t.Errorf("GET %s?owner=%s = %d, want 403 — the capability admits the "+
"collection, not the tenant: %s", collection, foreignRealOrg, named.status, named.body)
}
if owners := named.owners(t); len(owners) > 0 {
t.Errorf("LEAK: naming %s returned rows owned by %v", foreignRealOrg, owners)
}
unnamed := h.send(t, "GET", "/v1/iam/"+collection, auth, nil)
owners := unnamed.owners(t)
for owner := range owners {
if owner != "hanzo" {
t.Errorf("LEAK: naming no owner returned %q's rows (owners=%v): %s",
owner, owners, unnamed.body)
}
}
if unnamed.status != 200 || owners["hanzo"] == 0 {
t.Errorf("hanzo-console's own %s page = %d owners=%v, want 200 carrying hanzo: %s",
collection, unnamed.status, owners, unnamed.body)
}
})
}
}