diff --git a/apps/iam/contract_test.go b/apps/iam/contract_test.go index f9646b8ae..30e6497b2 100644 --- a/apps/iam/contract_test.go +++ b/apps/iam/contract_test.go @@ -26,6 +26,7 @@ func TestAuthorizationContract(t *testing.T) { "/v1/iam/web3": authztest.Open, "/v1/iam/auth": authztest.Open, "/v1/iam/registry": authztest.Open, + "/v1/iam/stats": authztest.Open, // public aggregate user/org counts, zero PII "/v1/iam/accounts": authztest.Open, // this browser's signed-in accounts, from its cookie }, Data: func(t *testing.T) string { diff --git a/apps/iam/iam.go b/apps/iam/iam.go index 6d18a87cb..d5d9e37cd 100644 --- a/apps/iam/iam.go +++ b/apps/iam/iam.go @@ -248,6 +248,7 @@ func Use(app cloud.Router, deps cloud.Deps) error { // organization's cert can be neither created nor used to sign. iamserver.UseVault(vault{}) host.Use(web3Middleware()) + exposeStats(host) host.Use(iamserver.NewApp(db)) log.Info("iam embedded in-process (clean iam-v2, zip-native + hanzoai/orm — iam-v1 retired)", "store", StorePath(dir), "prefixes", Prefixes) diff --git a/apps/iam/stats.go b/apps/iam/stats.go new file mode 100644 index 000000000..969f1a8bc --- /dev/null +++ b/apps/iam/stats.go @@ -0,0 +1,115 @@ +// Copyright © 2026 Hanzo AI. MIT License. + +package iam + +import ( + "context" + "net/http" + "sync" + "time" + + "github.com/hanzoai/cloud/sdk" + "github.com/hanzoai/iam/pkg/model" + "github.com/hanzoai/orm" + "github.com/zap-proto/zip" +) + +const publicStatsTTL = 5 * time.Minute + +// PublicStats holds public, aggregate counts of Hanzo IAM entities. No +// personally identifiable information or per-tenant detail is exposed. +type PublicStats struct { + // Users is the total number of active Hanzo IAM user accounts. + Users int64 `json:"users"` + // Organizations is the total number of Hanzo IAM organizations. + Organizations int64 `json:"organizations"` +} + +// ResponseHeaders advertises public 5-minute edge caching with 1-hour +// stale-while-revalidate so callers (such as forge.hanzo.ai and public +// dashboards) share a single cached copy at the edge. +func (*PublicStats) ResponseHeaders() map[string]string { + return map[string]string{ + "Cache-Control": "public, max-age=300, s-maxage=300, stale-while-revalidate=3600", + } +} + +var ( + statsMu sync.Mutex + statsDB orm.DB + statsCached PublicStats + statsAt time.Time +) + +func resetPublicStatsCache() { + statsMu.Lock() + statsDB = nil + statsCached = PublicStats{} + statsAt = time.Time{} + statsMu.Unlock() +} + +// exposeStats registers GET /v1/iam/stats on the public IAM router. +func exposeStats(host cloud.Router) { + host.Get("/v1/iam/stats", publicStats, + zip.WithOperationID("iamPublicStats"), + zip.WithSummary("Public aggregate counts of Hanzo IAM users and organizations"), + zip.WithTags("iam"), + zip.WithResponseHeader("Cache-Control")) +} + +// publicStats answers with live aggregate counts of active Hanzo IAM users and +// organizations. Results are cached in-process for 5 minutes and carry public +// edge Cache-Control headers. When the identity store is unavailable, it fails +// closed with HTTP 503 rather than returning zeroes. +func publicStats(ctx context.Context, _ *cloud.Unit) (*PublicStats, error) { + db := DB() + if db == nil { + return nil, zip.Errorf(http.StatusServiceUnavailable, "iam: identity store unavailable") + } + + now := time.Now() + statsMu.Lock() + if statsDB == db && !statsAt.IsZero() && now.Sub(statsAt) < publicStatsTTL { + out := statsCached + statsMu.Unlock() + return &out, nil + } + statsMu.Unlock() + + totalUsers, err := orm.TypedQuery[model.User](db).Count(ctx) + if err != nil { + return nil, zip.Errorf(http.StatusServiceUnavailable, "iam: count users: %v", err) + } + // IsDeleted carries `omitempty`, so active rows omit the field altogether. + // Fetch only rows where the field is present and subtract those marked true + // in Go, avoiding backend-specific boolean JSON comparison quirks. + if flagged, derr := orm.TypedQuery[model.User](db).Filter("IsDeleted!=", nil).GetAll(ctx); derr == nil { + for _, u := range flagged { + if u != nil && u.IsDeleted { + totalUsers-- + } + } + if totalUsers < 0 { + totalUsers = 0 + } + } + + totalOrgs, err := orm.TypedQuery[model.Organization](db).Count(ctx) + if err != nil { + return nil, zip.Errorf(http.StatusServiceUnavailable, "iam: count organizations: %v", err) + } + + out := PublicStats{ + Users: int64(totalUsers), + Organizations: int64(totalOrgs), + } + + statsMu.Lock() + statsDB = db + statsCached = out + statsAt = time.Now() + statsMu.Unlock() + + return &out, nil +} diff --git a/apps/iam/stats_test.go b/apps/iam/stats_test.go new file mode 100644 index 000000000..24507026b --- /dev/null +++ b/apps/iam/stats_test.go @@ -0,0 +1,102 @@ +// Copyright © 2026 Hanzo AI. MIT License. + +package iam + +import ( + "context" + "encoding/json" + "net/http" + "os" + "path/filepath" + "strings" + "testing" + + luxlog "github.com/luxfi/log" + "github.com/zap-proto/zip" + + "github.com/hanzoai/cloud/sdk" + "github.com/hanzoai/iam/pkg/model" +) + +func TestPublicStatsCountsLiveUsersAndOrgs(t *testing.T) { + resetPublicStatsCache() + defer resetPublicStatsCache() + + app := mountApp(t) + db := DB() + if db == nil { + t.Fatal("DB() is nil after mountApp") + } + + ctx := context.Background() + // mountApp seeds one live user (hanzo/z) and a signing cert (no org rows). + // Put two organizations, two more live users, and one soft-deleted user. + for _, o := range []*model.Organization{ + {Owner: "admin", Name: "hanzo", DisplayName: "Hanzo"}, + {Owner: "admin", Name: "lux", DisplayName: "Lux"}, + } { + if _, err := db.Put(ctx, db.NewKey("organizations", o.Owner+"/"+o.Name, 0, nil), o); err != nil { + t.Fatalf("put org %s: %v", o.Name, err) + } + } + for _, u := range []*model.User{ + {Owner: "hanzo", Name: "alice", Email: "alice@hanzo.ai"}, + {Owner: "hanzo", Name: "bob", Email: "bob@hanzo.ai"}, + {Owner: "hanzo", Name: "gone", Email: "gone@hanzo.ai", IsDeleted: true}, + } { + if _, err := db.Put(ctx, db.NewKey("users", u.Owner+"/"+u.Name, 0, nil), u); err != nil { + t.Fatalf("put user %s: %v", u.Name, err) + } + } + + req := newGet("/v1/iam/stats") + resp, err := app.Test(req, zip.TestConfig{FailOnTimeout: true}) + if err != nil { + t.Fatalf("GET /v1/iam/stats: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Fatalf("status = %d, want 200", resp.StatusCode) + } + cc := resp.Header.Get("Cache-Control") + if !strings.Contains(cc, "public") || !strings.Contains(cc, "s-maxage=300") { + t.Errorf("Cache-Control = %q, want public with s-maxage=300", cc) + } + + var got PublicStats + if err := json.NewDecoder(resp.Body).Decode(&got); err != nil { + t.Fatalf("decode stats: %v", err) + } + if got.Users != 3 { + t.Errorf("users = %d, want 3 (1 seeded + 2 live, excluding soft-deleted)", got.Users) + } + if got.Organizations != 2 { + t.Errorf("organizations = %d, want 2 (1 seeded + 1 added)", got.Organizations) + } +} + +func TestPublicStatsDegradedReturns503(t *testing.T) { + resetPublicStatsCache() + defer resetPublicStatsCache() + + notADir := filepath.Join(t.TempDir(), "occupied") + if err := os.WriteFile(notADir, []byte("not a directory"), 0o600); err != nil { + t.Fatal(err) + } + app := zip.New(zip.Config{Logger: luxlog.New("iamtest"), DisableStartupMessage: true}) + t.Setenv("CLOUD_DATA_DIR", notADir) + if err := Use(app, cloud.Deps{}); err != nil { + t.Fatalf("Use: %v", err) + } + + status, _ := get(t, app, "/v1/iam/stats") + if status != http.StatusServiceUnavailable { + t.Errorf("degraded GET /v1/iam/stats = %d, want 503", status) + } +} + +func newGet(path string) *http.Request { + req, _ := http.NewRequest(http.MethodGet, path, nil) + return req +} diff --git a/apps/iam/zipdoc_gen.go b/apps/iam/zipdoc_gen.go index bdab506f9..31609ae44 100644 --- a/apps/iam/zipdoc_gen.go +++ b/apps/iam/zipdoc_gen.go @@ -7,6 +7,13 @@ import ( ) func init() { + zip.Describe("github.com/hanzoai/cloud/apps/iam GET /v1/iam/stats", zip.Doc{ + Description: "Answers with live aggregate counts of active Hanzo IAM users and\norganizations. Results are cached in-process for 5 minutes and carry public\nedge Cache-Control headers. When the identity store is unavailable, it fails\nclosed with HTTP 503 rather than returning zeroes.", + Fields: map[string]string{ + "PublicStats.organizations": "Organizations is the total number of Hanzo IAM organizations.", + "PublicStats.users": "Users is the total number of active Hanzo IAM user accounts.", + }, + }) zip.Describe("github.com/hanzoai/cloud/apps/iam POST /iam/approval", zip.Doc{ Description: "Answers with the CALLER'S OWN recorded approvalStatus.\n\nThe subject is the caller's and can never be an argument. A caller able to name\na subject could read another person's waitlist state, which is a small leak on\nits own and a membership oracle in bulk.\n\nIt returns the raw status and judges nothing. Whether \"pending\" gates a person\nis admission's rule, and it lives with the gate — one place decides, and the\nidentity store is not it.\n\nA subject with no user row is a REFUSAL, not an empty status. A machine token's\napp-id subject and a deleted user both land there, and admission reads an empty\nstatus as approved: answering \"\" for a principal the store does not know would\nwave through exactly the callers least entitled to it. The error path is\nadmission's documented fail-open, which is a decision it makes knowingly about\nan IAM it could not reach — not one this handler makes for it silently.", }) diff --git a/internal/host/build.go b/internal/host/build.go index 72c80dbe1..470cd8610 100644 --- a/internal/host/build.go +++ b/internal/host/build.go @@ -188,6 +188,8 @@ var publicCatalog = map[string]int{ // Public SVG README badges: one shared hourly copy per handle/options across origins. "/v1/leaderboard/badge": 3600, "/v1/reward/badge": 3600, + // Public aggregate IAM counts (zero PII): shared 5-minute edge copy. + "/v1/iam/stats": 300, } // staticEdgePolicy projects the static env/flag edge config into the boot-default