Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

authz.gno

// Package authz provides flexible authorization control for privileged actions.
//
// # Authorization Strategies
//
// The package supports multiple authorization strategies:
//   - Member-based: Single user or team of users
//   - Contract-based: The contract at a given path is itself the authority
//   - Auto-accept: Allow all actions
//   - Drop: Deny all actions
//
// Core Components
//
//   - Authority interface: Base interface implemented by all authorities
//   - Authorizer: Main wrapper object for authority management
//   - MemberAuthority: Manages authorized addresses
//   - ContractAuthority: Makes the contract at a path its own authority
//   - AutoAcceptAuthority: Accepts all actions
//   - DroppedAuthority: Denies all actions
//
// Quick Start
//
//	// Initialize with contract deployer as authority
//	var member address(...)
//	var auth = authz.NewWithMembers(member)
//
//	// Create functions that require authorization
//	func UpdateConfig(cur realm, newValue string) error {
//		return auth.DoByPrevious(0, cur, "update_config", func() error {
//			config = newValue
//			return nil
//		})
//	}
//
// See example_test.gno for more usage examples.
package authz

import (
	"chain"
	"errors"
	"strings"

	"gno.land/p/nym-moultest123/addrset/v0"
	"gno.land/p/nym-moultest123/once/v0"
	"gno.land/p/nt/avl/rotree/v0"
	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/ufmt/v0"
)

// Authorizer is the main wrapper object that handles authority management.
// It is configured with a replaceable Authority implementation.
type Authorizer struct {
	auth Authority
}

// Authority represents an entity that can authorize privileged actions.
// It is implemented by MemberAuthority, ContractAuthority, AutoAcceptAuthority,
// and DroppedAuthority.
//
// Authority is the canonical safe shape for cross-package authority
// interfaces: methods are address-typed (no realm/cur crosses the interface
// boundary), and consumers correctly derive `caller` from
// `cur.Previous().Address()` under `rlm.IsCurrent()` before invoking
// Authorize. No cur-leak (class 1) is possible through this interface.
//
// However, two RESIDUAL RISKS apply:
//
//   - Class-3 impl-substitution: NewWithAuthority and Authorizer.Transfer
//     accept any Authority impl. A malicious Authority can always-approve
//     (silent privilege escalation) or always-deny (denial-of-service).
//     Consumers should pass canonical impls from this package
//     (MemberAuthority, ContractAuthority, AutoAcceptAuthority,
//     DroppedAuthority) unless they have explicit reason to register a
//     foreign impl. We do not expose an IsCanonicalAuthority allowlist
//     because the package is intentionally extensible — third-party impls
//     are the design intent.
//
//   - Class-4 closed-over-authority: NewContractAuthority and
//     NewRestrictedContractAuthority capture a caller-supplied
//     PrivilegedActionHandler closure. The handler runs synchronously
//     inside Authorize with the consumer's authority. A hostile handler
//     can swallow actions, log the caller, or execute arbitrary code
//     under the consumer's frame. Register only trusted handler functions.
//     See r/gnops/valopers/init.gno for the realistic registration shape.
//
//   - Caller- and title-forgery on the RAW interface: Authorize takes
//     `caller` and `title` as ARGUMENTS, not from the frame. A consumer
//     that exposes a bare Authority (rather than the *Authorizer that
//     wraps it) therefore lets any holder present any caller and any
//     title. Caller-forgery is contained — the only authority-mutating
//     closure lives inside Authorizer.Transfer, so a forged caller on a
//     raw Authorize runs the caller's own inert closure and cannot
//     transfer; TestForgedCallerCannotTransfer pins that boundary.
//     Title-forgery is NOT contained: the title is passed straight to the
//     contractHandler, so a handler that branches on it (routing, quotas,
//     audit trails) must not treat it as trusted. Keep the Authority
//     unexported and hand out only what callers need; see
//     r/gnops/valopers/admin.gno, which exports a description string.
//
// We do NOT seal Authority via an unexported marker method — that pattern
// is bypassable via embedding in Gno; see
// p/test/seal/filetests/z_seal_*_filetest.gno for the four bypass tests.
type Authority interface {
	// Authorize executes a privileged action if the caller is authorized
	// Additional args can be provided for context (e.g., for proposal creation)
	Authorize(caller address, title string, action PrivilegedAction, args ...any) error

	// String returns a human-readable description of the authority
	String() string
}

// PrivilegedAction defines a function that performs a privileged action.
type PrivilegedAction func() error

// PrivilegedActionHandler is called by contract-based authorities to handle
// privileged actions.
type PrivilegedActionHandler func(title string, action PrivilegedAction) error

// NewWithMembers creates a new Authorizer whose authority is a
// MemberAuthority containing the given addresses. Callers express
// authority intent at the call site:
//
//	// "auth realm is the authority"
//	a := authz.NewWithMembers(cur.Address())
//
//	// "previous realm is the authority" (from a crossing function)
//	a := authz.NewWithMembers(cur.Previous().Address())
//
//	// "EOA caller is the authority" (from init(cur realm))
//	if !cur.Previous().IsUserCall() {
//	    panic("realm must be initialized by EOA")
//	}
//	a := authz.NewWithMembers(cur.Previous().Address())
//
// This replaces the previous NewWithCurrent / NewWithPrevious /
// NewWithOrigin sugar — those baked runtime.{Current,Previous,Origin}
// reads into the constructor, which (a) prevented use from package-
// level var initializers, (b) made the EOA-origin check inside
// NewWithOrigin an indirect address comparison rather than the
// straightforward IsUserCall predicate, and (c) coupled the
// constructor to the runtime walks the rest of the migration is
// moving away from.
func NewWithMembers(addrs ...address) *Authorizer {
	return &Authorizer{
		auth: NewMemberAuthority(addrs...),
	}
}

// NewWithAuthority creates a new Authorizer with a specific authority.
//
// SECURITY: `authority` is an open-interface input — any value satisfying
// Authority is accepted. A malicious impl can always-approve (privilege
// escalation) or always-deny (DoS). Prefer canonical impls from this
// package (NewMemberAuthority, NewContractAuthority, NewAutoAcceptAuthority,
// NewDroppedAuthority) unless you specifically need a foreign impl.
func NewWithAuthority(authority Authority) *Authorizer {
	return &Authorizer{
		auth: authority,
	}
}

// Authority returns the auth authority implementation
func (a *Authorizer) Authority() Authority {
	return a.auth
}

// Transfer changes the auth authority after validation. rlm must be the
// caller's own captured cur (asserted via rlm.IsCurrent()); the
// principal is rlm.Previous().Address(). Closes the address-parameter
// forgery: an external realm cannot supply Owner() as `caller` to
// bypass the underlying Authority's check.
//
// SECURITY (runtime substitution): once the current authority approves a
// Transfer, the new authority is installed and effective on the next call.
// If an attacker ever becomes the authority — even briefly — they can
// install a permanent DroppedAuthority (DoS) or an AutoAcceptAuthority
// (privilege escalation). Consumers concerned about this should wrap
// Transfer with a one-shot guard or a quorum/cooldown check.
//
// `newAuthority` is also an open-interface input — see NewWithAuthority's
// Class-3 caveat. Pass canonical impls.
func (a *Authorizer) Transfer(_ int, rlm realm, newAuthority Authority) error {
	if !rlm.IsCurrent() {
		return errors.New("unauthorized")
	}
	caller := rlm.Previous().Address()
	return a.auth.Authorize(caller, "transfer_authority", func() error {
		a.auth = newAuthority
		return nil
	})
}

// DoByCurrent executes a privileged action authorized as `rlm`. `rlm`
// must be the caller's own live cur (asserted via rlm.IsCurrent());
// the authorized principal is `rlm.Address()`. To authorize as the
// realm that called your function, use `DoByPrevious`.
//
//	auth.DoByCurrent(0, cur, "update_config", func() error { ... })    // current realm authorizes
//	auth.DoByPrevious(0, cur, "update_config", func() error { ... })   // calling realm authorizes
//
// The `_ int` first parameter is a deliberate sentinel that pushes
// `rlm realm` past the first-arg position so DoByCurrent stays a
// non-crossing method — otherwise it would be a crossing method and
// rlm.Previous() inside would resolve one realm deeper than the caller
// intended.
//
// SECURITY: the IsCurrent guard closes Class-2 designation forgery (see
// docs/resources/gno-security.md). A realm value's .Address() is set
// when the value is minted at a crossing frame; the value can in
// principle be stored and replayed. Without IsCurrent, a hostile realm
// could capture a high-privilege realm's cur.Previous() (e.g., when
// that realm called into it) and later pass the stored value here to
// authorize actions as that realm. IsCurrent rejects stale captures by
// requiring the value to match the topmost live crossing frame's cur.
func (a *Authorizer) DoByCurrent(_ int, rlm realm, title string, action PrivilegedAction, args ...any) error {
	if !rlm.IsCurrent() {
		return errors.New("unauthorized")
	}
	return a.auth.Authorize(rlm.Address(), title, action, args...)
}

