feat: Add delegation credential error webhook trigger (#24871)
* feat: add delegation credential error webhook trigger - Add DELEGATION_CREDENTIAL_ERROR to WebhookTriggerEvents enum - Create DelegationCredentialErrorDTO type for webhook payload - Implement DelegationCredentialErrorWebhookService - Add translation for delegation_credential_error - Enable webhook for API v2 organization webhooks This webhook will send delegation credential error data to configured URLs when errors occur during calendar authentication with delegation credentials. Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com> * fix: add delegation credential error payload type and type guards - Add DelegationCredentialErrorPayloadType to sendPayload.ts - Update WebhookPayloadType union to include new payload type - Add isDelegationCredentialErrorPayload type guard function - Update isEventPayload to exclude delegation credential errors - Update template application logic to handle new payload type - Add corresponding payload type to dto/types.ts for consistency Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com> * feat: add delegation credential error handling to WebhookNotificationHandler - Add DELEGATION_CREDENTIAL_ERROR case to createPayload switch - Return payload with error, credential, and user data - Ensures exhaustive type checking passes for new trigger Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com> * feat: restrict DELEGATION_CREDENTIAL_ERROR to organization webhooks only - Add validation in UserWebhooksService to reject DELEGATION_CREDENTIAL_ERROR - Add validation in EventTypeWebhooksService to reject DELEGATION_CREDENTIAL_ERROR - Ensures trigger is only available for API v2 organization webhooks as requested Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com> * feat: wire up delegation credential error webhook emission in calendar services - Add webhook emission calls in CalendarAuth.ts for Google Calendar delegation errors - Add webhook emission calls in Office365 CalendarService.ts for Azure AD delegation errors - Implement actual webhook emission using WebhookRepository pattern - Fix pre-existing lint warnings in Office365 CalendarService.ts (unused catch variables, unsafe optional chaining) Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com> * test: add e2e tests for DELEGATION_CREDENTIAL_ERROR webhook trigger - Add comprehensive e2e tests for creating, retrieving, updating, and deleting webhooks with DELEGATION_CREDENTIAL_ERROR trigger - Test combining DELEGATION_CREDENTIAL_ERROR with other triggers - Fix import in triggerDelegationCredentialErrorWebhook.ts to use default import for sendPayload - Tests follow existing patterns in organizations-webhooks.e2e-spec.ts Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com> * refactor: remove name field from webhook payload and delete unused service - Remove name field from triggerDelegationCredentialErrorWebhook function signature and payload - Update all call sites in GoogleCalendar and Office365 calendar services - Update DelegationCredentialErrorDTO and DelegationCredentialErrorPayloadType to remove name field - Delete unused DelegationCredentialErrorWebhookService.ts (dead code - not used anywhere) - The helper function approach is more appropriate for app-store integrations without DI Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com> * refactor: make fire-and-forget intent explicit for webhook emission - Add void cast to all triggerDelegationCredentialErrorWebhook calls - Remove redundant .catch() handlers (helper already handles errors internally) - This makes it clear that webhook emission is non-blocking by design - Avoids delaying error propagation while webhook HTTP requests complete Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com> * feat: await webhook emission and add HTTP timeout for guaranteed delivery - Change all triggerDelegationCredentialErrorWebhook calls from void to await - Add 10-second timeout to webhook HTTP requests using AbortController - Remove name field from DelegationCredentialErrorPayloadType to match payload - Ensures webhooks are sent before error is thrown (per user requirement) - Prevents indefinite hangs on unresponsive webhook endpoints Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com> * fix: make getAuthUrl async and await all call sites - Make getAuthUrl async to support awaiting webhook emission - Add await to all 3 getAuthUrl call sites (constructor, getAzureUserId, testDelegationCredentialSetup) - Remove leftover name field from getAzureUserId webhook call - Fixes TS1308 error about await in non-async function Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com> * docs: add JSDoc clarifying error handling guarantees for webhook trigger Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com> * Revert "docs: add JSDoc clarifying error handling guarantees for webhook trigger" This reverts commit 3e33090197bfe2f2e3fb890402b32e04c44305e3. * Revert "fix: make getAuthUrl async and await all call sites" This reverts commit de28b7337149104412c861fd9b05e76fffc1fed7. * Revert "feat: await webhook emission and add HTTP timeout for guaranteed delivery" This reverts commit 9da7241f83a8373b4fadc03ccf34e097c28adf3a. * Revert "refactor: make fire-and-forget intent explicit for webhook emission" This reverts commit f4f7fa06b7dfa151bfbea29905b8783261d9f353. * feat: await webhook emission to match standard pattern - Updated all webhook call sites to await triggerDelegationCredentialErrorWebhook - Made getAuthUrl async and updated all 3 call sites to await it - Removed .catch() wrappers at call sites (error handling is in trigger function) - Matches standard pattern used in WebhookService.sendPayload with Promise.allSettled - Ensures webhooks are sent before delegation errors are thrown Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com> * fix: address PR feedback - add migration, remove 'as any', remove user.name - Add Prisma migration for DELEGATION_CREDENTIAL_ERROR enum - Replace 'as any' type casting with safe type-narrowing helper in CalendarAuth.ts - Remove user.name field from DelegationCredentialErrorPayloadType (email is sufficient) - Ensure all type definitions are consistent across sendPayload.ts and dto/types.ts Addresses feedback from alishaz-polymath and morgan@cal.com Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com> * chore: cleanup type in CalendarAuth * fix: missing DELEGATION_CREDENTIAL_ERROR in WEBHOOK_TRIGGER_EVENTS_GROUPED_BY_APP constant * fix: review * fit: import webhook dto * fit: type error * feat: add delegation credential error webhook handling to Office365 video adapter - Emit webhook before throwing delegation credential errors in Office365 video - Added webhook emission in 4 locations: 1. Missing clientId/Secret in fetchNewTokenObject 2. Missing tenantId in getAuthUrl 3. Missing clientId/Secret in getAzureUserId 4. User doesn't exist in Azure AD - Made getAuthUrl async to support webhook emission - Follows same pattern as GoogleCalendar and Office365Calendar implementations Co-Authored-By: morgan@cal.com <morgan@cal.com> Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com> * fixup! Merge branch 'devin/delegation-credential-errors-webhook-1762171203' of https://git-manager.devin.ai/proxy/github.com/calcom/cal.com into devin/delegation-credential-errors-webhook-1762171203 --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com> Co-authored-by: cal.com <morgan@cal.com>
This commit is contained in:
co-authored by
morgan@cal.com <morgan@cal.com>
rajiv@cal.com <sahalrajiv6900@gmail.com>
Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Morgan
cal.com
parent
9e1e50e90b
commit
e6d44ce620
+95
@@ -209,4 +209,99 @@ describe("WebhooksController (e2e)", () => {
|
||||
.delete(`/v2/organizations/${org.id}/webhooks/${otherWebhook.id}`)
|
||||
.expect(403);
|
||||
});
|
||||
|
||||
describe("DELEGATION_CREDENTIAL_ERROR webhook trigger", () => {
|
||||
let delegationWebhook: TeamWebhookOutputResponseDto["data"];
|
||||
|
||||
it("/organizations/:orgId/webhooks (POST) should create webhook with DELEGATION_CREDENTIAL_ERROR trigger", () => {
|
||||
return request(app.getHttpServer())
|
||||
.post(`/v2/organizations/${org.id}/webhooks`)
|
||||
.send({
|
||||
subscriberUrl: "https://example.com/delegation-errors",
|
||||
triggers: ["DELEGATION_CREDENTIAL_ERROR"],
|
||||
active: true,
|
||||
} satisfies CreateWebhookInputDto)
|
||||
.expect(201)
|
||||
.then(async (res) => {
|
||||
expect(res.body.status).toBe("success");
|
||||
expect(res.body.data).toMatchObject({
|
||||
id: expect.any(String),
|
||||
subscriberUrl: "https://example.com/delegation-errors",
|
||||
triggers: ["DELEGATION_CREDENTIAL_ERROR"],
|
||||
active: true,
|
||||
teamId: org.id,
|
||||
});
|
||||
delegationWebhook = res.body.data;
|
||||
});
|
||||
});
|
||||
|
||||
it("/organizations/:orgId/webhooks/:webhookId (GET) should retrieve webhook with DELEGATION_CREDENTIAL_ERROR trigger", () => {
|
||||
return request(app.getHttpServer())
|
||||
.get(`/v2/organizations/${org.id}/webhooks/${delegationWebhook.id}`)
|
||||
.expect(200)
|
||||
.then((res) => {
|
||||
expect(res.body.status).toBe("success");
|
||||
expect(res.body.data).toMatchObject({
|
||||
id: delegationWebhook.id,
|
||||
subscriberUrl: "https://example.com/delegation-errors",
|
||||
triggers: ["DELEGATION_CREDENTIAL_ERROR"],
|
||||
active: true,
|
||||
teamId: org.id,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("/organizations/:orgId/webhooks/:webhookId (PATCH) should update webhook with DELEGATION_CREDENTIAL_ERROR trigger", () => {
|
||||
return request(app.getHttpServer())
|
||||
.patch(`/v2/organizations/${org.id}/webhooks/${delegationWebhook.id}`)
|
||||
.send({
|
||||
active: false,
|
||||
subscriberUrl: "https://example.com/delegation-errors-updated",
|
||||
} satisfies UpdateWebhookInputDto)
|
||||
.expect(200)
|
||||
.then((res) => {
|
||||
expect(res.body.data.active).toBe(false);
|
||||
expect(res.body.data.subscriberUrl).toBe("https://example.com/delegation-errors-updated");
|
||||
expect(res.body.data.triggers).toEqual(["DELEGATION_CREDENTIAL_ERROR"]);
|
||||
});
|
||||
});
|
||||
|
||||
it("/organizations/:orgId/webhooks (POST) should allow combining DELEGATION_CREDENTIAL_ERROR with other triggers", () => {
|
||||
return request(app.getHttpServer())
|
||||
.post(`/v2/organizations/${org.id}/webhooks`)
|
||||
.send({
|
||||
subscriberUrl: "https://example.com/combined-webhook",
|
||||
triggers: ["BOOKING_CREATED", "DELEGATION_CREDENTIAL_ERROR"],
|
||||
active: true,
|
||||
} satisfies CreateWebhookInputDto)
|
||||
.expect(201)
|
||||
.then(async (res) => {
|
||||
expect(res.body.status).toBe("success");
|
||||
expect(res.body.data).toMatchObject({
|
||||
id: expect.any(String),
|
||||
subscriberUrl: "https://example.com/combined-webhook",
|
||||
triggers: expect.arrayContaining(["BOOKING_CREATED", "DELEGATION_CREDENTIAL_ERROR"]),
|
||||
active: true,
|
||||
teamId: org.id,
|
||||
});
|
||||
await request(app.getHttpServer())
|
||||
.delete(`/v2/organizations/${org.id}/webhooks/${res.body.data.id}`)
|
||||
.expect(200);
|
||||
});
|
||||
});
|
||||
|
||||
it("/organizations/:orgId/webhooks/:webhookId (DELETE) should delete webhook with DELEGATION_CREDENTIAL_ERROR trigger", () => {
|
||||
return request(app.getHttpServer())
|
||||
.delete(`/v2/organizations/${org.id}/webhooks/${delegationWebhook.id}`)
|
||||
.expect(200)
|
||||
.then((res) => {
|
||||
expect(res.body.status).toBe("success");
|
||||
expect(res.body.data).toMatchObject({
|
||||
id: delegationWebhook.id,
|
||||
triggers: ["DELEGATION_CREDENTIAL_ERROR"],
|
||||
teamId: org.id,
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
import { PipedInputWebhookType } from "@/modules/webhooks/pipes/WebhookInputPipe";
|
||||
import { WebhooksRepository } from "@/modules/webhooks/webhooks.repository";
|
||||
import { ConflictException, Injectable } from "@nestjs/common";
|
||||
import { BadRequestException, ConflictException, Injectable } from "@nestjs/common";
|
||||
|
||||
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
|
||||
|
||||
@Injectable()
|
||||
export class EventTypeWebhooksService {
|
||||
constructor(private readonly webhooksRepository: WebhooksRepository) {}
|
||||
|
||||
async createEventTypeWebhook(eventTypeId: number, body: PipedInputWebhookType) {
|
||||
if (body.eventTriggers.includes(WebhookTriggerEvents.DELEGATION_CREDENTIAL_ERROR)) {
|
||||
throw new BadRequestException(
|
||||
"DELEGATION_CREDENTIAL_ERROR trigger is only available for organization webhooks"
|
||||
);
|
||||
}
|
||||
|
||||
const existingWebhook = await this.webhooksRepository.getEventTypeWebhookByUrl(
|
||||
eventTypeId,
|
||||
body.subscriberUrl
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
import { PipedInputWebhookType } from "@/modules/webhooks/pipes/WebhookInputPipe";
|
||||
import { WebhooksRepository } from "@/modules/webhooks/webhooks.repository";
|
||||
import { ConflictException, Injectable } from "@nestjs/common";
|
||||
import { BadRequestException, ConflictException, Injectable } from "@nestjs/common";
|
||||
|
||||
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
|
||||
|
||||
@Injectable()
|
||||
export class UserWebhooksService {
|
||||
constructor(private readonly webhooksRepository: WebhooksRepository) {}
|
||||
|
||||
async createUserWebhook(userId: number, body: PipedInputWebhookType) {
|
||||
if (body.eventTriggers.includes(WebhookTriggerEvents.DELEGATION_CREDENTIAL_ERROR)) {
|
||||
throw new BadRequestException(
|
||||
"DELEGATION_CREDENTIAL_ERROR trigger is only available for organization webhooks"
|
||||
);
|
||||
}
|
||||
|
||||
const existingWebhook = await this.webhooksRepository.getUserWebhookByUrl(userId, body.subscriberUrl);
|
||||
if (existingWebhook) {
|
||||
throw new ConflictException("Webhook with this subscriber url already exists for this user");
|
||||
|
||||
@@ -568,6 +568,7 @@
|
||||
"booking_paid": "Booking Paid",
|
||||
"ooo_created": "Out of Office Created",
|
||||
"booking_no_show_updated": "Booking No-Show Updated",
|
||||
"delegation_credential_error": "Delegation Credential Error",
|
||||
"event_triggers": "Event Triggers",
|
||||
"subscriber_url": "Subscriber URL",
|
||||
"create_new_webhook": "Create a new webhook",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import { calendar_v3 } from "@googleapis/calendar";
|
||||
import { OAuth2Client, JWT } from "googleapis-common";
|
||||
|
||||
import { triggerDelegationCredentialErrorWebhook } from "@calcom/features/webhooks/lib/triggerDelegationCredentialErrorWebhook";
|
||||
import {
|
||||
CalendarAppDelegationCredentialClientIdNotAuthorizedError,
|
||||
CalendarAppDelegationCredentialInvalidGrantError,
|
||||
@@ -124,20 +124,39 @@ export class CalendarAuth {
|
||||
} catch (error) {
|
||||
log.error("DelegatedTo: Error authorizing using JWT auth", JSON.stringify(error));
|
||||
|
||||
if ((error as any).response?.data?.error === "unauthorized_client") {
|
||||
throw new CalendarAppDelegationCredentialClientIdNotAuthorizedError(
|
||||
let delegationError: CalendarAppDelegationCredentialError;
|
||||
|
||||
const errorCode = (error as { response?: { data?: { error?: string } } }).response?.data?.error;
|
||||
if (errorCode === "unauthorized_client") {
|
||||
delegationError = new CalendarAppDelegationCredentialClientIdNotAuthorizedError(
|
||||
"Make sure that the Client ID for the delegation credential is added to the Google Workspace Admin Console"
|
||||
);
|
||||
}
|
||||
|
||||
if ((error as any).response?.data?.error === "invalid_grant") {
|
||||
throw new CalendarAppDelegationCredentialInvalidGrantError(
|
||||
} else if (errorCode === "invalid_grant") {
|
||||
delegationError = new CalendarAppDelegationCredentialInvalidGrantError(
|
||||
`User ${emailToImpersonate} might not exist in Google Workspace`
|
||||
);
|
||||
} else {
|
||||
// Catch all error
|
||||
delegationError = new CalendarAppDelegationCredentialError("Error authorizing delegation credential");
|
||||
}
|
||||
|
||||
// Catch all error
|
||||
throw new CalendarAppDelegationCredentialError("Error authorizing delegation credential");
|
||||
if (user && user.email && this.credential.appId) {
|
||||
await triggerDelegationCredentialErrorWebhook({
|
||||
error: delegationError,
|
||||
credential: {
|
||||
id: this.credential.id,
|
||||
type: this.credential.type,
|
||||
appId: this.credential.appId,
|
||||
},
|
||||
user: {
|
||||
id: this.credential.userId ?? 0,
|
||||
email: user.email,
|
||||
},
|
||||
orgId: this.credential.teamId,
|
||||
});
|
||||
}
|
||||
|
||||
throw delegationError;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import { findIana } from "windows-iana";
|
||||
|
||||
import { MSTeamsLocationType } from "@calcom/app-store/constants";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { triggerDelegationCredentialErrorWebhook } from "@calcom/features/webhooks/lib/triggerDelegationCredentialErrorWebhook";
|
||||
import { getLocation, getRichDescriptionHTML } from "@calcom/lib/CalEventParser";
|
||||
import {
|
||||
CalendarAppDelegationCredentialInvalidGrantError,
|
||||
@@ -82,7 +83,7 @@ export default class Office365CalendarService implements Calendar {
|
||||
|
||||
const { client_id, client_secret } = await this.getAuthCredentials(isDelegated);
|
||||
|
||||
const url = this.getAuthUrl(isDelegated, credential?.delegatedTo?.serviceAccountKey?.tenant_id);
|
||||
const url = await this.getAuthUrl(isDelegated, credential?.delegatedTo?.serviceAccountKey?.tenant_id);
|
||||
|
||||
const bodyParams = {
|
||||
scope: isDelegated
|
||||
@@ -123,12 +124,30 @@ export default class Office365CalendarService implements Calendar {
|
||||
this.log = logger.getSubLogger({ prefix: [`[[lib] ${this.integrationName}`] });
|
||||
}
|
||||
|
||||
private getAuthUrl(delegatedTo: boolean, tenantId?: string): string {
|
||||
private async getAuthUrl(delegatedTo: boolean, tenantId?: string): Promise<string> {
|
||||
if (delegatedTo) {
|
||||
if (!tenantId) {
|
||||
throw new CalendarAppDelegationCredentialInvalidGrantError(
|
||||
const error = new CalendarAppDelegationCredentialInvalidGrantError(
|
||||
"Invalid DelegationCredential Settings: tenantId is missing"
|
||||
);
|
||||
|
||||
if (this.credential.userId && this.credential.user && this.credential.appId) {
|
||||
await triggerDelegationCredentialErrorWebhook({
|
||||
error,
|
||||
credential: {
|
||||
id: this.credential.id,
|
||||
type: this.credential.type,
|
||||
appId: this.credential.appId,
|
||||
},
|
||||
user: {
|
||||
id: this.credential.userId,
|
||||
email: this.credential.user.email,
|
||||
},
|
||||
orgId: this.credential.teamId,
|
||||
});
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
return `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;
|
||||
}
|
||||
@@ -142,9 +161,27 @@ export default class Office365CalendarService implements Calendar {
|
||||
const client_secret = this.credential?.delegatedTo?.serviceAccountKey?.private_key;
|
||||
|
||||
if (!client_id || !client_secret) {
|
||||
throw new CalendarAppDelegationCredentialConfigurationError(
|
||||
const error = new CalendarAppDelegationCredentialConfigurationError(
|
||||
"Delegation credential without clientId or Secret"
|
||||
);
|
||||
|
||||
if (this.credential.userId && this.credential.user && this.credential.appId) {
|
||||
await triggerDelegationCredentialErrorWebhook({
|
||||
error,
|
||||
credential: {
|
||||
id: this.credential.id,
|
||||
type: this.credential.type,
|
||||
appId: this.credential.appId,
|
||||
},
|
||||
user: {
|
||||
id: this.credential.userId,
|
||||
email: this.credential.user.email,
|
||||
},
|
||||
orgId: this.credential.teamId,
|
||||
});
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
return { client_id, client_secret };
|
||||
@@ -160,15 +197,33 @@ export default class Office365CalendarService implements Calendar {
|
||||
|
||||
if (!isDelegated) return;
|
||||
|
||||
const url = this.getAuthUrl(isDelegated, credential?.delegatedTo?.serviceAccountKey?.tenant_id);
|
||||
const url = await this.getAuthUrl(isDelegated, credential?.delegatedTo?.serviceAccountKey?.tenant_id);
|
||||
|
||||
const delegationCredentialClientId = credential.delegatedTo?.serviceAccountKey?.client_id;
|
||||
const delegationCredentialClientSecret = credential.delegatedTo?.serviceAccountKey?.private_key;
|
||||
|
||||
if (!delegationCredentialClientId || !delegationCredentialClientSecret) {
|
||||
throw new CalendarAppDelegationCredentialConfigurationError(
|
||||
const error = new CalendarAppDelegationCredentialConfigurationError(
|
||||
"Delegation credential without clientId or Secret"
|
||||
);
|
||||
|
||||
if (this.credential.userId && this.credential.user && this.credential.appId) {
|
||||
await triggerDelegationCredentialErrorWebhook({
|
||||
error,
|
||||
credential: {
|
||||
id: this.credential.id,
|
||||
type: this.credential.type,
|
||||
appId: this.credential.appId,
|
||||
},
|
||||
user: {
|
||||
id: this.credential.userId,
|
||||
email: this.credential.user.email,
|
||||
},
|
||||
orgId: this.credential.teamId,
|
||||
});
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
const loginResponse = await fetch(url, {
|
||||
method: "POST",
|
||||
@@ -201,9 +256,27 @@ export default class Office365CalendarService implements Calendar {
|
||||
const parsedBody = await response.json();
|
||||
|
||||
if (!parsedBody?.value?.[0]?.id) {
|
||||
throw new CalendarAppDelegationCredentialInvalidGrantError(
|
||||
const error = new CalendarAppDelegationCredentialInvalidGrantError(
|
||||
"User might not exist in Microsoft Azure Active Directory"
|
||||
);
|
||||
|
||||
if (this.credential.userId && this.credential.user && this.credential.appId) {
|
||||
await triggerDelegationCredentialErrorWebhook({
|
||||
error,
|
||||
credential: {
|
||||
id: this.credential.id,
|
||||
type: this.credential.type,
|
||||
appId: this.credential.appId,
|
||||
},
|
||||
user: {
|
||||
id: this.credential.userId ?? 0,
|
||||
email: this.credential.user.email,
|
||||
},
|
||||
orgId: this.credential.teamId,
|
||||
});
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
this.azureUserId = parsedBody.value[0].id;
|
||||
}
|
||||
@@ -214,7 +287,7 @@ export default class Office365CalendarService implements Calendar {
|
||||
async testDelegationCredentialSetup(): Promise<boolean> {
|
||||
const delegationCredentialClientId = this.credential.delegatedTo?.serviceAccountKey?.client_id;
|
||||
const delegationCredentialClientSecret = this.credential.delegatedTo?.serviceAccountKey?.private_key;
|
||||
const url = this.getAuthUrl(
|
||||
const url = await this.getAuthUrl(
|
||||
Boolean(this.credential?.delegatedTo),
|
||||
this.credential?.delegatedTo?.serviceAccountKey?.tenant_id
|
||||
);
|
||||
@@ -375,7 +448,7 @@ export default class Office365CalendarService implements Calendar {
|
||||
alreadySuccessResponse = await this.fetchResponsesWithNextLink(responseBatchApi.responses);
|
||||
|
||||
return alreadySuccessResponse ? this.processBusyTimes(alreadySuccessResponse) : [];
|
||||
} catch (err) {
|
||||
} catch {
|
||||
return Promise.reject([]);
|
||||
}
|
||||
}
|
||||
@@ -477,7 +550,7 @@ export default class Office365CalendarService implements Calendar {
|
||||
type: "required" as const,
|
||||
})),
|
||||
...(event.team?.members
|
||||
? event.team?.members
|
||||
? event.team.members
|
||||
.filter((member) => member.email !== this.credential.user?.email)
|
||||
.map((member) => {
|
||||
const destinationCalendar =
|
||||
@@ -627,7 +700,7 @@ export default class Office365CalendarService implements Calendar {
|
||||
try {
|
||||
const parsedJson = JSON.parse(response);
|
||||
return parsedJson;
|
||||
} catch (error) {
|
||||
} catch {
|
||||
// Looking for html in body
|
||||
const openTag = '"body":<';
|
||||
const closeTag = "</html>";
|
||||
@@ -677,7 +750,7 @@ export default class Office365CalendarService implements Calendar {
|
||||
let errorBody: string | object;
|
||||
try {
|
||||
errorBody = await response.json();
|
||||
} catch (e) {
|
||||
} catch {
|
||||
errorBody = await response.text();
|
||||
}
|
||||
this.log.error(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { triggerDelegationCredentialErrorWebhook } from "@calcom/features/webhooks/lib/triggerDelegationCredentialErrorWebhook";
|
||||
import {
|
||||
CalendarAppDelegationCredentialConfigurationError,
|
||||
CalendarAppDelegationCredentialInvalidGrantError,
|
||||
@@ -63,12 +64,30 @@ const TeamsVideoApiAdapter = (credential: CredentialForCalendarServiceWithTenant
|
||||
: await getO365VideoAppKeys();
|
||||
|
||||
if (isDelegated && (!credentials.client_id || !credentials.client_secret)) {
|
||||
throw new CalendarAppDelegationCredentialConfigurationError(
|
||||
const error = new CalendarAppDelegationCredentialConfigurationError(
|
||||
"Delegation credential without clientId or Secret"
|
||||
);
|
||||
|
||||
if (credential.userId && credential.user && credential.appId) {
|
||||
await triggerDelegationCredentialErrorWebhook({
|
||||
error,
|
||||
credential: {
|
||||
id: credential.id,
|
||||
type: credential.type,
|
||||
appId: credential.appId,
|
||||
},
|
||||
user: {
|
||||
id: credential.userId ?? 0,
|
||||
email: credential.user.email,
|
||||
},
|
||||
orgId: credential.teamId,
|
||||
});
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
const url = getAuthUrl(isDelegated, credential?.delegatedTo?.serviceAccountKey?.tenant_id);
|
||||
const url = await getAuthUrl(isDelegated, credential?.delegatedTo?.serviceAccountKey?.tenant_id);
|
||||
const scope = isDelegated ? "https://graph.microsoft.com/.default" : OFFICE365_VIDEO_SCOPES.join(" ");
|
||||
|
||||
const params: Record<string, string> = {
|
||||
@@ -97,19 +116,37 @@ const TeamsVideoApiAdapter = (credential: CredentialForCalendarServiceWithTenant
|
||||
invalidateTokenObject: () => oAuthManagerHelper.invalidateCredential(credential.id),
|
||||
expireAccessToken: () => oAuthManagerHelper.markTokenAsExpired(credential),
|
||||
updateTokenObject: (tokenObject) => {
|
||||
if (!Boolean(credential.delegatedTo)) {
|
||||
if (!credential.delegatedTo) {
|
||||
return oAuthManagerHelper.updateTokenObject({ tokenObject, credentialId: credential.id });
|
||||
}
|
||||
return Promise.resolve();
|
||||
},
|
||||
});
|
||||
|
||||
function getAuthUrl(delegatedTo: boolean, tenantId?: string): string {
|
||||
async function getAuthUrl(delegatedTo: boolean, tenantId?: string): Promise<string> {
|
||||
if (delegatedTo) {
|
||||
if (!tenantId) {
|
||||
throw new CalendarAppDelegationCredentialInvalidGrantError(
|
||||
const error = new CalendarAppDelegationCredentialInvalidGrantError(
|
||||
"Invalid DelegationCredential Settings: tenantId is missing"
|
||||
);
|
||||
|
||||
if (credential.userId && credential.user && credential.appId) {
|
||||
await triggerDelegationCredentialErrorWebhook({
|
||||
error,
|
||||
credential: {
|
||||
id: credential.id,
|
||||
type: credential.type,
|
||||
appId: credential.appId,
|
||||
},
|
||||
user: {
|
||||
id: credential.userId ?? 0,
|
||||
email: credential.user.email,
|
||||
},
|
||||
orgId: credential.teamId,
|
||||
});
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
return `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;
|
||||
}
|
||||
@@ -132,15 +169,33 @@ const TeamsVideoApiAdapter = (credential: CredentialForCalendarServiceWithTenant
|
||||
|
||||
if (!isDelegated) return null;
|
||||
|
||||
const url = getAuthUrl(isDelegated, credential?.delegatedTo?.serviceAccountKey?.tenant_id);
|
||||
const url = await getAuthUrl(isDelegated, credential?.delegatedTo?.serviceAccountKey?.tenant_id);
|
||||
|
||||
const delegationCredentialClientId = credential.delegatedTo?.serviceAccountKey?.client_id;
|
||||
const delegationCredentialClientSecret = credential.delegatedTo?.serviceAccountKey?.private_key;
|
||||
|
||||
if (!delegationCredentialClientId || !delegationCredentialClientSecret) {
|
||||
throw new CalendarAppDelegationCredentialConfigurationError(
|
||||
const error = new CalendarAppDelegationCredentialConfigurationError(
|
||||
"Delegation credential without clientId or Secret"
|
||||
);
|
||||
|
||||
if (credential.userId && credential.user && credential.appId) {
|
||||
await triggerDelegationCredentialErrorWebhook({
|
||||
error,
|
||||
credential: {
|
||||
id: credential.id,
|
||||
type: credential.type,
|
||||
appId: credential.appId,
|
||||
},
|
||||
user: {
|
||||
id: credential.userId ?? 0,
|
||||
email: credential.user.email,
|
||||
},
|
||||
orgId: credential.teamId,
|
||||
});
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
const loginResponse = await fetch(url, {
|
||||
method: "POST",
|
||||
@@ -172,9 +227,27 @@ const TeamsVideoApiAdapter = (credential: CredentialForCalendarServiceWithTenant
|
||||
const parsedBody = await response.json();
|
||||
|
||||
if (!parsedBody?.value?.[0]?.id) {
|
||||
throw new CalendarAppDelegationCredentialInvalidGrantError(
|
||||
const error = new CalendarAppDelegationCredentialInvalidGrantError(
|
||||
"User might not exist in Microsoft Azure Active Directory"
|
||||
);
|
||||
|
||||
if (credential.userId && credential.user && credential.appId) {
|
||||
await triggerDelegationCredentialErrorWebhook({
|
||||
error,
|
||||
credential: {
|
||||
id: credential.id,
|
||||
type: credential.type,
|
||||
appId: credential.appId,
|
||||
},
|
||||
user: {
|
||||
id: credential.userId ?? 0,
|
||||
email: credential.user.email,
|
||||
},
|
||||
orgId: credential.teamId,
|
||||
});
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
azureUserId = parsedBody.value[0].id;
|
||||
return azureUserId;
|
||||
|
||||
@@ -20,6 +20,7 @@ export const WEBHOOK_TRIGGER_EVENTS_GROUPED_BY_APP = {
|
||||
WebhookTriggerEvents.OOO_CREATED,
|
||||
WebhookTriggerEvents.AFTER_HOSTS_CAL_VIDEO_NO_SHOW,
|
||||
WebhookTriggerEvents.AFTER_GUESTS_CAL_VIDEO_NO_SHOW,
|
||||
WebhookTriggerEvents.DELEGATION_CREDENTIAL_ERROR,
|
||||
] as const,
|
||||
"routing-forms": [
|
||||
WebhookTriggerEvents.FORM_SUBMITTED,
|
||||
|
||||
@@ -331,6 +331,12 @@ export interface AfterGuestsNoShowDTO extends BaseEventDTO {
|
||||
};
|
||||
}
|
||||
|
||||
export interface DelegationCredentialErrorDTO
|
||||
extends BaseEventDTO,
|
||||
Pick<DelegationCredentialErrorPayloadType, "error" | "credential" | "user"> {
|
||||
triggerEvent: typeof WebhookTriggerEvents.DELEGATION_CREDENTIAL_ERROR;
|
||||
}
|
||||
|
||||
export type WebhookEventDTO =
|
||||
| BookingCreatedDTO
|
||||
| BookingCancelledDTO
|
||||
@@ -349,7 +355,8 @@ export type WebhookEventDTO =
|
||||
| MeetingEndedDTO
|
||||
| InstantMeetingDTO
|
||||
| AfterHostsNoShowDTO
|
||||
| AfterGuestsNoShowDTO;
|
||||
| AfterGuestsNoShowDTO
|
||||
| DelegationCredentialErrorDTO;
|
||||
|
||||
// Service layer interfaces
|
||||
export interface WebhookTriggerArgs {
|
||||
@@ -482,6 +489,22 @@ export type OOOEntryPayloadType = {
|
||||
};
|
||||
};
|
||||
|
||||
export type DelegationCredentialErrorPayloadType = {
|
||||
error: {
|
||||
type: string;
|
||||
message: string;
|
||||
};
|
||||
credential: {
|
||||
id: number;
|
||||
type: string;
|
||||
appId: string;
|
||||
};
|
||||
user: {
|
||||
id: number;
|
||||
email: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type EventPayloadType = CalendarEvent &
|
||||
TranscriptionGeneratedPayload &
|
||||
EventTypeInfo & {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { compile } from "handlebars";
|
||||
|
||||
import type { TGetTranscriptAccessLink } from "@calcom/app-store/dailyvideo/zod";
|
||||
import { getHumanReadableLocationValue } from "@calcom/app-store/locations";
|
||||
import { DelegationCredentialErrorPayloadType } from "@calcom/features/webhooks/lib/dto/types";
|
||||
import { getUTCOffsetByTimezone } from "@calcom/lib/dayjs";
|
||||
import type { Payment, Webhook } from "@calcom/prisma/client";
|
||||
import type { CalendarEvent, Person } from "@calcom/types/Calendar";
|
||||
@@ -94,7 +95,11 @@ export type EventPayloadType = CalendarEvent &
|
||||
paymentData?: Payment;
|
||||
};
|
||||
|
||||
export type WebhookPayloadType = EventPayloadType | OOOEntryPayloadType | BookingNoShowUpdatedPayload;
|
||||
export type WebhookPayloadType =
|
||||
| EventPayloadType
|
||||
| OOOEntryPayloadType
|
||||
| BookingNoShowUpdatedPayload
|
||||
| DelegationCredentialErrorPayloadType;
|
||||
|
||||
type WebhookDataType = WebhookPayloadType & { triggerEvent: string; createdAt: string };
|
||||
|
||||
@@ -191,11 +196,17 @@ export function isOOOEntryPayload(data: WebhookPayloadType): data is OOOEntryPay
|
||||
}
|
||||
|
||||
export function isNoShowPayload(data: WebhookPayloadType): data is BookingNoShowUpdatedPayload {
|
||||
return "message" in data;
|
||||
return "message" in data && "bookingUid" in data;
|
||||
}
|
||||
|
||||
export function isDelegationCredentialErrorPayload(
|
||||
data: WebhookPayloadType
|
||||
): data is DelegationCredentialErrorPayloadType {
|
||||
return "error" in data && "credential" in data && "user" in data;
|
||||
}
|
||||
|
||||
export function isEventPayload(data: WebhookPayloadType): data is EventPayloadType {
|
||||
return !isNoShowPayload(data) && !isOOOEntryPayload(data);
|
||||
return !isNoShowPayload(data) && !isOOOEntryPayload(data) && !isDelegationCredentialErrorPayload(data);
|
||||
}
|
||||
|
||||
const sendPayload = async (
|
||||
@@ -222,7 +233,13 @@ const sendPayload = async (
|
||||
}
|
||||
|
||||
if (body === undefined) {
|
||||
if (template && (isOOOEntryPayload(data) || isEventPayload(data) || isNoShowPayload(data))) {
|
||||
if (
|
||||
template &&
|
||||
(isOOOEntryPayload(data) ||
|
||||
isEventPayload(data) ||
|
||||
isNoShowPayload(data) ||
|
||||
isDelegationCredentialErrorPayload(data))
|
||||
) {
|
||||
body = applyTemplate(template, { ...data, triggerEvent, createdAt }, contentType);
|
||||
} else {
|
||||
body = JSON.stringify({
|
||||
|
||||
@@ -125,6 +125,18 @@ export class WebhookNotificationHandler implements IWebhookNotificationHandler {
|
||||
};
|
||||
}
|
||||
|
||||
case WebhookTriggerEvents.DELEGATION_CREDENTIAL_ERROR: {
|
||||
return {
|
||||
triggerEvent: dto.triggerEvent,
|
||||
createdAt: dto.createdAt,
|
||||
payload: {
|
||||
error: dto.error,
|
||||
credential: dto.credential,
|
||||
user: dto.user,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
default: {
|
||||
// TypeScript exhaustiveness check - this should never happen if all cases are covered
|
||||
const _exhaustiveCheck: never = dto;
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { DelegationCredentialErrorPayloadType } from "@calcom/features/webhooks/lib/dto/types";
|
||||
import type { CalendarAppDelegationCredentialError } from "@calcom/lib/CalendarAppError";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
|
||||
|
||||
import { WebhookRepository } from "./repository/WebhookRepository";
|
||||
import sendPayload from "./sendPayload";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["triggerDelegationCredentialErrorWebhook"] });
|
||||
|
||||
/**
|
||||
* Triggers delegation credential error webhooks for organization webhooks subscribed to DELEGATION_CREDENTIAL_ERROR
|
||||
*/
|
||||
export async function triggerDelegationCredentialErrorWebhook(params: {
|
||||
error: CalendarAppDelegationCredentialError;
|
||||
credential: DelegationCredentialErrorPayloadType["credential"];
|
||||
user: DelegationCredentialErrorPayloadType["user"];
|
||||
orgId?: number | null;
|
||||
}): Promise<void> {
|
||||
try {
|
||||
const { error, credential, user, orgId } = params;
|
||||
|
||||
if (!orgId) {
|
||||
log.debug("Skipping webhook emission - no organization context");
|
||||
return;
|
||||
}
|
||||
|
||||
const webhookRepository = WebhookRepository.getInstance();
|
||||
const webhooks = await webhookRepository.getSubscribers({
|
||||
teamId: orgId,
|
||||
triggerEvent: WebhookTriggerEvents.DELEGATION_CREDENTIAL_ERROR,
|
||||
});
|
||||
|
||||
if (webhooks.length === 0) {
|
||||
log.debug("No webhooks subscribed to DELEGATION_CREDENTIAL_ERROR for organization", { orgId });
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = {
|
||||
error: {
|
||||
type: error.constructor.name,
|
||||
message: error.message,
|
||||
},
|
||||
credential: {
|
||||
id: credential.id,
|
||||
type: credential.type,
|
||||
appId: credential.appId || "unknown",
|
||||
},
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
},
|
||||
} satisfies DelegationCredentialErrorPayloadType;
|
||||
|
||||
const webhookPromises = webhooks.map((webhook) =>
|
||||
sendPayload(
|
||||
webhook.secret,
|
||||
WebhookTriggerEvents.DELEGATION_CREDENTIAL_ERROR,
|
||||
new Date().toISOString(),
|
||||
webhook,
|
||||
payload
|
||||
).catch((err) => {
|
||||
log.error("Failed to send delegation credential error webhook", {
|
||||
webhookId: webhook.id,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
await Promise.allSettled(webhookPromises);
|
||||
|
||||
log.info("Delegation credential error webhooks triggered", {
|
||||
webhookCount: webhooks.length,
|
||||
userId: user.id,
|
||||
credentialId: credential.id,
|
||||
errorType: error.constructor.name,
|
||||
});
|
||||
} catch (webhookError) {
|
||||
log.error("Failed to trigger delegation credential error webhook", {
|
||||
error: webhookError instanceof Error ? webhookError.message : String(webhookError),
|
||||
});
|
||||
}
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
-- AlterEnum
|
||||
ALTER TYPE "public"."WebhookTriggerEvents" ADD VALUE 'DELEGATION_CREDENTIAL_ERROR';
|
||||
@@ -1089,6 +1089,7 @@ enum WebhookTriggerEvents {
|
||||
AFTER_HOSTS_CAL_VIDEO_NO_SHOW
|
||||
AFTER_GUESTS_CAL_VIDEO_NO_SHOW
|
||||
FORM_SUBMITTED_NO_EVENT
|
||||
DELEGATION_CREDENTIAL_ERROR
|
||||
}
|
||||
|
||||
model Webhook {
|
||||
|
||||
Reference in New Issue
Block a user