|
| 1 | +# Copyright (c) 2023 Oracle and/or its affiliates. |
| 2 | +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. |
| 3 | +import datetime |
| 4 | +import io |
| 5 | +import json |
| 6 | +import logging |
| 7 | +from datetime import timedelta |
| 8 | + |
| 9 | +import requests |
| 10 | +from fdk import response |
| 11 | +from requests.auth import HTTPBasicAuth |
| 12 | + |
| 13 | +import ociVault |
| 14 | + |
| 15 | +oauth_apps = {} |
| 16 | + |
| 17 | +def initContext(context): |
| 18 | + # This method takes elements from the Application Context and from OCI Vault to create the OAuth App Clients object. |
| 19 | + if (len(oauth_apps) < 2): |
| 20 | + logging.getLogger().info('Retriving details about the API and backend OAuth Apps') |
| 21 | + try: |
| 22 | + logging.getLogger().info('initContext: Initializing context') |
| 23 | + |
| 24 | + # Using ociVault |
| 25 | + oauth_apps['apigw'] = {'introspection_endpoint': context['idcs_introspection_endpoint'], |
| 26 | + 'client_id': context['introspection_idcs_app_client_id'], |
| 27 | + 'client_secret': ociVault.getSecret(context['introspection_idcs_app_client_secret_ocid'])} |
| 28 | + oauth_apps['oic'] = {'token_endpoint': context['idcs_token_endpoint'], |
| 29 | + 'client_id': context['oic_idcs_app_client_id'], |
| 30 | + 'client_secret': ociVault.getSecret(context['oic_idcs_app_client_secret_ocid']), 'scope': context['oic_scope']} |
| 31 | + |
| 32 | + except Exception as ex: |
| 33 | + logging.getLogger().error('initContext: Failed to get config or secrets') |
| 34 | + print("ERROR [initContext]: Failed to get the configs", ex, flush=True) |
| 35 | + raise |
| 36 | + else: |
| 37 | + logging.getLogger().info('initContext: OAuth Apps already stored') |
| 38 | + |
| 39 | +def introspectToken(access_token, introspection_endpoint, client_id, client_secret): |
| 40 | + # This method handles the introspection of the received auth token to IDCS. |
| 41 | + payload = {'token': access_token} |
| 42 | + headers = {'Content-Type' : 'application/x-www-form-urlencoded;charset=UTF-8', |
| 43 | + 'Accept': 'application/json'} |
| 44 | + |
| 45 | + try: |
| 46 | + token = requests.post(introspection_endpoint, |
| 47 | + data=payload, |
| 48 | + headers=headers, |
| 49 | + auth=HTTPBasicAuth(client_id, client_secret)) |
| 50 | + |
| 51 | + except Exception as ex: |
| 52 | + logging.getLogger().error("introspectToken: Failed to introspect token" + ex) |
| 53 | + raise |
| 54 | + |
| 55 | + return token.json() |
| 56 | + |
| 57 | +def getBackEndAuthToken(token_endpoint, client_id, client_secret, scope): |
| 58 | + # This method gets the token from the back-end system (oic in this case) |
| 59 | + payload = {'grant_type': 'client_credentials', 'scope': scope} |
| 60 | + headers = {'Content-Type' : 'application/x-www-form-urlencoded;charset=UTF-8', |
| 61 | + 'Accept': 'application/json'} |
| 62 | + |
| 63 | + try: |
| 64 | + backend_token = requests.post(token_endpoint, |
| 65 | + data=payload, |
| 66 | + headers=headers, |
| 67 | + auth=HTTPBasicAuth(client_id, client_secret)) |
| 68 | + |
| 69 | + logging.getLogger().info("getBackEndAuthToken: Got the backend token " + backend_token.text) |
| 70 | + |
| 71 | + except Exception as ex: |
| 72 | + logging.getLogger().error("getBackEndAuthToken: Failed to get the backend token" + ex) |
| 73 | + raise |
| 74 | + |
| 75 | + return backend_token.json() |
| 76 | + |
| 77 | +def getAuthContext(token, client_apps): |
| 78 | + # This method populates the Auth Context that will be returned to the gateway. |
| 79 | + auth_context = {} |
| 80 | + |
| 81 | + # Calling IDCS to validate the token and retrieve the client info |
| 82 | + try: |
| 83 | + token_info = introspectToken(token[len('Bearer '):], client_apps['apigw']['introspection_endpoint'], client_apps['apigw']['client_id'], client_apps['apigw']['client_secret']) |
| 84 | + |
| 85 | + except Exception as ex: |
| 86 | + logging.getLogger().error("getAuthContext: Failed to introspect token" + ex) |
| 87 | + raise |
| 88 | + |
| 89 | + # If IDCS confirmed the token is valid and active, we can proceed to populate the auth context |
| 90 | + if (token_info['active'] == True): |
| 91 | + auth_context['active'] = True |
| 92 | + # auth_context['principal'] = token_info['sub'] |
| 93 | + auth_context['client_id'] = token_info['client_id'] |
| 94 | + auth_context['scope'] = token_info['scope'] |
| 95 | + |
| 96 | + # Retrieving the back-end Token |
| 97 | + backend_token = getBackEndAuthToken(client_apps['oic']['token_endpoint'], client_apps['oic']['client_id'], client_apps['oic']['client_secret'], client_apps['oic']['scope']) |
| 98 | + |
| 99 | + # The maximum TTL for this auth is the lesser of the API Client Auth (IDCS) and the Gateway Client Auth (oic) |
| 100 | + if (datetime.datetime.fromtimestamp(token_info['exp']) < (datetime.datetime.utcnow() + timedelta(seconds=backend_token['expires_in']))): |
| 101 | + auth_context['expiresAt'] = (datetime.datetime.fromtimestamp(token_info['exp'])).replace(tzinfo=datetime.timezone.utc).astimezone().replace(microsecond=0).isoformat() |
| 102 | + else: |
| 103 | + auth_context['expiresAt'] = (datetime.datetime.utcnow() + timedelta(seconds=backend_token['expires_in'])).replace(tzinfo=datetime.timezone.utc).astimezone().replace(microsecond=0).isoformat() |
| 104 | + |
| 105 | + # Storing the back_end_token in the context of the auth decision so we can map it to Authorization header using the request/response transformation policy |
| 106 | + auth_context['context'] = {'back_end_token': ('Bearer ' + str(backend_token['access_token']))} |
| 107 | + |
| 108 | + else: |
| 109 | + # API Client token is not active, so we will go ahead and respond with the wwwAuthenticate header |
| 110 | + auth_context['active'] = False |
| 111 | + auth_context['wwwAuthenticate'] = 'Bearer realm=\"identity.oraclecloud.com\"' |
| 112 | + |
| 113 | + return(auth_context) |
| 114 | + |
| 115 | +def handler(ctx, data: io.BytesIO=None): |
| 116 | + logging.getLogger().info('Entered Handler') |
| 117 | + initContext(dict(ctx.Config())) |
| 118 | + |
| 119 | + auth_context = {} |
| 120 | + try: |
| 121 | + gateway_auth = json.loads(data.getvalue()) |
| 122 | + |
| 123 | + auth_context = getAuthContext(gateway_auth['data']['token'], oauth_apps) |
| 124 | + |
| 125 | + if (auth_context['active']): |
| 126 | + logging.getLogger().info('Authorizer returning 200...') |
| 127 | + return response.Response( |
| 128 | + ctx, |
| 129 | + response_data=json.dumps(auth_context), |
| 130 | + status_code = 200, |
| 131 | + headers={"Content-Type": "application/json"} |
| 132 | + ) |
| 133 | + else: |
| 134 | + logging.getLogger().info('Authorizer returning 401...') |
| 135 | + return response.Response( |
| 136 | + ctx, |
| 137 | + response_data=json.dumps(str(auth_context)), |
| 138 | + status_code = 401, |
| 139 | + headers={"Content-Type": "application/json"} |
| 140 | + ) |
| 141 | + |
| 142 | + except (Exception, ValueError) as ex: |
| 143 | + logging.getLogger().info('error parsing json payload: ' + str(ex)) |
| 144 | + |
| 145 | + return response.Response( |
| 146 | + ctx, |
| 147 | + response_data=json.dumps(str(auth_context)), |
| 148 | + status_code = 401, |
| 149 | + headers={"Content-Type": "application/json"} |
| 150 | + ) |
| 151 | + |
0 commit comments