Prevent adding users as guests when their email matches a workspace domain (#14726)

* Prevent adding users as guests when their email matches a workspace domain

* Address review: skip existing users, use transaction, invite team domain emails as members from share popovers
This commit is contained in:
Tom Moor authored and GitHub committed 2026-11-26 09:48:40 -05:00
1 parent c7cf99aabc
commit 578bf73e6b
8 files changed
+183 -9

No files matched your search

@@ -231,7 +231,9 @@ function SharePopover({
{
email: idOrEmail,
name: idOrEmail,
role: inviteRole,
role: team.isTeamDomain(idOrEmail)
? team.defaultUserRole
: inviteRole,
},
]);
user = response[0];
@@ -328,6 +330,7 @@ function SharePopover({
isOwnerInvite,
t,
inviteRole,
team,
users,
]
);
@@ -191,7 +191,9 @@ function SharePopover({
{
email: idOrEmail,
name: idOrEmail,
role: inviteRole,
role: team.isTeamDomain(idOrEmail)
? team.defaultUserRole
: inviteRole,
},
]);
user = response[0];
@@ -287,6 +289,7 @@ function SharePopover({
isOwnerInvite,
t,
inviteRole,
team,
users,
]
);
+11
View File
@@ -127,6 +127,17 @@ class Team extends Model {
return access !== CommentingAccess.None && access !== false;
}
/**
* Whether the email address is on one of the team's domains.
*
* @param email The email address to check.
* @returns true if the email domain matches a team domain.
*/
isTeamDomain(email: string): boolean {
const domain = email.split("@").pop()?.toLowerCase();
return !!domain && !!this.allowedDomains?.includes(domain);
}
/**
* Whether the team is entitled to use the given feature.
*
+91 -3
View File
@@ -1,9 +1,9 @@
import { faker } from "@faker-js/faker";
import { UserRole } from "@shared/types";
import { buildTeam, buildUser } from "@server/test/factories";
import { Plan, UserRole } from "@shared/types";
import { buildAdmin, buildTeam, buildUser } from "@server/test/factories";
import userInviter from "./userInviter";
import { withContext } from "@server/test/support";
import { TeamDomain } from "@server/models";
import { Team, TeamDomain } from "@server/models";
describe("userInviter", () => {
it("should return sent invites", async () => {
@@ -90,6 +90,94 @@ describe("userInviter", () => {
expect(response.sent[0].email).toEqual(`test@${allowedDomain}`);
});
it("should error on guest invites for workspace domains", async () => {
const planSpy = vi
.spyOn(Team.prototype, "plan", "get")
.mockReturnValue(Plan.Business);
onTestFinished(() => planSpy.mockRestore());
const team = await buildTeam();
const user = await buildAdmin({ teamId: team.id });
await TeamDomain.create({
teamId: team.id,
name: "acme.org",
createdById: user.id,
});
await withContext(user, (ctx) =>
expect(
userInviter(ctx, {
invites: [
{
role: UserRole.Guest,
email: "Test@Acme.org",
name: "Test",
},
],
})
).rejects.toThrow(
"Users with an email on a workspace domain cannot be added as guests"
)
);
});
it("should skip guest invites for existing members on workspace domains", async () => {
const planSpy = vi
.spyOn(Team.prototype, "plan", "get")
.mockReturnValue(Plan.Business);
onTestFinished(() => planSpy.mockRestore());
const team = await buildTeam();
const user = await buildAdmin({ teamId: team.id });
await buildUser({ teamId: team.id, email: "member@acme.org" });
await TeamDomain.create({
teamId: team.id,
name: "acme.org",
createdById: user.id,
});
const response = await withContext(user, (ctx) =>
userInviter(ctx, {
invites: [
{
role: UserRole.Guest,
email: "member@acme.org",
name: "Test",
},
],
})
);
expect(response.unsent.length).toEqual(1);
});
it("should allow guest invites for other domains", async () => {
const planSpy = vi
.spyOn(Team.prototype, "plan", "get")
.mockReturnValue(Plan.Business);
onTestFinished(() => planSpy.mockRestore());
const team = await buildTeam();
const user = await buildAdmin({ teamId: team.id });
await TeamDomain.create({
teamId: team.id,
name: "acme.org",
createdById: user.id,
});
const response = await withContext(user, (ctx) =>
userInviter(ctx, {
invites: [
{
role: UserRole.Guest,
email: "test@other.com",
name: "Test",
},
],
})
);
expect(response.sent.length).toEqual(1);
});
it("should filter obviously bunk emails", async () => {
const user = await buildUser();
const response = await withContext(user, (ctx) =>
+13 -1
View File
@@ -6,7 +6,7 @@ import Logger from "@server/logging/Logger";
import { User, Team } from "@server/models";
import { UserFlag } from "@server/models/User";
import type { Context } from "@server/types";
import { DomainNotAllowedError } from "@server/errors";
import { DomainNotAllowedError, ValidationError } from "@server/errors";
import { authorize, can } from "@server/policies";
export type Invite = {
@@ -71,6 +71,18 @@ export default async function userInviter(
normalizedInvites,
(invite) => existingEmails.includes(invite.email)
);
for (const invite of filteredInvites) {
if (
invite.role === UserRole.Guest &&
(await team.isTeamDomain(invite.email))
) {
throw ValidationError(
"Users with an email on a workspace domain cannot be added as guests"
);
}
}
const users = [];
// send and record remaining invites
+24 -1
View File
@@ -1,11 +1,12 @@
import { randomUUID } from "node:crypto";
import { TeamValidation } from "@shared/validations";
import { Team } from "@server/models";
import { Team, TeamDomain } from "@server/models";
import {
buildTeam,
buildCollection,
buildAttachment,
buildSubdomain,
buildUser,
} from "@server/test/factories";
describe("Team", () => {
@@ -103,6 +104,28 @@ describe("Team", () => {
});
});
describe("isTeamDomain", () => {
it("should return false when the team has no domains", async () => {
const team = await buildTeam();
expect(await team.isTeamDomain("test@acme.org")).toEqual(false);
});
it("should match emails and domains regardless of case", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
await TeamDomain.create({
teamId: team.id,
name: "Acme.org",
createdById: user.id,
});
expect(await team.isTeamDomain("test@acme.org")).toEqual(true);
expect(await team.isTeamDomain("Test@ACME.org")).toEqual(true);
expect(await team.isTeamDomain("ACME.ORG")).toEqual(true);
expect(await team.isTeamDomain("test@other.org")).toEqual(false);
});
});
describe("collectionIds", () => {
it("should return non-private collection ids", async () => {
const team = await buildTeam();
+28 -1
View File
@@ -2,7 +2,11 @@ import crypto from "node:crypto";
import { URL } from "node:url";
import { addDays, subMinutes } from "date-fns";
import type { InferAttributes, InferCreationAttributes } from "sequelize";
import { type FindOptions, type SaveOptions } from "sequelize";
import {
type FindOptions,
type SaveOptions,
type Transaction,
} from "sequelize";
import { Op } from "sequelize";
import {
Column,
@@ -494,6 +498,29 @@ class Team extends ParanoidModel<
);
};
/**
* Find whether the passed domain or email matches one of the team's domains.
* Unlike isDomainAllowed, this returns false if no domains are set.
*
* @param domainOrEmail The domain or email to check.
* @param options Options such as the transaction to query with.
* @returns True if the domain matches a team domain.
*/
public isTeamDomain = async function (
this: Team,
domainOrEmail: string,
options?: { transaction?: Transaction | null }
): Promise<boolean> {
const allowedDomains = (await this.$get("allowedDomains", options)) || [];
const domain = isEmail(domainOrEmail)
? parseEmail(domainOrEmail).domain
: domainOrEmail.toLowerCase();
return allowedDomains.some(
(d: TeamDomain) => d.name.toLowerCase() === domain
);
};
// associations
@HasMany(() => Collection)
+8 -1
View File
@@ -386,9 +386,10 @@ async function updateRole(ctx: Context<T.UsersChangeRoleReq>) {
});
authorize(actor, "update", user);
await Team.findByPk(user.teamId, {
const team = await Team.findByPk(user.teamId, {
transaction,
lock: transaction.LOCK.NO_KEY_UPDATE,
rejectOnEmpty: true,
});
let name;
@@ -410,6 +411,12 @@ async function updateRole(ctx: Context<T.UsersChangeRoleReq>) {
}
if (role === UserRole.Guest) {
authorize(actor, "addGuest", actor.team);
if (user.email && (await team.isTeamDomain(user.email, { transaction }))) {
throw ValidationError(
"Users with an email on a workspace domain cannot be added as guests"
);
}
}
await user.updateWithCtx(ctx, { role }, { name });