Files
ai/controllers/zap_billing-usage.go
zeekay e71dfbc4f3 SuperAdmin is the host boundary's verdict, never the org a token names
util.IsSuperAdmin compared the resolved user's owner to "admin", a
second predicate beside the one the host boundary decides, and the two
disagreed. An admin-org application (no orgs, owner claim admin), an
admin-org person's sk- key, and an org spelled "admin " (the parse
trimmed orgs[0]) were each SuperAdmin here and refused by the boundary.

The host now states the verdict: object.SetSuper, which hanzo-inc/cloud
fills with principal.Super, the X-User-IsAdmin its boundary deletes from
every request and re-mints from authz.Claims.Sudo. Every HTTP seam that
turns a token into a principal goes through object.Verify, which stamps
it on iam.User.Sudo (never decoded); IsSuperAdmin and ScopeOwner read
that and compare no org. util.AdminOrg is gone; the rows that are the
platform's own are named by authz.AdminOrg.

With no host there is no SuperAdmin, and a ZAP door is not the host:
target deletes X-User-IsAdmin from a ZAP-built request, and zapPrincipal
carries a verdict only when the HTTP bridge vouched for the request it
was handed. A key is never the SuperAdmin, as at the host.
2026-10-18 22:21:43 -07:00

152 lines
6.1 KiB
Go

// Copyright 2023-2026 Hanzo AI Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// zap_billing-usage.go — native ZAP handlers for the billing/usage route group,
// migrated STRANGLER-style off the router (controllers/usage.go, cloud_usage.go,
// do_backfill.go). Each handler re-implements its controller twin against object/ +
// iam directly — it never wraps or transforms the controller. The same
// routes stay live on routers.App, which also backs the gateway fallback.
//
// Group routes (all HTTP-over-ZAP, gateway MsgType 200):
// GET /v1/get-usages
// GET /v1/get-range-usages
// GET /v1/get-users
// GET /v1/get-user-table-infos
// GET /v1/get-cloud-usages
// POST /v1/admin/ai/usage/backfill-do
//
// Identity is derived ONLY from the Bearer token (never the body) via the shared
// zapPrincipalUser seam (zap_model-routing-config.go): sk- IAM keys through
// getUserByAccessKey, JWTs through object.ParseAndValidateJWT (signature +
// iss/aud). Org scope is the principal's own Owner; only a same-brand super admin
// can widen scope, and only across orgs the god-view already exposes.
//
// The registry (registerGatewayPath / zapGatewayHandler), the identity seam
// (zapPrincipalUser / zapRequireSuperAdmin), and the envelope helpers (zapGwOk /
// zapGwError) all live in the sibling group file zap_model-routing-config.go —
// this file only self-registers its own routes from init() and adds its own
// handlers, so no two groups edit a shared registration file.
package controllers
import (
"context"
"net/url"
"strings"
"time"
iam "github.com/hanzoai/ai/internal/iam"
"github.com/luxfi/zap"
"github.com/hanzoai/ai/object"
"github.com/hanzoai/ai/util"
)
// registerZapBillingUsage wires this group's gateway routes into the shared
// registry. Invoked from init so the group self-registers from its own file;
// InitZapHandlers stays the single Node.Handle bootstrap and gains no per-group
// arm. Every route is HTTP-over-ZAP (MsgType 200) — there is no native cloud
// method for these HTTP/query-driven admin reads.
func registerZapBillingUsage() {
registerGatewayRoute("/v1/admin/ai/usage/backfill-do", zapPostBackfillDOUsageHandler)
}
func init() { registerZapBillingUsage() }
// zapRequireUsageAdmin mirrors the the router usage endpoints' guard: no verified
// principal → 401 (ResponseUnauthorized), authenticated non-admin → the
// admin-privilege refusal at HTTP 200 (ResponseError parity). Returns the user
// when authorized, else the refusal message to return verbatim. Admin here is
// ORG-level (util.IsAdmin) — the same check c.IsAdmin() runs — NOT super admin.
func zapRequireUsageAdmin(ctx context.Context, auth string) (*iam.User, *zap.Message) {
user := zapPrincipal(ctx, auth)
if user == nil {
m, _ := zapGwError(401, "auth:Please sign in first")
return nil, m
}
if !util.IsAdmin(user) {
m, _ := zapGwError(200, "auth:this operation requires admin privilege")
return nil, m
}
return user, nil
}
// usageTokenOwnBrand mirrors ApiController.principalIsOwnBrand for the Bearer
// path (ZAP has no cookie session): own-brand ONLY when the token is a JWT minted
// by THIS deployment's own issuer. sk- keys and foreign-brand JWTs are NOT
// own-brand, so a sibling-brand super admin is pinned to its own org.
func usageTokenOwnBrand(auth string) bool {
token := strings.TrimPrefix(auth, "Bearer ")
if token == "" || !isJwtToken(token) {
return false
}
return object.TokenIsOwnBrand(token)
}
// zapResolveCloudUsageScope mirrors ApiController.resolveCloudUsageScope. A
// non-super-admin (or a super admin whose token is NOT own-brand) is pinned to
// its own org — request hints (?org=/?owner=) ignored. A same-brand super admin
// targets one org via ?org= / ?owner=, or gets the all-orgs god-view (omitted,
// empty, "all", or "*"). ownBrand is passed in (computed from the token by the
// handler) so the policy is unit-testable without a real JWT. The X-Org-Id
// header fallback of the controller twin is intentionally absent: the gateway dispatch
// signature carries no headers, so on this wire super-admin targeting is by query
// only (the token owner is always the tenant floor).
func zapResolveCloudUsageScope(user *iam.User, ownBrand bool, query string) (org string, allOrgs bool) {
if !util.IsSuperAdmin(user) || !ownBrand {
return user.Owner, false
}
q, _ := url.ParseQuery(query)
target := strings.TrimSpace(q.Get("org"))
if target == "" {
target = strings.TrimSpace(q.Get("owner"))
}
if target == "" || strings.EqualFold(target, "all") || target == "*" {
return "", true
}
return target, false
}
// ── POST /v1/admin/ai/usage/backfill-do ──
func zapPostBackfillDOUsageHandler(ctx context.Context, method, _, query, auth string, _ []byte) (*zap.Message, error) {
// A WRITE to the platform-wide financial ledger — restrict to POST like the
// controller route, then re-check super admin (defense in depth, mirrors the
// controller self-guard). Fail-closed: no principal → 401, non-super → 403.
if method != "" && !strings.EqualFold(method, "POST") {
return zapGwError(404, "not found")
}
if _, refuse := zapRequireSuperAdmin(ctx, auth); refuse != nil {
return refuse, nil
}
q, _ := url.ParseQuery(query)
from, to := resolveDOBackfillWindow(q.Get("from"), q.Get("to"), time.Now())
opts := DOBackfillOptions{
From: from,
To: to,
DryRun: !doFlagFalse(q.Get("dryRun")), // WRITE requires an explicit dryRun=false
Force: doFlagTrue(q.Get("force")),
}
runCtx, cancel := context.WithTimeout(ctx, 60*time.Second)
defer cancel()
plan, err := RunDOBackfill(runCtx, opts)
if err != nil {
return zapGwError(200, err.Error())
}
return zapGwOk(plan)
}