Skip to content

An open-source, faster Devin alternative

TypeScript

hotfix: sandbox-logs endpoint was returning cross-tenant data (#242)

Mohamed Habib72d6df047b3e
diff --git a/internal/api/sandbox_logs.go b/internal/api/sandbox_logs.go
index d9e29cc0..10a32e72 100644
--- a/internal/api/sandbox_logs.go
+++ b/internal/api/sandbox_logs.go
@@ -19,7 +19,7 @@ import (
)
// allowedSources is the closed set of source values a client may filter
-// on. Anything else gets a 400 — never fed into the APL string.
+// on. Anything else gets a 400 — never fed into the query.
var allowedSources = map[string]struct{}{
"var_log": {},
"exec_stdout": {},
@@ -27,6 +27,31 @@ var allowedSources = map[string]struct{}{
"agent": {},
}
+// WARNING: Axiom's /v1/datasets/<dataset>/query endpoint silently
+// ignores unknown body fields. Sending `{"apl": "..."}` returns 200
+// with every event in the dataset (no filter applied). Always send the
+// `filter` field, and verify against a real response when changing the
+// body shape.
+type queryFilter struct {
+ Op string `json:"op"`
+ Field string `json:"field,omitempty"`
+ Value any `json:"value,omitempty"`
+ Filters []queryFilter `json:"filters,omitempty"`
+}
+
+type queryOrderField struct {
+ Field string `json:"field"`
+ Desc bool `json:"desc,omitempty"`
+}
+
+type queryRequest struct {
+ StartTime string `json:"startTime"`
+ EndTime string `json:"endTime"`
+ Filter queryFilter `json:"filter"`
+ Limit int `json:"limit,omitempty"`
+ Order []queryOrderField `json:"order,omitempty"`
+}
+
// getSandboxLogs streams sandbox session logs as Server-Sent Events.
//
// Flow:
@@ -106,7 +131,7 @@ func (s *Server) getSandboxLogs(c echo.Context) error {
// Initial historical batch.
histStart, histEnd := q.timeWindow(false)
- rows, err := s.queryAxiom(ctx, q.toAPL(s.axiomDataset, false), histStart, histEnd)
+ rows, err := s.queryAxiom(ctx, q.toRequest(histStart, histEnd, false))
if err != nil {
log.Printf("api: sandbox %s logs: initial query failed: %v", sandboxID, err)
writeSSEComment(c.Response(), "initial query failed")
@@ -155,7 +180,7 @@ func (s *Server) getSandboxLogs(c echo.Context) error {
tailQ.since = cursor
tailQ.until = time.Time{} // open-ended
tailStart, tailEnd := tailQ.timeWindow(true)
- newRows, err := s.queryAxiom(ctx, tailQ.toAPL(s.axiomDataset, true), tailStart, tailEnd)
+ newRows, err := s.queryAxiom(ctx, tailQ.toRequest(tailStart, tailEnd, true))
if err != nil {
// Don't kill the stream on a single failed poll — log
// and try again next tick. Persistent failures will
@@ -236,15 +261,13 @@ func parseLogQuery(sandboxID string, sandboxStarted time.Time, qs url.Values) (l
}
if v := qs.Get("q"); v != "" {
- // Disallow newlines + control chars; double-escape quotes.
- // APL string literals are double-quoted; embedded `"` is
- // escaped as `\"`. The set we strip here is the surface that
- // could break out of a string literal; everything else passes
- // through unchanged so search behaviour matches user intent.
+ // Defense in depth: reject control chars; Axiom's `contains`
+ // operator takes the value as a JSON string so quote escaping
+ // isn't needed.
if strings.ContainsAny(v, "\r\n\x00") {
return q, fmt.Errorf("q must not contain control characters")
}
- q.text = strings.ReplaceAll(v, `"`, `\"`)
+ q.text = v
}
if v := qs.Get("source"); v != "" {
@@ -278,38 +301,47 @@ func (q logQuery) timeWindow(tail bool) (time.Time, time.Time) {
return q.since, end
}
-// toAPL renders the query into a KQL/APL string. The sandbox_id filter
-// is the FIRST predicate after the dataset and is unconditionally
-// applied — there is no path that omits it. Every interpolated string
-// is either: a server-derived constant (sandboxID, dataset name), a
-// validated value from allowedSources, or pre-escaped (text search).
-//
-// `tail` selects an open-ended (no until) variant.
-func (q logQuery) toAPL(dataset string, tail bool) string {
- var b strings.Builder
- fmt.Fprintf(&b, "['%s']\n", dataset)
- fmt.Fprintf(&b, " | where sandbox_id == \"%s\"\n", q.sandboxID)
- if !q.since.IsZero() {
- fmt.Fprintf(&b, " | where _time >= datetime(\"%s\")\n", q.since.UTC().Format(time.RFC3339Nano))
- }
- if !tail && !q.until.IsZero() {
- fmt.Fprintf(&b, " | where _time <= datetime(\"%s\")\n", q.until.UTC().Format(time.RFC3339Nano))
+// toFilter: sandbox_id == q.sandboxID is ALWAYS the first conjunct
+// under the top-level AND. Do not add a path that omits or mutates it;
+// the regression test in sandbox_logs_test.go pins this.
+func (q logQuery) toFilter() queryFilter {
+ root := queryFilter{
+ Op: "and",
+ Filters: []queryFilter{
+ {Op: "==", Field: "sandbox_id", Value: q.sandboxID},
+ },
}
if q.text != "" {
- fmt.Fprintf(&b, " | where line contains \"%s\"\n", q.text)
+ root.Filters = append(root.Filters, queryFilter{
+ Op: "contains", Field: "line", Value: q.text,
+ })
}
if len(q.sources) > 0 {
- quoted := make([]string, len(q.sources))
- for i, s := range q.sources {
- quoted[i] = fmt.Sprintf("\"%s\"", s)
+ srcOr := queryFilter{Op: "or"}
+ for _, s := range q.sources {
+ srcOr.Filters = append(srcOr.Filters, queryFilter{
+ Op: "==", Field: "source", Value: s,
+ })
}
- fmt.Fprintf(&b, " | where source in (%s)\n", strings.Join(quoted, ", "))
+ root.Filters = append(root.Filters, srcOr)
+ }
+ return root
+}
+
+// toRequest: time range goes in startTime/endTime (server-side bound);
+// only the structural predicate goes in `filter`. Tail variant omits
+// Limit so every poll surfaces every new row since the cursor.
+func (q logQuery) toRequest(startTime, endTime time.Time, tail bool) queryRequest {
+ req := queryRequest{
+ StartTime: startTime.UTC().Format(time.RFC3339Nano),
+ EndTime: endTime.UTC().Format(time.RFC3339Nano),
+ Filter: q.toFilter(),
+ Order: []queryOrderField{{Field: "_time"}},
}
- fmt.Fprintf(&b, " | sort by _time asc\n")
if !tail {
- fmt.Fprintf(&b, " | limit %d\n", q.limit)
+ req.Limit = q.limit
}
- return b.String()
+ return req
}
// logEvent is the on-the-wire shape we re-emit to SSE clients. Mirrors
@@ -327,27 +359,13 @@ type logEvent struct {
ExitCode *int `json:"exit_code,omitempty"`
}
-// queryAxiom POSTs an APL query and parses the response.
-//
-// Axiom's APL endpoint is /v1/datasets/_apl/query (with format=tabular
-// off, default), and the response shape is:
+// queryAxiom POSTs a filter-style query and parses the response.
//
-// {
-// "matches": [{"data": {<event fields>}}, ...]
-// }
+// Endpoint: /v1/datasets/<dataset>/query. Response shape:
//
-// We don't need format=tabular; the default object form is what we want.
-func (s *Server) queryAxiom(ctx context.Context, apl string, startTime, endTime time.Time) ([]logEvent, error) {
- body, _ := json.Marshal(map[string]any{
- "apl": apl,
- "startTime": startTime.UTC().Format(time.RFC3339Nano),
- "endTime": endTime.UTC().Format(time.RFC3339Nano),
- })
- // Axiom's APL endpoint. /_apl/query takes the APL string verbatim
- // (the dataset name is encoded inside the APL itself, e.g.
- // `['oc-sandbox-logs'] | ...`). Tried the per-dataset
- // /v1/datasets/<dataset>/query path first but that returned 404
- // for APL-shaped bodies.
+// { "matches": [ { "_time": "...", "data": {<event fields>} }, ... ] }
+func (s *Server) queryAxiom(ctx context.Context, qreq queryRequest) ([]logEvent, error) {
+ body, _ := json.Marshal(qreq)
req, err := http.NewRequestWithContext(ctx, "POST",
fmt.Sprintf("https://api.axiom.co/v1/datasets/%s/query", url.PathEscape(s.axiomDataset)),
bytes.NewReader(body))
diff --git a/internal/api/sandbox_logs_test.go b/internal/api/sandbox_logs_test.go
index 8c536f5b..8a3709d5 100644
--- a/internal/api/sandbox_logs_test.go
+++ b/internal/api/sandbox_logs_test.go
@@ -1,19 +1,19 @@
package api
import (
+ "encoding/json"
"net/url"
"strings"
"testing"
"time"
)
-// TestAPL_AlwaysFiltersSandboxID is the load-bearing security test:
-// no matter what the user supplies in query params, the rendered APL
-// must filter on sandbox_id == the URL-path value. This is the
-// invariant that makes the auth model work — break this and a user
-// who can hit /api/sandboxes/X/logs but only owns Y could read X's
-// logs by sneaking past the filter.
-func TestAPL_AlwaysFiltersSandboxID(t *testing.T) {
+// TestFilter_AlwaysFiltersSandboxID is the load-bearing security test:
+// no matter what the user supplies in query params, the rendered filter
+// must have sandbox_id == the URL-path value as the first conjunct under
+// the top-level AND. Break this and a user who can hit
+// /api/sandboxes/X/logs but only owns Y could read X's logs.
+func TestFilter_AlwaysFiltersSandboxID(t *testing.T) {
cases := []struct {
name string
qs url.Values
@@ -23,7 +23,7 @@ func TestAPL_AlwaysFiltersSandboxID(t *testing.T) {
{"with sources", url.Values{"source": {"exec_stdout,exec_stderr"}}},
{"with limit", url.Values{"limit": {"500"}}},
{
- "injection attempt — quote in q",
+ "injection attempt — quotes in q",
url.Values{"q": {`" or sandbox_id != "anything`}},
},
}
@@ -34,30 +34,45 @@ func TestAPL_AlwaysFiltersSandboxID(t *testing.T) {
if err != nil {
t.Fatalf("parse: %v", err)
}
- apl := q.toAPL("oc-sandbox-logs", false)
- if !strings.Contains(apl, `where sandbox_id == "sb-target"`) {
- t.Errorf("APL missing sandbox_id filter:\n%s", apl)
+ f := q.toFilter()
+
+ if f.Op != "and" {
+ t.Errorf("top-level op = %q, want and", f.Op)
}
- // Verify the filter line is the FIRST predicate after the
- // dataset, not buried somewhere a search OR could subvert.
- lines := strings.Split(strings.TrimSpace(apl), "\n")
- if len(lines) < 2 {
- t.Fatalf("APL too short:\n%s", apl)
+ if len(f.Filters) == 0 {
+ t.Fatalf("top-level filter has no sub-filters")
}
- if !strings.Contains(lines[1], `where sandbox_id == "sb-target"`) {
- t.Errorf("sandbox_id filter not first predicate:\n%s", apl)
+ first := f.Filters[0]
+ if first.Op != "==" || first.Field != "sandbox_id" || first.Value != "sb-target" {
+ t.Errorf("first conjunct = %+v, want sandbox_id == sb-target", first)
}
})
}
}
-// TestAPL_RejectsBadSource: source values not in allowedSources are a
+// TestFilter_QInjectionStaysInValue: a malicious `q` parameter ends up as
+// a plain string in the JSON value, not as a sibling predicate.
+func TestFilter_QInjectionStaysInValue(t *testing.T) {
+ mal := `" or sandbox_id != "anything`
+ q, err := parseLogQuery("sb-target", time.Now(), url.Values{"q": {mal}})
+ if err != nil {
+ t.Fatalf("parse: %v", err)
+ }
+ f := q.toFilter()
+ // The text predicate is the second conjunct.
+ if len(f.Filters) < 2 {
+ t.Fatalf("expected at least 2 sub-filters, got %d", len(f.Filters))
+ }
+ txt := f.Filters[1]
+ if txt.Op != "contains" || txt.Field != "line" || txt.Value != mal {
+ t.Errorf("text predicate = %+v, expected contains(line, %q)", txt, mal)
+ }
+}
+
+// TestFilter_RejectsBadSource: source values not in allowedSources are a
// 400 at parse time, never interpolated.
-func TestAPL_RejectsBadSource(t *testing.T) {
- for _, bad := range []string{"system", "stdout", "exec_stdout'); drop --", ""} {
- if bad == "" {
- continue // empty values are stripped, not rejected
- }
+func TestFilter_RejectsBadSource(t *testing.T) {
+ for _, bad := range []string{"system", "stdout", "exec_stdout'); drop --"} {
t.Run(bad, func(t *testing.T) {
_, err := parseLogQuery("sb-x", time.Now(), url.Values{"source": {bad}})
if err == nil {
@@ -67,10 +82,10 @@ func TestAPL_RejectsBadSource(t *testing.T) {
}
}
-// TestAPL_RejectsControlCharsInQ: newlines / NULs in `q` would let a
-// user break out of the string literal and append APL of their own.
-// They must be rejected at parse time.
-func TestAPL_RejectsControlCharsInQ(t *testing.T) {
+// TestFilter_RejectsControlCharsInQ: newlines / NULs in `q` are rejected
+// at parse time to avoid any operator-side quirk with embedded control
+// characters.
+func TestFilter_RejectsControlCharsInQ(t *testing.T) {
for _, bad := range []string{"hello\nworld", "x\x00y", "\r"} {
_, err := parseLogQuery("sb-x", time.Now(), url.Values{"q": {bad}})
if err == nil {
@@ -79,52 +94,87 @@ func TestAPL_RejectsControlCharsInQ(t *testing.T) {
}
}
-// TestAPL_QuoteEscapeInQ: legitimate double quotes in `q` are escaped
-// to `\"` so the APL parses as a single string literal.
-func TestAPL_QuoteEscapeInQ(t *testing.T) {
- q, err := parseLogQuery("sb-x", time.Now(), url.Values{"q": {`hello "world"`}})
+// TestFilter_SourceList_Or: multiple sources become an OR subtree, not a
+// list-in-value.
+func TestFilter_SourceList_Or(t *testing.T) {
+ q, err := parseLogQuery("sb-x", time.Now(), url.Values{"source": {"exec_stdout,exec_stderr"}})
+ if err != nil {
+ t.Fatalf("parse: %v", err)
+ }
+ f := q.toFilter()
+ if len(f.Filters) < 2 {
+ t.Fatalf("expected sandbox_id + source-or, got %d sub-filters", len(f.Filters))
+ }
+ srcOr := f.Filters[1]
+ if srcOr.Op != "or" {
+ t.Errorf("source subtree op = %q, want or", srcOr.Op)
+ }
+ if len(srcOr.Filters) != 2 {
+ t.Fatalf("source OR has %d filters, want 2", len(srcOr.Filters))
+ }
+}
+
+// TestRequest_TailOmitsLimit: tail polls don't impose a row cap (every
+// poll wants every new event since the cursor).
+func TestRequest_TailOmitsLimit(t *testing.T) {
+ q, err := parseLogQuery("sb-x", time.Now().Add(-time.Hour), url.Values{"limit": {"50"}})
if err != nil {
t.Fatalf("parse: %v", err)
}
- apl := q.toAPL("d", false)
- if !strings.Contains(apl, `where line contains "hello \"world\""`) {
- t.Errorf("expected escaped quotes in APL:\n%s", apl)
+ tailReq := q.toRequest(time.Now().Add(-time.Hour), time.Now(), true)
+ if tailReq.Limit != 0 {
+ t.Errorf("tail request limit = %d, want 0 (omitted)", tailReq.Limit)
+ }
+ histReq := q.toRequest(time.Now().Add(-time.Hour), time.Now(), false)
+ if histReq.Limit != 50 {
+ t.Errorf("historical request limit = %d, want 50", histReq.Limit)
}
}
-// TestAPL_TailVariantOmitsLimitAndUntil: the live-tail render path
-// shouldn't bound by `until` or apply a row cap — every poll wants
-// every new event since the cursor.
-func TestAPL_TailVariantOmitsLimitAndUntil(t *testing.T) {
+// TestRequest_BodyShape — full marshaled-JSON smoke test. Failure here
+// likely means the body shape has drifted in a way Axiom won't
+// understand; cross-reference against the API docs before changing.
+func TestRequest_BodyShape(t *testing.T) {
q, err := parseLogQuery("sb-x", time.Now().Add(-time.Hour), url.Values{
- "until": {time.Now().Format(time.RFC3339)},
- "limit": {"50"},
+ "q": {"oops"},
+ "source": {"exec_stdout"},
})
if err != nil {
t.Fatalf("parse: %v", err)
}
- tailAPL := q.toAPL("d", true)
- if strings.Contains(tailAPL, "_time <=") {
- t.Errorf("tail APL must not bound by until:\n%s", tailAPL)
- }
- if strings.Contains(tailAPL, "limit") {
- t.Errorf("tail APL must not apply limit:\n%s", tailAPL)
+ start := time.Date(2026, 5, 13, 0, 0, 0, 0, time.UTC)
+ end := time.Date(2026, 5, 13, 1, 0, 0, 0, time.UTC)
+ req := q.toRequest(start, end, false)
+ body, err := json.Marshal(req)
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
}
-
- // And the historical render path DOES include them.
- histAPL := q.toAPL("d", false)
- if !strings.Contains(histAPL, "_time <=") {
- t.Errorf("historical APL missing until:\n%s", histAPL)
+ for _, must := range []string{
+ `"startTime":"2026-05-13T00:00:00Z"`,
+ `"endTime":"2026-05-13T01:00:00Z"`,
+ `"filter":{"op":"and",`,
+ `"op":"==","field":"sandbox_id","value":"sb-x"`,
+ `"op":"contains","field":"line","value":"oops"`,
+ `"op":"==","field":"source","value":"exec_stdout"`,
+ `"limit":1000`,
+ `"order":[{"field":"_time"}]`,
+ } {
+ if !strings.Contains(string(body), must) {
+ t.Errorf("body missing %q:\n%s", must, body)
+ }
}
- if !strings.Contains(histAPL, "limit") {
- t.Errorf("historical APL missing limit:\n%s", histAPL)
+ // And it must NOT contain an `apl` field — the regression that
+ // caused the cross-tenant leak. The per-dataset endpoint silently
+ // ignores unknown body fields, so {"apl": "..."} comes back with
+ // every event in the dataset.
+ if strings.Contains(string(body), `"apl"`) {
+ t.Errorf("body contains an `apl` field — this is the bug we're guarding against:\n%s", body)
}
}
-// TestAPL_LimitClamp: caller-supplied limit > 10000 is silently
-// clamped to 10000 (we don't 400 here — the cap is a defense, not a
-// contract).
-func TestAPL_LimitClamp(t *testing.T) {
+// TestParseLogQuery_LimitClamp: caller-supplied limit > 10000 is silently
+// clamped to 10000 (the cap is a defense, not a contract).
+func TestParseLogQuery_LimitClamp(t *testing.T) {
q, err := parseLogQuery("sb-x", time.Now(), url.Values{"limit": {"99999"}})
if err != nil {
t.Fatalf("parse: %v", err)