Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Safeguard Agentic Scanner

Agentic repo 的快速 heuristic scanner。輸入 Git URL 或上傳 ZIP 後,它會執行以下工作。

  • 偵測危險模式,包括無限工具迴圈、不安全的 subprocess/requests 用法、缺少核准 gate、prompt injection 風險、憑證外洩、過度寬廣的存取權限、自我修改,以及不安全的 eval/exec
  • 說明每項發現不安全的原因及修正方式。
  • 可選擇產生含註解的 patch diff,在相關程式碼行旁標記風險。

後端使用 FastAPI,前端使用 Streamlit。分析邏輯位於 shared/analyzer.py,使兩層共用相同規則。

快速開始

  1. 建立環境並安裝相依套件。
python -m venv .venv
. .venv/Scripts/activate  # Windows
uv pip install -r requirements.txt
  1. 執行後端。
uvicorn backend.app.main:app --host 0.0.0.0 --port 8000 --reload
  1. 執行前端。設定 BACKEND_URL 讓 Streamlit 呼叫 API;如果未設定,Streamlit 會在本機執行 analyzer。
set BACKEND_URL=http://localhost:8000
streamlit run frontend/app.py

Hugging Face Spaces(Streamlit)

  • 將 repo root 的 app.py 保留為 Space entrypoint。
  • 如有需要,將 HUGGINGFACE_API_TOKEN(HF provider)及/或 OLLAMA_HOST 設為 Space secrets。
  • 部署為 Streamlit Space,預設會執行 streamlit run app.py

選用方式:以 safeguard model 啟動 Ollama,進一步使用 LLM 改善結果。

ollama run gpt-oss:20b-cloud  # downloads model on first run
# If your Ollama host is remote, export OLLAMA_HOST=http://host:11434

選用方式:使用 Hugging Face inference,例如 openai/gpt-oss-safeguard-20b

HUGGINGFACE_API_TOKEN=your_token_here
# place in .env or export in your shell
# Choose provider=huggingface and model=openai/gpt-oss-safeguard-20b in UI/API

API 範例

  • Health:curl http://localhost:8000/health
  • 分析 repo URL。
curl -X POST http://localhost:8000/analyze/url \
  -H "Content-Type: application/json" \
  -d "{\"repo_url\":\"https://github.com/example/agentic-repo\",\"propose_patch\":true,\"use_llm\":true,\"llm_model\":\"gpt-oss:20b-cloud\",\"llm_provider\":\"ollama\"}"
  • 分析上傳的 ZIP。
curl -X POST http://localhost:8000/analyze/upload \
  -F "file=@repo.zip" \
  -F "propose_patch=true" \
  -F "use_llm=true" \
  -F "llm_model=gpt-oss:20b-cloud" \
  -F "llm_provider=ollama"

偵測方式

  • 規則位於 shared/analyzer.py,依風險類別提供 regex/自訂 detector。
  • 支援的檔案類型包括 .py.js.ts.tsx.sh.md.yaml.yml.json
  • 每項發現包括檔案、行數、嚴重程度、說明及修正提示。
  • 選用的 patch 建議會在風險程式碼行前加入 #// FIXME 註解,並輸出 unified diff,不會修改 repo。
  • 選用的 LLM 改善功能會透過 Ollama 將發現與程式碼片段傳給 gpt-oss-safeguard,或透過 Hugging Face 傳給 openai/gpt-oss-safeguard-20b,回傳較完整的分析,以及模型建議的 diff block(如有)。

擴充

  • shared/analyzer.py 調整或加入規則,包括 RULES list 及 detector。
  • 透過 UI/API 更換 LLM provider/model。使用 Hugging Face 時,設定 HUGGINGFACE_API_TOKEN 並使用 openai/gpt-oss-safeguard-20b。其他 provider,例如 Groq/OpenAI,可透過擴充 run_llm_review 加入。
  • 強化 _missing_approval_detector 或加入設定驅動政策,以收緊 network/domain allowlist 及核准語意。

注意事項

  • Scanner 採 heuristic 方法,可能產生 false positive 或 false negative。只應用於分流,仍須人工審查。
  • Git clone 使用 git clone --depth 1。請確認執行後端的位置可以連線至目標 host。
  • 不要將 HUGGINGFACE_API_TOKEN 或其他憑證寫入 repo、ZIP、掃描輸出或 patch。上傳第三方程式碼及將片段傳送至模型 provider 前,也須確認授權、隱私與資料處理界線。