Skip to content

chore: update go to 1.24.1 #17194

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

Merged
merged 2 commits into from
Apr 1, 2025
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion .github/actions/setup-go/action.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ description: |
inputs:
version:
description: "The Go version to use."
default: "1.22.12"
default: "1.24.1"
runs:
using: "composite"
steps:
Expand Down
42 changes: 13 additions & 29 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,30 +24,19 @@ linters-settings:
enabled-checks:
# - appendAssign
# - appendCombine
- argOrder
# - assignOp
# - badCall
- badCond
- badLock
- badRegexp
- boolExprSimplify
# - builtinShadow
- builtinShadowDecl
- captLocal
- caseOrder
- codegenComment
# - commentedOutCode
- commentedOutImport
- commentFormatting
- defaultCaseOrder
- deferUnlambda
# - deprecatedComment
# - docStub
- dupArg
- dupBranchBody
- dupCase
- dupImport
- dupSubExpr
# - elseif
- emptyFallthrough
# - emptyStringTest
Expand All @@ -56,56 +45,43 @@ linters-settings:
# - exitAfterDefer
# - exposedSyncMutex
# - filepathJoin
- flagDeref
- flagName
- hexLiteral
# - httpNoBody
# - hugeParam
# - ifElseChain
# - importShadow
- indexAlloc
- initClause
- mapKey
- methodExprCall
# - nestingReduce
- newDeref
- nilValReturn
# - octalLiteral
- offBy1
# - paramTypeCombine
# - preferStringWriter
# - preferWriteByte
# - ptrToRefParam
# - rangeExprCopy
# - rangeValCopy
- regexpMust
- regexpPattern
# - regexpSimplify
- ruleguard
- singleCaseSwitch
- sloppyLen
# - sloppyReassign
- sloppyTypeAssert
- sortSlice
- sprintfQuotedString
- sqlQuery
# - stringConcatSimplify
# - stringXbytes
# - suspiciousSorting
- switchTrue
- truncateCmp
- typeAssertChain
# - typeDefFirst
- typeSwitchVar
# - typeUnparen
- underef
# - unlabelStmt
# - unlambda
# - unnamedResult
# - unnecessaryBlock
# - unnecessaryDefer
# - unslice
- valSwap
- weakCond
# - whyNoLint
# - wrapperFunc
Expand Down Expand Up @@ -203,6 +179,14 @@ linters-settings:
- G601

issues:
exclude-dirs:
- coderd/database/dbmem
- node_modules
- .git

exclude-files:
- scripts/rules.go

