diff --git a/api-gateway-routes/api_gateway_proxy_function.rb b/api-gateway-routes/api_gateway_proxy_function.rb index 088620e0..acbb2887 100644 --- a/api-gateway-routes/api_gateway_proxy_function.rb +++ b/api-gateway-routes/api_gateway_proxy_function.rb @@ -4,7 +4,9 @@ require 'aws-sdk-apigatewaymanagementapi' require 'uri' require_relative 'auth_response_helper' +require_relative 'session_id_helper' include AuthResponseHelper +include SessionIdHelper MAX_SQS_RETRIES = 3 INITIAL_RETRY_SLEEP_S = 0.5 @@ -176,15 +178,6 @@ def get_region(context) context.invoked_function_arn.split(':')[3] end -# SQS queues can only be named with the following characters: -# alphanumeric characters, hyphens (-), and underscores (_) -# See https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/SQS/Client.html#create_queue-instance_method -# The connection ID always ends with an '='. We remove that here so we can use the connection ID as -# our session ID. -def get_session_id(event) - event["requestContext"]["connectionId"].delete_suffix("=") -end - def get_sqs_url(event, context) region = get_region(context) # ARN is of the format arn:aws:lambda:{region}:{account_id}:function:{lambda_name} diff --git a/api-gateway-routes/session_id_helper.rb b/api-gateway-routes/session_id_helper.rb new file mode 100644 index 00000000..651e172e --- /dev/null +++ b/api-gateway-routes/session_id_helper.rb @@ -0,0 +1,11 @@ +module SessionIdHelper + # The session ID is the connection ID with any trailing '=' removed, so it can + # be used as an SQS queue name. SQS queues can only be named with the following + # characters: alphanumeric characters, hyphens (-), and underscores (_). + # See https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/SQS/Client.html#create_queue-instance_method + # The connection ID is base64-encoded, so it can end with one or more '=' + # padding characters. We remove all of them here. + def get_session_id(event) + event["requestContext"]["connectionId"].sub(/=+$/, "") + end +end diff --git a/api-gateway-routes/test/session_id_helper_test.rb b/api-gateway-routes/test/session_id_helper_test.rb new file mode 100644 index 00000000..a1b72b91 --- /dev/null +++ b/api-gateway-routes/test/session_id_helper_test.rb @@ -0,0 +1,23 @@ +require 'minitest/autorun' +require_relative '../session_id_helper' +include SessionIdHelper + +class SessionIdHelperTest < Minitest::Test + def test_strips_single_trailing_padding_character + assert_equal 'PoofdetIoAMCJpg', get_session_id(event_with_connection_id('PoofdetIoAMCJpg=')) + end + + def test_strips_multiple_trailing_padding_characters + assert_equal 'gQwo_Q8CiQAYKAImwA', get_session_id(event_with_connection_id('gQwo_Q8CiQAYKAImwA==')) + end + + def test_leaves_connection_id_without_padding_unchanged + assert_equal 'abc-123_XYZ', get_session_id(event_with_connection_id('abc-123_XYZ')) + end + + private + + def event_with_connection_id(connection_id) + {"requestContext" => {"connectionId" => connection_id}} + end +end