File size: 6,378 Bytes
da64db2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e673ce2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da64db2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
#!/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()