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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

馃敀 API Key Encryption #1160

Merged
merged 2 commits into from
Jul 29, 2023
Merged
Show file tree
Hide file tree
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
7 changes: 3 additions & 4 deletions next/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -108,10 +108,9 @@ model OAuthCredentials {
redirect_uri String

// Post install
token_type String?
access_token String?
scope String?
data Json?
token_type String?
access_token_enc String?
scope String?

create_date DateTime @default(now())
update_date DateTime? @updatedAt
Expand Down
9 changes: 5 additions & 4 deletions platform/reworkd_platform/db/crud/oauth.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ async def get_installation_by_user_id(
query = select(OauthCredentials).filter(
OauthCredentials.user_id == user_id,
OauthCredentials.provider == provider,
OauthCredentials.access_token.isnot(None),
OauthCredentials.access_token_enc.isnot(None),
)

return (await self.session.execute(query)).scalars().first()
Expand All @@ -52,7 +52,7 @@ async def get_installation_by_organization_id(
query = select(OauthCredentials).filter(
OauthCredentials.organization_id == organization_id,
OauthCredentials.provider == provider,
OauthCredentials.access_token.isnot(None),
OauthCredentials.access_token_enc.isnot(None),
OauthCredentials.organization_id.isnot(None),
)

Expand All @@ -61,10 +61,11 @@ async def get_installation_by_organization_id(
async def get_all(self, user: UserBase) -> Dict[str, str]:
query = (
select(
OauthCredentials.provider, func.any_value(OauthCredentials.access_token)
OauthCredentials.provider,
func.any_value(OauthCredentials.access_token_enc),
)
.filter(
OauthCredentials.access_token.isnot(None),
OauthCredentials.access_token_enc.isnot(None),
OauthCredentials.organization_id == user.organization_id,
)
.group_by(OauthCredentials.provider)
Expand Down
5 changes: 2 additions & 3 deletions platform/reworkd_platform/db/models/auth.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from sqlalchemy import String, JSON
from sqlalchemy import String
from sqlalchemy.orm import mapped_column

from reworkd_platform.db.base import TrackedModel
Expand Down Expand Up @@ -30,6 +30,5 @@ class OauthCredentials(TrackedModel):

# Post-installation
token_type = mapped_column(String, nullable=True)
access_token = mapped_column(String, nullable=True)
access_token_enc = mapped_column(String, nullable=True)
scope = mapped_column(String, nullable=True)
data = mapped_column(JSON, nullable=True)
22 changes: 12 additions & 10 deletions platform/reworkd_platform/services/oauth_installers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
# from slack.web import WebClient
from abc import ABC, abstractmethod
from typing import TypeVar

from fastapi import Depends, Path
from slack_sdk import WebClient
Expand All @@ -9,11 +8,10 @@
from reworkd_platform.db.crud.oauth import OAuthCrud
from reworkd_platform.db.models.auth import OauthCredentials
from reworkd_platform.schemas import UserBase
from reworkd_platform.services.security import encryption_service
from reworkd_platform.settings import Settings, settings as platform_settings
from reworkd_platform.web.api.http_responses import forbidden

T = TypeVar("T", bound="OAuthInstaller")


class OAuthInstaller(ABC):
def __init__(self, crud: OAuthCrud, settings: Settings):
Expand All @@ -28,6 +26,10 @@ async def install(self, user: UserBase, redirect_uri: str) -> str:
async def install_callback(self, code: str, state: str) -> OauthCredentials:
raise NotImplementedError()

@staticmethod
def store_access_token(creds: OauthCredentials, access_token: str) -> None:
creds.access_token_enc = encryption_service.encrypt(access_token)


class SlackInstaller(OAuthInstaller):
PROVIDER = "slack"
Expand All @@ -46,22 +48,22 @@ async def install(self, user: UserBase, redirect_uri: str) -> str:
)

async def install_callback(self, code: str, state: str) -> OauthCredentials:
installation = await self.crud.get_installation_by_state(state)
if not installation:
creds = await self.crud.get_installation_by_state(state)
if not creds:
raise forbidden()

oauth_response = WebClient().oauth_v2_access(
client_id=self.settings.slack_client_id,
client_secret=self.settings.slack_client_secret,
code=code,
state=state,
redirect_uri=self.settings.slack_redirect_uri,
)

installation.token_type = oauth_response["token_type"]
installation.access_token = oauth_response["access_token"]
installation.scope = oauth_response["scope"]
installation.data = oauth_response.data
return await installation.save(self.crud.session)
OAuthInstaller.store_access_token(creds, oauth_response["access_token"])
creds.token_type = oauth_response["token_type"]
creds.scope = oauth_response["scope"]
return await creds.save(self.crud.session)


integrations = {
Expand Down
17 changes: 17 additions & 0 deletions platform/reworkd_platform/services/security.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from cryptography.fernet import Fernet

from reworkd_platform.settings import settings


class EncryptionService:
def __init__(self, secret: bytes):
self.fernet = Fernet(secret)

def encrypt(self, text: str) -> bytes:
return self.fernet.encrypt(text.encode("utf-8"))

def decrypt(self, encoded_bytes: bytes) -> str:
return self.fernet.decrypt(encoded_bytes).decode("utf-8")


encryption_service = EncryptionService(settings.secret_signing_key.encode())
12 changes: 5 additions & 7 deletions platform/reworkd_platform/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,20 +39,18 @@ class Settings(BaseSettings):
with environment variables.
"""

# Application settings
host: str = "127.0.0.1"
port: int = 8000

# Quantity of workers for uvicorn
workers_count: int = 1

# Enable uvicorn reloading
reload: bool = True

# Current environment
environment: ENVIRONMENT = "development"

log_level: LOG_LEVEL = "INFO"

# Make sure you update this with your own secret key
# Must be 32 url-safe base64-encoded bytes
secret_signing_key: str = "JF52S66x6WMoifP5gZreiguYs9LYMn0lkXqgPYoNMD0="

# OpenAI
openai_api_base: str = "https://api.openai.com/v1"
openai_api_key: str = "<Should be updated via env>"
Expand Down
28 changes: 28 additions & 0 deletions platform/reworkd_platform/tests/test_security.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import pytest
from cryptography.fernet import Fernet, InvalidToken

from reworkd_platform.services.security import EncryptionService


def test_encrypt_decrypt():
key = Fernet.generate_key()
service = EncryptionService(key)

original_text = "Hello, world!"
encrypted = service.encrypt(original_text)
decrypted = service.decrypt(encrypted)

assert original_text == decrypted


def test_invalid_key():
key = Fernet.generate_key()

different_key = Fernet.generate_key()
different_service = EncryptionService(different_key)

original_text = "Hello, world!"
encrypted = Fernet(key).encrypt(original_text.encode())

with pytest.raises(InvalidToken):
different_service.decrypt(encrypted)
4 changes: 3 additions & 1 deletion platform/reworkd_platform/web/api/auth/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
installer_factory,
OAuthInstaller,
)
from reworkd_platform.services.security import encryption_service
from reworkd_platform.services.sockets import websockets
from reworkd_platform.settings import settings
from reworkd_platform.web.api.dependencies import get_current_user, get_organization
Expand Down Expand Up @@ -93,7 +94,8 @@ async def slack_channels(
if not (creds := await crud.get_installation_by_organization_id(org.id, "slack")):
raise forbidden()

client = WebClient(token=creds.access_token)
token = encryption_service.decrypt(creds.access_token_enc)
client = WebClient(token=token)
channels = [
Channel(name=c["name"], id=c["id"])
for c in client.conversations_list(types=["public_channel"])["channels"]
Expand Down
Loading