Bug: [BUG] 5xx is thrown when invalid certificate and private key is configured in MCA for Netcetera



### Bug Description

5xx is thrown during authentication call when invalid certificate and private key is configured in MCA for Netcetera

### Expected Behavior

4xx should be thrown when invalid certificate or private keys are configured during MCA creation or updation.

### Actual Behavior

5xx is thrown during authentication call when invalid certificate and private key is configured in MCA for Netcetera

### Steps To Reproduce

Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant.
1. Create a netcetera connector with invalid certificate or private key.
2. No validation error is thrown.


### Context For The Bug

_No response_

### Environment

Are you using hyperswitch hosted version? Yes/No
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.

If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution:
2. Rust version (output of `rustc --version`): ``
3. App version (output of `cargo r --features vergen -- --version`): ``


### Have you spent some time checking if this bug has been raised before?

- [X] I checked and didn't find a similar issue

### Have you read the Contributing Guidelines?

- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)

### Are you willing to submit a PR?

Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index f9da9908d95..fc83573e21d 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -858,27 +858,7 @@ pub async fn create_payment_connector(
             expected_format: "auth_type and api_key".to_string(),
         })?;
 
-    validate_auth_and_metadata_type(req.connector_name, &auth, &req.metadata).map_err(|err| {
-        match *err.current_context() {
-            errors::ConnectorError::InvalidConnectorName => {
-                err.change_context(errors::ApiErrorResponse::InvalidRequestData {
-                    message: "The connector name is invalid".to_string(),
-                })
-            }
-            errors::ConnectorError::InvalidConnectorConfig { config: field_name } => err
-                .change_context(errors::ApiErrorResponse::InvalidRequestData {
-                    message: format!("The {} is invalid", field_name),
-                }),
-            errors::ConnectorError::FailedToObtainAuthType => {
-                err.change_context(errors::ApiErrorResponse::InvalidRequestData {
-                    message: "The auth type is invalid for the connector".to_string(),
-                })
-            }
-            _ => err.change_context(errors::ApiErrorResponse::InvalidRequestData {
-                message: "The request body is invalid".to_string(),
-            }),
-        }
-    })?;
+    validate_auth_and_metadata_type(req.connector_name, &auth, &req.metadata)?;
 
     let frm_configs = get_frm_config_as_secret(req.frm_configs);
 
@@ -1208,27 +1188,7 @@ pub async fn update_payment_connector(
             field_name: "connector",
         })
         .attach_printable_lazy(|| format!("unable to parse connector name {connector_name:?}"))?;
-    validate_auth_and_metadata_type(connector_enum, &auth, &metadata).map_err(|err| match *err
-        .current_context()
-    {
-        errors::ConnectorError::InvalidConnectorName => {
-            err.change_context(errors::ApiErrorResponse::InvalidRequestData {
-                message: "The connector name is invalid".to_string(),
-            })
-        }
-        errors::ConnectorError::InvalidConnectorConfig { config: field_name } => err
-            .change_context(errors::ApiErrorResponse::InvalidRequestData {
-                message: format!("The {} is invalid", field_name),
-            }),
-        errors::ConnectorError::FailedToObtainAuthType => {
-            err.change_context(errors::ApiErrorResponse::InvalidRequestData {
-                message: "The auth type is invalid for the connector".to_string(),
-            })
-        }
-        _ => err.change_context(errors::ApiErrorResponse::InvalidRequestData {
-            message: "The request body is invalid".to_string(),
-        }),
-    })?;
+    validate_auth_and_metadata_type(connector_enum, &auth, &metadata)?;
 
     let (connector_status, disabled) =
         validate_status_and_disabled(req.status, req.disabled, auth, mca.status)?;
@@ -1817,7 +1777,35 @@ pub async fn connector_agnostic_mit_toggle(
     ))
 }
 
