Skip to content

Commit 08acfd2

Browse files
Merge pull request #73 from diegopereiraeng/main
Auth Fix
2 parents eff9121 + 9f23195 commit 08acfd2

File tree

3 files changed

+106
-53
lines changed

3 files changed

+106
-53
lines changed

.drone.yml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ pool:
99
use: ubuntu
1010

1111
steps:
12-
- name: pr test java 17
12+
- name: pr test java
1313
image: plugins/docker:20
1414
settings:
1515
daemon_off: false
@@ -19,13 +19,13 @@ steps:
1919
when:
2020
ref:
2121
- "refs/pull/**" # Only run for pull requests
22-
- name: publish-2.0.5-java17
22+
- name: publish-2.1.0
2323
image: plugins/docker:20
2424
settings:
2525
# auto_tag: true
2626
# auto_tag_suffix: v2.0.2-java17
2727
tags:
28-
- v2.0.5
28+
- v2.1.0
2929
- latest
3030
# - stable-java17
3131
daemon_off: false

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,12 @@ This plugin is designed to run SonarQube scans and handle the results and conver
1111

1212
<img src="https://github.com/drone-plugins/sonarqube-scanner/blob/main/sonar-result-v2.png" alt="Results" width="800"/>
1313

14-
1514
### Simple Pipeline example
15+
1616
```yaml
1717
- step:
1818
type: Plugin
19-
name: "Check Sonar "
19+
name: "Check Sonar"
2020
identifier: run_sonar
2121
spec:
2222
connectorRef: account.DockerHubDiego

plugin.go

Lines changed: 101 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,11 @@ var (
4040
basicAuth = "Basic "
4141
)
4242

43+
const (
44+
lineBreak = "----------------------------------------------"
45+
lineBreak2 = "|----------------------------------------------------------------|"
46+
)
47+
4348
type (
4449
Config struct {
4550
Key string
@@ -102,13 +107,22 @@ type (
102107
// TaskResponse Give Compute Engine task details such as type, status, duration and associated component.
103108
TaskResponse struct {
104109
Task struct {
105-
ID string `json:"id"`
106-
Type string `json:"type"`
107-
ComponentID string `json:"componentId"`
108-
ComponentKey string `json:"componentKey"`
109-
ComponentName string `json:"componentName"`
110-
AnalysisID string `json:"analysisId"`
111-
Status string `json:"status"`
110+
ID string `json:"id"`
111+
Type string `json:"type"`
112+
ComponentID string `json:"componentId"`
113+
ComponentKey string `json:"componentKey"`
114+
ComponentName string `json:"componentName"`
115+
ComponentQualifier string `json:"componentQualifier"`
116+
AnalysisID string `json:"analysisId"`
117+
Status string `json:"status"`
118+
SubmittedAt string `json:"submittedAt"`
119+
SubmitterLogin string `json:"submitterLogin"`
120+
StartedAt string `json:"startedAt"`
121+
ExecutedAt string `json:"executedAt"`
122+
ExecutionTimeMs int `json:"executionTimeMs"`
123+
HasScannerContext bool `json:"hasScannerContext"`
124+
WarningCount int `json:"warningCount"`
125+
Warnings []string `json:"warnings"`
112126
} `json:"task"`
113127
}
114128

@@ -181,8 +195,6 @@ type AnalysisResponse struct {
181195
} `json:"analyses"`
182196
}
183197

184-
const lineBreak = "----------------------------------------------"
185-
186198
func init() {
187199
netClient = &http.Client{
188200
Timeout: time.Second * 10,
@@ -750,34 +762,49 @@ func getStatus(task *TaskResponse, report *SonarReport) string {
750762
"analysisId": {task.Task.AnalysisID},
751763
}
752764
sonarToken := os.Getenv("PLUGIN_SONAR_TOKEN")
765+
766+
// First try with Basic Auth
753767
projectRequest, err := http.NewRequest("GET", report.ServerURL+"/api/qualitygates/project_status?"+reportRequest.Encode(), nil)
754-
projectRequest.Header.Add("Authorization", basicAuth+sonarToken)
755-
projectResponse, err := netClient.Do(projectRequest)
756768
if err != nil {
757769
logrus.WithFields(logrus.Fields{
758770
"error": err,
759-
}).Info("Failed to get status, retrying with encoded token...")
771+
}).Fatal("Failed get status")
772+
}
773+
fmt.Printf("==> Job Quality Gate Request:\n")
774+
fmt.Printf(report.ServerURL + "/api/qualitygates/project_status?" + reportRequest.Encode())
775+
fmt.Printf("\n")
776+
fmt.Printf("\n")
777+
projectRequest.Header.Add("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(sonarToken+":")))
778+
projectResponse, err := netClient.Do(projectRequest)
779+
780+
if err != nil || projectResponse.StatusCode != http.StatusOK {
781+
logrus.WithFields(logrus.Fields{
782+
"error": err,
783+
}).Info("Failed to get status with Basic Auth, retrying with Bearer token...")
760784

761-
// Retry with the token encoded in base64
762-
encodedToken := base64.StdEncoding.EncodeToString([]byte(sonarToken))
763-
projectRequest.Header.Set("Authorization", "Basic "+encodedToken)
785+
// Retry with Bearer token
786+
projectRequest.Header.Set("Authorization", "Bearer "+sonarToken)
764787
projectResponse, err = netClient.Do(projectRequest)
765788

766-
if err != nil {
789+
if err != nil || projectResponse.StatusCode != http.StatusOK {
767790
logrus.WithFields(logrus.Fields{
768791
"error": err,
769-
}).Fatal("Failed to get status after retry")
792+
}).Fatal("Failed to get status after retry with Bearer token")
770793
}
771794
}
772-
buf, _ := ioutil.ReadAll(projectResponse.Body)
795+
796+
buf, _ := io.ReadAll(projectResponse.Body)
797+
fmt.Printf("==> Report Result:\n")
798+
fmt.Println(string(buf))
799+
fmt.Printf("\n")
773800
project := ProjectStatusResponse{}
774801
if err := json.Unmarshal(buf, &project); err != nil {
775802
logrus.WithFields(logrus.Fields{
776803
"error": err,
777804
}).Fatal("Failed")
778805
}
779806
fmt.Printf("==> Report Result:\n")
780-
fmt.Printf(string(buf))
807+
fmt.Println(string(buf))
781808

782809
// JUNUT
783810
junitReport := ""
@@ -968,50 +995,55 @@ func GetProjectStatus(sonarHost string, analysisId string, projectSlug string) (
968995
return buf, nil
969996
}
970997

998+
func addBearerToken(req *http.Request, token string) {
999+
req.Header.Add("Authorization", "Bearer "+token)
1000+
}
1001+
1002+
func addBasicAuth(req *http.Request, token string) {
1003+
req.SetBasicAuth(token, "")
1004+
}
1005+
9711006
func GetLatestTaskID(sonarHost string, projectSlug string) (string, error) {
9721007
fmt.Printf("\nStarting Task ID Discovery\n")
9731008
url := fmt.Sprintf("%s/api/project_analyses/search?project=%s&ps=1", sonarHost, projectSlug)
9741009
fmt.Printf("URL: %s\n", url)
9751010

976-
req, err := http.NewRequest("GET", url, nil)
1011+
taskRequest, err := http.NewRequest("GET", url, nil)
9771012
if err != nil {
9781013
fmt.Printf("\nError to create request in Task discovery: %s\n", err.Error())
9791014
return "", err
9801015
}
9811016

9821017
sonarToken := os.Getenv("PLUGIN_SONAR_TOKEN")
983-
req.SetBasicAuth(sonarToken, "")
984-
resp, err := netClient.Do(req)
1018+
// First, try with Bearer token
1019+
addBearerToken(taskRequest, sonarToken)
1020+
taskResponse, err := netClient.Do(taskRequest)
9851021
if err != nil {
986-
fmt.Printf("\nRequest Error in Task discovery: %s\n", err.Error())
987-
return "", err
1022+
logrus.WithFields(logrus.Fields{
1023+
"error": err,
1024+
}).Fatal("Failed get sonar job status")
9881025
}
989-
defer resp.Body.Close()
9901026

991-
if resp.StatusCode == http.StatusForbidden {
992-
fmt.Printf("\nError in Task discovery: %s\n", "Check your token permission - probably it does not have 'Browse' permission on the project")
993-
fmt.Printf("Retrying with encoded token...\n")
994-
995-
encodedToken := base64.StdEncoding.EncodeToString([]byte(sonarToken))
996-
req.Header.Add("Authorization", basicAuth+encodedToken)
997-
fmt.Printf("Token encoded: %s\n", encodedToken)
998-
req.SetBasicAuth(encodedToken, "")
999-
resp, err = netClient.Do(req)
1027+
// If Forbidden, try with Basic Auth
1028+
if taskResponse.StatusCode == http.StatusForbidden {
1029+
fmt.Printf("\nRetrying with Basic Auth...\n")
1030+
addBasicAuth(taskRequest, sonarToken)
1031+
taskResponse, err = netClient.Do(taskRequest)
10001032
if err != nil {
1001-
fmt.Printf("\nRequest Error in Task discovery after retry: %s\n", err.Error())
1002-
return "", err
1033+
logrus.WithFields(logrus.Fields{
1034+
"error": err,
1035+
}).Fatal("Failed get sonar job status")
10031036
}
1004-
defer resp.Body.Close()
10051037
}
10061038

1007-
if resp.StatusCode != http.StatusOK {
1008-
if resp.StatusCode == http.StatusUnauthorized {
1039+
if taskResponse.StatusCode != http.StatusOK {
1040+
if taskResponse.StatusCode == http.StatusUnauthorized {
10091041
fmt.Printf("\nError in Task discovery: %s\n", "Invalid Credentials - your token is not valid")
10101042
}
1011-
return "", fmt.Errorf("HTTP request error. Status code: %d", resp.StatusCode)
1043+
return "", fmt.Errorf("HTTP request error. Status code: %d", taskResponse.StatusCode)
10121044
}
10131045

1014-
body, err := ioutil.ReadAll(resp.Body)
1046+
body, err := io.ReadAll(taskResponse.Body)
10151047
if err != nil {
10161048
fmt.Printf("\nError reading response body in Task discovery: %s\n", err.Error())
10171049
return "", err
@@ -1049,27 +1081,48 @@ func getSonarJobStatus(report *SonarReport) *TaskResponse {
10491081
if err != nil {
10501082
logrus.WithFields(logrus.Fields{
10511083
"error": err,
1052-
}).Fatal("Failed get sonar job status")
1084+
}).Fatal("Failed to create request for Sonar job status")
10531085
}
1054-
taskRequest.Header.Add("Authorization", basicAuth+os.Getenv("PLUGIN_SONAR_TOKEN"))
1086+
1087+
sonarToken := os.Getenv("PLUGIN_SONAR_TOKEN")
1088+
taskRequest.Header.Add("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(sonarToken+":")))
1089+
10551090
taskResponse, err := netClient.Do(taskRequest)
10561091
if err != nil {
10571092
logrus.WithFields(logrus.Fields{
10581093
"error": err,
1059-
}).Fatal("Failed get sonar job status")
1094+
}).Fatal("Failed to get Sonar job status")
10601095
}
1096+
1097+
if taskResponse.StatusCode == http.StatusForbidden {
1098+
fmt.Println("Basic Auth failed. Retrying with Bearer token...")
1099+
taskRequest.Header.Set("Authorization", "Bearer "+sonarToken)
1100+
taskResponse, err = netClient.Do(taskRequest)
1101+
if err != nil {
1102+
logrus.WithFields(logrus.Fields{
1103+
"error": err,
1104+
}).Fatal("Failed to get Sonar job status with Bearer token")
1105+
}
1106+
}
1107+
10611108
buf, err := io.ReadAll(taskResponse.Body)
10621109
if err != nil {
10631110
logrus.WithFields(logrus.Fields{
10641111
"error": err,
1065-
}).Fatal("Failed to read sonar job status response body")
1112+
}).Fatal("Failed to read Sonar job status response body")
10661113
}
1114+
1115+
fmt.Printf("\n==> Job Status Response:\n")
1116+
fmt.Println(string(buf))
1117+
fmt.Printf("\n")
1118+
10671119
task := TaskResponse{}
1068-
fmt.Println("|----------------------------------------------------------------|")
1120+
1121+
fmt.Println(lineBreak2)
10691122
fmt.Println("| Report Result: |")
1070-
fmt.Println("|----------------------------------------------------------------|")
1123+
fmt.Println(lineBreak2)
10711124
fmt.Print(string(buf))
1072-
fmt.Println("|----------------------------------------------------------------|")
1125+
fmt.Println(lineBreak2)
10731126
json.Unmarshal(buf, &task)
10741127
return &task
10751128
}

0 commit comments

Comments
 (0)