dex-connector-amazon-lambda 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dex_connector_amazon_lambda-0.1.0.dist-info/METADATA +15 -0
- dex_connector_amazon_lambda-0.1.0.dist-info/RECORD +19 -0
- dex_connector_amazon_lambda-0.1.0.dist-info/WHEEL +4 -0
- dex_connector_amazon_lambda-0.1.0.dist-info/licenses/LICENSE +21 -0
- dex_connectors/amazon_lambda/__init__.py +22 -0
- dex_connectors/amazon_lambda/_generated/__init__.py +2 -0
- dex_connectors/amazon_lambda/_generated/config.py +28 -0
- dex_connectors/amazon_lambda/_generated/connection.py +144 -0
- dex_connectors/amazon_lambda/_generated/definitions.py +40 -0
- dex_connectors/amazon_lambda/_generated/mock.py +74 -0
- dex_connectors/amazon_lambda/_generated/models.py +23 -0
- dex_connectors/amazon_lambda/_generated/steps.py +81 -0
- dex_connectors/amazon_lambda/client.py +197 -0
- dex_connectors/amazon_lambda/connection.py +8 -0
- dex_connectors/amazon_lambda/dex-connector.json +64 -0
- dex_connectors/amazon_lambda/lambdamock/__init__.py +6 -0
- dex_connectors/amazon_lambda/models.py +8 -0
- dex_connectors/amazon_lambda/sigv4.py +82 -0
- dex_connectors/amazon_lambda/steps.py +5 -0
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: dex-connector-amazon-lambda
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Amazon Lambda connector for Dex Flows
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Python: >=3.11
|
|
8
|
+
Requires-Dist: dex-connectors-sdk==0.1.0
|
|
9
|
+
Requires-Dist: dex-python-sdk>=1.28.0
|
|
10
|
+
Requires-Dist: httpx>=0.27
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# Amazon Lambda Python connector
|
|
14
|
+
|
|
15
|
+
The `get_function` Query reads a Lambda function name and ARN. Configure AWS Region and signing credentials as described in the [connector README](../README.md). The [runnable Flow](examples/function_lookup/README.md) exercises a real Dex Worker and local provider fixture. Live AWS access has not been verified.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
dex_connectors/amazon_lambda/__init__.py,sha256=ggig3FFgF7EGAhq4-D88gHCOLZc3ZmVMypgWxul-H4c,660
|
|
2
|
+
dex_connectors/amazon_lambda/client.py,sha256=U32ivtiQ-3jgK2v5ZMe0kRh2wUWMoL7QyHwT5AaP8Ek,8375
|
|
3
|
+
dex_connectors/amazon_lambda/connection.py,sha256=Licy8wMnABF6Ll42qlEifeXWEqZAxwB70ax8T-V8ahA,442
|
|
4
|
+
dex_connectors/amazon_lambda/dex-connector.json,sha256=zE_N8LYHE8jWJCyVjFDGSeuoZ16452S7nCJlIKF-v9I,1587
|
|
5
|
+
dex_connectors/amazon_lambda/models.py,sha256=QLsS-vdpNvZUkGGZ1u7nRgmBNzaZ0nkrzxWD8vgolNo,373
|
|
6
|
+
dex_connectors/amazon_lambda/sigv4.py,sha256=g4qXeCKbfzxXELq2OyxzbOd_Hxz5TBc9e-8uXIlfYOw,2783
|
|
7
|
+
dex_connectors/amazon_lambda/steps.py,sha256=ZNczCsQg2q2WGLCfZlnlnJAXe9K6JFVkedr4Ip24a90,197
|
|
8
|
+
dex_connectors/amazon_lambda/_generated/__init__.py,sha256=ShfMsAGzSt4xuhCaf20ibgtfXl4pXomZb00ovUw6CeI,66
|
|
9
|
+
dex_connectors/amazon_lambda/_generated/config.py,sha256=xJqRj4D1BQTsQo6E9-SChr0b6nSysukh1N8rgvvmGuk,633
|
|
10
|
+
dex_connectors/amazon_lambda/_generated/connection.py,sha256=VkBALnGAMEy6xlfQyU__ZSXoMaqqt9ZnBWDWq2S_HJ8,6552
|
|
11
|
+
dex_connectors/amazon_lambda/_generated/definitions.py,sha256=WUZp74oBhcia6XD6bz8jLl6Yp04XCR3V0qLn-88guGw,1305
|
|
12
|
+
dex_connectors/amazon_lambda/_generated/mock.py,sha256=ibyqaQZgZv2kcOeQLvPFBX0NMmekmnEZb1LTdvGF9Rk,3158
|
|
13
|
+
dex_connectors/amazon_lambda/_generated/models.py,sha256=4sSuTgclgQGv-MOPc3pHV4-spMcZ5X6lpc7yZ8E2MHo,703
|
|
14
|
+
dex_connectors/amazon_lambda/_generated/steps.py,sha256=yLezXwCzuqw7tTBCvhW6qAO0DVYJc5MJNjCc2wgRYOM,3347
|
|
15
|
+
dex_connectors/amazon_lambda/lambdamock/__init__.py,sha256=sEODfqQ6BJ0_cxRmH7FUHlzuhGC26jntpGD0cmUtm_U,167
|
|
16
|
+
dex_connector_amazon_lambda-0.1.0.dist-info/METADATA,sha256=o4Gj1CiCcgCBq3w9cCeie0iwEMqlm_dYEnG2pef5Rzw,682
|
|
17
|
+
dex_connector_amazon_lambda-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
18
|
+
dex_connector_amazon_lambda-0.1.0.dist-info/licenses/LICENSE,sha256=qxaONjKKLHWsQ8r6n9ajKgIIs03Fjeww2u-iDuIJZPM,1065
|
|
19
|
+
dex_connector_amazon_lambda-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Super Durable
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated keyation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# Copyright (c) 2026 Super Durable
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
"""Amazon Lambda key Queries for Dex Flows."""
|
|
4
|
+
|
|
5
|
+
from .client import Client, Config, Credentials, GetFunctionOperation
|
|
6
|
+
from .connection import Connection, new_connection, new_connection_with_operations, new_project_connection
|
|
7
|
+
from .models import FunctionDetails, GetFunctionInput
|
|
8
|
+
from .steps import new_get_function_step
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"Client",
|
|
12
|
+
"Config",
|
|
13
|
+
"Connection",
|
|
14
|
+
"Credentials",
|
|
15
|
+
"GetFunctionInput",
|
|
16
|
+
"FunctionDetails",
|
|
17
|
+
"GetFunctionOperation",
|
|
18
|
+
"new_connection",
|
|
19
|
+
"new_connection_with_operations",
|
|
20
|
+
"new_get_function_step",
|
|
21
|
+
"new_project_connection",
|
|
22
|
+
]
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# Copyright (c) 2026 Super Durable
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
# ruff: noqa
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
from dex_connectors.sdk import SecretString
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True, slots=True)
|
|
11
|
+
class Config:
|
|
12
|
+
|
|
13
|
+
endpoint: str
|
|
14
|
+
region: str = "us-east-1"
|
|
15
|
+
timeout_seconds: float = 15
|
|
16
|
+
max_response_bytes: int = 2097152
|
|
17
|
+
|
|
18
|
+
setattr(Config, '__module__', 'dex_connectors.amazon_lambda.client')
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True, slots=True)
|
|
22
|
+
class Credentials:
|
|
23
|
+
|
|
24
|
+
access_key_id: SecretString
|
|
25
|
+
secret_access_key: SecretString
|
|
26
|
+
session_token: SecretString
|
|
27
|
+
|
|
28
|
+
setattr(Credentials, '__module__', 'dex_connectors.amazon_lambda.client')
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
# Copyright (c) 2026 Super Durable
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
# ruff: noqa
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
from dex_connectors.sdk import ConnectionRef, Query, Call, SecretString
|
|
9
|
+
from dex_connectors.sdk.projectconfig import ConnectionKey, LoadedProject
|
|
10
|
+
|
|
11
|
+
from ..client import Client, Config, Credentials
|
|
12
|
+
from .definitions import CONNECTOR_ID, GET_FUNCTION_DEFINITION
|
|
13
|
+
from ..models import FunctionDetails, GetFunctionInput
|
|
14
|
+
|
|
15
|
+
class Connection:
|
|
16
|
+
|
|
17
|
+
__slots__ = ('_get_function', '_client', 'reference')
|
|
18
|
+
|
|
19
|
+
def __init__(self,
|
|
20
|
+
reference: ConnectionRef,
|
|
21
|
+
get_function: Query[GetFunctionInput, FunctionDetails],
|
|
22
|
+
client: Client | None = None,
|
|
23
|
+
) -> None:
|
|
24
|
+
reference.validate()
|
|
25
|
+
if reference.provider != CONNECTOR_ID or get_function is None:
|
|
26
|
+
raise ValueError("Amazon Lambda connection provider and operations are required")
|
|
27
|
+
if get_function.definition().operation != GET_FUNCTION_DEFINITION.operation:
|
|
28
|
+
raise ValueError("Amazon Lambda connection operation identity differs")
|
|
29
|
+
self.reference = reference
|
|
30
|
+
self._get_function = get_function
|
|
31
|
+
self._client = client
|
|
32
|
+
|
|
33
|
+
def get_function(self) -> Query[GetFunctionInput, FunctionDetails]:
|
|
34
|
+
return self._get_function
|
|
35
|
+
|
|
36
|
+
async def aclose(self) -> None:
|
|
37
|
+
if self._client is not None:
|
|
38
|
+
await self._client.aclose()
|
|
39
|
+
|
|
40
|
+
def __repr__(self) -> str:
|
|
41
|
+
return "amazon_lambda.Connection([REDACTED])"
|
|
42
|
+
|
|
43
|
+
def __reduce__(self) -> tuple[object, ...]:
|
|
44
|
+
raise TypeError("Amazon Lambda connections cannot be serialized")
|
|
45
|
+
|
|
46
|
+
setattr(Connection, '__module__', 'dex_connectors.amazon_lambda.connection')
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def new_connection(client: Client, reference: ConnectionRef) -> Connection:
|
|
50
|
+
if client is None:
|
|
51
|
+
raise ValueError("Amazon Lambda client is required")
|
|
52
|
+
return Connection(reference, client.get_function(), client)
|
|
53
|
+
|
|
54
|
+
setattr(new_connection, '__module__', 'dex_connectors.amazon_lambda.connection')
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def new_connection_with_operations(
|
|
58
|
+
get_function: Query[GetFunctionInput, FunctionDetails],
|
|
59
|
+
reference: ConnectionRef,
|
|
60
|
+
) -> Connection:
|
|
61
|
+
return Connection(reference, get_function)
|
|
62
|
+
|
|
63
|
+
setattr(new_connection_with_operations, '__module__', 'dex_connectors.amazon_lambda.connection')
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class _ProjectCredentialSource:
|
|
67
|
+
|
|
68
|
+
def __init__(self, project: LoadedProject, key: ConnectionKey) -> None:
|
|
69
|
+
self.project = project
|
|
70
|
+
self.key = key
|
|
71
|
+
|
|
72
|
+
async def resolve(self, call: Call) -> Credentials:
|
|
73
|
+
material = await self.project.resolve_credential(self.key, str(call.id))
|
|
74
|
+
if not isinstance(material, dict):
|
|
75
|
+
raise ValueError("Amazon Lambda stored credential does not match the connector credential fields")
|
|
76
|
+
if set(material) - set(('access_key_id', 'secret_access_key', 'session_token')):
|
|
77
|
+
raise ValueError("Amazon Lambda stored credential does not match the connector credential fields")
|
|
78
|
+
access_key_id = material.get("access_key_id")
|
|
79
|
+
if access_key_id is not None and not (isinstance(access_key_id, str)):
|
|
80
|
+
raise ValueError("Amazon Lambda credential access_key_id has an invalid type")
|
|
81
|
+
secret_access_key = material.get("secret_access_key")
|
|
82
|
+
if secret_access_key is not None and not (isinstance(secret_access_key, str)):
|
|
83
|
+
raise ValueError("Amazon Lambda credential secret_access_key has an invalid type")
|
|
84
|
+
session_token = material.get("session_token")
|
|
85
|
+
if session_token is not None and not (isinstance(session_token, str)):
|
|
86
|
+
raise ValueError("Amazon Lambda credential session_token has an invalid type")
|
|
87
|
+
if not access_key_id:
|
|
88
|
+
raise ValueError("Amazon Lambda credential access_key_id is required")
|
|
89
|
+
if not secret_access_key:
|
|
90
|
+
raise ValueError("Amazon Lambda credential secret_access_key is required")
|
|
91
|
+
return Credentials(SecretString(access_key_id), SecretString(secret_access_key), SecretString(session_token or ''))
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def new_project_connection(
|
|
95
|
+
project: LoadedProject, connection_name: str, http_client: httpx.AsyncClient | None = None
|
|
96
|
+
) -> Connection:
|
|
97
|
+
if project is None:
|
|
98
|
+
raise ValueError("Amazon Lambda connection requires loaded project configuration")
|
|
99
|
+
reference = ConnectionRef(CONNECTOR_ID, connection_name)
|
|
100
|
+
reference.validate()
|
|
101
|
+
key = ConnectionKey(CONNECTOR_ID, connection_name)
|
|
102
|
+
matching = [
|
|
103
|
+
entry
|
|
104
|
+
for entry in project.configuration.connections
|
|
105
|
+
if entry.connector_id == CONNECTOR_ID and entry.connection_name == connection_name
|
|
106
|
+
]
|
|
107
|
+
if len(matching) != 1:
|
|
108
|
+
raise ValueError("Amazon Lambda project connection is missing or duplicated")
|
|
109
|
+
if matching[0].provider != CONNECTOR_ID:
|
|
110
|
+
raise ValueError("Amazon Lambda project connection provider differs")
|
|
111
|
+
config = _decode_config(matching[0].configuration)
|
|
112
|
+
client = Client(config, _ProjectCredentialSource(project, key), http_client)
|
|
113
|
+
return new_connection(client, reference)
|
|
114
|
+
|
|
115
|
+
setattr(new_project_connection, '__module__', 'dex_connectors.amazon_lambda.connection')
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _decode_config(value: dict[str, Any]) -> Config:
|
|
119
|
+
if set(value) - {"region", "endpoint", "timeout", "maxResponseBytes"}:
|
|
120
|
+
raise ValueError("Amazon Lambda configuration has unknown fields")
|
|
121
|
+
config_arguments: dict[str, Any] = {}
|
|
122
|
+
if "region" in value and value["region"] != '':
|
|
123
|
+
region = value["region"]
|
|
124
|
+
if not (isinstance(region, str)):
|
|
125
|
+
raise ValueError("Amazon Lambda configuration region has an invalid type")
|
|
126
|
+
config_arguments['region'] = region
|
|
127
|
+
if "endpoint" in value and value["endpoint"] != '':
|
|
128
|
+
endpoint = value["endpoint"]
|
|
129
|
+
if not (isinstance(endpoint, str)):
|
|
130
|
+
raise ValueError("Amazon Lambda configuration endpoint has an invalid type")
|
|
131
|
+
config_arguments['endpoint'] = endpoint
|
|
132
|
+
else:
|
|
133
|
+
config_arguments['endpoint'] = ''
|
|
134
|
+
if "timeout" in value and value["timeout"] != '':
|
|
135
|
+
timeout = value["timeout"]
|
|
136
|
+
if not (type(timeout) is int):
|
|
137
|
+
raise ValueError("Amazon Lambda configuration timeout has an invalid type")
|
|
138
|
+
config_arguments['timeout_seconds'] = timeout / 1_000_000_000
|
|
139
|
+
if "maxResponseBytes" in value and value["maxResponseBytes"] != '':
|
|
140
|
+
max_response_bytes = value["maxResponseBytes"]
|
|
141
|
+
if not (type(max_response_bytes) is int):
|
|
142
|
+
raise ValueError("Amazon Lambda configuration maxResponseBytes has an invalid type")
|
|
143
|
+
config_arguments['max_response_bytes'] = max_response_bytes
|
|
144
|
+
return Config(**config_arguments)
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# Copyright (c) 2026 Super Durable
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
# ruff: noqa
|
|
4
|
+
|
|
5
|
+
from datetime import timedelta
|
|
6
|
+
|
|
7
|
+
from dex_connectors.sdk import (
|
|
8
|
+
BranchDefinition,
|
|
9
|
+
MutationDefinition,
|
|
10
|
+
OperationRef,
|
|
11
|
+
QueryDefinition,
|
|
12
|
+
RetryPolicy,
|
|
13
|
+
StepDefaults,
|
|
14
|
+
default_connector_step_execute_retry_policy,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
CONNECTOR_ID = "amazon-lambda"
|
|
18
|
+
PROVIDER = "amazon-lambda"
|
|
19
|
+
GET_FUNCTION_OPERATION_ID = "getFunction"
|
|
20
|
+
DEFECT = "defect"
|
|
21
|
+
FOUND = "found"
|
|
22
|
+
INVALID_RESPONSE = "invalidResponse"
|
|
23
|
+
MISSING = "missing"
|
|
24
|
+
PROVIDER_REJECTED = "providerRejected"
|
|
25
|
+
|
|
26
|
+
GET_FUNCTION_DEFINITION = QueryDefinition(
|
|
27
|
+
OperationRef(CONNECTOR_ID, GET_FUNCTION_OPERATION_ID),
|
|
28
|
+
(
|
|
29
|
+
BranchDefinition(FOUND, "AWS returned the function configuration.", False),
|
|
30
|
+
BranchDefinition(MISSING, "The function does not exist in the selected Region.", True),
|
|
31
|
+
BranchDefinition(PROVIDER_REJECTED, "AWS conclusively rejected the request or credentials.", True),
|
|
32
|
+
BranchDefinition(INVALID_RESPONSE, "AWS returned malformed or oversized function metadata.", True),
|
|
33
|
+
BranchDefinition(DEFECT, "The function name, endpoint, Region, or credentials are invalid.", True),
|
|
34
|
+
),
|
|
35
|
+
StepDefaults(
|
|
36
|
+
timedelta(seconds=30),
|
|
37
|
+
2,
|
|
38
|
+
execute_retry=default_connector_step_execute_retry_policy(),
|
|
39
|
+
),
|
|
40
|
+
)
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# Copyright (c) 2026 Super Durable
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
# ruff: noqa
|
|
4
|
+
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
|
|
7
|
+
from dex_connectors.sdk import ConnectionRef, Failure, FailureKind
|
|
8
|
+
from dex_connectors.sdk.connectormock import Case, Query
|
|
9
|
+
|
|
10
|
+
from ..connection import Connection, new_connection_with_operations
|
|
11
|
+
from ..models import FunctionDetails, GetFunctionInput
|
|
12
|
+
from .definitions import CONNECTOR_ID, DEFECT, FOUND, GET_FUNCTION_DEFINITION, INVALID_RESPONSE, MISSING, PROVIDER_REJECTED
|
|
13
|
+
|
|
14
|
+
def get_function_found(value: FunctionDetails, failure: Failure | None = None) -> Case[FunctionDetails]:
|
|
15
|
+
return Case.branch_result(FOUND, value, failure)
|
|
16
|
+
|
|
17
|
+
setattr(get_function_found, '__module__', "dex_connectors.amazon_lambda.lambdamock")
|
|
18
|
+
|
|
19
|
+
def get_function_missing(value: FunctionDetails, failure: Failure | None = None) -> Case[FunctionDetails]:
|
|
20
|
+
return Case.branch_result(MISSING, value, failure)
|
|
21
|
+
|
|
22
|
+
setattr(get_function_missing, '__module__', "dex_connectors.amazon_lambda.lambdamock")
|
|
23
|
+
|
|
24
|
+
def get_function_provider_rejected(value: FunctionDetails, failure: Failure | None = None) -> Case[FunctionDetails]:
|
|
25
|
+
return Case.branch_result(PROVIDER_REJECTED, value, failure)
|
|
26
|
+
|
|
27
|
+
setattr(get_function_provider_rejected, '__module__', "dex_connectors.amazon_lambda.lambdamock")
|
|
28
|
+
|
|
29
|
+
def get_function_invalid_response(value: FunctionDetails, failure: Failure | None = None) -> Case[FunctionDetails]:
|
|
30
|
+
return Case.branch_result(INVALID_RESPONSE, value, failure)
|
|
31
|
+
|
|
32
|
+
setattr(get_function_invalid_response, '__module__', "dex_connectors.amazon_lambda.lambdamock")
|
|
33
|
+
|
|
34
|
+
def get_function_defect(value: FunctionDetails, failure: Failure | None = None) -> Case[FunctionDetails]:
|
|
35
|
+
return Case.branch_result(DEFECT, value, failure)
|
|
36
|
+
|
|
37
|
+
setattr(get_function_defect, '__module__', "dex_connectors.amazon_lambda.lambdamock")
|
|
38
|
+
|
|
39
|
+
def get_function_retry(failure: Failure, after_seconds: float = 0) -> Case[FunctionDetails]:
|
|
40
|
+
return Case.retry(failure, after_seconds)
|
|
41
|
+
|
|
42
|
+
setattr(get_function_retry, '__module__', "dex_connectors.amazon_lambda.lambdamock")
|
|
43
|
+
|
|
44
|
+
def get_function_found_default() -> Case[FunctionDetails]:
|
|
45
|
+
return Case.branch_result(FOUND, FunctionDetails(name='example-function', arn='arn:aws:lambda:us-east-1:123456789012:function:example-function'))
|
|
46
|
+
|
|
47
|
+
setattr(get_function_found_default, '__module__', "dex_connectors.amazon_lambda.lambdamock")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class Mock:
|
|
51
|
+
|
|
52
|
+
def __init__(self, connection_name: str = "amazon-lambda") -> None:
|
|
53
|
+
self.get_function_script: Query[GetFunctionInput, FunctionDetails] = Query(GET_FUNCTION_DEFINITION)
|
|
54
|
+
self.get_function_script.default(get_function_found_default())
|
|
55
|
+
self._connection = new_connection_with_operations(
|
|
56
|
+
get_function=self.get_function_script,
|
|
57
|
+
reference=ConnectionRef(CONNECTOR_ID, connection_name),
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
def connection(self) -> Connection:
|
|
61
|
+
return self._connection
|
|
62
|
+
|
|
63
|
+
setattr(Mock, '__module__', "dex_connectors.amazon_lambda.lambdamock")
|
|
64
|
+
|
|
65
|
+
__all__ = [
|
|
66
|
+
"Mock",
|
|
67
|
+
"get_function_found",
|
|
68
|
+
"get_function_missing",
|
|
69
|
+
"get_function_provider_rejected",
|
|
70
|
+
"get_function_invalid_response",
|
|
71
|
+
"get_function_defect",
|
|
72
|
+
"get_function_retry",
|
|
73
|
+
"get_function_found_default",
|
|
74
|
+
]
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# Copyright (c) 2026 Super Durable
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
# ruff: noqa
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field as _dataclass_field
|
|
6
|
+
|
|
7
|
+
# GetFunctionInput identifies one Lambda function in the configured Region.
|
|
8
|
+
@dataclass(frozen=True, slots=True)
|
|
9
|
+
class GetFunctionInput:
|
|
10
|
+
function_name: str = _dataclass_field(default='', metadata={'dex_json_name': 'functionName'})
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
setattr(GetFunctionInput, '__module__', 'dex_connectors.amazon_lambda.models')
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
# FunctionDetails returns the stable identity of a Lambda function.
|
|
17
|
+
@dataclass(frozen=True, slots=True)
|
|
18
|
+
class FunctionDetails:
|
|
19
|
+
name: str = ''
|
|
20
|
+
arn: str = ''
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
setattr(FunctionDetails, '__module__', 'dex_connectors.amazon_lambda.models')
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# Copyright (c) 2026 Super Durable
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
# ruff: noqa
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable, Mapping
|
|
6
|
+
from typing import Any, TypeVar
|
|
7
|
+
|
|
8
|
+
import dex
|
|
9
|
+
from dex_connectors.sdk import (
|
|
10
|
+
QueryResult,
|
|
11
|
+
QueryStep,
|
|
12
|
+
QueryStepConfig,
|
|
13
|
+
StepAnnotations,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
from ..connection import Connection
|
|
17
|
+
from ..models import FunctionDetails, GetFunctionInput
|
|
18
|
+
|
|
19
|
+
StepInput = TypeVar("StepInput")
|
|
20
|
+
|
|
21
|
+
def new_get_function_step(
|
|
22
|
+
*,
|
|
23
|
+
step_type: str,
|
|
24
|
+
step_input_type: type[StepInput],
|
|
25
|
+
annotations: StepAnnotations | Mapping[str, str],
|
|
26
|
+
connection: Connection,
|
|
27
|
+
connection_name: str,
|
|
28
|
+
map_to_operation_input: Callable[[StepInput], GetFunctionInput],
|
|
29
|
+
found: dex.StepTarget[QueryResult[FunctionDetails]],
|
|
30
|
+
missing: dex.StepTarget[QueryResult[FunctionDetails]] | None = None,
|
|
31
|
+
provider_rejected: dex.StepTarget[QueryResult[FunctionDetails]] | None = None,
|
|
32
|
+
invalid_response: dex.StepTarget[QueryResult[FunctionDetails]] | None = None,
|
|
33
|
+
defect: dex.StepTarget[QueryResult[FunctionDetails]] | None = None,
|
|
34
|
+
result_attribute: dex.Attribute[QueryResult[FunctionDetails]] | None = None,
|
|
35
|
+
step_options_override: dex.StepOptions | None = None,
|
|
36
|
+
) -> QueryStep[StepInput, GetFunctionInput, FunctionDetails]:
|
|
37
|
+
if connection is None or connection.reference.name != connection_name:
|
|
38
|
+
raise ValueError("Amazon Lambda Step connection name must match its connection reference")
|
|
39
|
+
if isinstance(annotations, StepAnnotations):
|
|
40
|
+
step_annotations = annotations
|
|
41
|
+
else:
|
|
42
|
+
if not isinstance(annotations, Mapping) or set(annotations) != {"groupId", "groupLabel", "explanation"}:
|
|
43
|
+
raise ValueError("Amazon Lambda Step annotations require groupId, groupLabel, and explanation")
|
|
44
|
+
if any(not isinstance(value, str) for value in annotations.values()):
|
|
45
|
+
raise ValueError("Amazon Lambda Step annotations must be strings")
|
|
46
|
+
step_annotations = StepAnnotations(annotations["groupId"], annotations["groupLabel"], annotations["explanation"])
|
|
47
|
+
branches = {
|
|
48
|
+
"found": found,
|
|
49
|
+
}
|
|
50
|
+
if missing is not None:
|
|
51
|
+
branches["missing"] = missing
|
|
52
|
+
if provider_rejected is not None:
|
|
53
|
+
branches["providerRejected"] = provider_rejected
|
|
54
|
+
if invalid_response is not None:
|
|
55
|
+
branches["invalidResponse"] = invalid_response
|
|
56
|
+
if defect is not None:
|
|
57
|
+
branches["defect"] = defect
|
|
58
|
+
return QueryStep(
|
|
59
|
+
QueryStepConfig(
|
|
60
|
+
step_type=step_type,
|
|
61
|
+
step_input_type=step_input_type,
|
|
62
|
+
annotations=step_annotations,
|
|
63
|
+
operation=_bound_operation(connection, "get_function"),
|
|
64
|
+
connection=connection.reference,
|
|
65
|
+
map_to_operation_input=map_to_operation_input,
|
|
66
|
+
branches=branches,
|
|
67
|
+
result_attribute=result_attribute,
|
|
68
|
+
step_options_override=step_options_override,
|
|
69
|
+
)
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
setattr(new_get_function_step, '__module__', 'dex_connectors.amazon_lambda.steps')
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _bound_operation(connection: Connection, operation_name: str) -> Any:
|
|
76
|
+
source = getattr(connection, operation_name, None)
|
|
77
|
+
if source is None:
|
|
78
|
+
source = getattr(getattr(connection, "operations", None), operation_name, None)
|
|
79
|
+
if source is None:
|
|
80
|
+
raise ValueError(f"connection operation {operation_name} is missing")
|
|
81
|
+
return source() if callable(source) else source
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
# Copyright (c) 2026 Super Durable
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
"""Signed Amazon Lambda function reads with Go-compatible outcomes."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import re
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from datetime import UTC, datetime
|
|
12
|
+
|
|
13
|
+
import httpx
|
|
14
|
+
from dex_connectors.sdk import (
|
|
15
|
+
Call,
|
|
16
|
+
CredentialProvider,
|
|
17
|
+
Failure,
|
|
18
|
+
FailureKind,
|
|
19
|
+
QueryAttempt,
|
|
20
|
+
QueryDefinition,
|
|
21
|
+
Receipt,
|
|
22
|
+
)
|
|
23
|
+
from dex_connectors.sdk.providerhttp import (
|
|
24
|
+
BodyTooLargeError,
|
|
25
|
+
ProviderTransportError,
|
|
26
|
+
is_header_safe_credential,
|
|
27
|
+
new_provider_http_client,
|
|
28
|
+
parse_retry_after,
|
|
29
|
+
read_bounded_body,
|
|
30
|
+
send_traced,
|
|
31
|
+
validate_base_url,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
from ._generated.config import Config as Config
|
|
35
|
+
from ._generated.config import Credentials as Credentials
|
|
36
|
+
from ._generated.definitions import GET_FUNCTION_DEFINITION
|
|
37
|
+
from .models import FunctionDetails, GetFunctionInput
|
|
38
|
+
from .sigv4 import sign_headers
|
|
39
|
+
|
|
40
|
+
_FUNCTION_NAME = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
|
|
41
|
+
_REGION = re.compile(r"^[a-z]{2}(?:-gov)?-[a-z]+-[0-9]+$")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True, slots=True)
|
|
45
|
+
class _Exchange:
|
|
46
|
+
"""One bounded provider response or local failure."""
|
|
47
|
+
|
|
48
|
+
status: int = 0
|
|
49
|
+
body: bytes = b""
|
|
50
|
+
retry_after: float = 0
|
|
51
|
+
error: str = ""
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _failure(kind: FailureKind, message: str) -> Failure:
|
|
55
|
+
return Failure(kind, "amazon-lambda", "getFunction", message)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _branch(branch: str, kind: FailureKind, message: str) -> QueryAttempt[FunctionDetails]:
|
|
59
|
+
return QueryAttempt.branch_result(branch, FunctionDetails(), Receipt(), _failure(kind, message))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _retry(kind: FailureKind, message: str, delay: float = 0) -> QueryAttempt[FunctionDetails]:
|
|
63
|
+
return QueryAttempt.retry(_failure(kind, message), delay)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class Client:
|
|
67
|
+
"""Resolve AWS credentials and sign each GetFunction request."""
|
|
68
|
+
|
|
69
|
+
def __init__(
|
|
70
|
+
self,
|
|
71
|
+
config: Config,
|
|
72
|
+
credentials: CredentialProvider[Credentials],
|
|
73
|
+
http_client: httpx.AsyncClient | None = None,
|
|
74
|
+
now: Callable[[], datetime] | None = None,
|
|
75
|
+
) -> None:
|
|
76
|
+
if config is None or credentials is None:
|
|
77
|
+
raise ValueError("Lambda configuration and credential source are required")
|
|
78
|
+
if (
|
|
79
|
+
not _REGION.fullmatch(config.region)
|
|
80
|
+
or config.timeout_seconds <= 0
|
|
81
|
+
or config.max_response_bytes < 1
|
|
82
|
+
):
|
|
83
|
+
raise ValueError("Lambda Region or request limits are invalid")
|
|
84
|
+
endpoint = config.endpoint or f"https://lambda.{config.region}.amazonaws.com"
|
|
85
|
+
self.endpoint = validate_base_url(endpoint).rstrip("/")
|
|
86
|
+
self.region = config.region
|
|
87
|
+
self.max_response_bytes = config.max_response_bytes
|
|
88
|
+
self.credentials = credentials
|
|
89
|
+
self.http_client = http_client or new_provider_http_client(config.timeout_seconds)
|
|
90
|
+
self._owns_client = http_client is None
|
|
91
|
+
self.now = now or (lambda: datetime.now(UTC))
|
|
92
|
+
|
|
93
|
+
def get_function(self) -> GetFunctionOperation:
|
|
94
|
+
"""Bind the getFunction Query to this client."""
|
|
95
|
+
return GetFunctionOperation(self)
|
|
96
|
+
|
|
97
|
+
async def aclose(self) -> None:
|
|
98
|
+
"""Close an owned transport after Worker shutdown."""
|
|
99
|
+
if self._owns_client:
|
|
100
|
+
await self.http_client.aclose()
|
|
101
|
+
|
|
102
|
+
async def _get_function(self, call: Call, name: str) -> _Exchange:
|
|
103
|
+
try:
|
|
104
|
+
credentials = await self.credentials.resolve(call)
|
|
105
|
+
access_key = credentials.access_key_id.reveal()
|
|
106
|
+
secret_key = credentials.secret_access_key.reveal()
|
|
107
|
+
session_token = credentials.session_token.reveal()
|
|
108
|
+
except (ValueError, LookupError, OSError, AttributeError):
|
|
109
|
+
return _Exchange(error="credential")
|
|
110
|
+
if not all((is_header_safe_credential(access_key), is_header_safe_credential(secret_key))) or (
|
|
111
|
+
session_token and not is_header_safe_credential(session_token)
|
|
112
|
+
):
|
|
113
|
+
return _Exchange(error="credential")
|
|
114
|
+
url = self.endpoint + "/2015-03-31/functions/" + name
|
|
115
|
+
headers = sign_headers(
|
|
116
|
+
method="GET",
|
|
117
|
+
url=url,
|
|
118
|
+
headers={},
|
|
119
|
+
body=b"",
|
|
120
|
+
access_key_id=access_key,
|
|
121
|
+
secret_access_key=secret_key,
|
|
122
|
+
session_token=session_token,
|
|
123
|
+
region=self.region,
|
|
124
|
+
service="lambda",
|
|
125
|
+
signing_time=self.now(),
|
|
126
|
+
)
|
|
127
|
+
try:
|
|
128
|
+
request = self.http_client.build_request("GET", url, headers=headers)
|
|
129
|
+
response, _ = await send_traced(self.http_client, request)
|
|
130
|
+
except (ProviderTransportError, httpx.HTTPError, ValueError):
|
|
131
|
+
return _Exchange(error="request")
|
|
132
|
+
try:
|
|
133
|
+
retry_after = parse_retry_after(response.headers.get("Retry-After", ""), self.now())
|
|
134
|
+
try:
|
|
135
|
+
body = await read_bounded_body(response, self.max_response_bytes)
|
|
136
|
+
except BodyTooLargeError:
|
|
137
|
+
return _Exchange(status=response.status_code, retry_after=retry_after, error="too_large")
|
|
138
|
+
except ProviderTransportError:
|
|
139
|
+
return _Exchange(status=response.status_code, retry_after=retry_after, error="interrupted")
|
|
140
|
+
if any(secret.encode() in body for secret in (access_key, secret_key, session_token) if secret):
|
|
141
|
+
return _Exchange(status=response.status_code, retry_after=retry_after, error="credential")
|
|
142
|
+
return _Exchange(status=response.status_code, body=body, retry_after=retry_after)
|
|
143
|
+
finally:
|
|
144
|
+
await response.aclose()
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class GetFunctionOperation:
|
|
148
|
+
"""Read one Lambda function's name and ARN."""
|
|
149
|
+
|
|
150
|
+
def __init__(self, client: Client) -> None:
|
|
151
|
+
self.client = client
|
|
152
|
+
|
|
153
|
+
def definition(self) -> QueryDefinition:
|
|
154
|
+
"""Return the generated Query contract."""
|
|
155
|
+
return GET_FUNCTION_DEFINITION
|
|
156
|
+
|
|
157
|
+
async def invoke(self, call: Call, input: GetFunctionInput) -> QueryAttempt[FunctionDetails]:
|
|
158
|
+
"""Classify signed provider outcomes and bounded metadata."""
|
|
159
|
+
if not isinstance(input, GetFunctionInput) or not _FUNCTION_NAME.fullmatch(input.function_name):
|
|
160
|
+
return _branch("defect", FailureKind.VALIDATION, "Lambda function name is invalid")
|
|
161
|
+
exchange = await self.client._get_function(call, input.function_name)
|
|
162
|
+
if exchange.error == "credential":
|
|
163
|
+
return _branch(
|
|
164
|
+
"defect", FailureKind.AUTHENTICATION, "Lambda credentials are unavailable or invalid"
|
|
165
|
+
)
|
|
166
|
+
if exchange.error == "request":
|
|
167
|
+
return _retry(FailureKind.TRANSPORT, "Lambda request failed")
|
|
168
|
+
if exchange.status == 429:
|
|
169
|
+
return _retry(FailureKind.RATE_LIMIT, "Lambda rate limited the request", exchange.retry_after)
|
|
170
|
+
if exchange.status == 408 or exchange.status >= 500:
|
|
171
|
+
return _retry(FailureKind.AVAILABILITY, "Lambda is temporarily unavailable", exchange.retry_after)
|
|
172
|
+
if exchange.status == 404:
|
|
173
|
+
return QueryAttempt.branch_result("missing", FunctionDetails(), Receipt())
|
|
174
|
+
if exchange.status != 200:
|
|
175
|
+
return _branch(
|
|
176
|
+
"providerRejected", FailureKind.PROVIDER_REJECTION, f"Lambda rejected HTTP {exchange.status}"
|
|
177
|
+
)
|
|
178
|
+
if exchange.error == "too_large":
|
|
179
|
+
return _branch(
|
|
180
|
+
"invalidResponse",
|
|
181
|
+
FailureKind.RESPONSE_TOO_LARGE,
|
|
182
|
+
"Lambda response exceeded the configured limit",
|
|
183
|
+
)
|
|
184
|
+
if exchange.error:
|
|
185
|
+
return _retry(FailureKind.TRANSPORT, "Lambda response was interrupted")
|
|
186
|
+
try:
|
|
187
|
+
document = json.loads(exchange.body)
|
|
188
|
+
except (ValueError, UnicodeDecodeError):
|
|
189
|
+
return _branch("invalidResponse", FailureKind.PROTOCOL, "Lambda returned invalid function JSON")
|
|
190
|
+
if not isinstance(document, dict) or not isinstance(document.get("Configuration"), dict):
|
|
191
|
+
return _branch("invalidResponse", FailureKind.PROTOCOL, "Lambda returned invalid function JSON")
|
|
192
|
+
configuration = document["Configuration"]
|
|
193
|
+
name = configuration.get("FunctionName")
|
|
194
|
+
arn = configuration.get("FunctionArn")
|
|
195
|
+
if name != input.function_name or not isinstance(arn, str) or not arn:
|
|
196
|
+
return _branch("invalidResponse", FailureKind.PROTOCOL, "Lambda returned invalid function JSON")
|
|
197
|
+
return QueryAttempt.branch_result("found", FunctionDetails(name, arn), Receipt())
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# Copyright (c) 2026 Super Durable
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
"""Amazon Lambda connection and project credential binding."""
|
|
4
|
+
|
|
5
|
+
from ._generated.connection import Connection as Connection
|
|
6
|
+
from ._generated.connection import new_connection as new_connection
|
|
7
|
+
from ._generated.connection import new_connection_with_operations as new_connection_with_operations
|
|
8
|
+
from ._generated.connection import new_project_connection as new_project_connection
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
{
|
|
2
|
+
"connectorId": "amazon-lambda",
|
|
3
|
+
"releaseTag": "connectors/amazon/lambda/go/v0.1.0",
|
|
4
|
+
"package": {
|
|
5
|
+
"ecosystem": "pypi",
|
|
6
|
+
"name": "dex-connector-amazon-lambda",
|
|
7
|
+
"version": "0.1.0"
|
|
8
|
+
},
|
|
9
|
+
"factories": [
|
|
10
|
+
{
|
|
11
|
+
"name": "new_get_function_step",
|
|
12
|
+
"kind": "query",
|
|
13
|
+
"operationId": "getFunction",
|
|
14
|
+
"inputType": "GetFunctionInput",
|
|
15
|
+
"description": "Read the function name and ARN from AWS Lambda GetFunction.",
|
|
16
|
+
"fields": {
|
|
17
|
+
"stepType": "step_type",
|
|
18
|
+
"annotations": "annotations",
|
|
19
|
+
"connectionName": "connection_name",
|
|
20
|
+
"resultAttribute": "result_attribute"
|
|
21
|
+
},
|
|
22
|
+
"branches": [
|
|
23
|
+
{
|
|
24
|
+
"id": "found",
|
|
25
|
+
"field": "found",
|
|
26
|
+
"optional": false
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
"id": "missing",
|
|
30
|
+
"field": "missing",
|
|
31
|
+
"optional": true
|
|
32
|
+
},
|
|
33
|
+
{
|
|
34
|
+
"id": "providerRejected",
|
|
35
|
+
"field": "provider_rejected",
|
|
36
|
+
"optional": true
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
"id": "invalidResponse",
|
|
40
|
+
"field": "invalid_response",
|
|
41
|
+
"optional": true
|
|
42
|
+
},
|
|
43
|
+
{
|
|
44
|
+
"id": "defect",
|
|
45
|
+
"field": "defect",
|
|
46
|
+
"optional": true
|
|
47
|
+
}
|
|
48
|
+
],
|
|
49
|
+
"inputSchema": {
|
|
50
|
+
"additionalProperties": false,
|
|
51
|
+
"description": "GetFunctionInput identifies one Lambda function in the configured Region.",
|
|
52
|
+
"properties": {
|
|
53
|
+
"functionName": {
|
|
54
|
+
"type": "string"
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
"required": [
|
|
58
|
+
"functionName"
|
|
59
|
+
],
|
|
60
|
+
"type": "object"
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
]
|
|
64
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# Copyright (c) 2026 Super Durable
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
"""Public Amazon Lambda models generated from the Go contract."""
|
|
4
|
+
|
|
5
|
+
from ._generated.config import Config as Config
|
|
6
|
+
from ._generated.config import Credentials as Credentials
|
|
7
|
+
from ._generated.models import FunctionDetails as FunctionDetails
|
|
8
|
+
from ._generated.models import GetFunctionInput as GetFunctionInput
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# Copyright (c) 2026 Super Durable
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
"""AWS Signature Version 4 header signing for Lambda REST requests."""
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import hmac
|
|
7
|
+
from datetime import UTC, datetime
|
|
8
|
+
from urllib.parse import quote, urlsplit
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
_ALGORITHM = "AWS4-HMAC-SHA256"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def sign_headers(
|
|
16
|
+
*,
|
|
17
|
+
method: str,
|
|
18
|
+
url: str,
|
|
19
|
+
headers: dict[str, str],
|
|
20
|
+
body: bytes,
|
|
21
|
+
access_key_id: str,
|
|
22
|
+
secret_access_key: str,
|
|
23
|
+
session_token: str,
|
|
24
|
+
region: str,
|
|
25
|
+
service: str,
|
|
26
|
+
signing_time: datetime,
|
|
27
|
+
) -> dict[str, str]:
|
|
28
|
+
"""Return headers plus X-Amz-Date, any session token, and the Authorization header.
|
|
29
|
+
|
|
30
|
+
Every supplied header, the host, and a nonzero content length are signed, matching the
|
|
31
|
+
canonical request the AWS Go SDK signer builds for the same request.
|
|
32
|
+
"""
|
|
33
|
+
parsed = urlsplit(url)
|
|
34
|
+
amz_date = signing_time.astimezone(UTC).strftime("%Y%m%dT%H%M%SZ")
|
|
35
|
+
scope_date = amz_date[:8]
|
|
36
|
+
signed = dict(headers)
|
|
37
|
+
signed["X-Amz-Date"] = amz_date
|
|
38
|
+
if session_token:
|
|
39
|
+
signed["X-Amz-Security-Token"] = session_token
|
|
40
|
+
canonical = {name.lower(): " ".join(value.strip().split()) for name, value in signed.items()}
|
|
41
|
+
canonical["host"] = httpx.URL(url).netloc.decode()
|
|
42
|
+
if body:
|
|
43
|
+
canonical["content-length"] = str(len(body))
|
|
44
|
+
signed_header_names = ";".join(sorted(canonical))
|
|
45
|
+
canonical_headers = "".join(f"{name}:{canonical[name]}\n" for name in sorted(canonical))
|
|
46
|
+
canonical_request = "\n".join(
|
|
47
|
+
(
|
|
48
|
+
method,
|
|
49
|
+
quote(parsed.path or "/", safe="/-_.~"),
|
|
50
|
+
_canonical_query(parsed.query),
|
|
51
|
+
canonical_headers,
|
|
52
|
+
signed_header_names,
|
|
53
|
+
hashlib.sha256(body).hexdigest(),
|
|
54
|
+
)
|
|
55
|
+
)
|
|
56
|
+
scope = f"{scope_date}/{region}/{service}/aws4_request"
|
|
57
|
+
string_to_sign = "\n".join(
|
|
58
|
+
(_ALGORITHM, amz_date, scope, hashlib.sha256(canonical_request.encode()).hexdigest())
|
|
59
|
+
)
|
|
60
|
+
key = _hmac(("AWS4" + secret_access_key).encode(), scope_date)
|
|
61
|
+
for part in (region, service, "aws4_request"):
|
|
62
|
+
key = _hmac(key, part)
|
|
63
|
+
signature = hmac.new(key, string_to_sign.encode(), hashlib.sha256).hexdigest()
|
|
64
|
+
signed["Authorization"] = (
|
|
65
|
+
f"{_ALGORITHM} Credential={access_key_id}/{scope}, SignedHeaders={signed_header_names}, "
|
|
66
|
+
f"Signature={signature}"
|
|
67
|
+
)
|
|
68
|
+
return signed
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _hmac(key: bytes, message: str) -> bytes:
|
|
72
|
+
return hmac.new(key, message.encode(), hashlib.sha256).digest()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _canonical_query(query: str) -> str:
|
|
76
|
+
if not query:
|
|
77
|
+
return ""
|
|
78
|
+
pairs = []
|
|
79
|
+
for item in query.split("&"):
|
|
80
|
+
name, _, value = item.partition("=")
|
|
81
|
+
pairs.append((quote(name, safe="-_.~"), quote(value, safe="-_.~")))
|
|
82
|
+
return "&".join(f"{name}={value}" for name, value in sorted(pairs))
|