Skip to content

Conversation

@hariombalhara
Copy link
Member

@hariombalhara hariombalhara commented May 19, 2025

What does this PR do?

Fixes PRI-277

This PR unifies OAuth and JWT authentication by abstracting the existing JWT implementations to use OAuthManager as well. This makes JWT and OAuth approach quite similar and easier to understand.

It in-turn allows us to reuse the access token for JWT flow too which is used by Delegation Credential flow

Key Changes:

  • Unified Authentication: Created CalendarAuth class that handles both OAuth and JWT authentication through the same interface
  • Token Reuse: Extended OAuthManager to work with JWT, enabling access token reuse by creating credentials with tokens when needed
  • getCurrentTokenObject support in OAuthManager
  • Code Abstraction: Refactored existing OAuth and JWT code into a cleaner, shared architecture
  • Enhanced Token Management: JWT now benefits from the same token expiry checking and refresh mechanisms as OAuth
  • Better token Expiry handling - Earlier we were considering a token as expired when it was actually expired but now we consider it expired if it will expire in next 5 seconds.
  • Better error reporting from OAuthManager

Tests

  • Added more tests for CalendarService and moved auth based tests to separate CalendarService.auth.test.ts module. The tests in auth.test.ts dont mock OAuthManager and are better able to test auth flow
  • Added more tests for OAuthManager to test new functionality

Mandatory Tasks (DO NOT REMOVE)

  • I have self-reviewed the code (A decent size PR without self-review might be rejected).
  • I have updated the developer docs in /docs if this PR makes changes that would require a documentation change. If N/A, write N/A here and check the checkbox.
  • I confirm automated tests are in place that prove my fix is effective or that my feature works.

How should this be tested?

@github-actions
Copy link
Contributor

github-actions bot commented May 19, 2025

Hey there and thank you for opening this pull request! 👋🏼

We require pull request titles to follow the Conventional Commits specification and it looks like your proposed title needs to be adjusted.

Details:

No release type found in pull request title "persist-access-token-dwd". Add a prefix to indicate what kind of release this pull request corresponds to. For reference, see https://www.conventionalcommits.org/

Available types:
 - feat: A new feature
 - fix: A bug fix
 - docs: Documentation only changes
 - style: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
 - refactor: A code change that neither fixes a bug nor adds a feature
 - perf: A code change that improves performance
 - test: Adding missing tests or correcting existing tests
 - build: Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)
 - ci: Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)
 - chore: Other changes that don't modify src or test files
 - revert: Reverts a previous commit

Copy link
Member Author

hariombalhara commented May 19, 2025

@vercel
Copy link

vercel bot commented May 19, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
cal ⬜️ Ignored (Inspect) Visit Preview May 26, 2025 8:50am

expect(async () => {
return auth.getTokenObjectOrFetch();
}).rejects.toThrowError("Invalid token response");
}).rejects.toThrowError("fetchNewTokenObject error");
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now we report the actual error

Comment on lines +502 to +539
if (json && json.myFetchError) {
// Throw error back as it isn't a valid token response and we can't process it further
throw new Error(json.myFetchError);
}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We report the actual error now instead of going forward with this json and then being unable to parse the obviously invalid token and then throwing 'Invalid token response' error.

This was hiding the actual reason behind the error.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Most of the helper functions are moved to utils.ts so that they can be shared with CalendarService.auth.test.ts as well

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, all the auth testing related tests are moved to CalendarService.auth.test.ts where we don't mock OAuthManager and are more reliably to test Authentication.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test module has all the auth related tests moved from CalendarService.test.ts

@hariombalhara hariombalhara force-pushed the 05-19-persist-access-token-dwd branch from 38c2dbc to 8a75800 Compare May 20, 2025 10:17
@hariombalhara hariombalhara changed the title persist-access-token-dwd fix: Ensure that Delegation Credential are able to reuse access_token May 20, 2025
@hariombalhara hariombalhara force-pushed the 05-19-persist-access-token-dwd branch from 8a75800 to 66a4889 Compare May 20, 2025 10:29
@github-actions
Copy link
Contributor

github-actions bot commented May 20, 2025

E2E results are ready!

