Spaces:
Running on Zero
Running on Zero
Rate-limit by the address Hugging Face's load balancer saw; remove temporary check
Browse files
app.py
CHANGED
|
@@ -36,7 +36,7 @@ NODE_BIN = os.path.join(NODE_ROOT, 'bin')
|
|
| 36 |
NODE = os.path.join(NODE_BIN, 'node')
|
| 37 |
NPM_CLI = os.path.join(NODE_ROOT, 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js')
|
| 38 |
# Request headers the API reads, and response headers it sets. Everything else stays behind.
|
| 39 |
-
PASS_IN = ('authorization', 'content-type', 'origin', 'x-
|
| 40 |
PASS_OUT = ('content-type', 'cache-control', 'x-content-type-options', 'x-frame-options', 'referrer-policy',
|
| 41 |
'retry-after', 'allow')
|
| 42 |
NO_STORE = {'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff'}
|
|
@@ -95,8 +95,10 @@ threading.Thread(target=run_api, daemon=True).start()
|
|
| 95 |
|
| 96 |
# ---------------------------------------------------------------- front door
|
| 97 |
class SiteOnly:
|
| 98 |
-
"""CORS for the website only, wrapped around everything else
|
| 99 |
-
|
|
|
|
|
|
|
| 100 |
|
| 101 |
def __init__(self, app):
|
| 102 |
self.app = app
|
|
@@ -137,18 +139,18 @@ server = Front(title='m.ai API', docs_url=None, redoc_url=None, openapi_url=None
|
|
| 137 |
upstream = httpx.AsyncClient(base_url=f'http://127.0.0.1:{API_PORT}', timeout=httpx.Timeout(70, connect=3))
|
| 138 |
|
| 139 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
@server.api_route('/', methods=['GET', 'HEAD'], include_in_schema=False)
|
| 141 |
def home():
|
| 142 |
return PlainTextResponse(f'm.ai API is running. The website is {SITE}\n', headers=NO_STORE)
|
| 143 |
|
| 144 |
|
| 145 |
-
if os.environ.get('SHOW_FORWARDING') == 'yes': # temporary: shows a caller its own forwarding headers
|
| 146 |
-
@server.get('/forwarding', include_in_schema=False)
|
| 147 |
-
def forwarding(request: Request):
|
| 148 |
-
return JSONResponse({k: v for k, v in request.headers.items() if k.startswith('x-') or k in ('forwarded', 'via')}
|
| 149 |
-
| {'client': request.client and request.client.host}, headers=NO_STORE)
|
| 150 |
-
|
| 151 |
-
|
| 152 |
@server.api_route('/api/{path:path}', methods=['GET', 'HEAD', 'POST'], include_in_schema=False)
|
| 153 |
async def api(path: str, request: Request):
|
| 154 |
if int(request.headers.get('content-length') or 0) > BODY_LIMIT:
|
|
@@ -160,6 +162,7 @@ async def api(path: str, request: Request):
|
|
| 160 |
return JSONResponse({'error': 'Request too large.'}, 413, headers=NO_STORE)
|
| 161 |
body.append(chunk)
|
| 162 |
headers = {k: v for k, v in request.headers.items() if k in PASS_IN}
|
|
|
|
| 163 |
try:
|
| 164 |
reply = await upstream.send(upstream.build_request(request.method, '/api/' + path, params=request.query_params,
|
| 165 |
headers=headers, content=b''.join(body)), stream=True)
|
|
|
|
| 36 |
NODE = os.path.join(NODE_BIN, 'node')
|
| 37 |
NPM_CLI = os.path.join(NODE_ROOT, 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js')
|
| 38 |
# Request headers the API reads, and response headers it sets. Everything else stays behind.
|
| 39 |
+
PASS_IN = ('authorization', 'content-type', 'origin', 'x-razorpay-signature', 'x-razorpay-event-id')
|
| 40 |
PASS_OUT = ('content-type', 'cache-control', 'x-content-type-options', 'x-frame-options', 'referrer-policy',
|
| 41 |
'retry-after', 'allow')
|
| 42 |
NO_STORE = {'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff'}
|
|
|
|
| 95 |
|
| 96 |
# ---------------------------------------------------------------- front door
|
| 97 |
class SiteOnly:
|
| 98 |
+
"""CORS for the website only, wrapped around everything else (Gradio's own CORS layer lets any site in on a public
|
| 99 |
+
host, so its access-control headers are dropped here). Hugging Face's edge proxy in front of every Space adds its
|
| 100 |
+
own permissive CORS headers anyway, so CORS is not the lock: no cookies are used, every paid action needs the
|
| 101 |
+
user's Firebase token, and the API refuses requests from other sites with 403."""
|
| 102 |
|
| 103 |
def __init__(self, app):
|
| 104 |
self.app = app
|
|
|
|
| 139 |
upstream = httpx.AsyncClient(base_url=f'http://127.0.0.1:{API_PORT}', timeout=httpx.Timeout(70, connect=3))
|
| 140 |
|
| 141 |
|
| 142 |
+
def visitor_ip(request):
|
| 143 |
+
"""Hugging Face's load balancer appends the visitor's address to X-Forwarded-For; anything before it was sent by
|
| 144 |
+
the client and could be made up, so only the last entry counts (it keys the API's per-address rate limits)."""
|
| 145 |
+
hops = [h.strip() for h in request.headers.get('x-forwarded-for', '').split(',') if h.strip()]
|
| 146 |
+
return hops[-1] if hops else (request.client.host if request.client else 'unknown')
|
| 147 |
+
|
| 148 |
+
|
| 149 |
@server.api_route('/', methods=['GET', 'HEAD'], include_in_schema=False)
|
| 150 |
def home():
|
| 151 |
return PlainTextResponse(f'm.ai API is running. The website is {SITE}\n', headers=NO_STORE)
|
| 152 |
|
| 153 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
@server.api_route('/api/{path:path}', methods=['GET', 'HEAD', 'POST'], include_in_schema=False)
|
| 155 |
async def api(path: str, request: Request):
|
| 156 |
if int(request.headers.get('content-length') or 0) > BODY_LIMIT:
|
|
|
|
| 162 |
return JSONResponse({'error': 'Request too large.'}, 413, headers=NO_STORE)
|
| 163 |
body.append(chunk)
|
| 164 |
headers = {k: v for k, v in request.headers.items() if k in PASS_IN}
|
| 165 |
+
headers['x-forwarded-for'] = visitor_ip(request)
|
| 166 |
try:
|
| 167 |
reply = await upstream.send(upstream.build_request(request.method, '/api/' + path, params=request.query_params,
|
| 168 |
headers=headers, content=b''.join(body)), stream=True)
|