Skip to content

The Unified and Autonomous Development Platform

feat: CRUD API end points for code comments and replies

Robin Shenfbec1d57f543
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/CodeCommentReplyResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/CodeCommentReplyResource.java
new file mode 100644
index 0000000000..f053e4463d
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/CodeCommentReplyResource.java
@@ -0,0 +1,129 @@
+package io.onedev.server.rest.resource;
+
+import java.io.Serializable;
+
+import jakarta.inject.Inject;
+import jakarta.inject.Singleton;
+import jakarta.validation.Valid;
+import jakarta.validation.constraints.NotBlank;
+import jakarta.validation.constraints.NotNull;
+import jakarta.validation.constraints.Size;
+import jakarta.ws.rs.Consumes;
+import jakarta.ws.rs.DELETE;
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.POST;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.PathParam;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+
+import org.apache.shiro.authz.UnauthenticatedException;
+import org.apache.shiro.authz.UnauthorizedException;
+
+import io.onedev.server.model.CodeCommentReply;
+import io.onedev.server.rest.annotation.Api;
+import io.onedev.server.rest.annotation.EntityCreate;
+import io.onedev.server.security.SecurityUtils;
+import io.onedev.server.service.CodeCommentReplyService;
+import io.onedev.server.service.CodeCommentService;
+
+@Path("/code-comment-replies")
+@Consumes(MediaType.APPLICATION_JSON)
+@Produces(MediaType.APPLICATION_JSON)
+@Singleton
+public class CodeCommentReplyResource {
+
+ private final CodeCommentReplyService replyService;
+
+ private final CodeCommentService commentService;
+
+ @Inject
+ public CodeCommentReplyResource(CodeCommentReplyService replyService, CodeCommentService commentService) {
+ this.replyService = replyService;
+ this.commentService = commentService;
+ }
+
+ @Api(order=100)
+ @Path("/{replyId}")
+ @GET
+ public CodeCommentReply getReply(@PathParam("replyId") Long replyId) {
+ var reply = replyService.load(replyId);
+ if (!SecurityUtils.canReadCode(reply.getComment().getProject()))
+ throw new UnauthorizedException();
+ return reply;
+ }
+
+ @Api(order=200, description="Create a code comment reply as the authenticated user")
+ @POST
+ public Long createReply(@NotNull @Valid CodeCommentReplyCreateData data) {
+ var user = SecurityUtils.getUser();
+ if (user == null)
+ throw new UnauthenticatedException();
+ var comment = commentService.load(data.getCommentId());
+ if (!SecurityUtils.canReadCode(comment.getProject()))
+ throw new UnauthorizedException();
+ var reply = new CodeCommentReply();
+ reply.setComment(comment);
+ reply.setUser(user);
+ reply.setContent(data.getContent());
+ reply.setCompareContext(comment.getCompareContext());
+ replyService.create(reply);
+ return reply.getId();
+ }
+
+ @Api(order=250, description="Update the content of a code comment reply")
+ @Path("/{replyId}")
+ @POST
+ public Response updateReply(@PathParam("replyId") Long replyId,
+ @NotBlank @Size(max=CodeCommentReply.MAX_CONTENT_LEN) String content) {
+ var reply = replyService.load(replyId);
+ if (!SecurityUtils.canReadCode(reply.getComment().getProject()) || !SecurityUtils.canModifyOrDelete(reply))
+ throw new UnauthorizedException();
+ if (!reply.getContent().equals(content)) {
+ reply.setContent(content);
+ replyService.update(reply);
+ }
+ return Response.ok().build();
+ }
+
+ @Api(order=300)
+ @Path("/{replyId}")
+ @DELETE
+ public Response deleteReply(@PathParam("replyId") Long replyId) {
+ var reply = replyService.load(replyId);
+ if (!SecurityUtils.canReadCode(reply.getComment().getProject()) || !SecurityUtils.canModifyOrDelete(reply))
+ throw new UnauthorizedException();
+ replyService.delete(reply);
+ return Response.ok().build();
+ }
+
+ @EntityCreate(CodeCommentReply.class)
+ public static class CodeCommentReplyCreateData implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private Long commentId;
+
+ private String content;
+
+ @NotNull
+ public Long getCommentId() {
+ return commentId;
+ }
+
+ public void setCommentId(Long commentId) {
+ this.commentId = commentId;
+ }
+
+ @NotBlank
+ @Size(max=CodeCommentReply.MAX_CONTENT_LEN)
+ public String getContent() {
+ return content;
+ }
+
+ public void setContent(String content) {
+ this.content = content;
+ }
+ }
+}
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/CodeCommentResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/CodeCommentResource.java
index dbb75d1bac..a7ad43588d 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/CodeCommentResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/CodeCommentResource.java
@@ -1,24 +1,53 @@
package io.onedev.server.rest.resource;
+import java.io.Serializable;
+import java.util.Collection;
+import java.util.List;
+
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
+import jakarta.validation.Valid;
+import jakarta.validation.constraints.NotBlank;
+import jakarta.validation.constraints.NotNull;
+import jakarta.validation.constraints.Size;
+import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
+import jakarta.ws.rs.NotAcceptableException;
+import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
+import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
+import org.eclipse.jgit.lib.FileMode;
+import org.eclipse.jgit.lib.ObjectId;
+import org.jspecify.annotations.Nullable;
import io.onedev.server.data.migration.VersionedXmlDoc;
+import io.onedev.server.git.BlobIdent;
import io.onedev.server.service.AuditService;
import io.onedev.server.service.CodeCommentService;
+import io.onedev.server.service.CodeCommentStatusChangeService;
+import io.onedev.server.service.ProjectService;
import io.onedev.server.model.CodeComment;
+import io.onedev.server.model.CodeCommentReply;
+import io.onedev.server.model.CodeCommentStatusChange;
+import io.onedev.server.model.Project;
+import io.onedev.server.model.support.CompareContext;
+import io.onedev.server.model.support.Mark;
import io.onedev.server.rest.annotation.Api;
+import io.onedev.server.rest.annotation.EntityCreate;
+import io.onedev.server.rest.resource.support.RestConstants;
+import io.onedev.server.search.entity.codecomment.CodeCommentQuery;
import io.onedev.server.security.SecurityUtils;
+import io.onedev.server.util.diff.DiffUtils;
+import io.onedev.server.util.diff.WhitespaceOption;
@Path("/code-comments")
@Consumes(MediaType.APPLICATION_JSON)
@@ -30,10 +59,17 @@ public class CodeCommentResource {
private final AuditService auditService;
+ private final ProjectService projectService;
+
+ private final CodeCommentStatusChangeService statusChangeService;
+
@Inject
- public CodeCommentResource(CodeCommentService commentService, AuditService auditService) {
+ public CodeCommentResource(CodeCommentService commentService, AuditService auditService,
+ ProjectService projectService, CodeCommentStatusChangeService statusChangeService) {
this.commentService = commentService;
this.auditService = auditService;
+ this.projectService = projectService;
+ this.statusChangeService = statusChangeService;
}
@Api(order=100)
@@ -46,7 +82,165 @@ public class CodeCommentResource {
return comment;
}
- @Api(order=200)
+ @Api(order=125, description="Get the comment position mapped to a commit using the same line mapping as the pull request UI. "
+ + "The file path is unchanged and trailing whitespace is ignored. Return status code 204 if the position cannot be mapped.")
+ @Path("/{commentId}/mark")
+ @GET
+ @Nullable
+ public Mark getMark(@PathParam("commentId") Long commentId,
+ @QueryParam("commitHash") @NotBlank @Api(description="Full hash of the commit to map the position to") String commitHash) {
+ var comment = commentService.load(commentId);
+ var project = comment.getProject();
+ if (!SecurityUtils.canReadCode(project))
+ throw new UnauthorizedException();
+ validateCommit(project, commitHash, false);
+ var mark = comment.getMark();
+ var targetCommitHash = ObjectId.fromString(commitHash).name();
+ var newBlobIdent = new BlobIdent(targetCommitHash, mark.getPath(), FileMode.REGULAR_FILE.getBits());
+ var newLines = project.readLines(newBlobIdent, WhitespaceOption.IGNORE_TRAILING, false);
+ if (newLines == null)
+ return null;
+ var oldBlobIdent = new BlobIdent(mark.getCommitHash(), mark.getPath(), FileMode.REGULAR_FILE.getBits());
+ var oldLines = project.readLines(oldBlobIdent, WhitespaceOption.IGNORE_TRAILING, true);
+ if (oldLines == null)
+ return null;
+ var range = DiffUtils.mapRange(DiffUtils.mapLines(oldLines, newLines), mark.getRange());
+ return range != null ? new Mark(targetCommitHash, mark.getPath(), range) : null;
+ }
+
+ @Api(order=150, description="Get all replies of a code comment")
+ @Path("/{commentId}/replies")
+ @GET
+ public Collection<CodeCommentReply> getReplies(@PathParam("commentId") Long commentId) {
+ var comment = commentService.load(commentId);
+ if (!SecurityUtils.canReadCode(comment.getProject()))
+ throw new UnauthorizedException();
+ return comment.getReplies();
+ }
+
+ @Api(order=175, description="Query code comments in a project")
+ @GET
+ public List<CodeComment> queryComments(
+ @QueryParam("projectId") @NotNull Long projectId,
+ @QueryParam("query") @Api(description="Syntax of this query is the same as in the project's code comments page", example="unresolved") String query,
+ @QueryParam("offset") @Api(example="0") int offset,
+ @QueryParam("count") @Api(example="100") int count) {
+ var project = projectService.load(projectId);
+ if (!SecurityUtils.canReadCode(project))
+ throw new UnauthorizedException();
+ var subject = SecurityUtils.getSubject();
+ if (!SecurityUtils.isAdministrator(subject) && count > RestConstants.MAX_PAGE_SIZE)
+ throw new NotAcceptableException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
+ var parsedQuery = CodeCommentQuery.parse(project, query, true);
+ return commentService.query(project, null, parsedQuery, offset, count);
+ }
+
+ @Api(order=200, description="Create a code comment as the authenticated user")
+ @POST
+ public Long createComment(@NotNull @Valid CodeCommentCreateData data) {
+ var user = SecurityUtils.getUser();
+ if (user == null)
+ throw new UnauthenticatedException();
+ var project = projectService.load(data.getProjectId());
+ if (!SecurityUtils.canReadCode(project))
+ throw new UnauthorizedException();
+
+ var mark = data.getMark();
+ var context = data.getCompareContext();
+ var request = context.getPullRequest();
+ if (request != null && !request.getProject().equals(project))
+ throw new BadRequestException("Pull request must belong to the comment project");
+ validateCommit(project, mark.getCommitHash(), false);
+ validateCommit(project, context.getOldCommitHash(), true);
+ validateCommit(project, context.getNewCommitHash(), false);
+ if (!mark.getCommitHash().equals(context.getOldCommitHash())
+ && !mark.getCommitHash().equals(context.getNewCommitHash()))
+ throw new BadRequestException("Comment commit must be one of the comparison commits");
+ if (mark.getPath() == null || mark.getPath().isBlank() || mark.getRange() == null)
+ throw new BadRequestException("Comment path and range are required");
+ if (context.getWhitespaceOption() == null)
+ throw new BadRequestException("Comparison whitespace option is required");
+ var range = mark.getRange();
+ if (range.getFromRow() < 0 || range.getToRow() < range.getFromRow()
+ || range.getFromColumn() < -1 || range.getToColumn() < -1
+ || range.getTabWidth() <= 0
+ || range.getFromRow() == range.getToRow() && range.getToColumn() != -1
+ && range.getToColumn() < range.getFromColumn())
+ throw new BadRequestException("Invalid comment range");
+ var blob = project.getBlob(mark.getBlobIdent(), false);
+ if (blob == null || blob.getText() == null)
+ throw new BadRequestException("Comment path must refer to a text file at the specified commit");
+ var lines = blob.getText().getLines();
+ if (range.getToRow() >= lines.size())
+ throw new BadRequestException("Comment range is outside the file");
+
+ var comment = new CodeComment();
+ comment.setProject(project);
+ comment.setUser(user);
+ comment.setContent(data.getContent());
+ comment.setMark(mark);
+ comment.setCompareContext(context);
+ commentService.create(comment);
+ return comment.getId();
+ }
+
+ private void validateCommit(Project project, String commitHash, boolean allowZero) {
+ if (commitHash == null || !ObjectId.isId(commitHash))
+ throw new BadRequestException("A full commit hash is required");
+ if (allowZero && commitHash.equals(ObjectId.zeroId().name()))
+ return;
+ if (project.getRevCommit(commitHash, false) == null)
+ throw new BadRequestException("Commit does not exist in the comment project: " + commitHash);
+ }
+
+ @Api(order=250, description="Update the content of an existing code comment")
+ @Path("/{commentId}")
+ @POST
+ public Response updateComment(@PathParam("commentId") Long commentId,
+ @NotBlank @Size(max=CodeComment.MAX_CONTENT_LEN) String content) {
+ var comment = commentService.load(commentId);
+ if (!SecurityUtils.canReadCode(comment.getProject()) || !SecurityUtils.canModifyOrDelete(comment))
+ throw new UnauthorizedException();
+ if (!comment.getContent().equals(content)) {
+ comment.setContent(content);
+ commentService.update(comment);
+ }
+ return Response.ok().build();
+ }
+
+ @Api(order=260, description="Resolve a code comment, optionally adding a note as a reply")
+ @Path("/{commentId}/resolve")
+ @POST
+ public Response resolveComment(@PathParam("commentId") Long commentId,
+ @Size(max=CodeCommentReply.MAX_CONTENT_LEN) String note) {
+ return changeStatus(commentId, true, note);
+ }
+
+ @Api(order=270, description="Unresolve a code comment, optionally adding a note as a reply")
+ @Path("/{commentId}/unresolve")
+ @POST
+ public Response unresolveComment(@PathParam("commentId") Long commentId,
+ @Size(max=CodeCommentReply.MAX_CONTENT_LEN) String note) {
+ return changeStatus(commentId, false, note);
+ }
+
+ private Response changeStatus(Long commentId, boolean resolved, String note) {
+ var comment = commentService.load(commentId);
+ var subject = SecurityUtils.getSubject();
+ if (!SecurityUtils.canReadCode(subject, comment.getProject()) || !SecurityUtils.canChangeStatus(subject, comment))
+ throw new UnauthorizedException();
+ if (comment.isResolved() != resolved) {
+ var change = new CodeCommentStatusChange();
+ change.setComment(comment);
+ change.setUser(SecurityUtils.getUser(subject));
+ change.setResolved(resolved);
+ change.setCompareContext(comment.getCompareContext());
+ statusChangeService.create(change, note);
+ }
+ return Response.ok().build();
+ }
+
+ @Api(order=300)
@Path("/{commentId}")
@DELETE
public Response deleteComment(@PathParam("commentId") Long commentId) {
@@ -58,5 +252,59 @@ public class CodeCommentResource {
auditService.audit(comment.getProject(), "deleted code comment on file \"" + comment.getMark().getPath() + "\" via RESTful API", oldAuditContent, null);
return Response.ok().build();
}
-
+
+ @EntityCreate(CodeComment.class)
+ public static class CodeCommentCreateData implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private Long projectId;
+
+ private String content;
+
+ private Mark mark;
+
+ private CompareContext compareContext;
+
+ @NotNull
+ public Long getProjectId() {
+ return projectId;
+ }
+
+ public void setProjectId(Long projectId) {
+ this.projectId = projectId;
+ }
+
+ @NotBlank
+ @Size(max=CodeComment.MAX_CONTENT_LEN)
+ public String getContent() {
+ return content;
+ }
+
+ public void setContent(String content) {
+ this.content = content;
+ }
+
+ @NotNull
+ @Api(description="Code location: full commitHash, path, and range with zero-based fromRow, fromColumn, "
+ + "toRow and toColumn (end column exclusive). Range tabWidth defaults to 1")
+ public Mark getMark() {
+ return mark;
+ }
+
+ public void setMark(Mark mark) {
+ this.mark = mark;
+ }
+
+ @NotNull
+ @Api(description="Comparison context with full old/new commit hashes and optional pullRequestId. "
+ + "For a comment on a single revision, use the same hash for both commits")
+ public CompareContext getCompareContext() {
+ return compareContext;
+ }
+
+ public void setCompareContext(CompareContext compareContext) {
+ this.compareContext = compareContext;
+ }
+ }
}
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/PullRequestResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/PullRequestResource.java
index ad0b023fc4..2fee671e8f 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/PullRequestResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/PullRequestResource.java
@@ -39,6 +39,7 @@ import io.onedev.commons.utils.StringUtils;
import io.onedev.server.attachment.AttachmentService;
import io.onedev.server.data.migration.VersionedXmlDoc;
import io.onedev.server.model.Build;
+import io.onedev.server.model.CodeComment;
import io.onedev.server.model.PullRequest;
import io.onedev.server.model.PullRequestAssignment;
import io.onedev.server.model.PullRequestChange;
@@ -197,6 +198,16 @@ public class PullRequestResource {
return pullRequest.getComments();
}
+ @Api(order=550, description="Get all code comments of the pull request")
+ @Path("/{requestId}/code-comments")
+ @GET
+ public Collection<CodeComment> getCodeComments(@PathParam("requestId") Long requestId) {
+ PullRequest pullRequest = pullRequestService.load(requestId);
+ if (!SecurityUtils.canReadCode(pullRequest.getProject()))
+ throw new UnauthorizedException();
+ return pullRequest.getCodeComments();
+ }
+
@Api(order=600)
@Path("/{requestId}/watches")
@GET
diff --git a/server-core/src/main/java/io/onedev/server/security/SecurityUtils.java b/server-core/src/main/java/io/onedev/server/security/SecurityUtils.java
index e32755c495..43318aea1f 100644
--- a/server-core/src/main/java/io/onedev/server/security/SecurityUtils.java
+++ b/server-core/src/main/java/io/onedev/server/security/SecurityUtils.java
@@ -643,7 +643,7 @@ public class SecurityUtils extends org.apache.shiro.SecurityUtils {
if (canWriteCode(subject, comment.getProject())
|| comment.getUser().equals(user)
- || canManageCodeComments(comment.getProject())) {
+ || canManageCodeComments(subject, comment.getProject())) {
return true;
}
diff --git a/server-core/src/main/java/io/onedev/server/util/jackson/ObjectMapperProvider.java b/server-core/src/main/java/io/onedev/server/util/jackson/ObjectMapperProvider.java
index 8cbf354220..adb703609b 100644
--- a/server-core/src/main/java/io/onedev/server/util/jackson/ObjectMapperProvider.java
+++ b/server-core/src/main/java/io/onedev/server/util/jackson/ObjectMapperProvider.java
@@ -14,6 +14,8 @@ import jakarta.inject.Provider;
import jakarta.inject.Singleton;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonParser;
@@ -37,6 +39,7 @@ import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.util.StdDateFormat;
import io.onedev.commons.loader.ImplementationRegistry;
+import io.onedev.commons.utils.PlanarRange;
import io.onedev.server.web.page.layout.AdministrationSettingContribution;
import io.onedev.server.web.page.layout.ContributedAdministrationSetting;
import io.onedev.server.web.page.project.setting.ContributedProjectSetting;
@@ -127,6 +130,7 @@ public class ObjectMapperProvider implements Provider<ObjectMapper> {
mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
+ mapper.addMixIn(PlanarRange.class, PlanarRangeMixin.class);
SimpleModule emptyStringModule = new SimpleModule();
emptyStringModule.addDeserializer(String.class, new JsonDeserializer<String>() {
@@ -146,4 +150,15 @@ public class ObjectMapperProvider implements Provider<ObjectMapper> {
return mapper;
}
+ private abstract static class PlanarRangeMixin {
+
+ @JsonCreator
+ public PlanarRangeMixin(
+ @JsonProperty(value="fromRow", required=true) int fromRow,
+ @JsonProperty(value="fromColumn", required=true) int fromColumn,
+ @JsonProperty(value="toRow", required=true) int toRow,
+ @JsonProperty(value="toColumn", required=true) int toColumn) {
+ }
+ }
+
}
diff --git a/server-core/src/test/java/io/onedev/server/rest/resource/CodeCommentReplyResourceTest.java b/server-core/src/test/java/io/onedev/server/rest/resource/CodeCommentReplyResourceTest.java
new file mode 100644
index 0000000000..4f5195d387
--- /dev/null
+++ b/server-core/src/test/java/io/onedev/server/rest/resource/CodeCommentReplyResourceTest.java
@@ -0,0 +1,167 @@
+package io.onedev.server.rest.resource;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+import org.apache.shiro.authz.UnauthenticatedException;
+import org.apache.shiro.authz.UnauthorizedException;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.MockedStatic;
+
+import io.onedev.server.model.CodeComment;
+import io.onedev.server.model.CodeCommentReply;
+import io.onedev.server.model.Project;
+import io.onedev.server.model.User;
+import io.onedev.server.model.support.CompareContext;
+import io.onedev.server.rest.resource.CodeCommentReplyResource.CodeCommentReplyCreateData;
+import io.onedev.server.security.SecurityUtils;
+import io.onedev.server.service.CodeCommentReplyService;
+import io.onedev.server.service.CodeCommentService;
+import io.onedev.server.validation.HibernateValidationTestSupport;
+
+class CodeCommentReplyResourceTest extends HibernateValidationTestSupport {
+
+ private CodeCommentReplyService replies;
+ private CodeCommentService comments;
+ private CodeCommentReplyResource resource;
+ private CodeComment comment;
+ private User user;
+ private MockedStatic<SecurityUtils> security;
+
+ @BeforeEach
+ void setUp() {
+ replies = mock(CodeCommentReplyService.class);
+ comments = mock(CodeCommentService.class);
+ resource = new CodeCommentReplyResource(replies, comments);
+ comment = new CodeComment();
+ comment.setId(1L);
+ comment.setProject(new Project());
+ comment.setCompareContext(new CompareContext());
+ user = new User();
+ user.setId(2L);
+ when(comments.load(1L)).thenReturn(comment);
+ security = mockStatic(SecurityUtils.class);
+ security.when(SecurityUtils::getUser).thenReturn(user);
+ security.when(SecurityUtils::getAuthUser).thenReturn(user);
+ security.when(() -> SecurityUtils.canReadCode(comment.getProject())).thenReturn(true);
+ }
+
+ @AfterEach
+ void tearDown() {
+ if (security != null)
+ security.close();
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ void createsReplyWithAuthenticatedAuthorAndParentContext(boolean scopedToken) {
+ if (scopedToken)
+ security.when(SecurityUtils::getAuthUser).thenReturn(null);
+ var data = createData();
+ doAnswer(invocation -> {
+ CodeCommentReply reply = invocation.getArgument(0);
+ assertSame(comment, reply.getComment());
+ assertSame(user, reply.getUser());
+ assertSame(comment.getCompareContext(), reply.getCompareContext());
+ assertEquals(data.getContent(), reply.getContent());
+ assertNotNull(reply.getDate());
+ reply.setId(3L);
+ return null;
+ }).when(replies).create(any());
+ assertEquals(3L, resource.createReply(data));
+ }
+
+ @Test
+ void requiresAuthenticationAndCodeReadPermissionToCreate() {
+ security.when(SecurityUtils::getUser).thenReturn(null);
+ assertThrows(UnauthenticatedException.class, () -> resource.createReply(createData()));
+ verifyNoInteractions(comments, replies);
+ security.when(SecurityUtils::getUser).thenReturn(user);
+ security.when(SecurityUtils::getAuthUser).thenReturn(null);
+ security.when(() -> SecurityUtils.canReadCode(comment.getProject())).thenReturn(false);
+ assertThrows(UnauthorizedException.class, () -> resource.createReply(createData()));
+ verifyNoInteractions(replies);
+ }
+
+ @Test
+ void readsAndUpdatesReplyWithoutChangingAuthorOrContext() {
+ var reply = existingReply();
+ assertSame(reply, resource.getReply(3L));
+ security.when(() -> SecurityUtils.canModifyOrDelete(reply)).thenReturn(true);
+ var date = reply.getDate();
+ try (var response = resource.updateReply(3L, "Updated")) {
+ assertEquals(200, response.getStatus());
+ }
+ assertEquals("Updated", reply.getContent());
+ assertSame(comment, reply.getComment());
+ assertSame(user, reply.getUser());
+ assertSame(comment.getCompareContext(), reply.getCompareContext());
+ assertEquals(date, reply.getDate());
+ try (var response = resource.updateReply(3L, "Updated")) {
+ assertEquals(200, response.getStatus());
+ }
+ verify(replies, times(1)).update(reply);
+ }
+
+ @Test
+ void enforcesReadAndModificationPermissions() {
+ var reply = existingReply();
+ assertThrows(UnauthorizedException.class, () -> resource.updateReply(3L, "Updated"));
+ assertThrows(UnauthorizedException.class, () -> resource.deleteReply(3L));
+ security.when(() -> SecurityUtils.canModifyOrDelete(reply)).thenReturn(true);
+ security.when(() -> SecurityUtils.canReadCode(comment.getProject())).thenReturn(false);
+ assertThrows(UnauthorizedException.class, () -> resource.getReply(3L));
+ assertThrows(UnauthorizedException.class, () -> resource.updateReply(3L, "Updated"));
+ assertThrows(UnauthorizedException.class, () -> resource.deleteReply(3L));
+ assertEquals("Original", reply.getContent());
+ verify(replies, never()).update(any());
+ verify(replies, never()).delete(any(CodeCommentReply.class));
+ }
+
+ @Test
+ void deletesThroughReplyService() {
+ var reply = existingReply();
+ security.when(() -> SecurityUtils.canModifyOrDelete(reply)).thenReturn(true);
+ try (var response = resource.deleteReply(3L)) {
+ assertEquals(200, response.getStatus());
+ }
+ verify(replies).delete(reply);
+ }
+
+ @Test
+ void validatesCreateAndUpdateContent() throws Exception {
+ assertPaths(validator.validate(new CodeCommentReplyCreateData()), "commentId", "content");
+ var data = createData();
+ assertTrue(validator.validate(data).isEmpty());
+ var create = CodeCommentReplyResource.class.getMethod("createReply", CodeCommentReplyCreateData.class);
+ var update = CodeCommentReplyResource.class.getMethod("updateReply", Long.class, String.class);
+ for (String content : new String[] {null, " ", "x".repeat(CodeCommentReply.MAX_CONTENT_LEN + 1)}) {
+ data.setContent(content);
+ assertFalse(validator.forExecutables().validateParameters(resource, create, new Object[] {data}).isEmpty());
+ assertFalse(validator.forExecutables().validateParameters(resource, update, new Object[] {3L, content}).isEmpty());
+ }
+ }
+
+ private CodeCommentReplyCreateData createData() {
+ var data = new CodeCommentReplyCreateData();
+ data.setCommentId(1L);
+ data.setContent("Original");
+ return data;
+ }
+
+ private CodeCommentReply existingReply() {
+ var reply = new CodeCommentReply();
+ reply.setId(3L);
+ reply.setComment(comment);
+ reply.setUser(user);
+ reply.setContent("Original");
+ reply.setCompareContext(comment.getCompareContext());
+ when(replies.load(3L)).thenReturn(reply);
+ return reply;
+ }
+}
diff --git a/server-core/src/test/java/io/onedev/server/rest/resource/CodeCommentResourceTest.java b/server-core/src/test/java/io/onedev/server/rest/resource/CodeCommentResourceTest.java
new file mode 100644
index 0000000000..26ee60655f
--- /dev/null
+++ b/server-core/src/test/java/io/onedev/server/rest/resource/CodeCommentResourceTest.java
@@ -0,0 +1,363 @@
+package io.onedev.server.rest.resource;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Set;
+
+import jakarta.ws.rs.BadRequestException;
+
+import org.apache.shiro.authz.UnauthenticatedException;
+import org.apache.shiro.authz.UnauthorizedException;
+import org.apache.shiro.subject.Subject;
+import org.eclipse.jgit.lib.FileMode;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.ArgumentCaptor;
+import org.mockito.MockedStatic;
+
+import io.onedev.commons.loader.AppLoader;
+import io.onedev.commons.loader.ImplementationRegistry;
+import io.onedev.commons.utils.PlanarRange;
+import io.onedev.server.data.migration.VersionedXmlDoc;
+import io.onedev.server.git.Blob;
+import io.onedev.server.git.BlobIdent;
+import io.onedev.server.model.CodeComment;
+import io.onedev.server.model.CodeCommentReply;
+import io.onedev.server.model.CodeCommentStatusChange;
+import io.onedev.server.model.Project;
+import io.onedev.server.model.PullRequest;
+import io.onedev.server.model.User;
+import io.onedev.server.model.support.CompareContext;
+import io.onedev.server.model.support.Mark;
+import io.onedev.server.persistence.dao.Dao;
+import io.onedev.server.rest.resource.CodeCommentResource.CodeCommentCreateData;
+import io.onedev.server.security.SecurityUtils;
+import io.onedev.server.service.AuditService;
+import io.onedev.server.service.CodeCommentService;
+import io.onedev.server.service.CodeCommentStatusChangeService;
+import io.onedev.server.service.ProjectService;
+import io.onedev.server.util.jackson.ObjectMapperProvider;
+import io.onedev.server.util.jackson.hibernate.HibernateObjectMapperConfigurator;
+import io.onedev.server.util.jackson.hibernate.HibernateObjectMapperModule;
+import io.onedev.server.util.diff.WhitespaceOption;
+import io.onedev.server.validation.HibernateValidationTestSupport;
+
+class CodeCommentResourceTest extends HibernateValidationTestSupport {
+
+ private static final String COMMIT = "1234567890123456789012345678901234567890";
+
+ private CodeCommentService comments;
+ private CodeCommentStatusChangeService statusChanges;
+ private AuditService audit;
+ private ProjectService projects;
+ private CodeCommentResource resource;
+ private Project project;
+ private User user;
+ private Subject subject;
+ private MockedStatic<SecurityUtils> security;
+ private MockedStatic<VersionedXmlDoc> xml;
+
+ @BeforeEach
+ void setUp() {
+ comments = mock(CodeCommentService.class);
+ statusChanges = mock(CodeCommentStatusChangeService.class);
+ audit = mock(AuditService.class);
+ projects = mock(ProjectService.class);
+ resource = new CodeCommentResource(comments, audit, projects, statusChanges);
+ project = mock(Project.class);
+ user = new User();
+ user.setId(2L);
+ when(projects.load(1L)).thenReturn(project);
+ when(project.getRevCommit(COMMIT, false)).thenReturn(mock(RevCommit.class));
+ var blob = mock(Blob.class);
+ when(blob.getText()).thenReturn(new Blob.Text(StandardCharsets.UTF_8, "hello\nworld"));
+ when(project.getBlob(any(BlobIdent.class), eq(false))).thenReturn(blob);
+ security = mockStatic(SecurityUtils.class);
+ subject = mock(Subject.class);
+ security.when(SecurityUtils::getSubject).thenReturn(subject);
+ security.when(() -> SecurityUtils.getUser(subject)).thenReturn(user);
+ security.when(SecurityUtils::getUser).thenReturn(user);
+ security.when(SecurityUtils::getAuthUser).thenReturn(user);
+ security.when(() -> SecurityUtils.canReadCode(project)).thenReturn(true);
+ xml = mockStatic(VersionedXmlDoc.class);
+ var document = mock(VersionedXmlDoc.class);
+ when(document.toXML()).thenReturn("<comment/>");
+ xml.when(() -> VersionedXmlDoc.fromBean(any())).thenReturn(document);
+ }
+
+ @AfterEach
+ void tearDown() {
+ if (xml != null)
+ xml.close();
+ if (security != null)
+ security.close();
+ }
+
+ @Test
+ void mapsCommentRangeLikePullRequestUiWithoutChangingOriginalMark() {
+ var comment = existingComment();
+ comment.setMark(new Mark(COMMIT, "file.txt", new PlanarRange(0, 1, 2, 3)));
+ var originalMark = comment.getMark();
+ var targetCommit = "abcdefabcdefabcdefabcdefabcdefabcdefabcd";
+ when(project.getRevCommit(targetCommit, false)).thenReturn(mock(RevCommit.class));
+ when(project.readLines(any(BlobIdent.class), any(WhitespaceOption.class), anyBoolean())).thenCallRealMethod();
+ var oldBlob = mock(Blob.class);
+ when(oldBlob.getText()).thenReturn(new Blob.Text(StandardCharsets.UTF_8, "first \nmiddle\nlast"));
+ when(project.getBlob(new BlobIdent(COMMIT, "file.txt", FileMode.REGULAR_FILE.getBits()), true)).thenReturn(oldBlob);
+ var newBlob = mock(Blob.class);
+ when(newBlob.getText()).thenReturn(new Blob.Text(StandardCharsets.UTF_8, "inserted\nfirst\nmiddle \nlast"));
+ when(project.getBlob(new BlobIdent(targetCommit, "file.txt", FileMode.REGULAR_FILE.getBits()), false)).thenReturn(newBlob);
+
+ assertEquals(new Mark(targetCommit, "file.txt", new PlanarRange(1, 1, 3, 3)), resource.getMark(4L, targetCommit));
+ assertSame(originalMark, comment.getMark());
+
+ // The UI rejects a range with a changed interior line even if both endpoints still match.
+ when(newBlob.getText()).thenReturn(new Blob.Text(StandardCharsets.UTF_8, "inserted\nfirst\nchanged\nlast"));
+ assertNull(resource.getMark(4L, targetCommit));
+ when(newBlob.getText()).thenReturn(null);
+ assertNull(resource.getMark(4L, targetCommit));
+ when(project.getBlob(new BlobIdent(targetCommit, "file.txt", FileMode.REGULAR_FILE.getBits()), false)).thenReturn(null);
+ assertNull(resource.getMark(4L, targetCommit));
+ verifyNoInteractions(audit);
+ }
+
+ @Test
+ void checksPermissionAndTargetCommitBeforeMappingComment() {
+ existingComment();
+ assertThrows(BadRequestException.class, () -> resource.getMark(4L, null));
+ assertThrows(BadRequestException.class, () -> resource.getMark(4L, "invalid"));
+ assertThrows(BadRequestException.class, () -> resource.getMark(4L, "abcdefabcdefabcdefabcdefabcdefabcdefabcd"));
+ security.when(() -> SecurityUtils.canReadCode(project)).thenReturn(false);
+ assertThrows(UnauthorizedException.class, () -> resource.getMark(4L, COMMIT));
+ verify(project, never()).readLines(any(), any(), anyBoolean());
+ }
+
+ @Test
+ void listsOnlyRepliesOfTheRequestedCommentWithCodeReadPermission() {
+ var comment = existingComment();
+ assertTrue(resource.getReplies(4L).isEmpty());
+ var reply = new CodeCommentReply();
+ reply.setComment(comment);
+ comment.getReplies().add(reply);
+ assertSame(comment.getReplies(), resource.getReplies(4L));
+ security.when(() -> SecurityUtils.canReadCode(project)).thenReturn(false);
+ assertThrows(UnauthorizedException.class, () -> resource.getReplies(4L));
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ void createsCommentFromJsonWithPullRequestContext(boolean scopedToken) throws Exception {
+ if (scopedToken)
+ security.when(SecurityUtils::getAuthUser).thenReturn(null);
+ var request = new PullRequest();
+ request.setId(3L);
+ request.setTargetProject(project);
+ var dao = mock(Dao.class);
+ when(dao.load(PullRequest.class, 3L)).thenReturn(request);
+ var mapper = new ObjectMapperProvider(Set.of(), Set.of(), mock(ImplementationRegistry.class),
+ Set.of(new HibernateObjectMapperConfigurator(new HibernateObjectMapperModule(dao)))).get();
+ try (var loader = mockStatic(AppLoader.class)) {
+ loader.when(() -> AppLoader.getInstance(Dao.class)).thenReturn(dao);
+ var data = mapper.readValue("{\"projectId\":1,\"content\":\"Review this\","
+ + "\"mark\":{\"commitHash\":\"" + COMMIT + "\",\"path\":\"file.txt\","
+ + "\"range\":{\"fromRow\":0,\"fromColumn\":0,\"toRow\":0,\"toColumn\":5}},"
+ + "\"compareContext\":{\"oldCommitHash\":\"" + COMMIT + "\",\"newCommitHash\":\"" + COMMIT
+ + "\",\"pullRequestId\":3}}", CodeCommentCreateData.class);
+ assertTrue(validator.validate(data).isEmpty());
+ var range = new PlanarRange(0, 0, 1, 4, 4);
+ assertEquals(range, mapper.readValue(mapper.writeValueAsString(range), PlanarRange.class));
+ doAnswer(invocation -> {
+ CodeComment comment = invocation.getArgument(0);
+ assertSame(project, comment.getProject());
+ assertSame(user, comment.getUser());
+ assertSame(request, comment.getCompareContext().getPullRequest());
+ assertEquals(new PlanarRange(0, 0, 0, 5), comment.getMark().getRange());
+ assertEquals("Review this", comment.getContent());
+ comment.setId(4L);
+ return null;
+ }).when(comments).create(any());
+ assertEquals(4L, resource.createComment(data));
+ verifyNoInteractions(audit);
+ }
+ }
+
+ @Test
+ void requiresAuthenticationAndCodeReadPermissionToCreate() {
+ security.when(SecurityUtils::getUser).thenReturn(null);
+ assertThrows(UnauthenticatedException.class, () -> resource.createComment(createData()));
+ verifyNoInteractions(projects, comments);
+ security.when(SecurityUtils::getUser).thenReturn(user);
+ security.when(SecurityUtils::getAuthUser).thenReturn(null);
+ security.when(() -> SecurityUtils.canReadCode(project)).thenReturn(false);
+ assertThrows(UnauthorizedException.class, () -> resource.createComment(createData()));
+ verifyNoInteractions(comments, audit);
+ }
+
+ @Test
+ void rejectsCrossProjectPullRequestAndInvalidLocations() {
+ var data = createData();
+ var request = new PullRequest();
+ request.setTargetProject(new Project());
+ data.getCompareContext().setPullRequest(request);
+ assertThrows(BadRequestException.class, () -> resource.createComment(data));
+ data.getCompareContext().setPullRequest(null);
+ data.getMark().setCommitHash("invalid");
+ assertThrows(BadRequestException.class, () -> resource.createComment(data));
+ data.getMark().setCommitHash(COMMIT);
+ data.getMark().setRange(new PlanarRange(0, 0, 2, 0));
+ assertThrows(BadRequestException.class, () -> resource.createComment(data));
+ data.getMark().setRange(new PlanarRange(0, 0, 0, 5));
+ when(project.getRevCommit(COMMIT, false)).thenReturn(null);
+ assertThrows(BadRequestException.class, () -> resource.createComment(data));
+ verifyNoInteractions(comments, audit);
+ }
+
+ @Test
+ void updatesOnlyContentAndSkipsUnchangedContent() {
+ var comment = existingComment();
+ security.when(() -> SecurityUtils.canModifyOrDelete(comment)).thenReturn(true);
+ var mark = comment.getMark();
+ var context = comment.getCompareContext();
+ try (var response = resource.updateComment(4L, "Updated")) {
+ assertEquals(200, response.getStatus());
+ }
+ assertEquals("Updated", comment.getContent());
+ assertSame(user, comment.getUser());
+ assertSame(mark, comment.getMark());
+ assertSame(context, comment.getCompareContext());
+ try (var response = resource.updateComment(4L, "Updated")) {
+ assertEquals(200, response.getStatus());
+ }
+ verify(comments, times(1)).update(comment);
+ verifyNoInteractions(audit);
+ }
+
+ @Test
+ void auditsDeletionOfCodeCommentThread() {
+ var comment = existingComment();
+ security.when(() -> SecurityUtils.canModifyOrDelete(comment)).thenReturn(true);
+ try (var response = resource.deleteComment(4L)) {
+ assertEquals(200, response.getStatus());
+ }
+ verify(comments).delete(comment);
+ verify(audit).audit(project, "deleted code comment on file \"file.txt\" via RESTful API", "<comment/>", null);
+ }
+
+ @Test
+ void rejectsEditingWithoutPermission() {
+ var comment = existingComment();
+ assertThrows(UnauthorizedException.class, () -> resource.updateComment(4L, "Updated"));
+ security.when(() -> SecurityUtils.canModifyOrDelete(comment)).thenReturn(true);
+ security.when(() -> SecurityUtils.canReadCode(project)).thenReturn(false);
+ assertThrows(UnauthorizedException.class, () -> resource.updateComment(4L, "Updated"));
+ assertEquals("Original", comment.getContent());
+ verify(comments, never()).update(any());
+ verifyNoInteractions(audit);
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ void changesStatusWithOptionalNoteAndPreservesContext(boolean resolved) {
+ var comment = existingComment();
+ comment.setResolved(!resolved);
+ security.when(() -> SecurityUtils.canChangeStatus(subject, comment)).thenReturn(true);
+ String note = resolved ? "Fixed in the latest revision" : null;
+ try (var response = resolved ? resource.resolveComment(4L, note) : resource.unresolveComment(4L, note)) {
+ assertEquals(200, response.getStatus());
+ }
+ var change = ArgumentCaptor.forClass(CodeCommentStatusChange.class);
+ verify(statusChanges).create(change.capture(), eq(note));
+ assertSame(comment, change.getValue().getComment());
+ assertSame(user, change.getValue().getUser());
+ assertEquals(resolved, change.getValue().isResolved());
+ assertSame(comment.getCompareContext(), change.getValue().getCompareContext());
+ verify(comments, never()).update(any());
+ verifyNoInteractions(audit);
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ void rejectsStatusChangesAfterCodeReadAccessIsRevoked(boolean resolved) {
+ var comment = existingComment();
+ comment.setResolved(resolved);
+ security.when(() -> SecurityUtils.canChangeStatus(subject, comment)).thenReturn(true);
+ security.when(() -> SecurityUtils.canReadCode(project)).thenReturn(false);
+ assertThrows(UnauthorizedException.class, () -> resource.resolveComment(4L, "Note"));
+ assertThrows(UnauthorizedException.class, () -> resource.unresolveComment(4L, "Note"));
+ assertEquals(resolved, comment.isResolved());
+ verifyNoInteractions(statusChanges, audit);
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ void checksStatusPermissionEvenWhenAlreadyInRequestedState(boolean resolved) {
+ var comment = existingComment();
+ comment.setResolved(resolved);
+ assertThrows(UnauthorizedException.class, () -> {
+ if (resolved)
+ resource.resolveComment(4L, "Note");
+ else
+ resource.unresolveComment(4L, "Note");
+ });
+ security.when(() -> SecurityUtils.canChangeStatus(subject, comment)).thenReturn(true);
+ try (var response = resolved ? resource.resolveComment(4L, "Note") : resource.unresolveComment(4L, "Note")) {
+ assertEquals(200, response.getStatus());
+ }
+ verifyNoInteractions(statusChanges);
+ }
+
+ @Test
+ void validatesOptionalNoteLength() throws Exception {
+ for (String methodName : new String[] {"resolveComment", "unresolveComment"}) {
+ var method = CodeCommentResource.class.getMethod(methodName, Long.class, String.class);
+ assertTrue(validator.forExecutables().validateParameters(resource, method,
+ new Object[] {4L, null}).isEmpty());
+ assertFalse(validator.forExecutables().validateParameters(resource, method,
+ new Object[] {4L, "x".repeat(CodeCommentReply.MAX_CONTENT_LEN + 1)}).isEmpty());
+ }
+ }
+
+ @Test
+ void validatesRequiredFieldsAndContentLength() throws Exception {
+ assertPaths(validator.validate(new CodeCommentCreateData()), "projectId", "content", "mark", "compareContext");
+ var method = CodeCommentResource.class.getMethod("updateComment", Long.class, String.class);
+ for (String content : new String[] {null, " ", "x".repeat(CodeComment.MAX_CONTENT_LEN + 1)}) {
+ assertFalse(validator.forExecutables().validateParameters(resource, method,
+ new Object[] {4L, content}).isEmpty());
+ }
+ assertTrue(validator.forExecutables().validateParameters(resource, method,
+ new Object[] {4L, "Updated"}).isEmpty());
+ }
+
+ private CodeCommentCreateData createData() {
+ var data = new CodeCommentCreateData();
+ data.setProjectId(1L);
+ data.setContent("Original");
+ data.setMark(new Mark(COMMIT, "file.txt", new PlanarRange(0, 0, 0, 5)));
+ var context = new CompareContext();
+ context.setOldCommitHash(COMMIT);
+ context.setNewCommitHash(COMMIT);
+ data.setCompareContext(context);
+ return data;
+ }
+
+ private CodeComment existingComment() {
+ var data = createData();
+ var comment = new CodeComment();
+ comment.setId(4L);
+ comment.setProject(project);
+ comment.setUser(user);
+ comment.setContent(data.getContent());
+ comment.setMark(data.getMark());
+ comment.setCompareContext(data.getCompareContext());
+ when(comments.load(4L)).thenReturn(comment);
+ return comment;
+ }
+}