return {
...credential,
key: booleanKeyStatus,
delegatedTo: !!credential.delegatedTo,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure that delegatedTo isn't logged fully.

safeStringify({
enrichedHosts: enrichedHosts.map((host) => {
return {
userId: host.user.id,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't log anything more than what we need.

Comment on lines +77 to +108
vi.mock("googleapis-common", async () => {
const actual = await vi.importActual("googleapis-common");
return {
...actual,
OAuth2Client: vi.fn().mockImplementation((...args: [string, string, string]) => {
lastCreatedOAuth2Client = {
type: "oauth2",
args,
setCredentials: setCredentialsMock,
isTokenExpiring: vi.fn().mockReturnValue(true),
refreshToken: vi.fn().mockResolvedValue({
res: {
data: MOCK_OAUTH2_TOKEN,
status: 200,
statusText: "OK",
},
}),
};
return lastCreatedOAuth2Client;
}),
JWT: vi.fn().mockImplementation((config: MockJWT["config"]) => {
lastCreatedJWT = {
type: "jwt",
config,
authorize: vi.fn().mockResolvedValue(undefined),
};
return lastCreatedJWT;
}),
};
});
vi.mock("@googleapis/admin", () => adminMock);
vi.mock("@googleapis/calendar", () => calendarMock);
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved these here from CalendarService.test.ts

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved here fromCalendarService.test.ts

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved here fromCalendarService.test.ts

@hariombalhara hariombalhara changed the base branch from main to graphite-base/21389 May 22, 2025 09:04
@hariombalhara hariombalhara force-pushed the 05-19-persist-access-token-dwd branch from adf5260 to 64b5781 Compare May 22, 2025 09:04
@hariombalhara hariombalhara changed the base branch from graphite-base/21389 to 05-22-fix_error_in_selected-calendars_cron_for_delegation_credential May 22, 2025 09:04
@linear
Copy link

linear bot commented May 23, 2025

PRI-277

@graphite-app
Copy link

graphite-app bot commented May 23, 2025

Graphite Automations

"Add consumer team as reviewer" took an action on this PR • (05/23/25)

1 reviewer was added to this PR based on Keith Williams's automation.

"Add foundation team as reviewer" took an action on this PR • (05/25/25)

1 reviewer was added to this PR based on Keith Williams's automation.

@hariombalhara hariombalhara requested a review from zomars May 23, 2025 11:07
@hariombalhara hariombalhara self-assigned this May 23, 2025
@hariombalhara hariombalhara added the High priority Created by Linear-GitHub Sync label May 23, 2025
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cubic found 12 issues across 20 files. Review them in cubic.dev

React with 👍 or 👎 to teach cubic. Tag @cubic-dev-ai to give specific feedback.

});

// If no delegation-credential is updated, create one
if (updated.count === 0) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Creating a new delegation-credential after an updateMany that returned 0 is vulnerable to a classic race condition. If two parallel requests run this code, both can see count === 0 and each create a new row, leading to duplicate credentials. This should be handled with an atomic upsert or a Prisma transaction.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An upsert isn't possible at the moment because userId and delegationCredentialId isn't unique

@hariombalhara hariombalhara changed the title fix: GoogleCalendar - Ensure that Delegation Credential are able to reuse access_token fix: GoogleCalendar - Ensure that Delegation Credentials are able to reuse access_token May 23, 2025
@zomars zomars enabled auto-merge (squash) May 23, 2025 20:50
zomars
zomars previously approved these changes May 23, 2025
@Udit-takkar
Copy link
Contributor

E2E tests are failing @hariombalhara

@hariombalhara
Copy link
Member Author

@Udit-takkar Passing now !! It was build issue from github

@zomars zomars merged commit 30060f0 into main May 26, 2025
84 of 88 checks passed
@zomars zomars deleted the 05-19-persist-access-token-dwd branch May 26, 2025 14:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

authentication area: authentication, auth, google sign in, password, SAML, password reset, can't log in automated-tests area: unit tests, e2e tests, playwright calendar-apps area: calendar, google calendar, outlook, lark, microsoft 365, apple calendar core area: core, team members only enterprise area: enterprise, audit log, organisation, SAML, SSO High priority Created by Linear-GitHub Sync ❗️ migrations contains migration files ready-for-e2e

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants