feat: usage base billed - license key check - move to private api (#15222)

Co-authored-by: Omar López <[email protected]>
This commit is contained in:
sean-brydonandOmar López authored and GitHub committed 2024-07-25 13:20:24 -07:00
1 parent 53c37a9ddf
commit e16662e655
16 files changed
+586 -59

No files matched your search

@@ -3,7 +3,7 @@ import type { GetServerSidePropsContext, NextApiRequest, NextApiResponse } from
import type { AuthOptions, Session } from "next-auth";
import { getToken } from "next-auth/jwt";
import checkLicense from "@calcom/features/ee/common/server/checkLicense";
import LicenseKeyService from "@calcom/ee/common/server/LicenseKeyService";
import { getUserAvatarUrl } from "@calcom/lib/getAvatarUrl";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
@@ -65,7 +65,8 @@ export async function getServerSession(options: {
return null;
}
const hasValidLicense = await checkLicense(prisma);
const licenseKeyService = await LicenseKeyService.create();
const hasValidLicense = await licenseKeyService.checkLicense();
let upId = token.upId;
@@ -7,7 +7,7 @@ import CredentialsProvider from "next-auth/providers/credentials";
import EmailProvider from "next-auth/providers/email";
import GoogleProvider from "next-auth/providers/google";
import checkLicense from "@calcom/features/ee/common/server/checkLicense";
import LicenseKeyService from "@calcom/ee/common/server/LicenseKeyService";
import createUsersAndConnectToOrg from "@calcom/features/ee/dsync/lib/users/createUsersAndConnectToOrg";
import ImpersonationProvider from "@calcom/features/ee/impersonation/lib/ImpersonationProvider";
import { getOrgFullOrigin, subdomainSuffix } from "@calcom/features/ee/organizations/lib/orgDomains";
@@ -619,7 +619,9 @@ export const AUTH_OPTIONS: AuthOptions = {
},
async session({ session, token, user }) {
log.debug("callbacks:session - Session callback called", safeStringify({ session, token, user }));
const hasValidLicense = await checkLicense(prisma);
const licenseKeyService = await LicenseKeyService.create();
const hasValidLicense = await licenseKeyService.checkLicense();
const profileId = token.profileId;
const calendsoSession: Session = {
...session,
@@ -0,0 +1,190 @@
import "../../../../../tests/libs/__mocks__/prisma";
import * as cache from "memory-cache";
import { describe, it, expect, beforeEach, vi, afterEach } from "vitest";
import { getDeploymentKey } from "../../deployment/lib/getDeploymentKey";
import { createSignature, generateNonce } from "./private-api-utils";
const baseUrl = "http://test-api.com";
const licenseKey = "test-license-key";
/** So we can override in specific test below */
process.env.NEXT_PUBLIC_IS_E2E = "0";
/** All fetch call in LicenseKeyService will fail without this */
process.env.CAL_SIGNATURE_TOKEN = "dummy";
/**
* This is needed to ensure the constants and env are fresh.
* If not, we would need to override constants on each scenario with differing constants/env vars.
*/
async function getLicenseKeyService() {
return (await import("./LicenseKeyService")).default;
}
async function stubEnvAndReload(key: string, value: string) {
// We set env variable
vi.stubEnv(key, value);
// We refresh constants and prevent cached modules.
// @see https://github.com/vitest-dev/vitest/issues/4232#issuecomment-1745452522
vi.resetModules();
await import("@calcom/lib/constants");
}
// Mock dependencies
vi.mock("memory-cache", () => ({
get: vi.fn(),
put: vi.fn(),
}));
vi.mock("../../deployment/lib/getDeploymentKey", () => ({
getDeploymentKey: vi.fn(),
}));
vi.mock("./private-api-utils", () => ({
generateNonce: vi.fn(),
createSignature: vi.fn(),
}));
const BASE_HEADERS = {
"Content-Type": "application/json",
};
describe("LicenseKeyService", () => {
beforeEach(async () => {
vi.mocked(getDeploymentKey).mockResolvedValue(licenseKey);
});
afterEach(() => {
vi.resetAllMocks();
vi.unstubAllEnvs();
});
describe("create", () => {
it("should create an instance of LicenseKeyService", async () => {
const LicenseKeyService = await getLicenseKeyService();
const service = await LicenseKeyService.create();
expect(service).toBeInstanceOf(LicenseKeyService);
});
});
describe("incrementUsage", () => {
it("should call the incrementUsage API and return the response", async () => {
const mockResponse = { success: true };
const fetchSpy = vi.spyOn(global, "fetch").mockResolvedValue({
json: vi.fn().mockResolvedValue(mockResponse),
} as any);
vi.mocked(generateNonce).mockReturnValue("mocked-nonce");
vi.mocked(createSignature).mockReturnValue("mocked-signature");
stubEnvAndReload("CALCOM_PRIVATE_API_ROUTE", baseUrl);
const LicenseKeyService = await getLicenseKeyService();
const service = await LicenseKeyService.create();
const response = await service.incrementUsage();
expect(response).toEqual(mockResponse);
expect(fetchSpy).toHaveBeenCalledWith(`${baseUrl}/v1/license/usage/increment?event=booking`, {
body: undefined,
headers: {
...BASE_HEADERS,
nonce: "mocked-nonce",
signature: "mocked-signature",
"x-cal-license-key": "test-license-key",
},
method: "POST",
mode: "cors",
});
});
it("should throw an error if the API call fails", async () => {
const fetchSpy = vi.spyOn(global, "fetch").mockRejectedValue(new Error("API Failure"));
vi.mocked(generateNonce).mockReturnValue("mocked-nonce");
vi.mocked(createSignature).mockReturnValue("mocked-signature");
stubEnvAndReload("CALCOM_PRIVATE_API_ROUTE", baseUrl);
const LicenseKeyService = await getLicenseKeyService();
const service = await LicenseKeyService.create();
await expect(service.incrementUsage()).rejects.toThrow("API Failure");
expect(fetchSpy).toHaveBeenCalledWith(`${baseUrl}/v1/license/usage/increment?event=booking`, {
body: undefined,
headers: {
...BASE_HEADERS,
nonce: "mocked-nonce",
signature: "mocked-signature",
"x-cal-license-key": "test-license-key",
},
method: "POST",
mode: "cors",
});
});
});
describe("checkLicense", () => {
it("should return true if NEXT_PUBLIC_IS_E2E is set", async () => {
stubEnvAndReload("NEXT_PUBLIC_IS_E2E", "1");
const LicenseKeyService = await getLicenseKeyService();
const service = await LicenseKeyService.create();
const result = await service.checkLicense();
expect(result).toBe(true);
});
it("should return cached response if available", async () => {
const url = `${baseUrl}/v1/license/${licenseKey}`;
vi.mocked(cache.get).mockReturnValue(true);
stubEnvAndReload("CALCOM_PRIVATE_API_ROUTE", baseUrl);
const LicenseKeyService = await getLicenseKeyService();
const service = await LicenseKeyService.create();
const result = await service.checkLicense();
expect(result).toBe(true);
expect(cache.get).toHaveBeenCalledWith(url);
});
it("should fetch license validity from API if not cached", async () => {
const url = `${baseUrl}/v1/license/${licenseKey}`;
vi.mocked(cache.get).mockReturnValue(null);
const mockResponse = { status: true };
const fetchSpy = vi.spyOn(global, "fetch").mockResolvedValue({
json: vi.fn().mockResolvedValue(mockResponse),
} as any);
vi.mocked(generateNonce).mockReturnValue("mocked-nonce");
vi.mocked(createSignature).mockReturnValue("mocked-signature");
stubEnvAndReload("CALCOM_PRIVATE_API_ROUTE", baseUrl);
const LicenseKeyService = await getLicenseKeyService();
const service = await LicenseKeyService.create();
const result = await service.checkLicense();
expect(result).toBe(true);
expect(cache.get).toHaveBeenCalledWith(url);
expect(fetchSpy).toHaveBeenCalledWith(url, {
body: undefined,
headers: {
...BASE_HEADERS,
nonce: "mocked-nonce",
signature: "mocked-signature",
"x-cal-license-key": "test-license-key",
},
mode: "cors",
});
});
it("should return false if API call fails", async () => {
const url = `${baseUrl}/v1/license/${licenseKey}`;
stubEnvAndReload("CALCOM_PRIVATE_API_ROUTE", baseUrl);
vi.mocked(cache.get).mockReturnValue(null);
vi.mocked(generateNonce).mockReturnValue("mocked-nonce");
vi.mocked(createSignature).mockReturnValue("mocked-signature");
const fetchSpy = vi.spyOn(global, "fetch").mockRejectedValue(new Error("API Failure"));
const LicenseKeyService = await getLicenseKeyService();
const service = await LicenseKeyService.create();
const result = await service.checkLicense();
expect(result).toBe(false);
expect(fetchSpy).toHaveBeenCalledWith(url, {
body: undefined,
headers: {
...BASE_HEADERS,
nonce: "mocked-nonce",
signature: "mocked-signature",
"x-cal-license-key": "test-license-key",
},
mode: "cors",
});
});
});
});
@@ -0,0 +1,97 @@
import * as cache from "memory-cache";
import { CALCOM_PRIVATE_API_ROUTE } from "@calcom/lib/constants";
import prisma from "@calcom/prisma";
import { getDeploymentKey } from "../../deployment/lib/getDeploymentKey";
import { generateNonce, createSignature } from "./private-api-utils";
export enum UsageEvent {
BOOKING = "booking",
USER = "user",
}
class LicenseKeyService {
private readonly baseUrl = CALCOM_PRIVATE_API_ROUTE;
private readonly licenseKey: string;
public readonly CACHING_TIME = 86_400_000; // 24 hours in milliseconds
// Private constructor to prevent direct instantiation
private constructor(licenseKey: string) {
this.baseUrl = CALCOM_PRIVATE_API_ROUTE;
this.licenseKey = licenseKey;
}
// Static async factory method
public static async create(): Promise<LicenseKeyService> {
const licenseKey = await getDeploymentKey(prisma);
return new LicenseKeyService(licenseKey);
}
private async fetcher({
url,
body,
options = {},
}: {
url: string;
body?: Record<string, unknown>;
options?: RequestInit;
}): Promise<Response> {
const nonce = generateNonce();
const signatureToken = process.env.CAL_SIGNATURE_TOKEN;
if (!signatureToken) {
throw new Error("CAL_SIGNATURE_TOKEN needs to be set");
}
const signature = createSignature(body || {}, nonce, signatureToken);
const headers = {
...options.headers,
"Content-Type": "application/json",
nonce: nonce,
signature: signature,
"x-cal-license-key": this.licenseKey,
};
return await fetch(url, {
...options,
headers: headers,
body: JSON.stringify(body),
});
}
async incrementUsage(usageEvent?: UsageEvent) {
try {
const response = await this.fetcher({
url: `${this.baseUrl}/v1/license/usage/increment?event=${usageEvent ?? UsageEvent.BOOKING}`,
options: {
method: "POST",
mode: "cors",
},
});
return await response.json();
} catch (error) {
console.error("Incrementing usage failed:", error);
throw error;
}
}
async checkLicense(): Promise<boolean> {
/** We skip for E2E testing */
if (process.env.NEXT_PUBLIC_IS_E2E === "1") return true;
/** We check first on env */
const url = `${this.baseUrl}/v1/license/${this.licenseKey}`;
const cachedResponse = cache.get(url);
if (cachedResponse) return cachedResponse;
try {
const response = await this.fetcher({ url, options: { mode: "cors" } });
const data = await response.json();
cache.put(url, data.stauts, this.CACHING_TIME);
return data.status;
} catch (error) {
console.error("Check license failed:", error);
return false;
}
}
}
export default LicenseKeyService;
@@ -0,0 +1,13 @@
import crypto from "crypto";
export const generateNonce = (): string => {
return crypto.randomBytes(16).toString("hex");
};
// Utility function to create a signature
export const createSignature = (body: Record<string, unknown>, nonce: string, secretKey: string): string => {
return crypto
.createHmac("sha256", secretKey)
.update(JSON.stringify(body) + nonce)
.digest("hex");
};
@@ -1,9 +1,13 @@
import type { PrismaClient } from "@calcom/prisma";
export async function getDeploymentKey(prisma: PrismaClient) {
if (process.env.CALCOM_LICENSE_KEY) {
return process.env.CALCOM_LICENSE_KEY;
}
const deployment = await prisma.deployment.findUnique({
where: { id: 1 },
select: { licenseKey: true },
});
return deployment?.licenseKey || process.env.CALCOM_LICENSE_KEY || "";
return deployment?.licenseKey || "";
}
@@ -72,7 +72,7 @@ const CreateANewLicenseKeyFormChild = ({ session }: { session: Ensure<SessionCon
function calculateMonthlyPrice() {
const occurrence = watchedBillingPeriod === "MONTHLY" ? 1 : 12;
const sum = watchedEntityCount * watchedEntityPrice * occurrence;
const sum = watchedEntityCount * watchedEntityPrice;
return `$ ${sum / 100} / ${occurrence} months`;
}
+2
View File
@@ -153,6 +153,8 @@ export const CLOUDFLARE_SITE_ID = process.env.NEXT_PUBLIC_CLOUDFLARE_SITEKEY;
export const MINIMUM_NUMBER_OF_ORG_SEATS = 30;
export const ORG_SELF_SERVE_ENABLED = process.env.NEXT_PUBLIC_ORG_SELF_SERVE_ENABLED === "1";
export const ORG_MINIMUM_PUBLISHED_TEAMS_SELF_SERVE = 0;
export const CALCOM_PRIVATE_API_ROUTE = process.env.CALCOM_PRIVATE_API_ROUTE || "https://goblin.cal.com";
/**
* The maximum number of days we should check for if we don't find all required bookable days
* Counter start from current day and we would like to not go beyond 2 months(max days possible) from current day.
@@ -0,0 +1,32 @@
import { Prisma } from "@prisma/client";
import LicenseKeyService, { UsageEvent } from "@calcom/ee/common/server/LicenseKeyService";
export function usageTrackingExtention() {
return Prisma.defineExtension({
query: {
booking: {
async create({ args, query }) {
try {
const licenseKeyService = await LicenseKeyService.create();
await licenseKeyService.incrementUsage();
} catch (e) {
console.log(e);
}
return query(args);
},
},
user: {
async create({ args, query }) {
try {
const licenseKeyService = await LicenseKeyService.create();
await licenseKeyService.incrementUsage(UsageEvent.USER);
} catch (e) {
console.log(e);
}
return query(args);
},
},
},
});
}
+3
View File
@@ -4,6 +4,7 @@ import { withAccelerate } from "@prisma/extension-accelerate";
import { bookingIdempotencyKeyExtension } from "./extensions/booking-idempotency-key";
import { excludePendingPaymentsExtension } from "./extensions/exclude-pending-payment-teams";
import { usageTrackingExtention } from "./extensions/usage-tracking";
import { bookingReferenceMiddleware } from "./middleware";
const prismaOptions: Prisma.PrismaClientOptions = {};
@@ -21,6 +22,7 @@ const prismaWithoutClientExtensions =
export const customPrisma = (options?: Prisma.PrismaClientOptions) =>
new PrismaClientWithoutExtension({ ...prismaOptions, ...options })
.$extends(usageTrackingExtention())
.$extends(excludePendingPaymentsExtension())
.$extends(bookingIdempotencyKeyExtension())
.$extends(withAccelerate());
@@ -32,6 +34,7 @@ bookingReferenceMiddleware(prismaWithoutClientExtensions);
// FIXME: Due to some reason, there are types failing in certain places due to the $extends. Fix it and then enable it
// Specifically we get errors like `Type 'string | Date | null | undefined' is not assignable to type 'Exact<string | Date | null | undefined, string | Date | null | undefined>'`
const prismaWithClientExtensions = prismaWithoutClientExtensions
.$extends(usageTrackingExtention())
.$extends(excludePendingPaymentsExtension())
.$extends(bookingIdempotencyKeyExtension())
.$extends(withAccelerate());
@@ -1,6 +1,8 @@
import * as crypto from "crypto";
import { z } from "zod";
import { CALCOM_PRIVATE_API_ROUTE } from "@calcom/lib/constants";
import type { TrpcSessionUser } from "../../../trpc";
import type { TCreateSelfHostedLicenseSchema } from "./createSelfHostedLicenseKey.schema";
@@ -49,7 +51,7 @@ const fetchWithSignature = async (
};
const createSelfHostedInstance = async ({ input, ctx }: GetOptions) => {
const privateApiUrl = process.env.CALCOM_PRIVATE_API_ROUTE;
const privateApiUrl = CALCOM_PRIVATE_API_ROUTE;
const signatureToken = process.env.CAL_SIGNATURE_TOKEN;
if (!privateApiUrl || !signatureToken) {