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 command to elevate a user (or the bot) as room administrator #219

Merged
merged 17 commits into from
Mar 7, 2022
Merged
Show file tree
Hide file tree
Changes from 15 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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,6 @@ typings/

# Python packing directories.
mjolnir.egg-info/

# VS
.vs
8 changes: 8 additions & 0 deletions config/default.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,14 @@ protectedRooms:
# Manually add these rooms to the protected rooms list if you want them protected.
protectAllJoinedRooms: false

# Server administration commands
maranda marked this conversation as resolved.
Show resolved Hide resolved
admin:
# The make admin command allows you to use the Synapse admin API to force
# a room dministrator of the target room which is local to Mjolnir's HomeServer
maranda marked this conversation as resolved.
Show resolved Hide resolved
# to change the Power Level of either a target user or bot itself to room
# administrator.
enableMakeRoomAdminCommand: true
maranda marked this conversation as resolved.
Show resolved Hide resolved

# Misc options for command handling and commands
commands:
# If true, Mjolnir will respond to commands like !help and !ban instead of
Expand Down
8 changes: 8 additions & 0 deletions config/harness.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,14 @@ protectedRooms: []
# Manually add these rooms to the protected rooms list if you want them protected.
protectAllJoinedRooms: false

# Server administration commands
admin:
maranda marked this conversation as resolved.
Show resolved Hide resolved
# The make admin command allows you to use the Synapse admin API to force
# a room dministrator of the target room which is local to Mjolnir's HomeServer
# to change the Power Level of either a target user or bot itself to room
# administrator.
enableMakeRoomAdminCommand: true

# Misc options for command handling and commands
commands:
# If true, Mjolnir will respond to commands like !help and !ban instead of
Expand Down
13 changes: 13 additions & 0 deletions src/Mjolnir.ts
Original file line number Diff line number Diff line change
Expand Up @@ -964,6 +964,19 @@ export class Mjolnir {
});
}

/**
* Make a user administrator via the Synapse Admin API
* @param roomId the room where the user (or the bot) shall be made administrator.
* @param userId optionally specify the user mxID to be made administrator, if not specified the bot mxID will be used.
* @returns The list of errors encountered, for reporting to the management room.
*/
public async makeUserRoomAdmin(roomId: string, userId?: string): Promise<any> {
const endpoint = `/_synapse/admin/v1/rooms/${roomId}/make_room_admin`;
return await this.client.doRequest("POST", endpoint, null, {
user_id: userId || await this.client.getUserId(), /* if not specified make the bot administrator */
});
}

public queueRedactUserMessagesIn(userId: string, roomId: string) {
this.eventRedactionQueue.add(new RedactUserInRoom(userId, roomId));
}
Expand Down
4 changes: 4 additions & 0 deletions src/commands/CommandHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import { execSetPowerLevelCommand } from "./SetPowerLevelCommand";
import { execShutdownRoomCommand } from "./ShutdownRoomCommand";
import { execAddAliasCommand, execMoveAliasCommand, execRemoveAliasCommand, execResolveCommand } from "./AliasCommands";
import { execKickCommand } from "./KickCommand";
import { execMakeRoomAdminCommand } from "./MakeRoomAdminCommand";

export const COMMAND_PREFIX = "!mjolnir";

