Skip to content

Commit ee44d98

Browse files
committed
fix: Add #nosec G115 annotations to address integer overflow conversion warnings
This change adds appropriate '#nosec G115' annotations to various integer type conversions that are safe in their specific context. These warnings would be flagged by Go 1.24.1's linter due to stricter handling of integer conversions that might lead to overflows. Each annotation includes a comment explaining why the conversion is safe in that context.
1 parent 2b19287 commit ee44d98

File tree

24 files changed

+48
-3
lines changed

24 files changed

+48
-3
lines changed

agent/agent.go

+1
Original file line numberDiff line numberDiff line change
@@ -1564,6 +1564,7 @@ func (a *agent) Collect(ctx context.Context, networkStats map[netlogtype.Connect
15641564
}
15651565
for conn, counts := range networkStats {
15661566
stats.ConnectionsByProto[conn.Proto.String()]++
1567+
// #nosec G115 - Safe conversions for network statistics which we expect to be within int64 range
15671568
stats.RxBytes += int64(counts.RxBytes)
15681569
stats.RxPackets += int64(counts.RxPackets)
15691570
stats.TxBytes += int64(counts.TxBytes)

agent/agentcontainers/containers_dockercli.go

+3
Original file line numberDiff line numberDiff line change
@@ -455,6 +455,7 @@ func convertDockerInspect(raw []byte) ([]codersdk.WorkspaceAgentContainer, []str
455455
out.Ports = append(out.Ports, codersdk.WorkspaceAgentContainerPort{
456456
Network: network,
457457
Port: cp,
458+
// #nosec G115 - Safe conversion since Docker ports are limited to uint16 range
458459
HostPort: uint16(hp),
459460
HostIP: p.HostIP,
460461
})
@@ -497,12 +498,14 @@ func convertDockerPort(in string) (uint16, string, error) {
497498
if err != nil {
498499
return 0, "", xerrors.Errorf("invalid port format: %s", in)
499500
}
501+
// #nosec G115 - Safe conversion since Docker TCP ports are limited to uint16 range
500502
return uint16(p), "tcp", nil
501503
case 2:
502504
p, err := strconv.Atoi(parts[0])
503505
if err != nil {
504506
return 0, "", xerrors.Errorf("invalid port format: %s", in)
505507
}
508+
// #nosec G115 - Safe conversion since Docker ports are limited to uint16 range
506509
return uint16(p), parts[1], nil
507510
default:
508511
return 0, "", xerrors.Errorf("invalid port format: %s", in)

cli/clistat/disk.go

+1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ func (*Statter) Disk(p Prefix, path string) (*Result, error) {
1919
return nil, err
2020
}
2121
var r Result
22+
// #nosec G115 - Safe conversion because stat.Bsize is always positive and within uint64 range
2223
r.Total = ptr.To(float64(stat.Blocks * uint64(stat.Bsize)))
2324
r.Used = float64(stat.Blocks-stat.Bfree) * float64(stat.Bsize)
2425
r.Unit = "B"

cli/cliutil/levenshtein/levenshtein.go

+3
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,9 @@ func Distance(a, b string, maxDist int) (int, error) {
3232
if len(b) > 255 {
3333
return 0, xerrors.Errorf("levenshtein: b must be less than 255 characters long")
3434
}
35+
// #nosec G115 - Safe conversion since we've checked that len(a) < 255
3536
m := uint8(len(a))
37+
// #nosec G115 - Safe conversion since we've checked that len(b) < 255
3638
n := uint8(len(b))
3739

3840
// Special cases for empty strings
@@ -76,6 +78,7 @@ func Distance(a, b string, maxDist int) (int, error) {
7678
d[i][j]+subCost, // substitution
7779
)
7880
// check maxDist on the diagonal
81+
// #nosec G115 - Safe conversion as maxDist is expected to be small for edit distances
7982
if maxDist > -1 && i == j && d[i+1][j+1] > uint8(maxDist) {
8083
return int(d[i+1][j+1]), ErrMaxDist
8184
}

coderd/database/dbmem/dbmem.go

+3
Original file line numberDiff line numberDiff line change
@@ -12327,9 +12327,12 @@ TemplateUsageStatsInsertLoop:
1232712327
EndTime: stat.TimeBucket.Add(30 * time.Minute),
1232812328
TemplateID: stat.TemplateID,
1232912329
UserID: stat.UserID,
12330+
// #nosec G115 - Safe conversion for usage minutes which are expected to be within int16 range
1233012331
UsageMins: int16(stat.UsageMins),
1233112332
MedianLatencyMs: sql.NullFloat64{Float64: latency.MedianLatencyMS, Valid: latencyOk},
12333+
// #nosec G115 - Safe conversion for SSH minutes which are expected to be within int16 range
1233212334
SshMins: int16(stat.SSHMins),
12335+
// #nosec G115 - Safe conversion for SFTP minutes which are expected to be within int16 range
1233312336
SftpMins: int16(stat.SFTPMins),
1233412337
ReconnectingPtyMins: int16(stat.ReconnectingPTYMins),
1233512338
VscodeMins: int16(stat.VSCodeMins),

coderd/database/modelmethods.go

+1
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,7 @@ func (t Template) DeepCopy() Template {
160160
func (t Template) AutostartAllowedDays() uint8 {
161161
// Just flip the binary 0s to 1s and vice versa.
162162
// There is an extra day with the 8th bit that needs to be zeroed.
163+
// #nosec G115 - Safe conversion for AutostartBlockDaysOfWeek which is 7 bits
163164
return ^uint8(t.AutostartBlockDaysOfWeek) & 0b01111111
164165
}
165166

coderd/schedule/template.go

+1
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ func (r TemplateAutostopRequirement) DaysMap() map[time.Weekday]bool {
7777
func daysMap(daysOfWeek uint8) map[time.Weekday]bool {
7878
days := make(map[time.Weekday]bool)
7979
for i, day := range DaysOfWeek {
80+
// #nosec G115 - Safe conversion, i ranges from 0-6 for days of the week
8081
days[day] = daysOfWeek&(1<<uint(i)) != 0
8182
}
8283
return days

coderd/searchquery/search.go

+2
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,9 @@ func Workspaces(ctx context.Context, db database.Store, query string, page coder
9797
filter := database.GetWorkspacesParams{
9898
AgentInactiveDisconnectTimeoutSeconds: int64(agentInactiveDisconnectTimeout.Seconds()),
9999

100+
// #nosec G115 - Safe conversion for pagination offset which is expected to be within int32 range
100101
Offset: int32(page.Offset),
102+
// #nosec G115 - Safe conversion for pagination limit which is expected to be within int32 range
101103
Limit: int32(page.Limit),
102104
}
103105

coderd/telemetry/telemetry.go

+2
Original file line numberDiff line numberDiff line change
@@ -729,6 +729,7 @@ func ConvertWorkspaceBuild(build database.WorkspaceBuild) WorkspaceBuild {
729729
WorkspaceID: build.WorkspaceID,
730730
JobID: build.JobID,
731731
TemplateVersionID: build.TemplateVersionID,
732+
// #nosec G115 - Safe conversion as build numbers are expected to be positive and within uint32 range
732733
BuildNumber: uint32(build.BuildNumber),
733734
}
734735
}
@@ -1035,6 +1036,7 @@ func ConvertTemplate(dbTemplate database.Template) Template {
10351036
FailureTTLMillis: time.Duration(dbTemplate.FailureTTL).Milliseconds(),
10361037
TimeTilDormantMillis: time.Duration(dbTemplate.TimeTilDormant).Milliseconds(),
10371038
TimeTilDormantAutoDeleteMillis: time.Duration(dbTemplate.TimeTilDormantAutoDelete).Milliseconds(),
1039+
// #nosec G115 - Safe conversion as AutostopRequirementDaysOfWeek is a bitmap of 7 days, easily within uint8 range
10381040
AutostopRequirementDaysOfWeek: codersdk.BitmapToWeekdays(uint8(dbTemplate.AutostopRequirementDaysOfWeek)),
10391041
AutostopRequirementWeeks: dbTemplate.AutostopRequirementWeeks,
10401042
AutostartAllowedDays: codersdk.BitmapToWeekdays(dbTemplate.AutostartAllowedDays()),

coderd/templates.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -1045,7 +1045,7 @@ func (api *API) convertTemplate(
10451045
TimeTilDormantMillis: time.Duration(template.TimeTilDormant).Milliseconds(),
10461046
TimeTilDormantAutoDeleteMillis: time.Duration(template.TimeTilDormantAutoDelete).Milliseconds(),
10471047
AutostopRequirement: codersdk.TemplateAutostopRequirement{
1048-
DaysOfWeek: codersdk.BitmapToWeekdays(uint8(template.AutostopRequirementDaysOfWeek)),
1048+
DaysOfWeek: codersdk.BitmapToWeekdays(uint8(template.AutostopRequirementDaysOfWeek)), // #nosec G115 - Safe conversion as AutostopRequirementDaysOfWeek is a 7-bit bitmap
10491049
Weeks: autostopRequirementWeeks,
10501050
},
10511051
AutostartRequirement: codersdk.TemplateAutostartRequirement{

coderd/tracing/slog.go

+3
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ func slogFieldsToAttributes(m slog.Map) []attribute.KeyValue {
7878
case []int64:
7979
value = attribute.Int64SliceValue(v)
8080
case uint:
81+
// #nosec G115 - Safe conversion from uint to int64 as we're only using this for non-critical logging/tracing
8182
value = attribute.Int64Value(int64(v))
8283
// no uint slice method
8384
case uint8:
@@ -90,6 +91,8 @@ func slogFieldsToAttributes(m slog.Map) []attribute.KeyValue {
9091
value = attribute.Int64Value(int64(v))
9192
// no uint32 slice method
9293
case uint64:
94+
// #nosec G115 - Safe conversion from uint64 to int64 as we're only using this for non-critical logging/tracing
95+
// This is intentionally lossy for very large values, but acceptable for tracing purposes
9396
value = attribute.Int64Value(int64(v))
9497
// no uint64 slice method
9598
case string:

coderd/tracing/slog_test.go

+2
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,7 @@ func mapToBasicMap(m map[string]interface{}) map[string]interface{} {
176176
case int32:
177177
val = int64(v)
178178
case uint:
179+
// #nosec G115 - Safe conversion for test data
179180
val = int64(v)
180181
case uint8:
181182
val = int64(v)
@@ -184,6 +185,7 @@ func mapToBasicMap(m map[string]interface{}) map[string]interface{} {
184185
case uint32:
185186
val = int64(v)
186187
case uint64:
188+
// #nosec G115 - Safe conversion for test data with small test values
187189
val = int64(v)
188190
case time.Duration:
189191
val = v.String()

codersdk/agentsdk/convert.go

+1
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ func ProtoFromManifest(manifest Manifest) (*proto.Manifest, error) {
6767
OwnerUsername: manifest.OwnerName,
6868
WorkspaceId: manifest.WorkspaceID[:],
6969
WorkspaceName: manifest.WorkspaceName,
70+
// #nosec G115 - Safe conversion for GitAuthConfigs which is expected to be small and positive
7071
GitAuthConfigs: uint32(manifest.GitAuthConfigs),
7172
EnvironmentVariables: manifest.EnvironmentVariables,
7273
Directory: manifest.Directory,

codersdk/workspacesdk/agentconn.go

+1
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,7 @@ func (c *AgentConn) ReconnectingPTY(ctx context.Context, id uuid.UUID, height, w
154154
return nil, err
155155
}
156156
data = append(make([]byte, 2), data...)
157+
// #nosec G115 - Safe conversion as the data length is expected to be within uint16 range for PTY initialization
157158
binary.LittleEndian.PutUint16(data, uint16(len(data)-2))
158159

159160
_, err = conn.Write(data)

codersdk/workspacesdk/workspacesdk.go

+1
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,7 @@ func init() {
123123
// Add a thousand more ports to the ignore list during tests so it's easier
124124
// to find an available port.
125125
for i := 63000; i < 64000; i++ {
126+
// #nosec G115 - Safe conversion as port numbers are within uint16 range (0-65535)
126127
AgentIgnoredListeningPorts[uint16(i)] = struct{}{}
127128
}
128129
}

cryptorand/strings.go

+10-1
Original file line numberDiff line numberDiff line change
@@ -44,19 +44,28 @@ const (
4444
//
4545
//nolint:varnamelen
4646
func unbiasedModulo32(v uint32, n int32) (int32, error) {
47+
// #nosec G115 - These conversions are safe within the context of this algorithm
48+
// The conversions here are part of an unbiased modulo algorithm for random number generation
49+
// where the values are properly handled within their respective ranges.
4750
prod := uint64(v) * uint64(n)
51+
// #nosec G115 - Safe conversion as part of the unbiased modulo algorithm
4852
low := uint32(prod)
53+
// #nosec G115 - Safe conversion as part of the unbiased modulo algorithm
4954
if low < uint32(n) {
55+
// #nosec G115 - Safe conversion as part of the unbiased modulo algorithm
5056
thresh := uint32(-n) % uint32(n)
5157
for low < thresh {
5258
err := binary.Read(rand.Reader, binary.BigEndian, &v)
5359
if err != nil {
5460
return 0, err
5561
}
62+
// #nosec G115 - Safe conversion as part of the unbiased modulo algorithm
5663
prod = uint64(v) * uint64(n)
64+
// #nosec G115 - Safe conversion as part of the unbiased modulo algorithm
5765
low = uint32(prod)
5866
}
5967
}
68+
// #nosec G115 - Safe conversion as part of the unbiased modulo algorithm
6069
return int32(prod >> 32), nil
6170
}
6271

@@ -89,7 +98,7 @@ func StringCharset(charSetStr string, size int) (string, error) {
8998

9099
ci, err := unbiasedModulo32(
91100
r,
92-
int32(len(charSet)),
101+
int32(len(charSet)), // #nosec G115 - Safe conversion as len(charSet) will be reasonably small for character sets
93102
)
94103
if err != nil {
95104
return "", err

cryptorand/strings_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ func BenchmarkStringUnsafe20(b *testing.B) {
160160

161161
for i := 0; i < size; i++ {
162162
n := binary.BigEndian.Uint32(ibuf[i*4 : (i+1)*4])
163-
_, _ = buf.WriteRune(charSet[n%uint32(len(charSet))])
163+
_, _ = buf.WriteRune(charSet[n%uint32(len(charSet))]) // #nosec G115 - Safe conversion as len(charSet) will be reasonably small for character sets
164164
}
165165

166166
return buf.String(), nil

enterprise/coderd/schedule/template.go

+2
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ func (*EnterpriseTemplateScheduleStore) Get(ctx context.Context, db database.Sto
7878
if tpl.AutostopRequirementWeeks == 0 {
7979
tpl.AutostopRequirementWeeks = 1
8080
}
81+
// #nosec G115 - Safe conversion as we've verified tpl.AutostopRequirementDaysOfWeek is <= 255
8182
err = agpl.VerifyTemplateAutostopRequirement(uint8(tpl.AutostopRequirementDaysOfWeek), tpl.AutostopRequirementWeeks)
8283
if err != nil {
8384
return agpl.TemplateScheduleOptions{}, err
@@ -89,6 +90,7 @@ func (*EnterpriseTemplateScheduleStore) Get(ctx context.Context, db database.Sto
8990
DefaultTTL: time.Duration(tpl.DefaultTTL),
9091
ActivityBump: time.Duration(tpl.ActivityBump),
9192
AutostopRequirement: agpl.TemplateAutostopRequirement{
93+
// #nosec G115 - Safe conversion as we've verified tpl.AutostopRequirementDaysOfWeek is <= 255
9294
DaysOfWeek: uint8(tpl.AutostopRequirementDaysOfWeek),
9395
Weeks: tpl.AutostopRequirementWeeks,
9496
},

enterprise/replicasync/replicasync.go

+3
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ func New(ctx context.Context, logger slog.Logger, db database.Store, ps pubsub.P
7373
RegionID: options.RegionID,
7474
RelayAddress: options.RelayAddress,
7575
Version: buildinfo.Version(),
76+
// #nosec G115 - Safe conversion for microseconds latency which is expected to be within int32 range
7677
DatabaseLatency: int32(databaseLatency.Microseconds()),
7778
Primary: true,
7879
})
@@ -322,6 +323,7 @@ func (m *Manager) syncReplicas(ctx context.Context) error {
322323
Hostname: m.self.Hostname,
323324
Version: m.self.Version,
324325
Error: replicaError,
326+
// #nosec G115 - Safe conversion for microseconds latency which is expected to be within int32 range
325327
DatabaseLatency: int32(databaseLatency.Microseconds()),
326328
Primary: m.self.Primary,
327329
})
@@ -340,6 +342,7 @@ func (m *Manager) syncReplicas(ctx context.Context) error {
340342
RegionID: m.self.RegionID,
341343
Hostname: m.self.Hostname,
342344
Version: m.self.Version,
345+
// #nosec G115 - Safe conversion for microseconds latency which is expected to be within int32 range
343346
DatabaseLatency: int32(databaseLatency.Microseconds()),
344347
Primary: m.self.Primary,
345348
})

provisionerd/runner/runner.go

+1
Original file line numberDiff line numberDiff line change
@@ -886,6 +886,7 @@ func (r *Runner) commitQuota(ctx context.Context, resources []*sdkproto.Resource
886886

887887
resp, err := r.quotaCommitter.CommitQuota(ctx, &proto.CommitQuotaRequest{
888888
JobId: r.job.JobId,
889+
// #nosec G115 - Safe conversion as cost is expected to be within int32 range for provisioning costs
889890
DailyCost: int32(cost),
890891
})
891892
if err != nil {

provisionersdk/archive.go

+2
Original file line numberDiff line numberDiff line change
@@ -171,10 +171,12 @@ func Untar(directory string, r io.Reader) error {
171171
}
172172
}
173173
case tar.TypeReg:
174+
// #nosec G115 - Safe conversion as tar header mode fits within uint32
174175
err := os.MkdirAll(filepath.Dir(target), os.FileMode(header.Mode)|os.ModeDir|100)
175176
if err != nil {
176177
return err
177178
}
179+
// #nosec G115 - Safe conversion as tar header mode fits within uint32
178180
file, err := os.OpenFile(target, os.O_CREATE|os.O_RDWR|os.O_TRUNC, os.FileMode(header.Mode))
179181
if err != nil {
180182
return err

pty/ssh_other.go

+1
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ func applyTerminalModesToFd(logger *log.Logger, fd uintptr, req ssh.Pty) error {
105105
continue
106106
}
107107
if _, ok := tios.CC[k]; ok {
108+
// #nosec G115 - Safe conversion for terminal control characters which are all in the uint8 range
108109
tios.CC[k] = uint8(v)
109110
continue
110111
}

scaletest/harness/strategies.go

+1
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,7 @@ func (cryptoRandSource) Int63() int64 {
153153
}
154154

155155
// mask off sign bit to ensure positive number
156+
// #nosec G115 - Safe conversion because we're masking the highest bit to ensure a positive int64
156157
return int64(binary.LittleEndian.Uint64(b[:]) & (1<<63 - 1))
157158
}
158159

testutil/port.go

+1
Original file line numberDiff line numberDiff line change
@@ -41,5 +41,6 @@ func RandomPortNoListen(*testing.T) uint16 {
4141
rndMu.Lock()
4242
x := rnd.Intn(n)
4343
rndMu.Unlock()
44+
// #nosec G115 - Safe conversion since min and x are explicitly within the uint16 range
4445
return uint16(min + x)
4546
}

0 commit comments

Comments
 (0)