chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

+294
View File
@@ -0,0 +1,294 @@
# Resource access boundaries
`access` contains shared permission resolution without depending on Gin or the
application service implementations. HTTP adapters keep parameter parsing, status
codes, RBAC rollout behavior, and response projection at their existing boundaries.
| Entry point | Shared rule | Additional boundary |
| --- | --- | --- |
| Resource mutations with URL/body KB selectors | `CheckOwnershipOrRole`: creator at Contributor or above, or sufficient tenant role | API-key capabilities, KB scope and tenant visibility remain separate checks |
| KB/document detail and content routes | `ResolveKB`: own tenant, organization share, then read-only shared agent | Tenant role/ownership guards and API-key capabilities |
| Shared documents, chunks, search targets and suggestions | `KBSharePermissions`: organization grants only | Existing user requirements and caller-specific filtering/error behavior |
| FAQ and tag service reads | `resolveKBReadTenant`: execution tenant or organization share | Direct cross-tenant calls require a user; no implicit agent fallback |
| KB list, document search and batch restoration with `agent_id` | Shared-agent lookup, then `SharedAgentKBScope` | API-key intersection; dynamic list/search selections also apply capability filtering |
| Wiki fixer source tenant | Organization Editor permission | Built-in fixer only; exactly one KB |
| Message file shared-KB fallback | Organization Viewer permission | Persisted message reference, exact resource handle, KB/resource owner match |
| KB file proxy | `ResolveKBFile`: exact Viewer grant and current explicit KB binding | Owner tenant and exports namespace; original uploads retain their separate download permission |
| Message file proxy | `ResolveMessageFile`: session ownership and exact persisted output reference | Current shared-agent or organization-KB permission for source-owned resources |
| Message artifact download | `ResolveMessageArtifact`: session ownership and persisted artifact index | Session-owned output remains accessible; source-owned output rechecks current sharing |
| FAQ and tag mutations | `RequireKBWrite`: exact Editor operation grant | API-key ingest capability and KB scope; tenant-role/creator checks remain at the admission boundary |
## Ownership and write roles
URL middleware and body-based handlers use the same lazy ownership decision.
The middleware adapter resolves identity, RBAC rollout configuration and the
configuration-gated superuser flag. API-key principals, sufficient roles,
cross-tenant superusers and disabled enforcement skip the creator lookup.
API keys still require their route capabilities and allowed KB scope.
When a lookup is needed, it must check tenant visibility before returning the
creator. An empty creator never matches an empty user. Middleware passes missing
resources to the handler, reports lookup failures as 503 and audits only actual
policy denials. Body-based handlers retain their existing 404/403/500 mapping.
KB, initialization, Wiki and body-based KB lookups share the same tenant check.
## Caller and resource tenant
`types.Caller` holds the authenticated tenant, user and tenant role. Auth records
it once; `KBRequest.Caller` and `KBAccess.Caller` use that same identity. The
legacy `TenantIDContextKey` continues to scope repository/model execution, so
existing storage APIs do not need a coordinated signature migration.
Use `types.WithExecutionTenant` to switch execution tenants. It captures the
caller first, even when identity is missing, and grants no access by itself.
Use `KBAccess.Context` after authorization to carry both the exact KB grant and
its execution tenant, or `WithGrant` to carry the grant without switching yet.
Grants bind the KB ID, owner tenant, caller and resolved permission; changing
execution tenant cannot turn a Viewer grant into Editor or expose another KB.
HTTP adapters retain Gin's caller keys for existing handlers.
Service reads use `KBPermissions` to check caller ownership, exact upstream
grants, then organization shares for the original caller. This check also applies
to documents/chunks returned by the initial tenant-scoped batch query, not just
rows found during cross-tenant expansion. Search preflight, result enrichment,
FAQ/tag reads, search targets and suggestion scopes follow the same boundary.
General document search enumerates the caller's own/shared KBs; its execution
tenant is not a new identity.
After authorizing a shared agent, `WithSharedAgent` carries its configured,
source-tenant-bound read scope into the pipeline. An arbitrary execution switch
cannot substitute for that grant. `logger.CloneContext` preserves the caller and
resource grants for detached work within the operation. Context grants contain
immutable snapshots; deriving a context does not mutate a sibling search branch.
They are not persisted as authority for subsequent requests. API-key scope is
reapplied when consuming any grant.
## Organization shares
`KBSharePermissions` fixes the caller tenant and role for one operation and caches
the granular decision per KB. Reading many documents/chunks from one KB therefore
queries its membership once. Both denied decisions and errors are cached within
that operation. The next request creates a new resolver and observes revocations.
The resolver is not a process-wide cache and is not shared between goroutines.
The share service remains responsible for the role cap across share permission,
organization membership and caller tenant role. The resolver returns lookup errors
so strict search preflight can report an infrastructure failure while best-effort
result expansion can omit inaccessible rows. `ResolveKB` retains its independent
read-only agent fallback when organization resolution cannot grant access.
## Shared-agent KB scope
A scope is created only after looking up an accessible shared agent. `all` means
all KBs in that agent's tenant; `selected` means its explicit nonempty ID set.
`none`, unknown modes and empty selections authorize no KBs. A nil/empty ID slice
never implicitly grants an entire tenant. Specifying an agent does not permit
falling back to a different shared agent.
These rules do not replace message/session ownership, persisted file-reference
validation, resource binding, Agent tool search-target restrictions, or embed/IM
capability checks. Raw tenant files and message files have different authorization
contracts and must not be admitted by a generic KB grant alone.
## FAQ and tag writes
FAQ/tag service mutations consume an explicit Editor grant; setting an execution
tenant or supplying a KB ID is insufficient. `ResolveKB` keeps the effective
permission used for response projection, but caps its context grant to the
requested operation. Thus an owner read does not mint a reusable write grant.
HTTP routes retain their existing role/creator admission checks. API-key ingest
capability and KB scope are reapplied when consuming a write grant.
Trusted FAQ-import, data-source sync and automatic-tagging workers use
`WithKBTaskWrite` after loading and validating their target KB and child-resource
bindings. This represents continuation of an admitted job, not renewed user
authorization on every retry. It carries exactly one KB, preserves the caller
or its absence, survives in-operation context cloning, and grants no tenant-wide
role. Services use the KB owner's TenantInfo for model/index configuration.
Batch FAQ updates resolve all source/destination tags, entries and exclusions
before mutation. Batch deletion also resolves all parent documents first.
Tag-only batch updates use the same plan. Tag groups execute in ascending seq_id
order, then explicit entry updates override only their specified fields.
Import retains per-entry content-validation results, but out-of-scope resource
references are rejected before admission and checked again in the worker.
This preflight prevents partial writes caused by invalid resource selections;
it does not add a transaction across the database, task queue and search index.
## File authorization and transport
File resolvers return request-local `FileAccess` locators before any storage
reader is opened. The KB catalog accepts only explicit resource bindings to live
documents in the exact live KB. Registered physical aliases resolve to the same
resource ID; chunk/wiki text is never authorization evidence. Historical files
without explicit bindings fail closed and need a trusted migration. A same-tenant
path or handle prefix cannot replace a KB binding. Message evidence comes from
persisted content, references, images, artifacts and tool results; tool arguments
do not prove that the message returned a file. The organization-shared KB
fallback also checks the catalog for an independent live KB/file binding;
retrieval text and a currently shared KB ID alone are insufficient.
Source-owned shared-agent files also require the current live agent share.
KB sources need an explicit live KB binding allowed by the agent's current
`all`/`selected` selection and the caller's API-key KB scope; `none`, unknown
modes, removed KB selections and deleted sources fail closed. Independently
generated artifacts remain accessible when explicitly bound to the exact
authorized message as an artifact. Mentioning a file in message text or the
artifact list does not create that binding. Caller-owned artifacts retain their
session ownership contract.
The storage adapter uses the authorized owner and backend. The shared
`filetransport` package owns response headers, safe inline/download disposition,
streaming and reader closure. Seekable readers use standard HTTP Range and HEAD
handling; streaming-only backends return full content with `Accept-Ranges: none`
without buffering the object (RFC 9110 sections 14.2 and 14.3). Permission-controlled responses use `private, no-store` so a later
request rechecks current access. Tenant-wide and signed-token file routes keep
their own authorization and caching contracts.
## Document and chunk writes
Document metadata, manual content, reparse, document tags/folders, image edits, chunk mutations
and generated-question edits consume explicit Editor grants after loading the
persisted document/KB binding. Full chunk objects cannot reparent existing rows.
Batch inputs are deduplicated and fully validated, including missing IDs and
each KB's grant, before writes. Text edits also check the parent/image-child
relationships that they will modify. Body-based HTTP routes explicitly resolve
an Editor operation; a previously cached owner read is not a write admission.
Document deletion shares a preflight plan and executor for single and batch
calls. The plan validates every selection and KB, loads owner TenantInfo and
routing metadata, and captures image references before marking rows as deleting.
Index/graph failures leave the document and original file available for retry.
Wiki deletion collects all chunk types before deleting chunks, so parent, image
and summary citations are removed along with text citations.
Physical file cleanup remains best effort after database deletion; this does not
introduce a transaction across database, indexes and storage or durable blob GC.
New queued deletion payloads pin `knowledge_base_id` as well as tenant and exact
document IDs. Workers consume a private cleanup scope bound to those references,
not general KB write permission; already deleted IDs are successful no-ops.
A moved document rejects the batch before side effects. Pre-upgrade payloads that
omit the KB are accepted only when remaining rows resolve to one same-tenant KB;
they cannot reconstruct the KB that existed at enqueue time. Failure callbacks
skip rejected scopes and condition status updates on tenant, KB and deleting
state. Scope/identity errors are not retried; infrastructure failures are.
Single/batch delete, clear-content and batch-reparse admission reject already
moving documents with HTTP 409 before enqueue. Workers recheck current state;
a deletion conflict is terminal for that admitted task, so retries cannot
follow a document into a different KB. This does not serialize admission with
a concurrent move. Synchronous metadata/image/chunk/summary handlers preserve
application 403/409 errors, including wrapped errors.
Batch reparse and batch document tags resolve an Editor operation and apply the
same creator-or-Admin admission policy as single-document writes, respecting
RBAC rollout/API-key behavior. Batch reparse payloads likewise carry the admitted
KB ID. Workers validate the whole batch before any submission and use exactly one `WithKBTaskWrite` grant;
each reparse reload consumes that grant and rejects a document still moving.
Missing/mixed/moved selections fail without submitting earlier batch members.
Legacy reparse payloads can reconstruct only a present, single-KB binding.
Session-history, temporary-KB and clone cleanup use exact server-derived
references from their already admitted operations. These cleanup contexts cannot
be used for document/chunk updates or additional IDs. Parsing and enrichment
workers use repositories for their internal persistence and rollback; they must
keep their existing task ownership checks, abort checks and resource bindings.
Repository access is not an incoming-request authorization API.
## Clone and move operations
`WithKBTransfer` admits the exact source/target pair after HTTP role/creator
checks. Clone consumes source Viewer, target Editor and the API-key
`manage_kbs` capability; move consumes Editor on both sides and `ingest`.
Both operations remain within one tenant. Creating a clone reserves its target
ID before enqueue and carries its creator into the worker. The ID of a new
resource is not checked against an existing-resource API-key allow-list.
Workers reload both KBs, validate their owners and consume a private pair grant.
Document/FAQ plans validate all selected resources, chunks, parents and tags
before destructive work. Lifecycle reads include every chunk type and indexing
state. A document's `_knowledge_transfer` metadata records task identity and
progress; retries reuse the reserved target, replace incomplete clones, skip
completed vector moves and retry outstanding wiki cleanup/parser enqueue.
This field is internal operation state, not caller-supplied custom metadata.
For `reparse`, transfer `done` means target binding and parser admission are
complete, not that parsing has finished. `ParseStatus` remains the parser's
state. `reparse_pending` already admits the target parser; extending the
`moving` write guard to that phase would also block legitimate worker writes.
Locking all writes until parsing finishes is a separate processing/concurrency
contract, including ordinary reparses, and is not provided by this transfer marker.
Failed clone chunk/index writes attempt rollback after conditionally claiming
the original destination. Rollback failures are returned, references retained
when cleanup is uncertain, and later retries replace the failed copy. Accounting
is committed only after the clone succeeds. FAQ containers do not inherit the
source document's transfer marker.
Source wiki cleanup starts only after the document ownership CAS succeeds.
The transfer checkpoint preserves source chunk IDs and summary before reparse
removes them. Retract page lists are persisted before page source refs are removed, so queue
failures retain retry evidence. Cleanup errors propagate; redelivery resumes cleanup after a
committed move without repeating vector/chunk relocation. These retries do not
provide a distributed transaction or recovery after retries are exhausted.
Vector reuse relocates KB metadata while preserving physical vector/chunk IDs.
Weaviate and Milvus drain the first source-filtered page until a follow-up query
is empty, avoiding offset limits/skipped rows. Repeated IDs or partial failures
return errors and leave the document checkpoint pending for retry.
OpenSearch selects the entire source KB/document pair, even without DB chunks,
and rejects version conflicts, timeouts and partial failures before DB relocation.
OpenSearch and Elasticsearch 7/8 require present non-negative `total`/`updated`
counts with `updated == total`; their move scripts do not skip/delete documents.
A zero/zero result allows a retry after metadata already reached the target.
Reparse cleanup loads and validates the source KB before touching any backend,
reusing its storage binding throughout; a failed/missing lookup cannot fall
back to the tenant default store.
Vector reuse never copies vectors and then deletes by the same document ID. Source and
target must use the same vector store for reuse, and the same concrete file
storage instance for either mode. Doris ANN tables cannot safely replace rows
without a delete/insert gap, so their moves require `reparse`. Clone still
requires compatible embedding models and vector stores; a move also retains
the existing same-model requirement. This is not a cross-storage migration API.
Conditional document checkpoints bind tenant, KB, status and the stored update
time. They keep storage accounting in the same database transaction and read
back timestamp precision. Delete stops when its checkpoint no longer matches.
Ordinary document/chunk writes reject a document in the `moving` phase. Parser
admission and failure callbacks verify the task's persisted tenant/KB binding;
table-summary failure cleanup also stops if its document changed.
## Follow-up work outside this refactor
These are separate follow-ups, not capabilities provided by this package:
1. **Complete worker contracts and concurrency control.** Audit enrichment,
table-summary, multimodal, wiki and indexing workers end to end. Standardize
payload resource bindings, processing-attempt IDs and conditional writes,
including operations admitted before a concurrent move. Do not replace
these checks with an execution-tenant switch or a blanket task write grant.
2. **Durable recovery across systems.** Add a transactional outbox and explicit
recovery/cancellation for exhausted transfer tasks. Current retries use the
same admitted task identity; a new move request is not a resume API. Database,
queue, vector, graph and blob operations are not one atomic transaction.
Physical file cleanup remains best effort and needs durable garbage collection.
3. **External-backend integration coverage.** Exercise clone/move, partial
backend failures, retries, pagination and search/edit behavior against live
PostgreSQL, Elasticsearch 7/8, OpenSearch, Qdrant, Milvus, Weaviate,
TencentVectorDB and Doris. Local SQLite vector tests and backend compilation
do not establish this coverage. Doris ANN vector reuse remains unsupported.
4. **Finish service-layer migration.** Apply explicit operation grants to the
remaining KB configuration/duplicate/delete, wiki and resource-administration
service methods, preserving their existing route admission policies. Keep
user/organization membership, embed, IM and signed-resource contracts separate.
5. **Trusted legacy file migration.** Backfill historical file bindings from
verified provenance, not arbitrary chunk/wiki mentions. Unbound historical
files now fail closed; request-path text fallback has been removed. Migrate
old queued payloads and transfer records without captured source wiki refs.
A legacy delete task without a KB ID can reconstruct only its present
unambiguous binding, not its original enqueue-time binding.
No public request schema or database column migration is required by this
refactor. Internal service interfaces require operation contexts, queued payloads
add optional scope fields, and malformed/out-of-scope batch selections now fail
before mutation instead of being silently skipped. Callers must also handle a
409 for document edits/deletes while a move is in progress.
+94
View File
@@ -0,0 +1,94 @@
package access
import (
"context"
"academy/internal/types"
)
// Context grants contain values, not mutable KB objects. Deriving a context
// copies the grant slice so parallel search branches cannot widen each other.
type kbGrant struct {
caller types.Caller
kbID string
tenantID uint64
permission types.OrgMemberRole
task bool
}
type agentGrant struct {
caller types.Caller
scope types.SharedAgentKBScope
}
// WithSharedAgent scopes execution after the caller has authorized this exact
// agent. Only its configured KBs receive read access; other source-tenant KBs
// and the source tenant's organization memberships are not inherited.
func WithSharedAgent(ctx context.Context, agent *types.CustomAgent) context.Context {
grant := agentGrant{caller: types.CallerFromContext(ctx), scope: types.NewSharedAgentKBScope(agent)}
ctx = context.WithValue(ctx, types.SharedAgentGrantContextKey, grant)
if agent == nil {
return ctx
}
return types.WithExecutionTenant(ctx, agent.TenantID)
}
// HasKBGrant checks only previously resolved resource access. It never infers
// ownership from the execution tenant, and always reapplies API-key scope.
func HasKBGrant(ctx context.Context, kbID string, tenantID uint64, required types.OrgMemberRole) bool {
if !required.IsValid() || types.AuthorizeTenantAPIKeyKnowledgeBases(ctx, kbID) != nil {
return false
}
caller := types.CallerFromContext(ctx)
if kbID == "" || tenantID == 0 {
return false
}
grants, _ := ctx.Value(types.KBGrantsContextKey).([]kbGrant)
for _, grant := range grants {
if (caller.TenantID != 0 || grant.task) && grant.caller == caller && grant.kbID == kbID &&
grant.tenantID == tenantID &&
grant.permission.HasPermission(required) {
return true
}
}
grant, ok := ctx.Value(types.SharedAgentGrantContextKey).(agentGrant)
return ok && caller.TenantID != 0 && required == types.OrgRoleViewer && grant.caller == caller &&
grant.scope.Allows(kbID, tenantID)
}
// KBPermissions combines caller ownership, exact context grants and organization
// shares for one service operation. Pass nil shares when that entry point does
// not permit organization expansion (for example, a caller without a user).
type KBPermissions struct {
ctx context.Context
caller types.Caller
shares *KBSharePermissions
}
// NewKBPermissions resolves reads for one caller and operation.
func NewKBPermissions(ctx context.Context, shares KBShareLookup) *KBPermissions {
caller := types.CallerFromContext(ctx)
return &KBPermissions{
ctx: ctx,
caller: caller,
shares: NewKBSharePermissions(ctx, shares, caller.TenantID, caller.Role),
}
}
// Check combines caller ownership, exact grants and organization sharing.
func (p *KBPermissions) Check(kbID string, ownerTenantID uint64, required types.OrgMemberRole) (bool, error) {
if kbID == "" || ownerTenantID == 0 || !required.IsValid() {
return false, nil
}
if err := types.AuthorizeTenantAPIKeyKnowledgeBases(p.ctx, kbID); err != nil {
return false, err
}
if (p.caller.TenantID == ownerTenantID && required == types.OrgRoleViewer) ||
HasKBGrant(p.ctx, kbID, ownerTenantID, required) {
return true, nil
}
if p.caller.TenantID == 0 || p.caller.TenantID == ownerTenantID {
return false, nil
}
return p.shares.Check(kbID, required)
}
+140
View File
@@ -0,0 +1,140 @@
package access
import (
"context"
"testing"
"academy/internal/logger"
"academy/internal/types"
"github.com/stretchr/testify/require"
)
func callerContext() context.Context {
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1))
ctx = context.WithValue(ctx, types.UserIDContextKey, "user")
return context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleContributor)
}
func TestKBGrantSurvivesExecutionSwitchAndDetachWithoutWidening(t *testing.T) {
ctx := callerContext()
kb := &types.KnowledgeBase{ID: "shared", TenantID: 2}
grant, err := ResolveKB(
ctx,
KBRequest{Caller: types.CallerFromContext(ctx)},
kb,
types.OrgRoleViewer,
&shareLookup{permission: types.OrgRoleViewer},
nil,
)
require.NoError(t, err)
ctx = grant.Context(ctx)
require.Equal(t, uint64(2), types.MustTenantIDFromContext(ctx))
ctx = logger.CloneContext(types.WithExecutionTenant(ctx, 3))
require.Equal(
t,
types.Caller{TenantID: 1, UserID: "user", Role: types.TenantRoleContributor},
types.CallerFromContext(ctx),
)
require.True(t, HasKBGrant(ctx, "shared", 2, types.OrgRoleViewer))
// A later mutation of the service model cannot mutate the captured grant.
kb.ID = "private"
require.False(t, HasKBGrant(ctx, "private", 2, types.OrgRoleViewer))
require.False(t, HasKBGrant(ctx, "shared", 3, types.OrgRoleViewer))
require.False(t, HasKBGrant(ctx, "shared", 2, types.OrgRoleEditor))
for _, caller := range []types.Caller{
{TenantID: 9, UserID: "user", Role: types.TenantRoleContributor},
{TenantID: 1, UserID: "other", Role: types.TenantRoleContributor},
{TenantID: 1, UserID: "user", Role: types.TenantRoleViewer},
} {
otherCtx := types.WithCaller(ctx, caller)
require.False(t, HasKBGrant(otherCtx, "shared", 2, types.OrgRoleViewer))
require.Equal(
t,
caller,
types.CallerFromContext(grant.Context(otherCtx)),
"reusing a grant cannot impersonate its caller",
)
require.Equal(
t,
uint64(3),
types.MustTenantIDFromContext(grant.Context(otherCtx)),
"a caller mismatch must not change execution scope",
)
}
narrowed := types.WithTenantAPIKeyScope(
ctx,
types.TenantAPIKeyScope{KnowledgeBaseIDs: types.StringArray{"another"}},
)
require.False(t, HasKBGrant(narrowed, "shared", 2, types.OrgRoleViewer))
}
func TestExecutionTenantDoesNotGrantOwnershipOrChangeShareIdentity(t *testing.T) {
ctx := types.WithExecutionTenant(callerContext(), 2)
shares := &shareLookup{}
allowed, err := NewKBPermissions(ctx, shares).Check("private", 2, types.OrgRoleViewer)
require.NoError(t, err)
require.False(t, allowed)
require.Equal(t, uint64(1), shares.caller)
require.Equal(t, types.TenantRoleContributor, shares.role)
ctx = types.WithExecutionTenant(context.Background(), 2)
allowed, err = NewKBPermissions(ctx, nil).Check("private", 2, types.OrgRoleViewer)
require.NoError(t, err)
require.False(t, allowed, "an absent caller must not become the execution tenant")
}
func TestSharedAgentGrantPreservesConfiguredScopeAcrossDetach(t *testing.T) {
for _, mode := range []string{"all", "selected", "none", "unknown"} {
t.Run(mode, func(t *testing.T) {
agent := &types.CustomAgent{
TenantID: 2,
Config: types.CustomAgentConfig{KBSelectionMode: mode, KnowledgeBases: []string{"selected"}},
}
ctx := logger.CloneContext(WithSharedAgent(callerContext(), agent))
require.Equal(t, uint64(1), types.CallerFromContext(ctx).TenantID)
require.Equal(t, uint64(2), types.MustTenantIDFromContext(ctx))
require.Equal(t, mode == "all" || mode == "selected", HasKBGrant(ctx, "selected", 2, types.OrgRoleViewer))
require.Equal(t, mode == "all", HasKBGrant(ctx, "other", 2, types.OrgRoleViewer))
require.False(t, HasKBGrant(ctx, "selected", 3, types.OrgRoleViewer))
require.False(t, HasKBGrant(ctx, "selected", 2, types.OrgRoleEditor))
})
}
}
func TestKBGrantBranchesRemainIndependent(t *testing.T) {
base := callerContext()
grant := &KBAccess{Caller: types.CallerFromContext(base), EffectiveTenantID: 2, Permission: types.OrgRoleViewer}
grant.KnowledgeBase = &types.KnowledgeBase{ID: "first", TenantID: 2}
first := grant.WithGrant(base)
grant.KnowledgeBase = &types.KnowledgeBase{ID: "second", TenantID: 2}
second := grant.WithGrant(base)
require.True(t, HasKBGrant(first, "first", 2, types.OrgRoleViewer))
require.False(t, HasKBGrant(first, "second", 2, types.OrgRoleViewer))
require.True(t, HasKBGrant(second, "second", 2, types.OrgRoleViewer))
require.False(t, HasKBGrant(second, "first", 2, types.OrgRoleViewer))
}
func TestKBPermissionsOwnerShortcutOnlyGrantsRead(t *testing.T) {
roles := []types.TenantRole{types.TenantRoleViewer, types.TenantRoleContributor, types.TenantRoleAdmin}
for _, role := range roles {
ctx := context.WithValue(callerContext(), types.TenantRoleContextKey, role)
permissions := NewKBPermissions(ctx, nil)
for _, required := range []types.OrgMemberRole{types.OrgRoleViewer, types.OrgRoleEditor, types.OrgRoleAdmin} {
allowed, err := permissions.Check("kb", 1, required)
require.NoError(t, err)
require.Equal(t, required == types.OrgRoleViewer, allowed)
}
grant := &KBAccess{
Caller: types.CallerFromContext(ctx),
KnowledgeBase: &types.KnowledgeBase{ID: "kb", TenantID: 1},
EffectiveTenantID: 1,
Permission: types.OrgRoleEditor,
}
permissions = NewKBPermissions(grant.Context(ctx), nil)
allowed, err := permissions.Check("kb", 1, types.OrgRoleEditor)
require.NoError(t, err)
require.True(t, allowed)
allowed, err = permissions.Check("kb", 1, types.OrgRoleAdmin)
require.NoError(t, err)
require.False(t, allowed)
}
}
+297
View File
@@ -0,0 +1,297 @@
package access
import (
"context"
"encoding/json"
"fmt"
"strings"
"academy/internal/types"
"academy/internal/types/interfaces"
secutils "academy/internal/utils"
)
// FileAccess is a request-local result, produced before storage is opened.
// Physical locators are not a substitute for KB/message authorization.
type FileAccess struct {
OwnerTenantID uint64
Path string
Filename string
StorageBackendID string
}
// FileCatalog resolves logical references to their stored owner and locator.
type FileCatalog interface {
ResolvePath(context.Context, string) (string, *types.StoredResource, error)
}
func resolveFile(
ctx context.Context,
catalog FileCatalog,
reference string,
) (FileAccess, *types.StoredResource, error) {
file := FileAccess{Path: reference, Filename: reference}
if catalog == nil {
if _, resource := types.ParseResourcePath(reference); resource {
return file, nil, ErrNotFound
}
return file, nil, nil
}
path, resource, err := catalog.ResolvePath(ctx, reference)
if err != nil {
return file, nil, ErrNotFound
}
file.Path = path
file.Filename = path
if resource != nil {
file.OwnerTenantID = resource.TenantID
file.StorageBackendID = resource.StorageBackendID
if strings.TrimSpace(resource.OriginalName) != "" {
file.Filename = resource.OriginalName
}
}
return file, resource, nil
}
// ResolveKBFile requires the route's exact KB grant and an independent live
// explicit binding check. Rewriting the execution tenant is insufficient.
func ResolveKBFile(
ctx context.Context,
grant *KBAccess,
kbID, reference string,
catalog FileCatalog,
bindings interfaces.KBResourceLookup,
) (FileAccess, error) {
var empty FileAccess
if grant == nil || grant.KnowledgeBase == nil || grant.KnowledgeBase.ID != kbID ||
grant.Caller != types.CallerFromContext(ctx) || !grant.Permission.HasPermission(types.OrgRoleViewer) {
return empty, ErrForbidden
}
if err := types.AuthorizeTenantAPIKeyKnowledgeBases(ctx, kbID); err != nil {
return empty, err
}
file, resource, err := resolveFile(ctx, catalog, reference)
if err != nil {
return empty, err
}
owner := grant.EffectiveTenantID
if owner == 0 || (resource != nil && resource.TenantID != owner) {
return empty, ErrForbidden
}
if err := secutils.ValidateKBScopedStoragePath(file.Path, owner); err != nil {
return empty, ErrForbidden
}
if bindings == nil {
return empty, ErrForbidden
}
bound, err := bindings.IsReferencedByKnowledgeBase(ctx, owner, kbID, reference)
if err != nil {
return empty, fmt.Errorf("check KB file binding: %w", err)
}
if !bound {
return empty, ErrForbidden
}
file.OwnerTenantID = owner
return file, nil
}
// artifactRefState says whether a reference names one of this message's
// artifacts, and if so whether the user has deleted it.
type artifactRefState int
const (
artifactRefNone artifactRefState = iota
artifactRefLive
artifactRefDeleted
)
// artifactReferenceState resolves a reference against the message's artifacts.
// A live row anywhere in the list wins over a tombstone: the same file can be
// attached twice at different positions, and one of them still being there
// means the message really does still offer it.
func artifactReferenceState(message *types.Message, reference string) artifactRefState {
state := artifactRefNone
for _, artifact := range message.Artifacts {
if artifact.URL != reference {
continue
}
if !artifact.Deleted() {
return artifactRefLive
}
state = artifactRefDeleted
}
return state
}
// MessageReferencesFile examines only persisted rendering/output fields. Tool
// arguments and request metadata are not evidence of a returned file.
func MessageReferencesFile(message *types.Message, reference string) bool {
if message == nil {
return false
}
// Artifacts are checked before the answer text, and a deleted one is a hard
// no. Deleting a generated file does not rewrite the answer that produced
// it, so its `resource://` handle is still sitting in message.Content; if
// the text were consulted first, the message-scoped file proxy would keep
// serving a file the user deleted — including to a shared-agent visitor,
// and including the case where the bytes survived because a knowledge entry
// still holds them. Those other owners have their own access paths.
switch artifactReferenceState(message, reference) {
case artifactRefDeleted:
return false
case artifactRefLive:
return true
}
if types.ContainsStorageReference(message.Content, reference) {
return true
}
for _, value := range []interface{}{message.KnowledgeReferences, message.Images} {
data, _ := json.Marshal(value)
if types.ContainsStorageReference(string(data), reference) {
return true
}
}
for _, step := range message.AgentSteps {
for _, call := range step.ToolCalls {
if call.Result == nil {
continue
}
data, _ := json.Marshal(call.Result)
if types.ContainsStorageReference(string(data), reference) {
return true
}
}
}
return false
}
// ResolveMessageFile loads the session-authorized message using the original
// caller and rechecks its current sharing relationships on every request.
func ResolveMessageFile(ctx context.Context, sessionID, messageID, reference string, messages MessageFileLookup,
agents SharedAgentFileLookup, catalog FileCatalog, kbShares MessageKBShareAuthorizer,
) (FileAccess, error) {
caller := types.CallerFromContext(ctx)
if caller.TenantID == 0 {
return FileAccess{}, ErrUnauthorized
}
if messages == nil {
return FileAccess{}, ErrNotFound
}
ctx = types.WithExecutionTenant(ctx, caller.TenantID)
message, err := messages.GetMessage(ctx, sessionID, messageID)
if err != nil || message == nil {
return FileAccess{}, ErrNotFound
}
return AuthorizeMessageFile(ctx, message, reference, agents, catalog, kbShares)
}
// AuthorizeMessageFile also serves index-based artifact downloads after their
// session/message lookup. It never accepts an unchecked client message.
func AuthorizeMessageFile(ctx context.Context, message *types.Message, reference string, agents SharedAgentFileLookup,
catalog FileCatalog, kbShares MessageKBShareAuthorizer,
) (FileAccess, error) {
caller := types.CallerFromContext(ctx)
if caller.TenantID == 0 {
return FileAccess{}, ErrUnauthorized
}
if !MessageReferencesFile(message, reference) {
return FileAccess{}, ErrForbidden
}
file, resource, err := resolveFile(ctx, catalog, reference)
if err != nil {
return FileAccess{}, err
}
owner := message.AgentTenantID
if resource != nil {
owner = resource.TenantID
}
if owner == 0 {
return FileAccess{}, ErrForbidden
}
if message.Role == "user" && owner != caller.TenantID {
return FileAccess{}, ErrForbidden
}
if kbShares.Bindings == nil {
kbShares.Bindings, _ = catalog.(interfaces.KBResourceLookup)
}
kbAuthorized := false
if resource != nil && message.AgentTenantID != 0 && message.AgentTenantID != owner {
kbAuthorized = kbShares.resourceAccessibleViaSharedKB(ctx, message, resource, caller.TenantID, caller.Role)
if !kbAuthorized {
return FileAccess{}, ErrForbidden
}
}
if owner != caller.TenantID && !kbAuthorized {
if message.AgentTenantID == 0 {
kbAuthorized = kbShares.resourceAccessibleViaSharedKB(ctx, message, resource, caller.TenantID, caller.Role)
}
if !kbAuthorized {
if message.AgentID == "" || agents == nil {
return FileAccess{}, ErrForbidden
}
agent, err := agents.GetSharedAgentForTenant(ctx, caller.TenantID, caller.Role, message.AgentID, owner)
if err != nil || agent == nil || agent.TenantID != owner {
return FileAccess{}, ErrForbidden
}
bindings, ok := catalog.(interfaces.MessageFileBindingLookup)
if !ok {
return FileAccess{}, ErrForbidden
}
origins, err := bindings.GetMessageFileBindings(ctx, owner, reference, message.ID)
if err != nil || origins == nil {
return FileAccess{}, ErrForbidden
}
allowed := origins.MessageArtifact
scope := types.NewSharedAgentKBScope(agent)
for _, kbID := range origins.KnowledgeBaseIDs {
if scope.Allows(kbID, owner) && types.AuthorizeTenantAPIKeyKnowledgeBases(ctx, kbID) == nil {
allowed = true
}
}
if !allowed {
return FileAccess{}, ErrForbidden
}
}
}
if resource == nil {
if err := secutils.ValidateStoragePathTenant(file.Path, owner); err != nil {
return FileAccess{}, ErrForbidden
}
}
file.OwnerTenantID = owner
return file, nil
}
// ResolveMessageArtifact selects a persisted artifact after session ownership
// was checked. Session-owned output stays downloadable independently of the
// agent; source-owned output still requires its current sharing permission.
func ResolveMessageArtifact(ctx context.Context, message *types.Message, index int, agents SharedAgentFileLookup,
catalog FileCatalog, kbShares MessageKBShareAuthorizer,
) (FileAccess, error) {
caller := types.CallerFromContext(ctx)
if caller.TenantID == 0 {
return FileAccess{}, ErrUnauthorized
}
if message == nil || index < 0 || index >= len(message.Artifacts) {
return FileAccess{}, ErrNotFound
}
artifact := message.Artifacts[index]
// Tombstones keep their slot so the indices of later artifacts stay put;
// they are not downloadable through any path, shared or owned.
if artifact.Deleted() {
return FileAccess{}, ErrNotFound
}
file, resource, err := resolveFile(ctx, catalog, artifact.URL)
if err != nil {
return FileAccess{}, err
}
if (resource != nil && resource.TenantID == caller.TenantID) ||
(resource == nil && secutils.ValidateStoragePathTenant(file.Path, caller.TenantID) == nil) {
file.OwnerTenantID = caller.TenantID
file.Filename = artifact.FileName
return file, nil
}
file, err = AuthorizeMessageFile(ctx, message, artifact.URL, agents, catalog, kbShares)
file.Filename = artifact.FileName
return file, err
}
+226
View File
@@ -0,0 +1,226 @@
package access
import (
"context"
"errors"
"testing"
"time"
"academy/internal/types"
"github.com/stretchr/testify/require"
)
type fileCatalog struct{ resource *types.StoredResource }
func (c fileCatalog) ResolvePath(_ context.Context, ref string) (string, *types.StoredResource, error) {
if c.resource == nil {
return ref, nil, nil
}
return c.resource.PhysicalPath, c.resource, nil
}
type fileBinding struct {
allowed bool
err error
kb string
tenant uint64
}
func (b *fileBinding) IsReferencedByKnowledgeBase(_ context.Context, tenant uint64, kb, _ string) (bool, error) {
b.kb, b.tenant = kb, tenant
return b.allowed, b.err
}
type fileMessages struct {
message *types.Message
tenant uint64
}
func (m *fileMessages) GetMessage(ctx context.Context, _, _ string) (*types.Message, error) {
m.tenant = types.MustTenantIDFromContext(ctx)
return m.message, nil
}
func TestKBFilesRequireExactGrantAndBinding(t *testing.T) {
base := callerContext()
grant := &KBAccess{
Caller: types.CallerFromContext(base),
KnowledgeBase: &types.KnowledgeBase{ID: "kb", TenantID: 2},
EffectiveTenantID: 2,
Permission: types.OrgRoleViewer,
}
ctx := grant.Context(base)
bindings := &fileBinding{allowed: true}
const ref = "resource://AbCdEfGhIjKlMnOpQrStUv"
catalog := fileCatalog{
&types.StoredResource{TenantID: 2, PhysicalPath: "local://2/exports/a.png", OriginalName: "a.png"},
}
file, err := ResolveKBFile(ctx, grant, "kb", ref, catalog, bindings)
require.NoError(t, err)
require.Equal(t, uint64(2), file.OwnerTenantID)
require.Equal(t, "kb", bindings.kb)
require.Equal(t, uint64(2), bindings.tenant)
bindings.allowed = false
_, err = ResolveKBFile(ctx, grant, "kb", ref, catalog, bindings)
require.ErrorIs(t, err, ErrForbidden, "a same-tenant file still needs an exact KB binding")
bindings.allowed = true
_, err = ResolveKBFile(ctx, grant, "another", ref, catalog, bindings)
require.ErrorIs(t, err, ErrForbidden)
_, err = ResolveKBFile(ctx, nil, "kb", ref, catalog, bindings)
require.ErrorIs(t, err, ErrForbidden, "execution tenant alone is not a grant")
bindings.err = errors.New("database unavailable")
_, err = ResolveKBFile(ctx, grant, "kb", ref, catalog, bindings)
require.ErrorIs(t, err, bindings.err)
}
func TestMessageFilesRequireReferenceAndRecheckRevocation(t *testing.T) {
const ref = "resource://AbCdEfGhIjKlMnOpQrStUv"
messages := &fileMessages{
message: &types.Message{ID: "message", AgentID: "agent", AgentTenantID: 2, Role: "assistant"},
}
agents := &agentLookup{agent: &types.CustomAgent{ID: "agent", TenantID: 2}}
catalog := artifactFileCatalog{
fileCatalog{&types.StoredResource{TenantID: 2, PhysicalPath: "local://2/exports/a.png"}},
}
ctx := types.WithExecutionTenant(callerContext(), 2)
_, err := ResolveMessageFile(ctx, "session", "message", ref, messages, agents, catalog, MessageKBShareAuthorizer{})
require.ErrorIs(t, err, ErrForbidden)
messages.message.Content = "![image](" + ref + "x)"
_, err = ResolveMessageFile(ctx, "session", "message", ref, messages, agents, catalog, MessageKBShareAuthorizer{})
require.ErrorIs(t, err, ErrForbidden, "a longer handle is not the requested handle")
messages.message.Content = "![image](" + ref + ")"
_, err = ResolveMessageFile(ctx, "session", "message", ref, messages, agents, catalog, MessageKBShareAuthorizer{})
require.NoError(t, err)
require.Equal(t, uint64(1), messages.tenant, "session lookup must use the caller")
agents.agent = nil
_, err = ResolveMessageFile(ctx, "session", "message", ref, messages, agents, catalog, MessageKBShareAuthorizer{})
require.ErrorIs(t, err, ErrForbidden, "historical references cannot bypass share revocation")
}
func TestMessageArtifactsKeepSessionOwnershipSeparateFromAgentOutput(t *testing.T) {
const ref = "resource://AbCdEfGhIjKlMnOpQrStUv"
message := &types.Message{
AgentID: "agent",
AgentTenantID: 2,
Artifacts: types.MessageArtifacts{{URL: ref, FileName: "report.pdf"}},
}
catalog := fileCatalog{&types.StoredResource{TenantID: 1, PhysicalPath: "local://1/exports/report.pdf"}}
file, err := ResolveMessageArtifact(callerContext(), message, 0, nil, catalog, MessageKBShareAuthorizer{})
require.NoError(t, err)
require.Equal(t, uint64(1), file.OwnerTenantID)
catalog.resource.TenantID = 2
catalog.resource.PhysicalPath = "local://2/exports/report.pdf"
_, err = ResolveMessageArtifact(callerContext(), message, 0, nil, catalog, MessageKBShareAuthorizer{})
require.ErrorIs(t, err, ErrForbidden)
}
type messageFileKBs struct{ kb *types.KnowledgeBase }
func (k messageFileKBs) GetKnowledgeBasesByIDsOnly(context.Context, []string) ([]*types.KnowledgeBase, error) {
return []*types.KnowledgeBase{k.kb}, nil
}
func TestMessageSharedKBFilesRequireLiveBinding(t *testing.T) {
const ref = "resource://AbCdEfGhIjKlMnOpQrStUv"
message := &types.Message{
AgentTenantID: 1, Role: "assistant",
KnowledgeReferences: types.References{{KnowledgeBaseID: "shared", Content: ref}},
}
catalog := fileCatalog{&types.StoredResource{
Handle: "AbCdEfGhIjKlMnOpQrStUv", TenantID: 2, PhysicalPath: "local://2/exports/a.png",
}}
binding := &fileBinding{allowed: true}
shares := &shareLookup{permission: types.OrgRoleViewer}
authorizer := MessageKBShareAuthorizer{
ShareGuard: shares, KBs: messageFileKBs{kb: &types.KnowledgeBase{ID: "shared", TenantID: 2}}, Bindings: binding,
}
_, err := AuthorizeMessageFile(callerContext(), message, ref, nil, catalog, authorizer)
require.NoError(t, err)
require.Equal(t, "shared", binding.kb)
require.Equal(t, uint64(2), binding.tenant)
binding.allowed = false
_, err = AuthorizeMessageFile(callerContext(), message, ref, nil, catalog, authorizer)
require.ErrorIs(t, err, ErrForbidden, "retrieval text alone must not authorize an unrelated same-tenant resource")
binding.allowed = true
binding.err = errors.New("binding lookup unavailable")
_, err = AuthorizeMessageFile(callerContext(), message, ref, nil, catalog, authorizer)
require.ErrorIs(t, err, ErrForbidden)
binding.err = nil
authorizer.Bindings = nil
_, err = AuthorizeMessageFile(callerContext(), message, ref, nil, catalog, authorizer)
require.ErrorIs(t, err, ErrForbidden, "missing live lookup must fail closed")
}
// This fixture represents a catalog claim made by the artifact collector.
type artifactFileCatalog struct{ fileCatalog }
func (artifactFileCatalog) GetMessageFileBindings(
_ context.Context,
_ uint64,
_, messageID string,
) (*types.MessageFileBindings, error) {
return &types.MessageFileBindings{MessageArtifact: messageID == "message"}, nil
}
// Deleting a generated file does not rewrite the answer that produced it, so
// its handle stays in message.Content. The message-scoped file proxy must not
// treat that leftover text as permission to keep serving the file — including
// when the bytes survived because a knowledge entry still holds them, and
// including for a shared-agent visitor who never had delete rights.
func TestDeletedArtifactIsNotServedFromTheAnswerText(t *testing.T) {
const ref = "resource://AbCdEfGhIjKlMnOpQrStUv"
deletedAt := time.Now()
messages := &fileMessages{message: &types.Message{
ID: "message", AgentID: "agent", AgentTenantID: 2, Role: "assistant",
Content: "![report](" + ref + ")",
Artifacts: types.MessageArtifacts{{URL: ref, FileName: "report.pdf"}},
}}
agents := &agentLookup{agent: &types.CustomAgent{ID: "agent", TenantID: 2}}
catalog := artifactFileCatalog{
fileCatalog{&types.StoredResource{TenantID: 2, PhysicalPath: "local://2/exports/report.pdf"}},
}
ctx := types.WithExecutionTenant(callerContext(), 2)
_, err := ResolveMessageFile(ctx, "session", "message", ref, messages, agents, catalog, MessageKBShareAuthorizer{})
require.NoError(t, err, "a live artifact is served as before")
messages.message.Artifacts[0].DeletedAt = &deletedAt
_, err = ResolveMessageFile(ctx, "session", "message", ref, messages, agents, catalog, MessageKBShareAuthorizer{})
require.ErrorIs(t, err, ErrForbidden, "the handle left in the answer text must not re-authorize a deleted file")
// The index-addressed artifact download agrees.
_, err = ResolveMessageArtifact(ctx, messages.message, 0, agents, catalog, MessageKBShareAuthorizer{})
require.ErrorIs(t, err, ErrNotFound)
}
// The same file can be attached twice at different positions. One of them
// still being live means the message really does still offer it.
func TestOneLiveCopyKeepsTheFileServable(t *testing.T) {
const ref = "resource://AbCdEfGhIjKlMnOpQrStUv"
deletedAt := time.Now()
message := &types.Message{
ID: "message", AgentTenantID: 1, Role: "assistant",
Content: "![report](" + ref + ")",
Artifacts: types.MessageArtifacts{
{URL: ref, FileName: "report.pdf", DeletedAt: &deletedAt},
{URL: ref, FileName: "report.pdf"},
},
}
require.True(t, MessageReferencesFile(message, ref))
message.Artifacts[1].DeletedAt = &deletedAt
require.False(t, MessageReferencesFile(message, ref), "with every copy deleted the message no longer offers it")
}
// A reference the message never produced as an artifact keeps its old path:
// knowledge-base images and user attachments are authorized by the text.
func TestNonArtifactReferencesStillAuthorizeFromContent(t *testing.T) {
const kbImage = "resource://ZzZzZzZzZzZzZzZzZzZzZz"
deletedAt := time.Now()
message := &types.Message{
ID: "message", AgentTenantID: 1, Role: "assistant",
Content: "![kb](" + kbImage + ")",
Artifacts: types.MessageArtifacts{{URL: "resource://AbCdEfGhIjKlMnOpQrStUv", DeletedAt: &deletedAt}},
}
require.True(t, MessageReferencesFile(message, kbImage))
}
+65
View File
@@ -0,0 +1,65 @@
package access
import (
"context"
apperrors "academy/internal/errors"
"academy/internal/logger"
"academy/internal/types"
)
// AuthorizeKBAccess rejects multi-KB searches whose scope includes a KB
// that the original caller is not entitled to read. Exact upstream grants
// support shared KB/agent execution; other foreign KBs need an organization
// permission check for the caller via KBPermissions, applying the 3-D cap
// (share role + caller's tenant-org role + tenant Viewer cap) introduced
// in Plan 3 of #1303.
//
// Returning NotFound rather than Forbidden avoids leaking the existence
// of unauthorized KB IDs that the caller could not otherwise observe.
// Structured logs record the rejection with the offending kb_id (always
// safe — KB IDs are UUIDs without sensitive content) and the requesting
// tenant for audit.
func AuthorizeKBAccess(
ctx context.Context,
shares KBShareLookup,
kbs []*types.KnowledgeBase,
) error {
if len(kbs) == 0 {
return nil
}
kbIDs := make([]string, 0, len(kbs))
for _, kb := range kbs {
kbIDs = append(kbIDs, kb.ID)
}
if err := types.AuthorizeTenantAPIKeyKnowledgeBases(ctx, kbIDs...); err != nil {
return err
}
requestTenantID := types.CallerFromContext(ctx).TenantID
permissions := NewKBPermissions(ctx, shares)
for _, kb := range kbs {
hasPermission, permErr := permissions.Check(kb.ID, kb.TenantID, types.OrgRoleViewer)
if permErr != nil {
logger.ErrorWithFields(ctx, permErr, map[string]interface{}{
"caller_tenant_id": requestTenantID,
"kb_tenant_id": kb.TenantID,
"kb_id": kb.ID,
"reason": "shared-KB permission lookup failed",
})
return apperrors.NewInternalServerError("failed to verify knowledge base access")
}
if !hasPermission {
logger.WarnWithFields(ctx, logger.Fields{
"caller_tenant_id": requestTenantID,
"kb_tenant_id": kb.TenantID,
"kb_id": kb.ID,
"reason": "tenant lacks viewer permission for foreign-tenant KB",
}, "search scope rejected: unauthorized foreign-tenant KB")
return apperrors.NewNotFoundError("knowledge base not found")
}
}
return nil
}
+62
View File
@@ -0,0 +1,62 @@
package access
import (
"context"
"academy/internal/types"
)
// KBSharePermissions resolves organization grants for one caller during one
// operation. It deliberately does not grant tenant ownership or shared-agent
// access. Callers retain their own policy for lookup failures (abort or filter).
// Create a new instance for each operation; it is not a cross-request cache and
// must not be shared between goroutines.
type KBSharePermissions struct {
ctx context.Context
lookup KBShareLookup
tenantID uint64
role types.TenantRole
results map[string]kbSharePermission
}
type kbSharePermission struct {
role types.OrgMemberRole
shared bool
err error
}
// NewKBSharePermissions creates a request-local permission cache.
func NewKBSharePermissions(
ctx context.Context,
lookup KBShareLookup,
tenantID uint64,
role types.TenantRole,
) *KBSharePermissions {
return &KBSharePermissions{
ctx: ctx,
lookup: lookup,
tenantID: tenantID,
role: role,
results: make(map[string]kbSharePermission),
}
}
// Permission caches both grants and failures so multiple documents/chunks in a
// KB observe the same decision, without repeating the membership queries.
func (p *KBSharePermissions) Permission(kbID string) (types.OrgMemberRole, bool, error) {
if kbID == "" || p.tenantID == 0 || p.lookup == nil {
return "", false, nil
}
result, ok := p.results[kbID]
if !ok {
result.role, result.shared, result.err = p.lookup.CheckTenantKBPermission(p.ctx, kbID, p.tenantID, p.role)
p.results[kbID] = result
}
return result.role, result.shared, result.err
}
// Check tests the required role against the cached organization permission.
func (p *KBSharePermissions) Check(kbID string, required types.OrgMemberRole) (bool, error) {
role, shared, err := p.Permission(kbID)
return err == nil && shared && role.IsValid() && required.IsValid() && role.HasPermission(required), err
}
@@ -0,0 +1,84 @@
package access
import (
"context"
"errors"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/require"
)
type permissionLookupFunc func(context.Context, string, uint64, types.TenantRole) (types.OrgMemberRole, bool, error)
func (f permissionLookupFunc) CheckTenantKBPermission(
ctx context.Context,
id string,
tenant uint64,
role types.TenantRole,
) (types.OrgMemberRole, bool, error) {
return f(ctx, id, tenant, role)
}
func TestKBSharePermissionsCachePerOperation(t *testing.T) {
calls := map[string]int{}
granted := true
lookup := permissionLookupFunc(
func(_ context.Context, kb string, tenant uint64, role types.TenantRole) (types.OrgMemberRole, bool, error) {
require.Equal(t, uint64(1), tenant)
require.Equal(t, types.TenantRoleContributor, role)
calls[kb]++
return types.OrgRoleEditor, granted, nil
},
)
permissions := NewKBSharePermissions(context.Background(), lookup, 1, types.TenantRoleContributor)
for _, required := range []types.OrgMemberRole{types.OrgRoleViewer, types.OrgRoleEditor, types.OrgRoleAdmin} {
allowed, err := permissions.Check("kb", required)
require.NoError(t, err)
require.Equal(t, required != types.OrgRoleAdmin, allowed)
}
require.Equal(t, 1, calls["kb"], "different minimum roles share the same membership lookup")
_, err := permissions.Check("other", types.OrgRoleViewer)
require.NoError(t, err)
require.Equal(t, 1, calls["other"])
granted = false
fresh := NewKBSharePermissions(context.Background(), lookup, 1, types.TenantRoleContributor)
allowed, err := fresh.Check("kb", types.OrgRoleViewer)
require.NoError(t, err)
require.False(t, allowed, "a new operation must observe share revocation")
require.Equal(t, 2, calls["kb"])
}
func TestKBSharePermissionsCachesFailuresWithoutGranting(t *testing.T) {
failure := errors.New("database unavailable")
calls := 0
lookup := permissionLookupFunc(
func(context.Context, string, uint64, types.TenantRole) (types.OrgMemberRole, bool, error) {
calls++
return types.OrgRoleAdmin, true, failure
},
)
permissions := NewKBSharePermissions(context.Background(), lookup, 1, types.TenantRoleAdmin)
for i := 0; i < 3; i++ {
allowed, err := permissions.Check("kb", types.OrgRoleViewer)
require.False(t, allowed)
require.ErrorIs(t, err, failure, "callers must retain the infrastructure error")
}
require.Equal(t, 1, calls)
}
func TestKBSharePermissionsMissingLookupAndInvalidRolesDeny(t *testing.T) {
permissions := NewKBSharePermissions(context.Background(), nil, 1, types.TenantRoleAdmin)
allowed, err := permissions.Check("kb", types.OrgRoleViewer)
require.NoError(t, err)
require.False(t, allowed)
lookup := permissionLookupFunc(
func(context.Context, string, uint64, types.TenantRole) (types.OrgMemberRole, bool, error) {
return types.OrgRoleEditor, true, nil
},
)
permissions = NewKBSharePermissions(context.Background(), lookup, 1, types.TenantRoleAdmin)
allowed, err = permissions.Check("kb", "unknown")
require.NoError(t, err)
require.False(t, allowed)
}
+227
View File
@@ -0,0 +1,227 @@
package access
import (
"context"
"fmt"
"academy/internal/types"
)
// KBTransferOperation selects the source and destination permission contract.
type KBTransferOperation string
// Supported knowledge-base transfer operations.
const (
KBTransferClone KBTransferOperation = "clone"
KBTransferMove KBTransferOperation = "move"
)
type kbTransferGrant struct {
caller types.Caller
tenant uint64
source, target, taskID, creatorID string
operation KBTransferOperation
create bool
}
// WithKBTransfer admits a pair of resources after the entry point has resolved
// the source and destination grants and applied its creator/role policy. A new
// clone destination must be a server-reserved ID; it is not an existing KB.
func WithKBTransfer(
ctx context.Context,
source, target *types.KnowledgeBase,
operation KBTransferOperation,
taskID string,
create bool,
) (context.Context, error) {
caller := types.CallerFromContext(ctx)
if taskID == "" {
return ctx, ErrForbidden
}
if err := validateTransferPair(source, target, caller.TenantID, operation, create); err != nil {
return ctx, err
}
if err := transferAPIScope(ctx, source.ID, target.ID, operation, create); err != nil {
return ctx, err
}
required := types.OrgRoleViewer
if operation == KBTransferMove {
required = types.OrgRoleEditor
}
if !HasKBGrant(ctx, source.ID, source.TenantID, required) ||
(!create && !HasKBGrant(ctx, target.ID, target.TenantID, types.OrgRoleEditor)) {
return ctx, ErrForbidden
}
return withTransferGrant(ctx, source, target, operation, taskID, create, false), nil
}
// WithKBTransferTask continues an admitted task. Both KBs must first be loaded
// with their persisted owners (or a reserved new clone destination). This scope
// cannot authorize a different pair or upgrade the worker into a tenant user.
func WithKBTransferTask(
ctx context.Context,
source, target *types.KnowledgeBase,
expectedTenant uint64,
operation KBTransferOperation,
taskID string,
create bool,
) (context.Context, error) {
if taskID == "" {
return ctx, ErrForbidden
}
if err := validateTransferPair(source, target, expectedTenant, operation, create); err != nil {
return ctx, err
}
ctx = types.WithExecutionTenant(ctx, expectedTenant)
return withTransferGrant(ctx, source, target, operation, taskID, create, true), nil
}
func withTransferGrant(
ctx context.Context,
source, target *types.KnowledgeBase,
operation KBTransferOperation,
taskID string,
create, task bool,
) context.Context {
caller := types.CallerFromContext(ctx)
grant := kbTransferGrant{
caller: caller,
tenant: source.TenantID,
source: source.ID,
target: target.ID,
taskID: taskID,
creatorID: target.CreatorID,
operation: operation,
create: create,
}
required := types.OrgRoleViewer
if operation == KBTransferMove {
required = types.OrgRoleEditor
}
ctx = context.WithValue(ctx, types.KBGrantsContextKey, []kbGrant{
{caller: caller, kbID: source.ID, tenantID: source.TenantID, permission: required, task: task},
{caller: caller, kbID: target.ID, tenantID: target.TenantID, permission: types.OrgRoleEditor, task: task},
})
return context.WithValue(ctx, types.KBTransferContextKey, grant)
}
// RequireKBTransfer consumes the exact caller, operation and resource-pair grant.
func RequireKBTransfer(ctx context.Context, source, target *types.KnowledgeBase, operation KBTransferOperation) error {
grant, ok := ctx.Value(types.KBTransferContextKey).(kbTransferGrant)
if !ok || grant.caller != types.CallerFromContext(ctx) || grant.operation != operation {
return ErrForbidden
}
if err := validateTransferPair(source, target, grant.tenant, operation, grant.create); err != nil {
return err
}
if grant.source != source.ID || grant.target != target.ID {
return ErrForbidden
}
return transferAPIScope(ctx, source.ID, target.ID, operation, grant.create)
}
// CloneDestination exposes only the destination already admitted by the
// request/worker; CopyKnowledgeBase cannot turn an empty ID into ambient write.
func CloneDestination(ctx context.Context, sourceID string) (id string, create bool, creatorID string, err error) {
g, ok := ctx.Value(types.KBTransferContextKey).(kbTransferGrant)
if !ok || g.caller != types.CallerFromContext(ctx) || g.operation != KBTransferClone || g.source != sourceID {
return "", false, "", ErrForbidden
}
return g.target, g.create, g.creatorID, nil
}
// TransferTaskID returns the admitted operation identity for retry checkpoints.
func TransferTaskID(ctx context.Context) string {
g, ok := ctx.Value(types.KBTransferContextKey).(kbTransferGrant)
if !ok || g.caller != types.CallerFromContext(ctx) {
return ""
}
return g.taskID
}
func validateTransferPair(
source, target *types.KnowledgeBase,
tenant uint64,
operation KBTransferOperation,
create bool,
) error {
if source == nil || target == nil || tenant == 0 || source.ID == "" || target.ID == "" ||
source.TenantID != tenant ||
target.TenantID != tenant {
return ErrForbidden
}
if source.ID == target.ID {
return fmt.Errorf("source and target knowledge bases must differ")
}
if operation != KBTransferClone && operation != KBTransferMove || create && operation != KBTransferClone {
return ErrForbidden
}
return nil
}
func transferAPIScope(
ctx context.Context,
sourceID, targetID string,
operation KBTransferOperation,
create bool,
) error {
ids := []string{sourceID}
if !create {
ids = append(ids, targetID)
}
if err := types.AuthorizeTenantAPIKeyKnowledgeBases(ctx, ids...); err != nil {
return err
}
capability := types.APIKeyCapabilityManageKnowledgeBases
if operation == KBTransferMove {
capability = types.APIKeyCapabilityIngest
}
if scope, ok := types.TenantAPIKeyScopeFromContext(ctx); ok && !scope.FullAccess &&
!scope.HasCapability(capability) {
return ErrForbidden
}
return nil
}
// ValidateKBTransferCompatibility is shared by synchronous admission and task
// execution, so invalid modes/configurations fail before resource mutations.
func ValidateKBTransferCompatibility(
source, target *types.KnowledgeBase,
operation KBTransferOperation,
mode string,
tenant *types.Tenant,
) error {
if source == nil || target == nil {
return ErrNotFound
}
if source.ID == target.ID {
return fmt.Errorf("source and target knowledge bases must differ")
}
if source.Type != target.Type {
return fmt.Errorf("source and target knowledge bases must have the same type")
}
if source.EmbeddingModelID != target.EmbeddingModelID {
return fmt.Errorf("source and target knowledge bases use different embedding models")
}
if operation == KBTransferMove && mode != "reuse_vectors" && mode != "reparse" {
return fmt.Errorf("unknown move mode: %s", mode)
}
if (operation == KBTransferClone || mode == "reuse_vectors") && !source.SharesStoreWith(target) {
return fmt.Errorf("source and target knowledge bases use different vector stores; use reparse mode for moves")
}
// A move retains file paths too, so resolving them through another storage
// instance would make the document unreadable, even when vectors are reparsed.
defaultID, defaultProvider := "", ""
if tenant != nil {
if tenant.DefaultStorageBackendID != nil {
defaultID = *tenant.DefaultStorageBackendID
}
if tenant.StorageEngineConfig != nil {
defaultProvider = tenant.StorageEngineConfig.DefaultProvider
}
}
if !source.SharesStorageBackendWith(target, defaultID, defaultProvider) {
return fmt.Errorf("source and target knowledge bases use different storage instances")
}
return nil
}
@@ -0,0 +1,96 @@
package access
import (
"context"
"fmt"
"testing"
"academy/internal/logger"
"academy/internal/types"
"github.com/stretchr/testify/require"
)
func TestTransferAdmissionRequiresIndependentGrants(t *testing.T) {
source, target := &types.KnowledgeBase{ID: "source", TenantID: 1}, &types.KnowledgeBase{ID: "target", TenantID: 1}
ctx := types.WithCaller(
context.Background(),
types.Caller{TenantID: 1, UserID: "user", Role: types.TenantRoleAdmin},
)
_, err := WithKBTransfer(ctx, source, target, KBTransferMove, "task", false)
require.ErrorIs(t, err, ErrForbidden)
request := KBRequest{Caller: types.CallerFromContext(ctx)}
sourceRead, err := ResolveKB(ctx, request, source, types.OrgRoleViewer, nil, nil)
require.NoError(t, err)
targetRead, err := ResolveKB(ctx, request, target, types.OrgRoleViewer, nil, nil)
require.NoError(t, err)
reads := targetRead.WithGrant(sourceRead.WithGrant(ctx))
_, err = WithKBTransfer(reads, source, target, KBTransferClone, "task", false)
require.ErrorIs(t, err, ErrForbidden, "owner read projection must not authorize target replacement")
targetWrite, err := ResolveKB(ctx, request, target, types.OrgRoleEditor, nil, nil)
require.NoError(t, err)
cloneCtx, err := WithKBTransfer(targetWrite.WithGrant(reads), source, target, KBTransferClone, "task", false)
require.NoError(t, err)
require.NoError(t, RequireKBTransfer(logger.CloneContext(cloneCtx), source, target, KBTransferClone))
require.False(t, HasKBGrant(cloneCtx, source.ID, 1, types.OrgRoleEditor))
_, err = WithKBTransfer(targetWrite.WithGrant(reads), source, target, KBTransferMove, "task", false)
require.ErrorIs(t, err, ErrForbidden)
}
func TestTransferTaskScopeIsExactAndDoesNotCreateCaller(t *testing.T) {
source, target := &types.KnowledgeBase{ID: "source", TenantID: 7}, &types.KnowledgeBase{ID: "target", TenantID: 7}
ctx, err := WithKBTransferTask(context.Background(), source, target, 7, KBTransferMove, "task", false)
require.NoError(t, err)
ctx = logger.CloneContext(ctx)
require.Zero(t, types.CallerFromContext(ctx).TenantID)
require.NoError(t, RequireKBTransfer(ctx, source, target, KBTransferMove))
require.ErrorIs(t, RequireKBTransfer(ctx, source, target, KBTransferClone), ErrForbidden)
require.ErrorIs(
t,
RequireKBTransfer(ctx, source, &types.KnowledgeBase{ID: "third", TenantID: 7}, KBTransferMove),
ErrForbidden,
)
require.False(t, HasKBGrant(ctx, "third", 7, types.OrgRoleViewer))
_, err = WithKBTransferTask(
ctx,
source,
&types.KnowledgeBase{ID: "target", TenantID: 8},
7,
KBTransferMove,
"task",
false,
)
require.ErrorIs(t, err, ErrForbidden)
changed := types.WithCaller(ctx, types.Caller{TenantID: 7, UserID: "different"})
require.ErrorIs(t, RequireKBTransfer(changed, source, target, KBTransferMove), ErrForbidden)
}
func TestTransferAPICapabilitiesRemainSeparate(t *testing.T) {
source, target := &types.KnowledgeBase{ID: "source", TenantID: 1}, &types.KnowledgeBase{ID: "target", TenantID: 1}
for _, tc := range []struct {
operation KBTransferOperation
capability string
create bool
ids []string
allowed bool
}{
{KBTransferClone, "manage_kbs", false, []string{"source", "target"}, true},
{KBTransferClone, "ingest", false, []string{"source", "target"}, false},
{KBTransferMove, "ingest", false, []string{"source", "target"}, true},
{KBTransferMove, "manage_kbs", false, []string{"source", "target"}, false},
{KBTransferMove, "ingest", false, []string{"source"}, false},
{KBTransferClone, "manage_kbs", true, []string{"source"}, true},
} {
t.Run(
fmt.Sprintf("%s/%s/create=%v/ids=%d", tc.operation, tc.capability, tc.create, len(tc.ids)),
func(t *testing.T) {
ctx, err := WithKBTransferTask(context.Background(), source, target, 1, tc.operation, "task", tc.create)
require.NoError(t, err)
ctx = types.WithTenantAPIKeyScope(
ctx,
types.TenantAPIKeyScope{Capabilities: types.StringArray{tc.capability}, KnowledgeBaseIDs: tc.ids},
)
require.Equal(t, tc.allowed, RequireKBTransfer(ctx, source, target, tc.operation) == nil)
},
)
}
}
+45
View File
@@ -0,0 +1,45 @@
package access
import (
"context"
"academy/internal/types"
)
// RequireKBWrite consumes an explicit operation grant. Tenant ownership and
// role checks belong to the entry point that resolved the grant; an execution
// tenant alone, or a shared-agent/read grant, never authorizes a mutation.
func RequireKBWrite(ctx context.Context, kb *types.KnowledgeBase) error {
if kb == nil || kb.ID == "" || kb.TenantID == 0 {
return ErrNotFound
}
if scope, ok := types.TenantAPIKeyScopeFromContext(ctx); ok && !scope.FullAccess &&
!scope.HasCapability(types.APIKeyCapabilityIngest) {
return ErrForbidden
}
if !HasKBGrant(ctx, kb.ID, kb.TenantID, types.OrgRoleEditor) {
return ErrForbidden
}
return nil
}
// WithKBTaskWrite is for trusted workers continuing an admitted operation.
// The worker supplies a server-loaded KB and verifies its child-resource
// bindings before any side effects. It grants only this KB, preserves the
// original caller (including an absent caller), and never creates an Admin.
// This is a task execution grant, not a way to authorize an incoming request.
func WithKBTaskWrite(ctx context.Context, kb *types.KnowledgeBase, expectedTenant uint64) (context.Context, error) {
if kb == nil || kb.ID == "" || expectedTenant == 0 || kb.TenantID != expectedTenant {
return ctx, ErrForbidden
}
ctx = types.WithExecutionTenant(ctx, expectedTenant)
grant := kbGrant{
caller: types.CallerFromContext(ctx),
kbID: kb.ID,
tenantID: expectedTenant,
permission: types.OrgRoleEditor,
task: true,
}
// A worker gets exactly one scope, without inheriting another task's KBs.
return context.WithValue(ctx, types.KBGrantsContextKey, []kbGrant{grant}), nil
}
@@ -0,0 +1,85 @@
package access
import (
"context"
"testing"
"academy/internal/logger"
"academy/internal/types"
"github.com/stretchr/testify/require"
)
func TestKBWriteConsumesOperationGrant(t *testing.T) {
ctx := callerContext()
kb := &types.KnowledgeBase{ID: "kb", TenantID: types.CallerFromContext(ctx).TenantID}
read, err := ResolveKB(ctx, KBRequest{Caller: types.CallerFromContext(ctx)}, kb, types.OrgRoleViewer, nil, nil)
require.NoError(t, err)
require.Equal(t, types.OrgRoleAdmin, read.Permission, "owner permission projection remains unchanged")
require.ErrorIs(t, RequireKBWrite(read.Context(ctx), kb), ErrForbidden, "an owner read does not grant mutation")
require.ErrorIs(t, RequireKBWrite(types.WithExecutionTenant(ctx, kb.TenantID), kb), ErrForbidden)
write, err := ResolveKB(ctx, KBRequest{Caller: types.CallerFromContext(ctx)}, kb, types.OrgRoleEditor, nil, nil)
require.NoError(t, err)
ctx = logger.CloneContext(write.Context(ctx))
require.NoError(t, RequireKBWrite(ctx, kb))
require.ErrorIs(t, RequireKBWrite(ctx, &types.KnowledgeBase{ID: "other", TenantID: kb.TenantID}), ErrForbidden)
require.ErrorIs(t, RequireKBWrite(ctx, &types.KnowledgeBase{ID: kb.ID, TenantID: kb.TenantID + 1}), ErrForbidden)
for _, tt := range []struct {
name string
scope types.TenantAPIKeyScope
allowed bool
}{
{"retrieve only", types.TenantAPIKeyScope{Capabilities: types.StringArray{"retrieve"}}, false},
{
"ingest",
types.TenantAPIKeyScope{
Capabilities: types.StringArray{"ingest"},
KnowledgeBaseIDs: types.StringArray{"kb"},
},
true,
},
{
"wrong KB",
types.TenantAPIKeyScope{
Capabilities: types.StringArray{"ingest"},
KnowledgeBaseIDs: types.StringArray{"other"},
},
false,
},
{"full access", types.TenantAPIKeyScope{FullAccess: true}, true},
} {
t.Run(tt.name, func(t *testing.T) {
err := RequireKBWrite(types.WithTenantAPIKeyScope(ctx, tt.scope), kb)
require.Equal(t, tt.allowed, err == nil)
})
}
}
func TestKBTaskWriteIsExplicitAndBounded(t *testing.T) {
kb := &types.KnowledgeBase{ID: "kb", TenantID: 7}
base := context.Background()
ctx, err := WithKBTaskWrite(base, kb, 7)
require.NoError(t, err)
ctx = logger.CloneContext(ctx)
require.Zero(t, types.CallerFromContext(ctx).TenantID, "a worker must not impersonate the tenant owner")
require.NoError(t, RequireKBWrite(ctx, kb))
allowed, err := NewKBPermissions(ctx, nil).Check("kb", 7, types.OrgRoleViewer)
require.NoError(t, err)
require.True(t, allowed, "a scoped write task can read its KB")
allowed, err = NewKBPermissions(ctx, nil).Check("other", 7, types.OrgRoleViewer)
require.NoError(t, err)
require.False(t, allowed)
require.ErrorIs(t, RequireKBWrite(ctx, &types.KnowledgeBase{ID: "other", TenantID: 7}), ErrForbidden)
_, err = WithKBTaskWrite(base, kb, 8)
require.ErrorIs(t, err, ErrForbidden)
_, err = WithKBTaskWrite(base, kb, 0)
require.ErrorIs(t, err, ErrForbidden)
require.False(t, HasKBGrant(base, "kb", 7, types.OrgRoleEditor), "the parent context stays unmodified")
request := callerContext()
task, err := WithKBTaskWrite(request, kb, 7)
require.NoError(t, err)
require.Equal(t, types.CallerFromContext(request), types.CallerFromContext(task))
changed := types.WithCaller(task, types.Caller{TenantID: 99, UserID: "another"})
require.ErrorIs(t, RequireKBWrite(changed, kb), ErrForbidden)
}
@@ -0,0 +1,38 @@
package access
import (
"encoding/json"
apperrors "academy/internal/errors"
"academy/internal/types"
)
// RejectMovingKnowledge is shared by admission and persisted service checks.
// Admission prevents misleading task acceptance; workers must recheck after
// enqueue because a move can claim the document in the intervening window.
func RejectMovingKnowledge(knowledge *types.Knowledge) error {
if knowledge == nil {
return apperrors.NewNotFoundError("knowledge not found")
}
fields := map[string]json.RawMessage{}
if len(knowledge.Metadata) != 0 {
if err := json.Unmarshal(knowledge.Metadata, &fields); err != nil {
return err
}
}
raw := fields[types.KnowledgeTransferMetadataKey]
if len(raw) == 0 {
return nil
}
var state struct {
Operation KBTransferOperation `json:"operation"`
Phase string `json:"phase"`
}
if err := json.Unmarshal(raw, &state); err != nil {
return err
}
if state.Operation == KBTransferMove && state.Phase == "moving" {
return apperrors.NewConflictError("knowledge has an unfinished move; retry the move first")
}
return nil
}
@@ -0,0 +1,156 @@
// Package access resolves resource permissions independently of HTTP routing.
// Tenant roles, API-key capabilities, and resource ownership guards remain
// separate checks; a KB grant does not replace them.
package access
import (
"context"
"errors"
"fmt"
"academy/internal/types"
)
// Resource access errors retain distinct adapter response mappings.
var (
ErrUnauthorized = errors.New("kb_access: unauthorized")
ErrNotFound = errors.New("kb_access: not found")
ErrForbidden = errors.New("kb_access: forbidden")
ErrInvalidAgentSource = errors.New("kb_access: invalid agent source")
)
// KBRequest keeps the authenticated caller separate from the resource tenant.
// AgentSourceTenantID is parsed only when the explicit-agent fallback is used.
type KBRequest struct {
Caller types.Caller
AgentID string
AgentSourceTenantID string
}
// KBAccess binds a resolved resource permission to its original caller.
type KBAccess struct {
KnowledgeBase *types.KnowledgeBase
Caller types.Caller
EffectiveTenantID uint64
Permission types.OrgMemberRole
// A read resolution must not mint a write grant even for the KB owner.
operationPermission types.OrgMemberRole
}
// Context scopes resource operations without changing the authenticated caller.
func (a *KBAccess) Context(ctx context.Context) context.Context {
if a == nil || a.KnowledgeBase == nil {
return ctx
}
scoped := a.WithGrant(ctx)
if types.CallerFromContext(scoped) != a.Caller.Normalize() {
return ctx
}
return types.WithExecutionTenant(scoped, a.EffectiveTenantID)
}
// WithGrant carries this authorization without changing execution scope.
func (a *KBAccess) WithGrant(ctx context.Context) context.Context {
if a == nil || a.KnowledgeBase == nil {
return ctx
}
caller := a.Caller.Normalize()
if existing, ok := ctx.Value(types.CallerContextKey).(types.Caller); ok && existing != caller {
return ctx // A grant cannot replace an already authenticated caller.
}
grants, _ := ctx.Value(types.KBGrantsContextKey).([]kbGrant)
permission := a.Permission
if a.operationPermission.IsValid() && permission.HasPermission(a.operationPermission) {
permission = a.operationPermission
}
grants = append(
append([]kbGrant(nil), grants...),
kbGrant{caller: caller, kbID: a.KnowledgeBase.ID, tenantID: a.EffectiveTenantID, permission: permission},
)
return context.WithValue(types.WithCaller(ctx, caller), types.KBGrantsContextKey, grants)
}
// KBShareLookup resolves organization sharing with the caller role cap.
type KBShareLookup interface {
CheckTenantKBPermission(context.Context, string, uint64, types.TenantRole) (types.OrgMemberRole, bool, error)
}
// SharedAgentLookup verifies access to a particular shared agent.
type SharedAgentLookup interface {
GetSharedAgentForTenant(context.Context, uint64, types.TenantRole, string, ...uint64) (*types.CustomAgent, error)
}
// AgentShareLookup also supports read access through any reachable agent.
type AgentShareLookup interface {
SharedAgentLookup
TenantCanAccessKBViaSomeSharedAgent(context.Context, uint64, types.TenantRole, *types.KnowledgeBase) (bool, error)
}
// ResolveKB authorizes a server-loaded KB (or a document's persisted KB/tenant
// reference). Its tenant is authoritative; resolving the owner from a share
// record again would add a lookup and a second source of truth. It never treats
// an effective resource tenant as the caller.
// Share lookup errors do not grant access; an independent agent grant may still
// allow reading. An explicit agent selector never falls back to another agent.
func ResolveKB(ctx context.Context, request KBRequest, kb *types.KnowledgeBase, required types.OrgMemberRole,
shares KBShareLookup, agents AgentShareLookup,
) (*KBAccess, error) {
if request.Caller.TenantID == 0 {
return nil, ErrUnauthorized
}
if kb == nil || kb.ID == "" {
return nil, ErrNotFound
}
if err := types.AuthorizeTenantAPIKeyKnowledgeBases(ctx, kb.ID); err != nil {
return nil, err
}
request.Caller = request.Caller.Normalize()
if caller, ok := ctx.Value(types.CallerContextKey).(types.Caller); ok && caller != request.Caller {
return nil, ErrForbidden
}
grant := func(permission types.OrgMemberRole) (*KBAccess, error) {
return &KBAccess{
KnowledgeBase: kb, Caller: request.Caller,
EffectiveTenantID: kb.TenantID, Permission: permission, operationPermission: required,
}, nil
}
if kb.TenantID == request.Caller.TenantID {
return grant(types.OrgRoleAdmin)
}
if shares != nil {
permissions := NewKBSharePermissions(ctx, shares, request.Caller.TenantID, request.Caller.Role)
permission, shared, err := permissions.Permission(kb.ID)
if err == nil && shared && permission.HasPermission(required) {
return grant(permission)
}
}
if required != types.OrgRoleViewer || agents == nil {
return nil, ErrForbidden
}
if request.AgentID != "" {
source, err := types.ParseAgentSourceTenantID(request.AgentSourceTenantID)
if err != nil {
return nil, fmt.Errorf("%w: %s", ErrInvalidAgentSource, err)
}
agent, err := agents.GetSharedAgentForTenant(
ctx,
request.Caller.TenantID,
request.Caller.Role,
request.AgentID,
source,
)
if err == nil && types.SharedAgentIncludesKB(agent, kb) {
return grant(types.OrgRoleViewer)
}
} else {
allowed,
err := agents.TenantCanAccessKBViaSomeSharedAgent(ctx,
request.Caller.TenantID,
request.Caller.Role,
kb)
if err == nil && allowed {
return grant(types.OrgRoleViewer)
}
}
return nil, ErrForbidden
}
@@ -0,0 +1,282 @@
package access
import (
"context"
"errors"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/require"
)
type shareLookup struct {
permission types.OrgMemberRole
err error
caller uint64
role types.TenantRole
}
func (s *shareLookup) CheckTenantKBPermission(
_ context.Context,
_ string,
caller uint64,
role types.TenantRole,
) (types.OrgMemberRole, bool, error) {
s.caller, s.role = caller, role
return s.permission, s.permission != "", s.err
}
type agentLookup struct {
agent *types.CustomAgent
any bool
err error
anyCalls int
source uint64
}
func (s *agentLookup) GetSharedAgentForTenant(
_ context.Context,
_ uint64,
_ types.TenantRole,
_ string,
source ...uint64,
) (*types.CustomAgent, error) {
s.source = source[0]
return s.agent, s.err
}
func (s *agentLookup) TenantCanAccessKBViaSomeSharedAgent(
context.Context,
uint64,
types.TenantRole,
*types.KnowledgeBase,
) (bool, error) {
s.anyCalls++
return s.any, s.err
}
func TestResolveKBPermissionMatrix(t *testing.T) {
for _, tt := range []struct {
name string
own bool
permission types.OrgMemberRole
required types.OrgMemberRole
shareError bool
agentID, source, mode string
selected []string
wrongTenant, missingAgent, agentError, anyAgent bool
want types.OrgMemberRole
wantErr error
}{
{name: "own KB", own: true, required: types.OrgRoleEditor, want: types.OrgRoleAdmin},
{
name: "organization reader",
permission: types.OrgRoleViewer,
required: types.OrgRoleViewer,
want: types.OrgRoleViewer,
},
{
name: "organization editor",
permission: types.OrgRoleEditor,
required: types.OrgRoleEditor,
want: types.OrgRoleEditor,
},
{
name: "reader cannot write",
permission: types.OrgRoleViewer,
required: types.OrgRoleEditor,
wantErr: ErrForbidden,
},
{
name: "share lookup fails closed",
permission: types.OrgRoleEditor,
shareError: true,
required: types.OrgRoleViewer,
wantErr: ErrForbidden,
},
{
name: "independent agent grant after share error",
shareError: true,
anyAgent: true,
required: types.OrgRoleViewer,
want: types.OrgRoleViewer,
},
{name: "any shared agent read", anyAgent: true, required: types.OrgRoleViewer, want: types.OrgRoleViewer},
{name: "any agent cannot write", anyAgent: true, required: types.OrgRoleEditor, wantErr: ErrForbidden},
{
name: "agent lookup error",
anyAgent: true,
agentError: true,
required: types.OrgRoleViewer,
wantErr: ErrForbidden,
},
{
name: "explicit all",
agentID: "agent",
source: "2",
mode: "all",
required: types.OrgRoleViewer,
want: types.OrgRoleViewer,
},
{
name: "explicit selected",
agentID: "agent",
mode: "selected",
selected: []string{"kb"},
required: types.OrgRoleViewer,
want: types.OrgRoleViewer,
},
{
name: "selection miss does not fall back",
agentID: "agent",
mode: "selected",
selected: []string{"other"},
anyAgent: true,
required: types.OrgRoleViewer,
wantErr: ErrForbidden,
},
{
name: "none does not fall back",
agentID: "agent",
mode: "none",
anyAgent: true,
required: types.OrgRoleViewer,
wantErr: ErrForbidden,
},
{
name: "unknown mode denied",
agentID: "agent",
mode: "invalid",
required: types.OrgRoleViewer,
wantErr: ErrForbidden,
},
{
name: "tenant mismatch denied",
agentID: "agent",
mode: "all",
wrongTenant: true,
required: types.OrgRoleViewer,
wantErr: ErrForbidden,
},
{
name: "missing explicit agent does not fall back",
agentID: "agent",
missingAgent: true,
anyAgent: true,
required: types.OrgRoleViewer,
wantErr: ErrForbidden,
},
{
name: "invalid source rejected",
agentID: "agent",
source: "bad",
mode: "all",
required: types.OrgRoleViewer,
wantErr: ErrInvalidAgentSource,
},
{
name: "own grant precedes agent parsing",
own: true,
agentID: "agent",
source: "bad",
required: types.OrgRoleViewer,
want: types.OrgRoleAdmin,
},
{
name: "share grant precedes agent parsing",
permission: types.OrgRoleViewer,
agentID: "agent",
source: "bad",
required: types.OrgRoleViewer,
want: types.OrgRoleViewer,
},
} {
t.Run(tt.name, func(t *testing.T) {
kb := &types.KnowledgeBase{ID: "kb", TenantID: 2}
if tt.own {
kb.TenantID = 1
}
shares := &shareLookup{permission: tt.permission}
if tt.shareError {
shares.err = errors.New("unavailable")
}
agents := &agentLookup{
any: tt.anyAgent,
agent: &types.CustomAgent{
TenantID: 2,
Config: types.CustomAgentConfig{KBSelectionMode: tt.mode, KnowledgeBases: tt.selected},
},
}
if tt.wrongTenant {
agents.agent.TenantID = 3
}
if tt.missingAgent {
agents.agent = nil
}
if tt.agentError {
agents.err = errors.New("unavailable")
}
request := KBRequest{
Caller: types.Caller{TenantID: 1, Role: types.TenantRoleViewer},
AgentID: tt.agentID,
AgentSourceTenantID: tt.source,
}
grant, err := ResolveKB(context.Background(), request, kb, tt.required, shares, agents)
if tt.wantErr != nil {
require.ErrorIs(t, err, tt.wantErr)
require.Nil(t, grant)
} else {
require.NoError(t, err)
require.Equal(t, tt.want, grant.Permission)
require.Equal(t, uint64(1), grant.Caller.TenantID)
require.Equal(t, kb.TenantID, grant.EffectiveTenantID)
}
if !tt.own {
require.Equal(t, uint64(1), shares.caller)
require.Equal(t, types.TenantRoleViewer, shares.role)
}
if tt.agentID != "" {
require.Zero(t, agents.anyCalls)
}
if tt.source == "2" {
require.Equal(t, uint64(2), agents.source)
}
})
}
}
func TestResolveKBMissingIdentityResourceAndAPIKeyScope(t *testing.T) {
kb := &types.KnowledgeBase{ID: "kb", TenantID: 1}
_, err := ResolveKB(context.Background(), KBRequest{}, kb, types.OrgRoleViewer, nil, nil)
require.ErrorIs(t, err, ErrUnauthorized)
_, err = ResolveKB(
context.Background(),
KBRequest{Caller: types.Caller{TenantID: 1}},
nil,
types.OrgRoleViewer,
nil,
nil,
)
require.ErrorIs(t, err, ErrNotFound)
ctx := types.WithTenantAPIKeyScope(
context.Background(),
types.TenantAPIKeyScope{KnowledgeBaseIDs: types.StringArray{"other"}},
)
_, err = ResolveKB(ctx, KBRequest{Caller: types.Caller{TenantID: 1}}, kb, types.OrgRoleViewer, nil, nil)
require.Error(t, err, "API key scope must apply even to owned KBs")
}
@@ -0,0 +1,249 @@
package access
import (
"context"
"strings"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// MessageFileLookup is the narrow message-service surface needed by the
// message-scoped file proxy. Keeping it small makes the authorization boundary
// independently testable.
type MessageFileLookup interface {
GetMessage(ctx context.Context, sessionID, messageID string) (*types.Message, error)
}
// SharedAgentFileLookup verifies that a source workspace's agent is still
// shared to the caller. Revoking the share therefore also revokes historical
// message-file access.
type SharedAgentFileLookup interface {
GetSharedAgentForTenant(
ctx context.Context,
tenantID uint64,
callerTenantRole types.TenantRole,
agentID string,
sourceTenantID ...uint64,
) (*types.CustomAgent, error)
}
// KBSharePermissionGuard is the org-share surface the message-scoped proxy
// needs for its shared-KB fallback.
type KBSharePermissionGuard = KBShareLookup
// KBTenantLookup resolves knowledge bases without a tenant filter, so a
// message's persisted retrieval evidence can be mapped back to the knowledge
// bases the chunks were retrieved from.
type KBTenantLookup interface {
GetKnowledgeBasesByIDsOnly(ctx context.Context, ids []string) ([]*types.KnowledgeBase, error)
}
// KnowledgeOwnerLookup resolves a knowledge entry to its knowledge base for
// message references that predate the denormalized knowledge_base_id field.
type KnowledgeOwnerLookup interface {
GetKnowledgeByIDOnly(ctx context.Context, id string) (*types.Knowledge, error)
}
// MessageKBShareAuthorizer bundles the read-only lookups behind the
// message proxy's org-shared-KB fallback. A nil ShareGuard or KBs lookup
// disables the fallback. A live Bindings lookup is also required and can
// be supplied by the resource catalog. A nil Knowledges lookup only disables the
// pre-denormalization KnowledgeID path.
type MessageKBShareAuthorizer struct {
ShareGuard KBSharePermissionGuard
KBs KBTenantLookup
Knowledges KnowledgeOwnerLookup
Bindings interfaces.KBResourceLookup
}
// resourceAccessibleViaSharedKB reports whether the message's persisted
// retrieval evidence proves the resource came from an org-shared KB the
// caller may read. This is the fallback for replies whose agent belongs to
// the caller's own workspace while the retrieved resources belong to the
// workspace that shared the knowledge base (#3022).
//
// Evidence required from one retrieval record: a canonical resource://
// handle (not a prefix of a longer token) appears in the chunk text or
// image_info, its knowledge base belongs to the resource's tenant, and
// that KB is org-shared to the caller with at least viewer permission, and
// an independent live resource binding confirms the file still belongs to it.
// Smart-reasoning turns persist that evidence on AgentSteps when
// KnowledgeReferences was never filled. Any lookup failure fails closed.
func (a MessageKBShareAuthorizer) resourceAccessibleViaSharedKB(
ctx context.Context,
message *types.Message,
resource *types.StoredResource,
callerTenantID uint64,
callerTenantRole types.TenantRole,
) bool {
if a.ShareGuard == nil || a.KBs == nil || a.Bindings == nil || message == nil || resource == nil {
return false
}
handle, ok := types.ParseResourcePath(types.BuildResourcePath(resource.Handle))
if !ok {
return false
}
kbIDs := a.collectSharedKBEvidenceIDs(ctx, message, handle)
if len(kbIDs) == 0 {
return false
}
kbs, err := a.KBs.GetKnowledgeBasesByIDsOnly(ctx, kbIDs)
if err != nil {
return false
}
permissions := NewKBSharePermissions(ctx, a.ShareGuard, callerTenantID, callerTenantRole)
for _, kb := range kbs {
if kb == nil || kb.TenantID != resource.TenantID {
continue
}
shared, err := permissions.Check(kb.ID, types.OrgRoleViewer)
if err == nil && shared {
bound, bindingErr := a.Bindings.IsReferencedByKnowledgeBase(
ctx, resource.TenantID, kb.ID, types.BuildResourcePath(handle))
if bindingErr == nil && bound {
return true
}
}
}
return false
}
func (a MessageKBShareAuthorizer) collectSharedKBEvidenceIDs(
ctx context.Context,
message *types.Message,
handle string,
) []string {
seenKB := make(map[string]bool)
seenKnowledge := make(map[string]bool)
var kbIDs, knowledgeIDs []string
addKB := func(id string) {
if id == "" || seenKB[id] {
return
}
seenKB[id] = true
kbIDs = append(kbIDs, id)
}
addKnowledge := func(id string) {
if id == "" || seenKnowledge[id] {
return
}
seenKnowledge[id] = true
knowledgeIDs = append(knowledgeIDs, id)
}
for _, ref := range message.KnowledgeReferences {
if !searchResultHasResourceHandle(ref, handle) {
continue
}
if ref.KnowledgeBaseID != "" {
addKB(ref.KnowledgeBaseID)
continue
}
addKnowledge(ref.KnowledgeID)
}
collectKBEvidenceFromValue(message.AgentSteps, handle, "", "", addKB, addKnowledge)
if a.Knowledges != nil {
for _, knowledgeID := range knowledgeIDs {
knowledge, err := a.Knowledges.GetKnowledgeByIDOnly(ctx, knowledgeID)
if err != nil || knowledge == nil {
continue
}
addKB(knowledge.KnowledgeBaseID)
}
}
return kbIDs
}
func searchResultHasResourceHandle(ref *types.SearchResult, handle string) bool {
if ref == nil {
return false
}
return textHasResourceHandle(ref.Content, handle) ||
textHasResourceHandle(ref.MatchedContent, handle) ||
textHasResourceHandle(ref.ImageInfo, handle)
}
func textHasResourceHandle(text, handle string) bool {
if text == "" || handle == "" {
return false
}
want := types.BuildResourcePath(handle)
for _, ref := range types.ScanResourceReferences(text) {
if ref == want {
return true
}
}
return false
}
func collectKBEvidenceFromValue(
v interface{},
handle, kbID, knowledgeID string,
addKB, addKnowledge func(string),
) {
switch val := v.(type) {
case string:
if !textHasResourceHandle(val, handle) {
return
}
if kbID != "" {
addKB(kbID)
return
}
addKnowledge(knowledgeID)
case types.AgentSteps:
for _, step := range val {
collectKBEvidenceFromValue(step, handle, kbID, knowledgeID, addKB, addKnowledge)
}
case types.AgentStep:
collectKBEvidenceFromValue(val.ToolCalls, handle, kbID, knowledgeID, addKB, addKnowledge)
case []types.ToolCall:
for _, call := range val {
collectKBEvidenceFromValue(call, handle, kbID, knowledgeID, addKB, addKnowledge)
}
case types.ToolCall:
if val.Result != nil {
collectKBEvidenceFromValue(val.Result.Output, handle, kbID, knowledgeID, addKB, addKnowledge)
collectKBEvidenceFromValue(val.Result.Data, handle, kbID, knowledgeID, addKB, addKnowledge)
}
case map[string]interface{}:
nextKB := firstNonEmptyString(
stringFromAnyMap(val, "knowledge_base_id"),
stringFromAnyMap(val, "knowledge_base"),
kbID,
)
nextKnowledge := firstNonEmptyString(stringFromAnyMap(val, "knowledge_id"), knowledgeID)
for _, nested := range val {
collectKBEvidenceFromValue(nested, handle, nextKB, nextKnowledge, addKB, addKnowledge)
}
case []interface{}:
for _, item := range val {
collectKBEvidenceFromValue(item, handle, kbID, knowledgeID, addKB, addKnowledge)
}
case []map[string]interface{}:
for _, item := range val {
collectKBEvidenceFromValue(item, handle, kbID, knowledgeID, addKB, addKnowledge)
}
}
}
func stringFromAnyMap(m map[string]interface{}, key string) string {
if m == nil {
return ""
}
s, _ := m[key].(string)
return strings.TrimSpace(s)
}
func firstNonEmptyString(values ...string) string {
for _, value := range values {
if strings.TrimSpace(value) != "" {
return strings.TrimSpace(value)
}
}
return ""
}
+74
View File
@@ -0,0 +1,74 @@
package access
import (
"errors"
"academy/internal/types"
)
var (
// ErrResourceNotFound means the ownership lookup found no resource visible
// in the caller's tenant. HTTP adapters decide how to produce the 404.
ErrResourceNotFound = errors.New("rbac: resource not found")
// ErrOwnershipForbidden indicates neither ownership nor the required role.
ErrOwnershipForbidden = errors.New("rbac: ownership or role insufficient")
)
// OwnershipRequest carries server-resolved identity and rollout policy. The
// cross-tenant bypass must already account for the cluster configuration.
// This gate does not replace API-key capabilities or resource-scope checks.
type OwnershipRequest struct {
UserID string
Role types.TenantRole
APIKey bool
CrossTenantSuperuser bool
Enforce bool
}
// OwnershipDecision contains the details adapters need for logs and audits.
// The error returned with it determines whether access was allowed.
type OwnershipDecision struct {
CreatorID string
EnforcementSkipped bool
LookupFailed bool
}
// CreatorRoleFloor is the lowest role at which creating a resource still lets
// the caller manage it. Below it a member mutates nothing, including what they
// created before being demoted.
const CreatorRoleFloor = types.TenantRoleContributor
// CheckOwnershipOrRole performs no resource lookup when API-key authorization,
// role, superuser status, or the RBAC rollout policy already settles the gate.
// The lookup must enforce tenant visibility before returning a creator ID.
func CheckOwnershipOrRole(
request OwnershipRequest,
required types.TenantRole,
lookup func() (string, error),
) (OwnershipDecision, error) {
var decision OwnershipDecision
if request.APIKey || request.Role.HasPermission(required) || request.CrossTenantSuperuser {
return decision, nil
}
if !request.Enforce {
decision.EnforcementSkipped = true
return decision, nil
}
if lookup == nil {
decision.LookupFailed = true
return decision, errors.New("rbac: creator lookup unavailable")
}
creator, err := lookup()
decision.CreatorID = creator
if errors.Is(err, ErrResourceNotFound) {
return decision, ErrResourceNotFound
}
if err != nil {
decision.LookupFailed = true
return decision, err
}
if creator != "" && creator == request.UserID && request.Role.HasPermission(CreatorRoleFloor) {
return decision, nil
}
return decision, ErrOwnershipForbidden
}
@@ -0,0 +1,127 @@
package access
import (
"errors"
"fmt"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/require"
)
func TestCheckOwnershipOrRoleSkipsLookupWhenGateAlreadyResolved(t *testing.T) {
for _, tt := range []struct {
name string
request OwnershipRequest
skipped bool
}{
{name: "API key", request: OwnershipRequest{APIKey: true, Role: types.TenantRoleViewer, Enforce: true}},
{name: "admin", request: OwnershipRequest{Role: types.TenantRoleAdmin, Enforce: true}},
{name: "owner role", request: OwnershipRequest{Role: types.TenantRoleOwner, Enforce: true}},
{
name: "cross tenant superuser",
request: OwnershipRequest{
Role: types.TenantRoleViewer,
CrossTenantSuperuser: true,
Enforce: true,
},
},
{name: "enforcement disabled", request: OwnershipRequest{Role: types.TenantRoleViewer}, skipped: true},
{name: "role before rollout", request: OwnershipRequest{Role: types.TenantRoleAdmin}},
} {
t.Run(tt.name, func(t *testing.T) {
decision, err := CheckOwnershipOrRole(tt.request, types.TenantRoleAdmin, func() (string, error) {
t.Fatal("ownership lookup must not run on a fast path")
return "", errors.New("unavailable")
})
require.NoError(t, err)
require.Equal(t, tt.skipped, decision.EnforcementSkipped)
require.False(t, decision.LookupFailed)
})
}
}
func TestCheckOwnershipOrRoleResolvesCreator(t *testing.T) {
failure := errors.New("database unavailable")
for _, tt := range []struct {
name, user, creator string
lookupErr, wantErr error
lookupFailed bool
}{
{name: "creator", user: "user", creator: "user"},
{name: "other creator", user: "user", creator: "other", wantErr: ErrOwnershipForbidden},
{name: "tenant owned", user: "user", wantErr: ErrOwnershipForbidden},
{name: "missing identity cannot match empty creator", wantErr: ErrOwnershipForbidden},
{name: "missing resource", user: "user", lookupErr: ErrResourceNotFound, wantErr: ErrResourceNotFound},
{
name: "wrapped missing resource",
user: "user",
lookupErr: fmt.Errorf("load: %w",
ErrResourceNotFound),
wantErr: ErrResourceNotFound,
},
{
name: "lookup failure wins over creator match",
user: "user",
creator: "user",
lookupErr: failure,
wantErr: failure,
lookupFailed: true,
},
{
name: "lookup denial remains a lookup failure",
lookupErr: ErrOwnershipForbidden,
wantErr: ErrOwnershipForbidden,
lookupFailed: true,
},
} {
t.Run(tt.name, func(t *testing.T) {
calls := 0
decision, err := CheckOwnershipOrRole(
OwnershipRequest{UserID: tt.user, Role: types.TenantRoleContributor, Enforce: true},
types.TenantRoleAdmin,
func() (string, error) {
calls++
return tt.creator, tt.lookupErr
},
)
require.Equal(t, 1, calls)
require.ErrorIs(t, err, tt.wantErr)
require.Equal(t, tt.creator, decision.CreatorID)
require.Equal(t, tt.lookupFailed, decision.LookupFailed)
})
}
}
func TestCheckOwnershipOrRoleMissingLookupFailsClosed(t *testing.T) {
decision, err := CheckOwnershipOrRole(
OwnershipRequest{Role: types.TenantRoleContributor, Enforce: true}, types.TenantRoleAdmin, nil)
require.Error(t, err)
require.True(t, decision.LookupFailed)
}
func TestCheckOwnershipOrRoleDeniesCreatorsBelowTheFloor(t *testing.T) {
for _, role := range []types.TenantRole{types.TenantRoleViewer, ""} {
t.Run(string(role)+"-creator", func(t *testing.T) {
decision, err := CheckOwnershipOrRole(
OwnershipRequest{UserID: "user", Role: role, Enforce: true},
types.TenantRoleAdmin,
func() (string, error) { return "user", nil },
)
require.ErrorIs(t, err, ErrOwnershipForbidden)
require.False(t, decision.LookupFailed)
})
}
}
func TestCheckOwnershipOrRoleKeepsNotFoundBelowTheFloor(t *testing.T) {
_, err := CheckOwnershipOrRole(
OwnershipRequest{UserID: "user", Role: types.TenantRoleViewer, Enforce: true},
types.TenantRoleAdmin,
func() (string, error) { return "", ErrResourceNotFound },
)
require.ErrorIs(t, err, ErrResourceNotFound)
}
+19
View File
@@ -0,0 +1,19 @@
package access
import (
"context"
"academy/internal/config"
"academy/internal/types"
)
// IsCrossTenantSuperuser reports whether the caller's user attribute and the
// cluster-wide flag both allow bypassing workspace role gates. API-key and
// resource-scope authorization remain separate checks.
func IsCrossTenantSuperuser(ctx context.Context, cfg *config.Config) bool {
if cfg == nil || cfg.Tenant == nil || !cfg.Tenant.EnableCrossTenantAccess {
return false
}
u, ok := ctx.Value(types.UserContextKey).(*types.User)
return ok && u != nil && u.CanAccessAllTenants
}