Skip to content

chore: refactor webhook pkg to make it reusable in other repos - #5594

Merged
mihir20 merged 38 commits into
masterfrom
mihir/seperate-out-webhook-auth
May 15, 2025
Merged

mihir20 merged 38 commits into
masterfrom
mihir/seperate-out-webhook-auth

Conversation

@mihir20

@mihir20 mihir20 commented Mar 12, 2025 •

Copy link
Copy Markdown
Contributor

Description

  • Move webhook authentication logic to new auth package (webhook/auth/auth.go)
  • Refactor AuthRequestContext type and move types to gateway/types package
  • Update stat reporting interface to use StatReporter instead of concrete SourceStat
  • fetch transformer features before starting gateway server
  • improved error handling
  • Update mock implementations to align with new interface changes
  • Consolidate webhook handling code and improve type safety
  • Add new source details structure to AuthRequestContext for better data encapsulation

Linear Ticket

https://linear.app/rudderstack/issue/PIPE-1940/common-webhook-for-ingestion-service-and-gateway

Security

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

@mihir20
mihir20 force-pushed the mihir/seperate-out-webhook-auth branch 2 times, most recently from 706c033 to 633cb99 Compare March 13, 2025 13:39
@mihir20
mihir20 force-pushed the mihir/seperate-out-webhook-auth branch from 9e407f9 to 6703653 Compare April 7, 2025 06:37
Comment thread gateway/webhook/webhook.go Resolved
Comment thread gateway/webhook/setup.go Resolved
@mihir20
mihir20 force-pushed the mihir/seperate-out-webhook-auth branch from 684b880 to 56dedcf Compare April 10, 2025 09:46
@codecov

codecov Bot commented Apr 10, 2025 •

Copy link
Copy Markdown

Codecov Report

Attention: Patch coverage is 76.19048% with 55 lines in your changes missing coverage. Please review.

Project coverage is 76.92%. Comparing base (c7e3b37) to head (c884481).
Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
gateway/webhook/webhook.go 52.70% 31 Missing and 4 partials ⚠️
gateway/handle_lifecycle.go 64.86% 11 Missing and 2 partials ⚠️
gateway/handle_webhook.go 25.00% 2 Missing and 1 partial ⚠️
gateway/webhook/auth/auth.go 91.66% 1 Missing and 2 partials ⚠️
testhelper/health/checker.go 91.66% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #5594      +/-   ##
==========================================
- Coverage   76.97%   76.92%   -0.05%     
==========================================
  Files         496      497       +1     
  Lines       67796    67952     +156     
==========================================
+ Hits        52183    52275      +92     
- Misses      12786    12836      +50     
- Partials     2827     2841      +14     

☔ 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.

@mihir20
mihir20 force-pushed the mihir/seperate-out-webhook-auth branch 4 times, most recently from 73973f9 to 5f24fd8 Compare April 15, 2025 19:35
@mihir20
mihir20 requested review from fracasula, ktgowtham and vinayteki95 and removed request for fracasula April 25, 2025 06:54
Comment thread gateway/response/response.go Resolved
Comment thread gateway/handle_observability.go Resolved
Comment thread gateway/webhook/setup.go Outdated

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Since I suggested to rename WebhookHandler to WebhookRequestHandler, and given that in here I see RequestHandler, now I wonder what is the actual difference from this interface (i.e. WebHookI - terrible name btw, it needs some love from you @mihir20 :D) and the above one WebhookHandler.

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.

this interface in not in use we can remove this, But I got your point will do some refactoring around this and above comment 👍

Comment thread gateway/webhook/webhook.go Resolved
Comment thread gateway/webhook/setup.go Resolved
Comment thread gateway/webhook/auth/auth.go Resolved
@mihir20
mihir20 marked this pull request as ready for review May 6, 2025 09:02
Comment thread gateway/webhook/webhook.go Resolved
Comment thread gateway/webhook/auth/auth.go Resolved
Comment thread gateway/handle_lifecycle.go Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Not relate to this PR, but aren't we creating some sort of circular dependencies?
gw is dependent on webhook. and webhook has a reference to gw handle.

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.

yes, webhook is not dependent directly on gw it depends on an interface and implementation of this interface currently do not depend on webhook but in future it can depend on webhook which may create cyclic dependency.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Circular Dependencies

  • The webhook package depends on the gateway package (gwtypes), and the gateway package depends on the webhook package, creating a circular dependency.
  • Specifically, the circular dependency occurs in the following places:
    • The webhook package depends on the gateway package:
      • In gateway/webhook/setup.go, the webhook package imports gwtypes from the gateway package and uses it in interface definitions and method signatures.
      • In gateway/webhook/model/model.go, the FailedWebhookPayload struct uses *gwtypes.AuthRequestContext from the gateway package.
      • In gateway/webhook/webhook.go, the webhook package imports and uses gwtypes for authentication and request handling.
    • The gateway package depends on the webhook package:
      • In gateway/handle.go, the gateway package has a field of type webhook.WebhookRequestHandler.
      • In gateway/handle_webhook.go, the gateway implements the WebhookRequestProcessor interface defined in the webhook package.
      • In gateway/mocks/mockwebhook.go, the gateway package has mock implementations for webhook interfaces.

[optional] Not required as part of this effort, but I'm starting to think that we could move the shared types to a common package that both gateway and webhook can depend on.

Also for the gw depending on webhook, I think we could solve it by using Dependency Injection and pass a ready to be used webhook handler to the gw.

@mihir20 if you feel like this wouldn't be too complex and want to take a stab at it, I won't complain 😅

@mihir20
mihir20 requested review from fracasula and ktgowtham May 8, 2025 09:20
mihir20 added 4 commits May 8, 2025 19:08
…kage

- Move webhook authentication logic to new auth package (webhook/auth/auth.go)
- Refactor AuthRequestContext type and move types to gateway/types package
- Update stat reporting interface to use StatReporter instead of concrete SourceStat
- Modify Dockerfiles to use Go 1.24.1
- Update mock implementations to align with new interface changes
- Consolidate webhook handling code and improve type safety
- Add new source details structure to AuthRequestContext for better data encapsulation

This reorganization improves code maintainability and separation of concerns while maintaining existing functionality.

Signed-off-by: mihir <[email protected]>
Introduce new webhook v2 handler behind Gateway.webhookV2HandlerEnabled flag. Includes:
- Config parameter to enable/disable v2 handler
- Dedicated auth middleware for v2 with enhanced error handling
- Updated request enqueuing logic with size-based routing
- Middleware now passes request context to failure handler

This maintains backward compatibility by defaulting to v1 unless enabled.

Signed-off-by: mihir <[email protected]>
Replace request size-based enqueue condition with webhookV2HandlerEnabled flag check to control routing logic. This allows gradual rollout of the updated webhook handler implementation through configuration.

Signed-off-by: mihir <[email protected]>
Separate the TrackRequestMetrics method into a dedicated RequestMetricsTracker interface that Gateway embeds. This improves interface segregation and allows OSS customers to implement per-request webhook metrics tracking independently while maintaining existing Gateway functionality.

Signed-off-by: mihir <[email protected]>
@mihir20
mihir20 force-pushed the mihir/seperate-out-webhook-auth branch from 0335da2 to f8b3c9d Compare May 8, 2025 13:39
@mihir20 mihir20 changed the title chore: refactor webhook authentication logic into a separate package. chore: refactor webhook pkg to make it reusable in other repos May 9, 2025

@fracasula fracasula left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Approving with a few comments, some are minor some are optional. Please address the minor ones before merging.

Comment thread gateway/types/types.go
return misc.GetTagName(arctx.WriteKey, arctx.SourceName)
}

