Files
ai/web_wire_test.go
zeekayandHanzo Dev 6065605df6 refactor(api): name ai's resources for what they are, not for IAM's words
ai inherited five identity nouns from casibase — users, applications,
permissions, providers, sessions — and published all five under /v1/ai/*. IAM
publishes the same five words at /v1/iam/*, which cloud proxies wholesale to the
identity service. One noun, two addresses, and no way for a reader to know which
of them held the row. Each was answered separately, from the handler down.

permissions was a MIRROR. Every method in controllers/permission.go was an iam.*
call — the REST client in internal/iam, straight to the IAM server — so
/v1/ai/permissions held nothing and was a second address for
/v1/iam/permissions. Deleted, along with the controller that existed only to
serve it. The console's two live calls now go to IAM directly, which is already
where PermissionUtil sends the user to review what it just created.

users was USAGE wearing an identity name: object.GetUsers reads a store's
MESSAGES and returns the distinct senders, and its sibling rolls those same
messages up per user. Both are cuts of the usage record, so they are
sub-collections of it — /v1/ai/usages/{user-names,by-user}. Neither was ever a
user directory.

applications are KUBERNETES DEPLOYMENTS: a template rendered through kustomize
into a manifest, applied to a namespace, with a pod phase for Status and a
service URL. Nothing about an OAuth client. Now /v1/ai/deployments.

sessions are ai's OWN cookie sessions — Signin writes the beego session id,
Signout deletes it — so IAM cannot see them and /v1/iam/sessions is a different
set of rows. They stay, as /v1/ai/signin-sessions.

providers stay exactly where they are: ai's own provider table (model,
embedding, storage, tts, stt, agent, scan), super-admin gated, and the one
console module already calling the right address.

The POLICY KEYS DO NOT MOVE. The filters hold hand-curated super-admin and
balance sets keyed by the old flat names, so key/keyPlural pin "application" and
"session", and the two usage cuts keep get-users / get-user-table-infos through
kebab(method). A renamed URL with a renamed key would silently un-gate an admin
endpoint; TestPolicyKeyRoundTrip now asserts each one at its new address.

Fixed while here: the sessions member GET resolved to "GetSession", which the
embedded web.Controller also defines as its session-value getter. Reflection
found that one — so the table test passed — and dispatch then called a
one-argument method with no arguments, panicking. readMethod names
GetSingleSession, which now reads the composite id its route actually supplies.

The published spec is regenerated from the table (hanzoai/openapi, same branch):
107 paths, drift test green.

Co-authored-by: Hanzo Dev <[email protected]>
2026-07-27 11:38:35 -07:00

122 lines
4.5 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 ai
import (
"io"
"net/http"
"strings"
"testing"
"github.com/hanzoai/ai/routers"
"github.com/zap-proto/zip"
)
// wiredStatus drives one request through the fully wired native router — the
// filter chain (rewrites, auth, tenant, …) plus reflection dispatch — over the
// same /v1/* mount the unified binary uses, and returns the status code.
func wiredStatus(t *testing.T, method, path, body string) int {
t.Helper()
wireTestSessions()
routers.InstallFilters()
SetHandler(routers.App)
defer SetHandler(nil)
app := zip.New(zip.Config{DisableStartupMessage: true})
mountRoutes(app)
var r io.Reader
if body != "" {
r = strings.NewReader(body)
}
req, _ := http.NewRequest(method, "http://example.com"+path, r)
req.Header.Set("Content-Type", "application/json")
resp, err := app.Fiber().Test(req)
if err != nil {
t.Fatalf("Test %s %s: %v", method, path, err)
}
return resp.StatusCode
}
// TestWiredResourceRouteDispatches proves the generated resource surface is
// live through the fully-wired router: a namespaced REST path reaches its
// handler rather than 404-ing.
func TestWiredResourceRouteDispatches(t *testing.T) {
for _, c := range []struct{ method, path string }{
{"GET", "/v1/ai/account"},
{"GET", "/v1/ai/deployments"},
{"GET", "/v1/ai/stores/acme/thing"},
{"GET", "/v1/ai/stores"},
{"GET", "/v1/ai/version"},
// NB: /v1/ai/signin is deliberately not probed here — its handler makes a
// live OAuth call, so a pass would depend on the network. Its registration
// is covered by the table tests instead.
{"GET", "/v1/ai/signin-sessions"},
{"GET", "/v1/ai/usages/user-names"},
} {
if code := wiredStatus(t, c.method, c.path, "{}"); code == http.StatusNotFound {
t.Errorf("%s %s must dispatch, got 404", c.method, c.path)
}
}
}
// TestOldAddressesAreGone is the "one way" guarantee, stated as a test. Every
// endpoint used to be reachable at up to THREE URLs — the flat compound route,
// the same route under /v1/cloud/*, and (for auth) under /v1/ai/*. Each extra
// address was a place a policy could be applied inconsistently. They must 404.
func TestOldAddressesAreGone(t *testing.T) {
for _, c := range []struct{ method, path string }{
{"GET", "/v1/get-account"},
{"GET", "/v1/get-applications"},
{"GET", "/v1/get-stores"},
{"GET", "/v1/get-providers"},
{"POST", "/v1/add-application"},
{"POST", "/v1/signin"},
{"GET", "/v1/cloud/get-account"},
{"GET", "/v1/cloud/get-providers"},
{"GET", "/v1/ai/get-account"},
// The identity nouns ai borrowed from casibase. /v1/ai/permissions was a
// second address for the IAM service's permissions and has no successor
// here; the other three moved to names that say what ai actually serves.
{"GET", "/v1/ai/permissions"},
{"GET", "/v1/ai/users"},
{"GET", "/v1/ai/applications"},
{"GET", "/v1/ai/sessions"},
} {
// "Gone" means NO HANDLER RUNS. Usually that shows up as a 404 from the
// router. For a path whose name is still in the super-admin policy set
// (the set is keyed by name, and policyKey still derives that name for
// the live REST route), the authz filter denies an unauthenticated caller
// BEFORE routing — 401/403, also without dispatching. Both outcomes are
// the property under test; a 2xx or a 405 would mean a handler was found.
code := wiredStatus(t, c.method, c.path, "{}")
switch code {
case http.StatusNotFound, http.StatusUnauthorized, http.StatusForbidden:
default:
t.Errorf("%s %s must be GONE, got %d — a second address for one resource",
c.method, c.path, code)
}
}
}
// TestWiredGatedResourceAuthReject proves the super-admin gate still fires at the
// NEW address: unauthenticated provider reads are denied before dispatch.
func TestWiredGatedResourceAuthReject(t *testing.T) {
code := wiredStatus(t, "GET", "/v1/ai/providers", "")
if code != http.StatusUnauthorized && code != http.StatusForbidden {
t.Errorf("unauthenticated /v1/ai/providers must be denied (401/403), got %d", code)
}
}