Skip to content

feat: let users to disable auth by PREDECESSOR_ID #69

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

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ defuse-randomness.path = "randomness"
defuse-test-utils.path = "test-utils"

anyhow = "1"
bitflags = "2.9.0"
bnum = { version = "0.13", features = ["borsh"] }
chrono = { version = "0.4", default-features = false }
derive_more = "2.0"
Expand Down Expand Up @@ -85,9 +86,10 @@ tokio = { version = "1.38", default-features = false }
[workspace.lints.clippy]
all = { level = "deny", priority = -1 }
pedantic = { level = "deny", priority = -1 }
module_name_repetitions = "allow"
missing_errors_doc = "allow"
missing_panics_doc = "allow"
module_name_repetitions = "allow"
must_use_candidate = "allow"


[profile.release]
Expand Down
22 changes: 12 additions & 10 deletions Makefile.toml
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
[config]
init_task = "add-cache-dir-tags"
default_to_workspace = false
skip_core_tasks = true

[env]
TARGET_DIR = "${PWD}/res"
TARGET_DIR = "${CARGO_MAKE_WORKSPACE_WORKING_DIRECTORY}/res"
POA_TOKEN_WASM = "${TARGET_DIR}/defuse_poa_token.wasm"
POA_TOKEN_WITH_NO_REGISTRATION_DIR = "${TARGET_DIR}/poa-token-no-registration"
POA_TOKEN_WASM_NO_REGISTRATION_WASM = "${POA_TOKEN_WITH_NO_REGISTRATION_DIR}/defuse_poa_token.wasm"
Expand All @@ -12,15 +13,18 @@ POA_TOKEN_WASM_NO_REGISTRATION_WASM = "${POA_TOKEN_WITH_NO_REGISTRATION_DIR}/def
alias = "build"

[tasks.clippy]
dependencies = ["add-cache-dir-tag"]
command = "cargo"
args = ["clippy", "--workspace", "--all-targets", "--no-deps"]

[tasks.build]
dependencies = ["add-cache-dir-tag", "build-defuse", "build-poa-factory", "contract-stats", "build-poa-token-no-registration"]
dependencies = [
"build-defuse",
"build-poa-factory",
"contract-stats",
"build-poa-token-no-registration",
]

[tasks.build-defuse]
dependencies = ["add-cache-dir-tag"]
command = "cargo"
args = [
"near",
Expand All @@ -37,7 +41,7 @@ args = [
]

[tasks.build-poa-factory]
dependencies = ["add-cache-dir-tag", "build-poa-token"]
dependencies = ["build-poa-token"]
command = "cargo"
args = [
"near",
Expand All @@ -54,7 +58,6 @@ args = [
]

[tasks.build-poa-token]
dependencies = ["add-cache-dir-tag"]
command = "cargo"
args = [
"near",
Expand All @@ -71,7 +74,6 @@ args = [
]

[tasks.build-poa-token-no-registration]
dependencies = ["add-cache-dir-tag"]
command = "cargo"
args = [
"near",
Expand Down Expand Up @@ -116,9 +118,9 @@ category = "Tools"
script = "cd ${TARGET_DIR} && du -ah *.wasm"

# We add CACHEDIR.TAG as it helps in making system level applications, e.g., backup systems, understand that this directory is just for disposable things.
[tasks.add-cache-dir-tag]
[tasks.add-cache-dir-tags]
condition = { platforms = ["linux", "mac"] }
script = [
"mkdir -p target res",
"echo 'Signature: 8a477f597d28d172789f06886806bc55' | tee target/CACHEDIR.TAG res/CACHEDIR.TAG > /dev/null"
"mkdir -p ${CARGO_MAKE_CRATE_TARGET_DIRECTORY} ${TARGET_DIR}",
"echo 'Signature: 8a477f597d28d172789f06886806bc55' | tee ${CARGO_MAKE_CRATE_TARGET_DIRECTORY}/CACHEDIR.TAG ${TARGET_DIR}/CACHEDIR.TAG > /dev/null",
]
3 changes: 3 additions & 0 deletions admin-utils/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,8 @@ edition.workspace = true
version.workspace = true
repository.workspace = true

[lints]
workspace = true

[dependencies]
near-sdk.workspace = true
3 changes: 3 additions & 0 deletions bitmap/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ edition.workspace = true
version.workspace = true
repository.workspace = true

[lints]
workspace = true

[dependencies]
defuse-map-utils.workspace = true

Expand Down
3 changes: 3 additions & 0 deletions controller/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,8 @@ edition.workspace = true
version.workspace = true
repository.workspace = true

[lints]
workspace = true

[dependencies]
near-sdk.workspace = true
3 changes: 3 additions & 0 deletions core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ edition.workspace = true
version.workspace = true
repository.workspace = true

[lints]
workspace = true

[dependencies]
defuse-bitmap.workspace = true
defuse-crypto = { workspace = true, features = ["serde"] }
Expand Down
27 changes: 27 additions & 0 deletions core/src/engine/state/cached.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,15 @@ where
.get(account_id)
.map_or_else(|| self.view.is_account_locked(account_id), Lock::is_locked)
}

fn is_auth_by_predecessor_id_disabled(&self, account_id: &AccountIdRef) -> bool {
let was_disabled = self.view.is_auth_by_predecessor_id_disabled(account_id);
let toggled = self
.accounts
.get(account_id)
.is_some_and(|a| a.as_inner_unchecked().auth_by_predecessor_id_toggled);
was_disabled ^ toggled
}
}

impl<W> State for CachedState<W>
Expand Down Expand Up @@ -300,6 +309,22 @@ where
)],
)
}

