mirror of
https://github.com/OpenBB-finance/OpenBB.git
synced 2026-11-25 18:53:26 +00:00
store key and auth_token as encrypted values
This commit is contained in:
@@ -65,7 +65,7 @@ async def websocket_endpoint( # noqa: PLR0915
|
||||
|
||||
if (
|
||||
broadcast_server.auth_token is not None
|
||||
and auth_token != broadcast_server.auth_token
|
||||
and auth_token != broadcast_server._decrypt_value(broadcast_server.auth_token)
|
||||
):
|
||||
await websocket.accept()
|
||||
await websocket.send_text(
|
||||
@@ -131,15 +131,33 @@ class BroadcastServer:
|
||||
sleep_time: float = 0.25,
|
||||
auth_token: Optional[str] = None,
|
||||
):
|
||||
# pylint: disable=import-outside-toplevel
|
||||
import os
|
||||
|
||||
self.results_file = results_file
|
||||
self.table_name = table_name
|
||||
self.logger = get_logger("openbb.websocket.broadcast_server")
|
||||
self.sleep_time = sleep_time
|
||||
self.auth_token = auth_token
|
||||
self._app = app
|
||||
self._key = os.urandom(32)
|
||||
self._iv = os.urandom(16)
|
||||
self.auth_token = self._encrypt_value(auth_token) if auth_token else None
|
||||
self.websocket = None
|
||||
|
||||
def _encrypt_value(self, value: str) -> str:
|
||||
"""Encrypt the value for storage."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
from openbb_websockets.helpers import encrypt_value
|
||||
|
||||
return encrypt_value(self._key, self._iv, value)
|
||||
|
||||
def _decrypt_value(self, value: str) -> str:
|
||||
"""Decrypt the value for use."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
from openbb_websockets.helpers import decrypt_value
|
||||
|
||||
return decrypt_value(self._key, self._iv, value)
|
||||
|
||||
async def stream_results(self): # noqa: PLR0915
|
||||
"""Continuously read the database and send new messages as JSON via WebSocket."""
|
||||
import sqlite3 # noqa
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
# pylint: disable=too-many-statements
|
||||
# flake8: noqa: PLR0915
|
||||
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Any, Literal, Optional, Union
|
||||
|
||||
@@ -96,6 +97,7 @@ class WebSocketClient:
|
||||
# pylint: disable=import-outside-toplevel
|
||||
import asyncio # noqa
|
||||
import atexit
|
||||
import os
|
||||
import tempfile
|
||||
import threading
|
||||
from aiosqlite import DatabaseError
|
||||
@@ -110,13 +112,20 @@ class WebSocketClient:
|
||||
self.table_name = table_name if table_name else "records"
|
||||
self._limit = limit
|
||||
self.data_model = data_model
|
||||
self._auth_token = auth_token
|
||||
self._symbol = symbol
|
||||
self._kwargs = (
|
||||
[f"{k}={str(v).strip().replace(' ', '_')}" for k, v in kwargs.items()]
|
||||
if kwargs
|
||||
else None
|
||||
)
|
||||
self._key = os.urandom(32)
|
||||
self._iv = os.urandom(16)
|
||||
self._auth_token = self._encrypt_value(auth_token) if auth_token else None
|
||||
# strings in kwargs are encrypted before storing in the class but unencrypted when passed to the provider module.
|
||||
if kwargs:
|
||||
for k, v in kwargs.items():
|
||||
if isinstance(v, str):
|
||||
encrypted_value = self._encrypt_value(v)
|
||||
kwargs[k] = encrypted_value
|
||||
else:
|
||||
kwargs[k] = v
|
||||
|
||||
self._kwargs = kwargs if kwargs else {}
|
||||
|
||||
self._process: Any = None
|
||||
self._psutil_process: Any = None
|
||||
@@ -153,6 +162,20 @@ class WebSocketClient:
|
||||
self.logger.error(msg)
|
||||
self._exception = OpenBBError(msg)
|
||||
|
||||
def _encrypt_value(self, value):
|
||||
"""Encrypt a value before storing."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
from openbb_websockets.helpers import encrypt_value
|
||||
|
||||
return encrypt_value(self._key, self._iv, value)
|
||||
|
||||
def _decrypt_value(self, encrypted_value):
|
||||
"""Decrypt the value for use."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
from openbb_websockets.helpers import decrypt_value
|
||||
|
||||
return decrypt_value(self._key, self._iv, encrypted_value)
|
||||
|
||||
def _atexit(self) -> None:
|
||||
"""Clean up the WebSocket client processes at exit."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
@@ -349,8 +372,23 @@ class WebSocketClient:
|
||||
if self.limit:
|
||||
command.extend([f"limit={self.limit}"])
|
||||
|
||||
if self._kwargs:
|
||||
for kwarg in self._kwargs:
|
||||
kwargs = self._kwargs.copy()
|
||||
|
||||
if kwargs:
|
||||
for k, v in kwargs.items():
|
||||
if isinstance(v, str):
|
||||
unencrypted_value = self._decrypt_value(v)
|
||||
kwargs[k] = unencrypted_value
|
||||
else:
|
||||
kwargs[k] = v
|
||||
|
||||
_kwargs = (
|
||||
[f"{k}={str(v).strip().replace(' ', '_')}" for k, v in kwargs.items()]
|
||||
if kwargs
|
||||
else None
|
||||
)
|
||||
|
||||
for kwarg in _kwargs:
|
||||
if kwarg not in command:
|
||||
command.extend([kwarg])
|
||||
|
||||
@@ -566,6 +604,10 @@ class WebSocketClient:
|
||||
else None
|
||||
)
|
||||
|
||||
def _get_auth_token(self):
|
||||
"""Get the authentication token."""
|
||||
return self._decrypt_value(self._auth_token) if self._auth_token else None
|
||||
|
||||
def start_broadcasting(
|
||||
self,
|
||||
host: str = "127.0.0.1",
|
||||
@@ -605,7 +647,7 @@ class WebSocketClient:
|
||||
f"port={open_port}",
|
||||
f"results_file={self.results_file}",
|
||||
f"table_name={self.table_name}",
|
||||
f"auth_token={self._auth_token}",
|
||||
f"auth_token={self._get_auth_token()}",
|
||||
]
|
||||
if kwargs:
|
||||
for kwarg in kwargs:
|
||||
|
||||
@@ -73,6 +73,36 @@ async def get_status(name: Optional[str] = None, client: Optional[Any] = None) -
|
||||
return status
|
||||
|
||||
|
||||
def encrypt_value(key, iv, value):
|
||||
"""Encrypt a value before storing."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
import base64 # noqa
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
||||
|
||||
backend = default_backend()
|
||||
cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=backend)
|
||||
encryptor = cipher.encryptor()
|
||||
encrypted_value = encryptor.update(value.encode()) + encryptor.finalize()
|
||||
return base64.b64encode(encrypted_value).decode()
|
||||
|
||||
|
||||
def decrypt_value(key, iv, encrypted_value):
|
||||
"""Decrypt the value for use."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
import base64 # noqa
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
||||
|
||||
backend = default_backend()
|
||||
cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=backend)
|
||||
decryptor = cipher.decryptor()
|
||||
decrypted_value = (
|
||||
decryptor.update(base64.b64decode(encrypted_value)) + decryptor.finalize()
|
||||
)
|
||||
return decrypted_value.decode()
|
||||
|
||||
|
||||
async def check_auth(name: str, auth_token: Optional[str] = None) -> bool:
|
||||
"""Check the auth token."""
|
||||
if name not in connected_clients:
|
||||
@@ -82,7 +112,7 @@ async def check_auth(name: str, auth_token: Optional[str] = None) -> bool:
|
||||
return True
|
||||
if auth_token is None:
|
||||
raise UnauthorizedError(f"Client authorization token is required for {name}.")
|
||||
if auth_token != client._auth_token:
|
||||
if auth_token != client._get_auth_token():
|
||||
raise UnauthorizedError(f"Invalid client authorization token for {name}.")
|
||||
return True
|
||||
|
||||
|
||||
Reference in New Issue
Block a user