Skip to content

Commit ef7bcf7

Browse files
committed
chore: added filters for permissions, reverted logger
1 parent e32af29 commit ef7bcf7

File tree

7 files changed

+366
-159
lines changed

7 files changed

+366
-159
lines changed

packages/gator-permissions-snap/src/index.ts

Lines changed: 1 addition & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/* eslint-disable no-restricted-globals */
22
import type { GetSnapsResponse } from '@metamask/7715-permissions-shared/types';
3-
import { logger, logToFile } from '@metamask/7715-permissions-shared/utils';
3+
import { logger } from '@metamask/7715-permissions-shared/utils';
44
import {
55
AuthType,
66
JwtBearerAuth,
@@ -208,28 +208,8 @@ export const onRpcRequest: OnRpcRequestHandler = async ({
208208
request,
209209
}) => {
210210
logger.debug(`RPC request (origin="${origin}"): method="${request.method}"`);
211-
logToFile('SNAP================================================1');
212-
logger.debug('🔍 Detailed origin info:', {
213-
origin,
214-
originType: typeof origin,
215-
originLength: origin?.length,
216-
method: request.method,
217-
});
218-
logToFile('SNAP================================================2');
219-
// Special logging for revocation requests
220-
if (request.method === 'permissionsProvider_submitRevocation') {
221-
logger.debug('🚨 REVOCATION RPC REQUEST DETECTED 🚨');
222-
logger.debug('Origin:', origin);
223-
logger.debug('Origin type:', typeof origin);
224-
logger.debug('Method:', request.method);
225-
logger.debug('Params:', request.params);
226-
}
227211

228212
if (!isMethodAllowedForOrigin(origin, request.method)) {
229-
logger.debug('❌ Permission denied:', {
230-
origin,
231-
method: request.method,
232-
});
233213
throw new InvalidRequestError(
234214
`Origin '${origin}' is not allowed to call '${request.method}'`,
235215
);

packages/gator-permissions-snap/src/profileSync/profileSync.ts

Lines changed: 1 addition & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import { zPermissionResponse } from '@metamask/7715-permissions-shared/types';
55
import {
66
logger,
77
extractZodError,
8-
logToFile,
98
} from '@metamask/7715-permissions-shared/utils';
109
import {
1110
hashDelegation,
@@ -202,13 +201,10 @@ export function createProfileSyncManager(
202201
*/
203202
async function authenticate(): Promise<void> {
204203
try {
205-
logToFile('🔐 PROFILE SYNC: Starting authentication...');
206204
logger.debug('Profile Sync: Attempting to get access token');
207205
await auth.getAccessToken();
208-
logToFile('✅ PROFILE SYNC: Authentication successful');
209206
logger.debug('Profile Sync: Access token obtained successfully');
210207
} catch (error) {
211-
logToFile('❌ PROFILE SYNC: Authentication failed:', error);
212208
logger.error('Error fetching access token:', error);
213209
throw error;
214210
}
@@ -393,11 +389,6 @@ export function createProfileSyncManager(
393389
isRevoked: boolean,
394390
): Promise<void> {
395391
try {
396-
logToFile('🔄 PROFILE SYNC: Updating permission revocation status:', {
397-
delegationHash: existingPermission.permissionResponse.context,
398-
currentRevokedStatus: existingPermission.isRevoked,
399-
newRevokedStatus: isRevoked,
400-
});
401392
logger.debug('Profile Sync: Updating permission revocation status:', {
402393
existingPermission,
403394
isRevoked,
@@ -410,26 +401,16 @@ export function createProfileSyncManager(
410401
...existingPermission,
411402
isRevoked,
412403
};
413-
logToFile('📝 PROFILE SYNC: Created updated permission object:', {
414-
delegationHash: updatedPermission.permissionResponse.context,
415-
isRevoked: updatedPermission.isRevoked,
416-
siteOrigin: updatedPermission.siteOrigin,
417-
});
404+
418405
logger.debug(
419406
'Profile Sync: Created updated permission object:',
420407
updatedPermission,
421408
);
422409

423410
// Store the updated permission
424-
logToFile('💾 PROFILE SYNC: Storing updated permission...');
425411
await storeGrantedPermission(updatedPermission);
426-
logToFile('✅ PROFILE SYNC: Successfully stored updated permission');
427412
logger.debug('Profile Sync: Successfully stored updated permission');
428413
} catch (error) {
429-
logToFile(
430-
'❌ PROFILE SYNC: Error updating permission revocation status:',
431-
error,
432-
);
433414
logger.error(
434415
'Error updating permission revocation status with existing permission:',
435416
error,

packages/gator-permissions-snap/src/rpc/rpcHandler.ts

Lines changed: 55 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { PermissionResponse } from '@metamask/7715-permissions-shared/types';
2-
import { logger, logToFile } from '@metamask/7715-permissions-shared/utils';
2+
import { logger } from '@metamask/7715-permissions-shared/utils';
33
import { decodeDelegations, hashDelegation } from '@metamask/delegation-core';
44
import { InvalidInputError, type Json } from '@metamask/snaps-sdk';
55

@@ -36,9 +36,10 @@ export type RpcHandler = {
3636
/**
3737
* Handles get granted permissions requests.
3838
*
39-
* @returns The granted permissions.
39+
* @param params - Optional parameters for filtering permissions.
40+
* @returns The granted permissions, optionally filtered.
4041
*/
41-
getGrantedPermissions(): Promise<Json>;
42+
getGrantedPermissions(params?: Json): Promise<Json>;
4243

4344
/**
4445
* Handles submit revocation requests.
@@ -124,13 +125,58 @@ export function createRpcHandler(config: {
124125
/**
125126
* Handles get granted permissions requests.
126127
*
127-
* @returns The granted permissions.
128+
* @param params - Optional parameters for filtering permissions.
129+
* @returns The granted permissions, optionally filtered.
128130
*/
129-
const getGrantedPermissions = async (): Promise<Json> => {
130-
logger.debug('getGrantedPermissions()');
131-
const grantedPermission =
132-
await profileSyncManager.getAllGrantedPermissions();
133-
return grantedPermission as Json[];
131+
const getGrantedPermissions = async (params?: Json): Promise<Json> => {
132+
logger.debug('getGrantedPermissions()', params);
133+
134+
// Get all permissions
135+
const allPermissions = await profileSyncManager.getAllGrantedPermissions();
136+
137+
// If no params provided, return all permissions (backward compatibility)
138+
if (!params || typeof params !== 'object') {
139+
return allPermissions as Json[];
140+
}
141+
142+
// Parse filtering options
143+
const { isRevoked, siteOrigin, chainId, delegationManager } = params as {
144+
isRevoked?: boolean;
145+
siteOrigin?: string;
146+
chainId?: string;
147+
delegationManager?: string;
148+
};
149+
150+
// Apply filters
151+
let filteredPermissions = allPermissions;
152+
153+
if (typeof isRevoked === 'boolean') {
154+
filteredPermissions = filteredPermissions.filter(
155+
(permission) => permission.isRevoked === isRevoked,
156+
);
157+
}
158+
159+
if (typeof siteOrigin === 'string') {
160+
filteredPermissions = filteredPermissions.filter(
161+
(permission) => permission.siteOrigin === siteOrigin,
162+
);
163+
}
164+
165+
if (typeof chainId === 'string') {
166+
filteredPermissions = filteredPermissions.filter(
167+
(permission) => permission.permissionResponse.chainId === chainId,
168+
);
169+
}
170+
171+
if (typeof delegationManager === 'string') {
172+
filteredPermissions = filteredPermissions.filter(
173+
(permission) =>
174+
permission.permissionResponse.signerMeta.delegationManager ===
175+
delegationManager,
176+
);
177+
}
178+
179+
return filteredPermissions as Json[];
134180
};
135181

136182
/**
@@ -140,41 +186,24 @@ export function createRpcHandler(config: {
140186
* @returns Success confirmation.
141187
*/
142188
const submitRevocation = async (params: Json): Promise<Json> => {
143-
logToFile('================================================2');
144-
logger.debug('=== SUBMIT REVOCATION RPC CALLED ===');
145189
logger.debug('submitRevocation() called with params:', params);
146-
logger.debug('Params type:', typeof params);
147-
logger.debug('Params stringified:', JSON.stringify(params, null, 2));
148190

149191
const { permissionContext } = validateRevocationParams(params);
150192

151-
logger.debug('Validated permissionContext:', permissionContext);
152-
153193
// First, get the existing permission to validate it exists
154194
logger.debug(
155195
'Looking up existing permission for permissionContext:',
156196
permissionContext,
157197
);
158198
const existingPermission =
159199
await profileSyncManager.getGrantedPermission(permissionContext);
160-
console.log('existingPermissionBefore:', existingPermission);
161200

162201
if (!existingPermission) {
163-
logger.debug(
164-
'❌ Permission not found for permissionContext:',
165-
permissionContext,
166-
);
167202
throw new InvalidInputError(
168203
`Permission not found for permission context: ${permissionContext}`,
169204
);
170205
}
171206

172-
logger.debug('✅ Found existing permission:', {
173-
permissionContext,
174-
isRevoked: existingPermission.isRevoked,
175-
siteOrigin: existingPermission.siteOrigin,
176-
});
177-
178207
// Extract delegationManager and chainId from the permission response for logging
179208
const { chainId: permissionChainId, signerMeta } =
180209
existingPermission.permissionResponse;
@@ -188,7 +217,6 @@ export function createRpcHandler(config: {
188217

189218
// Check if the delegation is actually disabled on-chain
190219
if (!delegationManager) {
191-
logger.debug('❌ No delegation manager found');
192220
throw new InvalidInputError(
193221
`No delegation manager found for permission context: ${permissionContext}`,
194222
);
@@ -197,7 +225,6 @@ export function createRpcHandler(config: {
197225
// For on-chain validation, we need to check each delegation in the context
198226
try {
199227
const delegations = decodeDelegations(permissionContext);
200-
logger.debug('Decoded delegations from context:', delegations.length);
201228

202229
// Check if any delegation is disabled on-chain
203230
// For now, we'll check the first delegation. This might need adjustment based on business logic
@@ -209,27 +236,16 @@ export function createRpcHandler(config: {
209236
}
210237

211238
const delegationHash = hashDelegation(firstDelegation);
212-
logger.debug('Checking if delegation is disabled on-chain...', {
213-
delegationHash,
214-
chainId: permissionChainId,
215-
delegationManager,
216-
});
217-
218239
const isDelegationDisabled =
219240
await profileSyncManager.checkDelegationDisabledOnChain(
220241
delegationHash,
221242
permissionChainId,
222243
delegationManager,
223244
);
224245

225-
console.log(
226-
'++++++++++++++++++++isDelegationDisabled:',
227-
isDelegationDisabled,
228-
);
229246
logger.debug('On-chain check result:', { isDelegationDisabled });
230247

231248
if (!isDelegationDisabled) {
232-
logger.debug('❌ Delegation is not disabled on-chain');
233249
throw new InvalidInputError(
234250
`Delegation ${delegationHash} is not disabled on-chain. Cannot process revocation.`,
235251
);
@@ -245,22 +261,12 @@ export function createRpcHandler(config: {
245261
);
246262
}
247263

248-
// Update the permission's revocation status using the optimized method
249-
// This avoids re-fetching the permission we already have
250264
logger.debug('Updating permission revocation status to true...');
251265
await profileSyncManager.updatePermissionRevocationStatusWithPermission(
252266
existingPermission,
253267
true,
254268
);
255269

256-
const existingPermissionAfter =
257-
await profileSyncManager.getGrantedPermission(permissionContext);
258-
259-
console.log('existingPermissionAfter:', existingPermissionAfter);
260-
logToFile('existingPermissionAfter:', existingPermissionAfter);
261-
262-
logger.debug('✅ Revocation completed successfully');
263-
logger.debug('=== SUBMIT REVOCATION RPC COMPLETED ===');
264270
return { success: true };
265271
};
266272

packages/gator-permissions-snap/src/utils/validate.ts

Lines changed: 1 addition & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,7 @@ import {
22
type RequestExecutionPermissionsParam,
33
zRequestExecutionPermissionsParam,
44
} from '@metamask/7715-permissions-shared/types';
5-
import {
6-
extractZodError,
7-
logger,
8-
logToFile,
9-
} from '@metamask/7715-permissions-shared/utils';
5+
import { extractZodError } from '@metamask/7715-permissions-shared/utils';
106
import type { Hex } from '@metamask/delegation-core';
117
import { InvalidInputError, type Json } from '@metamask/snaps-sdk';
128
import { z } from 'zod';
@@ -57,24 +53,16 @@ export function validateRevocationParams(params: Json): {
5753
permissionContext: Hex;
5854
} {
5955
try {
60-
logToFile('================================================3');
61-
logger.debug('🔍 Validating revocation params:', params);
62-
logger.debug('Params type:', typeof params);
63-
6456
if (!params || typeof params !== 'object') {
65-
logger.debug('❌ Invalid params: not an object');
6657
throw new InvalidInputError('Parameters are required');
6758
}
6859

69-
logger.debug('✅ Params is valid object, parsing with Zod...');
7060
const validated = zRevocationParams.parse(params);
71-
logger.debug('✅ Zod validation successful:', validated);
7261

7362
return {
7463
permissionContext: validated.permissionContext as Hex,
7564
};
7665
} catch (error) {
77-
logger.debug('❌ Validation failed:', error);
7866
if (error instanceof z.ZodError) {
7967
throw new InvalidInputError(extractZodError(error.errors));
8068
}

packages/gator-permissions-snap/test/end-to-end/index.test.tsx

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,5 +43,29 @@ describe('Kernel Snap', () => {
4343
});
4444
});
4545
});
46+
47+
describe('success', () => {
48+
it('should return empty array when no permissions are granted', async () => {
49+
const response = await snapRequest({
50+
method: 'permissionsProvider_getGrantedPermissions',
51+
origin: 'metamask',
52+
});
53+
54+
expect(response).toRespondWith([]);
55+
});
56+
57+
it('should accept filtering parameters', async () => {
58+
const response = await snapRequest({
59+
method: 'permissionsProvider_getGrantedPermissions',
60+
origin: 'metamask',
61+
params: {
62+
isRevoked: false,
63+
siteOrigin: 'https://example.com',
64+
},
65+
});
66+
67+
expect(response).toRespondWith([]);
68+
});
69+
});
4670
});
4771
});

0 commit comments

Comments
 (0)