Skip to content

Commit 8e74ce9

Browse files
(gosec) Apply G115 fixes to internal/integration/unified package
Address gosec G115 integer overflow warnings in unified test runner: - Add SafeConvertNumeric for test parameter conversions - Use nolint for int32 to uint64 conversions (always safe) - Add SafeConvertNumeric for event count and option conversions
1 parent a5725e7 commit 8e74ce9

File tree

6 files changed

+69
-23
lines changed

6 files changed

+69
-23
lines changed

internal/integration/unified/client_entity.go

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"go.mongodb.org/mongo-driver/v2/internal/integration/mtest"
2121
"go.mongodb.org/mongo-driver/v2/internal/integtest"
2222
"go.mongodb.org/mongo-driver/v2/internal/logger"
23+
"go.mongodb.org/mongo-driver/v2/internal/mathutil"
2324
"go.mongodb.org/mongo-driver/v2/mongo"
2425
"go.mongodb.org/mongo-driver/v2/mongo/options"
2526
"go.mongodb.org/mongo-driver/v2/mongo/readconcern"
@@ -91,7 +92,12 @@ func awaitMinimumPoolSize(ctx context.Context, entity *clientEntity, minPoolSize
9192
case <-awaitCtx.Done():
9293
return fmt.Errorf("timed out waiting for client to reach minPoolSize")
9394
case <-ticker.C:
94-
if uint64(entity.eventsCount[connectionReadyEvent]) >= minPoolSize {
95+
creCount, err := mathutil.SafeConvertNumeric[uint64](int(entity.eventsCount[connectionReadyEvent]))
96+
if err != nil {
97+
return fmt.Errorf("connectionReadyEvent count %d exceeds maximum uint64 size: %w", entity.eventsCount[connectionReadyEvent], err)
98+
}
99+
100+
if creCount >= minPoolSize {
95101
return nil
96102
}
97103
}
@@ -261,7 +267,7 @@ func (c *clientEntity) disconnect(ctx context.Context) error {
261267
return nil
262268
}
263269

264-
if err := c.Client.Disconnect(ctx); err != nil {
270+
if err := c.Disconnect(ctx); err != nil {
265271
return err
266272
}
267273

@@ -665,11 +671,26 @@ func setClientOptionsFromURIOptions(clientOpts *options.ClientOptions, uriOpts b
665671
case "maxidletimems":
666672
clientOpts.SetMaxConnIdleTime(time.Duration(value.(int32)) * time.Millisecond)
667673
case "minpoolsize":
668-
clientOpts.SetMinPoolSize(uint64(value.(int32)))
674+
minPoolSize, err := mathutil.SafeConvertNumeric[uint64](int(value.(int32)))
675+
if err != nil {
676+
return fmt.Errorf("minPoolSize value %d is out of range: %w", value.(int32), err)
677+
}
678+
679+
clientOpts.SetMinPoolSize(minPoolSize)
669680
case "maxpoolsize":
670-
clientOpts.SetMaxPoolSize(uint64(value.(int32)))
681+
maxPoolSize, err := mathutil.SafeConvertNumeric[uint64](int(value.(int32)))
682+
if err != nil {
683+
return fmt.Errorf("maxPoolSize value %d is out of range: %w", value.(int32), err)
684+
}
685+
686+
clientOpts.SetMaxPoolSize(maxPoolSize)
671687
case "maxconnecting":
672-
clientOpts.SetMaxConnecting(uint64(value.(int32)))
688+
maxConnecting, err := mathutil.SafeConvertNumeric[uint64](int(value.(int32)))
689+
if err != nil {
690+
return fmt.Errorf("maxConnecting value %d is out of range: %w", value.(int32), err)
691+
}
692+
693+
clientOpts.SetMaxConnecting(maxConnecting)
673694
case "readconcernlevel":
674695
clientOpts.SetReadConcern(&readconcern.ReadConcern{Level: value.(string)})
675696
case "retryreads":

internal/integration/unified/collection_operation_execution.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import (
1515

1616
"go.mongodb.org/mongo-driver/v2/bson"
1717
"go.mongodb.org/mongo-driver/v2/internal/bsonutil"
18+
"go.mongodb.org/mongo-driver/v2/internal/mathutil"
1819
"go.mongodb.org/mongo-driver/v2/internal/mongoutil"
1920
"go.mongodb.org/mongo-driver/v2/mongo"
2021
"go.mongodb.org/mongo-driver/v2/mongo/options"
@@ -1144,8 +1145,12 @@ func executeInsertMany(ctx context.Context, operation *operation) (*operationRes
11441145
// We return InsertedIDs as []any but the CRUD spec documents it as a map[int64]any, so
11451146
// comparisons will fail if we include it in the result document. This is marked as an optional field and is
11461147
// always surrounded in an $$unsetOrMatches assertion, so we leave it out of the document.
1148+
insertedCount, err := mathutil.SafeConvertNumeric[int32](len(res.InsertedIDs))
1149+
if err != nil {
1150+
return nil, err
1151+
}
11471152
raw = bsoncore.NewDocumentBuilder().
1148-
AppendInt32("insertedCount", int32(len(res.InsertedIDs))).
1153+
AppendInt32("insertedCount", insertedCount).
11491154
AppendInt32("deletedCount", 0).
11501155
AppendInt32("matchedCount", 0).
11511156
AppendInt32("modifiedCount", 0).

internal/integration/unified/entity.go

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,14 @@ import (
1818
"time"
1919

2020
"go.mongodb.org/mongo-driver/v2/bson"
21+
"go.mongodb.org/mongo-driver/v2/internal/mathutil"
2122
"go.mongodb.org/mongo-driver/v2/mongo"
2223
"go.mongodb.org/mongo-driver/v2/mongo/options"
2324
"go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore"
2425
)
2526

26-
var (
27-
// ErrEntityMapOpen is returned when a slice entity is accessed while the EntityMap is open
28-
ErrEntityMapOpen = errors.New("slices cannot be accessed while EntityMap is open")
29-
)
27+
// ErrEntityMapOpen is returned when a slice entity is accessed while the EntityMap is open
28+
var ErrEntityMapOpen = errors.New("slices cannot be accessed while EntityMap is open")
3029

3130
var (
3231
tlsCAFile = os.Getenv("CSFLE_TLS_CA_FILE")
@@ -96,17 +95,23 @@ func (eo *entityOptions) setHeartbeatFrequencyMS(freq time.Duration) {
9695
}
9796

9897
if _, ok := eo.URIOptions["heartbeatFrequencyMS"]; !ok {
98+
freqMS, err := mathutil.SafeConvertNumeric[int32](int64(freq.Milliseconds()))
99+
if err != nil {
100+
panic(fmt.Sprintf("heartbeatFrequencyMS value %d overflows int32", freq.Milliseconds()))
101+
}
102+
99103
// The UST values for heartbeatFrequencyMS are given as int32,
100104
// so we need to cast the frequency as int32 before setting it
101105
// on the URIOptions map.
102-
eo.URIOptions["heartbeatFrequencyMS"] = int32(freq.Milliseconds())
106+
eo.URIOptions["heartbeatFrequencyMS"] = freqMS
103107
}
104108
}
105109

106110
// newCollectionEntityOptions constructs an entity options object for a
107111
// collection.
108112
func newCollectionEntityOptions(id string, databaseID string, collectionName string,
109-
opts *dbOrCollectionOptions) *entityOptions {
113+
opts *dbOrCollectionOptions,
114+
) *entityOptions {
110115
options := &entityOptions{
111116
ID: id,
112117
DatabaseID: databaseID,
@@ -598,7 +603,6 @@ func getKmsCredential(kmsDocument bson.Raw, credentialName string, envVar string
598603
return "", fmt.Errorf("unable to get environment value for %v. Please set the CSFLE environment variable: %v", credentialName, envVar)
599604
}
600605
return os.Getenv(envVar), nil
601-
602606
}
603607

604608
func (em *EntityMap) addClientEncryptionEntity(entityOptions *entityOptions) error {

internal/integration/unified/error.go

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import (
1313
"strings"
1414

1515
"go.mongodb.org/mongo-driver/v2/bson"
16+
"go.mongodb.org/mongo-driver/v2/internal/mathutil"
1617
"go.mongodb.org/mongo-driver/v2/mongo"
1718
)
1819

@@ -199,28 +200,38 @@ func extractErrorDetails(err error) (errorDetails, bool) {
199200
details.raw = converted.Raw
200201
case mongo.WriteException:
201202
if converted.WriteConcernError != nil {
202-
details.codes = append(details.codes, int32(converted.WriteConcernError.Code))
203+
if code, err := mathutil.SafeConvertNumeric[int32](converted.WriteConcernError.Code); err == nil {
204+
details.codes = append(details.codes, code)
205+
}
203206
details.codeNames = append(details.codeNames, converted.WriteConcernError.Name)
204207
}
205208
for _, we := range converted.WriteErrors {
206-
details.codes = append(details.codes, int32(we.Code))
209+
if code, err := mathutil.SafeConvertNumeric[int32](we.Code); err == nil {
210+
details.codes = append(details.codes, code)
211+
}
207212
}
208213
details.labels = converted.Labels
209214
details.raw = converted.Raw
210215
case mongo.BulkWriteException:
211216
if converted.WriteConcernError != nil {
212-
details.codes = append(details.codes, int32(converted.WriteConcernError.Code))
217+
if code, err := mathutil.SafeConvertNumeric[int32](converted.WriteConcernError.Code); err == nil {
218+
details.codes = append(details.codes, code)
219+
}
213220
details.codeNames = append(details.codeNames, converted.WriteConcernError.Name)
214221
}
215222
for _, we := range converted.WriteErrors {
216-
details.codes = append(details.codes, int32(we.Code))
223+
if code, err := mathutil.SafeConvertNumeric[int32](we.Code); err == nil {
224+
details.codes = append(details.codes, code)
225+
}
217226
details.raw = we.Raw
218227
}
219228
details.labels = converted.Labels
220229
case mongo.ClientBulkWriteException:
221230
if converted.WriteError != nil {
222231
details.raw = converted.WriteError.Raw
223-
details.codes = append(details.codes, int32(converted.WriteError.Code))
232+
if code, err := mathutil.SafeConvertNumeric[int32](converted.WriteError.Code); err == nil {
233+
details.codes = append(details.codes, code)
234+
}
224235
}
225236
default:
226237
return errorDetails{}, false

internal/integration/unified/event_verification.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -429,22 +429,22 @@ func stringifyEventsForClient(client *clientEntity) string {
429429

430430
str.WriteString("\n\nStarted Events\n\n")
431431
for _, evt := range client.startedEvents() {
432-
str.WriteString(fmt.Sprintf("[%s] %s\n", evt.ConnectionID, evt.Command))
432+
fmt.Fprintf(str, "[%s] %s\n", evt.ConnectionID, evt.Command)
433433
}
434434

435435
str.WriteString("\nSucceeded Events\n\n")
436436
for _, evt := range client.succeededEvents() {
437-
str.WriteString(fmt.Sprintf("[%s] CommandName: %s, Reply: %s\n", evt.ConnectionID, evt.CommandName, evt.Reply))
437+
fmt.Fprintf(str, "[%s] CommandName: %s, Reply: %s\n", evt.ConnectionID, evt.CommandName, evt.Reply)
438438
}
439439

440440
str.WriteString("\nFailed Events\n\n")
441441
for _, evt := range client.failedEvents() {
442-
str.WriteString(fmt.Sprintf("[%s] CommandName: %s, Failure: %s\n", evt.ConnectionID, evt.CommandName, evt.Failure))
442+
fmt.Fprintf(str, "[%s] CommandName: %s, Failure: %s\n", evt.ConnectionID, evt.CommandName, evt.Failure)
443443
}
444444

445445
str.WriteString("\nPool Events\n\n")
446446
for _, evt := range client.poolEvents() {
447-
str.WriteString(fmt.Sprintf("[%s] Event Type: %q\n", evt.Address, evt.Type))
447+
fmt.Fprintf(str, "[%s] Event Type: %q\n", evt.Address, evt.Type)
448448
}
449449

450450
return str.String()

internal/integration/unified/testrunner_operation.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import (
1414

1515
"go.mongodb.org/mongo-driver/v2/bson"
1616
"go.mongodb.org/mongo-driver/v2/internal/integration/mtest"
17+
"go.mongodb.org/mongo-driver/v2/internal/mathutil"
1718
"go.mongodb.org/mongo-driver/v2/mongo"
1819
"go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore"
1920
"go.mongodb.org/mongo-driver/v2/x/mongo/driver/session"
@@ -205,7 +206,11 @@ func executeTestRunnerOperation(ctx context.Context, op *operation, loopDone <-c
205206
return err
206207
}
207208

208-
expected := int32(lookupInteger(args, "connections"))
209+
expected, err := mathutil.SafeConvertNumeric[int32](lookupInteger(args, "connections"))
210+
if err != nil {
211+
return fmt.Errorf("'connections' argument is out of int32 range: %w", err)
212+
}
213+
209214
actual := client.numberConnectionsCheckedOut()
210215
if expected != actual {
211216
return fmt.Errorf("expected %d connections to be checked out, got %d", expected, actual)

0 commit comments

Comments
 (0)