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

Verify Slack webhook tokens #776

Open
wants to merge 6 commits into
base: develop
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/776.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Verify Slack webhook tokens.
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I figured bugfix is the closest this comes to, since it was arguably a bug that we never did this before.

22 changes: 11 additions & 11 deletions docs/link_channels.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@ first the individual Matrix room and Slack channel need to be created, and then
a command needs to be issued in the administration console room to add the link
to the bridge's database.

## Determining your channel ID

You'll need a "channel ID" to link rooms.
To obtain it, right-click your channel name in Slack and select "Copy Link".
The channel id is the last argument in the url
(`https://XXX.Slack.com/messages/<channel id>/`)

## RTM API

The Real Time Messaging (RTM) API is the newer and recommended way to use the bridge.
Expand Down Expand Up @@ -47,12 +54,9 @@ The Real Time Messaging (RTM) API is the newer and recommended way to use the br
/invite @bot-user-name
```

You will also need to determine the "channel ID" that Slack uses to identify
the channel. Right-click your channel name in Slack and select "Copy Link".
The channel id is the last argument in the url
(`https://XXX.Slack.com/messages/<channel id>/`)
4. Obtain the channel ID (see "Determining your channel ID")

4. Issue a ``link`` command in the administration control room with these
5. Issue a ``link`` command in the administration control room with these
collected values as arguments:

