Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add API for single pull request scan #370

Merged
merged 15 commits into from
Jan 5, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ To enable _LPVS_ license scanning for your project, you need to set up GitHub We

Configuration from your project side is now complete!

Alternatively, you can use the Pull Request Single Scan API to analyze the code of a specific pull request.
Please refer to the [API Documentation](doc/lpvs-api.yaml) for more information.

---

### 2. Using pre-built LPVS Docker images
Expand Down
51 changes: 50 additions & 1 deletion doc/lpvs-api.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
openapi: 3.0.0
info:
title: LPVS API
version: v2-20231124
version: v2-20231228
description: >-
License Pre-Validation Service (LPVS) is a tool designed to proactively manage
license-related risks in Open Source code. It conducts in-depth analysis of your
Expand Down Expand Up @@ -48,6 +48,55 @@ paths:
schema:
$ref: '#/components/schemas/WebhookResponseForbidden'

/scan/{gitHubDomain}/{gitHubOrg}/{gitHubRepo}/{prNumber}:
tiokim marked this conversation as resolved.
Show resolved Hide resolved
post:
tags:
- GitHub Pull Request Single Scan API
summary: GitHub Pull Request Single Scan
description: Endpoint for performing a single scan operation based on GitHub organization, repository, and pull request number.
parameters:
- in: path
name: gitHubDomain
required: true
schema:
type: string
description: GitHub domain name
example: 'github.com'
- in: path
name: gitHubOrg
required: true
schema:
type: string
description: GitHub organization name
example: 'Samsung'
- in: path
name: gitHubRepo
required: true
schema:
type: string
description: GitHub repository name
example: 'LPVS'
- in: path
name: prNumber
required: true
schema:
type: integer
description: Pull request number
example: 100
responses:
'200':
description: 200 OK
content:
application/json:
schema:
$ref: '#/components/schemas/WebhookResponseOK'
'403':
description: 403 Forbidden
content:
application/json:
schema:
$ref: '#/components/schemas/WebhookResponseForbidden'

/api/v1/web/user/login:
get:
tags:
Expand Down
4 changes: 4 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,10 @@
<artifactId>h2</artifactId>
<version>2.2.220</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>

</dependencies>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
package com.lpvs.controller;

import com.lpvs.entity.LPVSQueue;
import com.lpvs.entity.enums.LPVSPullRequestAction;
import com.lpvs.repository.LPVSQueueRepository;
import com.lpvs.service.LPVSGitHubService;
import com.lpvs.service.LPVSQueueService;
Expand All @@ -15,17 +16,18 @@
import com.lpvs.entity.LPVSResponseWrapper;
import lombok.extern.slf4j.Slf4j;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import org.apache.commons.codec.binary.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;

