Class: MLEUtility
- Inherits:
-
Object
- Object
- MLEUtility
- Defined in:
- lib/AuthenticationSDK/util/MLEUtility.rb
Class Method Summary collapse
- .check_is_mle_encrypted_response(responseBody) ⇒ Object
- .check_is_mle_for_API(merchant_config, inbound_mle_status, operation_ids) ⇒ Object
- .check_is_response_mle_for_api(merchant_config, operation_ids) ⇒ Object
- .create_request_payload(compact_jwe) ⇒ Object
- .decrypt_mle_response_payload(merchantConfig, responseBody) ⇒ Object
- .disable_mle_plaintext_logging! ⇒ Object
- .enable_mle_plaintext_logging! ⇒ Object
- .encrypt_request_payload(merchantConfig, requestBody) ⇒ Object
- .extract_serial_number_from_certificate(certificate) ⇒ Object
- .mle_plaintext_logging_enabled? ⇒ Boolean
- .validate_and_auto_extract_response_mle_kid(merchant_config) ⇒ Object
Class Method Details
.check_is_mle_encrypted_response(responseBody) ⇒ Object
145 146 147 148 149 150 151 152 153 154 155 156 |
# File 'lib/AuthenticationSDK/util/MLEUtility.rb', line 145 def self.check_is_mle_encrypted_response(responseBody) return false if responseBody.nil? || responseBody.strip.empty? begin jsonObject = JSON.parse(responseBody) return false unless jsonObject.is_a?(Hash) && jsonObject.size == 1 jsonObject.key?('encryptedResponse') && jsonObject['encryptedResponse'].is_a?(String) rescue JSON::ParserError, TypeError false end end |
.check_is_mle_for_API(merchant_config, inbound_mle_status, operation_ids) ⇒ Object
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/AuthenticationSDK/util/MLEUtility.rb', line 35 def self.check_is_mle_for_API(merchant_config, inbound_mle_status, operation_ids) is_mle_for_api = false if inbound_mle_status&.casecmp('optional') == 0 && merchant_config.enableRequestMLEForOptionalApisGlobally is_mle_for_api = true end if inbound_mle_status&.casecmp('mandatory') == 0 is_mle_for_api = !merchant_config.disableRequestMLEForMandatoryApisGlobally end if !merchant_config.internalMapToControlRequestMLEonAPI.nil? && !merchant_config.internalMapToControlRequestMLEonAPI.empty? && operation_ids operation_ids.each do |operation_id| if merchant_config.internalMapToControlRequestMLEonAPI.key?(operation_id) is_mle_for_api = merchant_config.internalMapToControlRequestMLEonAPI[operation_id] break end end end is_mle_for_api end |
.check_is_response_mle_for_api(merchant_config, operation_ids) ⇒ Object
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 |
# File 'lib/AuthenticationSDK/util/MLEUtility.rb', line 123 def self.check_is_response_mle_for_api(merchant_config, operation_ids) isResponseMLEForApi = false if merchant_config.enableResponseMleGlobally isResponseMLEForApi = true end # operation_ids is an array of the multiple public function for apiCallFunction such as apiCall, apiCallAsync # Control the Response MLE only from map # Special Note: If API expect MLE Response mandatory and map is saying to receive non MLE response then API might throw an error from CyberSource if merchant_config.internalMapToControlResponseMLEonAPI operation_ids.each do |operation_id| if merchant_config.internalMapToControlResponseMLEonAPI.key?(operation_id) isResponseMLEForApi = merchant_config.internalMapToControlResponseMLEonAPI[operation_id] break end end end isResponseMLEForApi end |
.create_request_payload(compact_jwe) ⇒ Object
119 120 121 |
# File 'lib/AuthenticationSDK/util/MLEUtility.rb', line 119 def self.create_request_payload(compact_jwe) "{ \"encryptedRequest\": \"#{compact_jwe}\" }" end |
.decrypt_mle_response_payload(merchantConfig, responseBody) ⇒ Object
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 |
# File 'lib/AuthenticationSDK/util/MLEUtility.rb', line 158 def self.decrypt_mle_response_payload(merchantConfig, responseBody) @log_obj ||= Log.new(merchantConfig.log_config, 'MLEUtility') if !self.check_is_mle_encrypted_response(responseBody) raise StandardError.new('Response body is not MLE encrypted.') end mlePrivateKey = self.get_mle_response_private_key(merchantConfig) jweResponseToken = self.get_response_mle_token(responseBody) # When mle token is empty or null then fall back to non mle encrypted response if jweResponseToken.nil? || jweResponseToken.strip.empty? return responseBody end begin # Fail-safe: only emit decrypted-MLE bodies when an operator has explicitly # called MLEUtility.enable_mle_plaintext_logging! AND the logger is at # DEBUG. Even then, route the payload through SensitiveDataFilter so # PCI/PII fields (PAN, CVV, account, expiration, token, ...) are masked # before reaching any appender. plaintext_logging = MLEUtility.mle_plaintext_logging_enabled? && @log_obj.logger.debug? if plaintext_logging formatter = SensitiveDataFilter.new @log_obj.logger.debug("LOG_NETWORK_RESPONSE_BEFORE_MLE_DECRYPTION: #{formatter.maskSensitiveDataInJson(responseBody)}") else @log_obj.logger.debug('LOG_NETWORK_RESPONSE_BEFORE_MLE_DECRYPTION: <encrypted payload omitted>') end decryptedResponse = AuthJWEUtility.decrypt_jwe_using_private_key(mlePrivateKey, jweResponseToken) if plaintext_logging formatter ||= SensitiveDataFilter.new @log_obj.logger.debug("LOG_NETWORK_RESPONSE_AFTER_MLE_DECRYPTION: #{formatter.maskSensitiveDataInJson(decryptedResponse)}") else @log_obj.logger.debug('LOG_NETWORK_RESPONSE_AFTER_MLE_DECRYPTION: <decrypted payload not logged>') end return decryptedResponse rescue => e raise StandardError.new(Constants::ERROR_PREFIX + "An error occurred during MLE decryption: #{e.}") end end |
.disable_mle_plaintext_logging! ⇒ Object
31 32 33 |
# File 'lib/AuthenticationSDK/util/MLEUtility.rb', line 31 def disable_mle_plaintext_logging! @mle_plaintext_logging_enabled = false end |
.enable_mle_plaintext_logging! ⇒ Object
27 28 29 |
# File 'lib/AuthenticationSDK/util/MLEUtility.rb', line 27 def enable_mle_plaintext_logging! @mle_plaintext_logging_enabled = true end |
.encrypt_request_payload(merchantConfig, requestBody) ⇒ Object
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
# File 'lib/AuthenticationSDK/util/MLEUtility.rb', line 57 def self.encrypt_request_payload(merchantConfig, requestBody) return nil if requestBody.nil? return requestBody if requestBody == '{}' @log_obj ||= Log.new(merchantConfig.log_config, 'MLEUtility') @log_obj.logger.info('Encrypting request payload') @log_obj.logger.debug('LOG_REQUEST_BEFORE_MLE: ' + requestBody) mleCertificate = Cache.new.getRequestMLECertificateFromCache(merchantConfig) if mleCertificate.nil? && Constants::AUTH_TYPE_HTTP.downcase == merchantConfig.authenticationType.downcase @log_obj.logger.debug("The certificate to use for MLE for requests is not provided in the merchant configuration. Please ensure that the certificate path is provided.") @log_obj.logger.debug("Currently, MLE for requests using HTTP Signature as authentication is not supported by Cybersource. By default, the SDK will fall back to non-encrypted requests.") return requestBody end # Check if using shared secret JWT without explicit MLE certificate path if mleCertificate.nil? && Constants::AUTH_TYPE_JWT.downcase == merchantConfig.authenticationType.downcase && merchantConfig.is_shared_secret_key_type? @log_obj.logger.debug("MLE for requests with JWT shared secret authentication requires mleForRequestPublicCertPath to be explicitly provided in merchant configuration.") @log_obj.logger.debug("Please set mleForRequestPublicCertPath to the path of your MLE public certificate file.") raise StandardError.new(Constants::ERROR_PREFIX + "Missing MLE certificate for JWT shared secret authentication. Please provide the MLE public certificate path in the configuration.") end begin serial_number = self.extract_serial_number_from_certificate(mleCertificate) jwk = JOSE::JWK.from_key(mleCertificate.public_key) if jwk.nil? @log_obj.logger.error('Failed to create JWK object from public key') raise StandardError.new('Failed to create JWK object from public key') end headers = { 'alg' => 'RSA-OAEP-256', 'enc' => 'A256GCM', 'typ' => 'JWT', 'kid' => serial_number, 'iat' => Time.now.to_i } jwe = JOSE::JWE.block_encrypt(jwk, requestBody, headers) compact_jwe = jwe.compact mle_request_body = self.create_request_payload(compact_jwe) @log_obj.logger.debug('LOG_REQUEST_AFTER_MLE: ' + mle_request_body) return mle_request_body rescue StandardError => e @log_obj.logger.error("An error occurred during encryption: #{e.}") raise e end end |
.extract_serial_number_from_certificate(certificate) ⇒ Object
110 111 112 113 114 115 116 117 |
# File 'lib/AuthenticationSDK/util/MLEUtility.rb', line 110 def self.extract_serial_number_from_certificate(certificate) raise StandardError.new('Certificate cannot be nil') if certificate.nil? raise StandardError.new('Certificate subject and issuer cannot both be empty') if certificate.subject.to_s.empty? && certificate.issuer.to_s.empty? certificate.subject.to_a.each do |attribute| return attribute[1] if attribute[0].include?('serialNumber') end raise StandardError.new('Serial number not found in certificate subject') end |
.mle_plaintext_logging_enabled? ⇒ Boolean
23 24 25 |
# File 'lib/AuthenticationSDK/util/MLEUtility.rb', line 23 def mle_plaintext_logging_enabled? @mle_plaintext_logging_enabled == true end |
.validate_and_auto_extract_response_mle_kid(merchant_config) ⇒ Object
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 |
# File 'lib/AuthenticationSDK/util/MLEUtility.rb', line 234 def self.validate_and_auto_extract_response_mle_kid(merchant_config) @log_obj ||= Log.new(merchant_config.log_config, 'MLEUtility') if !merchant_config.responseMlePrivateKey.nil? && !merchant_config.responseMlePrivateKey.to_s.strip.empty? @log_obj.logger.debug('responseMlePrivateKey is provided directly, using configured responseMleKID') return merchant_config.responseMleKID end @log_obj.logger.debug('Validating responseMleKID for JWT token generation') cybs_kid = nil p12_file = false # File path validity begin CertificateUtility.validatePathAndFile(merchant_config.responseMlePrivateKeyFilePath, 'responseMlePrivateKeyFilePath', merchant_config.log_config) extension = File.extname(merchant_config.responseMlePrivateKeyFilePath).delete_prefix('.').downcase if extension == 'p12' || extension == 'pfx' p12_file = true end rescue IOError => e @log_obj.logger.debug('No valid private key file path provided, skipping auto-extraction') end if p12_file @log_obj.logger.debug('P12/PFX file detected, checking if it is a CyberSource certificate') cached_data = Cache.new.get_mle_kid_data_from_cache(merchant_config) if !cached_data.nil? if !cached_data.kid.nil? # KID present means it's a CyberSource P12, use it cybs_kid = cached_data.kid else # KID is null means either non-CyberSource P12 or extraction failed @log_obj.logger.debug('Private key file is not a CyberSource generated P12/PFX file, skipping auto-extraction') end end else @log_obj.logger.debug('Private key file is not a P12/PFX file, skipping auto-extraction') end if !cybs_kid.nil? @log_obj.logger.debug('Successfully auto-extracted responseMleKID from CyberSource P12 certificate') end configured_kid = merchant_config.responseMleKID if cybs_kid.nil? && configured_kid.nil? raise StandardError.new('responseMleKID is required when response MLE is enabled. ' + 'Could not auto-extract from certificate and no manual configuration provided. ' + 'Please provide responseMleKID explicitly in your configuration.' ) elsif cybs_kid.nil? @log_obj.logger.debug('Using manually configured responseMleKID') return configured_kid elsif configured_kid.nil? @log_obj.logger.debug('Using auto-extracted responseMleKID from CyberSource certificate') return cybs_kid elsif cybs_kid != configured_kid @log_obj.logger.warn('Auto-extracted responseMleKID does not match manually configured responseMleKID. Using configured value as preference') end return configured_kid end |