Skip to content
Open
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
142 changes: 142 additions & 0 deletions packages/app-store/caldavcalendar/api/add.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import { symmetricEncrypt } from "@calcom/lib/crypto";
import prisma from "@calcom/prisma";
import type { NextApiRequest, NextApiResponse } from "next";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { BuildCalendarService } from "../lib";
import handler from "./add";

const ENCRYPTION_KEY = "12345678901234567890123456789012";

vi.mock("@calcom/prisma", () => ({
default: {
user: {
findFirstOrThrow: vi.fn(),
},
credential: {
findMany: vi.fn(),
create: vi.fn(),
},
},
}));

vi.mock("../lib", () => ({
BuildCalendarService: vi.fn(),
}));

const mockPrisma = prisma as unknown as {
user: {
findFirstOrThrow: ReturnType<typeof vi.fn>;
};
credential: {
findMany: ReturnType<typeof vi.fn>;
create: ReturnType<typeof vi.fn>;
};
};

const mockBuildCalendarService = BuildCalendarService as unknown as ReturnType<typeof vi.fn>;

type MockResponse = {
status: ReturnType<typeof vi.fn>;
json: ReturnType<typeof vi.fn>;
};

const createMockResponse = (): MockResponse => {
const response = {
status: vi.fn(),
json: vi.fn(),
};

response.status.mockReturnValue(response);
response.json.mockReturnValue(response);

return response;
};

describe("caldav add api", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.stubEnv("CALENDSO_ENCRYPTION_KEY", ENCRYPTION_KEY);

mockPrisma.user.findFirstOrThrow.mockResolvedValue({
id: 1,
email: "team-owner@example.com",
});

mockBuildCalendarService.mockReturnValue({
listCalendars: vi.fn().mockResolvedValue([]),
});

mockPrisma.credential.create.mockResolvedValue({ id: 101 });
});

it("allows a second credential on the same URL when credentials are different", async () => {
const sharedUrl = "https://nextcloud.example.com/remote.php/dav";

mockPrisma.credential.findMany.mockResolvedValue([
{
key: symmetricEncrypt(
JSON.stringify({ username: "user-one", password: "password-one", url: sharedUrl }),
ENCRYPTION_KEY
),
},
]);

const req = {
method: "POST",
body: {
username: "user-two",
password: "password-two",
url: sharedUrl,
},
session: {
user: {
id: 1,
},
},
} as unknown as NextApiRequest;

const res = createMockResponse();

await handler(req, res as unknown as NextApiResponse);

expect(mockBuildCalendarService).toHaveBeenCalledTimes(1);
expect(mockPrisma.credential.create).toHaveBeenCalledTimes(1);
expect(res.status).toHaveBeenCalledWith(200);
});

it("treats the exact same URL, username, and password as an idempotent add", async () => {
const sameCredential = {
username: "same-user",
password: "same-password",
url: "https://nextcloud.example.com/remote.php/dav",
};

mockPrisma.credential.findMany.mockResolvedValue([
{
key: symmetricEncrypt(JSON.stringify(sameCredential), ENCRYPTION_KEY),
},
]);

const req = {
method: "POST",
body: sameCredential,
session: {
user: {
id: 1,
},
},
} as unknown as NextApiRequest;

const res = createMockResponse();

await handler(req, res as unknown as NextApiResponse);

expect(mockBuildCalendarService).not.toHaveBeenCalled();
expect(mockPrisma.credential.create).not.toHaveBeenCalled();
expect(res.status).toHaveBeenCalledWith(200);
});

afterEach(() => {
vi.unstubAllEnvs();
});
});
109 changes: 96 additions & 13 deletions packages/app-store/caldavcalendar/api/add.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,68 @@
import type { NextApiRequest, NextApiResponse } from "next";

import { symmetricEncrypt } from "@calcom/lib/crypto";
import process from "node:process";
import { symmetricDecrypt, symmetricEncrypt } from "@calcom/lib/crypto";
import logger from "@calcom/lib/logger";
import prisma from "@calcom/prisma";

import type { NextApiRequest, NextApiResponse } from "next";
import getInstalledAppPath from "../../_utils/getInstalledAppPath";
import { BuildCalendarService } from "../lib";

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
type CalDavCredentialIdentity = {
username: string;
password: string;
url: string;
};

const getEncryptionKey = (): string => process.env.CALENDSO_ENCRYPTION_KEY || "";

const getCalDavIdentityFromCredentialKey = (credentialKey: unknown): CalDavCredentialIdentity | null => {
if (typeof credentialKey !== "string") {
return null;
}

try {
const decrypted = JSON.parse(symmetricDecrypt(credentialKey, getEncryptionKey()));

if (
typeof decrypted?.username !== "string" ||
typeof decrypted?.password !== "string" ||
typeof decrypted?.url !== "string"
) {
return null;
}

return {
username: decrypted.username,
password: decrypted.password,
url: decrypted.url,
};
} catch {
return null;
}
};

const hasMatchingCalDavIdentity = (
existingCredentialKeys: unknown[],
newCredentialIdentity: CalDavCredentialIdentity
): boolean => {
return existingCredentialKeys.some((credentialKey) => {
const existingIdentity = getCalDavIdentityFromCredentialKey(credentialKey);

if (!existingIdentity) {
return false;
}

return (
existingIdentity.url === newCredentialIdentity.url &&
existingIdentity.username === newCredentialIdentity.username &&
existingIdentity.password === newCredentialIdentity.password
);
});
};

export default async function handler(
req: NextApiRequest,
res: NextApiResponse
): Promise<undefined | NextApiResponse> {
if (req.method === "POST") {
const { username, password, url } = req.body;
// Get user
Expand All @@ -21,12 +76,35 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
},
});

const existingCredentials = await prisma.credential.findMany({
where: {
userId: user.id,
appId: "caldav-calendar",
type: "caldav_calendar",
},
select: {
key: true,
},
});

const duplicateIdentityExists = hasMatchingCalDavIdentity(
existingCredentials.map((credential) => credential.key),
{
username,
password,
url,
}
);

if (duplicateIdentityExists) {
return res
.status(200)
.json({ url: getInstalledAppPath({ variant: "calendar", slug: "caldav-calendar" }) });
}

const data = {
type: "caldav_calendar",
key: symmetricEncrypt(
JSON.stringify({ username, password, url }),
process.env.CALENDSO_ENCRYPTION_KEY || ""
),
key: symmetricEncrypt(JSON.stringify({ username, password, url }), getEncryptionKey()),
userId: user.id,
teamId: null,
appId: "caldav-calendar",
Expand All @@ -51,10 +129,15 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
let message = e.message;
if (e.message.indexOf("Invalid credentials") > -1 && url.indexOf("dav.php") > -1) {
const parsedUrl = new URL(url);
const adminUrl = `${parsedUrl.protocol}//${parsedUrl.hostname}${
parsedUrl.port ? `:${parsedUrl.port}` : ""
}/admin/?/settings/standard/`;
message = `Couldn\'t connect to caldav account, please verify WebDAV authentication type is set to "Basic"`;
const parsedPort = parsedUrl.port;
let adminUrl = `${parsedUrl.protocol}//${parsedUrl.hostname}`;

if (parsedPort) {
adminUrl = `${adminUrl}:${parsedPort}`;
}

adminUrl = `${adminUrl}/admin/?/settings/standard/`;
message = `Couldn't connect to caldav account, please verify WebDAV authentication type is set to "Basic"`;
return res.status(500).json({ message, actionUrl: adminUrl });
}
}
Expand Down
Loading