Skip to content

Conversation

zubairirfan96
Copy link
Collaborator

@zubairirfan96 zubairirfan96 commented Aug 28, 2025

Summary by CodeRabbit

  • New Features

    • Added support for configuring OAuth via “OAuth Connection ID”.
    • Introduced dual-structure token storage compatibility (old and new formats).
  • Bug Fixes

    • More reliable OAuth1/2 header generation with robust URL, query, and body handling.
    • Properly computes body hashes across content types and skips binary multipart fields.
    • Safer handling of unresolved template variables and preserves 0 expiry values.
  • Chores

    • Version bumps: Core 1.5.51, SDK 1.0.46.

samme-abdul and others added 6 commits August 25, 2025 22:20
Updated APICall, AccessTokenManager, and OAuth.helper to support both legacy and new OAuth token storage structures. Added logic to distinguish between structures, improved parameter extraction for OAuth1 signatures, and ensured correct token updates and retrievals for both formats. Also replaced usage of oauthService with oauth_con_id for more robust identification.
Removed unnecessary console.log statements from OAuth.helper.ts for cleaner output. Updated AccessTokenManager to store expiration timestamp as a string if available, improving consistency in token expiration handling.
AccessTokenManager now correctly persists rotated refresh tokens and handles expiration timestamps with nullish checks. OAuth.helper.ts avoids logging sensitive OAuth config data in plaintext and refines token data structure updates to better preserve existing fields.
Corrects the assignment of expires_in to preserve 0 and undefined values, and updates the in-memory refresh token if the provider rotates it during access token refresh.
Refactor OAuth token handling for new structure support
Copy link

coderabbitai bot commented Aug 28, 2025

Walkthrough

Introduces oauth_con_id config; reroutes OAuth token/header handling to use it. Adds dual-structure token support (old vs new) across retrieval, refresh, and storage. Refactors OAuth1/2 parameter extraction and signing. Updates AccessTokenManager constructor and save logic. Removes rootUrl from OAuth flows. Bumps core and sdk versions.

Changes

Cohort / File(s) Summary
Version bumps
packages/core/package.json, packages/sdk/package.json
Incremented versions: core 1.5.50 → 1.5.51; sdk 1.0.45 → 1.0.46.
APICall config and header handling
packages/core/src/Components/APICall/APICall.class.ts
Added config field oauth_con_id; switched OAuth header gating to oauth_con_id; removed rootUrl derivation; updated generateOAuthHeaders call signature; changed header merge to concatenate array/object; minor formatting.
AccessTokenManager dual-structure support
packages/core/src/Components/APICall/AccessTokenManager.ts
Constructor now accepts tokensData and isNewStructure; refresh logic writes structure-aware payloads to vault; updates internal state after save; preserves expires_in=0; improved error logging and rethrow.
OAuth helper: retrieval, signing, and storage
packages/core/src/Components/APICall/OAuth.helper.ts
HandleOAuthHeaders signature drops rootUrl; expanded OAuth1/2 param extraction, content-type handling, and signing; detects old/new token structures; structure-aware client-credentials acquisition and vault updates; tokenKey now from oauth_con_id; enhanced warnings/logging.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Caller as APICall.class
  participant Helper as OAuth.helper
  participant Vault as Vault Store
  participant ATM as AccessTokenManager
  participant API as Target API

  Caller->>Helper: handleOAuthHeaders(agent, config, reqConfig, logger)
  Helper->>Vault: retrieveOAuthTokens(oauth_con_id)
  Vault-->>Helper: { tokensData, keyId, isNewStructure }
  alt OAuth2 (service != oauth1)
    Helper->>ATM: new AccessTokenManager(..., tokensData, ..., isNewStructure)
    ATM->>API: POST token_url (refresh or client credentials)
    API-->>ATM: { access_token, refresh_token?, expires_in }
    ATM->>Vault: save updatedData (structure-aware)
    ATM-->>Helper: Bearer token
    Helper-->>Caller: headers{ Authorization: Bearer ... }
  else OAuth1
    Helper->>Helper: Build base URL, collect params/body hash
    Helper-->>Caller: headers{ Authorization: OAuth ... }
  end
  Caller->>API: Request with merged headers
  API-->>Caller: Response