// DoByPrevious executes a privileged action authorized as the realm
// that called the function invoking DoByPrevious. `rlm` must be the
// caller's own live cur; the principal is derived as
// `rlm.Previous().Address()`. Mirrors the Transfer/AddMember pattern:
// always take live cur, derive the caller-of-caller internally rather
// than accepting a stored/forwarded realm value.
func (a *Authorizer) DoByPrevious(_ int, rlm realm, title string, action PrivilegedAction, args ...any) error {
	if !rlm.IsCurrent() {
		return errors.New("unauthorized")
	}
	return a.auth.Authorize(rlm.Previous().Address(), title, action, args...)
}

// String returns a string representation of the auth authority.
//
// A non-canonical impl is wrapped as custom_authority[...] so that the
// official "dropped" is distinguishable from a "*custom*: dropped"
// (autoclaimed) one. Shared with ContractAuthority.String, which applies
// the same rule to its nested proposer.
func (a *Authorizer) String() string {
	return canonicalAuthorityString(a.auth)
}

// MemberAuthority is the default implementation using addrset for member
// management.
type MemberAuthority struct {
	members addrset.Set
}

func NewMemberAuthority(members ...address) *MemberAuthority {
	auth := &MemberAuthority{}
	for _, addr := range members {
		auth.members.Add(addr)
	}
	return auth
}

func (a *MemberAuthority) Authorize(caller address, title string, action PrivilegedAction, args ...any) error {
	if !a.members.Has(caller) {
		return errors.New("unauthorized")
	}

	if err := action(); err != nil {
		return err
	}
	return nil
}

func (a *MemberAuthority) String() string {
	addrs := []string{}
	a.members.Tree().Iterate("", "", func(key string, _ any) bool {
		addrs = append(addrs, key)
		return false
	})
	addrsStr := strings.Join(addrs, ",")
	return ufmt.Sprintf("member_authority[%s]", addrsStr)
}

// AddMember adds a new member to the authority. rlm must be the caller's
// own captured cur; the principal is rlm.Previous().Address() and must
// already be a member. The IsCurrent guard closes the forgery where an
// external realm passes Owner() as caller to bypass members.Has(caller).
func (a *MemberAuthority) AddMember(_ int, rlm realm, addr address) error {
	if !rlm.IsCurrent() {
		return errors.New("unauthorized")
	}
	caller := rlm.Previous().Address()
	return a.Authorize(caller, "add_member", func() error {
		a.members.Add(addr)
		return nil
	})
}

// AddMembers adds a list of members to the authority. Same rlm contract
// as AddMember.
func (a *MemberAuthority) AddMembers(_ int, rlm realm, addrs ...address) error {
	if !rlm.IsCurrent() {
		return errors.New("unauthorized")
	}
	caller := rlm.Previous().Address()
	return a.Authorize(caller, "add_members", func() error {
		for _, addr := range addrs {
			a.members.Add(addr)
		}
		return nil
	})
}

// RemoveMember removes a member from the authority. Same rlm contract
// as AddMember.
func (a *MemberAuthority) RemoveMember(_ int, rlm realm, addr address) error {
	if !rlm.IsCurrent() {
		return errors.New("unauthorized")
	}
	caller := rlm.Previous().Address()
	return a.Authorize(caller, "remove_member", func() error {
		a.members.Remove(addr)
		return nil
	})
}

// Tree returns a read-only view of the members tree
func (a *MemberAuthority) Tree() *rotree.ReadOnlyTree {
	tree := a.members.Tree().(*avl.Tree)
	return rotree.Wrap(tree, nil)
}

// Has checks if the given address is a member of the authority
func (a *MemberAuthority) Has(addr address) bool {
	return a.members.Has(addr)
}

// ContractAuthority implements async contract-based authority
type ContractAuthority struct {
	contractPath    string
	contractAddr    address
	contractHandler PrivilegedActionHandler
	proposer        Authority // controls who can create proposals
}

// NewContractAuthority makes the contract at `path` its OWN authority:
// the default proposer accepts only chain.PackageAddress(path), so a
// privileged action proceeds only when driven from that contract's own
// frame.
//
// NewRestrictedContractAuthority does NOT widen this — it REPLACES it.
// See its godoc; with an explicit proposer, `path` is a label and
// contractAddr is never consulted.
//
// The `caller` compared against that address is established upstream by
// Authorizer.DoByCurrent / DoByPrevious / Transfer under rlm.IsCurrent(),
// so an external realm cannot present the contract address.
//
// BREAKING: the default proposer used to be
// NewAutoAcceptAuthority ("anyone can propose"). Consumers that relied on
// arbitrary callers driving a plain ContractAuthority will start getting
// "unauthorized"; that is the fix, not a regression. Pass an explicit
// proposer to NewRestrictedContractAuthority to opt back in.
//
// SECURITY — the gate binds the contract's IDENTITY, not its intent.
// Inside any crossing frame of the contract, rlm.Address() is
// unconditionally PackageAddress(path), so `DoByCurrent` from within the
// contract is a tautology; only DoByPrevious and Transfer gain a real
// check. Consequently ANY exported function of the contract that returns
// a crossing closure (or anything else carrying its frame) hands this
// authority to its caller. Keep privileged closures unexported.
//
// So DO NOT write NewContractAuthority(ownPath) + DoByCurrent. It reads
// like "only I may do this" and compiles to "anyone may do this". Point
// `path` at the principal you actually want to assert — usually the
// governance realm that will drive the action — and use DoByPrevious, so
// the comparison is against whoever crossed in:
//
//	// in r/gnops/valopers/init.gno
//	auth = authz.NewWithAuthority(
//	    authz.NewContractAuthority("gno.land/r/gov/dao", handler),
//	)
//	// in the privileged write
//	auth.DoByPrevious(0, rlm, "update-instructions", action)
//
// Own-path is right only when something OTHER than the contract's own
// frame supplies the caller — i.e. you drive it via DoByPrevious from a
// realm you have deliberately let call in, or via Transfer.
//
// SECURITY — a gate is only as good as the principal it names. Pointing
// `path` at a realm whose frame ANY caller can mint buys nothing. Check,
// for whatever principal you choose, that nothing exported by that realm
// hands out its frame identity:
//
//   - `gno.land/r/gov/dao` is safe to assert ONLY because
//     SimpleExecutor.Execute rejects invocation from outside the proxy
//     (r/gov/dao/types.gno). Before that gate existed, dao's exported
//     NewSimpleExecutor + Execute let any realm mint a frame whose
//     Previous() was r/gov/dao, so this whole pairing authenticated
//     nothing. Do not assume a governance path is unforgeable; verify it.
//   - Whatever the principal, an exported function of YOUR realm whose
//     signature is assignable to a callback type the principal invokes
//     (for r/gov/dao: `func(realm) error`) is itself the leak — the
//     principal will happily call it for an attacker. Keep privileged
//     entrypoints out of that shape, or take extra parameters.
//
// Neither shape defends against re-exporting the privileged closure: its
// holder picks the Previous() they present by wrapping it in an executor
// of their own. Unexported closures remain the load-bearing rule.
//
// A syntactically valid but WRONG `path` is a permanent brick, not an
// error: the authority accepts nobody, and Transfer routes through the
// same gate, so it cannot be rotated out either. Construction rejects
// malformed paths, but it cannot tell a wrong path from a right one —
// e.g. "gno.land/r/gov/dao/impl/v0" (the path r/gov/dao's own
// allowedDAOs list holds) is well-formed and permanently dead, because
// an executor's Previous() is the PROXY path, never the impl. Give the
// consumer a governance-gated rotation entrypoint before deploying; see
// r/gnops/valopers/admin.gno's NewAuthorityRotationProposalRequest.
//
// SECURITY (Class-4 captured callback): `handler` is a caller-supplied
// closure that runs SYNCHRONOUSLY inside Authorize, with the consumer's
// authority. A hostile handler can swallow actions, log the caller, or
// execute arbitrary code under the consumer's frame. The package-internal
// wrappedAction enforces at-most-once invocation and NOTHING ELSE — in
// particular it does not check the caller, and the handler may call it
// however it likes (multiple times, never, out of order). Register only
// trusted handler functions; treat handler registration as the trust
// boundary.
//
// Panics if `path` is empty or malformed, or if `handler` is nil.
func NewContractAuthority(path string, handler PrivilegedActionHandler) *ContractAuthority {
	addr := chain.PackageAddress(assertValidContractPath(path))
	// The default proposer is a real Authority, not an absent one. Encoding
	// the strictest policy as a nil field would mean the secure default is
	// what you get by leaving something OUT: a struct literal that skips
	// this constructor, a persisted value from an older build, or re-adding
	// `if proposer == nil { proposer = NewAutoAcceptAuthority() }` would all
	// silently be wide open again. A one-field struct costs the same as the
	// nil it replaces and cannot be reached by omission.
	return newContractAuthority(path, addr, handler, &contractIdentityAuthority{addr: addr})
}

