bb71233826549c96b72832bc4bba405c2baa91e8
31 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
bb71233826 | chore: add architecture lint guardrails (#2168) | ||
|
|
b2518b9b8b | fix(ui): preserve cancel progress across task switches (#2199) | ||
|
|
c95d44193c | fix: make walkthrough MCP failures actionable (#2209) | ||
|
|
431e5d40fe | fix: enforce classified Git admission paths (#2150) (#2181) | ||
|
|
e68d3f1d8f | docs(plugins): improve plugin authoring guidance (#2164) | ||
|
|
e077658a61 | refactor: centralize runtime feature flag bindings (#2142) | ||
|
|
c7be985a29 |
feat(i18n): localize shared-task artifacts in the creator's locale (#2147)
Co-authored-by: Kandev Agent <agent@kandev.dev> |
||
|
|
83c3c1ccf1 |
feat(i18n): ratchet new code to require t()/<Trans> everywhere (#2105)
Co-authored-by: Kandev Agent <agent@kandev.dev> |
||
|
|
6cd89a78d3 |
feat(i18n): add scoped i18n foundation with one migrated page (#2097)
Co-authored-by: Kandev Agent <agent@kandev.dev> |
||
|
|
5182cfb95a | chore: improve harness guidance and ACP debugging (#1969) | ||
|
|
c3d235b83b |
fix(auth): close per-user session isolation gaps (service, WS, orchestrator) (#1939)
* fix(auth): scope session-keyed reads and mutations to the workspace owner Session-keyed service entry points did not apply per-user scoping, so knowing another user's session or task ID was enough to reach it: - GetTaskSession, ListTaskSessions, GetPrimarySession returned rows for any ID. These feed GET /task-sessions/:id and GET /tasks/:id/sessions, whose DTO carries session Metadata, the host worktree path, the branch, and container/executor IDs. - DismissLastAgentError mutated any session. - ApproveSession approved a workflow review step on any session, which advances the task's workflow — the highest-impact of the set. Authorize via authorizeTaskID off the row already read, rather than AuthorizeSessionAccess, which would re-read the session on what is a hot path. Internal identity-less callers (pollers, event bus, office schedulers, office agent JWTs) and the synthetic identity used while auth is disabled stay unscoped, and unowned pre-auth rows stay visible. Batch helpers that take ID lists are deliberately left alone: their callers derive IDs from an already-authorized task list, so per-ID checks would add N queries to list views for no gain. Recorded in AGENTS.md. Also route httpApproveSession through handleNotFound so a denial answers 404 like every other session route instead of a 500 that would confirm the session exists. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(auth): scope the session-keyed paths that bypass the task service An adversarial sweep of the previous commit found session-keyed surfaces reachable with a caller-supplied ID and no ownership check. They bypass the task service, so scoping its methods did not cover them: - POST /task-sessions/:id/{set-mode,set-model,set-config-option, authenticate} and .../processes/:processId/stop resolve their execution with a bare in-memory lookup, which skips the GetOrEnsure* chokepoint where the lifecycle per-user check runs. A non-owner could switch another user's model or mode, re-authenticate their agent, or kill their process. Guarded by a shared denySessionAccess helper. - The orchestrator reads sessions through its own repo handle, so GetTaskSessionStatus and CheckSessionPR inherited nothing from the task service. CheckSessionPR also installs a PR watch as a side effect. Added a SetSessionAccessChecker hook mirroring the lifecycle manager's, wired to taskSvc.AuthorizeSessionAccess. The check runs before CheckSessionPR's unconfigured-GitHub early return so it applies regardless of setup, and denials reuse the "session not found" shape so they cannot be told apart from a missing session. - GetMessage had no scoping while ListMessages beside it did, so a caller holding another user's (session_id, message_id) pair could read their shell output. This does NOT close the whole surface. A second sweep found the orchestrator's session-mutating WS actions (session.stop/delete/rename/ set_primary/set_plan_mode/reset_context/recover/launch/ensure, agent.cancel, permission.respond) and agent.stdin / agent.resize also unscoped — agent.stdin writes arbitrary input into another user's agent process. Those touch live session lifecycle and need their own change; recorded in AGENTS.md so the gap is not mistaken for covered. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(auth): scope every session-keyed WS action, plus a gateway backstop Completes the sweep. Dispatched WS actions were left to authorize themselves at the service layer, and a dozen never did — a caller with a guessed session ID could stop, delete, rename, relaunch or reset another user's live agent session, cancel their in-flight turn, answer their permission prompts, or write arbitrary bytes into their agent process. Two layers, deliberately both: 1. Gateway backstop. Client.authorizeAction checks any dispatched payload carrying task_id or session_id against the client's identity before dispatch. Per-method opt-in across ~74 actions in four packages had been missed repeatedly; this makes a newly added action scoped by default. Verified safe to apply generically: session_id means a task session everywhere, and user-shell/terminal actions key off task_id / task_environment_id, so nothing is misread. 2. Explicit guards, for defense in depth and for non-WS callers: - orchestrator: StopSession, DeleteSession, SetPrimarySession, RenameSession, ResetAgentContext, CancelAgent, RespondToPermission, SetSessionPlanModeByID, RecoverSession, LaunchSession, EnsureSession, CancelTransientRetry. Added SetTaskAccessChecker for the task-keyed ones. LaunchSession guards every intent at the single funnel; SessionID is empty on create, so the task check carries that case. - agent.stdin / agent.resize now call lifecycleMgr.CheckSessionAccess, the helper already documented for bare-lookup handlers. Guards go first in each method, before any repo/executor use. TestSessionKeyedEntryPointsGuardBeforeDependencies runs all twelve with nil dependencies and fails on a panic if one is placed too late. Denials are indistinguishable from a missing resource: WS returns not-found, CancelTransientRetry reports "nothing cancelled", and GetTaskSessionStatus reuses its "session not found" shape. Unwired checkers stay permissive throughout, so identity-less internal callers (schedulers, event bus, workflow engine) and pre-auth single-user instances are unaffected — pinned per entry point. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(auth): scope environment-keyed user-shell actions Third sweep finding, in surface the previous commit's own comment claimed was covered. The user-shell actions key off task_environment_id and treat task_id as optional, so a task_id-only backstop missed them: user_shell.stop with an empty task_id and a foreign task_environment_id fell through to the legacy runner path and tore down another user's terminal PTY. That path never reaches GetOrEnsureExecutionForEnvironment, where the environment check normally runs, so neither layer caught it. - Gateway backstop now also reads task_environment_id, gated by a new AuthPolicy.ActionEnvironment hook wired to taskSvc.AuthorizeEnvironmentAccess. This covers all three environment-keyed actions generically, not just the reported one. - wsUserShellStop guards explicitly via a new lifecycleMgr.CheckEnvironmentAccess, mirroring CheckSessionAccess, so the fallback is safe independent of the gateway. Corrected the comment that wrongly asserted task_environment_id was already covered, and recorded in AGENTS.md both the exact field names the backstop reads and why a permissive type on one of them would silently opt out. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(auth): authorize both IDs on task+session entry points Review finding (P1). Entry points taking both a task and a session ID only checked the session, so a caller could satisfy that check with one of their own sessions while pointing taskID at another user's task: - CheckSessionPR then used the unchecked taskID for GetTaskPR, resolveTaskRepo, resolvePrimaryTaskRepositoryID and EnsurePRWatch — cross-workspace PR disclosure plus a PR-watch write. - CancelTransientRetry handed it to handleRecoverableFailure, which writes against that task. Both now use a new authorizeTaskSessionPair, which authorizes each ID and additionally requires the pair to be consistent, so the two arguments cannot describe different tasks. GetTaskSessionStatus already validated the pair after loading the session and is unchanged. The consistency half is skipped when the session cannot be loaded: both IDs are authorized by then, so a mismatch is a caller bug rather than a cross-user leak, and failing there would change behavior for identity-less internal callers. Recorded the rule in AGENTS.md — a two-ID entry point must never use authorizeSession alone. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(auth): scope AttachWorkspaceSources Found while rebasing onto main. POST /tasks/:id/workspace-sources and the add_workspace_sources_kandev MCP tool landed on main during this PR's review with no ownership check, so a caller could attach repositories and folders to another user's task and have them materialized into that task's workspace. Same class as the rest of this PR, so fixed here rather than left for a follow-up. The WS dispatch backstop added earlier already covered the browser path (the payload carries task_id); this closes the HTTP route and the MCP tool, which do not go through it. ErrTaskNotFound already maps to 404 in workspaceSourceHTTPStatus, so the denial surfaces correctly without touching the handler. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(auth): map denied shell-output reads to 404 Review finding. GetMessage became per-user scoped earlier in this PR, so a denial now arrives as ErrTaskNotFound. httpGetShellOutput only mapped sql.ErrNoRows to 404, sending everything else to the 500 branch — so a foreign message answered 500 while a missing one answered 404, which is an existence signal and inconsistent with the 404-everywhere rule the other session routes follow. Kept the sql.ErrNoRows branch explicit rather than replacing it outright: isNotFound classifies typed sentinels and the "not found" substring, and "sql: no rows in result set" matches neither, so routing that case through handleNotFound alone regressed the missing-message response to 500 (caught by TestHTTPShellOutputSnapshot). Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * test(auth): make the shell-output scoping test actually exercise the guard Both reviewers caught that TestHTTPGetShellOutputDeniesForeignMessageWith404 was vacuous. httpGetShellOutput has a second 404 gate after the service call — `if !ok || message.TaskSessionID != c.Param("id")` — and ExtractShellExecOutput returns ok=false for nil metadata. The fixture had none, so the route answered 404 through that gate whether or not scoping denied the read. Confirmed by mutation rather than inspection: with the authorization removed from GetMessage the test still passed. With valid shell-output metadata in the fixture it returns 200 and the victim's stdout, so the test fails as intended; restoring the guard makes it pass again. Also mutation-tested the sibling denial tests, since this is a defect class rather than a one-off: - TestHTTPGetTaskSessionDeniesForeignSessionWith404 — sound, returns 200 with the session DTO when the guard is removed. - TestProcessRoutesDenyForeignSession — catches removal, though via the documented nil-lifecycleMgr panic rather than a status assertion. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * test(auth): add an in-test witness to the shell-output scoping test Review suggestion. The fixture fix made the test exercise the guard, but nothing in the test proved the 404 came from authorization rather than the route's post-service `!ok` gate — which is exactly how it went vacuous in the first place. The evidence lived in a commit message describing a manual mutation run, not in the test. Now asserts both directions, matching the approve-route test: the non-owner gets 404, and the owner does NOT. If the assertion ever stops proving authorization, the owner case fails and says so. Re-verified by mutation: removing the guard from GetMessage fails the test with 200 and the victim's stdout; restoring it passes. 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> |
||
|
|
75abf779ed | feat(github): support per-workspace GitHub App registrations (#1810) | ||
|
|
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> |
||
|
|
919a39e49a |
feat(auth): opt-in authentication & multi-user segregation (#1930)
* feat(auth): add auth core — identities, sessions, PATs, invites, mode state machine Phase 1 of opt-in authentication + multi-user segregation: - internal/auth: argon2id password hashing (PHC), opaque session/PAT tokens (SHA-256 at rest), login rate limiter, auth-mode state machine (disabled/setup/enabled), setup-wizard promotion of the pre-auth default-user row into the admin account, invites, admin user management with last-admin guard. - internal/auth/store: auth_identities (OIDC-ready), auth_sessions, auth_api_tokens, auth_invites tables (SQLite+Postgres dialects). - internal/auth/authn: request-identity plumbing (gin + plain contexts), RequireAdmin middleware. - users table: display_name/role/status columns via new MigrateLogger wiring; AccountRepository surface (consumer-scoped, keeps existing Repository fakes untouched). - config: AuthConfig.Required/SessionTTLHours/CookieName (KANDEV_AUTH_REQUIRED), FeaturesConfig.Auth; profiles.yaml + runtime flag registry entry for KANDEV_FEATURES_AUTH. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(auth): enforce opt-in auth over HTTP — middleware, auth API, boot payload Phase 2 of opt-in authentication + multi-user segregation: - internal/auth/httpmw: global gin middleware after CORS. Disabled mode injects the synthetic single-user admin identity (behavior unchanged); enabled mode resolves session cookie then PAT bearer, with an explicit allowlist (health, SPA bootstrap reads, credential endpoints, self-authenticating webhooks), deferral for WS/proxy upgrades and office agent JWTs, and SPA shell availability for the login page. - internal/auth/httpapi: full auth surface — setup wizard, login/logout, me, password change, sessions, PATs, invites (mint/preview/accept), auth settings (enable/disable), admin user management. - Boot payload: initialState.auth block always present; unauthenticated visitors on auth-enabled instances get features+auth only (no data). - External MCP: PAT required once auth is enabled (open while disabled). - Admin guards on destructive system routes and runtime-flag overrides. - Startup warning when bound non-loopback with auth disabled (ServerConfig.NonLoopbackBinds fail-closed nudge). - Wiring: auth store in Repositories, auth service in Services, ClaimUnownedWorkspaces backfill on the task repository. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(auth): per-user workspace scoping across HTTP services Phase 3 of opt-in authentication + multi-user segregation: - Task service: workspaces, workflows, repositories, and tasks are scoped to the request identity (owner-only visibility; pre-auth unowned rows stay shared). Denials use *NotFound sentinels - no existence leak. Internal callers and the disabled-mode synthetic identity remain unscoped, preserving behavior exactly when auth is off. - CreateWorkspace stamps the authenticated caller as owner. - Session chokepoint: lifecycle Manager.GetOrEnsureExecution runs a settable session-access check covering shell/files/ports/vscode/LSP. - Secrets: per-user user_id column, scoped CRUD/list, ClaimUnowned wired into the setup-wizard backfills. - Boot payload inherits scoping automatically. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(auth): scope WebSocket gateway to authenticated users Phase 4 of opt-in authentication + multi-user segregation: - Connection auth: /ws, /terminal, /lsp, /vscode, /port-proxy routes are guarded when auth is enabled - session cookie (same-origin upgrade), resolved identity from the HTTP middleware, or ?token=<PAT> for headerless programmatic clients; JSON 401 before any upgrade. - Client identity: every WS client carries its authn.Identity; dispatched RPC actions (workspace.list, task CRUD, ...) run under a context carrying it, so WS RPC gets the same per-user scoping as HTTP. - Subscription checks: task/session subscribe+focus verify workspace visibility via the task service; user topic subscriptions are pinned to the client's own user. - Broadcast routing: new Hub.BroadcastToWorkspace routes workspace-scoped events (task/workflow/repo/office/session-state) to the owner's clients only, with safe fallbacks (unowned/unresolvable -> broadcast) so events never vanish; instance-wide events (executors, environments, agent profiles, system jobs) stay global by design. - Replaced the long-standing discarded-token TODO in HandleConnection. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * docs(auth): add feature spec and backend architecture notes for opt-in auth - docs/specs/auth/spec.md: product behavior (opt-in, setup wizard, per-user workspaces, sessions/PATs, invites, public surface, v1 limits) - apps/backend/AGENTS.md: internal/auth package layout + scoping rules for new service entry points and WS broadcast call sites Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * docs(auth): public documentation for opt-in authentication - New docs/public/authentication.md: enabling, users & invites, PATs, public endpoints, limitations, disabling - run-as-a-service.md: network-security note now points at the real authentication boundary instead of reverse-proxy-only guidance - meta.json: nav entry under Configure Kandev Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * docs(auth): ADR for opt-in authentication architecture Records the load-bearing choices: mode state machine + synthetic identity in disabled mode, opaque DB-backed credentials over JWTs, default-user promotion at setup, service-layer scoping with no-admin-bypass, and the explicit public allowlist. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(web): auth UI — login, setup wizard, invites, users & account settings Adds the frontend half of opt-in authentication: a pre-auth gate in main.tsx that renders the setup wizard or login/invite pages instead of the app shell whenever the boot payload's auth block says so, a new `auth` store slice + feature flag mirroring the backend's StatePayload, credentialed fetch (`credentials: "include"`) with a 401 handler that clears the session and redirects to /login, and a full auth-api.ts client for the /api/v1/auth and /api/v1/users routes. Settings additions: a System > Users page (list/create/disable/promote users, invite-link dialog) and System > Authentication page (enable/ disable with confirm + env-locked banner), gated on the `auth` feature flag and admin role. A new Account sidebar group (Profile & Password, API Tokens) is shown to signed-in users once auth is enabled. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * test(auth): E2E lifecycle suite + fix workspace event WS leak it caught New dedicated Playwright auth project (backend restarts with KANDEV_AUTH_REQUIRED=true, isolated from the tokenless default suite): setup-mode boot gating, admin setup wizard, login/logout + bad credentials, PATs, admin-surface authorization, anonymous WS rejection, UI login flow, and the acceptance test - two-user segregation across HTTP, boot payload, and WebSocket. The segregation spec immediately caught a real leak: workspace.* event payloads carry their ID as 'id' (the payload IS the workspace DTO), not 'workspace_id', so BroadcastToWorkspace fell back to broadcast-to-all for workspace create/update/delete. Fixed with action-aware extraction plus a unit regression test. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(auth): close cross-user access gaps found in security audit Two independent security audits of the auth branch found several authorization gaps where session/workspace-scoped surfaces were not wired to the new per-user chokepoint. All fixed: - IDOR on reverse-proxy/terminal routes (vscode, port-proxy, terminal): these resolve executions via GetExecutionBySessionID / GetOrEnsureExecutionForEnvironment / EnsurePassthroughExecution, which skipped the session-access check that only GetOrEnsureExecution ran. Added the check inside the env/passthrough resolvers (before the cache short-circuit) and an explicit CheckSessionAccess gate in the two bare-lookup proxy handlers. An authenticated non-owner can no longer reach another user's IDE, forwarded ports, or shell. - Cross-user agent-conversation read: ListMessages / ListMessagesPaginated / SearchMessages now authorize the session. - Cross-user repository-script read/inject: script CRUD now authorizes the parent repository's workspace. - Office HTTP surface: a group middleware enforces workspace ownership on :wsId routes for real users (agent-JWT callers keep their claim scoping). - Login rate-limit bypass: SetTrustedProxies(nil) so a spoofed X-Forwarded-For can't rotate the limiter key on a directly-reachable backend. - Invite double-provisioning race: MarkInviteUsed is now the atomic serialization point (consumed before user creation). - Setup wizard: serialized with a mutex so concurrent first-visitors can't corrupt the promoted admin profile. - Log sanitizer: explicit kandev_pat_ redaction rule. Regression tests added for message/script scoping and the execution-access-before-cache invariant. Auth E2E (incl. two-user segregation) still green. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(auth): scope repository active-session-count endpoint GET /api/v1/repositories/:id/active-session-count went through CountActiveSessionsByRepository, which was not identity-scoped - a cross-user info leak of another owner's active session counts. Added the same authorizeRepositoryID gate the script routes use. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(auth): add json tags to auth store models — omit digests, fix token UI The auth store structs (APIToken, Invite, LoginIdentity, Session) had db: tags but no json: tags, so the handlers that serialize them directly sent Go-cased keys (CreatedAt, Name) AND leaked the SHA-256/password digests to clients. Two consequences: - The API-tokens UI showed 'Invalid Date' and an empty name (frontend reads created_at/name). - token_sha256 / password_hash were serialized in list responses. Added json tags with snake_case keys the frontend reads and json:"-" on every credential digest. Regression test asserts digests never serialize and the snake_case timestamp/name keys are present. Also adds the auth-screenshots capture spec (artifacts gitignored). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(web): move auth enable into feature toggles; show current user in sidebar Remove the standalone Authentication settings page and its dedicated settings/get-auth-settings API surface now that enabling auth lives in the Feature Toggles system, and drop env_required now that /auth/me no longer returns it. Add a current-user chip with a logout action to the sidebar footer, shown only in enabled auth mode. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * refactor(auth): make features.auth the single on/off control Per review feedback: authentication configuration now lives entirely in the existing Feature Toggles system rather than a separate Authentication settings section. - The auth mode is derived from the features.auth runtime flag (KANDEV_FEATURES_AUTH): off -> disabled, on+no-admin -> setup, on+admin -> enabled. Removed the parallel auth.mode system setting, the SetEnabled service method, GET/PATCH /api/v1/auth/settings, the AuthConfig.Required field, KANDEV_AUTH_REQUIRED, and the auth service's Settings-store dependency and EnvRequired/env_required. - The features.auth registry entry is re-described as the actual enable switch (high-risk, restart-required) and defaults off in every profile (dev was previously true — that only revealed UI before; now it would enforce, so it must be an explicit opt-in). - Setup no longer persists a mode; completing the wizard creates the admin and the mode auto-derives to enabled. - Startup 'exposed without auth' warning + all docs (public guide, run-as-a-service, spec, ADR, AGENTS.md) point at the feature toggle. - E2E: auth specs use KANDEV_FEATURES_AUTH; screenshot spec captures the Feature Toggles page instead of the removed Authentication page; the member-restriction assertion targets an admin invite route. - Tests updated across service/httpmw/httpapi/profiles for the derived mode; full suite green (only pre-existing sandbox-FS failures remain). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(auth): complete cross-user isolation — integrations, automation, plan/walkthrough, session reads A follow-up isolation audit found that per-user scoping had been wired into the task service, secrets, office, and the WS gateway — but several workspace/task/session-scoped surfaces still resolved a caller-supplied ID with no ownership gate. Closed all of them; cross-user access now returns 404 across the board. - Integrations (jira/linear/sentry/slack/azure-devops/gitlab/github/ workflow-sync): a global middleware authorizes the workspace_id (query, or gitlab's /workspaces/:id/ path) on those route groups. Previously a member who knew another user's workspace ID could read/overwrite their integration connection config and watches. - Automation: workspace-authorizer seam gates get/list/create/update/delete/ enable/disable, triggers, run history, and — critically — the webhook secret. Was fully cross-tenant over WS before. - Task plans (PlanService) and walkthroughs (WalkthroughService): task- authorizer seam on every read/write. These bypassed the task service. - Session reads that hit the repo directly — session turns, task context, git snapshots, file reviews — now call AuthorizeSession/TaskAccess. Internal callers (pollers, schedulers, MCP) carry no identity and stay unscoped; disabled mode is unaffected. Regression tests added (plan/walkthrough scoping, automation authorizer matrix, integration path extraction) and the two-user E2E now asserts integration routes are shielded. Docs (spec, ADR, public guide) updated to state what is isolated and that filesystem/agent-credential isolation remains an OS-level limitation. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(web): current-user chip uses border hover, not accent fill The sidebar current-user chip used hover:bg-accent (a purpleish fill). Switch to the border-hover idiom used elsewhere (border border-transparent -> hover:border-border) with the neutral hover:bg-muted/50 the adjacent workspace picker uses, so the hover reads as a subtle outline instead of a colored background. Screenshot spec now captures the chip hover state. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(web): right-align current-user chip in the sidebar footer Push the user chip to the far right of the expanded footer (ml-auto) so it sits opposite the left-aligned icon buttons; collapsed mode keeps the centered vertical stack unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(auth): reject synthetic identity on management routes and scope office run broadcasts Address code-review findings on the opt-in authentication PR: - P1: while auth is disabled the middleware injects a synthetic admin (RoleAdmin), and RequireAdmin alone let it through — so anyone hitting a not-yet-enabled instance could mint a PAT or plant an admin that survives enablement and hijacks first-run setup. Add authn.RequireRealIdentity and guard the credential/session/user-management routes with it (public bootstrap routes stay reachable). Responds 404 while disabled. - P1: office run events carry task_id but no workspace_id, so they fell back to a global broadcast and leaked across users. Resolve the workspace from the task and route via the new Hub.BroadcastToWorkspaceOrDrop, which fails closed (drops rather than global-broadcasts) when the workspace is unknown and auth is enforced. - nit: type createAuthSlice as a single-arg creator and call it with just set. Also register the authentication docs page and its settings routes in docs/public/coverage.json so the public-docs validator passes. 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> |
||
|
|
7fd99c3f33 | feat: complete GitLab integration parity (#1832) | ||
|
|
2a1f7c2edf |
feat: sync workflows from a configured github repo (#1721)
* feat: sync workflows from a configured github repo Per-workspace setting pointing at a GitHub repo directory of portable workflow export files. A background poller fetches it on an interval and creates, updates, or deletes the matching workflows; a force-sync endpoint bypasses the content-hash check. Synced workflows carry source/source_path provenance and coexist with manual ones; changes that cannot be applied safely (steps or workflows that still hold tasks, ambiguous step names, unparseable files) surface as warnings in the new settings section. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(web): fill workflow sync form from a pasted github link A new Repository link field parses plain repo URLs, SSH remotes, and tree/blob links (which also carry branch and directory) into the structured owner/repo/branch/path fields. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(web): simplify workflow sync form to link, branch, and interval The repository link is now the only repo input: owner, repo, and directory resolve from the pasted URL (echoed as a summary under the field), and a stored config renders back into a canonical tree link via buildGitHubRepoUrl. Branch and poll interval stay individually editable. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(web): collapse workflow sync into a button, dialog, and status card The Workflows settings page now shows only a GitHub Sync button by default; the link/branch/interval form lives in a dialog that closes on successful save or removal. Once configured, a compact status card (mirroring the GitHub connection-status card) shows the synced repo, branch, directory, last result, warnings, and a Sync now action. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(web): move github sync button into the workflows page header The GitHub Sync trigger now stacks under the Workspace settings button on the top right, and the extra separator around the sync area is gone — unconfigured workspaces show no sync chrome at all, configured ones show just the status card above the workflow list. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(web): move github sync button next to the workflow actions GitHub Sync now sits in the Workflows section toolbar alongside Export All, Import, and Add Workflow; the status card renders inside the section above the workflow list. The toolbar moved to its own component to keep the page under the file-size limit. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(web): separate sync status card from the workflow list Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(web): align sync status card with the workflow list gutter Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: repair local edits to synced workflows on periodic sync Periodic syncs previously skipped applying when the repo content hash was unchanged, so local UI edits to a synced workflow were only reverted by a manual Sync now. Every sync now reconciles against the repo; the applier compares each step against its definition and only writes (and broadcasts) actual differences, so a no-drift sync stays silent. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat: make github-synced workflows read-only Workflows with source=github reject UI mutations: workflow rename, description, agent-profile, and delete return 409 from the task-domain handlers; step create/update/delete/reorder and template application are guarded in the workflow controller. The sync applier writes through the service/repo layer and stays exempt. The frontend disables the card's inputs, save/delete, and the step pipeline editor for synced workflows, with a tooltip pointing at the synced repository. Drift repair on sync remains as the backstop. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat: optional workflow sync polling and repo-derived branch picker A per-workspace auto-sync toggle (poll_enabled, default on) controls the background polling loop; when off the workspace only syncs via Sync now. The dialog's branch field becomes a select fed by the repository's actual branches (same loader the task-create dialog uses), falling back to free text until branches load. Existing dev databases gain the new column via an idempotent ALTER. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat: release synced workflows when the sync config is removed Deleting a workspace's workflow sync configuration converts its GitHub-sourced workflows back to manual ownership (source=manual), so they become editable instead of being stranded read-only. Release runs before the config row is deleted so a failure keeps the config for retry. The settings page reloads after removal (and after syncs that changed workflows) so cards unlock without a manual refresh. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(web): drop branch selector and compact the auto-sync row The pasted link already carries the branch (main by default), so the dialog no longer needs a branch field — the resolved summary echoes it. The auto-sync toggle is now one compact row with the interval inline and a single short helper line. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: address PR review feedback Backend: fail-open read-only guard on workflow lookup errors (fixes MCP step handler CI failures); poller Stop holds its mutex through drain; per-workspace lock serializes syncs against config delete/replace; rollback workflow creation when provenance stamping fails; idiomatic duplicate-column migration via db.IsDuplicateColumnError; branch-name validation and a 30-day interval cap; generic 500s with logged detail; WS read-only rejections use CONFLICT with the real reason; e2e reset aborts when sync-config cleanup fails; test hygiene (t.Cleanup, SetMaxOpenConns). Frontend: malformed percent escapes parse as invalid instead of throwing; save disabled during initial load and for invalid intervals; Remove disabled while saving; stale async config responses discarded; delete-dialog confirms re-check read-only; focusable Synced badge; explicit button types; failed polls labeled 'last attempt'; unique warning list keys; test cleanup via afterEach. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: guard workflow sync test fake against concurrent poller access The poller invokes the fake applier from its own goroutine while the synctest test asserts on call counts; -race caught the unguarded reads. Also documents that the per-workspace lock is deliberately held across the GitHub fetch. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Kandev Agent <agent@kandev.dev> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
892ce9bf09 | fix(worktree): preserve colon paths in copy files (#1674) | ||
|
|
fd7c7a2b0f | feat(worktree): add per-file copy/symlink materialization per repository (#1650) | ||
|
|
818e9c7abc | chore: improve harness feedback workflow (#1561) | ||
|
|
49c482bd4d | fix: prevent leaked agent processes on shutdown (#1498) | ||
|
|
a28c4226de | fix: make schema migrations replayable (#1489) | ||
|
|
19c17b1321 | chore: improve agent harness skills (#1378) | ||
|
|
f444fba455 | perf(chat): eliminate redundant re-renders and markdown re-parsing (#1357) | ||
|
|
224383c557 | chore: improve PR fixup and E2E harness guidance (#1351) | ||
|
|
68a9f77b15 | fix(harness): harden pr-state and e2e guidance (#1331) | ||
|
|
13c72844d5 | docs: improve agent harness guidance for tests, PR fixup, and debugging (#1235) | ||
|
|
d1c73d2f2c | feat: surface subagent task tool calls as cards in task chat (#1132) | ||
|
|
43977ca570 | fix(web): keep markdown table headers readable on narrow content (#1122) | ||
|
|
de92557f46 |
test(backend): wire goleak goroutine-leak detection across 8 packages (#1139)
* chore(backend): add go.uber.org/goleak test dependency Promotes the previously-indirect goleak v1.3.0 to a direct require so per-package TestMain calls can use it for goroutine leak detection. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(backend/lifecycle): drain workspace-stream backoff on Manager.Stop StreamManager.connectWorkspaceStream slept the full retry backoff in time.Sleep between failed attempts. SessionTraceContext is deliberately uncancellable (it carries a long-lived span), so if the Manager began shutting down mid-backoff the goroutine outlived Stop() and stranded until the timer fired. Thread Manager.stopCh through the StreamManager constructor and add a sleepOrStop helper that selects between the timer and the shutdown signal. ReconnectAll's startup sleep gets the same treatment. TestConnectWorkspaceStream_BackoffDrainsOnStop closes stopCh while a failing-port retry is in flight and asserts the goroutine exits within 500ms — fails without the fix, passes with it. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(backend/github): close sqlite DB in newTestStore to drain connectionOpener newTestStore opened *sqlx.DB via db.OpenSQLite but never registered a Close on cleanup, leaving database/sql.(*DB).connectionOpener goroutines parked across test boundaries. Add t.Cleanup(sqlxDB.Close); goleak's per-package TestMain (added in a follow-up commit) is the regression check. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * test(backend): wire goleak.VerifyTestMain across leak-prone packages Per-package TestMain in: - internal/integrations/healthpoll (auth-health ticker loop) - internal/jira, internal/linear (auth + issue-watch loops) - internal/github (PR / review / issue poller loops) - internal/gateway/websocket (per-conn pumps + terminal bridge) - internal/orchestrator (detached event-handler goroutines) - internal/agent/runtime/lifecycle (remote-status loop, StreamManager helpers; ignores OTel batch-span processor and OTLP retry helper — initialised early in the process and only exit on shutdown) - internal/agentctl/server/process (extends the existing fixture-binary TestMain so subprocess + PTY pump leaks surface there) Catches regressions where a Start/Stop forgets to drain on WaitGroup, or a detached goroutine forgets to honour ctx/stopCh cancellation. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * docs(backend): document goroutine ownership and leak-testing convention New "Goroutine ownership and leak testing" subsection under Conventions in apps/backend/AGENTS.md (CLAUDE.md symlinks to it). Covers: - Lifecycle: Start/Stop + WaitGroup, both idempotent. - Cancellation: every long wait selects on ctx.Done() or stopCh; never time.Sleep in retry loops (reference lifecycle.StreamManager.sleepOrStop). - Detached helpers: must respect the owning type's shutdown signal. - Leak testing: new packages spawning goroutines add goleak.VerifyTestMain; IgnoreTopFunction is reserved for genuine third-party background goroutines and must carry a comment explaining the suppression. Lists the packages currently instrumented so future contributors can mirror the pattern. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * chore(backend/lifecycle): drop dead OTel IgnoreTopFunction from goleak setup Review follow-up. agentctl/tracing.initTracing only spawns the OTel SDK provider when OTEL_EXPORTER_OTLP_ENDPOINT is set; in tests it isn't, so the noop provider is used and no batchSpanProcessor / OTLP retry goroutines ever exist. The IgnoreTopFunction calls were dead suppressions and the comment ("called by NewManager via the agent execution trace path") misdescribed when the SDK init runs. Drop the ignores and correct AGENTS.md to stop citing OTel as the canonical suppression example. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * test(backend/lifecycle): drop unneeded 50ms sleep from backoff-drain test QA follow-up. The 50ms time.Sleep before close(stopCh) in TestConnectWorkspaceStream_BackoffDrainsOnStop was meant to ensure the goroutine had entered the backoff sleep before shutdown — but that ordering doesn't affect the test outcome: - With the fix: sleepOrStop sees stopCh already closed and returns false on the first call, so the goroutine drains within one attempt regardless of when stopCh closes. - Without the fix: time.Sleep ignores stopCh, the goroutine burns its full 5-retry backoff (~31s), and the 500ms timeout fires. Removing the sleep makes the test ~12x faster (15ms vs 200ms total) and removes the only time.Sleep-based wait from the new tests, aligning with the codebase's "channel-based sync, no sleep waits" convention. Verified by 50x -race and 5x revert-and-fail. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(backend/github): drain HTTP idle conns before goleak inspects CI surfaced a leaked goroutine on the Linux runner that local runs missed: a single net/http.(*http2ClientConn).readLoop parked on a TLS read, created by net/http.(*http2Transport).newClientConn. The package's anonymousHTTPClient and PATClient's rewriteTransport both route through http.DefaultTransport's connection pool, so an idle HTTP/2 connection in that pool keeps the reader goroutine alive past m.Run() — invisible on sandboxed local runs where outbound network is blocked. Replace github/goleak_test.go's plain VerifyTestMain with an expanded TestMain that drains http.DefaultTransport's idle connections before goleak.Find runs. This is the stdlib's documented teardown for the connection pool, keeps the assertion strict (no IgnoreTopFunction), and doesn't leak into production code. Other in-scope packages don't need this — they don't use http.DefaultTransport for HTTPS calls. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(backend): drain ws.Done on stopCh; always run goleak in github tests - lifecycle/streams.go: replace bare <-ws.Done() with a select that also watches sm.stopCh so a connected goroutine drains when Manager.Stop() fires before the remote WS closes. A nil stopCh (isolated tests) blocks the nil channel case forever, degrading to plain <-ws.Done() semantics. - github/goleak_test.go: remove the exitCode==0 guard around goleak.Find so leaks are always surfaced even when a test has already failed; original exit code is preserved (leaks only promote it to 1). Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(backend/lifecycle): close ws on stopCh so agentctl WS loops drain cubic flagged that the previous shutdown path observed stopCh but never called ws.Close(), so the underlying WebSocket and its agentctl-side read/write goroutines (workspace_stream.go:67-68) kept running past Manager.Stop(). ClearWorkspaceStream only removes the WS from the execution's tracking — it doesn't close the connection. Call ws.Close() on the stopCh path. ws.Close is idempotent via closeOnce, so it's safe even if the remote end already closed. TestConnectWorkspaceStream_ClosesWSOnStop connects to a mock workspace server that stays open until the client closes its side; after stopCh fires, the test asserts ws.Done() closes within 500ms — which is only true if connectWorkspaceStream invoked ws.Close(). Verified to fail without the fix and pass with it. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * test(backend/lifecycle): use channel sync instead of sleep polling in ws-close test cubic flagged that TestConnectWorkspaceStream_ClosesWSOnStop polled execution.GetWorkspaceStream() in a 500ms sleep loop, which is brittle under CI load. connectWorkspaceStream already accepts a ready channel that closes after SetWorkspaceStream — pass it in and wait on the channel instead. synctest isn't viable here (real network I/O), so channel-based sync is the testing convention per AGENTS.md. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> --------- Co-authored-by: Kandev Agent <agent@kandev.dev> Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com> |
||
|
|
9a462e52c8 | refactor(orchestrator): extract WatcherDispatchCoordinator + WatcherSource (#1070) | ||
|
|
372779ad32 | feat(preview): inspect mode with pin and area annotations (#917) |