-pub(crate) fn validate_auth_and_metadata_type(
+pub fn validate_auth_and_metadata_type(
+    connector_name: api_models::enums::Connector,
+    auth_type: &types::ConnectorAuthType,
+    connector_meta_data: &Option<pii::SecretSerdeValue>,
+) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> {
+    validate_connector_auth_type(auth_type)?;
+    validate_auth_and_metadata_type_with_connector(connector_name, auth_type, connector_meta_data)
+        .map_err(|err| match *err.current_context() {
+            errors::ConnectorError::InvalidConnectorName => {
+                err.change_context(errors::ApiErrorResponse::InvalidRequestData {
+                    message: "The connector name is invalid".to_string(),
+                })
+            }
+            errors::ConnectorError::InvalidConnectorConfig { config: field_name } => err
+                .change_context(errors::ApiErrorResponse::InvalidRequestData {
+                    message: format!("The {} is invalid", field_name),
+                }),
+            errors::ConnectorError::FailedToObtainAuthType => {
+                err.change_context(errors::ApiErrorResponse::InvalidRequestData {
+                    message: "The auth type is invalid for the connector".to_string(),
+                })
+            }
+            _ => err.change_context(errors::ApiErrorResponse::InvalidRequestData {
+                message: "The request body is invalid".to_string(),
+            }),
+        })
+}
+
+pub(crate) fn validate_auth_and_metadata_type_with_connector(
     connector_name: api_models::enums::Connector,
     val: &types::ConnectorAuthType,
     connector_meta_data: &Option<pii::SecretSerdeValue>,
@@ -2094,6 +2082,84 @@ pub(crate) fn validate_auth_and_metadata_type(
     }
 }
 
+pub(crate) fn validate_connector_auth_type(
+    auth_type: &types::ConnectorAuthType,
+) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> {
+    let validate_non_empty_field = |field_value: &str, field_name: &str| {
+        if field_value.trim().is_empty() {
+            Err(errors::ApiErrorResponse::InvalidDataFormat {
+                field_name: format!("connector_account_details.{}", field_name),
+                expected_format: "a non empty String".to_string(),
+            }
+            .into())
+        } else {
+            Ok(())
+        }
+    };
+    match auth_type {
+        hyperswitch_domain_models::router_data::ConnectorAuthType::TemporaryAuth => Ok(()),
+        hyperswitch_domain_models::router_data::ConnectorAuthType::HeaderKey { api_key } => {
+            validate_non_empty_field(api_key.peek(), "api_key")
+        }
+        hyperswitch_domain_models::router_data::ConnectorAuthType::BodyKey { api_key, key1 } => {
+            validate_non_empty_field(api_key.peek(), "api_key")?;
+            validate_non_empty_field(key1.peek(), "key1")
+        }
+        hyperswitch_domain_models::router_data::ConnectorAuthType::SignatureKey {
+            api_key,
+            key1,
+            api_secret,
+        } => {
+            validate_non_empty_field(api_key.peek(), "api_key")?;
+            validate_non_empty_field(key1.peek(), "key1")?;
+            validate_non_empty_field(api_secret.peek(), "api_secret")
+        }
+        hyperswitch_domain_models::router_data::ConnectorAuthType::MultiAuthKey {
+            api_key,
+            key1,
+            api_secret,
+            key2,
+        } => {
+            validate_non_empty_field(api_key.peek(), "api_key")?;
+            validate_non_empty_field(key1.peek(), "key1")?;
+            validate_non_empty_field(api_secret.peek(), "api_secret")?;
+            validate_non_empty_field(key2.peek(), "key2")
+        }
+        hyperswitch_domain_models::router_data::ConnectorAuthType::CurrencyAuthKey {
+            auth_key_map,
+        } => {
+            if auth_key_map.is_empty() {
+                Err(errors::ApiErrorResponse::InvalidDataFormat {
+                    field_name: "connector_account_details.auth_key_map".to_string(),
+                    expected_format: "a non empty map".to_string(),
+                }
+                .into())
+            } else {
+                Ok(())
+            }
+        }
+        hyperswitch_domain_models::router_data::ConnectorAuthType::CertificateAuth {
+            certificate,
+            private_key,
+        } => {
+            helpers::create_identity_from_certificate_and_key(
+                certificate.to_owned(),
+                private_key.to_owned(),
+            )
+            .change_context(errors::ApiErrorResponse::InvalidDataFormat {
+                field_name:
+                    "connector_account_details.certificate or connector_account_details.private_key"
+                        .to_string(),
+                expected_format:
+                    "a valid base64 encoded string of PEM encoded Certificate and Private Key"
+                        .to_string(),
+            })?;
+            Ok(())
+        }
+        hyperswitch_domain_models::router_data::ConnectorAuthType::NoKey => Ok(()),
+    }
+}
+
 #[cfg(feature = "dummy_connector")]
 pub async fn validate_dummy_connector_enabled(
     state: &SessionState,

## Type of Change
<!-- Put an `x` in the boxes that apply -->

- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD

## Description
<!-- Describe your changes in detail -->
Wrote a validation function to validate ConnectorAuthType being passed during MCA create and update.


### Additional Changes

- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables

<!--
Provide links to the files with corresponding changes.

Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->


## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.

If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->


## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Manual.
1. SignatureKey
```
curl --location 'http://localhost:8080/account/postman_merchant_GHAction_3589e3c3-2b53-4627-b0f9-8449b37a9c07/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
    "connector_type": "fiz_operations",
    "connector_name": "cybersource",
    "connector_account_details": {
        "auth_type": "SignatureKey",
        "api_key": "",
        "key1": "",
        "api_secret": ""
    },
    "test_mode": true,
    "disabled": false,
    "business_country": "US",
    "business_label": "default",
    "metadata": {
        "acquirer_bin": "438309",
        "acquirer_merchant_id": "00002000000"
    }
}'
```

2. BodyKey
```
curl --location 'http://localhost:8080/account/postman_merchant_GHAction_f40f3037-ca64-462a-9a00-1e63b69abca0/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
    "connector_type": "fiz_operations",
    "connector_name": "airwallex",
    "connector_account_details": {
        "auth_type": "BodyKey",
        "api_key": "",
        "key1": ""
    },
    "test_mode": true,
    "disabled": false,
    "business_country": "US",
    "business_label": "default",
    "metadata": {
        "acquirer_bin": "438309",
        "acquirer_merchant_id": "00002000000"
    }
}'
```

3. SignatureKey
```
curl --location 'http://localhost:8080/account/postman_merchant_GHAction_f40f3037-ca64-462a-9a00-1e63b69abca0/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
    "connector_type": "fiz_operations",
    "connector_name": "checkout",
    "connector_account_details": {
        "auth_type": "SignatureKey",
        "api_key": "",
        "key1": "",
        "api_secret": ""
    },
    "test_mode": true,
    "disabled": false,
    "business_country": "US",
    "business_label": "default",
    "metadata": {
        "acquirer_bin": "438309",
        "acquirer_merchant_id": "00002000000"
    }
}'
```

4. MultiAuthKey
```
curl --location 'http://localhost:8080/account/postman_merchant_GHAction_f40f3037-ca64-462a-9a00-1e63b69abca0/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
    "connector_type": "fiz_operations",
    "connector_name": "forte",
    "connector_account_details": {
        "auth_type": "MultiAuthKey",
        "api_key": "",
        "key1": "",
        "api_secret": "",
        "key2": ""
    },
    "test_mode": true,
    "disabled": false,
    "business_country": "US",
    "business_label": "default",
    "metadata": {
        "acquirer_bin": "438309",
        "acquirer_merchant_id": "00002000000"
    }
}'
```

5. CurrencyAuthKey
```
curl --location 'http://localhost:8080/account/postman_merchant_GHAction_f40f3037-ca64-462a-9a00-1e63b69abca0/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
    "connector_type": "fiz_operations",
    "connector_name": "cashtocode",
    "connector_account_details": {
        "auth_type": "CurrencyAuthKey",
        "auth_key_map": {}
    },
    "test_mode": true,
    "disabled": false,
    "business_country": "US",
    "business_label": "default",
    "metadata": {
        "acquirer_bin": "438309",
        "acquirer_merchant_id": "00002000000"
    }
}'
```

6. CertificateAuth
```
curl --location 'http://localhost:8080/account/postman_merchant_GHAction_f40f3037-ca64-462a-9a00-1e63b69abca0/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
    "connector_type": "authentication_processor",
    "business_country": "US",
    "business_label": "default",
    "connector_name": "netcetera",
    "connector_account_details": {
        "auth_type": "CertificateAuth",
        "certificate": "",
        "private_key": ""
    },
    "test_mode": true,
    "disabled": false,
    "metadata": {
        "mcc": "5411",
        "merchant_country_code": "840",
        "merchant_name": "Dummy Merchant",
        "endpoint_prefix": "flowbird",
        "three_ds_requestor_name": "juspay-prev",
        "three_ds_requestor_id": "juspay-prev",
        "pull_mechanism_for_external_3ds_enabled": false
    }
}'
```

All above curls contain invalid data in connector_account_details. So should be getting appropriate error message like below.
```
{
    "error": {
        "type": "invalid_request",
        "message": "connector_account_details.certificate or connector_account_details.private_key contains invalid data. Expected format is a valid base64 encoded string of PEM encoded Certificate and Private Key",
        "code": "IR_05"
    }
}
```


## Checklist
<!-- Put an `x` in the boxes that apply -->

- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