fn set_auth_by_predecessor_id(&mut self, account_id: AccountId, enable: bool) -> Result<bool> {
let was_disabled = self.is_auth_by_predecessor_id_disabled(&account_id);
let toggle = was_disabled ^ !enable;
if toggle {
self.accounts
.get_or_create(account_id.clone(), |owner_id| {
self.view.is_account_locked(owner_id)
})
.as_unlocked_mut()
.ok_or(DefuseError::AccountLocked(account_id))?
// toggle
.auth_by_predecessor_id_toggled ^= true;
}
Ok(!was_disabled)
}
}

#[derive(Debug, Default, Clone)]
Expand Down Expand Up @@ -338,6 +363,8 @@ impl CachedAccounts {
pub struct CachedAccount {
nonces: Nonces<HashMap<U248, U256>>,

auth_by_predecessor_id_toggled: bool,

public_keys_added: HashSet<PublicKey>,
public_keys_removed: HashSet<PublicKey>,

Expand Down
10 changes: 10 additions & 0 deletions core/src/engine/state/deltas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,11 @@ where
fn is_account_locked(&self, account_id: &AccountIdRef) -> bool {
self.state.is_account_locked(account_id)
}

#[inline]
fn is_auth_by_predecessor_id_disabled(&self, account_id: &AccountIdRef) -> bool {
self.state.is_auth_by_predecessor_id_disabled(account_id)
}
}

impl<S> State for Deltas<S>
Expand Down Expand Up @@ -170,6 +175,11 @@ where
) -> Result<()> {
self.state.storage_deposit(owner_id, storage_deposit)
}

#[inline]
fn set_auth_by_predecessor_id(&mut self, account_id: AccountId, enable: bool) -> Result<bool> {
self.state.set_auth_by_predecessor_id(account_id, enable)
}
}

/// Accumulates internal deposits and withdrawals on different tokens
Expand Down
8 changes: 8 additions & 0 deletions core/src/engine/state/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ pub trait StateView {

fn is_account_locked(&self, account_id: &AccountIdRef) -> bool;

/// Returns whether authentication by PREDECESSOR is disabled.
fn is_auth_by_predecessor_id_disabled(&self, account_id: &AccountIdRef) -> bool;

#[inline]
fn cached(self) -> CachedState<Self>
where
Expand Down Expand Up @@ -93,4 +96,9 @@ pub trait State: StateView {
owner_id: &AccountIdRef,
storage_deposit: StorageDeposit,
) -> Result<()>;

/// Sets whether authentication by `PREDECESSOR_ID` is enabled.
/// Returns whether authentication by `PREDECESSOR_ID` was enabled
/// before.
fn set_auth_by_predecessor_id(&mut self, account_id: AccountId, enable: bool) -> Result<bool>;
}
3 changes: 3 additions & 0 deletions core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,7 @@ pub enum DefuseError {

#[error("wrong verifying_contract")]
WrongVerifyingContract,

#[error("authentication by PREDECESSOR_ID is disabled for account '{0}'")]
AuthByPredecessorIdDisabled(AccountId),
}
7 changes: 6 additions & 1 deletion core/src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ use near_sdk::{near, serde::Deserialize};
use crate::{
accounts::{AccountEvent, PublicKeyEvent},
fees::{FeeChangedEvent, FeeCollectorChangedEvent},
intents::{IntentEvent, token_diff::TokenDiffEvent, tokens::Transfer},
intents::{
IntentEvent, account::SetAuthByPredecessorId, token_diff::TokenDiffEvent, tokens::Transfer,
},
};