type StatReporter interface {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

What is the reason for exporting/exposing this type vs using internal/stats/SourceStat directly?

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.

We want to use this from ingestion svc as well, so we had to expose this here.

Comment thread gateway/webhook/auth/auth_test.go Outdated
defer resp.Body.Close()

// Validate response
if resp.StatusCode != tt.expectedResponseCode {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Why the if then t.Errorf with a custom string? Can't we just do require.Equal? Same in the rest of this test.

Comment thread gateway/webhook/webhook.go Outdated
ss.Report(webhook.stats)
}

func getWebhookFailureReason(err string, statusCode int) string {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Can you rename the variable to errMessage? Because idiomatically speaking when someone sees an err variable in Go they know it's going to be an error but this isn't the case so for clarity we could simply rename it.

case statusCode != 0:
return response.SourceTransformerNonSuccessResponse
case err != "":
return response.SourceTransformerResponseError

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[optional] Not needed at all of course, but I never got the chance to comment about fallthrough so... here we are 😂

case err != "":
    fallthrough
default:
    return response.SourceTransformerResponseError

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.

TIL: didn't knew about fallthrough

Comment thread gateway/webhook/webhook.go Outdated
failureReason = response.SourceTransformerNonSuccessResponse
}
failedWebhookPayloads = append(failedWebhookPayloads, &model.FailedWebhookPayload{RequestContext: webRequest.authContext, Payload: payloadArr[idx], SourceType: breq.sourceType, Reason: failureReason})
bt.webhook.logger.Errorf("webhook %s source transformation failed with error: %s and status code: %s", breq.sourceType, resp.Err, resp.StatusCode)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

We could use the non-sugared logger here right?

Comment thread gateway/webhook/webhook.go Outdated
if lastRecvCount != webhook.recvCount.Load() || lastAckCount != webhook.ackCount.Load() {
lastRecvCount = webhook.recvCount.Load()
lastAckCount = webhook.ackCount.Load()
webhook.logger.Debug("WebhookRequestHandler Recv/Ack ", webhook.recvCount.Load(), webhook.ackCount.Load())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Again, non-sugared logger can be used here.

Comment thread gateway/webhook/webhookTransformer.go Resolved
Comment thread gateway/handle_lifecycle.go Outdated

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Circular Dependencies

  • The webhook package depends on the gateway package (gwtypes), and the gateway package depends on the webhook package, creating a circular dependency.
  • Specifically, the circular dependency occurs in the following places:
    • The webhook package depends on the gateway package:
      • In gateway/webhook/setup.go, the webhook package imports gwtypes from the gateway package and uses it in interface definitions and method signatures.
      • In gateway/webhook/model/model.go, the FailedWebhookPayload struct uses *gwtypes.AuthRequestContext from the gateway package.
      • In gateway/webhook/webhook.go, the webhook package imports and uses gwtypes for authentication and request handling.
    • The gateway package depends on the webhook package:
      • In gateway/handle.go, the gateway package has a field of type webhook.WebhookRequestHandler.
      • In gateway/handle_webhook.go, the gateway implements the WebhookRequestProcessor interface defined in the webhook package.
      • In gateway/mocks/mockwebhook.go, the gateway package has mock implementations for webhook interfaces.

[optional] Not required as part of this effort, but I'm starting to think that we could move the shared types to a common package that both gateway and webhook can depend on.

Also for the gw depending on webhook, I think we could solve it by using Dependency Injection and pass a ready to be used webhook handler to the gw.

@mihir20 if you feel like this wouldn't be too complex and want to take a stab at it, I won't complain 😅

@mihir20
mihir20 merged commit 1ee57bc into master May 15, 2025
@mihir20
mihir20 deleted the mihir/seperate-out-webhook-auth branch May 15, 2025 15:26
mihir20 pushed a commit that referenced this pull request May 26, 2025
🤖 I have created a release *beep* *boop*
---


##
[1.50.0-rc.1](v1.49.0...v1.50.0-rc.1)
(2025-05-26)


### Features

* implement aws v2 implementation
([#5852](#5852))
([18fd4fb](18fd4fb))


### Bug Fixes

* do not panic for invalid router payload
([#5880](#5880))
([f4a0e7c](f4a0e7c))
* server panicking with invalid byte sequence for encoding utf8 0x00
([#5882](#5882))
([4c1a0de](4c1a0de))
* skip source_id when fetching warehouse schema from database
([#5886](#5886))
([092ee2a](092ee2a))
* warehouse pending tables to skip
([#5867](#5867))
([864fd49](864fd49))
* warehouse transformations
([#5875](#5875))
([715ccfa](715ccfa))


### Miscellaneous

* **deps:** bump the go-deps group across 1 directory with 25 updates
([#5890](#5890))
([3c4ddd8](3c4ddd8))
* **jobsdb:** migrate incomplete datasets in pairs excluding completed
ones ([#5876](#5876))
([9d8b573](9d8b573))
* **jobsdb:** remove support for jobDoneMigrateThres
([#5873](#5873))
([4745d2b](4745d2b))
* make reporting client params configurable
([#5891](#5891))
([39f7e75](39f7e75))
* move house keeping action to commit sha
([#5885](#5885))
([d379e82](d379e82))
* refactor config change dtype for config to json.RawMessage
([#5874](#5874))
([940adb0](940adb0))
* refactor webhook pkg to make it reusable in other repos
([#5594](#5594))
([1ee57bc](1ee57bc))
* remove redundant structure for account with definition
([#5872](#5872))
([89bc62b](89bc62b))
* remove support for transformer-based kafka batching
([#5870](#5870))
([60a571c](60a571c))
* revert support new consent resolution strategy values
([#5855](#5855))
([c7e3b37](c7e3b37))
* revert use account to decide oauth type of a destination
([#5861](#5861))
([6232755](6232755))
* **router:** additional observability metrics
([#5887](#5887))
([da3ba3c](da3ba3c))
* sync release v1.49.0 to main branch
([#5851](#5851))
([78cc5a9](78cc5a9))
* use jsonrs from rudder-go-kit
([#5869](#5869))
([39064af](39064af))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).
atzoum pushed a commit that referenced this pull request May 26, 2025
🤖 I have created a release *beep* *boop*
---


##
[1.50.0-rc.2](v1.49.0...v1.50.0-rc.2)
(2025-05-26)


### Features

* implement aws v2 implementation
([#5852](#5852))
([18fd4fb](18fd4fb))


### Bug Fixes

* do not panic for invalid router payload
([#5880](#5880))
([f4a0e7c](f4a0e7c))
* error gathering metrics, metric was collected before with the same
name and label values
([#5900](#5900))
([422f45b](422f45b))
* handle missing eventUpload config gracefully
([#5898](#5898))
([05a926d](05a926d))
* server panicking with invalid byte sequence for encoding utf8 0x00
([#5882](#5882))
([4c1a0de](4c1a0de))
* skip source_id when fetching warehouse schema from database
([#5886](#5886))
([092ee2a](092ee2a))
* warehouse pending tables to skip
([#5867](#5867))
([864fd49](864fd49))
* warehouse transformations
([#5875](#5875))
([715ccfa](715ccfa))


### Miscellaneous

* **deps:** bump the go-deps group across 1 directory with 25 updates
([#5890](#5890))
([3c4ddd8](3c4ddd8))
* **jobsdb:** migrate incomplete datasets in pairs excluding completed
ones ([#5876](#5876))
([9d8b573](9d8b573))
* **jobsdb:** remove support for jobDoneMigrateThres
([#5873](#5873))
([4745d2b](4745d2b))
* make reporting client params configurable
([#5891](#5891))
([39f7e75](39f7e75))
* move house keeping action to commit sha
([#5885](#5885))
([d379e82](d379e82))
* refactor config change dtype for config to json.RawMessage
([#5874](#5874))
([940adb0](940adb0))
* refactor webhook pkg to make it reusable in other repos
([#5594](#5594))
([1ee57bc](1ee57bc))
* remove redundant structure for account with definition
([#5872](#5872))
([89bc62b](89bc62b))
* remove support for transformer-based kafka batching
([#5870](#5870))
([60a571c](60a571c))
* revert support new consent resolution strategy values
([#5855](#5855))
([c7e3b37](c7e3b37))
* revert use account to decide oauth type of a destination
([#5861](#5861))
([6232755](6232755))
* **router:** additional observability metrics
([#5887](#5887))
([da3ba3c](da3ba3c))
* sync release v1.49.0 to main branch
([#5851](#5851))
([78cc5a9](78cc5a9))
* use jsonrs from rudder-go-kit
([#5869](#5869))
([39064af](39064af))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).
mihir20 pushed a commit that referenced this pull request May 27, 2025
🤖 I have created a release *beep* *boop*
---


##
[1.50.0](v1.49.0...v1.50.0)
(2025-05-26)


### Features

* implement aws v2 implementation
([#5852](#5852))
([18fd4fb](18fd4fb))


### Bug Fixes

* do not panic for invalid router payload
([#5880](#5880))
([f4a0e7c](f4a0e7c))
* error gathering metrics, metric was collected before with the same
name and label values
([#5900](#5900))
([422f45b](422f45b))
* handle missing eventUpload config gracefully
([#5898](#5898))
([05a926d](05a926d))
* server panicking with invalid byte sequence for encoding utf8 0x00
([#5882](#5882))
([4c1a0de](4c1a0de))
* skip source_id when fetching warehouse schema from database
([#5886](#5886))
([092ee2a](092ee2a))
* warehouse pending tables to skip
([#5867](#5867))
([864fd49](864fd49))
* warehouse transformations
([#5875](#5875))
([715ccfa](715ccfa))


### Miscellaneous

* **deps:** bump the go-deps group across 1 directory with 25 updates
([#5890](#5890))
([3c4ddd8](3c4ddd8))
* **jobsdb:** migrate incomplete datasets in pairs excluding completed
ones ([#5876](#5876))
([9d8b573](9d8b573))
* **jobsdb:** remove support for jobDoneMigrateThres
([#5873](#5873))
([4745d2b](4745d2b))
* make reporting client params configurable
([#5891](#5891))
([39f7e75](39f7e75))
* move house keeping action to commit sha
([#5885](#5885))
([d379e82](d379e82))
* refactor config change dtype for config to json.RawMessage
([#5874](#5874))
([940adb0](940adb0))
* refactor webhook pkg to make it reusable in other repos
([#5594](#5594))
([1ee57bc](1ee57bc))
* remove redundant structure for account with definition
([#5872](#5872))
([89bc62b](89bc62b))
* remove support for transformer-based kafka batching
([#5870](#5870))
([60a571c](60a571c))
* revert support new consent resolution strategy values
([#5855](#5855))
([c7e3b37](c7e3b37))
* revert use account to decide oauth type of a destination
([#5861](#5861))
([6232755](6232755))
* **router:** additional observability metrics
([#5887](#5887))
([da3ba3c](da3ba3c))
* sync release v1.49.0 to main branch
([#5851](#5851))
([78cc5a9](78cc5a9))
* use jsonrs from rudder-go-kit
([#5869](#5869))
([39064af](39064af))

---
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