Skip to content

Conversation

@oto-macenauer-absa
Copy link
Collaborator

@oto-macenauer-absa oto-macenauer-absa commented Sep 12, 2025

This pull request enhances the robustness and reliability of the src/event_gate_lambda.py module by improving error handling during imports and the initialization of the token public key. The changes ensure that failures are caught early and reported explicitly, which will help with debugging and stability.

Improvements to import handling:

  • Added explicit import for UnsupportedAlgorithm from cryptography.exceptions with a fallback to prevent crashes if the import fails.
  • Modified the import of writer modules (writer_eventbridge, writer_kafka, writer_postgres) to use a try/except block, providing a fallback for environments where relative imports may fail.

Enhancements to token public key initialization:

  • Wrapped the HTTP request and deserialization logic for fetching the token public key in a try/except block to catch network, decoding, and cryptography errors. If initialization fails, an explicit error is logged and a RuntimeError is raised.

Release notes:

  • Fix module imports

Summary by CodeRabbit

  • Bug Fixes

    • Improved reliability when fetching and loading token public keys, with clearer logged errors and a raised error on failure.
    • Prevented startup issues by ensuring the database writer is initialized during startup.
    • More resilient handling of network, decoding, and key-deserialization errors to avoid intermittent crashes.
  • Chores

    • Hardened imports and initialization to work consistently across environments.
    • Expanded logging to make failure points easier to diagnose.
    • Minor comment updates reflecting the more robust key retrieval flow.

@coderabbitai
Copy link

coderabbitai bot commented Sep 12, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

Adds guarded imports for cryptography exceptions and writer modules, hardens token public key retrieval/deserialization with expanded exception handling and logging, raises RuntimeError on failure, and ensures writer_postgres.init(logger) is called during startup. Minor comment updates.

Changes

Cohort / File(s) Summary of Changes
Startup hardening and error handling
src/event_gate_lambda.py
Guarded import of UnsupportedAlgorithm (fallback to Exception); resilient imports for writer_eventbridge, writer_kafka, and writer_postgres to handle package/non-package contexts; token public key GET/base64/DER deserialization wrapped in try/except catching requests.RequestException, ValueError, KeyError, and UnsupportedAlgorithm; logs failures with logger.exception and raises RuntimeError on init failure; calls writer_postgres.init(logger) during startup; small comment updates.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor AWS as AWS Lambda
  participant EG as event_gate_lambda
  participant WR as writer_postgres
  participant HT as Token Key HTTP Endpoint
  participant CR as CryptographyLib

  AWS->>EG: Cold start / import
  EG->>EG: Guarded imports (UnsupportedAlgorithm, writers)
  EG->>HT: GET /token-public-key
  alt Success
    HT-->>EG: Base64-encoded key
    EG->>CR: base64 decode + load_der_public_key
    CR-->>EG: Public key
    EG->>WR: init(logger)
    WR-->>EG: Initialized
    EG-->>AWS: Ready
  else Failure (requests/ValueError/KeyError/UnsupportedAlgorithm)
    HT-->>EG: Error or invalid data
    EG->>EG: logger.exception(...) / log error
    EG-->>AWS: Raise RuntimeError
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • Zejnilovic
  • ABMC831
  • petr-pokorny-absa

Poem

I thump my paw at startup’s gate,
I fetch the key and test our fate.
If bytes go skew, I mark the trail,
Logs whisper why the hop grew frail.
Postgres warmed — I wiggle, celebrate. 🐇✨

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0876699 and b2dac9d.

📒 Files selected for processing (1)
  • src/event_gate_lambda.py (2 hunks)
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch bugfix/module-import

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4e5b95f and 0876699.

📒 Files selected for processing (1)
  • src/event_gate_lambda.py (2 hunks)
🧰 Additional context used
🪛 Ruff (0.12.2)
src/event_gate_lambda.py

36-36: Do not catch blind exception: Exception

(BLE001)


101-101: Probable use of requests call with verify=False disabling SSL certificate checks

(S501)


112-112: Avoid specifying long messages outside the exception class

(TRY003)

🪛 GitHub Actions: Build and Test
src/event_gate_lambda.py

[error] 1-1: Command 'black --check $(git ls-files '*.py')' failed: 1 file would be reformatted.

🔇 Additional comments (2)
src/event_gate_lambda.py (2)

39-44: Guarded writer imports look good.

The relative→absolute import fallback is appropriate for both package and ad-hoc execution contexts.


1-1: CI: Black failing — run Black locally and commit formatted code.

CI reports Black formatting errors for src/event_gate_lambda.py. My verification run couldn't execute black (installed to ~/.local/bin, not on PATH). Run locally and commit the result:

python -m pip install --user black ruff
python -m black src/event_gate_lambda.py
python -m ruff check src/event_gate_lambda.py

Comment on lines +33 to +37
# Added explicit import for serialization-related exceptions
try: # pragma: no cover - import guard
from cryptography.exceptions import UnsupportedAlgorithm # type: ignore
except Exception: # pragma: no cover - very defensive
UnsupportedAlgorithm = Exception # type: ignore
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Don't alias UnsupportedAlgorithm to Exception — it turns the later except into a catch‑all.

If the import fails, UnsupportedAlgorithm = Exception makes except (..., UnsupportedAlgorithm) equivalent to except Exception, hiding unrelated bugs. Catch only ImportError and provide a narrow fallback type.

