First Commit

This commit is contained in:
2024-01-14 19:24:30 -03:00
commit f5a8be69ca
62 changed files with 1739 additions and 0 deletions

7
files/createapi/config Normal file
View File

@@ -0,0 +1,7 @@
[DEFAULT]
user=ocid1.user.oc1..aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
fingerprint=36:04:63:cd:36:04:63:cd:36:04:63:cd:36:04:63:cd
key_file=oci_api_key.pem
tenancy=ocid1.tenancy.oc1..aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
region=us-ashburn-1

View File

@@ -0,0 +1,12 @@
{
"ClientId" : "0b8cd92bb60b8cd92bb60b8cd92bb6",
"ClientSecret" : "41964196-2cfb-2cfb-2cfb-63246a63246a",
"BaseUrl" : "https://idcs-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.identity.oraclecloud.com",
"AudienceServiceUrl" : "https://idcs-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.identity.oraclecloud.com",
"scope" : "aaaaaaaaaaaaaaaaaaaaaaa.apigateway.us-ashburn-1.oci.customer-oci.com/super_scope",
"TokenIssuer" : "https://identity.oraclecloud.com",
"redirectURL": "http://localhost:8000/callback",
"logoutSufix":"/oauth2/v1/userlogout",
"LogLevel":"INFO",
"ConsoleLog":"True"
}

View File

@@ -0,0 +1,136 @@
{
"compartment_id": "<API Gateway Compartment OCID>",
"defined_tags": {
"Oracle-Tags": {
"CreatedBy": "oracleidentitycloudservice/cristiano.hoshikawa@oracle.com",
"CreatedOn": "2024-01-01T13:15:34.193Z"
}
},
"display_name": "createApi",
"endpoint": "https://aaaaaaaaaaaaaaaaaaaaaaaaaa.apigateway.us-ashburn-1.oci.customer-oci.com/createApi",
"freeform_tags": {},
"gateway_id": "ocid1.apigateway.oc1.iad.amaaaaaanamaaaaaanamaaaaaanamaaaaaanamaaaaaanamaaaaaanamaaaaaan",
"id": "ocid1.apideployment.oc1.iad.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"lifecycle_details": null,
"lifecycle_state": "ACTIVE",
"path_prefix": "/createApi",
"specification": {
"logging_policies": {
"access_log": null,
"execution_log": {
"is_enabled": null,
"log_level": "INFO"
}
},
"request_policies": {
"authentication": {
"cache_key": [
"token",
"displayName",
"apiCompartmentId"
],
"function_id": "<createApi function OCID>",
"is_anonymous_access_allowed": false,
"parameters": {
"apiCompartmentId": "request.headers[apiCompartmentId]",
"body": "request.body",
"displayName": "request.headers[displayName]",
"token": "request.headers[token]"
},
"token_header": null,
"token_query_param": null,
"type": "CUSTOM_AUTHENTICATION",
"validation_failure_policy": null
},
"cors": null,
"dynamic_authentication": null,
"mutual_tls": {
"allowed_sans": [],
"is_verified_certificate_required": false
},
"rate_limiting": null,
"usage_plans": null
},
"routes": [
{
"backend": {
"body": "{\"status\": \"success\"}",
"headers": [],
"status": 200,
"type": "STOCK_RESPONSE_BACKEND"
},
"logging_policies": {
"access_log": null,
"execution_log": {
"is_enabled": null,
"log_level": null
}
},
"methods": [
"POST"
],
"path": "/create",
"request_policies": {
"authorization": {
"type": "AUTHENTICATION_ONLY"
},
"body_validation": null,
"cors": null,
"header_transformations": {
"filter_headers": null,
"rename_headers": null,
"set_headers": {
"items": [
{
"if_exists": "OVERWRITE",
"name": "token",
"values": [
"${request.headers[token]}"
]
},
{
"if_exists": "OVERWRITE",
"name": "displayName",
"values": [
"${request.headers[displayName]}"
]
},
{
"if_exists": "OVERWRITE",
"name": "apiCompartmentId",
"values": [
"${request.headers[apiCompartmentId]}"
]
}
]
}
},
"header_validations": null,
"query_parameter_transformations": null,
"query_parameter_validations": null,
"response_cache_lookup": null
},
"response_policies": {
"header_transformations": {
"filter_headers": null,
"rename_headers": null,
"set_headers": {
"items": [
{
"if_exists": "APPEND",
"name": "api_id",
"values": [
"${request.auth[api_id]}"
]
}
]
}
},
"response_cache_store": null
}
}
]
},
"time_created": "2024-01-01T13:15:35.448000+00:00",
"time_updated": "2024-01-01T13:39:00.396000+00:00"
}

