mirror of
https://github.com/hanzoai/gateway.git
synced 2026-11-02 08:45:10 +00:00
THE LIVE ESCALATION, in the path that ships. `X-User-IsAdmin` is the fleet's PLATFORM-authority header — cloud gates its cross-tenant surfaces on it and the money gates read the bit-field beside it. This edge minted it from claims.IsAdmin, which is IAM's ORG-ROLE bit: an org owner carries it inside their own org. So every org owner reached the fleet as a platform admin. I reported this fixed earlier. It was not. I patched iamauth.InjectIdentity, which has ZERO non-test callers — the shipped KrakenD middleware and the ZAP relay each carried their own inline mint, and both still read the org bit. Two more statements of the same rule, and the one I fixed was the dead one. Fixed where they run: the HTTP edge (auth_middleware.go) now applies edge.Mint, and the relay (gate.go) sets f.IsAdmin — which forward re-emits as X-User-IsAdmin — from PlatformSudo. X-User-IsOrgAdmin is minted for the first time, so org-scoped self-service has its own header to read instead of borrowing platform authority. ONE DECISION. iamauth is DELETED (834 lines) along with the shim over it. What a claim means, which org a request acts in, who pays, which headers get minted — all of it is hanzoai/authz and hanzoai/authz/edge now, and net/http's own header type satisfies edge.Headers, so applying it here is a loop rather than a second implementation. What is left is the part genuinely this deployment's: package token holds the issuer and the AUDIENCE ALLOWLIST (authz.Verify deliberately does not check `aud`, because IAM sets it to the requesting CLIENT), and identity.go holds the money bit vocabulary and the vendor-prefix strip. ONE JWT LIBRARY on the identity path. Verification is golang-jwt/v5, the library IAM SIGNS with, through authz.Verify + the edge's JWKS reader. go-jose is gone from it, and the tests now mint with the same library they verify with — a test signing with a different one is testing a signer the estate does not run. It also makes `kid` mandatory, matching IAM (signClaims always stamps it). THREE HEADERS DROPPED, because IAM never emitted the claims behind them: `roles`, `permissions` and `phone` are absent from the signed claim set and from claims_supported, so the three-shape parsers for the first two read a claim that never arrived, and X-Roles / X-Phone-Number were always empty. All three names STAY in the strip set, so a forged copy still never survives. Removing the permissions parser also closes a latent grant: a token carrying that claim used to be handed the bits it named. The vendor-prefix backstop (X-IAM-*, X-HANZO-*) stays here rather than in the estate's edge, because sweeping prefixes must ENUMERATE header names — which is transport-specific, while edge.Headers is deliberately Get/Set/Del. It is folded into one stripClaimed call with the exact-name strip, because two calls would be an ordering trap that fails silently. Falsified both ways: restoring `if cl.IsAdmin` in edge.Mint turns TestOrgOwnerIsNotAPlatformAdmin and TestAdminOrgMachineGetsNeitherAdminHeader red; granting the admin bit from the org role turns TestOrgAdminNeverMintsPlatformAuthority and TestPermissions_OrgAdminGetsNoAdminBit red. Green on both build tags, including the `legacy` tag production ships. tests/ stays red on the KrakenD fixture suite — verified identical on a stashed tree, so it is not from this change. Co-authored-by: Hanzo Dev <[email protected]>
265 lines
7.0 KiB
Go
265 lines
7.0 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
type server struct {
|
|
cfg *config
|
|
store *store
|
|
agg *aggregator
|
|
|
|
mu sync.Mutex
|
|
cache map[string]cachedID // cookie-hash → identity (60s TTL)
|
|
}
|
|
|
|
type cachedID struct {
|
|
id identity
|
|
exp time.Time
|
|
}
|
|
|
|
// gate is the DATA-LAYER superadmin enforcement, independent of the ingress
|
|
// admin-guard ForwardAuth. The predicate is the single platform fact: the
|
|
// caller's org equals AdminOrg. Resolved from a Bearer/Basic JWT (the API path)
|
|
// or the cloud first-party session cookie (the browser path). Fail-closed:
|
|
// no superadmin identity → 403, never god-mode data.
|
|
func (s *server) gate(next http.HandlerFunc) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
id, ok := s.authenticate(r)
|
|
if !ok {
|
|
writeErr(w, http.StatusForbidden, "superadmin required")
|
|
return
|
|
}
|
|
ctx := context.WithValue(r.Context(), identityKey, id)
|
|
next(w, r.WithContext(ctx))
|
|
}
|
|
}
|
|
|
|
func (s *server) authenticate(r *http.Request) (identity, bool) {
|
|
// (1) JWT (Bearer/Basic) — carries `owner` directly.
|
|
if claims, err := s.cfg.validator.Verify(r.Header); err == nil && claims != nil {
|
|
if claims.Owner == s.cfg.adminOrg {
|
|
return identity{
|
|
Owner: claims.Owner, Name: claims.Name, Email: claims.Email,
|
|
DisplayName: claims.Name, IsGlobalAdmin: true,
|
|
}, true
|
|
}
|
|
return identity{}, false // a valid non-admin token is a definitive deny
|
|
}
|
|
// (2) cloud session cookie → /v1/ai/account.
|
|
return s.sessionIdentity(r)
|
|
}
|
|
|
|
func (s *server) sessionIdentity(r *http.Request) (identity, bool) {
|
|
cookie := r.Header.Get("Cookie")
|
|
if cookie == "" {
|
|
return identity{}, false
|
|
}
|
|
key := hashStr(cookie)
|
|
if id, ok := s.cacheGet(key); ok {
|
|
return id, id.Owner == s.cfg.adminOrg
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
|
|
defer cancel()
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.cfg.cloudURL+"/v1/ai/account", nil)
|
|
if err != nil {
|
|
return identity{}, false
|
|
}
|
|
req.Header.Set("Cookie", cookie)
|
|
req.Header.Set("Accept", "application/json")
|
|
resp, err := httpClient.Do(req)
|
|
if err != nil {
|
|
return identity{}, false
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode != http.StatusOK {
|
|
return identity{}, false
|
|
}
|
|
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
|
var env struct {
|
|
Status string `json:"status"`
|
|
Data struct {
|
|
Owner string `json:"owner"`
|
|
Name string `json:"name"`
|
|
Email string `json:"email"`
|
|
DisplayName string `json:"displayName"`
|
|
Type string `json:"type"`
|
|
IsForbidden bool `json:"isForbidden"`
|
|
IsGlobalAdmin bool `json:"isGlobalAdmin"`
|
|
} `json:"data"`
|
|
}
|
|
if err := json.Unmarshal(body, &env); err != nil {
|
|
return identity{}, false
|
|
}
|
|
d := env.Data
|
|
if d.Type == "anonymous-user" || d.IsForbidden {
|
|
return identity{}, false
|
|
}
|
|
if d.Owner != s.cfg.adminOrg {
|
|
return identity{}, false
|
|
}
|
|
id := identity{Owner: d.Owner, Name: d.Name, Email: d.Email, DisplayName: nz(d.DisplayName, d.Name), IsGlobalAdmin: true}
|
|
s.cachePut(key, id)
|
|
return id, true
|
|
}
|
|
|
|
// ---- handlers -------------------------------------------------------------
|
|
|
|
func (s *server) handleMe(w http.ResponseWriter, r *http.Request) {
|
|
writeOK(w, identityOf(r))
|
|
}
|
|
|
|
func (s *server) handleOverview(w http.ResponseWriter, r *http.Request) {
|
|
o, err := s.store.overview(r.Context())
|
|
if err != nil {
|
|
writeErr(w, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
writeOK(w, o)
|
|
}
|
|
|
|
func (s *server) handleOrgs(w http.ResponseWriter, r *http.Request) {
|
|
rows, err := s.store.listOrgs(r.Context())
|
|
if err != nil {
|
|
writeErr(w, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
writeOK(w, rows, len(rows))
|
|
}
|
|
|
|
func (s *server) handleUsers(w http.ResponseWriter, r *http.Request) {
|
|
q := r.URL.Query()
|
|
page := atoiOr(q.Get("p"), 1)
|
|
size := atoiOr(q.Get("pageSize"), 50)
|
|
if size < 1 || size > 1000 {
|
|
size = 50
|
|
}
|
|
if page < 1 {
|
|
page = 1
|
|
}
|
|
rows, total, err := s.store.listUsers(r.Context(), strings.TrimSpace(q.Get("q")), q.Get("org"), size, (page-1)*size)
|
|
if err != nil {
|
|
writeErr(w, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
writeOK(w, rows, total)
|
|
}
|
|
|
|
func (s *server) handleUsage(w http.ResponseWriter, r *http.Request) {
|
|
q := r.URL.Query()
|
|
to := time.Now()
|
|
from := to.AddDate(0, 0, -30)
|
|
if v := parseTime(q.Get("from")); !v.IsZero() {
|
|
from = v
|
|
}
|
|
if v := parseTime(q.Get("to")); !v.IsZero() {
|
|
to = v
|
|
}
|
|
d, err := s.store.usage(r.Context(), q.Get("org"), from, to)
|
|
if err != nil {
|
|
writeErr(w, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
writeOK(w, d)
|
|
}
|
|
|
|
func (s *server) handleProducts(w http.ResponseWriter, r *http.Request) {
|
|
rows, err := s.store.listProducts(r.Context(), r.URL.Query().Get("kind"))
|
|
if err != nil {
|
|
writeErr(w, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
writeOK(w, rows, len(rows))
|
|
}
|
|
|
|
func (s *server) handleAudit(w http.ResponseWriter, r *http.Request) {
|
|
q := r.URL.Query()
|
|
size := atoiOr(q.Get("pageSize"), 100)
|
|
recs, total, err := s.agg.liveAudit(r.Context(), q.Get("org"), size)
|
|
if err != nil {
|
|
writeErr(w, http.StatusBadGateway, err.Error())
|
|
return
|
|
}
|
|
out := make([]map[string]any, 0, len(recs))
|
|
for _, rec := range recs {
|
|
out = append(out, map[string]any{
|
|
"createdTime": rec["createdTime"],
|
|
"organization": rec["organization"],
|
|
"user": rec["user"],
|
|
"clientIp": rec["clientIp"],
|
|
"method": rec["method"],
|
|
"action": rec["action"],
|
|
"requestUri": rec["requestUri"],
|
|
})
|
|
}
|
|
writeOK(w, out, total)
|
|
}
|
|
|
|
func (s *server) handleApplications(w http.ResponseWriter, r *http.Request) {
|
|
q := r.URL.Query()
|
|
size := atoiOr(q.Get("pageSize"), 100)
|
|
rows, total, err := s.agg.liveApplications(r.Context(), q.Get("owner"), size)
|
|
if err != nil {
|
|
writeErr(w, http.StatusBadGateway, err.Error())
|
|
return
|
|
}
|
|
writeOK(w, rows, total)
|
|
}
|
|
|
|
func (s *server) handleRoles(w http.ResponseWriter, r *http.Request) {
|
|
q := r.URL.Query()
|
|
size := atoiOr(q.Get("pageSize"), 100)
|
|
rows, total, err := s.agg.liveRoles(r.Context(), q.Get("owner"), size)
|
|
if err != nil {
|
|
writeErr(w, http.StatusBadGateway, err.Error())
|
|
return
|
|
}
|
|
writeOK(w, rows, total)
|
|
}
|
|
|
|
func (s *server) handleSync(w http.ResponseWriter, r *http.Request) {
|
|
go s.agg.syncOnce(context.Background())
|
|
writeOK(w, map[string]any{"started": true})
|
|
}
|
|
|
|
// ---- identity cache -------------------------------------------------------
|
|
|
|
func (s *server) cacheGet(key string) (identity, bool) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.cache == nil {
|
|
return identity{}, false
|
|
}
|
|
c, ok := s.cache[key]
|
|
if !ok || time.Now().After(c.exp) {
|
|
return identity{}, false
|
|
}
|
|
return c.id, true
|
|
}
|
|
|
|
func (s *server) cachePut(key string, id identity) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.cache == nil {
|
|
s.cache = map[string]cachedID{}
|
|
}
|
|
if len(s.cache) > 4096 {
|
|
s.cache = map[string]cachedID{}
|
|
}
|
|
s.cache[key] = cachedID{id: id, exp: time.Now().Add(60 * time.Second)}
|
|
}
|
|
|
|
func hashStr(s string) string {
|
|
h := sha256.Sum256([]byte(s))
|
|
return hex.EncodeToString(h[:])
|
|
}
|