// NewRestrictedContractAuthority creates a contract authority whose
// proposer REPLACES the contract-identity gate.
//
// This is the escape hatch, not a second lock. `proposer` becomes the ONLY
// authorization decision: contractAddr is not consulted on this path, so
// `path` degrades to a label that appears in String() and asserts nothing.
// NewRestrictedContractAuthority(p, h, NewAutoAcceptAuthority()) is exactly
// the old default behaviour ("anyone can propose"), stated
// explicitly rather than reached by default.
//
// In particular NewRestrictedContractAuthority("gno.land/r/gov/dao", h,
// NewMemberAuthority(alice)) does NOT mean "GovDAO and alice". It means
// "alice, and not GovDAO".
//
// SECURITY:
//   - `handler` is the same Class-4 captured-callback risk as
//     NewContractAuthority — runs synchronously inside Authorize with the
//     consumer's authority. Register only trusted handler functions.
//   - `proposer` is an open-interface input (Class-3 impl-substitution).
//     A hostile proposer Authority can always-approve creation of any
//     proposal, defeating the restriction. Pass canonical impls only.
//     String() renders a non-canonical proposer wrapped as
//     custom_authority[...] so such a substitution is at least visible.
func NewRestrictedContractAuthority(path string, handler PrivilegedActionHandler, proposer Authority) Authority {
	if proposer == nil {
		panic("proposer cannot be nil")
	}
	addr := chain.PackageAddress(assertValidContractPath(path))
	return newContractAuthority(path, addr, handler, proposer)
}

// newContractAuthority is the single construction path: both exported
// constructors validate, then land here, so a guard added once applies to
// both. `handler` is rejected here rather than surfaced at Authorize time
// because Authorize checks contractHandler == nil BEFORE consulting the
// proposer, and Transfer routes through Authorize — so a nil-handler
// authority could never be rotated out. It is a permanent brick with no
// on-chain recovery for anyone: the same bricked-governance failure
// mode, reached by accident.
func newContractAuthority(path string, addr address, handler PrivilegedActionHandler, proposer Authority) *ContractAuthority {
	if handler == nil {
		panic("contract handler cannot be nil")
	}
	return &ContractAuthority{
		contractPath:    path,
		contractAddr:    addr,
		contractHandler: handler,
		proposer:        proposer,
	}
}

// assertValidContractPath rejects paths that chain.PackageAddress would
// hash happily but that no realm could ever present, which would brick the
// authority permanently (nobody authorizes, and Transfer routes through the
// same gate so nobody can rotate out). Returns `path` so it composes.
//
// The authoritative rule is gnolang.ReGnoUserPkgPath ("all paths must be
// lowercase ascii alphanumeric characters", gnovm/pkg/gnolang/mempackage.go),
// but no validator is exported to Gno code — chain's isValidSubpath /
// assertValidSubpath are unexported, and there is no chain.IsValidPkgPath.
// So this is a deliberately permissive superset: segment ("/" segment)*,
// segment = [a-z0-9] ([a-z0-9_.-]* [a-z0-9])?. It accepts every real
// package path and catches what actually gets typed wrong — trailing or
// embedded whitespace, empty segments, uppercase, stray punctuation. It
// CANNOT catch a well-formed path that is simply the wrong principal. See
// NewContractAuthority's godoc on rotation.
func assertValidContractPath(path string) string {
	if path == "" {
		panic("contract path cannot be empty")
	}
	if !strings.Contains(path, "/") {
		panic("contract path must be a package path, e.g. gno.land/r/gov/dao")
	}
	start := 0
	for i := 0; i <= len(path); i++ {
		if i == len(path) || path[i] == '/' {
			if !isValidContractPathSegment(path[start:i]) {
				panic("contract path must be '/'-separated segments of [a-z0-9] with '_.-' allowed inside a segment, e.g. gno.land/r/gov/dao")
			}
			start = i + 1
		}
	}
	return path
}

func isValidContractPathSegment(seg string) bool {
	if seg == "" {
		return false
	}
	for i := 0; i < len(seg); i++ {
		switch c := seg[i]; {
		case c >= 'a' && c <= 'z', c >= '0' && c <= '9':
		case c == '_' || c == '.' || c == '-':
			// Allowed only strictly inside a segment.
			if i == 0 || i == len(seg)-1 {
				return false
			}
		default:
			return false
		}
	}
	return true
}

// contractIdentityAuthority is the default proposer installed by
// NewContractAuthority: the contract at the bound path, and nobody else.
// Unexported and unmutable by design — AddMember/RemoveMember are
// meaningless for a fixed contract identity, which is why this is not a
// MemberAuthority holding one address.
type contractIdentityAuthority struct {
	addr address
}

func (a *contractIdentityAuthority) Authorize(caller address, _ string, action PrivilegedAction, _ ...any) error {
	if caller != a.addr {
		return errors.New("unauthorized")
	}
	return action()
}

func (a *contractIdentityAuthority) String() string { return "contract-identity" }

func (a *ContractAuthority) Authorize(caller address, title string, action PrivilegedAction, args ...any) error {
	if a.contractHandler == nil {
		return errors.New("contract handler is not set")
	}

	// setup a once instance to ensure the action is executed only once
	executionOnce := once.Once{}

	// wrappedAction enforces at-most-once invocation. The previous
	// gate `unsafe.CurrentRealm() == contractAddr` is removed: it
	// was .Title()-bypassable (runtime.CurrentRealm walks past
	// non-crossing frames to the most-recent crossing ancestor) and
	// the trust boundary is now upstream — Authorizer.DoByCurrent /
	// DoByPrevious require rlm.IsCurrent() and pass a non-forgeable
	// principal to Authorize, while the consumer realm's handler
	// closure is the Class-4 trust root by lexical capture at
	// registration time.
	wrappedAction := func() error {
		return executionOnce.DoErr(func() error {
			return action()
		})
	}

	handle := func() error {
		if err := a.contractHandler(title, wrappedAction); err != nil {
			return err
		}
		return nil
	}

	// The proposer IS the authorization decision. For an authority built by
	// NewContractAuthority it is a contractIdentityAuthority bound to
	// contractAddr — the contract itself and nobody else; for one built by
	// NewRestrictedContractAuthority it is whatever the consumer installed,
	// and contractAddr is deliberately not consulted (see that constructor's
	// godoc). `caller` is established upstream by Authorizer.DoByCurrent /
	// DoByPrevious / Transfer under rlm.IsCurrent(), so an external realm
	// cannot present an arbitrary principal here.
	//
	// A nil proposer is not a policy, it is a malformed value: both
	// constructors always install one, so nil means the struct was built by
	// a literal that bypassed them. Fail closed rather than dereference.
	if a.proposer == nil {
		return errors.New("proposer is not set")
	}
	return a.proposer.Authorize(caller, title+"_proposal", handle, args...)
}

// String renders the contract path AND the proposer.
//
// The proposer half is security-relevant, not cosmetic: it is the only
// thing distinguishing a gated authority from a wide-open one. Rendering
// the path alone made
//
//	NewContractAuthority(path, handler)                              // gated
//	NewRestrictedContractAuthority(path, handler, AutoAccept{})      // open to all
//
// byte-identical, so any consumer test asserting on this string — and
// any on-chain reader inspecting it — was blind to the difference. A
// consumer realm could have its authority swapped for a fully permissive
// one and its assertions would stay green.
//
// "contract-identity" names the default installed by NewContractAuthority:
// the contract at contractPath, and nobody else, may drive this authority.
//
// The proposer is rendered through canonicalAuthorityString, NOT by calling
// a.proposer.String() directly. Authority is an open interface, so a foreign
// impl can return any text it likes — including "contract-identity". That
// made a fully permissive authority byte-identical to the gated default
// again, defeating the very assertions this rendering exists to support.
// Non-canonical impls are wrapped as custom_authority[...], mirroring what
// Authorizer.String has always done at the outer level.
//
// Read the `contract=` half with care: it is load-bearing only for the
// contract-identity default. With any other proposer it is a label —
// see NewRestrictedContractAuthority.
func (a *ContractAuthority) String() string {
	return ufmt.Sprintf(
		"contract_authority[contract=%s,proposer=%s]",
		a.contractPath,
		canonicalAuthorityString(a.proposer),
	)
}

// canonicalAuthorityString renders an Authority, wrapping any
// implementation that is not one of this package's own as
// custom_authority[...] so a foreign impl cannot impersonate a canonical
// one by choosing its String() text. Shared by ContractAuthority.String
// (for the nested proposer) and Authorizer.String (for the installed
// authority).
func canonicalAuthorityString(auth Authority) string {
	if auth == nil {
		// Only reachable via a struct literal that bypassed the
		// constructors; Authorize fails closed on the same condition.
		return "<unset>"
	}
	switch auth.(type) {
	case *MemberAuthority, *ContractAuthority, *AutoAcceptAuthority,
		*droppedAuthority, *contractIdentityAuthority:
		return auth.String()
	default:
		return ufmt.Sprintf("custom_authority[%s]", auth.String())
	}
}

// AutoAcceptAuthority implements an authority that accepts all actions
// AutoAcceptAuthority is a simple authority that automatically accepts all
// actions.
// It can be used as a proposer authority to allow anyone to create proposals.
type AutoAcceptAuthority struct{}

func NewAutoAcceptAuthority() *AutoAcceptAuthority {
	return &AutoAcceptAuthority{}
}

func (a *AutoAcceptAuthority) Authorize(caller address, title string, action PrivilegedAction, args ...any) error {
	return action()
}

func (a *AutoAcceptAuthority) String() string {
	return "auto_accept_authority"
}

// droppedAuthority implements an authority that denies all actions
type droppedAuthority struct{}

func NewDroppedAuthority() Authority {
	return &droppedAuthority{}
}

func (a *droppedAuthority) Authorize(caller address, title string, action PrivilegedAction, args ...any) error {
	return errors.New("dropped authority: all actions are denied")
}

func (a *droppedAuthority) String() string {
	return "dropped_authority"
}

authz_test.gno

package authz

import (
	"chain"
	"errors"
	"strings"
	"testing"

	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
)

func TestNewWithCurrent(cur realm, t *testing.T) {
	alice := testutils.TestAddress("alice")
	testing.SetRealm(testing.NewUserRealm(alice))

	auth := NewWithMembers(cur.Address())

	// Check that the current authority is a MemberAuthority
	memberAuth, ok := auth.Authority().(*MemberAuthority)
	uassert.True(t, ok, "expected MemberAuthority")

	// Check that the caller is a member
	uassert.True(t, memberAuth.Has(alice), "caller should be a member")

	// Check string representation
	uassert.True(t, strings.Contains(auth.String(), alice.String()))
}

func TestNewWithAuthority(cur realm, t *testing.T) {
	alice := testutils.TestAddress("alice")
	memberAuth := NewMemberAuthority(alice)

	auth := NewWithAuthority(memberAuth)

	// Check that the current authority is the one we provided
	uassert.True(t, auth.Authority() == memberAuth, "expected provided authority")
}

func TestAuthorizerAuthorize(cur realm, t *testing.T) {
	alice := testutils.TestAddress("alice")
	testing.SetRealm(testing.NewUserRealm(alice))

	auth := NewWithMembers(cur.Address())

	// Test successful action with args
	executed := false
	args := []any{"test_arg", 123}
	err := auth.DoByCurrent(0, cur, "test_action", func() error {
		executed = true
		return nil
	}, args...)

	uassert.True(t, err == nil, "expected no error")
	uassert.True(t, executed, "action should have been executed")

	// Test unauthorized action with args
	testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("bob")))

	executed = false
	err = auth.DoByCurrent(0, cur, "test_action", func() error {
		executed = true
		return nil
	}, "unauthorized_arg")

	uassert.True(t, err != nil, "expected error")
	uassert.False(t, executed, "action should not have been executed")

	// Test action returning error
	testing.SetRealm(testing.NewUserRealm(alice))
	expectedErr := errors.New("test error")

	err = auth.DoByCurrent(0, cur, "test_action", func() error {
		return expectedErr
	})

	uassert.True(t, err == expectedErr, "expected specific error")
}

func TestAuthorizerTransfer(cur realm, t *testing.T) {
	alice := testutils.TestAddress("alice")
	testing.SetRealm(testing.NewUserRealm(alice))

	auth := NewWithMembers(cur.Address())

	// Test transfer to new member authority
	bob := testutils.TestAddress("bob")
	newAuth := NewMemberAuthority(bob)

	var err error
	func(cur realm) { err = auth.Transfer(0, cur, newAuth) }(cross(cur))
	uassert.True(t, err == nil, "expected no error")
	uassert.True(t, auth.Authority() == newAuth, "expected new authority")

	// Test unauthorized transfer: principal is not a member of newAuth.
	carol := testutils.TestAddress("carol")
	testing.SetRealm(testing.NewUserRealm(carol))

	func(cur realm) { err = auth.Transfer(0, cur, NewMemberAuthority(alice)) }(cross(cur))
	uassert.True(t, err != nil, "expected error")

	// Test transfer to contract authority — bob is the current authority.
	testing.SetRealm(testing.NewUserRealm(bob))
	contractAuth := NewContractAuthority("gno.land/r/test", func(title string, action PrivilegedAction) error {
		return action()
	})

	func(cur realm) { err = auth.Transfer(0, cur, contractAuth) }(cross(cur))
	uassert.True(t, err == nil, "expected no error")
	uassert.True(t, auth.Authority() == contractAuth, "expected contract authority")
}

func TestAuthorizerTransferChain(cur realm, t *testing.T) {
	alice := testutils.TestAddress("alice")
	testing.SetRealm(testing.NewUserRealm(alice))

	// Create a chain of transfers
	auth := NewWithMembers(cur.Address())

	// First transfer to a new member authority
	bob := testutils.TestAddress("bob")
	memberAuth := NewMemberAuthority(bob)

	var err error
	func(cur realm) { err = auth.Transfer(0, cur, memberAuth) }(cross(cur))
	uassert.True(t, err == nil, "unexpected error in first transfer")

	// Then transfer to a contract authority — bob is now the authority.
	testing.SetRealm(testing.NewUserRealm(bob))
	contractAuth := NewContractAuthority("gno.land/r/test", func(title string, action PrivilegedAction) error {
		return action()
	})
	func(cur realm) { err = auth.Transfer(0, cur, contractAuth) }(cross(cur))
	uassert.True(t, err == nil, "unexpected error in second transfer")

	// Finally transfer to an auto-accept authority. The authority is now
	// the contract authority, whose default proposer is the contract
	// itself, so the transfer's caller —
	// cur.Previous() — must be the contract. Set the outer realm to the
	// contract, then cross into a closure so cur.Previous() resolves to
	// it.
	autoAuth := NewAutoAcceptAuthority()
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/test"))
	func(cur realm) { err = auth.Transfer(0, cur, autoAuth) }(cross(cur))
	uassert.True(t, err == nil, "unexpected error in final transfer")
	uassert.True(t, auth.Authority() == autoAuth, "expected auto-accept authority")
}

func TestAuthorizerTransferUnauthorizedRejected(cur realm, t *testing.T) {
	// Regression for the address-parameter forgery: previously Transfer
	// took a caller-supplied `caller address` that an attacker realm could
	// set to the real owner. After the IsCurrent + rlm.Previous() fix, the
	// principal is the captured cur's previous and cannot be forged.
	admin := testutils.TestAddress("admin")
	attacker := testutils.TestAddress("attacker")

	testing.SetRealm(testing.NewUserRealm(admin))
	auth := NewWithMembers(cur.Address()) // admin is the initial authority

	initialAuth, ok := auth.Authority().(*MemberAuthority)
	uassert.True(t, ok)
	uassert.True(t, initialAuth.Has(admin))
	uassert.False(t, initialAuth.Has(attacker))

	// Attacker context: cur.Previous() inside the closure will be attacker.
	testing.SetRealm(testing.NewUserRealm(attacker))
	attackerAuth := NewMemberAuthority(attacker)
	var err error
	func(cur realm) { err = auth.Transfer(0, cur, attackerAuth) }(cross(cur))

	uassert.True(t, err != nil, "attacker transfer must be rejected")

	// Authority unchanged: still the initial admin-only MemberAuthority.
	finalAuth, ok := auth.Authority().(*MemberAuthority)
	uassert.True(t, ok)
	uassert.True(t, finalAuth == initialAuth, "authority must not have changed")
	uassert.True(t, finalAuth.Has(admin))
	uassert.False(t, finalAuth.Has(attacker))
}

func TestAuthorizerWithDroppedAuthority(cur realm, t *testing.T) {
	alice := testutils.TestAddress("alice")
	testing.SetRealm(testing.NewUserRealm(alice))

	auth := NewWithMembers(cur.Address())

	// Transfer to dropped authority
	var err error
	func(cur realm) { err = auth.Transfer(0, cur, NewDroppedAuthority()) }(cross(cur))
	uassert.True(t, err == nil, "expected no error")

	// Try to execute action
	err = auth.DoByCurrent(0, cur, "test_action", func() error {
		return nil
	})
	uassert.True(t, err != nil, "expected error from dropped authority")

	// Try to transfer again
	func(cur realm) { err = auth.Transfer(0, cur, NewMemberAuthority(alice)) }(cross(cur))
	uassert.True(t, err != nil, "expected error when transferring from dropped authority")
}

func TestContractAuthorityHandlerExecutionOnce(cur realm, t *testing.T) {
	attempts := 0
	executed := 0

	contractAuth := NewContractAuthority("gno.land/r/test", func(title string, action PrivilegedAction) error {
		// Try to execute the action twice in the same handler
		if err := action(); err != nil {
			return err
		}
		attempts++

		// Second execution should fail
		if err := action(); err != nil {
			return err
		}
		attempts++
		return nil
	})

	// Set caller to contract address
	codeRealm := testing.NewCodeRealm("gno.land/r/test")
	testing.SetRealm(codeRealm)
	code := codeRealm.Address()

	testArgs := []any{"proposal_id", 42, "metadata", map[string]string{"key": "value"}}
	err := contractAuth.Authorize(code, "test_action", func() error {
		executed++
		return nil
	}, testArgs...)

	uassert.True(t, err == nil, "handler execution should succeed")
	uassert.True(t, attempts == 2, "handler should have attempted execution twice")
	uassert.True(t, executed == 1, "handler should have executed once")
}

