Skip to content

The platform for continuously improving AI agents.

Serve robots.txt on the API host so search engines stop crawling API endpoints (#248)

samoverminde0741540040a
diff --git a/overbae/api/robots.py b/overbae/api/robots.py
new file mode 100644
index 00000000..23fad7f9
--- /dev/null
+++ b/overbae/api/robots.py
@@ -0,0 +1,17 @@
+"""robots.txt for the API host: crawlers stay out, except for /.well-known/.
+
+MCP OAuth discovery and app-verification fetches live under /.well-known/.
+"""
+
+from django.http import HttpResponse
+from django.views.decorators.http import require_safe
+
+# Allow comes first so first-match and longest-match parsers read the file the same way.
+ROBOTS_TXT = "User-agent: *\nAllow: /.well-known/\nDisallow: /\n"
+
+
+@require_safe
+def robots_txt(request):
+ """Plain Django on purpose: DRF's ``@api_view(["GET"])`` answers HEAD with 405 and
+ ``Accept: text/plain`` with 406, and neither is acceptable for a crawler fetch."""
+ return HttpResponse(ROBOTS_TXT, content_type="text/plain; charset=utf-8")
diff --git a/overbae/urls.py b/overbae/urls.py
index d2859d23..9ebdb600 100644
--- a/overbae/urls.py
+++ b/overbae/urls.py
@@ -50,6 +50,7 @@ from overbae.api.native_evaluation import NativeEvaluationViewSet
from overbae.api.optimizer import OptimizerCandidateViewSet, OptimizerExperimentViewSet
from overbae.api.otlp import otlp_traces
from overbae.api.public_models import PublicModelLibraryDetailView, PublicModelLibraryListView
+from overbae.api.robots import robots_txt
from overbae.api.signal_views import SignalEventViewSet, SignalSubscriptionViewSet
from overbae.api.sync import SyncView
from overbae.api.training_experiments import TrainingExperimentViewSet
@@ -169,6 +170,7 @@ urlpatterns += [
path("api/mcp-oauth/consent/", MCPConsentView.as_view(), name="mcp-oauth-consent"),
path(settings.ADMIN_URL_PATH, admin.site.urls),
path("health", health_check, name="health"),
+ path("robots.txt", robots_txt, name="robots-txt"),
path("api/v1/traces", otlp_traces, name="otlp-traces"),
path("v1/traces", otlp_traces, name="otlp-traces-compat"),
# OpenAI-compatible inference API
diff --git a/tests/test_api_robots.py b/tests/test_api_robots.py
new file mode 100644
index 00000000..4d2efc9e
--- /dev/null
+++ b/tests/test_api_robots.py
@@ -0,0 +1,75 @@
+"""The API host tells crawlers to stay out except /.well-known/, whatever credentials they send."""
+
+from urllib.robotparser import RobotFileParser
+
+import pytest
+from starlette.testclient import TestClient
+
+from overbae.asgi import application
+
+API_URL = "https://api.overmindlab.ai"
+BLOCKED_PATHS = ("/", "/api/capabilities/", "/api/docs/", "/health")
+FETCHABLE_PATHS = (
+ "/.well-known/oauth-authorization-server",
+ "/.well-known/openai-apps-challenge",
+)
+
+
+def client():
+ """Not entered as a context manager: the MCP session manager's lifespan can run only
+ once per process."""
+ return TestClient(application)
+
+
+def first_match_allows(rules: str, path: str) -> bool:
+ """A crawler that obeys the first rule matching the path, whatever its length."""
+ for line in rules.splitlines():
+ field, _, value = (part.strip() for part in line.partition(":"))
+ if field.lower() in ("allow", "disallow") and value and path.startswith(value):
+ return field.lower() == "allow"
+ return True
+
+
+def longest_match_allows(rules: str, path: str) -> bool:
+ """Google's reading (RFC 9309): the longest matching rule wins, and Allow wins a tie."""
+ best = (-1, True)
+ for line in rules.splitlines():
+ field, _, value = (part.strip() for part in line.partition(":"))
+ if field.lower() in ("allow", "disallow") and value and path.startswith(value):
+ best = max(best, (len(value), field.lower() == "allow"))
+ return best[1]
+
+
[email protected]("headers", [{}, {"X-Api-Key": "not-a-key"}])
+def test_robots_txt_blocks_crawlers_but_not_well_known_without_authentication(client, headers):
+ """A bad ``X-Api-Key`` must get the file too: DRF answers one with 401, even with AllowAny."""
+ response = client.get("/robots.txt", headers=headers)
+
+ assert response.status_code == 200
+ assert response.headers["content-type"].startswith("text/plain")
+ rules = RobotFileParser()
+ rules.parse(response.text.splitlines())
+ for agent in ("Googlebot", "bingbot", "SomeOtherBot"):
+ for path in BLOCKED_PATHS:
+ assert not rules.can_fetch(agent, f"{API_URL}{path}"), (agent, path)
+ for path in FETCHABLE_PATHS:
+ assert rules.can_fetch(agent, f"{API_URL}{path}"), (agent, path)
+
+
[email protected]("allows", [first_match_allows, longest_match_allows])
+def test_first_and_longest_match_crawlers_read_the_rules_the_same_way(client, allows):
+ """Google keeps the longest matching rule, simpler parsers the first one;
+ ``RobotFileParser`` only became longest-match in Python 3.13.14."""
+ rules = client.get("/robots.txt").text
+
+ assert not any(allows(rules, path) for path in BLOCKED_PATHS)
+ assert all(allows(rules, path) for path in FETCHABLE_PATHS)
+
+
+def test_head_robots_txt_is_answered_like_get(client):
+ """Fails if the view moves behind DRF's ``@api_view(["GET"])``, which answers HEAD with 405."""
+ response = client.head("/robots.txt")
+
+ assert response.status_code == 200
+ assert response.headers["content-type"].startswith("text/plain")