Skip to content
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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: update gosec #2933

Merged
merged 5 commits into from
Oct 28, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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 deletion .github/workflows/sast-linters.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ jobs:
fetch-depth: 0

- name: Run Gosec Security Scanner
uses: zeta-chain/[email protected].0-zeta
uses: zeta-chain/[email protected].4-zeta2
with:
args: -exclude-generated -exclude-dir testutil ./...

Expand Down
1 change: 1 addition & 0 deletions cmd/zetaclientd/p2p_diagnostics.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ func RunDiagnostics(
startLogger.Info().Msgf("Successfully announced!")

// every 1min, print out the p2p diagnostic
// #nosec G115 interval is in range and not user controlled
ticker := time.NewTicker(time.Duration(cfg.P2PDiagnosticTicker) * time.Second)
round := 0
gartnera marked this conversation as resolved.
Show resolved Hide resolved

Expand Down
2 changes: 2 additions & 0 deletions e2e/e2etests/test_bitcoin_std_deposit.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,5 +59,7 @@ func TestBitcoinStdMemoDeposit(r *runner.E2ERunner, args []string) {
amountIncreased := new(big.Int).Sub(balanceAfter, balanceBefore)
amountSatoshis, err := bitcoin.GetSatoshis(amount)
require.NoError(r, err)
require.Positive(r, amountSatoshis)
// #nosec G115 always positive
gartnera marked this conversation as resolved.
Show resolved Hide resolved
require.Equal(r, uint64(amountSatoshis), amountIncreased.Uint64())
}
3 changes: 2 additions & 1 deletion e2e/runner/setup_solana.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ func (r *E2ERunner) SetupSolana(deployerPrivateKey string) {
inst.DataBytes, err = borsh.Serialize(solanacontracts.InitializeParams{
Discriminator: solanacontracts.DiscriminatorInitialize(),
TssAddress: r.TSSAddress,
ChainID: uint64(chains.SolanaLocalnet.ChainId),
// #nosec G115 chain id always positive
ChainID: uint64(chains.SolanaLocalnet.ChainId),
})
require.NoError(r, err)

Expand Down
1 change: 1 addition & 0 deletions pkg/contracts/ton/gateway.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ func (gw *Gateway) parseInbound(tx ton.Transaction) (*Transaction, error) {

var (
sender = *sourceID
// #nosec G115 always in range
opCode = Op(op)

gartnera marked this conversation as resolved.
Show resolved Hide resolved
content any
Expand Down
1 change: 1 addition & 0 deletions pkg/crypto/aes256_gcm.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ func DecryptAES256GCM(ciphertext []byte, password string) ([]byte, error) {
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]

// decrypt the ciphertext
// #nosec G407 false positive https://github.com/securego/gosec/issues/1211
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
Expand Down
1 change: 1 addition & 0 deletions pkg/memo/codec_compact.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ func (c *CodecCompact) packLength(length int) ([]byte, error) {
if length > math.MaxUint8 {
return nil, fmt.Errorf("data length %d exceeds %d bytes", length, math.MaxUint8)
}
// #nosec G115 range checked
data[0] = uint8(length)
case LenBytesLong:
if length > math.MaxUint16 {
Expand Down
7 changes: 4 additions & 3 deletions pkg/ticker/ticker.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,8 @@
t.logger.Info().Msgf("Ticker stopped")
}

// SecondsFromUint64 converts uint64 to time.Duration in seconds.
func SecondsFromUint64(d uint64) time.Duration {
return time.Duration(d) * time.Second
// DurationFromUint64Seconds converts uint64 of secodns to time.Duration.
gartnera marked this conversation as resolved.
Show resolved Hide resolved
func DurationFromUint64Seconds(seconds uint64) time.Duration {
// #nosec G115 seconds should be in range and is not user controlled
return time.Duration(seconds) * time.Second

Check warning on line 189 in pkg/ticker/ticker.go

View check run for this annotation

Codecov / codecov/patch

pkg/ticker/ticker.go#L187-L189

Added lines #L187 - L189 were not covered by tests
gartnera marked this conversation as resolved.
Show resolved Hide resolved
}
7 changes: 4 additions & 3 deletions precompiles/logs/logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,10 @@ type Argument struct {
// AddLog adds log to stateDB
func AddLog(ctx sdk.Context, precompileAddr common.Address, stateDB vm.StateDB, topics []common.Hash, data []byte) {
stateDB.AddLog(&types.Log{
Address: precompileAddr,
Topics: topics,
Data: data,
Address: precompileAddr,
Topics: topics,
Data: data,
// #nosec G115 block height always positive
BlockNumber: uint64(ctx.BlockHeight()),
})
}
Expand Down
5 changes: 3 additions & 2 deletions precompiles/staking/staking.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,9 @@ func (c *Contract) GetAllValidators(
validatorsRes[i] = Validator{
OperatorAddress: v.OperatorAddress,
ConsensusPubKey: v.ConsensusPubkey.String(),
BondStatus: uint8(v.Status),
Jailed: v.Jailed,
// #nosec G115 enum always in range
BondStatus: uint8(v.Status),
Jailed: v.Jailed,
}
}

Expand Down
4 changes: 3 additions & 1 deletion rpc/backend/node_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,10 @@ func (b *Backend) Syncing() (interface{}, error) {
}

return map[string]interface{}{
// #nosec G115 block height always positive
"startingBlock": hexutil.Uint64(status.SyncInfo.EarliestBlockHeight),
"currentBlock": hexutil.Uint64(status.SyncInfo.LatestBlockHeight),
// #nosec G115 block height always positive
"currentBlock": hexutil.Uint64(status.SyncInfo.LatestBlockHeight),
// "highestBlock": nil, // NA
// "pulledStates": nil, // NA
// "knownStates": nil, // NA
Expand Down
6 changes: 4 additions & 2 deletions rpc/backend/tx_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -304,8 +304,10 @@ func (b *Backend) GetTransactionReceipt(hash common.Hash) (map[string]interface{

// Inclusion information: These fields provide information about the inclusion of the
// transaction corresponding to this receipt.
"blockHash": common.BytesToHash(resBlock.Block.Header.Hash()).Hex(),
"blockNumber": hexutil.Uint64(res.Height),
"blockHash": common.BytesToHash(resBlock.Block.Header.Hash()).Hex(),
// #nosec G115 height always positive
"blockNumber": hexutil.Uint64(res.Height),
// #nosec G115 tx index always positive
"transactionIndex": hexutil.Uint64(res.EthTxIndex),

// sender and receiver (contract or EOA) addreses
Expand Down
8 changes: 8 additions & 0 deletions rpc/namespaces/ethereum/debug/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ func (a *API) BlockProfile(file string, nsec uint) error {
runtime.SetBlockProfileRate(1)
defer runtime.SetBlockProfileRate(0)

// #nosec G115 uint always in int64 range
gartnera marked this conversation as resolved.
Show resolved Hide resolved
time.Sleep(time.Duration(nsec) * time.Second)
return writeProfile("block", file, a.logger)
}
Expand All @@ -137,6 +138,7 @@ func (a *API) CpuProfile(file string, nsec uint) error { //nolint: golint, style
if err := a.StartCPUProfile(file); err != nil {
return err
}
// #nosec G115 uint always in int64 range
time.Sleep(time.Duration(nsec) * time.Second)
return a.StopCPUProfile()
}
Expand All @@ -156,6 +158,7 @@ func (a *API) GoTrace(file string, nsec uint) error {
if err := a.StartGoTrace(file); err != nil {
return err
}
// #nosec G115 uint always in int64 range
time.Sleep(time.Duration(nsec) * time.Second)
return a.StopGoTrace()
}
Expand Down Expand Up @@ -273,6 +276,7 @@ func (a *API) WriteMemProfile(file string) error {
func (a *API) MutexProfile(file string, nsec uint) error {
a.logger.Debug("debug_mutexProfile", "file", file, "nsec", nsec)
runtime.SetMutexProfileFraction(1)
// #nosec G115 uint always in int64 range
time.Sleep(time.Duration(nsec) * time.Second)
defer runtime.SetMutexProfileFraction(0)
return writeProfile("mutex", file, a.logger)
Expand Down Expand Up @@ -305,6 +309,7 @@ func (a *API) SetGCPercent(v int) int {

// GetHeaderRlp retrieves the RLP encoded for of a single header.
func (a *API) GetHeaderRlp(number uint64) (hexutil.Bytes, error) {
// #nosec G115 number always in int64 range
header, err := a.backend.HeaderByNumber(rpctypes.BlockNumber(number))
if err != nil {
return nil, err
Expand All @@ -315,6 +320,7 @@ func (a *API) GetHeaderRlp(number uint64) (hexutil.Bytes, error) {

// GetBlockRlp retrieves the RLP encoded for of a single block.
func (a *API) GetBlockRlp(number uint64) (hexutil.Bytes, error) {
// #nosec G115 number always in int64 range
block, err := a.backend.EthBlockByNumber(rpctypes.BlockNumber(number))
if err != nil {
return nil, err
Expand All @@ -325,6 +331,7 @@ func (a *API) GetBlockRlp(number uint64) (hexutil.Bytes, error) {

// PrintBlock retrieves a block and returns its pretty printed form.
func (a *API) PrintBlock(number uint64) (string, error) {
// #nosec G115 number always in int64 range
block, err := a.backend.EthBlockByNumber(rpctypes.BlockNumber(number))
if err != nil {
return "", err
Expand All @@ -335,6 +342,7 @@ func (a *API) PrintBlock(number uint64) (string, error) {

// SeedHash retrieves the seed hash of a block.
func (a *API) SeedHash(number uint64) (string, error) {
// #nosec G115 number always in int64 range
_, err := a.backend.HeaderByNumber(rpctypes.BlockNumber(number))
if err != nil {
return "", err
Expand Down
32 changes: 18 additions & 14 deletions rpc/types/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,20 +133,24 @@ func FormatBlock(
}

result := map[string]interface{}{
"number": hexutil.Uint64(header.Height),
"hash": hexutil.Bytes(header.Hash()),
"parentHash": common.BytesToHash(header.LastBlockID.Hash.Bytes()),
"nonce": ethtypes.BlockNonce{}, // PoW specific
"sha3Uncles": ethtypes.EmptyUncleHash, // No uncles in Tendermint
"logsBloom": bloom,
"stateRoot": hexutil.Bytes(header.AppHash),
"miner": validatorAddr,
"mixHash": common.Hash{},
"difficulty": (*hexutil.Big)(big.NewInt(0)),
"extraData": "0x",
"size": hexutil.Uint64(size),
"gasLimit": hexutil.Uint64(gasLimit), // Static gas limit
"gasUsed": (*hexutil.Big)(gasUsed),
// #nosec G115 block height always positive
"number": hexutil.Uint64(header.Height),
"hash": hexutil.Bytes(header.Hash()),
"parentHash": common.BytesToHash(header.LastBlockID.Hash.Bytes()),
"nonce": ethtypes.BlockNonce{}, // PoW specific
"sha3Uncles": ethtypes.EmptyUncleHash, // No uncles in Tendermint
"logsBloom": bloom,
"stateRoot": hexutil.Bytes(header.AppHash),
"miner": validatorAddr,
"mixHash": common.Hash{},
"difficulty": (*hexutil.Big)(big.NewInt(0)),
"extraData": "0x",
// #nosec G115 size always positive
"size": hexutil.Uint64(size),
// #nosec G115 gasLimit always positive
"gasLimit": hexutil.Uint64(gasLimit), // Static gas limit
"gasUsed": (*hexutil.Big)(gasUsed),
// #nosec G115 timestamp always positive
"timestamp": hexutil.Uint64(header.Time.Unix()),
"transactionsRoot": transactionsRoot,
"receiptsRoot": ethtypes.EmptyRootHash,
Expand Down
2 changes: 1 addition & 1 deletion scripts/gosec.sh
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
#!/usr/bin/env bash

docker run -it --rm -w /node -v "$(pwd):/node" ghcr.io/zeta-chain/gosec:2.21.0-zeta -exclude-generated -exclude-dir testutil ./...
docker run -it --rm -w /node -v "$(pwd):/node" ghcr.io/zeta-chain/gosec:2.21.4-zeta2 -exclude-generated -exclude-dir testutil ./...
1 change: 1 addition & 0 deletions zetaclient/chains/bitcoin/observer/inbound.go
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,7 @@ func (ob *Observer) CheckReceiptForBtcTxHash(ctx context.Context, txHash string,
}

// check confirmation
// #nosec G115 block height always positive
if !ob.IsBlockConfirmed(uint64(blockVb.Height)) {
return "", fmt.Errorf("block %d is not confirmed yet", blockVb.Height)
}
Expand Down
4 changes: 2 additions & 2 deletions zetaclient/chains/evm/observer/inbound.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
// TODO(revamp): move ticker function to a separate file
func (ob *Observer) WatchInbound(ctx context.Context) error {
sampledLogger := ob.Logger().Inbound.Sample(&zerolog.BasicSampler{N: 10})
interval := ticker.SecondsFromUint64(ob.ChainParams().InboundTicker)
interval := ticker.DurationFromUint64Seconds(ob.ChainParams().InboundTicker)

Check warning on line 41 in zetaclient/chains/evm/observer/inbound.go

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/evm/observer/inbound.go#L41

Added line #L41 was not covered by tests
task := func(ctx context.Context, t *ticker.Ticker) error {
return ob.watchInboundOnce(ctx, t, sampledLogger)
}
Expand Down Expand Up @@ -70,7 +70,7 @@
ob.Logger().Inbound.Err(err).Msg("WatchInbound: observeInbound error")
}

newInterval := ticker.SecondsFromUint64(ob.ChainParams().InboundTicker)
newInterval := ticker.DurationFromUint64Seconds(ob.ChainParams().InboundTicker)

Check warning on line 73 in zetaclient/chains/evm/observer/inbound.go

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/evm/observer/inbound.go#L73

Added line #L73 was not covered by tests
t.SetInterval(newInterval)

return nil
Expand Down
1 change: 1 addition & 0 deletions zetaclient/chains/evm/observer/outbound.go
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,7 @@ func (ob *Observer) FilterTSSOutboundInBlock(ctx context.Context, blockNumber ui
for i := range block.Transactions {
tx := block.Transactions[i]
if ethcommon.HexToAddress(tx.From) == ob.TSS().EVMAddress() {
// #nosec G115 nonce always positive
gartnera marked this conversation as resolved.
Show resolved Hide resolved
nonce := uint64(tx.Nonce)
if !ob.IsTxConfirmed(nonce) {
if receipt, txx, ok := ob.checkConfirmedTx(ctx, tx.Hash, nonce); ok {
Expand Down
4 changes: 2 additions & 2 deletions zetaclient/chains/ton/observer/inbound.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@

var (
chainID = ob.Chain().ChainId
initialInterval = ticker.SecondsFromUint64(ob.ChainParams().InboundTicker)
initialInterval = ticker.DurationFromUint64Seconds(ob.ChainParams().InboundTicker)

Check warning on line 34 in zetaclient/chains/ton/observer/inbound.go

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/ton/observer/inbound.go#L34

Added line #L34 was not covered by tests
sampledLogger = ob.Logger().Inbound.Sample(&zerolog.BasicSampler{N: 10})
)

Expand All @@ -47,7 +47,7 @@
ob.Logger().Inbound.Err(err).Msg("WatchInbound: observeInbound error")
}

newInterval := ticker.SecondsFromUint64(ob.ChainParams().InboundTicker)
newInterval := ticker.DurationFromUint64Seconds(ob.ChainParams().InboundTicker)

Check warning on line 50 in zetaclient/chains/ton/observer/inbound.go

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/ton/observer/inbound.go#L50

Added line #L50 was not covered by tests
t.SetInterval(newInterval)

return nil
Expand Down
2 changes: 1 addition & 1 deletion zetaclient/orchestrator/orchestrator.go
Original file line number Diff line number Diff line change
Expand Up @@ -618,7 +618,7 @@ func (oc *Orchestrator) ScheduleCctxSolana(
oc.logger.Error().Msgf("ScheduleCctxSolana: chain observer is not a solana observer")
return
}
// #nosec G701 positive
// #nosec G115 G701 positive
gartnera marked this conversation as resolved.
Show resolved Hide resolved
interval := uint64(observer.ChainParams().OutboundScheduleInterval)

// schedule keysign for each pending cctx
Expand Down
4 changes: 3 additions & 1 deletion zetaclient/types/dynamic_ticker.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
return &DynamicTicker{
name: name,
interval: interval,
impl: time.NewTicker(time.Duration(interval) * time.Second),
// #nosec G115 interval is in range and not user controlled
impl: time.NewTicker(time.Duration(interval) * time.Second),
gartnera marked this conversation as resolved.
Show resolved Hide resolved
}, nil
}

Expand All @@ -38,6 +39,7 @@
t.impl.Stop()
oldInterval := t.interval
t.interval = newInterval
// #nosec G115 interval is in range and not user controlled

Check warning on line 42 in zetaclient/types/dynamic_ticker.go

View check run for this annotation

Codecov / codecov/patch

zetaclient/types/dynamic_ticker.go#L42

Added line #L42 was not covered by tests
gartnera marked this conversation as resolved.
Show resolved Hide resolved
t.impl = time.NewTicker(time.Duration(t.interval) * time.Second)
logger.Info().Msgf("%s ticker interval changed from %d to %d", t.name, oldInterval, newInterval)
}
Expand Down
1 change: 1 addition & 0 deletions zetaclient/zetacore/client_worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
}()

var (
// #nosec G115 interval is in range and not user controlled

Check warning on line 24 in zetaclient/zetacore/client_worker.go

View check run for this annotation

Codecov / codecov/patch

zetaclient/zetacore/client_worker.go#L24

Added line #L24 was not covered by tests
updateEvery = time.Duration(app.Config().ConfigUpdateTicker) * time.Second
ticker = time.NewTicker(updateEvery)
logger = c.logger.Sample(logSampler)
Expand Down
Loading