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(CoSigner): implementing contract-call and native-token-transfer permissions check #809

Merged
merged 3 commits into from
Oct 15, 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
55 changes: 19 additions & 36 deletions integration/sessions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,18 @@ import { ethers } from "ethers"
import { canonicalize } from 'json-canonicalize';
import { createSign, createPrivateKey } from 'crypto';

const contractCallPermission = {
type: "contract-call",
data: {
address:"0x2E65BAfA07238666c3b239E94F32DaD3cDD6498D",
}
}

const permissionContext = "0x00"

describe('Sessions/Permissions', () => {
const { baseUrl, projectId, httpClient } = getTestSetup();
const address = `eip155:1:${ethers.Wallet.createRandom().address}`;
// Session payload
const payload = {
permission: {
permissionType: "exampleType",
data: "exampleData",
required: true,
onChainValidated: false
}
}
// New session PCI
let new_pci: string;
// New session signing (private) key
Expand All @@ -27,18 +27,8 @@ describe('Sessions/Permissions', () => {
type: "k256",
data: "0x"
},
permissions: [
{
type: "custom",
data: "0x"
}
],
policies: [
{
type: "custom",
data: "0x"
}
]
permissions: [contractCallPermission],
policies: []
}

let resp: any = await httpClient.post(
Expand Down Expand Up @@ -74,19 +64,9 @@ describe('Sessions/Permissions', () => {
type: "k256",
data: "0x"
},
permissions: [
{
type: "custom",
data: "0x"
}
],
policies: [
{
type: "custom",
data: "0x"
}
],
context: "0x00"
permissions: [contractCallPermission],
policies: [],
context: permissionContext
}

let resp: any = await httpClient.post(
Expand All @@ -102,7 +82,7 @@ describe('Sessions/Permissions', () => {
`${baseUrl}/v1/sessions/${address}/getcontext?projectId=${projectId}&pci=${new_pci}`
)
expect(resp.status).toBe(200)
expect(resp.data.context).toBe('0x00')
expect(resp.data.context).toBe(permissionContext)
})

it('revoke PCI permission', async () => {
Expand All @@ -113,6 +93,7 @@ describe('Sessions/Permissions', () => {
expect(resp.status).toBe(200)
expect(resp.data.pcis.length).toBe(1)
expect(resp.data.pcis[0].pci).toBe(new_pci)
expect(resp.data.pcis[0].revokedAt).toBe(null)

let payload = {
pci: new_pci,
Expand All @@ -130,6 +111,8 @@ describe('Sessions/Permissions', () => {
`${baseUrl}/v1/sessions/${address}?projectId=${projectId}`
)
expect(resp.status).toBe(200)
expect(resp.data.pcis.length).toBe(0)
expect(resp.data.pcis.length).toBe(1)
// Check revokedAt is fullfilled
expect(typeof resp.data.pcis[0].revokedAt).toBe('number')
})
})
46 changes: 45 additions & 1 deletion src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,18 @@ pub enum RpcError {

#[error("Permission context was not updated yet: {0}")]
PermissionContextNotUpdated(String),

#[error("Permission is revoked: {0}")]
RevokedPermission(String),

#[error("Cosigner permission denied: {0}")]
CosignerPermissionDenied(String),

#[error("Cosigner unsupported permission: {0}")]
CosignerUnsupportedPermission(String),

#[error("ABI decoding error: {0}")]
AbiDecodingError(String),
}

impl IntoResponse for RpcError {
Expand Down Expand Up @@ -480,7 +492,15 @@ impl IntoResponse for RpcError {
)),
)
.into_response()
},
},
Self::RevokedPermission(pci) => (
StatusCode::BAD_REQUEST,
Json(new_error_response(
"pci".to_string(),
format!("Permission is revoked: {}", pci),
)),
)
.into_response(),
Self::WrongBase64Format(e) => (
StatusCode::BAD_REQUEST,
Json(new_error_response(
Expand All @@ -505,6 +525,14 @@ impl IntoResponse for RpcError {
)),
)
.into_response(),
Self::AbiDecodingError(e) => (
StatusCode::BAD_REQUEST,
Json(new_error_response(
"calldata".to_string(),
format!("ABI signature decoding error: {}", e),
)),
)
.into_response(),
Self::TransactionProviderError => (
StatusCode::SERVICE_UNAVAILABLE,
Json(new_error_response(
Expand Down Expand Up @@ -553,6 +581,22 @@ impl IntoResponse for RpcError {
)),
)
.into_response(),
Self::CosignerPermissionDenied(e) => (
StatusCode::UNAUTHORIZED,
Json(new_error_response(
"".to_string(),
format!("Cosigner permission denied: {}", e),
)),
)
.into_response(),
Self::CosignerUnsupportedPermission(e) => (
StatusCode::UNAUTHORIZED,
Json(new_error_response(
"".to_string(),
format!("Unsupported permission in CoSigner: {}", e),
)),
)
.into_response(),
// Any other errors considering as 500
_ => (
StatusCode::INTERNAL_SERVER_ERROR,
Expand Down
51 changes: 46 additions & 5 deletions src/handlers/sessions/cosign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,17 @@ use {
error::RpcError,
state::AppState,
storage::irn::OperationType,
utils::crypto::{
abi_encode_two_bytes_arrays, call_get_user_op_hash, disassemble_caip10,
is_address_valid, pack_signature, to_eip191_message, CaipNamespaces, ChainId,
UserOperation,
utils::{
crypto::{
abi_encode_two_bytes_arrays, call_get_user_op_hash, disassemble_caip10,
is_address_valid, pack_signature, to_eip191_message, CaipNamespaces, ChainId,
UserOperation,
},
permissions::{
contract_call_permission_check, native_token_transfer_permission_check,
ContractCallPermissionData, NativeTokenTransferPermissionData, PermissionType,
},
sessions::extract_execution_batch_components,
},
},
axum::{
Expand All @@ -23,7 +30,8 @@ use {
},
serde::{Deserialize, Serialize},
serde_json::json,
std::{sync::Arc, time::SystemTime},
std::{str::FromStr, sync::Arc, time::SystemTime},
tracing::debug,
wc::future::FutureExt,
};

Expand Down Expand Up @@ -139,6 +147,39 @@ async fn handler_internal(
.add_irn_latency(irn_call_start, OperationType::Hget);
let storage_permissions_item =
serde_json::from_str::<StoragePermissionsItem>(&storage_permissions_item)?;
let call_data = request_payload.user_op.call_data.clone();

// Extract the batch components
let execution_batch = extract_execution_batch_components(call_data.to_vec())?;

// Check permissions by types
for permission in storage_permissions_item.permissions {
match PermissionType::from_str(permission.r#type.as_str()) {
Ok(permission_type) => match permission_type {
PermissionType::ContractCall => {
debug!("Executing contract call permission check");
contract_call_permission_check(
execution_batch.clone(),
serde_json::from_value::<ContractCallPermissionData>(
permission.data.clone(),
)?,
)?;
}
PermissionType::NativeTokenTransfer => {
debug!("Executing native token transfer permission check");
native_token_transfer_permission_check(
execution_batch.clone(),
serde_json::from_value::<NativeTokenTransferPermissionData>(
permission.data.clone(),
)?,
)?;
}
},
Err(_) => {
return Err(RpcError::CosignerUnsupportedPermission(permission.r#type));
}
}
}

// Check and get the permission context if it's updated
let _permission_context = storage_permissions_item
Expand Down
1 change: 1 addition & 0 deletions src/handlers/sessions/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ async fn handler_internal(
context: None,
verification_key: public_key_der_hex.clone(),
signing_key: private_key_der_hex.clone(),
revoked_at: None,
};

let irn_call_start = SystemTime::now();
Expand Down
2 changes: 2 additions & 0 deletions src/handlers/sessions/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ struct Pci {
pub permissions: Vec<PermissionTypeData>,
pub policies: Vec<PermissionTypeData>,
pub context: Option<Bytes>,
pub revoked_at: Option<usize>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
Expand Down Expand Up @@ -107,6 +108,7 @@ async fn handler_internal(
permissions: storage_permissions_item.permissions,
policies: storage_permissions_item.policies,
context: storage_permissions_item.context,
revoked_at: storage_permissions_item.revoked_at,
});
}

Expand Down
1 change: 1 addition & 0 deletions src/handlers/sessions/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ pub struct StoragePermissionsItem {
context: Option<Bytes>,
verification_key: String,
signing_key: String,
revoked_at: Option<usize>,
}

/// Permission revoke request schema
Expand Down
46 changes: 40 additions & 6 deletions src/handlers/sessions/revoke.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
use {
super::{super::HANDLER_TASK_METRICS, PermissionRevokeRequest, QueryParams},
super::{
super::HANDLER_TASK_METRICS, PermissionRevokeRequest, QueryParams, StoragePermissionsItem,
},
crate::{
error::RpcError, state::AppState, storage::irn::OperationType,
utils::crypto::disassemble_caip10,
},
axum::{
extract::{Path, Query, State},
response::Response,
response::{IntoResponse, Response},
Json,
},
std::{sync::Arc, time::SystemTime},
Expand Down Expand Up @@ -39,12 +41,44 @@ async fn handler_internal(
// Checking the CAIP-10 address format
disassemble_caip10(&address)?;

// Remove the session/permission item from the IRN
// Get the PCI object from the IRN
let irn_call_start = SystemTime::now();
let storage_permissions_item = irn_client
.hget(address.clone(), request_payload.pci.clone())
.await?
.ok_or_else(|| {
RpcError::PermissionNotFound(address.clone(), request_payload.pci.clone())
})?;
state
.metrics
.add_irn_latency(irn_call_start, OperationType::Hget);
let mut storage_permissions_item =
serde_json::from_str::<StoragePermissionsItem>(&storage_permissions_item)?;

if storage_permissions_item.revoked_at.is_some() {
return Err(RpcError::RevokedPermission(request_payload.pci.clone()));
}

// Update the revoked_at field
storage_permissions_item.revoked_at = Some(
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or(std::time::Duration::new(0, 0))
.as_secs() as usize,
);

// Store it back to the IRN database
let irn_call_start = SystemTime::now();
irn_client.hdel(address, request_payload.pci).await?;
irn_client
.hset(
address,
request_payload.pci,
serde_json::to_string(&storage_permissions_item)?.into(),
)
.await?;
state
.metrics
.add_irn_latency(irn_call_start, OperationType::Hdel);
.add_irn_latency(irn_call_start, OperationType::Hset);

Ok(Response::default())
Ok(().into_response())
}
2 changes: 2 additions & 0 deletions src/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ use rand::{distributions::Alphanumeric, Rng};
pub mod build;
pub mod crypto;
pub mod network;
pub mod permissions;
pub mod rate_limit;
pub mod sessions;

pub fn generate_random_string(len: usize) -> String {
let rng = rand::thread_rng();
Expand Down
Loading
Loading