Skip to content

Commit

Permalink
Support deployments using Matrix Authentication Service (#577)
Browse files Browse the repository at this point in the history
  • Loading branch information
H-Shay authored Mar 5, 2025
1 parent 42d133d commit a6fe858
Show file tree
Hide file tree
Showing 11 changed files with 490 additions and 7 deletions.
12 changes: 11 additions & 1 deletion config/default.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -275,4 +275,14 @@ displayReports: true
# How sensitive the NsfwProtection should be, which determines if an image should be redacted. A number between 0 - .99,
# with a lower number indicating greater sensitivity, possibly resulting in images being more aggressively flagged
# and redacted as NSFW
nsfwSensitivity: .6
nsfwSensitivity: .6

# Set this to true if the synapse this mjolnir is protecting is using Matrix Authentication Service for auth
# If so, provide the base url and clientId + clientSecret needed to obtain a token from MAS - see
# https://element-hq.github.io/matrix-authentication-service/index.html for more information about
# configuring MAS clients/authorization grants
#MAS:
# use: true
# url: "https://auth.your-auth.com"
# clientId: 'SOMEID'
# clientSecret: 'SoMEseCreT'
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"@types/pg": "^8.6.5",
"@types/request": "^2.48.8",
"@types/shell-quote": "1.7.1",
"@types/simple-oauth2": "^5.0.7",
"crypto-js": "^4.2.0",
"eslint": "^7.32",
"expect": "^27.0.6",
Expand Down Expand Up @@ -64,6 +65,7 @@
"pg": "^8.8.0",
"prom-client": "^14.1.0",
"shell-quote": "^1.7.3",
"simple-oauth2": "^5.1.0",
"ulidx": "^0.3.0",
"yaml": "^2.2.2"
},
Expand Down
132 changes: 132 additions & 0 deletions src/MASClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
/*
Copyright 2025 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 { ClientCredentials, AccessToken } from "simple-oauth2";
import { IConfig } from "./config";
import axios from "axios";
import { LogService } from "@vector-im/matrix-bot-sdk";

export class MASClient {
public readonly config: IConfig;
private client: ClientCredentials;
private accessToken: AccessToken;

constructor(config: IConfig) {
LogService.info("MAS client", "Setting up MAS client");
this.config = config;
const clientConfig = {
client: {
id: config.MAS.clientId,
secret: config.MAS.clientSecret,
},
auth: {
tokenPath: config.MAS.url + "/oauth2/token",
tokenHost: config.MAS.url,
},
};
this.client = new ClientCredentials(clientConfig);
}

public async getAccessToken() {
if (!this.accessToken || this.accessToken.expired()) {
// fetch a new one
const tokenParams = { scope: "urn:mas:admin" };
try {
this.accessToken = await this.client.getToken(tokenParams);
} catch (error) {
LogService.error("MAS client", "Error fetching auth token for MAS:", error.message);
throw error;
}
}
return this.accessToken;
}

public async getMASUserId(userId: string): Promise<string> {
const index = userId.indexOf(":");
const localpart = userId.substring(1, index);

try {
const resp = await this.doRequest("get", `/api/admin/v1/users/by-username/${localpart}`);
return resp.data.id;
} catch (error) {
LogService.error("MAS client", `Error fetching MAS id for user ${userId}:`, error.message);
throw error;
}
}

public async deactivateMASUser(userId: string): Promise<void> {
const MASId = await this.getMASUserId(userId);
try {
await this.doRequest("post", `/api/admin/v1/users/${MASId}/deactivate`);
} catch (error) {
LogService.error("MAS client", `Error deactivating user ${userId} via MAS`, error.message);
throw error;
}
}

public async lockMASUser(userId: string): Promise<void> {
const MASId = await this.getMASUserId(userId);
try {
await this.doRequest("post", `/api/admin/v1/users/${MASId}/lock`);
} catch (error) {
LogService.error("MAS client", `Error locking user ${userId} via MAS:`, error.message);
throw error;
}
}

public async unlockMASUser(userId: string): Promise<void> {
const MASId = await this.getMASUserId(userId);
try {
await this.doRequest("post", `/api/admin/v1/users/${MASId}/unlock`);
} catch (error) {
LogService.error("MAS client", `Error unlocking user ${userId} via MAS:`, error.message);
throw error;
}
}

public async UserIsMASAdmin(userId: string): Promise<boolean> {
const index = userId.indexOf(":");
const localpart = userId.substring(1, index);
const path = `/api/admin/v1/users/by-username/${localpart}`;

let resp;
try {
resp = await this.doRequest("get", path);
} catch (error) {
LogService.error("MAS client", `Error determining if MAS user ${userId} is admin: `, error.message);
throw error;
}
return resp.data.attributes.admin;
}

public async doRequest(method: string, path: string) {
const url = this.config.MAS.url + path;
const accessToken = await this.getAccessToken();
const headers = {
"User-Agent": "Mjolnir",
"Content-Type": "application/json; charset=UTF-8",
"Authorization": `Bearer ${accessToken.token.access_token}`,
};
LogService.info("MAS client", `Calling ${url}`);

const resp = await axios({
method,
url,
headers,
});
return resp.data;
}
}
38 changes: 35 additions & 3 deletions src/Mjolnir.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import { MatrixEmitter, MatrixSendClient } from "./MatrixEmitter";
import { OpenMetrics } from "./webapis/OpenMetrics";
import { LRUCache } from "lru-cache";
import { ModCache } from "./ModCache";
import { MASClient } from "./MASClient";

export const STATE_NOT_STARTED = "not_started";
export const STATE_CHECKING_PERMISSIONS = "checking_permissions";
Expand Down Expand Up @@ -100,6 +101,16 @@ export class Mjolnir {
*/
public moderators: ModCache;

