Files
kandev/apps/backend/internal/task/service/service_access.go
T
João Salavisa 103878047c fix(auth): scope in-session agent MCP calls to the task owner (#1937)
* fix(auth): scope in-session agent MCP calls to the task owner

The MCP tools an agent gets automatically inside its own session are
relayed over the agent's WebSocket stream, which carries no credential.
The backend dispatched them on the raw stream context, so the task
service saw no identity — its signal for an internal caller (event bus,
pollers, office schedulers) — and served the request unscoped. An agent
that supplied another user's task_id or workflow_id was given their
data, violating the rule that knowing an ID must not grant access.

Resolve the owning user from the stream's own AgentExecution (task ->
workspace -> owner) and attach that real stored identity before
dispatch, so the existing authorize* checks apply exactly as they do on
the PAT-authenticated /mcp endpoint. The owning task never comes from
the agent-supplied payload: honoring a payload session_id would let an
agent name another user's session and inherit their identity.

Tool handlers are unchanged. Auth disabled stays unscoped, unclaimed
pre-auth workspaces stay visible to everyone, and a lookup failure
denies the dispatch rather than falling back to full access.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(auth): never leave in-session MCP dispatch unscoped

Review follow-up. Three paths still returned an identity-free context
under enforced auth, and "no identity" is exactly what the task service
reads as an internal caller and serves unscoped:

- Unowned workspace. CreateWorkspace only stamps an owner for scoped
  callers, so internal callers keep producing owner_id='' rows after
  setup. Those streams got full cross-user access. Scope them to a
  sentinel user ID no account can hold: the service's "empty owner_id or
  my own ID" rule then limits them to the unowned rows that are public
  by the compatibility contract, and nothing else.
- Task with no workspace. Same treatment, same reasoning.
- Missing task or workspace row. A lookup that reports not-found as
  (nil, nil) fell through to unscoped; treat it as a resolution failure.

Also deny, rather than fabricate a member identity, when the owner's
account is gone or disabled. Disabling a user revokes their sessions and
PATs, so a still-running agent session was the one remaining way into
their workspace.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-25 09:56:47 +01:00

180 lines
5.8 KiB
Go

