diff --git a/.github/workflows/backend-tests.yml b/.github/workflows/backend-tests.yml index 6abcfe8191..6d63e0a2ff 100644 --- a/.github/workflows/backend-tests.yml +++ b/.github/workflows/backend-tests.yml @@ -252,3 +252,8 @@ jobs: # every platform. - name: Test windows-sensitive packages run: go test -race -v ./internal/agentctl/server/process/... ./internal/agent/runtime/agentctl/launcher/... + + # Keep this targeted: the service package has broad subprocess coverage, + # while this native test is the Windows path-semantics regression. + - name: Test explicit local repository paths + run: go test -race -v -run '^TestExplicitLocalRepositoryWindowsPathSemantics$' ./internal/task/service diff --git a/apps/backend/internal/common/gitref/gitref.go b/apps/backend/internal/common/gitref/gitref.go index d2cc17d491..cd4cfb5d35 100644 --- a/apps/backend/internal/common/gitref/gitref.go +++ b/apps/backend/internal/common/gitref/gitref.go @@ -80,12 +80,12 @@ func DefaultBranchOrEmpty(repoPath string) (string, error) { } // guardRepoPath rejects relative paths and any path containing `..` segments -// before passing the value into the file-reading helpers below. Callers -// already validate against an allowlist (see service.resolveAllowedLocalPath), -// but CodeQL's go/path-injection taint analysis doesn't trace that as a -// sanitizer, so we re-check here at the I/O boundary. The check is also -// genuinely useful: any caller — migration code, tests, future callers — -// must hand us an absolute, traversal-free path or we refuse to read. +// before passing the value into the file-reading helpers below. Service +// callers provide canonical explicit repository paths, but CodeQL's +// go/path-injection taint analysis does not trace that as a sanitizer, so we +// re-check here at the I/O boundary. The check is also genuinely useful: any +// caller - migration code, tests, or future callers - must hand us an absolute, +// traversal-free path or we refuse to read. func guardRepoPath(repoPath string) (string, error) { if repoPath == "" { return "", fmt.Errorf("repository path is required") diff --git a/apps/backend/internal/integration/integration_test.go b/apps/backend/internal/integration/integration_test.go index 0e5e053e39..08875af0fe 100644 --- a/apps/backend/internal/integration/integration_test.go +++ b/apps/backend/internal/integration/integration_test.go @@ -8,6 +8,7 @@ import ( "net/http" "net/http/httptest" "os" + "os/exec" "path/filepath" "strings" "sync" @@ -221,6 +222,10 @@ func createTempRepoDir(t *testing.T) string { baseDir := t.TempDir() repoPath := filepath.Join(baseDir, "repo") require.NoError(t, os.MkdirAll(repoPath, 0o755)) + cmd := exec.Command("git", "init", "-b", "main", ".") + cmd.Dir = repoPath + output, err := cmd.CombinedOutput() + require.NoError(t, err, "git init: %s", output) return repoPath } diff --git a/apps/backend/internal/task/handlers/repository_handlers.go b/apps/backend/internal/task/handlers/repository_handlers.go index 58e93c7c6f..4608d01262 100644 --- a/apps/backend/internal/task/handlers/repository_handlers.go +++ b/apps/backend/internal/task/handlers/repository_handlers.go @@ -206,10 +206,17 @@ func (h *RepositoryHandlers) httpListBranches(c *gin.Context) { c.JSON(http.StatusBadRequest, gin.H{"error": "specify only one of repository_id or path"}) return } + if repoID != "" { + repository, err := h.service.GetRepository(c.Request.Context(), repoID) + if err != nil || repository == nil || repository.WorkspaceID != c.Param("id") { + c.JSON(http.StatusNotFound, gin.H{"error": "repository not found"}) + return + } + } result, err := h.service.ListBranchesWithCurrent(c.Request.Context(), repoID, path) if err != nil { - if errors.Is(err, service.ErrPathNotAllowed) { - c.JSON(http.StatusBadRequest, gin.H{"error": "path is not within allowed roots"}) + if errors.Is(err, service.ErrInvalidRepositoryPath) { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } h.logger.Error("failed to list branches", zap.Error(err)) @@ -235,8 +242,8 @@ func (h *RepositoryHandlers) httpLocalRepositoryStatus(c *gin.Context) { } status, err := h.service.LocalRepositoryStatus(c.Request.Context(), path) if err != nil { - if errors.Is(err, service.ErrPathNotAllowed) { - c.JSON(http.StatusBadRequest, gin.H{"error": "path is not within allowed roots"}) + if errors.Is(err, service.ErrInvalidRepositoryPath) { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } h.logger.Error("failed to read local repository status", zap.Error(err)) @@ -323,49 +330,40 @@ func (h *RepositoryHandlers) httpGetRepository(c *gin.Context) { func (h *RepositoryHandlers) httpListRepositoryBranches(c *gin.Context) { repoID := c.Param("id") ctx := c.Request.Context() - - repo, err := h.service.GetRepository(ctx, repoID) - if err != nil { + if _, err := h.service.GetRepository(ctx, repoID); err != nil { handleNotFound(c, h.logger, err, "repository not found") return } var fetchedAt, fetchError string if c.Query("refresh") == queryValueTrue { - fetchedAt, fetchError = h.refreshBranchesAtPath(ctx, repoID, repo.LocalPath) + fetchedAt, fetchError = h.refreshRepositoryBranches(ctx, repoID) } - // Use the unified branch lister (HEAD's API) with empty repoID + path. - branches, err := h.service.ListBranches(ctx, "", repo.LocalPath) + result, err := h.service.ListBranchesWithCurrent(ctx, repoID, "") if err != nil { - if errors.Is(err, service.ErrPathNotAllowed) { - c.JSON(http.StatusBadRequest, gin.H{"error": "repository path is not allowed"}) - return - } h.logger.Error("failed to list repository branches", zap.Error(err)) c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list repository branches"}) return } - current := h.currentBranchAtPath(ctx, repo.LocalPath) - dtoBranches := make([]dto.BranchDTO, len(branches)) - for i, branch := range branches { + dtoBranches := make([]dto.BranchDTO, len(result.Branches)) + for i, branch := range result.Branches { dtoBranches[i] = dto.FromBranch(branch) } c.JSON(http.StatusOK, dto.RepositoryBranchesResponse{ Branches: dtoBranches, Total: len(dtoBranches), - CurrentBranch: current, + CurrentBranch: result.CurrentBranch, FetchedAt: fetchedAt, FetchError: fetchError, }) } -// refreshBranchesAtPath runs `git fetch` for the already-resolved repository -// path and returns the timestamp + error string suitable for the response -// body. Failures are best-effort: the branches are still returned so a -// transient network error doesn't blank the dropdown. -func (h *RepositoryHandlers) refreshBranchesAtPath(ctx context.Context, repoID, localPath string) (fetchedAt, fetchError string) { - res, err := h.service.RefreshBranchesAtPath(ctx, localPath) +// refreshRepositoryBranches runs an identity-bound `git fetch` and returns +// response metadata. Failures are best-effort so a transient network error +// does not blank the branch dropdown. +func (h *RepositoryHandlers) refreshRepositoryBranches(ctx context.Context, repoID string) (fetchedAt, fetchError string) { + res, err := h.service.RefreshRepositoryBranches(ctx, repoID) if err != nil { h.logger.Warn("branch refresh failed", zap.String("repo_id", repoID), zap.Error(err)) return "", err.Error() @@ -379,19 +377,6 @@ func (h *RepositoryHandlers) refreshBranchesAtPath(ctx context.Context, repoID, return fetchedAt, fetchError } -// currentBranchAtPath is best-effort; failures (empty path, detached HEAD, -// IO error) return an empty string so the branches response still ships. -func (h *RepositoryHandlers) currentBranchAtPath(ctx context.Context, localPath string) string { - if localPath == "" { - return "" - } - branch, err := h.service.LocalRepositoryCurrentBranch(ctx, localPath) - if err != nil { - return "" - } - return branch -} - type httpUpdateRepositoryRequest struct { Name *string `json:"name"` SourceType *string `json:"source_type"` diff --git a/apps/backend/internal/task/handlers/repository_handlers_test.go b/apps/backend/internal/task/handlers/repository_handlers_test.go index 4829fe97cf..6e82205451 100644 --- a/apps/backend/internal/task/handlers/repository_handlers_test.go +++ b/apps/backend/internal/task/handlers/repository_handlers_test.go @@ -1,11 +1,220 @@ package handlers import ( + "bytes" + "context" "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "net/url" + "path/filepath" "strings" "testing" + + "github.com/gin-gonic/gin" + "github.com/jmoiron/sqlx" + "github.com/kandev/kandev/internal/common/logger" + "github.com/kandev/kandev/internal/db" + "github.com/kandev/kandev/internal/events/bus" + "github.com/kandev/kandev/internal/task/models" + "github.com/kandev/kandev/internal/task/repository" + taskrepo "github.com/kandev/kandev/internal/task/repository/sqlite" + "github.com/kandev/kandev/internal/task/service" ) +func TestHTTPCreateRepositoryRejectsInvalidLocalPathWithoutPersistence(t *testing.T) { + router, repo := newRepositoryHTTPTestRouter(t) + body, err := json.Marshal(httpCreateRepositoryRequest{ + Name: "Not Git", + SourceType: "local", + LocalPath: t.TempDir(), + }) + if err != nil { + t.Fatalf("Marshal request: %v", err) + } + req := httptest.NewRequest(http.MethodPost, "/api/v1/workspaces/ws-1/repositories", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + response := httptest.NewRecorder() + + router.ServeHTTP(response, req) + + if response.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want %d; body = %s", response.Code, http.StatusBadRequest, response.Body.String()) + } + repositories, err := repo.ListRepositories(context.Background(), "ws-1") + if err != nil { + t.Fatalf("ListRepositories: %v", err) + } + if len(repositories) != 0 { + t.Fatalf("invalid repository was persisted: %+v", repositories) + } +} + +type repositoryHandlerRemoteLister struct { + calls int +} + +func (l *repositoryHandlerRemoteLister) ListRepoBranches(_ context.Context, owner, name string) ([]service.Branch, error) { + l.calls++ + if owner != "owner" || name != "repo" { + return nil, errors.New("unexpected provider identity") + } + return []service.Branch{{Name: "main", Type: "remote"}}, nil +} + +func TestHTTPListRepositoryBranchesUsesRepositoryIdentity(t *testing.T) { + router, repo, svc := newRepositoryHTTPTestRouterWithService(t) + if err := repo.CreateRepository(context.Background(), &models.Repository{ + ID: "provider-repo", + WorkspaceID: "ws-1", + Name: "owner/repo", + SourceType: "provider", + LocalPath: t.TempDir(), + Provider: "github", + ProviderOwner: "owner", + ProviderName: "repo", + }); err != nil { + t.Fatalf("CreateRepository: %v", err) + } + svc.SetRemoteBranchLister(&repositoryHandlerRemoteLister{}) + + request := httptest.NewRequest(http.MethodGet, "/api/v1/repositories/provider-repo/branches", nil) + response := httptest.NewRecorder() + router.ServeHTTP(response, request) + + if response.Code != http.StatusOK { + t.Fatalf("status = %d, want %d; body = %s", response.Code, http.StatusOK, response.Body.String()) + } + if !strings.Contains(response.Body.String(), `"name":"main"`) { + t.Fatalf("response missing remote main branch: %s", response.Body.String()) + } +} + +func TestHTTPListBranchesRejectsRepositoryFromAnotherWorkspace(t *testing.T) { + router, repo, svc := newRepositoryHTTPTestRouterWithService(t) + for _, workspaceID := range []string{"ws-a", "ws-b"} { + if err := repo.CreateWorkspace(context.Background(), &models.Workspace{ID: workspaceID, Name: workspaceID}); err != nil { + t.Fatalf("CreateWorkspace %s: %v", workspaceID, err) + } + } + if err := repo.CreateRepository(context.Background(), &models.Repository{ + ID: "provider-repo", + WorkspaceID: "ws-b", + Name: "owner/repo", + SourceType: "provider", + Provider: "github", + ProviderOwner: "owner", + ProviderName: "repo", + }); err != nil { + t.Fatalf("CreateRepository: %v", err) + } + lister := &repositoryHandlerRemoteLister{} + svc.SetRemoteBranchLister(lister) + + crossWorkspace := httptest.NewRequest( + http.MethodGet, + "/api/v1/workspaces/ws-a/branches?repository_id=provider-repo", + nil, + ) + crossResponse := httptest.NewRecorder() + router.ServeHTTP(crossResponse, crossWorkspace) + if crossResponse.Code != http.StatusNotFound { + t.Fatalf("cross-workspace status = %d, want %d; body = %s", crossResponse.Code, http.StatusNotFound, crossResponse.Body.String()) + } + if lister.calls != 0 { + t.Fatalf("provider lister calls after rejected cross-workspace request = %d, want 0", lister.calls) + } + + sameWorkspace := httptest.NewRequest( + http.MethodGet, + "/api/v1/workspaces/ws-b/branches?repository_id=provider-repo", + nil, + ) + sameResponse := httptest.NewRecorder() + router.ServeHTTP(sameResponse, sameWorkspace) + if sameResponse.Code != http.StatusOK { + t.Fatalf("same-workspace status = %d, want %d; body = %s", sameResponse.Code, http.StatusOK, sameResponse.Body.String()) + } + if lister.calls != 1 { + t.Fatalf("provider lister calls = %d, want 1", lister.calls) + } +} + +func TestHTTPListBranchesRejectsInvalidExplicitPath(t *testing.T) { + router, _ := newRepositoryHTTPTestRouter(t) + request := httptest.NewRequest( + http.MethodGet, + "/api/v1/workspaces/ws-1/branches?path="+url.QueryEscape(t.TempDir()), + nil, + ) + response := httptest.NewRecorder() + + router.ServeHTTP(response, request) + + if response.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want %d; body = %s", response.Code, http.StatusBadRequest, response.Body.String()) + } +} + +func TestHTTPLocalRepositoryStatusRejectsInvalidExplicitPath(t *testing.T) { + router, _ := newRepositoryHTTPTestRouter(t) + request := httptest.NewRequest( + http.MethodGet, + "/api/v1/workspaces/ws-1/repositories/local-status?path="+url.QueryEscape(t.TempDir()), + nil, + ) + response := httptest.NewRecorder() + + router.ServeHTTP(response, request) + + if response.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want %d; body = %s", response.Code, http.StatusBadRequest, response.Body.String()) + } +} + +func newRepositoryHTTPTestRouter(t *testing.T) (*gin.Engine, *taskrepo.Repository) { + t.Helper() + router, repo, _ := newRepositoryHTTPTestRouterWithService(t) + return router, repo +} + +func newRepositoryHTTPTestRouterWithService(t *testing.T) (*gin.Engine, *taskrepo.Repository, *service.Service) { + t.Helper() + dbConn, err := db.OpenSQLite(filepath.Join(t.TempDir(), "test.db")) + if err != nil { + t.Fatalf("OpenSQLite: %v", err) + } + sqlxDB := sqlx.NewDb(dbConn, "sqlite3") + repo, cleanup, err := repository.Provide(sqlxDB, sqlxDB, nil) + if err != nil { + t.Fatalf("repository.Provide: %v", err) + } + t.Cleanup(func() { + if err := cleanup(); err != nil { + t.Errorf("cleanup repository: %v", err) + } + if err := sqlxDB.Close(); err != nil { + t.Errorf("close database: %v", err) + } + }) + if err := repo.CreateWorkspace(context.Background(), &models.Workspace{ID: "ws-1", Name: "Workspace"}); err != nil { + t.Fatalf("CreateWorkspace: %v", err) + } + log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json", OutputPath: "stdout"}) + if err != nil { + t.Fatalf("NewLogger: %v", err) + } + eventBus := bus.NewMemoryEventBus(log) + svc := service.NewService(service.Repos{ + Workspaces: repo, + RepoEntities: repo, + }, eventBus, log, service.RepositoryDiscoveryConfig{}) + router := gin.New() + NewRepositoryHandlers(svc, log).registerHTTP(router) + return router, repo, svc +} + // TestRepositoryCreateRequestJSONIncludesCopyFiles verifies that the // copy_files field is wired through the JSON encoding/decoding for both the // HTTP and WS create-repository request shapes. Failure here means the diff --git a/apps/backend/internal/task/handlers/task_http_handlers.go b/apps/backend/internal/task/handlers/task_http_handlers.go index 740371dff3..47760909e9 100644 --- a/apps/backend/internal/task/handlers/task_http_handlers.go +++ b/apps/backend/internal/task/handlers/task_http_handlers.go @@ -455,7 +455,7 @@ type httpTaskRepositoryInput struct { // Fresh-branch flow (local executor only): when FreshBranch is true the // handler discards uncommitted changes in the local clone and creates - // NewBranchName from BaseBranch before the task is persisted. + // NewBranchName from BaseBranch after the task repository is persisted. // ConfirmDiscard must be true if the working tree is dirty; otherwise // the request is rejected with 409 + the dirty file list. // ConsentedDirtyFiles is the dirty-file list the UI showed the user; @@ -720,11 +720,15 @@ func (h *TaskHandlers) commitFreshBranch( // so skip the destructive checkout and the DELETE+INSERT rewrite. return true } - if !h.applyFreshBranch(c, title, inputs, repos) { - if delErr := h.service.DeleteTask(c.Request.Context(), taskID); delErr != nil { - h.logger.Warn("failed to compensate by deleting task after fresh-branch failure", - zap.String("task_id", taskID), zap.Error(delErr)) - } + task, err := h.service.GetTask(c.Request.Context(), taskID) + if err != nil { + h.logger.Error("failed to reload task repositories for fresh branch", zap.String("task_id", taskID), zap.Error(err)) + h.rollbackFreshBranchTask(c.Request.Context(), taskID) + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to resolve task repository"}) + return false + } + if !h.applyFreshBranch(c, title, inputs, repos, task.Repositories) { + h.rollbackFreshBranchTask(c.Request.Context(), taskID) return false } // Persist the rewritten BaseBranch (set by applyFreshBranch) onto the task. @@ -743,8 +747,16 @@ func (h *TaskHandlers) commitFreshBranch( return true } +func (h *TaskHandlers) rollbackFreshBranchTask(ctx context.Context, taskID string) { + if err := h.service.DeleteTask(ctx, taskID); err != nil { + h.logger.Warn("failed to compensate by deleting task after fresh-branch failure", + zap.String("task_id", taskID), zap.Error(err)) + } +} + // applyFreshBranch executes the fresh-branch flow for any local-executor -// repository inputs that opted in. Mutates `repos[i].BaseBranch` to the +// repository inputs that opted in, resolving each repository from the ordered +// rows persisted on the new task. Mutates `repos[i].BaseBranch` to the // newly-created branch on success so the persisted task uses it as the // effective base branch on every session resume. Writes the appropriate // HTTP error response and returns false on failure. @@ -752,24 +764,31 @@ func (h *TaskHandlers) commitFreshBranch( // When the caller doesn't supply NewBranchName, the backend generates a // semantic name from the task title (matching the worktree executor's // branch-naming) so the user only has to flip a switch. -func (h *TaskHandlers) applyFreshBranch(c *gin.Context, taskTitle string, inputs []httpTaskRepositoryInput, repos []dto.TaskRepositoryInput) bool { +func (h *TaskHandlers) applyFreshBranch( + c *gin.Context, + taskTitle string, + inputs []httpTaskRepositoryInput, + repos []dto.TaskRepositoryInput, + persisted []*models.TaskRepository, +) bool { ctx := c.Request.Context() for i, raw := range inputs { if !raw.FreshBranch { continue } - repoPath, ok := h.resolveLocalRepoPath(c, raw) - if !ok { + if i >= len(persisted) || persisted[i] == nil || persisted[i].RepositoryID == "" { + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to resolve task repository"}) return false } + repositoryID := persisted[i].RepositoryID baseBranch := raw.BaseBranch if baseBranch == "" { // User didn't pick one — fall back to the repo's checked-out branch. - baseBranch, _ = h.service.LocalRepositoryCurrentBranch(ctx, repoPath) + baseBranch, _ = h.service.RepositoryCurrentBranch(ctx, repositoryID) } newBranch := resolveFreshBranchName(raw.NewBranchName, taskTitle) err := h.service.PerformFreshBranch(ctx, service.FreshBranchRequest{ - RepoPath: repoPath, + RepositoryID: repositoryID, BaseBranch: baseBranch, NewBranch: newBranch, ConfirmDiscard: raw.ConfirmDiscard, @@ -797,22 +816,6 @@ func resolveFreshBranchName(rawNewBranch, taskTitle string) string { return worktree.SemanticWorktreeName(taskTitle, worktree.SmallSuffix(3)) } -func (h *TaskHandlers) resolveLocalRepoPath(c *gin.Context, raw httpTaskRepositoryInput) (string, bool) { - if raw.LocalPath != "" { - return raw.LocalPath, true - } - if raw.RepositoryID == "" { - c.JSON(http.StatusBadRequest, gin.H{"error": "fresh_branch requires repository_id or local_path"}) - return "", false - } - repo, err := h.service.GetRepository(c.Request.Context(), raw.RepositoryID) - if err != nil || repo == nil || repo.LocalPath == "" { - c.JSON(http.StatusBadRequest, gin.H{"error": "repository has no local path"}) - return "", false - } - return repo.LocalPath, true -} - func (h *TaskHandlers) respondFreshBranchError(c *gin.Context, err error) { var dirty *service.ErrDirtyWorkingTree if errors.As(err, &dirty) { @@ -822,10 +825,6 @@ func (h *TaskHandlers) respondFreshBranchError(c *gin.Context, err error) { }) return } - if errors.Is(err, service.ErrPathNotAllowed) { - c.JSON(http.StatusBadRequest, gin.H{"error": "repository path is not within an allowed root"}) - return - } if errors.Is(err, service.ErrInvalidGitRef) { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return diff --git a/apps/backend/internal/task/handlers/task_http_handlers_test.go b/apps/backend/internal/task/handlers/task_http_handlers_test.go index 8e417c949f..821b4cc376 100644 --- a/apps/backend/internal/task/handlers/task_http_handlers_test.go +++ b/apps/backend/internal/task/handlers/task_http_handlers_test.go @@ -6,6 +6,9 @@ import ( "errors" "net/http" "net/http/httptest" + "os" + "os/exec" + "path/filepath" "strconv" "strings" "sync" @@ -1049,6 +1052,149 @@ func TestResolveFreshBranchName(t *testing.T) { } } +type freshBranchIdentityRepository struct { + mockRepository + task *models.Task + taskRepos []*models.TaskRepository + repositories map[string]*models.Repository + listTaskErr error + deletedTask bool +} + +func (r *freshBranchIdentityRepository) GetTask(_ context.Context, _ string) (*models.Task, error) { + return r.task, nil +} + +func (r *freshBranchIdentityRepository) DeleteTask(_ context.Context, _ string) error { + r.deletedTask = true + return nil +} + +func (r *freshBranchIdentityRepository) ListTaskRepositories(_ context.Context, _ string) ([]*models.TaskRepository, error) { + return r.taskRepos, r.listTaskErr +} + +func (r *freshBranchIdentityRepository) GetRepository(_ context.Context, id string) (*models.Repository, error) { + repo, ok := r.repositories[id] + if !ok { + return nil, errors.New("repository not found") + } + return repo, nil +} + +func (r *freshBranchIdentityRepository) DeleteTaskRepositoriesByTask(_ context.Context, _ string) error { + r.taskRepos = nil + return nil +} + +func (r *freshBranchIdentityRepository) CreateTaskRepository(_ context.Context, taskRepo *models.TaskRepository) error { + r.taskRepos = append(r.taskRepos, taskRepo) + return nil +} + +func TestCommitFreshBranchUsesPersistedTaskRepositoryIdentity(t *testing.T) { + gin.SetMode(gin.TestMode) + realRepoPath := initHandlerGitRepository(t, filepath.Join(t.TempDir(), "real")) + decoyRepoPath := initHandlerGitRepository(t, filepath.Join(t.TempDir(), "decoy")) + repo := &freshBranchIdentityRepository{ + task: &models.Task{ID: "task-1", WorkspaceID: "ws-1"}, + taskRepos: []*models.TaskRepository{{ + ID: "task-repo-1", TaskID: "task-1", RepositoryID: "real-repo", BaseBranch: "main", Position: 0, + }}, + repositories: map[string]*models.Repository{ + "real-repo": {ID: "real-repo", WorkspaceID: "ws-1", Name: "real", SourceType: "local", LocalPath: realRepoPath}, + }, + } + log := newTestLogger(t) + svc := service.NewService(service.Repos{ + Workspaces: repo, Tasks: repo, TaskRepos: repo, Workflows: repo, + Messages: repo, Turns: repo, Sessions: repo, GitSnapshots: repo, + RepoEntities: repo, Executors: repo, Environments: repo, + TaskEnvironments: repo, Reviews: repo, + }, nil, log, service.RepositoryDiscoveryConfig{Roots: []string{filepath.Dir(decoyRepoPath)}}) + handler := &TaskHandlers{service: svc, logger: log} + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/tasks", nil) + inputs := []httpTaskRepositoryInput{{ + RepositoryID: "real-repo", LocalPath: decoyRepoPath, BaseBranch: "main", + FreshBranch: true, NewBranchName: "feature/identity", + }} + repos := []dto.TaskRepositoryInput{{RepositoryID: "real-repo", BaseBranch: "main", LocalPath: decoyRepoPath}} + + if ok := handler.commitFreshBranch(c, "task-1", "Identity", "ws-1", inputs, repos); !ok { + t.Fatalf("commitFreshBranch failed: status=%d body=%s", recorder.Code, recorder.Body.String()) + } + if branch := handlerGitCurrentBranch(t, realRepoPath); branch != "feature/identity" { + t.Fatalf("persisted repository branch = %q, want feature/identity", branch) + } + if branch := handlerGitCurrentBranch(t, decoyRepoPath); branch != "main" { + t.Fatalf("request path branch = %q, want unchanged main", branch) + } + if len(repo.taskRepos) != 1 || repo.taskRepos[0].BaseBranch != "feature/identity" { + t.Fatalf("persisted task repositories = %+v, want rewritten feature/identity branch", repo.taskRepos) + } +} + +func TestCommitFreshBranchRollsBackTaskWhenPersistedRepositoriesCannotBeLoaded(t *testing.T) { + gin.SetMode(gin.TestMode) + repo := &freshBranchIdentityRepository{ + task: &models.Task{ID: "task-1", WorkspaceID: "ws-1"}, + listTaskErr: errors.New("database unavailable"), + } + log := newTestLogger(t) + svc := service.NewService(service.Repos{ + Workspaces: repo, Tasks: repo, TaskRepos: repo, Workflows: repo, + Messages: repo, Turns: repo, Sessions: repo, GitSnapshots: repo, + RepoEntities: repo, Executors: repo, Environments: repo, + TaskEnvironments: repo, Reviews: repo, + }, nil, log, service.RepositoryDiscoveryConfig{}) + handler := &TaskHandlers{service: svc, logger: log} + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/tasks", nil) + inputs := []httpTaskRepositoryInput{{RepositoryID: "repo-1", FreshBranch: true}} + repos := []dto.TaskRepositoryInput{{RepositoryID: "repo-1"}} + + if ok := handler.commitFreshBranch(c, "task-1", "Identity", "ws-1", inputs, repos); ok { + t.Fatal("commitFreshBranch succeeded despite task repository load error") + } + if !repo.deletedTask { + t.Fatal("created task was not rolled back") + } +} + +func initHandlerGitRepository(t *testing.T, path string) string { + t.Helper() + if err := os.MkdirAll(path, 0o755); err != nil { + t.Fatalf("MkdirAll: %v", err) + } + for _, args := range [][]string{ + {"init", "-b", "main"}, + {"config", "user.email", "test@example.com"}, + {"config", "user.name", "Test"}, + {"commit", "--allow-empty", "-m", "init"}, + } { + cmd := exec.Command("git", args...) + cmd.Dir = path + if output, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git %v: %v: %s", args, err, output) + } + } + return path +} + +func handlerGitCurrentBranch(t *testing.T, path string) string { + t.Helper() + cmd := exec.Command("git", "rev-parse", "--abbrev-ref", "HEAD") + cmd.Dir = path + output, err := cmd.Output() + if err != nil { + t.Fatalf("git current branch: %v", err) + } + return strings.TrimSpace(string(output)) +} + func TestAssociatePRFromRepoInputs(t *testing.T) { log := newTestLogger(t) diff --git a/apps/backend/internal/task/service/fresh_branch.go b/apps/backend/internal/task/service/fresh_branch.go index 3458f1886c..f96c0f88ec 100644 --- a/apps/backend/internal/task/service/fresh_branch.go +++ b/apps/backend/internal/task/service/fresh_branch.go @@ -34,8 +34,9 @@ var ErrFreshBranchCheckout = errors.New("checkout failed") // hide the fact that some user work has already been destroyed. var ErrPartialDiscard = errors.New("partial discard: tracked changes were reset but git clean failed") -// FreshBranchRequest performs a destructive checkout on a local repository: -// discard uncommitted changes, then create NewBranch from BaseBranch. +// FreshBranchRequest performs a destructive checkout on a saved local +// repository: discard uncommitted changes, then create NewBranch from +// BaseBranch. RepositoryID is resolved to its persisted exact-path grant. // // ConsentedDirtyFiles is the dirty-file list the caller already showed to // the user. The backend re-reads dirty files at execution time and rejects @@ -43,7 +44,7 @@ var ErrPartialDiscard = errors.New("partial discard: tracked changes were reset // consented list — this protects against silent loss of files that became // dirty between the consent dialog and the actual discard. type FreshBranchRequest struct { - RepoPath string + RepositoryID string BaseBranch string NewBranch string ConfirmDiscard bool @@ -82,7 +83,7 @@ func (s *Service) PerformFreshBranch(ctx context.Context, req FreshBranchRequest if err != nil { return err } - absPath, err := s.resolveAllowedLocalPath(req.RepoPath) + absPath, err := s.resolveRepositoryLocalPath(ctx, req.RepositoryID) if err != nil { return err } diff --git a/apps/backend/internal/task/service/fresh_branch_test.go b/apps/backend/internal/task/service/fresh_branch_test.go index 2ffe97a407..39d1f68d33 100644 --- a/apps/backend/internal/task/service/fresh_branch_test.go +++ b/apps/backend/internal/task/service/fresh_branch_test.go @@ -8,6 +8,8 @@ import ( "path/filepath" "strings" "testing" + + "github.com/kandev/kandev/internal/task/models" ) func TestPerformFreshBranch_CleanWorkingTree(t *testing.T) { @@ -17,10 +19,11 @@ func TestPerformFreshBranch_CleanWorkingTree(t *testing.T) { initRealGitRepo(t, repoPath) svc := newDiscoveryService(t, root) + repositoryID := persistFreshBranchRepository(t, svc, repoPath) err := svc.PerformFreshBranch(context.Background(), FreshBranchRequest{ - RepoPath: repoPath, - BaseBranch: "main", - NewBranch: "feature/x", + RepositoryID: repositoryID, + BaseBranch: "main", + NewBranch: "feature/x", }) if err != nil { t.Fatalf("PerformFreshBranch error: %v", err) @@ -38,10 +41,11 @@ func TestPerformFreshBranch_DirtyWithoutConfirm(t *testing.T) { writeDirty(t, repoPath, "untracked.txt", "hi") svc := newDiscoveryService(t, root) + repositoryID := persistFreshBranchRepository(t, svc, repoPath) err := svc.PerformFreshBranch(context.Background(), FreshBranchRequest{ - RepoPath: repoPath, - BaseBranch: "main", - NewBranch: "feature/x", + RepositoryID: repositoryID, + BaseBranch: "main", + NewBranch: "feature/x", }) var dirty *ErrDirtyWorkingTree if !errors.As(err, &dirty) { @@ -68,8 +72,9 @@ func TestPerformFreshBranch_DirtyWithConfirm(t *testing.T) { writeDirty(t, repoPath, "untracked.txt", "hi") svc := newDiscoveryService(t, root) + repositoryID := persistFreshBranchRepository(t, svc, repoPath) err := svc.PerformFreshBranch(context.Background(), FreshBranchRequest{ - RepoPath: repoPath, + RepositoryID: repositoryID, BaseBranch: "main", NewBranch: "feature/x", ConfirmDiscard: true, @@ -95,8 +100,9 @@ func TestPerformFreshBranch_DirtyWithExtraUnconsented(t *testing.T) { writeDirty(t, repoPath, "extra.txt", "hi") svc := newDiscoveryService(t, root) + repositoryID := persistFreshBranchRepository(t, svc, repoPath) err := svc.PerformFreshBranch(context.Background(), FreshBranchRequest{ - RepoPath: repoPath, + RepositoryID: repositoryID, BaseBranch: "main", NewBranch: "feature/x", ConfirmDiscard: true, @@ -139,10 +145,11 @@ func TestPerformFreshBranch_RefusesExistingBranch(t *testing.T) { } svc := newDiscoveryService(t, root) + repositoryID := persistFreshBranchRepository(t, svc, repoPath) err := svc.PerformFreshBranch(context.Background(), FreshBranchRequest{ - RepoPath: repoPath, - BaseBranch: "main", - NewBranch: "feature/existing", + RepositoryID: repositoryID, + BaseBranch: "main", + NewBranch: "feature/existing", }) if err == nil { t.Fatal("expected PerformFreshBranch to refuse overwriting an existing branch") @@ -156,13 +163,14 @@ func TestPerformFreshBranch_RejectsFlagLikeRefs(t *testing.T) { initRealGitRepo(t, repoPath) svc := newDiscoveryService(t, root) + repositoryID := persistFreshBranchRepository(t, svc, repoPath) if err := svc.PerformFreshBranch(context.Background(), FreshBranchRequest{ - RepoPath: repoPath, BaseBranch: "main", NewBranch: "--upload-pack=evil", + RepositoryID: repositoryID, BaseBranch: "main", NewBranch: "--upload-pack=evil", }); err == nil { t.Fatal("expected rejection for ref starting with --") } if err := svc.PerformFreshBranch(context.Background(), FreshBranchRequest{ - RepoPath: repoPath, BaseBranch: "-flag", NewBranch: "feature/x", + RepositoryID: repositoryID, BaseBranch: "-flag", NewBranch: "feature/x", }); err == nil { t.Fatal("expected rejection for ref starting with -") } @@ -175,13 +183,14 @@ func TestPerformFreshBranch_RejectsEmptyFields(t *testing.T) { initRealGitRepo(t, repoPath) svc := newDiscoveryService(t, root) + repositoryID := persistFreshBranchRepository(t, svc, repoPath) if err := svc.PerformFreshBranch(context.Background(), FreshBranchRequest{ - RepoPath: repoPath, NewBranch: "feature/x", + RepositoryID: repositoryID, NewBranch: "feature/x", }); err == nil { t.Fatal("expected error for empty BaseBranch") } if err := svc.PerformFreshBranch(context.Background(), FreshBranchRequest{ - RepoPath: repoPath, BaseBranch: "main", + RepositoryID: repositoryID, BaseBranch: "main", }); err == nil { t.Fatal("expected error for empty NewBranch") } @@ -206,6 +215,22 @@ func TestLocalRepositoryStatus_CleanRepo(t *testing.T) { } } +func TestLocalRepositoryStatus_ExplicitPathOutsideDiscoveryRoots(t *testing.T) { + isolateGitEnvForTest(t) + discoveryRoot := t.TempDir() + repoPath := filepath.Join(t.TempDir(), "explicit-repo") + initRealGitRepo(t, repoPath) + + svc := newDiscoveryService(t, discoveryRoot) + status, err := svc.LocalRepositoryStatus(context.Background(), repoPath) + if err != nil { + t.Fatalf("LocalRepositoryStatus: %v", err) + } + if status.CurrentBranch != "main" { + t.Fatalf("CurrentBranch = %q, want main", status.CurrentBranch) + } +} + func TestLocalRepositoryStatus_HandlesSpacesAndRenames(t *testing.T) { isolateGitEnvForTest(t) root := t.TempDir() @@ -353,3 +378,19 @@ func isolateGitEnvForTest(t *testing.T) { } } } + +func persistFreshBranchRepository(t *testing.T, svc *Service, repoPath string) string { + t.Helper() + ctx := context.Background() + const workspaceID = "fresh-branch-workspace" + const repositoryID = "fresh-branch-repository" + if err := svc.workspaces.CreateWorkspace(ctx, &models.Workspace{ID: workspaceID, Name: "Workspace"}); err != nil { + t.Fatalf("CreateWorkspace: %v", err) + } + if err := svc.repoEntities.CreateRepository(ctx, &models.Repository{ + ID: repositoryID, WorkspaceID: workspaceID, Name: "Repository", SourceType: sourceTypeLocal, LocalPath: repoPath, + }); err != nil { + t.Fatalf("CreateRepository: %v", err) + } + return repositoryID +} diff --git a/apps/backend/internal/task/service/repository_discovery.go b/apps/backend/internal/task/service/repository_discovery.go index 977a8b4d66..c471bfeeed 100644 --- a/apps/backend/internal/task/service/repository_discovery.go +++ b/apps/backend/internal/task/service/repository_discovery.go @@ -56,6 +56,8 @@ type RepositoryPathValidation struct { var ErrPathNotAllowed = errors.New("path is not within an allowed root") +var ErrInvalidRepositoryPath = errors.New("invalid repository path") + // gitHEAD is the HEAD git ref. const gitHEAD = "HEAD" @@ -108,43 +110,156 @@ func (s *Service) DiscoverLocalRepositories(ctx context.Context, root string) (R } func (s *Service) ValidateLocalRepositoryPath(ctx context.Context, path string) (RepositoryPathValidation, error) { - absPath, err := filepath.Abs(path) + absPath, err := filepath.Abs(filepath.Clean(path)) if err != nil { return RepositoryPathValidation{}, fmt.Errorf("invalid path: %w", err) } - roots := s.discoveryRoots() - allowed := isPathAllowed(absPath, roots) - info, statErr := os.Stat(absPath) - exists := statErr == nil - isDir := exists && info.IsDir() - isGit := false - defaultBranch := "" - message := "" - - switch { - case !allowed: - message = "Path is outside the allowed roots" - case !exists: - message = "Path does not exist" - case !isDir: - message = "Path is not a directory" - default: - var gitErr error - defaultBranch, gitErr = readGitDefaultBranch(absPath) - isGit = gitErr == nil - if !isGit { - message = "Not a git repository" - } + result := RepositoryPathValidation{Path: absPath, Allowed: true} + canonicalPath, defaultBranch, resolveErr := resolveExplicitLocalRepositoryPath(absPath) + if resolveErr == nil { + result.Path = canonicalPath + result.Exists = true + result.IsGitRepo = true + result.DefaultBranch = defaultBranch + return result, nil } - return RepositoryPathValidation{ - Path: absPath, - Exists: exists, - IsGitRepo: isGit, - Allowed: allowed, - DefaultBranch: defaultBranch, - Message: message, - }, nil + // codeql[go/path-injection] Intentional read-only diagnostics for the local path selected by the user. + info, statErr := os.Stat(absPath) + result.Exists = statErr == nil + switch { + case errors.Is(statErr, os.ErrNotExist): + result.Message = "Path does not exist" + case statErr != nil: + result.Message = "Path cannot be accessed" + case !info.IsDir(): + result.Message = "Path is not a directory" + default: + result.Message = "Not a git repository" + } + return result, nil +} + +// resolveExplicitLocalRepositoryPath validates a path the user selected +// directly. Discovery roots intentionally do not apply to explicit choices. +func resolveExplicitLocalRepositoryPath(repoPath string) (string, string, error) { + if repoPath == "" { + return "", "", fmt.Errorf("%w: path is required", ErrInvalidRepositoryPath) + } + absPath, err := filepath.Abs(filepath.Clean(repoPath)) + if err != nil { + return "", "", fmt.Errorf("%w: %v", ErrInvalidRepositoryPath, err) + } + canonicalPath, err := filepath.EvalSymlinks(absPath) + if err != nil { + return "", "", fmt.Errorf("%w: %v", ErrInvalidRepositoryPath, err) + } + // codeql[go/path-injection] Intentional validation of the canonical local repository selected by the user. + info, err := os.Stat(canonicalPath) + if err != nil { + return "", "", fmt.Errorf("%w: %v", ErrInvalidRepositoryPath, err) + } + if !info.IsDir() { + return "", "", fmt.Errorf("%w: path is not a directory", ErrInvalidRepositoryPath) + } + if err := validateExplicitGitMetadata(canonicalPath); err != nil { + return "", "", fmt.Errorf("%w: %v", ErrInvalidRepositoryPath, err) + } + defaultBranch, err := readGitDefaultBranch(canonicalPath) + if err != nil { + return "", "", fmt.Errorf("%w: not a git repository", ErrInvalidRepositoryPath) + } + return filepath.Clean(canonicalPath), defaultBranch, nil +} + +// validateExplicitGitMetadata rejects metadata indirection that does not prove +// it belongs to the selected repository. A real linked worktree has a .git +// pointer whose target contains both a reciprocal gitdir pointer and a +// commondir placing that target under /worktrees. Without those +// checks, a crafted folder could borrow another repository's .git directory +// and turn an exact-path grant into permission to mutate unrelated Git refs. +func validateExplicitGitMetadata(repoPath string) error { + gitPath := filepath.Join(repoPath, ".git") + // codeql[go/path-injection] The canonical repository path is validated before inspecting its exact .git child. + info, err := os.Lstat(gitPath) + if err != nil { + return err + } + if info.Mode()&os.ModeSymlink != 0 { + return errors.New(".git metadata must not be a symbolic link") + } + if info.IsDir() { + return validateStandaloneGitMetadata(gitPath) + } + if !info.Mode().IsRegular() { + return errors.New(".git metadata must be a directory or linked-worktree pointer") + } + return validateLinkedWorktreeMetadata(repoPath, gitPath) +} + +func validateStandaloneGitMetadata(gitPath string) error { + // codeql[go/path-injection] gitPath is the validated repository's real, non-symlink .git directory. + if _, err := os.Lstat(filepath.Join(gitPath, "commondir")); err == nil { + return errors.New("standalone .git metadata must not redirect its common directory") + } else if !errors.Is(err, os.ErrNotExist) { + return err + } + return nil +} + +func validateLinkedWorktreeMetadata(repoPath, gitPath string) error { + gitDir, err := resolveGitDir(repoPath) + if err != nil { + return err + } + canonicalGitDir, err := filepath.EvalSymlinks(gitDir) + if err != nil { + return err + } + canonicalGitFile, err := filepath.EvalSymlinks(gitPath) + if err != nil { + return err + } + + backPointer, err := readMetadataPath(filepath.Join(canonicalGitDir, "gitdir"), canonicalGitDir) + if err != nil { + return errors.New(".git pointer is not a linked worktree") + } + if !sameCanonicalPath(backPointer, canonicalGitFile) { + return errors.New("linked-worktree metadata does not point back to the selected repository") + } + + commonDir, err := readMetadataPath(filepath.Join(canonicalGitDir, "commondir"), canonicalGitDir) + if err != nil { + return errors.New("linked-worktree metadata has no valid common directory") + } + worktreesDir := filepath.Join(commonDir, "worktrees") + rel, err := filepath.Rel(worktreesDir, canonicalGitDir) + if err != nil || rel == "." || rel == ".." || filepath.Dir(rel) != "." { + return errors.New("linked-worktree metadata is outside its common directory") + } + return nil +} + +func readMetadataPath(path, relativeTo string) (string, error) { + // codeql[go/path-injection] Linked-worktree metadata is canonicalized and verified by reciprocal pointers. + content, err := os.ReadFile(path) + if err != nil { + return "", err + } + metadataPath := strings.TrimSpace(string(content)) + if metadataPath == "" { + return "", errors.New("metadata path is empty") + } + if !filepath.IsAbs(metadataPath) { + metadataPath = filepath.Join(relativeTo, metadataPath) + } + return filepath.EvalSymlinks(filepath.Clean(metadataPath)) +} + +func sameCanonicalPath(left, right string) bool { + rel, err := filepath.Rel(left, right) + return err == nil && rel == "." } // BranchListResult bundles a branch list with the currently-checked-out @@ -198,7 +313,7 @@ func (s *Service) ListBranchesWithCurrent(ctx context.Context, repoID, path stri // HEAD is detached or unreadable. return BranchListResult{ Branches: branches, - CurrentBranch: readGitCurrentBranch(resolved, s.discoveryRoots()), + CurrentBranch: readExplicitGitCurrentBranch(resolved), }, nil } @@ -232,42 +347,68 @@ func (s *Service) listRemoteBranchesIfApplicable(ctx context.Context, repoID str return branches, true, err } -// resolveBranchListingPath turns the request inputs into a validated -// absolute path to list branches in. Both inputs go through the same -// allowed-roots / dir / symlink validation via resolveAllowedLocalPath. +// resolveBranchListingPath turns the request inputs into a validated, +// canonical path to list branches in. A repository ID resolves the durable +// path grant stored on the repository; a raw path is an explicit read-only +// pre-registration probe. Discovery roots do not authorize either case. func (s *Service) resolveBranchListingPath(ctx context.Context, repoID, path string) (string, error) { switch { case repoID != "": - repo, err := s.repoEntities.GetRepository(ctx, repoID) - if err != nil { - return "", err - } - if repo.LocalPath == "" { - return "", fmt.Errorf("repository local path is empty") - } - path = repo.LocalPath + return s.resolveRepositoryLocalPath(ctx, repoID) case path == "": return "", fmt.Errorf("repository_id or path is required") } - return s.resolveAllowedLocalPath(path) + resolved, _, err := resolveExplicitLocalRepositoryPath(path) + return resolved, err +} + +func (s *Service) resolveRepositoryLocalPath(ctx context.Context, repoID string) (string, error) { + if repoID == "" { + return "", errors.New("repository ID is required") + } + repo, err := s.repoEntities.GetRepository(ctx, repoID) + if err != nil { + return "", err + } + if repo.LocalPath == "" { + return "", errors.New("repository local path is empty") + } + resolved, _, err := resolveExplicitLocalRepositoryPath(repo.LocalPath) + if err != nil { + return "", err + } + if !sameCanonicalPath(filepath.Clean(repo.LocalPath), resolved) { + return "", fmt.Errorf("%w: saved repository path resolves to a different location", ErrInvalidRepositoryPath) + } + return resolved, nil +} + +// RepositoryCurrentBranch returns the current branch for a saved repository, +// resolving its exact path grant by repository ID. +func (s *Service) RepositoryCurrentBranch(ctx context.Context, repoID string) (string, error) { + resolved, err := s.resolveRepositoryLocalPath(ctx, repoID) + if err != nil { + return "", err + } + return readExplicitGitCurrentBranch(resolved), nil } // LocalRepositoryCurrentBranch returns the currently checked-out branch for a // local repository on disk. Returns the branch name (e.g. "main") or an empty // string if HEAD is detached or unreadable. func (s *Service) LocalRepositoryCurrentBranch(ctx context.Context, path string) (string, error) { - absPath, err := s.resolveAllowedLocalPath(path) + absPath, _, err := resolveExplicitLocalRepositoryPath(path) if err != nil { return "", err } - return readGitCurrentBranch(absPath, s.discoveryRoots()), nil + return readExplicitGitCurrentBranch(absPath), nil } // LocalRepositoryStatus returns the current branch and dirty file list for a // local repository on disk. Used by the task-create dialog to preflight the // fresh-branch flow before committing to a destructive checkout. func (s *Service) LocalRepositoryStatus(ctx context.Context, path string) (LocalRepoStatus, error) { - absPath, err := s.resolveAllowedLocalPath(path) + absPath, _, err := resolveExplicitLocalRepositoryPath(path) if err != nil { return LocalRepoStatus{}, err } @@ -276,75 +417,26 @@ func (s *Service) LocalRepositoryStatus(ctx context.Context, path string) (Local return LocalRepoStatus{}, err } return LocalRepoStatus{ - CurrentBranch: readGitCurrentBranch(absPath, s.discoveryRoots()), + CurrentBranch: readExplicitGitCurrentBranch(absPath), DirtyFiles: dirty, }, nil } -func (s *Service) resolveAllowedLocalPath(repoPath string) (string, error) { - if repoPath == "" { - return "", fmt.Errorf("repository path is required") - } - roots := s.discoveryRoots() - abs, err := filepath.Abs(filepath.Clean(repoPath)) +// readExplicitGitCurrentBranch preserves linked-worktree support: an explicit +// repository's .git file may legitimately point at metadata outside the +// worktree directory. The repository has already passed Git validation before +// this helper is called, so its resolved metadata directory is trusted for the +// narrow HEAD read. +func readExplicitGitCurrentBranch(repoPath string) string { + gitDir, err := resolveGitDir(repoPath) if err != nil { - return "", fmt.Errorf("invalid repository path: %w", err) + return "" } - // Resolve symlinks before the allowlist check so that OS-level symlinks - // (e.g. /var -> /private/var on macOS) don't produce false negatives. - // normalizeRoots already resolves symlinks on the roots themselves, so both - // sides of the comparison are canonical after this step. - resolved, err := filepath.EvalSymlinks(abs) + canonicalGitDir, err := filepath.EvalSymlinks(gitDir) if err != nil { - return "", err + return "" } - safe, err := pathWithinRoots(filepath.Clean(resolved), roots) - if err != nil { - return "", err - } - info, err := os.Stat(safe) - if err != nil { - return "", err - } - if !info.IsDir() { - return "", fmt.Errorf("repository path is not a directory") - } - return safe, nil -} - -// pathWithinRoots returns abs only when it sits inside one of the allowed -// roots after resolving relative segments. The returned string is the -// trusted, validated path; callers should never use the original input for -// subsequent file operations. -// -// Each root is also passed through filepath.EvalSymlinks before comparison so -// that OS-level symlinks (e.g. /var -> /private/var on macOS) do not produce -// false negatives when abs was obtained via EvalSymlinks but the stored root -// was not. -func pathWithinRoots(abs string, roots []string) (string, error) { - for _, root := range roots { - if root == "" { - continue - } - // Resolve symlinks on the root so both sides of the comparison are - // canonical. Ignore errors — if the root itself doesn't exist we skip it. - canonRoot := root - if r, err := filepath.EvalSymlinks(root); err == nil { - canonRoot = r - } - rel, err := filepath.Rel(canonRoot, abs) - if err != nil { - continue - } - if rel == "." { - return abs, nil - } - if rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { - continue - } - return abs, nil - } - return "", ErrPathNotAllowed + return readGitCurrentBranch(repoPath, []string{canonicalGitDir}) } func (s *Service) discoveryRoots() []string { @@ -528,14 +620,11 @@ func isWithinRoot(path string, root string) bool { } absPath = filepath.Clean(absPath) absRoot = filepath.Clean(absRoot) - if absPath == absRoot { - return true + rel, err := filepath.Rel(absRoot, absPath) + if err != nil { + return false } - separator := string(os.PathSeparator) - if !strings.HasSuffix(absRoot, separator) { - absRoot += separator - } - return strings.HasPrefix(absPath, absRoot) + return rel == "." || (rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator))) } // readGitCurrentBranch returns the currently checked-out branch by reading diff --git a/apps/backend/internal/task/service/repository_discovery_test.go b/apps/backend/internal/task/service/repository_discovery_test.go index 0f3b20ab3a..3d362990a6 100644 --- a/apps/backend/internal/task/service/repository_discovery_test.go +++ b/apps/backend/internal/task/service/repository_discovery_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "os" + "os/exec" "path/filepath" "sort" "strings" @@ -64,11 +65,21 @@ func TestValidateLocalRepositoryPath(t *testing.T) { if err != nil { t.Fatalf("ValidateLocalRepositoryPath outside error: %v", err) } - if outside.Allowed { - t.Fatalf("expected outside path to be disallowed") + if !outside.Allowed || !outside.Exists || !outside.IsGitRepo { + t.Fatalf("expected explicit outside repository to validate, got %+v", outside) } - if outside.Message != "Path is outside the allowed roots" { - t.Fatalf("expected outside message, got %q", outside.Message) + if outside.Message != "" { + t.Fatalf("expected no outside-root validation message, got %q", outside.Message) + } + + discovered, err := svc.DiscoverLocalRepositories(context.Background(), "") + if err != nil { + t.Fatalf("DiscoverLocalRepositories error: %v", err) + } + for _, repo := range discovered.Repositories { + if repo.Path == outside.Path { + t.Fatalf("explicit validation widened automatic discovery to %q", repo.Path) + } } missingPath := filepath.Join(root, "missing") @@ -695,6 +706,158 @@ func TestListBranches_RoutesProviderRepoToRemoteLister(t *testing.T) { } } +func TestListBranches_SavedRepositoryOutsideDiscoveryRoots(t *testing.T) { + isolateGitEnvForTest(t) + discoveryRoot := t.TempDir() + repoPath := filepath.Join(t.TempDir(), "explicit-repo") + initRealGitRepo(t, repoPath) + + svc := newDiscoveryService(t, discoveryRoot) + ctx := context.Background() + if err := svc.workspaces.CreateWorkspace(ctx, &models.Workspace{ID: "ws-1", Name: "Workspace"}); err != nil { + t.Fatalf("CreateWorkspace: %v", err) + } + if err := svc.repoEntities.CreateRepository(ctx, &models.Repository{ + ID: "outside-repo", WorkspaceID: "ws-1", Name: "outside", SourceType: sourceTypeLocal, LocalPath: repoPath, + }); err != nil { + t.Fatalf("CreateRepository: %v", err) + } + + result, err := svc.ListBranchesWithCurrent(ctx, "outside-repo", "") + if err != nil { + t.Fatalf("ListBranchesWithCurrent by repository ID: %v", err) + } + if len(result.Branches) != 1 || result.Branches[0].Name != "main" { + t.Fatalf("branches = %+v, want main", result.Branches) + } + if result.CurrentBranch != "main" { + t.Fatalf("CurrentBranch = %q, want main", result.CurrentBranch) + } +} + +func TestSavedRepositoryRejectsRetargetedCanonicalPath(t *testing.T) { + isolateGitEnvForTest(t) + originalPath := filepath.Join(t.TempDir(), "saved-repo") + initRealGitRepo(t, originalPath) + + svc := newDiscoveryService(t, t.TempDir()) + ctx := context.Background() + if err := svc.workspaces.CreateWorkspace(ctx, &models.Workspace{ID: "ws-1", Name: "Workspace"}); err != nil { + t.Fatalf("CreateWorkspace: %v", err) + } + created, err := svc.CreateRepository(ctx, &CreateRepositoryRequest{ + WorkspaceID: "ws-1", Name: "saved", SourceType: sourceTypeLocal, LocalPath: originalPath, + }) + if err != nil { + t.Fatalf("CreateRepository: %v", err) + } + + movedPath := originalPath + "-moved" + if err := os.Rename(originalPath, movedPath); err != nil { + t.Fatalf("Rename saved repository: %v", err) + } + victimPath := filepath.Join(t.TempDir(), "victim-repo") + initRealGitRepo(t, victimPath) + if err := os.Symlink(victimPath, originalPath); err != nil { + t.Skipf("symlink creation unavailable: %v", err) + } + + t.Run("identity-bound read", func(t *testing.T) { + if _, err := svc.ListBranchesWithCurrent(ctx, created.ID, ""); err == nil { + t.Fatal("expected saved repository read to reject a retargeted canonical path") + } + }) + t.Run("identity-bound mutation", func(t *testing.T) { + err := svc.PerformFreshBranch(ctx, FreshBranchRequest{ + RepositoryID: created.ID, + BaseBranch: "main", + NewBranch: "feature/retargeted", + }) + if err == nil { + t.Fatal("expected fresh branch to reject a retargeted canonical path") + } + cmd := exec.Command("git", "show-ref", "--verify", "--quiet", "refs/heads/feature/retargeted") + cmd.Dir = victimPath + cmd.Env = isolatedGitEnv() + if err := cmd.Run(); err == nil { + t.Fatal("fresh branch mutated the retargeted repository") + } + }) +} + +func TestListBranches_RawExplicitPathOutsideDiscoveryRoots(t *testing.T) { + isolateGitEnvForTest(t) + discoveryRoot := t.TempDir() + repoPath := filepath.Join(t.TempDir(), "explicit-repo") + initRealGitRepo(t, repoPath) + + svc := newDiscoveryService(t, discoveryRoot) + branches, err := svc.ListBranches(context.Background(), "", repoPath) + if err != nil { + t.Fatalf("ListBranches by explicit path: %v", err) + } + if len(branches) != 1 || branches[0].Name != "main" { + t.Fatalf("branches = %+v, want main", branches) + } +} + +func TestListBranches_SavedLinkedWorktreeOutsideDiscoveryRoots(t *testing.T) { + isolateGitEnvForTest(t) + primaryPath := filepath.Join(t.TempDir(), "primary") + linkedPath := filepath.Join(t.TempDir(), "linked") + initRealGitRepo(t, primaryPath) + cmd := exec.Command("git", "worktree", "add", "-b", "linked", linkedPath, "main") + cmd.Dir = primaryPath + cmd.Env = isolatedGitEnv() + if output, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git worktree add: %v: %s", err, output) + } + + svc := newDiscoveryService(t, t.TempDir()) + ctx := context.Background() + if err := svc.workspaces.CreateWorkspace(ctx, &models.Workspace{ID: "ws-1", Name: "Workspace"}); err != nil { + t.Fatalf("CreateWorkspace: %v", err) + } + if err := svc.repoEntities.CreateRepository(ctx, &models.Repository{ + ID: "linked-repo", WorkspaceID: "ws-1", Name: "linked", SourceType: sourceTypeLocal, LocalPath: linkedPath, + }); err != nil { + t.Fatalf("CreateRepository: %v", err) + } + + result, err := svc.ListBranchesWithCurrent(ctx, "linked-repo", "") + if err != nil { + t.Fatalf("ListBranchesWithCurrent: %v", err) + } + if result.CurrentBranch != "linked" { + t.Fatalf("CurrentBranch = %q, want linked", result.CurrentBranch) + } +} + +func TestValidateLinkedWorktreeMetadataRejectsSelfReferentialCommonDir(t *testing.T) { + repoPath := filepath.Join(t.TempDir(), "linked") + gitDir := filepath.Join(t.TempDir(), "metadata") + if err := os.MkdirAll(repoPath, 0o755); err != nil { + t.Fatalf("MkdirAll repo: %v", err) + } + if err := os.MkdirAll(gitDir, 0o755); err != nil { + t.Fatalf("MkdirAll metadata: %v", err) + } + gitPath := filepath.Join(repoPath, ".git") + if err := os.WriteFile(gitPath, []byte("gitdir: "+gitDir+"\n"), 0o600); err != nil { + t.Fatalf("WriteFile .git: %v", err) + } + if err := os.WriteFile(filepath.Join(gitDir, "gitdir"), []byte(gitPath+"\n"), 0o600); err != nil { + t.Fatalf("WriteFile gitdir: %v", err) + } + if err := os.WriteFile(filepath.Join(gitDir, "commondir"), []byte(".\n"), 0o600); err != nil { + t.Fatalf("WriteFile commondir: %v", err) + } + + if err := validateLinkedWorktreeMetadata(repoPath, gitPath); err == nil { + t.Fatal("expected self-referential common directory to be rejected") + } +} + func TestListBranches_FallsThroughWhenNoRemoteListerWired(t *testing.T) { svc, _, repo := createTestService(t) ctx := context.Background() diff --git a/apps/backend/internal/task/service/repository_discovery_windows_test.go b/apps/backend/internal/task/service/repository_discovery_windows_test.go new file mode 100644 index 0000000000..cc40c227f2 --- /dev/null +++ b/apps/backend/internal/task/service/repository_discovery_windows_test.go @@ -0,0 +1,70 @@ +package service + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +func TestExplicitLocalRepositoryWindowsPathSemantics(t *testing.T) { + base := t.TempDir() + discoveryRoot := filepath.Join(base, "Discovery") + if err := os.MkdirAll(discoveryRoot, 0o755); err != nil { + t.Fatalf("create discovery root: %v", err) + } + + repoPath := filepath.Join(base, "External", "Repo") + if err := os.MkdirAll(repoPath, 0o755); err != nil { + t.Fatalf("create repository directory: %v", err) + } + cmd := exec.Command("git", "init", "-b", "main", ".") + cmd.Dir = repoPath + if output, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("initialize repository: %v\n%s", err, output) + } + + svc := newDiscoveryService(t, discoveryRoot) + explicitPath := windowsPathVariant(repoPath, true) + "/" + validation, err := svc.ValidateLocalRepositoryPath(context.Background(), explicitPath) + if err != nil { + t.Fatalf("validate explicit repository: %v", err) + } + if !validation.Exists || !validation.IsGitRepo || !validation.Allowed { + t.Fatalf("expected explicit repository outside discovery roots to validate: %+v", validation) + } + if validation.DefaultBranch != "main" { + t.Fatalf("expected main default branch, got %q", validation.DefaultBranch) + } + + discovered, err := svc.DiscoverLocalRepositories(context.Background(), "") + if err != nil { + t.Fatalf("discover repositories: %v", err) + } + if len(discovered.Repositories) != 0 { + t.Fatalf("explicit validation must not widen discovery roots: %+v", discovered.Repositories) + } + + containedPath := filepath.Join(discoveryRoot, "Nested", "Repository") + rootVariant := windowsPathVariant(discoveryRoot, true) + "/" + if !isWithinRoot(containedPath, rootVariant) { + t.Fatalf("expected mixed-case drive and separator variant to remain within %q", rootVariant) + } + if !isWithinRoot(windowsPathVariant(discoveryRoot, true)+"/", discoveryRoot) { + t.Fatal("expected trailing separator and drive-letter casing to preserve path equality") + } + if isWithinRoot(filepath.Join(base, "Discovery-sibling"), discoveryRoot) { + t.Fatal("sibling prefix must not be treated as contained") + } +} + +func windowsPathVariant(path string, lowercaseDrive bool) string { + volume := filepath.VolumeName(path) + if lowercaseDrive { + volume = strings.ToLower(volume) + } + path = volume + strings.TrimPrefix(path, filepath.VolumeName(path)) + return strings.ReplaceAll(path, `\`, "/") +} diff --git a/apps/backend/internal/task/service/repository_fetch.go b/apps/backend/internal/task/service/repository_fetch.go index 55763acdba..0f6c56c954 100644 --- a/apps/backend/internal/task/service/repository_fetch.go +++ b/apps/backend/internal/task/service/repository_fetch.go @@ -2,11 +2,9 @@ package service import ( "context" - "errors" "fmt" "os" "os/exec" - "path/filepath" "sync" "time" @@ -133,33 +131,12 @@ func newNonInteractiveGitFetchCmd(ctx context.Context, repoPath string) *exec.Cm // RefreshRepositoryBranches resolves the repository's local path and runs // `git fetch` for it, subject to a per-repository cooldown and single-flight -// deduplication. Returns ErrPathNotAllowed when the repository's path is not -// inside an allowed discovery root. +// deduplication. The persisted repository path is the durable exact-path grant; +// discovery roots only constrain automatic scanning. func (s *Service) RefreshRepositoryBranches(ctx context.Context, repoID string) (BranchRefreshResult, error) { - repo, err := s.repoEntities.GetRepository(ctx, repoID) + localPath, err := s.resolveRepositoryLocalPath(ctx, repoID) if err != nil { return BranchRefreshResult{}, err } - return s.RefreshBranchesAtPath(ctx, repo.LocalPath) -} - -// RefreshBranchesAtPath validates an already-resolved repository path and runs -// `git fetch` for it, subject to the same cooldown and single-flight as -// RefreshRepositoryBranches. Use this when the caller already has the path in -// hand to avoid a redundant repository lookup. -func (s *Service) RefreshBranchesAtPath(ctx context.Context, localPath string) (BranchRefreshResult, error) { - if localPath == "" { - return BranchRefreshResult{}, errors.New("repository local path is empty") - } - absPath, err := filepath.Abs(localPath) - if err != nil { - return BranchRefreshResult{}, fmt.Errorf("invalid repository path: %w", err) - } - if !isPathAllowed(absPath, s.discoveryRoots()) { - return BranchRefreshResult{}, ErrPathNotAllowed - } - if info, statErr := os.Stat(absPath); statErr != nil || !info.IsDir() { - return BranchRefreshResult{}, errors.New("repository path is not a directory") - } - return s.branchFetcher.Fetch(ctx, absPath), nil + return s.branchFetcher.Fetch(ctx, localPath), nil } diff --git a/apps/backend/internal/task/service/repository_fetch_test.go b/apps/backend/internal/task/service/repository_fetch_test.go index 9f9943ae93..134e1534dc 100644 --- a/apps/backend/internal/task/service/repository_fetch_test.go +++ b/apps/backend/internal/task/service/repository_fetch_test.go @@ -7,6 +7,8 @@ import ( "path/filepath" "sync" "testing" + + "github.com/kandev/kandev/internal/task/models" ) // TestBranchFetcher_CooldownSkipsRepeatedFetches verifies that a second call @@ -138,3 +140,32 @@ func makeRepoWithCommit(t *testing.T, path string) string { } return path } + +func TestRefreshRepositoryBranches_SavedRepositoryOutsideDiscoveryRoots(t *testing.T) { + isolateGitEnvForTest(t) + discoveryRoot := t.TempDir() + repoPath := filepath.Join(t.TempDir(), "explicit-repo") + initRealGitRepo(t, repoPath) + + svc := newDiscoveryService(t, discoveryRoot) + ctx := context.Background() + if err := svc.workspaces.CreateWorkspace(ctx, &models.Workspace{ID: "ws-1", Name: "Workspace"}); err != nil { + t.Fatalf("CreateWorkspace: %v", err) + } + if err := svc.repoEntities.CreateRepository(ctx, &models.Repository{ + ID: "outside-repo", WorkspaceID: "ws-1", Name: "outside", SourceType: sourceTypeLocal, LocalPath: repoPath, + }); err != nil { + t.Fatalf("CreateRepository: %v", err) + } + + result, err := svc.RefreshRepositoryBranches(ctx, "outside-repo") + if err != nil { + t.Fatalf("RefreshRepositoryBranches: %v", err) + } + if result.FetchedAt.IsZero() { + t.Fatal("FetchedAt is zero") + } + if result.Err != nil { + t.Fatalf("fetch result error: %v", result.Err) + } +} diff --git a/apps/backend/internal/task/service/service_resources.go b/apps/backend/internal/task/service/service_resources.go index 63abfff935..ed890e2c7a 100644 --- a/apps/backend/internal/task/service/service_resources.go +++ b/apps/backend/internal/task/service/service_resources.go @@ -581,6 +581,10 @@ func (s *Service) ReorderWorkflows(ctx context.Context, workspaceID string, work // Repository operations func (s *Service) CreateRepository(ctx context.Context, req *CreateRepositoryRequest) (*models.Repository, error) { + localPath, err := canonicalRepositoryLocalPath(req.LocalPath) + if err != nil { + return nil, err + } sourceType := req.SourceType if sourceType == "" { sourceType = sourceTypeLocal @@ -608,7 +612,7 @@ func (s *Service) CreateRepository(ctx context.Context, req *CreateRepositoryReq WorkspaceID: req.WorkspaceID, Name: req.Name, SourceType: sourceType, - LocalPath: req.LocalPath, + LocalPath: localPath, Provider: req.Provider, ProviderRepoID: req.ProviderRepoID, ProviderOwner: req.ProviderOwner, @@ -674,7 +678,11 @@ func (s *Service) FindOrCreateRepository(ctx context.Context, req *FindOrCreateR existing = replacement dirty := false if existing.LocalPath == "" && req.LocalPath != "" { - existing.LocalPath = req.LocalPath + localPath, pathErr := canonicalRepositoryLocalPath(req.LocalPath) + if pathErr != nil { + return nil, false, pathErr + } + existing.LocalPath = localPath dirty = true } // Backfill default_branch when the caller carries one and the existing @@ -716,7 +724,15 @@ func (s *Service) UpdateRepository(ctx context.Context, id string, req *UpdateRe if err != nil { return nil, err } - if err := applyRepositoryUpdates(repository, req); err != nil { + updates := *req + if req.LocalPath != nil { + localPath, pathErr := canonicalRepositoryLocalPath(*req.LocalPath) + if pathErr != nil { + return nil, pathErr + } + updates.LocalPath = &localPath + } + if err := applyRepositoryUpdates(repository, &updates); err != nil { return nil, err } repository.UpdatedAt = time.Now().UTC() @@ -731,6 +747,17 @@ func (s *Service) UpdateRepository(ctx context.Context, id string, req *UpdateRe return repository, nil } +func canonicalRepositoryLocalPath(localPath string) (string, error) { + if localPath == "" { + return "", nil + } + canonicalPath, _, err := resolveExplicitLocalRepositoryPath(localPath) + if err != nil { + return "", fmt.Errorf("%w: %w", ErrInvalidRepositorySettings, err) + } + return canonicalPath, nil +} + // applyRepositoryUpdates applies the non-nil fields from req onto repository. // Returns an error if the WorktreeBranchPrefix is invalid. func applyRepositoryUpdates(repository *models.Repository, req *UpdateRepositoryRequest) error { diff --git a/apps/backend/internal/task/service/service_resources_test.go b/apps/backend/internal/task/service/service_resources_test.go index 9f083cf927..484e17a927 100644 --- a/apps/backend/internal/task/service/service_resources_test.go +++ b/apps/backend/internal/task/service/service_resources_test.go @@ -5,6 +5,8 @@ import ( "encoding/json" "errors" "fmt" + "os" + "path/filepath" "strings" "sync/atomic" "testing" @@ -16,6 +18,236 @@ import ( "github.com/kandev/kandev/internal/worktree" ) +func TestService_CreateRepositoryCanonicalizesExplicitLocalPath(t *testing.T) { + svc, _, repo := createTestService(t) + ctx := context.Background() + if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-1", Name: "Workspace"}); err != nil { + t.Fatalf("CreateWorkspace: %v", err) + } + + discoveryRoot := t.TempDir() + svc.discoveryConfig.Roots = []string{discoveryRoot} + repoPath := filepath.Join(t.TempDir(), "outside-repo") + makeRepo(t, repoPath) + uncleanPath := repoPath + string(os.PathSeparator) + ".." + string(os.PathSeparator) + filepath.Base(repoPath) + + created, err := svc.CreateRepository(ctx, &CreateRepositoryRequest{ + WorkspaceID: "ws-1", + Name: "Outside Repo", + SourceType: sourceTypeLocal, + LocalPath: uncleanPath, + }) + if err != nil { + t.Fatalf("CreateRepository: %v", err) + } + canonicalPath, err := filepath.EvalSymlinks(repoPath) + if err != nil { + t.Fatalf("EvalSymlinks: %v", err) + } + if created.LocalPath != canonicalPath { + t.Fatalf("LocalPath = %q, want canonical path %q", created.LocalPath, canonicalPath) + } + stored, err := repo.GetRepository(ctx, created.ID) + if err != nil { + t.Fatalf("GetRepository: %v", err) + } + if stored.LocalPath != canonicalPath { + t.Fatalf("stored LocalPath = %q, want %q", stored.LocalPath, canonicalPath) + } +} + +func TestService_CreateRepositoryRejectsInvalidLocalPathWithoutPersistence(t *testing.T) { + svc, _, repo := createTestService(t) + ctx := context.Background() + if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-1", Name: "Workspace"}); err != nil { + t.Fatalf("CreateWorkspace: %v", err) + } + + missingPath := filepath.Join(t.TempDir(), "missing") + filePath := filepath.Join(t.TempDir(), "file") + if err := os.WriteFile(filePath, []byte("not a repository"), 0o644); err != nil { + t.Fatalf("WriteFile: %v", err) + } + type invalidPathCase struct { + name string + path string + } + invalidPaths := []invalidPathCase{ + {name: "missing", path: missingPath}, + {name: "file", path: filePath}, + {name: "plain directory", path: t.TempDir()}, + } + metadataOwner := filepath.Join(t.TempDir(), "metadata-owner") + makeRepo(t, metadataOwner) + forgedWorktree := filepath.Join(t.TempDir(), "forged-worktree") + if err := os.MkdirAll(forgedWorktree, 0o755); err != nil { + t.Fatalf("MkdirAll forged worktree: %v", err) + } + if err := os.WriteFile( + filepath.Join(forgedWorktree, ".git"), + []byte("gitdir: "+filepath.Join(metadataOwner, ".git")+"\n"), + 0o644, + ); err != nil { + t.Fatalf("WriteFile forged .git pointer: %v", err) + } + invalidPaths = append(invalidPaths, invalidPathCase{name: "forged gitdir pointer", path: forgedWorktree}) + forgedCommonDir := filepath.Join(t.TempDir(), "forged-common-dir") + makeRepo(t, forgedCommonDir) + if err := os.WriteFile( + filepath.Join(forgedCommonDir, ".git", "commondir"), + []byte(filepath.Join(metadataOwner, ".git")+"\n"), + 0o644, + ); err != nil { + t.Fatalf("WriteFile forged commondir: %v", err) + } + invalidPaths = append(invalidPaths, invalidPathCase{name: "forged common directory", path: forgedCommonDir}) + loopPath := filepath.Join(t.TempDir(), "loop") + if err := os.Symlink(loopPath, loopPath); err == nil { + invalidPaths = append(invalidPaths, invalidPathCase{name: "symlink loop", path: loopPath}) + } + + for _, testCase := range invalidPaths { + t.Run(testCase.name, func(t *testing.T) { + _, err := svc.CreateRepository(ctx, &CreateRepositoryRequest{ + WorkspaceID: "ws-1", + Name: "Invalid Repo", + SourceType: sourceTypeLocal, + LocalPath: testCase.path, + }) + if !errors.Is(err, ErrInvalidRepositorySettings) || !errors.Is(err, ErrInvalidRepositoryPath) { + t.Fatalf("CreateRepository error = %v, want typed invalid path error", err) + } + }) + } + repositories, err := repo.ListRepositories(ctx, "ws-1") + if err != nil { + t.Fatalf("ListRepositories: %v", err) + } + if len(repositories) != 0 { + t.Fatalf("invalid repository was persisted: %+v", repositories) + } +} + +func TestService_UpdateRepositoryRejectsInvalidLocalPathWithoutPersistence(t *testing.T) { + svc, _, repo := createTestService(t) + ctx := context.Background() + if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-1", Name: "Workspace"}); err != nil { + t.Fatalf("CreateWorkspace: %v", err) + } + created, err := svc.CreateRepository(ctx, &CreateRepositoryRequest{ + WorkspaceID: "ws-1", + Name: "Provider Repo", + SourceType: sourceTypeProvider, + Provider: "github", + }) + if err != nil { + t.Fatalf("CreateRepository: %v", err) + } + + invalidPath := t.TempDir() + _, err = svc.UpdateRepository(ctx, created.ID, &UpdateRepositoryRequest{LocalPath: &invalidPath}) + if !errors.Is(err, ErrInvalidRepositorySettings) { + t.Fatalf("UpdateRepository error = %v, want ErrInvalidRepositorySettings", err) + } + stored, err := repo.GetRepository(ctx, created.ID) + if err != nil { + t.Fatalf("GetRepository: %v", err) + } + if stored.LocalPath != "" { + t.Fatalf("invalid LocalPath persisted as %q", stored.LocalPath) + } +} + +func TestService_UpdateRepositoryCanonicalizesExplicitLocalPath(t *testing.T) { + svc, _, repo := createTestService(t) + ctx := context.Background() + if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-1", Name: "Workspace"}); err != nil { + t.Fatalf("CreateWorkspace: %v", err) + } + created, err := svc.CreateRepository(ctx, &CreateRepositoryRequest{ + WorkspaceID: "ws-1", + Name: "Provider Repo", + SourceType: sourceTypeProvider, + Provider: "github", + }) + if err != nil { + t.Fatalf("CreateRepository: %v", err) + } + + repoPath := filepath.Join(t.TempDir(), "outside-repo") + makeRepo(t, repoPath) + uncleanPath := repoPath + string(os.PathSeparator) + ".." + string(os.PathSeparator) + filepath.Base(repoPath) + updated, err := svc.UpdateRepository(ctx, created.ID, &UpdateRepositoryRequest{LocalPath: &uncleanPath}) + if err != nil { + t.Fatalf("UpdateRepository: %v", err) + } + canonicalPath, err := filepath.EvalSymlinks(repoPath) + if err != nil { + t.Fatalf("EvalSymlinks: %v", err) + } + if updated.LocalPath != canonicalPath { + t.Fatalf("LocalPath = %q, want canonical path %q", updated.LocalPath, canonicalPath) + } +} + +func TestService_CreateRepositoryAllowsPathlessProvider(t *testing.T) { + svc, _, repo := createTestService(t) + ctx := context.Background() + if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-1", Name: "Workspace"}); err != nil { + t.Fatalf("CreateWorkspace: %v", err) + } + created, err := svc.CreateRepository(ctx, &CreateRepositoryRequest{ + WorkspaceID: "ws-1", + Name: "owner/repo", + SourceType: sourceTypeProvider, + Provider: "github", + }) + if err != nil { + t.Fatalf("CreateRepository: %v", err) + } + if created.LocalPath != "" { + t.Fatalf("LocalPath = %q, want empty", created.LocalPath) + } +} + +func TestService_FindOrCreateRepositoryRejectsInvalidLocalPathBackfill(t *testing.T) { + svc, _, repo := createTestService(t) + ctx := context.Background() + if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-1", Name: "Workspace"}); err != nil { + t.Fatalf("CreateWorkspace: %v", err) + } + created, err := svc.CreateRepository(ctx, &CreateRepositoryRequest{ + WorkspaceID: "ws-1", + Name: "owner/repo", + SourceType: sourceTypeProvider, + Provider: "github", + ProviderOwner: "owner", + ProviderName: "repo", + }) + if err != nil { + t.Fatalf("CreateRepository: %v", err) + } + + invalidPath := t.TempDir() + _, _, err = svc.FindOrCreateRepository(ctx, &FindOrCreateRepositoryRequest{ + WorkspaceID: "ws-1", + Provider: "github", + ProviderOwner: "owner", + ProviderName: "repo", + LocalPath: invalidPath, + }) + if !errors.Is(err, ErrInvalidRepositorySettings) { + t.Fatalf("FindOrCreateRepository error = %v, want ErrInvalidRepositorySettings", err) + } + stored, err := repo.GetRepository(ctx, created.ID) + if err != nil { + t.Fatalf("GetRepository: %v", err) + } + if stored.LocalPath != "" { + t.Fatalf("invalid LocalPath backfill persisted as %q", stored.LocalPath) + } +} + // errWorkspaceRepo is a WorkspaceRepository that always returns an error from // ListWorkspaces. Used to exercise the DB-error path of GetOfficeWorkflowIDs. type errWorkspaceRepo struct { diff --git a/apps/backend/internal/task/service/service_tasks.go b/apps/backend/internal/task/service/service_tasks.go index 55d4c8b1cf..9b0402c446 100644 --- a/apps/backend/internal/task/service/service_tasks.go +++ b/apps/backend/internal/task/service/service_tasks.go @@ -16,7 +16,6 @@ import ( v1 "github.com/kandev/kandev/pkg/api/v1" "go.uber.org/zap" - "github.com/kandev/kandev/internal/common/gitref" "github.com/kandev/kandev/internal/events" "github.com/kandev/kandev/internal/task/models" taskrepo "github.com/kandev/kandev/internal/task/repository" @@ -610,10 +609,15 @@ func (s *Service) resolveRepoInputLocal( ctx context.Context, workspaceID string, repoInput TaskRepositoryInput, repoByPath map[string]*models.Repository, baseBranch string, ) (string, string, bool, error) { - repo := repoByPath[repoInput.LocalPath] + lookupPath := repoInput.LocalPath + canonicalPath, probedBranch, pathErr := resolveExplicitLocalRepositoryPath(repoInput.LocalPath) + if pathErr == nil { + lookupPath = canonicalPath + } + repo := repoByPath[lookupPath] created := false if repo == nil { - if isKandevTaskWorktreePath(repoInput.LocalPath, s.discoveryConfig.TaskWorktreeRoots) { + if isKandevTaskWorktreePath(lookupPath, s.discoveryConfig.TaskWorktreeRoots) { return "", "", false, fmt.Errorf("local path %q points at a Kandev task worktree; use the source repository or GitHub URL", repoInput.LocalPath) } name := strings.TrimSpace(repoInput.Name) @@ -629,15 +633,12 @@ func (s *Service) resolveRepoInputLocal( // branch, which would permanently pin repositories.default_branch to // a feature branch and break every downstream merge-base lookup. defaultBranch := repoInput.DefaultBranch - if defaultBranch == "" { - // Probe must operate on a path validated against the discovery - // allowlist — repoInput.LocalPath comes straight from the HTTP body - // and feeds into os.Stat/ReadFile inside gitref.DefaultBranch, so - // without this guard a caller could traverse the filesystem. - if safePath, pathErr := s.resolveAllowedLocalPath(repoInput.LocalPath); pathErr == nil { - if probed, err := gitref.DefaultBranchOrEmpty(safePath); err == nil && probed != "" { - defaultBranch = probed - } + if defaultBranch == "" && pathErr == nil { + // A manually supplied path is an explicit read-only probe. Canonical + // repository validation protects the filesystem read; discovery roots + // only constrain automatic scans. + if probedBranch != "" { + defaultBranch = probedBranch } } createdRepo, createErr := s.CreateRepository(ctx, &CreateRepositoryRequest{ @@ -653,6 +654,7 @@ func (s *Service) resolveRepoInputLocal( repo = createdRepo if repoByPath != nil { repoByPath[repoInput.LocalPath] = repo + repoByPath[repo.LocalPath] = repo } created = true } else { diff --git a/apps/backend/internal/task/service/service_test.go b/apps/backend/internal/task/service/service_test.go index ff3d48ab9f..b3db787622 100644 --- a/apps/backend/internal/task/service/service_test.go +++ b/apps/backend/internal/task/service/service_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "os" + "os/exec" "path/filepath" "strings" "sync" @@ -423,6 +424,104 @@ func TestService_CreateTask(t *testing.T) { } } +func TestService_CreateTaskProbesDefaultBranchForExplicitRepositoryOutsideDiscoveryRoots(t *testing.T) { + isolateGitEnvForTest(t) + svc, _, repo := createTestService(t) + ctx := context.Background() + repoPath := filepath.Join(t.TempDir(), "explicit-repo") + initRealGitRepo(t, repoPath) + cmd := exec.Command("git", "checkout", "-b", "feature/current") + cmd.Dir = repoPath + cmd.Env = isolatedGitEnv() + if output, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git checkout feature branch: %v: %s", err, output) + } + + const workspaceID = "ws-explicit" + const workflowID = "wf-explicit" + if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: workspaceID, Name: "Workspace"}); err != nil { + t.Fatalf("CreateWorkspace: %v", err) + } + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: workflowID, WorkspaceID: workspaceID, Name: "Workflow"}); err != nil { + t.Fatalf("CreateWorkflow: %v", err) + } + task, err := svc.CreateTask(ctx, &CreateTaskRequest{ + WorkspaceID: workspaceID, + WorkflowID: workflowID, + WorkflowStepID: "step-1", + Title: "Explicit repository", + Repositories: []TaskRepositoryInput{{ + LocalPath: repoPath, BaseBranch: "feature/current", Name: "explicit-repo", + }}, + }) + if err != nil { + t.Fatalf("CreateTask: %v", err) + } + if len(task.Repositories) != 1 { + t.Fatalf("task repositories = %d, want 1", len(task.Repositories)) + } + saved, err := repo.GetRepository(ctx, task.Repositories[0].RepositoryID) + if err != nil { + t.Fatalf("GetRepository: %v", err) + } + if saved.DefaultBranch != "main" { + t.Fatalf("DefaultBranch = %q, want main", saved.DefaultBranch) + } +} + +func TestResolveRepoInputLocalDeduplicatesCanonicalPathAliases(t *testing.T) { + isolateGitEnvForTest(t) + svc, _, repo := createTestService(t) + ctx := context.Background() + const workspaceID = "ws-canonical-alias" + if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: workspaceID, Name: "Workspace"}); err != nil { + t.Fatalf("CreateWorkspace: %v", err) + } + + repoPath := filepath.Join(t.TempDir(), "canonical-repo") + initRealGitRepo(t, repoPath) + aliasPath := filepath.Join(t.TempDir(), "repository-alias") + if err := os.Symlink(repoPath, aliasPath); err != nil { + t.Skipf("symlink creation unavailable: %v", err) + } + canonicalPath, err := filepath.EvalSymlinks(repoPath) + if err != nil { + t.Fatalf("EvalSymlinks: %v", err) + } + + repoByPath := map[string]*models.Repository{} + aliasID, _, aliasCreated, err := svc.resolveRepoInputLocal( + ctx, + workspaceID, + TaskRepositoryInput{LocalPath: aliasPath}, + repoByPath, + "", + ) + if err != nil { + t.Fatalf("resolve alias: %v", err) + } + if !aliasCreated { + t.Fatal("expected alias lookup to create repository") + } + + canonicalID, _, canonicalCreated, err := svc.resolveRepoInputLocal( + ctx, + workspaceID, + TaskRepositoryInput{LocalPath: canonicalPath}, + repoByPath, + "", + ) + if err != nil { + t.Fatalf("resolve canonical path: %v", err) + } + if canonicalCreated { + t.Fatal("canonical alias created a duplicate repository") + } + if canonicalID != aliasID { + t.Fatalf("canonical repository ID = %q, want %q", canonicalID, aliasID) + } +} + // TestService_CreateTask_DefaultsPriorityWhenEmpty pins the regression // from the office priority migration. The migration added a CHECK // constraint that the priority column must be one of {critical, high, diff --git a/apps/web/app/settings/workspace/workspace-repositories-client.tsx b/apps/web/app/settings/workspace/workspace-repositories-client.tsx index bf1a6dfb40..26caf92a93 100644 --- a/apps/web/app/settings/workspace/workspace-repositories-client.tsx +++ b/apps/web/app/settings/workspace/workspace-repositories-client.tsx @@ -42,6 +42,7 @@ import { type RepositoryWithScripts, } from "@/app/settings/workspace/workspace-repositories-dirty"; import { defaultWorktreeBranchTemplate } from "@/lib/worktree-branch-template"; +import { isValidManualRepository } from "@/app/settings/workspace/workspace-repositories-validation"; type RepositoryItem = RepositoryWithScripts & { __autoOpen?: boolean }; type WorkspaceRepositoriesClientProps = { @@ -347,7 +348,7 @@ function useDiscoverDialog( setManualValidation({ status: "loading" }); try { const result = await validateRequest.run(workspace.id, manualRepoPath.trim()); - if (result.allowed && result.exists && result.is_git) + if (isValidManualRepository(result)) setManualValidation({ status: "success", isValid: true, diff --git a/apps/web/app/settings/workspace/workspace-repositories-validation.test.ts b/apps/web/app/settings/workspace/workspace-repositories-validation.test.ts new file mode 100644 index 0000000000..322ba37bd9 --- /dev/null +++ b/apps/web/app/settings/workspace/workspace-repositories-validation.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from "vitest"; +import type { RepositoryPathValidationResponse } from "@/lib/types/http"; +import { isValidManualRepository } from "./workspace-repositories-validation"; + +describe("manual repository validation", () => { + it("does not use discovery-root allowance to reject an existing Git repository", () => { + const result: RepositoryPathValidationResponse = { + path: "C:\\src\\project", + exists: true, + is_git: true, + allowed: false, + }; + + expect(isValidManualRepository(result)).toBe(true); + }); + + it.each([ + { exists: false, is_git: true }, + { exists: true, is_git: false }, + ])("rejects a path when exists=$exists and is_git=$is_git", ({ exists, is_git }) => { + const result: RepositoryPathValidationResponse = { + path: "/src/project", + exists, + is_git, + allowed: true, + }; + + expect(isValidManualRepository(result)).toBe(false); + }); +}); diff --git a/apps/web/app/settings/workspace/workspace-repositories-validation.ts b/apps/web/app/settings/workspace/workspace-repositories-validation.ts new file mode 100644 index 0000000000..a5cb90f0e1 --- /dev/null +++ b/apps/web/app/settings/workspace/workspace-repositories-validation.ts @@ -0,0 +1,5 @@ +import type { RepositoryPathValidationResponse } from "@/lib/types/http"; + +export function isValidManualRepository(result: RepositoryPathValidationResponse): boolean { + return result.exists && result.is_git; +} diff --git a/apps/web/e2e/tests/github/pr-action-create-task-dialog.spec.ts b/apps/web/e2e/tests/github/pr-action-create-task-dialog.spec.ts index 29babba07e..5455e71697 100644 --- a/apps/web/e2e/tests/github/pr-action-create-task-dialog.spec.ts +++ b/apps/web/e2e/tests/github/pr-action-create-task-dialog.spec.ts @@ -1,5 +1,8 @@ +import { execSync } from "node:child_process"; +import fs from "node:fs"; import path from "node:path"; import { test, expect } from "../../fixtures/test-base"; +import { makeGitEnv } from "../../helpers/git-helper"; test.describe("GitHub PR task launcher", () => { test("opens the create task dialog in Remote mode when the matching repo is a stale task worktree", async ({ @@ -29,17 +32,24 @@ test.describe("GitHub PR task launcher", () => { }, ]); - await apiClient.createRepository( - seedData.workspaceId, - path.join(backend.tmpDir, ".kandev", "tasks", "pr-1541-fix-skip-cle_3bm", "stalerepo"), - "main", - { - name: `${owner}/${repo}`, - provider: "github", - provider_owner: owner, - provider_name: repo, - }, + const staleWorktreePath = path.join( + backend.tmpDir, + ".kandev", + "tasks", + "pr-1541-fix-skip-cle_3bm", + "stalerepo", ); + fs.mkdirSync(staleWorktreePath, { recursive: true }); + const gitEnv = makeGitEnv(backend.tmpDir); + execSync("git init -b main", { cwd: staleWorktreePath, env: gitEnv }); + execSync('git commit --allow-empty -m "init"', { cwd: staleWorktreePath, env: gitEnv }); + + await apiClient.createRepository(seedData.workspaceId, staleWorktreePath, "main", { + name: `${owner}/${repo}`, + provider: "github", + provider_owner: owner, + provider_name: repo, + }); await testPage.goto("/github"); await expect(testPage.getByTestId("github-presets-scope-bar")).toBeVisible({ diff --git a/apps/web/e2e/tests/office/project-repository-picker.spec.ts b/apps/web/e2e/tests/office/project-repository-picker.spec.ts index 0dcd32e28e..22074ceabe 100644 --- a/apps/web/e2e/tests/office/project-repository-picker.spec.ts +++ b/apps/web/e2e/tests/office/project-repository-picker.spec.ts @@ -1,6 +1,8 @@ +import { execSync } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; import { test, expect } from "../../fixtures/office-fixture"; +import { makeGitEnv } from "../../helpers/git-helper"; /** * Project page — repository picker (chip-style, popover-driven). @@ -110,6 +112,9 @@ test.describe("Project repository picker", () => { // we'll type — the classic /work/app vs /work/app-old overlap. const oldPath = path.join(backend.tmpDir, "repos", "app-old"); fs.mkdirSync(oldPath, { recursive: true }); + const gitEnv = makeGitEnv(backend.tmpDir); + execSync("git init -b main", { cwd: oldPath, env: gitEnv }); + execSync('git commit --allow-empty -m "init"', { cwd: oldPath, env: gitEnv }); await apiClient.createRepository(officeSeed.workspaceId, oldPath, "main", { name: "app-old" }); await testPage.goto(`/office/projects/${projectId}`); diff --git a/apps/web/e2e/tests/settings/mobile-repository-add-local.spec.ts b/apps/web/e2e/tests/settings/mobile-repository-add-local.spec.ts new file mode 100644 index 0000000000..cd927991c7 --- /dev/null +++ b/apps/web/e2e/tests/settings/mobile-repository-add-local.spec.ts @@ -0,0 +1,19 @@ +import { test } from "../../fixtures/test-base"; +import { addExplicitLocalRepository } from "./repository-add-local-helpers"; + +test.describe("Add explicit local repository on mobile", () => { + test("validates and saves a Git repository outside automatic discovery roots", async ({ + testPage, + apiClient, + backend, + seedData, + }) => { + await addExplicitLocalRepository({ + page: testPage, + apiClient, + backend, + seedData, + mobile: true, + }); + }); +}); diff --git a/apps/web/e2e/tests/settings/repository-add-local-helpers.ts b/apps/web/e2e/tests/settings/repository-add-local-helpers.ts new file mode 100644 index 0000000000..a14ab0b38c --- /dev/null +++ b/apps/web/e2e/tests/settings/repository-add-local-helpers.ts @@ -0,0 +1,104 @@ +import { execSync } from "node:child_process"; +import fs from "node:fs"; +import path from "node:path"; +import { expect, type Page } from "@playwright/test"; +import type { BackendContext } from "../../fixtures/backend"; +import type { SeedData } from "../../fixtures/test-base"; +import type { ApiClient } from "../../helpers/api-client"; +import { makeGitEnv } from "../../helpers/git-helper"; +import type { ListRepositoriesResponse, Repository } from "../../../lib/types/http"; + +export async function addExplicitLocalRepository(options: { + page: Page; + apiClient: ApiClient; + backend: BackendContext; + seedData: SeedData; + mobile?: boolean; +}) { + const { page, apiClient, backend, seedData, mobile = false } = options; + if (mobile) await page.setViewportSize({ width: 390, height: 844 }); + + const externalRoot = fs.mkdtempSync( + path.join(path.dirname(backend.tmpDir), "kandev-e2e-external-repository-"), + ); + const repoName = mobile ? "outside-mobile-repository" : "outside-desktop-repository"; + const repoPath = path.join(externalRoot, repoName); + const canonicalPath = fs.realpathSync(externalRoot); + let savedRepository: Repository | undefined; + + try { + fs.mkdirSync(repoPath, { recursive: true }); + const gitEnv = makeGitEnv(backend.tmpDir); + execSync("git init -b main", { cwd: repoPath, env: gitEnv }); + fs.writeFileSync(path.join(repoPath, "README.md"), "# Explicit local repository\n"); + execSync("git add README.md", { cwd: repoPath, env: gitEnv }); + execSync('git commit -m "init explicit repository"', { cwd: repoPath, env: gitEnv }); + + const relativeToBackendHome = path.relative(backend.tmpDir, repoPath); + expect(relativeToBackendHome.startsWith(`..${path.sep}`)).toBe(true); + + await page.goto(`/settings/workspace/${seedData.workspaceId}/repositories`); + await page.getByRole("button", { name: "Add Local Repository" }).click(); + + const dialog = page.getByRole("dialog", { name: "Add Local Repository" }); + await expect(dialog).toBeVisible(); + const manualPath = dialog.getByPlaceholder("/absolute/path/to/repository"); + await manualPath.fill(repoPath); + + const validationResponse = page.waitForResponse( + (response) => + response.url().includes("/repositories/validate?") && + response.request().method() === "GET" && + response.ok(), + ); + await dialog.getByRole("button", { name: "Validate", exact: true }).click(); + await validationResponse; + await expect(dialog.getByText("Valid git repository", { exact: true })).toBeVisible(); + + const useRepository = dialog.getByRole("button", { name: "Use Repository" }); + await expect(useRepository).toBeEnabled(); + await useRepository.click(); + await expect(dialog).toBeHidden(); + + await expect(page.getByPlaceholder("/path/to/repository")).toHaveValue(repoPath); + const createResponse = page.waitForResponse( + (response) => + response.url().endsWith(`/api/v1/workspaces/${seedData.workspaceId}/repositories`) && + response.request().method() === "POST" && + response.ok(), + ); + await page + .getByTestId("settings-floating-save") + .getByRole("button", { name: "Save changes" }) + .click(); + savedRepository = (await (await createResponse).json()) as Repository; + + await page.reload(); + const savedCard = page.locator('[data-slot="card"]', { hasText: repoName }); + await expect(savedCard).toBeVisible({ timeout: 15_000 }); + await expect(savedCard.getByText(fs.realpathSync(repoPath), { exact: true })).toBeVisible(); + + const listResponse = await apiClient.rawRequest( + "GET", + `/api/v1/workspaces/${seedData.workspaceId}/repositories`, + ); + expect(listResponse.ok).toBe(true); + const listed = (await listResponse.json()) as ListRepositoriesResponse; + expect(listed.repositories).toContainEqual( + expect.objectContaining({ id: savedRepository.id, local_path: fs.realpathSync(repoPath) }), + ); + + if (mobile) { + expect( + await page.evaluate(() => document.documentElement.scrollWidth > window.innerWidth), + ).toBe(false); + } + } finally { + if (savedRepository) { + await apiClient + .rawRequest("DELETE", `/api/v1/repositories/${savedRepository.id}`) + .catch(() => undefined); + } + fs.rmSync(canonicalPath, { recursive: true, force: true }); + } +} diff --git a/apps/web/e2e/tests/settings/repository-add-local.spec.ts b/apps/web/e2e/tests/settings/repository-add-local.spec.ts new file mode 100644 index 0000000000..1abda1784c --- /dev/null +++ b/apps/web/e2e/tests/settings/repository-add-local.spec.ts @@ -0,0 +1,13 @@ +import { test } from "../../fixtures/test-base"; +import { addExplicitLocalRepository } from "./repository-add-local-helpers"; + +test.describe("Add explicit local repository", () => { + test("validates and saves a Git repository outside automatic discovery roots", async ({ + testPage, + apiClient, + backend, + seedData, + }) => { + await addExplicitLocalRepository({ page: testPage, apiClient, backend, seedData }); + }); +}); diff --git a/apps/web/lib/types/http.ts b/apps/web/lib/types/http.ts index c38beb6554..f10a000408 100644 --- a/apps/web/lib/types/http.ts +++ b/apps/web/lib/types/http.ts @@ -532,6 +532,7 @@ export type RepositoryPathValidationResponse = { path: string; exists: boolean; is_git: boolean; + /** @deprecated Compatibility field; manual validity is determined by `exists` and `is_git`. */ allowed: boolean; default_branch?: string; message?: string; diff --git a/docs/configuration.md b/docs/configuration.md index 59fec358f6..d5eb83ca98 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -101,7 +101,7 @@ logging: compress: true # gzip rotated files repositoryDiscovery: - roots: [] # absolute paths to scan for local git repos + roots: [] # automatic scan roots; explicit repository paths need not be included maxDepth: 5 worktree: @@ -118,6 +118,10 @@ debug: pprofEnabled: false # enables /debug/pprof and /api/v1/debug/memory ``` +`repositoryDiscovery.roots` and `repositoryDiscovery.maxDepth` bound automatic filesystem scans. +They do not authorize explicitly selected repository paths. When a user enters an absolute path in +**Add Local Repository**, Kandev validates that exact accessible Git repository before saving it. + ## Required vs optional Almost every field has a default and is optional. The exceptions: diff --git a/docs/decisions/2026-07-20-explicit-local-repository-trust.md b/docs/decisions/2026-07-20-explicit-local-repository-trust.md new file mode 100644 index 0000000000..d9aae0ba5b --- /dev/null +++ b/docs/decisions/2026-07-20-explicit-local-repository-trust.md @@ -0,0 +1,74 @@ +# ADR-2026-07-20-explicit-local-repository-trust: Explicit Local Repository Trust + +**Status:** accepted +**Date:** 2026-07-20 +**Area:** backend, frontend + +## Context + +Kandev uses `repositoryDiscovery.roots` to bound automatic filesystem scans, defaulting to the +current user's home directory. The same roots were also reused to reject manually entered local +repository paths and later Git operations. Packaged Windows users could therefore browse to a valid +repository outside their home directory but could not add or use it, and the packaged runtime did +not provide a durable configuration-file location for widening the roots. + +The existing product already treats an explicitly selected local folder as trusted by the local +user, and repository records persist an exact `local_path`. Automatic traversal and explicit +selection have different risk and lifecycle characteristics and should not share one boundary. + +## Decision + +`repositoryDiscovery.roots` and `repositoryDiscovery.maxDepth` govern automatic repository +discovery only. They do not determine whether a user may explicitly select a repository. + +An explicit local repository selection is validated and canonicalized by the backend before it is +persisted. The resulting repository record, scoped to its workspace, is the durable trust grant for +that exact repository path. The grant does not extend to the repository's parent directory, drive, +or other repositories beneath the same parent. + +Git metadata indirection must preserve that exact grant. A normal `.git` directory must not redirect +its common directory, and a file-based `.git` pointer is accepted only when the target metadata has +the reciprocal backpointer and common-directory placement created by `git worktree`. Saved +repository operations also require the path to resolve to the same canonical location recorded at +creation time. Unverifiable layouts such as arbitrary `.git` pointers or `--separate-git-dir` are +rejected rather than treated as linked worktrees. + +Read-only pre-registration operations may inspect an explicitly supplied path so the UI can +validate it and show repository status before saving. Fetches and destructive Git operations must +resolve a persisted repository identity server-side instead of trusting a raw path from the +request. Provider-backed repositories may remain pathless until Kandev materializes them. +Workspace-qualified routes must additionally verify that the persisted repository belongs to the +workspace named by the route before reading provider or filesystem state. + +Containment checks that remain necessary for automatic scans or nested Git metadata use canonical +filesystem paths and platform-correct comparisons. Windows drive-letter casing, separators, and +UNC volume semantics must not be implemented with a raw string-prefix comparison. + +## Consequences + +- Native Windows, macOS, and Linux users can add an exact repository anywhere the Kandev process + can access without changing a global scan root. +- Automatic discovery remains bounded and does not start traversing whole drives or newly trusted + parent trees. +- Repository creation and local-path updates become authoritative validation boundaries instead of + relying on prior UI validation. +- Legitimate linked Git worktrees remain usable, while unverifiable external Git-metadata layouts + require a separate product and security decision before support is added. +- Git operations increasingly require repository IDs, which narrows the impact of forged raw paths + but requires migration of existing path-oriented service and handler calls. +- Deployments exposed to untrusted users still need an authentication and authorization policy; + discovery roots are not a substitute for that policy. + +## Alternatives Considered + +1. **Persist user-editable global discovery roots.** Rejected because selecting one repository + should not grant access to every sibling repository or make automatic scans traverse a wider + tree. +2. **Trust all drives for native desktop or CLI launches.** Rejected because launch-mode detection + is not a durable security boundary and the behavior would diverge across packaging modes. +3. **Search `~/.kandev/config.yaml` or expose `--config` only.** Rejected as the primary fix because + it leaves the normal Add Local Repository workflow broken and requires users to understand + backend configuration. +4. **Use the launcher's original working directory as the default root.** Rejected because it is + session-dependent, does not help repositories on other drives, and conflates process startup + location with durable repository trust. diff --git a/docs/decisions/INDEX.md b/docs/decisions/INDEX.md index 8d52e17bfb..854e019c67 100644 --- a/docs/decisions/INDEX.md +++ b/docs/decisions/INDEX.md @@ -57,3 +57,4 @@ Read individual ADRs for full context. Create new ones via `/record decision` or | 2026-07-18-turn-configuration-snapshots | [Attribute runtime configuration to turns](2026-07-18-turn-configuration-snapshots.md) | accepted | backend, frontend | 2026-07-18 | | 2026-07-19-reject-mcp-actions-on-raw-websocket | [Reject MCP Actions on the Raw WebSocket](2026-07-19-reject-mcp-actions-on-raw-websocket.md) | accepted | backend, protocol | 2026-07-19 | | 2026-07-19-workspace-symlink-entries | [Treat Nested Workspace Symlinks as Entries](2026-07-19-workspace-symlink-entries.md) | accepted | backend, infra | 2026-07-19 | +| 2026-07-20-explicit-local-repository-trust | [Explicit Local Repository Trust](2026-07-20-explicit-local-repository-trust.md) | accepted | backend, frontend | 2026-07-20 | diff --git a/docs/plans/explicit-local-repository-trust/plan.md b/docs/plans/explicit-local-repository-trust/plan.md new file mode 100644 index 0000000000..7e3717decb --- /dev/null +++ b/docs/plans/explicit-local-repository-trust/plan.md @@ -0,0 +1,124 @@ +--- +spec: docs/specs/workspaces/local-repositories.md +created: 2026-07-20 +status: completed +--- + +# Implementation Plan: Explicit Local Repository Trust + +## Overview + +Separate bounded automatic discovery from explicit local-repository validation, then make the +repository record the durable exact-path grant. Migrate mutating Git operations to repository +identity, update the existing dialog contract without changing its layout, and finish with native +Windows and browser regression coverage. + +## Backend + +- Add one canonical explicit-path resolver for non-empty local repository paths. It resolves an + absolute clean path, canonicalizes symlinks, verifies a directory and Git repository, and returns + typed validation errors suitable for 4xx responses. +- Use the resolver in manual validation and in local repository create/update. Provider-backed + repositories with empty local paths remain valid. +- Retain `repositoryDiscovery.roots` only in automatic discovery. Replace remaining raw string + containment with platform-correct relative-path comparison where containment is still required. +- Resolve saved repositories by ID for branch refresh and fresh-branch mutation. Raw path endpoints + remain read-only pre-registration probes. +- Preserve the `allowed` validation response field for compatibility while removing it from the + frontend validity decision. + +## Frontend + +- Treat `exists && is_git` as the successful manual-validation contract in the existing Add Local + Repository dialog. +- Keep loading, success, and failure messages and the current responsive dialog layout unchanged. +- Add a focused pure validation helper test so the deprecated `allowed=false` value cannot recreate + the Windows regression while older backends remain understandable. + +## Documentation + +- Clarify in public and reference configuration docs that discovery roots bound automatic scans and + do not need to include repositories selected explicitly. +- Keep the ADR, spec, and root indexes synchronized. + +## Tests + +- Service regression: a Git repository outside configured discovery roots validates, canonicalizes, + persists, lists branches, refreshes, and supports identity-bound fresh-branch behavior. +- Negative service/handler cases: missing, file, plain directory, inaccessible/canonicalization + failure, and invalid update all fail without persistence. +- Discovery regression: an explicit saved repository does not widen the roots used by automatic + discovery. +- Windows regression: drive-letter casing, trailing separators, and native canonicalization run in + the existing Windows backend job. +- Browser regression: desktop and mobile Add Local Repository flows save a real Git repository + outside the backend's configured/default discovery root. + +## Implementation Waves + +Wave 1: + +- [x] [task-01-explicit-path-contract](task-01-explicit-path-contract.md) - done + +Wave 2: + +- [x] [task-02-identity-bound-git-operations](task-02-identity-bound-git-operations.md) - done + +Wave 3: + +- [x] [task-03-frontend-validation-contract](task-03-frontend-validation-contract.md) - done + +Wave 4: + +- [x] [task-04-cross-platform-regression](task-04-cross-platform-regression.md) - done + +## Verification + +Run the Go commands from `apps/backend`: + +```bash +rtk go test -v ./internal/task/service -run 'Test(ValidateLocalRepositoryPath|CreateRepository|UpdateRepository|DiscoverLocalRepositories)' +rtk go test -v ./internal/task/service -run 'Test(RefreshRepositoryBranches|PerformFreshBranch|ListBranches)' +rtk go test -race ./internal/task/service ./internal/task/handlers +``` + +Run the backend Make targets from the repository root: + +```bash +rtk make -C apps/backend fmt +rtk make -C apps/backend test +rtk make -C apps/backend lint +``` + +Run from `apps/web`: + +```bash +rtk pnpm test -- app/settings/workspace/workspace-repositories-validation.test.ts +rtk pnpm run typecheck +rtk pnpm e2e -- e2e/tests/settings/repository-add-local.spec.ts --project=chromium +rtk pnpm e2e -- e2e/tests/settings/mobile-repository-add-local.spec.ts --project=mobile-chrome +``` + +Run from `apps/`: + +```bash +rtk pnpm --filter @kandev/web lint +``` + +Formatting runs before full test and lint verification because formatters may change line layout and +expose complexity thresholds. + +## Risks + +- Repository creation is reused by local and provider flows; validation must not reject pathless or + not-yet-materialized provider repositories. +- Fresh-branch compensation currently happens after task creation. Identity migration must preserve + task rollback and dirty-file consent behavior. +- Canonicalization must not break linked Git worktrees whose `.git` metadata points to a common + directory outside the worktree root. +- Keeping the deprecated `allowed` field avoids an abrupt API removal, but its new compatibility + meaning must be documented and tested. + +## Open Questions + +None. diff --git a/docs/plans/explicit-local-repository-trust/task-01-explicit-path-contract.md b/docs/plans/explicit-local-repository-trust/task-01-explicit-path-contract.md new file mode 100644 index 0000000000..ed8615e0cd --- /dev/null +++ b/docs/plans/explicit-local-repository-trust/task-01-explicit-path-contract.md @@ -0,0 +1,53 @@ +--- +id: "01-explicit-path-contract" +title: "Explicit local path contract" +status: done +wave: 1 +depends_on: [] +plan: "plan.md" +spec: "../../specs/workspaces/local-repositories.md" +--- + +# Task 01: Explicit Local Path Contract + +## Acceptance + +- Manual validation accepts a real Git repository outside configured discovery roots while + automatic discovery remains bounded by those roots. +- Create and update canonicalize and validate non-empty local paths server-side and return 4xx for + invalid paths without persisting changes. +- Pathless provider repositories retain their existing behavior. + +## Verification + +From `apps/backend`: + +```bash +rtk go test -v ./internal/task/service -run 'Test(ValidateLocalRepositoryPath|CreateRepository|UpdateRepository|DiscoverLocalRepositories)' +rtk go test -race ./internal/task/service +``` + +## Files Likely Touched + +- `apps/backend/internal/task/service/repository_discovery.go` +- `apps/backend/internal/task/service/repository_discovery_test.go` +- `apps/backend/internal/task/service/service_resources.go` +- `apps/backend/internal/task/service/service_test.go` +- `apps/backend/internal/task/handlers/repository_handlers.go` +- `apps/backend/internal/task/handlers/repository_handlers_test.go` +- `apps/backend/internal/task/dto/dto.go` + +## Dependencies + +None. + +## Inputs + +- Spec: `What`, `API Surface`, `Failure Modes`, and the manual-selection scenarios. +- ADR: exact saved repository path is the durable grant; discovery roots govern scans only. +- Existing path canonicalization and Git metadata handling in `repository_discovery.go`. + +## Output Contract + +Report changed behavior, files, red/green test evidence, exact commands run, blockers, linked-worktree +risks, and update this task plus `plan.md` to done. diff --git a/docs/plans/explicit-local-repository-trust/task-02-identity-bound-git-operations.md b/docs/plans/explicit-local-repository-trust/task-02-identity-bound-git-operations.md new file mode 100644 index 0000000000..750ae98fdf --- /dev/null +++ b/docs/plans/explicit-local-repository-trust/task-02-identity-bound-git-operations.md @@ -0,0 +1,55 @@ +--- +id: "02-identity-bound-git-operations" +title: "Identity-bound Git operations" +status: done +wave: 2 +depends_on: ["01-explicit-path-contract"] +plan: "plan.md" +spec: "../../specs/workspaces/local-repositories.md" +--- + +# Task 02: Identity-Bound Git Operations + +## Acceptance + +- Saved repositories outside discovery roots support branch listing and refresh through repository + ID. +- Fresh-branch mutation resolves the repository persisted for the task before executing Git and + preserves dirty-file consent and compensation behavior. +- Raw paths remain limited to read-only validation, branch, and status probes. + +## Verification + +From `apps/backend`: + +```bash +rtk go test -v ./internal/task/service -run 'Test(RefreshRepositoryBranches|PerformFreshBranch|ListBranches)' +rtk go test -v ./internal/task/handlers -run 'Test.*FreshBranch|Test.*RepositoryBranches' +rtk go test -race ./internal/task/service ./internal/task/handlers +``` + +## Files Likely Touched + +- `apps/backend/internal/task/service/repository_discovery.go` +- `apps/backend/internal/task/service/repository_fetch.go` +- `apps/backend/internal/task/service/fresh_branch.go` +- `apps/backend/internal/task/service/fresh_branch_test.go` +- `apps/backend/internal/task/service/repository_discovery_test.go` +- `apps/backend/internal/task/handlers/repository_handlers.go` +- `apps/backend/internal/task/handlers/task_http_handlers.go` +- `apps/backend/internal/task/handlers/task_http_handlers_test.go` + +## Dependencies + +- Task 01 provides the canonical explicit-path validation boundary. + +## Inputs + +- Spec: identity-bound refresh and destructive-operation scenarios. +- Existing post-create fresh-branch compensation in `task_http_handlers.go`. +- Existing repository and task-repository persistence interfaces. + +## Output Contract + +Report identity resolution changes, preservation of destructive-operation safeguards, red/green test +evidence, files, commands, blockers, and update this task plus `plan.md` to done. diff --git a/docs/plans/explicit-local-repository-trust/task-03-frontend-validation-contract.md b/docs/plans/explicit-local-repository-trust/task-03-frontend-validation-contract.md new file mode 100644 index 0000000000..02097ebe6c --- /dev/null +++ b/docs/plans/explicit-local-repository-trust/task-03-frontend-validation-contract.md @@ -0,0 +1,55 @@ +--- +id: "03-frontend-validation-contract" +title: "Frontend validation contract" +status: done +wave: 3 +depends_on: ["01-explicit-path-contract", "02-identity-bound-git-operations"] +plan: "plan.md" +spec: "../../specs/workspaces/local-repositories.md" +--- + +# Task 03: Frontend Validation Contract + +## Acceptance + +- The Add Local Repository dialog treats an existing Git repository as valid regardless of the + deprecated `allowed` response value. +- Existing loading, success, error, keyboard, desktop, and mobile layout behavior is unchanged. +- A focused unit test prevents reintroducing discovery-root containment into manual validity. + +## Verification + +From `apps/web`: + +```bash +rtk pnpm test -- app/settings/workspace/workspace-repositories-validation.test.ts +rtk pnpm run typecheck +``` + +From `apps/`: + +```bash +rtk pnpm --filter @kandev/web lint +``` + +## Files Likely Touched + +- `apps/web/app/settings/workspace/workspace-repositories-client.tsx` +- `apps/web/app/settings/workspace/workspace-repositories-validation.ts` +- `apps/web/app/settings/workspace/workspace-repositories-validation.test.ts` +- `apps/web/lib/types/http.ts` + +## Dependencies + +- Tasks 01 and 02 establish the backend response and identity behavior. + +## Inputs + +- Spec: manual validation API and user scenarios. +- Mobile-parity rule: this is state/contract normalization inside an existing responsive dialog; no + layout or touch control changes are planned. Task 04 supplies real desktop and mobile flow proof. + +## Output Contract + +Report the contract change, tests, files, typecheck/lint results, visual behavior risks, blockers, and +update this task plus `plan.md` to done. diff --git a/docs/plans/explicit-local-repository-trust/task-04-cross-platform-regression.md b/docs/plans/explicit-local-repository-trust/task-04-cross-platform-regression.md new file mode 100644 index 0000000000..dd31079dd8 --- /dev/null +++ b/docs/plans/explicit-local-repository-trust/task-04-cross-platform-regression.md @@ -0,0 +1,60 @@ +--- +id: "04-cross-platform-regression" +title: "Cross-platform repository regression coverage" +status: done +wave: 4 +depends_on: ["01-explicit-path-contract", "02-identity-bound-git-operations", "03-frontend-validation-contract"] +plan: "plan.md" +spec: "../../specs/workspaces/local-repositories.md" +--- + +# Task 04: Cross-Platform Repository Regression Coverage + +## Acceptance + +- A Windows-native backend test covers drive-letter casing, separators, and a repository outside + configured discovery roots, and the existing Windows CI job runs it. +- Desktop and mobile Playwright flows add and save a real repository outside automatic discovery + roots. +- Public configuration documentation clearly limits discovery roots to automatic scanning. + +## Verification + +From `apps/backend`: + +```bash +rtk go test -v ./internal/task/service -run 'Test.*ExplicitLocalRepository.*Windows|TestValidateLocalRepositoryPath' +``` + +From `apps/web` after rebuilding the production web/backend assets required by E2E: + +```bash +rtk pnpm e2e -- e2e/tests/settings/repository-add-local.spec.ts --project=chromium +rtk pnpm e2e -- e2e/tests/settings/mobile-repository-add-local.spec.ts --project=mobile-chrome +``` + +## Files Likely Touched + +- `apps/backend/internal/task/service/repository_discovery_windows_test.go` +- `.github/workflows/backend-tests.yml` +- `apps/web/e2e/tests/settings/repository-add-local.spec.ts` +- `apps/web/e2e/tests/settings/mobile-repository-add-local.spec.ts` +- `docs/public/configuration.md` +- `docs/configuration.md` +- `docs/specs/INDEX.md` +- `docs/decisions/INDEX.md` + +## Dependencies + +- Tasks 01-03 provide the integrated behavior under test. + +## Inputs + +- Spec scenarios for Windows native paths, discovery isolation, persistence, and invalid paths. +- Existing E2E backend HOME isolation and settings fixtures. +- Existing Windows backend workflow in `.github/workflows/backend-tests.yml`. + +## Output Contract + +Report cross-platform and browser evidence, docs changed, exact commands, skipped checks with reasons, +blockers, and update this task plus `plan.md` to done. diff --git a/docs/public/configuration.md b/docs/public/configuration.md index fec18bf504..48690c5d6a 100644 --- a/docs/public/configuration.md +++ b/docs/public/configuration.md @@ -142,7 +142,7 @@ Debug output may contain repository paths, subprocess output, prompts, file cont | YAML key | Environment variable | Default | Current behavior | |---|---|---|---| -| `repositoryDiscovery.roots` | `KANDEV_REPOSITORYDISCOVERY_ROOTS` | `[]` | Local roots exposed to repository discovery. Prefer absolute paths. Array encoding through environment variables is Viper-dependent; YAML is clearer. | +| `repositoryDiscovery.roots` | `KANDEV_REPOSITORYDISCOVERY_ROOTS` | `[]` | Roots traversed by automatic repository discovery. Explicitly selected repository paths need not be included. Prefer absolute paths. Array encoding through environment variables is Viper-dependent; YAML is clearer. | | `repositoryDiscovery.maxDepth` | `KANDEV_REPOSITORYDISCOVERY_MAXDEPTH` | `5` | Positive directory traversal depth. | | `worktree.enabled` | `KANDEV_WORKTREE_ENABLED` | `true` | Enables the worktree provider. | | `worktree.defaultBranch` | `KANDEV_WORKTREE_DEFAULTBRANCH` | `main` | Accepted compatibility field; current task behavior uses each repository's stored/detected default branch instead. | @@ -151,7 +151,7 @@ Debug output may contain repository paths, subprocess output, prompts, file cont | `worktree.pullTimeoutSeconds` | `KANDEV_WORKTREE_PULLTIMEOUTSECONDS` | `60` | Git pull timeout during worktree preparation. | | `repoClone.basePath` | `KANDEV_REPOCLONE_BASEPATH` | `/repos` | Base directory for provider-backed clones. A leading `~/` expands. | -Discovery roots grant Kandev visibility into local filesystem trees and repositories. Scope them narrowly. Worktrees and clones can contain credentials or generated files ignored by Git; review repository copy-file and setup/cleanup settings before remote execution. See [Git operations](./git-operations.md). +Discovery roots bound automatic filesystem traversal, so scope them narrowly. They do not authorize explicitly selected repository paths: **Add Local Repository** validates and saves the exact accessible Git repository the user chooses without widening automatic scans. Worktrees and clones can contain credentials or generated files ignored by Git; review repository copy-file and setup/cleanup settings before remote execution. See [Git operations](./git-operations.md). ### Debug configuration @@ -190,6 +190,9 @@ repositoryDiscovery: - "/srv/repositories" ``` +This example changes automatic discovery only. An explicitly selected repository may live outside +`/srv/repositories` if the Kandev process can access and validate it. + A complete shape, including compatibility fields, is: ```yaml @@ -249,7 +252,7 @@ logging: compress: true repositoryDiscovery: - roots: [] + roots: [] # automatic scan roots; explicit paths need not be included maxDepth: 5 worktree: diff --git a/docs/public/use-kandev.md b/docs/public/use-kandev.md index 6dffd85593..b69bb12914 100644 --- a/docs/public/use-kandev.md +++ b/docs/public/use-kandev.md @@ -55,9 +55,9 @@ The first-run dialog scans supported agent CLIs, lets you inspect detected profi 1. Open **Settings > Workspaces > Default Workspace > Repositories**. If you created or renamed the workspace, choose that workspace instead. 2. Select **Add Local Repository**. -3. Choose a discovered repository, or enter an absolute path and select **Validate**. The backend accepts only an existing Git repository within its configured discovery roots (the current user's home directory by default) or Kandev's configured clone base. +3. Choose a discovered repository, or enter an absolute path and select **Validate**. The backend accepts any existing Git repository the Kandev process can access. Configured discovery roots bound automatic scans; they do not restrict an explicit path. 4. Select **Use Repository**. This opens an unsaved repository card. -5. Review the repository name, worktree branch template, pull behavior, setup/cleanup/dev scripts, copied files, and custom commands. Then select **Save**. +5. Review the repository name, worktree branch template, pull behavior, setup/cleanup/dev scripts, copied files, and custom commands. Then select **Save changes**. New local repository records default to: @@ -69,6 +69,8 @@ New local repository records default to: Scripts execute in agent workspaces and therefore belong to the trust boundary. Do not add an unreviewed command or copy pattern. Repository deletion is irreversible in the UI and is blocked while an active task session still references the repository. +Repositories saved by an older Kandev version may still contain a path spelling with symbolic-link components. If branch operations report that such a saved path resolves to a different location after upgrading, edit and save the repository path again to record its current canonical location. Kandev does not silently accept the new resolution because that would also accept a saved path whose symbolic-link target was changed after registration. + Remote repository and issue/PR URLs are not added from this settings page. Use the **Remote** tab in **New Task** after configuring GitHub, or paste a supported GitHub URL there. See [Integrations](integrations.md) and [Tasks and workflows](tasks-and-workflows.md). ## Configure an agent profile @@ -138,7 +140,7 @@ Common corrections: - If an agent is absent after installation, run **Rescan** and inspect the host terminal's `PATH`. - If a profile has no usable model or mode, authenticate the CLI, rescan, and reopen the profile. Capability probing can heal selections that an upgraded CLI removed. -- If repository validation fails, use an absolute path inside an allowed discovery root and confirm it is a Git working tree. +- If repository validation fails, use an absolute path to an existing, accessible Git working tree. Discovery roots control automatic scans only; they do not restrict an explicit path. - If a worktree cannot be prepared, resolve dirty/conflicting branch state, remote authentication, pull errors, setup-script failures, and disk exhaustion before retrying. - If the browser did not open, use the URL printed by the launcher or start with `--headless`; do not assume port `38429` when the launcher selected a fallback. diff --git a/docs/specs/INDEX.md b/docs/specs/INDEX.md index bc91dac13a..d75f02e96d 100644 --- a/docs/specs/INDEX.md +++ b/docs/specs/INDEX.md @@ -93,6 +93,7 @@ Per-workspace credentials and triage triggers for external services. | Spec | Status | |---|---| | [deletion](workspaces/deletion.md) | shipped | +| [local-repositories](workspaces/local-repositories.md) | shipped | ## costs/ — cost tracking & budgets diff --git a/docs/specs/workspaces/local-repositories.md b/docs/specs/workspaces/local-repositories.md new file mode 100644 index 0000000000..4a4662c200 --- /dev/null +++ b/docs/specs/workspaces/local-repositories.md @@ -0,0 +1,124 @@ +--- +status: shipped +created: 2026-07-20 +owner: kandev +--- + +# Local Workspace Repositories + +## Why + +Users need to connect repositories already present on the machine running Kandev, including native +Windows repositories outside the user's home directory. Explicitly adding one repository should +work without widening automatic filesystem scans or editing packaged runtime configuration. + +## What + +- A user can add a local Git repository by entering or selecting an absolute path that the Kandev + process can access. +- Manual selection is valid independently of `repositoryDiscovery.roots`; those roots govern only + automatic discovery scans. +- Kandev validates and canonicalizes a non-empty local repository path before saving it. A saved + repository records the exact canonical path the user selected. +- Trusting one repository does not trust its parent directory, filesystem volume, or sibling + repositories. +- Saved repositories remain usable for branch listing, current status, refresh, task creation, and + fresh-branch workflows after restart. +- A saved repository must continue resolving to its recorded canonical location. Git metadata + outside that location is accepted only for a verifiable linked worktree with reciprocal metadata. +- Provider-backed repositories may be saved without a local path and are unaffected until Kandev + materializes a local clone. +- Path behavior is platform-native, including Windows drive-letter paths and UNC paths. + +Decision: [ADR-2026-07-20-explicit-local-repository-trust](../../decisions/2026-07-20-explicit-local-repository-trust.md). + +## Data Model + +The existing `repositories` record is the durable grant: + +| Field | Contract | +| --- | --- | +| `id` | Stable repository identity used by later Git operations. | +| `workspace_id` | Workspace that owns the repository grant. | +| `source_type` | `local` for explicitly selected on-machine repositories; `provider` may remain pathless. | +| `local_path` | Canonical absolute path for a saved local repository. Empty is permitted for pathless provider repositories. | + +No parent-directory grant or install-wide discovery-root record is created. + +## API Surface + +- `GET /api/v1/workspaces/:id/repositories/discover` + continues scanning only configured discovery roots. A caller-provided `root` must remain within + those roots. +- `GET /api/v1/workspaces/:id/repositories/validate?path=...` + validates an explicitly selected path without applying discovery-root containment. It returns the + existing path, existence, Git, default-branch, and message fields. The legacy `allowed` field is + retained for compatibility but no longer represents discovery-root containment. +- `POST /api/v1/workspaces/:id/repositories` and `PATCH /api/v1/repositories/:id` + validate and canonicalize non-empty local paths server-side. Invalid paths return a 4xx response + and are not persisted. +- Read-only pre-registration branch and local-status requests may use an explicit raw path. +- Fetch and destructive fresh-branch operations resolve a persisted repository ID before touching + the filesystem. +- Workspace-qualified repository requests reject IDs owned by another workspace before provider or + filesystem access. + +## Permissions + +This feature follows Kandev's current trusted-local-user model: explicitly selecting or saving a +repository is a user grant to access that exact path. Automatic discovery remains constrained by +deployment configuration. A future multi-user authorization model must gate repository grants +directly rather than treating discovery roots as an authorization mechanism. + +## Failure Modes + +| Condition | Observable behavior | +| --- | --- | +| Path is missing | Validation reports that the path does not exist; create/update returns 4xx. | +| Path is not a directory | Validation reports that it is not a directory; create/update returns 4xx. | +| Directory is not a Git repository | Validation reports that it is not a Git repository; create/update returns 4xx. | +| Canonicalization or access fails | The operation fails without persisting or mutating repository state. | +| `.git` metadata points at an unrelated repository or unverifiable external metadata | Validation fails and the path is not persisted. | +| A saved path later resolves to a different canonical location | Identity-bound reads and mutations fail closed. | +| A pre-canonical saved path contains symbolic-link components | The user re-saves it once to persist its canonical location. | +| Saved repository later disappears | Read and Git operations surface the filesystem error; the stored grant remains until edited or deleted. | +| Automatic scan requests an unconfigured root | Discovery rejects the request and does not scan it. | +| Destructive request supplies only an untrusted raw path | The operation fails closed and does not run Git. | + +## Persistence Guarantees + +The canonical `repositories.local_path` survives backend and launcher restarts through the existing +repository store. No in-memory root mutation or packaged `config.yaml` edit is required. Deleting +the repository record removes that exact durable grant from the workspace. + +## Scenarios + +- **GIVEN** automatic discovery is rooted at the user's home directory, **WHEN** a Windows user + manually validates and saves `D:\Projects\app`, **THEN** Kandev accepts the repository and persists + its canonical native path. +- **GIVEN** a manually saved repository outside every discovery root, **WHEN** the user lists or + refreshes its branches after a restart, **THEN** Kandev resolves the saved repository ID and the + operation succeeds. +- **GIVEN** a manually saved repository outside every discovery root, **WHEN** the user confirms a + fresh-branch operation for it, **THEN** Kandev resolves the saved repository ID before changing + the working tree. +- **GIVEN** `D:\Projects\app` was explicitly saved, **WHEN** automatic discovery runs, **THEN** it does + not scan `D:\Projects` unless that directory is separately configured as a discovery root. +- **GIVEN** a missing directory, ordinary directory, or inaccessible path, **WHEN** a user tries to + save it as a local repository, **THEN** the backend rejects the request even if the frontend did + not validate first. +- **GIVEN** path spelling differs only by Windows drive-letter casing or trailing separators, + **WHEN** Kandev canonicalizes and compares the path, **THEN** it treats the spellings according to + Windows filesystem semantics. + +## Out of Scope + +- A settings page for managing install-wide discovery roots. +- Automatically trusting an entire drive, home-directory parent, or repository parent directory. +- Changing provider clone placement or container host-path mounting. +- Introducing multi-user authentication or repository-grant roles. +- Making packaged runtime configuration files writable from the UI. + +## Implementation Plan + +See [Explicit Local Repository Trust plan](../../plans/explicit-local-repository-trust/plan.md).