Documentation
¶
Overview ¶
Copyright 2023-2025 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.
Package routers @APIVersion 1.70.0 @Title Hanzo Cloud RESTful API @Description Swagger Docs of Hanzo Cloud Backend API @Contact cloud@hanzo.ai @SecurityDefinition AccessToken apiKey Authorization header @Schemes https,http @ExternalDocs Find out more about Hanzo Cloud @ExternalDocsUrl https://hanzo.ai/cloud
Index ¶
- func AuthAvailableFilter(c *zip.Ctx) error
- func AuthzFilter(c *zip.Ctx) error
- func BalanceGateFilter(c *zip.Ctx) error
- func CacheControlFilter(c *zip.Ctx) error
- func CorsFilter(c *zip.Ctx) error
- func Document(app *zip.App) map[string]any
- func GetOrg(c *zip.Ctx) string
- func GetSessionUser(c *zip.Ctx) *iam.User
- func GetTenantOrgID(c *zip.Ctx) string
- func GetTenantProjectID(c *zip.Ctx) string
- func GetTenantUserID(c *zip.Ctx) string
- func HstsFilter(c *zip.Ctx) error
- func InitBalanceGate()
- func InitTierCache()
- func InstallFilters(app *zip.App)
- func Patterns(app *zip.App) map[string][]string
- func PrometheusFilter(c *zip.Ctx) error
- func RateLimitFilter(c *zip.Ctx) error
- func Record(c *zip.Ctx) error
- func Recovered(c *zip.Ctx) (err error)
- func Register(app *zip.App)
- func TenantContextFilter(c *zip.Ctx) error
- func TrafficTapFilter(c *zip.Ctx) error
- type BalanceGate
- type Doc
- type Quota
- type RateLimiter
- type Response
- type Tier
- type TierCache
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AuthAvailableFilter ¶ added in v1.832.10
AuthAvailableFilter refuses every request while this process cannot validate a bearer token, and is the ONE place that decision is made.
It runs BEFORE any filter that reads a token (AutoSignin, Balance, Tenant, Authz), so no downstream code ever sees the difference between "this token is invalid" and "no cert was ever established". That difference is the whole point: the two look identical at a token-parsing call site, and treating the second as the first is what once left the service Running and answering 401 to everything, including free routes, with no crashloop and no alert to catch it.
503, not 401. A 401 says "your credential is wrong" to a caller whose credential is fine, invites a client to discard a good token and re-authenticate, and reads as normal traffic on every dashboard. 503 says the honest thing — the service cannot answer right now — and Retry-After tells a client when to come back.
It is deliberately NOT a readiness probe. A probe failure would take the pod out of service entirely; identity being briefly unreachable should cost the requests that need identity, not the process. Requests are refused while it is down and served again on the first attempt that succeeds, with no restart.
func AuthzFilter ¶
func BalanceGateFilter ¶
BalanceGateFilter is a BeforeRouter filter that checks whether the requesting user has a positive Commerce balance before allowing paid API requests to proceed. It runs after AutoSigninFilter (which sets session users for legacy auth paths) and handles its own user resolution for JWT and IAM API key auth paths.
Posture: fail-CLOSED on balance, never on money. When billing is unconfigured (no gate) or the billing subject cannot be identified, the request passes to the downstream auth/controller layer, which re-checks (identity is that layer's job). When the subject IS identified, a positive spendable balance is REQUIRED: a known-insufficient balance is denied 402 (add credits), and a balance that cannot be verified is denied 503 (retry) — both deny. AI is prepaid; a billing-backend outage becomes a retryable 503, never free inference.
func CacheControlFilter ¶
CacheControlFilter adds Cache-Control headers to prevent caching of sensitive API endpoints This ensures that sensitive data (like passwords, user chats, messages) are not cached by intermediary proxies, SSL terminators, or browsers
func CorsFilter ¶
func Document ¶ added in v1.832.46
Document is everything this service serves, as one OpenAPI 3.1 document.
The result is deterministic: it reads the route table and two package-level tables, and nothing here reads the clock, the environment, or a random source.
func GetOrg ¶ added in v1.804.1
GetOrg resolves the organization for data-scoping in filters from the VERIFIED request principal — never a raw client header.
On the direct (non-gateway) ingress the X-Org-Id header is fully client-controlled, so trusting it would let any caller act as any org (cross-tenant read/write + billing attribution). It is honored ONLY when it matches the authenticated principal's own org, or the principal is a global admin (cross-org platform access). A non-admin can never escape their own org via a header; an unauthenticated caller's header is ignored entirely.
Behind the gateway the injected X-Org-Id equals the JWT owner, so this resolves identically — the gateway path is unaffected.
func GetSessionUser ¶
GetSessionUser is the identity a FILTER sees, and it is the same identity the handler sees: the request's verified IAM token, read by the one function that reads it. Filters and handlers cannot disagree about who is calling.
It used to read a per-pod in-memory session store, and its own comment recorded the cost: the store is filled by a session hook that does not run when the embedded binary serves these routes, so this answered nil on every request and the filters billed and rate-limited by the raw key instead. A store that is nil in production is not an identity source. The token always travels with the request.
func GetTenantOrgID ¶
GetTenantOrgID returns the org from IAM web.
func GetTenantProjectID ¶
GetTenantProjectID returns the project ID from IAM web.
func GetTenantUserID ¶
GetTenantUserID returns the user ID from IAM web.
func HstsFilter ¶
HstsFilter adds HTTP Strict Transport Security header to HTTPS responses This ensures browsers only access the website using HTTPS
func InitBalanceGate ¶
func InitBalanceGate()
InitBalanceGate reads Commerce connection parameters from app config and creates the balance gate. Must be called once during startup. If Commerce is not configured, the gate is not created and BalanceGateFilter is a no-op. IAM connection parameters are NOT read here: key resolution goes through the one resolver (controllers.GetUserByAccessKey), which owns that config.
func InitTierCache ¶
func InitTierCache()
InitTierCache reads Commerce connection parameters from app config and creates the tier cache. Must be called once during startup. If Commerce is not configured (no commerceEndpoint), the cache is not created and DefaultTierFunc falls back to env-var overrides or TierZenFree.
func InstallFilters ¶ added in v1.822.2
InstallFilters puts the request chain in front of every route, in this order.
It installs onto the APP it is handed, and there is no once-guard. There was one, and it was a leftover from the router being a package variable: guarding a per-app installation with a process-wide Once means the SECOND app built in a process gets no chain at all — no auth, no balance gate, and no recover. One process only ever serves one app, so production never saw it; a test that builds a second one did, as a panic escaping a chain that was never installed.
EACH ONE DECIDES WHETHER TO CONTINUE, and says so by returning c.Continue() or not. That used to be implied: a filter wrote a response and returned, and the router inferred a refusal from the fact that something had been written. The refusals are now the shape of the code.
There is no "after" list. Recording used to be two filters — one before the router, one after the handler — passing a username between them through a request parameter; it is one middleware holding a local across the handler. Cookie rewriting was the other after-filter, and it went with the session store it patched.
Two filters are gone entirely, and both were doing somebody else's job:
- Auto-signin accepted an MD5 of clientId:clientSecret, or HTTP Basic against the configured pair, and minted an IsAdmin identity into a per-pod in-memory store. IAM mints credentials; this service reads the one presented.
- Static served a landing folder, the admin bundle and /storage from a path taken off the URL, and rewrote main.<hash>.js on the way out. Static content is ingress and the static plugin. Every route here is /v1.
There are no path-rewriting filters either. Two used to lead the chain: /v1/cloud/* → /v1/* rewrote EVERY route into a second address, and /v1/iam/* did the same for four account endpoints. Between them a single endpoint answered at three URLs, each one a place a policy could be applied inconsistently. Resources live at exactly one address, generated from the table in resources.go.
func Patterns ¶ added in v1.833.89
Patterns is the live route table as path → verbs.
zip declares routes as a flat list of (method, pattern); this is the same information keyed the way its callers ask it — "what does this address serve" — which is the question both the OpenAPI document and the filter-path test have. It is derived, never maintained, so it cannot claim a verb the app does not serve.
func PrometheusFilter ¶
func RateLimitFilter ¶
RateLimitFilter holds every /v1 request to a rate and a quota.
EVERY request, because the ceilings are asked about the CALLER rather than about the credential they happened to carry — see limitSubject. The exceptions are the paths isRateLimitExempt names and anything outside /v1, which is not this API.
func Record ¶ added in v1.833.89
Record attributes each request to the principal that made it, and writes the row after the handler has answered.
It was TWO filters passing a username between them through a request parameter, because a before-the-router filter and an after-the-handler filter have no other way to share. One middleware holds it in a local across the handler: nothing to name, nothing to look up, nothing to lose.
func Recovered ¶ added in v1.833.89
Recovered turns a panic into a 500, so one request cannot take anything else with it.
It is FIRST in the chain, which is deliberate: it has to cover the filters as well as the handlers. A gate that panics while deciding whether to admit a request is the worst place to lose the process, because it happens before anything has been served.
This is not new behaviour, it is behaviour that had to be moved. The router this service used to run recovered in two places of its own — once around the filter chain and once around handler dispatch — so a nil dereference anywhere in ~360 handlers became a 500 and the process carried on. zip installs no recovery (its own examples show the app adding one), and under fasthttp an unrecovered panic takes the connection. Registering the routes natively removed the old router and its recover with it; this is the recover, in one place, where the chain is built.
The body is the house envelope and says nothing else. A panic is ours, not the caller's: the stack goes to the log where an engineer reads it, and the caller gets a 500 they can retry rather than a description of our internals.
func Register ¶ added in v1.833.89
Register binds every /v1 route this service serves onto the app, and installs the filter chain around them. Routes are explicit; there is no annotation-based registration.
ONE entry point, called by ai.App. It used to be an init() writing onto a package-level router, so the table existed the moment the package was imported — before anything could say what it should be registered ON, and with no way for a test to ask for a clean one.
THE FILTERS GO ON FIRST, and that is not cosmetic: the router walks its stack in registration order, so a filter added after a route never runs before it. The chain would still be installed, still be tested, and simply not be in front of anything.
func TenantContextFilter ¶
TenantContextFilter captures IAM identity context for downstream scoping and observability. The org is taken from the VERIFIED principal (GetOrg), NOT the raw X-Org-Id header: on the direct ingress that header is client-controlled, so storing it verbatim would let any caller spoof a tenant. GetOrg honors the header only for the principal's own org (or a global admin), so the stored org is always the caller's real tenant.
func TrafficTapFilter ¶ added in v1.817.0
TrafficTapFilter is a BeforeRouter tap that folds each genuine inbound /v1 API request into the in-process traffic aggregate (object.GlobalTraffic), keyed by the EDGE-supplied geo (Cloudflare CF-IPCountry + optional CF-Region-Code) and a coarse service class derived from the path. It powers the public world.hanzo.ai live- traffic globe.
PRIVACY (load-bearing): it reads ONLY the country/region geo headers. It never reads CF-Connecting-IP or any client IP, never hashes anything, and hands the aggregate nothing but (country, region, service) — Record has no IP parameter to pass one to. It is a pure side effect: it never writes a response, never blocks, never errors, and returns immediately, so its position in the filter chain cannot affect any request's outcome.
Types ¶
type BalanceGate ¶
type BalanceGate struct {
// contains filtered or unexported fields
}
BalanceGate enforces a positive spendable balance before paid requests. The balance itself lives in the shared object.BalanceLedger — the ONE source of truth also used by the controller debit path to reserve (before a request) and settle (after). Reading the ledger here makes the gate reservation-aware and reflects local settles immediately, so the cache window can never serve a stale-positive balance after the funds are spent. The gate adds only its own freshness scheduling (async refresh from Commerce) and identity resolution.
type Doc ¶ added in v1.832.7
type Doc struct{ Summary, Description string }
Doc is one operation's prose: the opening sentence, and the whole comment.
type Quota ¶ added in v1.833.72
type Quota struct {
// contains filtered or unexported fields
}
Quota admits requests while a key is inside its tier's ceiling for every period.
func NewQuota ¶ added in v1.833.72
NewQuota creates a Quota that evicts keys untouched for a full month every cleanupInterval. The tierFunc callback resolves an API key to its Tier; pass nil to always use TierZenFree.
func (*Quota) Spend ¶ added in v1.833.72
Spend charges one request to key and reports whether every period admitted it.
A refusal names the period that refused and the instant it next rolls, which is what a caller needs to know to come back. A REFUSED request is charged to nothing: one exhausted ceiling must not go on burning down the longer ones, which would let a caller who is out for eight hours lose their whole month.
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter tracks per-key rate limiters with automatic cleanup of stale entries.
func InitRateLimiter ¶
func InitRateLimiter(tierFunc func(string) Tier) *RateLimiter
InitRateLimiter creates the global rate limiter. Must be called once during startup (before web.Run). Returns the instance so the caller can call Stop() on shutdown.
It says what it armed, and says it by READING tierLimits. Boot used to print the tiers as prose from where it called this, and prose does not follow a table: the line named a free tier of 10/min next to two tiers that no longer exist, and a reader took it for the configuration. A boot line is evidence of what was armed, so it comes from the thing that armed it.
func NewRateLimiter ¶
func NewRateLimiter(tierFunc func(string) Tier, cleanupInterval time.Duration) *RateLimiter
NewRateLimiter creates a RateLimiter that starts a background goroutine to evict stale entries every cleanupInterval. The tierFunc callback resolves an API key to its Tier; pass nil to always use TierZenFree.
func (*RateLimiter) Allow ¶
func (rl *RateLimiter) Allow(apiKey string) bool
Allow checks whether a request from the given API key should be permitted. It returns true if the request is within the rate limit.
func (*RateLimiter) Metrics ¶
func (rl *RateLimiter) Metrics() (allowed, denied uint64)
Metrics returns the current rate limit hit/pass counters.
func (*RateLimiter) RetryAfter ¶
func (rl *RateLimiter) RetryAfter(apiKey string) int
RetryAfter returns the number of seconds until the next token is available for the given API key. Returns 0 if the key has no entry.
func (*RateLimiter) Stop ¶
func (rl *RateLimiter) Stop()
Stop terminates the background cleanup goroutine.
type Tier ¶
type Tier string
Tier represents an API usage tier with associated rate limits. All tiers follow the "zen-*" naming convention as the canonical identifier.
func DefaultTierFunc ¶
DefaultTierFunc resolves a rate-limit key to a Tier using a three-level lookup. The key is whatever limitSubject named the caller: an IAM org slug when a billing subject resolved, a confirmed page key, or a digest of the address the caller arrived from when neither. All of them flow through the same path:
- Static env-var overrides (RATE_LIMIT_TIERS) -- highest priority, for operator-managed mappings. Supports exact and prefix matching (works for both org slugs like "acme=zen-enterprise" and key prefixes like "sk-0d2eb").
- Commerce tier cache -- backed by async lookups to Commerce billing API (GET /v1/billing/tier?user=<org>). On cache hit, the cached tier is returned immediately. On cache miss, TierZenFree is returned and a background goroutine populates the cache so the next request uses the correct tier.
- TierZenFree -- default when no override or cache entry exists.
This function never blocks on network I/O. Commerce lookups happen asynchronously; the worst case is that a new org's first few requests are rate-limited at the free tier until the cache is populated.
Source Files
¶
- auth_available_filter.go
- authz_filter.go
- base.go
- cache_control_filter.go
- cors_filter.go
- filter_balance.go
- filters.go
- finetune_router.go
- hsts_filter.go
- openapi.go
- org_resolver.go
- prometheus_filter.go
- quota.go
- ratelimit.go
- record.go
- recover.go
- resources.go
- route.go
- router.go
- shape.go
- tenant_context_filter.go
- traffic_filter.go
- wired.go
- wired_gen.go