-
Notifications
You must be signed in to change notification settings - Fork 1
Add OAuth2 token management and storage implementation #78
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from 1 commit
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
29d31e9
Add OAuth2 token management and storage implementation
anatolyshipitz 25a6345
Refactor OAuth2TokenManager and remove unused types
anatolyshipitz 6e28da6
Add OAuth2Error class and integrate into token management
anatolyshipitz 2c5cc80
Enhance OAuth2TokenManager tests for token retrieval and error handling
anatolyshipitz e871c4e
Refactor OAuth2TokenManager and enhance error handling
anatolyshipitz d4d0f2e
Merge branch 'main' into feature/65031_oauth_service
anatolyshipitz 60c0b1c
Enhance OAuth2TokenManager with improved error handling and constants
anatolyshipitz 74ac3c3
Enhance OAuth2TokenManager with token validation and error handling i…
anatolyshipitz e356bd6
Enhance OAuth2TokenManager with additional token validation checks
anatolyshipitz 449abb4
Refactor OAuth2 token management interfaces and consolidate types
anatolyshipitz 7092850
Refactor OAuth2 token loading to support asynchronous operations
anatolyshipitz cf78db5
Enhance OAuth2Error class with error code functionality
anatolyshipitz a939883
Enhance setTokenDataForTesting method in OAuth2TokenManager
anatolyshipitz 6379c43
Add unit tests for FileTokenStorage and OAuth2TokenRefreshProvider
anatolyshipitz 8881bea
Add unit tests for OAuth2TokenManager and OAuth2TokenRefreshProvider
anatolyshipitz f6845a9
Add edge case unit tests for OAuth2TokenManager
anatolyshipitz 3abdcc5
Add unit tests for token refresh handling in OAuth2TokenManager
anatolyshipitz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| import { promises as fs } from 'fs'; | ||
| import { readFileSync } from 'fs'; | ||
| import { join } from 'path'; | ||
|
|
||
| import { TokenStorageProvider } from './IOAuth2TokenManager'; | ||
| import { TokenData } from './types'; | ||
|
|
||
| export class FileTokenStorage implements TokenStorageProvider { | ||
| private readonly tokenFilePath: string; | ||
| private readonly serviceName: string; | ||
|
|
||
| constructor(serviceName: string = 'qbo', tokenFilePath?: string) { | ||
| this.serviceName = serviceName; | ||
| this.tokenFilePath = | ||
| tokenFilePath || | ||
| join(process.cwd(), 'data', 'oauth2_tokens', `${serviceName}.json`); | ||
| } | ||
|
|
||
| async save(tokenData: TokenData): Promise<void> { | ||
| try { | ||
| const dir = join(this.tokenFilePath, '..'); | ||
|
|
||
| await fs.mkdir(dir, { recursive: true }); | ||
| await fs.writeFile( | ||
| this.tokenFilePath, | ||
| JSON.stringify(tokenData, null, 2), | ||
| ); | ||
| } catch { | ||
| throw new Error('Failed to save token data to file'); | ||
| } | ||
| } | ||
|
|
||
| load(): TokenData | null { | ||
| try { | ||
| const data = readFileSync(this.tokenFilePath, 'utf8'); | ||
| const tokenData = JSON.parse(data) as TokenData; | ||
|
|
||
| if (!this.isValidTokenData(tokenData)) { | ||
| return null; | ||
| } | ||
|
|
||
| return tokenData; | ||
| } catch (error) { | ||
| if ((error as NodeJS.ErrnoException).code === 'ENOENT') { | ||
| return null; | ||
| } | ||
|
|
||
| return null; | ||
| } | ||
| } | ||
|
|
||
| async clear(): Promise<void> { | ||
| try { | ||
| await fs.unlink(this.tokenFilePath); | ||
| } catch (error) { | ||
| if ((error as NodeJS.ErrnoException).code !== 'ENOENT') { | ||
| throw new Error('Failed to clear token data from file'); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private isValidTokenData(data: unknown): data is TokenData { | ||
| return ( | ||
| typeof data === 'object' && | ||
| data !== null && | ||
| typeof (data as TokenData).access_token === 'string' && | ||
| typeof (data as TokenData).refresh_token === 'string' && | ||
| typeof (data as TokenData).expires_at === 'number' && | ||
| typeof (data as TokenData).token_type === 'string' | ||
| ); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| import { TokenData } from './types'; | ||
|
|
||
| /** | ||
| * Interface for token storage providers | ||
| * Handles saving and loading token data to/from persistent storage | ||
| */ | ||
| export interface TokenStorageProvider { | ||
| /** | ||
| * Save token data to storage | ||
| * @param tokenData - The token data to save | ||
| */ | ||
| save(tokenData: TokenData): Promise<void>; | ||
|
|
||
| /** | ||
| * Load token data from storage | ||
| * @returns TokenData if available, null otherwise | ||
| */ | ||
| load(): TokenData | null; | ||
|
|
||
| /** | ||
| * Clear stored token data | ||
| */ | ||
| clear(): Promise<void>; | ||
| } | ||
|
|
||
| /** | ||
| * Interface for token refresh providers | ||
| * Handles refreshing access tokens using refresh tokens | ||
| */ | ||
| export interface TokenRefreshProvider { | ||
|
anatolyshipitz marked this conversation as resolved.
Outdated
|
||
| /** | ||
| * Refresh access token using refresh token | ||
| * @param refreshToken - The refresh token to use | ||
| * @returns Promise resolving to new TokenData | ||
| */ | ||
| refreshToken(refreshToken: string): Promise<TokenData>; | ||
| } | ||
|
|
||
| /** | ||
| * Interface for OAuth2 token manager | ||
| * Main interface for token management operations | ||
| */ | ||
| export interface IOAuth2TokenManager { | ||
| /** | ||
| * Get a valid access token, refreshing if necessary | ||
| * @returns Promise resolving to access token string | ||
| */ | ||
| getAccessToken(): Promise<string>; | ||
|
|
||
| /** | ||
| * Get the current refresh token | ||
| * @returns refresh token string | ||
| */ | ||
| getCurrentRefreshToken(): string; | ||
|
|
||
| /** | ||
| * Check if current token is valid | ||
| * @returns boolean indicating if token is valid | ||
| */ | ||
| isTokenValid(): boolean; | ||
| } | ||
108 changes: 108 additions & 0 deletions
108
workers/main/src/services/OAuth2/OAuth2TokenManager.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; | ||
|
|
||
| import { OAuth2TokenManager } from './OAuth2TokenManager'; | ||
| import { TokenData } from './types'; | ||
|
|
||
| vi.mock('./FileTokenStorage', () => ({ | ||
| FileTokenStorage: vi.fn().mockImplementation(() => ({ | ||
| save: vi.fn().mockResolvedValue(undefined), | ||
| load: vi.fn().mockReturnValue(null), | ||
| clear: vi.fn().mockResolvedValue(undefined), | ||
| })), | ||
| })); | ||
|
|
||
| vi.mock('./OAuth2TokenRefreshProvider', () => ({ | ||
| OAuth2TokenRefreshProvider: vi.fn().mockImplementation(() => ({ | ||
| refreshToken: vi.fn().mockResolvedValue({ | ||
| access_token: 'new-access-token', | ||
| refresh_token: 'new-refresh-token', | ||
| expires_at: Date.now() + 3600000, | ||
| token_type: 'Bearer', | ||
| }), | ||
| })), | ||
| })); | ||
|
|
||
| vi.mock('../../configs/qbo', () => ({ | ||
| qboConfig: { | ||
| clientId: 'test-client-id', | ||
| clientSecret: 'test-client-secret', | ||
| refreshToken: 'test-refresh-token', | ||
| tokenUrl: 'https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer', | ||
| }, | ||
| })); | ||
|
|
||
| describe('OAuth2TokenManager', () => { | ||
| let tokenManager: OAuth2TokenManager; | ||
|
|
||
| beforeEach(() => { | ||
| tokenManager = new OAuth2TokenManager('qbo', 'test-refresh-token'); | ||
| vi.clearAllMocks(); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| vi.resetAllMocks(); | ||
| }); | ||
|
|
||
| describe('constructor', () => { | ||
| it('should create OAuth2TokenManager instance', () => { | ||
| expect(tokenManager).toBeInstanceOf(OAuth2TokenManager); | ||
| }); | ||
|
|
||
| it('should create OAuth2TokenManager with custom service name', () => { | ||
| const customTokenManager = new OAuth2TokenManager( | ||
| 'custom-service', | ||
| 'custom-refresh-token', | ||
| ); | ||
|
|
||
| expect(customTokenManager).toBeInstanceOf(OAuth2TokenManager); | ||
| }); | ||
| }); | ||
|
|
||
| describe('isTokenValid', () => { | ||
| it('should return false when no token is set', () => { | ||
| expect(tokenManager.isTokenValid()).toBe(false); | ||
| }); | ||
|
|
||
| it('should return false when token is expired', () => { | ||
| const expiredTokenData: TokenData = { | ||
| access_token: 'expired-token', | ||
| refresh_token: 'refresh-token', | ||
| expires_at: Date.now() - 3600000, | ||
| token_type: 'Bearer', | ||
| }; | ||
|
|
||
| const setTokenData = ( | ||
| tokenManager as unknown as { setTokenData: (data: TokenData) => void } | ||
| ).setTokenData.bind(tokenManager); | ||
|
|
||
| setTokenData(expiredTokenData); | ||
|
anatolyshipitz marked this conversation as resolved.
Outdated
|
||
|
|
||
| expect(tokenManager.isTokenValid()).toBe(false); | ||
| }); | ||
|
|
||
| it('should return true when token is valid', () => { | ||
| const validTokenData: TokenData = { | ||
| access_token: 'valid-token', | ||
| refresh_token: 'refresh-token', | ||
| expires_at: Date.now() + 3600000, | ||
| token_type: 'Bearer', | ||
| }; | ||
|
|
||
| const setTokenData = ( | ||
| tokenManager as unknown as { setTokenData: (data: TokenData) => void } | ||
| ).setTokenData.bind(tokenManager); | ||
|
|
||
| setTokenData(validTokenData); | ||
|
|
||
| expect(tokenManager.isTokenValid()).toBe(true); | ||
| }); | ||
| }); | ||
|
|
||
| describe('getCurrentRefreshToken', () => { | ||
| it('should return refresh token from config when no cached token', async () => { | ||
| const refreshToken = tokenManager.getCurrentRefreshToken(); | ||
|
|
||
| expect(refreshToken).toBe('test-refresh-token'); | ||
| }); | ||
| }); | ||
| }); | ||
|
anatolyshipitz marked this conversation as resolved.
Outdated
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.