Repository navigation
Expand file tree
/
Copy pathaccess.rs
More file actions
299 lines (270 loc) · 10.9 KB
/
Copy pathaccess.rs
File metadata and controls
299 lines (270 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
//! Common access-control checks shared across contracts (issue #825).
//!
//! Before this module every contract hand-rolled the same three lines:
//!
//! ```ignore
//! admin.require_auth();
//! let stored_admin: Address = env.storage().instance().get(&DataKey::Admin).unwrap();
//! assert!(admin == stored_admin, "Only admin can do the thing");
//! ```
//!
//! The storage *key* differs per contract (each has its own `DataKey` enum), so
//! these helpers take the key as a generic parameter rather than assuming one.
//! That keeps the storage slot explicit at the call site while the auth check,
//! the missing-admin case, and the panic message live in exactly one place:
//!
//! ```ignore
//! access::require_admin(&env, &admin, &DataKey::Admin);
//! ```
//!
//! # Invariants
//!
//! - **Authorization Requirement**: All access-control checks require cryptographic proof via `require_auth()`.
//! - **Fail-Closed**: Unauthorized access attempts result in immediate panics; no partial state changes.
//! - **Immutability of Slots**: Once an authority (admin, arbiter, owner) is stored, identity mismatches are fatal.
//! - **Explicit Storage Keys**: The key for each authority slot is passed explicitly to prevent key collisions.
//! - **Clear Error Messages**: Each function produces a distinct panic message that aids debugging.
//!
//! Panic messages are string literals rather than named constants on purpose:
//! `assert!(cond, LITERAL)` compiles to a static-string panic, whereas
//! `assert!(cond, "{}", SOME_CONST)` drags `core::fmt` into the contract wasm.
//! Each message is documented on the function that raises it.
use soroban_sdk::{Address, Env, IntoVal, Val};
/// Reads the `Address` stored at `key` in instance storage.
///
/// # Invariants Enforced
///
/// - **Initialization Check**: Panics if the storage slot is uninitialized (empty).
/// - **Deterministic Failure**: Uses a human-readable message to distinguish this error from others.
///
/// Panics with `"Not initialized"` if the slot is empty, which is a clearer
/// failure than the bare `.unwrap()` this replaces.
pub fn read_authority<K>(env: &Env, key: &K) -> Address
where
K: IntoVal<Env, Val>,
{
env.storage().instance().get(key).expect("Not initialized")
}
/// Returns whether `caller` is the admin stored at `admin_key`.
///
/// # Invariants Enforced
///
/// - **Pure Predicate**: This is a read-only check; no auth requirement, no side effects.
/// - **Identity-Based**: Direct address comparison; no role inheritance or delegation.
/// - **Initialization Check**: Panics if the admin slot is not yet initialized.
///
/// Pure predicate: it neither requires auth nor panics on a mismatch. Use it to
/// build a compound check; use [`require_admin`] to gate an entry point.
///
/// Panics with `"Not initialized"` if the admin slot is empty.
pub fn is_admin<K>(env: &Env, caller: &Address, admin_key: &K) -> bool
where
K: IntoVal<Env, Val>,
{
*caller == read_authority(env, admin_key)
}
/// Requires that `caller` authorized this invocation and is the stored admin.
///
/// # Invariants Enforced
///
/// - **Authorization Requirement**: The caller must provide cryptographic proof via `require_auth()`.
/// - **Identity Verification**: The caller's address must match the stored admin address exactly.
/// - **Atomic Checks**: Both authorization and identity are verified together; partial success is impossible.
/// - **Fail-Closed**: If either check fails, the contract halts immediately with a panic.
/// - **Initialization Check**: Panics clearly if the admin slot is not yet initialized.
///
/// Panics with `"Unauthorized: admin required"` otherwise.
pub fn require_admin<K>(env: &Env, caller: &Address, admin_key: &K)
where
K: IntoVal<Env, Val>,
{
caller.require_auth();
assert!(
is_admin(env, caller, admin_key),
"Unauthorized: admin required"
);
}
/// Requires that `caller` authorized this invocation and is the address held in
/// a non-admin authority slot — a dispute arbiter, an oracle, a fee collector.
///
/// # Invariants Enforced
///
/// - **Authorization Requirement**: The caller must provide cryptographic proof via `require_auth()`.
/// - **Role Separation**: This checks a distinct role slot, not the admin role.
/// - **Single-Role Assignment**: Only one address may hold the authority role at a time.
/// - **Initialization Check**: Panics clearly if the authority slot is not yet initialized.
///
/// Panics with `"Unauthorized: authority required"` otherwise.
pub fn require_authority<K>(env: &Env, caller: &Address, authority_key: &K)
where
K: IntoVal<Env, Val>,
{
caller.require_auth();
assert!(
*caller == read_authority(env, authority_key),
"Unauthorized: authority required"
);
}
/// Requires that `caller` authorized this invocation and is either the stored
/// admin or `permitted` — e.g. an escrow that both its payer and the admin may
/// cancel.
///
/// # Invariants Enforced
///
/// - **Authorization Requirement**: The caller must provide cryptographic proof via `require_auth()`.
/// - **Dual-Approval Pattern**: Either the admin or the permitted address may proceed.
/// - **No Implicit Roles**: Holding one role does not grant the other; checks are independent.
/// - **Short-Circuit Evaluation**: Once one condition passes, no further checks occur.
///
/// Panics with `"Unauthorized: admin or permitted caller required"` otherwise.
pub fn require_admin_or<K>(env: &Env, caller: &Address, admin_key: &K, permitted: &Address)
where
K: IntoVal<Env, Val>,
{
caller.require_auth();
assert!(
caller == permitted || is_admin(env, caller, admin_key),
"Unauthorized: admin or permitted caller required"
);
}
/// Requires that `caller` authorized this invocation and owns the resource.
///
/// # Invariants Enforced
///
/// - **Authorization Requirement**: The caller must provide cryptographic proof via `require_auth()`.
/// - **Ownership Verification**: The caller's address must match the resource owner's address exactly.
/// - **No Admin Override**: This check does not grant the admin any special privileges; only the owner may pass.
/// - **Per-Resource Check**: Ownership is verified for a specific resource, not globally.
///
/// `owner` is read by the caller from whatever per-resource key the contract
/// uses (`DataKey::NFTOwner(id)`, a listing's `seller`, ...), so this helper
/// covers only the auth-and-compare half.
///
/// Panics with `"Unauthorized: owner required"` otherwise.
pub fn require_owner(caller: &Address, owner: &Address) {
caller.require_auth();
assert!(caller == owner, "Unauthorized: owner required");
}
#[cfg(test)]
mod tests {
use super::*;
use soroban_sdk::{contract, contractimpl, contracttype, testutils::Address as _};
#[contracttype]
enum TestKey {
Admin,
Arbiter,
}
/// Thin wrapper contract so the helpers are exercised through a real
/// invocation frame — `require_auth` needs one.
#[contract]
struct AccessTestContract;
#[contractimpl]
impl AccessTestContract {
pub fn init(env: Env, admin: Address) {
env.storage().instance().set(&TestKey::Admin, &admin);
}
pub fn set_arbiter(env: Env, arbiter: Address) {
env.storage().instance().set(&TestKey::Arbiter, &arbiter);
}
pub fn admin_only(env: Env, caller: Address) {
require_admin(&env, &caller, &TestKey::Admin);
}
pub fn arbiter_only(env: Env, caller: Address) {
require_authority(&env, &caller, &TestKey::Arbiter);
}
pub fn admin_or(env: Env, caller: Address, permitted: Address) {
require_admin_or(&env, &caller, &TestKey::Admin, &permitted);
}
pub fn owner_only(_env: Env, caller: Address, owner: Address) {
require_owner(&caller, &owner);
}
pub fn check_is_admin(env: Env, caller: Address) -> bool {
is_admin(&env, &caller, &TestKey::Admin)
}
pub fn read_admin(env: Env) -> Address {
read_authority(&env, &TestKey::Admin)
}
}
fn setup() -> (Env, AccessTestContractClient<'static>, Address) {
let env = Env::default();
env.mock_all_auths();
let id = env.register_contract(None, AccessTestContract);
let client = AccessTestContractClient::new(&env, &id);
let admin = Address::generate(&env);
client.init(&admin);
(env, client, admin)
}
#[test]
fn admin_passes_require_admin() {
let (_, client, admin) = setup();
client.admin_only(&admin);
assert!(client.check_is_admin(&admin));
assert_eq!(client.read_admin(), admin);
}
#[test]
#[should_panic(expected = "Unauthorized: admin required")]
fn non_admin_fails_require_admin() {
let (env, client, _) = setup();
let intruder = Address::generate(&env);
client.admin_only(&intruder);
}
#[test]
fn is_admin_is_false_for_other_address() {
let (env, client, _) = setup();
let other = Address::generate(&env);
assert!(!client.check_is_admin(&other));
}
#[test]
#[should_panic(expected = "Not initialized")]
fn empty_slot_reports_not_initialized() {
let (_, client, admin) = setup();
// The `Arbiter` slot was never written.
client.arbiter_only(&admin);
}
#[test]
fn authority_slot_is_checked_independently_of_admin() {
let (env, client, _) = setup();
let arbiter = Address::generate(&env);
client.set_arbiter(&arbiter);
client.arbiter_only(&arbiter);
// Holding the arbiter slot does not make an address the admin.
assert!(!client.check_is_admin(&arbiter));
}
#[test]
#[should_panic(expected = "Unauthorized: authority required")]
fn admin_is_not_automatically_the_authority() {
let (env, client, admin) = setup();
let arbiter = Address::generate(&env);
client.set_arbiter(&arbiter);
client.arbiter_only(&admin);
}
#[test]
fn require_admin_or_accepts_both_parties() {
let (env, client, admin) = setup();
let payer = Address::generate(&env);
client.admin_or(&admin, &payer);
client.admin_or(&payer, &payer);
}
#[test]
#[should_panic(expected = "Unauthorized: admin or permitted caller required")]
fn require_admin_or_rejects_third_party() {
let (env, client, _) = setup();
let payer = Address::generate(&env);
let intruder = Address::generate(&env);
client.admin_or(&intruder, &payer);
}
#[test]
fn require_owner_accepts_owner() {
let (env, client, _) = setup();
let owner = Address::generate(&env);
client.owner_only(&owner, &owner);
}
#[test]
#[should_panic(expected = "Unauthorized: owner required")]
fn require_owner_rejects_non_owner() {
let (env, client, _) = setup();
let owner = Address::generate(&env);
let intruder = Address::generate(&env);
client.owner_only(&intruder, &owner);
}
}