Skip to content

Commit 1095a0b

Browse files
Enhance error handling and import robustness in event_gate_lambda (#62)
* Enhance error handling and import robustness in event_gate_lambda * Fix formatting
1 parent 4e5b95f commit 1095a0b

File tree

1 file changed

+20
-6
lines changed

1 file changed

+20
-6
lines changed

src/event_gate_lambda.py

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,17 @@
3131
from jsonschema import validate
3232
from jsonschema.exceptions import ValidationError
3333

34-
from . import writer_eventbridge, writer_kafka, writer_postgres
34+
# Added explicit import for serialization-related exceptions
35+
try: # pragma: no cover - import guard
36+
from cryptography.exceptions import UnsupportedAlgorithm # type: ignore
37+
except Exception: # pragma: no cover - very defensive
38+
UnsupportedAlgorithm = Exception # type: ignore
39+
40+
# Import writer modules with explicit ImportError fallback
41+
try:
42+
from . import writer_eventbridge, writer_kafka, writer_postgres
43+
except ImportError: # fallback when executed outside package context
44+
import writer_eventbridge, writer_kafka, writer_postgres # type: ignore[no-redef]
3545

3646
# Import configuration directory symbols with explicit ImportError fallback
3747
try:
@@ -86,11 +96,15 @@
8696
logger.debug("Loaded ACCESS definitions")
8797

8898
TOKEN_PROVIDER_URL = CONFIG["token_provider_url"]
89-
# Add timeout to avoid hanging requests
90-
response_json = requests.get(CONFIG["token_public_key_url"], verify=False, timeout=5).json() # nosec external
91-
token_public_key_encoded = response_json["key"]
92-
TOKEN_PUBLIC_KEY: Any = serialization.load_der_public_key(base64.b64decode(token_public_key_encoded))
93-
logger.debug("Loaded TOKEN_PUBLIC_KEY")
99+
# Add timeout to avoid hanging requests; wrap in robust error handling so failures are explicit
100+
try:
101+
response_json = requests.get(CONFIG["token_public_key_url"], verify=False, timeout=5).json() # nosec external
102+
token_public_key_encoded = response_json["key"]
103+
TOKEN_PUBLIC_KEY: Any = serialization.load_der_public_key(base64.b64decode(token_public_key_encoded))
104+
logger.debug("Loaded TOKEN_PUBLIC_KEY")
105+
except (requests.RequestException, ValueError, KeyError, UnsupportedAlgorithm) as exc:
106+
logger.exception("Failed to fetch or deserialize token public key from %s", CONFIG.get("token_public_key_url"))
107+
raise RuntimeError("Token public key initialization failed") from exc
94108

95109
writer_eventbridge.init(logger, CONFIG)
96110
writer_kafka.init(logger, CONFIG)

0 commit comments

Comments
 (0)