Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix: scope same-origin web crawl to entry URL path by default (#63472)

Alex Vcdde539fab83
diff --git a/products/business_knowledge/backend/api/serializers.py b/products/business_knowledge/backend/api/serializers.py
index 09cb4197d485..4ae7e4fe58b3 100644
--- a/products/business_knowledge/backend/api/serializers.py
+++ b/products/business_knowledge/backend/api/serializers.py
@@ -1,5 +1,7 @@
"""DRF serializers for business_knowledge."""
+from urllib.parse import urlparse
+
from django.core.files.uploadedfile import UploadedFile
from django.utils import timezone
@@ -27,6 +29,21 @@ from ..models import (
)
+def _derive_scope_globs(url: str) -> list[str]:
+ """
+ Auto-derive include globs from the entry URL path so that same-origin
+ crawls are scoped to the URL's section by default.
+
+ - Root path (``/`` or empty) → empty list (crawl the whole origin).
+ - Non-root → ``[path, path/*]`` to match the index page + descendants
+ without sibling bleed (e.g. ``/docs/support`` won't grab ``/docs/support-center``).
+ """
+ path = urlparse(url).path.rstrip("/") or "/"
+ if path == "/":
+ return []
+ return [path, f"{path}/*"]
+
+
class _GlobListField(serializers.ListField):
"""
Tiny wrapper so each entry is validated as a non-empty string and the
@@ -271,6 +288,14 @@ class UpdateUrlSourceSerializer(_NameValidationMixin, _UrlValidationMixin, seria
attrs = super().to_internal_value(data)
crawl_config_keys = {"include_globs", "exclude_globs", "max_pages", "max_depth"}
crawl_fields = {k: attrs.pop(k) for k in crawl_config_keys if k in attrs}
+ # Re-derive scope when include_globs was NOT sent (user didn't override),
+ # the URL is changing, and mode is same-origin.
+ if (
+ "include_globs" not in crawl_fields
+ and "url" in attrs
+ and attrs.get("crawl_mode", data.get("crawl_mode")) == CrawlMode.SAME_ORIGIN.value
+ ):
+ crawl_fields["include_globs"] = _derive_scope_globs(attrs["url"])
if crawl_fields:
attrs["crawl_config"] = crawl_fields
return attrs
@@ -363,8 +388,11 @@ class CreateCrawlSourceSerializer(_NameValidationMixin, _UrlValidationMixin, ser
def to_internal_value(self, data: dict) -> dict:
attrs = super().to_internal_value(data)
attrs["source_type"] = SourceType.URL.value
+ include_globs = attrs.pop("include_globs")
+ if not include_globs and attrs.get("crawl_mode") == CrawlMode.SAME_ORIGIN.value:
+ include_globs = _derive_scope_globs(attrs["url"])
attrs["crawl_config"] = {
- "include_globs": attrs.pop("include_globs"),
+ "include_globs": include_globs,
"exclude_globs": attrs.pop("exclude_globs"),
"max_pages": attrs.pop("max_pages"),
"max_depth": attrs.pop("max_depth"),
diff --git a/products/business_knowledge/backend/tests/test_api.py b/products/business_knowledge/backend/tests/test_api.py
index f0eebf83ce16..12474ba5b44c 100644
--- a/products/business_knowledge/backend/tests/test_api.py
+++ b/products/business_knowledge/backend/tests/test_api.py
@@ -1,4 +1,4 @@
-from posthog.test.base import APIBaseTest
+from posthog.test.base import APIBaseTest, BaseTest
from unittest.mock import patch
from django.utils import timezone
@@ -9,6 +9,7 @@ from rest_framework import status
from posthog.models.activity_logging.activity_log import ActivityLog
from products.business_knowledge.backend import logic
+from products.business_knowledge.backend.api.serializers import _derive_scope_globs
from products.business_knowledge.backend.constants import CLASSIFY_MAX_ATTEMPTS
from products.business_knowledge.backend.models import KnowledgeChunk, KnowledgeDocument, KnowledgeSource, SafetyVerdict
@@ -406,3 +407,140 @@ class TestKnowledgeDocumentSearchScopes(APIBaseTest):
self._auth_with_pak(["insight:read"])
response = self.client.get(self.url)
assert response.status_code == status.HTTP_403_FORBIDDEN
+
+
+class TestDeriveScopeGlobs(BaseTest):
+ @parameterized.expand(
+ [
+ ("subpath", "https://posthog.com/docs/support", ["/docs/support", "/docs/support/*"]),
+ ("deep_subpath", "https://example.com/a/b/c", ["/a/b/c", "/a/b/c/*"]),
+ ("root_slash", "https://posthog.com/", []),
+ ("root_no_slash", "https://posthog.com", []),
+ ("trailing_slash_stripped", "https://example.com/docs/", ["/docs", "/docs/*"]),
+ ]
+ )
+ def test_derivation(self, _name: str, url: str, expected: list[str]) -> None:
+ assert _derive_scope_globs(url) == expected
+
+
+@patch("posthoganalytics.feature_enabled", return_value=True)
+@patch("products.business_knowledge.backend.api.serializers.is_url_allowed", return_value=(True, None))
+class TestCrawlSourceAutoScope(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.api_url = f"/api/projects/{self.team.id}/business_knowledge/sources/"
+
+ @patch("products.business_knowledge.backend.api.views.KnowledgeSourceViewSet._start_background_ingest")
+ @patch("products.business_knowledge.backend.api.views.logic.claim_url_source")
+ def test_same_origin_derives_globs_from_entry_url(self, mock_claim, _bg, _url, _ff) -> None:
+ mock_claim.return_value = KnowledgeSource(
+ id="00000000-0000-0000-0000-000000000001",
+ team=self.team,
+ name="Support docs",
+ source_type="url",
+ status="processing",
+ crawl_mode="same_origin",
+ crawl_config={
+ "include_globs": ["/docs/support", "/docs/support/*"],
+ "exclude_globs": [],
+ "max_pages": 50,
+ "max_depth": 2,
+ },
+ )
+ response = self.client.post(
+ self.api_url,
+ {
+ "source_type": "url",
+ "name": "Support docs",
+ "url": "https://posthog.com/docs/support",
+ "crawl_mode": "same_origin",
+ },
+ format="json",
+ )
+ assert response.status_code == status.HTTP_201_CREATED, response.content
+ call_kwargs = mock_claim.call_args.kwargs
+ assert call_kwargs["crawl_config"]["include_globs"] == ["/docs/support", "/docs/support/*"]
+
+ @patch("products.business_knowledge.backend.api.views.KnowledgeSourceViewSet._start_background_ingest")
+ @patch("products.business_knowledge.backend.api.views.logic.claim_url_source")
+ def test_explicit_include_globs_override_auto_scope(self, mock_claim, _bg, _url, _ff) -> None:
+ mock_claim.return_value = KnowledgeSource(
+ id="00000000-0000-0000-0000-000000000002",
+ team=self.team,
+ name="Custom",
+ source_type="url",
+ status="processing",
+ crawl_mode="same_origin",
+ crawl_config={"include_globs": ["/custom/*"], "exclude_globs": [], "max_pages": 50, "max_depth": 2},
+ )
+ response = self.client.post(
+ self.api_url,
+ {
+ "source_type": "url",
+ "name": "Custom",
+ "url": "https://posthog.com/docs/support",
+ "crawl_mode": "same_origin",
+ "include_globs": ["/custom/*"],
+ },
+ format="json",
+ )
+ assert response.status_code == status.HTTP_201_CREATED, response.content
+ call_kwargs = mock_claim.call_args.kwargs
+ assert call_kwargs["crawl_config"]["include_globs"] == ["/custom/*"]
+
+ @patch("products.business_knowledge.backend.api.views.KnowledgeSourceViewSet._start_background_ingest")
+ @patch("products.business_knowledge.backend.api.views.logic.claim_url_source")
+ def test_root_url_derives_empty_globs(self, mock_claim, _bg, _url, _ff) -> None:
+ mock_claim.return_value = KnowledgeSource(
+ id="00000000-0000-0000-0000-000000000003",
+ team=self.team,
+ name="Whole site",
+ source_type="url",
+ status="processing",
+ crawl_mode="same_origin",
+ crawl_config={"include_globs": [], "exclude_globs": [], "max_pages": 50, "max_depth": 2},
+ )
+ response = self.client.post(
+ self.api_url,
+ {
+ "source_type": "url",
+ "name": "Whole site",
+ "url": "https://posthog.com/",
+ "crawl_mode": "same_origin",
+ },
+ format="json",
+ )
+ assert response.status_code == status.HTTP_201_CREATED, response.content
+ call_kwargs = mock_claim.call_args.kwargs
+ assert call_kwargs["crawl_config"]["include_globs"] == []
+
+ @patch("products.business_knowledge.backend.api.views.KnowledgeSourceViewSet._start_background_ingest")
+ @patch("products.business_knowledge.backend.api.views.logic.update_url_source")
+ def test_update_url_rederives_globs_when_not_sent(self, mock_update, _bg, _url, _ff) -> None:
+ source = KnowledgeSource.objects.unscoped().create(
+ id="00000000-0000-0000-0000-000000000004",
+ team=self.team,
+ name="Old source",
+ source_type="url",
+ status="ready",
+ source_url="https://posthog.com/docs/old",
+ crawl_mode="same_origin",
+ crawl_config={
+ "include_globs": ["/docs/old", "/docs/old/*"],
+ "exclude_globs": [],
+ "max_pages": 50,
+ "max_depth": 2,
+ },
+ )
+ mock_update.return_value = source
+ response = self.client.patch(
+ f"{self.api_url}{source.id}/",
+ {
+ "url": "https://posthog.com/docs/new",
+ "crawl_mode": "same_origin",
+ },
+ format="json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.content
+ call_kwargs = mock_update.call_args.kwargs
+ assert call_kwargs["crawl_config"]["include_globs"] == ["/docs/new", "/docs/new/*"]
diff --git a/products/business_knowledge/frontend/components/CrawlConfigFields.tsx b/products/business_knowledge/frontend/components/CrawlConfigFields.tsx
index 94cbed781b79..000a608331ea 100644
--- a/products/business_knowledge/frontend/components/CrawlConfigFields.tsx
+++ b/products/business_knowledge/frontend/components/CrawlConfigFields.tsx
@@ -1,24 +1,39 @@
+import { LemonCollapse } from 'lib/lemon-ui/LemonCollapse'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonInput } from 'lib/lemon-ui/LemonInput'
import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'
-export function CrawlConfigFields({ crawlMode }: { crawlMode: string }): JSX.Element | null {
+function derivedScopeLabel(url: string): string {
+ try {
+ const parsed = new URL(url)
+ const path = parsed.pathname.replace(/\/+$/, '') || '/'
+ if (path === '/') {
+ return 'the whole site'
+ }
+ return `${parsed.hostname}${path} and pages under it`
+ } catch {
+ return 'pages at this URL'
+ }
+}
+
+export function CrawlConfigFields({ crawlMode, url }: { crawlMode: string; url: string }): JSX.Element | null {
if (crawlMode === 'single') {
return null
}
+
+ const isSameOrigin = crawlMode === 'same_origin'
+
return (
<>
- <LemonField
- name="include_globs"
- label="Include globs"
- info="URL path patterns to include. One per line or comma-separated. Empty = include everything."
- >
- <LemonTextArea minRows={2} placeholder={'/docs/*\n/handbook/*'} />
- </LemonField>
+ {isSameOrigin && url.trim() && (
+ <p className="text-xs text-muted mt-0">
+ Will index <strong>{derivedScopeLabel(url)}</strong>. Use "Skip paths" below to exclude sections.
+ </p>
+ )}
<LemonField
name="exclude_globs"
- label="Exclude globs"
- info="URL path patterns to exclude. Applied after include."
+ label="Skip paths"
+ info="URL path patterns to skip (fnmatch). One per line or comma-separated. E.g. /docs/internal/*"
>
<LemonTextArea minRows={2} placeholder="/docs/private/*" />
</LemonField>
@@ -26,12 +41,38 @@ export function CrawlConfigFields({ crawlMode }: { crawlMode: string }): JSX.Ele
<LemonField name="max_pages" label="Max pages" className="flex-1">
<LemonInput type="number" min={1} max={500} />
</LemonField>
- {crawlMode === 'same_origin' && (
+ {isSameOrigin && (
<LemonField name="max_depth" label="Max depth" className="flex-1">
<LemonInput type="number" min={0} max={5} />
</LemonField>
)}
</div>
+ <LemonCollapse
+ panels={[
+ {
+ key: 'advanced',
+ header: 'Advanced: override include scope',
+ content: (
+ <LemonField
+ name="include_globs"
+ label="Include globs"
+ info="Override the auto-derived scope. URL path patterns to include (fnmatch). One per line or comma-separated. Empty = scope to Entry URL path."
+ >
+ <LemonTextArea
+ minRows={2}
+ placeholder={
+ isSameOrigin
+ ? 'Leave empty to use entry URL path as scope'
+ : '/docs/*\n/handbook/*'
+ }
+ />
+ </LemonField>
+ ),
+ },
+ ]}
+ size="small"
+ embedded
+ />
</>
)
}
diff --git a/products/business_knowledge/frontend/components/CrawlModeHelp.tsx b/products/business_knowledge/frontend/components/CrawlModeHelp.tsx
index 918d8476afb6..3e58623e2dd7 100644
--- a/products/business_knowledge/frontend/components/CrawlModeHelp.tsx
+++ b/products/business_knowledge/frontend/components/CrawlModeHelp.tsx
@@ -21,7 +21,8 @@ export function CrawlModeHelp(): JSX.Element {
}
return (
<p className="text-xs text-muted">
- BFS-crawl from this URL staying on the same scheme + host + port. Honors robots.txt.
+ Indexes this page and everything under its path on the same site. Use "Skip paths" to carve out sections you
+ don't want; depth and max pages bound the crawl. Honors robots.txt.
</p>
)
}
diff --git a/products/business_knowledge/frontend/components/CreateKnowledgeSourceModal.tsx b/products/business_knowledge/frontend/components/CreateKnowledgeSourceModal.tsx
index 4847b32adfa4..da4b4cadd990 100644
--- a/products/business_knowledge/frontend/components/CreateKnowledgeSourceModal.tsx
+++ b/products/business_knowledge/frontend/components/CreateKnowledgeSourceModal.tsx
@@ -114,7 +114,7 @@ export function CreateKnowledgeSourceModal({
/>
</LemonField>
<CrawlModeHelp />
- <CrawlConfigFields crawlMode={urlSource.crawl_mode} />
+ <CrawlConfigFields crawlMode={urlSource.crawl_mode} url={urlSource.url} />
<LemonField
name="refresh_interval"
label="Auto-refresh"
diff --git a/products/business_knowledge/frontend/components/EditKnowledgeSourceModal.tsx b/products/business_knowledge/frontend/components/EditKnowledgeSourceModal.tsx
index 0400a4cfee83..a4ab52264ff4 100644
--- a/products/business_knowledge/frontend/components/EditKnowledgeSourceModal.tsx
+++ b/products/business_knowledge/frontend/components/EditKnowledgeSourceModal.tsx
@@ -65,7 +65,7 @@ export function EditKnowledgeSourceModal({
]}
/>
</LemonField>
- <CrawlConfigFields crawlMode={editUrlSource.crawl_mode} />
+ <CrawlConfigFields crawlMode={editUrlSource.crawl_mode} url={editUrlSource.url} />
<LemonField
name="refresh_interval"
label="Auto-refresh"
diff --git a/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.ts b/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.ts
index aca10495de98..33d3778a0c63 100644
--- a/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.ts
+++ b/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.ts
@@ -193,6 +193,7 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
} as UrlSourceFormValues,
errors: validateUrl,
submit: async (values: UrlSourceFormValues) => {
+ const includeGlobs = splitGlobs(values.include_globs)
const payload: CreateUrlSourcePayload = {
name: values.name,
url: values.url,
@@ -200,7 +201,9 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
crawl_mode: values.crawl_mode,
refresh_interval: values.refresh_interval,
...(values.crawl_mode !== 'single' && {
- include_globs: splitGlobs(values.include_globs),
+ // Only send include_globs when the user explicitly set them;
+ // otherwise the backend auto-derives scope from the entry URL path.
+ ...(includeGlobs.length > 0 && { include_globs: includeGlobs }),
exclude_globs: splitGlobs(values.exclude_globs),
max_pages: values.max_pages,
max_depth: values.max_depth,
@@ -319,13 +322,14 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
if (!current) {
return
}
+ const editIncludeGlobs = splitGlobs(vals.include_globs)
const payload: UpdateSourcePayload = {
name: vals.name,
url: vals.url,
crawl_mode: vals.crawl_mode,
refresh_interval: vals.refresh_interval,
...(vals.crawl_mode !== 'single' && {
- include_globs: splitGlobs(vals.include_globs),
+ ...(editIncludeGlobs.length > 0 && { include_globs: editIncludeGlobs }),
exclude_globs: splitGlobs(vals.exclude_globs),
max_pages: vals.max_pages,
max_depth: vals.max_depth,