Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/iam/contract_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
1 change: 1 addition & 0 deletions apps/iam/iam.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
115 changes: 115 additions & 0 deletions apps/iam/stats.go
Original file line number Diff line number Diff line change
@@ -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
}
102 changes: 102 additions & 0 deletions apps/iam/stats_test.go
Original file line number Diff line number Diff line change
@@ -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
}
7 changes: 7 additions & 0 deletions apps/iam/zipdoc_gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions internal/host/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading