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

Add option to omit the hook payload data from matrix events from generic hooks #1004

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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 changelog.d/1004.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add an option in the config to disable hook bodies in Matrix messages.
27 changes: 27 additions & 0 deletions spec/generic-hooks.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,31 @@ describe('Inbound (Generic) Webhooks', () => {
error: "This hook has expired",
});
});

it('should allow disabling hook data in matrix events.', async () => {
const user = testEnv.getUser('user');
const roomId = await user.createRoom({ name: 'My Test Webhooks room'});
const okMsg = user.waitForRoomEvent({ eventType: "m.room.message", sender: testEnv.botMxid, roomId });
const url = await createInboundConnection(user, testEnv.botMxid, roomId, '2h');
expect((await okMsg).data.content.body).toEqual('Room configured to bridge webhooks. See admin room for secret url.');
const stateEvent = (await user.getRoomState(roomId)).find(v => v.type === GenericHookConnection.CanonicalEventType)
await user.sendStateEvent(roomId, stateEvent.type, stateEvent.state_key, {
...stateEvent.content,
includeHookBody: false,
});

const expectedMsg = user.waitForRoomEvent({ eventType: "m.room.message", sender: testEnv.botMxid, roomId });
const req = await fetch(url, {
method: "PUT",
body: "Hello world"
});
expect(req.status).toEqual(200);
expect(await req.json()).toEqual({ ok: true });
expect((await expectedMsg).data.content).toEqual({
msgtype: 'm.notice',
body: 'Received webhook data: Hello world',
formatted_body: '<p>Received webhook data: Hello world</p>',
format: 'org.matrix.custom.html',
});
});
});
12 changes: 9 additions & 3 deletions src/Connections/GenericHook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@
* (in UTC) time.
*/
expirationDate?: string;

includeHookBody?: boolean;
}

export interface GenericHookSecrets {
Expand Down Expand Up @@ -152,7 +154,7 @@
}

static validateState(state: Partial<Record<keyof GenericHookConnectionState, unknown>>): GenericHookConnectionState {
const {name, transformationFunction, waitForComplete, expirationDate: expirationDateStr} = state;
const {name, transformationFunction, waitForComplete, expirationDate: expirationDateStr, includeHookBody} = state;
if (!name) {
throw new ApiError('Missing name', ErrCode.BadValue);
}
Expand All @@ -162,6 +164,9 @@
if (waitForComplete !== undefined && typeof waitForComplete !== "boolean") {
throw new ApiError("'waitForComplete' must be a boolean", ErrCode.BadValue);
}
if (includeHookBody !== undefined && typeof includeHookBody !== "boolean") {
throw new ApiError("'includeHookBody' must be a boolean", ErrCode.BadValue);
}
// Use !=, not !==, to check for both undefined and null
if (transformationFunction != undefined) {
if (!this.quickModule) {
Expand All @@ -186,6 +191,7 @@
name,
transformationFunction: transformationFunction || undefined,
waitForComplete,
includeHookBody: includeHookBody ?? true,
expirationDate,
};
}
Expand Down Expand Up @@ -249,7 +255,6 @@
throw new ApiError('Expiration date must be set', ErrCode.BadValue);
}


await GenericHookConnection.ensureRoomAccountData(roomId, intent, hookId, validState.name);
await intent.underlyingClient.sendStateEvent(roomId, this.CanonicalEventType, validState.name, validState);
const connection = new GenericHookConnection(roomId, validState, hookId, validState.name, messageClient, config.generic, as, intent, storage);
Expand Down Expand Up @@ -355,7 +360,7 @@
if (this.cachedDisplayname !== expectedDisplayname) {
this.cachedDisplayname = (await intent.underlyingClient.getUserProfile(this.intent.userId)).displayname;
}
} catch (ex) {

Check warning on line 363 in src/Connections/GenericHook.ts

View workflow job for this annotation

GitHub Actions / lint-node

'ex' is defined but never used
// Couldn't fetch, probably not set.
this.cachedDisplayname = undefined;
}
Expand Down Expand Up @@ -580,7 +585,7 @@
await ensureUserIsInRoom(senderIntent, this.intent.underlyingClient, this.roomId);

// Matrix cannot handle float data, so make sure we parse out any floats.
const safeData = GenericHookConnection.sanitiseObjectForMatrixJSON(data);
const safeData = (this.config.includeHookBody && this.state.includeHookBody) ? GenericHookConnection.sanitiseObjectForMatrixJSON(data) : undefined;

await this.messageClient.sendMatrixMessage(this.roomId, {
msgtype: content.msgtype || "m.notice",
Expand Down Expand Up @@ -617,6 +622,7 @@
waitForComplete: this.waitForComplete,
name: this.state.name,
expirationDate: this.state.expirationDate,
includeHookBody: this.config.includeHookBody && this.state.includeHookBody,
},
...(showSecrets ? { secrets: {
url: new URL(this.hookId, this.config.parsedUrlPrefix),
Expand Down
3 changes: 3 additions & 0 deletions src/config/sections/generichooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export interface BridgeGenericWebhooksConfigYAML {
maxExpiryTime?: string;
sendExpiryNotice?: boolean;
requireExpiryTime?: boolean;
includeHookBody?: boolean;
}

export class BridgeConfigGenericWebhooks {
Expand All @@ -33,6 +34,7 @@ export class BridgeConfigGenericWebhooks {
public readonly allowJsTransformationFunctions?: boolean;
public readonly waitForComplete?: boolean;
public readonly enableHttpGet: boolean;
public readonly includeHookBody: boolean;

@hideKey()
public readonly maxExpiryTimeMs?: number;
Expand All @@ -47,6 +49,7 @@ export class BridgeConfigGenericWebhooks {
this.enableHttpGet = yaml.enableHttpGet || false;
this.sendExpiryNotice = yaml.sendExpiryNotice || false;
this.requireExpiryTime = yaml.requireExpiryTime || false;
this.includeHookBody = yaml.includeHookBody || false;
try {
this.parsedUrlPrefix = makePrefixedUrl(yaml.urlPrefix);
this.urlPrefix = () => { return this.parsedUrlPrefix.href; }
Expand Down
Loading