func TestContractAuthorityExecutionTwice(cur realm, t *testing.T) {
	executed := 0

	contractAuth := NewContractAuthority("gno.land/r/test", func(title string, action PrivilegedAction) error {
		return action()
	})

	// Set caller to contract address
	codeRealm := testing.NewCodeRealm("gno.land/r/test")
	testing.SetRealm(codeRealm)
	code := codeRealm.Address()
	testArgs := []any{"proposal_id", 42, "metadata", map[string]string{"key": "value"}}

	err := contractAuth.Authorize(code, "test_action", func() error {
		executed++
		return nil
	}, testArgs...)

	uassert.True(t, err == nil, "handler execution should succeed")
	uassert.True(t, executed == 1, "handler should have executed once")

	// A new action, even with the same title, should be executed
	err = contractAuth.Authorize(code, "test_action", func() error {
		executed++
		return nil
	}, testArgs...)

	uassert.True(t, err == nil, "handler execution should succeed")
	uassert.True(t, executed == 2, "handler should have executed twice")
}

func TestContractAuthorityWithProposer(cur realm, t *testing.T) {
	alice := testutils.TestAddress("alice")
	memberAuth := NewMemberAuthority(alice)

	handlerCalled := false
	actionExecuted := false

	contractAuth := NewRestrictedContractAuthority("gno.land/r/test", func(title string, action PrivilegedAction) error {
		handlerCalled = true
		// Set caller to contract address before executing action
		testing.SetRealm(testing.NewCodeRealm("gno.land/r/test"))
		return action()
	}, memberAuth)

	// Test authorized member
	testArgs := []any{"proposal_metadata", "test value"}
	err := contractAuth.Authorize(alice, "test_action", func() error {
		actionExecuted = true
		return nil
	}, testArgs...)

	uassert.True(t, err == nil, "authorized member should be able to propose")
	uassert.True(t, handlerCalled, "contract handler should be called")
	uassert.True(t, actionExecuted, "action should be executed")

	// Reset flags for unauthorized test
	handlerCalled = false
	actionExecuted = false

	// Test unauthorized proposer
	bob := testutils.TestAddress("bob")
	err = contractAuth.Authorize(bob, "test_action", func() error {
		actionExecuted = true
		return nil
	}, testArgs...)

	uassert.True(t, err != nil, "unauthorized member should not be able to propose")
	uassert.False(t, handlerCalled, "contract handler should not be called for unauthorized proposer")
	uassert.False(t, actionExecuted, "action should not be executed for unauthorized proposer")
}

func TestAutoAcceptAuthority(cur realm, t *testing.T) {
	alice := testutils.TestAddress("alice")
	auth := NewAutoAcceptAuthority()

	// Test that any action is authorized
	executed := false
	err := auth.Authorize(alice, "test_action", func() error {
		executed = true
		return nil
	})

	uassert.True(t, err == nil, "auto-accept should not return error")
	uassert.True(t, executed, "action should have been executed")

	// Test with different caller
	random := testutils.TestAddress("random")
	executed = false
	err = auth.Authorize(random, "test_action", func() error {
		executed = true
		return nil
	})

	uassert.True(t, err == nil, "auto-accept should not care about caller")
	uassert.True(t, executed, "action should have been executed")
}

func TestAutoAcceptAuthorityWithArgs(cur realm, t *testing.T) {
	auth := NewAutoAcceptAuthority()
	anyuser := testutils.TestAddress("anyuser")

	// Test that any action is authorized with args
	executed := false
	testArgs := []any{"arg1", 42, "arg3"}
	err := auth.Authorize(anyuser, "test_action", func() error {
		executed = true
		return nil
	}, testArgs...)

	uassert.True(t, err == nil, "auto-accept should not return error")
	uassert.True(t, executed, "action should have been executed")
}

func TestMemberAuthorityMultipleMembers(cur realm, t *testing.T) {
	alice := testutils.TestAddress("alice")
	bob := testutils.TestAddress("bob")
	carol := testutils.TestAddress("carol")

	// Create authority with multiple members
	auth := NewMemberAuthority(alice, bob)

	// Test that both members can execute actions
	for _, member := range []address{alice, bob} {
		err := auth.Authorize(member, "test_action", func() error {
			return nil
		})
		uassert.True(t, err == nil, "member should be authorized")
	}

	// Test that non-member cannot execute
	err := auth.Authorize(carol, "test_action", func() error {
		return nil
	})
	uassert.True(t, err != nil, "non-member should not be authorized")

	// Test Tree() functionality
	tree := auth.Tree()
	uassert.True(t, tree.Size() == 2, "tree should have 2 members")

	// Verify both members are in the tree
	found := make(map[address]bool)
	tree.Iterate("", "", func(key string, _ any) bool {
		found[address(key)] = true
		return false
	})
	uassert.True(t, found[alice], "alice should be in the tree")
	uassert.True(t, found[bob], "bob should be in the tree")
	uassert.False(t, found[carol], "carol should not be in the tree")

	// Test read-only nature of the tree
	defer func() {
		r := recover()
		uassert.True(t, r != nil, "modifying read-only tree should panic")
	}()
	tree.Set(string(carol), nil) // This should panic
}

func TestAuthorizerCurrentNeverNil(cur realm, t *testing.T) {
	auth := NewWithMembers(cur.Address())

	// Authority should never be nil after initialization
	uassert.True(t, auth.Authority() != nil, "current authority should not be nil")

	// Authority should not be nil after transfer
	var err error
	func(cur realm) { err = auth.Transfer(0, cur, NewAutoAcceptAuthority()) }(cross(cur))
	uassert.True(t, err == nil, "transfer should succeed")
	uassert.True(t, auth.Authority() != nil, "current authority should not be nil after transfer")
}

func TestContractAuthorityValidation(cur realm, t *testing.T) {
	handler := func(title string, action PrivilegedAction) error {
		return nil
	}

	// Empty path panics (consistent with NewRestrictedContractAuthority).
	uassert.PanicsWithMessage(t, cur, "contract path cannot be empty", func() {
		NewContractAuthority("", handler)
	})

	// A nil handler panics at CONSTRUCTION rather than being tolerated and
	// surfaced at Authorize time. Tolerating it produced a permanent brick:
	// see TestNilHandlerWouldBeUnrotatable below.
	uassert.PanicsWithMessage(t, cur, "contract handler cannot be nil", func() {
		NewContractAuthority("gno.land/r/test", nil)
	})

	// The Authorize-time guard stays for a zero-value ContractAuthority,
	// which the constructors cannot produce but a struct literal can.
	code := testing.NewCodeRealm("gno.land/r/test").Address()
	zero := &ContractAuthority{contractPath: "gno.land/r/test", contractAddr: code}
	err := zero.Authorize(code, "test", func() error {
		return nil
	})
	uassert.True(t, err != nil, "nil handler authority should fail to authorize")

	// Test valid configuration
	contractAuth := NewContractAuthority("gno.land/r/test", handler)
	err = contractAuth.Authorize(code, "test", func() error {
		return nil
	})
	uassert.True(t, err == nil, "valid contract authority should authorize successfully")
}

func TestAuthorizerString(cur realm, t *testing.T) {
	auth := NewWithMembers(cur.Address())
	addr := cur.Address()

	// Test initial string representation
	str := auth.String()
	uassert.Equal(t, str, "member_authority["+string(addr)+"]")

	// Test string after transfer — caller is the current member (cur).
	autoAuth := NewAutoAcceptAuthority()
	var err error
	func(cur realm) { err = auth.Transfer(0, cur, autoAuth) }(cross(cur))
	uassert.True(t, err == nil, "transfer should succeed")
	str = auth.String()
	uassert.Equal(t, str, "auto_accept_authority")

	// Test custom authority — auto-accept lets anyone transfer.
	customAuth := &mockAuthority{}
	func(cur realm) { err = auth.Transfer(0, cur, customAuth) }(cross(cur))
	uassert.True(t, err == nil, "transfer should succeed")
	str = auth.String()
	uassert.Equal(t, str, "custom_authority[mock]")
}

type mockAuthority struct{}

func (c mockAuthority) String() string { return "mock" }
func (a mockAuthority) Authorize(caller address, title string, action PrivilegedAction, args ...any) error {
	// autoaccept
	return action()
}