import java.util.Date;
import java.util.Optional;
import javax.annotation.PostConstruct;
Expand All @@ -38,7 +40,7 @@
*/
@RestController
@Slf4j
public class GitHubWebhooksController {
public class GitHubController {

/**
* The GitHub secret used for validating webhook payloads.
Expand Down Expand Up @@ -90,7 +92,7 @@ public void initializeGitHubSecret() {
private static final String ALGORITHM = "HmacSHA256";

/**
* Constructor for GitHubWebhooksController.
* Constructor for GitHubController.
* Initializes LPVSQueueService, LPVSGitHubService, LPVSQueueRepository, GitHub secret, and LPVSExitHandler.
*
* @param queueService LPVSQueueService for handling user-related business logic.
Expand All @@ -99,7 +101,7 @@ public void initializeGitHubSecret() {
* @param GITHUB_SECRET The GitHub secret used for validating webhook payloads.
* @param exitHandler LPVSExitHandler for handling application exit scenarios.
*/
public GitHubWebhooksController(
public GitHubController(
LPVSQueueService queueService,
LPVSGitHubService gitHubService,
LPVSQueueRepository queueRepository,
Expand Down Expand Up @@ -166,6 +168,77 @@ public ResponseEntity<LPVSResponseWrapper> gitHubWebhooks(
.body(new LPVSResponseWrapper(SUCCESS));
}

/**
* Handles a GitHub single scan request.
*
* This endpoint performs a single scan operation based on the GitHub organization, repository,
* and pull request number provided in the path variables. The method validates
* the input parameters and performs necessary security checks.
*
* @param gitHubDomain The GitHub domain name.
* @param gitHubOrg The GitHub organization name. Must not be empty and should be a valid string.
* @param gitHubRepo The GitHub repository name. Must not be empty and should be a valid string.
* @param prNumber The pull request number. Must be a positive integer greater than or equal to 1.
* @return ResponseEntity with LPVSResponseWrapper containing the result of the scan.
* If successful, returns HTTP 200 OK with the success message.
* If there are validation errors or security issues, returns HTTP 403 FORBIDDEN.
*/
@RequestMapping(
value = "/scan/{gitHubDomain}/{gitHubOrg}/{gitHubRepo}/{prNumber}",
method = RequestMethod.POST)
public ResponseEntity<LPVSResponseWrapper> gitHubSingleScan(
@PathVariable("gitHubDomain") @NotEmpty @Valid String gitHubDomain,
@PathVariable("gitHubOrg") @NotEmpty @Valid String gitHubOrg,
@PathVariable("gitHubRepo") @NotEmpty @Valid String gitHubRepo,
@PathVariable("prNumber") @Min(1) @Valid Integer prNumber)
throws InterruptedException {
log.debug("New GitHub single scan request received");

if (GITHUB_SECRET.trim().isEmpty()) {
log.error("Received empty GITHUB_SECRET");
return ResponseEntity.status(HttpStatus.FORBIDDEN)
.headers(LPVSWebhookUtil.generateSecurityHeaders())
.body(new LPVSResponseWrapper(ERROR));
}

// Validate and sanitize user inputs to prevent XSS attacks
gitHubDomain = HtmlUtils.htmlEscape(gitHubDomain);
gitHubOrg = HtmlUtils.htmlEscape(gitHubOrg);
gitHubRepo = HtmlUtils.htmlEscape(gitHubRepo);

String prUrl =
"https://"
+ gitHubDomain
+ "/"
+ gitHubOrg
+ "/"
+ gitHubRepo
+ "/pull/"
+ prNumber;
LPVSQueue scanConfig =
gitHubService.getInternalQueueByPullRequest(HtmlUtils.htmlEscape(prUrl));
if (scanConfig == null) {
log.error("Error with connection to GitHub.");
return ResponseEntity.status(HttpStatus.FORBIDDEN)
.headers(LPVSWebhookUtil.generateSecurityHeaders())
.body(new LPVSResponseWrapper(ERROR));
}
scanConfig.setAction(LPVSPullRequestAction.SINGLE_SCAN);
scanConfig.setAttempts(0);
scanConfig.setDate(new Date());
scanConfig.setReviewSystemType("github");
queueRepository.save(scanConfig);
log.debug("Pull request scanning is enabled");
gitHubService.setPendingCheck(scanConfig);
log.debug("Set status to Pending done");
queueService.addFirst(scanConfig);
log.debug("Put Scan config to the queue done");
log.debug("Response sent");
return ResponseEntity.ok()
.headers(LPVSWebhookUtil.generateSecurityHeaders())
.body(new LPVSResponseWrapper(SUCCESS));
}

/**
* Verifies if the signature matches the calculated signature using the GitHub secret.
*
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/lpvs/controller/package-info.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
* This package contains the controller classes for handling various aspects of the License Pre-Validation Service (LPVS).
* Controllers in this package manage interactions related to GitHub webhooks, user interfaces, and API endpoints.
* <p>
* - {@link com.lpvs.controller.GitHubWebhooksController}: Manages GitHub webhook events, processes payloads, and interacts
* - {@link com.lpvs.controller.GitHubController}: Manages GitHub webhook events, processes payloads, and interacts
* with LPVS services for queue handling and GitHub operations.
* </p><p>
* - {@link com.lpvs.controller.LPVSWebController}: Controls the web interface and API endpoints for LPVS, including user
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,12 @@ public enum LPVSPullRequestAction {
/**
* Represents the action of triggering a rescan of a pull request.
*/
RESCAN("rescan");
RESCAN("rescan"),

/**
* Represents the action of triggering a manual single scan of a pull request.
*/
SINGLE_SCAN("single-scan");

/**
* The string representation of the pull request action.
Expand Down Expand Up @@ -77,6 +82,8 @@ public static LPVSPullRequestAction convertFrom(String action) {
return UPDATE;
} else if (action.equals(RESCAN.getPullRequestAction())) {
return RESCAN;
} else if (action.equals(SINGLE_SCAN.getPullRequestAction())) {
return SINGLE_SCAN;
} else {
return null;
}
Expand Down
Loading
Loading