Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions sql-scripts/03_locale.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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.'),
Expand Down Expand Up @@ -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'),
Expand Down
21 changes: 21 additions & 0 deletions src/Libraries/Taskist.Core/Common/TaskVisibility.cs
Original file line number Diff line number Diff line change
@@ -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<int> accessibleProjectIds, IReadOnlySet<int> 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
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -239,6 +240,10 @@ public async Task<IActionResult> Create(BacklogModel model,
List<CustomFieldValueModel> 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;

Expand Down Expand Up @@ -518,6 +523,9 @@ public async Task<IActionResult> UnlinkBranch(int id, int branchId)
[CheckPermission(nameof(PermissionProvider.ManageBacklog))]
public async Task<IActionResult> 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<string>() });

var (branches, error) = await _gitBranchService.SearchBranchesAsync(id, term, repositoryId);
var task = await _backlogItemService.GetByIdAsync(id);
var repositories = task == null ? [] : await _gitRepositoryService.GetProjectContextsAsync(task.ProjectId);
Expand Down Expand Up @@ -570,15 +578,34 @@ public async Task<IActionResult> BatchUpdate(string ids)
}

[HttpPost]
[CheckPermission(nameof(PermissionProvider.ManageBacklog))]
public async Task<IActionResult> 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<int>();
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)
: [];
Expand Down Expand Up @@ -614,10 +641,14 @@ public async Task<IActionResult> 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
});
}

Expand All @@ -635,6 +666,9 @@ await _backlogItemService.UpdateBatchAsync(model.TaskIds, model.TaskTypeId, mode

public async Task<IActionResult> Documents(int id)
{
if (!await _backlogItemService.CanViewTaskAsync(id))
return AccessDeniedPartial();

var data = await _backlogItemService.GetAllDocumentAsync(id);
var model = data.Select(s => new BacklogDocumentGridModel
{
Expand Down Expand Up @@ -710,6 +744,9 @@ public async Task<IActionResult> DeleteDocument(int token)
[CheckPermission(nameof(PermissionProvider.ManageBacklog))]
public async Task<IActionResult> History(int id)
{
if (!await _backlogItemService.CanViewTaskAsync(id))
return AccessDeniedPartial();

var data = await _backlogItemService.GetAllHistoryAsync(id);
return PartialView(BacklogHistoryMapper.ToGridModels(data));
}
Expand All @@ -721,6 +758,9 @@ public async Task<IActionResult> History(int id)
[CheckPermission(nameof(PermissionProvider.ManageBacklog))]
public async Task<IActionResult> Comments(int id)
{
if (!await _backlogItemService.CanViewTaskAsync(id))
return AccessDeniedPartial();

var data = await _backlogItemService.GetAllCommentsAsync(id);
var model = new BacklogCommentModel()
{
Expand All @@ -743,6 +783,13 @@ public async Task<IActionResult> Comments(int id)
[CheckPermission(nameof(PermissionProvider.ManageBacklog))]
public async Task<IActionResult> 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)
Expand Down Expand Up @@ -1450,7 +1497,7 @@ public async Task<JsonResponseModel> UpdateCustomField(int id, int reference, st
public async Task<ClosingCommentStatusModel> 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);
Expand All @@ -1477,7 +1524,8 @@ public async Task<bool> CheckStatusCommentsRequired(int status)
public async Task<JsonResult> GetParentTasks(string q, int id)
{
var model = new List<SelectListItem>();
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)
{
Expand Down Expand Up @@ -1617,7 +1665,8 @@ public async Task<IActionResult> ExportToExcel(int[] createdby,
public async Task<IActionResult> 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);
Expand Down Expand Up @@ -1763,6 +1812,15 @@ private async Task<int> ResolveProjectIdAsync(int projectId)
return accessible.FirstOrDefault()?.Id ?? 0;
}

private async Task<Func<Backlog, bool>> 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<BacklogGridModel> GetProjectAccess(int projectId)
{
var loggedUser = await _workContext.GetCurrentUserAsync();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 = $('<div class="comment-item">'
+ '<div class="comment-avatar"></div>'
+ '<div class="comment-body">'
Expand Down
55 changes: 55 additions & 0 deletions src/Tests/Taskist.Tests/Common/TaskVisibilityTests.cs
Original file line number Diff line number Diff line change
@@ -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<int> Member = [1];
private static readonly HashSet<int> ViewAll = [1];
private static readonly HashSet<int> 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
}
Loading