func TestAuthorityString(cur realm, t *testing.T) {
	alice := testutils.TestAddress("alice")

	// MemberAuthority
	memberAuth := NewMemberAuthority(alice)
	memberStr := memberAuth.String()
	expectedMemberStr := "member_authority[g1v9kxjcm9ta047h6lta047h6lta047h6lzd40gh]"
	uassert.Equal(t, memberStr, expectedMemberStr)

	// ContractAuthority — the proposer is rendered, not just the path.
	// Without it the two constructors below are indistinguishable, which
	// is what made consumer-level assertions on this string blind to an
	// authority being swapped for a wide-open one.
	contractAuth := NewContractAuthority("gno.land/r/test", func(title string, action PrivilegedAction) error { return nil })
	contractStr := contractAuth.String()
	expectedContractStr := "contract_authority[contract=gno.land/r/test,proposer=contract-identity]"
	uassert.Equal(t, contractStr, expectedContractStr)

	// Same path, same handler, explicit open proposer — must render
	// differently from the gated default above.
	openAuth := NewRestrictedContractAuthority(
		"gno.land/r/test",
		func(title string, action PrivilegedAction) error { return nil },
		NewAutoAcceptAuthority(),
	)
	uassert.Equal(t,
		"contract_authority[contract=gno.land/r/test,proposer=auto_accept_authority]",
		openAuth.String())
	uassert.NotEqual(t, contractStr, openAuth.String())

	// AutoAcceptAuthority
	autoAuth := NewAutoAcceptAuthority()
	autoStr := autoAuth.String()
	expectedAutoStr := "auto_accept_authority"
	uassert.Equal(t, autoStr, expectedAutoStr)

	// DroppedAuthority
	droppedAuth := NewDroppedAuthority()
	droppedStr := droppedAuth.String()
	expectedDroppedStr := "dropped_authority"
	uassert.Equal(t, droppedStr, expectedDroppedStr)
}

// TestContractAuthorityUnauthorizedCaller verifies the
// fix: a ContractAuthority's default proposer is the contract itself, so
// any other caller is rejected UPSTREAM (at the proposer) and the handler
// and privileged action never run. Previously the default proposer was
// AutoAcceptAuthority, and the only guard was a handler-side
// `unsafe.CurrentRealm() == contractAddr` check — which was bypassable
// and which many consumers (e.g. r/gnops/valopers) omitted entirely,
// leaving no caller check at all.
func TestContractAuthorityUnauthorizedCaller(cur realm, t *testing.T) {
	contractPath := "gno.land/r/testcontract"
	contractAddr := chain.PackageAddress(contractPath)
	unauthorizedAddr := testutils.TestAddress("unauthorized")

	// A permissive handler that simply runs the action — the realistic
	// shape a consumer registers. The package, not the handler, must be
	// the one that rejects an unauthorized caller.
	handlerExecuted := false
	contractHandler := func(title string, action PrivilegedAction) error {
		handlerExecuted = true
		return action()
	}
	contractAuth := NewContractAuthority(contractPath, contractHandler)

	actionExecuted := false
	privilegedAction := func() error {
		actionExecuted = true
		return nil
	}

	// 1. Unauthorized caller: rejected by the contract-identity proposer
	// before the handler or the action can run.
	err := contractAuth.Authorize(unauthorizedAddr, "test_action", privilegedAction)
	uassert.Error(t, err, "unauthorized caller must be rejected")
	uassert.ErrorContains(t, err, "unauthorized", "rejection must come from the contract-identity proposer")
	uassert.False(t, handlerExecuted, "handler must not run for an unauthorized caller")
	uassert.False(t, actionExecuted, "privileged action must not run for an unauthorized caller")

	// 2. The contract itself is authorized.
	err = contractAuth.Authorize(contractAddr, "test_action", privilegedAction)
	uassert.NoError(t, err, "the contract itself must be authorized")
	uassert.True(t, handlerExecuted, "handler must run when the contract is the caller")
	uassert.True(t, actionExecuted, "privileged action must run when the contract is the caller")
}

// TestAuthorizerDoByPrevious verifies the "calling realm authorizes"
// pattern: a function (the inner crossing closure) invokes
// DoByPrevious so the authority check sees cur.Previous() — the realm
// that crossed into it — not the function's own realm.
//
// Each scenario crosses into the inner closure via cross(cur) after
// SetRealm — inside the closure, cur is the fresh live cur and
// cur.Previous() is the SetRealm'd outer realm. This is the only way
// to exercise DoByPrevious correctly under the IsCurrent guard, which
// rejects synthetic realm values (testing.MakeRealm) and stored
// stale captures.
func TestAuthorizerDoByPrevious(cur realm, t *testing.T) {
	alice := testutils.TestAddress("alice")
	bob := testutils.TestAddress("bob")

	auth := NewWithMembers(alice)

	// alice (member) crosses in: cur.Previous() == alice inside the inner closure.
	testing.SetRealm(testing.NewUserRealm(alice))
	executed := false
	args := []any{"test_arg", 123}
	func(cur realm) {
		err := auth.DoByPrevious(0, cur, "test_action", func() error {
			executed = true
			return nil
		}, args...)
		uassert.NoError(t, err, "expected no error")
		uassert.True(t, executed, "action should have been executed")
	}(cross(cur))

	expectedErr := errors.New("test error")
	func(cur realm) {
		err := auth.DoByPrevious(0, cur, "test_action", func() error {
			return expectedErr
		})
		uassert.ErrorContains(t, err, expectedErr.Error(), "expected error")
	}(cross(cur))

	// bob (not a member) crosses in: Authorize must reject.
	testing.SetRealm(testing.NewUserRealm(bob))
	executed = false
	func(cur realm) {
		err := auth.DoByPrevious(0, cur, "test_action", func() error {
			executed = true
			return nil
		}, "unauthorized_arg")
		uassert.ErrorContains(t, err, "unauthorized", "expected error")
		uassert.False(t, executed, "action should not have been executed")
	}(cross(cur))
}

// ---------------------------------------------------------------------------
// Contract-identity gate: regression suite.
//
// A plain NewContractAuthority now defaults its proposer to the contract
// ITSELF (MemberAuthority of the contract's own package address) instead of
// AutoAcceptAuthority. These tests pin the security contract: only the
// contract may drive privileged actions, an external caller can neither
// drive nor Transfer the authority, the contract can still rotate its own
// authority, and the escape hatch for a genuinely-open proposer still
// exists.
// ---------------------------------------------------------------------------

// The default proposer accepts the contract itself and rejects everyone
// else, before the handler or action can run.
func TestDefaultProposerIsContractOnly(cur realm, t *testing.T) {
	const path = "gno.land/r/defcontract"
	contractAddr := chain.PackageAddress(path)

	ran := 0
	ca := NewContractAuthority(path, func(_ string, action PrivilegedAction) error {
		return action()
	})

	// The contract itself: authorized.
	err := ca.Authorize(contractAddr, "action", func() error { ran++; return nil })
	uassert.NoError(t, err, "the contract itself must be authorized")

	// Anyone else: rejected at the proposer, action never runs.
	outsider := testutils.TestAddress("outsider")
	err = ca.Authorize(outsider, "action", func() error { ran++; return nil })
	uassert.Error(t, err, "a non-contract caller must be rejected")
	uassert.ErrorContains(t, err, "unauthorized", "rejection must come from the contract-identity proposer")

	uassert.Equal(t, 1, ran, "only the contract's action must have run")
}

// An external realm that holds another realm's Authorizer cannot Transfer
// it. The caller derived under IsCurrent is that external realm, not the
// contract, so the rotation is rejected and the authority is left intact.
func TestExternalTransferRejected(cur realm, t *testing.T) {
	authorizer := NewWithAuthority(
		NewContractAuthority("gno.land/r/victim", func(_ string, action PrivilegedAction) error {
			return action()
		}),
	)

	attacker := testutils.TestAddress("attacker")
	testing.SetRealm(testing.NewUserRealm(attacker))

	var err error
	func(cur realm) { err = authorizer.Transfer(0, cur, NewDroppedAuthority()) }(cross(cur))

	uassert.Error(t, err, "external Transfer must be rejected")
	uassert.ErrorContains(t, err, "unauthorized", "rejection must come from the contract-identity proposer")

	_, ok := authorizer.Authority().(*ContractAuthority)
	uassert.True(t, ok, "authority must be unchanged after a rejected rotation")
}

// Same shape via DoByPrevious (a privileged action instead of a
// Transfer): an external caller is rejected and the action never runs.
func TestExternalDoByPreviousRejected(cur realm, t *testing.T) {
	authorizer := NewWithAuthority(
		NewContractAuthority("gno.land/r/victim2", func(_ string, action PrivilegedAction) error {
			return action()
		}),
	)

	ran := false
	testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("randomuser")))
	var err error
	func(cur realm) {
		err = authorizer.DoByPrevious(0, cur, "privileged", func() error { ran = true; return nil })
	}(cross(cur))

	uassert.Error(t, err, "external DoByPrevious must be rejected")
	uassert.False(t, ran, "privileged action must not run for an external caller")
}

