Skip to content

Commit

Permalink
fix new gocritic lints where autofixable
Browse files Browse the repository at this point in the history
  • Loading branch information
majewsky committed Mar 20, 2024
1 parent b8323aa commit 73875f6
Show file tree
Hide file tree
Showing 128 changed files with 2,112 additions and 2,112 deletions.
8 changes: 4 additions & 4 deletions cmd/anycastmonitor/main.go
Expand Up @@ -84,7 +84,7 @@ func AddCommandTo(parent *cobra.Command) {
}

type anycastMonitorJob struct {
RepoClients map[string]*client.RepoClient //key = account name
RepoClients map[string]*client.RepoClient // key = account name
}

func run(cmd *cobra.Command, args []string) {
Expand All @@ -110,17 +110,17 @@ func run(cmd *cobra.Command, args []string) {
}
}

//expose metrics endpoint
// expose metrics endpoint
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.Handler())
ctx := httpext.ContextWithSIGINT(context.Background(), 1*time.Second)
go func() {
must.Succeed(httpext.ListenAndServeContext(ctx, listenAddress, mux))
}()

//enter long-running check loop
// enter long-running check loop
manifestRef := models.ManifestReference{Tag: "latest"}
job.ValidateImages(ctx, manifestRef) //once immediately to initialize the metrics
job.ValidateImages(ctx, manifestRef) // once immediately to initialize the metrics
job.ValidateAnycastMembership(ctx, anycastURL, apiPublicHostname)
tick := time.Tick(30 * time.Second)
for {
Expand Down
10 changes: 5 additions & 5 deletions cmd/api/gui_redirect.go
Expand Up @@ -38,7 +38,7 @@ type guiRedirecter struct {

// AddTo implements the api.API interface.
func (g *guiRedirecter) AddTo(r *mux.Router) {
//check if this feature is enabled
// check if this feature is enabled
if g.urlStr == "" {
return
}
Expand All @@ -47,15 +47,15 @@ func (g *guiRedirecter) AddTo(r *mux.Router) {
}

func (g *guiRedirecter) tryRedirectToGUI(w http.ResponseWriter, r *http.Request) {
//only attempt to redirect if it's a web browser doing the request
// only attempt to redirect if it's a web browser doing the request
if !strings.Contains(r.Header.Get("Accept"), "text/html") {
respondNotFound(w, r)
return
}

vars := mux.Vars(r)

//do we have this account/repo?
// do we have this account/repo?
account, err := keppel.FindAccount(g.db, vars["account"])
if err != nil || account == nil {
respondNotFound(w, r)
Expand All @@ -68,7 +68,7 @@ func (g *guiRedirecter) tryRedirectToGUI(w http.ResponseWriter, r *http.Request)
return
}

//is it publicly readable?
// is it publicly readable?
policies, err := account.ParseRBACPolicies()
if err != nil {
respondNotFound(w, r)
Expand All @@ -80,7 +80,7 @@ func (g *guiRedirecter) tryRedirectToGUI(w http.ResponseWriter, r *http.Request)
}
ip := httpext.GetRequesterIPFor(r)
if policy.Matches(ip, repo.Name, auth.AnonymousUserIdentity.UserName()) {
//do the redirect
// do the redirect
s := g.urlStr
s = strings.Replace(s, "%AUTH_TENANT_ID%", account.AuthTenantID, -1)

Check failure on line 85 in cmd/api/gui_redirect.go

View workflow job for this annotation

GitHub Actions / Build & Lint

wrapperFunc: use strings.ReplaceAll method in `strings.Replace(s, "%AUTH_TENANT_ID%", account.AuthTenantID, -1)` (gocritic)
s = strings.Replace(s, "%ACCOUNT_NAME%", account.Name, -1)

Check failure on line 86 in cmd/api/gui_redirect.go

View workflow job for this annotation

GitHub Actions / Build & Lint

wrapperFunc: use strings.ReplaceAll method in `strings.Replace(s, "%ACCOUNT_NAME%", account.Name, -1)` (gocritic)
Expand Down
4 changes: 2 additions & 2 deletions cmd/api/header_reflect.go
Expand Up @@ -27,7 +27,7 @@ import (

// guiRedirecter is an api.API that implements the GET /debug/reflect-headers endpoint.
type headerReflector struct {
Enabled bool //usually only on dev/QA systems
Enabled bool // usually only on dev/QA systems
}

// AddTo implements the api.API interface.
Expand All @@ -38,7 +38,7 @@ func (hr *headerReflector) AddTo(r *mux.Router) {
}

func reflectHeaders(w http.ResponseWriter, r *http.Request) {
//echo all request headers into the response body
// echo all request headers into the response body
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusOK)
for key, vals := range r.Header {
Expand Down
22 changes: 11 additions & 11 deletions cmd/api/main.go
Expand Up @@ -82,11 +82,11 @@ func run(cmd *cobra.Command, args []string) {
rle = &keppel.RateLimitEngine{Driver: rld, Client: rc}
}

//start background goroutines
// start background goroutines
ctx := httpext.ContextWithSIGINT(context.Background(), 10*time.Second)
runPeering(ctx, cfg, db)

//wire up HTTP handlers
// wire up HTTP handlers
corsMiddleware := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"HEAD", "GET", "POST", "PUT", "DELETE"},
Expand All @@ -97,7 +97,7 @@ func run(cmd *cobra.Command, args []string) {
auth.NewAPI(cfg, ad, fd, db),
registryv2.NewAPI(cfg, ad, fd, sd, icd, db, auditor, rle),
peerv1.NewAPI(cfg, ad, db),
&headerReflector{logg.ShowDebug}, //the header reflection endpoint is only enabled where debugging is enabled (i.e. usually in dev/QA only)
&headerReflector{logg.ShowDebug}, // the header reflection endpoint is only enabled where debugging is enabled (i.e. usually in dev/QA only)
&guiRedirecter{db, os.Getenv("KEPPEL_GUI_URI")},
httpapi.HealthCheckAPI{
SkipRequestLog: true,
Expand All @@ -113,7 +113,7 @@ func run(cmd *cobra.Command, args []string) {
mux.Handle("/", handler)
mux.Handle("/metrics", promhttp.Handler())

//start HTTP server
// start HTTP server
apiListenAddress := osext.GetenvOrDefault("KEPPEL_API_LISTEN_ADDRESS", ":8080")
must.Succeed(httpext.ListenAndServeContext(ctx, apiListenAddress, mux))
}
Expand All @@ -133,11 +133,11 @@ func initRedis() (*redis.Client, error) {
}

func setupDBIfRequested(db *keppel.DB) error {
//This method performs specialized first-time setup for conformance test
//scenarios where we always start with a fresh empty database.
// This method performs specialized first-time setup for conformance test
// scenarios where we always start with a fresh empty database.
//
//This setup cannot be done before keppel-api has been started, because the
//DB schema has not been populated yet at that point.
// This setup cannot be done before keppel-api has been started, because the
// DB schema has not been populated yet at that point.
if osext.GetenvBool("KEPPEL_RUN_DB_SETUP_FOR_CONFORMANCE_TEST") {
// clear out database before running conformance tests to be not out of sync with cleared out storage filedriver
// borrowed from test setup
Expand Down Expand Up @@ -173,9 +173,9 @@ func setupDBIfRequested(db *keppel.DB) error {

func reportClientIP(inner http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
//This middleware adds the X-Keppel-Your-Ip header to all requests, which is used:
//1. by end users to understand which IPs they need to put in their RBAC policies
//2. by Keppel operators to check if X-Forwarded-For is transported correctly through reverse proxies
// This middleware adds the X-Keppel-Your-Ip header to all requests, which is used:
// 1. by end users to understand which IPs they need to put in their RBAC policies
// 2. by Keppel operators to check if X-Forwarded-For is transported correctly through reverse proxies
w.Header().Set("X-Keppel-Your-Ip", httpext.GetRequesterIPFor(r))
inner.ServeHTTP(w, r)
})
Expand Down
14 changes: 7 additions & 7 deletions cmd/api/peering.go
Expand Up @@ -44,19 +44,19 @@ func runPeering(ctx context.Context, cfg keppel.Configuration, db *keppel.DB) {
}

if len(isPeerHostName) == 0 {
//nothing to do
// nothing to do
return
}

//add missing entries to `peers` table
// add missing entries to `peers` table
for peerHostName := range isPeerHostName {
_ = must.Return(db.Exec(
`INSERT INTO peers (hostname) VALUES ($1) ON CONFLICT DO NOTHING`,
peerHostName,
))
}

//remove old entries from `peers` table
// remove old entries from `peers` table
var allPeers []keppel.Peer
_ = must.Return(db.Select(&allPeers, `SELECT * FROM peers`))
for _, peer := range allPeers {
Expand Down Expand Up @@ -99,19 +99,19 @@ func tryIssueNewPasswordForPeer(ctx context.Context, cfg keppel.Configuration, d
}
defer sqlext.RollbackUnlessCommitted(tx)

//select next peer that needs a new password, if any
// select next peer that needs a new password, if any
var peer keppel.Peer
err = tx.SelectOne(&peer, getNextPeerQuery, time.Now().Add(-10*time.Minute))
if errors.Is(err, sql.ErrNoRows) {
//nothing to do
// nothing to do
//nolint:errcheck
tx.Rollback() //avoid the log line generated by sqlext.RollbackUnlessCommitted()
tx.Rollback() // avoid the log line generated by sqlext.RollbackUnlessCommitted()
return nil
}
if err != nil {
return err
}

//issue password (this will also commit the transaction)
// issue password (this will also commit the transaction)
return tasks.IssueNewPasswordForPeer(ctx, cfg, db, tx, peer)
}
10 changes: 5 additions & 5 deletions cmd/healthmonitor/constants.go
Expand Up @@ -20,17 +20,17 @@ package healthmonitorcmd

import "encoding/base64"

//This file contains a minimal complete Docker image (one blob with the image
//configuration and one manifest) as generated by the Dockerfile:
// This file contains a minimal complete Docker image (one blob with the image
// configuration and one manifest) as generated by the Dockerfile:
//
// FROM scratch
// ADD hello.txt /
//
//where hello.txt contains the string "hello\n".
// where hello.txt contains the string "hello\n".
//
//NOTE: This is technically not minimal. We could have an image without any
//layers whatsoever. However, we explicitly include a small layer because layer
//downloads and config downloads exercise different code paths in the API.
// layers whatsoever. However, we explicitly include a small layer because layer
// downloads and config downloads exercise different code paths in the API.

const minimalImageConfiguration = `{"architecture":"amd64","config":{"Hostname":"","Domainname":"","User":"","AttachStdin":false,"AttachStdout":false,"AttachStderr":false,"Tty":false,"OpenStdin":false,"StdinOnce":false,"Env":["PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"],"Cmd":null,"Image":"","Volumes":null,"WorkingDir":"","Entrypoint":null,"OnBuild":null,"Labels":null},"container_config":{"Hostname":"","Domainname":"","User":"","AttachStdin":false,"AttachStdout":false,"AttachStderr":false,"Tty":false,"OpenStdin":false,"StdinOnce":false,"Env":["PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"],"Cmd":["/bin/sh","-c","#(nop) ADD file:7d1b8e6c9123955c22ae5efea6309bc3436ed116b03932f650caae30c06ab651 in / "],"Image":"","Volumes":null,"WorkingDir":"","Entrypoint":null,"OnBuild":null,"Labels":null},"created":"2021-02-23T10:00:06.332861325Z","docker_version":"20.10.1","history":[{"created":"2021-02-23T10:00:06.332861325Z","created_by":"/bin/sh -c #(nop) ADD file:7d1b8e6c9123955c22ae5efea6309bc3436ed116b03932f650caae30c06ab651 in / "}],"os":"linux","rootfs":{"type":"layers","diff_ids":["sha256:967a3b82a0bf0e6079cb995d96faed65135d465a349e73390e6de3112273d5ca"]}}`

Expand Down
12 changes: 6 additions & 6 deletions cmd/healthmonitor/main.go
Expand Up @@ -77,7 +77,7 @@ type healthMonitorJob struct {
RepoClient *client.RepoClient

LastResultLock *sync.RWMutex
LastResult *bool //nil during initialization, non-nil indicates result of last healthcheck
LastResult *bool // nil during initialization, non-nil indicates result of last healthcheck
}

func run(cmd *cobra.Command, args []string) {
Expand Down Expand Up @@ -105,7 +105,7 @@ func run(cmd *cobra.Command, args []string) {

ctx := httpext.ContextWithSIGINT(context.Background(), 1*time.Second)

//run one-time preparations
// run one-time preparations
err = job.PrepareKeppelAccount(ctx)
if err != nil {
logg.Fatal("while preparing Keppel account: %s", err.Error())
Expand All @@ -115,16 +115,16 @@ func run(cmd *cobra.Command, args []string) {
logg.Fatal("while uploading test image: %s", err.Error())
}

//expose metrics endpoint
// expose metrics endpoint
mux := http.NewServeMux()
mux.HandleFunc("/healthcheck", job.ReportHealthcheckResult)
mux.Handle("/metrics", promhttp.Handler())
go func() {
must.Succeed(httpext.ListenAndServeContext(ctx, listenAddress, mux))
}()

//enter long-running check loop
job.ValidateImage(ctx, manifestRef) //once immediately to initialize the metric
// enter long-running check loop
job.ValidateImage(ctx, manifestRef) // once immediately to initialize the metric
tick := time.Tick(30 * time.Second)
for {
select {
Expand All @@ -141,7 +141,7 @@ func (j *healthMonitorJob) PrepareKeppelAccount(ctx context.Context) error {
reqBody := map[string]any{
"account": map[string]any{
"auth_tenant_id": j.AuthDriver.CurrentAuthTenantID(),
//anonymous pull access is needed for `keppel server anycastmonitor`
// anonymous pull access is needed for `keppel server anycastmonitor`
"rbac_policies": []map[string]any{{
"match_repository": "healthcheck",
"permissions": []string{"anonymous_pull"},
Expand Down
4 changes: 2 additions & 2 deletions cmd/janitor/main.go
Expand Up @@ -66,7 +66,7 @@ func run(cmd *cobra.Command, args []string) {

ctx := httpext.ContextWithSIGINT(context.Background(), 10*time.Second)

//start task loops
// start task loops
janitor := tasks.NewJanitor(cfg, fd, sd, icd, db, auditor)
go janitor.AccountFederationAnnouncementJob(nil).Run(ctx)
go janitor.AbandonedUploadCleanupJob(nil).Run(ctx)
Expand All @@ -81,7 +81,7 @@ func run(cmd *cobra.Command, args []string) {
go janitor.CheckTrivySecurityStatusJob(nil).Run(ctx, jobloop.NumGoroutines(3))
}

//start HTTP server for Prometheus metrics and health check
// start HTTP server for Prometheus metrics and health check
handler := httpapi.Compose(
httpapi.HealthCheckAPI{SkipRequestLog: true},
pprofapi.API{IsAuthorized: pprofapi.IsRequestFromLocalhost},
Expand Down
16 changes: 8 additions & 8 deletions internal/api/auth/api.go
Expand Up @@ -71,18 +71,18 @@ func respondWithError(w http.ResponseWriter, code int, err error) bool {
func (a *API) handleGetAuth(w http.ResponseWriter, r *http.Request) {
httpapi.IdentifyEndpoint(r, "/keppel/v1/auth")

//parse request
// parse request
req, err := parseRequest(r.URL.RawQuery, a.cfg)
if respondWithError(w, http.StatusBadRequest, err) {
return
}

//special cases for anycast requests
// special cases for anycast requests
if req.IntendedAudience.IsAnycast {
if len(req.Scopes) > 1 {
//NOTE: This is not a fundamental restriction, there was just no demand for
//it yet. If the requirement comes up, we could ask all relevant upstreams
//for tokens and issue one token that grants the sum of all accesses.
// it yet. If the requirement comes up, we could ask all relevant upstreams
// for tokens and issue one token that grants the sum of all accesses.
respondWithError(w, http.StatusInternalServerError, errors.New("anycast tokens cannot be issued for multiple scopes at once"))
return
}
Expand All @@ -96,8 +96,8 @@ func (a *API) handleGetAuth(w http.ResponseWriter, r *http.Request) {
return
}

//if we don't have this account locally, but the request is an anycast
//request and one of our peers has the account, ask them to issue the token
// if we don't have this account locally, but the request is an anycast
// request and one of our peers has the account, ask them to issue the token
if account == nil {
err := a.reverseProxyTokenReqToUpstream(w, r, req.IntendedAudience, repoScope.AccountName)
if !errors.Is(err, keppel.ErrNoSuchPrimaryAccount) {
Expand Down Expand Up @@ -135,8 +135,8 @@ func (a *API) reverseProxyTokenReqToUpstream(w http.ResponseWriter, r *http.Requ
return err
}

//protect against infinite forwarding loops in case different Keppels have
//different ideas about who is the primary account
// protect against infinite forwarding loops in case different Keppels have
// different ideas about who is the primary account
if forwardedBy := r.URL.Query().Get("X-Keppel-Forwarded-By"); forwardedBy != "" {
logg.Error("not forwarding anycast token request for account %q to %s because request was already forwarded to us by %s",
accountName, primaryHostName, forwardedBy)
Expand Down

0 comments on commit 73875f6

Please sign in to comment.