Expand Down Expand Up @@ -109,6 +110,8 @@ export async function handleCommand(roomId: string, event: { content: { body: st
return await execShutdownRoomCommand(roomId, event, mjolnir, parts);
} else if (parts[1] === 'kick' && parts.length > 2) {
return await execKickCommand(roomId, event, mjolnir, parts);
} else if (parts[1] === 'make' && parts[2] === 'admin' && parts.length > 3) {
return await execMakeRoomAdminCommand(roomId, event, mjolnir, parts);
} else {
// Help menu
const menu = "" +
Expand Down Expand Up @@ -146,6 +149,7 @@ export async function handleCommand(roomId: string, event: { content: { body: st
"!mjolnir resolve <room alias> - Resolves a room alias to a room ID\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" +
"!mjolnir powerlevel <user ID> <power level> [room alias/ID] - Sets the power level of the user in the specified room (or all protected rooms)\n" +
"!mjolnir make admin <room alias> [room alias/ID] - Make the specified user or the bot itself admin of the room\n" +
maranda marked this conversation as resolved.
Show resolved Hide resolved
"!mjolnir help - This menu\n";
const html = `<b>Mjolnir help:</b><br><pre><code>${htmlEscape(menu)}</code></pre>`;
const text = `Mjolnir help:\n${menu}`;
Expand Down
34 changes: 34 additions & 0 deletions src/commands/MakeRoomAdminCommand.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
Copyright 2021, 2022 Marco Cirillo

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 config from "../config";
import { Mjolnir } from "../Mjolnir";
import { RichReply } from "matrix-bot-sdk";

// !mjolnir make admin <room> [<user ID>]
export async function execMakeRoomAdminCommand(roomId: string, event: any, mjolnir: Mjolnir, parts: string[]) {
const isAdmin = await mjolnir.isSynapseAdmin();
if (!config.admin?.enableMakeRoomAdminCommand || !isAdmin) {
const message = "The command is either not enabled in the config, or I can't perform the requested operation";
maranda marked this conversation as resolved.
Show resolved Hide resolved
const reply = RichReply.createFor(roomId, event, message, message);
reply['msgtype'] = "m.notice";
mjolnir.client.sendMessage(roomId, reply);
return;
}

await mjolnir.makeUserRoomAdmin(await mjolnir.client.resolveRoom(parts[3]), parts[4]);
maranda marked this conversation as resolved.
Show resolved Hide resolved
await mjolnir.client.unstableApis.addReactionToEvent(roomId, event['event_id'], '✅');
}
3 changes: 3 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ interface IConfig {
fasterMembershipChecks: boolean;
automaticallyRedactForReasons: string[]; // case-insensitive globs
protectAllJoinedRooms: boolean;
admin?: {
enableMakeRoomAdminCommand: boolean;
maranda marked this conversation as resolved.
Show resolved Hide resolved
}
commands: {
allowNoPrefix: boolean;
additionalPrefixes: string[];
Expand Down
111 changes: 111 additions & 0 deletions test/integration/commands/makedminCommandTest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import { strict as assert } from "assert";

import config from "../../../src/config";
import { newTestUser } from "../clientHelper";
import { PowerLevelAction } from "matrix-bot-sdk/lib/models/PowerLevelAction";
import { LogService } from "matrix-bot-sdk";
import { getFirstReaction } from "./commandUtils";

describe("Test: The make admin command", function () {
afterEach(function () {
this.moderator?.stop();
this.userA?.stop();
this.userB?.stop();
this.userC?.stop();
});

it('Mjölnir make the bot self room administrator', async function () {
this.timeout(90000);
if (!config.admin?.enableMakeRoomAdminCommand) {
done();
}
const mjolnir = config.RUNTIME.client!;
const mjolnirUserId = await mjolnir.getUserId();
const moderator = await newTestUser({ name: { contains: "moderator" } });
const userA = await newTestUser({ name: { contains: "a" } });
const userAId = await userA.getUserId();
this.moderator = moderator;
this.userA = userA;
let powerLevels: any;

await moderator.joinRoom(config.managementRoom);
LogService.debug("makeadminTest", `Joining managementRoom: ${config.managementRoom}`);
let targetRoom = await moderator.createRoom({ invite: [mjolnirUserId] });
maranda marked this conversation as resolved.
Show resolved Hide resolved
LogService.debug("makeadminTest", `moderator creating targetRoom: ${targetRoom}; and inviting ${mjolnirUserId}`);
await moderator.sendMessage(this.mjolnir.managementRoomId, { msgtype: 'm.text.', body: `!mjolnir rooms add ${targetRoom}` });
LogService.debug("makeadminTest", `Adding targetRoom: ${targetRoom}`);
try {
await moderator.start();
await userA.start();
await userA.joinRoom(targetRoom);
powerLevels = await mjolnir.getRoomStateEvent(targetRoom, "m.room.power_levels", "");
if (powerLevels["users"][mjolnirUserId] === 100) {
maranda marked this conversation as resolved.
Show resolved Hide resolved
assert.fail(`Bot is already an admin of ${targetRoom}`);
}
await getFirstReaction(mjolnir, this.mjolnir.managementRoomId, '✅', async () => {
LogService.debug("makeadminTest", `Sending: !mjolnir make admin ${targetRoom}`);
return await moderator.sendMessage(this.mjolnir.managementRoomId, { msgtype: 'm.text', body: `!mjolnir make admin ${targetRoom}` });
});
} finally {
await moderator.stop();
await userA.stop();
}
LogService.debug("makeadminTest", `Making self admin`);

powerLevels = await mjolnir.getRoomStateEvent(targetRoom, "m.room.power_levels", "");
assert.equal(powerLevels["users"][mjolnirUserId], 100, "Bot user is not room admin.");
maranda marked this conversation as resolved.
Show resolved Hide resolved
assert.equal(powerLevels["users"][userAId], (0 || undefined), "User A must not be room admin.");
});

it('Mjölnir make the tester room administrator', async function () {
this.timeout(90000);
if (!config.admin?.enableMakeRoomAdminCommand) {
done();
}
const mjolnir = config.RUNTIME.client!;
const moderator = await newTestUser({ name: { contains: "moderator" } });
const userA = await newTestUser({ name: { contains: "a" } });
const userB = await newTestUser({ name: { contains: "b" } });
const userC = await newTestUser({ name: { contains: "c" } });
const userBId = await userB.getUserId();
const userCId = await userC.getUserId();
this.moderator = moderator;
this.userA = userA;
this.userB = userB;
maranda marked this conversation as resolved.
Show resolved Hide resolved
this.userC = userC;
let powerLevels: any;

await moderator.joinRoom(this.mjolnir.managementRoomId);
LogService.debug("makeadminTest", `Joining managementRoom: ${this.mjolnir.managementRoomId}`);
let targetRoom = await userA.createRoom({ invite: [userBId, userCId] });
LogService.debug("makeadminTest", `User A creating targetRoom: ${targetRoom}; and inviting ${userBId} and ${userCId}`);
try {
await userB.start();
await userC.start();
await userB.joinRoom(targetRoom);
await userC.joinRoom(targetRoom);
} finally {
LogService.debug("makeadminTest", `${userBId} and ${userCId} joining targetRoom: ${targetRoom}`);
await userB.stop();
maranda marked this conversation as resolved.
Show resolved Hide resolved
await userC.stop();
}
try {
await moderator.start();
powerLevels = await userA.getRoomStateEvent(targetRoom, "m.room.power_levels", "");
if (powerLevels["users"][userBId] === 100) {
maranda marked this conversation as resolved.
Show resolved Hide resolved
assert.fail(`User B is already an admin of ${targetRoom}`);
}
await getFirstReaction(mjolnir, this.mjolnir.managementRoomId, '✅', async () => {
LogService.debug("makeadminTest", `Sending: !mjolnir make admin ${targetRoom} ${userBId}`);
return await moderator.sendMessage(this.mjolnir.managementRoomId, { msgtype: 'm.text', body: `!mjolnir make admin ${targetRoom} ${userBId}` });
});
} finally {
await moderator.stop();
}
LogService.debug("makeadminTest", `Making User B admin`);

powerLevels = await userA.getRoomStateEvent(targetRoom, "m.room.power_levels", "");
assert.equal(powerLevels["users"][userBId], 100, "User B is not room admin.");
maranda marked this conversation as resolved.
Show resolved Hide resolved
assert.equal(powerLevels["users"][userCId], (0 || undefined), "User C must not be room admin.");
});
});