Files
ai/controllers/zap_knowledge-stores-files-vectors.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

925 lines
30 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.
// Native ZAP handlers for the knowledge group: stores, storage-providers,
// files, tree-files, the file activation cache, and vectors.
//
// STRANGLER: each controller method (ApiController.Get/Update/Add/DeleteStore,
// RefreshStoreVectors, GetStoreNames, GetStorageProviders, Get/Update/Add/
// DeleteFile, RefreshFileVectors, UploadFile, Update/Add/DeleteTreeFile,
// ActivateFile, GetActiveFile, Get/Update/Add/DeleteVector, DeleteAllVectors)
// is re-implemented here as a pure ZAP handler against object/ + iam, mirroring
// zap_native.go:zapChatHandler. It NEVER wraps or drives the controller
// and never holds an http.ResponseWriter. The same routes stay live on
// routers.App, which also backs the gateway fallback.
//
// REGISTRATION (recipe, collision-free — mirrors zap_responses.go): this file
// declares NO shared registry symbol, so it compiles standalone in the strangler
// hybrid and never collides with a sibling group's registerCloud/registerGateway
// definition. It exposes its native-method and gateway-path tables as
// uniquely-named data (zapKnowledgeCloud / zapKnowledgeGateway) keyed to this
// group's handlers. This file's init() ranges over these to registerCloud(method,
// h) / registerGatewayPath(path, h). No group edits a shared registration file.
//
// PARITY NOTES:
// - Query params (owner, id, store, pageSize, p, field, value, sortField,
// sortOrder, key, filename, isLeaf, prefix) and the former multipart file /
// Host header have no ZAP carrier, so they are decoded from the ONE JSON
// body — the same pattern zap_router-policy-stats uses.
// Identity is ALWAYS the resolved credential (auth), NEVER a body field.
// - The gateway table below is EMPTY, on purpose: these resources live at
// /v1/ai/{stores,files,tree-files,vectors}, where a member answers four verbs
// at /:owner/:name and a path-only matcher would pick the wrong handler
// (zap_gateway_fallback.go). The MsgType 100 method names are this group's
// whole ZAP surface; a gateway request reaches these resources through the
// router.
package controllers
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"mime/multipart"
"net/http"
"sort"
"strings"
"github.com/luxfi/zap"
iam "github.com/hanzoai/ai/internal/iam"
"github.com/hanzoai/ai/conf"
"github.com/hanzoai/ai/object"
"github.com/hanzoai/ai/util"
)
// ── ZAP dispatch tables (group-local, collision-free) ────────────────────
//
// A type ALIAS (not a new named type) so no shared symbol is declared.
type zapKnowledgeHandlerFn = func(ctx context.Context, auth string, body []byte) (*zap.Message, error)
// zapKnowledgeCloud maps native cloud method → handler (MsgType 100).
// init self-registers this group's dispatch tables into the canonical registry.
func init() {
for method, h := range zapKnowledgeCloud {
registerCloud(method, h)
}
for path, h := range zapKnowledgeGateway {
registerGatewayPath(path, h)
}
}
var zapKnowledgeCloud = map[string]zapKnowledgeHandlerFn{
"stores.get-global": zapGetGlobalStoresHandler,
"stores.get": zapGetStoresHandler,
"stores.get-one": zapGetStoreHandler,
"stores.update": zapUpdateStoreHandler,
"stores.add": zapAddStoreHandler,
"stores.delete": zapDeleteStoreHandler,
"stores.refresh-vectors": zapRefreshStoreVectorsHandler,
"stores.get-names": zapGetStoreNamesHandler,
"storage.get-providers": zapGetStorageProvidersHandler,
"files.get-global": zapGetGlobalFilesHandler,
"files.get": zapGetFilesHandler,
"files.get-one": zapGetFileHandler,
"files.update": zapUpdateFileHandler,
"files.add": zapAddFileHandler,
"files.delete": zapDeleteFileHandler,
"files.refresh-vectors": zapRefreshFileVectorsHandler,
"files.upload": zapUploadFileHandler,
"files.activate": zapActivateFileHandler,
"files.get-active": zapGetActiveFileHandler,
"treefiles.update": zapUpdateTreeFileHandler,
"treefiles.add": zapAddTreeFileHandler,
"treefiles.delete": zapDeleteTreeFileHandler,
"vectors.get-global": zapGetGlobalVectorsHandler,
"vectors.get": zapGetVectorsHandler,
"vectors.get-one": zapGetVectorHandler,
"vectors.update": zapUpdateVectorHandler,
"vectors.add": zapAddVectorHandler,
"vectors.delete": zapDeleteVectorHandler,
"vectors.delete-all": zapDeleteAllVectorsHandler,
}
// zapKnowledgeGateway maps gateway path → handler (MsgType 200). Longest-prefix
// wins (see PARITY NOTES).
var zapKnowledgeGateway = map[string]zapKnowledgeHandlerFn{}
// ── Shared seams (identity + response envelope + param parity) ───────────
// zapKSFVScopedOwner mirrors GetScopedOwner: authenticated principal required,
// scoped to its own org. A raw ZAP door carries no SuperAdmin verdict, so the body
// "owner" field never retargets it. Returns (owner, user, nil) or (…, deny).
func zapKSFVScopedOwner(ctx context.Context, auth string, bodyOwner string) (string, *iam.User, *zap.Message) {
user := zapPrincipal(ctx, auth)
if user == nil {
msg, _ := zapError(http.StatusUnauthorized, "auth:Please sign in first")
return "", nil, msg
}
return util.ScopeOwner(user, bodyOwner), user, nil
}
// zapRequireAdmin mirrors ApiController.RequireAdmin (preview passes; else an
// org-level admin principal is required).
func zapRequireAdmin(ctx context.Context, auth string) (*iam.User, *zap.Message) {
user := zapPrincipal(ctx, auth)
if conf.IsPreviewMode() {
return user, nil
}
if !util.IsAdmin(user) {
msg, _ := zapError(http.StatusForbidden, "auth:this operation requires admin privilege")
return nil, msg
}
return user, nil
}
// zapRequireSignedIn mirrors RequireSignedIn / RequireSessionOwner: a
// principal is required, else 401.
func zapRequireSignedIn(ctx context.Context, auth string) (*iam.User, *zap.Message) {
user := zapPrincipal(ctx, auth)
if user == nil {
msg, _ := zapError(http.StatusUnauthorized, "auth:Please sign in first")
return nil, msg
}
return user, nil
}
// zapKSFVLang mirrors GetAcceptLanguage on a carrier that has no Accept-Language
// header: an optional body "language", defaulting to "en" (as zapChatHandler).
func zapKSFVLang(lang string) string {
if lang == "" {
return "en"
}
return lang
}
// zapKnowledgeParams is the body-decoded projection of the former query params.
type zapKnowledgeParams struct {
Owner string `json:"owner"`
Id string `json:"id"`
Store string `json:"store"`
Name string `json:"name"`
PageSize string `json:"pageSize"`
P string `json:"p"`
Field string `json:"field"`
Value string `json:"value"`
SortField string `json:"sortField"`
SortOrder string `json:"sortOrder"`
Prefix string `json:"prefix"`
Key string `json:"key"`
Filename string `json:"filename"`
IsLeaf bool `json:"isLeaf"`
Host string `json:"host"`
Language string `json:"language"`
// File upload / tree-leaf content (base64, dataURL-prefixed or raw).
File string `json:"file"`
FileType string `json:"type"`
}
func zapDecodeParams(body []byte) zapKnowledgeParams {
var p zapKnowledgeParams
if len(body) > 0 {
_ = json.Unmarshal(body, &p)
}
return p
}
// zapPaginated reports whether both pageSize and p are present (the the router branch
// that pages + admin-gates) and computes offset/limit like pagination.SetPaginator.
func zapPaginated(p zapKnowledgeParams) (bool, int, int) {
if p.PageSize == "" || p.P == "" {
return false, 0, 0
}
limit := util.ParseInt(p.PageSize)
page := max(util.ParseInt(p.P), 1)
return true, (page - 1) * limit, limit
}
// zapDecodeBase64File mirrors UploadFile's decode: strips an optional dataURL
// prefix ("data:...;base64,") then base64-decodes.
func zapDecodeBase64File(fileBase64 string) ([]byte, error) {
payload := fileBase64
if _, after, ok := strings.Cut(fileBase64, ","); ok {
payload = after
}
return base64.StdEncoding.DecodeString(payload)
}
// zapBytesFile adapts a byte slice to multipart.File (AddTreeFile only io.Copy's
// it). bytes.Reader already implements Read/ReadAt/Seek; add a no-op Close.
type zapBytesFile struct{ *bytes.Reader }
func (zapBytesFile) Close() error { return nil }
// zapAddRecordForFile mirrors addRecordForFile without an HTTP context: it builds
// the audit Record directly (NewRecord's ctx-derived fields have no ZAP carrier)
// and writes it via the SAME object.AddRecord the HTTP path uses.
func zapAddRecordForFile(user *iam.User, action, sessionId, key, filename string, isLeaf bool, lang string) error {
typ := "Folder"
if isLeaf {
typ = "File"
}
_, storeName, err := util.GetOwnerAndNameFromIdWithError(sessionId)
if err != nil {
return err
}
path := fmt.Sprintf("/%s/%s", key, filename)
if filename == "" {
path = key
}
text := fmt.Sprintf("%s%s, Session: %s, Path: %s", action, typ, storeName, path)
rec := &object.Record{
User: GetUserName(user),
Organization: user.Owner,
RequestUri: text,
}
_, _, err = object.AddRecord(rec, lang)
return err
}
// ── stores ───────────────────────────────────────────────────────────────
func zapGetGlobalStoresHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
p := zapDecodeParams(body)
paged, offset, limit := zapPaginated(p)
if !paged {
stores, err := object.GetGlobalStores()
if err != nil {
return zapError(http.StatusOK, err.Error())
}
return zapOk(stores)
}
if _, deny := zapRequireAdmin(ctx, auth); deny != nil {
return deny, nil
}
count, err := object.GetStoreCount(p.Name, p.Field, p.Value)
if err != nil {
return zapError(http.StatusOK, err.Error())
}
stores, err := object.GetPaginationStores(offset, limit, p.Name, p.Field, p.Value, p.SortField, p.SortOrder)
if err != nil {
return zapError(http.StatusOK, err.Error())
}
sort.SliceStable(stores, func(i, j int) bool {
return stores[i].IsDefault && !stores[j].IsDefault
})
if err = object.PopulateStoreCounts(stores); err != nil {
return zapError(http.StatusOK, err.Error())
}
return zapOk(stores, count)
}
func zapGetStoresHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
p := zapDecodeParams(body)
owner, user, deny := zapKSFVScopedOwner(ctx, auth, p.Owner)
if deny != nil {
return deny, nil
}
stores, err := object.GetStores(owner)
if err != nil {
return zapError(http.StatusOK, err.Error())
}
stores = FilterStoresByHomepage(stores, user)
return zapOk(stores)
}
func zapGetStoreHandler(_ context.Context, auth string, body []byte) (*zap.Message, error) {
p := zapDecodeParams(body)
var store *object.Store
var err error
if p.Id == "admin/_cloud_default_store_" {
store, err = object.GetDefaultStore("admin")
} else {
store, err = object.GetStore(p.Id)
}
if err != nil {
return zapError(http.StatusOK, err.Error())
}
// Populate builds absolute URLs from the request origin. ZAP has no Host, so
// populate only when the caller supplies one; a populate error is non-fatal
// (mirrors ResponseOk(store, err.Error())).
if store != nil && strings.TrimSpace(p.Host) != "" {
origin := getOriginFromHost(p.Host)
if err = store.Populate(origin, zapKSFVLang(p.Language)); err != nil {
return zapOk(store, err.Error())
}
}
return zapOk(store)
}
// zapDecodeStoreWithId decodes the store object from the body and resolves the
// target id: an explicit sibling "id" key wins (rename case), else the store's
// own owner/name — preserving the HTTP body-is-store wire shape.
func zapDecodeStoreWithId(body []byte) (*object.Store, string, error) {
var store object.Store
if err := json.Unmarshal(body, &store); err != nil {
return nil, "", err
}
var idHolder struct {
Id string `json:"id"`
}
_ = json.Unmarshal(body, &idHolder)
id := idHolder.Id
if id == "" {
id = store.GetId()
}
return &store, id, nil
}
func zapUpdateStoreHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
caller, deny := zapRequireSignedIn(ctx, auth)
if deny != nil {
return deny, nil
}
store, id, err := zapDecodeStoreWithId(body)
if err != nil {
return zapError(http.StatusOK, err.Error())
}
oldStore, err := storeFor(caller, id)
if err != nil {
return zapError(http.StatusOK, err.Error())
}
store.Owner = oldStore.Owner
if oldStore.IsDefault && !store.IsDefault {
return zapError(http.StatusOK, "store:given that there must be one default store in Hanzo Cloud, you cannot set this store to non-default. You can directly set another store as default")
}
success, err := object.UpdateStore(id, store)
if err != nil {
return zapError(http.StatusOK, err.Error())
}
if !oldStore.IsDefault && store.IsDefault {
stores, err := object.GetGlobalStores()
if err != nil {
return zapError(http.StatusOK, err.Error())
}
for _, store2 := range stores {
if store2.GetId() != store.GetId() && store2.IsDefault {
store2.IsDefault = false
success, err = object.UpdateStore(store2.GetId(), store2)
if err != nil {
return zapError(http.StatusOK, err.Error())
}
}
}
}
return zapOk(success)
}
func zapAddStoreHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
var store object.Store
if err := json.Unmarshal(body, &store); err != nil {
return zapError(http.StatusOK, err.Error())
}
// A store is created into the same org GetStores reads back, and no other. The
// owner arrived on the request body, so a member of ANY org could file a store
// into the chat plane's own tenant — where it is reachable as a default store,
// and a default store names the model every chat answer runs and bills. This is
// the scope the controller twin resolves (AddStore, store.go); only the admin org may
// name an owner, and it names it through this seam rather than on the row.
owner, _, deny := zapKSFVScopedOwner(ctx, auth, store.Owner)
if deny != nil {
return deny, nil
}
store.Owner = owner
if err := object.SyncDefaultProvidersToStore(&store); err != nil {
return zapError(http.StatusOK, err.Error())
}
if store.ModelProvider == "" {
modelProvider, err := object.GetDefaultModelProvider()
if err != nil {
return zapError(http.StatusOK, err.Error())
}
if modelProvider != nil {
store.ModelProvider = modelProvider.Name
}
}
if store.EmbeddingProvider == "" {
embeddingProvider, err := object.GetDefaultEmbeddingProvider()
if err != nil {
return zapError(http.StatusOK, err.Error())
}
if embeddingProvider != nil {
store.EmbeddingProvider = embeddingProvider.Name
}
}
success, err := object.AddStore(&store)
if err != nil {
return zapError(http.StatusOK, err.Error())
}
return zapOk(success)
}
func zapDeleteStoreHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
caller, deny := zapRequireSignedIn(ctx, auth)
if deny != nil {
return deny, nil
}
var store object.Store
if err := json.Unmarshal(body, &store); err != nil {
return zapError(http.StatusOK, err.Error())
}
stored, err := storeFor(caller, store.GetId())
if err != nil {
return zapError(http.StatusOK, err.Error())
}
if stored.IsDefault {
return zapError(http.StatusOK, "store:Cannot delete the default store")
}
success, err := object.DeleteStore(stored)
if err != nil {
return zapError(http.StatusOK, err.Error())
}
return zapOk(success)
}
func zapRefreshStoreVectorsHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
if _, deny := zapRequireSignedIn(ctx, auth); deny != nil {
return deny, nil
}
var store object.Store
if err := json.Unmarshal(body, &store); err != nil {
return zapError(http.StatusOK, err.Error())
}
p := zapDecodeParams(body)
ok, err := object.RefreshStoreVectors(&store, zapKSFVLang(p.Language))
if err != nil {
return zapError(http.StatusOK, err.Error())
}
return zapOk(ok)
}
func zapGetStoreNamesHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
p := zapDecodeParams(body)
owner, user, deny := zapKSFVScopedOwner(ctx, auth, p.Owner)
if deny != nil {
return deny, nil
}
storeNames, err := object.GetStoresByFields(owner, "name", "display_name")
if err != nil {
return zapError(http.StatusOK, err.Error())
}
storeNames = FilterStoresByHomepage(storeNames, user)
return zapOk(storeNames)
}
// ── storage providers ────────────────────────────────────────────────────
func zapGetStorageProvidersHandler(ctx context.Context, auth string, _ []byte) (*zap.Message, error) {
if _, deny := zapRequireSignedIn(ctx, auth); deny != nil {
return deny, nil
}
providers, err := getStorageProviders()
if err != nil {
return zapError(http.StatusOK, err.Error())
}
return zapOk(providers)
}
// ── files ────────────────────────────────────────────────────────────────
func zapGetGlobalFilesHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
p := zapDecodeParams(body)
paged, offset, limit := zapPaginated(p)
if !paged {
files, err := object.GetGlobalFiles()
if err != nil {
return zapError(http.StatusOK, err.Error())
}
return zapOk(files)
}
if _, deny := zapRequireAdmin(ctx, auth); deny != nil {
return deny, nil
}
count, err := object.GetFileCount("", p.Field, p.Value)
if err != nil {
return zapError(http.StatusOK, err.Error())
}
files, err := object.GetPaginationFiles("", offset, limit, p.Field, p.Value, p.SortField, p.SortOrder)
if err != nil {
return zapError(http.StatusOK, err.Error())
}
return zapOk(files, count)
}
func zapGetFilesHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
p := zapDecodeParams(body)
owner, _, deny := zapKSFVScopedOwner(ctx, auth, p.Owner)
if deny != nil {
return deny, nil
}
var files []*object.File
var err error
if p.Store != "" {
files, err = object.GetFilesByStore(owner, p.Store)
} else {
files, err = object.GetFiles(owner)
}
if err != nil {
return zapError(http.StatusOK, err.Error())
}
return zapOk(files)
}
func zapGetFileHandler(_ context.Context, _ string, body []byte) (*zap.Message, error) {
p := zapDecodeParams(body)
file, err := object.GetFile(p.Id)
if err != nil {
return zapError(http.StatusOK, err.Error())
}
return zapOk(file)
}
func zapUpdateFileHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
if _, deny := zapRequireSignedIn(ctx, auth); deny != nil {
return deny, nil
}
p := zapDecodeParams(body)
var file object.File
if err := json.Unmarshal(body, &file); err != nil {
return zapError(http.StatusOK, err.Error())
}
// Whose row this is, not what the body said — the same answer this table's
// listing uses.
file.Owner = theirOrg(zapPrincipal(ctx, auth))
id := p.Id
// The id names which row, and it names one of the caller's own.
if deny := zapReachable(ctx, auth, id, theirOrg); deny != nil {
return deny, nil
}
if id == "" {
id = file.GetId()
}
success, err := object.UpdateFile(id, &file)
if err != nil {
return zapError(http.StatusOK, err.Error())
}
return zapOk(success)
}
func zapAddFileHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
if _, deny := zapRequireSignedIn(ctx, auth); deny != nil {
return deny, nil
}
var file object.File
if err := json.Unmarshal(body, &file); err != nil {
return zapError(http.StatusOK, err.Error())
}
// Whose row this is, not what the body said — the same answer this table's
// listing uses.
file.Owner = theirOrg(zapPrincipal(ctx, auth))
success, err := object.AddFile(&file)
if err != nil {
return zapError(http.StatusOK, err.Error())
}
return zapOk(success)
}
func zapDeleteFileHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
if _, deny := zapRequireSignedIn(ctx, auth); deny != nil {
return deny, nil
}
p := zapDecodeParams(body)
var file object.File
if err := json.Unmarshal(body, &file); err != nil {
return zapError(http.StatusOK, err.Error())
}
// Whose row this is, not what the body said — the same answer this table's
// listing uses.
file.Owner = theirOrg(zapPrincipal(ctx, auth))
success, err := object.DeleteFile(&file, zapKSFVLang(p.Language))
if err != nil {
return zapError(http.StatusOK, err.Error())
}
return zapOk(success)
}
func zapRefreshFileVectorsHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
if _, deny := zapRequireSignedIn(ctx, auth); deny != nil {
return deny, nil
}
p := zapDecodeParams(body)
var file object.File
if err := json.Unmarshal(body, &file); err != nil {
return zapError(http.StatusOK, err.Error())
}
ok, err := object.RefreshFileVectors(&file, zapKSFVLang(p.Language))
if err != nil {
return zapError(http.StatusOK, err.Error())
}
return zapOk(ok)
}
func zapUploadFileHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
user, deny := zapRequireSignedIn(ctx, auth)
if deny != nil {
return deny, nil
}
userName := GetUserName(user)
p := zapDecodeParams(body)
if p.File == "" || p.FileType == "" || p.Name == "" {
return zapError(http.StatusOK, "application:Missing required parameters")
}
if !strings.Contains(p.File, ",") {
return zapError(http.StatusOK, "resource:Invalid file data format")
}
fileBytes, err := zapDecodeBase64File(p.File)
if err != nil {
return zapError(http.StatusOK, err.Error())
}
filePath := fmt.Sprintf("cloud/avatars/%s/%s", userName, p.Name)
fileUrl, err := object.UploadFileToStorageSafe(userName, "file", "UploadStoreAvatar", filePath, fileBytes)
if err != nil {
return zapError(http.StatusOK, err.Error())
}
return zapOk(fileUrl)
}
// ── file activation cache ────────────────────────────────────────────────
func zapActivateFileHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
if _, deny := zapRequireSignedIn(ctx, auth); deny != nil {
return deny, nil
}
p := zapDecodeParams(body)
prefix := getCachePrefix(p.Filename)
if prefix == "" {
return zapOk(false)
}
path := fmt.Sprintf("%s/%s", cacheDir, p.Key)
rememberPath(prefix, path)
if !util.FileExist(getAppPath(p.Filename)) {
util.CopyFile(getAppPath(p.Filename), getAppPath(prefix))
}
return zapOk(true)
}
func zapGetActiveFileHandler(_ context.Context, _ string, body []byte) (*zap.Message, error) {
p := zapDecodeParams(body)
res := ""
if v, ok := cachedPath(p.Prefix); ok {
res = v
}
return zapOk(res)
}
// ── tree files ───────────────────────────────────────────────────────────
func zapUpdateTreeFileHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
user, deny := zapRequireSignedIn(ctx, auth)
if deny != nil {
return deny, nil
}
p := zapDecodeParams(body)
var file object.TreeFile
if err := json.Unmarshal(body, &file); err != nil {
return zapError(http.StatusOK, err.Error())
}
lang := zapKSFVLang(p.Language)
res := object.UpdateTreeFile(p.Store, p.Key, &file)
if res {
if err := zapAddRecordForFile(user, "Update", p.Store, p.Key, "", true, lang); err != nil {
return zapError(http.StatusOK, err.Error())
}
}
return zapOk(res)
}
func zapAddTreeFileHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
user, deny := zapRequireSignedIn(ctx, auth)
if deny != nil {
return deny, nil
}
userName := GetUserName(user)
p := zapDecodeParams(body)
lang := zapKSFVLang(p.Language)
// Leaf content arrives base64-encoded in the body (no multipart on ZAP).
var file multipart.File
if p.IsLeaf {
if p.File == "" {
return zapError(http.StatusOK, "resource:Invalid file data format")
}
fileBytes, err := zapDecodeBase64File(p.File)
if err != nil {
return zapError(http.StatusOK, err.Error())
}
file = zapBytesFile{bytes.NewReader(fileBytes)}
}
res, bs, err := object.AddTreeFile(p.Store, userName, p.Key, p.IsLeaf, p.Filename, file, lang)
if err != nil {
return zapError(http.StatusOK, err.Error())
}
if res {
if err = addFileToCache(p.Key, p.Filename, bs); err != nil {
return zapError(http.StatusOK, err.Error())
}
if err = zapAddRecordForFile(user, "Add", p.Store, p.Key, p.Filename, p.IsLeaf, lang); err != nil {
return zapError(http.StatusOK, err.Error())
}
}
return zapOk(res)
}
func zapDeleteTreeFileHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
user, deny := zapRequireSignedIn(ctx, auth)
if deny != nil {
return deny, nil
}
p := zapDecodeParams(body)
lang := zapKSFVLang(p.Language)
res, err := object.DeleteTreeFile(p.Store, p.Key, p.IsLeaf, lang)
if err != nil {
return zapError(http.StatusOK, err.Error())
}
if res {
if err = zapAddRecordForFile(user, "Delete", p.Store, p.Key, "", p.IsLeaf, lang); err != nil {
return zapError(http.StatusOK, err.Error())
}
}
return zapOk(res)
}
// ── vectors ──────────────────────────────────────────────────────────────
func zapGetGlobalVectorsHandler(_ context.Context, _ string, _ []byte) (*zap.Message, error) {
vectors, err := object.GetGlobalVectors()
if err != nil {
return zapError(http.StatusOK, err.Error())
}
return zapOk(vectors)
}
func zapGetVectorsHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
user, deny := zapRequireSignedIn(ctx, auth)
if deny != nil {
return deny, nil
}
owner := user.Owner
p := zapDecodeParams(body)
storeName, isoDeny := zapEnforceStoreIsolation(user, p.Store)
if isoDeny != nil {
return isoDeny, nil
}
paged, offset, limit := zapPaginated(p)
if !paged {
vectors, err := object.GetVectors(owner)
if err != nil {
return zapError(http.StatusOK, err.Error())
}
return zapOk(vectors)
}
count, err := object.GetVectorCount(owner, storeName, p.Field, p.Value)
if err != nil {
return zapError(http.StatusOK, err.Error())
}
vectors, err := object.GetPaginationVectors(owner, storeName, offset, limit, p.Field, p.Value, p.SortField, p.SortOrder)
if err != nil {
return zapError(http.StatusOK, err.Error())
}
return zapOk(vectors, count)
}
func zapGetVectorHandler(_ context.Context, _ string, body []byte) (*zap.Message, error) {
p := zapDecodeParams(body)
vector, err := object.GetVector(p.Id)
if err != nil {
return zapError(http.StatusOK, err.Error())
}
return zapOk(vector)
}
func zapUpdateVectorHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
if _, deny := zapRequireSignedIn(ctx, auth); deny != nil {
return deny, nil
}
p := zapDecodeParams(body)
var vector object.Vector
if err := json.Unmarshal(body, &vector); err != nil {
return zapError(http.StatusOK, err.Error())
}
// Whose row this is, not what the body said — the same answer this table's
// listing uses.
vector.Owner = theirOrg(zapPrincipal(ctx, auth))
id := p.Id
// The id names which row, and it names one of the caller's own.
if deny := zapReachable(ctx, auth, id, theirOrg); deny != nil {
return deny, nil
}
if id == "" {
id = vector.GetId()
}
success, err := object.UpdateVector(id, &vector, zapKSFVLang(p.Language))
if err != nil {
return zapError(http.StatusOK, err.Error())
}
return zapOk(success)
}
func zapAddVectorHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
if _, deny := zapRequireSignedIn(ctx, auth); deny != nil {
return deny, nil
}
var vector object.Vector
if err := json.Unmarshal(body, &vector); err != nil {
return zapError(http.StatusOK, err.Error())
}
// Whose row this is, not what the body said — the same answer this table's
// listing uses.
vector.Owner = theirOrg(zapPrincipal(ctx, auth))
if vector.Provider == "" {
embeddingProvider, err := object.GetDefaultEmbeddingProvider()
if err != nil {
return zapError(http.StatusOK, err.Error())
}
if embeddingProvider != nil {
vector.Provider = embeddingProvider.Name
}
}
success, err := object.AddVector(&vector)
if err != nil {
return zapError(http.StatusOK, err.Error())
}
return zapOk(success)
}
func zapDeleteVectorHandler(ctx context.Context, auth string, body []byte) (*zap.Message, error) {
if _, deny := zapRequireSignedIn(ctx, auth); deny != nil {
return deny, nil
}
var vector object.Vector
if err := json.Unmarshal(body, &vector); err != nil {
return zapError(http.StatusOK, err.Error())
}
// Whose row this is, not what the body said — the same answer this table's
// listing uses.
vector.Owner = theirOrg(zapPrincipal(ctx, auth))
success, err := object.DeleteVector(&vector)
if err != nil {
return zapError(http.StatusOK, err.Error())
}
return zapOk(success)
}
func zapDeleteAllVectorsHandler(ctx context.Context, auth string, _ []byte) (*zap.Message, error) {
user, deny := zapRequireSignedIn(ctx, auth)
if deny != nil {
return deny, nil
}
owner := user.Owner
vectors, err := object.GetVectors(owner)
if err != nil {
return zapError(http.StatusOK, err.Error())
}
allSuccess := true
for i := range vectors {
success, err := object.DeleteVector(vectors[i])
if err != nil {
return zapError(http.StatusOK, err.Error())
}
if !success {
allSuccess = false
}
}
return zapOk(allSuccess)
}