Skip to content

refactor: oauth service - #6387

Merged
atzoum merged 2 commits into
masterfrom
chore.oauthCb
Oct 7, 2025
Merged

atzoum merged 2 commits into
masterfrom
chore.oauthCb

Conversation

@atzoum

@atzoum atzoum commented Sep 29, 2025 •

Copy link
Copy Markdown
Contributor

Description

Refactoring the oauth service with main focus on v2.OAuthHandler (formerly v2.Authorizer) and ultimate goal to introduce circuit breakers in the near future during token retrieval.

Improvements

  • Method signature cleanup:
    • Simplified and specialized method arguments.
    • Methods now return either a value or an error (instead of multiple values).
    • Sentinel error introduced for detecting invalid grant errors.
  • Removed redundancy: Eliminated extra token expiration check and refresh in BingAds, since OAuthHandler already ensures token validity.
  • Type safety: Narrowed-down cache for better correctness.
  • Renaming for clarity & consistency:
    • Authorizer → OAuthHandler
    • DefinitionName/DestDefName/DestName → DestType
    • AccountSecret → OAuthToken
    • RefreshTokenParams → OAuthTokenParams (also cleaned up some fields)
    • RefreshTokenBodyParams → OAuthTokenRequestBody
    • AuthStatusToggleParams → StatusRequestParams (also cleaned up some fields)
  • Structural improvement: IsOAuthDestination should not be a DestinationInfo method.

Fixes

  • Refreshing a cached token through control plane during FetchToken previously sent the old secret as null, preventing refresh.
  • AuthStatusToggle always returned an error.
  • During preRoundTrip, if FetchToken returned an invalid grant error, the following AuthStatusToggle call used an invalid status (AUTH_STATUS_INACTIVE instead of inactive).
  • If the in-memory cache was empty, requests to the control-plane didn’t hint to refresh the resident token before returning it when expired.
  • Concurrent modification issue with inflight status requests map in AuthStatusToggle (now using a dedicated mutex).
  • Regulation worker wasn’t retrying OAuth errors because the way that the error message was injected into the JSON payload, was making it invalid. Test scenarios also missed this due to incorrect verification logic.

Linear Ticket

resolves PIPE-2445

Security

  • The code changed/added as part of this pull request won't create any security issues with how the software is being used.

@atzoum
atzoum marked this pull request as draft September 29, 2025 09:12
@atzoum atzoum changed the title refactor: oauth module [WIP] refactor: oauth module Sep 29, 2025
@atzoum
atzoum force-pushed the chore.oauthCb branch 7 times, most recently from 68dac63 to 36ba978 Compare September 29, 2025 13:20
@codecov

codecov Bot commented Sep 29, 2025 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.86792% with 59 lines in your changes missing coverage. Please review.
✅ Project coverage is 77.63%. Comparing base (27d3de3) to head (1db1b86).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
services/oauth/v2/oauth_handler.go 92.51% 21 Missing and 4 partials ⚠️
services/oauth/v2/http/transport.go 66.12% 19 Missing and 2 partials ⚠️
services/oauth/v2/oauth_destination.go 88.57% 3 Missing and 1 partial ⚠️
services/oauth/v2/types.go 72.72% 2 Missing and 1 partial ⚠️
services/oauth/v2/controlplane/cp_connector.go 83.33% 1 Missing and 1 partial ⚠️
...yncdestinationmanager/bing-ads/audience/manager.go 66.66% 1 Missing ⚠️
...r/asyncdestinationmanager/bing-ads/common/token.go 85.71% 0 Missing and 1 partial ⚠️
...ionmanager/bing-ads/offline-conversions/manager.go 66.66% 1 Missing ⚠️
services/oauth/v2/utils.go 75.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #6387      +/-   ##
==========================================
- Coverage   77.73%   77.63%   -0.11%     
==========================================
  Files         524      528       +4     
  Lines       70401    70366      -35     
