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
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

import io.mixeway.mixewayflowapi.api.coderepo.dto.*;
import io.mixeway.mixewayflowapi.api.coderepo.service.CodeRepoApiService;
import io.mixeway.mixewayflowapi.api.gitlabcicd.dto.GitLabCICDRequestDto;
import io.mixeway.mixewayflowapi.db.entity.CodeRepo;
import io.mixeway.mixewayflowapi.db.entity.CodeRepoBranch;
import io.mixeway.mixewayflowapi.domain.coderepo.CreateCodeRepoService;
import io.mixeway.mixewayflowapi.domain.coderepo.DeleteCodeRepoService;
import io.mixeway.mixewayflowapi.exceptions.CodeRepoNotFoundException;
Expand Down Expand Up @@ -193,4 +195,31 @@ public ResponseEntity<StatusDTO> deleteCodeRepo(@PathVariable("id") Long id, Pri
return new ResponseEntity<>(new StatusDTO("Internal server error"), HttpStatus.INTERNAL_SERVER_ERROR);
}
}

@PreAuthorize("hasAuthority('USER')")
@PostMapping(value = "/api/v1/coderepo/run-orch")
public ResponseEntity<String> runRepoScan(@RequestHeader("X-API-KEY") String apiKey, @Valid @RequestBody RunOrchRequestDto requestDto) {
try {
String repoUrl = requestDto.getRepoUrl();
Long teamId = requestDto.getTeamId();
String branch = requestDto.getBranch();
String domain = requestDto.getDomain();

if (!codeRepoApiService.isRepoInTeamById(repoUrl, teamId)) {
String errorMessage = String.format("The repository with URL '%s' does not belong to the team with ID '%d'.", repoUrl, teamId);
return new ResponseEntity<>(errorMessage, HttpStatus.FORBIDDEN);
}

if (!codeRepoApiService.isValidApiKey(apiKey, repoUrl)) {
String errorMessage = String.format("The provided API key is invalid for the repository with URL '%s'.", repoUrl);
return new ResponseEntity<>(errorMessage, HttpStatus.UNAUTHORIZED);
}

String scanDetails = codeRepoApiService.runScan(repoUrl, branch, domain);

return new ResponseEntity<>(scanDetails, HttpStatus.OK);
} catch (Exception e){
return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package io.mixeway.mixewayflowapi.api.coderepo.dto;
import jakarta.validation.constraints.NotNull;
import lombok.Data;

@Data
public class RunOrchRequestDto {
private String repoUrl;
private Long teamId;
private String branch;
private String domain;

public RunOrchRequestDto() {}

@NotNull(message = "RepoURL must not be null.")
public String getRepoUrl() {
return repoUrl;
}

@NotNull(message = "TeamID must not be null.")
public Long getTeamId() {
return teamId;
}

public String getBranch() { return branch; }

public String getDomain() {
return domain;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package io.mixeway.mixewayflowapi.api.coderepo.dto;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class RunOrchScanDetailsDto {
String name;
String description;
String explanation;
String recommendation;
String location;
String source;
String status;
String severity;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package io.mixeway.mixewayflowapi.api.coderepo.dto;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class RunOrchScanReportDto {

String repoUrl;
String branch;
String linkToScanDetails;

List<RunOrchScanDetailsDto> findings;
}
Original file line number Diff line number Diff line change
@@ -1,22 +1,28 @@
package io.mixeway.mixewayflowapi.api.coderepo.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import io.mixeway.mixewayflowapi.api.coderepo.dto.GetCodeReposResponseDto;
import io.mixeway.mixewayflowapi.db.entity.CodeRepo;
import io.mixeway.mixewayflowapi.db.entity.Team;
import io.mixeway.mixewayflowapi.api.coderepo.dto.RunOrchScanDetailsDto;
import io.mixeway.mixewayflowapi.api.coderepo.dto.RunOrchScanReportDto;
import io.mixeway.mixewayflowapi.api.gitlabcicd.dto.GitLabCICDDetailsResponseDto;
import io.mixeway.mixewayflowapi.db.entity.*;
import io.mixeway.mixewayflowapi.db.repository.UserRepository;
import io.mixeway.mixewayflowapi.domain.coderepo.FindCodeRepoService;
import io.mixeway.mixewayflowapi.domain.coderepo.UpdateCodeRepoService;
import io.mixeway.mixewayflowapi.domain.finding.FindFindingService;
import io.mixeway.mixewayflowapi.domain.team.FindTeamService;
import io.mixeway.mixewayflowapi.exceptions.CodeRepoNotFoundException;
import io.mixeway.mixewayflowapi.exceptions.TeamNotFoundException;
import io.mixeway.mixewayflowapi.exceptions.UnauthorizedException;
import io.mixeway.mixewayflowapi.scanmanager.service.ScanManagerService;
import io.mixeway.mixewayflowapi.utils.PermissionFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.aspectj.apache.bcel.classfile.Code;
import org.springframework.stereotype.Service;

import java.security.Principal;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;

@Service
Expand All @@ -28,6 +34,8 @@ public class CodeRepoApiService {
private final PermissionFactory permissionFactory;
private final FindTeamService findTeamService;
private final UpdateCodeRepoService updateCodeRepoService;
private final UserRepository userRepository;
private final FindFindingService findFindingService;

public List<GetCodeReposResponseDto> getRepos(Principal principal) {
return findCodeRepoService.getCodeReposResponseDtos(principal);
Expand Down Expand Up @@ -101,4 +109,89 @@ public void renameCodeRepo(Long repoId, String newName, Principal principal) {
permissionFactory.canUserManageTeam(repo.getTeam(), principal);
updateCodeRepoService.renameCodeRepo(repo, newName);
}

public Boolean isRepoInTeamById(String repoUrl, Long teamId) {
try {
Optional<CodeRepo> codeRepo = findCodeRepoService.findCodeRepoByUrl(repoUrl);

return codeRepo.isPresent() && teamId.equals(codeRepo.get().getTeam().getId());
} catch (Exception e) {
log.error("[CodeRepo] Error checking if repo '{}' belongs to team '{}': {}", repoUrl, teamId, e.getMessage());
return false;
}
}

public Boolean isValidApiKey(String apiKey, String repoUrl) {
Optional<UserInfo> userOptional = userRepository.findByApiKey(apiKey);
Optional<Team> codeRepoTeam = findTeamService.findByRepoUrl(repoUrl);

if (userOptional.isEmpty() || codeRepoTeam.isEmpty()) {
return false;
}

List<UserInfo> teamUsers = userRepository.getUsersByTeamId(codeRepoTeam.get().getId());

if (teamUsers.contains(userOptional.get())) {
log.info("[Team Service] User's {} API key validation succeeded", userOptional.get().getUsername());
return true;
} else {
log.info("[Team Service] User's {} API key validation failed", userOptional.get().getUsername());
return false;
}
}

public String runScan(String repoUrl, String branch, String domain) {

CodeRepo codeRepo = findCodeRepoService.findCodeRepoByUrl(repoUrl).orElse(null);

CodeRepoBranch repoBranch;

if (branch == null) {
repoBranch = codeRepo.getDefaultBranch();
} else {
repoBranch = codeRepo.getBranches().stream().filter(b -> b.getName().equals(branch)).findFirst().orElse(null);
}

scanManagerService.scanRepositorySync(codeRepo, repoBranch, null, null);

RunOrchScanReportDto scanReport = new RunOrchScanReportDto();

scanReport.setRepoUrl(repoUrl);
scanReport.setBranch(branch);
if (domain != null) {
scanReport.setLinkToScanDetails("https://" + domain + "/#/show-repo/" + codeRepo.getId());
}

ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);

Collection<Finding.Status> statuses = Arrays.asList(Finding.Status.NEW, Finding.Status.EXISTING);

List<Finding> findings = findFindingService.findByCodeRepoAndCodeRepoBranchAndStatusIn(codeRepo, repoBranch, statuses);

List<RunOrchScanDetailsDto> findingsDetails = new ArrayList<>();
for (Finding finding : findings) {
RunOrchScanDetailsDto scanDetails = new RunOrchScanDetailsDto();

scanDetails.setName(finding.getVulnerability().getName());
scanDetails.setDescription(finding.getVulnerability().getDescription());
scanDetails.setExplanation(finding.getExplanation());
scanDetails.setRecommendation(finding.getVulnerability().getRecommendation());
scanDetails.setLocation(finding.getLocation());
scanDetails.setSource(String.valueOf(finding.getSource()));
scanDetails.setStatus(String.valueOf(finding.getStatus()));
scanDetails.setSeverity(String.valueOf(finding.getSeverity()));

findingsDetails.add(scanDetails);
}

scanReport.setFindings(findingsDetails);

try {
return mapper.writeValueAsString(scanReport);
} catch (Exception e) {
log.error("Error while serializing scan report: {}", e.getMessage());
}
return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public CodeRepoBranch getCodeRepoBranch(String branch, CodeRepo codeRepo) {
}

public void runCodeRepoScan(CodeRepo codeRepo, CodeRepoBranch codeRepoBranch) {
scanManagerService.scanRepositoryViaGitLabCICD(codeRepo, codeRepoBranch, null, null);
scanManagerService.scanRepositorySync(codeRepo, codeRepoBranch, null, null);
}

public String createScanSummary(CodeRepo codeRepo, CodeRepoBranch codeRepoBranch, String domain) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ public void scanRepository(CodeRepo codeRepo, CodeRepoBranch codeRepoBranch, Str
}

} catch (Exception e) {
log.error("[ScanManagerService] Exception during scan, failed to fetch repository: {} - {}", codeRepo.getRepourl(), e.getMessage(), e);
log.error("[ScanManagerService] Exception during scan, failed to fetch repository: {}", codeRepo.getRepourl());
} finally {
// Update status
try {
Expand Down Expand Up @@ -243,7 +243,7 @@ public void scanRepository(CodeRepo codeRepo, CodeRepoBranch codeRepoBranch, Str
});
}

public void scanRepositoryViaGitLabCICD(CodeRepo codeRepo, CodeRepoBranch codeRepoBranch, String commitId, Long iid) {
public void scanRepositorySync(CodeRepo codeRepo, CodeRepoBranch codeRepoBranch, String commitId, Long iid) {
// Get or create a lock object for the repository
Object repoLock = repoLocks.computeIfAbsent(codeRepo.getId(), k -> new Object());

Expand Down Expand Up @@ -340,7 +340,7 @@ public void scanRepositoryViaGitLabCICD(CodeRepo codeRepo, CodeRepoBranch codeRe
}

} catch (Exception e) {
log.error("[ScanManagerService] Exception during scan, failed to fetch repository: {} - {}", codeRepo.getRepourl(), e.getMessage(), e);
log.error("[ScanManagerService] Exception during scan, failed to fetch repository: {}", codeRepo.getRepourl());
} finally {
// Update status
try {
Expand Down