Skip to content

fixing some bugs and cleaning the code#19

Open
KevinRusu wants to merge 1 commit into
benevolentbandwidth:mainfrom
KevinRusu:main
Open

fixing some bugs and cleaning the code#19
KevinRusu wants to merge 1 commit into
benevolentbandwidth:mainfrom
KevinRusu:main

Conversation

@KevinRusu

Copy link
Copy Markdown
Contributor

Addresses a set of bugs and hardening issues found during a code audit of the FastAPI backend:

  • Startup validation — server now refuses to start if USE_MOCK=false and BEACON_API_KEY is not set; logs a clear warning when running authless in dev/mock mode. Previously, misconfigurations were only discovered on the first live request.
  • Fix unreachable error handler — the "Set USE_MOCK=true" message could never appear because the code caught NotImplementedError but GeminiProvider raised RuntimeError. Introduced a shared ProviderConfigError type so the catch works correctly.
  • Timing-safe auth — replaced != key comparison with secrets.compare_digest to prevent timing attacks.
  • Log privacy — user domains no longer logged at INFO level (browsing history on the server). Verdict + score stay at INFO; domain moves to DEBUG.
  • Mock score pass-through — MockProvider now mirrors the real provider's score range instead of returning fixed 9/5/1 values, so dev mode exercises the full pipeline.
  • Configurable Gemini model — model name now reads from GEMINI_MODEL env var (default gemini-2.5-flash-lite) so upgrades don't require a code change.
  • CORS hardening — allow_headers narrowed to the two headers the extension actually sends; origins now configurable via ALLOWED_ORIGINS env var.
  • Remove phantom PROVIDER env var (was documented in .env.example but never read by any code)
  • Simplified Dockerfile — collapsed redundant identical two-stage build into one stage.

Copilot AI review requested due to automatic review settings June 12, 2026 02:09

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

Improve production-readiness of the API by tightening configuration validation, security defaults, and provider configurability.

Changes:

  • Add startup config validation and a dedicated ProviderConfigError for provider misconfiguration.
  • Make Gemini model configurable via GEMINI_MODEL and improve missing-key guidance.
  • Harden auth comparison, tighten CORS settings, and simplify the Dockerfile.

Reviewed changes

Copilot reviewed 8 out of 9 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
api/providers/mock_provider.py Adjust mock scoring/reasons to align output with heuristic inputs.
api/providers/gemini_provider.py Add configurable model selection and raise typed config errors.
api/main.py Add fail-fast startup validation, adjust CORS, and refine logging/error handling.
api/exceptions.py Introduce ProviderConfigError for missing provider configuration.
api/auth.py Use constant-time comparison for API key validation.
api/README.md Document new env vars and updated production-mode requirements.
api/Dockerfile Remove redundant multi-stage build.
api/.env.example Update example env vars (model/origins).
.gitignore Ignore additional generated/output directories.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +6 to +26
score = request.heuristic_score
if score >= 7:
return AnalyzeResponse(
risk_score=9,
risk_score=score,
label="scam",
action="block",
reason="Domain registered recently; urgency language matches credential-harvesting patterns.",
reason="Heuristic signals indicate high likelihood of phishing or fraud.",
)
if request.heuristic_score >= 4:
if score >= 4:
return AnalyzeResponse(
risk_score=5,
risk_score=score,
label="uncertain",
action="warn",
reason="Some indicators of potential phishing detected.",
reason="Some suspicious indicators detected; proceed with caution.",
)
return AnalyzeResponse(
risk_score=1,
risk_score=score,
label="safe",
action="allow",
reason="No significant risk indicators detected.",
)
) No newline at end of file
Comment on lines 2 to +7
from google import genai
from google.genai import types
from schemas import AnalyzeRequest, AnalyzeResponse
from exceptions import ProviderConfigError

MODEL = os.getenv("GEMINI_MODEL", "gemini-2.5-flash-lite")
Comment thread api/main.py
Comment on lines +24 to +40
def _validate_config() -> None:
use_mock = os.getenv("USE_MOCK", "true").lower() == "true"
has_key = bool(os.getenv("BEACON_API_KEY", ""))

if not use_mock and not has_key:
raise RuntimeError(
"BEACON_API_KEY must be set when USE_MOCK=false. "
"Set it in api/.env or the environment."
)
if use_mock and not has_key:
logger.warning("AUTH DISABLED — BEACON_API_KEY not set (mock/dev mode only)")

# Eagerly initialise the provider so a missing GEMINI_API_KEY fails here
# with a clear message rather than producing a 503 on the first request.
get_provider()

_validate_config()
Comment thread api/main.py
Comment on lines +74 to 76
except ProviderConfigError as e:
logger.error("provider not configured: %s", e)
raise HTTPException(status_code=503, detail="LLM provider not configured. Set USE_MOCK=true.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants