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.

chore(hogql): add a local language service playground (#101600)

Paweł Szczura6f7ebb9bf06
diff --git a/docs/internal/hogql-language-service-demo.md b/docs/internal/hogql-language-service-demo.md
new file mode 100644
index 000000000000..1ec75afa42e6
--- /dev/null
+++ b/docs/internal/hogql-language-service-demo.md
@@ -0,0 +1,120 @@
+# Local HogQL playground
+
+The playground embeds the real Go language service's HTTP handlers in the demo process.
+It loads a synthetic catalog and serves a small browser editor, without Django, ClickHouse, project data, or credentials.
+It does not execute queries.
+
+## Run
+
+From the repository root:
+
+```bash
+.codex/with-flox env GOTOOLCHAIN=auto go -C services/hogql-language-service run ./cmd/demo
+```
+
+Open <http://127.0.0.1:8092>.
+Use `-port 8093` after `./cmd/demo` if the default port is occupied.
+For port forwarding, bind the demo page to all interfaces:
+
+```bash
+.codex/with-flox env GOTOOLCHAIN=auto go -C services/hogql-language-service run ./cmd/demo -host 0.0.0.0
+```
+
+Forward port `8092` and open the forwarded URL.
+This mode accepts the forwarded hostname and HTTP or HTTPS origins matching that hostname.
+The demo has no authentication; use your development environment's private forwarding controls.
+Only the demo page listens on a port; the embedded service has no separate listener.
+Go may download the module's required toolchain on the first run.
+Agents must request elevated execution when starting the demo because it opens a local HTTP listener.
+
+The demo and `cmd/server` share `internal/httpapi`, including request decoding, completion, validation, response encoding, and rate limiting.
+The demo seeds a private in-memory catalog for synthetic team 1 / user 1 and dispatches requests directly to those handlers.
+It does not spawn subprocesses, build another binary, poll readiness, or use an HTTP client.
+Demo settings are explicit and do not read production service environment variables.
+It does not connect to or modify an existing development service.
+The catalog lives in memory with a 24-hour TTL; restart the demo to refresh it.
+Ctrl+C stops the demo server.
+The page defaults to `127.0.0.1` and accepts requests for its own host and origin.
+Binding to `0.0.0.0` or `::` permits other hostnames for forwarding while still rejecting cross-origin browser requests.
+
+The production Dockerfile builds only `cmd/server` and copies only that binary into its final image.
+The demo command, its embedded browser assets, and synthetic catalog are not included in that binary or final image.
+Production authentication and environment configuration remain in `cmd/server`.
+The demo exposes only fixed-scope completion and validation adapters, not the service's catalog mutation routes.
+Do not add the demo to deployment configuration or the production server's routes.
+
+## Manual checks
+
+- Select **Event fields**, click **Complete at cursor**, then click a suggestion to insert it.
+- Select **Valid CTE** and click **Validate**. The service should accept the query and list `events` as its underlying table.
+- Select **Unknown field** or **Unknown table** to inspect diagnostics and typo suggestions.
+- Select **Unicode diagnostic offsets**, validate, and click the diagnostic. It should select `timstamp`, even with the emoji earlier in the query.
+- Select **Property pagination** and use **Load more** to retrieve all 35 matching names.
+- Select **Quoted identifiers** and insert `billing address` to inspect identifier quoting. The service supplies quoted insertion text; the page does not add quotes.
+- Use **CTE completion** and **Subquery completion** to inspect current derived-relation support. Empty suggestions are shown as returned by the service, without a browser fallback.
+- Open raw responses to inspect parser errors, diagnostics, pagination cursors, physical table names, and catalog revisions.
+
+Ctrl/Command+Enter validates; Ctrl/Command+Shift+Enter completes.
+Ctrl+Space is left available for the operating system's input-source shortcut.
+Enable **Analyze as you type** to run both operations after a 300 ms typing pause.
+The checkbox is off by default. Enabling it also analyzes the current query; loading an example or inserting a suggestion schedules analysis too.
+Turning it off cancels scheduled analysis and in-flight requests. Manual buttons and shortcuts remain available.
+Empty queries and unfinished input-method composition do not trigger automatic requests.
+Completion requests use UTF-16 offsets, matching the textarea selection API.
+Validation requests explicitly select UTF-8 offsets; the page converts those byte ranges to UTF-16 for diagnostic selection.
+Raw responses and copied exchanges keep the service's original offsets.
+The page shows service time separately from browser round-trip time.
+Editing the query clears results and cancels pending requests; moving the cursor clears completion results.
+
+## Share a reproduction
+
+Each result panel has a **Copy request and response** button.
+It copies a JSON record of the most recent completed request for that operation, including the original query, completion cursor position and pagination cursor, completion encoding, HTTP status, and full response with catalog revision.
+The browser path and corresponding service path are included for replay.
+HTTP errors retain their response body, and network errors retain their request and error message.
+Canceled requests do not replace the last captured exchange.
+
+Each panel keeps one captured exchange when you edit the query or move the cursor; the next completed request for that operation replaces it.
+For pagination, the copied exchange represents the latest page, including the cursor used to request it.
+Turn off **Analyze as you type** to keep a reproduction while experimenting further.
+The capture is kept only in page memory and is lost on refresh.
+
+If clipboard access is unavailable, including on some HTTP forwarded URLs, the button opens and selects the captured JSON so you can press Ctrl/Command+C.
+Paste it with a short description of the expected suggestions to report an autocomplete issue.
+The demo does not send feedback anywhere automatically.
+
+## Catalog
+
+`services/hogql-language-service/cmd/demo/catalog.go` defines a hand-maintained subset of the public HogQL schema shapes for `events`, `persons`, `sessions`, and `groups`.
+It also defines invented `postgres.demo.orders` and `demo_customers` warehouse tables, event/person/session/group property namespaces, and 35 `demo_property_*` names for pagination.
+Only names and types are present; there are no event rows, person records, customer examples, or production schema exports.
+The sidebar and `/api/catalog` display the exact catalog published to the service.
+To change it, edit `catalog.go` and restart the command.
+
+## Exclusions and follow-up work
+
+These are deliberate boundaries of the demo or service behavior to investigate later.
+They are not evidence that a query would succeed or fail in the full PostHog compiler.
+
+| Area | Current boundary and reason | Follow-up and acceptance check |
+| -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Full PostHog catalog parity | The fixture is a small, static subset so the demo runs without Django. Virtual joins and all product tables are not modeled completely. | Add an optional catalog generator using a synthetic local project. Compare its published schema with Django's catalog for that project and document required services. |
+| Derived-relation completion | The page does not synthesize CTE or subquery fields when the service returns no suggestions. This keeps service gaps visible. | Implement the shared query analyzer, then use the CTE and subquery examples to verify projected fields, aliases, and types in both completion and validation. |
+| Identifier quoting | The page uses the service's quoted `insertText`. Completion inside an already quoted identifier is not supported by the textarea adapter. | Add quote-aware token replacement before supporting completion inside existing quotes. Check escaped backticks and mid-token edits. |
+| Alias and property semantics | The demo does not correct select-alias visibility, property provenance through CTEs, or shadowing behavior. | Extend the analyzer with Python-resolver-backed scope rules. Check a CTE named `events` that projects person properties, and aliases used in `WHERE`, `GROUP BY`, `HAVING`, and `ORDER BY`. |
+| Other HogQL constructs | Examples do not establish coverage for unions, scalar `WITH` aliases, CTE column-name lists, recursive CTEs, or every dialect. | Decide supported constructs explicitly in the analyzer design; add examples and observable regression coverage for each supported construct. Retain the service's exclusion of recursive CTE support unless that scope changes. |
+| Query execution and compiler parity | No database or Python metadata endpoint is called; validation reflects only this Go service. | Add an opt-in comparison mode against a synthetic local Django project if compiler parity testing is needed. Keep execution separate and explicitly enabled. |
+| Editor integration | A textarea keeps the page dependency-free. Optional debounced validation and completion run after edits. Monaco highlighting, squiggles, and completion inside already quoted identifiers are not provided. Insertion replaces an ordinary identifier around the captured cursor. | Add a locally bundled editor adapter when testing editor behavior, with cursor/range tests for quoted names, escaped characters, and mid-token edits. |
+| Custom catalog editing and permissions | One synthetic team/user catalog is seeded at startup. There is no upload UI, identity picker, catalog refresh button, permission mutation, or JWT workflow. | Add isolated synthetic catalog variants for permission/tenant testing; verify catalog revisions and isolation through authenticated endpoints before adding identity controls. |
+| Performance conclusions | The fixture is small and timings are exploratory. This page is not a load test or latency acceptance gate. | Use the existing large-catalog benchmarks and dedicated latency test; add query-shape benchmarks for the shared analyzer as needed. |
+| Hosting and production | Private development port forwarding is supported with `-host 0.0.0.0`. The demo serves HTTP without authentication or built-in TLS and stays excluded from production. | Use authenticated development forwarding. Public hosting would need a separate authentication and TLS design; production service endpoints remain outside this demo. |
+| Persistence | Query text and results live only in the page; refreshing discards them. This avoids silently storing pasted query text. | If useful, add explicit local export/import of synthetic examples with a documented file format. |
+
+## Verification
+
+```bash
+.codex/with-flox env GOTOOLCHAIN=auto go -C services/hogql-language-service test ./cmd/demo
+.codex/with-flox env GOTOOLCHAIN=auto go -C services/hogql-language-service vet ./cmd/demo
+```
+
+Browser checks must exercise this page against the embedded service, including completion insertion, pagination, Unicode diagnostic selection, stale-response handling, and a narrow desktop window.
diff --git a/docs/internal/hogql-language-service.md b/docs/internal/hogql-language-service.md
index a756abcca52a..6ae16c1d4b3b 100644
--- a/docs/internal/hogql-language-service.md
+++ b/docs/internal/hogql-language-service.md
@@ -135,6 +135,12 @@ Measurements must separate catalog lookup, parsing, translation, network transit
decoding, and serialization. A combined translation and execution path is justified only if the extra service hop
prevents the overhead target.
+## Local playground
+
+For manual development testing, the separate [local playground](hogql-language-service-demo.md) embeds the shared HTTP handlers with an isolated synthetic catalog and a browser editor.
+It is excluded from the production binary and container image.
+Its guide records catalog approximations, unsupported workflows, and follow-up checks.
+
## Non-goals
- Reimplementing PostHog membership or permission resolution in Go.
diff --git a/services/hogql-language-service/cmd/demo/assets/app.js b/services/hogql-language-service/cmd/demo/assets/app.js
new file mode 100644
index 000000000000..57461e61ff28
--- /dev/null
+++ b/services/hogql-language-service/cmd/demo/assets/app.js
@@ -0,0 +1,450 @@
+const byId = (id) => document.getElementById(id)
+const editor = byId('query')
+const examples = [
+ {
+ name: 'Event fields',
+ query: 'SELECT e.§\nFROM events AS e\nLIMIT 100',
+ note: 'Complete after e. to explore event fields.',
+ },
+ {
+ name: 'Valid CTE',
+ query: "WITH recent AS (\n SELECT uuid, event, timestamp\n FROM events\n WHERE event = '$pageview'\n)\nSELECT uuid FROM recent§",
+ note: 'Validate a CTE with an unqualified projected field.',
+ },
+ {
+ name: 'CTE completion',
+ query: 'WITH recent AS (\n SELECT uuid, event AS event_name FROM events\n)\nSELECT recent.§ FROM recent',
+ note: 'Probe CTE completion. Missing projected suggestions are a service limitation.',
+ },
+ {
+ name: 'Subquery completion',
+ query: 'SELECT nested.§\nFROM (SELECT person_id, count() AS event_count FROM events GROUP BY person_id) AS nested',
+ note: 'Probe derived fields. The demo shows exactly what the service supports.',
+ },
+ {
+ name: 'Event properties',
+ query: 'SELECT e.properties.$§\nFROM events AS e',
+ note: 'Complete event property names from the synthetic catalog.',
+ },
+ {
+ name: 'Person properties',
+ query: 'SELECT p.properties.§\nFROM persons AS p',
+ note: 'Complete person properties through a table alias.',
+ },
+ {
+ name: 'Property pagination',
+ query: 'SELECT properties.demo_property_§ FROM events',
+ note: 'There are 35 matching synthetic properties. Use Load more to test pagination.',
+ },
+ {
+ name: 'Unknown field',
+ query: 'SELECT timstamp§ FROM events',
+ note: 'Validate to see a typo suggestion. Click a diagnostic to select its range.',
+ },
+ {
+ name: 'Unknown table',
+ query: 'SELECT uuid FROM evnts§',
+ note: 'Validate to see the unknown-table diagnostic and suggested match.',
+ },
+ {
+ name: 'Warehouse table',
+ query: 'SELECT o.§ FROM postgres.demo.orders AS o',
+ note: 'Test a three-part synced-table name.',
+ },
+ {
+ name: 'Quoted identifiers',
+ query: 'SELECT c.§ FROM demo_customers AS c',
+ note: 'Insert billing address or café to check identifier quoting.',
+ },
+ {
+ name: 'Unicode diagnostic offsets',
+ query: "SELECT '😀', timstamp§ FROM events",
+ note: 'Validate, then click the diagnostic. The selected range should be timstamp.',
+ },
+]
+
+let catalog = null
+let selection = { query: '', position: 0 }
+let completionSnapshot = null
+let nextCursor = ''
+let analysisTimer = null
+let composing = false
+const requests = { validation: null, completion: null }
+const feedback = { validation: '', completion: '' }
+const copying = { validation: false, completion: false }
+
+function captureFeedback(kind, exchange) {
+ feedback[kind] = JSON.stringify(exchange, null, 2)
+ byId(`${kind}-feedback`).value = feedback[kind]
+ byId(`${kind}-copy`).disabled = copying[kind]
+ byId(`${kind}-copy-status`).textContent = 'Last completed request, retained when the editor changes.'
+}
+
+async function copyFeedback(kind) {
+ const text = feedback[kind]
+ if (!text || copying[kind]) {
+ return
+ }
+ copying[kind] = true
+ byId(`${kind}-copy`).disabled = true
+ try {
+ await navigator.clipboard.writeText(text)
+ byId(`${kind}-copy-status`).textContent = 'Copied request and response.'
+ } catch {
+ byId(`${kind}-feedback-details`).open = true
+ const field = byId(`${kind}-feedback`)
+ field.value = text
+ field.focus()
+ field.select()
+ byId(`${kind}-copy-status`).textContent =
+ 'Clipboard access is unavailable. Press Ctrl/⌘ C to copy the selected text.'
+ } finally {
+ copying[kind] = false
+ byId(`${kind}-copy`).disabled = false
+ }
+}
+
+function node(tag, text, className = '') {
+ const element = document.createElement(tag)
+ element.textContent = text
+ element.className = className
+ return element
+}
+
+function setBusy(kind, busy) {
+ if (kind === 'validation') {
+ byId('validate').disabled = busy
+ byId('validate').textContent = busy ? 'Validating…' : 'Validate'
+ } else {
+ byId('complete').disabled = busy
+ byId('more').disabled = busy
+ byId('complete').textContent = busy ? 'Completing…' : 'Complete at cursor'
+ }
+}
+
+function invalidate(kind) {
+ requests[kind]?.abort()
+ requests[kind] = null
+ setBusy(kind, false)
+ byId(`${kind}-time`).textContent = ''
+ byId(`${kind}-json`).textContent = 'No request for this editor state.'
+ if (kind === 'validation') {
+ byId('validation').replaceChildren(node('p', 'Validate the query to see diagnostics.', 'muted'))
+ } else {
+ completionSnapshot = null
+ nextCursor = ''
+ byId('suggestions').replaceChildren()
+ byId('more').hidden = true
+ byId('completion-status').textContent = 'Place the cursor where you want suggestions.'
+ }
+}
+
+function cancelScheduledAnalysis() {
+ clearTimeout(analysisTimer)
+ analysisTimer = null
+}
+
+function scheduleAnalysis() {
+ cancelScheduledAnalysis()
+ if (!byId('auto-analyze').checked || composing || !editor.value.trim()) {
+ return
+ }
+ analysisTimer = setTimeout(() => {
+ analysisTimer = null
+ validate()
+ complete()
+ }, 300)
+}
+
+function syncSelection() {
+ const queryChanged = selection.query !== editor.value
+ if (queryChanged) {
+ invalidate('validation')
+ }
+ if (queryChanged || selection.position !== editor.selectionStart) {
+ invalidate('completion')
+ }
+ selection = { query: editor.value, position: editor.selectionStart }
+ const before = editor.value.slice(0, editor.selectionStart)
+ const lines = before.split('\n')
+ byId('position').textContent =
+ `Line ${lines.length}, column ${lines.at(-1).length + 1} · UTF-16 offset ${editor.selectionStart}`
+ if (queryChanged) {
+ scheduleAnalysis()
+ }
+}
+
+async function request(kind, payload, onResult) {
+ if (requests[kind]) {
+ return
+ }
+ const controller = new AbortController()
+ requests[kind] = controller
+ setBusy(kind, true)
+ const started = performance.now()
+ const endpoint = kind === 'completion' ? 'autocomplete' : 'validate'
+ const requestBody = kind === 'completion' ? { ...payload, positionEncoding: 'utf-16' } : payload
+ const exchange = {
+ operation: endpoint,
+ recordedAt: new Date().toISOString(),
+ catalogSource: 'services/hogql-language-service/cmd/demo/catalog.go',
+ request: {
+ method: 'POST',
+ path: `/api/${endpoint}`,
+ servicePath: `/teams/1/users/1/${endpoint}`,
+ body: requestBody,
+ },
+ response: null,
+ }
+ try {
+ const response = await fetch(`/api/${endpoint}`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(requestBody),
+ signal: controller.signal,
+ })
+ const body = await response.text()
+ if (requests[kind] !== controller) {
+ return
+ }
+ let responseBody = body
+ try {
+ responseBody = JSON.parse(body)
+ } catch {}
+ exchange.response = {
+ status: response.status,
+ contentType: response.headers.get('Content-Type'),
+ body: responseBody,
+ }
+ captureFeedback(kind, exchange)
+ if (!response.ok) {
+ throw new Error(`HTTP ${response.status}: ${body}`)
+ }
+ const data = JSON.parse(body)
+ if (requests[kind] !== controller) {
+ return
+ }
+ byId(`${kind}-json`).textContent = JSON.stringify(data, null, 2)
+ byId(`${kind}-time`).textContent =
+ `${(data.durationMicros / 1000).toFixed(2)} ms service · ${(performance.now() - started).toFixed(0)} ms round trip`
+ onResult(data)
+ } catch (error) {
+ if (controller.signal.aborted) {
+ return
+ }
+ if (!exchange.response) {
+ captureFeedback(kind, { ...exchange, error: error.message })
+ }
+ const message = `${error.message} Retry the request, or restart the demo if the service stopped.`
+ byId(`${kind}-json`).textContent = message
+ if (kind === 'validation') {
+ byId('validation').replaceChildren(node('p', message, 'bad'))
+ } else {
+ byId('completion-status').textContent = message
+ }
+ } finally {
+ if (requests[kind] === controller) {
+ requests[kind] = null
+ setBusy(kind, false)
+ }
+ }
+}
+
+function validate() {
+ syncSelection()
+ const snapshot = editor.value
+ return request('validation', { query: snapshot, positionEncoding: 'utf-8' }, (data) => {
+ const queryBytes = new TextEncoder().encode(snapshot)
+ const editorOffset = (byteOffset) => new TextDecoder().decode(queryBytes.subarray(0, byteOffset)).length
+ const result = byId('validation')
+ result.replaceChildren(
+ node(
+ 'p',
+ data.valid ? 'Valid according to the Go service.' : `${data.diagnostics.length} diagnostic(s)`,
+ data.valid ? 'good' : 'bad'
+ )
+ )
+ result.append(node('p', `Referenced tables: ${data.tableNames?.join(', ') || 'none'}`, 'hint'))
+ for (const diagnostic of data.diagnostics) {
+ const button = node('button', diagnostic.message, 'diagnostic')
+ button.type = 'button'
+ button.append(node('small', `${diagnostic.code} · UTF-8 bytes ${diagnostic.start}–${diagnostic.end}`))
+ if (diagnostic.suggestions?.length) {
+ button.append(node('small', `Suggestions: ${diagnostic.suggestions.map((s) => s.label).join(', ')}`))
+ }
+ button.addEventListener('click', () => {
+ if (editor.value !== snapshot) {
+ return
+ }
+ editor.focus()
+ editor.setSelectionRange(editorOffset(diagnostic.start), editorOffset(diagnostic.end))
+ syncSelection()
+ })
+ result.append(button)
+ }
+ })
+}
+
+function insertSuggestion(suggestion, snapshot) {
+ if (editor.value !== snapshot.query || editor.selectionStart !== snapshot.position) {
+ return
+ }
+ const before = snapshot.query.slice(0, snapshot.position)
+ const prefix = before.match(/[\p{L}\p{N}_$]*$/u)[0]
+ const suffix = snapshot.query.slice(snapshot.position).match(/^[\p{L}\p{N}_$]*/u)[0]
+ editor.focus()
+ editor.setRangeText(
+ suggestion.insertText || suggestion.label,
+ snapshot.position - prefix.length,
+ snapshot.position + suffix.length,
+ 'end'
+ )
+ syncSelection()
+}
+
+function complete(more = false) {
+ syncSelection()
+ if (requests.completion) {
+ return
+ }
+ const snapshot = { ...selection }
+ const cursor = more ? nextCursor : ''
+ if (more && (!completionSnapshot || !cursor)) {
+ return
+ }
+ if (!more) {
+ byId('suggestions').replaceChildren()
+ byId('more').hidden = true
+ }
+ return request('completion', { ...snapshot, cursor }, (data) => {
+ completionSnapshot = snapshot
+ nextCursor = data.nextCursor || ''
+ for (const suggestion of data.suggestions || []) {
+ const button = node('button', '', 'suggestion')
+ button.type = 'button'
+ button.append(node('span', suggestion.label), node('small', suggestion.detail || suggestion.kind))
+ button.title = `Insert ${suggestion.insertText || suggestion.label}`
+ button.addEventListener('click', () => insertSuggestion(suggestion, snapshot))
+ byId('suggestions').append(button)
+ }
+ const shown = byId('suggestions').childElementCount
+ byId('completion-status').textContent = data.total
+ ? `${shown} of ${data.total} suggestions. Click to insert.`
+ : 'No suggestions at this cursor. Check the catalog or try another example.'
+ if (data.parseError) {
+ byId('completion-status').textContent += ` Parser: ${data.parseError}`
+ }
+ byId('more').hidden = !nextCursor
+ })
+}
+
+function renderCatalog() {
+ if (!catalog) {
+ return
+ }
+ const filter = byId('catalog-filter').value.toLowerCase()
+ const root = byId('catalog')
+ root.replaceChildren()
+ const groups = Object.entries(catalog.tables).map(([name, table]) => [name, Object.values(table.fields)])
+ for (const [name, properties] of Object.entries(catalog.properties)) {
+ groups.push([`${name} properties`, properties.map((p) => ({ name: p.name, type: p.property_type }))])
+ }
+ for (const [name, fields] of groups) {
+ const visible = fields.filter((field) => `${name} ${field.name}`.toLowerCase().includes(filter))
+ if (!visible.length) {
+ continue
+ }
+ const details = node('details', '')
+ details.open = !!filter || name === 'events'
+ details.append(node('summary', `${name} (${visible.length})`))
+ for (const field of visible.sort((a, b) => a.name.localeCompare(b.name))) {
+ const row = node('div', '', 'catalog-field')
+ row.append(node('span', field.name), node('span', field.type))
+ details.append(row)
+ }
+ root.append(details)
+ }
+ if (!root.childElementCount) {
+ root.append(node('p', 'No matching fields. Try another search.', 'muted'))
+ }
+}
+
+function loadExample() {
+ const example = examples[Number(byId('example').value)]
+ const position = example.query.indexOf('§')
+ editor.value = example.query.replace('§', '')
+ editor.focus()
+ editor.setSelectionRange(position, position)
+ byId('example-note').textContent = example.note
+ syncSelection()
+}
+
+for (const [index, example] of examples.entries()) {
+ const option = node('option', example.name)
+ option.value = String(index)
+ byId('example').append(option)
+}
+byId('example').addEventListener('change', loadExample)
+byId('validate').addEventListener('click', validate)
+byId('complete').addEventListener('click', () => complete())
+byId('more').addEventListener('click', () => complete(true))
+byId('catalog-filter').addEventListener('input', renderCatalog)
+for (const kind of Object.keys(feedback)) {
+ byId(`${kind}-copy`).addEventListener('click', () => copyFeedback(kind))
+}
+byId('auto-analyze').addEventListener('change', () => {
+ scheduleAnalysis()
+ if (!byId('auto-analyze').checked) {
+ for (const kind of Object.keys(requests)) {
+ if (requests[kind]) {
+ invalidate(kind)
+ }
+ }
+ }
+})
+editor.addEventListener('compositionstart', () => {
+ composing = true
+ cancelScheduledAnalysis()
+})
+editor.addEventListener('compositionend', () => {
+ composing = false
+ syncSelection()
+ scheduleAnalysis()
+})
+window.addEventListener('pagehide', () => {
+ cancelScheduledAnalysis()
+ for (const kind of Object.keys(requests)) {
+ if (requests[kind]) {
+ invalidate(kind)
+ }
+ }
+})
+for (const event of ['input', 'keyup', 'click', 'select']) {
+ editor.addEventListener(event, syncSelection)
+}
+editor.addEventListener('keydown', (event) => {
+ if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') {
+ event.preventDefault()
+ if (event.shiftKey) {
+ complete()
+ } else {
+ validate()
+ }
+ }
+})
+loadExample()
+fetch('/api/catalog')
+ .then(async (response) => {
+ if (!response.ok) {
+ throw new Error(`HTTP ${response.status}`)
+ }
+ const publication = await response.json()
+ catalog = publication.catalog
+ renderCatalog()
+ byId('connection').textContent =
+ `${Object.keys(catalog.tables).length} synthetic tables loaded · ${publication.revision}`
+ })
+ .catch((error) => {
+ byId('connection').textContent =
+ `Could not load the catalog: ${error.message}. Refresh the page or restart the demo.`
+ })
diff --git a/services/hogql-language-service/cmd/demo/assets/index.html b/services/hogql-language-service/cmd/demo/assets/index.html
new file mode 100644
index 000000000000..e06515f50c84
--- /dev/null
+++ b/services/hogql-language-service/cmd/demo/assets/index.html
@@ -0,0 +1,146 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>HogQL local playground</title>
+ <link rel="stylesheet" href="/style.css" />
+ <script src="/app.js" defer></script>
+ </head>
+ <body>
+ <header>
+ <div>
+ <span class="eyebrow">Developer tools</span>
+ <h1>HogQL playground</h1>
+ </div>
+ <span class="badge">Local only · synthetic catalog</span>
+ </header>
+ <p class="intro">
+ Try autocomplete and validation against a separate instance of the Go language service. Queries are
+ analyzed, never executed.
+ </p>
+ <main>
+ <section class="workspace">
+ <div class="editor panel">
+ <div class="section-heading">
+ <h2>Query</h2>
+ <span id="position" class="muted"></span>
+ </div>
+ <label for="example">Load an example</label>
+ <select id="example"></select>
+ <p id="example-note" class="hint"></p>
+ <label for="query" class="sr-only">HogQL query</label>
+ <textarea
+ id="query"
+ spellcheck="false"
+ autocapitalize="off"
+ autocomplete="off"
+ aria-describedby="editor-help"
+ ></textarea>
+ <div class="toolbar">
+ <button id="validate" class="primary" type="button">Validate</button>
+ <button id="complete" type="button">Complete at cursor</button>
+ <label class="checkbox-label">
+ <input id="auto-analyze" type="checkbox" />
+ Analyze as you type
+ </label>
+ <span id="editor-help" class="hint">Ctrl/⌘ Enter: validate · Ctrl/⌘ Shift Enter: complete</span>
+ </div>
+ <p id="connection" class="hint" role="status">Loading the synthetic catalog…</p>
+ </div>
+ <div class="results">
+ <section class="panel" aria-labelledby="validation-title">
+ <div class="section-heading">
+ <h2 id="validation-title">Validation</h2>
+ <span id="validation-time" class="muted"></span>
+ </div>
+ <div id="validation" aria-live="polite">
+ <p class="muted">Validate the query to see diagnostics.</p>
+ </div>
+ <button id="validation-copy" type="button" disabled>Copy request and response</button>
+ <p id="validation-copy-status" class="hint" role="status"></p>
+ <details id="validation-feedback-details">
+ <summary>Last validation request and response</summary>
+ <textarea
+ id="validation-feedback"
+ class="feedback-text"
+ readonly
+ spellcheck="false"
+ aria-label="Validation request and response"
+ ></textarea>
+ </details>
+ <details>
+ <summary>Raw validation response</summary>
+ <pre id="validation-json">No request yet.</pre>
+ </details>
+ </section>
+ <section class="panel" aria-labelledby="completion-title">
+ <div class="section-heading">
+ <h2 id="completion-title">Completion</h2>
+ <span id="completion-time" class="muted"></span>
+ </div>
+ <p id="completion-status" class="hint" aria-live="polite">
+ Place the cursor where you want suggestions.
+ </p>
+ <div id="suggestions"></div>
+ <button id="more" type="button" hidden>Load more</button>
+ <button id="completion-copy" type="button" disabled>Copy request and response</button>
+ <p id="completion-copy-status" class="hint" role="status"></p>
+ <details id="completion-feedback-details">
+ <summary>Last completion request and response</summary>
+ <textarea
+ id="completion-feedback"
+ class="feedback-text"
+ readonly
+ spellcheck="false"
+ aria-label="Completion request and response"
+ ></textarea>
+ </details>
+ <details>
+ <summary>Raw completion response</summary>
+ <pre id="completion-json">No request yet.</pre>
+ </details>
+ </section>
+ </div>
+ </section>
+ <aside class="panel" aria-labelledby="catalog-title">
+ <div class="section-heading">
+ <h2 id="catalog-title">Synthetic catalog</h2>
+ <a href="/api/catalog" target="_blank" rel="noopener">View JSON</a>
+ </div>
+ <p class="hint">
+ A small PostHog-like schema with invented warehouse tables and property names. No project data is
+ loaded.
+ </p>
+ <label for="catalog-filter">Filter fields and properties</label>
+ <input id="catalog-filter" type="search" placeholder="For example, timestamp" />
+ <div id="catalog"></div>
+ <details class="limitations">
+ <summary>Scope and limitations</summary>
+ <p>
+ This page calls the real Go autocomplete and validate endpoints. It does not run SQL or compare
+ results with Django.
+ </p>
+ <p>
+ CTE and subquery examples help expose gaps in the service. The page displays its responses
+ without filling in suggestions itself.
+ </p>
+ <p>
+ The catalog is a hand-maintained subset. Virtual joins, all product tables, and project-specific
+ schemas are not modeled completely.
+ </p>
+ <p>
+ Enable Analyze as you type to validate and complete after a short typing pause, or use the
+ buttons and shortcuts. Click a suggestion to insert it. Results clear when you edit the query or
+ move the completion cursor.
+ </p>
+ <p>
+ Follow-up work and exclusions are tracked in
+ <code>docs/internal/hogql-language-service-demo.md</code>.
+ </p>
+ </details>
+ </aside>
+ </main>
+ <footer>UTF-16 editor positions · In-memory catalog · No Django or ClickHouse required</footer>
+ </body>
+</html>
diff --git a/services/hogql-language-service/cmd/demo/assets/style.css b/services/hogql-language-service/cmd/demo/assets/style.css
new file mode 100644
index 000000000000..3020588abde0
--- /dev/null
+++ b/services/hogql-language-service/cmd/demo/assets/style.css
@@ -0,0 +1,348 @@
+:root {
+ font-family: system-ui, sans-serif;
+ color: #242424;
+ color-scheme: light;
+ background: #f5f4f0;
+}
+
+* {
+ box-sizing: border-box;
+}
+
+body {
+ max-width: 1600px;
+ padding: 32px;
+ margin: 0 auto;
+}
+
+header,
+.section-heading,
+.toolbar {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 12px;
+ align-items: center;
+ justify-content: space-between;
+}
+
+.checkbox-label {
+ display: inline-flex;
+ gap: 7px;
+ align-items: center;
+ margin: 0;
+ font-weight: 400;
+ cursor: pointer;
+}
+
+.checkbox-label input {
+ width: auto;
+ margin: 0;
+ accent-color: #242424;
+}
+
+h1 {
+ margin: 5px 0 0;
+ font-size: 28px;
+ letter-spacing: -0.7px;
+}
+
+h2 {
+ margin: 0;
+ font-size: 16px;
+}
+
+.eyebrow {
+ font-size: 12px;
+ color: #666;
+}
+
+.badge {
+ padding: 6px 10px;
+ font-size: 12px;
+ background: #ffefc6;
+ border: 1px solid #e6d19d;
+ border-radius: 6px;
+}
+
+.intro {
+ margin: 20px 0 24px;
+ font-size: 14px;
+ line-height: 1.6;
+ color: #65625d;
+}
+
+main {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) 310px;
+ gap: 20px;
+ align-items: start;
+}
+
+.workspace {
+ min-width: 0;
+ container-type: inline-size;
+}
+
+.panel {
+ min-width: 0;
+ padding: 20px;
+ background: #fffefa;
+ border: 1px solid #dfdcd4;
+ border-radius: 10px;
+}
+
+.section-heading {
+ margin-bottom: 18px;
+}
+
+.results {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 16px;
+ margin-top: 16px;
+}
+
+label {
+ display: block;
+ margin-bottom: 7px;
+ font-size: 12px;
+ font-weight: 600;
+}
+
+select,
+input,
+textarea,
+button {
+ font: inherit;
+}
+
+select,
+input {
+ width: 100%;
+ padding: 8px 10px;
+ font-size: 13px;
+ color: inherit;
+ background: white;
+ border: 1px solid #c9c6be;
+ border-radius: 5px;
+}
+
+textarea {
+ width: 100%;
+ min-height: 260px;
+ padding: 16px;
+ font:
+ 13px/1.8 ui-monospace,
+ SFMono-Regular,
+ Consolas,
+ monospace;
+ color: #242424;
+ tab-size: 4;
+ white-space: pre;
+ resize: vertical;
+ background: #fff;
+ border: 1px solid #c9c6be;
+ border-radius: 6px;
+}
+
+.feedback-text {
+ min-height: 180px;
+ margin-top: 10px;
+ font-size: 11px;
+ overflow-wrap: anywhere;
+ white-space: pre-wrap;
+}
+
+button {
+ padding: 8px 12px;
+ font-size: 13px;
+ color: inherit;
+ cursor: pointer;
+ background: #fff;
+ border: 1px solid #c9c6be;
+ border-radius: 5px;
+}
+
+button:hover {
+ background: #f2f0eb;
+ border-color: #a7a297;
+}
+
+button:disabled {
+ cursor: wait;
+ opacity: 0.55;
+}
+
+.primary {
+ color: #fff;
+ background: #242424;
+ border-color: #242424;
+}
+
+.primary:hover {
+ background: #444;
+}
+
+.toolbar {
+ justify-content: flex-start;
+ margin-top: 12px;
+}
+
+:focus-visible {
+ outline: 2px solid #b86220;
+ outline-offset: 3px;
+}
+
+.hint,
+.muted {
+ font-size: 12px;
+ line-height: 1.6;
+ color: #706c65;
+}
+
+.hint {
+ margin: 10px 0;
+}
+
+.good {
+ color: #267442;
+}
+
+.bad {
+ color: #ae3329;
+}
+
+.diagnostic,
+.suggestion {
+ display: block;
+ width: 100%;
+ margin: 7px 0;
+ text-align: left;
+ overflow-wrap: anywhere;
+}
+
+.diagnostic {
+ background: #fff1ee;
+ border-color: #eed0c9;
+}
+
+.diagnostic small,
+.suggestion small {
+ display: block;
+ margin-top: 4px;
+ color: #706c65;
+}
+
+.suggestion {
+ display: flex;
+ gap: 12px;
+ align-items: baseline;
+ justify-content: space-between;
+}
+
+.suggestion small {
+ flex-shrink: 0;
+}
+
+details {
+ padding-top: 12px;
+ margin-top: 16px;
+ font-size: 12px;
+ border-top: 1px solid #e8e5de;
+}
+
+summary {
+ overflow-wrap: anywhere;
+ cursor: pointer;
+}
+
+pre {
+ max-height: 260px;
+ padding: 12px;
+ overflow: auto;
+ font:
+ 11px/1.6 ui-monospace,
+ monospace;
+ overflow-wrap: anywhere;
+ white-space: pre-wrap;
+ background: #f3f1eb;
+ border-radius: 5px;
+}
+
+#suggestions {
+ max-height: 340px;
+ overflow: auto;
+}
+
+#catalog {
+ max-height: 620px;
+ margin-top: 16px;
+ overflow: auto;
+}
+
+.catalog-field {
+ display: flex;
+ gap: 8px;
+ justify-content: space-between;
+ padding: 6px 0;
+ font:
+ 11px/1.5 ui-monospace,
+ monospace;
+ overflow-wrap: anywhere;
+ border-bottom: 1px solid #f0eee8;
+}
+
+.catalog-field span:last-child {
+ color: #777;
+}
+
+a {
+ font-size: 12px;
+ color: #805025;
+}
+
+.limitations {
+ line-height: 1.6;
+ color: #706c65;
+}
+
+code {
+ overflow-wrap: anywhere;
+}
+
+footer {
+ margin-top: 24px;
+ font-size: 12px;
+ color: #807b72;
+}
+
+.sr-only {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ border: 0;
+}
+
+[hidden] {
+ display: none !important;
+}
+
+@container (max-width: 650px) {
+ .results {
+ grid-template-columns: 1fr;
+ }
+}
+
+@media (max-width: 950px) {
+ main {
+ grid-template-columns: minmax(0, 1fr);
+ }
+
+ body {
+ padding: 20px;
+ }
+}
diff --git a/services/hogql-language-service/cmd/demo/catalog.go b/services/hogql-language-service/cmd/demo/catalog.go
new file mode 100644
index 000000000000..13d73bae7440
--- /dev/null
+++ b/services/hogql-language-service/cmd/demo/catalog.go
@@ -0,0 +1,72 @@
+package main
+
+import (
+ "fmt"
+
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/catalog"
+)
+
+type catalogPublication struct {
+ Revision string `json:"revision"`
+ Catalog catalog.Catalog `json:"catalog"`
+}
+
+func demoTable(name, kind string, fields map[string]string) catalog.Table {
+ table := catalog.Table{Name: name, Type: kind, Fields: make(map[string]catalog.Field, len(fields))}
+ for name, fieldType := range fields {
+ table.Fields[name] = catalog.Field{Name: name, Type: fieldType}
+ }
+ return table
+}
+
+func syntheticCatalog() catalogPublication {
+ tables := map[string]catalog.Table{}
+ for _, table := range []catalog.Table{
+ demoTable("events", "posthog", map[string]string{
+ "uuid": "uuid", "event": "string", "timestamp": "datetime", "created_at": "datetime",
+ "distinct_id": "string", "person_id": "uuid", "properties": "json", "elements_chain": "string",
+ "$session_id": "string", "$window_id": "string", "person": "virtual_table",
+ "session": "virtual_table", "group_0": "virtual_table", "group_1": "virtual_table",
+ }),
+ demoTable("persons", "posthog", map[string]string{
+ "id": "uuid", "created_at": "datetime", "properties": "json", "is_identified": "boolean", "last_seen_at": "datetime",
+ }),
+ demoTable("sessions", "posthog", map[string]string{
+ "session_id": "string", "distinct_id": "string", "$start_timestamp": "datetime", "$end_timestamp": "datetime",
+ "$session_duration": "float", "$pageview_count": "integer", "$autocapture_count": "integer",
+ "$entry_current_url": "string", "$exit_current_url": "string", "$entry_pathname": "string", "$channel_type": "string",
+ }),
+ demoTable("groups", "posthog", map[string]string{
+ "key": "string", "index": "integer", "created_at": "datetime", "updated_at": "datetime", "properties": "json",
+ }),
+ demoTable("postgres.demo.orders", "data_warehouse", map[string]string{
+ "id": "integer", "person_id": "uuid", "amount": "float", "currency": "string", "status": "string", "created_at": "datetime",
+ }),
+ demoTable("demo_customers", "data_warehouse", map[string]string{
+ "id": "integer", "email": "string", "plan": "string", "billing address": "string", "café": "string",
+ }),
+ } {
+ tables[table.Name] = table
+ }
+ properties := map[string][]catalog.Property{
+ "event": {
+ {Name: "$current_url", ValueType: "String"}, {Name: "$pathname", ValueType: "String"},
+ {Name: "$browser", ValueType: "String"}, {Name: "$os", ValueType: "String"},
+ {Name: "$device_type", ValueType: "String"}, {Name: "$geoip_country_name", ValueType: "String"},
+ {Name: "$geoip_city_name", ValueType: "String"}, {Name: "$referrer", ValueType: "String"},
+ {Name: "$utm_source", ValueType: "String"}, {Name: "$session_id", ValueType: "String"},
+ {Name: "order_total", ValueType: "Numeric"}, {Name: "button_text", ValueType: "String"},
+ },
+ "person": {
+ {Name: "email", ValueType: "String"}, {Name: "name", ValueType: "String"},
+ {Name: "plan", ValueType: "String"}, {Name: "company", ValueType: "String"}, {Name: "$initial_referrer", ValueType: "String"},
+ },
+ "session": {{Name: "$entry_current_url", ValueType: "String"}, {Name: "$exit_current_url", ValueType: "String"}},
+ "group:0": {{Name: "name", ValueType: "String"}, {Name: "industry", ValueType: "String"}, {Name: "employee_count", ValueType: "Numeric"}},
+ "group:1": {{Name: "name", ValueType: "String"}, {Name: "region", ValueType: "String"}},
+ }
+ for index := range 35 {
+ properties["event"] = append(properties["event"], catalog.Property{Name: fmt.Sprintf("demo_property_%02d", index), ValueType: "String"})
+ }
+ return catalogPublication{Revision: "synthetic-demo-v1", Catalog: catalog.Catalog{Tables: tables, Properties: properties}}
+}
diff --git a/services/hogql-language-service/cmd/demo/main.go b/services/hogql-language-service/cmd/demo/main.go
new file mode 100644
index 000000000000..b9606e2994a5
--- /dev/null
+++ b/services/hogql-language-service/cmd/demo/main.go
@@ -0,0 +1,148 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "embed"
+ "encoding/json"
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "io/fs"
+ "log/slog"
+ "net"
+ "net/http"
+ "os"
+ "os/signal"
+ "strings"
+ "syscall"
+ "time"
+
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/catalog"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/httpapi"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/ratelimit"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/serviceauth"
+)
+
+// Embedding only in this command keeps the demo out of the production server binary.
+//
+//go:embed assets/*
+var assets embed.FS
+
+func newDemoHandler(host string) (http.Handler, error) {
+ publication := syntheticCatalog()
+ payload, err := json.Marshal(publication)
+ if err != nil {
+ return nil, err
+ }
+ catalogs := catalog.NewRegistry(1, 16<<20, 24*time.Hour)
+ if err := catalogs.Put(serviceauth.Authorization{TeamID: 1, UserID: 1}, publication.Revision, catalog.Prepare(&publication.Catalog)); err != nil {
+ return nil, err
+ }
+ preAuthLimiter, err := ratelimit.New(ratelimit.Config{Capacity: 300, RefillPerSec: 100, MaxEntries: 10000, IdleTTL: 10 * time.Minute})
+ if err != nil {
+ return nil, err
+ }
+ principalLimiter, err := ratelimit.New(ratelimit.Config{Capacity: 120, RefillPerSec: 60, MaxEntries: 10000, IdleTTL: 10 * time.Minute})
+ if err != nil {
+ return nil, err
+ }
+ backend := httpapi.NewHandler(httpapi.Config{
+ Catalogs: catalogs,
+ Auth: serviceauth.New(nil, true),
+ PreAuthLimiter: preAuthLimiter,
+ PrincipalLimiter: principalLimiter,
+ Logger: slog.Default(),
+ })
+ return demoHandler(backend, host, payload), nil
+}
+
+func demoHandler(backend http.Handler, host string, payload []byte) http.Handler {
+ static, _ := fs.Sub(assets, "assets")
+ mux := http.NewServeMux()
+ mux.Handle("GET /", http.FileServer(http.FS(static)))
+ mux.HandleFunc("GET /api/catalog", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ // The payload is the JSON-encoded synthetic catalog; application/json and nosniff prevent HTML interpretation.
+ // nosemgrep: go.lang.security.audit.xss.no-direct-write-to-responsewriter.no-direct-write-to-responsewriter
+ _, _ = w.Write(payload)
+ })
+ for _, operation := range []string{"autocomplete", "validate"} {
+ mux.HandleFunc("POST /api/"+operation, func(w http.ResponseWriter, r *http.Request) {
+ body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 128<<10))
+ if err != nil {
+ http.Error(w, "Request too large. Use a shorter query.", http.StatusRequestEntityTooLarge)
+ return
+ }
+ request, err := http.NewRequestWithContext(r.Context(), http.MethodPost, "/teams/1/users/1/"+operation, bytes.NewReader(body))
+ if err != nil {
+ http.Error(w, "Could not create request. Restart the demo.", http.StatusInternalServerError)
+ return
+ }
+ request.Header.Set("Content-Type", "application/json")
+ request.RemoteAddr = r.RemoteAddr
+ backend.ServeHTTP(w, request)
+ })
+ }
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'")
+ w.Header().Set("X-Content-Type-Options", "nosniff")
+ w.Header().Set("Cache-Control", "no-store")
+ origin := r.Header.Get("Origin")
+ if (host != "" && r.Host != host) || (origin != "" && origin != "http://"+r.Host && origin != "https://"+r.Host) {
+ http.Error(w, "Send requests from the demo page's own address.", http.StatusForbidden)
+ return
+ }
+ if r.Method == http.MethodPost && !strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") {
+ http.Error(w, "Send JSON requests from the demo page.", http.StatusUnsupportedMediaType)
+ return
+ }
+ mux.ServeHTTP(w, r)
+ })
+}
+
+func run(ctx context.Context, host string, port int) error {
+ listener, err := net.Listen("tcp", net.JoinHostPort(host, fmt.Sprint(port)))
+ if err != nil {
+ return err
+ }
+ defer listener.Close()
+ allowedHost := listener.Addr().String()
+ if ip := net.ParseIP(host); ip != nil && ip.IsUnspecified() {
+ allowedHost = ""
+ }
+ handler, err := newDemoHandler(allowedHost)
+ if err != nil {
+ return err
+ }
+ server := &http.Server{
+ Handler: handler,
+ ReadHeaderTimeout: 5 * time.Second,
+ ReadTimeout: 10 * time.Second,
+ WriteTimeout: 10 * time.Second,
+ IdleTimeout: 60 * time.Second,
+ }
+ go func() {
+ <-ctx.Done()
+ _ = server.Close()
+ }()
+ fmt.Printf("\nHogQL demo: http://%s\nSynthetic catalog only. Queries are not executed. Press Ctrl+C to stop.\n\n", listener.Addr())
+ err = server.Serve(listener)
+ if errors.Is(err, http.ErrServerClosed) {
+ return nil
+ }
+ return err
+}
+
+func main() {
+ host := flag.String("host", "127.0.0.1", "bind address; use 0.0.0.0 for port forwarding")
+ port := flag.Int("port", 8092, "port for the demo page")
+ flag.Parse()
+ ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ defer cancel()
+ if err := run(ctx, *host, *port); err != nil && !errors.Is(err, context.Canceled) {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+}
diff --git a/services/hogql-language-service/cmd/demo/main_test.go b/services/hogql-language-service/cmd/demo/main_test.go
new file mode 100644
index 000000000000..18a13a38597f
--- /dev/null
+++ b/services/hogql-language-service/cmd/demo/main_test.go
@@ -0,0 +1,128 @@
+package main
+
+import (
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/completion"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/validation"
+)
+
+func TestDemoRejectsForeignBrowserRequests(t *testing.T) {
+ for _, test := range []struct {
+ name, host, origin, contentType string
+ forwarded bool
+ status int
+ }{
+ {name: "foreign host", host: "example.com", contentType: "application/json", status: http.StatusForbidden},
+ {name: "foreign origin", host: "127.0.0.1:8092", origin: "https://example.com", contentType: "application/json", status: http.StatusForbidden},
+ {name: "opaque origin", host: "127.0.0.1:8092", origin: "null", contentType: "application/json", status: http.StatusForbidden},
+ {name: "form post", host: "127.0.0.1:8092", contentType: "application/x-www-form-urlencoded", status: http.StatusUnsupportedMediaType},
+ {name: "forwarded foreign origin", host: "demo.example.com", origin: "https://other.example.com", contentType: "application/json", forwarded: true, status: http.StatusForbidden},
+ {name: "forwarded opaque origin", host: "demo.example.com", origin: "null", contentType: "application/json", forwarded: true, status: http.StatusForbidden},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ request := httptest.NewRequest(http.MethodPost, "http://"+test.host+"/api/validate", strings.NewReader(`{"query":"SELECT 1"}`))
+ request.Header.Set("Origin", test.origin)
+ request.Header.Set("Content-Type", test.contentType)
+ response := httptest.NewRecorder()
+ allowedHost := "127.0.0.1:8092"
+ if test.forwarded {
+ allowedHost = ""
+ }
+ demoHandler(nil, allowedHost, nil).ServeHTTP(response, request)
+ if response.Code != test.status {
+ t.Fatalf("status = %d, want %d", response.Code, test.status)
+ }
+ })
+ }
+}
+
+func TestDemoEmbeddedService(t *testing.T) {
+ handler, err := newDemoHandler("127.0.0.1:8092")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, test := range []struct {
+ method, path, body string
+ status int
+ }{
+ {http.MethodPost, "/api/validate", `{"query":"WITH t AS (SELECT uuid FROM events) SELECT uuid FROM t"}`, http.StatusOK},
+ {http.MethodPost, "/api/autocomplete", `{"query":"SELECT events.tim FROM events","position":17}`, http.StatusOK},
+ {http.MethodPost, "/api/validate", `{"query":"SELECT 1","unknown":true}`, http.StatusBadRequest},
+ {http.MethodPost, "/api/validate", strings.Repeat(" ", (128<<10)+1), http.StatusRequestEntityTooLarge},
+ {http.MethodPut, "/teams/1/users/1/catalog", `{}`, http.StatusMethodNotAllowed},
+ {http.MethodPost, "/teams/2/users/2/validate", `{"query":"SELECT 1"}`, http.StatusMethodNotAllowed},
+ } {
+ t.Run(test.method+test.path+"/"+http.StatusText(test.status), func(t *testing.T) {
+ request := httptest.NewRequest(test.method, "http://127.0.0.1:8092"+test.path, strings.NewReader(test.body))
+ request.Header.Set("Content-Type", "application/json")
+ response := httptest.NewRecorder()
+ handler.ServeHTTP(response, request)
+ if response.Code != test.status {
+ t.Fatalf("response = %d %s, want %d", response.Code, response.Body.String(), test.status)
+ }
+ if test.status != http.StatusOK {
+ return
+ }
+ var revision struct {
+ CatalogRevision string `json:"catalogRevision"`
+ }
+ if err := json.Unmarshal(response.Body.Bytes(), &revision); err != nil || revision.CatalogRevision != syntheticCatalog().Revision {
+ t.Fatalf("catalog revision = %q (%v)", revision.CatalogRevision, err)
+ }
+ if test.path == "/api/validate" {
+ var result validation.Result
+ if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil || !result.Valid || len(result.Diagnostics) != 0 || len(result.TableNames) != 1 || result.TableNames[0] != "events" {
+ t.Fatalf("validation = %s (%v)", response.Body.String(), err)
+ }
+ } else {
+ var result completion.Result
+ if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil || len(result.Suggestions) != 1 || result.Suggestions[0].Label != "timestamp" {
+ t.Fatalf("completion = %s (%v)", response.Body.String(), err)
+ }
+ }
+ })
+ }
+}
+
+func TestDemoForwardsLanguageRequests(t *testing.T) {
+ for _, test := range []struct {
+ operation, host, origin, allowedHost string
+ }{
+ {"validate", "127.0.0.1:8092", "http://127.0.0.1:8092", "127.0.0.1:8092"},
+ {"autocomplete", "127.0.0.1:8092", "http://127.0.0.1:8092", "127.0.0.1:8092"},
+ {"validate", "demo.example.com", "https://demo.example.com", ""},
+ {"autocomplete", "localhost:9000", "http://localhost:9000", ""},
+ } {
+ t.Run(test.operation+"/"+test.host, func(t *testing.T) {
+ payload := `{"query":"SELECT '😀', e. FROM events AS e","position":16,"positionEncoding":"utf-16","cursor":"MjU="}`
+ backend := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ body, err := io.ReadAll(r.Body)
+ if err != nil || string(body) != payload || r.URL.Path != "/teams/1/users/1/"+test.operation || r.Method != http.MethodPost {
+ t.Errorf("forwarded request = %s %s %s (%v)", r.Method, r.URL.Path, body, err)
+ }
+ if r.Header.Get("Authorization") != "" || r.Header.Get("Cookie") != "" {
+ t.Error("browser credentials forwarded to demo backend")
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusBadRequest)
+ _, _ = w.Write([]byte(`{"error":"demo response"}`))
+ })
+ request := httptest.NewRequest(http.MethodPost, "http://"+test.host+"/api/"+test.operation, strings.NewReader(payload))
+ request.Header.Set("Content-Type", "application/json")
+ request.Header.Set("Origin", test.origin)
+ request.Header.Set("Authorization", "Bearer fake-demo-token")
+ request.Header.Set("Cookie", "session=fake-demo-session")
+ response := httptest.NewRecorder()
+ demoHandler(backend, test.allowedHost, nil).ServeHTTP(response, request)
+ if response.Code != http.StatusBadRequest || response.Body.String() != `{"error":"demo response"}` {
+ t.Fatalf("response = %d %s", response.Code, response.Body.String())
+ }
+ })
+ }
+}
diff --git a/services/hogql-language-service/cmd/server/main.go b/services/hogql-language-service/cmd/server/main.go
index 1a1d95dd0f62..097a27c80208 100644
--- a/services/hogql-language-service/cmd/server/main.go
+++ b/services/hogql-language-service/cmd/server/main.go
@@ -1,8 +1,6 @@
package main
import (
- "context"
- "encoding/json"
"errors"
"fmt"
"log/slog"
@@ -15,67 +13,11 @@ import (
"time"
"github.com/PostHog/posthog/services/hogql-language-service/internal/catalog"
- "github.com/PostHog/posthog/services/hogql-language-service/internal/completion"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/httpapi"
"github.com/PostHog/posthog/services/hogql-language-service/internal/ratelimit"
"github.com/PostHog/posthog/services/hogql-language-service/internal/serviceauth"
- "github.com/PostHog/posthog/services/hogql-language-service/internal/textposition"
- "github.com/PostHog/posthog/services/hogql-language-service/internal/validation"
)
-type server struct {
- catalogs *catalog.Registry
- auth *serviceauth.Authenticator
- preAuthLimiter *ratelimit.Limiter
- principalLimiter *ratelimit.Limiter
- logger *slog.Logger
-}
-
-type requestLogDetails struct {
- operation string
- authorization *serviceauth.Authorization
- result string
- catalogTables int
- catalogProperties int
-}
-
-type requestLogDetailsKey struct{}
-
-type loggingResponseWriter struct {
- http.ResponseWriter
- statusCode int
- responseBytes int
-}
-
-type completionRequest struct {
- Query string `json:"query"`
- Position *int `json:"position,omitempty"`
- PositionEncoding completion.PositionEncoding `json:"positionEncoding,omitempty"`
- Cursor string `json:"cursor,omitempty"`
-}
-
-type completionResponse struct {
- completion.Result
- CatalogRevision string `json:"catalogRevision"`
- DurationMicros int64 `json:"durationMicros"`
- PositionEncoding completion.PositionEncoding `json:"positionEncoding"`
-}
-
-type validationRequest struct {
- Query string `json:"query"`
- PositionEncoding textposition.Encoding `json:"positionEncoding,omitempty"`
-}
-
-type validationResponse struct {
- validation.Result
- CatalogRevision string `json:"catalogRevision"`
- PositionEncoding textposition.Encoding `json:"positionEncoding"`
-}
-
-type catalogUpdate struct {
- Revision string `json:"revision"`
- Catalog catalog.Catalog `json:"catalog"`
-}
-
func main() {
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
slog.SetDefault(logger)
@@ -112,22 +54,23 @@ func main() {
fatalConfiguration(err)
}
- s := &server{
- catalogs: catalog.NewRegistry(maxCatalogs, int64(maxCatalogBytes), catalogTTL),
- auth: serviceauth.New(keys, allowInsecure),
- preAuthLimiter: configuredLimiter("PRE_AUTH_RATE_LIMIT", 300, 100, maxRateLimitKeys, rateLimitIdleTTL),
- principalLimiter: configuredLimiter("PRINCIPAL_RATE_LIMIT", 120, 60, maxRateLimitKeys, rateLimitIdleTTL),
- logger: logger,
- }
+ catalogs := catalog.NewRegistry(maxCatalogs, int64(maxCatalogBytes), catalogTTL)
+ handler := httpapi.NewHandler(httpapi.Config{
+ Catalogs: catalogs,
+ Auth: serviceauth.New(keys, allowInsecure),
+ PreAuthLimiter: configuredLimiter("PRE_AUTH_RATE_LIMIT", 300, 100, maxRateLimitKeys, rateLimitIdleTTL),
+ PrincipalLimiter: configuredLimiter("PRINCIPAL_RATE_LIMIT", 120, 60, maxRateLimitKeys, rateLimitIdleTTL),
+ Logger: logger,
+ })
httpServer := &http.Server{
Addr: listenAddress,
- Handler: s.handler(),
+ Handler: handler,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 60 * time.Second,
}
- stats := s.catalogs.Stats()
+ stats := catalogs.Stats()
slog.Info("HogQL language service listening", "address", listenAddress, "catalogs", stats.Catalogs, "tables", stats.Tables, "properties", stats.Properties)
if err := httpServer.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
slog.Error("server stopped", "error", err)
@@ -135,298 +78,6 @@ func main() {
}
}
-func (s *server) handler() http.Handler {
- mux := http.NewServeMux()
- mux.Handle("GET /health", requestOperation("health", http.HandlerFunc(s.health)))
- mux.Handle("PUT /teams/{teamID}/users/{userID}/catalog", requestOperation("publish", s.authorized(serviceauth.OperationPublish, s.putCatalog)))
- mux.Handle("DELETE /teams/{teamID}/users/{userID}/catalog", requestOperation("delete", s.authorized(serviceauth.OperationDelete, s.deleteCatalog)))
- mux.Handle("POST /teams/{teamID}/users/{userID}/autocomplete", requestOperation("complete", s.authorized(serviceauth.OperationComplete, s.autocomplete)))
- mux.Handle("POST /teams/{teamID}/users/{userID}/validate", requestOperation("validate", s.authorized(serviceauth.OperationValidate, s.validate)))
- return securityHeaders(s.logRequests(mux))
-}
-
-func (s *server) logRequests(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- started := time.Now()
- details := &requestLogDetails{operation: "unmatched"}
- response := &loggingResponseWriter{ResponseWriter: w}
- next.ServeHTTP(response, r.WithContext(context.WithValue(r.Context(), requestLogDetailsKey{}, details)))
-
- statusCode := response.statusCode
- if statusCode == 0 {
- statusCode = http.StatusOK
- }
- result := details.result
- if result == "" {
- if statusCode < http.StatusBadRequest {
- result = "success"
- } else {
- result = "error"
- }
- }
- attributes := []any{
- "operation", details.operation,
- "method", r.Method,
- "status_code", statusCode,
- "duration_ms", float64(time.Since(started).Microseconds()) / 1000,
- "response_bytes", response.responseBytes,
- "result", result,
- }
- if details.authorization != nil {
- attributes = append(attributes, "team_id", details.authorization.TeamID, "user_id", details.authorization.UserID)
- }
- if details.result == "catalog_published" {
- attributes = append(attributes, "catalog_tables", details.catalogTables, "catalog_properties", details.catalogProperties)
- }
-
- logger := s.logger
- if logger == nil {
- logger = slog.Default()
- }
- switch {
- case details.operation == "health" && statusCode < http.StatusBadRequest:
- logger.Debug("http_request", attributes...)
- case statusCode >= http.StatusInternalServerError:
- logger.Error("http_request", attributes...)
- case statusCode >= http.StatusBadRequest && details.result != "catalog_miss":
- logger.Warn("http_request", attributes...)
- default:
- logger.Info("http_request", attributes...)
- }
- })
-}
-
-func requestOperation(operation string, next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if details := requestDetails(r); details != nil {
- details.operation = operation
- }
- next.ServeHTTP(w, r)
- })
-}
-
-func (w *loggingResponseWriter) WriteHeader(statusCode int) {
- if w.statusCode != 0 {
- return
- }
- w.statusCode = statusCode
- w.ResponseWriter.WriteHeader(statusCode)
-}
-
-func (w *loggingResponseWriter) Write(body []byte) (int, error) {
- if w.statusCode == 0 {
- w.WriteHeader(http.StatusOK)
- }
- written, err := w.ResponseWriter.Write(body)
- w.responseBytes += written
- return written, err
-}
-
-func (w *loggingResponseWriter) Unwrap() http.ResponseWriter {
- return w.ResponseWriter
-}
-
-func requestDetails(r *http.Request) *requestLogDetails {
- details, _ := r.Context().Value(requestLogDetailsKey{}).(*requestLogDetails)
- return details
-}
-
-func setRequestResult(r *http.Request, result string) {
- if details := requestDetails(r); details != nil {
- details.result = result
- }
-}
-
-func securityHeaders(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("X-Content-Type-Options", "nosniff")
- next.ServeHTTP(w, r)
- })
-}
-
-type authorizedHandler func(http.ResponseWriter, *http.Request, serviceauth.Authorization)
-
-func (s *server) authorized(operation serviceauth.Operation, next authorizedHandler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- preAuthAllowed, retryAfter := s.preAuthLimiter.Allow(remoteAddress(r))
- authorization, err := authorizationFromPath(r)
- if err != nil {
- if !preAuthAllowed {
- setRequestResult(r, "rate_limited")
- writeRateLimitResponse(w, retryAfter)
- } else {
- setRequestResult(r, "invalid_scope")
- http.Error(w, err.Error(), http.StatusBadRequest)
- }
- return
- }
- if err := s.auth.Verify(r.Header.Get("Authorization"), authorization, operation); err != nil {
- if !preAuthAllowed {
- setRequestResult(r, "rate_limited")
- writeRateLimitResponse(w, retryAfter)
- } else {
- setRequestResult(r, "unauthorized")
- http.Error(w, "unauthorized", http.StatusUnauthorized)
- }
- return
- }
- if details := requestDetails(r); details != nil {
- details.authorization = &authorization
- }
- if allowed, retryAfter := s.principalLimiter.Allow(authorizationKey(authorization)); !allowed {
- setRequestResult(r, "rate_limited")
- writeRateLimitResponse(w, retryAfter)
- return
- }
- next(w, r, authorization)
- })
-}
-
-func (s *server) putCatalog(w http.ResponseWriter, r *http.Request, authorization serviceauth.Authorization) {
- var input catalogUpdate
- if !decodeJSON(w, r, 64<<20, &input) {
- return
- }
- if err := catalog.ValidateRevision(input.Revision); err != nil {
- setRequestResult(r, "catalog_rejected")
- http.Error(w, err.Error(), http.StatusBadRequest)
- return
- }
- if err := catalog.ValidateCatalog(&input.Catalog); err != nil {
- setRequestResult(r, "catalog_rejected")
- http.Error(w, err.Error(), http.StatusBadRequest)
- return
- }
- if err := s.catalogs.Put(authorization, input.Revision, catalog.Prepare(&input.Catalog)); err != nil {
- setRequestResult(r, "catalog_rejected")
- http.Error(w, err.Error(), http.StatusBadRequest)
- return
- }
- if details := requestDetails(r); details != nil {
- details.result = "catalog_published"
- details.catalogTables = len(input.Catalog.Tables)
- for _, properties := range input.Catalog.Properties {
- details.catalogProperties += len(properties)
- }
- }
- writeJSON(w, http.StatusOK, map[string]any{"teamId": authorization.TeamID, "userId": authorization.UserID, "revision": input.Revision})
-}
-
-func (s *server) deleteCatalog(w http.ResponseWriter, r *http.Request, authorization serviceauth.Authorization) {
- if !s.catalogs.Delete(authorization) {
- setRequestResult(r, "catalog_miss")
- http.Error(w, "catalog not found", http.StatusNotFound)
- return
- }
- setRequestResult(r, "catalog_deleted")
- w.WriteHeader(http.StatusNoContent)
-}
-
-func (s *server) autocomplete(w http.ResponseWriter, r *http.Request, authorization serviceauth.Authorization) {
- var input completionRequest
- if !decodeJSON(w, r, 128<<10, &input) {
- return
- }
- current, revision, ok := s.catalogs.Get(authorization)
- if !ok {
- setRequestResult(r, "catalog_miss")
- http.Error(w, "catalog not found", http.StatusNotFound)
- return
- }
- setRequestResult(r, "catalog_hit")
- position := -1
- if input.Position != nil {
- position = *input.Position
- }
- positionEncoding := input.PositionEncoding
- if positionEncoding == "" {
- positionEncoding = completion.PositionEncodingUTF8
- }
- started := time.Now()
- result, err := completion.Complete(current, input.Query, position, positionEncoding, input.Cursor)
- if err != nil {
- setRequestResult(r, "invalid_query")
- http.Error(w, err.Error(), http.StatusBadRequest)
- return
- }
- writeJSON(w, http.StatusOK, completionResponse{
- Result: result,
- CatalogRevision: revision,
- DurationMicros: time.Since(started).Microseconds(),
- PositionEncoding: positionEncoding,
- })
-}
-
-func (s *server) validate(w http.ResponseWriter, r *http.Request, authorization serviceauth.Authorization) {
- var input validationRequest
- if !decodeJSON(w, r, 128<<10, &input) {
- return
- }
- current, revision, ok := s.catalogs.Get(authorization)
- if !ok {
- setRequestResult(r, "catalog_miss")
- http.Error(w, "catalog not found", http.StatusNotFound)
- return
- }
- setRequestResult(r, "catalog_hit")
- positionEncoding := input.PositionEncoding
- if positionEncoding == "" {
- positionEncoding = textposition.UTF16
- }
- result, err := validation.ValidateWithEncoding(current, input.Query, positionEncoding)
- if err != nil {
- setRequestResult(r, "invalid_query")
- http.Error(w, err.Error(), http.StatusBadRequest)
- return
- }
- writeJSON(w, http.StatusOK, validationResponse{Result: result, CatalogRevision: revision, PositionEncoding: positionEncoding})
-}
-
-func (s *server) health(w http.ResponseWriter, _ *http.Request) {
- writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
-}
-
-func decodeJSON(w http.ResponseWriter, r *http.Request, maxBytes int64, target any) bool {
- decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBytes))
- decoder.DisallowUnknownFields()
- if err := decoder.Decode(target); err != nil {
- setRequestResult(r, "invalid_json")
- http.Error(w, "invalid request: "+err.Error(), http.StatusBadRequest)
- return false
- }
- return true
-}
-
-func authorizationFromPath(r *http.Request) (serviceauth.Authorization, error) {
- teamID, err := strconv.ParseInt(r.PathValue("teamID"), 10, 64)
- if err != nil {
- return serviceauth.Authorization{}, errors.New("teamID and userID must be positive integers")
- }
- userID, err := strconv.ParseInt(r.PathValue("userID"), 10, 64)
- if err != nil || teamID <= 0 || userID <= 0 {
- return serviceauth.Authorization{}, errors.New("teamID and userID must be positive integers")
- }
- return serviceauth.Authorization{TeamID: teamID, UserID: userID}, nil
-}
-
-func remoteAddress(r *http.Request) string {
- host, _, err := net.SplitHostPort(r.RemoteAddr)
- if err != nil {
- return r.RemoteAddr
- }
- return host
-}
-
-func authorizationKey(authorization serviceauth.Authorization) string {
- return strconv.FormatInt(authorization.TeamID, 10) + ":" + strconv.FormatInt(authorization.UserID, 10)
-}
-
-func writeRateLimitResponse(w http.ResponseWriter, retryAfter time.Duration) {
- seconds := max(int64(1), int64((retryAfter+time.Second-1)/time.Second))
- w.Header().Set("Retry-After", strconv.FormatInt(seconds, 10))
- http.Error(w, "rate limit exceeded", http.StatusTooManyRequests)
-}
-
func isLoopbackAddress(address string) bool {
host, _, err := net.SplitHostPort(address)
if err != nil {
@@ -497,21 +148,6 @@ func positiveFloatEnv(name string, fallback float64) (float64, error) {
return parsed, nil
}
-func writeJSON(w http.ResponseWriter, status int, value any) {
- body, err := json.Marshal(value)
- if err != nil {
- http.Error(w, "encode response", http.StatusInternalServerError)
- return
- }
- w.Header().Set("Content-Type", "application/json; charset=utf-8")
- w.Header().Set("Content-Length", strconv.Itoa(len(body)))
- w.WriteHeader(status)
- // nosemgrep: go.lang.security.audit.xss.no-direct-write-to-responsewriter.no-direct-write-to-responsewriter -- json.Marshal escapes strings and this response has an application/json content type.
- if _, err := w.Write(body); err != nil {
- slog.Warn("write response", "error", err)
- }
-}
-
func allowInsecureAuthentication(listenAddress, configured string) (bool, error) {
if configured != "1" {
return false, nil
diff --git a/services/hogql-language-service/cmd/server/main_test.go b/services/hogql-language-service/cmd/server/main_test.go
index e2aaecded213..dd739754708e 100644
--- a/services/hogql-language-service/cmd/server/main_test.go
+++ b/services/hogql-language-service/cmd/server/main_test.go
@@ -1,76 +1,6 @@
package main
-import (
- "bytes"
- "encoding/json"
- "io"
- "log/slog"
- "net/http"
- "net/http/httptest"
- "strconv"
- "strings"
- "testing"
- "time"
- "unicode/utf16"
-
- "github.com/PostHog/posthog/services/hogql-language-service/internal/catalog"
- "github.com/PostHog/posthog/services/hogql-language-service/internal/completion"
- "github.com/PostHog/posthog/services/hogql-language-service/internal/ratelimit"
- "github.com/PostHog/posthog/services/hogql-language-service/internal/serviceauth"
-)
-
-func TestAutocompleteUsesOnlyRequestedTeamAndUserCatalog(t *testing.T) {
- s := newTestServer(t)
- handler := s.handler()
- putCatalogForTest(t, handler, 1, 10, "revision-one", "orders")
- putCatalogForTest(t, handler, 1, 20, "revision-two", "accounts")
- putCatalogForTest(t, handler, 2, 10, "revision-three", "invoices")
-
- for _, test := range []struct {
- teamID int64
- userID int64
- revision string
- table string
- }{
- {teamID: 1, userID: 10, revision: "revision-one", table: "orders"},
- {teamID: 1, userID: 20, revision: "revision-two", table: "accounts"},
- {teamID: 2, userID: 10, revision: "revision-three", table: "invoices"},
- } {
- body := `{"query":"SELECT * FROM "}`
- path := scopePath(test.teamID, test.userID) + "/autocomplete"
- request := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
- request.Header.Set("Content-Type", "application/json")
- response := httptest.NewRecorder()
- handler.ServeHTTP(response, request)
- if response.Code != http.StatusOK {
- t.Fatalf("autocomplete returned %d: %s", response.Code, response.Body.String())
- }
- if contentType := response.Header().Get("Content-Type"); contentType != "application/json; charset=utf-8" {
- t.Fatalf("unexpected Content-Type: %q", contentType)
- }
- if response.Header().Get("X-Content-Type-Options") != "nosniff" {
- t.Fatal("response is missing X-Content-Type-Options: nosniff")
- }
- if contentLength := response.Header().Get("Content-Length"); contentLength != strconv.Itoa(response.Body.Len()) {
- t.Fatalf("Content-Length = %q, response size = %d", contentLength, response.Body.Len())
- }
- var result completionResponse
- if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
- t.Fatal(err)
- }
- if result.CatalogRevision != test.revision || !hasSuggestion(result.Suggestions, test.table) {
- t.Fatalf("unexpected response for team %d user %d: %#v", test.teamID, test.userID, result)
- }
- if result.PositionEncoding != completion.PositionEncodingUTF8 {
- t.Fatalf("unexpected position encoding: %q", result.PositionEncoding)
- }
- for _, otherTable := range []string{"orders", "accounts", "invoices"} {
- if otherTable != test.table && hasSuggestion(result.Suggestions, otherTable) {
- t.Fatalf("%s leaked into team %d user %d", otherTable, test.teamID, test.userID)
- }
- }
- }
-}
+import "testing"
func TestInsecureAuthenticationRequiresExplicitLoopbackOptIn(t *testing.T) {
for _, test := range []struct {
@@ -89,231 +19,3 @@ func TestInsecureAuthenticationRequiresExplicitLoopbackOptIn(t *testing.T) {
}
}
}
-
-func TestAutocompleteRequiresKnownTeamAndUser(t *testing.T) {
- s := newTestServer(t)
- for _, test := range []struct {
- path string
- body string
- status int
- }{
- {path: "/teams/1/users/invalid/autocomplete", body: `{"query":"SELECT "}`, status: http.StatusBadRequest},
- {path: "/teams/invalid/users/10/validate", body: `{"query":"SELECT 1"}`, status: http.StatusBadRequest},
- {path: scopePath(1, 10) + "/autocomplete", body: `{"query":"SELECT "}`, status: http.StatusNotFound},
- } {
- request := httptest.NewRequest(http.MethodPost, test.path, strings.NewReader(test.body))
- response := httptest.NewRecorder()
- s.handler().ServeHTTP(response, request)
- if response.Code != test.status {
- t.Fatalf("expected %d, got %d: %s", test.status, response.Code, response.Body.String())
- }
- if response.Header().Get("X-Content-Type-Options") != "nosniff" {
- t.Fatal("error response is missing X-Content-Type-Options: nosniff")
- }
- }
-}
-
-func TestValidateEncodesDiagnosticPositions(t *testing.T) {
- s := newTestServer(t)
- handler := s.handler()
- putCatalogForTest(t, handler, 1, 10, "revision-one", "events")
- query := "SELECT '😀', missing FROM events"
- byteStart := strings.Index(query, "missing")
- utf16Start := len(utf16.Encode([]rune(query[:byteStart])))
-
- for _, test := range []struct {
- encoding string
- responseEncoding string
- start int
- }{
- {encoding: "utf-8", responseEncoding: "utf-8", start: byteStart},
- {encoding: "utf-16", responseEncoding: "utf-16", start: utf16Start},
- {responseEncoding: "utf-16", start: utf16Start},
- } {
- body, err := json.Marshal(map[string]any{"query": query, "positionEncoding": test.encoding})
- if err != nil {
- t.Fatal(err)
- }
- request := httptest.NewRequest(http.MethodPost, scopePath(1, 10)+"/validate", bytes.NewReader(body))
- request.Header.Set("Content-Type", "application/json")
- response := httptest.NewRecorder()
- handler.ServeHTTP(response, request)
- if response.Code != http.StatusOK {
- t.Fatalf("validate returned %d: %s", response.Code, response.Body.String())
- }
- var result validationResponse
- if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
- t.Fatal(err)
- }
- if string(result.PositionEncoding) != test.responseEncoding {
- t.Fatalf("position encoding = %q, want %q", result.PositionEncoding, test.responseEncoding)
- }
- if len(result.Diagnostics) != 1 {
- t.Fatalf("diagnostics = %#v", result.Diagnostics)
- }
- diagnostic := result.Diagnostics[0]
- if diagnostic.Start != test.start || diagnostic.End != test.start+len("missing") {
- t.Fatalf("%s diagnostic span = [%d,%d), want [%d,%d)", test.responseEncoding, diagnostic.Start, diagnostic.End, test.start, test.start+len("missing"))
- }
- }
-}
-
-func TestRequestLogIncludesMetadataWithoutRequestContents(t *testing.T) {
- var logs bytes.Buffer
- s := newTestServer(t)
- s.logger = slog.New(slog.NewJSONHandler(&logs, nil))
- handler := s.handler()
- putCatalogForTest(t, handler, 1, 10, "revision-one", "events")
- logs.Reset()
-
- request := httptest.NewRequest(http.MethodPost, scopePath(1, 10)+"/validate", strings.NewReader(`{"query":"SELECT 'do-not-log-query'"}`))
- request.Header.Set("Authorization", "Bearer do-not-log-token")
- response := httptest.NewRecorder()
- handler.ServeHTTP(response, request)
- if response.Code != http.StatusOK {
- t.Fatalf("validate returned %d: %s", response.Code, response.Body.String())
- }
-
- var entry map[string]any
- if err := json.Unmarshal(bytes.TrimSpace(logs.Bytes()), &entry); err != nil {
- t.Fatalf("decode request log: %v\n%s", err, logs.String())
- }
- for key, expected := range map[string]any{
- "msg": "http_request",
- "operation": "validate",
- "method": http.MethodPost,
- "status_code": float64(http.StatusOK),
- "response_bytes": float64(response.Body.Len()),
- "result": "catalog_hit",
- "team_id": float64(1),
- "user_id": float64(10),
- } {
- if entry[key] != expected {
- t.Errorf("%s = %#v, want %#v", key, entry[key], expected)
- }
- }
- if duration, ok := entry["duration_ms"].(float64); !ok || duration < 0 {
- t.Errorf("duration_ms = %#v", entry["duration_ms"])
- }
- if strings.Contains(logs.String(), "do-not-log-query") || strings.Contains(logs.String(), "do-not-log-token") {
- t.Fatalf("request contents leaked into log: %s", logs.String())
- }
-
- logs.Reset()
- request = httptest.NewRequest(http.MethodGet, "/unknown", nil)
- response = httptest.NewRecorder()
- handler.ServeHTTP(response, request)
- if response.Code != http.StatusNotFound {
- t.Fatalf("unknown route returned %d: %s", response.Code, response.Body.String())
- }
- entry = map[string]any{}
- if err := json.Unmarshal(bytes.TrimSpace(logs.Bytes()), &entry); err != nil {
- t.Fatalf("decode unmatched request log: %v\n%s", err, logs.String())
- }
- for key, expected := range map[string]any{
- "level": "WARN",
- "msg": "http_request",
- "operation": "unmatched",
- "method": http.MethodGet,
- "status_code": float64(http.StatusNotFound),
- "result": "error",
- } {
- if entry[key] != expected {
- t.Errorf("%s = %#v, want %#v", key, entry[key], expected)
- }
- }
-}
-
-func TestPrincipalRateLimitRunsBeforeBodyDecodeAndDoesNotCrossScopes(t *testing.T) {
- preAuthLimiter, err := ratelimit.New(ratelimit.Config{Capacity: 1, RefillPerSec: 0.001, MaxEntries: 10, IdleTTL: time.Hour})
- if err != nil {
- t.Fatal(err)
- }
- principalLimiter, err := ratelimit.New(ratelimit.Config{Capacity: 1, RefillPerSec: 0.001, MaxEntries: 10, IdleTTL: time.Hour})
- if err != nil {
- t.Fatal(err)
- }
- s := &server{
- catalogs: catalog.NewRegistry(10, 1<<20, time.Hour),
- auth: serviceauth.New(nil, true),
- preAuthLimiter: preAuthLimiter,
- principalLimiter: principalLimiter,
- logger: discardLogger(),
- }
- value := &catalog.Catalog{Tables: map[string]catalog.Table{}, Properties: map[string][]catalog.Property{}}
- for _, authorization := range []serviceauth.Authorization{{TeamID: 1, UserID: 10}, {TeamID: 1, UserID: 20}} {
- if err := s.catalogs.Put(authorization, "1", catalog.Prepare(value)); err != nil {
- t.Fatal(err)
- }
- }
-
- request := httptest.NewRequest(http.MethodPost, scopePath(1, 10)+"/autocomplete", strings.NewReader(`{"query":"SELECT "}`))
- response := httptest.NewRecorder()
- s.handler().ServeHTTP(response, request)
- if response.Code != http.StatusOK {
- t.Fatalf("first request returned %d: %s", response.Code, response.Body.String())
- }
-
- request = httptest.NewRequest(http.MethodPost, scopePath(1, 10)+"/autocomplete", strings.NewReader(`{`))
- response = httptest.NewRecorder()
- s.handler().ServeHTTP(response, request)
- if response.Code != http.StatusTooManyRequests || response.Header().Get("Retry-After") == "" {
- t.Fatalf("limited request returned %d without Retry-After: %s", response.Code, response.Body.String())
- }
-
- request = httptest.NewRequest(http.MethodPost, scopePath(1, 20)+"/autocomplete", strings.NewReader(`{"query":"SELECT "}`))
- response = httptest.NewRecorder()
- s.handler().ServeHTTP(response, request)
- if response.Code != http.StatusOK {
- t.Fatalf("another user inherited the rate limit: %d: %s", response.Code, response.Body.String())
- }
-}
-
-func putCatalogForTest(t *testing.T, handler http.Handler, teamID, userID int64, revision, table string) {
- t.Helper()
- body := `{"revision":"` + revision + `","catalog":{"tables":{"` + table + `":{"name":"` + table + `","type":"warehouse","fields":{}}},"properties":{}}}`
- path := scopePath(teamID, userID) + "/catalog"
- request := httptest.NewRequest(http.MethodPut, path, strings.NewReader(body))
- response := httptest.NewRecorder()
- handler.ServeHTTP(response, request)
- if response.Code != http.StatusOK {
- t.Fatalf("catalog upload returned %d: %s", response.Code, response.Body.String())
- }
-}
-
-func newTestServer(t *testing.T) *server {
- t.Helper()
- config := ratelimit.Config{Capacity: 1000, RefillPerSec: 1000, MaxEntries: 100, IdleTTL: time.Hour}
- preAuthLimiter, err := ratelimit.New(config)
- if err != nil {
- t.Fatal(err)
- }
- principalLimiter, err := ratelimit.New(config)
- if err != nil {
- t.Fatal(err)
- }
- return &server{
- catalogs: catalog.NewRegistry(10, 1<<20, time.Hour),
- auth: serviceauth.New(nil, true),
- preAuthLimiter: preAuthLimiter,
- principalLimiter: principalLimiter,
- logger: discardLogger(),
- }
-}
-
-func discardLogger() *slog.Logger {
- return slog.New(slog.NewTextHandler(io.Discard, nil))
-}
-
-func scopePath(teamID, userID int64) string {
- return "/teams/" + strconv.FormatInt(teamID, 10) + "/users/" + strconv.FormatInt(userID, 10)
-}
-
-func hasSuggestion(suggestions []completion.Suggestion, label string) bool {
- for _, suggestion := range suggestions {
- if suggestion.Label == label {
- return true
- }
- }
- return false
-}
diff --git a/services/hogql-language-service/internal/httpapi/handler.go b/services/hogql-language-service/internal/httpapi/handler.go
new file mode 100644
index 000000000000..d307ec987cc7
--- /dev/null
+++ b/services/hogql-language-service/internal/httpapi/handler.go
@@ -0,0 +1,399 @@
+package httpapi
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "log/slog"
+ "net"
+ "net/http"
+ "strconv"
+ "time"
+
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/catalog"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/completion"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/ratelimit"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/serviceauth"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/textposition"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/validation"
+)
+
+type server struct {
+ catalogs *catalog.Registry
+ auth *serviceauth.Authenticator
+ preAuthLimiter *ratelimit.Limiter
+ principalLimiter *ratelimit.Limiter
+ logger *slog.Logger
+}
+
+type requestLogDetails struct {
+ operation string
+ authorization *serviceauth.Authorization
+ result string
+ catalogTables int
+ catalogProperties int
+}
+
+type requestLogDetailsKey struct{}
+
+type loggingResponseWriter struct {
+ http.ResponseWriter
+ statusCode int
+ responseBytes int
+}
+
+type completionRequest struct {
+ Query string `json:"query"`
+ Position *int `json:"position,omitempty"`
+ PositionEncoding completion.PositionEncoding `json:"positionEncoding,omitempty"`
+ Cursor string `json:"cursor,omitempty"`
+}
+
+type completionResponse struct {
+ completion.Result
+ CatalogRevision string `json:"catalogRevision"`
+ DurationMicros int64 `json:"durationMicros"`
+ PositionEncoding completion.PositionEncoding `json:"positionEncoding"`
+}
+
+type validationRequest struct {
+ Query string `json:"query"`
+ PositionEncoding textposition.Encoding `json:"positionEncoding,omitempty"`
+}
+
+type validationResponse struct {
+ validation.Result
+ CatalogRevision string `json:"catalogRevision"`
+ PositionEncoding textposition.Encoding `json:"positionEncoding"`
+}
+
+type catalogUpdate struct {
+ Revision string `json:"revision"`
+ Catalog catalog.Catalog `json:"catalog"`
+}
+
+type Config struct {
+ Catalogs *catalog.Registry
+ Auth *serviceauth.Authenticator
+ PreAuthLimiter *ratelimit.Limiter
+ PrincipalLimiter *ratelimit.Limiter
+ Logger *slog.Logger
+}
+
+func NewHandler(config Config) http.Handler {
+ s := &server{
+ catalogs: config.Catalogs,
+ auth: config.Auth,
+ preAuthLimiter: config.PreAuthLimiter,
+ principalLimiter: config.PrincipalLimiter,
+ logger: config.Logger,
+ }
+ return s.handler()
+}
+
+func (s *server) handler() http.Handler {
+ mux := http.NewServeMux()
+ mux.Handle("GET /health", requestOperation("health", http.HandlerFunc(s.health)))
+ mux.Handle("PUT /teams/{teamID}/users/{userID}/catalog", requestOperation("publish", s.authorized(serviceauth.OperationPublish, s.putCatalog)))
+ mux.Handle("DELETE /teams/{teamID}/users/{userID}/catalog", requestOperation("delete", s.authorized(serviceauth.OperationDelete, s.deleteCatalog)))
+ mux.Handle("POST /teams/{teamID}/users/{userID}/autocomplete", requestOperation("complete", s.authorized(serviceauth.OperationComplete, s.autocomplete)))
+ mux.Handle("POST /teams/{teamID}/users/{userID}/validate", requestOperation("validate", s.authorized(serviceauth.OperationValidate, s.validate)))
+ return securityHeaders(s.logRequests(mux))
+}
+
+func (s *server) logRequests(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ started := time.Now()
+ details := &requestLogDetails{operation: "unmatched"}
+ response := &loggingResponseWriter{ResponseWriter: w}
+ next.ServeHTTP(response, r.WithContext(context.WithValue(r.Context(), requestLogDetailsKey{}, details)))
+
+ statusCode := response.statusCode
+ if statusCode == 0 {
+ statusCode = http.StatusOK
+ }
+ result := details.result
+ if result == "" {
+ if statusCode < http.StatusBadRequest {
+ result = "success"
+ } else {
+ result = "error"
+ }
+ }
+ attributes := []any{
+ "operation", details.operation,
+ "method", r.Method,
+ "status_code", statusCode,
+ "duration_ms", float64(time.Since(started).Microseconds()) / 1000,
+ "response_bytes", response.responseBytes,
+ "result", result,
+ }
+ if details.authorization != nil {
+ attributes = append(attributes, "team_id", details.authorization.TeamID, "user_id", details.authorization.UserID)
+ }
+ if details.result == "catalog_published" {
+ attributes = append(attributes, "catalog_tables", details.catalogTables, "catalog_properties", details.catalogProperties)
+ }
+
+ logger := s.logger
+ if logger == nil {
+ logger = slog.Default()
+ }
+ switch {
+ case details.operation == "health" && statusCode < http.StatusBadRequest:
+ logger.Debug("http_request", attributes...)
+ case statusCode >= http.StatusInternalServerError:
+ logger.Error("http_request", attributes...)
+ case statusCode >= http.StatusBadRequest && details.result != "catalog_miss":
+ logger.Warn("http_request", attributes...)
+ default:
+ logger.Info("http_request", attributes...)
+ }
+ })
+}
+
+func requestOperation(operation string, next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if details := requestDetails(r); details != nil {
+ details.operation = operation
+ }
+ next.ServeHTTP(w, r)
+ })
+}
+
+func (w *loggingResponseWriter) WriteHeader(statusCode int) {
+ if w.statusCode != 0 {
+ return
+ }
+ w.statusCode = statusCode
+ w.ResponseWriter.WriteHeader(statusCode)
+}
+
+func (w *loggingResponseWriter) Write(body []byte) (int, error) {
+ if w.statusCode == 0 {
+ w.WriteHeader(http.StatusOK)
+ }
+ written, err := w.ResponseWriter.Write(body)
+ w.responseBytes += written
+ return written, err
+}
+
+func (w *loggingResponseWriter) Unwrap() http.ResponseWriter {
+ return w.ResponseWriter
+}
+
+func requestDetails(r *http.Request) *requestLogDetails {
+ details, _ := r.Context().Value(requestLogDetailsKey{}).(*requestLogDetails)
+ return details
+}
+
+func setRequestResult(r *http.Request, result string) {
+ if details := requestDetails(r); details != nil {
+ details.result = result
+ }
+}
+
+func securityHeaders(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("X-Content-Type-Options", "nosniff")
+ next.ServeHTTP(w, r)
+ })
+}
+
+type authorizedHandler func(http.ResponseWriter, *http.Request, serviceauth.Authorization)
+
+func (s *server) authorized(operation serviceauth.Operation, next authorizedHandler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ preAuthAllowed, retryAfter := s.preAuthLimiter.Allow(remoteAddress(r))
+ authorization, err := authorizationFromPath(r)
+ if err != nil {
+ if !preAuthAllowed {
+ setRequestResult(r, "rate_limited")
+ writeRateLimitResponse(w, retryAfter)
+ } else {
+ setRequestResult(r, "invalid_scope")
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ }
+ return
+ }
+ if err := s.auth.Verify(r.Header.Get("Authorization"), authorization, operation); err != nil {
+ if !preAuthAllowed {
+ setRequestResult(r, "rate_limited")
+ writeRateLimitResponse(w, retryAfter)
+ } else {
+ setRequestResult(r, "unauthorized")
+ http.Error(w, "unauthorized", http.StatusUnauthorized)
+ }
+ return
+ }
+ if details := requestDetails(r); details != nil {
+ details.authorization = &authorization
+ }
+ if allowed, retryAfter := s.principalLimiter.Allow(authorizationKey(authorization)); !allowed {
+ setRequestResult(r, "rate_limited")
+ writeRateLimitResponse(w, retryAfter)
+ return
+ }
+ next(w, r, authorization)
+ })
+}
+
+func (s *server) putCatalog(w http.ResponseWriter, r *http.Request, authorization serviceauth.Authorization) {
+ var input catalogUpdate
+ if !decodeJSON(w, r, 64<<20, &input) {
+ return
+ }
+ if err := catalog.ValidateRevision(input.Revision); err != nil {
+ setRequestResult(r, "catalog_rejected")
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ if err := catalog.ValidateCatalog(&input.Catalog); err != nil {
+ setRequestResult(r, "catalog_rejected")
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ if err := s.catalogs.Put(authorization, input.Revision, catalog.Prepare(&input.Catalog)); err != nil {
+ setRequestResult(r, "catalog_rejected")
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ if details := requestDetails(r); details != nil {
+ details.result = "catalog_published"
+ details.catalogTables = len(input.Catalog.Tables)
+ for _, properties := range input.Catalog.Properties {
+ details.catalogProperties += len(properties)
+ }
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"teamId": authorization.TeamID, "userId": authorization.UserID, "revision": input.Revision})
+}
+
+func (s *server) deleteCatalog(w http.ResponseWriter, r *http.Request, authorization serviceauth.Authorization) {
+ if !s.catalogs.Delete(authorization) {
+ setRequestResult(r, "catalog_miss")
+ http.Error(w, "catalog not found", http.StatusNotFound)
+ return
+ }
+ setRequestResult(r, "catalog_deleted")
+ w.WriteHeader(http.StatusNoContent)
+}
+
+func (s *server) autocomplete(w http.ResponseWriter, r *http.Request, authorization serviceauth.Authorization) {
+ var input completionRequest
+ if !decodeJSON(w, r, 128<<10, &input) {
+ return
+ }
+ current, revision, ok := s.catalogs.Get(authorization)
+ if !ok {
+ setRequestResult(r, "catalog_miss")
+ http.Error(w, "catalog not found", http.StatusNotFound)
+ return
+ }
+ setRequestResult(r, "catalog_hit")
+ position := -1
+ if input.Position != nil {
+ position = *input.Position
+ }
+ positionEncoding := input.PositionEncoding
+ if positionEncoding == "" {
+ positionEncoding = completion.PositionEncodingUTF8
+ }
+ started := time.Now()
+ result, err := completion.Complete(current, input.Query, position, positionEncoding, input.Cursor)
+ if err != nil {
+ setRequestResult(r, "invalid_query")
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ writeJSON(w, http.StatusOK, completionResponse{
+ Result: result,
+ CatalogRevision: revision,
+ DurationMicros: time.Since(started).Microseconds(),
+ PositionEncoding: positionEncoding,
+ })
+}
+
+func (s *server) validate(w http.ResponseWriter, r *http.Request, authorization serviceauth.Authorization) {
+ var input validationRequest
+ if !decodeJSON(w, r, 128<<10, &input) {
+ return
+ }
+ current, revision, ok := s.catalogs.Get(authorization)
+ if !ok {
+ setRequestResult(r, "catalog_miss")
+ http.Error(w, "catalog not found", http.StatusNotFound)
+ return
+ }
+ setRequestResult(r, "catalog_hit")
+ positionEncoding := input.PositionEncoding
+ if positionEncoding == "" {
+ positionEncoding = textposition.UTF16
+ }
+ result, err := validation.ValidateWithEncoding(current, input.Query, positionEncoding)
+ if err != nil {
+ setRequestResult(r, "invalid_query")
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ writeJSON(w, http.StatusOK, validationResponse{Result: result, CatalogRevision: revision, PositionEncoding: positionEncoding})
+}
+
+func (s *server) health(w http.ResponseWriter, _ *http.Request) {
+ writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
+}
+
+func decodeJSON(w http.ResponseWriter, r *http.Request, maxBytes int64, target any) bool {
+ decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBytes))
+ decoder.DisallowUnknownFields()
+ if err := decoder.Decode(target); err != nil {
+ setRequestResult(r, "invalid_json")
+ http.Error(w, "invalid request: "+err.Error(), http.StatusBadRequest)
+ return false
+ }
+ return true
+}
+
+func authorizationFromPath(r *http.Request) (serviceauth.Authorization, error) {
+ teamID, err := strconv.ParseInt(r.PathValue("teamID"), 10, 64)
+ if err != nil {
+ return serviceauth.Authorization{}, errors.New("teamID and userID must be positive integers")
+ }
+ userID, err := strconv.ParseInt(r.PathValue("userID"), 10, 64)
+ if err != nil || teamID <= 0 || userID <= 0 {
+ return serviceauth.Authorization{}, errors.New("teamID and userID must be positive integers")
+ }
+ return serviceauth.Authorization{TeamID: teamID, UserID: userID}, nil
+}
+
+func remoteAddress(r *http.Request) string {
+ host, _, err := net.SplitHostPort(r.RemoteAddr)
+ if err != nil {
+ return r.RemoteAddr
+ }
+ return host
+}
+
+func authorizationKey(authorization serviceauth.Authorization) string {
+ return strconv.FormatInt(authorization.TeamID, 10) + ":" + strconv.FormatInt(authorization.UserID, 10)
+}
+
+func writeRateLimitResponse(w http.ResponseWriter, retryAfter time.Duration) {
+ seconds := max(int64(1), int64((retryAfter+time.Second-1)/time.Second))
+ w.Header().Set("Retry-After", strconv.FormatInt(seconds, 10))
+ http.Error(w, "rate limit exceeded", http.StatusTooManyRequests)
+}
+
+func writeJSON(w http.ResponseWriter, status int, value any) {
+ body, err := json.Marshal(value)
+ if err != nil {
+ http.Error(w, "encode response", http.StatusInternalServerError)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json; charset=utf-8")
+ w.Header().Set("Content-Length", strconv.Itoa(len(body)))
+ w.WriteHeader(status)
+ // nosemgrep: go.lang.security.audit.xss.no-direct-write-to-responsewriter.no-direct-write-to-responsewriter -- json.Marshal escapes strings and this response has an application/json content type.
+ if _, err := w.Write(body); err != nil {
+ slog.Warn("write response", "error", err)
+ }
+}
diff --git a/services/hogql-language-service/internal/httpapi/handler_test.go b/services/hogql-language-service/internal/httpapi/handler_test.go
new file mode 100644
index 000000000000..3ccb64e115a7
--- /dev/null
+++ b/services/hogql-language-service/internal/httpapi/handler_test.go
@@ -0,0 +1,301 @@
+package httpapi
+
+import (
+ "bytes"
+ "encoding/json"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+ "unicode/utf16"
+
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/catalog"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/completion"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/ratelimit"
+ "github.com/PostHog/posthog/services/hogql-language-service/internal/serviceauth"
+)
+
+func TestAutocompleteUsesOnlyRequestedTeamAndUserCatalog(t *testing.T) {
+ s := newTestServer(t)
+ handler := s.handler()
+ putCatalogForTest(t, handler, 1, 10, "revision-one", "orders")
+ putCatalogForTest(t, handler, 1, 20, "revision-two", "accounts")
+ putCatalogForTest(t, handler, 2, 10, "revision-three", "invoices")
+
+ for _, test := range []struct {
+ teamID int64
+ userID int64
+ revision string
+ table string
+ }{
+ {teamID: 1, userID: 10, revision: "revision-one", table: "orders"},
+ {teamID: 1, userID: 20, revision: "revision-two", table: "accounts"},
+ {teamID: 2, userID: 10, revision: "revision-three", table: "invoices"},
+ } {
+ body := `{"query":"SELECT * FROM "}`
+ path := scopePath(test.teamID, test.userID) + "/autocomplete"
+ request := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
+ request.Header.Set("Content-Type", "application/json")
+ response := httptest.NewRecorder()
+ handler.ServeHTTP(response, request)
+ if response.Code != http.StatusOK {
+ t.Fatalf("autocomplete returned %d: %s", response.Code, response.Body.String())
+ }
+ if contentType := response.Header().Get("Content-Type"); contentType != "application/json; charset=utf-8" {
+ t.Fatalf("unexpected Content-Type: %q", contentType)
+ }
+ if response.Header().Get("X-Content-Type-Options") != "nosniff" {
+ t.Fatal("response is missing X-Content-Type-Options: nosniff")
+ }
+ if contentLength := response.Header().Get("Content-Length"); contentLength != strconv.Itoa(response.Body.Len()) {
+ t.Fatalf("Content-Length = %q, response size = %d", contentLength, response.Body.Len())
+ }
+ var result completionResponse
+ if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
+ t.Fatal(err)
+ }
+ if result.CatalogRevision != test.revision || !hasSuggestion(result.Suggestions, test.table) {
+ t.Fatalf("unexpected response for team %d user %d: %#v", test.teamID, test.userID, result)
+ }
+ if result.PositionEncoding != completion.PositionEncodingUTF8 {
+ t.Fatalf("unexpected position encoding: %q", result.PositionEncoding)
+ }
+ for _, otherTable := range []string{"orders", "accounts", "invoices"} {
+ if otherTable != test.table && hasSuggestion(result.Suggestions, otherTable) {
+ t.Fatalf("%s leaked into team %d user %d", otherTable, test.teamID, test.userID)
+ }
+ }
+ }
+}
+
+func TestAutocompleteRequiresKnownTeamAndUser(t *testing.T) {
+ s := newTestServer(t)
+ for _, test := range []struct {
+ path string
+ body string
+ status int
+ }{
+ {path: "/teams/1/users/invalid/autocomplete", body: `{"query":"SELECT "}`, status: http.StatusBadRequest},
+ {path: "/teams/invalid/users/10/validate", body: `{"query":"SELECT 1"}`, status: http.StatusBadRequest},
+ {path: scopePath(1, 10) + "/autocomplete", body: `{"query":"SELECT "}`, status: http.StatusNotFound},
+ } {
+ request := httptest.NewRequest(http.MethodPost, test.path, strings.NewReader(test.body))
+ response := httptest.NewRecorder()
+ s.handler().ServeHTTP(response, request)
+ if response.Code != test.status {
+ t.Fatalf("expected %d, got %d: %s", test.status, response.Code, response.Body.String())
+ }
+ if response.Header().Get("X-Content-Type-Options") != "nosniff" {
+ t.Fatal("error response is missing X-Content-Type-Options: nosniff")
+ }
+ }
+}
+
+func TestValidateEncodesDiagnosticPositions(t *testing.T) {
+ s := newTestServer(t)
+ handler := s.handler()
+ putCatalogForTest(t, handler, 1, 10, "revision-one", "events")
+ query := "SELECT '😀', missing FROM events"
+ byteStart := strings.Index(query, "missing")
+ utf16Start := len(utf16.Encode([]rune(query[:byteStart])))
+
+ for _, test := range []struct {
+ encoding string
+ responseEncoding string
+ start int
+ }{
+ {encoding: "utf-8", responseEncoding: "utf-8", start: byteStart},
+ {encoding: "utf-16", responseEncoding: "utf-16", start: utf16Start},
+ {responseEncoding: "utf-16", start: utf16Start},
+ } {
+ body, err := json.Marshal(map[string]any{"query": query, "positionEncoding": test.encoding})
+ if err != nil {
+ t.Fatal(err)
+ }
+ request := httptest.NewRequest(http.MethodPost, scopePath(1, 10)+"/validate", bytes.NewReader(body))
+ request.Header.Set("Content-Type", "application/json")
+ response := httptest.NewRecorder()
+ handler.ServeHTTP(response, request)
+ if response.Code != http.StatusOK {
+ t.Fatalf("validate returned %d: %s", response.Code, response.Body.String())
+ }
+ var result validationResponse
+ if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
+ t.Fatal(err)
+ }
+ if string(result.PositionEncoding) != test.responseEncoding {
+ t.Fatalf("position encoding = %q, want %q", result.PositionEncoding, test.responseEncoding)
+ }
+ if len(result.Diagnostics) != 1 {
+ t.Fatalf("diagnostics = %#v", result.Diagnostics)
+ }
+ diagnostic := result.Diagnostics[0]
+ if diagnostic.Start != test.start || diagnostic.End != test.start+len("missing") {
+ t.Fatalf("%s diagnostic span = [%d,%d), want [%d,%d)", test.responseEncoding, diagnostic.Start, diagnostic.End, test.start, test.start+len("missing"))
+ }
+ }
+}
+
+func TestRequestLogIncludesMetadataWithoutRequestContents(t *testing.T) {
+ var logs bytes.Buffer
+ s := newTestServer(t)
+ s.logger = slog.New(slog.NewJSONHandler(&logs, nil))
+ handler := s.handler()
+ putCatalogForTest(t, handler, 1, 10, "revision-one", "events")
+ logs.Reset()
+
+ request := httptest.NewRequest(http.MethodPost, scopePath(1, 10)+"/validate", strings.NewReader(`{"query":"SELECT 'do-not-log-query'"}`))
+ request.Header.Set("Authorization", "Bearer do-not-log-token")
+ response := httptest.NewRecorder()
+ handler.ServeHTTP(response, request)
+ if response.Code != http.StatusOK {
+ t.Fatalf("validate returned %d: %s", response.Code, response.Body.String())
+ }
+
+ var entry map[string]any
+ if err := json.Unmarshal(bytes.TrimSpace(logs.Bytes()), &entry); err != nil {
+ t.Fatalf("decode request log: %v\n%s", err, logs.String())
+ }
+ for key, expected := range map[string]any{
+ "msg": "http_request",
+ "operation": "validate",
+ "method": http.MethodPost,
+ "status_code": float64(http.StatusOK),
+ "response_bytes": float64(response.Body.Len()),
+ "result": "catalog_hit",
+ "team_id": float64(1),
+ "user_id": float64(10),
+ } {
+ if entry[key] != expected {
+ t.Errorf("%s = %#v, want %#v", key, entry[key], expected)
+ }
+ }
+ if duration, ok := entry["duration_ms"].(float64); !ok || duration < 0 {
+ t.Errorf("duration_ms = %#v", entry["duration_ms"])
+ }
+ if strings.Contains(logs.String(), "do-not-log-query") || strings.Contains(logs.String(), "do-not-log-token") {
+ t.Fatalf("request contents leaked into log: %s", logs.String())
+ }
+
+ logs.Reset()
+ request = httptest.NewRequest(http.MethodGet, "/unknown", nil)
+ response = httptest.NewRecorder()
+ handler.ServeHTTP(response, request)
+ if response.Code != http.StatusNotFound {
+ t.Fatalf("unknown route returned %d: %s", response.Code, response.Body.String())
+ }
+ entry = map[string]any{}
+ if err := json.Unmarshal(bytes.TrimSpace(logs.Bytes()), &entry); err != nil {
+ t.Fatalf("decode unmatched request log: %v\n%s", err, logs.String())
+ }
+ for key, expected := range map[string]any{
+ "level": "WARN",
+ "msg": "http_request",
+ "operation": "unmatched",
+ "method": http.MethodGet,
+ "status_code": float64(http.StatusNotFound),
+ "result": "error",
+ } {
+ if entry[key] != expected {
+ t.Errorf("%s = %#v, want %#v", key, entry[key], expected)
+ }
+ }
+}
+
+func TestPrincipalRateLimitRunsBeforeBodyDecodeAndDoesNotCrossScopes(t *testing.T) {
+ preAuthLimiter, err := ratelimit.New(ratelimit.Config{Capacity: 1, RefillPerSec: 0.001, MaxEntries: 10, IdleTTL: time.Hour})
+ if err != nil {
+ t.Fatal(err)
+ }
+ principalLimiter, err := ratelimit.New(ratelimit.Config{Capacity: 1, RefillPerSec: 0.001, MaxEntries: 10, IdleTTL: time.Hour})
+ if err != nil {
+ t.Fatal(err)
+ }
+ s := &server{
+ catalogs: catalog.NewRegistry(10, 1<<20, time.Hour),
+ auth: serviceauth.New(nil, true),
+ preAuthLimiter: preAuthLimiter,
+ principalLimiter: principalLimiter,
+ logger: discardLogger(),
+ }
+ value := &catalog.Catalog{Tables: map[string]catalog.Table{}, Properties: map[string][]catalog.Property{}}
+ for _, authorization := range []serviceauth.Authorization{{TeamID: 1, UserID: 10}, {TeamID: 1, UserID: 20}} {
+ if err := s.catalogs.Put(authorization, "1", catalog.Prepare(value)); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ request := httptest.NewRequest(http.MethodPost, scopePath(1, 10)+"/autocomplete", strings.NewReader(`{"query":"SELECT "}`))
+ response := httptest.NewRecorder()
+ s.handler().ServeHTTP(response, request)
+ if response.Code != http.StatusOK {
+ t.Fatalf("first request returned %d: %s", response.Code, response.Body.String())
+ }
+
+ request = httptest.NewRequest(http.MethodPost, scopePath(1, 10)+"/autocomplete", strings.NewReader(`{`))
+ response = httptest.NewRecorder()
+ s.handler().ServeHTTP(response, request)
+ if response.Code != http.StatusTooManyRequests || response.Header().Get("Retry-After") == "" {
+ t.Fatalf("limited request returned %d without Retry-After: %s", response.Code, response.Body.String())
+ }
+
+ request = httptest.NewRequest(http.MethodPost, scopePath(1, 20)+"/autocomplete", strings.NewReader(`{"query":"SELECT "}`))
+ response = httptest.NewRecorder()
+ s.handler().ServeHTTP(response, request)
+ if response.Code != http.StatusOK {
+ t.Fatalf("another user inherited the rate limit: %d: %s", response.Code, response.Body.String())
+ }
+}
+
+func putCatalogForTest(t *testing.T, handler http.Handler, teamID, userID int64, revision, table string) {
+ t.Helper()
+ body := `{"revision":"` + revision + `","catalog":{"tables":{"` + table + `":{"name":"` + table + `","type":"warehouse","fields":{}}},"properties":{}}}`
+ path := scopePath(teamID, userID) + "/catalog"
+ request := httptest.NewRequest(http.MethodPut, path, strings.NewReader(body))
+ response := httptest.NewRecorder()
+ handler.ServeHTTP(response, request)
+ if response.Code != http.StatusOK {
+ t.Fatalf("catalog upload returned %d: %s", response.Code, response.Body.String())
+ }
+}
+
+func newTestServer(t *testing.T) *server {
+ t.Helper()
+ config := ratelimit.Config{Capacity: 1000, RefillPerSec: 1000, MaxEntries: 100, IdleTTL: time.Hour}
+ preAuthLimiter, err := ratelimit.New(config)
+ if err != nil {
+ t.Fatal(err)
+ }
+ principalLimiter, err := ratelimit.New(config)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return &server{
+ catalogs: catalog.NewRegistry(10, 1<<20, time.Hour),
+ auth: serviceauth.New(nil, true),
+ preAuthLimiter: preAuthLimiter,
+ principalLimiter: principalLimiter,
+ logger: discardLogger(),
+ }
+}
+
+func discardLogger() *slog.Logger {
+ return slog.New(slog.NewTextHandler(io.Discard, nil))
+}
+
+func scopePath(teamID, userID int64) string {
+ return "/teams/" + strconv.FormatInt(teamID, 10) + "/users/" + strconv.FormatInt(userID, 10)
+}
+
+func hasSuggestion(suggestions []completion.Suggestion, label string) bool {
+ for _, suggestion := range suggestions {
+ if suggestion.Label == label {
+ return true
+ }
+ }
+ return false
+}