233
files/createapi/func.py Normal file
View File

@@ -0,0 +1,233 @@
import base64
import json
import io
from fdk import response
import oci
import requests
#### IDCS Routines
#### https://docs.oracle.com/en/learn/apigw-modeldeployment/index.html#introduction
#### https://docs.oracle.com/en/learn/migrate-api-to-api-gateway/#introduction
def auth_idcs(token, url, clientID, secretID):
url = url + "/oauth2/v1/introspect"
auth = clientID + ":" + secretID
auth_bytes = auth.encode("ascii")
auth_base64_bytes = base64.b64encode(auth_bytes)
auth_base64_message = auth_base64_bytes.decode("ascii")
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + auth_base64_message
}
payload = "token=" + token
response = requests.request("POST", url, headers=headers, data=payload)
return response
#Function used to load the configurations from the config.json file
def getOptions():
fo = open("config.json", "r")
config = fo.read()
options = json.loads(config)
return options
### OCI API Gateway Migration Routines
def migrate_to_apigw(payload, url, clientID, secretID):
auth = clientID + ":" + secretID
auth_bytes = auth.encode("ascii")
auth_base64_bytes = base64.b64encode(auth_bytes)
auth_base64_message = auth_base64_bytes.decode("ascii")
headers = {
'Content-Type': 'application/json',
'Authorization': 'Basic ' + auth_base64_message
}
response = requests.request("POST", url, headers=headers, data=payload)
return response
def find_base_path(strPath):
base_path = strPath.split('/')[1]
if (len(base_path) == 0):
base_path = strPath
else:
base_path = "/" + base_path
return base_path
def find_path(strPath):
base_path = strPath.split('/')
if (len(base_path) == 0):
return strPath
else:
auxPath = ""
skipCount = 0
for b in base_path:
if (skipCount > 1):
auxPath = auxPath + "/" + b
skipCount = skipCount + 1
base_path = auxPath
return auxPath
def process_api_spec(displayName, compartmentId, environment, swagger):
type = "REST"
config = oci.config.from_file("config")
apigateway_client = oci.apigateway.ApiGatewayClient(config)
logging = oci.loggingingestion.LoggingClient(config)
#-----------------------------------------------------------------
try:
data = swagger
fullSpec = json.loads(data)
version = "3"
try:
version = (fullSpec["swagger"])[:1]
except:
version = (fullSpec["openapi"])[:1]
print("version", version)
if (version == "3"):
endPoint = fullSpec["servers"][0]["url"]
else:
endPoint = fullSpec["host"]
listApis = apigateway_client.list_apis(compartment_id=compartmentId, display_name=displayName, lifecycle_state="ACTIVE")
apis = json.loads(str(listApis.data))
c = len(apis["items"])
api_id = ""
if (c == 0):
print("create api")
create_api_response = apigateway_client.create_api(
create_api_details=oci.apigateway.models.CreateApiDetails(
compartment_id=compartmentId,
display_name=displayName,
content=data))
api_created = json.loads(str(create_api_response.data))
api_id = api_created
else:
print("update api")
update_api_response = apigateway_client.update_api(api_id=apis["items"][0]["id"],
update_api_details=oci.apigateway.models.UpdateApiDetails(
display_name=displayName,
content=data))
api_updated = dict(update_api_response.headers)
api_id = api_updated
return api_id
except(Exception) as ex:
jsonData = 'error parsing json payload: ' + str(ex)
put_logs_response = logging.put_logs(
log_id="ocid1.log.oc1.iad.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
put_logs_details=oci.loggingingestion.models.PutLogsDetails(
specversion="EXAMPLE-specversion-Value",
log_entry_batches=[
oci.loggingingestion.models.LogEntryBatch(
entries=[
oci.loggingingestion.models.LogEntry(
data="error: " + jsonData,
id="ocid1.test.oc1..00000001.EXAMPLE-id-Value")],
source="EXAMPLE-source-Value",
type="EXAMPLE-type-Value")]))
###
def handler(ctx, data: io.BytesIO = None):
config = oci.config.from_file("config")
logging = oci.loggingingestion.LoggingClient(config)
# functions context variables
app_context = dict(ctx.Config())
jsonData = ""
options = getOptions()
try:
header = json.loads(data.getvalue().decode('utf-8'))["data"]
url = options["BaseUrl"]
body = dict(json.loads(data.getvalue().decode('utf-8')).get("data"))["body"]
# body content
swagger = str(body)
body = json.loads(body)
environment = "DEV" #for future development
# header values
access_token = header["token"]
displayName = header["displayName"]
compartmentId = header['apiCompartmentId']
authorization = auth_idcs(access_token, url, options["ClientId"], options["ClientSecret"])
try:
if (authorization.json().get("active") != True):
return response.Response(
ctx,
status_code=401,
response_data=json.dumps({"active": False, "wwwAuthenticate": jsonData})
)
except(Exception) as ex1:
jsonData = 'error parsing json payload: ' + str(ex1)
put_logs_response = logging.put_logs(
log_id="ocid1.log.oc1.iad.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
put_logs_details=oci.loggingingestion.models.PutLogsDetails(
specversion="EXAMPLE-specversion-Value",
log_entry_batches=[
oci.loggingingestion.models.LogEntryBatch(
entries=[
oci.loggingingestion.models.LogEntry(
data="error: " + jsonData,
id="ocid1.test.oc1..00000001.EXAMPLE-id-Value")],
source="EXAMPLE-source-Value",
type="EXAMPLE-type-Value")]))
return response.Response(
ctx,
status_code=401,
response_data=json.dumps({"active": False, "wwwAuthenticate": jsonData})
)
# Create API spec
api_id = process_api_spec(displayName, compartmentId, environment, swagger)
rdata = json.dumps({
"active": True,
"context": {
"environment": environment,
"display_name": displayName,
"api_id": json.dumps(api_id)
}})
return response.Response(
ctx, response_data=rdata,
status_code=200,
headers={"Content-Type": "application/json", "data": rdata}
)
except(Exception) as ex:
jsonData = 'error parsing json payload: ' + str(ex)
put_logs_response = logging.put_logs(
log_id="ocid1.log.oc1.iad.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
put_logs_details=oci.loggingingestion.models.PutLogsDetails(
specversion="EXAMPLE-specversion-Value",
log_entry_batches=[
oci.loggingingestion.models.LogEntryBatch(
entries=[
oci.loggingingestion.models.LogEntry(
data="error: " + jsonData + "/" + swagger,
id="ocid1.test.oc1..00000001.EXAMPLE-id-Value")],
source="EXAMPLE-source-Value",
type="EXAMPLE-type-Value")]))
pass
return response.Response(
ctx,
status_code=401,
response_data=json.dumps({"active": False, "wwwAuthenticate": jsonData})
)

