feat(knowledge-base): validate vector store bindings on create, copy, and delete
Wires KnowledgeBase.VectorStoreID and the ownership-aware retrieve factory into the user-facing knowledge-base lifecycle: - POST /knowledge-bases validates the requested vector_store_id against the caller's tenant scope and the engine registry. New error codes ErrVectorStoreBindingInvalid (2200) and ErrVectorStoreUnavailable (2201) distinguish the typed branches without echoing UUIDs to the client. - GET / POST / PUT / PUT-pin responses embed the bound store's display metadata (name, source, engine_type, status) without exposing any connection credentials. Cross-tenant shared KBs receive a suppressed payload (vector_store_id stripped, source="shared") so operator-chosen store names cannot be enumerated across tenants. - POST /knowledge-bases/copy synchronously rejects clones whose target has a different embedding model or vector store, before the async clone task is enqueued. The async clone worker re-applies the same checks for defense in depth. - DELETE /vector-stores/:id refuses to remove a store with bound KBs, inside a transaction that row-locks the store on PostgreSQL and serializes via WAL on SQLite. unregister-from-registry is wrapped in defer/recover so a panic surfaces as a structured warning instead of silently leaking a stale engine. - vector_store_id is immutable after creation. The GORM <-:create tag blocks every ORM update path; the service-layer DTO omits the field entirely; a reflection-based regression test catches any future maintainer who adds it back to either layer. - Empty-string vector_store_id is normalized to nil at both the create path and inside SharesStoreWith, so rows persisted by callers that did not run Normalize first cannot trip false same-store comparisons. Part of #993. Depends on #994 and #1310.
This commit is contained in:
@@ -45,6 +45,50 @@ type TenantStoreOwnership interface {
|
||||
StoreOwnedBy(ctx context.Context, storeID string, tenantID uint64) (bool, error)
|
||||
}
|
||||
|
||||
// VerifyBinding asserts that a non-empty storeID is owned by tenantID and
|
||||
// registered in the in-memory engine registry. It encapsulates the two
|
||||
// checks that gate every store-bound resolution so that callers outside
|
||||
// the retriever package (notably the KB create-validation path) can reuse
|
||||
// the same sentinel hierarchy instead of duplicating the logic.
|
||||
//
|
||||
// Resolution rules:
|
||||
//
|
||||
// - ownership.StoreOwnedBy returns an infrastructure error → that error
|
||||
// is returned verbatim so callers can decide retry/abort.
|
||||
// - ownership returns (false, nil) → ErrVectorStoreForbidden.
|
||||
// - ownership returns (true, nil) + registry.GetByStoreID fails →
|
||||
// ErrVectorStoreNotFound.
|
||||
// - all checks succeed → nil.
|
||||
//
|
||||
// VerifyBinding itself never echoes the store UUID; callers MUST wrap the
|
||||
// sentinels into user-facing errors at the boundary (and log the
|
||||
// tenant/store pair via structured fields when appropriate).
|
||||
//
|
||||
// resolveBoundEngine (below) intentionally does NOT delegate to VerifyBinding
|
||||
// because it also needs the resolved engine service; sharing would require
|
||||
// either a second registry lookup or returning the service from VerifyBinding,
|
||||
// both of which dilute the helper's single purpose. The two paths are kept
|
||||
// in lockstep by the factory_test.go matrix.
|
||||
func VerifyBinding(
|
||||
ctx context.Context,
|
||||
registry interfaces.RetrieveEngineRegistry,
|
||||
ownership TenantStoreOwnership,
|
||||
tenantID uint64,
|
||||
storeID string,
|
||||
) error {
|
||||
owned, err := ownership.StoreOwnedBy(ctx, storeID, tenantID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !owned {
|
||||
return ErrVectorStoreForbidden
|
||||
}
|
||||
if _, err := registry.GetByStoreID(storeID); err != nil {
|
||||
return ErrVectorStoreNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateRetrieveEngineForKB returns a CompositeRetrieveEngine resolved from
|
||||
// a KB's VectorStore binding.
|
||||
//
|
||||
|
||||
@@ -384,6 +384,71 @@ func TestFactoryParallelInvocation(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// VerifyBinding tests — sentinel SSOT used by the KB create-validation
|
||||
// path. Mirrors the branches of resolveBoundEngine without constructing an
|
||||
// actual CompositeRetrieveEngine.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestVerifyBinding(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
esEngine := &fakeEngine{
|
||||
engineType: types.ElasticsearchRetrieverEngineType,
|
||||
support: []types.RetrieverType{types.VectorRetrieverType},
|
||||
}
|
||||
|
||||
t.Run("ownership infra error is returned verbatim", func(t *testing.T) {
|
||||
registry := registryWithStores(t, nil, nil)
|
||||
ownership := &fakeOwnership{err: errors.New("db boom")}
|
||||
err := VerifyBinding(ctx, registry, ownership, 1, "store-A")
|
||||
if err == nil || err.Error() != "db boom" {
|
||||
t.Fatalf("expected verbatim infra error, got %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("not owned -> ErrVectorStoreForbidden", func(t *testing.T) {
|
||||
registry := registryWithStores(t, nil, nil)
|
||||
ownership := &fakeOwnership{owned: map[string]uint64{}}
|
||||
err := VerifyBinding(ctx, registry, ownership, 1, "store-A")
|
||||
if !errors.Is(err, ErrVectorStoreForbidden) {
|
||||
t.Fatalf("expected ErrVectorStoreForbidden, got %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("owned but unregistered -> ErrVectorStoreNotFound", func(t *testing.T) {
|
||||
registry := registryWithStores(t, nil, nil)
|
||||
ownership := &fakeOwnership{owned: map[string]uint64{"store-A": 1}}
|
||||
err := VerifyBinding(ctx, registry, ownership, 1, "store-A")
|
||||
if !errors.Is(err, ErrVectorStoreNotFound) {
|
||||
t.Fatalf("expected ErrVectorStoreNotFound, got %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("owned and registered -> nil", func(t *testing.T) {
|
||||
registry := registryWithStores(t,
|
||||
map[string]*fakeEngine{"store-A": esEngine},
|
||||
nil,
|
||||
)
|
||||
ownership := &fakeOwnership{owned: map[string]uint64{"store-A": 1}}
|
||||
if err := VerifyBinding(ctx, registry, ownership, 1, "store-A"); err != nil {
|
||||
t.Fatalf("expected nil, got %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("cross-tenant returns Forbidden (not Found)", func(t *testing.T) {
|
||||
// store owned by tenant 2, queried by tenant 1
|
||||
registry := registryWithStores(t,
|
||||
map[string]*fakeEngine{"store-A": esEngine},
|
||||
nil,
|
||||
)
|
||||
ownership := &fakeOwnership{owned: map[string]uint64{"store-A": 2}}
|
||||
err := VerifyBinding(ctx, registry, ownership, 1, "store-A")
|
||||
if !errors.Is(err, ErrVectorStoreForbidden) {
|
||||
t.Fatalf("expected ErrVectorStoreForbidden, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ----- helpers -----
|
||||
|
||||
func strPtr(s string) *string { return &s }
|
||||
|
||||
Reference in New Issue
Block a user