Skip to content

Commit dbd318b

Browse files
authored
PBM-1307: Disallow WriteConcern for unacknowledged write operation (#941)
1 parent 744857d commit dbd318b

File tree

1 file changed

+28
-2
lines changed

1 file changed

+28
-2
lines changed

pbm/connect/connect.go

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,14 +54,25 @@ func ReadConcern(readConcern *readconcern.ReadConcern) MongoOption {
5454
// If the option is not specified the default is: [writeconcern.Majority].
5555
func WriteConcern(writeConcern *writeconcern.WriteConcern) MongoOption {
5656
return func(opts *options.ClientOptions) error {
57-
if writeConcern == nil {
58-
return errors.New("WriteConcern not specified")
57+
if err := validateWriteConcern(writeConcern); err != nil {
58+
return err
5959
}
60+
6061
opts.SetWriteConcern(writeConcern)
6162
return nil
6263
}
6364
}
6465

66+
func validateWriteConcern(writeConcern *writeconcern.WriteConcern) error {
67+
if writeConcern == nil {
68+
return errors.New("WriteConcern not specified")
69+
}
70+
if w, ok := writeConcern.W.(int); ok && w == 0 {
71+
return errors.New("WriteConcern without acknowledgment is not allowed (w: 0)")
72+
}
73+
return nil
74+
}
75+
6576
// NoRS option removes replica set name setting
6677
func NoRS() MongoOption {
6778
return func(opts *options.ClientOptions) error {
@@ -102,6 +113,9 @@ func MongoConnectWithOpts(ctx context.Context,
102113

103114
// apply and override using end-user options from conn string
104115
mopts.ApplyURI(uri)
116+
if err := validateConnStringOpts(mopts); err != nil {
117+
return nil, nil, errors.Wrap(err, "invalid connection string option")
118+
}
105119

106120
// override with explicit options from the code
107121
for _, opt := range mongoOptions {
@@ -125,6 +139,18 @@ func MongoConnectWithOpts(ctx context.Context,
125139
return conn, mopts, nil
126140
}
127141

142+
func validateConnStringOpts(opts *options.ClientOptions) error {
143+
var err error
144+
if err = opts.Validate(); err != nil {
145+
return err
146+
}
147+
if err = validateWriteConcern(opts.WriteConcern); err != nil {
148+
return err
149+
}
150+
151+
return nil
152+
}
153+
128154
func MongoConnect(
129155
ctx context.Context,
130156
uri string,

0 commit comments

Comments
 (0)