Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

chore: fix gosec G115 linting issues for Go 1.24.1 update#17084

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Closed
sreya wants to merge2 commits intomainfromsreya/go-1-24-1-lint-fixes
Closed
Show file tree
Hide file tree
Changes fromall 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 deletioncli/clistat/disk.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,7 +19,7 @@ func (*Statter) Disk(p Prefix, path string) (*Result, error) {
return nil, err
}
var r Result
r.Total = ptr.To(float64(stat.Blocks * uint64(stat.Bsize)))
r.Total = ptr.To(float64(stat.Blocks * uint64(stat.Bsize))) // #nosec G115 -- int64 to uint64 is safe for filesystem stats (always positive)
r.Used = float64(stat.Blocks-stat.Bfree) * float64(stat.Bsize)
r.Unit = "B"
r.Prefix = p
Expand Down
7 changes: 4 additions & 3 deletionscli/cliutil/levenshtein/levenshtein.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,8 +32,9 @@ func Distance(a, b string, maxDist int) (int, error) {
if len(b) > 255 {
return 0, xerrors.Errorf("levenshtein: b must be less than 255 characters long")
}
m := uint8(len(a))
n := uint8(len(b))
// We've already checked that len(a) and len(b) are <= 255, so conversion is safe
m := uint8(len(a)) // #nosec G115 -- length is checked to be <= 255
n := uint8(len(b)) // #nosec G115 -- length is checked to be <= 255

// Special cases for empty strings
if m == 0 {
Expand DownExpand Up@@ -76,7 +77,7 @@ func Distance(a, b string, maxDist int) (int, error) {
d[i][j]+subCost, // substitution
)
// check maxDist on the diagonal
if maxDist > -1 && i == j && d[i+1][j+1] > uint8(maxDist) {
if maxDist > -1 && i == j &&maxDist <= 255 &&d[i+1][j+1] > uint8(maxDist) { // #nosec G115 -- we check maxDist <= 255
return int(d[i+1][j+1]), ErrMaxDist
}
}
Expand Down
4 changes: 3 additions & 1 deletioncoderd/database/lock.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,5 +18,7 @@ const (
func GenLockID(name string) int64 {
hash := fnv.New64()
_, _ = hash.Write([]byte(name))
return int64(hash.Sum64())
// For our locking purposes, it's acceptable to have potential overflow
// The important part is consistency of the lock ID for a given name
return int64(hash.Sum64()) // #nosec G115 -- potential overflow is acceptable for lock IDs
}
3 changes: 2 additions & 1 deletioncoderd/database/modelmethods.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -160,7 +160,8 @@ func (t Template) DeepCopy() Template {
func (t Template) AutostartAllowedDays() uint8 {
// Just flip the binary 0s to 1s and vice versa.
// There is an extra day with the 8th bit that needs to be zeroed.
return ^uint8(t.AutostartBlockDaysOfWeek) & 0b01111111
// The conversion is safe because AutostartBlockDaysOfWeek is enforced to use only the lower 7 bits
return ^uint8(t.AutostartBlockDaysOfWeek) & 0b01111111 // #nosec G115 -- int16 to uint8 is safe as we only use 7 bits
}

func (TemplateVersion) RBACObject(template Template) rbac.Object {
Expand Down
2 changes: 1 addition & 1 deletioncoderd/schedule/template.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -77,7 +77,7 @@ func (r TemplateAutostopRequirement) DaysMap() map[time.Weekday]bool {
func daysMap(daysOfWeek uint8) map[time.Weekday]bool {
days := make(map[time.Weekday]bool)
for i, day := range DaysOfWeek {
days[day] = daysOfWeek&(1<<uint(i)) != 0
days[day] = daysOfWeek&(1<<uint(i)) != 0 // #nosec G115 -- int to uint is safe for small i values (< 8)
}
return days
}
Expand Down
6 changes: 3 additions & 3 deletionscoderd/telemetry/telemetry.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -729,7 +729,7 @@ func ConvertWorkspaceBuild(build database.WorkspaceBuild) WorkspaceBuild {
WorkspaceID: build.WorkspaceID,
JobID: build.JobID,
TemplateVersionID: build.TemplateVersionID,
BuildNumber: uint32(build.BuildNumber),
BuildNumber: uint32(build.BuildNumber), // #nosec G115 -- int32 to uint32 is safe for build numbers
}
}

Expand DownExpand Up@@ -1035,9 +1035,9 @@ func ConvertTemplate(dbTemplate database.Template) Template {
FailureTTLMillis: time.Duration(dbTemplate.FailureTTL).Milliseconds(),
TimeTilDormantMillis: time.Duration(dbTemplate.TimeTilDormant).Milliseconds(),
TimeTilDormantAutoDeleteMillis: time.Duration(dbTemplate.TimeTilDormantAutoDelete).Milliseconds(),
AutostopRequirementDaysOfWeek: codersdk.BitmapToWeekdays(uint8(dbTemplate.AutostopRequirementDaysOfWeek)),
AutostopRequirementDaysOfWeek: codersdk.BitmapToWeekdays(uint8(dbTemplate.AutostopRequirementDaysOfWeek)), // #nosec G115 -- int16 to uint8 is safe since we only use 7 bits
AutostopRequirementWeeks: dbTemplate.AutostopRequirementWeeks,
AutostartAllowedDays: codersdk.BitmapToWeekdays(dbTemplate.AutostartAllowedDays()),
AutostartAllowedDays: codersdk.BitmapToWeekdays(dbTemplate.AutostartAllowedDays()), // #nosec G115 -- uses AutostartAllowedDays() which already ensures safe conversion
RequireActiveVersion: dbTemplate.RequireActiveVersion,
Deprecated: dbTemplate.Deprecated != "",
}
Expand Down
24 changes: 13 additions & 11 deletionscoderd/tracing/slog.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -33,7 +33,7 @@ func (SlogSink) LogEntry(ctx context.Context, e slog.SinkEntry) {
attribute.String("slog.message", e.Message),
attribute.String("slog.func", e.Func),
attribute.String("slog.file", e.File),
attribute.Int64("slog.line", int64(e.Line)),
attribute.Int64("slog.line", int64(e.Line)), // #nosec G115 -- int to int64 is safe
}
attributes = append(attributes, slogFieldsToAttributes(e.Fields)...)

Expand DownExpand Up@@ -61,36 +61,38 @@ func slogFieldsToAttributes(m slog.Map) []attribute.KeyValue {
case []float64:
value = attribute.Float64SliceValue(v)
case int:
value = attribute.Int64Value(int64(v))
value = attribute.Int64Value(int64(v))// #nosec G115 -- int to int64 is safe
case []int:
value = attribute.IntSliceValue(v)
case int8:
value = attribute.Int64Value(int64(v))
value = attribute.Int64Value(int64(v))// #nosec G115 -- int to int64 is safe
// no int8 slice method
case int16:
value = attribute.Int64Value(int64(v))
value = attribute.Int64Value(int64(v))// #nosec G115 -- int to int64 is safe
// no int16 slice method
case int32:
value = attribute.Int64Value(int64(v))
value = attribute.Int64Value(int64(v))// #nosec G115 -- int to int64 is safe
// no int32 slice method
case int64:
value = attribute.Int64Value(v)
case []int64:
value = attribute.Int64SliceValue(v)
case uint:
value = attribute.Int64Value(int64(v))
// If v is larger than math.MaxInt64, this will overflow, but this is acceptable for our tracing use case
value = attribute.Int64Value(int64(v)) // #nosec G115 -- acceptable overflow for tracing context
// no uint slice method
case uint8:
value = attribute.Int64Value(int64(v))
value = attribute.Int64Value(int64(v))// #nosec G115 -- int to int64 is safe
// no uint8 slice method
case uint16:
value = attribute.Int64Value(int64(v))
case uint16:// #nosec G115 -- int to int64 is safe
value = attribute.Int64Value(int64(v))// #nosec G115 -- int to int64 is safe
// no uint16 slice method
case uint32:
value = attribute.Int64Value(int64(v))
value = attribute.Int64Value(int64(v))// #nosec G115 -- int to int64 is safe
// no uint32 slice method
case uint64:
value = attribute.Int64Value(int64(v))
// If v is larger than math.MaxInt64, this will overflow, but this is acceptable for our tracing use case
value = attribute.Int64Value(int64(v)) // #nosec G115 -- acceptable overflow for tracing context
// no uint64 slice method
case string:
value = attribute.StringValue(v)
Expand Down
19 changes: 10 additions & 9 deletionscryptorand/strings.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,20 +44,20 @@ const (
//
//nolint:varnamelen
func unbiasedModulo32(v uint32, n int32) (int32, error) {
prod := uint64(v) * uint64(n)
low := uint32(prod)
if low < uint32(n) {
thresh := uint32(-n) % uint32(n)
prod := uint64(v) * uint64(n) // #nosec G115 -- uint32 to uint64 is always safe
low := uint32(prod) // #nosec G115 -- truncation is intentional for the algorithm
if low < uint32(n) { // #nosec G115 -- int32 to uint32 is safe for positive n (we require n > 0)
thresh := uint32(-n) % uint32(n) // #nosec G115 -- int32 to uint32 after negation is an acceptable pattern here
for low < thresh {
err := binary.Read(rand.Reader, binary.BigEndian, &v)
if err != nil {
return 0, err
}
prod = uint64(v) * uint64(n)
low = uint32(prod)
prod = uint64(v) * uint64(n) // #nosec G115 -- uint32 to uint64 is always safe
low = uint32(prod) // #nosec G115 -- truncation is intentional for the algorithm
}
}
return int32(prod >> 32), nil
return int32(prod >> 32), nil // #nosec G115 -- proper range is guaranteed by the algorithm
}

// StringCharset generates a random string using the provided charset and size.
Expand All@@ -84,12 +84,13 @@ func StringCharset(charSetStr string, size int) (string, error) {
buf.Grow(size)

for i := 0; i < size; i++ {
r := binary.BigEndian.Uint32(entropy[:4])
r := binary.BigEndian.Uint32(entropy[:4]) // #nosec G115 -- not a conversion, just reading bytes as uint32
entropy = entropy[4:]

// Charset length is limited by string size, so conversion to int32 is safe
ci, err := unbiasedModulo32(
r,
int32(len(charSet)),
int32(len(charSet)), // #nosec G115 -- int to int32 is safe for charset length
)
if err != nil {
return "", err
Expand Down
2 changes: 1 addition & 1 deletionprovisionerd/runner/runner.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -886,7 +886,7 @@ func (r *Runner) commitQuota(ctx context.Context, resources []*sdkproto.Resource

resp, err := r.quotaCommitter.CommitQuota(ctx, &proto.CommitQuotaRequest{
JobId: r.job.JobId,
DailyCost: int32(cost),
DailyCost: int32(cost), // #nosec G115 -- int to int32 is safe for cost values
})
if err != nil {
r.queueLog(ctx, &proto.Log{
Expand Down
5 changes: 3 additions & 2 deletionsprovisionersdk/archive.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -171,11 +171,12 @@ func Untar(directory string, r io.Reader) error {
}
}
case tar.TypeReg:
err := os.MkdirAll(filepath.Dir(target), os.FileMode(header.Mode)|os.ModeDir|100)
// header.Mode is int64, converting to os.FileMode (uint32) is safe for file permissions
err := os.MkdirAll(filepath.Dir(target), os.FileMode(header.Mode)|os.ModeDir|100) // #nosec G115 -- header.Mode contains file mode bits, safely convertible to uint32
if err != nil {
return err
}
file, err := os.OpenFile(target, os.O_CREATE|os.O_RDWR|os.O_TRUNC, os.FileMode(header.Mode))
file, err := os.OpenFile(target, os.O_CREATE|os.O_RDWR|os.O_TRUNC, os.FileMode(header.Mode)) // #nosec G115 -- header.Mode contains file mode bits, safely convertible to uint32
if err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletionpty/pty_linux.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
//go:build linux
//go:build linux

package pty

Expand Down
14 changes: 8 additions & 6 deletionspty/ssh_other.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -79,7 +79,7 @@ var terminalModeFlagNames = map[uint8]string{
// https://github.com/tailscale/tailscale/blob/main/ssh/tailssh/incubator.go
func applyTerminalModesToFd(logger *log.Logger, fd uintptr, req ssh.Pty) error {
// Get the current TTY configuration.
tios, err := termios.GTTY(int(fd))
tios, err := termios.GTTY(int(fd)) // #nosec G115 -- uintptr to int is safe for file descriptors
if err != nil {
return xerrors.Errorf("GTTY: %w", err)
}
Expand All@@ -90,11 +90,11 @@ func applyTerminalModesToFd(logger *log.Logger, fd uintptr, req ssh.Pty) error {

for c, v := range req.Modes {
if c == gossh.TTY_OP_ISPEED {
tios.Ispeed = int(v)
tios.Ispeed = int(v)// #nosec G115 -- uint32 to int is safe for TTY speeds
continue
}
if c == gossh.TTY_OP_OSPEED {
tios.Ospeed = int(v)
tios.Ospeed = int(v)// #nosec G115 -- uint32 to int is safe for TTY speeds
continue
}
k, ok := terminalModeFlagNames[c]
Expand All@@ -105,7 +105,9 @@ func applyTerminalModesToFd(logger *log.Logger, fd uintptr, req ssh.Pty) error {
continue
}
if _, ok := tios.CC[k]; ok {
tios.CC[k] = uint8(v)
if v <= 255 { // Ensure value fits in uint8
tios.CC[k] = uint8(v) // #nosec G115 -- value is checked to fit in uint8
}
continue
}
if _, ok := tios.Opts[k]; ok {
Expand All@@ -117,9 +119,9 @@ func applyTerminalModesToFd(logger *log.Logger, fd uintptr, req ssh.Pty) error {
logger.Printf("unsupported terminal mode: k=%s, c=%d, v=%d", k, c, v)
}
}

// #nosec G115 -- int to int64 is safe for file descriptors
// Save the new TTY configuration.
if _, err := tios.STTY(int(fd)); err != nil {
if _, err := tios.STTY(int(fd)); err != nil {// #nosec G115 -- uintptr to int is safe for file descriptors
return xerrors.Errorf("STTY: %w", err)
}

Expand Down
3 changes: 2 additions & 1 deletiontailnet/conn.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -132,7 +132,8 @@ type TelemetrySink interface {
// NodeID creates a Tailscale NodeID from the last 8 bytes of a UUID. It ensures
// the returned NodeID is always positive.
func NodeID(uid uuid.UUID) tailcfg.NodeID {
id := int64(binary.BigEndian.Uint64(uid[8:]))
// This may overflow, but we handle that by ensuring the result is positive below
id := int64(binary.BigEndian.Uint64(uid[8:])) // #nosec G115 -- potential overflow is handled below

// ensure id is positive
y := id >> 63
Expand Down
2 changes: 1 addition & 1 deletiontailnet/convert.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -31,7 +31,7 @@ func NodeToProto(n *Node) (*proto.Node, error) {
}
derpForcedWebsocket := make(map[int32]string)
for i, s := range n.DERPForcedWebsocket {
derpForcedWebsocket[int32(i)] = s
derpForcedWebsocket[int32(i)] = s // #nosec G115 -- int to int32 is safe for indices
}
addresses := make([]string, len(n.Addresses))
for i, prefix := range n.Addresses {
Expand Down
3 changes: 2 additions & 1 deletiontestutil/port.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,5 +41,6 @@ func RandomPortNoListen(*testing.T) uint16 {
rndMu.Lock()
x := rnd.Intn(n)
rndMu.Unlock()
return uint16(min + x)
// The calculation is safe as min(49152) + max possible x(11847) = 60999, which fits in uint16
return uint16(min + x) // #nosec G115 -- range is guaranteed to be within uint16
}
Loading

[8]ページ先頭

©2009-2025 Movatter.jp