# Rules listed here: https://github.com/securego/gosec#available-rules
exclude-rules:
- path: _test\.go
Expand All @@ -211,20 +195,20 @@ issues:
- errcheck
- forcetypeassert
- exhaustruct # This is unhelpful in tests.
- revive # TODO(JonA): disabling in order to update golangci-lint
- gosec # TODO(JonA): disabling in order to update golangci-lint
- path: scripts/*
linters:
- exhaustruct
- path: scripts/rules.go
linters:
- ALL

fix: true
max-issues-per-linter: 0
max-same-issues: 0

run:
skip-dirs:
- node_modules
- .git
skip-files:
- scripts/rules.go
timeout: 10m

# Over time, add more and more linters from
Expand Down
18 changes: 12 additions & 6 deletions agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -936,7 +936,7 @@ func (a *agent) run() (retErr error) {
connMan.startAgentAPI("send logs", gracefulShutdownBehaviorRemain,
func(ctx context.Context, aAPI proto.DRPCAgentClient24) error {
err := a.logSender.SendLoop(ctx, aAPI)
if xerrors.Is(err, agentsdk.LogLimitExceededError) {
if xerrors.Is(err, agentsdk.ErrLogLimitExceeded) {
// we don't want this error to tear down the API connection and propagate to the
// other routines that use the API. The LogSender has already dropped a warning
// log, so just return nil here.
Expand Down Expand Up @@ -1583,9 +1583,13 @@ func (a *agent) Collect(ctx context.Context, networkStats map[netlogtype.Connect
}
for conn, counts := range networkStats {
stats.ConnectionsByProto[conn.Proto.String()]++
// #nosec G115 - Safe conversions for network statistics which we expect to be within int64 range
stats.RxBytes += int64(counts.RxBytes)
// #nosec G115 - Safe conversions for network statistics which we expect to be within int64 range
stats.RxPackets += int64(counts.RxPackets)
// #nosec G115 - Safe conversions for network statistics which we expect to be within int64 range
stats.TxBytes += int64(counts.TxBytes)
// #nosec G115 - Safe conversions for network statistics which we expect to be within int64 range
stats.TxPackets += int64(counts.TxPackets)
}

Expand Down Expand Up @@ -1638,11 +1642,12 @@ func (a *agent) Collect(ctx context.Context, networkStats map[netlogtype.Connect
wg.Wait()
sort.Float64s(durations)
durationsLength := len(durations)
if durationsLength == 0 {
switch {
case durationsLength == 0:
stats.ConnectionMedianLatencyMs = -1
} else if durationsLength%2 == 0 {
case durationsLength%2 == 0:
stats.ConnectionMedianLatencyMs = (durations[durationsLength/2-1] + durations[durationsLength/2]) / 2
} else {
default:
stats.ConnectionMedianLatencyMs = durations[durationsLength/2]
}
// Convert from microseconds to milliseconds.
Expand Down Expand Up @@ -1749,7 +1754,7 @@ func (a *agent) HTTPDebug() http.Handler {
r.Get("/debug/magicsock", a.HandleHTTPDebugMagicsock)
r.Get("/debug/magicsock/debug-logging/{state}", a.HandleHTTPMagicsockDebugLoggingState)
r.Get("/debug/manifest", a.HandleHTTPDebugManifest)
r.NotFound(func(w http.ResponseWriter, r *http.Request) {
r.NotFound(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte("404 not found"))
})
Expand Down Expand Up @@ -2034,7 +2039,7 @@ func (a *apiConnRoutineManager) wait() error {
}

func PrometheusMetricsHandler(prometheusRegistry *prometheus.Registry, logger slog.Logger) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/plain")

// Based on: https://github.com/tailscale/tailscale/blob/280255acae604796a1113861f5a84e6fa2dc6121/ipn/localapi/localapi.go#L489
Expand Down Expand Up @@ -2070,5 +2075,6 @@ func WorkspaceKeySeed(workspaceID uuid.UUID, agentName string) (int64, error) {
return 42, err
}

// #nosec G115 - Safe conversion to generate int64 hash from Sum64, data loss acceptable
return int64(h.Sum64()), nil
}
7 changes: 5 additions & 2 deletions agent/agentcontainers/containers_dockercli.go
Original file line number Diff line number Diff line change
Expand Up @@ -453,8 +453,9 @@ func convertDockerInspect(raw []byte) ([]codersdk.WorkspaceAgentContainer, []str
hostPortContainers[hp] = append(hostPortContainers[hp], in.ID)
}
out.Ports = append(out.Ports, codersdk.WorkspaceAgentContainerPort{
Network: network,
Port: cp,
Network: network,
Port: cp,
// #nosec G115 - Safe conversion since Docker ports are limited to uint16 range
HostPort: uint16(hp),
HostIP: p.HostIP,
})
Expand Down Expand Up @@ -497,12 +498,14 @@ func convertDockerPort(in string) (uint16, string, error) {
if err != nil {
return 0, "", xerrors.Errorf("invalid port format: %s", in)
}
// #nosec G115 - Safe conversion since Docker TCP ports are limited to uint16 range
return uint16(p), "tcp", nil
case 2:
p, err := strconv.Atoi(parts[0])
if err != nil {
return 0, "", xerrors.Errorf("invalid port format: %s", in)
}
// #nosec G115 - Safe conversion since Docker ports are limited to uint16 range
return uint16(p), parts[1], nil
default:
return 0, "", xerrors.Errorf("invalid port format: %s", in)
Expand Down
1 change: 1 addition & 0 deletions agent/agentrsa/key_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ func BenchmarkGenerateDeterministicKey(b *testing.B) {
for range b.N {
// always record the result of DeterministicPrivateKey to prevent
// the compiler eliminating the function call.
// #nosec G404 - Using math/rand is acceptable for benchmarking deterministic keys
r = agentrsa.GenerateDeterministicKey(rand.Int64())
}

Expand Down
5 changes: 3 additions & 2 deletions agent/agentssh/agentssh.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ func NewServer(ctx context.Context, logger slog.Logger, prometheusRegistry *prom
slog.F("destination_port", destinationPort))
return true
},
PtyCallback: func(ctx ssh.Context, pty ssh.Pty) bool {
PtyCallback: func(_ ssh.Context, _ ssh.Pty) bool {
return true
},
ReversePortForwardingCallback: func(ctx ssh.Context, bindHost string, bindPort uint32) bool {
Expand All @@ -240,7 +240,7 @@ func NewServer(ctx context.Context, logger slog.Logger, prometheusRegistry *prom
"cancel-streamlocal-forward@openssh.com": unixForwardHandler.HandleSSHRequest,
},
X11Callback: s.x11Callback,
ServerConfigCallback: func(ctx ssh.Context) *gossh.ServerConfig {
ServerConfigCallback: func(_ ssh.Context) *gossh.ServerConfig {
return &gossh.ServerConfig{
NoClientAuth: true,
}
Expand Down Expand Up @@ -702,6 +702,7 @@ func (s *Server) startPTYSession(logger slog.Logger, session ptySession, magicTy
windowSize = nil
continue
}
// #nosec G115 - Safe conversions for terminal dimensions which are expected to be within uint16 range
resizeErr := ptty.Resize(uint16(win.Height), uint16(win.Width))
// If the pty is closed, then command has exited, no need to log.
if resizeErr != nil && !errors.Is(resizeErr, pty.ErrClosed) {
Expand Down
7 changes: 6 additions & 1 deletion agent/agentssh/x11.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,8 @@ func (s *Server) x11Handler(ctx ssh.Context, x11 ssh.X11) (displayNumber int, ha
OriginatorPort uint32
}{
OriginatorAddress: tcpAddr.IP.String(),
OriginatorPort: uint32(tcpAddr.Port),
// #nosec G115 - Safe conversion as TCP port numbers are within uint32 range (0-65535)
OriginatorPort: uint32(tcpAddr.Port),
}))
if err != nil {
s.logger.Warn(ctx, "failed to open X11 channel", slog.Error(err))
Expand Down Expand Up @@ -294,6 +295,7 @@ func addXauthEntry(ctx context.Context, fs afero.Fs, host string, display string
return xerrors.Errorf("failed to write family: %w", err)
}

// #nosec G115 - Safe conversion for host name length which is expected to be within uint16 range
err = binary.Write(file, binary.BigEndian, uint16(len(host)))
if err != nil {
return xerrors.Errorf("failed to write host length: %w", err)
Expand All @@ -303,6 +305,7 @@ func addXauthEntry(ctx context.Context, fs afero.Fs, host string, display string
return xerrors.Errorf("failed to write host: %w", err)
}

// #nosec G115 - Safe conversion for display name length which is expected to be within uint16 range
err = binary.Write(file, binary.BigEndian, uint16(len(display)))
if err != nil {
return xerrors.Errorf("failed to write display length: %w", err)
Expand All @@ -312,6 +315,7 @@ func addXauthEntry(ctx context.Context, fs afero.Fs, host string, display string
return xerrors.Errorf("failed to write display: %w", err)
}

// #nosec G115 - Safe conversion for auth protocol length which is expected to be within uint16 range
err = binary.Write(file, binary.BigEndian, uint16(len(authProtocol)))
if err != nil {
return xerrors.Errorf("failed to write auth protocol length: %w", err)
Expand All @@ -321,6 +325,7 @@ func addXauthEntry(ctx context.Context, fs afero.Fs, host string, display string
return xerrors.Errorf("failed to write auth protocol: %w", err)
}

// #nosec G115 - Safe conversion for auth cookie length which is expected to be within uint16 range
err = binary.Write(file, binary.BigEndian, uint16(len(authCookieBytes)))
if err != nil {
return xerrors.Errorf("failed to write auth cookie length: %w", err)
Expand Down
4 changes: 2 additions & 2 deletions agent/apphealth.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,8 +167,8 @@ func shouldStartTicker(app codersdk.WorkspaceApp) bool {
return app.Healthcheck.URL != "" && app.Healthcheck.Interval > 0 && app.Healthcheck.Threshold > 0
}

func healthChanged(old map[uuid.UUID]codersdk.WorkspaceAppHealth, new map[uuid.UUID]codersdk.WorkspaceAppHealth) bool {
for name, newValue := range new {
func healthChanged(old map[uuid.UUID]codersdk.WorkspaceAppHealth, updated map[uuid.UUID]codersdk.WorkspaceAppHealth) bool {
for name, newValue := range updated {
oldValue, found := old[name]
if !found {
return true
Expand Down
7 changes: 4 additions & 3 deletions agent/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,21 +89,22 @@ func (a *agent) collectMetrics(ctx context.Context) []*proto.Stats_Metric {
for _, metric := range metricFamily.GetMetric() {
labels := toAgentMetricLabels(metric.Label)

if metric.Counter != nil {
switch {
case metric.Counter != nil:
collected = append(collected, &proto.Stats_Metric{
Name: metricFamily.GetName(),
Type: proto.Stats_Metric_COUNTER,
Value: metric.Counter.GetValue(),
Labels: labels,
})
} else if metric.Gauge != nil {
case metric.Gauge != nil:
collected = append(collected, &proto.Stats_Metric{
Name: metricFamily.GetName(),
Type: proto.Stats_Metric_GAUGE,
Value: metric.Gauge.GetValue(),
Labels: labels,
})
} else {
default:
a.logger.Error(ctx, "unsupported metric type", slog.F("type", metricFamily.Type.String()))
}
}
Expand Down
5 changes: 3 additions & 2 deletions agent/reconnectingpty/buffered.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ func newBuffered(ctx context.Context, logger slog.Logger, execer agentexec.Exece
// Add TERM then start the command with a pty. pty.Cmd duplicates Path as the
// first argument so remove it.
cmdWithEnv := execer.PTYCommandContext(ctx, cmd.Path, cmd.Args[1:]...)
//nolint:gocritic
cmdWithEnv.Env = append(rpty.command.Env, "TERM=xterm-256color")
cmdWithEnv.Dir = rpty.command.Dir
ptty, process, err := pty.Start(cmdWithEnv)
Expand Down Expand Up @@ -236,7 +237,7 @@ func (rpty *bufferedReconnectingPTY) Wait() {
_, _ = rpty.state.waitForState(StateClosing)
}

func (rpty *bufferedReconnectingPTY) Close(error error) {
func (rpty *bufferedReconnectingPTY) Close(err error) {
// The closing state change will be handled by the lifecycle.
rpty.state.setState(StateClosing, error)
rpty.state.setState(StateClosing, err)
}
2 changes: 2 additions & 0 deletions agent/reconnectingpty/screen.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ func (rpty *screenReconnectingPTY) doAttach(ctx context.Context, conn net.Conn,
rpty.command.Path,
// pty.Cmd duplicates Path as the first argument so remove it.
}, rpty.command.Args[1:]...)...)
//nolint:gocritic
cmd.Env = append(rpty.command.Env, "TERM=xterm-256color")
cmd.Dir = rpty.command.Dir
ptty, process, err := pty.Start(cmd, pty.WithPTYOption(
Expand Down Expand Up @@ -340,6 +341,7 @@ func (rpty *screenReconnectingPTY) sendCommand(ctx context.Context, command stri
// -X runs a command in the matching session.
"-X", command,
)
//nolint:gocritic
cmd.Env = append(rpty.command.Env, "TERM=xterm-256color")
cmd.Dir = rpty.command.Dir
cmd.Stdout = &stdout
Expand Down
4 changes: 2 additions & 2 deletions apiversion/apiversion.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ import (

// New returns an *APIVersion with the given major.minor and
// additional supported major versions.
func New(maj, min int) *APIVersion {
func New(maj, minor int) *APIVersion {
v := &APIVersion{
supportedMajor: maj,
supportedMinor: min,
supportedMinor: minor,
additionalMajors: make([]int, 0),
}
return v
Expand Down
Loading
Loading