Skip to content
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

chore: Fix datasource creation throwing 400 #34588

Merged
merged 5 commits into from
Jun 29, 2024

Conversation

sharat87
Copy link
Member

@sharat87 sharat87 commented Jun 28, 2024

The recent changes to deny any requests that have unrecognized fields in the body, is making the datasource creation API fail. This is because we are sending extra fields that shouldn't be sent.

Slack conversation.

/test sanity datasource

Warning

Workflow run: https://github.com/appsmithorg/appsmith/actions/runs/9714799545
Commit: 85495fb
Cypress dashboard.
Tags: @tag.Sanity, @tag.Datasource
It seems like no tests ran 😔. We are not able to recognize it, please check workflow here.

Summary by CodeRabbit

  • New Features
    • Enhanced data security by adding a method to sanitize and retain only necessary authentication information for various authentication types.

Copy link
Contributor

coderabbitai bot commented Jun 28, 2024

Walkthrough

This update to the DatasourcesApi.ts file introduces a new method cleanAuthenticationObject, which sanitizes authentication data by retaining only the necessary fields. This ensures proper handling of different authentication types such as dbAuth, oAuth2, basic, apiKey, bearerToken, and snowflakeKeyPairAuth.

Changes

File Change Summary
.../src/api/DatasourcesApi.ts Added cleanAuthenticationObject to sanitize authentication data based on authenticationType

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant DatasourcesApi

    Client->>DatasourcesApi: call cleanAuthenticationObject(authentication)
    DatasourcesApi->>DatasourcesApi: Determine authenticationType
    alt dbAuth, oAuth2, basic, apiKey, bearerToken, snowflakeKeyPairAuth
        DatasourcesApi->>DatasourcesApi: Sanitize authentication data
    end
    DatasourcesApi-->>Client: Return sanitized authentication object
Loading

Poem

In code's meadow, a new method sprouted,
cleanAuthenticationObject, the data routed.
Sanitizing fields like a gentle breeze,
Keeping auth paths clear with graceful ease.
Different types, all neat and tight,
With DatasourcesApi, security's light!


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

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>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai 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:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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

Documentation and Community

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

@github-actions github-actions bot added the skip-changelog Adding this label to a PR prevents it from being listed in the changelog label Jun 28, 2024
@sharat87
Copy link
Member Author

/build-deploy-preview skip-tests=true

Copy link

Deploying Your Preview: https://github.com/appsmithorg/appsmith/actions/runs/9713514957.
Workflow: On demand build Docker image and deploy preview.
skip-tests: true.
env: ``.
PR: 34588.
recreate: .

@sharat87 sharat87 added the ok-to-test Required label for CI label Jun 28, 2024
Copy link

Deploy-Preview-URL: https://ce-34588.dp.appsmith.com

@sharat87 sharat87 added ok-to-test Required label for CI and removed ok-to-test Required label for CI labels Jun 28, 2024
@sharat87 sharat87 marked this pull request as ready for review June 28, 2024 16:22
Copy link
Contributor

@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: 1

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between e662e7e and 85495fb.

Files selected for processing (1)
  • app/client/src/api/DatasourcesApi.ts (2 hunks)
Additional context used
Biome
app/client/src/api/DatasourcesApi.ts

[error] 24-240: Avoid classes that contain only static members.

Prefer using simple functions instead of classes with only static members.

(lint/complexity/noStaticOnlyClass)


[error] 53-53: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

Additional comments not posted (2)
app/client/src/api/DatasourcesApi.ts (2)

Line range hint 24-240: Consider refactoring to a simple module.

The class DatasourcesApi only contains static methods, which can be a sign that a class structure is not necessary. Consider refactoring to a simple module with functions to simplify the structure and enhance modularity.
[REFACTOR_SUGGESTion]

- class DatasourcesApi {
-   static url = "v1/datasources";
-   // static methods
- }
+ const DatasourcesApiUrl = "v1/datasources";
+ // Export functions directly

73-130: Review of cleanAuthenticationObject method.

The method appears to be well-implemented with a clear switch-case structure for different authentication types. However, ensure that all fields are necessary and securely handled, especially sensitive fields like passwords and keys.

Consider adding more comments to explain the rationale behind the choices of fields to retain for each authentication type, enhancing maintainability.

app/client/src/api/DatasourcesApi.ts Outdated Show resolved Hide resolved
Copy link
Contributor

@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: 2

Outside diff range and nitpick comments (1)
app/client/src/api/DatasourcesApi.ts (1)

Line range hint 24-240: Consider refactoring the class into a module.

The class DatasourcesApi only contains static methods, which might be better structured as a module. This can enhance clarity and reduce the overhead associated with class syntax.

Consider converting DatasourcesApi into a module with exported functions. This approach can simplify the structure and usage of these API methods.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 85495fb and b45824a.

Files selected for processing (1)
  • app/client/src/api/DatasourcesApi.ts (2 hunks)
Additional context used
Biome
app/client/src/api/DatasourcesApi.ts