View File

@@ -0,0 +1,8 @@
schema_version: 20180708
name: create-api
version: 0.0.37
runtime: python
build_image: fnproject/python:3.9-dev
run_image: fnproject/python:3.9
entrypoint: /python/bin/fdk /function/func.py handler
memory: 256

View File

@@ -0,0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RV4UM8QKfViBZasZBclCOvt8j+lDK
MIIEpAIBAAKCAQEA16UCid4+eyt6kzo+u1BRV4UM8QKfViBZasZBclCOvt8j+lDK
MIIEpAIBAAKCAQEA16UCid4+eyt6kzo+u1BRV4UM8QKfViBZasZBclCOvt8j+lDK
MIIEpAIBAAKCAQEA16UCid4+eyt6kzo+u1BRV4UM8QKfViBZasZBclCOvt8j+lDK
MIIEpAIBAAKCAQEA16UCid4+eyt6kzo+u1BRV4UM8QKfViBZasZBclCOvt8j+lDK
+PlyICemh7G2GNTwleCu61CVYaVcXxZG8LQkHAHCykuq+R7d6lwxkHQTIyKmUj+o
6BCWIQKBgQCAHaQZ4p/XDHVqajity2YCauQKM7eD0cyUnY9h+MKkih1g7brU43DR
u1yJoOnQzddapVr7yVXMl874mU+Jgm7arh+XRL8WuV2RtltKurBhYqtSwiGg0JFx
pRZm1D73NtXRaTSSwYdXakQjPb4FaFdwBouxVylP6GSy4kI2iva3og==
-----END RSA PRIVATE KEY-----

View File

@@ -0,0 +1,9 @@
fdk>=0.1.54
requests
oci
cryptography
six
PyJWT
py3_lru_cache
simplejson