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

feat: authz rules grant specific #3

Draft
wants to merge 30 commits into
base: vitwit/v0.50.5
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 12 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
645 changes: 599 additions & 46 deletions api/cosmos/authz/v1beta1/authz.pulsar.go

Large diffs are not rendered by default.

42 changes: 42 additions & 0 deletions proto/cosmos/authz/v1beta1/authz.proto
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import "google/protobuf/timestamp.proto";
import "gogoproto/gogo.proto";
import "google/protobuf/any.proto";
import "cosmos/base/v1beta1/coin.proto";

Check failure on line 10 in proto/cosmos/authz/v1beta1/authz.proto

View workflow job for this annotation

GitHub Actions / lint

Import "cosmos/base/v1beta1/coin.proto" is unused.

option go_package = "github.com/cosmos/cosmos-sdk/x/authz";
option (gogoproto.goproto_getters_all) = false;
Expand All @@ -29,6 +30,9 @@
// doesn't have a time expiration (other conditions in `authorization`
// may apply to invalidate the grant)
google.protobuf.Timestamp expiration = 2 [(gogoproto.stdtime) = true, (gogoproto.nullable) = true];

// rules are conditions to execute the grant.
bytes rules = 3;
}

// GrantAuthorization extends a grant with both the addresses of the grantee and granter.
Expand All @@ -46,3 +50,41 @@
// msg_type_urls contains the list of TypeURL of a sdk.Msg.
repeated string msg_type_urls = 1;
}

// // AuthzRules defines the rules for authz messages.
// message AuthzRules {
// // Send authz rules
// SendAuthzRules send = 1 [(gogoproto.nullable) = false];

// // Stake authz rules
// StakeAuthzRules stake = 2 [(gogoproto.nullable) = false];

// // Generic authz rules
// GenericAuthzRules generic = 3 [(gogoproto.nullable) = false];
// }

// // Send authz rules
// message SendAuthzRules {
// repeated cosmos.base.v1beta1.Coin spend_limit = 1 [
// (gogoproto.nullable) = false,
// (amino.dont_omitempty) = true,
// (amino.encoding) = "legacy_coins",
// (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"
// ];
// repeated string blocked_recipients = 2;
// }

// // Stake authz rules
// message StakeAuthzRules {
// repeated string blocked_validators = 1;
// }

// // Generic authz rules
// message GenericAuthzRules {
// repeated string blocked_messages = 1;
// }

