#!/usr/bin/env python3 """ Test script to verify bearer token authentication for all endpoints """ import requests import os from dotenv import load_dotenv load_dotenv() # Configuration BASE_URL = "http://127.0.0.1:8000" # Change to your deployment URL when testing live HF_API_KEY = os.getenv("HF_API_KEY") def test_endpoint(endpoint, method="GET", headers=None, json_data=None): """Test an endpoint and return the response""" url = f"{BASE_URL}{endpoint}" try: if method == "GET": response = requests.get(url, headers=headers) elif method == "POST": response = requests.post(url, headers=headers, json=json_data) return { "status_code": response.status_code, "success": response.status_code < 400, "response": response.json() if response.headers.get("content-type", "").startswith("application/json") else response.text } except Exception as e: return { "status_code": None, "success": False, "error": str(e) } def main(): """Run authentication tests""" print("๐Ÿ” Testing Bearer Token Authentication") print("=" * 50) if not HF_API_KEY: print("โŒ HF_API_KEY not found in environment variables") return # Test headers auth_headers = { "Authorization": f"Bearer {HF_API_KEY}", "Content-Type": "application/json" } no_auth_headers = { "Content-Type": "application/json" } invalid_auth_headers = { "Authorization": "Bearer invalid_token_123", "Content-Type": "application/json" } tests = [ # Public endpoint (should work without auth) { "name": "Public Health Check (No Auth)", "endpoint": "/api/v1/health/public", "method": "GET", "headers": no_auth_headers, "should_succeed": True }, # Protected endpoints without auth (should fail) { "name": "Protected Health Check (No Auth)", "endpoint": "/api/v1/health", "method": "GET", "headers": no_auth_headers, "should_succeed": False }, # Protected endpoints with invalid auth (should fail) { "name": "Protected Health Check (Invalid Auth)", "endpoint": "/api/v1/health", "method": "GET", "headers": invalid_auth_headers, "should_succeed": False }, # Protected endpoints with valid auth (should succeed) { "name": "Protected Health Check (Valid Auth)", "endpoint": "/api/v1/health", "method": "GET", "headers": auth_headers, "should_succeed": True }, # Test generate endpoint with auth { "name": "Generate Endpoint (Valid Auth)", "endpoint": "/api/v1/generate", "method": "POST", "headers": auth_headers, "json_data": { "terms": ["test", "card"], "card_date": "2024-01-01", "lang": "en" }, "should_succeed": True }, # Test generate endpoint without auth { "name": "Generate Endpoint (No Auth)", "endpoint": "/api/v1/generate", "method": "POST", "headers": no_auth_headers, "json_data": { "terms": ["test", "card"], "card_date": "2024-01-01", "lang": "en" }, "should_succeed": False }, # Test new user info endpoint { "name": "Get Current User (Valid JWT - after login)", "endpoint": "/api/v1/auth/me", "method": "GET", "headers": {}, # Will be filled after login "should_succeed": True, "requires_jwt": True }, { "name": "Get Current User (No Auth)", "endpoint": "/api/v1/auth/me", "method": "GET", "headers": no_auth_headers, "should_succeed": False }, { "name": "Get Current User (HF API Key)", "endpoint": "/api/v1/auth/me", "method": "GET", "headers": auth_headers, "should_succeed": False # HF API key should not work for user endpoints }, ] results = [] for test in tests: print(f"\n๐Ÿงช Testing: {test['name']}") result = test_endpoint( test["endpoint"], test["method"], test["headers"], test.get("json_data") ) expected_success = test["should_succeed"] actual_success = result["success"] if expected_success == actual_success: status = "โœ… PASS" else: status = "โŒ FAIL" print(f" {status} - Status: {result['status_code']}") if not result["success"] and "error" in result: print(f" Error: {result['error']}") elif "response" in result: # Print first few lines of response for debugging response_str = str(result["response"]) if len(response_str) > 100: response_str = response_str[:100] + "..." print(f" Response: {response_str}") results.append({ "test": test["name"], "passed": expected_success == actual_success, "status_code": result["status_code"] }) # Summary print("\n" + "=" * 50) print("๐Ÿ“Š Test Summary") print("=" * 50) passed = sum(1 for r in results if r["passed"]) total = len(results) print(f"โœ… Passed: {passed}/{total}") print(f"โŒ Failed: {total - passed}/{total}") if passed == total: print("\n๐ŸŽ‰ All authentication tests passed!") else: print("\nโš ๏ธ Some tests failed. Check the output above.") print("\nFailed tests:") for result in results: if not result["passed"]: print(f" - {result['test']}") if __name__ == "__main__": main()