Loading
sequenceDiagram
  autonumber
  participant Helper as OAuth.helper
  participant Vault as Vault Store
  participant CC as ClientCredentials Flow
  note over Helper: Client credentials path
  Helper->>Vault: get tokensData (new/old structure)
  alt New structure
    Helper->>CC: request token using auth_settings
    CC-->>Helper: access_token, expires_in
    Helper->>Vault: update auth_data.primary/expires_in<br/>and auth_settings
  else Old structure
    Helper->>CC: request token using oauth_info
    CC-->>Helper: access_token, expires_in
    Helper->>Vault: update primary/expires_in and oauth_info
  end
  Helper-->>Helper: Return access_token
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

I twitch my whiskers at tokens two,
Old burrow, new burrow—both will do.
I hop through headers, sign the breeze,
OAuth winds rustle JSON trees.
With version bumps and careful cheer,
I stash fresh carrots in the vault this year. 🥕✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch dev

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbit in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbit in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbit gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbit read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbit help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbit ignore or @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbit summary or @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbit or @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
packages/core/src/Components/APICall/APICall.class.ts (2)

100-100: Bug: headers transformed into an array; axios expects an object.
Using concat() yields an array of header objects, breaking axios.request. Merge as an object.

Apply:

-            reqConfig.headers = (await parseHeaders(input, config, agent)).concat({ ...headers });
+            reqConfig.headers = { ...(await parseHeaders(input, config, agent)), ...headers };

100-122: Ensure consistent headers representation

  • ForkedAgent.class.ts:39 uses agentRequest.headers = []
  • APICall.class.ts:121 uses reqConfig.headers = reqConfig.headers.concat(...)
    Unify headers as either an object map or an array of header entries and update both sites plus the related type definitions accordingly.
packages/core/src/Components/APICall/OAuth.helper.ts (2)

272-333: Standardize handleOAuthHeaders to return only OAuth header patch.
Currently OAuth1 branch returns merged headers while OAuth2 returns only Authorization; make it consistent so callers can merge once.