// AuthzRuleKeys is app specific options to the keys
message AuthzRuleKeys {
bytes raw_json = 1;
}
Empty file modified scripts/dep-assert.sh
100755 → 100644
Empty file.
Empty file modified scripts/go-lint-all.bash
100755 → 100644
Empty file.
Empty file modified scripts/go-mod-tidy-all.sh
100755 → 100644
Empty file.
Empty file modified scripts/go-update-dep-all.sh
100755 → 100644
Empty file.
Empty file modified scripts/init-simapp.sh
100755 → 100644
Empty file.
Empty file modified scripts/mockgen.sh
100755 → 100644
Empty file.
Empty file modified scripts/protoc-swagger-gen.sh
100755 → 100644
Empty file.
Empty file modified scripts/protocgen-pulsar.sh
100755 → 100644
Empty file.
Empty file modified scripts/protocgen.sh
100755 → 100644
Empty file.
Empty file modified scripts/validate-gentxs.sh
100755 → 100644
Empty file.
1 change: 1 addition & 0 deletions simapp/ante.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) {
ante.NewValidateMemoDecorator(options.AccountKeeper),
ante.NewConsumeGasForTxSizeDecorator(options.AccountKeeper),
ante.NewDeductFeeDecorator(options.AccountKeeper, options.BankKeeper, options.FeegrantKeeper, options.TxFeeChecker),
ante.NewAuthzDecorator(options.AuthzKeeper),
ante.NewSetPubKeyDecorator(options.AccountKeeper), // SetPubKeyDecorator must be called before all signature verification decorators
ante.NewValidateSigCountDecorator(options.AccountKeeper),
ante.NewSigGasConsumeDecorator(options.AccountKeeper, options.SigGasConsumer),
Expand Down
4 changes: 3 additions & 1 deletion simapp/app.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//go:build app_v1
//go:build !app_v1

package simapp

Expand Down Expand Up @@ -522,6 +522,7 @@ func NewSimApp(
app.SetPreBlocker(app.PreBlocker)
app.SetBeginBlocker(app.BeginBlocker)
app.SetEndBlocker(app.EndBlocker)

app.setAnteHandler(txConfig)

// In v0.46, the SDK introduces _postHandlers_. PostHandlers are like
Expand Down Expand Up @@ -566,6 +567,7 @@ func (app *SimApp) setAnteHandler(txConfig client.TxConfig) {
HandlerOptions{
ante.HandlerOptions{
AccountKeeper: app.AccountKeeper,
AuthzKeeper: app.AuthzKeeper,
BankKeeper: app.BankKeeper,
SignModeHandler: txConfig.SignModeHandler(),
FeegrantKeeper: app.FeeGrantKeeper,
Expand Down
2 changes: 1 addition & 1 deletion simapp/app_v2.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//go:build !app_v1
//go:build app_v1

package simapp

Expand Down
1 change: 1 addition & 0 deletions x/auth/ante/ante.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
// HandlerOptions are the options required for constructing a default SDK AnteHandler.
type HandlerOptions struct {
AccountKeeper AccountKeeper
AuthzKeeper AuthzKeeper
BankKeeper types.BankKeeper
ExtensionOptionChecker ExtensionOptionChecker
FeegrantKeeper FeegrantKeeper
Expand Down
129 changes: 129 additions & 0 deletions x/auth/ante/authz_rules_ante.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
package ante

import (
"fmt"
"strings"

errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
authztypes "github.com/cosmos/cosmos-sdk/x/authz"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
)

type AuthzDecorator struct {
azk AuthzKeeper
}

func NewAuthzDecorator(azk AuthzKeeper) AuthzDecorator {
return AuthzDecorator{
azk: azk,
}
}

// AuthzDecorator checks the authorization message grants for some rules.
func (azd AuthzDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) {
sigTx, ok := tx.(authsigning.SigVerifiableTx)
if !ok {
return ctx, errorsmod.Wrap(sdkerrors.ErrTxDecode, "invalid tx type")
}

signers, err := sigTx.GetSigners()
if err != nil {
return ctx, err
}

grantee := signers[0]

msgs := tx.GetMsgs()
for _, msg := range msgs {
// Check if the message is an authorization message
if authzMsg, ok := msg.(*authztypes.MsgExec); ok {

rulesKeys, err := azd.azk.GetAuthzRulesKeys(ctx)
if err != nil {
return ctx, err
}

msgs, err := authzMsg.GetMessages()
atheeshp marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return ctx, err
}

for _, innerMsg := range msgs {
switch innerMsgConverted := innerMsg.(type) {
case *banktypes.MsgSend:
sendRuleKeysInterface, ok := rulesKeys["Send"]
if !ok {
fmt.Println("no rule keys")
continue
}

granter, err := azd.azk.AddressCodec().StringToBytes(innerMsgConverted.FromAddress)
if err != nil {
return ctx, err
}

_, rules := azd.azk.GetAuthzWithRules(ctx, grantee, granter, sdk.MsgTypeURL(&banktypes.MsgSend{}))
if rules != nil {
sendRulesKeys := sendRuleKeysInterface.([]string)
if checkSendAuthzRulesViolated(innerMsgConverted, rules, sendRulesKeys) {
return ctx, fmt.Errorf("authz rules are not meeting")
}
}
}
}
}
}

// Continue with the transaction if all checks pass
return next(ctx, tx, simulate)
}

// checkSendAuthzRulesViolated returns true if the rules are voilated
func checkSendAuthzRulesViolated(msg *banktypes.MsgSend, sendAuthzRules map[string]interface{}, sendRulesKeys []string) bool {
for _, key := range sendRulesKeys {

fmt.Printf("\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\": %v\n", ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
fmt.Printf("sendAuthzRules: %v\n", sendAuthzRules)
if blockedAddrsStrInt, ok := sendAuthzRules["AllowRecipients"]; key == "AllowRecipients" && ok {
blockedAddrsStr := blockedAddrsStrInt.(string)
blockedAddrs := strings.Split(blockedAddrsStr, ",")
for _, blockedRecipient := range blockedAddrs {
if msg.ToAddress == blockedRecipient {
return true
}
}
}

if spendLimitInt, ok := sendAuthzRules["SpendLImit"]; key == "SpendLImit" && ok {
spendLimit := spendLimitInt.(string)
limit, err := sdk.ParseCoinsNormalized(spendLimit)
if err != nil {
return true
}
if !limit.IsAllGTE(msg.Amount) {
return true
}

return true
}

}

return false
}

func checkGenericAuthzRules(_ *authztypes.MsgGrant, authz *authztypes.GenericAuthorization, genericRules map[string]string) bool {
if msgsStr, ok := genericRules["blockedMessages"]; ok {
msgs := strings.Split(msgsStr, ",")
for _, v := range msgs {
if v == authz.Msg {
return true
}
}
}

return false
}
8 changes: 8 additions & 0 deletions x/auth/ante/expected_keepers.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/cosmos-sdk/x/authz"
)

// AccountKeeper defines the contract needed for AccountKeeper related APIs.
Expand All @@ -23,3 +24,10 @@ type AccountKeeper interface {
type FeegrantKeeper interface {
UseGrantedFees(ctx context.Context, granter, grantee sdk.AccAddress, fee sdk.Coins, msgs []sdk.Msg) error
}

type AuthzKeeper interface {
GetAuthzOptions() map[string]map[string]string
GetAuthzRulesKeys(ctx context.Context) (map[string]interface{}, error)
GetAuthzWithRules(ctx context.Context, grantee, granter sdk.AccAddress, msgType string) (authz.Authorization, map[string]interface{})
AddressCodec() address.Codec
}
4 changes: 4 additions & 0 deletions x/authz/authorizations.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package authz

import (
context "context"
"encoding/json"

"github.com/cosmos/gogoproto/proto"

Expand All @@ -24,6 +25,9 @@ type Authorization interface {
// ValidateBasic does a simple validation check that
// doesn't require access to any other information.
ValidateBasic() error

// GetOptions are, rules defined if any.
GetOptions() json.RawMessage
}

// AcceptResponse instruments the controller of an authz message if the request is accepted
Expand Down
Loading
Loading