// The contract-identity model does NOT lock out legitimate governance: the
// contract can still rotate (Transfer) its own authority when the transfer
// is driven with the contract as the previous realm (caller == contractAddr).
func TestContractCanRotateItsOwnAuthority(cur realm, t *testing.T) {
	const path = "gno.land/r/selfgov"
	authorizer := NewWithAuthority(
		NewContractAuthority(path, func(_ string, action PrivilegedAction) error {
			return action()
		}),
	)

	// Drive the transfer with the contract as the caller: set the outer
	// realm to the contract, then cross into a closure so cur.Previous()
	// resolves to the contract.
	testing.SetRealm(testing.NewCodeRealm(path))
	var err error
	func(cur realm) { err = authorizer.Transfer(0, cur, NewAutoAcceptAuthority()) }(cross(cur))

	uassert.NoError(t, err, "the contract itself must be able to rotate its authority")
	_, ok := authorizer.Authority().(*AutoAcceptAuthority)
	uassert.True(t, ok, "authority should have rotated to auto-accept")
}

// Boundary test: the raw Authority.Authorize takes `caller` as a plain
// parameter, so a holder of the raw Authority can forge caller ==
// contractAddr. This proves that even so, a forged-caller raw Authorize
// only runs the action the caller itself supplies — it CANNOT mutate an
// Authorizer's installed authority, because the Transfer mutation lives
// only inside Authorizer.Transfer (which derives caller non-forgeably).
// The lesson encoded here: consumers must reach a ContractAuthority through
// the Authorizer wrapper and must not hand out the raw Authority.
//
// WHAT THIS TEST DOES AND DOES NOT FREEZE. Only the final assertion is a
// security property. That raw Authorize ACCEPTS a forged caller is
// current behaviour, not a guarantee — it is the consequence of `caller`
// being a parameter on an exported interface method. If someone later
// hardens that path so raw Authorize stops accepting a forged caller,
// this test going red means the test is stale, NOT that the change is
// wrong: delete the two intermediate assertions and keep the last one.
// (Recorded because asserting NoError here reads like the forgeability
// is wanted. It is tolerated, and only because of what follows.)
func TestForgedCallerCannotTransfer(cur realm, t *testing.T) {
	const path = "gno.land/r/boundary"
	contractAddr := chain.PackageAddress(path)

	authorizer := NewWithAuthority(
		NewContractAuthority(path, func(_ string, action PrivilegedAction) error {
			return action()
		}),
	)

	// Attacker obtains the raw Authority and forges the contract as caller.
	attackerRan := false
	err := authorizer.Authority().Authorize(contractAddr, "transfer_authority", func() error {
		attackerRan = true
		return nil
	})

	// Current behaviour, documented above — not a property to preserve.
	uassert.NoError(t, err, "raw Authorize currently accepts a forged caller (see comment)")
	uassert.True(t, attackerRan, "only the caller's own inert closure runs")

	// THE property: the installed authority is UNCHANGED. Raw Authorize
	// cannot perform a Transfer — the mutation closure is private to
	// Authorizer.Transfer, which derives caller non-forgeably.
	_, ok := authorizer.Authority().(*ContractAuthority)
	uassert.True(t, ok, "raw Authorize must not be able to transfer the authority")
}

// Two contract authorities on different paths never cross-authorize.
func TestContractPathIsolation(cur realm, t *testing.T) {
	caB := NewContractAuthority("gno.land/r/pathb", func(_ string, action PrivilegedAction) error {
		return action()
	})
	addrA := chain.PackageAddress("gno.land/r/patha")

	ran := false
	err := caB.Authorize(addrA, "action", func() error { ran = true; return nil })
	uassert.Error(t, err, "contract A must not authorize contract B's authority")
	uassert.False(t, ran, "action must not run across contract identities")
}

// Escape hatch: a consumer that genuinely wants open proposals can still
// opt in via NewRestrictedContractAuthority with an AutoAcceptAuthority
// proposer — restoring the pre-fix "anyone can propose" behavior explicitly.
func TestRestrictedAutoAcceptEscapeHatch(cur realm, t *testing.T) {
	ca := NewRestrictedContractAuthority(
		"gno.land/r/open",
		func(_ string, action PrivilegedAction) error { return action() },
		NewAutoAcceptAuthority(),
	)

	ran := false
	err := ca.Authorize(testutils.TestAddress("anyone"), "action", func() error { ran = true; return nil })
	uassert.NoError(t, err, "an explicit AutoAccept proposer restores open proposals")
	uassert.True(t, ran, "action must run under an explicit AutoAccept proposer")
}

// Why the nil handler is now rejected at construction rather than
// tolerated: Authorize checks contractHandler == nil BEFORE consulting the
// proposer, and Transfer routes through Authorize, so there is no rotation
// path out. It is a permanent brick reachable by an ordinary deployer
// typo -- the same bricked-governance failure mode, by accident.
//
// The zero value is used because the constructor no longer allows it.
func TestNilHandlerWouldBeUnrotatable(cur realm, t *testing.T) {
	const path = "gno.land/r/nilbrick"
	addr := chain.PackageAddress(path)
	authorizer := NewWithAuthority(&ContractAuthority{
		contractPath: path,
		contractAddr: addr,
		// Both handler and proposer are nil: a struct literal is the only
		// way to reach this, and Authorize fails closed on either.
	})

	// Drive the rotation as the contract itself -- the only principal the
	// default proposer accepts. If this cannot escape, nobody can.
	testing.SetRealm(testing.NewCodeRealm(path))
	var err error
	func(cur realm) { err = authorizer.Transfer(0, cur, NewAutoAcceptAuthority()) }(cross(cur))

	uassert.Error(t, err, "a nil-handler authority must not be silently rotatable")
	_, stuck := authorizer.Authority().(*ContractAuthority)
	uassert.True(t, stuck, "nil-handler authority is unrotatable -- hence rejected at construction")
}

// A crossing closure declared HERE carries this package's identity, not
// the contract path's -- testing.SetRealm does not change that, because
// the VM mints a crossing frame's realm from the callee's declaring
// package. So the DoByCurrent shape that Example_contractAuthority teaches
// cannot be exercised from inside this package at all; it needs a real
// realm. It is covered by filetests/z_contract_authority_shape_filetest.gno.
//
// The same property is why an exported crossing closure leaks a realm's
// authority to any caller -- it is one mechanism seen from two
// sides. This test pins the half that is observable here: an unrelated
// package's frame is rejected.
func TestForeignFrameCannotDriveContractAuthority(cur realm, t *testing.T) {
	auth := NewWithAuthority(NewContractAuthority("gno.land/r/demo/dao", mockDAOHandler))

	testing.SetRealm(testing.NewCodeRealm("gno.land/r/example"))
	ran := false
	var err error
	func(cur realm) {
		err = auth.DoByCurrent(0, cur, "update_params", func() error {
			ran = true
			return nil
		})
	}(cross(cur))

	uassert.Error(t, err, "a frame from another package must not drive this authority")
	uassert.False(t, ran, "the action must not run")
}

// A malformed contract path binds the authority to an address no realm can
// ever present. Because Transfer routes through the same gate, such an
// authority is also unrotatable: a permanent brick, and the same failure
// mode the nil-handler panic exists to prevent. Rejected at construction.
//
// Pre-fix these all constructed happily; the AutoAccept default made the
// typo harmless (and insecure), so nothing complained.
func TestContractPathValidationRejectsMalformed(cur realm, t *testing.T) {
	handler := func(_ string, action PrivilegedAction) error { return action() }

	for _, path := range []string{
		"gno.land/r/gov/dao ",  // trailing space
		" gno.land/r/gov/dao",  // leading space
		"gno.land/r/gov/dao\n", // trailing newline
		"gno.land/r/gov dao",   // embedded space
		" ",
		"not a path",
		"GNO.LAND/R/GOV/DAO", // uppercase: not a legal gno pkgpath
		"gno.land//r/gov/dao",
		"gno.land/r/gov/dao/",
		"singlesegment",
	} {
		uassert.PanicsContains(t, cur, "contract path", func() {
			NewContractAuthority(path, handler)
		}, "malformed path must be rejected: "+path)
		uassert.PanicsContains(t, cur, "contract path", func() {
			NewRestrictedContractAuthority(path, handler, NewAutoAcceptAuthority())
		}, "malformed path must be rejected by the restricted ctor too: "+path)
	}

	// Real paths still construct, including dashes, digits, underscores and
	// version suffixes.
	for _, path := range []string{
		"gno.land/r/gov/dao",
		"gno.land/r/gnops/valopers",
		"gno.land/p/nym-moultest123/authz/v0",
		"gno.land/r/sys/validators/v0",
		"gno.land/r/some-user/my_pkg2",
	} {
		uassert.NotPanics(t, cur, func() {
			NewContractAuthority(path, handler)
		}, "legitimate path must construct: "+path)
	}
}

// spoofProposer is a wide-open Authority that LIES in String(), returning
// the same text the canonical contract-identity default renders.
type spoofProposer struct{}

func (spoofProposer) Authorize(caller address, title string, action PrivilegedAction, args ...any) error {
	return action()
}

func (spoofProposer) String() string { return "contract-identity" }