-                const oauthHeader = buildOAuth1Header(
+                const oauthHeader = buildOAuth1Header(
                     reqConfig.url,
                     reqConfig.method,
                     {
                         consumerKey: oAuthConfig.consumerKey,
                         consumerSecret: oAuthConfig.consumerSecret,
                         token: oauthTokens.primaryToken,
                         tokenSecret: oauthTokens.secondaryToken,
                     },
                     additionalParams
                 );
-
-                headers = { ...reqConfig.headers, ...oauthHeader };
+                headers = oauthHeader; // return only OAuth header patch
                 logger.debug('OAuth1 access token check success.');

Follow-up in APICall.class.ts already merges with existing headers via object spread.


378-380: Add timeout to token fetch.
Prevent hangs on identity endpoints.

-            const response = await axios.post(tokenURL, params.toString(), {
-                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
-            });
+            const response = await axios.post(
+                tokenURL,
+                params.toString(),
+                { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, timeout: 10000 }
+            );
🧹 Nitpick comments (1)
packages/core/src/Components/APICall/APICall.class.ts (1)

127-131: Redact sensitive headers in debug logs.
reqConfig may include Authorization; avoid logging it verbatim.

-                logger.debug('Making API call', { ...reqConfig, data: dataForDebug });
+                const { headers, ...rest } = reqConfig;
+                logger.debug('Making API call', { ...rest, headers: '[redacted]', data: dataForDebug });
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge Base: Disabled due to data retention organization setting

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 33a5a4c and 20a96dc.

⛔ Files ignored due to path filters (1)
  • packages/sdk/src/Components/generated/APICall.ts is excluded by !**/generated/**
📒 Files selected for processing (5)
  • packages/core/package.json (1 hunks)
  • packages/core/src/Components/APICall/APICall.class.ts (2 hunks)
  • packages/core/src/Components/APICall/AccessTokenManager.ts (2 hunks)
  • packages/core/src/Components/APICall/OAuth.helper.ts (8 hunks)
  • packages/sdk/package.json (1 hunks)
🔇 Additional comments (5)
packages/core/package.json (1)

3-3: LGTM: version bump only.
No issues spotted. Ensure CHANGELOG reflects 1.5.51.

packages/sdk/package.json (1)

3-3: LGTM: version bump only.
No issues spotted. Ensure release notes updated to 1.0.46.

packages/core/src/Components/APICall/AccessTokenManager.ts (2)

112-139: Token save path looks correct for dual structures.
Merge logic preserves new (auth_data) and old layouts; refresh_token rotation handled. Good.


147-156: State refresh after save is consistent.
Updates in-memory tokens and preserves 0 for expires_in. Good.

packages/core/src/Components/APICall/OAuth.helper.ts (1)

24-135: OAuth1 param extraction hardening looks solid.
Covers query, form, body hash, and multipart cases with sensible logging. Good.

Comment on lines +117 to 122
if (config?.data?.oauth_con_id !== '' && config?.data?.oauth_con_id !== 'None') {
const additionalParams = extractAdditionalParamsForOAuth1(reqConfig);
const oauthHeaders = await generateOAuthHeaders(agent, config, reqConfig, logger, additionalParams, rootUrl);
const oauthHeaders = await generateOAuthHeaders(agent, config, reqConfig, logger, additionalParams);
//reqConfig.headers = { ...reqConfig.headers, ...oauthHeaders };
reqConfig.headers = reqConfig.headers.concat({ ...oauthHeaders });
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix OAuth gating and header merge.
Undefined oauth_con_id currently passes the condition; also avoid concat on headers.

-                if (config?.data?.oauth_con_id !== '' && config?.data?.oauth_con_id !== 'None') {
+                if (typeof config?.data?.oauth_con_id === 'string' && config.data.oauth_con_id.trim() && config.data.oauth_con_id !== 'None') {
                     const additionalParams = extractAdditionalParamsForOAuth1(reqConfig);
-                    const oauthHeaders = await generateOAuthHeaders(agent, config, reqConfig, logger, additionalParams);
-                    //reqConfig.headers = { ...reqConfig.headers, ...oauthHeaders };
-                    reqConfig.headers = reqConfig.headers.concat({ ...oauthHeaders });
+                    const oauthHeaders = await generateOAuthHeaders(agent, config, reqConfig, logger, additionalParams);
+                    reqConfig.headers = { ...(reqConfig.headers || {}), ...oauthHeaders };
                 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (config?.data?.oauth_con_id !== '' && config?.data?.oauth_con_id !== 'None') {
const additionalParams = extractAdditionalParamsForOAuth1(reqConfig);
const oauthHeaders = await generateOAuthHeaders(agent, config, reqConfig, logger, additionalParams, rootUrl);
const oauthHeaders = await generateOAuthHeaders(agent, config, reqConfig, logger, additionalParams);
//reqConfig.headers = { ...reqConfig.headers, ...oauthHeaders };
reqConfig.headers = reqConfig.headers.concat({ ...oauthHeaders });
}
if (typeof config?.data?.oauth_con_id === 'string' && config.data.oauth_con_id.trim() && config.data.oauth_con_id !== 'None') {
const additionalParams = extractAdditionalParamsForOAuth1(reqConfig);
const oauthHeaders = await generateOAuthHeaders(agent, config, reqConfig, logger, additionalParams);
reqConfig.headers = { ...(reqConfig.headers || {}), ...oauthHeaders };
}
🤖 Prompt for AI Agents
In packages/core/src/Components/APICall/APICall.class.ts around lines 117-122,
the condition allows undefined oauth_con_id to pass and headers are being
concatenated as if they were an array; update the gating to check for a truthy,
non-empty, non-'None' value (e.g. config?.data?.oauth_con_id &&
config.data.oauth_con_id !== 'None') and replace the concat with an object merge
that ensures headers is an object (e.g. reqConfig.headers = {
...(reqConfig.headers || {}), ...oauthHeaders }) so OAuth headers are only added
when present and merged correctly.

Comment on lines 176 to 181
export const retrieveOAuthTokens = async (agent, config) => {
let tokenKey: any = null;
try {
tokenKey = `OAUTH_${config.componentId ?? config.id}_TOKENS`;
tokenKey = config?.data?.oauth_con_id;

try {
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Guard when oauth_con_id is missing.
Avoid vault get with undefined key.

 export const retrieveOAuthTokens = async (agent, config) => {
   let tokenKey: any = null;
   try {
-        tokenKey = config?.data?.oauth_con_id;
+        tokenKey = config?.data?.oauth_con_id;
+        if (!tokenKey || tokenKey === 'None') {
+            throw new Error('oauth_con_id is required to retrieve OAuth tokens');
+        }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const retrieveOAuthTokens = async (agent, config) => {
let tokenKey: any = null;
try {
tokenKey = `OAUTH_${config.componentId ?? config.id}_TOKENS`;
tokenKey = config?.data?.oauth_con_id;
try {
export const retrieveOAuthTokens = async (agent, config) => {
let tokenKey: any = null;
try {
tokenKey = config?.data?.oauth_con_id;
if (!tokenKey || tokenKey === 'None') {
throw new Error('oauth_con_id is required to retrieve OAuth tokens');
}
try {
// ... existing inner try block code
}
// ...
} catch (err) {
// ...
}
};
🤖 Prompt for AI Agents
In packages/core/src/Components/APICall/OAuth.helper.ts around lines 176 to 181,
the code uses config?.data?.oauth_con_id directly and passes it to the vault get
which can be undefined; add a guard so you do not call the vault with an
undefined key: read tokenKey = config?.data?.oauth_con_id and if it is
null/undefined (or empty string) then return a sensible value or throw a
descriptive error (or log and return) instead of proceeding to vault.get; ensure
subsequent code assumes tokenKey is a non-empty string (narrow the type) and add
a unit/test or comment that vault.get will only be called with a valid key.

Comment on lines +425 to +431
updatedData.oauth_info = {
oauth_keys_prefix: `OAUTH_${config?.data?.oauth_con_id?.split('_')[1]}`,
service: 'oauth2_client_credentials',
tokenURL,
clientID,
clientSecret
};
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid 'OAUTH_undefined' when deriving oauth_keys_prefix (old structure).
Compute prefix safely as done for new structure.

-                    updatedData.oauth_info = {
-                        oauth_keys_prefix: `OAUTH_${config?.data?.oauth_con_id?.split('_')[1]}`,
+                    const parts = String(config?.data?.oauth_con_id ?? '').split('_');
+                    const prefixSuffix = parts.length > 1 ? parts[1] : parts[0];
+                    updatedData.oauth_info = {
+                        oauth_keys_prefix: prefixSuffix ? `OAUTH_${prefixSuffix}` : undefined,
                         service: 'oauth2_client_credentials',
                         tokenURL,
                         clientID,
                         clientSecret
                     };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
updatedData.oauth_info = {
oauth_keys_prefix: `OAUTH_${config?.data?.oauth_con_id?.split('_')[1]}`,
service: 'oauth2_client_credentials',
tokenURL,
clientID,
clientSecret
};
// Safely derive the OAuth key prefix to avoid "OAUTH_undefined"
const parts = String(config?.data?.oauth_con_id ?? '').split('_');
const prefixSuffix = parts.length > 1 ? parts[1] : parts[0];
updatedData.oauth_info = {
oauth_keys_prefix: prefixSuffix ? `OAUTH_${prefixSuffix}` : undefined,
service: 'oauth2_client_credentials',
tokenURL,
clientID,
clientSecret
};
🤖 Prompt for AI Agents
In packages/core/src/Components/APICall/OAuth.helper.ts around lines 425 to 431,
the oauth_keys_prefix may become "OAUTH_undefined" when config.data.oauth_con_id
doesn't follow the expected old structure; compute the suffix safely and avoid
using split result directly. Extract a safeSuffix: if config?.data?.oauth_con_id
is falsy use an empty string, otherwise try splitting and use the second segment
if present, else fall back to the whole oauth_con_id (or empty string), then set
oauth_keys_prefix to `OAUTH_${safeSuffix}` so "undefined" is never inserted.

@alaa-eddine-k alaa-eddine-k merged commit e56cb0c into main Aug 28, 2025
1 check passed
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.

3 participants