/**
* Whether the Synapse Mjolnir is protecting uses the Matrix Authentication Service
*/
public readonly usingMAS: boolean;

/**
* Client for making calls to MAS (if using)
*/
public MASClient: MASClient;

/**
* Adds a listener to the client that will automatically accept invitations.
* @param {MatrixSendClient} client
Expand Down Expand Up @@ -214,6 +225,11 @@ export class Mjolnir {
this.protectedRoomsConfig = new ProtectedRoomsConfig(client);
this.policyListManager = new PolicyListManager(this);

if (config.MAS.use) {
this.usingMAS = true;
this.MASClient = new MASClient(config);
}

// Setup bot.

matrixEmitter.on("room.event", this.handleEvent.bind(this));
Expand Down Expand Up @@ -563,9 +579,13 @@ export class Mjolnir {

public async isSynapseAdmin(): Promise<boolean> {
try {
const endpoint = `/_synapse/admin/v1/users/${await this.client.getUserId()}/admin`;
const response = await this.client.doRequest("GET", endpoint);
return response["admin"];
if (this.usingMAS) {
return await this.MASClient.UserIsMASAdmin(this.clientUserId);
} else {
const endpoint = `/_synapse/admin/v1/users/${await this.client.getUserId()}/admin`;
const response = await this.client.doRequest("GET", endpoint);
return response["admin"];
}
} catch (e) {
LogService.error("Mjolnir", "Error determining if Mjolnir is a server admin:");
LogService.error("Mjolnir", extractRequestError(e));
Expand All @@ -590,6 +610,18 @@ export class Mjolnir {
return await this.client.doRequest("PUT", endpoint, null, body);
}

public async lockSynapseUser(userId: string): Promise<any> {
const endpoint = `/_synapse/admin/v2/users/${userId}`;
const body = { locked: true };
return await this.client.doRequest("PUT", endpoint, null, body);
}

public async unlockSynapseUser(userId: string): Promise<any> {
const endpoint = `/_synapse/admin/v2/users/${userId}`;
const body = { locked: false };
return await this.client.doRequest("PUT", endpoint, null, body);
}

public async shutdownSynapseRoom(roomId: string, message?: string): Promise<any> {
const endpoint = `/_synapse/admin/v1/rooms/${roomId}`;
return await this.client.doRequest("DELETE", endpoint, null, {
Expand Down
8 changes: 8 additions & 0 deletions src/commands/CommandHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ import { execSetupProtectedRoom } from "./SetupDecentralizedReportingCommand";
import { execSuspendCommand } from "./SuspendCommand";
import { execUnsuspendCommand } from "./UnsuspendCommand";
import { execIgnoreCommand, execListIgnoredCommand } from "./IgnoreCommand";
import { execLockCommand } from "./LockCommand";
import { execUnlockCommand } from "./UnlockCommand";

export const COMMAND_PREFIX = "!mjolnir";

Expand Down Expand Up @@ -146,6 +148,10 @@ export async function handleCommand(roomId: string, event: { content: { body: st
return await execIgnoreCommand(roomId, event, mjolnir, parts);
} else if (parts[1] === "ignored") {
return await execListIgnoredCommand(roomId, event, mjolnir, parts);
} else if (parts[1] === "lock") {
return await execLockCommand(roomId, event, mjolnir, parts);
} else if (parts[1] === "unlock") {
return await execUnlockCommand(roomId, event, mjolnir, parts);
} else if (parts[1] === "help") {
// Help menu
const protectionMenu =
Expand All @@ -172,6 +178,8 @@ export async function handleCommand(roomId: string, event: { content: { body: st
"!mjolnir make admin <room alias> [user alias/ID] - Make the specified user or the bot itself admin of the room\n" +
"!mjolnir suspend <user ID> - Suspend the specified user\n" +
"!mjolnir unsuspend <user ID> - Unsuspend the specified user\n" +
"!mjolnir lock <user ID> - Lock the account of the specified user\n" +
"!mjolnir unlock <user ID> - Unlock the account of the specified user\n" +
"!mjolnir ignore <user ID/server name> - Add user to list of users/servers that cannot be banned/ACL'd. Note that this does not survive restart.\n" +
"!mjolnir ignored - List currently ignored entities.\n" +
"!mjolnir shutdown room <room alias/ID> [message] - Uses the bot's account to shut down a room, preventing access to the room on this server\n";
Expand Down
18 changes: 16 additions & 2 deletions src/commands/DeactivateCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ limitations under the License.
*/

import { Mjolnir } from "../Mjolnir";
import { RichReply } from "@vector-im/matrix-bot-sdk";
import { LogLevel, RichReply } from "@vector-im/matrix-bot-sdk";

// !mjolnir deactivate <user ID>
export async function execDeactivateCommand(roomId: string, event: any, mjolnir: Mjolnir, parts: string[]) {
Expand All @@ -30,6 +30,20 @@ export async function execDeactivateCommand(roomId: string, event: any, mjolnir:
return;
}

await mjolnir.deactivateSynapseUser(target);
if (mjolnir.usingMAS) {
try {
await mjolnir.MASClient.deactivateMASUser(target);
} catch (err) {
mjolnir.managementRoomOutput.logMessage(
LogLevel.ERROR,
"Deactivate Command",
`There was an error deactivating ${target}, please check the logs for more information.`,
);
await mjolnir.client.unstableApis.addReactionToEvent(roomId, event["event_id"], "❌");
return;
}
} else {
await mjolnir.deactivateSynapseUser(target);
}
await mjolnir.client.unstableApis.addReactionToEvent(roomId, event["event_id"], "✅");
}
49 changes: 49 additions & 0 deletions src/commands/LockCommand.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
Copyright 2025 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 { Mjolnir } from "../Mjolnir";
import { LogLevel, RichReply } from "@vector-im/matrix-bot-sdk";

// !mjolnir lock <user ID>
export async function execLockCommand(roomId: string, event: any, mjolnir: Mjolnir, parts: string[]) {
const target = parts[2];

const isAdmin = await mjolnir.isSynapseAdmin();
if (!isAdmin) {
const message = "I am not a Synapse administrator, or the endpoint is blocked";
const reply = RichReply.createFor(roomId, event, message, message);
reply["msgtype"] = "m.notice";
mjolnir.client.sendMessage(roomId, reply);
return;
}

if (mjolnir.usingMAS) {
try {
await mjolnir.MASClient.lockMASUser(target);
} catch (err) {
mjolnir.managementRoomOutput.logMessage(
LogLevel.ERROR,
"Lock Command",
`There was an error locking ${target}, please check the logs for more information.`,
);
await mjolnir.client.unstableApis.addReactionToEvent(roomId, event["event_id"], "❌");
return;
}
} else {
await mjolnir.lockSynapseUser(target);
}
await mjolnir.client.unstableApis.addReactionToEvent(roomId, event["event_id"], "✅");
}
49 changes: 49 additions & 0 deletions src/commands/UnlockCommand.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
Copyright 2025 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 { Mjolnir } from "../Mjolnir";
import { LogLevel, RichReply } from "@vector-im/matrix-bot-sdk";

// !mjolnir unlock <user ID>
export async function execUnlockCommand(roomId: string, event: any, mjolnir: Mjolnir, parts: string[]) {
const target = parts[2];

const isAdmin = await mjolnir.isSynapseAdmin();
if (!isAdmin) {
const message = "I am not a Synapse administrator, or the endpoint is blocked";
const reply = RichReply.createFor(roomId, event, message, message);
reply["msgtype"] = "m.notice";
mjolnir.client.sendMessage(roomId, reply);
return;
}

if (mjolnir.usingMAS) {
try {
await mjolnir.MASClient.unlockMASUser(target);
} catch (err) {
mjolnir.managementRoomOutput.logMessage(
LogLevel.ERROR,
"Unlock Command",
`There was an error unlocking ${target}, please check the logs for more information.`,
);
await mjolnir.client.unstableApis.addReactionToEvent(roomId, event["event_id"], "❌");
return;
}
} else {
await mjolnir.unlockSynapseUser(target);
}
await mjolnir.client.unstableApis.addReactionToEvent(roomId, event["event_id"], "✅");
}
Loading

0 comments on commit a6fe858

Please sign in to comment.