chore: profile repository refactor (#25328)
* chore: profile repository refactor * remove comment * remove comment * cleaning * review addressed * rename the method name
This commit is contained in:
1 parent
7ca2082c62
commit
b98bb8b852
11 files changed
+785
-37
No files matched your search
@@ -557,7 +557,7 @@ export const getOptions = ({
|
||||
);
|
||||
const { upId } = determineProfile({ profiles: allProfiles, token });
|
||||
|
||||
const profile = await ProfileRepository.findByUpId(upId);
|
||||
const profile = await ProfileRepository.findByUpIdWithAuth(upId, existingUser.id);
|
||||
if (!profile) {
|
||||
throw new Error("Profile not found");
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ export type EventTypesByViewer = Awaited<ReturnType<typeof getEventTypesByViewer
|
||||
|
||||
export const getEventTypesByViewer = async (user: User, filters?: Filters, forRoutingForms?: boolean) => {
|
||||
const userProfile = user.profile;
|
||||
const profile = await ProfileRepository.findByUpId(userProfile.upId);
|
||||
const profile = await ProfileRepository.findByUpIdWithAuth(userProfile.upId, user.id);
|
||||
const parentOrgHasLockedEventTypes =
|
||||
profile?.organization?.organizationSettings?.lockEventTypeCreationForUsers;
|
||||
const isFilterSet = filters && hasFilter(filters);
|
||||
|
||||
@@ -166,7 +166,16 @@ export class EventTypeRepository {
|
||||
) {
|
||||
if (!upId) return [];
|
||||
const lookupTarget = ProfileRepository.getLookupTarget(upId);
|
||||
const profileId = lookupTarget.type === LookupTarget.User ? null : lookupTarget.id;
|
||||
// Handle both UUID-based and legacy numeric profile IDs
|
||||
let profileId: number | null = null;
|
||||
if (lookupTarget.type === LookupTarget.Profile) {
|
||||
if ("uid" in lookupTarget && lookupTarget.uid) {
|
||||
const profile = await ProfileRepository.findByUid(lookupTarget.uid);
|
||||
profileId = profile?.id ?? null;
|
||||
} else if ("id" in lookupTarget && lookupTarget.id !== undefined) {
|
||||
profileId = lookupTarget.id;
|
||||
}
|
||||
}
|
||||
const select = {
|
||||
...eventTypeSelect,
|
||||
hashedLink: hashedLinkSelect,
|
||||
|
||||
@@ -61,12 +61,23 @@ const getWhereForfindAllByUpId = async (upId: string, where?: Prisma.MembershipW
|
||||
* TODO: When we add profileId to membership, we lookup by profileId
|
||||
* If the profile is movedFromUser, we lookup all memberships without profileId as well.
|
||||
*/
|
||||
const profile = await ProfileRepository.findById(lookupTarget.id);
|
||||
let profile;
|
||||
if ("uid" in lookupTarget && lookupTarget.uid) {
|
||||
profile = await ProfileRepository.findByUid(lookupTarget.uid);
|
||||
} else if ("id" in lookupTarget && lookupTarget.id !== undefined) {
|
||||
profile = await ProfileRepository.findById(lookupTarget.id);
|
||||
} else {
|
||||
return [];
|
||||
}
|
||||
if (!profile) {
|
||||
return [];
|
||||
}
|
||||
const userId = "user" in profile && profile.user ? profile.user.id : null;
|
||||
if (!userId) {
|
||||
return [];
|
||||
}
|
||||
prismaWhere = {
|
||||
userId: profile.user.id,
|
||||
userId,
|
||||
...where,
|
||||
};
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,481 @@
|
||||
import prismock from "../../../../tests/libs/__mocks__/prisma";
|
||||
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
|
||||
import { ProfileRepository, LookupTarget } from "./ProfileRepository";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
|
||||
vi.mock("@calcom/lib/server/repository/teamUtils", () => ({
|
||||
getParsedTeam: <T>(org: T) => org,
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/lib/logger", () => ({
|
||||
default: {
|
||||
getSubLogger: () => ({
|
||||
debug: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
describe("ProfileRepository.findByUpIdWithAuth - IDOR Security Fix", () => {
|
||||
let user1: { id: number; email: string; username: string };
|
||||
let user2: { id: number; email: string; username: string };
|
||||
let org1: { id: number; name: string; slug: string };
|
||||
let org2: { id: number; name: string; slug: string };
|
||||
let profile1: { id: number; uid: string; upId: string };
|
||||
let profile2: { id: number; uid: string; upId: string };
|
||||
let membership1: { id: number };
|
||||
let membership2: { id: number };
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.resetAllMocks();
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
await prismock.reset();
|
||||
|
||||
// Create User 1
|
||||
user1 = await prismock.user.create({
|
||||
data: {
|
||||
email: "[email protected]",
|
||||
username: "user1",
|
||||
name: "User 1",
|
||||
},
|
||||
});
|
||||
|
||||
// Create User 2
|
||||
user2 = await prismock.user.create({
|
||||
data: {
|
||||
email: "[email protected]",
|
||||
username: "user2",
|
||||
name: "User 2",
|
||||
},
|
||||
});
|
||||
|
||||
// Create Organization 1
|
||||
org1 = await prismock.team.create({
|
||||
data: {
|
||||
name: "Organization 1",
|
||||
slug: "org1",
|
||||
isOrganization: true,
|
||||
metadata: {},
|
||||
},
|
||||
});
|
||||
|
||||
// Create Organization 2
|
||||
org2 = await prismock.team.create({
|
||||
data: {
|
||||
name: "Organization 2",
|
||||
slug: "org2",
|
||||
isOrganization: true,
|
||||
metadata: {},
|
||||
},
|
||||
});
|
||||
|
||||
// Create Profile 1 for User 1 in Organization 1
|
||||
const profile1Data = await prismock.profile.create({
|
||||
data: {
|
||||
uid: ProfileRepository.generateProfileUid(),
|
||||
userId: user1.id,
|
||||
organizationId: org1.id,
|
||||
username: "user1-org1",
|
||||
},
|
||||
include: {
|
||||
user: true,
|
||||
organization: true,
|
||||
},
|
||||
});
|
||||
profile1 = {
|
||||
id: profile1Data.id,
|
||||
uid: profile1Data.uid,
|
||||
upId: `prof-${profile1Data.uid}`,
|
||||
};
|
||||
|
||||
// Create Profile 2 for User 2 in Organization 2
|
||||
const profile2Data = await prismock.profile.create({
|
||||
data: {
|
||||
uid: ProfileRepository.generateProfileUid(),
|
||||
userId: user2.id,
|
||||
organizationId: org2.id,
|
||||
username: "user2-org2",
|
||||
},
|
||||
include: {
|
||||
user: true,
|
||||
organization: true,
|
||||
},
|
||||
});
|
||||
profile2 = {
|
||||
id: profile2Data.id,
|
||||
uid: profile2Data.uid,
|
||||
upId: `prof-${profile2Data.uid}`,
|
||||
};
|
||||
|
||||
// Create membership: User 1 is member of Org 1
|
||||
membership1 = await prismock.membership.create({
|
||||
data: {
|
||||
userId: user1.id,
|
||||
teamId: org1.id,
|
||||
role: MembershipRole.MEMBER,
|
||||
accepted: true,
|
||||
},
|
||||
});
|
||||
|
||||
// Create membership: User 2 is member of Org 2
|
||||
membership2 = await prismock.membership.create({
|
||||
data: {
|
||||
userId: user2.id,
|
||||
teamId: org2.id,
|
||||
role: MembershipRole.MEMBER,
|
||||
accepted: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
describe("UUID-based profile identifiers (new secure format)", () => {
|
||||
it("should allow user to access their own profile", async () => {
|
||||
const result = await ProfileRepository.findByUpIdWithAuth(profile1.upId, user1.id);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.id).toBe(profile1.id);
|
||||
expect(result?.upId).toBe(profile1.upId);
|
||||
expect(result?.organizationId).toBe(org1.id);
|
||||
});
|
||||
|
||||
it("should allow user to access profile from their organization", async () => {
|
||||
// Add User 1 as member of Org 1 (already done in setup)
|
||||
// User 1 should be able to access their own profile
|
||||
const result = await ProfileRepository.findByUpIdWithAuth(profile1.upId, user1.id);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.id).toBe(profile1.id);
|
||||
});
|
||||
|
||||
it("should prevent cross-tenant access - user from org1 cannot access org2 profile", async () => {
|
||||
const result = await ProfileRepository.findByUpIdWithAuth(profile2.upId, user1.id);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should prevent cross-tenant access - user from org2 cannot access org1 profile", async () => {
|
||||
const result = await ProfileRepository.findByUpIdWithAuth(profile1.upId, user2.id);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should prevent unauthorized access when user is not a member", async () => {
|
||||
// Create a third user who is not a member of either org
|
||||
const user3 = await prismock.user.create({
|
||||
data: {
|
||||
email: "[email protected]",
|
||||
username: "user3",
|
||||
name: "User 3",
|
||||
},
|
||||
});
|
||||
|
||||
const result = await ProfileRepository.findByUpIdWithAuth(profile1.upId, user3.id);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should allow access when user is a member of the organization", async () => {
|
||||
// Add User 1 as a member of Org 2
|
||||
await prismock.membership.create({
|
||||
data: {
|
||||
userId: user1.id,
|
||||
teamId: org2.id,
|
||||
role: MembershipRole.MEMBER,
|
||||
accepted: true,
|
||||
},
|
||||
});
|
||||
|
||||
// Now User 1 should be able to access Profile 2 (from Org 2)
|
||||
const result = await ProfileRepository.findByUpIdWithAuth(profile2.upId, user1.id);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.id).toBe(profile2.id);
|
||||
});
|
||||
|
||||
it("should prevent access when membership is not accepted", async () => {
|
||||
// Add User 1 as a pending member of Org 2
|
||||
await prismock.membership.create({
|
||||
data: {
|
||||
userId: user1.id,
|
||||
teamId: org2.id,
|
||||
role: MembershipRole.MEMBER,
|
||||
accepted: false, // Not accepted
|
||||
},
|
||||
});
|
||||
|
||||
const result = await ProfileRepository.findByUpIdWithAuth(profile2.upId, user1.id);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Legacy numeric profile IDs (backward compatibility)", () => {
|
||||
it("should support legacy numeric IDs for backward compatibility", async () => {
|
||||
const legacyUpId = profile1.id.toString();
|
||||
const result = await ProfileRepository.findByUpIdWithAuth(legacyUpId, user1.id);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.id).toBe(profile1.id);
|
||||
});
|
||||
|
||||
it("should prevent cross-tenant access with legacy numeric IDs", async () => {
|
||||
const legacyUpId = profile2.id.toString();
|
||||
const result = await ProfileRepository.findByUpIdWithAuth(legacyUpId, user1.id);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should allow access to own profile with legacy numeric ID", async () => {
|
||||
const legacyUpId = profile1.id.toString();
|
||||
const result = await ProfileRepository.findByUpIdWithAuth(legacyUpId, user1.id);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.id).toBe(profile1.id);
|
||||
});
|
||||
});
|
||||
|
||||
describe("User profile identifiers (usr- format)", () => {
|
||||
it("should allow user to access their own user profile", async () => {
|
||||
const userUpId = `usr-${user1.id}`;
|
||||
const result = await ProfileRepository.findByUpIdWithAuth(userUpId, user1.id);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.upId).toBe(userUpId);
|
||||
expect(result?.id).toBeNull(); // User profiles don't have profile.id
|
||||
});
|
||||
|
||||
it("should prevent user from accessing another user's profile", async () => {
|
||||
const userUpId = `usr-${user2.id}`;
|
||||
const result = await ProfileRepository.findByUpIdWithAuth(userUpId, user1.id);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should require userId parameter for security", async () => {
|
||||
const userUpId = `usr-${user1.id}`;
|
||||
// userId is now required - this test verifies the method signature
|
||||
const result = await ProfileRepository.findByUpIdWithAuth(userUpId, user1.id);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.upId).toBe(userUpId);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Authorization edge cases", () => {
|
||||
it("should return null for non-existent profile", async () => {
|
||||
const fakeUpId = `prof-${ProfileRepository.generateProfileUid()}`;
|
||||
const result = await ProfileRepository.findByUpIdWithAuth(fakeUpId, user1.id);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should return null for invalid upId format", async () => {
|
||||
await expect(() => ProfileRepository.findByUpIdWithAuth("invalid-format", user1.id)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("should require userId parameter - authorization check always runs", async () => {
|
||||
// userId is now required - authorization check always runs
|
||||
const result = await ProfileRepository.findByUpIdWithAuth(profile1.upId, user1.id);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.id).toBe(profile1.id);
|
||||
});
|
||||
|
||||
it("should handle profile with platform organization correctly", async () => {
|
||||
// Create a platform organization
|
||||
const platformOrg = await prismock.team.create({
|
||||
data: {
|
||||
name: "Platform Org",
|
||||
slug: "platform",
|
||||
isOrganization: true,
|
||||
isPlatform: true,
|
||||
metadata: {},
|
||||
},
|
||||
});
|
||||
|
||||
const platformUser = await prismock.user.create({
|
||||
data: {
|
||||
email: "[email protected]",
|
||||
username: "platform",
|
||||
name: "Platform User",
|
||||
isPlatformManaged: true,
|
||||
},
|
||||
});
|
||||
|
||||
const platformProfile = await prismock.profile.create({
|
||||
data: {
|
||||
uid: ProfileRepository.generateProfileUid(),
|
||||
userId: platformUser.id,
|
||||
organizationId: platformOrg.id,
|
||||
username: "platform-user",
|
||||
},
|
||||
include: {
|
||||
user: true,
|
||||
organization: true,
|
||||
},
|
||||
});
|
||||
|
||||
const result = await ProfileRepository.findByUpIdWithAuth(
|
||||
`prof-${platformProfile.uid}`,
|
||||
platformUser.id
|
||||
);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("getLookupTarget - format parsing", () => {
|
||||
it("should correctly parse UUID-based profile ID", () => {
|
||||
const upId = `prof-${profile1.uid}`;
|
||||
const result = ProfileRepository.getLookupTarget(upId);
|
||||
|
||||
expect(result.type).toBe(LookupTarget.Profile);
|
||||
expect("uid" in result).toBe(true);
|
||||
if ("uid" in result) {
|
||||
expect(result.uid).toBe(profile1.uid);
|
||||
}
|
||||
});
|
||||
|
||||
it("should correctly parse legacy numeric profile ID", () => {
|
||||
const upId = profile1.id.toString();
|
||||
const result = ProfileRepository.getLookupTarget(upId);
|
||||
|
||||
expect(result.type).toBe(LookupTarget.Profile);
|
||||
expect("id" in result).toBe(true);
|
||||
if ("id" in result) {
|
||||
expect(result.id).toBe(profile1.id);
|
||||
}
|
||||
});
|
||||
|
||||
it("should correctly parse user profile ID", () => {
|
||||
const upId = `usr-${user1.id}`;
|
||||
const result = ProfileRepository.getLookupTarget(upId);
|
||||
|
||||
expect(result.type).toBe(LookupTarget.User);
|
||||
expect(result.id).toBe(user1.id);
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeProfile - UUID-based upId generation", () => {
|
||||
it("should generate prof-<uuid> format for upId", async () => {
|
||||
const profile = await prismock.profile.findUnique({
|
||||
where: { id: profile1.id },
|
||||
include: {
|
||||
user: true,
|
||||
organization: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
metadata: true,
|
||||
logoUrl: true,
|
||||
bannerUrl: true,
|
||||
isPrivate: true,
|
||||
isPlatform: true,
|
||||
hideBranding: true,
|
||||
brandColor: true,
|
||||
darkBrandColor: true,
|
||||
theme: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!profile) {
|
||||
throw new Error("Profile not found");
|
||||
}
|
||||
|
||||
// Import normalizeProfile
|
||||
const { normalizeProfile } = await import("./ProfileRepository");
|
||||
const normalized = normalizeProfile(profile);
|
||||
|
||||
expect(normalized.upId).toBe(`prof-${profile.uid}`);
|
||||
expect(normalized.upId).not.toBe(profile.id.toString());
|
||||
});
|
||||
});
|
||||
|
||||
describe("Regression: IDOR vulnerability prevention", () => {
|
||||
it("should prevent sequential ID enumeration attacks", async () => {
|
||||
// Simulate attacker trying to enumerate profiles
|
||||
const attacker = await prismock.user.create({
|
||||
data: {
|
||||
email: "[email protected]",
|
||||
username: "attacker",
|
||||
name: "Attacker",
|
||||
},
|
||||
});
|
||||
|
||||
// Try to access profile1 using its numeric ID (legacy format)
|
||||
const legacyUpId = profile1.id.toString();
|
||||
const result = await ProfileRepository.findByUpIdWithAuth(legacyUpId, attacker.id);
|
||||
|
||||
// Should be blocked - attacker is not a member of org1
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should prevent UUID guessing attacks", async () => {
|
||||
const attacker = await prismock.user.create({
|
||||
data: {
|
||||
email: "[email protected]",
|
||||
username: "attacker",
|
||||
name: "Attacker",
|
||||
},
|
||||
});
|
||||
|
||||
// Try to access profile using UUID (even if guessed)
|
||||
const guessedUpId = `prof-${ProfileRepository.generateProfileUid()}`;
|
||||
const result = await ProfileRepository.findByUpIdWithAuth(guessedUpId, attacker.id);
|
||||
|
||||
// Should return null (profile doesn't exist or no access)
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should prevent access to profiles from different organizations", async () => {
|
||||
// User 1 from Org 1 tries to access User 2's profile from Org 2
|
||||
const result = await ProfileRepository.findByUpIdWithAuth(profile2.upId, user1.id);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should allow legitimate access within same organization", async () => {
|
||||
// Create another profile in Org 1 for a different user
|
||||
const user3 = await prismock.user.create({
|
||||
data: {
|
||||
email: "[email protected]",
|
||||
username: "user3",
|
||||
name: "User 3",
|
||||
},
|
||||
});
|
||||
|
||||
await prismock.membership.create({
|
||||
data: {
|
||||
userId: user3.id,
|
||||
teamId: org1.id,
|
||||
role: MembershipRole.MEMBER,
|
||||
accepted: true,
|
||||
},
|
||||
});
|
||||
|
||||
const profile3 = await prismock.profile.create({
|
||||
data: {
|
||||
uid: ProfileRepository.generateProfileUid(),
|
||||
userId: user3.id,
|
||||
organizationId: org1.id,
|
||||
username: "user3-org1",
|
||||
},
|
||||
});
|
||||
|
||||
// User 1 (member of Org 1) should be able to access User 3's profile (also in Org 1)
|
||||
const result = await ProfileRepository.findByUpIdWithAuth(`prof-${profile3.uid}`, user1.id);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.id).toBe(profile3.id);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,6 +10,7 @@ import prisma from "@calcom/prisma";
|
||||
import type { User as PrismaUser } from "@calcom/prisma/client";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
import type { Team } from "@calcom/prisma/client";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { userMetadata } from "@calcom/prisma/zod-utils";
|
||||
import type { UpId, UserAsPersonalProfile, UserProfile } from "@calcom/types/UserProfile";
|
||||
|
||||
@@ -62,6 +63,23 @@ const organizationWithSettingsSelect = {
|
||||
},
|
||||
};
|
||||
|
||||
const organizationWithSettingsAndMembersSelect = {
|
||||
...organizationSelect,
|
||||
isPrivate: true,
|
||||
organizationSettings: {
|
||||
select: {
|
||||
lockEventTypeCreationForUsers: true,
|
||||
allowSEOIndexing: true,
|
||||
},
|
||||
},
|
||||
members: {
|
||||
select: membershipSelect,
|
||||
where: {
|
||||
accepted: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const profileSelect = {
|
||||
id: true,
|
||||
uid: true,
|
||||
@@ -130,10 +148,22 @@ export class ProfileRepository {
|
||||
id: parseInt(upId.replace("usr-", "")),
|
||||
} as const;
|
||||
}
|
||||
return {
|
||||
type: LookupTarget.Profile,
|
||||
id: parseInt(upId),
|
||||
} as const;
|
||||
if (upId.startsWith("prof-")) {
|
||||
// UUID-based profile identifier (new secure format)
|
||||
return {
|
||||
type: LookupTarget.Profile,
|
||||
uid: upId.replace("prof-", ""),
|
||||
} as const;
|
||||
}
|
||||
// Legacy support: numeric profile ID (deprecated, kept for backward compatibility)
|
||||
const numericId = parseInt(upId);
|
||||
if (!isNaN(numericId)) {
|
||||
return {
|
||||
type: LookupTarget.Profile,
|
||||
id: numericId,
|
||||
} as const;
|
||||
}
|
||||
throw new Error(`Invalid upId format: ${upId}`);
|
||||
}
|
||||
|
||||
private static async _create({
|
||||
@@ -296,9 +326,9 @@ export class ProfileRepository {
|
||||
|
||||
for (let i = 0; i < createdProfiles.length; i += DATABASE_CHUNK_SIZE) {
|
||||
const profilesBatch = createdProfiles.slice(i, i + DATABASE_CHUNK_SIZE);
|
||||
await Promise.allSettled([
|
||||
await Promise.allSettled(
|
||||
profilesBatch.map((profile) => {
|
||||
prisma.user.update({
|
||||
return prisma.user.update({
|
||||
where: {
|
||||
id: profile.userId,
|
||||
},
|
||||
@@ -308,8 +338,8 @@ export class ProfileRepository {
|
||||
},
|
||||
},
|
||||
});
|
||||
}),
|
||||
]);
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -435,11 +465,57 @@ export class ProfileRepository {
|
||||
return profile;
|
||||
}
|
||||
|
||||
static async findByUpId(upId: string) {
|
||||
static async findByUid(uid: string) {
|
||||
const profile = await prisma.profile.findFirst({
|
||||
where: {
|
||||
uid,
|
||||
},
|
||||
include: {
|
||||
user: {
|
||||
select: userSelect,
|
||||
},
|
||||
movedFromUser: {
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
organization: {
|
||||
select: organizationWithSettingsAndMembersSelect,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!profile) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return normalizeProfile(profile);
|
||||
}
|
||||
|
||||
static async findByUpIdWithAuth(upId: string, userId: number) {
|
||||
const lookupTarget = ProfileRepository.getLookupTarget(upId);
|
||||
log.debug("findByUpId", safeStringify({ upId, lookupTarget }));
|
||||
log.debug("findByUpIdWithAuth", safeStringify({ upId, lookupTarget, userId }));
|
||||
|
||||
if (lookupTarget.type === LookupTarget.User) {
|
||||
const user = await this.findUserByid({ id: lookupTarget.id });
|
||||
const targetUserId = lookupTarget.id;
|
||||
|
||||
if (targetUserId !== userId) {
|
||||
// Check if requesting user is an org admin/owner and can access target user's profile
|
||||
const canAccessAsAdmin = await ProfileRepository.checkOrgAdminAccessToUser({
|
||||
requestingUserId: userId,
|
||||
targetUserId,
|
||||
});
|
||||
|
||||
if (!canAccessAsAdmin) {
|
||||
log.warn(
|
||||
"Unauthorized access attempt to user profile",
|
||||
safeStringify({ upId, userId, targetUserId })
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const user = await this.findUserByid({ id: targetUserId });
|
||||
if (!user) {
|
||||
return null;
|
||||
}
|
||||
@@ -453,11 +529,94 @@ export class ProfileRepository {
|
||||
};
|
||||
}
|
||||
|
||||
const profile = await ProfileRepository.findById(lookupTarget.id);
|
||||
if (!profile) {
|
||||
let rawProfile;
|
||||
if ("uid" in lookupTarget) {
|
||||
// UUID-based lookup (new secure format)
|
||||
if (!lookupTarget.uid) {
|
||||
return null;
|
||||
}
|
||||
rawProfile = await prisma.profile.findFirst({
|
||||
where: { uid: lookupTarget.uid },
|
||||
include: {
|
||||
user: { select: userSelect },
|
||||
organization: {
|
||||
select: organizationWithSettingsAndMembersSelect,
|
||||
},
|
||||
},
|
||||
});
|
||||
} else {
|
||||
// Legacy numeric ID lookup (deprecated)
|
||||
rawProfile = await prisma.profile.findUnique({
|
||||
where: { id: lookupTarget.id },
|
||||
include: {
|
||||
user: { select: userSelect },
|
||||
movedFromUser: { select: { id: true } },
|
||||
organization: {
|
||||
select: {
|
||||
id: true,
|
||||
logoUrl: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
metadata: true,
|
||||
bannerUrl: true,
|
||||
isPrivate: true,
|
||||
isPlatform: true,
|
||||
hideBranding: true,
|
||||
brandColor: true,
|
||||
darkBrandColor: true,
|
||||
theme: true,
|
||||
organizationSettings: {
|
||||
select: {
|
||||
lockEventTypeCreationForUsers: true,
|
||||
allowSEOIndexing: true,
|
||||
},
|
||||
},
|
||||
members: {
|
||||
select: membershipSelect,
|
||||
where: {
|
||||
accepted: true,
|
||||
user: { profiles: { some: { id: lookupTarget.id } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (!rawProfile) {
|
||||
return null;
|
||||
}
|
||||
const user = profile.user;
|
||||
|
||||
// Authorization check: verify user has access to this profile
|
||||
const profileId = rawProfile.id;
|
||||
const organizationId = rawProfile.organizationId;
|
||||
|
||||
if (profileId && organizationId) {
|
||||
const hasAccess = await ProfileRepository.checkUserAccessToProfile({
|
||||
userId,
|
||||
profileId,
|
||||
organizationId,
|
||||
});
|
||||
|
||||
if (!hasAccess) {
|
||||
log.warn(
|
||||
"Unauthorized access attempt to profile",
|
||||
safeStringify({ upId, userId, profileId, organizationId })
|
||||
);
|
||||
return null;
|
||||
}
|
||||
} else if (profileId) {
|
||||
// For personal profiles, check if user owns it
|
||||
if (rawProfile.userId !== userId) {
|
||||
log.warn("Unauthorized access attempt to profile", safeStringify({ upId, userId, profileId }));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const profile = normalizeProfile(rawProfile);
|
||||
const user = rawProfile.user;
|
||||
|
||||
if (profile.organization?.isPlatform && !user.isPlatformManaged) {
|
||||
return {
|
||||
...this.buildPersonalProfileFromUser({ user }),
|
||||
@@ -470,6 +629,93 @@ export class ProfileRepository {
|
||||
};
|
||||
}
|
||||
|
||||
private static async checkOrgAdminAccessToUser({
|
||||
requestingUserId,
|
||||
targetUserId,
|
||||
}: {
|
||||
requestingUserId: number;
|
||||
targetUserId: number;
|
||||
}): Promise<boolean> {
|
||||
const requestingUserOrgMemberships = await prisma.membership.findMany({
|
||||
where: {
|
||||
userId: requestingUserId,
|
||||
accepted: true,
|
||||
role: {
|
||||
in: [MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
},
|
||||
team: {
|
||||
isOrganization: true,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
teamId: true,
|
||||
},
|
||||
});
|
||||
|
||||
const orgIdsWhereRequestingUserIsAdmin = requestingUserOrgMemberships.map((m) => m.teamId);
|
||||
|
||||
if (orgIdsWhereRequestingUserIsAdmin.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const targetUserOrgMembership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId: targetUserId,
|
||||
accepted: true,
|
||||
teamId: {
|
||||
in: orgIdsWhereRequestingUserIsAdmin,
|
||||
},
|
||||
team: {
|
||||
isOrganization: true,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
userId: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (targetUserOrgMembership) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static async checkUserAccessToProfile({
|
||||
userId,
|
||||
profileId,
|
||||
organizationId,
|
||||
}: {
|
||||
userId: number;
|
||||
profileId: number | null;
|
||||
organizationId: number | null;
|
||||
}): Promise<boolean> {
|
||||
if (!profileId || !organizationId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if user owns the profile
|
||||
const profile = await prisma.profile.findUnique({
|
||||
where: { id: profileId },
|
||||
select: { userId: true },
|
||||
});
|
||||
|
||||
if (profile?.userId === userId) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const membership = await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
teamId: organizationId,
|
||||
accepted: true,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
return !!membership;
|
||||
}
|
||||
|
||||
static async findById(id: number | null) {
|
||||
if (!id) {
|
||||
return null;
|
||||
@@ -753,6 +999,7 @@ export class ProfileRepository {
|
||||
export const normalizeProfile = <
|
||||
T extends {
|
||||
id: number;
|
||||
uid: string;
|
||||
organization: Pick<Team, keyof typeof organizationSelect>;
|
||||
createdAt?: Date;
|
||||
updatedAt?: Date;
|
||||
@@ -762,7 +1009,7 @@ export const normalizeProfile = <
|
||||
) => {
|
||||
return {
|
||||
...profile,
|
||||
upId: profile.id.toString(),
|
||||
upId: `prof-${profile.uid}`,
|
||||
organization: getParsedTeam(profile.organization),
|
||||
// Make these ↓ props ISO strings so that they can be returned from getServerSideProps as is without any issues
|
||||
...(profile.createdAt ? { createdAt: profile.createdAt.toISOString() } : null),
|
||||
|
||||
@@ -453,7 +453,7 @@ export class UserRepository {
|
||||
user: T;
|
||||
upId: UpId;
|
||||
}) {
|
||||
const profile = await ProfileRepository.findByUpId(upId);
|
||||
const profile = await ProfileRepository.findByUpIdWithAuth(upId, user.id);
|
||||
if (!profile) {
|
||||
return {
|
||||
...user,
|
||||
|
||||
+10
-10
@@ -20,7 +20,7 @@ vi.mock("@calcom/features/membership/repositories/MembershipRepository", () => (
|
||||
|
||||
vi.mock("@calcom/features/profile/repositories/ProfileRepository", () => ({
|
||||
ProfileRepository: {
|
||||
findByUpId: vi.fn(),
|
||||
findByUpIdWithAuth: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -70,7 +70,7 @@ describe("getUserEventGroups", () => {
|
||||
} as unknown as NonNullable<
|
||||
Awaited<
|
||||
ReturnType<
|
||||
typeof import("@calcom/features/profile/repositories/ProfileRepository").ProfileRepository.findByUpId
|
||||
typeof import("@calcom/features/profile/repositories/ProfileRepository").ProfileRepository.findByUpIdWithAuth
|
||||
>
|
||||
>
|
||||
>;
|
||||
@@ -87,7 +87,7 @@ describe("getUserEventGroups", () => {
|
||||
describe("Basic functionality", () => {
|
||||
it("should throw TRPCError when profile is not found", async () => {
|
||||
const { ProfileRepository } = await import("@calcom/features/profile/repositories/ProfileRepository");
|
||||
vi.mocked(ProfileRepository.findByUpId).mockResolvedValue(null);
|
||||
vi.mocked(ProfileRepository.findByUpIdWithAuth).mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
getUserEventGroups({
|
||||
@@ -103,7 +103,7 @@ describe("getUserEventGroups", () => {
|
||||
"@calcom/features/membership/repositories/MembershipRepository"
|
||||
);
|
||||
|
||||
vi.mocked(ProfileRepository.findByUpId).mockResolvedValue(mockProfile);
|
||||
vi.mocked(ProfileRepository.findByUpIdWithAuth).mockResolvedValue(mockProfile);
|
||||
vi.mocked(MembershipRepository.findAllByUpIdIncludeTeam).mockResolvedValue([]);
|
||||
mockFilterTeamsByEventTypeReadPermission.mockResolvedValue([]);
|
||||
|
||||
@@ -161,7 +161,7 @@ describe("getUserEventGroups", () => {
|
||||
>
|
||||
>[0];
|
||||
|
||||
vi.mocked(ProfileRepository.findByUpId).mockResolvedValue(mockProfile);
|
||||
vi.mocked(ProfileRepository.findByUpIdWithAuth).mockResolvedValue(mockProfile);
|
||||
vi.mocked(MembershipRepository.findAllByUpIdIncludeTeam).mockResolvedValue([mockTeamMembership]);
|
||||
mockFilterTeamsByEventTypeReadPermission.mockResolvedValue([mockTeamMembership]);
|
||||
|
||||
@@ -223,7 +223,7 @@ describe("getUserEventGroups", () => {
|
||||
>
|
||||
>[0];
|
||||
|
||||
vi.mocked(ProfileRepository.findByUpId).mockResolvedValue(mockProfile);
|
||||
vi.mocked(ProfileRepository.findByUpIdWithAuth).mockResolvedValue(mockProfile);
|
||||
vi.mocked(MembershipRepository.findAllByUpIdIncludeTeam).mockResolvedValue([mockTeamMembership]);
|
||||
mockFilterTeamsByEventTypeReadPermission.mockResolvedValue([mockTeamMembership]);
|
||||
|
||||
@@ -279,7 +279,7 @@ describe("getUserEventGroups", () => {
|
||||
>
|
||||
>[0];
|
||||
|
||||
vi.mocked(ProfileRepository.findByUpId).mockResolvedValue(mockProfile);
|
||||
vi.mocked(ProfileRepository.findByUpIdWithAuth).mockResolvedValue(mockProfile);
|
||||
vi.mocked(MembershipRepository.findAllByUpIdIncludeTeam).mockResolvedValue([mockTeamMembership]);
|
||||
mockFilterTeamsByEventTypeReadPermission.mockResolvedValue([mockTeamMembership]);
|
||||
|
||||
@@ -315,12 +315,12 @@ describe("getUserEventGroups", () => {
|
||||
} as unknown as NonNullable<
|
||||
Awaited<
|
||||
ReturnType<
|
||||
typeof import("@calcom/features/profile/repositories/ProfileRepository").ProfileRepository.findByUpId
|
||||
typeof import("@calcom/features/profile/repositories/ProfileRepository").ProfileRepository.findByUpIdWithAuth
|
||||
>
|
||||
>
|
||||
>;
|
||||
|
||||
vi.mocked(ProfileRepository.findByUpId).mockResolvedValue(mockProfileWithOrg);
|
||||
vi.mocked(ProfileRepository.findByUpIdWithAuth).mockResolvedValue(mockProfileWithOrg);
|
||||
vi.mocked(MembershipRepository.findAllByUpIdIncludeTeam).mockResolvedValue([]);
|
||||
mockFilterTeamsByEventTypeReadPermission.mockResolvedValue([]);
|
||||
|
||||
@@ -368,7 +368,7 @@ describe("getUserEventGroups", () => {
|
||||
>
|
||||
>[0];
|
||||
|
||||
vi.mocked(ProfileRepository.findByUpId).mockResolvedValue(mockProfile);
|
||||
vi.mocked(ProfileRepository.findByUpIdWithAuth).mockResolvedValue(mockProfile);
|
||||
vi.mocked(MembershipRepository.findAllByUpIdIncludeTeam).mockResolvedValue([mockTeamMembership]);
|
||||
mockFilterTeamsByEventTypeReadPermission.mockResolvedValue([mockTeamMembership]);
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@ const fetchEventTypeGroups = async ({
|
||||
teamId,
|
||||
}: {
|
||||
ctx: { user: NonNullable<TrpcSessionUser>; prisma: PrismaClient };
|
||||
profile: NonNullable<Awaited<ReturnType<typeof ProfileRepository.findByUpId>>>;
|
||||
profile: NonNullable<Awaited<ReturnType<typeof ProfileRepository.findByUpIdWithAuth>>>;
|
||||
parentOrgHasLockedEventTypes: boolean | undefined;
|
||||
skipEventTypes: boolean;
|
||||
teamId?: number;
|
||||
@@ -214,7 +214,7 @@ export const getActiveOnOptions = async ({ ctx, input }: GetActiveOnOptions) =>
|
||||
const shouldSkipEventTypes = isOrg;
|
||||
|
||||
const userProfile = ctx.user.profile;
|
||||
const profile = await ProfileRepository.findByUpId(userProfile.upId);
|
||||
const profile = await ProfileRepository.findByUpIdWithAuth(userProfile.upId, ctx.user.id);
|
||||
const parentOrgHasLockedEventTypes =
|
||||
profile?.organization?.organizationSettings?.lockEventTypeCreationForUsers;
|
||||
|
||||
|
||||
@@ -31,8 +31,8 @@ export const getUserEventGroups = async ({ ctx, input }: GetByViewerOptions) =>
|
||||
const user = ctx.user;
|
||||
const userProfile = user.profile;
|
||||
|
||||
// Validate profile exists
|
||||
const profile = await ProfileRepository.findByUpId(userProfile.upId);
|
||||
// Validate profile exists and user has access
|
||||
const profile = await ProfileRepository.findByUpIdWithAuth(userProfile.upId, user.id);
|
||||
if (!profile) {
|
||||
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR" });
|
||||
}
|
||||
|
||||
@@ -34,8 +34,8 @@ export class EventGroupBuilder {
|
||||
}> {
|
||||
const { userId, userUpId, filters, forRoutingForms } = input;
|
||||
|
||||
// Get user profile
|
||||
const profile = await this.dependencies.profileRepository.findByUpId(userUpId);
|
||||
// Get user profile with authorization check
|
||||
const profile = await this.dependencies.profileRepository.findByUpIdWithAuth(userUpId, userId);
|
||||
if (!profile) {
|
||||
throw new Error("Profile not found");
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user