package service
import (
"context"
"github.com/kandev/kandev/internal/auth/authn"
"github.com/kandev/kandev/internal/task/models"
"github.com/kandev/kandev/internal/task/repository/repoerrors"
)
// Per-user workspace scoping (opt-in authentication).
//
// Every user-facing service entry point calls one of the authorize* helpers.
// Scoping keys off the request-context identity placed there by the auth
// middleware:
// - no identity in ctx → internal caller (event bus, pollers, office
// schedulers) → unscoped, exactly as before the auth feature. In-session
// agent MCP calls used to land here too; they now arrive with the task
// owner's identity attached by internal/mcp/scope.
// - synthetic identity → auth disabled → unscoped (today's behavior)
// - real identity → workspaces are visible only to their owner;
// rows with an empty owner_id (created pre-auth) stay visible to everyone
// until the setup wizard claims them for the admin
//
// Denials use the *NotFound sentinels — a foreign workspace is
// indistinguishable from a nonexistent one (no existence leak).
// callerScope returns the scoping user ID; ok=false means unscoped.
func callerScope(ctx context.Context) (string, bool) {
identity, ok := authn.IdentityFromContext(ctx)
if !ok || identity.Synthetic {
return "", false
}
return identity.UserID, true
}
func workspaceVisibleTo(workspace *models.Workspace, userID string) bool {
return workspace == nil || workspace.OwnerID == "" || workspace.OwnerID == userID
}
// authorizeWorkspaceID checks visibility of a workspace by ID.
func (s *Service) authorizeWorkspaceID(ctx context.Context, workspaceID string) error {
userID, scoped := callerScope(ctx)
if !scoped || workspaceID == "" {
return nil
}
workspace, err := s.workspaces.GetWorkspace(ctx, workspaceID)
if err != nil {
return err
}
if !workspaceVisibleTo(workspace, userID) {
return repoerrors.ErrWorkspaceNotFound
}
return nil
}
// authorizeTaskID checks visibility of a task via its workspace.
func (s *Service) authorizeTaskID(ctx context.Context, taskID string) error {
userID, scoped := callerScope(ctx)
if !scoped {
return nil
}
task, err := s.tasks.GetTask(ctx, taskID)
if err != nil {
return err
}
if task.WorkspaceID == "" {
return nil
}
workspace, err := s.workspaces.GetWorkspace(ctx, task.WorkspaceID)
if err != nil {
// A dangling workspace reference should not hide the task from the
// single user who can already see everything else about it.
return nil //nolint:nilerr // visibility fallback, not an operation failure
}
if !workspaceVisibleTo(workspace, userID) {
return repoerrors.ErrTaskNotFound
}
return nil
}
// authorizeWorkflowID checks visibility of a workflow via its workspace.
func (s *Service) authorizeWorkflowID(ctx context.Context, workflowID string) error {
userID, scoped := callerScope(ctx)
if !scoped {
return nil
}
workflow, err := s.workflows.GetWorkflow(ctx, workflowID)
if err != nil {
return err
}
if workflow.WorkspaceID == "" {
return nil
}
workspace, err := s.workspaces.GetWorkspace(ctx, workflow.WorkspaceID)
if err != nil {
return nil //nolint:nilerr // visibility fallback, not an operation failure
}
if !workspaceVisibleTo(workspace, userID) {
return repoerrors.ErrWorkspaceNotFound
}
return nil
}
// AuthorizeTaskAccess is the public form of authorizeTaskID, consumed by the
// WS gateway's subscription checks.
func (s *Service) AuthorizeTaskAccess(ctx context.Context, taskID string) error {
return s.authorizeTaskID(ctx, taskID)
}
// AuthorizeWorkspaceAccess is the public form of authorizeWorkspaceID,
// consumed by the office route-scoping middleware.
func (s *Service) AuthorizeWorkspaceAccess(ctx context.Context, workspaceID string) error {
return s.authorizeWorkspaceID(ctx, workspaceID)
}
// AuthorizeSessionAccess checks visibility of a task session via its task's
// workspace. Wired into the lifecycle manager so session-scoped surfaces
// (files, processes, ports, vscode, terminal, LSP) are covered.
func (s *Service) AuthorizeSessionAccess(ctx context.Context, sessionID string) error {
_, scoped := callerScope(ctx)
if !scoped {
return nil
}
session, err := s.sessions.GetTaskSession(ctx, sessionID)
if err != nil {
return err
}
return s.authorizeTaskID(ctx, session.TaskID)
}
// AuthorizeEnvironmentAccess checks visibility of a task environment via its
// task's workspace. Used by the terminal environment-shell route, which
// resolves executions by environment ID rather than session ID.
func (s *Service) AuthorizeEnvironmentAccess(ctx context.Context, taskEnvironmentID string) error {
_, scoped := callerScope(ctx)
if !scoped {
return nil
}
env, err := s.taskEnvironments.GetTaskEnvironment(ctx, taskEnvironmentID)
if err != nil {
return err
}
return s.authorizeTaskID(ctx, env.TaskID)
}
// authorizeRepositoryID checks visibility of a repository via its workspace.
// Denials use ErrRepositoryNotFound (no existence leak).
func (s *Service) authorizeRepositoryID(ctx context.Context, repositoryID string) error {
if _, scoped := callerScope(ctx); !scoped {
return nil
}
repo, err := s.repoEntities.GetRepository(ctx, repositoryID)
if err != nil {
return err
}
if repo == nil {
return nil
}
if err := s.authorizeWorkspaceID(ctx, repo.WorkspaceID); err != nil {
return repoerrors.ErrRepositoryNotFound
}
return nil
}
// filterWorkspacesForCaller narrows a workspace list to the caller's view.
func filterWorkspacesForCaller(ctx context.Context, workspaces []*models.Workspace) []*models.Workspace {
userID, scoped := callerScope(ctx)
if !scoped {
return workspaces
}
visible := make([]*models.Workspace, 0, len(workspaces))
for _, workspace := range workspaces {
if workspaceVisibleTo(workspace, userID) {
visible = append(visible, workspace)
}
}
return visible
}