langflow icon indicating copy to clipboard operation
langflow copied to clipboard

fix: add backward-compatible Fernet key rotation

Open ainaanraza opened this issue 5 months ago • 2 comments

Summary

This PR addresses the Fernet key derivation security issue previously discussed in #11681 while preserving backward compatibility for existing encrypted credentials.

Changes

  • Replaced insecure key derivation with a cryptographically secure implementation.
  • Added legacy key support for existing encrypted credentials.
  • Introduced MultiFernet-based key rotation.
  • Updated AuthService to use the centralized Fernet helper.
  • Added tests for deterministic key derivation, Fernet compatibility, and legacy ciphertext decryption.

Backward Compatibility

Existing ciphertexts encrypted with the legacy derivation method remain decryptable through MultiFernet fallback support.

New encryptions always use the primary secure key.

Legacy ciphertexts are not automatically re-encrypted. Rotation occurs through the existing migration workflow or when credentials are updated and saved.

Related Work

Related to #11681.

This implementation specifically addresses the breaking-change concern raised during review by introducing a backward-compatible migration strategy.

Security Impact

Removes reliance on insecure key derivation while avoiding data loss for existing deployments.

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced authentication security through improved encryption key generation methods and stronger cryptographic standards.
    • Fully restored backward compatibility, ensuring all previously encrypted authentication tokens and sensitive data remain fully accessible and functional without requiring any action.
  • Tests

    • Added comprehensive test coverage validating new encryption implementations and compatibility with legacy authentication data.

ainaanraza avatar Jun 14 '26 21:06 ainaanraza

Review Change Stack

[!IMPORTANT]

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 6651b301-e969-40d2-a103-6c6489087518

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • [ ] 🔍 Trigger review

Walkthrough

Fernet key derivation for short secrets is replaced with deterministic PBKDF2. A new get_legacy_fernet_key reproduces the prior PRNG-based key for backward-compatible decryption. get_fernet returns MultiFernet([primary, legacy]) for short secrets and a single Fernet for longer ones. AuthService._get_fernet now delegates entirely to get_fernet. Three unit tests cover determinism, key uniqueness, and legacy decryption.

Changes

PBKDF2 Key Derivation and Legacy Backward Compatibility

Layer / File(s) Summary
PBKDF2 derivation, legacy key, and MultiFernet in get_fernet
src/backend/base/langflow/services/auth/utils.py
ensure_fernet_key now derives a deterministic 32-byte key via PBKDF2 for secrets shorter than 32 characters. get_legacy_fernet_key reproduces the previous PRNG-based key format. get_fernet returns MultiFernet([Fernet(primary), Fernet(legacy)]) for short secrets and Fernet(primary) for longer ones. Imports gain hashlib and MultiFernet.
AuthService._get_fernet delegation
src/backend/base/langflow/services/auth/service.py
Adds MultiFernet to imports, removes direct ensure_fernet_key + Fernet construction, and replaces _get_fernet body with a single call to get_fernet(self.settings), widening the return type to Fernet | MultiFernet.
Unit tests for determinism and legacy decrypt
src/backend/tests/unit/services/auth/test_auth_service.py
Adds three tests: PBKDF2 output is deterministic and yields a valid 44-char Fernet key; different short secrets yield different keys; AuthService.decrypt_api_key decrypts ciphertext produced with get_legacy_fernet_key.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 7 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 58.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Test Quality And Coverage ⚠️ Warning Tests lack coverage for key encryption behavior validation. While tests cover legacy decryption backward compatibility and PBKDF2 determinism, they don't verify that MultiFernet encrypts with the n... Add test verifying that new encryptions with short keys produce different ciphertexts than legacy encryption, confirming the primary PBKDF2 key is used for encryption in MultiFernet. Additionally, address pending review issues: remove un...
✅ Passed checks (7 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix: add backward-compatible Fernet key rotation' accurately summarizes the main change in the PR, which is implementing secure Fernet key derivation with backward compatibility support through MultiFernet.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Test Coverage For New Implementations ✅ Passed PR includes 4 comprehensive unit tests in test_auth_service.py covering all new cryptographic functionality: PBKDF2 deterministic derivation, Fernet validity, key uniqueness, and legacy backward co...
Test File Naming And Structure ✅ Passed Test file follows correct patterns: test_*.py naming, proper pytest structure with fixtures, descriptive test function names, logical organization with comments/docstrings, covers positive/negative...
Excessive Mock Usage Warning ✅ Passed The three new tests use zero mocks and test real cryptographic behavior directly. No excessive mocking detected; tests verify actual key derivation, encryption/decryption, and backward compatibilit...

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • [ ] Create PR with unit tests

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.

coderabbitai[bot] avatar Jun 14 '26 21:06 coderabbitai[bot]

Addressed the review feedback in the latest commits:

  • Replaced global random.seed() usage with an isolated random.Random(secret_key) instance while preserving legacy key output.
  • Added explicit documentation around the backward-compatibility requirements for legacy Fernet key derivation.
  • Fixed Ruff and test lint issues (E402, S311, TC002, import ordering, unused parameters).
  • Centralized MINIMUM_KEY_LENGTH handling.
  • Clarified that MultiFernet provides backward-compatible decryption but does not automatically re-encrypt stored ciphertext.

All code-related checks are now passing.

This PR continues to focus on addressing the backward-compatibility and key rotation concerns raised during the review of #11681.

The remaining autofix.ci / Update Component Index failure appears to be related to the workflow attempting to merge origin/release-1.11.0 and does not seem to be caused by the Fernet changes introduced in this PR.

ainaanraza avatar Jun 19 '26 10:06 ainaanraza