[error] 24-240: Avoid classes that contain only static members.

Prefer using simple functions instead of classes with only static members.

(lint/complexity/noStaticOnlyClass)

app/client/src/api/DatasourcesApi.ts Show resolved Hide resolved
Comment on lines +73 to +130
static cleanAuthenticationObject(authentication: any): any {
if (!authentication) {
return undefined;
}

const clean: any = {
authenticationType: authentication.authenticationType ?? "dbAuth",
};

switch (clean.authenticationType) {
case "dbAuth":
clean.authType = authentication.authType;
clean.username = authentication.username;
clean.password = authentication.password;
clean.databaseName = authentication.databaseName;
break;
case "oAuth2":
clean.grantType = authentication.grantType;
clean.isTokenHeader = authentication.isTokenHeader;
clean.isAuthorizationHeader = authentication.isAuthorizationHeader;
clean.clientId = authentication.clientId;
clean.clientSecret = authentication.clientSecret;
clean.authorizationUrl = authentication.authorizationUrl;
clean.expiresIn = authentication.expiresIn;
clean.accessTokenUrl = authentication.accessTokenUrl;
clean.scopeString = authentication.scopeString;
clean.scope = authentication.scope;
clean.sendScopeWithRefreshToken =
authentication.sendScopeWithRefreshToken;
clean.refreshTokenClientCredentialsLocation =
authentication.refreshTokenClientCredentialsLocation;
clean.headerPrefix = authentication.headerPrefix;
clean.customTokenParameters = authentication.customTokenParameters;
clean.audience = authentication.audience;
clean.resource = authentication.resource;
clean.useSelfSignedCert = authentication.useSelfSignedCert;
break;
case "basic":
clean.username = authentication.username;
clean.password = authentication.password;
break;
case "apiKey":
clean.addTo = authentication.addTo;
clean.label = authentication.label;
clean.headerPrefix = authentication.headerPrefix;
clean.value = authentication.value;
break;
case "bearerToken":
clean.bearerToken = authentication.bearerToken;
break;
case "snowflakeKeyPairAuth":
clean.username = authentication.username;
clean.privateKey = authentication.privateKey;
clean.passphrase = authentication.passphrase;
}

return clean;
}
Copy link
Contributor

@coderabbitai coderabbitai bot Jun 28, 2024

Choose a reason for hiding this comment

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

Refactor suggestion for cleanAuthenticationObject method.

This method effectively handles various authentication types by cleaning unnecessary fields. However, it can be optimized by using a mapping strategy instead of a large switch-case block, which can improve maintainability and readability.

- switch (clean.authenticationType) {
-   case "dbAuth":
-     clean.authType = authentication.authType;
-     clean.username = authentication.username;
-     ...
-   case "oAuth2":
-     clean.grantType = authentication.grantType;
-     ...
- }
+ const authFieldMap = {
+   "dbAuth": ["authType", "username", "password", "databaseName"],
+   "oAuth2": ["grantType", "isTokenHeader", "isAuthorizationHeader", "clientId", "clientSecret", "authorizationUrl", "expiresIn", "accessTokenUrl", "scopeString", "scope", "sendScopeWithRefreshToken", "refreshTokenClientCredentialsLocation", "headerPrefix", "customTokenParameters", "audience", "resource", "useSelfSignedCert"],
+   "basic": ["username", "password"],
+   ...
+ };
+ const fields = authFieldMap[clean.authenticationType] || [];
+ fields.forEach(field => {
+   clean[field] = authentication[field];
+ });
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
static cleanAuthenticationObject(authentication: any): any {
if (!authentication) {
return undefined;
}
const clean: any = {
authenticationType: authentication.authenticationType ?? "dbAuth",
};
switch (clean.authenticationType) {
case "dbAuth":
clean.authType = authentication.authType;
clean.username = authentication.username;
clean.password = authentication.password;
clean.databaseName = authentication.databaseName;
break;
case "oAuth2":
clean.grantType = authentication.grantType;
clean.isTokenHeader = authentication.isTokenHeader;
clean.isAuthorizationHeader = authentication.isAuthorizationHeader;
clean.clientId = authentication.clientId;
clean.clientSecret = authentication.clientSecret;
clean.authorizationUrl = authentication.authorizationUrl;
clean.expiresIn = authentication.expiresIn;
clean.accessTokenUrl = authentication.accessTokenUrl;
clean.scopeString = authentication.scopeString;
clean.scope = authentication.scope;
clean.sendScopeWithRefreshToken =
authentication.sendScopeWithRefreshToken;
clean.refreshTokenClientCredentialsLocation =
authentication.refreshTokenClientCredentialsLocation;
clean.headerPrefix = authentication.headerPrefix;
clean.customTokenParameters = authentication.customTokenParameters;
clean.audience = authentication.audience;
clean.resource = authentication.resource;
clean.useSelfSignedCert = authentication.useSelfSignedCert;
break;
case "basic":
clean.username = authentication.username;
clean.password = authentication.password;
break;
case "apiKey":
clean.addTo = authentication.addTo;
clean.label = authentication.label;
clean.headerPrefix = authentication.headerPrefix;
clean.value = authentication.value;
break;
case "bearerToken":
clean.bearerToken = authentication.bearerToken;
break;
case "snowflakeKeyPairAuth":
clean.username = authentication.username;
clean.privateKey = authentication.privateKey;
clean.passphrase = authentication.passphrase;
}
return clean;
}
static cleanAuthenticationObject(authentication: any): any {
if (!authentication) {
return undefined;
}
const clean: any = {
authenticationType: authentication.authenticationType ?? "dbAuth",
};
const authFieldMap = {
"dbAuth": ["authType", "username", "password", "databaseName"],
"oAuth2": ["grantType", "isTokenHeader", "isAuthorizationHeader", "clientId", "clientSecret", "authorizationUrl", "expiresIn", "accessTokenUrl", "scopeString", "scope", "sendScopeWithRefreshToken", "refreshTokenClientCredentialsLocation", "headerPrefix", "customTokenParameters", "audience", "resource", "useSelfSignedCert"],
"basic": ["username", "password"],
"apiKey": ["addTo", "label", "headerPrefix", "value"],
"bearerToken": ["bearerToken"],
"snowflakeKeyPairAuth": ["username", "privateKey", "passphrase"],
};
const fields = authFieldMap[clean.authenticationType] || [];
fields.forEach(field => {
clean[field] = authentication[field];
});
return clean;
}

