-
Notifications
You must be signed in to change notification settings - Fork 11
test: add integration tests for FullAccessKeyFallback
#66
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
2951d87
Add test contract
mooori 1c762cb
Add integration tests
mooori 33b4a2c
Remove unit tests
mooori 118de52
Make assert_full_access_keys independen of order
mooori f513dea
Comment on PublicKey conversion
mooori acb76d6
Fix clippy errors
mooori File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
35 changes: 35 additions & 0 deletions
35
near-plugins/tests/common/full_access_key_fallback_contract.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
21 changes: 21 additions & 0 deletions
21
near-plugins/tests/contracts/full_access_key_fallback/Cargo.toml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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] |
8 changes: 8 additions & 0 deletions
8
near-plugins/tests/contracts/full_access_key_fallback/Makefile
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
3 changes: 3 additions & 0 deletions
3
near-plugins/tests/contracts/full_access_key_fallback/rust-toolchain
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
21
near-plugins/tests/contracts/full_access_key_fallback/src/lib.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,179 @@ | ||
| // 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 { | ||
|
mooori marked this conversation as resolved.
|
||
| // Going via json since there seems to be no direct conversion, see this issue: | ||
| // https://github.com/near/workspaces-rs/issues/262 | ||
| #[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 plus | ||
| /// - the keys specified in `keys` | ||
| /// | ||
| /// with the order of keys being irrelevant. | ||
| /// | ||
| /// Moreover, it asserts that all access keys have `FullAccess` permission. | ||
| /// | ||
| /// Input parameter `keys` is expected to not contain duplicates. | ||
| async fn assert_full_access_keys(&self, keys: &[PublicKey]) { | ||
| // Assert the number of keys. | ||
| let access_key_infos = self | ||
| .contract | ||
| .view_access_keys() | ||
| .await | ||
| .expect("Should view access keys"); | ||
| assert_eq!( | ||
| access_key_infos.len(), | ||
| keys.len() + 1, // + 1 for the contract's key | ||
| ); | ||
|
|
||
| // Assert the attached access keys are the ones we expected and all have `FullAccess`. | ||
| // | ||
| // Since `workspaces::types::PublicKey` doesn't implement `Hash`, it cannot be stored in | ||
| // `std::collections::HashSet`. Hence the search in `access_key_infos` with | ||
| // `find()`. | ||
| let contract_key = self.contract.as_account().secret_key().public_key(); | ||
| let expected_keys = iter::once(&contract_key).chain(keys.iter()); | ||
| for expected_key in expected_keys { | ||
| let attached_key = access_key_infos | ||
| .iter() | ||
| .find(|info| &info.public_key == expected_key) | ||
| .unwrap_or_else(|| panic!("PublicKey {:?} is not attached", expected_key)); | ||
|
|
||
| assert!( | ||
| matches!( | ||
| attached_key.access_key.permission, | ||
| AccessKeyPermission::FullAccess, | ||
| ), | ||
| "Unexpected permission of access key {:?}: {:?}", | ||
| attached_key, | ||
| attached_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(()) | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.