Skip to content

Commit 87eebe6

Browse files
committed
feat(bcdc): enhance FromJSON method to validate permission values and handle out-of-range errors
1 parent dd61963 commit 87eebe6

File tree

1 file changed

+30
-10
lines changed

1 file changed

+30
-10
lines changed

binary-codec/types/permission_value.go

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"encoding/binary"
55
"encoding/json"
66
"errors"
7+
"math"
78

89
"github.com/Peersyst/xrpl-go/binary-codec/definitions"
910
"github.com/Peersyst/xrpl-go/binary-codec/types/interfaces"
@@ -12,6 +13,7 @@ import (
1213
var (
1314
ErrInvalidJSONNumber = errors.New("invalid json.Number")
1415
ErrUnsupportedPermissionType = errors.New("unsupported JSON type for PermissionValue")
16+
ErrPermissionValueOutOfRange = errors.New("permission value out of uint32 range")
1517
)
1618

1719
// PermissionValue represents a 32-bit unsigned integer permission value.
@@ -29,31 +31,48 @@ func (p *PermissionValue) FromJSON(value any) ([]byte, error) {
2931
value = pv
3032
}
3133

32-
var intValue uint32
33-
34+
var ui64 uint64
3435
switch v := value.(type) {
3536
case int:
36-
intValue = uint32(v)
37+
if v < 0 {
38+
return nil, ErrPermissionValueOutOfRange
39+
}
40+
ui64 = uint64(v)
3741
case int32:
38-
intValue = uint32(v)
42+
if v < 0 {
43+
return nil, ErrPermissionValueOutOfRange
44+
}
45+
ui64 = uint64(v)
3946
case int64:
40-
intValue = uint32(v)
47+
if v < 0 {
48+
return nil, ErrPermissionValueOutOfRange
49+
}
50+
ui64 = uint64(v)
4151
case uint32:
42-
intValue = v
52+
ui64 = uint64(v)
4353
case float64:
44-
intValue = uint32(v)
54+
if v < 0 || v > float64(math.MaxUint32) {
55+
return nil, ErrPermissionValueOutOfRange
56+
}
57+
ui64 = uint64(v)
4558
case json.Number:
4659
num, err := v.Int64()
47-
if err != nil {
60+
if err != nil || num < 0 {
4861
return nil, ErrInvalidJSONNumber
4962
}
50-
intValue = uint32(num)
63+
ui64 = uint64(num)
5164
default:
5265
return nil, ErrUnsupportedPermissionType
5366
}
5467

68+
if ui64 > math.MaxUint32 {
69+
return nil, ErrPermissionValueOutOfRange
70+
}
71+
72+
// Now safe to cast
73+
ui32 := uint32(ui64)
5574
buf := make([]byte, 4)
56-
binary.BigEndian.PutUint32(buf, intValue)
75+
binary.BigEndian.PutUint32(buf, ui32)
5776
return buf, nil
5877
}
5978

@@ -68,6 +87,7 @@ func (p *PermissionValue) ToJSON(parser interfaces.BinaryParser, _ ...int) (any,
6887

6988
permissionValue := binary.BigEndian.Uint32(b)
7089

90+
// #nosec G115
7191
if name, err := definitions.Get().GetDelegatablePermissionNameByValue(int32(permissionValue)); err == nil {
7292
return name, nil
7393
}

0 commit comments

Comments
 (0)