Sample to check session timeout¶
This example demonstrates how to check for session timeout settings in your account.
Prerequisites¶
Before running this example, ensure you have the following:
FunctionGraph function¶
session-timeout/src/index.py¶
import http.client
import json
import time
from otc_api_sign_core import signer
from requests import request
"""
Get the policy resource representation for RMS.
"""
def get_policy_resource(domain_id, resource):
return {
"domain_id": domain_id,
"region_id": resource.get("region_id"),
"resource_id": resource.get("id"),
"resource_name": resource.get("name"),
"resource_provider": resource.get("provider"),
"resource_type": resource.get("type"),
}
"""
The evaluation result will be either compliant or non-compliant.
In this example, if the session timeout configured for the account is greater than 30 minutes,
Compliant is returned. Otherwise, NonCompliant is returned.
see: https://docs.otc.t-systems.com/identity-access-management/api-ref/apis/security_settings/querying_the_login_authentication_policy.html
"""
def evaluate_compliance(context, domain_id):
logger = context.getLogger()
# Prepare the headers and endpoint URL for the IAM API request
# IAM is a global service, so we need to specify X-Domain-Id in the headers
# and use signed request
# The function needs also rights to call domain services.
headers = {
"X-Domain-Id": domain_id,
"Content-Type": "application/json"
}
endpoint_url = context.getUserData("IAM_ENDPOINT_URL")
url = f"{endpoint_url}/v3.0/OS-SECURITYPOLICY/domains/{domain_id}/login-policy"
sig = signer.Signer()
sig.Key = context.getSecurityAccessKey()
sig.Secret = context.getSecuritySecretKey()
sig.SecurityToken = context.getSecurityToken()
signed_request = signer.HttpRequest("GET", url, headers, "")
sig.Sign(signed_request)
response = request("GET", url, headers=signed_request.headers, data=None)
if response.status_code != http.client.OK:
logger.error("Failed to get login policy with response: %s", response.json())
return "NonCompliant"
response_json = response.json()
login_policy = response_json.get("login_policy", {})
session_timeout = login_policy.get("session_timeout", 0)
if session_timeout > 30:
logger.info("Compliant")
return "Compliant"
else:
logger.info("NonCompliant")
return "NonCompliant"
"""
Update the policy state in RMS with the evaluation result.
see: https://docs.otc.t-systems.com/config/api-ref/apis/compliance/updating_the_compliance_result.html#rms-04-0515
"""
def update_policy_state(context, domain_id, evaluation):
logger = context.getLogger()
endpoint_url = context.getUserData("RMS_ENDPOINT_URL")
url = f"{endpoint_url}/v1/resource-manager/domains/{domain_id}/policy-states"
logger.info(
"Updating policy state with URL: %s, payload: %s", url, json.dumps(evaluation)
)
headers = {
"Content-Type": "application/json;charset=UTF-8",
"X-Domain-Id": domain_id,
}
payload = json.dumps(evaluation)
sig = signer.Signer()
sig.Key = context.getSecurityAccessKey()
sig.Secret = context.getSecuritySecretKey()
sig.SecurityToken = context.getSecurityToken()
signed_request = signer.HttpRequest("PUT", url, headers, payload)
sig.Sign(signed_request)
response = request(
"PUT", url, headers=signed_request.headers, data=payload.encode()
)
return response
"""
FunctionGraph handler to handle the incoming event and evaluate compliance for the resource.
"""
def handler(event, context):
logger = context.getLogger()
logger.info("Invoking event: %s", json.dumps(event))
domain_id = event.get("domain_id")
resource = event.get("invoking_event", {})
if resource.get("name") != "Account":
logger.info("Name is not 'Account' but: %s", resource.get("name"))
return
compliance_state = evaluate_compliance(context, domain_id)
request_body = {
"policy_resource": get_policy_resource(event.get("domain_id"), resource),
"trigger_type": event.get("trigger_type"),
"compliance_state": compliance_state,
"policy_assignment_id": event.get("policy_assignment_id"),
"policy_assignment_name": event.get("policy_assignment_name"),
"function_urn": event.get("function_urn"),
"evaluation_time": event.get("evaluation_time"),
"evaluation_hash": event.get("evaluation_hash"),
}
for retry in range(3):
response = update_policy_state(context, event.get("domain_id"), request_body)
if response.status_code == http.client.TOO_MANY_REQUESTS:
logger.error("TOO_MANY_REQUESTS: retry again, attempt %d", retry + 1)
time.sleep(1)
else:
if response.status_code == http.client.OK:
logger.info("Update policyState successfully.")
elif response.status_code == http.client.BAD_REQUEST:
logger.error("CHECK TEST EVENT FOR EVALUATION_HASH. Bad request: %s", response.json())
else:
logger.error(
"Failed to update policyState with response: %s", response.json()
)
break
session-timeout/requirements.txt¶
otc-api-sign-sdk-python @ git+https://github.com/opentelekomcloud-community/otc-api-sign-sdk-python.git@0.1.0
Terraform deployment files¶
FunctionGraph deployment files¶
session-timeout/terraform/function.tf¶
##########################################################
# Python event function to handle ECS stopped compliance
##########################################################
resource "opentelekomcloud_fgs_function_v2" "MyFunction" {
name = format("%s_%s", var.prefix, var.function_name)
app = "default"
handler = var.handler_name
runtime = "Python3.10"
agency = opentelekomcloud_identity_agency_v3.agency.name
code_type = "zip"
func_code = filebase64(format("${path.module}/../%s", var.zip_file_name))
code_filename = basename(var.zip_file_name)
description = var.description
memory_size = 128
timeout = 30
max_instance_num = 10
log_group_id = opentelekomcloud_lts_group_v2.MyLogGroup.id
log_group_name = opentelekomcloud_lts_group_v2.MyLogGroup.group_name
log_topic_id = opentelekomcloud_lts_stream_v2.MyLogStream.id
log_topic_name = opentelekomcloud_lts_stream_v2.MyLogStream.stream_name
# set some environment variables
user_data = jsonencode({
"IAM_ENDPOINT_URL" : "https://iam.eu-de.otc.t-systems.com"
"RMS_ENDPOINT_URL" : "https://rms.eu-de.otc.t-systems.com"
})
tags = {
"app_group" = var.tag_app_group
}
}
output "MY_FUNCTION_URN" {
value = opentelekomcloud_fgs_function_v2.MyFunction.urn
}
output "MY_FUNCTION_VERSION" {
value = opentelekomcloud_fgs_function_v2.MyFunction.version
}
session-timeout/terraform/function-agency.tf¶
##################################################################
# Custom role to allow FunctionGraph to update RMS policy states
##################################################################
resource "opentelekomcloud_identity_role_v3" "role" {
display_name = format("%s-%s-role", var.prefix, var.function_name)
description = "Role for FunctionGraph to update RMS"
display_layer = "project"
statement {
effect = "Allow"
action = [
"rms:policyStates:update"
]
}
}
##################################################################
# Custom role to allow FunctionGraph to get login policy
##################################################################
resource "opentelekomcloud_identity_role_v3" "role_domain" {
display_name = format("%s-%s-domainrole", var.prefix, var.function_name)
description = "Domain role for FunctionGraph to get account login policy"
display_layer = "domain"
statement {
effect = "Allow"
action = [
"iam:securitypolicies:getLoginPolicy"
]
}
}
##########################################################
# Agency for FunctionGraph
# Attention: Creating agency will take some time.
# Calls to function after creating agency will fail until
# agency is set up.
##########################################################
resource "opentelekomcloud_identity_agency_v3" "agency" {
depends_on = [opentelekomcloud_identity_role_v3.role, opentelekomcloud_identity_role_v3.role_domain]
delegated_domain_name = "op_svc_cff"
name = format("%s-%s-agency", var.prefix, var.function_name)
description = "Agency for FunctionGraph for session timeout"
project_role {
all_projects = true
# project = var.OTC_SDK_PROJECTNAME
roles = [
opentelekomcloud_identity_role_v3.role.display_name
]
}
domain_roles = [
opentelekomcloud_identity_role_v3.role_domain.display_name
]
}
session-timeout/terraform/function-logging.tf¶
##########################################################
# Create Log Group
##########################################################
resource "opentelekomcloud_lts_group_v2" "MyLogGroup" {
group_name = format("%s_%s_%s", var.prefix, var.function_name, "log_group")
ttl_in_days = 1
tags = {
"app_group" = var.tag_app_group
}
}
##########################################################
# Create Log Stream
##########################################################
resource "opentelekomcloud_lts_stream_v2" "MyLogStream" {
group_id = opentelekomcloud_lts_group_v2.MyLogGroup.id
stream_name = format("%s_%s_%s", var.prefix, var.function_name, "log_stream")
tags = {
"app_group" = var.tag_app_group
}
}
session-timeout/terraform/test_event.tf¶
resource "opentelekomcloud_fgs_event_v2" "test2" {
function_urn = opentelekomcloud_fgs_function_v2.MyFunction.urn
name = "test2"
content = base64encode(jsonencode(
{
"domain_id" = var.OTC_SDK_DOMAIN_ID,
"policy_assignment_id" = opentelekomcloud_rms_policy_assignment_v1.my_policy_assignment.id,
"policy_assignment_name" = opentelekomcloud_rms_policy_assignment_v1.my_policy_assignment.name,
"function_urn" = opentelekomcloud_fgs_function_v2.MyFunction.urn,
"trigger_type" = "period",
"evaluation_time" = 1794817596177,
# YOU NEED TO UPDATE THIS evaluation_hash TO MATCH THE CURRENT EVALUATION.
# See function output for the correct evaluation_hash value.
"evaluation_hash" = "UPDATE_WITH_FUNCTION_OUTPUT",
"rule_parameter" = {},
"invoking_event" = {
"id" = var.OTC_SDK_DOMAIN_ID,
"name" = "Account",
"provider" = "",
"type" = "",
"region_id" = "global"
}
}
)
)
}
Note
You need to update the evaluation_hash in the test event to match the current evaluation. Run the function once from Config to get the correct evaluation_hash.
Config deployment files¶
session-timeout/terraform/rms.tf¶
#######################################################################
# Policy assignment for FunctionGraph to manage ECS expression compliance
#######################################################################
resource "opentelekomcloud_rms_policy_assignment_v1" "my_policy_assignment" {
name = format("%s-%s", var.prefix, "Session_Timeout")
description = "Policy assignment for FunctionGraph"
custom_policy {
auth_type = "agency"
auth_value = {
agency_name = format("\"%s\"", opentelekomcloud_identity_agency_v3.config_agency.name)
}
function_urn = format("%s:%s", opentelekomcloud_fgs_function_v2.MyFunction.urn, opentelekomcloud_fgs_function_v2.MyFunction.version)
}
period = "One_Hour"
status = "Enabled"
}
session-timeout/terraform/rms-agency.tf¶
##################################################################
# Custom role to allow RMS to execute FunctionGraph functions
##################################################################
resource "opentelekomcloud_identity_role_v3" "fg_role" {
display_name = format("%s-%s-config-role", var.prefix, var.function_name)
description = "Role for RMS to execute FunctionGraph functions"
display_layer = "project"
statement {
effect = "Allow"
action = [
"functiongraph:function:invokeAsync",
"functiongraph:function:getConfig"
]
resource = [
format("FunctionGraph:*:*:function:%s/%s",
opentelekomcloud_fgs_function_v2.MyFunction.app,
opentelekomcloud_fgs_function_v2.MyFunction.name)
]
}
}
#################################################################
# Config agency for RMS to access FunctionGraph
#################################################################
resource "opentelekomcloud_identity_agency_v3" "config_agency" {
name = format("%s-%s-config-agency", var.prefix, var.function_name)
description = "Config agency for FunctionGraph access"
delegated_domain_name = "op_svc_rms"
project_role {
all_projects = true
# project = var.OTC_SDK_PROJECTNAME
roles = [
#"FunctionGraph FullAccess"
opentelekomcloud_identity_role_v3.fg_role.display_name
]
}
}
Variables¶
Sample variables file:
session-timeout/terraform/variables.tfvars¶
# Terraform variables for scratch-event sample
# prefix of all resources
prefix = "python"
# description of the function
description = "Custom rule for session timeout"
# name of the function (will be prefixed)
function_name = "custom-rule-session-timeout"
# handler function name defined in your code, e.g. "index.handler"
handler_name = "src/index.handler"
# name of zip file to deploy
zip_file_name = "dist/code.zip"
# resources will be tagged with this app_group tag
tag_app_group = "custom-rule-session-timeout"
You might want to adjust the variables to your need.
Makefile¶
Sample Makefile:
session-timeout/Makefile¶
# Makefile for Terraform deployment
SHELL:=/bin/bash
# Terraform backend configuration
BACKEND_CONFIG_BUCKET := "doc-samples-tf-backend"
BACKEND_CONFIG_KEY := "terraform_state/python/custom-rule-session-timeout.tf"
BACKEND_CONFIG_REGION := "eu-de"
BACKEND_CONFIG_ENDPOINTS := "endpoints={s3=\"https://obs.eu-de.otc.t-systems.com\"}"
CURRENT_MAKEFILE := $(firstword $(MAKEFILE_LIST))
check_code:
python3 -m py_compile src/index.py
python3 ../utils/createZip.py
tf_init:
terraform -chdir=terraform \
init \
-backend-config=$(BACKEND_CONFIG_ENDPOINTS) \
-backend-config="bucket=$(BACKEND_CONFIG_BUCKET)" \
-backend-config="key=$(BACKEND_CONFIG_KEY)" \
-backend-config="region=$(BACKEND_CONFIG_REGION)"
tf_plan:
if [ ! -f "terraform/.terraform.lock.hcl" ]; then \
$(MAKE) -f $(CURRENT_MAKEFILE) tf_init; \
fi
terraform -chdir=terraform \
plan \
-var-file="variables.tfvars"
tf_apply: check_code
if [ ! -f "terraform/.terraform.lock.hcl" ]; then \
$(MAKE) -f $(CURRENT_MAKEFILE) tf_init; \
fi
terraform -chdir=terraform \
apply -auto-approve \
-var-file="variables.tfvars"
tf_destroy:
terraform -chdir=terraform \
destroy -auto-approve \
-var-file="variables.tfvars"
.PHONY: check_code tf_init tf_plan tf_apply tf_destroy
You might want to adjust the variables to your need:
# Terraform backend configuration
BACKEND_CONFIG_BUCKET := "doc-samples-tf-backend"
BACKEND_CONFIG_KEY := "terraform_state/python/custom-rule-session-timeout.tf"
BACKEND_CONFIG_REGION := "eu-de"
BACKEND_CONFIG_ENDPOINTS := "endpoints={s3=\"https://obs.eu-de.otc.t-systems.com\"}"
Deploy¶
To deploy using Terraform run:
make tf_apply
To destroy the deployed resources using Terraform run:
make tf_destroy