Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Refactor authentication key generation #2443

Merged
merged 3 commits into from
Jul 1, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 17 additions & 7 deletions src/backend/base/langflow/services/auth/utils.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import base64
import random
import warnings
from datetime import datetime, timedelta, timezone
from typing import Annotated, Coroutine, Optional, Union
Expand Down Expand Up @@ -330,17 +332,25 @@ def authenticate_user(username: str, password: str, db: Session = Depends(get_se
return user if verify_password(password, user.password) else None


def add_padding(s):
# Calculate the number of padding characters needed
padding_needed = 4 - len(s) % 4
return s + "=" * padding_needed
def ensure_valid_key(s: str) -> bytes:
# If the key is too short, we'll use it as a seed to generate a valid key
if len(s) < 32:
# Use the input as a seed for the random number generator
random.seed(s)
# Generate 32 random bytes
key = bytes(random.getrandbits(8) for _ in range(32))
else:
# If the key is long enough, use the first 32 bytes
key = s[:32].encode()

# Ensure the key is URL-safe base64-encoded
return base64.urlsafe_b64encode(key)


def get_fernet(settings_service=Depends(get_settings_service)):
SECRET_KEY = settings_service.auth_settings.SECRET_KEY.get_secret_value()
# It's important that your secret key is 32 url-safe base64-encoded byte
padded_secret_key = add_padding(SECRET_KEY)
fernet = Fernet(padded_secret_key)
valid_key = ensure_valid_key(SECRET_KEY)
fernet = Fernet(valid_key)
return fernet


Expand Down