feat: allow ad-hoc creation of new teams (#3964)

Co-authored-by: Tom Moor <tom@getoutline.com>
This commit is contained in:
Nan Yu
2022-10-16 08:57:27 -04:00
committed by GitHub
parent 1fbc000e03
commit 39fc8d5c14
33 changed files with 529 additions and 186 deletions

View File

@@ -25,7 +25,7 @@ describe("accountProvisioner", () => {
username: "jtester",
},
team: {
name: "New team",
name: "New workspace",
avatarUrl: "https://example.com/avatar.png",
subdomain: "example",
},
@@ -44,7 +44,7 @@ describe("accountProvisioner", () => {
expect(auth.accessToken).toEqual("123");
expect(auth.scopes.length).toEqual(1);
expect(auth.scopes[0]).toEqual("read");
expect(team.name).toEqual("New team");
expect(team.name).toEqual("New workspace");
expect(user.email).toEqual("jenny@example-company.com");
expect(user.username).toEqual("jtester");
expect(isNewUser).toEqual(true);

View File

@@ -1,10 +1,8 @@
import invariant from "invariant";
import { UniqueConstraintError } from "sequelize";
import WelcomeEmail from "@server/emails/templates/WelcomeEmail";
import {
AuthenticationError,
InvalidAuthenticationError,
EmailAuthenticationRequiredError,
AuthenticationProviderDisabledError,
} from "@server/errors";
import { APM } from "@server/logging/tracing";
@@ -181,25 +179,7 @@ async function accountProvisioner({
isNewTeam,
};
} catch (err) {
if (err instanceof UniqueConstraintError) {
const exists = await User.findOne({
where: {
email: userParams.email,
teamId: team.id,
},
});
if (exists) {
throw EmailAuthenticationRequiredError(
"Email authentication required",
team.url
);
} else {
throw AuthenticationError(err.message, team.url);
}
}
throw err;
throw AuthenticationError(err.message);
}
}

View File

@@ -0,0 +1,110 @@
import { Transaction } from "sequelize";
import slugify from "slugify";
import { RESERVED_SUBDOMAINS } from "@shared/utils/domains";
import { APM } from "@server/logging/tracing";
import { Team, Event } from "@server/models";
import { generateAvatarUrl } from "@server/utils/avatars";
type Props = {
/** The displayed name of the team */
name: string;
/** The domain name from the email of the user logging in */
domain?: string;
/** The preferred subdomain to provision for the team if not yet created */
subdomain: string;
/** The public url of an image representing the team */
avatarUrl?: string | null;
/** Details of the authentication provider being used */
authenticationProviders: {
/** The name of the authentication provider, eg "google" */
name: string;
/** External identifier of the authentication provider */
providerId: string;
}[];
/** The IP address of the incoming request */
ip: string;
/** Optional transaction to be chained from outside */
transaction: Transaction;
};
async function teamCreator({
name,
domain,
subdomain,
avatarUrl,
authenticationProviders,
ip,
transaction,
}: Props): Promise<Team> {
// If the service did not provide a logo/avatar then we attempt to generate
// one via ClearBit, or fallback to colored initials in worst case scenario
if (!avatarUrl) {
avatarUrl = await generateAvatarUrl({
name,
domain,
id: subdomain,
});
}
const team = await Team.create(
{
name,
avatarUrl,
authenticationProviders,
},
{
include: ["authenticationProviders"],
transaction,
}
);
await Event.create(
{
name: "teams.create",
teamId: team.id,
ip,
},
{
transaction,
}
);
const availableSubdomain = await findAvailableSubdomain(team, subdomain);
await team.update({ subdomain: availableSubdomain }, { transaction });
return team;
}
async function findAvailableSubdomain(team: Team, requestedSubdomain: string) {
// filter subdomain to only valid characters
// if there are less than the minimum length, use a default subdomain
const normalizedSubdomain = slugify(requestedSubdomain, {
lower: true,
strict: true,
});
let subdomain =
normalizedSubdomain.length < 3 ||
RESERVED_SUBDOMAINS.includes(normalizedSubdomain)
? "team"
: normalizedSubdomain;
let append = 0;
for (;;) {
const existing = await Team.findOne({ where: { subdomain } });
if (existing) {
// subdomain was invalid or already used, try another
subdomain = `${normalizedSubdomain}${++append}`;
} else {
break;
}
}
return subdomain;
}
export default APM.traceFunction({
serviceName: "command",
spanName: "teamCreator",
})(teamCreator);

View File

@@ -35,6 +35,7 @@ describe("teamProvisioner", () => {
await buildTeam({
subdomain: "myteam",
});
const result = await teamProvisioner({
name: "Test team",
subdomain: "myteam",
@@ -46,6 +47,7 @@ describe("teamProvisioner", () => {
ip,
});
expect(result.isNewTeam).toEqual(true);
expect(result.team.subdomain).toEqual("myteam1");
});

View File

@@ -1,3 +1,4 @@
import teamCreator from "@server/commands/teamCreator";
import { sequelize } from "@server/database/sequelize";
import env from "@server/env";
import {
@@ -5,10 +6,8 @@ import {
InvalidAuthenticationError,
MaximumTeamsError,
} from "@server/errors";
import Logger from "@server/logging/Logger";
import { APM } from "@server/logging/tracing";
import { Team, AuthenticationProvider, Event } from "@server/models";
import { generateAvatarUrl } from "@server/utils/avatars";
import { Team, AuthenticationProvider } from "@server/models";
type TeamProvisionerResult = {
team: Team;
@@ -106,54 +105,18 @@ async function teamProvisioner({
}
}
// If the service did not provide a logo/avatar then we attempt to generate
// one via ClearBit, or fallback to colored initials in worst case scenario
if (!avatarUrl) {
avatarUrl = await generateAvatarUrl({
// We cannot find an existing team, so we create a new one
const team = await sequelize.transaction((transaction) => {
return teamCreator({
name,
domain,
id: subdomain,
});
}
const team = await sequelize.transaction(async (transaction) => {
const team = await Team.create(
{
name,
avatarUrl,
authenticationProviders: [authenticationProvider],
},
{
include: "authenticationProviders",
transaction,
}
);
await Event.create(
{
name: "teams.create",
teamId: team.id,
ip,
},
{
transaction,
}
);
return team;
});
// Note provisioning the subdomain is done outside of the transaction as
// it is allowed to fail and the team can still be created, it also requires
// failed queries as part of iteration
try {
await provisionSubdomain(team, subdomain);
} catch (err) {
Logger.error("Provisioning subdomain failed", err, {
teamId: team.id,
subdomain,
avatarUrl,
authenticationProviders: [authenticationProvider],
ip,
transaction,
});
}
});
return {
team,
@@ -162,28 +125,6 @@ async function teamProvisioner({
};
}
async function provisionSubdomain(team: Team, requestedSubdomain: string) {
if (team.subdomain) {
return team.subdomain;
}
let subdomain = requestedSubdomain;
let append = 0;
for (;;) {
try {
await team.update({
subdomain,
});
break;
} catch (err) {
// subdomain was invalid or already used, try again
subdomain = `${requestedSubdomain}${++append}`;
}
}
return subdomain;
}
export default APM.traceFunction({
serviceName: "command",
spanName: "teamProvisioner",

View File

@@ -0,0 +1,21 @@
'use strict';
module.exports = {
async up (queryInterface, Sequelize) {
await queryInterface.removeConstraint("authentication_providers", "authentication_providers_providerId_key");
await queryInterface.addConstraint("authentication_providers", {
type: 'unique',
fields: ["providerId", "teamId"],
name: "authentication_providers_providerId_teamId_uk"
});
},
async down (queryInterface, Sequelize) {
await queryInterface.removeConstraint("authentication_providers", "authentication_providers_providerId_teamId_uk");
await queryInterface.addConstraint("authentication_providers", {
type: 'unique',
fields: ["providerId"],
name: "authentication_providers_providerId_key"
});
}
};

View File

@@ -0,0 +1,21 @@
'use strict';
module.exports = {
async up (queryInterface, Sequelize) {
await queryInterface.removeConstraint("user_authentications", "user_authentications_providerId_key");
await queryInterface.addConstraint("user_authentications", {
type: 'unique',
fields: ["providerId", "userId"],
name: "user_authentications_providerId_userId_uk"
});
},
async down (queryInterface, Sequelize) {
await queryInterface.removeConstraint("user_authentications", "user_authentications_providerId_userId_uk");
await queryInterface.addConstraint("user_authentications", {
type: 'unique',
fields: ["providerId"],
name: "user_authentications_providerId_key"
});
}
};

View File

@@ -55,7 +55,7 @@ export type TeamPreferences = Record<string, unknown>;
@Fix
class Team extends ParanoidModel {
@NotContainsUrl
@Length({ max: 255, msg: "name must be 255 characters or less" })
@Length({ min: 2, max: 255, msg: "name must be between 2 to 255 characters" })
@Column
name: string;

View File

@@ -1,3 +1,4 @@
import env from "@server/env";
import { buildUser, buildTeam, buildAdmin } from "@server/test/factories";
import { setupTestDatabase } from "@server/test/support";
import { serialize } from "./index";
@@ -12,6 +13,7 @@ it("should allow reading only", async () => {
const abilities = serialize(user, team);
expect(abilities.read).toEqual(true);
expect(abilities.manage).toEqual(false);
expect(abilities.createTeam).toEqual(false);
expect(abilities.createAttachment).toEqual(true);
expect(abilities.createCollection).toEqual(true);
expect(abilities.createDocument).toEqual(true);
@@ -27,6 +29,25 @@ it("should allow admins to manage", async () => {
const abilities = serialize(admin, team);
expect(abilities.read).toEqual(true);
expect(abilities.manage).toEqual(true);
expect(abilities.createTeam).toEqual(false);
expect(abilities.createAttachment).toEqual(true);
expect(abilities.createCollection).toEqual(true);
expect(abilities.createDocument).toEqual(true);
expect(abilities.createGroup).toEqual(true);
expect(abilities.createIntegration).toEqual(true);
});
it("should allow creation on hosted envs", async () => {
env.DEPLOYMENT = "hosted";
const team = await buildTeam();
const admin = await buildAdmin({
teamId: team.id,
});
const abilities = serialize(admin, team);
expect(abilities.read).toEqual(true);
expect(abilities.manage).toEqual(true);
expect(abilities.createTeam).toEqual(true);
expect(abilities.createAttachment).toEqual(true);
expect(abilities.createCollection).toEqual(true);
expect(abilities.createDocument).toEqual(true);

View File

@@ -1,3 +1,4 @@
import env from "@server/env";
import { Team, User } from "@server/models";
import { allow } from "./cancan";
@@ -10,6 +11,12 @@ allow(User, "share", Team, (user, team) => {
return team.sharing;
});
allow(User, "createTeam", Team, () => {
if (env.DEPLOYMENT !== "hosted") {
throw "createTeam only available on cloud";
}
});
allow(User, ["update", "manage"], Team, (user, team) => {
if (!team || user.isViewer || user.teamId !== team.id) {
return false;

View File

@@ -73,21 +73,20 @@ describe("#authenticationProviders.update", () => {
const user = await buildAdmin({
teamId: team.id,
});
await team.$create("authenticationProvider", {
const googleProvider = await team.$create("authenticationProvider", {
name: "google",
providerId: uuidv4(),
});
const authenticationProviders = await team.$get("authenticationProviders");
const res = await server.post("/api/authenticationProviders.update", {
body: {
id: authenticationProviders[0].id,
id: googleProvider.id,
isEnabled: false,
token: user.getJwtToken(),
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.name).toBe("slack");
expect(body.data.name).toBe("google");
expect(body.data.isEnabled).toBe(false);
expect(body.data.isConnected).toBe(true);
});

View File

@@ -30,6 +30,7 @@ router.post("authenticationProviders.update", auth(), async (ctx) => {
assertPresent(isEnabled, "isEnabled is required");
const { user } = ctx.state;
const authenticationProvider = await AuthenticationProvider.findByPk(id);
authorize(user, "update", authenticationProvider);
const enabled = !!isEnabled;

View File

@@ -1,9 +1,41 @@
import env from "@server/env";
import { TeamDomain } from "@server/models";
import { buildAdmin, buildCollection, buildTeam } from "@server/test/factories";
import { seed, getTestServer } from "@server/test/support";
const server = getTestServer();
describe("teams.create", () => {
it("creates a team", async () => {
env.DEPLOYMENT = "hosted";
const team = await buildTeam();
const user = await buildAdmin({ teamId: team.id });
const res = await server.post("/api/teams.create", {
body: {
token: user.getJwtToken(),
name: "new workspace",
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.team.name).toEqual("new workspace");
expect(body.data.team.subdomain).toEqual("new-workspace");
});
it("requires a cloud hosted deployment", async () => {
env.DEPLOYMENT = "self-hosted";
const team = await buildTeam();
const user = await buildAdmin({ teamId: team.id });
const res = await server.post("/api/teams.create", {
body: {
token: user.getJwtToken(),
name: "new workspace",
},
});
expect(res.status).toEqual(500);
});
});
describe("#team.update", () => {
it("should update team details", async () => {
const { admin } = await seed();

View File

@@ -1,9 +1,12 @@
import invariant from "invariant";
import Router from "koa-router";
import { RateLimiterStrategy } from "@server/RateLimiter";
import teamCreator from "@server/commands/teamCreator";
import teamUpdater from "@server/commands/teamUpdater";
import { sequelize } from "@server/database/sequelize";
import auth from "@server/middlewares/authentication";
import { rateLimiter } from "@server/middlewares/rateLimiter";
import { Team, TeamDomain } from "@server/models";
import { Event, Team, TeamDomain, User } from "@server/models";
import { authorize } from "@server/policies";
import { presentTeam, presentPolicies } from "@server/presenters";
import { assertUuid } from "@server/validation";
@@ -69,4 +72,83 @@ router.post(
}
);
router.post(
"teams.create",
auth(),
rateLimiter(RateLimiterStrategy.FivePerHour),
async (ctx) => {
const { user } = ctx.state;
const { name } = ctx.body;
const existingTeam = await Team.scope(
"withAuthenticationProviders"
).findByPk(user.teamId, {
rejectOnEmpty: true,
});
authorize(user, "createTeam", existingTeam);
const authenticationProviders = existingTeam.authenticationProviders.map(
(provider) => {
return {
name: provider.name,
providerId: provider.providerId,
};
}
);
invariant(
authenticationProviders?.length,
"Team must have at least one authentication provider"
);
const [team, newUser] = await sequelize.transaction(async (transaction) => {
const team = await teamCreator({
name,
subdomain: name,
authenticationProviders,
ip: ctx.ip,
transaction,
});
const newUser = await User.create(
{
teamId: team.id,
name: user.name,
email: user.email,
isAdmin: true,
avatarUrl: user.avatarUrl,
},
{ transaction }
);
await Event.create(
{
name: "users.create",
actorId: user.id,
userId: newUser.id,
teamId: newUser.teamId,
data: {
name: newUser.name,
},
ip: ctx.ip,
},
{ transaction }
);
return [team, newUser];
});
ctx.body = {
success: true,
data: {
team: presentTeam(team),
transferUrl: `${
team.url
}/auth/redirect?token=${newUser?.getTransferToken()}`,
},
};
}
);
export default router;