feat(auth): add workspace scope middleware and context
Introduces current-workspace context helpers plus a WorkspaceScope middleware that validates X-Workspace-ID against workspace memberships, defaulting to the actor's primary workspace. Prepares monitoring paths to resolve quota/access-state per request workspace instead of per tenant. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -10,6 +10,7 @@ type Actor struct {
|
||||
}
|
||||
|
||||
type actorKey struct{}
|
||||
type currentWorkspaceIDKey struct{}
|
||||
|
||||
func WithActor(ctx context.Context, actor Actor) context.Context {
|
||||
return context.WithValue(ctx, actorKey{}, actor)
|
||||
@@ -27,3 +28,26 @@ func MustActor(ctx context.Context) Actor {
|
||||
}
|
||||
return actor
|
||||
}
|
||||
|
||||
func WithCurrentWorkspaceID(ctx context.Context, workspaceID int64) context.Context {
|
||||
return context.WithValue(ctx, currentWorkspaceIDKey{}, workspaceID)
|
||||
}
|
||||
|
||||
func CurrentWorkspaceIDFromCtx(ctx context.Context) (int64, bool) {
|
||||
workspaceID, ok := ctx.Value(currentWorkspaceIDKey{}).(int64)
|
||||
if !ok || workspaceID <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
return workspaceID, true
|
||||
}
|
||||
|
||||
func CurrentWorkspaceID(ctx context.Context) int64 {
|
||||
if workspaceID, ok := CurrentWorkspaceIDFromCtx(ctx); ok {
|
||||
return workspaceID
|
||||
}
|
||||
actor, ok := ActorFromCtx(ctx)
|
||||
if !ok {
|
||||
return 0
|
||||
}
|
||||
return actor.PrimaryWorkspaceID
|
||||
}
|
||||
|
||||
@@ -47,3 +47,31 @@ func TestActorCarriesPrimaryWorkspaceID(t *testing.T) {
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, int64(30), actor.PrimaryWorkspaceID)
|
||||
}
|
||||
|
||||
func TestCurrentWorkspaceIDFallsBackToPrimaryWorkspace(t *testing.T) {
|
||||
ctx := WithActor(context.Background(), Actor{
|
||||
UserID: 10,
|
||||
TenantID: 20,
|
||||
PrimaryWorkspaceID: 30,
|
||||
Role: "member",
|
||||
})
|
||||
|
||||
assert.Equal(t, int64(30), CurrentWorkspaceID(ctx))
|
||||
_, ok := CurrentWorkspaceIDFromCtx(ctx)
|
||||
assert.False(t, ok)
|
||||
}
|
||||
|
||||
func TestCurrentWorkspaceIDUsesScopedWorkspace(t *testing.T) {
|
||||
ctx := WithActor(context.Background(), Actor{
|
||||
UserID: 10,
|
||||
TenantID: 20,
|
||||
PrimaryWorkspaceID: 30,
|
||||
Role: "member",
|
||||
})
|
||||
ctx = WithCurrentWorkspaceID(ctx, 40)
|
||||
|
||||
got, ok := CurrentWorkspaceIDFromCtx(ctx)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, int64(40), got)
|
||||
assert.Equal(t, int64(40), CurrentWorkspaceID(ctx))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user