fix: resolve the golint issues of source code (#18071)

Signed-off-by: chlins <chenyuzh@vmware.com>
This commit is contained in:
Chlins Zhang 2023-01-06 16:37:57 +08:00 committed by GitHub
parent b77d3aa153
commit 7ea89dc27f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
24 changed files with 79 additions and 40 deletions

View File

@ -16,11 +16,12 @@ package http
import ( import (
"crypto/tls" "crypto/tls"
"github.com/goharbor/harbor/src/lib/trace"
"net" "net"
"net/http" "net/http"
"time" "time"
"github.com/goharbor/harbor/src/lib/trace"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
) )
@ -45,6 +46,7 @@ func init() {
} }
} }
// AddTracingWithGlobalTransport adds the global transport for tracing.
func AddTracingWithGlobalTransport() { func AddTracingWithGlobalTransport() {
insecureHTTPTransport = otelhttp.NewTransport(insecureHTTPTransport, trace.HarborHTTPTraceOptions...) insecureHTTPTransport = otelhttp.NewTransport(insecureHTTPTransport, trace.HarborHTTPTraceOptions...)
secureHTTPTransport = otelhttp.NewTransport(secureHTTPTransport, trace.HarborHTTPTraceOptions...) secureHTTPTransport = otelhttp.NewTransport(secureHTTPTransport, trace.HarborHTTPTraceOptions...)
@ -86,14 +88,14 @@ func WithInsecureSkipVerify(skipVerify bool) func(*http.Transport) {
} }
} }
// WithMaxIdleConnsPerHost returns a TransportOption that configures the transport to use the specified number of idle connections per host // WithMaxIdleConns returns a TransportOption that configures the transport to use the specified number of idle connections per host
func WithMaxIdleConns(maxIdleConns int) func(*http.Transport) { func WithMaxIdleConns(maxIdleConns int) func(*http.Transport) {
return func(tr *http.Transport) { return func(tr *http.Transport) {
tr.MaxIdleConns = maxIdleConns tr.MaxIdleConns = maxIdleConns
} }
} }
// WithIdleConnTimeout returns a TransportOption that configures the transport to use the specified idle connection timeout // WithIdleconnectionTimeout returns a TransportOption that configures the transport to use the specified idle connection timeout
func WithIdleconnectionTimeout(idleConnectionTimeout time.Duration) func(*http.Transport) { func WithIdleconnectionTimeout(idleConnectionTimeout time.Duration) func(*http.Transport) {
return func(tr *http.Transport) { return func(tr *http.Transport) {
tr.IdleConnTimeout = idleConnectionTimeout tr.IdleConnTimeout = idleConnectionTimeout

View File

@ -41,6 +41,7 @@ type User struct {
OIDCUserMeta *OIDCUser `json:"oidc_user_meta,omitempty"` OIDCUserMeta *OIDCUser `json:"oidc_user_meta,omitempty"`
} }
// Users holds the slice of User.
type Users []*User type Users []*User
// MapByUserID returns map which key is UserID of the user and value is the user itself // MapByUserID returns map which key is UserID of the user and value is the user itself

View File

@ -19,10 +19,11 @@ import (
"context" "context"
stderrors "errors" stderrors "errors"
"fmt" "fmt"
accessorymodel "github.com/goharbor/harbor/src/pkg/accessory/model"
"strings" "strings"
"time" "time"
accessorymodel "github.com/goharbor/harbor/src/pkg/accessory/model"
"github.com/goharbor/harbor/src/controller/artifact/processor/chart" "github.com/goharbor/harbor/src/controller/artifact/processor/chart"
"github.com/goharbor/harbor/src/controller/artifact/processor/cnab" "github.com/goharbor/harbor/src/controller/artifact/processor/cnab"
"github.com/goharbor/harbor/src/controller/artifact/processor/image" "github.com/goharbor/harbor/src/controller/artifact/processor/image"
@ -141,6 +142,7 @@ type controller struct {
accessoryMgr accessory.Manager accessoryMgr accessory.Manager
} }
// ArtOption is the model type of artifact option.
type ArtOption struct { type ArtOption struct {
Tags []string Tags []string
Accs []accessorymodel.AccessoryData Accs []accessorymodel.AccessoryData

View File

@ -13,10 +13,12 @@ type reader struct {
limiter *rate.Limiter limiter *rate.Limiter
} }
// RateOpts is the model type of rate option.
type RateOpts struct { type RateOpts struct {
Rate float64 Rate float64
} }
// KBRATE is the pre-calculated const variable for KB.
const KBRATE = 1024 / 8 const KBRATE = 1024 / 8
// NewReader returns a Reader that is rate limited // NewReader returns a Reader that is rate limited

View File

@ -31,7 +31,7 @@ type Robot struct {
Permissions []*Permission `json:"permissions"` Permissions []*Permission `json:"permissions"`
} }
// IsSysLevel, true is a system level robot, others are project level. // IsSysLevel return true if is a system level robot, others are project level.
func (r *Robot) IsSysLevel() bool { func (r *Robot) IsSysLevel() bool {
return r.Level == LEVELSYSTEM return r.Level == LEVELSYSTEM
} }

View File

@ -148,6 +148,7 @@ func (t *Int64Type) get(str string) (interface{}, error) {
return parseInt64(str) return parseInt64(str)
} }
// Float64Type ...
type Float64Type struct{} type Float64Type struct{}
func (f *Float64Type) validate(str string) error { func (f *Float64Type) validate(str string) error {

View File

@ -9,6 +9,7 @@ import (
tracelib "github.com/goharbor/harbor/src/lib/trace" tracelib "github.com/goharbor/harbor/src/lib/trace"
) )
// InitTraceConfig inits trace config.
func InitTraceConfig(ctx context.Context) { func InitTraceConfig(ctx context.Context) {
cfgMgr, err := GetManager(common.InMemoryCfgManager) cfgMgr, err := GetManager(common.InMemoryCfgManager)
if err != nil { if err != nil {

View File

@ -6,7 +6,7 @@ import (
var testcases = []struct { var testcases = []struct {
url string url string
expectedUrl string expectedURL string
valid bool valid bool
}{ }{
{"http://harbor.foo.com", "http://harbor.foo.com", true}, {"http://harbor.foo.com", "http://harbor.foo.com", true},
@ -37,8 +37,8 @@ func TestValidateHTTPURL(t *testing.T) {
if err != nil { if err != nil {
t.Errorf("ValidateHTTPURL:%q gave err %v; want no error", test.url, err) t.Errorf("ValidateHTTPURL:%q gave err %v; want no error", test.url, err)
} }
if url != test.expectedUrl { if url != test.expectedURL {
t.Errorf("ValidateHTTPURL:%q gave %s; want %s", test.url, url, test.expectedUrl) t.Errorf("ValidateHTTPURL:%q gave %s; want %s", test.url, url, test.expectedURL)
} }
} else if !test.valid && err == nil { } else if !test.valid && err == nil {
t.Errorf("ValidateHTTPURL:%q gave <nil> error; want some error", test.url) t.Errorf("ValidateHTTPURL:%q gave <nil> error; want some error", test.url)

View File

@ -88,6 +88,7 @@ func IsConflictErr(err error) bool {
return IsErr(err, ConflictCode) return IsErr(err, ConflictCode)
} }
// IsChallengesUnsupportedErr checks whether the err chain contains ChallengesUnsupportedError
func IsChallengesUnsupportedErr(err error) bool { func IsChallengesUnsupportedErr(err error) bool {
return IsErr(err, ChallengesUnsupportedCode) return IsErr(err, ChallengesUnsupportedCode)
} }

View File

@ -90,7 +90,7 @@ func Clone(ctx context.Context) context.Context {
type operationNameKey struct{} type operationNameKey struct{}
// SetTransactionOpName sets the transaction operation name // SetTransactionOpNameToContext sets the transaction operation name
func SetTransactionOpNameToContext(ctx context.Context, name string) context.Context { func SetTransactionOpNameToContext(ctx context.Context, name string) context.Context {
if ctx == nil { if ctx == nil {
ctx = context.Background() ctx = context.Background()
@ -255,8 +255,8 @@ func ParamPlaceholderForIn(n int) string {
// to DDL and other statements that do not accept parameters) to be used as part // to DDL and other statements that do not accept parameters) to be used as part
// of an SQL statement. For example: // of an SQL statement. For example:
// //
// exp_date := pq.QuoteLiteral("2023-01-05 15:00:00Z") // exp_date := pq.QuoteLiteral("2023-01-05 15:00:00Z")
// err := db.Exec(fmt.Sprintf("CREATE ROLE my_user VALID UNTIL %s", exp_date)) // err := db.Exec(fmt.Sprintf("CREATE ROLE my_user VALID UNTIL %s", exp_date))
// //
// Any single quotes in name will be escaped. Any backslashes (i.e. "\") will be // Any single quotes in name will be escaped. Any backslashes (i.e. "\") will be
// replaced by two backslashes (i.e. "\\") and the C-style escape identifier // replaced by two backslashes (i.e. "\\") and the C-style escape identifier

View File

@ -16,7 +16,7 @@ package lib
import "strings" import "strings"
// TrimsLineBreaks trims line breaks in string. // TrimLineBreaks trims line breaks in string.
func TrimLineBreaks(s string) string { func TrimLineBreaks(s string) string {
escaped := strings.ReplaceAll(s, "\n", "") escaped := strings.ReplaceAll(s, "\n", "")
escaped = strings.ReplaceAll(escaped, "\r", "") escaped = strings.ReplaceAll(escaped, "\r", "")

View File

@ -19,12 +19,14 @@ import (
) )
const ( const (
// TraceEnvPrefix is the prefix of trace related env.
TraceEnvPrefix = "trace" TraceEnvPrefix = "trace"
) )
// C is the global configuration for trace // C is the global configuration for trace
var C Config var C Config
// InitGlobalConfig inits global config.
func InitGlobalConfig(opts ...Option) { func InitGlobalConfig(opts ...Option) {
C = NewConfig(opts...) C = NewConfig(opts...)
} }
@ -72,97 +74,115 @@ func (c *Config) String() string {
return fmt.Sprintf("{Enabled: %v, ServiceName: %v, SampleRate: %v, Namespace: %v, ServiceName: %v, Jaeger: %v, Otel: %v}", c.Enabled, c.ServiceName, c.SampleRate, c.Namespace, c.ServiceName, c.Jaeger, c.Otel) return fmt.Sprintf("{Enabled: %v, ServiceName: %v, SampleRate: %v, Namespace: %v, ServiceName: %v, Jaeger: %v, Otel: %v}", c.Enabled, c.ServiceName, c.SampleRate, c.Namespace, c.ServiceName, c.Jaeger, c.Otel)
} }
// Option is the wrapper for changing config.
type Option func(*Config) type Option func(*Config)
// WithEnabled pass in the enabled.
func WithEnabled(enabled bool) Option { func WithEnabled(enabled bool) Option {
return func(c *Config) { return func(c *Config) {
c.Enabled = enabled c.Enabled = enabled
} }
} }
// WithSampleRate pass in the sample rate.
func WithSampleRate(sampleRate float64) Option { func WithSampleRate(sampleRate float64) Option {
return func(c *Config) { return func(c *Config) {
c.SampleRate = sampleRate c.SampleRate = sampleRate
} }
} }
// WithNamespace pass in the namespace.
func WithNamespace(namespace string) Option { func WithNamespace(namespace string) Option {
return func(c *Config) { return func(c *Config) {
c.Namespace = namespace c.Namespace = namespace
} }
} }
// WithServiceName pass in the service name.
func WithServiceName(serviceName string) Option { func WithServiceName(serviceName string) Option {
return func(c *Config) { return func(c *Config) {
c.ServiceName = serviceName c.ServiceName = serviceName
} }
} }
// WithAttributes pass in the attributes.
func WithAttributes(attributes map[string]string) Option { func WithAttributes(attributes map[string]string) Option {
return func(c *Config) { return func(c *Config) {
c.Attributes = attributes c.Attributes = attributes
} }
} }
// WithJaegerEndpoint pass in the jaeger endpoint.
func WithJaegerEndpoint(endpoint string) Option { func WithJaegerEndpoint(endpoint string) Option {
return func(c *Config) { return func(c *Config) {
c.Jaeger.Endpoint = endpoint c.Jaeger.Endpoint = endpoint
} }
} }
// WithJaegerUsername pass in the jaeger username.
func WithJaegerUsername(username string) Option { func WithJaegerUsername(username string) Option {
return func(c *Config) { return func(c *Config) {
c.Jaeger.Username = username c.Jaeger.Username = username
} }
} }
// WithJaegerPassword pass in the jaeger password.
func WithJaegerPassword(password string) Option { func WithJaegerPassword(password string) Option {
return func(c *Config) { return func(c *Config) {
c.Jaeger.Password = password c.Jaeger.Password = password
} }
} }
// WithJaegerAgentHost pass in the jaeger agent host.
func WithJaegerAgentHost(host string) Option { func WithJaegerAgentHost(host string) Option {
return func(c *Config) { return func(c *Config) {
c.Jaeger.AgentHost = host c.Jaeger.AgentHost = host
} }
} }
// WithJaegerAgentPort pass in the jaeger agent port.
func WithJaegerAgentPort(port string) Option { func WithJaegerAgentPort(port string) Option {
return func(c *Config) { return func(c *Config) {
c.Jaeger.AgentPort = port c.Jaeger.AgentPort = port
} }
} }
// WithOtelEndpoint pass in the otel endpoint.
func WithOtelEndpoint(endpoint string) Option { func WithOtelEndpoint(endpoint string) Option {
return func(c *Config) { return func(c *Config) {
c.Otel.Endpoint = endpoint c.Otel.Endpoint = endpoint
} }
} }
// WithOtelURLPath pass in the url path.
func WithOtelURLPath(urlPath string) Option { func WithOtelURLPath(urlPath string) Option {
return func(c *Config) { return func(c *Config) {
c.Otel.URLPath = urlPath c.Otel.URLPath = urlPath
} }
} }
// WithOtelCompression pass in the otel compression.
func WithOtelCompression(compression bool) Option { func WithOtelCompression(compression bool) Option {
return func(c *Config) { return func(c *Config) {
c.Otel.Compression = compression c.Otel.Compression = compression
} }
} }
// WithOtelInsecure pass in the otel insecure.
func WithOtelInsecure(insecure bool) Option { func WithOtelInsecure(insecure bool) Option {
return func(c *Config) { return func(c *Config) {
c.Otel.Insecure = insecure c.Otel.Insecure = insecure
} }
} }
// WithOtelTimeout pass in the otel timeout.
func WithOtelTimeout(timeout int) Option { func WithOtelTimeout(timeout int) Option {
return func(c *Config) { return func(c *Config) {
c.Otel.Timeout = timeout c.Otel.Timeout = timeout
} }
} }
// NewConfig returns config which generated by passed in options.
func NewConfig(opts ...Option) Config { func NewConfig(opts ...Option) Config {
c := Config{Otel: OtelConfig{}, Jaeger: JaegerConfig{}} c := Config{Otel: OtelConfig{}, Jaeger: JaegerConfig{}}
for _, opt := range opts { for _, opt := range opts {
@ -171,7 +191,7 @@ func NewConfig(opts ...Option) Config {
return c return c
} }
// GetConfig returns the global configuration for trace // GetGlobalConfig returns the global configuration for trace
func GetGlobalConfig() Config { func GetGlobalConfig() Config {
return C return C
} }

View File

@ -113,7 +113,7 @@ func (s ShutdownFunc) Shutdown() {
s() s()
} }
// Init initializes the trace provider // InitGlobalTracer initializes the trace provider
func InitGlobalTracer(ctx context.Context) ShutdownFunc { func InitGlobalTracer(ctx context.Context) ShutdownFunc {
if !Enabled() { if !Enabled() {
otel.SetTracerProvider(oteltrace.NewNoopTracerProvider()) otel.SetTracerProvider(oteltrace.NewNoopTracerProvider())

View File

@ -16,12 +16,12 @@ package accessory
import ( import (
"context" "context"
"github.com/goharbor/harbor/src/lib/errors" "github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/icon" "github.com/goharbor/harbor/src/lib/icon"
"github.com/goharbor/harbor/src/lib/q" "github.com/goharbor/harbor/src/lib/q"
"github.com/goharbor/harbor/src/pkg/accessory/dao" "github.com/goharbor/harbor/src/pkg/accessory/dao"
"github.com/goharbor/harbor/src/pkg/accessory/model" "github.com/goharbor/harbor/src/pkg/accessory/model"
_ "github.com/goharbor/harbor/src/pkg/accessory/model/base" _ "github.com/goharbor/harbor/src/pkg/accessory/model/base"
_ "github.com/goharbor/harbor/src/pkg/accessory/model/cosign" _ "github.com/goharbor/harbor/src/pkg/accessory/model/cosign"
) )

View File

@ -17,9 +17,10 @@ package model
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/goharbor/harbor/src/lib/errors"
"sync" "sync"
"time" "time"
"github.com/goharbor/harbor/src/lib/errors"
) )
const ( const (
@ -31,11 +32,13 @@ const (
RefHard = "hard" RefHard = "hard"
) )
// RefProvider is the interface for ref provider.
type RefProvider interface { type RefProvider interface {
// Kind returns reference Kind. // Kind returns reference Kind.
Kind() string Kind() string
} }
// RefIdentifier is the interface for ref identifier.
/* /*
RefIdentifier RefIdentifier
@ -43,10 +46,12 @@ Soft reference: The accessory is not tied to the subject manifest.
Hard reference: The accessory is tied to the subject manifest. Hard reference: The accessory is tied to the subject manifest.
Deletion Deletion
1. Soft Reference: If the linkage is Soft Reference, when the subject artifact is removed, the linkage will be removed as well, the accessory artifact becomes an individual artifact. 1. Soft Reference: If the linkage is Soft Reference, when the subject artifact is removed, the linkage will be removed as well, the accessory artifact becomes an individual artifact.
2. Hard Reference: If the linkage is Hard Reference, the accessory artifact will be removed together with the subject artifact. 2. Hard Reference: If the linkage is Hard Reference, the accessory artifact will be removed together with the subject artifact.
Garbage Collection Garbage Collection
1. Soft Reference: If the linkage is Soft Reference, Harbor treats the accessory as normal artifact and will not set it as the GC candidate. 1. Soft Reference: If the linkage is Soft Reference, Harbor treats the accessory as normal artifact and will not set it as the GC candidate.
2. Hard Reference: If the linkage is Hard Reference, Harbor treats the accessory as an extra stuff of the subject artifact. It means, it being tied to the subject artifact and will be GCed whenever the subject artifact is marked and deleted. 2. Hard Reference: If the linkage is Hard Reference, Harbor treats the accessory as an extra stuff of the subject artifact. It means, it being tied to the subject artifact and will be GCed whenever the subject artifact is marked and deleted.
*/ */

View File

@ -103,7 +103,7 @@ func (p *Project) ContentTrustEnabled() bool {
return isTrue(enabled) return isTrue(enabled)
} }
// VulPrevented ... // ContentTrustCosignEnabled ...
func (p *Project) ContentTrustCosignEnabled() bool { func (p *Project) ContentTrustCosignEnabled() bool {
enabled, exist := p.GetMetadata(ProMetaEnableContentTrustCosign) enabled, exist := p.GetMetadata(ProMetaEnableContentTrustCosign)
if !exist { if !exist {

View File

@ -114,11 +114,11 @@ func (c *Client) ListProjects(name string) ([]*Project, error) {
} }
// ListProjectsWithQuery lists projects with query // ListProjectsWithQuery lists projects with query
func (c *Client) ListProjectsWithQuery(q string, with_detail bool) ([]*Project, error) { func (c *Client) ListProjectsWithQuery(q string, withDetail bool) ([]*Project, error) {
projects := []*Project{} projects := []*Project{}
// if old version does not support query, it will fallback to normal // if old version does not support query, it will fallback to normal
// list(list all). // list(list all).
url := fmt.Sprintf("%s/projects?q=%s&with_detail=%t", c.BasePath(), url.QueryEscape(q), with_detail) url := fmt.Sprintf("%s/projects?q=%s&with_detail=%t", c.BasePath(), url.QueryEscape(q), withDetail)
if err := c.C.GetAndIteratePagination(url, &projects); err != nil { if err := c.C.GetAndIteratePagination(url, &projects); err != nil {
return nil, err return nil, err
} }

View File

@ -40,6 +40,7 @@ type Filter struct {
Decoration string `json:"decoration,omitempty"` Decoration string `json:"decoration,omitempty"`
} }
// Validate checks the correctness of filter.
func (f *Filter) Validate() error { func (f *Filter) Validate() error {
switch f.Type { switch f.Type {
case FilterTypeResource, FilterTypeName, FilterTypeTag: case FilterTypeResource, FilterTypeName, FilterTypeTag:

View File

@ -33,6 +33,7 @@ func GetHTTPTransport(insecure bool) http.RoundTripper {
return commonhttp.GetHTTPTransport() return commonhttp.GetHTTPTransport()
} }
// Ping sends the ping request to registry.
func Ping(registry *model.Registry) (string, string, error) { func Ping(registry *model.Registry) (string, string, error) {
client := &http.Client{ client := &http.Client{
Transport: GetHTTPTransport(registry.Insecure), Transport: GetHTTPTransport(registry.Insecure),

View File

@ -347,7 +347,7 @@ func (e *executionDAO) querySetter(ctx context.Context, query *q.Query) (orm.Que
args = append(args, item) args = append(args, item)
} }
args = append(args, value) args = append(args, value)
inClause, err := orm.CreateInClause(ctx, buildInClauseSqlForExtraAttrs(keys), args...) inClause, err := orm.CreateInClause(ctx, buildInClauseSQLForExtraAttrs(keys), args...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -358,7 +358,7 @@ func (e *executionDAO) querySetter(ctx context.Context, query *q.Query) (orm.Que
} }
// Param keys is strings.Split() after trim "extra_attrs."/"ExtraAttrs." prefix // Param keys is strings.Split() after trim "extra_attrs."/"ExtraAttrs." prefix
func buildInClauseSqlForExtraAttrs(keys []string) string { func buildInClauseSQLForExtraAttrs(keys []string) string {
switch len(keys) { switch len(keys) {
case 0: case 0:
// won't fall into this case, as the if condition on "keyPrefix == key" // won't fall into this case, as the if condition on "keyPrefix == key"

View File

@ -346,7 +346,7 @@ func Test_buildInClauseSqlForExtraAttrs(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
if got := buildInClauseSqlForExtraAttrs(tt.args.keys); got != tt.want { if got := buildInClauseSQLForExtraAttrs(tt.args.keys); got != tt.want {
t.Errorf("buildInClauseSqlForExtraAttrs() = %v, want %v", got, tt.want) t.Errorf("buildInClauseSqlForExtraAttrs() = %v, want %v", got, tt.want)
} }
}) })

View File

@ -3,6 +3,10 @@ package cosign
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil"
"net/http"
"regexp"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
"github.com/goharbor/harbor/src/controller/artifact" "github.com/goharbor/harbor/src/controller/artifact"
"github.com/goharbor/harbor/src/lib" "github.com/goharbor/harbor/src/lib"
@ -14,9 +18,6 @@ import (
"github.com/goharbor/harbor/src/pkg/distribution" "github.com/goharbor/harbor/src/pkg/distribution"
"github.com/goharbor/harbor/src/server/middleware" "github.com/goharbor/harbor/src/server/middleware"
digest "github.com/opencontainers/go-digest" digest "github.com/opencontainers/go-digest"
"io/ioutil"
"net/http"
"regexp"
) )
var ( var (
@ -29,7 +30,7 @@ var (
mediaTypeCosignLayer = "application/vnd.dev.cosign.simplesigning.v1+json" mediaTypeCosignLayer = "application/vnd.dev.cosign.simplesigning.v1+json"
) )
// CosignSignatureMiddleware middleware to record the linkeage of artifact and its accessory // Middleware to record the linkeage of artifact and its accessory
/* PUT /v2/library/hello-world/manifests/sha256-1b26826f602946860c279fce658f31050cff2c596583af237d971f4629b57792.sig /* PUT /v2/library/hello-world/manifests/sha256-1b26826f602946860c279fce658f31050cff2c596583af237d971f4629b57792.sig
{ {
"schemaVersion":2, "schemaVersion":2,
@ -50,7 +51,7 @@ var (
] ]
} }
*/ */
func CosignSignatureMiddleware() func(http.Handler) http.Handler { func Middleware() func(http.Handler) http.Handler {
return middleware.AfterResponse(func(w http.ResponseWriter, r *http.Request, statusCode int) error { return middleware.AfterResponse(func(w http.ResponseWriter, r *http.Request, statusCode int) error {
if statusCode != http.StatusCreated { if statusCode != http.StatusCreated {
return nil return nil

View File

@ -2,6 +2,12 @@ package cosign
import ( import (
"fmt" "fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/goharbor/harbor/src/controller/repository" "github.com/goharbor/harbor/src/controller/repository"
"github.com/goharbor/harbor/src/lib" "github.com/goharbor/harbor/src/lib"
"github.com/goharbor/harbor/src/lib/q" "github.com/goharbor/harbor/src/lib/q"
@ -12,11 +18,6 @@ import (
"github.com/goharbor/harbor/src/pkg/distribution" "github.com/goharbor/harbor/src/pkg/distribution"
htesting "github.com/goharbor/harbor/src/testing" htesting "github.com/goharbor/harbor/src/testing"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
) )
type MiddlewareTestSuite struct { type MiddlewareTestSuite struct {
@ -127,15 +128,15 @@ func (suite *MiddlewareTestSuite) TestCosignSignature() {
ref := fmt.Sprintf("%s.sig", strings.ReplaceAll(subArtDigest, "sha256:", "sha256-")) ref := fmt.Sprintf("%s.sig", strings.ReplaceAll(subArtDigest, "sha256:", "sha256-"))
_, descriptor, req := suite.prepare(name, ref) _, descriptor, req := suite.prepare(name, ref)
_, repoId, err := repository.Ctl.Ensure(suite.Context(), name) _, repoID, err := repository.Ctl.Ensure(suite.Context(), name)
suite.Nil(err) suite.Nil(err)
subjectArtID := suite.addArt(projectID, repoId, name, subArtDigest) subjectArtID := suite.addArt(projectID, repoID, name, subArtDigest)
artID := suite.addArt(projectID, repoId, name, descriptor.Digest.String()) artID := suite.addArt(projectID, repoID, name, descriptor.Digest.String())
suite.Nil(err) suite.Nil(err)
res := httptest.NewRecorder() res := httptest.NewRecorder()
next := suite.NextHandler(http.StatusCreated, map[string]string{"Docker-Content-Digest": descriptor.Digest.String()}) next := suite.NextHandler(http.StatusCreated, map[string]string{"Docker-Content-Digest": descriptor.Digest.String()})
CosignSignatureMiddleware()(next).ServeHTTP(res, req) Middleware()(next).ServeHTTP(res, req)
suite.Equal(http.StatusCreated, res.Code) suite.Equal(http.StatusCreated, res.Code)
accs, err := accessory.Mgr.List(suite.Context(), &q.Query{ accs, err := accessory.Mgr.List(suite.Context(), &q.Query{
@ -158,13 +159,13 @@ func (suite *MiddlewareTestSuite) TestCosignSignatureDup() {
ref := fmt.Sprintf("%s.sig", strings.ReplaceAll(subArtDigest, "sha256:", "sha256-")) ref := fmt.Sprintf("%s.sig", strings.ReplaceAll(subArtDigest, "sha256:", "sha256-"))
_, descriptor, req := suite.prepare(name, ref) _, descriptor, req := suite.prepare(name, ref)
_, repoId, err := repository.Ctl.Ensure(suite.Context(), name) _, repoID, err := repository.Ctl.Ensure(suite.Context(), name)
suite.Nil(err) suite.Nil(err)
accID := suite.addArtAcc(projectID, repoId, name, subArtDigest, descriptor.Digest.String()) accID := suite.addArtAcc(projectID, repoID, name, subArtDigest, descriptor.Digest.String())
res := httptest.NewRecorder() res := httptest.NewRecorder()
next := suite.NextHandler(http.StatusCreated, map[string]string{"Docker-Content-Digest": descriptor.Digest.String()}) next := suite.NextHandler(http.StatusCreated, map[string]string{"Docker-Content-Digest": descriptor.Digest.String()})
CosignSignatureMiddleware()(next).ServeHTTP(res, req) Middleware()(next).ServeHTTP(res, req)
suite.Equal(http.StatusCreated, res.Code) suite.Equal(http.StatusCreated, res.Code)
accs, err := accessory.Mgr.List(suite.Context(), &q.Query{ accs, err := accessory.Mgr.List(suite.Context(), &q.Query{

View File

@ -79,7 +79,7 @@ func RegisterRoutes() {
Middleware(repoproxy.DisableBlobAndManifestUploadMiddleware()). Middleware(repoproxy.DisableBlobAndManifestUploadMiddleware()).
Middleware(immutable.Middleware()). Middleware(immutable.Middleware()).
Middleware(quota.PutManifestMiddleware()). Middleware(quota.PutManifestMiddleware()).
Middleware(cosign.CosignSignatureMiddleware()). Middleware(cosign.Middleware()).
Middleware(blob.PutManifestMiddleware()). Middleware(blob.PutManifestMiddleware()).
HandlerFunc(putManifest) HandlerFunc(putManifest)
// blob head // blob head