Files
xinmi/internal/logger/accesspolicy_context_test.go
T

53 lines
2.0 KiB
Go
Raw Normal View History

package logger
import (
"context"
"testing"
"github.com/Tencent/WeKnora/internal/accesspolicy"
)
func TestClonedContextPreservesResourceAuthorization(t *testing.T) {
for name, clone := range map[string]func(context.Context) context.Context{
"with_trace": CloneContext,
"without_trace": CloneContextWithoutTrace,
} {
t.Run(name, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
ctx = accesspolicy.WithSnapshot(ctx, &accesspolicy.Snapshot{
Restricted: true,
Permissions: map[string]bool{"knowledge.read": true},
Publications: map[string]bool{"knowledge:published": true},
Grants: map[string]bool{"knowledge:granted": true},
Hidden: map[string]bool{"knowledge:hidden": true},
NoExport: map[string]bool{"knowledge:published": true},
})
cancel()
detached := clone(ctx)
if detached.Err() != nil {
t.Fatal("cloned work must remain detached from request cancellation")
}
policy := accesspolicy.FromContext(detached)
if policy == nil || !policy.Restricted {
t.Fatal("authenticated resource restrictions must survive context cloning")
}
if !accesspolicy.Allowed(detached, "knowledge.read") || accesspolicy.Allowed(detached, "knowledge.write") {
t.Fatal("cloning changed module permissions")
}
if accesspolicy.Readable(detached, "knowledge", "private", false, policy == nil) {
t.Fatal("cloning must not expose another user's private knowledge")
}
if !accesspolicy.Readable(detached, "knowledge", "granted", false, false) ||
!accesspolicy.Readable(detached, "knowledge", "published", false, false) {
t.Fatal("cloning must retain explicit grants and publications")
}
if accesspolicy.Readable(detached, "knowledge", "hidden", true, true) || !policy.NoExport["knowledge:published"] {
t.Fatal("cloning must retain hidden-resource and export restrictions")
}
if accesspolicy.FromContext(clone(context.Background())) != nil {
t.Fatal("background workers without a snapshot retain native behavior")
}
})
}
}