Files
kandev/apps/backend/internal/linear/scope_watch_test.go
T
João Salavisa 116f7557dd fix(auth): scope integration config/watch routes to workspace owner (#1960)
* fix(auth): scope integration config/watch routes to workspace owner

The third-party integration route group is guarded by its own
query-only middleware (integrationWorkspaceScopeMiddleware), which
authorizes only the workspace_id query param and falls through when it
is absent. Two shapes bypassed it entirely under enforced auth:

- POST /{jira,linear,slack}/config/copy takes the copy TARGET from the
  request body (targetWorkspaceId), which no layer checked. A caller
  could copy their own connection settings + credential into another
  user's workspace by naming its ID, after which that workspace's
  identity-less poller would run against attacker-controlled config
  (Jira/Linear issue watchers auto-creating tasks from attacker issues;
  Slack bot token/webhook). CopyConfigToWorkspace now authorizes BOTH
  source and target up front, before the pre-write UpdateAuthHealth
  side effect. Mirrors github/copy.go.
- GET /{jira,linear}/watches/issue with workspace_id omitted returned
  ListAllIssueWatches across every workspace (JQL/filters, repo, agent
  and executor profile IDs, spawn prompt). It now filters to the
  caller's workspaces; an identity-less internal caller still sees all,
  preserving poller use.
- The config Get/Set/Delete entry points resolved an unowned global
  "default" workspace when workspace_id was omitted; they now
  resolve+authorize via resolveWorkspaceID.

Each service gains SetWorkspaceAuthorizer(taskSvc.AuthorizeWorkspaceAccess),
wired in backendapp; nil (unit tests, auth disabled) stays unscoped.
Denials surface repoerrors.ErrWorkspaceNotFound, mapped to 404 by the
handlers (no existence leak). Recorded the query-only-middleware rule in
integrations/AGENTS.md, including that Sentry and GitLab's
ListAllIssueWatches still need the same filter.

Regression tests added per package and mutation-verified: dropping only
the copy up-front guard fails on the victim health-flip witness;
dropping both guards fails on the config/secret witness.

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

* fix(auth): scope integration watch-write and data-plane paths too

Review of the prior commit (Codex + Claude, converging) found the same
body/query workspace-bypass class in surfaces the first pass missed:

- CreateIssueWatch / UpdateIssueWatch (Jira, Linear) never authorized the
  workspace. CreateIssueWatch takes WorkspaceID from the request body, so
  a caller could plant a persistent watch in another user's workspace that
  repeatedly spawns tasks with that user's credentials and an
  attacker-supplied filter/prompt. Now authorize req.WorkspaceID (create)
  and the loaded row's workspace (update). The by-ID mutation/trigger/reset
  handlers were already guarded by assertWatchInWorkspace + the
  query-authorizing middleware; the service-layer guard adds defense in
  depth and covers non-HTTP callers.
- TestConnectionForWorkspace (Jira, Linear, Slack) resolved the default
  workspace with no auth, so an omitted workspace_id + attacker-supplied
  siteUrl could exfiltrate that workspace's stored token. Now authorizes
  after normalize and returns a hard error (404), not a swallowed
  {OK:false}.
- Data-plane reads funnel through clientFor, which now resolves+authorizes
  the workspace — scoping search/projects/statuses in one chokepoint.
- filterIssueWatchesByAccess treated ANY authorizer error as a denial,
  silently dropping watches on a transient failure and returning a
  truncated 200. It now drops only on ErrWorkspaceNotFound and propagates
  everything else.

Denials map to 404 via the shared writeClientError / writeIssueWatchError
sinks and the two list/test handlers. Renamed the test helper
denyExcept -> denyOnly (it denies exactly the named workspaces). Added
per-package regression tests for create/update/list denial, authorizer
error propagation, connection-test denial, and data-plane denial;
mutation-verified the CreateIssueWatch guard.

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

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-26 16:29:58 +01:00

109 lines
4.1 KiB
Go

package linear
import (
"context"
"errors"
"testing"
"github.com/kandev/kandev/internal/task/repository/repoerrors"
)
// TestCreateIssueWatch_DeniesForeignWorkspace is the regression for the review's
// P1: CreateIssueWatch takes WorkspaceID from the request body, which the
// query-only integration middleware never authorizes.
func TestCreateIssueWatch_DeniesForeignWorkspace(t *testing.T) {
f := newSvcFixture(t)
ctx := context.Background()
f.svc.SetWorkspaceAuthorizer(denyOnly("ws-victim"))
_, err := f.svc.CreateIssueWatch(ctx, &CreateIssueWatchRequest{
WorkspaceID: "ws-victim", WorkflowID: "wf", WorkflowStepID: "step",
Filter: SearchFilter{Query: "bug"}, AgentProfileID: "ap",
})
if !errors.Is(err, repoerrors.ErrWorkspaceNotFound) {
t.Fatalf("expected ErrWorkspaceNotFound, got %v", err)
}
if all, _ := f.store.ListAllIssueWatches(ctx); len(all) != 0 {
t.Fatalf("watch was created in a foreign workspace: %d rows", len(all))
}
}
// TestUpdateIssueWatch_DeniesForeignWorkspace guards the by-ID mutation path:
// the watch ID alone reveals nothing about ownership.
func TestUpdateIssueWatch_DeniesForeignWorkspace(t *testing.T) {
f := newSvcFixture(t)
ctx := context.Background()
w := &IssueWatch{
WorkspaceID: "ws-victim", WorkflowID: "wf", WorkflowStepID: "step",
Filter: SearchFilter{Query: "bug"}, AgentProfileID: "ap", Enabled: true,
}
if err := f.store.CreateIssueWatch(ctx, w); err != nil {
t.Fatalf("seed watch: %v", err)
}
f.svc.SetWorkspaceAuthorizer(denyOnly("ws-victim"))
if _, err := f.svc.UpdateIssueWatch(ctx, w.ID, &UpdateIssueWatchRequest{}); !errors.Is(err, repoerrors.ErrWorkspaceNotFound) {
t.Fatalf("expected ErrWorkspaceNotFound, got %v", err)
}
}
// TestListIssueWatches_DeniesForeignWorkspace covers the single-workspace list
// path (the scoped form the settings page uses with an explicit workspace_id).
func TestListIssueWatches_DeniesForeignWorkspace(t *testing.T) {
f := newSvcFixture(t)
ctx := context.Background()
f.svc.SetWorkspaceAuthorizer(denyOnly("ws-victim"))
if _, err := f.svc.ListIssueWatches(ctx, "ws-victim"); !errors.Is(err, repoerrors.ErrWorkspaceNotFound) {
t.Fatalf("expected ErrWorkspaceNotFound, got %v", err)
}
}
// TestListAllIssueWatches_PropagatesAuthorizerError is the regression for the
// review's P2: a non-denial authorizer error (e.g. a transient DB failure) must
// surface, not be treated as a silent per-watch denial that returns a truncated
// 200.
func TestListAllIssueWatches_PropagatesAuthorizerError(t *testing.T) {
f := newSvcFixture(t)
ctx := context.Background()
if err := f.store.CreateIssueWatch(ctx, &IssueWatch{
WorkspaceID: "ws-1", WorkflowID: "wf", WorkflowStepID: "step",
Filter: SearchFilter{Query: "bug"}, AgentProfileID: "ap", Enabled: true,
}); err != nil {
t.Fatalf("seed watch: %v", err)
}
boom := errors.New("authorizer backend down")
f.svc.SetWorkspaceAuthorizer(func(context.Context, string) error { return boom })
if _, err := f.svc.ListAllIssueWatches(ctx); !errors.Is(err, boom) {
t.Fatalf("expected the authorizer error to propagate, got %v", err)
}
}
// TestTestConnection_DeniesForeignWorkspace is the regression for the review's
// P1 credential-exfiltration path.
func TestTestConnection_DeniesForeignWorkspace(t *testing.T) {
f := newSvcFixture(t)
ctx := context.Background()
f.svc.SetWorkspaceAuthorizer(denyOnly("ws-foreign"))
result, err := f.svc.TestConnectionForWorkspace(ctx, "ws-foreign", &SetConfigRequest{
AuthMethod: AuthMethodAPIKey, DefaultTeamKey: "ENG", Secret: "x",
})
if !errors.Is(err, repoerrors.ErrWorkspaceNotFound) {
t.Fatalf("expected ErrWorkspaceNotFound, got %v (result=%+v)", err, result)
}
}
// TestDataPlane_DeniesForeignWorkspace covers the clientFor chokepoint that all
// data-plane reads funnel through.
func TestDataPlane_DeniesForeignWorkspace(t *testing.T) {
f := newSvcFixture(t)
ctx := context.Background()
f.svc.SetWorkspaceAuthorizer(denyOnly("ws-foreign"))
if _, err := f.svc.SearchIssuesForWorkspace(ctx, "ws-foreign", SearchFilter{Query: "bug"}, "", 10); !errors.Is(err, repoerrors.ErrWorkspaceNotFound) {
t.Fatalf("expected ErrWorkspaceNotFound, got %v", err)
}
}