fix: api-key generator and verify-api-key validated
Browse files- app/security/auth_service.py +12 -8
- scripts/api_key_genenerator.py +38 -8
app/security/auth_service.py
CHANGED
|
@@ -43,24 +43,32 @@ class AuthService:
|
|
| 43 |
try:
|
| 44 |
decoded_data = base64.b64decode(encoded_data).decode()
|
| 45 |
data = json.loads(decoded_data)
|
|
|
|
| 46 |
except Exception as e:
|
| 47 |
raise HTTPException(
|
| 48 |
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 49 |
detail=f"Invalid API key data format: {str(e)}",
|
| 50 |
)
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
expected_signature = hmac.new(
|
| 53 |
self.secret.KEY.encode(),
|
| 54 |
-
|
| 55 |
-
{"username": data["username"], "created_at": data["created_at"]}
|
| 56 |
-
).encode(),
|
| 57 |
hashlib.sha256,
|
| 58 |
).hexdigest()
|
| 59 |
|
|
|
|
|
|
|
|
|
|
| 60 |
if data["signature"] != expected_signature:
|
| 61 |
raise HTTPException(
|
| 62 |
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 63 |
-
detail="Invalid API key signature",
|
| 64 |
)
|
| 65 |
|
| 66 |
result = data["username"]
|
|
@@ -80,10 +88,6 @@ class AuthService:
|
|
| 80 |
logger.trace(f"BEGIN: api_key: {api_key}")
|
| 81 |
username = self.decode_api_key(api_key)
|
| 82 |
|
| 83 |
-
# if username not in users or users[username] != api_key:
|
| 84 |
-
# raise HTTPException(
|
| 85 |
-
# status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials"
|
| 86 |
-
# )
|
| 87 |
result = username
|
| 88 |
logger.trace(f"END: result: {result}")
|
| 89 |
return result
|
|
|
|
| 43 |
try:
|
| 44 |
decoded_data = base64.b64decode(encoded_data).decode()
|
| 45 |
data = json.loads(decoded_data)
|
| 46 |
+
logger.trace(f"Decoded data: {data}")
|
| 47 |
except Exception as e:
|
| 48 |
raise HTTPException(
|
| 49 |
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 50 |
detail=f"Invalid API key data format: {str(e)}",
|
| 51 |
)
|
| 52 |
|
| 53 |
+
# Debug için JSON verilerini logla
|
| 54 |
+
json_data = {"username": data["username"], "created_at": data["created_at"]}
|
| 55 |
+
json_str = json.dumps(json_data)
|
| 56 |
+
logger.trace(f"JSON data for signature: {json_str}")
|
| 57 |
+
logger.trace(f"Secret key: {self.secret.KEY}")
|
| 58 |
+
|
| 59 |
expected_signature = hmac.new(
|
| 60 |
self.secret.KEY.encode(),
|
| 61 |
+
json_str.encode(),
|
|
|
|
|
|
|
| 62 |
hashlib.sha256,
|
| 63 |
).hexdigest()
|
| 64 |
|
| 65 |
+
logger.trace(f"Expected signature: {expected_signature}")
|
| 66 |
+
logger.trace(f"Received signature: {data['signature']}")
|
| 67 |
+
|
| 68 |
if data["signature"] != expected_signature:
|
| 69 |
raise HTTPException(
|
| 70 |
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 71 |
+
detail=f"Invalid API key signature: {data['signature']} != {expected_signature}",
|
| 72 |
)
|
| 73 |
|
| 74 |
result = data["username"]
|
|
|
|
| 88 |
logger.trace(f"BEGIN: api_key: {api_key}")
|
| 89 |
username = self.decode_api_key(api_key)
|
| 90 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
result = username
|
| 92 |
logger.trace(f"END: result: {result}")
|
| 93 |
return result
|
scripts/api_key_genenerator.py
CHANGED
|
@@ -19,6 +19,9 @@ import argparse
|
|
| 19 |
import hmac
|
| 20 |
import hashlib
|
| 21 |
from datetime import datetime
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
def generate_api_key(username: str, secret_key: str) -> str:
|
| 24 |
"""
|
|
@@ -32,18 +35,27 @@ def generate_api_key(username: str, secret_key: str) -> str:
|
|
| 32 |
str: Generated API_KEY (ACCESS_KEY, ACCESS_TOKEN)
|
| 33 |
"""
|
| 34 |
# Create encoded API key with timestamp
|
|
|
|
| 35 |
data = {
|
| 36 |
"username": username,
|
| 37 |
-
"created_at":
|
| 38 |
}
|
| 39 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
# Add HMAC signature for additional security
|
| 41 |
signature = hmac.new(
|
| 42 |
secret_key.encode(),
|
| 43 |
-
|
| 44 |
hashlib.sha256
|
| 45 |
).hexdigest()
|
| 46 |
|
|
|
|
|
|
|
| 47 |
data["signature"] = signature
|
| 48 |
|
| 49 |
# Create API key
|
|
@@ -51,7 +63,23 @@ def generate_api_key(username: str, secret_key: str) -> str:
|
|
| 51 |
json.dumps(data).encode()
|
| 52 |
).decode()
|
| 53 |
|
| 54 |
-
return api_key
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
def main():
|
| 57 |
parser = argparse.ArgumentParser(description="API Key Generator")
|
|
@@ -60,20 +88,22 @@ def main():
|
|
| 60 |
args = parser.parse_args()
|
| 61 |
|
| 62 |
try:
|
| 63 |
-
api_key = generate_api_key(args.username, args.secret_key)
|
|
|
|
| 64 |
print("\nAPI Key generated:")
|
| 65 |
print(f"Username: {args.username}")
|
| 66 |
print(f"API Key: {api_key}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
print("\nUsage example:")
|
| 68 |
print('curl -X POST "http://localhost:8000/v1/chat/completions" \\')
|
| 69 |
print(f' -H "Authorization: Bearer {api_key}" \\')
|
| 70 |
print(' -H "Content-Type: application/json" \\')
|
| 71 |
print(' -d \'{"model": "gpt-3.5-turbo", "messages": [{"role": "user", "content": "Hello!"}]}\'')
|
| 72 |
|
| 73 |
-
# Save the API key to a file
|
| 74 |
-
with open("api_key.txt", "w") as f:
|
| 75 |
-
f.write(api_key)
|
| 76 |
-
print("\nAPI Key saved to api_key.txt")
|
| 77 |
except argparse.ArgumentError as e:
|
| 78 |
print("Please provide a username and secret key", file=sys.stderr)
|
| 79 |
sys.exit(1)
|
|
|
|
| 19 |
import hmac
|
| 20 |
import hashlib
|
| 21 |
from datetime import datetime
|
| 22 |
+
from loguru import logger
|
| 23 |
+
|
| 24 |
+
logger.add("logs/api_key_generator.log")
|
| 25 |
|
| 26 |
def generate_api_key(username: str, secret_key: str) -> str:
|
| 27 |
"""
|
|
|
|
| 35 |
str: Generated API_KEY (ACCESS_KEY, ACCESS_TOKEN)
|
| 36 |
"""
|
| 37 |
# Create encoded API key with timestamp
|
| 38 |
+
timestamp = int(datetime.now().timestamp())
|
| 39 |
data = {
|
| 40 |
"username": username,
|
| 41 |
+
"created_at": timestamp
|
| 42 |
}
|
| 43 |
|
| 44 |
+
# Debug için JSON verilerini logla
|
| 45 |
+
json_data = {"username": username, "created_at": timestamp}
|
| 46 |
+
json_str = json.dumps(json_data)
|
| 47 |
+
logger.debug(f"JSON data for signature: {json_str}")
|
| 48 |
+
logger.debug(f"Secret key: {secret_key}")
|
| 49 |
+
|
| 50 |
# Add HMAC signature for additional security
|
| 51 |
signature = hmac.new(
|
| 52 |
secret_key.encode(),
|
| 53 |
+
json_str.encode(),
|
| 54 |
hashlib.sha256
|
| 55 |
).hexdigest()
|
| 56 |
|
| 57 |
+
logger.debug(f"Generated signature: {signature}")
|
| 58 |
+
|
| 59 |
data["signature"] = signature
|
| 60 |
|
| 61 |
# Create API key
|
|
|
|
| 63 |
json.dumps(data).encode()
|
| 64 |
).decode()
|
| 65 |
|
| 66 |
+
return api_key, timestamp
|
| 67 |
+
|
| 68 |
+
def save_api_key(username: str, api_key: str, timestamp: int):
|
| 69 |
+
"""
|
| 70 |
+
Save API key to api_keys.txt file in the same format as the shell script.
|
| 71 |
+
|
| 72 |
+
Args:
|
| 73 |
+
username (str): Username
|
| 74 |
+
api_key (str): Generated API key
|
| 75 |
+
timestamp (int): Creation timestamp
|
| 76 |
+
"""
|
| 77 |
+
formatted_timestamp = datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
|
| 78 |
+
with open("api_keys.txt", "a") as f:
|
| 79 |
+
f.write(f"Username: {username}\n")
|
| 80 |
+
f.write(f"API Key: {api_key}\n")
|
| 81 |
+
f.write(f"Timestamp: {formatted_timestamp}\n")
|
| 82 |
+
f.write("--------------------------------\n")
|
| 83 |
|
| 84 |
def main():
|
| 85 |
parser = argparse.ArgumentParser(description="API Key Generator")
|
|
|
|
| 88 |
args = parser.parse_args()
|
| 89 |
|
| 90 |
try:
|
| 91 |
+
api_key, timestamp = generate_api_key(args.username, args.secret_key)
|
| 92 |
+
|
| 93 |
print("\nAPI Key generated:")
|
| 94 |
print(f"Username: {args.username}")
|
| 95 |
print(f"API Key: {api_key}")
|
| 96 |
+
|
| 97 |
+
# Save to api_keys.txt
|
| 98 |
+
save_api_key(args.username, api_key, timestamp)
|
| 99 |
+
print("\nAPI Key saved to api_keys.txt")
|
| 100 |
+
|
| 101 |
print("\nUsage example:")
|
| 102 |
print('curl -X POST "http://localhost:8000/v1/chat/completions" \\')
|
| 103 |
print(f' -H "Authorization: Bearer {api_key}" \\')
|
| 104 |
print(' -H "Content-Type: application/json" \\')
|
| 105 |
print(' -d \'{"model": "gpt-3.5-turbo", "messages": [{"role": "user", "content": "Hello!"}]}\'')
|
| 106 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
except argparse.ArgumentError as e:
|
| 108 |
print("Please provide a username and secret key", file=sys.stderr)
|
| 109 |
sys.exit(1)
|