Copy link
Member Author

Choose a reason for hiding this comment

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

I'm not very certain this "improves" code readability, and especially maintainability (refactoring becomes impossible), so I'd rather not do this.

Copy link
Contributor

Choose a reason for hiding this comment

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

@sharat87, understood. We'll retain the current implementation. Thank you for the feedback.

@@ -67,6 +70,65 @@ class DatasourcesApi extends API {
return API.post(DatasourcesApi.url, datasourceConfig);
}

static cleanAuthenticationObject(authentication: any): any {
Copy link
Member

Choose a reason for hiding this comment

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

Is the usage of any avoidable here? Ideally would like to have as much type safety at compile time as possible.

Copy link
Member Author

Choose a reason for hiding this comment

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

I tried looking into it to setup a type, but, in my opinion, the type definitions to represent this just aren't there today. It's one of the reasons it was so hard to identify what fields are being sent to the server, because more often than not, the type of the request body wasn't an accurate representation of the runtime object fields.

I've raised it in the Slack group I just added you to as well. I'm considering tackling this in small pieces after I'm done with API hardening on the server side.

But for now, I don't have better options here, without blowing this PR up in size that is. Is that okay?

Copy link
Member

Choose a reason for hiding this comment

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

Hmm ... OK. I'm approving this for now. In the future, I think we can potentially copy over the object structures from the server to construct the types where they don't exist on the client.

Copy link
Member Author

Choose a reason for hiding this comment

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

Oh indeed. I've been thinking about generating an Api.ts with methods the same names as backend controller classes, full with type definitions for query params, request body, and response body. Almost like gRPC (I think). We'll get there. Right after I'm done hardening the server a bit more, I'll start biting off at the client. 🙂

@sharat87 sharat87 requested a review from mohanarpit June 29, 2024 02:06
@sharat87 sharat87 merged commit 4c07312 into release Jun 29, 2024
15 checks passed
@sharat87 sharat87 deleted the chore/fix-datasource-creation branch June 29, 2024 08:57
Shivam-z pushed a commit to Shivam-z/appsmith that referenced this pull request Jul 10, 2024
The recent changes to deny any requests that have unrecognized fields in
the body, is making the datasource creation API fail. This is because we
are sending extra fields that shouldn't be sent.

[Slack
conversation](https://theappsmith.slack.com/archives/CPQNLFHTN/p1719577339838649?thread_ts=1719466294.012589&cid=CPQNLFHTN).


**/test sanity datasource**



<!-- This is an auto-generated comment: Cypress test results  -->
> [!WARNING]
> Workflow run:
<https://github.com/appsmithorg/appsmith/actions/runs/9714799545>
> Commit: 85495fb
> <a
href="https://internal.appsmith.com/app/cypress-dashboard/rundetails-65890b3c81d7400d08fa9ee5?branch=master&workflowId=9714799545&attempt=1"
target="_blank">Cypress dashboard</a>.
> Tags: `@tag.Sanity, @tag.Datasource`
> It seems like **no tests ran** 😔. We are not able to recognize it,
please check <a
href="https://github.com/appsmithorg/appsmith/actions/runs/9714799545"
target="_blank">workflow here</a>.

<!-- end of auto-generated comment: Cypress test results  -->




<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **New Features**
- Enhanced data security by adding a method to sanitize and retain only
necessary authentication information for various authentication types.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ok-to-test Required label for CI skip-changelog Adding this label to a PR prevents it from being listed in the changelog
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants