Skip to content
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

feat(backend): Gate api methods #1807

Merged
merged 24 commits into from
Aug 6, 2024
Merged
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
4 changes: 4 additions & 0 deletions src/backend/backend.did
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ type AddUserCredentialRequest = record {
current_user_version : opt nat64;
credential_spec : CredentialSpec;
};
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We wish to be able to make features either fully enabled, fully disabled, or enabled for read methods only. This type is used to represent which of these states a feature is in.

type ApiEnabled = variant { ReadOnly; Enabled; Disabled };
type Arg = variant { Upgrade; Init : InitArg };
type ArgumentValue = variant { Int : int32; String : text };
type CanisterStatusResultV2 = record {
Expand All @@ -25,6 +26,7 @@ type CanisterStatusResultV2 = record {
};
type CanisterStatusType = variant { stopped; stopping; running };
type Config = record {
api : opt Guards;
ecdsa_key_name : text;
allowed_callers : vec principal;
supported_credentials : opt vec SupportedCredential;
Expand All @@ -48,6 +50,7 @@ type DefiniteCanisterSettingsArgs = record {
compute_allocation : nat;
};
type GetUserProfileError = variant { NotFound };
type Guards = record { user_data : ApiEnabled; threshold_key : ApiEnabled };
type HttpRequest = record {
url : text;
method : text;
Expand All @@ -61,6 +64,7 @@ type HttpResponse = record {
};
type IcrcToken = record { ledger_id : principal; index_id : opt principal };
type InitArg = record {
api : opt Guards;
ecdsa_key_name : text;
allowed_callers : vec principal;
supported_credentials : opt vec SupportedCredential;
Expand Down
45 changes: 45 additions & 0 deletions src/backend/src/guards.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,48 @@ pub fn caller_is_allowed() -> Result<(), String> {
Err("Caller is not allowed.".to_string())
}
}

/// User data writes are locked during and after a migration away to another canister.
pub fn may_write_user_data() -> Result<(), String> {
caller_is_not_anonymous()?;
if read_config(|s| s.api.unwrap_or_default().user_data.writable()) {
Ok(())
} else {
Err("User data is in read only mode due to a migration.".to_string())
}
}

/// User data writes are locked during and after a migration away to another canister.
pub fn may_read_user_data() -> Result<(), String> {
caller_is_not_anonymous()?;
if read_config(|s| s.api.unwrap_or_default().user_data.readable()) {
Ok(())
} else {
Err("User data cannot be read at this time due to a migration.".to_string())
}
}

/// Is getting threshold public keys is enabled?
pub fn may_read_threshold_keys() -> Result<(), String> {
caller_is_not_anonymous()?;
if read_config(|s| s.api.unwrap_or_default().threshold_key.readable()) {
Ok(())
} else {
Err("Reading threshold keys is disabled.".to_string())
}
}
/// Caller is allowed AND reading threshold keys is enabled.
pub fn caller_is_allowed_and_may_read_threshold_keys() -> Result<(), String> {
caller_is_allowed()?;
may_read_threshold_keys()
}

/// Is signing with threshold keys is enabled?
pub fn may_threshold_sign() -> Result<(), String> {
caller_is_not_anonymous()?;
if read_config(|s| s.api.unwrap_or_default().threshold_key.writable()) {
Ok(())
} else {
Err("Threshold signing is disabled.".to_string())
}
}
37 changes: 20 additions & 17 deletions src/backend/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
use crate::assertions::{assert_token_enabled_is_some, assert_token_symbol_length};
use crate::guards::{caller_is_allowed, caller_is_not_anonymous};
use crate::guards::{
caller_is_allowed, caller_is_allowed_and_may_read_threshold_keys, may_read_threshold_keys,
may_read_user_data, may_threshold_sign, may_write_user_data,
};
use crate::token::{add_to_user_token, remove_from_user_token};
use candid::{Nat, Principal};
use config::find_credential_config;
Expand Down Expand Up @@ -216,13 +219,13 @@ fn parse_eth_address(address: &str) -> [u8; 20] {
}

/// Returns the Ethereum address of the caller.
#[update(guard = "caller_is_not_anonymous")]
#[update(guard = "may_read_threshold_keys")]
async fn caller_eth_address() -> String {
pubkey_bytes_to_address(&ecdsa_pubkey_of(&ic_cdk::caller()).await)
}

/// Returns the Ethereum address of the specified .
#[update(guard = "caller_is_allowed")]
/// Returns the Ethereum address of the specified user.
#[update(guard = "caller_is_allowed_and_may_read_threshold_keys")]
async fn eth_address_of(p: Principal) -> String {
if p == Principal::anonymous() {
ic_cdk::trap("Anonymous principal is not authorized");
Expand Down Expand Up @@ -261,7 +264,7 @@ async fn pubkey_and_signature(caller: &Principal, message_hash: Vec<u8>) -> (Vec
}

/// Computes a signature for an [EIP-1559](https://eips.ethereum.org/EIPS/eip-1559) transaction.
#[update(guard = "caller_is_not_anonymous")]
#[update(guard = "may_threshold_sign")]
async fn sign_transaction(req: SignRequest) -> String {
use ethers_core::types::transaction::eip1559::Eip1559TransactionRequest;
use ethers_core::types::Signature;
Expand Down Expand Up @@ -309,7 +312,7 @@ async fn sign_transaction(req: SignRequest) -> String {
}

/// Computes a signature for a hex-encoded message according to [EIP-191](https://eips.ethereum.org/EIPS/eip-191).
#[update(guard = "caller_is_not_anonymous")]
#[update(guard = "may_threshold_sign")]
async fn personal_sign(plaintext: String) -> String {
let caller = ic_cdk::caller();

Expand All @@ -334,7 +337,7 @@ async fn personal_sign(plaintext: String) -> String {
}

/// Computes a signature for a precomputed hash.
#[update(guard = "caller_is_not_anonymous")]
#[update(guard = "may_threshold_sign")]
async fn sign_prehash(prehash: String) -> String {
let caller = ic_cdk::caller();

Expand All @@ -349,7 +352,7 @@ async fn sign_prehash(prehash: String) -> String {
format!("0x{}", hex::encode(&signature))
}

#[update(guard = "caller_is_not_anonymous")]
#[update(guard = "may_write_user_data")]
#[allow(clippy::needless_pass_by_value)]
fn set_user_token(token: UserToken) {
assert_token_symbol_length(&token).unwrap_or_else(|e| ic_cdk::trap(&e));
Expand All @@ -366,7 +369,7 @@ fn set_user_token(token: UserToken) {
mutate_state(|s| add_to_user_token(stored_principal, &mut s.user_token, &token, &find));
}

#[update(guard = "caller_is_not_anonymous")]
#[update(guard = "may_write_user_data")]
fn set_many_user_tokens(tokens: Vec<UserToken>) {
let stored_principal = StoredPrincipal(ic_cdk::caller());

Expand All @@ -385,7 +388,7 @@ fn set_many_user_tokens(tokens: Vec<UserToken>) {
});
}

#[update(guard = "caller_is_not_anonymous")]
#[update(guard = "may_write_user_data")]
#[allow(clippy::needless_pass_by_value)]
fn remove_user_token(token_id: UserTokenId) {
let addr = parse_eth_address(&token_id.contract_address);
Expand All @@ -398,14 +401,14 @@ fn remove_user_token(token_id: UserTokenId) {
mutate_state(|s| remove_from_user_token(stored_principal, &mut s.user_token, &find));
}

#[query(guard = "caller_is_not_anonymous")]
#[query(guard = "may_read_user_data")]
fn list_user_tokens() -> Vec<UserToken> {
let stored_principal = StoredPrincipal(ic_cdk::caller());
read_state(|s| s.user_token.get(&stored_principal).unwrap_or_default().0)
}

/// Add, remove or update custom token for the user.
#[update(guard = "caller_is_not_anonymous")]
#[update(guard = "may_write_user_data")]
#[allow(clippy::needless_pass_by_value)]
fn set_custom_token(token: CustomToken) {
let stored_principal = StoredPrincipal(ic_cdk::caller());
Expand All @@ -417,7 +420,7 @@ fn set_custom_token(token: CustomToken) {
mutate_state(|s| add_to_user_token(stored_principal, &mut s.custom_token, &token, &find));
}

#[update(guard = "caller_is_not_anonymous")]
#[update(guard = "may_write_user_data")]
fn set_many_custom_tokens(tokens: Vec<CustomToken>) {
let stored_principal = StoredPrincipal(ic_cdk::caller());

Expand All @@ -432,13 +435,13 @@ fn set_many_custom_tokens(tokens: Vec<CustomToken>) {
});
}

#[query(guard = "caller_is_not_anonymous")]
#[query(guard = "may_read_user_data")]
fn list_custom_tokens() -> Vec<CustomToken> {
let stored_principal = StoredPrincipal(ic_cdk::caller());
read_state(|s| s.custom_token.get(&stored_principal).unwrap_or_default().0)
}

#[update(guard = "caller_is_not_anonymous")]
#[update(guard = "may_write_user_data")]
#[allow(clippy::needless_pass_by_value)]
fn add_user_credential(request: AddUserCredentialRequest) -> Result<(), AddUserCredentialError> {
let user_principal = ic_cdk::caller();
Expand Down Expand Up @@ -474,7 +477,7 @@ fn add_user_credential(request: AddUserCredentialRequest) -> Result<(), AddUserC

/// It create a new user profile for the caller.
/// If the user has already a profile, it will return that profile.
#[update(guard = "caller_is_not_anonymous")]
#[update(guard = "may_write_user_data")]
fn create_user_profile() -> UserProfile {
let stored_principal = StoredPrincipal(ic_cdk::caller());

Expand All @@ -486,7 +489,7 @@ fn create_user_profile() -> UserProfile {
})
}

#[query(guard = "caller_is_not_anonymous")]
#[query(guard = "may_read_user_data")]
fn get_user_profile() -> Result<UserProfile, GetUserProfileError> {
let stored_principal = StoredPrincipal(ic_cdk::caller());

Expand Down
1 change: 1 addition & 0 deletions src/backend/tests/it/upgrade/credentials_init_args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ fn test_upgrade_credential_init_args() {
allowed_callers: allowed_callers.clone(),
ic_root_key_der: None,
supported_credentials: None,
api: None,
});
let encoded_updated_arg = encode_one(updated_arg).unwrap();

Expand Down
1 change: 1 addition & 0 deletions src/backend/tests/it/utils/pocketic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ pub(crate) fn init_arg() -> Arg {
issuer_origin: ISSUER_ORIGIN.to_string(),
credential_type: CredentialType::ProofOfUniqueness,
}]),
api: None,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bitdivine: Will you add some integration tests that exercise the API disabling?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Disabling APIs matters in the migration, so I was going to test that in the migration e2e tests. After the migration is complete I expect all of this will be deleted again. 😄

})
}

Expand Down
4 changes: 4 additions & 0 deletions src/declarations/backend/backend.did
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ type AddUserCredentialRequest = record {
current_user_version : opt nat64;
credential_spec : CredentialSpec;
};
type ApiEnabled = variant { ReadOnly; Enabled; Disabled };
type Arg = variant { Upgrade; Init : InitArg };
type ArgumentValue = variant { Int : int32; String : text };
type CanisterStatusResultV2 = record {
Expand All @@ -25,6 +26,7 @@ type CanisterStatusResultV2 = record {
};
type CanisterStatusType = variant { stopped; stopping; running };
type Config = record {
api : opt Guards;
ecdsa_key_name : text;
allowed_callers : vec principal;
supported_credentials : opt vec SupportedCredential;
Expand All @@ -48,6 +50,7 @@ type DefiniteCanisterSettingsArgs = record {
compute_allocation : nat;
};
type GetUserProfileError = variant { NotFound };
type Guards = record { user_data : ApiEnabled; threshold_key : ApiEnabled };
type HttpRequest = record {
url : text;
method : text;
Expand All @@ -61,6 +64,7 @@ type HttpResponse = record {
};
type IcrcToken = record { ledger_id : principal; index_id : opt principal };
type InitArg = record {
api : opt Guards;
ecdsa_key_name : text;
allowed_callers : vec principal;
supported_credentials : opt vec SupportedCredential;
Expand Down
7 changes: 7 additions & 0 deletions src/declarations/backend/backend.did.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export interface AddUserCredentialRequest {
current_user_version: [] | [bigint];
credential_spec: CredentialSpec;
}
export type ApiEnabled = { ReadOnly: null } | { Enabled: null } | { Disabled: null };
export type Arg = { Upgrade: null } | { Init: InitArg };
export type ArgumentValue = { Int: number } | { String: string };
export interface CanisterStatusResultV2 {
Expand All @@ -28,6 +29,7 @@ export interface CanisterStatusResultV2 {
}
export type CanisterStatusType = { stopped: null } | { stopping: null } | { running: null };
export interface Config {
api: [] | [Guards];
ecdsa_key_name: string;
allowed_callers: Array<Principal>;
supported_credentials: [] | [Array<SupportedCredential>];
Expand All @@ -51,6 +53,10 @@ export interface DefiniteCanisterSettingsArgs {
compute_allocation: bigint;
}
export type GetUserProfileError = { NotFound: null };
export interface Guards {
user_data: ApiEnabled;
threshold_key: ApiEnabled;
}
export interface HttpRequest {
url: string;
method: string;
Expand All @@ -67,6 +73,7 @@ export interface IcrcToken {
index_id: [] | [Principal];
}
export interface InitArg {
api: [] | [Guards];
ecdsa_key_name: string;
allowed_callers: Array<Principal>;
supported_credentials: [] | [Array<SupportedCredential>];
Expand Down
21 changes: 21 additions & 0 deletions src/declarations/backend/backend.factory.certified.did.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
// @ts-ignore
export const idlFactory = ({ IDL }) => {
const ApiEnabled = IDL.Variant({
ReadOnly: IDL.Null,
Enabled: IDL.Null,
Disabled: IDL.Null
});
const Guards = IDL.Record({
user_data: ApiEnabled,
threshold_key: ApiEnabled
});
const CredentialType = IDL.Variant({ ProofOfUniqueness: IDL.Null });
const SupportedCredential = IDL.Record({
ii_canister_id: IDL.Principal,
Expand All @@ -9,6 +18,7 @@ export const idlFactory = ({ IDL }) => {
credential_type: CredentialType
});
const InitArg = IDL.Record({
api: IDL.Opt(Guards),
ecdsa_key_name: IDL.Text,
allowed_callers: IDL.Vec(IDL.Principal),
supported_credentials: IDL.Opt(IDL.Vec(SupportedCredential)),
Expand Down Expand Up @@ -37,6 +47,7 @@ export const idlFactory = ({ IDL }) => {
Err: AddUserCredentialError
});
const Config = IDL.Record({
api: IDL.Opt(Guards),
ecdsa_key_name: IDL.Text,
allowed_callers: IDL.Vec(IDL.Principal),
supported_credentials: IDL.Opt(IDL.Vec(SupportedCredential)),
Expand Down Expand Up @@ -161,6 +172,15 @@ export const idlFactory = ({ IDL }) => {
};
// @ts-ignore
export const init = ({ IDL }) => {
const ApiEnabled = IDL.Variant({
ReadOnly: IDL.Null,
Enabled: IDL.Null,
Disabled: IDL.Null
});
const Guards = IDL.Record({
user_data: ApiEnabled,
threshold_key: ApiEnabled
});
const CredentialType = IDL.Variant({ ProofOfUniqueness: IDL.Null });
const SupportedCredential = IDL.Record({
ii_canister_id: IDL.Principal,
Expand All @@ -170,6 +190,7 @@ export const init = ({ IDL }) => {
credential_type: CredentialType
});
const InitArg = IDL.Record({
api: IDL.Opt(Guards),
ecdsa_key_name: IDL.Text,
allowed_callers: IDL.Vec(IDL.Principal),
supported_credentials: IDL.Opt(IDL.Vec(SupportedCredential)),
Expand Down
Loading