WeKnora/internal/middleware/auth_internal_dispatch_test.go

108 lines
3.6 KiB
Go
Raw Normal View History

feat(agent): add the built-in WeKnora assistant with an operation catalog (#4302) * feat(agent): add the built-in WeKnora assistant with an operation catalog Adds builtin-weknora-assistant, which inspects and manages WeKnora with the signed-in user's permissions: - find_operations / run_operation over an allow-listed API operation catalog, dispatched in-process through the real router as the user - builtin approval for write/destructive operations, refused when non-interactive - agent attribution in knowledge base activity, including async tasks - page_context request field, narrowed to the turn's search targets and rendered into runtime_context with model handles * refactor(agent): compile the operation catalog from x-agent Swagger annotations The catalog was a hand-written copy of what the swag annotations already describe: routes, parameters, enums and response shapes. It now compiles from the Swagger document embedded in the binary. Handlers opt in with // @x-agent {"id":"knowledge.delete","risk":"destructive",...} // @x-agent-hint "Cannot be undone." // @Param id path string true "知识ID" extensions(x-agent=knowledge_id) and response types mark the fields the model may see with an extensions:"x-agent" struct tag. Exposure stays opt-in at every level: unmarked operations, parameters and fields are not reachable, so a new field on Knowledge or a new query parameter never reaches the model by accident. NewCatalog still enforces the safety rules (forbidden areas, risk versus method, approval targets), and a test fails when the annotations and docs/swagger.json disagree. The twelve operations compile to the same routes, parameters and results as before; document results now share one field set, and the parse_status filter accepts deleting, which the API supports. * fix(agent): enforce resume and wiki context scopes
2026-10-15 04:18:30 +00:00
package middleware
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
// dispatchUserService serves users by ID and fails the test if the request
// is authenticated by token instead.
type dispatchUserService struct {
interfaces.UserService
t *testing.T
users map[string]*types.User
}
func (s *dispatchUserService) GetUserByID(_ context.Context, id string) (*types.User, error) {
if u, ok := s.users[id]; ok {
return u, nil
}
return nil, errors.New("not found")
}
func (s *dispatchUserService) ValidateToken(context.Context, string) (*types.User, uint64, error) {
s.t.Fatalf("an internal dispatch must not fall through to token authentication")
return nil, 0, nil
}
func runInternalDispatch(
ctx context.Context, t *testing.T, users map[string]*types.User, members *fakeMemberService, header http.Header,
) (int, types.Caller) {
t.Helper()
gin.SetMode(gin.TestMode)
r := gin.New()
var caller types.Caller
r.Use(Auth(
&fakeTenantService{tenant: &types.Tenant{ID: 7}},
&dispatchUserService{t: t, users: users},
members, nil, cfgWithRBAC(true),
))
r.GET("/api/v1/knowledge/:id", func(c *gin.Context) {
caller = types.CallerFromContext(c.Request.Context())
c.Status(http.StatusNoContent)
})
req := httptest.NewRequest(http.MethodGet, "/api/v1/knowledge/k1", nil).WithContext(ctx)
for k, v := range header {
req.Header[k] = v
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w.Code, caller
}
func TestInternalDispatchRebuildsSessionFromDatabase(t *testing.T) {
members := newFakeMemberService()
members.seedActive("u1", 7, types.TenantRoleContributor)
users := map[string]*types.User{"u1": {ID: "u1", TenantID: 7, IsActive: true}}
ctx := types.WithInternalDispatch(context.Background(), types.InternalDispatch{UserID: "u1", TenantID: 7})
code, caller := runInternalDispatch(ctx, t, users, members, http.Header{
// Credentials on a dispatched request are ignored, never honored.
"Authorization": {"Bearer forged"},
"X-Api-Key": {"sk-forged"},
"X-Tenant-Id": {"99"},
})
if code != http.StatusNoContent {
t.Fatalf("status = %d, want 204", code)
}
want := types.Caller{TenantID: 7, UserID: "u1", Role: types.TenantRoleContributor}
if caller != want {
t.Fatalf("caller = %+v, want %+v", caller, want)
}
}
func TestInternalDispatchRejectsInactiveUser(t *testing.T) {
members := newFakeMemberService()
members.seedActive("u1", 7, types.TenantRoleAdmin)
users := map[string]*types.User{"u1": {ID: "u1", TenantID: 7, IsActive: false}}
ctx := types.WithInternalDispatch(context.Background(), types.InternalDispatch{UserID: "u1", TenantID: 7})
if code, _ := runInternalDispatch(ctx, t, users, members, nil); code != http.StatusUnauthorized {
t.Fatalf("status = %d, want 401", code)
}
if code, _ := runInternalDispatch(
types.WithInternalDispatch(context.Background(), types.InternalDispatch{UserID: "ghost", TenantID: 7}),
t, users, members, nil,
); code != http.StatusUnauthorized {
t.Fatalf("unknown user status = %d, want 401", code)
}
}
func TestInternalDispatchRequiresMembershipInDispatchTenant(t *testing.T) {
members := newFakeMemberService()
members.seedActive("u1", 8, types.TenantRoleAdmin)
users := map[string]*types.User{"u1": {ID: "u1", TenantID: 8, IsActive: true}}
ctx := types.WithInternalDispatch(context.Background(), types.InternalDispatch{UserID: "u1", TenantID: 7})
if code, _ := runInternalDispatch(ctx, t, users, members, nil); code != http.StatusForbidden {
t.Fatalf("status = %d, want 403", code)
}
}