Skip to content
This repository has been archived by the owner on Aug 10, 2024. It is now read-only.

Commit

Permalink
troubleshooting api key integration
Browse files Browse the repository at this point in the history
  • Loading branch information
aliig committed Nov 30, 2023
1 parent c2e2732 commit 4e310fc
Show file tree
Hide file tree
Showing 6 changed files with 128 additions and 9 deletions.
13 changes: 8 additions & 5 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,6 @@ jobs:
steps:
- uses: actions/checkout@v2

- name: Set up API Key
run: |
echo "CURSEFORGE_API_KEY=${{ secrets.CURSEFORGE_API_KEY }}" >> $GITHUB_ENV
- name: Cache conda
uses: actions/cache@v2
with:
Expand All @@ -43,6 +39,13 @@ jobs:
run: |
conda env update --name ark --file environment.yml
- name: Encryption
run: |
echo "PASSPHRASE=$(openssl rand -base64 32)" >> $GITHUB_ENV
python src/crypto_script.py --mode encrypt --input "${{ secrets.CURSEFORGE_API_KEY }}" --output encrypted_key.enc --passphrase "${{ env.PASSPHRASE }}"
echo "${{ env.PASSPHRASE }}" > passphrase.txt
# Install
- name: Install PyInstaller
shell: bash -l {0}
run: |
Expand All @@ -53,7 +56,7 @@ jobs:
run: |
cd src
rm -f __init__.py
pyinstaller --onefile --name=arkserversuite --add-data "ps;ps" main.py
pyinstaller --onefile --name=arkserversuite --add-data "ps;ps" --add-data "../encrypted_key.enc;." --add-data "../passphrase.txt;." main.py
cd ..
mkdir -p dist
mv src/dist/arkserversuite.exe dist/arkserversuite.exe
Expand Down
1 change: 1 addition & 0 deletions encrypted_key.enc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
�k���Bڂ��"S EsgAAAAABlaDR2T-uPvCsPQbKFi6vi4fQ9n7tUtrToOTGkzhuV02K3LierP6epbEnUnuAB2eUgK0ltJWnzT1nArxSHJxl6GqTcgcM7eLU-_6HrAZXpa9PxoVrnV_OThtSFd5if1k0xPHwFIiwTgoJhG_bARwKTnGJgvw==
3 changes: 2 additions & 1 deletion environment.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ dependencies:
- pytest-mock
- python-dotenv
- colorlog
- tzlocal
- tzlocal
- cryptography
81 changes: 81 additions & 0 deletions src/crypto_script.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import base64
import os
import argparse
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.fernet import Fernet
from cryptography.hazmat.backends import default_backend


def derive_key(passphrase, salt=None):
"""Derives a key using the given passphrase and salt."""
if salt is None:
salt = os.urandom(16) # Generate a new salt for encryption
# Key Derivation Function
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=100000,
backend=default_backend(),
)
key = base64.urlsafe_b64encode(kdf.derive(passphrase.encode()))
return key, salt


def encrypt_data(data, passphrase):
key, salt = derive_key(passphrase)
cipher_suite = Fernet(key)
encrypted_data = cipher_suite.encrypt(data.encode())
return salt + encrypted_data # Prepend salt to encrypted data


def decrypt_data(encrypted_data_with_salt, passphrase):
salt = encrypted_data_with_salt[:16] # Extract the salt
encrypted_data = encrypted_data_with_salt[16:]
key, _ = derive_key(passphrase, salt)
cipher_suite = Fernet(key)
return cipher_suite.decrypt(encrypted_data)


def main():
parser = argparse.ArgumentParser(description="Encrypt/Decrypt data.")
parser.add_argument(
"--mode",
choices=["encrypt", "decrypt"],
required=True,
help="Operation mode: encrypt or decrypt",
)
parser.add_argument(
"--input", required=True, help="Input data to encrypt or path to input file"
)
parser.add_argument("--output", required=True, help="Output file path")
parser.add_argument(
"--passphrase", required=True, help="Passphrase for encryption/decryption"
)

args = parser.parse_args()

if args.mode == "encrypt":
try:
# Attempt to open the input as a file
with open(args.input, "r") as file:
data = file.read()
except FileNotFoundError:
# If file not found, treat input as a raw string
data = args.input

encrypted_data = encrypt_data(data, args.passphrase)
with open(args.output, "wb") as file:
file.write(encrypted_data)

elif args.mode == "decrypt":
with open(args.input, "rb") as file:
encrypted_data_with_salt = file.read()
decrypted_data = decrypt_data(encrypted_data_with_salt, args.passphrase)
with open(args.output, "wb") as file:
file.write(decrypted_data)


if __name__ == "__main__":
main()
23 changes: 20 additions & 3 deletions src/mods.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

from config import CONFIG
from logger import get_logger
from crypto_script import decrypt_data

logger = get_logger(__name__)

Expand All @@ -23,12 +24,28 @@ class Mod:
latest_dt: datetime | None


@cache
def _decrypt_api_key() -> str:
try:
with open("encrypted_key.enc", "rb") as file:
encrypted_data_with_salt = file.read()
with open("passphrase.txt", "r") as file:
passphrase = file.read().strip()
return decrypt_data(encrypted_data_with_salt, passphrase).decode()
except Exception as e:
logger.error(f"Error decrypting CURSEFORGE_API_KEY: {e}")
return None


def _get_api_key() -> str:
key = os.getenv("CURSEFORGE_API_KEY")
if key:
if key := os.getenv("CURSEFORGE_API_KEY"):
logger.debug("CURSEFORGE_API_KEY found in environment variables")
else:
logger.warning("CURSEFORGE_API_KEY not found in environment variables")
# get key from file with decryption
if key := _decrypt_api_key():
logger.debug("CURSEFORGE_API_KEY decrypted successfully")
else:
logger.warning("CURSEFORGE_API_KEY failed to decrypt or returned None")
return key


Expand Down
16 changes: 16 additions & 0 deletions tests/test_crypto_script.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import pytest
from crypto_script import encrypt_data, decrypt_data


def test_encrypt_decrypt():
original_string = "Test String"
passphrase = "StrongPassphrase"

# Encrypt the string
encrypted_data = encrypt_data(original_string, passphrase)

# Decrypt the data
decrypted_string = decrypt_data(encrypted_data, passphrase).decode()

# Assert that the decrypted string matches the original
assert decrypted_string == original_string

0 comments on commit 4e310fc

Please sign in to comment.