fix: 设置令牌后校验本机接口并限制访问主机
This commit is contained in:
+35
-1
@@ -1,16 +1,22 @@
|
|||||||
"""本机接口。只监听 127.0.0.1。功能路由按目录挂上。"""
|
"""本机接口。只监听 127.0.0.1。功能路由按目录挂上。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import ctypes
|
import ctypes
|
||||||
import logging
|
import logging
|
||||||
import msvcrt
|
import msvcrt
|
||||||
import os
|
import os
|
||||||
|
import secrets
|
||||||
import sys
|
import sys
|
||||||
from contextlib import asynccontextmanager, suppress
|
from contextlib import asynccontextmanager, suppress
|
||||||
from ctypes import wintypes
|
from ctypes import wintypes
|
||||||
|
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
from fastapi.middleware.trustedhost import TrustedHostMiddleware
|
||||||
|
from starlette.datastructures import Headers
|
||||||
|
from starlette.responses import JSONResponse
|
||||||
|
|
||||||
from app.features.download.router import router as download_router
|
from app.features.download.router import router as download_router
|
||||||
from app.platform.auth import router as auth_router
|
from app.platform.auth import router as auth_router
|
||||||
@@ -128,6 +134,33 @@ def _release_data_lock() -> None:
|
|||||||
handle.close()
|
handle.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _token_matches(provided: str, expected: str) -> bool:
|
||||||
|
if len(provided) != len(expected):
|
||||||
|
return False
|
||||||
|
return secrets.compare_digest(provided, expected)
|
||||||
|
|
||||||
|
|
||||||
|
class LocalTokenMiddleware:
|
||||||
|
"""仅当设置了 NQI_TOKEN 时校验 /api/*。健康检查除外。"""
|
||||||
|
|
||||||
|
def __init__(self, app):
|
||||||
|
self.app = app
|
||||||
|
|
||||||
|
async def __call__(self, scope, receive, send):
|
||||||
|
if scope.get("type") != "http":
|
||||||
|
await self.app(scope, receive, send)
|
||||||
|
return
|
||||||
|
token = os.environ.get("NQI_TOKEN") or ""
|
||||||
|
path = scope.get("path") or ""
|
||||||
|
if token and path.startswith("/api/") and path.rstrip("/") != "/api/health":
|
||||||
|
provided = Headers(scope=scope).get("x-nqi-token") or ""
|
||||||
|
if not _token_matches(provided, token):
|
||||||
|
response = JSONResponse({"detail": "未授权"}, status_code=401)
|
||||||
|
await response(scope, receive, send)
|
||||||
|
return
|
||||||
|
await self.app(scope, receive, send)
|
||||||
|
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def lifespan(_app: FastAPI):
|
async def lifespan(_app: FastAPI):
|
||||||
configure_logging()
|
configure_logging()
|
||||||
@@ -154,6 +187,8 @@ async def lifespan(_app: FastAPI):
|
|||||||
|
|
||||||
|
|
||||||
app = FastAPI(title="NqiTools", lifespan=lifespan)
|
app = FastAPI(title="NqiTools", lifespan=lifespan)
|
||||||
|
app.add_middleware(LocalTokenMiddleware)
|
||||||
|
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["127.0.0.1", "localhost"])
|
||||||
app.add_middleware(
|
app.add_middleware(
|
||||||
CORSMiddleware,
|
CORSMiddleware,
|
||||||
allow_origins=ORIGINS,
|
allow_origins=ORIGINS,
|
||||||
@@ -171,7 +206,6 @@ async def health() -> dict:
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import os
|
|
||||||
import socket
|
import socket
|
||||||
|
|
||||||
import uvicorn
|
import uvicorn
|
||||||
|
|||||||
Reference in New Issue
Block a user