Skip to content

Commit 381548e

Browse files
committed
improve error handling and parameter validation in extractEntityId
1 parent 3d413f6 commit 381548e

File tree

1 file changed

+14
-25
lines changed

1 file changed

+14
-25
lines changed

ee/packages/federation-matrix/src/api/middlewares/canAccessResource.ts

Lines changed: 14 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -5,35 +5,23 @@ import { createMiddleware } from 'hono/factory';
55

66
import { isAuthenticatedMiddleware } from './isAuthenticated';
77

8-
function extractEntityId(params: { eventId?: string; mediaId?: string; roomId?: string }, entityType: 'event' | 'media' | 'room'): string {
8+
function extractEntityId(
9+
params: { eventId?: string; mediaId?: string; roomId?: string },
10+
entityType: 'event' | 'media' | 'room',
11+
): string | null {
912
if (entityType === 'room') {
10-
const { roomId } = params;
11-
if (!roomId) {
12-
throw new Error('Room ID is required');
13-
}
14-
15-
return roomId;
13+
return params.roomId ?? null;
1614
}
1715

1816
if (entityType === 'media') {
19-
const { mediaId } = params;
20-
if (!mediaId) {
21-
throw new Error('Media ID is required');
22-
}
23-
24-
return mediaId;
17+
return params.mediaId ?? null;
2518
}
2619

2720
if (entityType === 'event') {
28-
const { eventId } = params;
29-
if (!eventId) {
30-
throw new Error('Event ID is required');
31-
}
32-
33-
return eventId;
21+
return params.eventId ?? null;
3422
}
3523

36-
throw new Error('Invalid entity type');
24+
return null;
3725
}
3826

3927
const canAccessResource = (federationAuth: EventAuthorizationService, entityType: 'event' | 'media' | 'room') =>
@@ -48,11 +36,12 @@ const canAccessResource = (federationAuth: EventAuthorizationService, entityType
4836
const eventId = c.req.param('eventId');
4937
const roomId = c.req.param('roomId');
5038

51-
const resourceAccess = await federationAuth.canAccessResource(
52-
entityType,
53-
extractEntityId({ mediaId, eventId, roomId }, entityType),
54-
authenticatedServer,
55-
);
39+
const resourceId = extractEntityId({ mediaId, eventId, roomId }, entityType);
40+
if (!resourceId) {
41+
return c.json({ errcode: 'M_INVALID_PARAM', error: `Missing required ${entityType} identifier` }, 400);
42+
}
43+
44+
const resourceAccess = await federationAuth.canAccessResource(entityType, resourceId, authenticatedServer);
5645
if (!resourceAccess) {
5746
return c.json(
5847
{

0 commit comments

Comments
 (0)