```
Expand Down Expand Up @@ -104,17 +108,13 @@ although it can be useful for single channels or if you are using Mattermost.
of its `token` field. Add a URL to this web hook pointing back at the
application service port you configured during setup.

You will also need to determine the "channel ID" that Slack uses to identify
the channel. Unfortunately, it is not easily obtained from the Slack UI. The
easiest way to do this is to send a message from Slack to the bridge; the
bridge will log the channel ID as part of the unrecognised message output.
You can then take note of the `channel_id` field.
1. Obtain the channel ID (see "Determining your channel ID")

1. Issue a ``link`` command in the administration control room with these
collected values as arguments:

```
link --channel_id CHANNELID --room !the-matrix:room.id --webhook_url https://hooks.Slack.com/services/ABC/DEF/123
link --channel_id CHANNELID --room !the-matrix:room.id --webhook_url https://hooks.Slack.com/services/ABC/DEF/123 --webhook_token TOKEN
```

## Unlink Channels
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@
"eslint-plugin-react-hooks": "^4.6.0",
"js-yaml": "^4.1.0",
"mocha": "^10.0.0",
"node-mocks-http": "^1.14.1",
"nyc": "^15.1.0",
"postcss": "^8.4.21",
"prom-client": "^14.0.1",
Expand Down
8 changes: 7 additions & 1 deletion src/AdminCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,11 +181,12 @@ export class AdminCommands {
return new AdminCommand(
"link",
"connect a Matrix and a Slack room together",
async ({respond, room, channel_id, webhook_url, slack_bot_token, team_id}: {
async ({respond, room, channel_id, webhook_url, webhook_token, slack_bot_token, team_id}: {
respond: ResponseCallback,
room?: string,
channel_id?: string,
webhook_url?: string,
webhook_token?: string,
slack_bot_token?: string,
team_id?: string,
}) => {
Expand All @@ -200,6 +201,7 @@ export class AdminCommands {
team_id,
slack_channel_id: channel_id,
slack_webhook_uri: webhook_url,
slack_webhook_token: webhook_token,
});
respond("Room is now " + r.getStatus());
if (r.SlackWebhookUri) {
Expand Down Expand Up @@ -234,6 +236,10 @@ export class AdminCommands {
alias: "u",
description: "Slack webhook URL. Used with Slack outgoing hooks integration",
},
webhook_token: {
alias: "k",
description: "Slack webhook token. Used with Slack outgoing hooks integration",
},
},
);
}
Expand Down
13 changes: 13 additions & 0 deletions src/BridgedRoom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
slack_channel_name?: string;
slack_channel_id?: string;
slack_webhook_uri?: string;
slack_webhook_token?: string;
slack_team_id?: string;
slack_type: SlackChannelTypes;
is_private?: boolean;
Expand Down Expand Up @@ -95,6 +96,14 @@
this.setValue("slackWebhookUri", value);
}

public get SlackWebhookToken(): string|undefined {
return this.slackWebhookToken;
}

public set SlackWebhookToken(value: string|undefined) {
this.setValue("slackWebhookToken", value);
}

public get MatrixRoomId(): string {
return this.matrixRoomId;
}
Expand Down Expand Up @@ -135,6 +144,7 @@
slack_channel_name: entry.remote.name,
slack_team_id: entry.remote.slack_team_id,
slack_webhook_uri: entry.remote.webhook_uri,
slack_webhook_token: entry.remote.webhook_token,
puppet_owner: entry.remote.puppet_owner,
is_private: entry.remote.slack_private,
slack_type: entry.remote.slack_type as SlackChannelTypes,
Expand All @@ -146,6 +156,7 @@
private slackChannelName?: string;
private slackChannelId?: string;
private slackWebhookUri?: string;
private slackWebhookToken?: string;
private slackTeamId?: string;
private slackType: SlackChannelTypes;
private isPrivate?: boolean;
Expand Down Expand Up @@ -184,6 +195,7 @@
this.slackChannelName = opts.slack_channel_name;
this.slackChannelId = opts.slack_channel_id;
this.slackWebhookUri = opts.slack_webhook_uri;
this.slackWebhookToken = opts.slack_webhook_token;
this.slackTeamId = opts.slack_team_id;
this.slackType = opts.slack_type || "channel";
if (opts.is_private === undefined) {
Expand Down Expand Up @@ -241,13 +253,14 @@
id: `INTEG-${this.inboundId}`,
matrix_id: this.matrixRoomId,
remote: {
id: this.slackChannelId!,

Check warning on line 256 in src/BridgedRoom.ts

View workflow job for this annotation

GitHub Actions / lint

Forbidden non-null assertion
name: this.slackChannelName!,

Check warning on line 257 in src/BridgedRoom.ts

View workflow job for this annotation

GitHub Actions / lint

Forbidden non-null assertion
slack_team_id: this.slackTeamId!,

Check warning on line 258 in src/BridgedRoom.ts

View workflow job for this annotation

GitHub Actions / lint

Forbidden non-null assertion
slack_type: this.slackType!,

Check warning on line 259 in src/BridgedRoom.ts

View workflow job for this annotation

GitHub Actions / lint

Forbidden non-null assertion
slack_private: this.isPrivate!,

Check warning on line 260 in src/BridgedRoom.ts

View workflow job for this annotation

GitHub Actions / lint

Forbidden non-null assertion
webhook_uri: this.slackWebhookUri!,

Check warning on line 261 in src/BridgedRoom.ts

View workflow job for this annotation

GitHub Actions / lint

Forbidden non-null assertion
webhook_token: this.slackWebhookToken!,

Check warning on line 262 in src/BridgedRoom.ts

View workflow job for this annotation

GitHub Actions / lint

Forbidden non-null assertion
puppet_owner: this.puppetOwner!,

Check warning on line 263 in src/BridgedRoom.ts

View workflow job for this annotation

GitHub Actions / lint

Forbidden non-null assertion
},
remote_id: this.inboundId,
};
Expand All @@ -256,7 +269,7 @@
}

public async getClientForRequest(userId: string): Promise<{id: string, client: WebClient}|null> {
const puppet = await this.main.clientFactory.getClientForUserWithId(this.SlackTeamId!, userId);

Check warning on line 272 in src/BridgedRoom.ts

View workflow job for this annotation

GitHub Actions / lint

Forbidden non-null assertion
if (puppet) {
return puppet;
}
Expand Down
6 changes: 6 additions & 0 deletions src/Main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1351,6 +1351,7 @@ export class Main {
public async actionLink(opts: {
matrix_room_id: string,
slack_webhook_uri?: string,
slack_webhook_token?: string,
slack_channel_id?: string,
slack_bot_token?: string,
team_id?: string,
Expand Down Expand Up @@ -1450,6 +1451,11 @@ export class Main {

if (opts.slack_webhook_uri) {
room.SlackWebhookUri = opts.slack_webhook_uri;
if (opts.slack_webhook_token) {
room.SlackWebhookToken = opts.slack_webhook_token;
} else {
throw new Error("Cannot link via a webhook without a webhook token");
}
}

if (opts.slack_channel_id) {
Expand Down
10 changes: 10 additions & 0 deletions src/SlackHookHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,16 @@ export class SlackHookHandler extends BaseSlackHandler {
return;
}

if (params.token !== room.SlackWebhookToken) {
log.warn(`Ignoring message for ${room.MatrixRoomId} due to webhook token mismatch`);

response.writeHead(HTTP_CODES.FORBIDDEN);
response.end();

endTimer({outcome: "dropped"});
return;
}

if (method === "POST" && path === "post") {
try {
if (!room) {
Expand Down
1 change: 1 addition & 0 deletions src/datastore/Models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export interface RoomEntry {
id: string;
name: string;
webhook_uri?: string;
webhook_token?: string;
slack_private?: boolean;
puppet_owner?: string;
};
Expand Down
119 changes: 119 additions & 0 deletions tests/integration/WebhookTest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
/*
Copyright 2024 The Matrix.org Foundation C.I.C.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { SlackHookHandler } from "../../src/SlackHookHandler";
import { FakeMain } from "../utils/fakeMain";
import { Main } from "../../src/Main";
import { expect } from "chai";
import * as httpMocks from "node-mocks-http";
import * as randomstring from "randomstring";
import { BridgedRoom } from "../../src/BridgedRoom";

const constructHarness = () => {
const main = new FakeMain({
oauth2: false,
teams: [
{
bot_token: "foo",
id: "12345",
name: "FakeTeam",
domain: "fake-domain",
user_id: "foo",
bot_id: "bar",
status: "ok",
scopes: "",
},
],
});
const hooks = new SlackHookHandler(main as unknown as Main);
return { hooks, main };
};

const DEFAULT_PAYLOAD = {
team_id: 'T06Q92QGCLC',
team_domain: 'mas',
service_id: '6899401468119',
channel_id: 'C06Q6525S71',
channel_name: 'bridge-testing',
timestamp: '1711628700.919889',
user_id: 'U06QMMZQRH5',
user_name: 'mario',
text: 'incoming!'
};

describe("WebhookTest", () => {
let harness: { hooks: SlackHookHandler, main: FakeMain };

beforeEach(() => {
harness = constructHarness();
});

async function checkResult(req: httpMocks.MockRequest<any>, expectations: (res: httpMocks.MockResponse<any>) => void): Promise<void> {
const res = httpMocks.createResponse({ eventEmitter: require('events').EventEmitter });
const promise = new Promise<void>((resolve, reject) => {
res.on('end', () => {
try {
expectations(res);
resolve();
} catch (err: unknown) {
reject(err);
}
});
});

harness.hooks['onRequest'](req, res);

req.emit('end');

return promise;
}

it("will ignore webhooks sent to unknown room", () => {
const req = httpMocks.createRequest({
method: 'POST',
url: 'http://foo.bar/webhooks/' + randomstring.generate(32),
params: DEFAULT_PAYLOAD,
});

return checkResult(req, res => {
expect(res.statusCode).to.equal(200);
});
});

it("will reject webhooks not containing a valid token", () => {
['invalid', undefined, null, true, "' or 1=1;--"].forEach(badToken => {
let room = new BridgedRoom(harness.main as unknown as Main, {
matrix_room_id: '!foo:bar.baz',
inbound_id: randomstring.generate(32),
slack_webhook_token: randomstring.generate(24),
slack_type: "channel",
});
harness.main.rooms.upsertRoom(room);

const req = httpMocks.createRequest({
method: 'POST',
url: 'http://foo.bar/webhooks/' + room.InboundId,
params: {
token: badToken,
...DEFAULT_PAYLOAD,
},
});

return checkResult(req, res => {
expect(res.statusCode).to.equal(403);
});
});
});
});
Loading
Loading