Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

build: Remove ORI permission system (#3624)

Ivan Starkovdb97945c69a4
diff --git a/apps/builder/app/shared/context.server.ts b/apps/builder/app/shared/context.server.ts
index 82b0e8e840..d873d02ed2 100644
--- a/apps/builder/app/shared/context.server.ts
+++ b/apps/builder/app/shared/context.server.ts
@@ -1,8 +1,9 @@
-import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
+import { type AppContext } from "@webstudio-is/trpc-interface/index.server";
import env from "~/env/env.server";
import { authenticator } from "~/services/auth.server";
import { trpcSharedClient } from "~/services/trpc.server";
import { entryApi } from "./entri/entri-api.server";
+
import {
getTokenPlanFeatures,
getUserPlanFeatures,
@@ -29,7 +30,6 @@ const createAuthorizationContext = async (
userId: user?.id,
authToken,
isServiceCall,
- authorizeTrpc: trpcSharedClient.authorize,
};
return context;
diff --git a/packages/authorization-token/src/db/authorization-token.ts b/packages/authorization-token/src/db/authorization-token.ts
index 76064e8be4..5f043ec7c7 100644
--- a/packages/authorization-token/src/db/authorization-token.ts
+++ b/packages/authorization-token/src/db/authorization-token.ts
@@ -5,7 +5,6 @@ import {
} from "@webstudio-is/prisma-client";
import {
authorizeProject,
- authorizeAuthorizationToken,
type AppContext,
AuthorizationError,
} from "@webstudio-is/trpc-interface/index.server";
@@ -26,22 +25,9 @@ export const findMany = async (
);
}
- // Get all leaf nodes for the project
- const leafNodes =
- await context.authorization.authorizeTrpc.expandLeafNodes.query({
- namespace: "Project",
- id: props.projectId,
- });
-
- const tokenLeafNodes = leafNodes.filter(
- (leafNode) => leafNode.namespace === "Token"
- );
-
const dbTokens = await prisma.authorizationToken.findMany({
where: {
- token: {
- in: tokenLeafNodes.map((leafNode) => leafNode.id),
- },
+ projectId: props.projectId,
},
// Stable order
orderBy: [
@@ -114,15 +100,6 @@ export const create = async (
);
}
- await authorizeAuthorizationToken.registerToken(
- {
- tokenId,
- projectId: props.projectId,
- relation: props.relation,
- },
- context
- );
-
const dbToken = await prisma.authorizationToken.create({
data: {
projectId: props.projectId,
@@ -167,15 +144,6 @@ export const update = async (
throw new AuthorizationError("Authorization token not found");
}
- if (previousToken.relation !== props.relation) {
- await authorizeAuthorizationToken.patchToken(
- { tokenId: props.token, projectId },
- previousToken.relation,
- props.relation,
- context
- );
- }
-
const dbToken = await prisma.authorizationToken.update({
where: {
// eslint-disable-next-line camelcase
diff --git a/packages/project/src/db/project.ts b/packages/project/src/db/project.ts
index 05efad4405..3d5b47abc8 100644
--- a/packages/project/src/db/project.ts
+++ b/packages/project/src/db/project.ts
@@ -53,7 +53,6 @@ export const create = async (
}
const projectId = crypto.randomUUID();
- await authorizeProject.registerProjectOwner({ projectId }, context);
const project = await prisma.$transaction(async (client) => {
const project = await client.project.create({
@@ -165,10 +164,6 @@ export const clone = async (
}
const newProjectId = crypto.randomUUID();
- await authorizeProject.registerProjectOwner(
- { projectId: newProjectId },
- context
- );
const clonedProject = await prisma.$transaction(async (client) => {
await cloneAssets(
diff --git a/packages/trpc-interface/package.json b/packages/trpc-interface/package.json
index 8fafaa53ab..8defd81019 100644
--- a/packages/trpc-interface/package.json
+++ b/packages/trpc-interface/package.json
@@ -14,6 +14,7 @@
"@trpc/client": "^10.38.1",
"@trpc/server": "^10.38.1",
"@webstudio-is/prisma-client": "workspace:*",
+ "memoize": "^10.0.0",
"ts-custom-error": "^3.3.1",
"zod": "^3.22.4"
},
diff --git a/packages/trpc-interface/src/authorize/authorization-token.server.ts b/packages/trpc-interface/src/authorize/authorization-token.server.ts
deleted file mode 100644
index d0ffcc6194..0000000000
--- a/packages/trpc-interface/src/authorize/authorization-token.server.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-import type { AppContext } from "../context/context.server";
-
-/**
- * For 3rd party authorization systems like Ory we need to register token for the project.
- *
- * We do that before the authorizationToken create (and out of the transaction),
- * so in case of an error we will have just stale records of non existed projects in authorization system.
- */
-export const registerToken = async (
- props: {
- projectId: string;
- tokenId: string;
- relation: "viewers" | "editors" | "builders" | "administrators";
- },
- context: AppContext
-) => {
- const { authorization } = context;
- const { userId, authorizeTrpc } = authorization;
-
- if (userId === undefined) {
- throw new Error("The user must be authenticated to create a token");
- }
-
- await authorizeTrpc.create.mutate({
- namespace: "Project",
- id: props.projectId,
- relation: props.relation,
- subjectSet: {
- namespace: "Token",
- id: props.tokenId,
- },
- });
-};
-
-// Implement any update operations in the single transaction on authorization system
-export const patchToken = async (
- props: { projectId: string; tokenId: string },
-
- prevRelation: "viewers" | "editors" | "builders" | "administrators",
-
- nextRelation: "viewers" | "editors" | "builders" | "administrators",
-
- context: AppContext
-) => {
- const { authorization } = context;
- const { userId, authorizeTrpc } = authorization;
-
- if (userId === undefined) {
- throw new Error("The user must be authenticated to delete a token");
- }
-
- if (prevRelation !== nextRelation) {
- await authorizeTrpc.patch.mutate([
- {
- action: "delete",
- relationTuple: {
- namespace: "Project",
- id: props.projectId,
- relation: prevRelation,
- subjectSet: {
- namespace: "Token",
- id: props.tokenId,
- },
- },
- },
- {
- action: "insert",
- relationTuple: {
- namespace: "Project",
- id: props.projectId,
- relation: nextRelation,
- subjectSet: {
- namespace: "Token",
- id: props.tokenId,
- },
- },
- },
- ]);
- }
-};
-
-export const unregisterToken = async (
- props: {
- projectId: string;
- tokenId: string;
- relation: "viewers" | "editors";
- },
- context: AppContext
-) => {
- const { authorization } = context;
- const { userId, authorizeTrpc } = authorization;
-
- if (userId === undefined) {
- throw new Error("The user must be authenticated to delete a token");
- }
-
- await authorizeTrpc.delete.mutate({
- namespace: "Project",
- id: props.projectId,
- relation: props.relation,
- subjectSet: {
- namespace: "Token",
- id: props.tokenId,
- },
- });
-};
diff --git a/packages/trpc-interface/src/authorize/project.server.ts b/packages/trpc-interface/src/authorize/project.server.ts
index da9d57b40a..6c271907b6 100644
--- a/packages/trpc-interface/src/authorize/project.server.ts
+++ b/packages/trpc-interface/src/authorize/project.server.ts
@@ -1,35 +1,70 @@
import type { Project } from "@webstudio-is/prisma-client";
-import type { AuthPermit } from "../shared/authorization-router";
import type { AppContext } from "../context/context.server";
+import { prisma } from "@webstudio-is/prisma-client";
+import memoize from "memoize";
-/**
- * For 3rd party authorization systems like Ory we need to register the project owner.
- *
- * We do that before the project create (and out of the transaction),
- * so in case of an error we will have just stale records of non existed projects in authorization system.
- */
-export const registerProjectOwner = async (
- props: { projectId: string },
- context: AppContext
-) => {
- const { authorization } = context;
- const { userId, authorizeTrpc } = authorization;
+export type AuthPermit = "view" | "edit" | "build" | "admin" | "own";
+
+type CheckInput = {
+ namespace: "Project";
+ id: string;
+
+ permit: AuthPermit;
- if (userId === undefined) {
- throw new Error("The user must be authenticated to create a project");
+ subjectSet: {
+ namespace: "User" | "Token";
+ id: string;
+ };
+};
+
+const check = async (input: CheckInput) => {
+ const { subjectSet } = input;
+
+ if (subjectSet.namespace === "User") {
+ // We check only if the user is the owner of the project
+ const row = await prisma.project.findFirst({
+ where: {
+ id: input.id,
+ userId: subjectSet.id,
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ return { allowed: row !== null };
}
- await authorizeTrpc.create.mutate({
- namespace: "Project",
- id: props.projectId,
- relation: "owners",
- subjectSet: {
- namespace: "User",
- id: userId,
- },
- });
+ const permitToRelationRewrite = {
+ view: ["viewers", "editors", "builders", "administrators"],
+ edit: ["editors", "builders", "administrators"],
+ build: ["builders", "administrators"],
+ admin: ["administrators"],
+ } as const;
+
+ if (subjectSet.namespace === "Token" && input.permit !== "own") {
+ const row = await prisma.authorizationToken.findFirst({
+ where: {
+ token: subjectSet.id,
+ relation: {
+ in: [...permitToRelationRewrite[input.permit]],
+ },
+ },
+ select: { token: true },
+ });
+
+ return { allowed: row !== null };
+ }
+
+ return { allowed: false };
};
+const memoizedCheck = memoize(check, {
+ // 1 minute
+ maxAge: 60 * 1000,
+ cacheKey: JSON.stringify,
+});
+
export const hasProjectPermit = async (
props: {
projectId: Project["id"];
@@ -41,13 +76,12 @@ export const hasProjectPermit = async (
try {
const { authorization } = context;
- const { authorizeTrpc } = authorization;
const checks = [];
const namespace = "Project";
// Allow load production build env i.e. "published" project
- if (props.permit === "view" && context.authorization.isServiceCall) {
+ if (props.permit === "view" && authorization.isServiceCall) {
return true;
}
@@ -71,7 +105,7 @@ export const hasProjectPermit = async (
// Check if the user is allowed to access the project
if (authorization.userId !== undefined) {
checks.push(
- authorizeTrpc.check.query({
+ memoizedCheck({
subjectSet: {
namespace: "User",
id: authorization.userId,
@@ -87,7 +121,7 @@ export const hasProjectPermit = async (
// Token doesn't have own permit, do not check it
if (authorization.authToken !== undefined && props.permit !== "own") {
checks.push(
- authorizeTrpc.check.query({
+ memoizedCheck({
namespace,
id: props.projectId,
subjectSet: {
diff --git a/packages/trpc-interface/src/context/context.server.ts b/packages/trpc-interface/src/context/context.server.ts
index ca6bb9cd0a..3f46ddd665 100644
--- a/packages/trpc-interface/src/context/context.server.ts
+++ b/packages/trpc-interface/src/context/context.server.ts
@@ -18,9 +18,6 @@ type AuthorizationContext = {
* Allow service 2 service communications to skip authorization for view calls
*/
isServiceCall: boolean;
-
- // Pass trpcClient through context as only main app can initialize it
- authorizeTrpc: TrpcInterfaceClient["authorize"];
};
type DomainContext = {
diff --git a/packages/trpc-interface/src/index.server.ts b/packages/trpc-interface/src/index.server.ts
index e14cad054f..93dcdff447 100644
--- a/packages/trpc-interface/src/index.server.ts
+++ b/packages/trpc-interface/src/index.server.ts
@@ -5,8 +5,8 @@ export type { AppContext } from "./context/context.server";
export { AuthorizationError } from "./context/errors.server";
export * as authorizeProject from "./authorize/project.server";
-export * as authorizeAuthorizationToken from "./authorize/authorization-token.server";
-export type { AuthPermit } from "./shared/authorization-router";
+export type { AuthPermit } from "./authorize/project.server";
+
export {
router,
procedure,
diff --git a/packages/trpc-interface/src/shared/authorization-router.ts b/packages/trpc-interface/src/shared/authorization-router.ts
deleted file mode 100644
index 2f1c2b5388..0000000000
--- a/packages/trpc-interface/src/shared/authorization-router.ts
+++ /dev/null
@@ -1,205 +0,0 @@
-import { z } from "zod";
-import { router, procedure } from "./trpc";
-
-import { prisma } from "@webstudio-is/prisma-client";
-
-const Relation = z.enum([
- "viewers",
- "editors",
- "builders",
- "administrators",
- "owners",
-]);
-const AuthPermit = z.enum(["view", "edit", "build", "admin", "own"]);
-export type AuthPermit = z.infer<typeof AuthPermit>;
-
-const DeleteCreateInput = z.discriminatedUnion("namespace", [
- z.object({
- namespace: z.literal("Project"),
- id: z.string(),
- relation: Relation,
-
- subjectSet: z.discriminatedUnion("namespace", [
- z.object({
- namespace: z.literal("User"),
- id: z.string(),
- }),
- z.object({
- namespace: z.literal("Token"),
- id: z.string(),
- }),
- z.object({
- namespace: z.literal("Email"),
- id: z.string(),
- relation: z.literal("owners"),
- }),
- ]),
- }),
-
- z.object({
- namespace: z.literal("Email"),
- id: z.string(),
- relation: z.enum(["owners"]),
- subjectSet: z.object({
- namespace: z.literal("User"),
- id: z.string(),
- }),
- }),
-]);
-
-export const authorizationRouter = router({
- /**
- * Relation expansion in authorize looks like a tree
- *
- * :#@Project:AliceProjectUUID#viewers
- * :#@Email:[email protected]#owner
- * :#@User:BobUUID️
- * :#@Token:LinkRandomSequence️
- *
- * We don't need the whole tree in UI and need only the leaf nodes.
- * i.e. @User:BobUUID️, @Token:LinkRandomSequence️ and the root relation i.e "viewers"
- */
- expandLeafNodes: procedure
- .input(
- z.object({
- namespace: z.literal("Project"),
- id: z.string(),
- })
- )
- .output(
- z.array(
- z.object({
- // top level relation
- relation: Relation,
- // subjectSet
- namespace: z.enum(["Email", "User", "Token"]),
- id: z.string(),
- })
- )
- )
- .query(async ({ input }) => {
- // Implement ory expand, on all relations
- const { namespace, id } = input;
- if (namespace !== "Project") {
- throw new Error("Not implemented");
- }
-
- // At OSS we support only owner relation for the users
- const ownerRow = await prisma.project.findUnique({
- where: {
- id,
- },
- select: {
- userId: true,
- },
- });
-
- const tokenRows = await prisma.authorizationToken.findMany({
- where: {
- projectId: id,
- },
- });
-
- const leafSubjectSets = [];
-
- if (ownerRow !== null && ownerRow.userId !== null) {
- leafSubjectSets.push({
- namespace: "User",
- id: ownerRow.userId,
- relation: "owners",
- } as const);
- }
-
- for (const tokenRow of tokenRows) {
- leafSubjectSets.push({
- namespace: "Token",
- id: tokenRow.token,
- relation: tokenRow.relation,
- } as const);
- }
-
- return leafSubjectSets;
- }),
-
- /**
- * Check if subject has permit on the resource
- */
- check: procedure
- .input(
- z.object({
- namespace: z.enum(["Project"]),
- id: z.string(),
-
- permit: AuthPermit,
-
- subjectSet: z.object({
- namespace: z.enum(["User", "Token"]),
- id: z.string(),
- }),
- })
- )
- .output(z.object({ allowed: z.boolean() }))
- .query(async ({ input }) => {
- const { subjectSet } = input;
-
- if (subjectSet.namespace === "User") {
- // We check only if the user is the owner of the project
- const row = await prisma.project.findFirst({
- where: {
- id: input.id,
- userId: subjectSet.id,
- },
- select: {
- id: true,
- },
- });
-
- return { allowed: row !== null };
- }
-
- const permitToRelationRewrite = {
- view: ["viewers", "editors", "builders", "administrators"],
- edit: ["editors", "builders", "administrators"],
- build: ["builders", "administrators"],
- admin: ["administrators"],
- } as const;
-
- if (subjectSet.namespace === "Token" && input.permit !== "own") {
- const row = await prisma.authorizationToken.findFirst({
- where: {
- token: subjectSet.id,
- relation: {
- in: [...permitToRelationRewrite[input.permit]],
- },
- },
- select: { token: true },
- });
-
- return { allowed: row !== null };
- }
-
- return { allowed: false };
- }),
- /**
- * In OSS we extract owner relation from the Project table, and the rest from the authorizationToken table
- */
- create: procedure.input(DeleteCreateInput).mutation(async ({ input }) => {
- // Do nothing in OSS
- }),
-
- delete: procedure.input(DeleteCreateInput).mutation(async ({ input }) => {
- // Do nothing in OSS
- }),
- patch: procedure
- .input(
- z.array(
- z.object({
- action: z.enum(["insert", "delete"]),
- relationTuple: DeleteCreateInput,
- })
- )
- )
- .mutation(async ({ input }) => {
- // Do nothing in OSS
- }),
-});
diff --git a/packages/trpc-interface/src/shared/shared-router.ts b/packages/trpc-interface/src/shared/shared-router.ts
index c935624056..e95ab7ffea 100644
--- a/packages/trpc-interface/src/shared/shared-router.ts
+++ b/packages/trpc-interface/src/shared/shared-router.ts
@@ -1,11 +1,9 @@
import type { createTRPCProxyClient } from "@trpc/client";
import { router } from "./trpc";
-import { authorizationRouter } from "./authorization-router";
import { domainRouter } from "./domain";
import { deploymentRouter } from "./deployment";
export const sharedRouter = router({
- authorize: authorizationRouter,
domain: domainRouter,
deployment: deploymentRouter,
});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index fefcb90b7c..db06af9a57 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2012,6 +2012,9 @@ importers:
'@webstudio-is/prisma-client':
specifier: workspace:*
version: link:../prisma-client
+ memoize:
+ specifier: ^10.0.0
+ version: 10.0.0
ts-custom-error:
specifier: ^3.3.1
version: 3.3.1
@@ -7955,6 +7958,10 @@ packages:
resolution: {integrity: sha512-rkpe71W0N0c0Xz6QD0eJETuWAJGnJ9afsl1srmwPrI+yBCkge5EycXXbYRyvL29zZVUWQCY7InPRCv3GDXuZNw==}
+ resolution: {integrity: sha512-H6cBLgsi6vMWOcCpvVCdFFnl3kerEXbrYh9q+lY6VXvQSmM6CkmV08VOwT+WE2tzIEqRPFfAq3fm4v/UIW6mSA==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-/EuHYwAPdLtXwAwSZkh/Gutery6pD2KYd44oQLhAvQp/50mpyduZh8Q7PYHXTCJ+wuXxt7oij2LXyIJOOYFPog==}
@@ -8178,6 +8185,10 @@ packages:
resolution: {integrity: sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==}
engines: {node: '>=4'}
@@ -14661,7 +14672,7 @@ snapshots:
'@vue/reactivity-transform': 3.3.4
'@vue/shared': 3.3.4
estree-walker: 2.0.2
- magic-string: 0.30.1
+ magic-string: 0.30.10
postcss: 8.4.38
source-map-js: 1.2.0
@@ -14676,7 +14687,7 @@ snapshots:
'@vue/compiler-core': 3.3.4
'@vue/shared': 3.3.4
estree-walker: 2.0.2
- magic-string: 0.30.1
+ magic-string: 0.30.10
dependencies:
@@ -17579,6 +17590,10 @@ snapshots:
+ dependencies:
+ mimic-function: 5.0.1
+
dependencies:
map-or-similar: 1.5.0
@@ -18012,6 +18027,8 @@ snapshots:
+
@@ -19428,7 +19445,7 @@ snapshots:
estree-walker: 3.0.3
is-reference: 3.0.1
locate-character: 3.0.0
- magic-string: 0.30.1
+ magic-string: 0.30.10
periscopic: 3.1.0