#[must_use = "make sure to `.emit()` this event"]
Expand Down Expand Up @@ -40,6 +42,9 @@ pub enum DefuseEvent<'a> {
#[event_version("0.2.1")]
#[from(skip)]
AccountUnlocked(AccountEvent<'a, ()>),

#[event_version("0.2.1")]
SetAuthByPredecessorId(AccountEvent<'a, SetAuthByPredecessorId>),
}

pub trait DefuseIntentEmit<'a>: Into<DefuseEvent<'a>> {
Expand Down
32 changes: 32 additions & 0 deletions core/src/intents/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,35 @@ impl ExecutableIntent for InvalidateNonces {
.try_for_each(|n| engine.state.commit_nonce(signer_id.to_owned(), n))
}
}

#[cfg_attr(
all(feature = "abi", not(target_arch = "wasm32")),
serde_as(schemars = true)
)]
#[cfg_attr(
not(all(feature = "abi", not(target_arch = "wasm32"))),
serde_as(schemars = false)
)]
#[near(serializers = [borsh, json])]
#[derive(Debug, Clone)]
pub struct SetAuthByPredecessorId {
pub enable: bool,
}

impl ExecutableIntent for SetAuthByPredecessorId {
fn execute_intent<S, I>(
self,
signer_id: &AccountIdRef,
engine: &mut Engine<S, I>,
_intent_hash: CryptoHash,
) -> Result<()>
where
S: State,
I: Inspector,
{
engine
.state
.set_auth_by_predecessor_id(signer_id.to_owned(), self.enable)
.map(|_| ())
}
}
3 changes: 3 additions & 0 deletions crypto/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ edition.workspace = true
version.workspace = true
repository.workspace = true

[lints]
workspace = true

[dependencies]
ed25519-dalek.workspace = true
hex.workspace = true
Expand Down
6 changes: 4 additions & 2 deletions defuse/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ defuse-map-utils = { workspace = true, optional = true }
defuse-serde-utils.workspace = true
defuse-wnear = { workspace = true, optional = true }

bitflags = { workspace = true, optional = true }
bnum.workspace = true
derive_more.workspace = true
impl-tools.workspace = true
Expand All @@ -42,9 +43,10 @@ rstest.workspace = true
[features]
abi = ["defuse-core/abi"]
contract = [
"dep:defuse-wnear",
"dep:defuse-map-utils",
"dep:bitflags",
"dep:defuse-bitmap",
"dep:defuse-borsh-utils",
"dep:defuse-io-utils",
"dep:defuse-map-utils",
"dep:defuse-wnear",
]
15 changes: 14 additions & 1 deletion defuse/src/accounts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use defuse_serde_utils::base64::AsBase64;
use near_plugins::AccessControllable;
use near_sdk::{AccountId, ext_contract};

#[ext_contract(ext_public_key_manager)]
#[ext_contract(ext_account_manager)]
pub trait AccountManager {
/// Check if account has given public key
fn has_public_key(&self, account_id: &AccountId, public_key: &PublicKey) -> bool;
Expand All @@ -31,6 +31,19 @@ pub trait AccountManager {

/// NOTE: MUST attach 1 yⓃ for security purposes.
fn invalidate_nonces(&mut self, nonces: Vec<AsBase64<Nonce>>);

/// Returns whether authentication by PREDECESSOR_ID is disabled
/// for given `account_id`
fn is_auth_by_predecessor_id_disabled(&self, account_id: &AccountId) -> bool;

/// Disables authentication by PREDECESSOR_ID for the caller,
/// i.e. PREDECESSOR_ID itself.
///
/// **WARN**: Doing so might lock you out of your funds if
/// you don't have any other public_keys added to your account.
///
/// NOTE: MUST attach 1 yⓃ for security purposes.
fn disable_auth_by_predecessor_id(&mut self);
}

#[ext_contract(ext_force_account_locker)]
Expand Down
Loading
Loading