mirror of
https://github.com/goharbor/harbor.git
synced 2025-02-16 20:01:35 +01:00
fix: update code for golangci-lint gosimple (#16974)
Signed-off-by: Shengwen Yu <yshengwen@vmware.com>
This commit is contained in:
parent
9b7289d862
commit
c2a9f5de64
@ -31,7 +31,7 @@ linters:
|
||||
- deadcode
|
||||
- errcheck
|
||||
# - gosec
|
||||
# - gosimple
|
||||
- gosimple
|
||||
- govet
|
||||
# - noctx
|
||||
# - rowserrcheck
|
||||
|
@ -119,7 +119,7 @@ func (cho *ChartOperator) GetChartDetails(content []byte) (*ChartVersionDetails,
|
||||
|
||||
// GetChartList returns a reorganized chart list
|
||||
func (cho *ChartOperator) GetChartList(content []byte) ([]*ChartInfo, error) {
|
||||
if content == nil || len(content) == 0 {
|
||||
if len(content) == 0 {
|
||||
return nil, errors.New("zero content")
|
||||
}
|
||||
|
||||
@ -160,7 +160,7 @@ func (cho *ChartOperator) GetChartList(content []byte) ([]*ChartInfo, error) {
|
||||
|
||||
// GetChartData returns raw data of chart
|
||||
func (cho *ChartOperator) GetChartData(content []byte) (*chart.Chart, error) {
|
||||
if content == nil || len(content) == 0 {
|
||||
if len(content) == 0 {
|
||||
return nil, errors.New("zero content")
|
||||
}
|
||||
|
||||
@ -175,7 +175,7 @@ func (cho *ChartOperator) GetChartData(content []byte) (*chart.Chart, error) {
|
||||
|
||||
// GetChartVersions returns the chart versions
|
||||
func (cho *ChartOperator) GetChartVersions(content []byte) (ChartVersions, error) {
|
||||
if content == nil || len(content) == 0 {
|
||||
if len(content) == 0 {
|
||||
return nil, errors.New("zero content")
|
||||
}
|
||||
|
||||
|
@ -32,7 +32,7 @@ type processedResult struct {
|
||||
//
|
||||
// See @ServiceHandler.GetIndexFile
|
||||
func (c *Controller) GetIndexFile(namespaces []string) (*helm_repo.IndexFile, error) {
|
||||
if namespaces == nil || len(namespaces) == 0 {
|
||||
if len(namespaces) == 0 {
|
||||
return emptyIndexFile(), nil
|
||||
}
|
||||
|
||||
|
@ -20,7 +20,7 @@ const (
|
||||
// GetCountOfCharts calculates and returns the total count of charts under the specified namespaces.
|
||||
// See @ServiceHandler.GetCountOfCharts
|
||||
func (c *Controller) GetCountOfCharts(namespaces []string) (uint64, error) {
|
||||
if namespaces == nil || len(namespaces) == 0 {
|
||||
if len(namespaces) == 0 {
|
||||
return 0, nil // Directly return 0 instead of non-nil error
|
||||
}
|
||||
|
||||
|
@ -41,7 +41,7 @@ func parseRedisConfig(redisConfigV string) (map[string]string, error) {
|
||||
redisConfig := make(map[string]string)
|
||||
redisConfig["key"] = cacheCollectionName
|
||||
|
||||
if strings.Index(redisConfigV, "//") < 0 {
|
||||
if !strings.Contains(redisConfigV, "//") {
|
||||
redisConfigV = "redis://" + redisConfigV
|
||||
}
|
||||
u, err := url.Parse(redisConfigV)
|
||||
|
@ -69,7 +69,6 @@ func NewJobServiceServer() *httptest.Server {
|
||||
panic(err)
|
||||
}
|
||||
rw.WriteHeader(http.StatusOK)
|
||||
return
|
||||
})
|
||||
mux.HandleFunc(fmt.Sprintf("%s/%s", jobsPrefix, jobUUID),
|
||||
func(rw http.ResponseWriter, req *http.Request) {
|
||||
@ -90,9 +89,8 @@ func NewJobServiceServer() *httptest.Server {
|
||||
return
|
||||
}
|
||||
rw.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
})
|
||||
mux.HandleFunc(fmt.Sprintf("%s", jobsPrefix),
|
||||
mux.HandleFunc(jobsPrefix,
|
||||
func(rw http.ResponseWriter, req *http.Request) {
|
||||
if req.Method == http.MethodPost {
|
||||
data, err := ioutil.ReadAll(req.Body)
|
||||
|
@ -1,7 +1,6 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/goharbor/harbor/src/pkg/permission/types"
|
||||
"strings"
|
||||
)
|
||||
@ -21,7 +20,7 @@ func (ns *systemNamespace) Kind() string {
|
||||
}
|
||||
|
||||
func (ns *systemNamespace) Resource(subresources ...types.Resource) types.Resource {
|
||||
return types.Resource(fmt.Sprintf("/system/")).Subresource(subresources...)
|
||||
return types.Resource("/system/").Subresource(subresources...)
|
||||
}
|
||||
|
||||
func (ns *systemNamespace) Identity() interface{} {
|
||||
|
@ -250,7 +250,7 @@ func IsIllegalLength(s string, min int, max int) bool {
|
||||
// IsContainIllegalChar ...
|
||||
func IsContainIllegalChar(s string, illegalChar []string) bool {
|
||||
for _, c := range illegalChar {
|
||||
if strings.Index(s, c) >= 0 {
|
||||
if strings.Contains(s, c) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
@ -259,11 +259,11 @@ func IsContainIllegalChar(s string, illegalChar []string) bool {
|
||||
|
||||
// ParseJSONInt ...
|
||||
func ParseJSONInt(value interface{}) (int, bool) {
|
||||
switch value.(type) {
|
||||
switch v := value.(type) {
|
||||
case float64:
|
||||
return int(value.(float64)), true
|
||||
return int(v), true
|
||||
case int:
|
||||
return value.(int), true
|
||||
return v, true
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
|
@ -124,7 +124,7 @@ func (c *controller) validateCfg(ctx context.Context, cfgs map[string]interface{
|
||||
}
|
||||
if !canBeModified {
|
||||
return errors.BadRequestError(nil).
|
||||
WithMessage(fmt.Sprintf("the auth mode cannot be modified as new users have been inserted into database"))
|
||||
WithMessage("the auth mode cannot be modified as new users have been inserted into database")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -38,16 +38,13 @@ func (p *Handler) Name() string {
|
||||
|
||||
// Handle ...
|
||||
func (p *Handler) Handle(ctx context.Context, value interface{}) error {
|
||||
switch value.(type) {
|
||||
switch v := value.(type) {
|
||||
case *event.PushArtifactEvent:
|
||||
pushArtEvent, _ := value.(*event.PushArtifactEvent)
|
||||
return p.handlePushArtifact(ctx, pushArtEvent)
|
||||
return p.handlePushArtifact(ctx, v)
|
||||
case *event.ScanImageEvent:
|
||||
scanImageEvent, _ := value.(*event.ScanImageEvent)
|
||||
return p.handleImageScanned(ctx, scanImageEvent)
|
||||
return p.handleImageScanned(ctx, v)
|
||||
case *event.ArtifactLabeledEvent:
|
||||
artifactLabeledEvent, _ := value.(*event.ArtifactLabeledEvent)
|
||||
return p.handleArtifactLabeled(ctx, artifactLabeledEvent)
|
||||
return p.handleArtifactLabeled(ctx, v)
|
||||
default:
|
||||
return errors.New("unsupported type")
|
||||
}
|
||||
|
@ -91,7 +91,7 @@ type controller struct {
|
||||
|
||||
func (c *controller) UpdateOIDCMeta(ctx context.Context, ou *commonmodels.OIDCUser, cols ...string) error {
|
||||
defaultCols := []string{"secret", "token"}
|
||||
if cols == nil || len(cols) == 0 {
|
||||
if len(cols) == 0 {
|
||||
cols = defaultCols
|
||||
}
|
||||
return c.oidcMetaMgr.Update(ctx, ou, cols...)
|
||||
|
@ -55,7 +55,7 @@ func (e *EmailAPI) Ping() {
|
||||
var ssl, insecure bool
|
||||
ctx := orm.Context()
|
||||
body := e.Ctx.Input.CopyBody(1 << 32)
|
||||
if body == nil || len(body) == 0 {
|
||||
if len(body) == 0 {
|
||||
cfg, err := config.Email(ctx)
|
||||
if err != nil {
|
||||
log.Errorf("failed to get email configurations: %v", err)
|
||||
|
@ -104,5 +104,4 @@ func (ia *InternalAPI) SyncQuota() {
|
||||
}
|
||||
log.Info("success to sync quota(API).")
|
||||
}()
|
||||
return
|
||||
}
|
||||
|
@ -223,7 +223,7 @@ func (a *Auth) ensure(ctx context.Context) error {
|
||||
if a.client == nil {
|
||||
a.client = &http.Client{}
|
||||
}
|
||||
if time.Now().Sub(a.settingTimeStamp) >= refreshDuration {
|
||||
if time.Since(a.settingTimeStamp) >= refreshDuration {
|
||||
setting, err := config.HTTPAuthProxySetting(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
|
@ -47,5 +47,5 @@ func (ul *UserLock) Lock(username string) {
|
||||
func (ul *UserLock) IsLocked(username string) bool {
|
||||
ul.rw.RLock()
|
||||
defer ul.rw.RUnlock()
|
||||
return time.Now().Sub(ul.failures[username]) <= ul.d
|
||||
return time.Since(ul.failures[username]) <= ul.d
|
||||
}
|
||||
|
@ -61,5 +61,4 @@ func (apc *AuthProxyController) HandleRedirect() {
|
||||
uri = "/"
|
||||
}
|
||||
apc.Ctx.Redirect(http.StatusMovedPermanently, uri)
|
||||
return
|
||||
}
|
||||
|
@ -136,7 +136,7 @@ func (oc *OIDCController) Callback() {
|
||||
return
|
||||
}
|
||||
userRec, onboarded := userOnboard(ctx, oc, info, username, tokenBytes)
|
||||
if onboarded == false {
|
||||
if !onboarded {
|
||||
log.Error("User not onboarded\n")
|
||||
return
|
||||
}
|
||||
|
@ -63,8 +63,8 @@ type JobLogRespHandler struct {
|
||||
func (h JobLogRespHandler) Handle(resp *http.Response) error {
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
h.theAPI.Ctx.ResponseWriter.Header().Set(http.CanonicalHeaderKey("Content-Length"), resp.Header.Get(http.CanonicalHeaderKey("Content-Length")))
|
||||
h.theAPI.Ctx.ResponseWriter.Header().Set(http.CanonicalHeaderKey("Content-Type"), "text/plain")
|
||||
h.theAPI.Ctx.ResponseWriter.Header().Set("Content-Length", resp.Header.Get("Content-Length"))
|
||||
h.theAPI.Ctx.ResponseWriter.Header().Set("Content-Type", "text/plain")
|
||||
|
||||
if _, err := io.Copy(h.theAPI.Ctx.ResponseWriter, resp.Body); err != nil {
|
||||
log.Errorf("failed to write log to response; %v", err)
|
||||
|
@ -278,8 +278,8 @@ func (dh *DefaultHandler) handleJSONData(w http.ResponseWriter, req *http.Reques
|
||||
|
||||
logger.Debugf("Serve http request '%s %s': %d %s", req.Method, req.URL.String(), code, data)
|
||||
|
||||
w.Header().Set(http.CanonicalHeaderKey("Accept"), "application/json")
|
||||
w.Header().Set(http.CanonicalHeaderKey("content-type"), "application/json")
|
||||
w.Header().Set("Accept", "application/json")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(code)
|
||||
writeDate(w, data)
|
||||
}
|
||||
|
@ -535,7 +535,7 @@ func (bt *basicTracker) retrieve() error {
|
||||
return err
|
||||
}
|
||||
|
||||
if vals == nil || len(vals) == 0 {
|
||||
if len(vals) == 0 {
|
||||
return errs.NoObjectFoundError(bt.jobID)
|
||||
}
|
||||
|
||||
@ -549,10 +549,8 @@ func (bt *basicTracker) retrieve() error {
|
||||
switch prop {
|
||||
case "id":
|
||||
res.Info.JobID = value
|
||||
break
|
||||
case "name":
|
||||
res.Info.JobName = value
|
||||
break
|
||||
case "kind":
|
||||
res.Info.JobKind = value
|
||||
case "unique":
|
||||
@ -563,39 +561,28 @@ func (bt *basicTracker) retrieve() error {
|
||||
res.Info.IsUnique = v
|
||||
case "status":
|
||||
res.Info.Status = value
|
||||
break
|
||||
case "ref_link":
|
||||
res.Info.RefLink = value
|
||||
break
|
||||
case "enqueue_time":
|
||||
res.Info.EnqueueTime = parseInt64(value)
|
||||
break
|
||||
case "update_time":
|
||||
res.Info.UpdateTime = parseInt64(value)
|
||||
break
|
||||
case "run_at":
|
||||
res.Info.RunAt = parseInt64(value)
|
||||
break
|
||||
case "check_in_at":
|
||||
res.Info.CheckInAt = parseInt64(value)
|
||||
break
|
||||
case "check_in":
|
||||
res.Info.CheckIn = "" // never read checkin placeholder data
|
||||
break
|
||||
case "cron_spec":
|
||||
res.Info.CronSpec = value
|
||||
break
|
||||
case "web_hook_url":
|
||||
res.Info.WebHookURL = value
|
||||
break
|
||||
case "die_at":
|
||||
res.Info.DieAt = parseInt64(value)
|
||||
case "upstream_job_id":
|
||||
res.Info.UpstreamJobID = value
|
||||
break
|
||||
case "numeric_policy_id":
|
||||
res.Info.NumericPID = parseInt64(value)
|
||||
break
|
||||
case "parameters":
|
||||
params := make(Parameters)
|
||||
if err := json.Unmarshal([]byte(value), ¶ms); err == nil {
|
||||
@ -603,10 +590,8 @@ func (bt *basicTracker) retrieve() error {
|
||||
} else {
|
||||
logger.Error(errors.Wrap(err, "retrieve: tracker"))
|
||||
}
|
||||
break
|
||||
case "revision":
|
||||
res.Info.Revision = parseInt64(value)
|
||||
break
|
||||
case "ack":
|
||||
ack := &ACK{}
|
||||
if err := json.Unmarshal([]byte(value), ack); err == nil {
|
||||
|
@ -154,7 +154,7 @@ func (pm *PolicyMigrator) Migrate() error {
|
||||
policy.ID = pID
|
||||
if !utils.IsEmptyStr(hookURL) {
|
||||
// Copy web hook URL
|
||||
policy.WebHookURL = fmt.Sprintf("%s", hookURL)
|
||||
policy.WebHookURL = hookURL
|
||||
}
|
||||
|
||||
if rawJSON, er := policy.Serialize(); er == nil {
|
||||
|
@ -194,7 +194,6 @@ func (rj *RedisJob) Run(j *work.Job) (err error) {
|
||||
}
|
||||
|
||||
logger.Infof("Retrying job %s:%s, revision: %d", j.Name, j.ID, tracker.Job().Info.Revision)
|
||||
break
|
||||
case job.SuccessStatus:
|
||||
// do nothing
|
||||
return nil
|
||||
|
@ -172,7 +172,7 @@ func (w *basicWorker) GetPoolID() string {
|
||||
|
||||
// RegisterJobs is used to register multiple jobs to worker.
|
||||
func (w *basicWorker) RegisterJobs(jobs map[string]interface{}) error {
|
||||
if jobs == nil || len(jobs) == 0 {
|
||||
if len(jobs) == 0 {
|
||||
// Do nothing
|
||||
return nil
|
||||
}
|
||||
|
@ -150,9 +150,7 @@ func parseOrList(value string) (*OrList, error) {
|
||||
return nil, err
|
||||
}
|
||||
ol := &OrList{}
|
||||
for _, v := range values {
|
||||
ol.Values = append(ol.Values, v)
|
||||
}
|
||||
ol.Values = append(ol.Values, values...)
|
||||
return ol, nil
|
||||
}
|
||||
|
||||
@ -162,9 +160,7 @@ func parseAndList(value string) (*AndList, error) {
|
||||
return nil, err
|
||||
}
|
||||
al := &AndList{}
|
||||
for _, v := range values {
|
||||
al.Values = append(al.Values, v)
|
||||
}
|
||||
al.Values = append(al.Values, values...)
|
||||
return al, nil
|
||||
}
|
||||
|
||||
|
@ -83,7 +83,7 @@ func (cho *operator) GetDetails(content []byte) (*VersionDetails, error) {
|
||||
|
||||
// GetData returns raw data of chart
|
||||
func (cho *operator) GetData(content []byte) (*helm_chart.Chart, error) {
|
||||
if content == nil || len(content) == 0 {
|
||||
if len(content) == 0 {
|
||||
return nil, errors.New("zero content")
|
||||
}
|
||||
|
||||
|
@ -26,7 +26,7 @@ import (
|
||||
|
||||
func init() {
|
||||
unitTest := os.Getenv("UTTEST")
|
||||
if strings.EqualFold(unitTest, "true") == true {
|
||||
if strings.EqualFold(unitTest, "true") {
|
||||
libCfg.Register(common.RestCfgManager, NewRESTCfgManager("sample_url", "sample_secret"))
|
||||
return
|
||||
}
|
||||
|
@ -112,5 +112,4 @@ func AddEvent(ctx context.Context, m n_event.Metadata, notify ...bool) {
|
||||
e.MustNotify = notify[0]
|
||||
}
|
||||
e.Events.PushBack(m)
|
||||
return
|
||||
}
|
||||
|
@ -55,7 +55,7 @@ type providerHelper struct {
|
||||
|
||||
func (p *providerHelper) get() (*gooidc.Provider, error) {
|
||||
if p.instance.Load() != nil {
|
||||
if time.Now().Sub(p.creationTime) > 3*time.Second {
|
||||
if time.Since(p.creationTime) > 3*time.Second {
|
||||
if err := p.create(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@ -153,7 +153,6 @@ func (s *Schema) Valid(v *validation.Validation) {
|
||||
}
|
||||
default:
|
||||
_ = v.SetError("filters", "invalid filter type")
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -91,9 +91,7 @@ func (df *defaultFilter) BuildFrom(pl *policy.Schema) Filter {
|
||||
if pl != nil && len(pl.Filters) > 0 {
|
||||
filters := make([]*policy.Filter, 0)
|
||||
// Copy filters and sort the filter list
|
||||
for _, fl := range pl.Filters {
|
||||
filters = append(filters, fl)
|
||||
}
|
||||
filters = append(filters, pl.Filters...)
|
||||
// Sort
|
||||
sort.SliceStable(filters, func(i, j int) bool {
|
||||
return filterOrder(filters[i].Type) < filterOrder(filters[j].Type)
|
||||
|
@ -113,9 +113,7 @@ func makeQuery(projectID int64, meta ...string) *q.Query {
|
||||
}
|
||||
if len(meta) > 0 {
|
||||
var names []string
|
||||
for _, name := range meta {
|
||||
names = append(names, name)
|
||||
}
|
||||
names = append(names, meta...)
|
||||
kw["name__in"] = names
|
||||
}
|
||||
|
||||
|
@ -34,7 +34,7 @@ func init() {
|
||||
// example:
|
||||
// https://registry.%s.aliyuncs.com
|
||||
// https://cr.%s.aliyuncs.com
|
||||
var regRegion = regexp.MustCompile("https://(registry|cr)\\.([\\w\\-]+)\\.aliyuncs\\.com")
|
||||
var regRegion = regexp.MustCompile(`https://(registry|cr)\.([\w\-]+)\.aliyuncs\.com`)
|
||||
|
||||
func getRegion(url string) (region string, err error) {
|
||||
if url == "" {
|
||||
|
@ -78,9 +78,7 @@ func (c *client) listArtifacts(repo string) ([]*model.Artifact, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, tag := range tags {
|
||||
accArt.Tags = append(accArt.Tags, tag)
|
||||
}
|
||||
accArt.Tags = append(accArt.Tags, tags...)
|
||||
|
||||
accArts = append(accArts, accArt)
|
||||
}
|
||||
|
@ -110,8 +110,8 @@ func (a *adapter) ManifestExist(repository, reference string) (exist bool, desc
|
||||
if err != nil {
|
||||
return exist, nil, err
|
||||
}
|
||||
contentType := resp.Header.Get(http.CanonicalHeaderKey("Content-Type"))
|
||||
contentLen := resp.Header.Get(http.CanonicalHeaderKey("Content-Length"))
|
||||
contentType := resp.Header.Get("Content-Type")
|
||||
contentLen := resp.Header.Get("Content-Length")
|
||||
len, _ := strconv.Atoi(contentLen)
|
||||
|
||||
return exist, &distribution.Descriptor{MediaType: contentType, Size: int64(len)}, nil
|
||||
|
@ -322,7 +322,7 @@ func (a *adapter) preparePushBlob(repository string) (string, error) {
|
||||
return "", err
|
||||
}
|
||||
|
||||
req.Header.Set(http.CanonicalHeaderKey("Content-Length"), "0")
|
||||
req.Header.Set("Content-Length", "0")
|
||||
resp, err := a.client.client.Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
@ -331,7 +331,7 @@ func (a *adapter) preparePushBlob(repository string) (string, error) {
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusAccepted {
|
||||
return resp.Header.Get(http.CanonicalHeaderKey("Docker-Upload-Uuid")), nil
|
||||
return resp.Header.Get("Docker-Upload-Uuid"), nil
|
||||
}
|
||||
|
||||
b, err := ioutil.ReadAll(resp.Body)
|
||||
|
@ -63,7 +63,7 @@ func (a *authorizer) Modify(req *http.Request) error {
|
||||
|
||||
// set authorization header
|
||||
if token != nil && len(token.Token) > 0 {
|
||||
req.Header.Add(http.CanonicalHeaderKey("Authorization"), fmt.Sprintf("Bearer %s", token.Token))
|
||||
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token.Token))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
@ -242,7 +242,7 @@ func (c *client) ManifestExist(repository, reference string) (bool, *distributio
|
||||
return false, nil, err
|
||||
}
|
||||
for _, mediaType := range accepts {
|
||||
req.Header.Add(http.CanonicalHeaderKey("Accept"), mediaType)
|
||||
req.Header.Add("Accept", mediaType)
|
||||
}
|
||||
resp, err := c.do(req)
|
||||
if err != nil {
|
||||
@ -252,9 +252,9 @@ func (c *client) ManifestExist(repository, reference string) (bool, *distributio
|
||||
return false, nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
dig := resp.Header.Get(http.CanonicalHeaderKey("Docker-Content-Digest"))
|
||||
contentType := resp.Header.Get(http.CanonicalHeaderKey("Content-Type"))
|
||||
contentLen := resp.Header.Get(http.CanonicalHeaderKey("Content-Length"))
|
||||
dig := resp.Header.Get("Docker-Content-Digest")
|
||||
contentType := resp.Header.Get("Content-Type")
|
||||
contentLen := resp.Header.Get("Content-Length")
|
||||
len, _ := strconv.Atoi(contentLen)
|
||||
return true, &distribution.Descriptor{Digest: digest.Digest(dig), MediaType: contentType, Size: int64(len)}, nil
|
||||
}
|
||||
@ -269,7 +269,7 @@ func (c *client) PullManifest(repository, reference string, acceptedMediaTypes .
|
||||
acceptedMediaTypes = accepts
|
||||
}
|
||||
for _, mediaType := range acceptedMediaTypes {
|
||||
req.Header.Add(http.CanonicalHeaderKey("Accept"), mediaType)
|
||||
req.Header.Add("Accept", mediaType)
|
||||
}
|
||||
resp, err := c.do(req)
|
||||
if err != nil {
|
||||
@ -280,12 +280,12 @@ func (c *client) PullManifest(repository, reference string, acceptedMediaTypes .
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
mediaType := resp.Header.Get(http.CanonicalHeaderKey("Content-Type"))
|
||||
mediaType := resp.Header.Get("Content-Type")
|
||||
manifest, _, err := distribution.UnmarshalManifest(mediaType, payload)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
digest := resp.Header.Get(http.CanonicalHeaderKey("Docker-Content-Digest"))
|
||||
digest := resp.Header.Get("Docker-Content-Digest")
|
||||
return manifest, digest, nil
|
||||
}
|
||||
|
||||
@ -295,13 +295,13 @@ func (c *client) PushManifest(repository, reference, mediaType string, payload [
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set(http.CanonicalHeaderKey("Content-Type"), mediaType)
|
||||
req.Header.Set("Content-Type", mediaType)
|
||||
resp, err := c.do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
return resp.Header.Get(http.CanonicalHeaderKey("Docker-Content-Digest")), nil
|
||||
return resp.Header.Get("Docker-Content-Digest"), nil
|
||||
}
|
||||
|
||||
func (c *client) DeleteManifest(repository, reference string) error {
|
||||
@ -352,14 +352,14 @@ func (c *client) PullBlob(repository, digest string) (int64, io.ReadCloser, erro
|
||||
return 0, nil, err
|
||||
}
|
||||
|
||||
req.Header.Add(http.CanonicalHeaderKey("Accept-Encoding"), "identity")
|
||||
req.Header.Add("Accept-Encoding", "identity")
|
||||
resp, err := c.do(req)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
|
||||
var size int64
|
||||
n := resp.Header.Get(http.CanonicalHeaderKey("Content-Length"))
|
||||
n := resp.Header.Get("Content-Length")
|
||||
// no content-length is acceptable, which can taken from manifests
|
||||
if len(n) > 0 {
|
||||
size, err = strconv.ParseInt(n, 10, 64)
|
||||
@ -385,14 +385,13 @@ func (c *client) initiateBlobUpload(repository string) (string, string, error) {
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
req.Header.Set(http.CanonicalHeaderKey("Content-Length"), "0")
|
||||
req.Header.Set("Content-Length", "0")
|
||||
resp, err := c.do(req)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
return resp.Header.Get(http.CanonicalHeaderKey("Location")),
|
||||
resp.Header.Get(http.CanonicalHeaderKey("Docker-Upload-UUID")), nil
|
||||
return resp.Header.Get("Location"), resp.Header.Get("Docker-Upload-UUID"), nil
|
||||
}
|
||||
|
||||
func (c *client) monolithicBlobUpload(location, digest string, size int64, data io.Reader) error {
|
||||
@ -418,7 +417,7 @@ func (c *client) MountBlob(srcRepository, digest, dstRepository string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set(http.CanonicalHeaderKey("Content-Length"), "0")
|
||||
req.Header.Set("Content-Length", "0")
|
||||
resp, err := c.do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
@ -516,7 +515,7 @@ func (c *client) do(req *http.Request) (*http.Response, error) {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
req.Header.Set(http.CanonicalHeaderKey("User-Agent"), UserAgent)
|
||||
req.Header.Set("User-Agent", UserAgent)
|
||||
resp, err := c.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@ -154,9 +154,7 @@ func (l *launcher) Launch(ctx context.Context, ply *policy.Metadata, executionID
|
||||
if err != nil {
|
||||
return 0, launcherError(err)
|
||||
}
|
||||
for _, repository := range repositories {
|
||||
repositoryCandidates = append(repositoryCandidates, repository)
|
||||
}
|
||||
repositoryCandidates = append(repositoryCandidates, repositories...)
|
||||
}
|
||||
// filter repositories according to the repository selectors
|
||||
for _, repositorySelector := range rule.ScopeSelectors["repository"] {
|
||||
|
@ -64,17 +64,17 @@ func (c *nativeToRelationalSchemaConverter) ToRelationalSchema(ctx context.Conte
|
||||
// parse the raw report with the V1 schema of the report to the normalized structures
|
||||
rawReport := new(vuln.Report)
|
||||
if err := json.Unmarshal([]byte(reportData), &rawReport); err != nil {
|
||||
return "", "", errors.Wrap(err, fmt.Sprintf("Error when toSchema V1 report to V2"))
|
||||
return "", "", errors.Wrap(err, "Error when toSchema V1 report to V2")
|
||||
}
|
||||
|
||||
if err := c.toSchema(ctx, reportUUID, registrationUUID, digest, reportData); err != nil {
|
||||
return "", "", errors.Wrap(err, fmt.Sprintf("Error when converting vulnerability report"))
|
||||
return "", "", errors.Wrap(err, "Error when converting vulnerability report")
|
||||
}
|
||||
|
||||
rawReport.Vulnerabilities = nil
|
||||
data, err := json.Marshal(rawReport)
|
||||
if err != nil {
|
||||
return "", "", errors.Wrap(err, fmt.Sprintf("Error when persisting raw report summary"))
|
||||
return "", "", errors.Wrap(err, "Error when persisting raw report summary")
|
||||
}
|
||||
|
||||
return reportUUID, string(data), nil
|
||||
@ -211,9 +211,7 @@ func (c *nativeToRelationalSchemaConverter) fromSchema(ctx context.Context, repo
|
||||
}
|
||||
if len(vulnerabilityItems) > 0 {
|
||||
rp.Vulnerabilities = make([]*vuln.VulnerabilityItem, 0)
|
||||
for _, v := range vulnerabilityItems {
|
||||
rp.Vulnerabilities = append(rp.Vulnerabilities, v)
|
||||
}
|
||||
rp.Vulnerabilities = append(rp.Vulnerabilities, vulnerabilityItems...)
|
||||
}
|
||||
|
||||
data, err := json.Marshal(rp)
|
||||
@ -280,17 +278,12 @@ func toVulnerabilityItem(record *scan.VulnerabilityRecord, artifactDigest string
|
||||
item.CVSSDetails.VectorV2 = record.CVSS2Vector
|
||||
item.CVSSDetails.VectorV3 = record.CVSS3Vector
|
||||
cweIDs := strings.Split(record.CWEIDs, ",")
|
||||
for _, cweID := range cweIDs {
|
||||
item.CWEIds = append(item.CWEIds, cweID)
|
||||
}
|
||||
item.CWEIds = cweIDs
|
||||
item.CWEIds = append(item.CWEIds, cweIDs...)
|
||||
item.Description = record.Description
|
||||
item.FixVersion = record.Fix
|
||||
item.Version = record.PackageVersion
|
||||
urls := strings.Split(record.URLs, "|")
|
||||
for _, url := range urls {
|
||||
item.Links = append(item.Links, url)
|
||||
}
|
||||
item.Links = append(item.Links, urls...)
|
||||
item.Severity = vuln.ParseSeverityVersion3(record.Severity)
|
||||
item.Package = record.Package
|
||||
var vendorAttributes map[string]interface{}
|
||||
|
@ -125,7 +125,6 @@ type notaryAuthorizer struct {
|
||||
}
|
||||
|
||||
func (n *notaryAuthorizer) Modify(req *http.Request) error {
|
||||
req.Header.Add(http.CanonicalHeaderKey("Authorization"),
|
||||
fmt.Sprintf("Bearer %s", n.token))
|
||||
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", n.token))
|
||||
return nil
|
||||
}
|
||||
|
@ -365,7 +365,7 @@ func buildInClauseSqlForExtraAttrs(keys []string) string {
|
||||
// act as a place holder to ensure "default" is equivalent to "len(keys) >= 2"
|
||||
return ""
|
||||
case 1:
|
||||
return fmt.Sprintf("select id from execution where extra_attrs->>?=?")
|
||||
return "select id from execution where extra_attrs->>?=?"
|
||||
default:
|
||||
// len(keys) >= 2
|
||||
elements := make([]string, len(keys)-1)
|
||||
|
@ -121,7 +121,7 @@ func (m *manager) Count(ctx context.Context, query *q.Query) (int64, error) {
|
||||
}
|
||||
|
||||
func (m *manager) UpdateProfile(ctx context.Context, user *commonmodels.User, cols ...string) error {
|
||||
if cols == nil || len(cols) == 0 {
|
||||
if len(cols) == 0 {
|
||||
cols = []string{"Email", "Realname", "Comment"}
|
||||
}
|
||||
return m.dao.Update(ctx, user, cols...)
|
||||
|
@ -105,7 +105,7 @@ func (c *client) DeleteManifest(repository, reference string) (err error) {
|
||||
}
|
||||
|
||||
func (c *client) do(req *http.Request) (*http.Response, error) {
|
||||
req.Header.Set(http.CanonicalHeaderKey("User-Agent"), UserAgent)
|
||||
req.Header.Set("User-Agent", UserAgent)
|
||||
resp, err := c.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@ -84,5 +84,4 @@ func (a *authHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if a.handler != nil {
|
||||
a.handler.ServeHTTP(w, r)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
@ -39,7 +39,6 @@ func attachToken(w http.ResponseWriter, r *http.Request) {
|
||||
func handleError(w http.ResponseWriter, r *http.Request) {
|
||||
attachToken(w, r)
|
||||
lib_http.SendError(w, errors.New(csrf.FailureReason(r)).WithCode(errors.ForbiddenCode))
|
||||
return
|
||||
}
|
||||
|
||||
func attach(handler http.Handler) http.Handler {
|
||||
|
@ -232,7 +232,6 @@ func DisableBlobAndManifestUploadMiddleware() func(http.Handler) http.Handler {
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
})
|
||||
}
|
||||
|
||||
|
@ -115,7 +115,6 @@ func (r *repositoryHandler) ServeHTTP(w http.ResponseWriter, req *http.Request)
|
||||
}
|
||||
|
||||
r.sendResponse(w, req, resRepos)
|
||||
return
|
||||
}
|
||||
|
||||
// sendResponse ...
|
||||
|
@ -262,28 +262,26 @@ func (n *notificationPolicyAPI) validateEventTypes(policy *policy_model.Policy)
|
||||
// including event type, enabled, creation time, last trigger time
|
||||
func (n *notificationPolicyAPI) constructPolicyWithTriggerTime(ctx context.Context, policies []*policy_model.Policy) ([]*models.WebhookLastTrigger, error) {
|
||||
res := []*models.WebhookLastTrigger{}
|
||||
if policies != nil {
|
||||
for _, policy := range policies {
|
||||
for _, t := range policy.EventTypes {
|
||||
ply := &models.WebhookLastTrigger{
|
||||
PolicyName: policy.Name,
|
||||
EventType: t,
|
||||
Enabled: policy.Enabled,
|
||||
CreationTime: strfmt.DateTime(policy.CreationTime),
|
||||
}
|
||||
if !policy.CreationTime.IsZero() {
|
||||
ply.CreationTime = strfmt.DateTime(policy.CreationTime)
|
||||
}
|
||||
|
||||
ltTime, err := n.getLastTriggerTimeGroupByEventType(ctx, t, policy.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ltTime.IsZero() {
|
||||
ply.LastTriggerTime = strfmt.DateTime(ltTime)
|
||||
}
|
||||
res = append(res, ply)
|
||||
for _, policy := range policies {
|
||||
for _, t := range policy.EventTypes {
|
||||
ply := &models.WebhookLastTrigger{
|
||||
PolicyName: policy.Name,
|
||||
EventType: t,
|
||||
Enabled: policy.Enabled,
|
||||
CreationTime: strfmt.DateTime(policy.CreationTime),
|
||||
}
|
||||
if !policy.CreationTime.IsZero() {
|
||||
ply.CreationTime = strfmt.DateTime(policy.CreationTime)
|
||||
}
|
||||
|
||||
ltTime, err := n.getLastTriggerTimeGroupByEventType(ctx, t, policy.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ltTime.IsZero() {
|
||||
ply.LastTriggerTime = strfmt.DateTime(ltTime)
|
||||
}
|
||||
res = append(res, ply)
|
||||
}
|
||||
}
|
||||
return res, nil
|
||||
|
@ -118,9 +118,9 @@ func (r *repositoryAPI) listAuthorizedProjectIDs(ctx context.Context) ([]int64,
|
||||
Keywords: map[string]interface{}{},
|
||||
}
|
||||
if secCtx.IsAuthenticated() {
|
||||
switch secCtx.(type) {
|
||||
switch v := secCtx.(type) {
|
||||
case *local.SecurityContext:
|
||||
currentUser := secCtx.(*local.SecurityContext).User()
|
||||
currentUser := v.User()
|
||||
query.Keywords["member"] = &project.MemberQuery{
|
||||
UserID: currentUser.UserID,
|
||||
GroupIDs: currentUser.GroupIDs,
|
||||
@ -130,7 +130,7 @@ func (r *repositoryAPI) listAuthorizedProjectIDs(ctx context.Context) ([]int64,
|
||||
// for the system level robot that covers all the project, see it as the system admin.
|
||||
var coverAll bool
|
||||
var names []string
|
||||
r := secCtx.(*robot.SecurityContext).User()
|
||||
r := v.User()
|
||||
for _, p := range r.Permissions {
|
||||
if p.Scope == robotCtr.SCOPEALLPROJECT {
|
||||
coverAll = true
|
||||
|
@ -176,7 +176,7 @@ func (r *retentionAPI) CreateRetention(ctx context.Context, params operation.Cre
|
||||
if err != nil {
|
||||
return r.SendError(ctx, err)
|
||||
}
|
||||
if old != nil && len(old) > 0 {
|
||||
if len(old) > 0 {
|
||||
return r.SendError(ctx, errors.BadRequestError(fmt.Errorf("project %v already has retention policy %v", p.Scope.Reference, old["retention_id"])))
|
||||
}
|
||||
|
||||
|
@ -69,8 +69,7 @@ func (s *scanAllAPI) StopScanAll(ctx context.Context, params operation.StopScanA
|
||||
return s.SendError(ctx, err)
|
||||
}
|
||||
if execution == nil {
|
||||
message := fmt.Sprintf("no scan all job is found currently")
|
||||
return s.SendError(ctx, errors.BadRequestError(nil).WithMessage(message))
|
||||
return s.SendError(ctx, errors.BadRequestError(nil).WithMessage("no scan all job is found currently"))
|
||||
}
|
||||
go func(ctx context.Context, eid int64) {
|
||||
err := s.execMgr.Stop(ctx, eid)
|
||||
|
Loading…
Reference in New Issue
Block a user