// A foreign proposer must not be able to impersonate the gated default in
// the rendered description. ContractAuthority.String() is promoted by this
// package as the one surface distinguishing a gated authority from a
// wide-open one, and consumers assert on it (r/gnops/valopers.Auth()). An
// impl that chooses its own String() text defeated that: a fully permissive
// authority rendered byte-identical to the default, so every string-based
// configuration pin stayed green while the gate was gone.
func TestSpoofedProposerCannotImpersonateContractIdentity(cur realm, t *testing.T) {
	const path = "gno.land/r/spoofprobe"
	handler := func(_ string, action PrivilegedAction) error { return action() }
	outsider := chain.PackageAddress("gno.land/r/outsider")

	gated := NewContractAuthority(path, handler)
	spoof := NewRestrictedContractAuthority(path, handler, spoofProposer{})

	// The behavioural difference the strings must reflect.
	uassert.Error(t, gated.Authorize(outsider, "t", func() error { return nil }),
		"the gated default must reject an outsider")
	uassert.NoError(t, spoof.Authorize(outsider, "t", func() error { return nil }),
		"the spoofing proposer is wide open -- that is the point of the test")

	// ...and they do.
	uassert.NotEqual(t, gated.String(), spoof.String(),
		"a wide-open authority must not render identically to the gated default")
	uassert.Equal(t,
		"contract_authority[contract="+path+",proposer=contract-identity]",
		gated.String())
	uassert.Equal(t,
		"contract_authority[contract="+path+",proposer=custom_authority[contract-identity]]",
		spoof.String(),
		"a non-canonical proposer must be wrapped, not trusted to name itself")

	// Same guarantee through the Authorizer wrapper, which is the shape a
	// consumer realm actually exposes.
	uassert.NotEqual(t,
		NewWithAuthority(gated).String(),
		NewWithAuthority(spoof).String())
}

// An explicit proposer REPLACES the contract-identity gate; it does not add
// to it. NewRestrictedContractAuthority(govdaoPath, h, member(alice)) means
// "alice, and not GovDAO" -- contractAddr is never consulted. Pinned because
// the rendered string reads like a conjunction and the old godoc said
// "widen", so a consumer could reasonably have expected "both".
func TestExplicitProposerReplacesIdentityGate(cur realm, t *testing.T) {
	const path = "gno.land/r/gov/dao"
	handler := func(_ string, action PrivilegedAction) error { return action() }
	govdao := chain.PackageAddress(path)
	alice := chain.PackageAddress("gno.land/r/alice")

	gated := NewContractAuthority(path, handler)
	replaced := NewRestrictedContractAuthority(path, handler, NewMemberAuthority(alice))

	uassert.NoError(t, gated.Authorize(govdao, "x", func() error { return nil }),
		"the default gate accepts the bound contract")
	uassert.Error(t, gated.Authorize(alice, "x", func() error { return nil }),
		"the default gate rejects everyone else")

	uassert.Error(t, replaced.Authorize(govdao, "x", func() error { return nil }),
		"an explicit proposer REPLACES the identity gate: govdao is no longer accepted")
	uassert.NoError(t, replaced.Authorize(alice, "x", func() error { return nil }),
		"only the explicit proposer's principal is accepted")
}

example_test.gno

package authz

// Example_basic demonstrates initializing and using a basic member authority
func Example_basic(cur realm) {
	// Initialize from the EOA caller (e.g. in init(cur realm) of a realm
	// being deployed): caller passes the EOA address; the realm itself
	// is responsible for verifying the caller is an EOA when needed.
	auth := NewWithMembers(cur.Previous().Address())

	// Authorize with DoByPrevious, NOT DoByCurrent: the member set holds
	// cur.Previous().Address(), and DoByCurrent would present
	// cur.Address() -- this realm -- which is never in that set, so the
	// action would silently never run. Seeding and authorizing must read
	// the SAME side of the frame. Matches the package Quick Start.
	if err := auth.DoByPrevious(0, cur, "update_config", func() error {
		// config = newValue
		return nil
	}); err != nil {
		panic(err)
	}
}

// Example_addingMembers demonstrates how to add new members to a member authority
func Example_addingMembers(cur realm) {
	// Seed with Previous(), not Address(): MemberAuthority.AddMember
	// derives its principal as rlm.Previous().Address(), so a set holding
	// only cur.Address() authorizes nobody and the AddMember below fails.
	auth := NewWithMembers(cur.Previous().Address())

	// Add a new member to the authority
	memberAuth := auth.Authority().(*MemberAuthority)
	if err := memberAuth.AddMember(0, cur, address("g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5")); err != nil {
		panic(err)
	}
}

// Example_contractAuthority demonstrates a contract-based authority.
//
// A plain NewContractAuthority accepts exactly one principal:
// chain.PackageAddress(path). Point `path` at the principal you want to
// ASSERT -- normally the governance realm that will drive the action --
// and authorize with DoByPrevious, so the comparison is against whoever
// crossed in. See NewContractAuthority's godoc.
//
// Do NOT pair a plain ContractAuthority on your OWN path with
// DoByCurrent. rlm.Address() inside any crossing frame of a realm is
// unconditionally PackageAddress(ownPath), so that gate compares the
// realm to itself, can never reject, and any exported crossing
// entrypoint next to it becomes an unauthenticated privileged write --
// the self-comparing-gate shape. Own-path is right only when something
// OTHER than your own frame supplies the caller, i.e. DoByPrevious from
// a realm you deliberately let call in, or Transfer.
//
// Nothing here catches a wrong pairing: Example_* functions that take
// any parameter are never executed by `gno test` (see isExampleFunc in
// gnovm/pkg/test/test.go -- it rejects on method receiver, parameters or
// results; "// Output:" plays no part in the predicate, so adding one
// does NOT make the body run), so a sentinel panic in here still reports
// ok. filetests/z_contract_authority_shape_filetest.gno executes the
// gate from a real realm instead.
//
// Corollary of the identity gate: do not export anything that returns a
// crossing closure of this realm, or callers inherit the authority.
func Example_contractAuthority(cur realm) {
	// This realm asserts "the governance realm governs me".
	auth := NewWithAuthority(
		NewContractAuthority(
			"gno.land/r/gov/dao", // the principal asserted, not this realm
			mockDAOHandler,       // defined elsewhere for example
		),
	)

	// Authorized only when gno.land/r/gov/dao is the realm that crossed
	// into this function -- in practice, when a passed proposal executes.
	// Every other caller presents its own address here and is refused,
	// which is the whole point of the gate. Never discard this error.
	if err := auth.DoByPrevious(0, cur, "update_params", func() error {
		return nil
	}); err != nil {
		panic(err)
	}
}

// Example_restrictedContractAuthority demonstrates a contract authority with member-only proposals
func Example_restrictedContractAuthority(cur realm) {
	// Initialize member authority for proposers
	proposerAuth := NewMemberAuthority(
		address("g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5"), // admin1
		address("g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj"), // admin2
	)

	// Create contract authority with restricted proposers
	auth := NewWithAuthority(
		NewRestrictedContractAuthority(
			"gno.land/r/demo/dao",
			mockDAOHandler,
			proposerAuth,
		),
	)

	// Only members can propose, and contract must approve.
	//
	// DoByPrevious, not DoByCurrent: the proposer set holds EOA
	// addresses, and DoByCurrent would present this realm's own address,
	// which is in no member set -- the proposer would reject and the
	// action would silently never run.
	if err := auth.DoByPrevious(0, cur, "update_params", func() error {
		// Executes after:
		// 1. Proposer initiates
		// 2. DAO approves
		return nil
	}); err != nil {
		panic(err)
	}
}

// Example_switchingAuthority demonstrates switching from member to contract
// authority.
//
// Note what a plain ContractAuthority on a FOREIGN path means after the
// transfer: this realm loses the ability to take the authority back, and
// DoByCurrent against it is dead. It is NOT a one-way door in the
// stronger sense an earlier draft implied — the foreign realm can still
// drive and rotate it via Previous() once it crosses in, which is the
// intended async-DAO shape. What is given up is the original owner's
// claim, not the authority's mutability. (The ADR for this change states
// the same thing; keep the two in step.) To keep the authority here
// while letting others propose, transfer to
// NewRestrictedContractAuthority(ownPath, handler, proposerAuth)
// instead.
func Example_switchingAuthority(cur realm) {
	// Start with member authority.
	//
	// Seed the member set with Previous(), not Address(): Transfer
	// derives its principal as rlm.Previous().Address(), so a set
	// containing only cur.Address() authorizes nobody but a
	// same-package cross-call, and the Transfer below would abort for
	// every external caller — including a realm that copies this into
	// init(cur realm), which then fails its deploy tx. Matches
	// Example_basic and NewWithMembers' godoc.
	auth := NewWithMembers(cur.Previous().Address())

	// Create and switch to contract authority — control moves to
	// gno.land/r/demo/dao.
	daoAuthority := NewContractAuthority(
		"gno.land/r/demo/dao",
		mockDAOHandler,
	)
	if err := auth.Transfer(0, cur, daoAuthority); err != nil {
		panic(err)
	}
}

// Mock handler for examples
func mockDAOHandler(title string, action PrivilegedAction) error {
	return action()
}

gnomod.toml

module = "gno.land/p/nym-moultest123/authz/v0"
gno = "0.9"

[addpkg]
  creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv"
  height = 186409
  max_deposit = "30000000ugnot"