How to use auth_keys_from_connection method in localstack

Best Python code snippet using localstack_python

message_forwarding.py

Source: message_forwarding.py Github

copy

Full Screen

...127 logEvents=[{"timestamp": now_utc(millis=True), "message": json.dumps(event)}],128 )129 else:130 LOG.warning('Unsupported Events rule target ARN: "%s"', target_arn)131def auth_keys_from_connection(connection: Dict):132 headers = {}133 auth_type = connection.get("AuthorizationType").upper()134 auth_parameters = connection.get("AuthParameters")135 if auth_type == AUTH_BASIC:136 basic_auth_parameters = auth_parameters.get("BasicAuthParameters", {})137 username = basic_auth_parameters.get("Username", "")138 password = basic_auth_parameters.get("Password", "")139 headers.update({"authorization": "Basic {}:{}".format(username, password)})140 if auth_type == AUTH_API_KEY:141 api_key_parameters = auth_parameters.get("ApiKeyAuthParameters", {})142 api_key_name = api_key_parameters.get("ApiKeyName", "")143 api_key_value = api_key_parameters.get("ApiKeyValue", "")144 headers.update({api_key_name: api_key_value})145 if auth_type == AUTH_OAUTH:146 oauth_parameters = auth_parameters.get("OAuthParameters", {})147 oauth_method = oauth_parameters.get("HttpMethod")148 oauth_endpoint = oauth_parameters.get("AuthorizationEndpoint", "")149 query_object = list_of_parameters_to_object(150 oauth_parameters.get("QueryStringParameters", [])151 )152 oauth_endpoint = add_query_params_to_url(oauth_endpoint, query_object)153 client_parameters = oauth_parameters.get("ClientParameters", {})154 client_id = client_parameters.get("ClientID", "")155 client_secret = client_parameters.get("ClientSecret", "")156 oauth_body = list_of_parameters_to_object(oauth_parameters.get("BodyParameters", []))157 oauth_body.update({"client_id": client_id, "client_secret": client_secret})158 oauth_header = list_of_parameters_to_object(oauth_parameters.get("HeaderParameters", []))159 oauth_result = requests.request(160 method=oauth_method,161 url=oauth_endpoint,162 data=json.dumps(oauth_body),163 headers=oauth_header,164 )165 oauth_data = json.loads(oauth_result.text)166 token_type = oauth_data.get("token_type", "")167 access_token = oauth_data.get("access_token", "")168 auth_header = "{} {}".format(token_type, access_token)169 headers.update({"authorization": auth_header})170 return headers171def list_of_parameters_to_object(items):172 return {item.get("Key"): item.get("Value") for item in items}173def send_event_to_api_destination(target_arn, event):174 """Send an event to an EventBridge API destination175 See https:/​/​docs.aws.amazon.com/​eventbridge/​latest/​userguide/​eb-api-destinations.html"""176 # ARN format: ...:api-destination/​{name}/​{uuid}177 region = target_arn.split(":")[3]178 api_destination_name = target_arn.split(":")[-1].split("/​")[1]179 events_client = connect_to_service("events", region_name=region)180 destination = events_client.describe_api_destination(Name=api_destination_name)181 # get destination endpoint details182 method = destination.get("HttpMethod", "GET")183 endpoint = destination.get("InvocationEndpoint")184 state = destination.get("ApiDestinationState") or "ACTIVE"185 LOG.debug('Calling EventBridge API destination (state "%s"): %s %s', state, method, endpoint)186 headers = {187 # default headers AWS sends with every api destination call188 "User-Agent": "Amazon/​EventBridge/​ApiDestinations",189 "Content-Type": "application/​json; charset=utf-8",190 "Range": "bytes=0-1048575",191 "Accept-Encoding": "gzip,deflate",192 "Connection": "close",193 }194 endpoint = add_api_destination_authorization(destination, headers, event)195 result = requests.request(196 method=method, url=endpoint, data=json.dumps(event or {}), headers=headers197 )198 if result.status_code >= 400:199 LOG.debug("Received code %s forwarding events: %s %s", result.status_code, method, endpoint)200 if result.status_code == 429 or 500 <= result.status_code <= 600:201 pass # TODO: retry logic (only retry on 429 and 5xx response status)202def add_api_destination_authorization(destination, headers, event):203 connection_arn = destination.get("ConnectionArn", "")204 connection_name = re.search(r"connection\/​([a-zA-Z0-9-_]+)\/​", connection_arn).group(1)205 connection_region = extract_region_from_arn(connection_arn)206 # Using backend directly due to boto hiding passwords, keys and secret values207 event_backend = moto_events_backends.get(connection_region)208 connection = event_backend.describe_connection(name=connection_name)209 headers.update(auth_keys_from_connection(connection))210 auth_parameters = connection.get("AuthParameters", {})211 invocation_parameters = auth_parameters.get("InvocationHttpParameters")212 endpoint = destination.get("InvocationEndpoint")213 if invocation_parameters:214 header_parameters = list_of_parameters_to_object(215 invocation_parameters.get("HeaderParameters", [])216 )217 headers.update(header_parameters)218 body_parameters = list_of_parameters_to_object(219 invocation_parameters.get("BodyParameters", [])220 )221 event.update(body_parameters)222 query_parameters = invocation_parameters.get("QueryStringParameters", [])223 query_object = list_of_parameters_to_object(query_parameters)...

Full Screen

Full Screen

Blogs

Check out the latest blogs from LambdaTest on this topic:

13 Best Java Testing Frameworks For 2023

The fact is not alien to us anymore that cross browser testing is imperative to enhance your application’s user experience. Enhanced knowledge of popular and highly acclaimed testing frameworks goes a long way in developing a new app. It holds more significance if you are a full-stack developer or expert programmer.

QA Innovation &#8211; Using the senseshaping concept to discover customer needs

QA Innovation - Using the senseshaping concept to discover customer needsQA testers have a unique role and responsibility to serve the customer. Serving the customer in software testing means protecting customers from application defects, failures, and perceived failures from missing or misunderstood requirements. Testing for known requirements based on documentation or discussion is the core of the testing profession. One unique way QA testers can both differentiate themselves and be innovative occurs when senseshaping is used to improve the application user experience.

Best 23 Web Design Trends To Follow In 2023

Having a good web design can empower business and make your brand stand out. According to a survey by Top Design Firms, 50% of users believe that website design is crucial to an organization’s overall brand. Therefore, businesses should prioritize website design to meet customer expectations and build their brand identity. Your website is the face of your business, so it’s important that it’s updated regularly as per the current web design trends.

Acquiring Employee Support for Change Management Implementation

Enterprise resource planning (ERP) is a form of business process management software—typically a suite of integrated applications—that assists a company in managing its operations, interpreting data, and automating various back-office processes. The introduction of a new ERP system is analogous to the introduction of a new product into the market. If the product is not handled appropriately, it will fail, resulting in significant losses for the business. Most significantly, the employees’ time, effort, and morale would suffer as a result of the procedure.

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run localstack automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful