kacapower commited on
Commit
de69476
·
1 Parent(s): 62122e0

fix(auth): authorize if PIN is valid OR token is valid, and set SameSite=None cookie for iframe

Browse files
Files changed (1) hide show
  1. app.py +43 -25
app.py CHANGED
@@ -5,6 +5,8 @@ Features:
5
  - Dual-layer security:
6
  * Dynamic 8-digit PIN generated daily at 05:30 AM IST (00:00:00 UTC) using UNLOCK_SECRET.
7
  * Hugging Face READ token authorization for external web app / API calls.
 
 
8
  - CORS enabled for custom frontend (e.g. allen.site.je).
9
  - Direct Session Detection: Automatically detects direct HF Space usage.
10
  - File upload support up to 50MB.
@@ -129,22 +131,30 @@ def verify_auth(
129
  token: Optional[str] = Query(None),
130
  cookie_pin: Optional[str] = None,
131
  ):
132
- # 1. Verify Hugging Face Read Token authorization if configured
133
- if HF_READ_TOKEN:
134
- bearer_token = ""
135
- if authorization and authorization.lower().startswith("bearer "):
136
- bearer_token = authorization[7:].strip()
137
- elif token:
138
- bearer_token = token.strip()
139
-
140
- if bearer_token != HF_READ_TOKEN:
141
- raise HTTPException(status_code=401, detail="Invalid or missing Hugging Face authorization token")
142
-
143
- # 2. Verify 8-Digit Daily Unlock PIN
144
  req_pin = (x_access_pin or pin or cookie_pin or "").strip()
145
- if UNLOCK_SECRET or ACCESS_PIN:
146
- if not is_pin_valid(req_pin):
147
- raise HTTPException(status_code=401, detail="Invalid or expired daily 8-digit unlock PIN")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
 
149
 
150
  def get_lock_html(error_msg: str = "") -> str:
@@ -573,7 +583,6 @@ def _response_headers(upstream: httpx.Response) -> dict:
573
  methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"],
574
  )
575
  async def proxy(path: str, request: Request):
576
- # Determine PIN from request
577
  cookie_pin = request.cookies.get("opencode_pin")
578
  query_pin = request.query_params.get("pin")
579
  header_pin = request.headers.get("X-Access-Pin")
@@ -586,21 +595,19 @@ async def proxy(path: str, request: Request):
586
  and "text/html" in request.headers.get("accept", "")
587
  )
588
 
589
- # If visiting root navigation directly in browser
590
  if is_navigation:
591
- # Check authentication
592
  if (UNLOCK_SECRET or ACCESS_PIN) and not is_pin_valid(effective_pin):
593
  err = "Invalid PIN entered" if query_pin else ""
594
  return HTMLResponse(get_lock_html(err), status_code=401 if query_pin else 200)
595
 
596
- # Successfully unlocked direct navigation session
597
  state["last_direct_session"] = time.time()
598
  resp = FileResponse(SHELL, media_type="text/html")
599
  if effective_pin:
600
- resp.set_cookie("opencode_pin", effective_pin, max_age=86400, httponly=True, samesite="lax")
601
  return resp
602
 
603
- # Check origin for external API calls
604
  origin = request.headers.get("origin") or request.headers.get("referer") or ""
605
  is_external = "hf.space" not in origin and origin != ""
606
 
@@ -614,7 +621,7 @@ async def proxy(path: str, request: Request):
614
  status_code=503,
615
  )
616
 
617
- # General auth verification for proxy endpoints
618
  if UNLOCK_SECRET or ACCESS_PIN or HF_READ_TOKEN:
619
  auth = request.headers.get("Authorization") or request.query_params.get("token")
620
  try:
@@ -639,13 +646,19 @@ async def proxy(path: str, request: Request):
639
  status_code=502,
640
  )
641
 
642
- return StreamingResponse(
643
  upstream.aiter_raw(),
644
  status_code=upstream.status_code,
645
  headers=_response_headers(upstream),
646
  background=BackgroundTask(upstream.aclose),
647
  )
648
 
 
 
 
 
 
 
649
 
650
  @app.websocket("/{path:path}")
651
  async def ws_proxy(websocket: WebSocket, path: str):
@@ -653,9 +666,14 @@ async def ws_proxy(websocket: WebSocket, path: str):
653
  await websocket.close(code=1011)
654
  return
655
 
656
- # Check PIN from query params or cookies if dynamic unlock PIN configured
657
  effective_pin = websocket.query_params.get("pin") or websocket.cookies.get("opencode_pin")
658
- if (UNLOCK_SECRET or ACCESS_PIN) and not is_pin_valid(effective_pin):
 
 
 
 
 
 
659
  await websocket.close(code=4401)
660
  return
661
 
 
5
  - Dual-layer security:
6
  * Dynamic 8-digit PIN generated daily at 05:30 AM IST (00:00:00 UTC) using UNLOCK_SECRET.
7
  * Hugging Face READ token authorization for external web app / API calls.
8
+ * Either valid 8-digit PIN OR valid HF token authorizes requests.
9
+ - Cookie persistence with SameSite=None for iframe sub-resources.
10
  - CORS enabled for custom frontend (e.g. allen.site.je).
11
  - Direct Session Detection: Automatically detects direct HF Space usage.
12
  - File upload support up to 50MB.
 
131
  token: Optional[str] = Query(None),
132
  cookie_pin: Optional[str] = None,
133
  ):
 
 
 
 
 
 
 
 
 
 
 
 
134
  req_pin = (x_access_pin or pin or cookie_pin or "").strip()
135
+ bearer_token = ""
136
+ if authorization and authorization.lower().startswith("bearer "):
137
+ bearer_token = authorization[7:].strip()
138
+ elif token:
139
+ bearer_token = token.strip()
140
+
141
+ # 1. If valid 8-digit PIN is provided, accept immediately
142
+ if (UNLOCK_SECRET or ACCESS_PIN) and is_pin_valid(req_pin):
143
+ return
144
+
145
+ # 2. If valid HF authorization token is provided, accept immediately
146
+ if HF_READ_TOKEN and bearer_token == HF_READ_TOKEN:
147
+ return
148
+
149
+ # 3. If no security configured on the Space, accept
150
+ if not (UNLOCK_SECRET or ACCESS_PIN or HF_READ_TOKEN):
151
+ return
152
+
153
+ # Otherwise reject with appropriate error
154
+ if req_pin and not is_pin_valid(req_pin):
155
+ raise HTTPException(status_code=401, detail="Invalid or expired daily 8-digit unlock PIN")
156
+
157
+ raise HTTPException(status_code=401, detail="Invalid or missing Hugging Face authorization token")
158
 
159
 
160
  def get_lock_html(error_msg: str = "") -> str:
 
583
  methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"],
584
  )
585
  async def proxy(path: str, request: Request):
 
586
  cookie_pin = request.cookies.get("opencode_pin")
587
  query_pin = request.query_params.get("pin")
588
  header_pin = request.headers.get("X-Access-Pin")
 
595
  and "text/html" in request.headers.get("accept", "")
596
  )
597
 
598
+ # 1. Direct browser visit to root on HF Space
599
  if is_navigation:
 
600
  if (UNLOCK_SECRET or ACCESS_PIN) and not is_pin_valid(effective_pin):
601
  err = "Invalid PIN entered" if query_pin else ""
602
  return HTMLResponse(get_lock_html(err), status_code=401 if query_pin else 200)
603
 
 
604
  state["last_direct_session"] = time.time()
605
  resp = FileResponse(SHELL, media_type="text/html")
606
  if effective_pin:
607
+ resp.set_cookie("opencode_pin", effective_pin, max_age=86400, httponly=True, samesite="none", secure=True)
608
  return resp
609
 
610
+ # 2. Check origin for external API calls
611
  origin = request.headers.get("origin") or request.headers.get("referer") or ""
612
  is_external = "hf.space" not in origin and origin != ""
613
 
 
621
  status_code=503,
622
  )
623
 
624
+ # 3. Auth verification for API / proxy traffic
625
  if UNLOCK_SECRET or ACCESS_PIN or HF_READ_TOKEN:
626
  auth = request.headers.get("Authorization") or request.query_params.get("token")
627
  try:
 
646
  status_code=502,
647
  )
648
 
649
+ resp = StreamingResponse(
650
  upstream.aiter_raw(),
651
  status_code=upstream.status_code,
652
  headers=_response_headers(upstream),
653
  background=BackgroundTask(upstream.aclose),
654
  )
655
 
656
+ # Set auth cookie for iframe sub-resources
657
+ if effective_pin and "iframe" in request.query_params:
658
+ resp.set_cookie("opencode_pin", effective_pin, max_age=86400, httponly=True, samesite="none", secure=True)
659
+
660
+ return resp
661
+
662
 
663
  @app.websocket("/{path:path}")
664
  async def ws_proxy(websocket: WebSocket, path: str):
 
666
  await websocket.close(code=1011)
667
  return
668
 
 
669
  effective_pin = websocket.query_params.get("pin") or websocket.cookies.get("opencode_pin")
670
+ token = websocket.query_params.get("token")
671
+
672
+ # Authorize if PIN is valid OR token matches HF_READ_TOKEN
673
+ pin_ok = is_pin_valid(effective_pin)
674
+ token_ok = bool(HF_READ_TOKEN and token == HF_READ_TOKEN)
675
+
676
+ if (UNLOCK_SECRET or ACCESS_PIN or HF_READ_TOKEN) and not (pin_ok or token_ok):
677
  await websocket.close(code=4401)
678
  return
679