==========================================
- Hits        54727    54629      -98     
- Misses      12857    12899      +42     
- Partials     2817     2838      +21     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@atzoum
atzoum force-pushed the chore.oauthCb branch 10 times, most recently from bfff6f7 to 1686433 Compare September 30, 2025 19:35
pkgLogger.Debugn("Actual response received", logger.NewStringField("response", string(respBodyBytes)))
// Update the same error response to all as the response received would be []JobRespSchema
respBodyBytes, err = sjson.SetRawBytes(respBodyBytes, "#.error", []byte(transportResponse.InterceptorResponse.Response))
respBodyBytes, err = sjson.SetBytes(respBodyBytes, "#.error", []byte(transportResponse.InterceptorResponse.Response))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Note: this is the bug that was corrupting the json response causing retries to never happen

Comment on lines -69 to -71
if currentOauthRetryAttempt > m.MaxOAuthRefreshRetryAttempts {
return job.Status
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Note: another bug, if we return at this point job status will be pending...

Comment on lines -65 to -82
if err = jsonrs.Unmarshal(authResponse.Account.Secret, &secret); err != nil {
return nil, fmt.Errorf("error in unmarshalling secret: %w", err)
}
currentTime := ts.CurrentTime()
expirationTime, err := time.Parse(misc.RFC3339Milli, secret.ExpirationDate)
if err != nil {
return nil, fmt.Errorf("error in parsing expirationDate: %w", err)
}
if currentTime.Before(expirationTime) {
return &secret, nil
}
refreshTokenParams.Secret = authResponse.Account.Secret
statusCode, authResponse, err = ts.OauthClientV2.RefreshToken(&refreshTokenParams)
// TODO: check if the error is not nil working verify during unit test
if err != nil {
return nil, fmt.Errorf("error in refreshing access token with this error: %w. StatusCode: %d", err, statusCode)
}
if err = jsonrs.Unmarshal(authResponse.Account.Secret, &secret); err != nil {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Note: no need to check and refresh here since OAuthHandler is supposed to be doing this already


var err error

rt.isOAuthDestination, err = destinationInfo.IsOAuthDestination(common.RudderFlowDelivery)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Note: having IsOAuthDestination a method of DestinationInfo is a bad design choice. One needs to know the internals of the method to figure out which DestinationInfo fields to populate for using the method. This is error-prone. Instead, having a clear function with all required parameters listed is much cleaner.

Augmenter oauthexts.Augmenter
Locker *sync.PartitionRWLocker
OAuthHandler *oauth.OAuthHandler
OAuthHandler oauth.OAuthHandler

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Note: OAuthHandler is now an interface

Comment on lines -195 to -205
_, authResponse, refErr := t.oauthHandler.RefreshToken(rts.refreshTokenParams)
if refErr != nil {
interceptorResp.Response = refErr.Error()
}
// refresh token success(retry)
// refresh token failed
// It can be failed due to the following reasons
// 1. invalid grant(abort)
// 2. control plan api call failed(retry)
// 3. some error happened while returning from RefreshToken function(retry)
if authResponse != nil && authResponse.Err == common.RefTokenInvalidGrant {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Note: this illustrates how returning too many values from a method can make the code more complex when used

@atzoum atzoum changed the title [WIP] refactor: oauth module refactor: oauth module Oct 1, 2025
@atzoum atzoum changed the title refactor: oauth module refactor: oauth service Oct 1, 2025
@atzoum
atzoum marked this pull request as ready for review October 1, 2025 10:37
@koladilip

Copy link
Copy Markdown
Contributor

@atzoum changes are looking fine but they are many changes so we need to test them carefully right so do you need help on that?

@atzoum

atzoum commented Oct 2, 2025

Copy link
Copy Markdown
Contributor Author

@atzoum changes are looking fine but they are many changes so we need to test them carefully right so do you need help on that?

Although I feel confident about these changes, it is true that we need to test the actual integrations. I suppose we don't have any automated integration tests for oauth? If so, yes I would need much help, but ideally we should be automating any tests we are performing.

@atzoum

atzoum commented Oct 3, 2025

Copy link
Copy Markdown
Contributor Author

@koladilip

  • As part of this pull request I will work on introducing actual integration tests for the oauth service, i.e. add tests in rudder-server calling the actual oauth endpoints (config-be/rudder-auth).
  • @pChondros can run the e2e tests for GARL
  • Could you please help with distributing work for any other manual testing that is needed (and potentially come up with a plan for automating these soon)?

@atzoum
atzoum merged commit caba16d into master Oct 7, 2025
@atzoum
atzoum deleted the chore.oauthCb branch October 7, 2025 05:14
This was referenced Oct 13, 2025
satishrudderstack pushed a commit that referenced this pull request Oct 14, 2025
🤖 I have created a release *beep* *boop*
---


##
[1.61.0-rc.1](v1.59.0...v1.61.0-rc.1)
(2025-10-13)


### Features

* **processor:** configurable delay option for event processing
([#6376](#6376))
([8321864](8321864))
* **processor:** configurable delay option for event processing
([#6376](#6376))
([14a14b5](14a14b5))
* **router:** jobsdb pickup query batch size adapting to throttling
limit ([#6338](#6338))
([c38b971](c38b971))


### Bug Fixes

* add outgoing metrics to proxy flow
([#6355](#6355))
([23a5c81](23a5c81))
* aws session config region
([#6354](#6354))
([23a5c81](23a5c81))
* dedup gauge
([#6359](#6359))
([a562df4](a562df4))
* improve HTML error extractration and truncation limits
([#6421](#6421))
([9611096](9611096))
* keydb consistent hashing
([#6403](#6403))
([f4a05ca](f4a05ca))
* keydb consistent hashing
([#6403](#6403))
([472e529](472e529))
* keydb grpc config
([#6370](#6370))
([cf04743](cf04743))
* missing keydb client stats
([#6360](#6360))
([c42e5c8](c42e5c8))
* naming collision in redis throttling configuration
([#6365](#6365))
([4f87afb](4f87afb))
* reporting event name trimming configuration
([#6417](#6417))
([f4a05ca](f4a05ca))
* save webhook failures
([#6409](#6409))
([27d3de3](27d3de3))
* set table type to external for glue
([#6386](#6386))
([9017582](9017582))
* ut mirroring tests
([#6341](#6341))
([51dd4f7](51dd4f7))
* **warehouse:** alter namespace col size
([#6379](#6379))
([fbba498](fbba498))
* **warehouse:** int to float datatype handling
([#6416](#6416))
([f4a05ca](f4a05ca))
* **warehouse:** skip extract async job failing test
([#6378](#6378))
([89a4d1e](89a4d1e))
* **warehouse:** skip users table for duplicates check in staging file
([#6422](#6422))
([8315e4e](8315e4e))


### Miscellaneous

* add authentication to reporting client
([#6384](#6384))
([502d2b0](502d2b0))
* add explicit permissions for workflows
([#6381](#6381))
([1d22623](1d22623))
* add readme for async destinaiton module
([#6356](#6356))
([cc80333](cc80333))
* apply security best practices
([#6428](#6428))
([49b1288](49b1288))
* change config key for pickupQueryThrottlingEnabled
([#6427](#6427))
([b82ec25](b82ec25))
* cleanup enableOptimizedConnectionDetailsKey flag from processor
([#6383](#6383))
([770c3fe](770c3fe))
* cleanup unused reporting client code after migrating to commonclient
([#6385](#6385))
([2dd4c49](2dd4c49))
* configurable event name trimming for reporting
([#6394](#6394))
([e757fa8](e757fa8))
* oauth service
([#6387](#6387))
([caba16d](caba16d))
* release 1.60.0
([#6390](#6390))
([c461070](c461070))
* remove deprecated throttling configuration keys
([#6377](#6377))
([8d667b7](8d667b7))
* skip building images for debendabot
([#6425](#6425))
([3cbc422](3cbc422))
* upgrade build-scan-push-action to v1.8.0
([#6350](#6350))
([51dd4f7](51dd4f7))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).
satishrudderstack added a commit that referenced this pull request Oct 15, 2025
##
[1.61.0](v1.59.0...v1.61.0)
(2025-10-15)


### Features

* **processor:** configurable delay option for event processing
([#6376](#6376))
([8321864](8321864))


### Bug Fixes

* improve HTML error extractration and truncation limits
([#6421](#6421))
([9611096](9611096))
* save webhook failures
([#6409](#6409))
([27d3de3](27d3de3))
* **warehouse:** skip users table for duplicates check in staging file
([#6422](#6422))
([8315e4e](8315e4e))


### Miscellaneous

* apply security best practices
([#6428](#6428))
([49b1288](49b1288))
* change config key for pickupQueryThrottlingEnabled
([#6427](#6427))
([b82ec25](b82ec25))
* change release to 1.61.0
([#6437](#6437))
([20f7879](20f7879))
* cleanup enableOptimizedConnectionDetailsKey flag from processor
([#6383](#6383))
([770c3fe](770c3fe))
* cleanup unused reporting client code after migrating to commonclient
([#6385](#6385))
([2dd4c49](2dd4c49))
* oauth service
([#6387](#6387))
([caba16d](caba16d))
* release 1.60.0
([#6390](#6390))
([c461070](c461070))
* skip building images for debendabot
([#6425](#6425))
([3cbc422](3cbc422))

---------

Co-authored-by: Satish Kumar <[email protected]>
satishrudderstack pushed a commit that referenced this pull request Oct 15, 2025
🤖 I have created a release *beep* *boop*
---


##
[1.61.0](v1.59.0...v1.61.0)
(2025-10-15)


### Features

* **processor:** configurable delay option for event processing
([#6376](#6376))
([14a14b5](14a14b5))
* **router:** jobsdb pickup query batch size adapting to throttling
limit ([#6338](#6338))
([c38b971](c38b971))


### Bug Fixes

* add outgoing metrics to proxy flow
([#6355](#6355))
([23a5c81](23a5c81))
* aws session config region
([#6354](#6354))
([23a5c81](23a5c81))
* dedup gauge
([#6359](#6359))
([a562df4](a562df4))
* improve HTML error extractration and truncation limits
([#6421](#6421))
([9611096](9611096))
* keydb consistent hashing
([#6403](#6403))
([f4a05ca](f4a05ca))
* keydb consistent hashing
([#6403](#6403))
([8321864](8321864))
* keydb consistent hashing
([#6403](#6403))
([472e529](472e529))
* keydb grpc config
([#6370](#6370))
([cf04743](cf04743))
* missing keydb client stats
([#6360](#6360))
([c42e5c8](c42e5c8))
* naming collision in redis throttling configuration
([#6365](#6365))
([4f87afb](4f87afb))
* reporting event name trimming configuration
([#6417](#6417))
([f4a05ca](f4a05ca))
* save webhook failures
([#6409](#6409))
([27d3de3](27d3de3))
* set table type to external for glue
([#6386](#6386))
([9017582](9017582))
* ut mirroring tests
([#6341](#6341))
([51dd4f7](51dd4f7))
* **warehouse:** alter namespace col size
([#6379](#6379))
([fbba498](fbba498))
* **warehouse:** int to float datatype handling
([#6416](#6416))
([f4a05ca](f4a05ca))
* **warehouse:** skip extract async job failing test
([#6378](#6378))
([89a4d1e](89a4d1e))
* **warehouse:** skip users table for duplicates check in staging file
([#6422](#6422))
([8315e4e](8315e4e))


### Miscellaneous

* add authentication to reporting client
([#6384](#6384))
([502d2b0](502d2b0))
* add explicit permissions for workflows
([#6381](#6381))
([1d22623](1d22623))
* add readme for async destinaiton module
([#6356](#6356))
([cc80333](cc80333))
* apply security best practices
([#6428](#6428))
([49b1288](49b1288))
* change config key for pickupQueryThrottlingEnabled
([#6427](#6427))
([b82ec25](b82ec25))
* change release to 1.61.0
([#6437](#6437))
([b89d17a](b89d17a))
* cleanup enableOptimizedConnectionDetailsKey flag from processor
([#6383](#6383))
([770c3fe](770c3fe))
* cleanup unused reporting client code after migrating to commonclient
([#6385](#6385))
([2dd4c49](2dd4c49))
* configurable event name trimming for reporting
([#6394](#6394))
([e757fa8](e757fa8))
* oauth service
([#6387](#6387))
([caba16d](caba16d))
* release 1.60.0
([#6390](#6390))
([c461070](c461070))
* remove deprecated throttling configuration keys
([#6377](#6377))
([8d667b7](8d667b7))
* skip building images for debendabot
([#6425](#6425))
([3cbc422](3cbc422))
* upgrade build-scan-push-action to v1.8.0
([#6350](#6350))
([51dd4f7](51dd4f7))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants