Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
44 changes: 0 additions & 44 deletions near-plugins/src/full_access_key_fallback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,47 +42,3 @@ impl AsEvent<FullAccessKeyAdded> for FullAccessKeyAdded {
}
}
}

#[cfg(not(target_arch = "wasm32"))]
#[cfg(test)]
mod tests {
// TODO: Make simulation test that verifies key get's added to the account
Comment thread
birchmd marked this conversation as resolved.
use crate as near_plugins;
use crate::test_utils::get_context;
use crate::{FullAccessKeyFallback, Ownable};
use near_sdk::{near_bindgen, testing_env, PublicKey};
use std::convert::TryInto;
use std::str::FromStr;

#[near_bindgen]
#[derive(Ownable, FullAccessKeyFallback)]
struct Contract;

fn key() -> PublicKey {
PublicKey::from_str("ed25519:6E8sCci9badyRkXb3JoRpBj5p8C6Tw41ELDZoiihKEtp").unwrap()
}

#[test]
#[should_panic(expected = r#"Ownable: Method must be called from owner"#)]
fn not_owner() {
let ctx = get_context();
testing_env!(ctx);

let mut contract = Contract;
contract.attach_full_access_key(key());
}

#[test]
fn simple() {
let mut ctx = get_context();
testing_env!(ctx.clone());

let mut contract = Contract;
contract.owner_set(Some("carol.test".to_string().try_into().unwrap()));

ctx.predecessor_account_id = "carol.test".to_string().try_into().unwrap();
testing_env!(ctx);

contract.attach_full_access_key(key());
}
}
35 changes: 35 additions & 0 deletions near-plugins/tests/common/full_access_key_fallback_contract.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
use near_sdk::serde_json::json;
use near_sdk::PublicKey;
use workspaces::result::ExecutionFinalResult;
use workspaces::{Account, Contract};

/// Wrapper for a contract that uses `#[full_access_key_fallback]`. It allows implementing helpers
/// for calling contract methods.
pub struct FullAccessKeyFallbackContract {
contract: Contract,
}

impl FullAccessKeyFallbackContract {
pub fn new(contract: Contract) -> Self {
Self { contract }
}

pub fn contract(&self) -> &Contract {
&self.contract
}

/// The `Promise` returned by trait method `attach_full_access_key` is resolved in the
/// workspaces transaction.
pub async fn attach_full_access_key(
&self,
caller: &Account,
public_key: PublicKey,
) -> workspaces::Result<ExecutionFinalResult> {
caller
.call(self.contract.id(), "attach_full_access_key")
.args_json(json!({ "public_key": public_key }))
.max_gas()
.transact()
.await
}
}
1 change: 1 addition & 0 deletions near-plugins/tests/common/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
pub mod access_controllable_contract;
pub mod full_access_key_fallback_contract;
pub mod ownable_contract;
pub mod pausable_contract;
pub mod repo;
Expand Down
21 changes: 21 additions & 0 deletions near-plugins/tests/contracts/full_access_key_fallback/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
[package]
name = "full_access_key_fallback"
version = "0.0.0"
edition = "2018"

[lib]
crate-type = ["cdylib", "rlib"]

[dependencies]
near-plugins = { path = "../../../../near-plugins" }
near-sdk = "4.1.0"

[profile.release]
codegen-units = 1
opt-level = "z"
lto = true
debug = false
panic = "abort"
overflow-checks = true

[workspace]
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
build:
cargo build --target wasm32-unknown-unknown --release

# Helpful for debugging. Requires `cargo-expand`.
expand:
cargo expand > expanded.rs

.PHONY: build expand
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[toolchain]
channel = "1.66.1"
components = ["clippy", "rustfmt"]
21 changes: 21 additions & 0 deletions near-plugins/tests/contracts/full_access_key_fallback/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
use near_plugins::{FullAccessKeyFallback, Ownable};
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::{near_bindgen, AccountId, PanicOnDefault};

/// Deriving `FullAccessKeyFallback` requires the contract to be `Ownable.`
#[near_bindgen]
#[derive(Ownable, FullAccessKeyFallback, PanicOnDefault, BorshDeserialize, BorshSerialize)]
pub struct Counter;

#[near_bindgen]
impl Counter {
/// Optionally set the owner in the constructor.
#[init]
pub fn new(owner: Option<AccountId>) -> Self {
let mut contract = Self;
if owner.is_some() {
contract.owner_set(owner);
}
contract
}
}
171 changes: 171 additions & 0 deletions near-plugins/tests/full_access_key_fallback.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
// Using `pub` to avoid invalid `dead_code` warnings, see
// https://users.rust-lang.org/t/invalid-dead-code-warning-for-submodule-in-integration-test/80259
pub mod common;

use anyhow::Ok;
use common::full_access_key_fallback_contract::FullAccessKeyFallbackContract;
use common::utils::{assert_only_owner_permission_failure, assert_success_with_unit_return};
use near_sdk::serde::Deserialize;
use near_sdk::serde_json::{from_value, json};
use std::iter;
use std::path::Path;
use workspaces::network::Sandbox;
use workspaces::types::{AccessKeyPermission, PublicKey};
use workspaces::{Account, AccountId, Contract, Worker};

const PROJECT_PATH: &str = "./tests/contracts/full_access_key_fallback";

/// Returns a new PublicKey that can be used in tests.
///
/// It returns a `near_sdk::PublicKey` since that's the type required for
/// `FullAccessKeyFallback::attach_full_access_key`.
fn new_public_key() -> near_sdk::PublicKey {
"ed25519:6E8sCci9badyRkXb3JoRpBj5p8C6Tw41ELDZoiihKEtp"
.parse()
.unwrap()
}

/// Converts a `near_sdk::PublicKey` to a `workspaces::types::PublicKey`.
fn pk_sdk_to_workspaces(public_key: near_sdk::PublicKey) -> PublicKey {
Comment thread
mooori marked this conversation as resolved.
#[derive(Deserialize)]
struct Wrapper {
public_key: PublicKey,
}

let ser = json!({ "public_key": public_key });
from_value::<Wrapper>(ser).unwrap().public_key
}

/// Allows spinning up a setup for testing the contract in [`PROJECT_PATH`] and bundles related
/// resources.
struct Setup {
/// Instance of the deployed contract.
contract: Contract,
/// Wrapper around the deployed contract that facilitates interacting with methods provided by
/// the `FullAccessKeyFallback` plugin.
fa_key_fallback_contract: FullAccessKeyFallbackContract,
/// A newly created account without any `Ownable` permissions.
unauth_account: Account,
}

impl Setup {
/// Deploys and initializes the contract in [`PROJECT_PATH`] and returns a new `Setup`.
///
/// The `owner` parameter is passed on to the contract's constructor, allowing to optionally set
/// the owner during initialization.
async fn new(worker: Worker<Sandbox>, owner: Option<AccountId>) -> anyhow::Result<Self> {
// Compile and deploy the contract.
let wasm =
common::repo::compile_project(Path::new(PROJECT_PATH), "full_access_key_fallback")
.await?;
let contract = worker.dev_deploy(&wasm).await?;
let fa_key_fallback_contract = FullAccessKeyFallbackContract::new(contract.clone());

// Call the contract's constructor.
contract
.call("new")
.args_json(json!({
"owner": owner,
}))
.max_gas()
.transact()
.await?
.into_result()?;

let unauth_account = worker.dev_create_account().await?;
Ok(Self {
contract,
fa_key_fallback_contract,
unauth_account,
})
}

/// Asserts the contract's access keys are:
///
/// - the contracts own key followed by
/// - the keys specified in `keys`
///
/// Moreover, it asserts that all access keys have `FullAccess` permission.
async fn assert_full_access_keys(&self, keys: &[PublicKey]) {
// Assert the number of keys.
let access_keys = self
.contract
.view_access_keys()
.await
.expect("Should view access keys");
assert_eq!(
access_keys.len(),
keys.len() + 1, // + 1 for the contract's key
);

// Assert the `access_keys` are the contract's key followed by `keys` (all full access).
let contract_key = self.contract.as_account().secret_key().public_key();
let expected_keys = iter::once(&contract_key).chain(keys.iter());
for (i, expected_key) in expected_keys.into_iter().enumerate() {
Comment thread
mooori marked this conversation as resolved.
Outdated
let access_key = &access_keys[i];
assert_eq!(
&access_key.public_key, expected_key,
"Unexpected PublicKey at index {}",
i
);
println!("looking at {:?}", expected_key);
assert!(
matches!(
access_key.access_key.permission,
AccessKeyPermission::FullAccess,
),
"Unexpected permission of access key at index {}: {:?}",
i,
access_key.access_key.permission,
);
}
}
}

/// Smoke test of contract setup.
#[tokio::test]
async fn test_setup() -> anyhow::Result<()> {
let worker = workspaces::sandbox().await?;
let _ = Setup::new(worker, None).await?;

Ok(())
}

#[tokio::test]
async fn test_non_owner_cannot_attach_full_access_key() -> anyhow::Result<()> {
let worker = workspaces::sandbox().await?;
let owner = worker.dev_create_account().await?;
let setup = Setup::new(worker, Some(owner.id().clone())).await?;

let new_fak = new_public_key();
let res = setup
.fa_key_fallback_contract
.attach_full_access_key(&setup.unauth_account, new_fak)
.await?;
assert_only_owner_permission_failure(res);

Ok(())
}

#[tokio::test]
async fn test_attach_full_access_key() -> anyhow::Result<()> {
let worker = workspaces::sandbox().await?;
let owner = worker.dev_create_account().await?;
let setup = Setup::new(worker, Some(owner.id().clone())).await?;

// Initially there's just the contract's access key.
setup.assert_full_access_keys(&[]).await;

// Owner may attach a full access key.
let new_fak = new_public_key();
let res = setup
.fa_key_fallback_contract
.attach_full_access_key(&owner, new_fak.clone())
.await?;
assert_success_with_unit_return(res);
setup
.assert_full_access_keys(&[pk_sdk_to_workspaces(new_fak)])
.await;

Ok(())
}