diff --git a/CHANGELOG.md b/CHANGELOG.md index 72f468e..141d3be 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,16 @@ Each release lists **Upgrade notes** when an install needs action beyond the ste - **Watch tasks** (Configuration → Work items → *Task watchers*, off by default): a Watch / Watching button with the watcher count and list in the task header, and a **Watching** filter (bell menu → *Tasks I'm watching*). The creator, developer and tester watch a task automatically, as does anyone who comments on it; anyone can unwatch, and that choice sticks. Watchers get an in-app notification when the status, developer/tester or comments change, including changes from Git merge requests, bulk updates and issue sync, but never for their own changes. Members who can no longer see the task stop receiving them. *E-mail watchers* also sends them by e-mail. ([#15](https://github.com/Taskist/taskist/issues/15)) +### Security + +- Backlog actions now check that you can see or edit the task, like the task page already did: + - **Bulk update** requires the Backlog permission and changes only the tasks you can edit; others are skipped and counted in the result message. + - **Creating a task** requires reporting rights in the chosen project. + - **Comments, history and the attachment list** are only shown, and **comments** only accepted, for tasks you can see. + - **The parent-task search, the release export and the branch search** leave out tasks you can't see. + + Previously any signed-in user with the Backlog permission could read or change tasks in projects they don't belong to by calling these actions directly. + ### Upgrade notes - New additive migration `AddBacklogWatcher` (table `BacklogWatcher`), applied automatically by Docker; manual installs run `dotnet ef database update` or the regenerated `sql-scripts/01_schema.sql`. Re-run `sql-scripts/03_locale.sql` for the new labels. diff --git a/sql-scripts/03_locale.sql b/sql-scripts/03_locale.sql index dbd77ab..d071850 100644 --- a/sql-scripts/03_locale.sql +++ b/sql-scripts/03_locale.sql @@ -64,6 +64,7 @@ FROM (VALUES (N'AnnouncementModel.ValidTo.RangeMsg', N'Valid To must be on or after Valid From'), (N'AnnouncementPage.Title', N'Announcements'), (N'Backlog.Assignee', N'Developer'), + (N'Backlog.BatchUpdate.Skipped', N'{0} task(s) you can''t edit were left unchanged.'), (N'Backlog.Branch.Base', N'Create from'), (N'Backlog.Branch.ConnectButton', N'Connect my Git account'), (N'Backlog.Branch.ConnectWhy', N'Branches are created with your own GitLab account, so GitLab shows you as the creator and applies your project permissions. You only need to connect once.'), @@ -174,6 +175,7 @@ FROM (VALUES (N'Backlog.Mr.TitleRequired', N'Enter a title.'), (N'Backlog.Mr.WillMove', N'Task {0} will move to "{1}" when the merge request is created (drafts wait until marked ready).'), (N'Backlog.NotAuthorizedEditMsg', N'You are not authorized to edit this task.'), + (N'Backlog.NotAuthorizedViewMsg', N'You don''t have access to this task.'), (N'Backlog.Parent', N'Parent Task'), (N'Backlog.PlannedStartDate', N'Planned Start'), (N'Backlog.Project', N'Project'), diff --git a/src/Libraries/Taskist.Core/Common/TaskVisibility.cs b/src/Libraries/Taskist.Core/Common/TaskVisibility.cs new file mode 100644 index 0000000..7ba0546 --- /dev/null +++ b/src/Libraries/Taskist.Core/Common/TaskVisibility.cs @@ -0,0 +1,21 @@ +using Taskist.Core.Domain.WorkItems; + +namespace Taskist.Core.Common; + +public static class TaskVisibility +{ + #region Methods + + public static bool CanSee(Backlog task, int userId, IReadOnlySet accessibleProjectIds, IReadOnlySet viewAllProjectIds) + { + if (task == null || task.Deleted || userId <= 0) + return false; + + if (!accessibleProjectIds.Contains(task.ProjectId)) + return false; + + return viewAllProjectIds.Contains(task.ProjectId) || task.AssigneeId == userId || task.TesterId == userId; + } + + #endregion +} diff --git a/src/Presentation/Taskist.Web/Controllers/WorkItems/BacklogController.cs b/src/Presentation/Taskist.Web/Controllers/WorkItems/BacklogController.cs index 118df61..d6e5177 100644 --- a/src/Presentation/Taskist.Web/Controllers/WorkItems/BacklogController.cs +++ b/src/Presentation/Taskist.Web/Controllers/WorkItems/BacklogController.cs @@ -5,6 +5,7 @@ using Taskist.Core.Domain.Masters; using Taskist.Core.Domain.Settings; using Taskist.Core.Domain.Users; +using Taskist.Core.Domain.WorkItems; using Taskist.Core.Dtos.Git; using Taskist.Core.Dtos.WorkItems; using Taskist.Core.Enums; @@ -239,6 +240,10 @@ public async Task Create(BacklogModel model, List fieldValues, bool addNew) { + var createAccess = await GetProjectAccess(model.ProjectId); + if (!createAccess.CanReport && !createAccess.CanEdit && !createAccess.CanClose) + return AccessDenied(); + var loggedUser = await _workContext.GetCurrentUserAsync(); var fieldValuesErrors = false; @@ -518,6 +523,9 @@ public async Task UnlinkBranch(int id, int branchId) [CheckPermission(nameof(PermissionProvider.ManageBacklog))] public async Task SearchBranches(int id, string? term, int? repositoryId = null) { + if (!await _backlogItemService.CanViewTaskAsync(id)) + return Json(new { status = HttpStatusCode.ValidationError, message = await _localizationService.GetResourceAsync("Backlog.NotAuthorizedViewMsg"), branches = Array.Empty() }); + var (branches, error) = await _gitBranchService.SearchBranchesAsync(id, term, repositoryId); var task = await _backlogItemService.GetByIdAsync(id); var repositories = task == null ? [] : await _gitRepositoryService.GetProjectContextsAsync(task.ProjectId); @@ -570,15 +578,34 @@ public async Task BatchUpdate(string ids) } [HttpPost] + [CheckPermission(nameof(PermissionProvider.ManageBacklog))] public async Task BatchUpdate(BacklogBatchUpdateModel model) { if (ModelState.IsValid) { - var taskIds = (model.TaskIds ?? string.Empty) + var requestedIds = (model.TaskIds ?? string.Empty) .Split(',', StringSplitOptions.RemoveEmptyEntries) .Select(x => x.ToInt()) + .Where(x => x > 0) + .Distinct() .ToArray(); + var editableIds = new List(); + foreach (var requestedId in requestedIds) + if (await _backlogItemService.CanEditTaskAsync(requestedId)) + editableIds.Add(requestedId); + + if (editableIds.Count == 0) + return Json(new JsonResponseModel + { + Status = HttpStatusCode.ValidationError, + Message = await _localizationService.GetResourceAsync("Backlog.NotAuthorizedEditMsg") + }); + + var taskIds = editableIds.ToArray(); + model.TaskIds = string.Join(",", taskIds); + var skippedCount = requestedIds.Length - taskIds.Length; + var projectIds = taskIds.Length > 0 ? await _backlogItemService.GetProjectIdsByTaskIdsAsync(taskIds) : []; @@ -614,10 +641,14 @@ public async Task BatchUpdate(BacklogBatchUpdateModel model) await _backlogItemService.UpdateBatchAsync(model.TaskIds, model.TaskTypeId, model.ReporterId, model.SeverityId, model.DueDate, model.ModuleId, model.SubModuleId, model.ReleaseId, model.AssigneeId, model.TesterId, model.StatusId); + + var saved = await _localizationService.GetResourceAsync("Message.SaveSuccess"); return Json(new JsonResponseModel { Status = HttpStatusCode.Success, - Message = await _localizationService.GetResourceAsync("Message.SaveSuccess") + Message = skippedCount > 0 + ? $"{saved} {string.Format(await _localizationService.GetResourceAsync("Backlog.BatchUpdate.Skipped"), skippedCount)}" + : saved }); } @@ -635,6 +666,9 @@ await _backlogItemService.UpdateBatchAsync(model.TaskIds, model.TaskTypeId, mode public async Task Documents(int id) { + if (!await _backlogItemService.CanViewTaskAsync(id)) + return AccessDeniedPartial(); + var data = await _backlogItemService.GetAllDocumentAsync(id); var model = data.Select(s => new BacklogDocumentGridModel { @@ -710,6 +744,9 @@ public async Task DeleteDocument(int token) [CheckPermission(nameof(PermissionProvider.ManageBacklog))] public async Task History(int id) { + if (!await _backlogItemService.CanViewTaskAsync(id)) + return AccessDeniedPartial(); + var data = await _backlogItemService.GetAllHistoryAsync(id); return PartialView(BacklogHistoryMapper.ToGridModels(data)); } @@ -721,6 +758,9 @@ public async Task History(int id) [CheckPermission(nameof(PermissionProvider.ManageBacklog))] public async Task Comments(int id) { + if (!await _backlogItemService.CanViewTaskAsync(id)) + return AccessDeniedPartial(); + var data = await _backlogItemService.GetAllCommentsAsync(id); var model = new BacklogCommentModel() { @@ -743,6 +783,13 @@ public async Task Comments(int id) [CheckPermission(nameof(PermissionProvider.ManageBacklog))] public async Task CommentCreate(int id, string comment, bool postToIssue = false) { + if (string.IsNullOrWhiteSpace(comment) || !await _backlogItemService.CanViewTaskAsync(id)) + return Json(new + { + success = false, + message = await _localizationService.GetResourceAsync("Backlog.NotAuthorizedViewMsg") + }); + postToIssue = postToIssue && await _issueSyncService.HasActiveLinkAsync(id); await _backlogItemService.InsertCommentAsync(id, comment, UserId, UserName, postToIssue); if (postToIssue) @@ -1450,7 +1497,7 @@ public async Task UpdateCustomField(int id, int reference, st public async Task GetClosingCommentStatus(int taskType, int status, int id = 0) { var response = new ClosingCommentStatusModel(); - if (id <= 0) + if (id <= 0 || !await _backlogItemService.CanViewTaskAsync(id)) return response; var requirement = await _closingRequirementService.EvaluateAsync(id, status, taskType); @@ -1477,7 +1524,8 @@ public async Task CheckStatusCommentsRequired(int status) public async Task GetParentTasks(string q, int id) { var model = new List(); - var entities = await _backlogItemService.SearchByTitleAsync(q, id); + var canSee = await TaskVisibilityAsync(); + var entities = (await _backlogItemService.SearchByTitleAsync(q, id)).Where(canSee); foreach (var item in entities) { @@ -1617,7 +1665,8 @@ public async Task ExportToExcel(int[] createdby, public async Task ExportReleaseToExcel(int releaseId) { var release = await _releaseService.GetByIdAsync(releaseId); - var entities = (await _backlogItemService.GetAllByReleaseAsync(releaseId)).ToList(); + var canSee = await TaskVisibilityAsync(); + var entities = (await _backlogItemService.GetAllByReleaseAsync(releaseId)).Where(canSee).ToList(); var taskIds = entities.Select(x => x.Id).ToArray(); var tagNames = await _tagService.GetTagNamesByTaskIdsAsync(taskIds); @@ -1763,6 +1812,15 @@ private async Task ResolveProjectIdAsync(int projectId) return accessible.FirstOrDefault()?.Id ?? 0; } + private async Task> TaskVisibilityAsync() + { + var userId = UserId; + var accessible = (await _userService.GetAllAccessibleProjects(userId)).Select(x => x.Id).ToHashSet(); + var viewAll = (await _userService.GetAllAccessibleProjects(userId, fetchOnlyCanViewOthersTask: true)).Select(x => x.Id).ToHashSet(); + + return x => TaskVisibility.CanSee(x, userId, accessible, viewAll); + } + private async Task GetProjectAccess(int projectId) { var loggedUser = await _workContext.GetCurrentUserAsync(); diff --git a/src/Presentation/Taskist.Web/wwwroot/js/pages/backlog/backlog-comments.js b/src/Presentation/Taskist.Web/wwwroot/js/pages/backlog/backlog-comments.js index 739ab9c..2685d04 100644 --- a/src/Presentation/Taskist.Web/wwwroot/js/pages/backlog/backlog-comments.js +++ b/src/Presentation/Taskist.Web/wwwroot/js/pages/backlog/backlog-comments.js @@ -30,6 +30,10 @@ var BacklogComments = (function () { var dto = { id: $root.data("task-id"), comment: comment, postToIssue: $root.find(".comment-post-to-issue").is(":checked") }; JSManager.ajaxPost($root.data("create-url"), dto, "comment-box", "Processing...", function (response) { + if (!response || response.success !== true) { + JSManager.showError(response && response.message ? response.message : "Failed"); + return; + } var $item = $('
' + '
' + '
' diff --git a/src/Tests/Taskist.Tests/Common/TaskVisibilityTests.cs b/src/Tests/Taskist.Tests/Common/TaskVisibilityTests.cs new file mode 100644 index 0000000..0c77ab0 --- /dev/null +++ b/src/Tests/Taskist.Tests/Common/TaskVisibilityTests.cs @@ -0,0 +1,55 @@ +using Taskist.Core.Common; +using Taskist.Core.Domain.WorkItems; + +namespace Taskist.Tests.Common; + +public class TaskVisibilityTests +{ + #region Helpers + + private static readonly HashSet Member = [1]; + private static readonly HashSet ViewAll = [1]; + private static readonly HashSet None = []; + + private static Backlog Task(int projectId = 1, int? assignee = null, int? tester = null, bool deleted = false) => + new() { ProjectId = projectId, AssigneeId = assignee, TesterId = tester, Deleted = deleted }; + + #endregion + + #region CanSee + + [Fact] + public void MemberWhoCanViewOthers_SeesAnyTaskInTheProject() + { + Assert.True(TaskVisibility.CanSee(Task(), 7, Member, ViewAll)); + } + + [Fact] + public void MemberWithoutViewOthers_SeesOnlyTasksTheyAreAssignedOrTesting() + { + Assert.False(TaskVisibility.CanSee(Task(), 7, Member, None)); + Assert.True(TaskVisibility.CanSee(Task(assignee: 7), 7, Member, None)); + Assert.True(TaskVisibility.CanSee(Task(tester: 7), 7, Member, None)); + } + + [Fact] + public void NonMember_SeesNothing_EvenWhenAssigned() + { + Assert.False(TaskVisibility.CanSee(Task(projectId: 2, assignee: 7), 7, Member, ViewAll)); + } + + [Fact] + public void DeletedOrMissingTask_IsHidden() + { + Assert.False(TaskVisibility.CanSee(Task(deleted: true), 7, Member, ViewAll)); + Assert.False(TaskVisibility.CanSee(null!, 7, Member, ViewAll)); + } + + [Fact] + public void AnonymousUser_SeesNothing() + { + Assert.False(TaskVisibility.CanSee(Task(assignee: 0), 0, Member, ViewAll)); + } + + #endregion +}