Apply:

-try:  # pragma: no cover - import guard
-    from cryptography.exceptions import UnsupportedAlgorithm  # type: ignore
-except Exception:  # pragma: no cover - very defensive
-    UnsupportedAlgorithm = Exception  # type: ignore
+try:  # pragma: no cover - import guard
+    from cryptography.exceptions import UnsupportedAlgorithm  # type: ignore
+except ImportError:  # pragma: no cover - only missing dependency
+    class UnsupportedAlgorithm(Exception):  # narrow fallback; avoids catch-all later
+        pass
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# Added explicit import for serialization-related exceptions
try: # pragma: no cover - import guard
from cryptography.exceptions import UnsupportedAlgorithm # type: ignore
except Exception: # pragma: no cover - very defensive
UnsupportedAlgorithm = Exception # type: ignore
# Added explicit import for serialization-related exceptions
try: # pragma: no cover - import guard
from cryptography.exceptions import UnsupportedAlgorithm # type: ignore
except ImportError: # pragma: no cover - only missing dependency
class UnsupportedAlgorithm(Exception): # narrow fallback; avoids catch-all later
pass
🧰 Tools
🪛 Ruff (0.12.2)

36-36: Do not catch blind exception: Exception

(BLE001)

🤖 Prompt for AI Agents
In src/event_gate_lambda.py around lines 33 to 37, the current blanket except
and alias UnsupportedAlgorithm = Exception makes later except (...,
UnsupportedAlgorithm) behave like a catch‑all; change the import guard to only
catch ImportError (not Exception) and, if the import fails, define a narrow
fallback exception type (e.g. a small subclass of Exception named
UnsupportedAlgorithm) so downstream except clauses only match that specific type
rather than all exceptions.

Comment on lines 98 to 112
# Add timeout to avoid hanging requests; wrap in robust error handling so failures are explicit
try:
response_json = requests.get(
CONFIG["token_public_key_url"], verify=False, timeout=5
).json() # nosec external
token_public_key_encoded = response_json["key"]
TOKEN_PUBLIC_KEY: Any = serialization.load_der_public_key(
base64.b64decode(token_public_key_encoded)
)
logger.debug("Loaded TOKEN_PUBLIC_KEY")
except (requests.RequestException, ValueError, KeyError, UnsupportedAlgorithm) as exc:
logger.exception(
"Failed to fetch or deserialize token public key from %s", CONFIG.get("token_public_key_url")
)
raise RuntimeError("Token public key initialization failed") from exc
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Harden the HTTP path further: raise on non-2xx and catch TypeError. Optionally avoid verify=False.

Raise on bad status before attempting JSON; include TypeError for non-string/bytes base64 inputs. Consider making TLS verification configurable instead of permanently disabled (S501).

Apply:

-try:
-    response_json = requests.get(
-        CONFIG["token_public_key_url"], verify=False, timeout=5
-    ).json()  # nosec external
-    token_public_key_encoded = response_json["key"]
-    TOKEN_PUBLIC_KEY: Any = serialization.load_der_public_key(
-        base64.b64decode(token_public_key_encoded)
-    )
-    logger.debug("Loaded TOKEN_PUBLIC_KEY")
-except (requests.RequestException, ValueError, KeyError, UnsupportedAlgorithm) as exc:
+try:
+    url = CONFIG["token_public_key_url"]
+    resp = requests.get(url, verify=False, timeout=(3, 5))  # nosec external
+    resp.raise_for_status()
+    response_json = resp.json()
+    token_public_key_encoded = response_json["key"]
+    TOKEN_PUBLIC_KEY: Any = serialization.load_der_public_key(
+        base64.b64decode(token_public_key_encoded)
+    )
+    logger.debug("Loaded TOKEN_PUBLIC_KEY")
+except (requests.RequestException, ValueError, KeyError, TypeError, UnsupportedAlgorithm) as exc:
     logger.exception(
-        "Failed to fetch or deserialize token public key from %s", CONFIG.get("token_public_key_url")
+        "Failed to fetch or deserialize token public key from %s", CONFIG.get("token_public_key_url")
     )
     raise RuntimeError("Token public key initialization failed") from exc

Optional follow-up (not in diff): make verification configurable, e.g., verify=CONFIG.get("token_public_key_verify_ssl", True).

🧰 Tools
🪛 Ruff (0.12.2)

101-101: Probable use of requests call with verify=False disabling SSL certificate checks

(S501)


112-112: Avoid specifying long messages outside the exception class

(TRY003)

🤖 Prompt for AI Agents
In src/event_gate_lambda.py around lines 98 to 112, the HTTP fetch should raise
on non-2xx responses and handle TypeError from base64 decoding, and TLS
verification should be configurable; modify the requests call to call
response.raise_for_status() (i.e., check status before .json()), add TypeError
to the except tuple alongside RequestException, ValueError, KeyError,
UnsupportedAlgorithm, and replace verify=False with a configurable flag (e.g.,
CONFIG.get("token_public_key_verify_ssl", True)) so TLS verification is not
permanently disabled.

@oto-macenauer-absa oto-macenauer-absa merged commit 1095a0b into master Sep 12, 2025
5 checks passed
@oto-macenauer-absa oto-macenauer-absa deleted the bugfix/module-import branch September 12, 2025 10:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants