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

Support deployments using Matrix Authentication Service #577

Open
wants to merge 6 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
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
158 changes: 158 additions & 0 deletions src/MASclient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
/*
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);
const accessToken = await this.getAccessToken();
try {
const resp = await axios({
method: "get",
url: this.config.mas.url + `/api/admin/v1/users/by-username/${localpart}`,
headers: {
"User-Agent": "Mjolnir",
"Content-Type": "application/json; charset=UTF-8",
"Authorization": `Bearer ${accessToken.token.access_token}`,
},
});
return resp.data.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> {
Copy link
Member

Choose a reason for hiding this comment

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

slight inconsistency in naming: is it MAS or Mas in functions? (either is fine - we should match existing styles if there's examples).

const masId = await this.getMASUserId(userId);
const accessToken = await this.getAccessToken();
const url = this.config.mas.url + `/api/admin/v1/users/${masId}/deactivate`;
try {
await axios({
method: "post",
url: url,
headers: {
"User-Agent": "Mjolnir",
"Content-Type": "application/json; charset=UTF-8",
"Authorization": `Bearer ${accessToken.token.access_token}`,
},
});
Comment on lines +83 to +91
Copy link
Member

Choose a reason for hiding this comment

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

moving the axios calls to a doRequest function would be best, so if we need to update something it's a single code site. The getAccessToken() call can be in that function too.

} 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);
const accessToken = await this.getAccessToken();
try {
await axios({
method: "post",
url: this.config.mas.url + `/api/admin/v1/users/${masId}/lock`,
headers: {
"User-Agent": "Mjolnir",
"Content-Type": "application/json; charset=UTF-8",
"Authorization": `Bearer ${accessToken.token.access_token}`,
},
});
} 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);
const accessToken = await this.getAccessToken();
try {
await axios({
method: "post",
url: this.config.mas.url + `/api/admin/v1/users/${masId}/unlock`,
headers: {
"User-Agent": "Mjolnir",
"Content-Type": "application/json; charset=UTF-8",
"Authorization": `Bearer ${accessToken.token.access_token}`,
},
});
} catch (error) {
LogService.error("Mas client", `Error unlocking user ${userId} via MAS:`, error.message);
throw error;
}
}

public async masUserIsAdmin(userId: string): Promise<boolean> {
const index = userId.indexOf(":");
const localpart = userId.substring(1, index);
const accessToken = await this.getAccessToken();

let resp;
try {
resp = await axios({
method: "get",
url: this.config.mas.url + `/api/admin/v1/users/by-username/${localpart}`,
headers: {
"User-Agent": "Janitor",
"Content-Type": "application/json; charset=UTF-8",
"Authorization": `Bearer ${accessToken.token.access_token}`,
},
});
} catch (error) {
LogService.error("MAS client", `Error determining if MAS user ${userId} is admin: `, error.message);
throw error;
}
return resp.data.data.attributes.admin;
}
}
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.masUserIsAdmin(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"], "✅");
}
Loading
Loading