Skip to content

Commit 6a2bffd

Browse files
pinosualpe
andauthored
Add grant system tests (#1626)
* Add grant system tests * Add unpermissioned chain test case * Fix tests * Update cli and fix feedbacks * Revisit CLI and system tests (#1627) * Restructure CLI; fix system test * Review feedback --------- Co-authored-by: Alexander Peters <[email protected]>
1 parent e0bfaa5 commit 6a2bffd

File tree

6 files changed

+119
-20
lines changed

6 files changed

+119
-20
lines changed

tests/system/cli.go

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package system
22

33
import (
44
"fmt"
5+
"io"
56
"os/exec"
67
"path/filepath"
78
"strconv"
@@ -196,6 +197,10 @@ func (c WasmdCli) CustomQuery(args ...string) string {
196197

197198
// execute shell command
198199
func (c WasmdCli) run(args []string) (output string, ok bool) {
200+
return c.runWithInput(args, nil)
201+
}
202+
203+
func (c WasmdCli) runWithInput(args []string, input io.Reader) (output string, ok bool) {
199204
if c.Debug {
200205
c.t.Logf("+++ running `%s %s`", c.execBinary, strings.Join(args, " "))
201206
}
@@ -207,6 +212,7 @@ func (c WasmdCli) run(args []string) (output string, ok bool) {
207212
}()
208213
cmd := exec.Command(locateExecutable("wasmd"), args...) //nolint:gosec
209214
cmd.Dir = workDir
215+
cmd.Stdin = input
210216
return cmd.CombinedOutput()
211217
}()
212218
ok = c.assertErrorFn(c.t, gotErr, string(gotOut))
@@ -256,13 +262,22 @@ func (c WasmdCli) WasmExecute(contractAddr, msg, from string, args ...string) st
256262

257263
// AddKey add key to default keyring. Returns address
258264
func (c WasmdCli) AddKey(name string) string {
259-
cmd := c.withKeyringFlags("keys", "add", name, "--no-backup")
265+
cmd := c.withKeyringFlags("keys", "add", name) //, "--no-backup")
260266
out, _ := c.run(cmd)
261267
addr := gjson.Get(out, "address").String()
262268
require.NotEmpty(c.t, addr, "got %q", out)
263269
return addr
264270
}
265271

272+
// AddKeyFromSeed recovers the key from given seed and add it to default keyring. Returns address
273+
func (c WasmdCli) AddKeyFromSeed(name, mnemoic string) string {
274+
cmd := c.withKeyringFlags("keys", "add", name, "--recover")
275+
out, _ := c.runWithInput(cmd, strings.NewReader(mnemoic))
276+
addr := gjson.Get(out, "address").String()
277+
require.NotEmpty(c.t, addr, "got %q", out)
278+
return addr
279+
}
280+
266281
// GetKeyAddr returns address
267282
func (c WasmdCli) GetKeyAddr(name string) string {
268283
cmd := c.withKeyringFlags("keys", "show", name, "-a")

tests/system/fraud_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import (
1313
)
1414

1515
func TestRecursiveMsgsExternalTrigger(t *testing.T) {
16+
sut.ResetChain(t)
1617
const maxBlockGas = 2_000_000
1718
sut.ModifyGenesisJSON(t, SetConsensusMaxGas(t, maxBlockGas))
1819
sut.StartChain(t)

tests/system/genesis_io.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,15 @@ func GetGenesisBalance(rawGenesis []byte, addr string) sdk.Coins {
3131
}
3232
return r
3333
}
34+
35+
// SetCodeUploadPermission sets the code upload permissions
36+
func SetCodeUploadPermission(t *testing.T, permission string, addresses ...string) GenesisMutator {
37+
return func(genesis []byte) []byte {
38+
t.Helper()
39+
state, err := sjson.Set(string(genesis), "app_state.wasm.params.code_upload_access.permission", permission)
40+
require.NoError(t, err)
41+
state, err = sjson.Set(state, "app_state.wasm.params.code_upload_access.addresses", addresses)
42+
require.NoError(t, err)
43+
return []byte(state)
44+
}
45+
}

tests/system/permissioned_test.go

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
//go:build system_test
2+
3+
package system
4+
5+
import (
6+
"os"
7+
"path/filepath"
8+
"testing"
9+
10+
"github.com/stretchr/testify/require"
11+
"github.com/tidwall/gjson"
12+
)
13+
14+
func TestGrantStoreCodePermissionedChain(t *testing.T) {
15+
cli := NewWasmdCLI(t, sut, verbose)
16+
// set params to restrict chain
17+
const chainAuthorityAddress = "wasm1pvuujjdk0xt043ga0j9nrfh5u8pzj4rpplyqkm"
18+
sut.ModifyGenesisJSON(t, SetCodeUploadPermission(t, "AnyOfAddresses", chainAuthorityAddress))
19+
20+
recoveredAddress := cli.AddKeyFromSeed("chain_authority", "aisle ship absurd wedding arch admit fringe foam cluster tide trim aisle salad shiver tackle palm glance wrist valley hamster couch crystal frozen chronic")
21+
require.Equal(t, chainAuthorityAddress, recoveredAddress)
22+
devAccount := cli.AddKey("dev_account")
23+
24+
sut.ModifyGenesisCLI(t,
25+
[]string{"genesis", "add-genesis-account", chainAuthorityAddress, "100000000stake"},
26+
)
27+
sut.ModifyGenesisCLI(t,
28+
[]string{"genesis", "add-genesis-account", devAccount, "100000000stake"},
29+
)
30+
31+
sut.StartChain(t)
32+
33+
// query params
34+
rsp := cli.CustomQuery("q", "wasm", "params")
35+
permission := gjson.Get(rsp, "code_upload_access.permission").String()
36+
addrRes := gjson.Get(rsp, "code_upload_access.addresses").Array()
37+
require.Equal(t, 1, len(addrRes))
38+
39+
require.Equal(t, permission, "AnyOfAddresses")
40+
require.Equal(t, chainAuthorityAddress, addrRes[0].Str)
41+
42+
// chain_authority grant upload permission to dev_account
43+
rsp = cli.CustomCommand("tx", "wasm", "grant", "store-code", devAccount, "*:*", "--from="+chainAuthorityAddress)
44+
RequireTxSuccess(t, rsp)
45+
46+
// dev_account store code fails as the address is not in the code-upload accept-list
47+
rsp = cli.CustomCommand("tx", "wasm", "store", "./testdata/hackatom.wasm.gzip", "--from="+devAccount, "--gas=1500000", "--fees=2stake")
48+
RequireTxFailure(t, rsp)
49+
50+
// create tx should work for addresses in the accept-list
51+
args := cli.withTXFlags("tx", "wasm", "store", "./testdata/hackatom.wasm.gzip", "--from="+chainAuthorityAddress, "--generate-only")
52+
tx, ok := cli.run(args)
53+
require.True(t, ok)
54+
55+
pathToTx := filepath.Join(t.TempDir(), "tx.json")
56+
err := os.WriteFile(pathToTx, []byte(tx), os.FileMode(0o744))
57+
require.NoError(t, err)
58+
59+
// store code via authz execution uses the given grant and should succeed
60+
rsp = cli.CustomCommand("tx", "authz", "exec", pathToTx, "--from="+devAccount, "--gas=1500000", "--fees=2stake")
61+
RequireTxSuccess(t, rsp)
62+
}

x/wasm/client/cli/tx.go

Lines changed: 26 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,7 @@ func GetTxCmd() *cobra.Command {
6767
MigrateContractCmd(),
6868
UpdateContractAdminCmd(),
6969
ClearContractAdminCmd(),
70-
GrantAuthorizationCmd(),
71-
GrantStoreCodeAuthorizationCmd(),
70+
GrantCmd(),
7271
UpdateInstantiateConfigCmd(),
7372
SubmitProposalCmd(),
7473
)
@@ -415,17 +414,31 @@ func parseExecuteArgs(contractAddr, execMsg string, sender sdk.AccAddress, flags
415414
}, nil
416415
}
417416

417+
func GrantCmd() *cobra.Command {
418+
txCmd := &cobra.Command{
419+
Use: "grant",
420+
Short: "Grant a authz permission",
421+
DisableFlagParsing: true,
422+
SilenceUsage: true,
423+
}
424+
txCmd.AddCommand(
425+
GrantAuthorizationCmd(),
426+
GrantStoreCodeAuthorizationCmd(),
427+
)
428+
return txCmd
429+
}
430+
418431
func GrantAuthorizationCmd() *cobra.Command {
419432
cmd := &cobra.Command{
420-
Use: "grant [grantee] [message_type=\"execution\"|\"migration\"] [contract_addr_bech32] --allow-raw-msgs [msg1,msg2,...] --allow-msg-keys [key1,key2,...] --allow-all-messages",
421-
Short: "Grant authorization to an address",
433+
Use: "contract [message_type=\"execution\"|\"migration\"] [grantee] [contract_addr_bech32] --allow-raw-msgs [msg1,msg2,...] --allow-msg-keys [key1,key2,...] --allow-all-messages",
434+
Short: "Grant authorization to interact with a contract on behalf of you",
422435
Long: fmt.Sprintf(`Grant authorization to an address.
423436
Examples:
424-
$ %s tx grant <grantee_addr> execution <contract_addr> --allow-all-messages --max-calls 1 --no-token-transfer --expiration 1667979596
437+
$ %s tx grant contract execution <grantee_addr> <contract_addr> --allow-all-messages --max-calls 1 --no-token-transfer --expiration 1667979596
425438
426-
$ %s tx grant <grantee_addr> execution <contract_addr> --allow-all-messages --max-funds 100000uwasm --expiration 1667979596
439+
$ %s tx grant contract execution <grantee_addr> <contract_addr> --allow-all-messages --max-funds 100000uwasm --expiration 1667979596
427440
428-
$ %s tx grant <grantee_addr> execution <contract_addr> --allow-all-messages --max-calls 5 --max-funds 100000uwasm --expiration 1667979596
441+
$ %s tx grant contract execution <grantee_addr> <contract_addr> --allow-all-messages --max-calls 5 --max-funds 100000uwasm --expiration 1667979596
429442
`, version.AppName, version.AppName, version.AppName),
430443
Args: cobra.ExactArgs(3),
431444
RunE: func(cmd *cobra.Command, args []string) error {
@@ -560,15 +573,15 @@ $ %s tx grant <grantee_addr> execution <contract_addr> --allow-all-messages --ma
560573

561574
func GrantStoreCodeAuthorizationCmd() *cobra.Command {
562575
cmd := &cobra.Command{
563-
Use: "grant [grantee] store-code [code_hash:permission]",
564-
Short: "Grant authorization to an address",
576+
Use: "store-code [grantee] [code_hash:permission]",
577+
Short: "Grant authorization to upload contract code on behalf of you",
565578
Long: fmt.Sprintf(`Grant authorization to an address.
566579
Examples:
567-
$ %s tx grant <grantee_addr> store-code 13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5:everybody 1wqrtry681b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5:nobody --expiration 1667979596
580+
$ %s tx grant store-code <grantee_addr> 13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5:everybody 1wqrtry681b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5:nobody --expiration 1667979596
568581
569-
$ %s tx grant <grantee_addr> store-code *:%s1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm,%s1vx8knpllrj7n963p9ttd80w47kpacrhuts497x
582+
$ %s tx grant store-code <grantee_addr> *:%s1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm,%s1vx8knpllrj7n963p9ttd80w47kpacrhuts497x
570583
`, version.AppName, version.AppName, version.AppName, version.AppName),
571-
Args: cobra.MinimumNArgs(3),
584+
Args: cobra.MinimumNArgs(2),
572585
RunE: func(cmd *cobra.Command, args []string) error {
573586
clientCtx, err := client.GetClientTxContext(cmd)
574587
if err != nil {
@@ -580,11 +593,7 @@ $ %s tx grant <grantee_addr> store-code *:%s1l2rsakp388kuv9k8qzq6lrm9taddae7fpx5
580593
return err
581594
}
582595

583-
if args[1] != "store-code" {
584-
return fmt.Errorf("%s authorization type not supported", args[1])
585-
}
586-
587-
grants, err := parseStoreCodeGrants(args[2:])
596+
grants, err := parseStoreCodeGrants(args[1:])
588597
if err != nil {
589598
return err
590599
}

x/wasm/types/authz.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ func (a *StoreCodeAuthorization) Accept(ctx sdk.Context, msg sdk.Msg) (authztype
5151
}
5252

5353
code := storeMsg.WASMByteCode
54-
permission := *storeMsg.InstantiatePermission
54+
permission := storeMsg.InstantiatePermission
5555

5656
if ioutils.IsGzip(code) {
5757
gasRegister, ok := GasRegisterFromContext(ctx)
@@ -127,7 +127,7 @@ func (g CodeGrant) ValidateBasic() error {
127127
}
128128

129129
// Accept checks if checksum and permission match the grant
130-
func (g CodeGrant) Accept(checksum []byte, permission AccessConfig) bool {
130+
func (g CodeGrant) Accept(checksum []byte, permission *AccessConfig) bool {
131131
if !strings.EqualFold(string(g.CodeHash), CodehashWildcard) && !bytes.EqualFold(g.CodeHash, checksum) {
132132
return false
133133
}

0 commit comments

Comments
 (0)