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

Allow appservice user namespace to contain non .*|.+ suffixes #151

Merged
merged 8 commits into from
Sep 1, 2021
Merged
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
29 changes: 19 additions & 10 deletions src/appservice/Appservice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ export class Appservice extends EventEmitter {
*/
public readonly metrics: Metrics = new Metrics();

private readonly userPrefix: string;
private readonly userPrefix: string | null;
private readonly aliasPrefix: string | null;
private readonly registration: IAppserviceRegistration;
private readonly storage: IAppserviceStorageProvider;
Expand Down Expand Up @@ -259,20 +259,20 @@ export class Appservice extends EventEmitter {

// Everything else can 404

// TODO: Should we permit other user namespaces and instead error when trying to use doSomethingBySuffix()?

if (!this.registration.namespaces || !this.registration.namespaces.users || this.registration.namespaces.users.length === 0) {
throw new Error("No user namespaces in registration");
}
if (this.registration.namespaces.users.length !== 1) {
throw new Error("Too many user namespaces registered: expecting exactly one");
}

this.userPrefix = (this.registration.namespaces.users[0].regex || "").split(":")[0];
if (!this.userPrefix.endsWith(".*") && !this.userPrefix.endsWith(".+")) {
throw new Error("Expected user namespace to be a prefix");
let userPrefix = (this.registration.namespaces.users[0].regex || "").split(":")[0];
if (!userPrefix.endsWith(".*") && !userPrefix.endsWith(".+")) {
this.userPrefix = null;
} else {
this.userPrefix = userPrefix.substring(0, userPrefix.length - 2); // trim off the .* part
}
this.userPrefix = this.userPrefix.substring(0, this.userPrefix.length - 2); // trim off the .* part


if (!this.registration.namespaces || !this.registration.namespaces.aliases || this.registration.namespaces.aliases.length === 0 || this.registration.namespaces.aliases.length !== 1) {
this.aliasPrefix = null;
Expand Down Expand Up @@ -328,9 +328,9 @@ export class Appservice extends EventEmitter {

/**
* Starts the application service, opening the bind address to begin processing requests.
* @returns {Promise<any>} resolves when started
* @returns {Promise<void>} resolves when started
*/
public begin(): Promise<any> {
public begin(): Promise<void> {
return new Promise<void>((resolve, reject) => {
this.appServer = this.app.listen(this.options.port, this.options.bindAddress, () => resolve());
}).then(() => this.botIntent.ensureRegistered());
Expand Down Expand Up @@ -381,6 +381,9 @@ export class Appservice extends EventEmitter {
* @returns {string} The user's ID.
*/
public getUserIdForSuffix(suffix: string): string {
if (!this.userPrefix) {
throw new Error(`Cannot use getUserIdForSuffix, provided namespace did not include a valid suffix`);
}
return `${this.userPrefix}${suffix}:${this.options.homeserverName}`;
}

Expand All @@ -405,6 +408,9 @@ export class Appservice extends EventEmitter {
* @returns {string} The suffix from the user ID.
*/
public getSuffixForUserId(userId: string): string {
if (!this.userPrefix) {
throw new Error(`Cannot use getUserIdForSuffix, provided namespace did not include a valid suffix`);
}
if (!userId || !userId.startsWith(this.userPrefix) || !userId.endsWith(`:${this.options.homeserverName}`)) {
// Invalid ID
return null;
Expand All @@ -425,7 +431,10 @@ export class Appservice extends EventEmitter {
* @returns {boolean} true if the user is namespaced, false otherwise
*/
public isNamespacedUser(userId: string): boolean {
return userId === this.botUserId || (userId.startsWith(this.userPrefix) && userId.endsWith(":" + this.options.homeserverName));
return userId === this.botUserId ||
!!this.registration.namespaces?.users.find(({regex}) =>
new RegExp(regex).test(userId)
Copy link
Owner

Choose a reason for hiding this comment

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

This should probably be cached, but is fine for now

);
}

/**
Expand Down
48 changes: 22 additions & 26 deletions test/appservice/AppserviceTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,32 +99,6 @@ describe('Appservice', () => {
}
});

it('should throw when there is no prefix namespace', async () => {
try {
new Appservice({
port: 0,
bindAddress: '127.0.0.1',
homeserverName: 'localhost',
homeserverUrl: 'https://localhost',
registration: {
as_token: "",
hs_token: "",
sender_localpart: "",
namespaces: {
users: [{exclusive: true, regex: "@.*_suffix:.+"}],
rooms: [],
aliases: [],
},
},
});

// noinspection ExceptionCaughtLocallyJS
throw new Error("Did not throw when expecting it");
} catch (e) {
expect(e.message).toEqual("Expected user namespace to be a prefix");
}
});

it('should accept a ".+" prefix namespace', async () => {
const appservice = new Appservice({
port: 0,
Expand Down Expand Up @@ -165,6 +139,28 @@ describe('Appservice', () => {
expect(appservice.getUserIdForSuffix('foo')).toEqual("@prefix_foo:localhost");
});

it('should allow disabling the suffix check', async () => {
const appservice = new Appservice({
port: 0,
bindAddress: '127.0.0.1',
homeserverName: 'localhost',
homeserverUrl: 'https://localhost',
registration: {
as_token: "",
hs_token: "",
sender_localpart: "",
namespaces: {
users: [{exclusive: true, regex: "@prefix_foo:localhost"}],
rooms: [],
aliases: [],
},
},
});
expect(() => appservice.getUserIdForSuffix('foo')).toThrowError("Cannot use getUserIdForSuffix, provided namespace did not include a valid suffix");
expect(() => appservice.getSuffixForUserId('foo')).toThrowError("Cannot use getUserIdForSuffix, provided namespace did not include a valid suffix");
expect(appservice.isNamespacedUser('@prefix_foo:localhost')).toEqual(true);
});

it('should return the right bot user ID', async () => {
const appservice = new Appservice({
port: 0,
Expand Down