Files
ai/controllers/provider_flags.go
zeekayandGitHub e8296c5b36 feat(providers): admin API + path-normalization hardening (filter-normalize + naked-handler self-auth + preview-lever) (#62)
* feat(providers): admin management API + State-gated routing + DO-first defaults

New global-admin-gated provider-management surface, wired to the SAME
object.Provider store (one source of truth — the generic CRUD store is not
forked). Closes the gap where toggling a provider's State had no effect on
routing, and makes DO-first the default with OpenRouter manageable in the
same table.

Endpoints (routers/router.go + globalAdminEndpoints gate in authz_filter.go):
- GET  /v1/admin/providers          list Model providers as a clean view:
        {name,displayName,type,enabled,primary,keyPresent,modelCount,providerUrl}
        keyPresent is a boolean ONLY — never the key or any fragment of it.
- POST /v1/admin/providers/toggle   {name,enabled} → set State Active/Disabled.
- POST /v1/admin/providers/primary  {name} → IsDefault on target, cleared on all
        other Model providers (exactly one primary).
- GET  /v1/provider-flags           PUBLIC, secret-free enabled-provider NAMES
        feed for the pricing catalog sync (replaces standalone ENABLE_OPENROUTER):
        {"enabledProviders":["do-ai","zen"]}.

Routing State gate (the toggle now actually takes effect):
- object.ModelProviderUsable: ONE predicate — a Model provider with State !=
  "Active" is unavailable. Consulted by GetModelProviderByName and
  GetModelProviderByNameForOrg (the completion/embeddings/image/BYOK chokepoints)
  and getModelProviderFromName (store/knowledge path), so every caller sees a
  disabled provider as "not configured" uniformly.
- Fallbacks honored: failover callProvider surfaces a nil (disabled/missing)
  provider as "... is unavailable ..."; isRetryableError treats "unavailable" as
  retryable so the failover loop advances to an Active fallback.
- object.InvalidateProviderNameCache: admin toggles evict the 60s hot-path cache
  so changes take effect on the next request, not after the TTL.

DO-first seed defaults + non-clobber fix (object/init.go):
- do-ai = Active + IsDefault (primary router); fireworks/openai-direct = Disabled;
  zen stays Active (branded first-party over do-ai); openrouter seeded Disabled.
- CRITICAL: State/IsDefault are set ONLY on initial CREATE and NEVER re-clobbered
  on an existing record, so an admin toggle persists across restarts. Type/SubType/
  ProviderUrl/ClientSecret continue to self-heal from the seed.

Secret safety:
- object.ProviderKeyPresent resolves on a COPY (env-first, mirroring the hot path),
  returns a bool, never mutates the caller's record, fail-closed when KMS is off.
- adminProviderView carries no secret fields; regression test asserts the JSON
  never contains clientSecret/providerKey/userKey/signKey or any resolved value.

Tests (all DB-free, passing): ModelProviderUsable, ProviderKeyPresent (present/
absent/env/kms-off/no-mutation), InvalidateProviderNameCache, adminProviderView
projection + secret-leak guard, modelCountByProvider static-map parity,
providersToRepointPrimary exactly-one, filterEnabledModelNames, provider-flags
JSON contract + OpenRouter default-off, isRetryableError "unavailable".

* fix(providers): close authz path-normalization bypass + atomic set-primary (red review)

Addresses the red review of the provider-admin backend (builds on 81c8e720).

C-1 [CRITICAL] AuthzFilter path-normalization bypass — permissionFilter keyed
globalAdminEndpoints on the RAW TrimPrefix path while Beego path.Cleans before
dispatch, so slash/dot variants of the gated multi-segment routes
(POST /v1/admin/providers/toggle/, /v1//admin/providers, /v1/./admin/providers,
/v1/admin/../admin/providers, …) bypassed the gate entirely and fell through to
the fully-open default → UNAUTHENTICATED disable of the primary provider =
platform-wide chat/embeddings/image DoS. Fixed with defense in depth:
  1. normalizedControllerName() path.Cleans the request path BEFORE the map
     lookup so the gate keys on the SAME canonical name Beego dispatches to —
     closing the entire "//", "/./", "/../", trailing-slash variant set for
     EVERY gated endpoint (admin/providers*, the get-*/*-provider CRUD, topology
     reads), not just the 3 admin routes.
  2. Controller self-guard RequireGlobalAdmin() at the top of GetAdminProviders,
     ToggleAdminProvider, SetPrimaryAdminProvider — reuses the existing
     c.principalUser() (session or VERIFIED Bearer JWT) + util.IsGlobalAdmin,
     fail-closed 401/403. Even if the filter is ever bypassed the controller
     refuses. NOT the preview-mode-relaxed org-level RequireAdmin.

H-1 [HIGH] set-primary non-atomic + default ignores State —
  - GetDefaultModelProvider now filters state="Active" (with is_default +
    category), so a disabled/ambiguous primary is never handed to the
    store/KB/RAG default-model path (store.go returns it with no usability check).
  - SetPrimaryAdminProvider replaced its per-record UpdateProvider loop (mid-loop
    failure could leave 0 or 2 primaries) with object.SetPrimaryModelProvider: two
    set-wide UPDATEs, PROMOTE-the-target-first then DEMOTE-the-rest, so there is
    never a zero-primary window. Params-bound, no interpolation.

LOW-2 [frontend red] reject set-primary on a disabled provider —
SetPrimaryAdminProvider 4xx's if !object.ModelProviderUsable(provider) (the ONE
enabled/allowed-to-route predicate; getAdminModelProvider already confirmed Model).

M-2 [MEDIUM] router-level bypass regression test — routers/authz_filter_test.go
adds the normalization-variant matrix (permissionFilter, every variant → 401
unauth / 403 org-admin, global-admin passes) AND a real Beego router+filter+memory
session httptest round-trip (mirrors red's harness). Proven to FAIL against the
pre-fix filter (variants returned 200 / reached the controller) and pass after.
object/provider_default_atomic_test.go asserts the promote-before-demote ordering
+ WHERE scoping + the state="Active" default query via built SQL (no DB).

Removes now-dead providersToRepointPrimary (the atomic UPDATE supersedes it).
Contract unchanged: GET /v1/admin/providers, /toggle, /primary, /provider-flags
keep their shapes; provider-flags stays public. Kept intact: secret non-leak,
cache eviction, ModelProviderUsable, ProviderKeyPresent. go build/vet clean.

* fix(authz): self-guard naked provider/model-route/cluster handlers + preview lever

Defense-in-depth follow-up to the path-normalization fix this branch already
carries (normalizedControllerName in permissionFilter). The provider / model-route
CRUD and cluster-introspection handlers relied SOLELY on the routers.permissionFilter
gate; add c.RequireGlobalAdmin() — the helper introduced with provider-admin, which
resolves the session OR a verified Bearer JWT via principalUser — as the FIRST
statement of each so a future filter desync can never reach them unauthenticated or
as a mere org admin. Mirrors the provider_admin handlers' self-guard exactly.

Gated (15): UpdateProvider, DeleteProvider, RefreshMcpTools, GetModelRoutes,
GetModelRoute, AddModelRoute, UpdateModelRoute, DeleteModelRoute, ReloadModelConfig,
GetNodes, GetPods, GetContainers, GetImages, GetMachines, GetK8sStatus.

Also (LOW): account.go GetAccount now reads conf.DisablePreviewMode() (env-first
DISABLE_PREVIEW_MODE lever) instead of beego.AppConfig.Bool directly, so the lever
governs it like the authz filter and RequireAdmin; drop the now-unused beego import.

Tests: new TestNakedHandlersRequireGlobalAdmin drives every gated handler and asserts
401 (anonymous) / 403 (org admin) on the deny path (guard returns before any DB call,
so no datastore needed). Resolve a rebase-induced duplicate ctrlFakeSession (F1's
index_auth_test.go + provider-admin's provider_admin_test.go both defined it) by
reusing the single package-level definition.

go build ./...=0, go vet clean, gofmt clean; go test ./routers ./controllers green.
2026-07-03 01:07:42 -07:00

86 lines
3.1 KiB
Go

// 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 controllers
import (
"sort"
"github.com/hanzoai/ai/object"
)
// providerFlags is the secret-free response of GET /v1/provider-flags. It carries
// ONLY the names of enabled Model providers — no keys, no URLs, no config — so it
// is safe to be served unauthenticated. The pricing catalog sync
// (hanzoai/pricing/src/sync.mjs) reads this to decide which providers' models to
// publish, replacing the standalone ENABLE_OPENROUTER env: the provider State
// toggle and the catalog become ONE control.
//
// Contract for the pricing agent:
//
// GET https://api.hanzo.ai/v1/provider-flags (also on the cloud ingress)
// 200 {"status":"ok","data":{"enabledProviders":["do-ai","zen"]}}
//
// enabledProviders is a sorted, de-duplicated list of admin-owned Model provider
// names whose State == "Active". To gate OpenRouter, sync.mjs checks whether
// "openrouter" is in this list instead of reading its own env flag.
type providerFlags struct {
EnabledProviders []string `json:"enabledProviders"`
}
// enabledModelProviderNames returns the sorted names of admin-owned Model
// providers that are currently enabled (State == "Active"). Secret-free by
// construction — it projects only the Name field.
func enabledModelProviderNames() ([]string, error) {
providers, err := object.GetProviders("admin")
if err != nil {
return nil, err
}
return filterEnabledModelNames(providers), nil
}
// filterEnabledModelNames is the pure projection: sorted, secret-free names of
// enabled (State=="Active") Model providers. DB-free so it is unit-tested
// directly.
func filterEnabledModelNames(providers []*object.Provider) []string {
names := make([]string, 0, len(providers))
for _, p := range providers {
if p.Category == "Model" && p.State == "Active" {
names = append(names, p.Name)
}
}
sort.Strings(names)
return names
}
// GetProviderFlags
// @Title GetProviderFlags
// @Tag Provider API
// @Description Public, secret-free list of enabled Model provider NAMES. Used by
//
// the pricing catalog sync to gate which providers' models are published
// (replaces the standalone ENABLE_OPENROUTER env — one control). Safe to be
// unauthenticated: no keys, URLs, or config are returned.
//
// @Success 200 {object} controllers.providerFlags The Response object
// @router /provider-flags [get]
func (c *ApiController) GetProviderFlags() {
names, err := enabledModelProviderNames()
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(providerFlags{EnabledProviders: names})
}