diff --git a/CHANGELOG.md b/CHANGELOG.md index 46638aab..4d8b5c36 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,7 @@ All notable changes to this project are documented in this file. The format is b - **`ask_operator` target warning**: a request whose question names a host or URL outside the goal targets is tagged as containing target-derived text (#197). - **Opt-in update banner**: `ARTEX_UPDATE_CHECK` makes the backend check the latest GitHub release at most once per 24 hours and the UI show a banner; off by default (#202). - **Release provenance**: release archives carry GitHub build provenance attestations and a CycloneDX SBOM (`gh attestation verify --repo BaaRai/ARTEX`); release notes are the matching `CHANGELOG.md` section (#219, #201). +- **HAR 1.2 traffic import and export**: `POST /api/traffic/import/har` imports raw HAR 1.2 JSON captures (up to 32 MiB / 2,000 entries / 32 MiB decoded bodies) with deterministic `har-` IDs (and `_artexExchangeId` preservation for ARTEX exports so distinct same-second exchanges round-trip without collapsing), base64 decoding, `postData.params` and `cookies` array fallbacks, URL userinfo stripping, blob spilling above 256 KiB, and full-text indexing, without applying capture rewrite rules (`exchange_rewrites` stays empty); per-entry errors are reported alongside `imported`/`skipped`/`failed` counts. `GET /api/traffic/export/har` exports filtered traffic (reusing the `GET /api/traffic` filters) as a compliant HAR 1.2 document (with explicit unknown placeholders for unrecorded timings and header sizes) in stable `(ts, id)` order, encoding UTF-8 bodies as text and binary bodies as base64, capped at 1,000 entries / 20 MiB raw headers+bodies (31 MiB JSON backstop, guaranteed under the 32 MiB import limit) with explicit truncation reporting via `X-ARTEX-HAR-*` headers and `_truncated`/`_truncatedReason`/`_totalMatched` fields. The Traffic page adds **Import HAR** and **Export HAR** controls. See `docs/traffic-har.md`. - **Capture-proxy rewrite rules, storage and API**: `GET`, `POST`, `PUT` and `DELETE /api/traffic/rewrite-rules` and `POST /api/traffic/rewrite-rules/{id}/toggle` manage rules that match a request or a response (method, host, URL, headers, body, status) and describe a rewrite (method, path and query, headers, body, status). Rules are validated on save, limited to 100 of which 50 enabled, created disabled, and stored in the new table `traffic_rewrite_rules` (migration `0005_traffic_rewrite_rules.sql`) with `matchers` and `actions` encrypted at rest. The value of an action marked `sensitive` is never returned, and an update sent without it keeps the stored one. The server compiles the enabled rules at startup and after every change and hands the snapshot to the proxy. The proxy applies them from the next entry. See `docs/traffic-rewrite-rules.md`. - **Capture-proxy rewrite rules applied**: the capture proxy applies enabled rules to each HTTP request before it is sent to the target and to each response before it reaches the client. Each action that ran is recorded in the new table `exchange_rewrites` in the same transaction as the exchange, `traffic_get` shows a `REWRITTEN` line, and `traffic_search` never finds a value a rule wrote. SSE status and headers are rewritten at the start of the stream. **WebSocket handshakes are not rewritten**: the capture library runs its hook after the upgrade, so the status and headers cannot be changed, and frames pass unchanged. **Responses of 5 MiB or more** are forwarded unchanged and not recorded in full, because the library does not call the response hook for them. Snapshots of original requests are capped at 1024 entries and 64 MiB. Replays (`POST /api/traffic/replay`) bypass capture rewrite rules by default via an internal `X-ARTEX-Replay-Nonce` header stripped unconditionally by the proxy, and apply the rules when opted in with `apply_rules: true` (the **Apply capture rewrite rules** checkbox in the Replay panel). `GET /api/traffic` exposes the proxy's `rewrite` counters (`large_responses`, `capacity_refusals`, `tombstone_drops`, `conversions`, `sweeps`), flags each exchange row with `rewritten`, and filters with `rewritten=all|rewritten|original` (also accepting `true`/`false`), surfaced with a filter control and row badge on the Traffic page. Traffic archives export version 2 with per-exchange `rewritten` and sorted distinct applied `rewrite_rule_ids` while remaining deterministic and backward-compatible with version 1 archives. The rule-management web UI comes later. - **Bulk finding status** (#298): select findings in the findings table and apply one disposition to all of them, up to 500 per call, in one transaction; each row still goes through the single-decision notification semantics and the change is mirrored onto its exploration node (#289). diff --git a/docs/traffic-har.md b/docs/traffic-har.md new file mode 100644 index 00000000..76587cb8 --- /dev/null +++ b/docs/traffic-har.md @@ -0,0 +1,130 @@ +# Traffic HAR 1.2 Import and Export + +ARTEX supports importing and exporting captured HTTP traffic using the **HAR 1.2** JSON format so operators can bring captures from browser DevTools or external proxies into the Traffic store and export filtered subsets out of ARTEX. + +Both routes require the standard administrator JWT (`Authorization: Bearer `) like the rest of `/api/traffic`, and return `503` when the traffic store is unavailable. + +--- + +## Import: `POST /api/traffic/import/har` + +### Request format + +Send a raw HAR 1.2 JSON document directly as the HTTP request body (`Content-Type: application/json`), capped at the standard API JSON body limit (**32 MiB**; oversized bodies return `413 Request Entity Too Large`). + +```bash +curl -X POST \ + -H "Authorization: Bearer $TOKEN" \ + -H "Content-Type: application/json" \ + --data-binary @capture.har \ + http://127.0.0.1:8787/api/traffic/import/har +``` + +The Traffic page also provides an **Import HAR** file picker (with the same 32 MiB limit) that reads a `.har` / `.json` file, posts it to this endpoint, displays loading/error state and a count summary, and refreshes the table. + +### Validation & error handling + +The request is rejected with `400 Bad Request` naming the reason when: + +- the body is empty or malformed JSON (including trailing content after the root object), +- the `log` object is missing, +- `log.version` is not `"1.2"`, +- `log.entries` is missing or `null`, +- `log.entries` exceeds the per-import entry cap (`2000` entries). + +Individual malformed entries (invalid `startedDateTime`, non-HTTP(S) URL, invalid HTTP method, header/cookie names or values containing CR/LF/NUL, out-of-range status, invalid base64 or unsupported body encoding) do **not** fail the whole import: they are counted in `failed` and reported in `errors` (up to 50 error details) while valid entries continue importing. HTTP/2 pseudo-headers starting with `:` (such as `:authority` or `:method` from browser DevTools) are skipped cleanly. + +### Response + +```json +{ + "imported": 12, + "skipped": 3, + "failed": 1, + "truncated": false, + "errors": [ + { "index": 4, "url": "notaurl", "reason": "invalid request url \"notaurl\"" } + ] +} +``` + +### Deterministic IDs, round-trip fidelity, & idempotence + +- **ARTEX exports (`_artexExchangeId`)**: Every entry exported by ARTEX carries the HAR 1.2 custom field `_artexExchangeId` set to the exchange's stored ID. When a valid `_artexExchangeId` (`[A-Za-z0-9._:-]`, 1–128 chars) is present on import, ARTEX preserves it. This guarantees that two distinct ARTEX exchanges recorded within the same second with identical method, URL, status, and bodies do **not** collapse into one row when imported into a fresh store, and that re-importing an export into the source store stays idempotent (`skipped`). +- **External HARs (no `_artexExchangeId`)**: Each entry receives a deterministic content-based ID: + +```text +har- +``` + + `ts_unix_seconds` is `startedDateTime` parsed as RFC 3339 and truncated to UTC Unix seconds (matching `exchanges.ts`). Re-importing the same external HAR skips existing IDs (`INSERT OR IGNORE`, hot rows always win). Identical entries in the same external HAR sharing `(ts_unix_seconds, method, canonical_url, status, req_body, resp_body)` are deduplicated (the first is imported, duplicates are counted in `skipped`). + +### Storage, bodies, cookies, `postData.params`, and userinfo + +- **URL userinfo**: Any `user:pass@` userinfo in `request.url` is stripped before storing, indexing, listing, exporting, or reporting errors (matching ARTEX's asset store). +- `host` is derived from `URL.Hostname()` and `url_template` from `db.TemplatePath(URL.EscapedPath())`; `path` stays empty. +- **Bodies & base64**: `response.content.text` and `request.postData.text` are stored as raw UTF-8 bytes when `encoding` is empty, and decoded via standard base64 when `encoding` is `"base64"`. When `request.postData.text` is empty and `request.postData.params` is populated, ARTEX reconstructs the form body as `application/x-www-form-urlencoded` (preserving parameter order). +- **Cookies arrays**: When `request.headers` does not already include a `Cookie` header and `request.cookies` is non-empty, ARTEX synthesizes a `Cookie` header from `request.cookies`. Likewise, when `response.headers` does not already include a `Set-Cookie` header and `response.cookies` is non-empty, ARTEX synthesizes `Set-Cookie` headers from `response.cookies`. When the headers are already present, they are kept as-is without duplication. +- `req_len` and `resp_len` record the actual decoded byte lengths. +- `content_type` comes from `response.content.mimeType` (falling back to the response `Content-Type` header). +- Bodies larger than the 256 KiB inline threshold spill to the content-addressed blob store (`_blobs/sha256/...`) with `blob_refs` rows, and searchable text bodies are added to the `ex_fts` full-text index — identical to proxy capture and `ImportArchive`. + +### Capture rewrite rules are NOT applied + +HAR import writes directly to the traffic store without passing through the MITM capture proxy. **Capture rewrite rules are never applied to imported exchanges**, no `exchange_rewrites` rows are created, and imported rows always have `rewritten: false`. + +### Import limits + +| Limit | Default | Behavior when exceeded | +|---|---|---| +| Raw HTTP request body | 32 MiB | `413 Request Entity Too Large` | +| Entries per HAR | 2,000 | `400 Bad Request` | +| Total decoded request + response body bytes | 32 MiB | Stops importing remaining entries, sets `"truncated": true`, counts remaining entries in `skipped`, and appends an explanatory item in `errors`. | + +--- + +## Export: `GET /api/traffic/export/har` + +### Request & filters + +Returns an `application/json` HAR 1.2 document (`Content-Disposition: attachment; filename="artex-traffic.har"`) ordered deterministically by `(ts ASC, id ASC)`. + +It reuses the same filter parser and SQL predicate builder as `GET /api/traffic`, supporting: + +- `host`, `method`, `path`, `status`, `q`, `body`, `rewritten` (`all` | `rewritten` | `original` | `true` | `false`), `resp_min`, `resp_max`. + +### HAR 1.2 compliance & unknown placeholders + +- `log.version` is `"1.2"` and `log.creator` is `{"name": "ARTEX", "version": ""}`. +- `startedDateTime` is formatted from `exchanges.ts` as UTC RFC 3339, and `_artexExchangeId` carries the exchange's stored ID. +- Request and response headers are parsed from the stored raw heads (`req_head` / `resp_head`). ARTEX does not invent `serverIPAddress` or headers that are not present in the store. +- Required HAR 1.2 fields whose values are not recorded by ARTEX are emitted with explicit **unknown placeholders** rather than fabricated measurements: + - `entry.time`: `0` + - `entry.cache`: `{}` + - `entry.timings`: `{"send": -1, "wait": -1, "receive": -1}` (unknown/unavailable per HAR 1.2) + - `request.cookies`, `request.queryString`, `response.cookies`: `[]` + - `request.headersSize`, `response.headersSize`: `-1` (unknown per HAR 1.2) + - `response.redirectURL`: `""` +- Bodies are read in full from inline columns or spilled blobs: valid NUL-free UTF-8 bodies are emitted as plain `text`, and binary / non-UTF-8 bodies are emitted with `encoding: "base64"`. + +### Export limits, import-compatibility invariant, & truncation reporting + +| Limit | Default | `truncatedReason` | +|---|---|---| +| Exported entries | 1,000 | `max_entries` | +| Total raw request + response headers and bodies | 20 MiB | `max_bytes` | +| Marshaled JSON size backstop | 31 MiB | `max_bytes` | + +**Cap invariant**: Every HAR produced by `GET /api/traffic/export/har` fits inside `POST /api/traffic/import/har`'s **32 MiB** HTTP body limit (and the Traffic page's 32 MiB file limit). Raw headers and bodies are capped at **20 MiB** so worst-case base64 expansion (`4/3x ≈ 26.7 MiB`) plus JSON structure stays comfortably under 32 MiB, backed by an explicit **31 MiB** marshaled-JSON cap so even heavily JSON-escaped payloads cannot trigger a `413` on re-import. + +Truncation is never silent. Every export reports it in both HTTP response headers and HAR 1.2 custom (`_`-prefixed) `log` fields: + +- Headers: + - `X-ARTEX-HAR-Truncated: true|false` + - `X-ARTEX-HAR-Truncated-Reason: max_entries|max_bytes` (when truncated) + - `X-ARTEX-HAR-Exported: ` + - `X-ARTEX-HAR-Matched: ` +- JSON (`log` object, omitted when not truncated): + - `_truncated: true` + - `_truncatedReason: "max_entries" | "max_bytes"` + - `_totalMatched: ` diff --git a/server/server.go b/server/server.go index cdc23a07..09efe3ab 100644 --- a/server/server.go +++ b/server/server.go @@ -898,6 +898,8 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("GET /api/traffic/blob", s.getTrafficBlob) mux.HandleFunc("POST /api/traffic/ingest", s.ingestTraffic) mux.HandleFunc("POST /api/traffic/replay", s.replayTraffic) + mux.HandleFunc("POST /api/traffic/import/har", s.importTrafficHAR) + mux.HandleFunc("GET /api/traffic/export/har", s.exportTrafficHAR) mux.HandleFunc("GET /api/commands", s.pgListCommands) mux.HandleFunc("GET /api/commands/stats", s.pgToolStats) // aggregate call counts per tool mux.HandleFunc("GET /api/llm/records", s.pgListLLMRecords) @@ -3541,19 +3543,7 @@ func (s *Server) getTraffic(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() page := atoiDefault(q.Get("page"), 0) size := atoiDefault(q.Get("size"), 100) - ex, matched, _ := tr.Page(traffic.PageQuery{ - Host: q.Get("host"), - Method: q.Get("method"), - Query: q.Get("q"), - Body: q.Get("body"), - Path: q.Get("path"), - Status: q.Get("status"), - Rewritten: q.Get("rewritten"), - RespMin: int64(atoiDefault(q.Get("resp_min"), -1)), - RespMax: int64(atoiDefault(q.Get("resp_max"), -1)), - Sort: q.Get("sort"), - Order: q.Get("order"), - }, page, size) + ex, matched, _ := tr.Page(parseTrafficPageQuery(q), page, size) count, _ := tr.Count() // global total, for the stat card writeJSON(w, 200, map[string]any{ "enabled": s.m.TrafficEnabled(), // reflect the capture toggle diff --git a/server/traffic_har.go b/server/traffic_har.go new file mode 100644 index 00000000..c69eb8cc --- /dev/null +++ b/server/traffic_har.go @@ -0,0 +1,96 @@ +package server + +import ( + "encoding/json" + "errors" + "io" + "net/http" + "net/url" + "strconv" + + "github.com/Autumn-27/artex/traffic" +) + +func parseTrafficPageQuery(q url.Values) traffic.PageQuery { + return traffic.PageQuery{ + Host: q.Get("host"), + Method: q.Get("method"), + Query: q.Get("q"), + Body: q.Get("body"), + Path: q.Get("path"), + Status: q.Get("status"), + Rewritten: q.Get("rewritten"), + RespMin: int64(atoiDefault(q.Get("resp_min"), -1)), + RespMax: int64(atoiDefault(q.Get("resp_max"), -1)), + Sort: q.Get("sort"), + Order: q.Get("order"), + } +} + +// importTrafficHAR accepts a raw HAR 1.2 JSON document (capped at decodeMaxBytes, +// 32 MiB) and imports valid entries into the traffic store with deterministic +// IDs. Imported traffic never passes through capture rewrite rules. +func (s *Server) importTrafficHAR(w http.ResponseWriter, r *http.Request) { + tr := s.m.Traffic() + if tr == nil { + writeErr(w, http.StatusServiceUnavailable, "traffic store is not available") + return + } + body := r.Body + if _, already := body.(*limitedBody); !already { + body = http.MaxBytesReader(w, body, decodeMaxBytes) + } + raw, err := io.ReadAll(body) + if err != nil { + var tooLarge *http.MaxBytesError + if errors.As(err, &tooLarge) { + writeErr(w, http.StatusRequestEntityTooLarge, "HAR payload exceeds 32 MiB limit") + return + } + writeErr(w, http.StatusBadRequest, "failed to read HAR body: "+err.Error()) + return + } + res, err := tr.ImportHAR(raw, traffic.HARImportOptions{}) + if err != nil { + if errors.Is(err, traffic.ErrInvalidHAR) { + writeErr(w, http.StatusBadRequest, err.Error()) + return + } + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + writeJSON(w, http.StatusOK, res) +} + +// exportTrafficHAR exports recorded traffic matching the query filters as an +// application/json HAR 1.2 document in stable chronological order. Entry and +// total-byte caps are enforced and reported via both X-ARTEX-HAR-* headers and +// HAR 1.2 custom fields (_truncated, _truncatedReason, _totalMatched). +func (s *Server) exportTrafficHAR(w http.ResponseWriter, r *http.Request) { + tr := s.m.Traffic() + if tr == nil { + writeErr(w, http.StatusServiceUnavailable, "traffic store is not available") + return + } + pq := parseTrafficPageQuery(r.URL.Query()) + doc, meta, err := tr.ExportHAR(pq, traffic.HARExportOptions{CreatorVersion: BuildVersion}) + if err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + payload, err := json.Marshal(doc) + if err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Header().Set("Content-Disposition", `attachment; filename="artex-traffic.har"`) + w.Header().Set("X-ARTEX-HAR-Truncated", strconv.FormatBool(meta.Truncated)) + w.Header().Set("X-ARTEX-HAR-Exported", strconv.Itoa(meta.Exported)) + w.Header().Set("X-ARTEX-HAR-Matched", strconv.Itoa(meta.TotalMatched)) + if meta.Truncated { + w.Header().Set("X-ARTEX-HAR-Truncated-Reason", meta.TruncatedReason) + } + w.WriteHeader(http.StatusOK) + _, _ = w.Write(payload) +} diff --git a/server/traffic_har_test.go b/server/traffic_har_test.go new file mode 100644 index 00000000..1b49837a --- /dev/null +++ b/server/traffic_har_test.go @@ -0,0 +1,256 @@ +package server + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Autumn-27/artex/traffic" +) + +func TestTrafficHAREndpointsRoundTripFilterAndErrors(t *testing.T) { + s, request := ingestServer(t) + + binPayload := []byte{0x00, 0x01, 0x89, 0x50, 0xfe, 0xff} + harIn := traffic.HAR{ + Log: &traffic.HARLog{ + Version: "1.2", + Creator: traffic.HARCreator{Name: "TestSuite", Version: "1.0"}, + Entries: []traffic.HAREntry{ + { + StartedDateTime: "2026-06-01T08:00:00Z", + Request: traffic.HARRequest{ + Method: "POST", + URL: "https://har-a.example/api/login", + Headers: []traffic.HARHeader{{Name: "Content-Type", Value: "application/json"}}, + PostData: &traffic.HARPostData{ + MimeType: "application/json", + Text: `{"user":"alice"}`, + }, + }, + Response: traffic.HARResponse{ + Status: 200, + Headers: []traffic.HARHeader{{Name: "Content-Type", Value: "application/json"}}, + Content: traffic.HARContent{ + MimeType: "application/json", + Text: `{"ok":true}`, + }, + }, + }, + { + StartedDateTime: "2026-06-01T08:00:10Z", + Request: traffic.HARRequest{ + Method: "GET", + URL: "https://har-b.example/blob.bin", + Headers: []traffic.HARHeader{}, + }, + Response: traffic.HARResponse{ + Status: 200, + Headers: []traffic.HARHeader{{Name: "Content-Type", Value: "application/octet-stream"}}, + Content: traffic.HARContent{ + MimeType: "application/octet-stream", + Text: base64.StdEncoding.EncodeToString(binPayload), + Encoding: "base64", + }, + }, + }, + }, + }, + } + rawIn, err := json.Marshal(harIn) + if err != nil { + t.Fatal(err) + } + + // Import via HTTP endpoint. + w := request(http.MethodPost, "/api/traffic/import/har", string(rawIn)) + if w.Code != http.StatusOK { + t.Fatalf("POST /api/traffic/import/har status=%d body=%s", w.Code, w.Body.String()) + } + var importRes traffic.HARImportResult + if err := json.Unmarshal(w.Body.Bytes(), &importRes); err != nil { + t.Fatal(err) + } + if importRes.Imported != 2 || importRes.Skipped != 0 || importRes.Failed != 0 { + t.Fatalf("importRes = %+v, want 2/0/0", importRes) + } + + // Re-import is idempotent. + w2 := request(http.MethodPost, "/api/traffic/import/har", string(rawIn)) + if w2.Code != http.StatusOK { + t.Fatalf("re-import status=%d body=%s", w2.Code, w2.Body.String()) + } + var importRes2 traffic.HARImportResult + if err := json.Unmarshal(w2.Body.Bytes(), &importRes2); err != nil { + t.Fatal(err) + } + if importRes2.Imported != 0 || importRes2.Skipped != 2 || importRes2.Failed != 0 { + t.Fatalf("re-import res = %+v, want 0/2/0", importRes2) + } + + // Imported rows are listed on GET /api/traffic with rewritten=false and zero exchange_rewrites rows. + wList := request(http.MethodGet, "/api/traffic?host=har-", "") + if wList.Code != http.StatusOK { + t.Fatalf("GET /api/traffic status=%d body=%s", wList.Code, wList.Body.String()) + } + var listResp struct { + Total int `json:"total"` + Exchanges []TrafficExchangeDTO `json:"exchanges"` + } + if err := json.Unmarshal(wList.Body.Bytes(), &listResp); err != nil { + t.Fatal(err) + } + if listResp.Total != 2 || len(listResp.Exchanges) != 2 { + t.Fatalf("listResp = %+v, want 2 exchanges", listResp) + } + for _, row := range listResp.Exchanges { + if row.Rewritten { + t.Fatalf("imported row %s marked rewritten", row.ID) + } + } + var rwCount int + if err := s.m.Traffic().DB().QueryRow(`SELECT COUNT(*) FROM exchange_rewrites`).Scan(&rwCount); err != nil || rwCount != 0 { + t.Fatalf("exchange_rewrites count after HTTP HAR import = %d err=%v, want 0", rwCount, err) + } + + // Filtered export by host returns only har-b.example with binary payload preserved as base64. + wExp := request(http.MethodGet, "/api/traffic/export/har?host=har-b.example", "") + if wExp.Code != http.StatusOK { + t.Fatalf("GET /api/traffic/export/har status=%d body=%s", wExp.Code, wExp.Body.String()) + } + if ct := wExp.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/json") { + t.Fatalf("export Content-Type = %q, want application/json", ct) + } + if wExp.Header().Get("X-ARTEX-HAR-Truncated") != "false" || wExp.Header().Get("X-ARTEX-HAR-Exported") != "1" || wExp.Header().Get("X-ARTEX-HAR-Matched") != "1" { + t.Fatalf("unexpected export headers: %+v", wExp.Header()) + } + var exported traffic.HAR + if err := json.Unmarshal(wExp.Body.Bytes(), &exported); err != nil { + t.Fatal(err) + } + if exported.Log == nil || exported.Log.Version != "1.2" || len(exported.Log.Entries) != 1 { + t.Fatalf("filtered export = %+v", exported.Log) + } + entry := exported.Log.Entries[0] + if entry.Request.URL != "https://har-b.example/blob.bin" || entry.Response.Content.Encoding != "base64" { + t.Fatalf("exported binary entry = %+v", entry) + } + decoded, err := base64.StdEncoding.DecodeString(entry.Response.Content.Text) + if err != nil || !bytes.Equal(decoded, binPayload) { + t.Fatalf("exported binary bytes mismatch: got=%x err=%v", decoded, err) + } + + // Re-importing the exported HAR via HTTP is idempotent. + wReimp := request(http.MethodPost, "/api/traffic/import/har", wExp.Body.String()) + if wReimp.Code != http.StatusOK || !strings.Contains(wReimp.Body.String(), `"imported":0`) || !strings.Contains(wReimp.Body.String(), `"skipped":1`) { + t.Fatalf("re-import exported HAR status=%d body=%s", wReimp.Code, wReimp.Body.String()) + } + + // Error cases -> 400 naming the reason. + for _, tc := range []struct { + name string + body string + want string + }{ + {"malformed", `{"log":`, "malformed JSON"}, + {"missing entries", `{"log":{"version":"1.2"}}`, "missing log.entries"}, + {"unsupported version", `{"log":{"version":"2.0","entries":[]}}`, "unsupported HAR version"}, + } { + wErr := request(http.MethodPost, "/api/traffic/import/har", tc.body) + if wErr.Code != http.StatusBadRequest || !strings.Contains(wErr.Body.String(), tc.want) { + t.Fatalf("%s: status=%d body=%s, want 400 containing %q", tc.name, wErr.Code, wErr.Body.String(), tc.want) + } + } + + // Traffic store unavailable -> 503 on both import and export. + sOff := &Server{m: &Manager{}} + wOffImp := httptest.NewRecorder() + sOff.importTrafficHAR(wOffImp, httptest.NewRequest(http.MethodPost, "/api/traffic/import/har", strings.NewReader(`{}`))) + if wOffImp.Code != http.StatusServiceUnavailable { + t.Fatalf("import with traffic off status=%d, want 503", wOffImp.Code) + } + wOffExp := httptest.NewRecorder() + sOff.exportTrafficHAR(wOffExp, httptest.NewRequest(http.MethodGet, "/api/traffic/export/har", nil)) + if wOffExp.Code != http.StatusServiceUnavailable { + t.Fatalf("export with traffic off status=%d, want 503", wOffExp.Code) + } +} + +func TestTrafficHAREndpointsRequireAuth(t *testing.T) { + s, _ := ingestServer(t) + + rImp := httptest.NewRequest(http.MethodPost, "/api/traffic/import/har", strings.NewReader(`{"log":{"version":"1.2","entries":[]}}`)) + wImp := httptest.NewRecorder() + s.Handler().ServeHTTP(wImp, rImp) + if wImp.Code != http.StatusUnauthorized { + t.Fatalf("unauthenticated HAR import status=%d, want 401", wImp.Code) + } + + rExp := httptest.NewRequest(http.MethodGet, "/api/traffic/export/har", nil) + wExp := httptest.NewRecorder() + s.Handler().ServeHTTP(wExp, rExp) + if wExp.Code != http.StatusUnauthorized { + t.Fatalf("unauthenticated HAR export status=%d, want 401", wExp.Code) + } +} + +func TestTrafficHARExportNearCapReimportsThroughHTTPHandler(t *testing.T) { + s, request := ingestServer(t) + tr := s.m.Traffic() + + // Seed a binary exchange near the 20 MiB export raw cap (~19.5 MiB). + const bodySize = 19*1024*1024 + 512*1024 + binBody := make([]byte, bodySize) + for i := range binBody { + binBody[i] = byte((i*17 + 0x81) & 0xff) + } + binBody[0] = 0x00 + + rawSeed, err := json.Marshal(traffic.HAR{ + Log: &traffic.HARLog{ + Version: "1.2", + Entries: []traffic.HAREntry{{ + StartedDateTime: "2026-06-02T00:00:00Z", + Request: traffic.HARRequest{Method: "GET", URL: "https://nearcap.example/bin", Headers: []traffic.HARHeader{}}, + Response: traffic.HARResponse{ + Status: 200, + Headers: []traffic.HARHeader{{Name: "Content-Type", Value: "application/octet-stream"}}, + Content: traffic.HARContent{ + Size: len(binBody), + MimeType: "application/octet-stream", + Text: base64.StdEncoding.EncodeToString(binBody), + Encoding: "base64", + }, + }, + }}, + }, + }) + if err != nil { + t.Fatal(err) + } + if _, err := tr.ImportHAR(rawSeed, traffic.HARImportOptions{}); err != nil { + t.Fatal(err) + } + + wExp := request(http.MethodGet, "/api/traffic/export/har?host=nearcap.example", "") + if wExp.Code != http.StatusOK { + t.Fatalf("export status=%d", wExp.Code) + } + if wExp.Header().Get("X-ARTEX-HAR-Truncated") != "false" { + t.Fatalf("expected non-truncated export, headers=%+v", wExp.Header()) + } + if wExp.Body.Len() >= decodeMaxBytes { + t.Fatalf("exported HAR size=%d exceeds decodeMaxBytes=%d", wExp.Body.Len(), decodeMaxBytes) + } + + // Re-import the exact exported bytes through the HTTP handler (including + // limitRequestBody 32 MiB middleware) — must answer 200, never 413. + wImp := request(http.MethodPost, "/api/traffic/import/har", wExp.Body.String()) + if wImp.Code != http.StatusOK { + t.Fatalf("re-import near-cap export via HTTP status=%d body=%s, want 200", wImp.Code, wImp.Body.String()) + } +} diff --git a/traffic/har.go b/traffic/har.go new file mode 100644 index 00000000..98681b08 --- /dev/null +++ b/traffic/har.go @@ -0,0 +1,966 @@ +package traffic + +import ( + "bytes" + "crypto/sha256" + "database/sql" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/url" + "os" + "path/filepath" + "strings" + "time" + "unicode/utf8" + + "github.com/Autumn-27/artex/db" +) + +const ( + // HARVersion is the HAR specification version produced and accepted. + HARVersion = "1.2" + + // DefaultHARMaxImportEntries caps how many entries a single HAR import accepts. + DefaultHARMaxImportEntries = 2000 + // DefaultHARMaxImportBytes caps total decoded request+response body bytes + // imported in a single HAR document. + DefaultHARMaxImportBytes int64 = 32 << 20 + + // DefaultHARMaxExportEntries caps how many exchanges a single HAR export emits. + DefaultHARMaxExportEntries = 1000 + // DefaultHARMaxExportBytes caps total raw header + body bytes emitted in a + // single HAR export. At 20 MiB raw, even pure binary payloads expand via + // base64 (4/3x ≈ 26.7 MiB) plus HAR JSON overhead safely below the 32 MiB + // HTTP import limit. + DefaultHARMaxExportBytes int64 = 20 << 20 + // DefaultHARMaxExportJSONBytes backstops the marshaled JSON size of an export + // (31 MiB, leaving 1 MiB margin below the 32 MiB import HTTP body cap) so + // even pathological JSON-escaped control-character payloads cannot exceed + // the import limit. + DefaultHARMaxExportJSONBytes int64 = 31 << 20 + + maxHARImportErrors = 50 + maxArtexIDLen = 128 +) + +// ErrInvalidHAR marks a malformed or unsupported HAR document (mapped to HTTP 400). +var ErrInvalidHAR = errors.New("invalid HAR") + +// HAR is a HAR 1.2 envelope. Required HAR 1.2 fields that the traffic store +// does not record use explicit unknown placeholders (time: 0, cache: {}, +// timings: {send:-1, wait:-1, receive:-1}, cookies: [], queryString: [], +// headersSize: -1, redirectURL: "") rather than fabricated measurements. +type HAR struct { + Log *HARLog `json:"log"` +} + +type HARLog struct { + Version string `json:"version"` + Creator HARCreator `json:"creator"` + Entries []HAREntry `json:"entries"` + Truncated bool `json:"_truncated,omitempty"` + TruncatedReason string `json:"_truncatedReason,omitempty"` + TotalMatched int `json:"_totalMatched,omitempty"` +} + +type HARCreator struct { + Name string `json:"name"` + Version string `json:"version"` +} + +type HARCache struct{} + +type HARTimings struct { + Send float64 `json:"send"` + Wait float64 `json:"wait"` + Receive float64 `json:"receive"` +} + +type HAREntry struct { + StartedDateTime string `json:"startedDateTime"` + Time float64 `json:"time"` + Request HARRequest `json:"request"` + Response HARResponse `json:"response"` + Cache HARCache `json:"cache"` + Timings HARTimings `json:"timings"` + ArtexExchangeID string `json:"_artexExchangeId,omitempty"` +} + +type HARRequest struct { + Method string `json:"method"` + URL string `json:"url"` + HTTPVersion string `json:"httpVersion"` + Cookies []HARCookie `json:"cookies"` + Headers []HARHeader `json:"headers"` + QueryString []HARParam `json:"queryString"` + PostData *HARPostData `json:"postData,omitempty"` + HeadersSize int `json:"headersSize"` + BodySize int `json:"bodySize"` +} + +type HARPostData struct { + MimeType string `json:"mimeType,omitempty"` + Params []HARParam `json:"params,omitempty"` + Text string `json:"text,omitempty"` + Encoding string `json:"encoding,omitempty"` +} + +type HARParam struct { + Name string `json:"name"` + Value string `json:"value"` + FileName string `json:"fileName,omitempty"` + ContentType string `json:"contentType,omitempty"` +} + +type HARCookie struct { + Name string `json:"name"` + Value string `json:"value"` + Path string `json:"path,omitempty"` + Domain string `json:"domain,omitempty"` + Expires string `json:"expires,omitempty"` + HTTPOnly bool `json:"httpOnly,omitempty"` + Secure bool `json:"secure,omitempty"` +} + +type HARResponse struct { + Status int `json:"status"` + StatusText string `json:"statusText"` + HTTPVersion string `json:"httpVersion"` + Cookies []HARCookie `json:"cookies"` + Headers []HARHeader `json:"headers"` + Content HARContent `json:"content"` + RedirectURL string `json:"redirectURL"` + HeadersSize int `json:"headersSize"` + BodySize int `json:"bodySize"` +} + +type HARContent struct { + Size int `json:"size"` + MimeType string `json:"mimeType"` + Text string `json:"text,omitempty"` + Encoding string `json:"encoding,omitempty"` +} + +type HARHeader struct { + Name string `json:"name"` + Value string `json:"value"` +} + +// HARImportOptions configures safety caps for ImportHAR. Zero values use the +// package defaults. +type HARImportOptions struct { + MaxEntries int + MaxTotalBytes int64 +} + +// HARImportError describes one entry that could not be imported. +type HARImportError struct { + Index int `json:"index"` + URL string `json:"url,omitempty"` + Reason string `json:"reason"` +} + +// HARImportResult summarizes one ImportHAR run. +type HARImportResult struct { + Imported int `json:"imported"` + Skipped int `json:"skipped"` + Failed int `json:"failed"` + Truncated bool `json:"truncated,omitempty"` + Errors []HARImportError `json:"errors,omitempty"` +} + +// HARExportOptions configures ExportHAR. Zero caps use package defaults. +type HARExportOptions struct { + CreatorVersion string + MaxEntries int + MaxTotalBytes int64 // raw header + body bytes cap + MaxJSONBytes int64 // marshaled JSON cap (defaults to DefaultHARMaxExportJSONBytes) +} + +// HARExportMeta reports export counts and whether a cap stopped the export. +type HARExportMeta struct { + Exported int + TotalMatched int + TotalBytes int64 // total raw header + body bytes exported + Truncated bool + TruncatedReason string // "" | "max_entries" | "max_bytes" +} + +// ImportHAR parses a HAR 1.2 JSON document and inserts valid entries into the +// traffic store. ARTEX-exported entries carrying a valid _artexExchangeId +// preserve that ID so distinct exchanges within the same second round-trip +// cleanly; external HAR entries receive a deterministic content-based har- ID +// so re-importing the same HAR is idempotent and skips existing rows. URL +// userinfo is stripped before storing, indexing, or reporting errors. Imported +// traffic never passes through capture rewrite rules and never gains +// exchange_rewrites rows. +func (t *Traffic) ImportHAR(raw []byte, opts HARImportOptions) (HARImportResult, error) { + if t == nil { + return HARImportResult{}, errors.New("traffic store is not available") + } + if opts.MaxEntries <= 0 { + opts.MaxEntries = DefaultHARMaxImportEntries + } + if opts.MaxTotalBytes <= 0 { + opts.MaxTotalBytes = DefaultHARMaxImportBytes + } + + doc, err := decodeHARDocument(raw) + if err != nil { + return HARImportResult{}, err + } + if len(doc.Log.Entries) > opts.MaxEntries { + return HARImportResult{}, fmt.Errorf("%w: HAR contains %d entries, exceeding limit of %d", ErrInvalidHAR, len(doc.Log.Entries), opts.MaxEntries) + } + + var res HARImportResult + addErr := func(idx int, rawURL, reason string) { + if len(res.Errors) < maxHARImportErrors { + res.Errors = append(res.Errors, HARImportError{ + Index: idx, + URL: redactURLUserinfo(rawURL), + Reason: reason, + }) + } + } + + var totalBytes int64 + for i, entry := range doc.Log.Entries { + parsed, err := parseHAREntry(entry) + if err != nil { + res.Failed++ + addErr(i, entry.Request.URL, err.Error()) + continue + } + entryBytes := int64(len(parsed.reqBody) + len(parsed.respBody)) + if totalBytes+entryBytes > opts.MaxTotalBytes { + remaining := len(doc.Log.Entries) - i + res.Truncated = true + res.Skipped += remaining + addErr(i, entry.Request.URL, fmt.Sprintf("decoded body byte cap (%d bytes) reached; %d remaining entries skipped", opts.MaxTotalBytes, remaining)) + break + } + + inserted, err := t.insertHARExchange(parsed) + if err != nil { + res.Failed++ + addErr(i, entry.Request.URL, err.Error()) + continue + } + if !inserted { + res.Skipped++ + continue + } + totalBytes += entryBytes + res.Imported++ + } + return res, nil +} + +func decodeHARDocument(raw []byte) (HAR, error) { + if len(bytes.TrimSpace(raw)) == 0 { + return HAR{}, fmt.Errorf("%w: empty HAR document", ErrInvalidHAR) + } + dec := json.NewDecoder(bytes.NewReader(raw)) + var doc HAR + if err := dec.Decode(&doc); err != nil { + return HAR{}, fmt.Errorf("%w: malformed JSON: %v", ErrInvalidHAR, err) + } + // Reject trailing non-whitespace tokens after the root object. + if err := dec.Decode(&struct{}{}); err != io.EOF { + return HAR{}, fmt.Errorf("%w: malformed JSON: trailing content after HAR object", ErrInvalidHAR) + } + if doc.Log == nil { + return HAR{}, fmt.Errorf("%w: missing log object", ErrInvalidHAR) + } + if strings.TrimSpace(doc.Log.Version) != HARVersion { + return HAR{}, fmt.Errorf("%w: unsupported HAR version %q (expected %s)", ErrInvalidHAR, doc.Log.Version, HARVersion) + } + if doc.Log.Entries == nil { + return HAR{}, fmt.Errorf("%w: missing log.entries", ErrInvalidHAR) + } + return doc, nil +} + +type parsedHARExchange struct { + id string + ts int64 + host string + method string + urlTemplate string + rawURL string + status int + reqCT string + respCT string + reqHead string + reqBody []byte + respHead string + respBody []byte +} + +func parseHAREntry(entry HAREntry) (parsedHARExchange, error) { + tsStr := strings.TrimSpace(entry.StartedDateTime) + if tsStr == "" { + return parsedHARExchange{}, errors.New("missing startedDateTime") + } + parsedTS, err := time.Parse(time.RFC3339Nano, tsStr) + if err != nil { + return parsedHARExchange{}, fmt.Errorf("invalid startedDateTime %q", entry.StartedDateTime) + } + ts := parsedTS.UTC().Unix() + + rawURL := strings.TrimSpace(entry.Request.URL) + u, err := url.Parse(rawURL) + if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") { + return parsedHARExchange{}, fmt.Errorf("invalid request url %q", redactURLUserinfo(entry.Request.URL)) + } + // Strip URL userinfo (user:pass@) before storing, indexing, or exporting, + // matching the asset store. + u.User = nil + + method := strings.ToUpper(strings.TrimSpace(entry.Request.Method)) + if method == "" || !validHeaderName(method) { + return parsedHARExchange{}, fmt.Errorf("invalid request method %q", entry.Request.Method) + } + if entry.Response.Status < 0 || entry.Response.Status > 999 { + return parsedHARExchange{}, fmt.Errorf("invalid response status %d", entry.Response.Status) + } + + reqHeaderText, reqCT, hasReqCookie, err := formatHARHeaders(entry.Request.Headers, "Cookie") + if err != nil { + return parsedHARExchange{}, fmt.Errorf("invalid request headers: %w", err) + } + if !hasReqCookie && len(entry.Request.Cookies) > 0 { + cookieHeader, err := formatHARRequestCookies(entry.Request.Cookies) + if err != nil { + return parsedHARExchange{}, fmt.Errorf("invalid request cookies: %w", err) + } + reqHeaderText += cookieHeader + } + + respHeaderText, respHeaderCT, hasRespSetCookie, err := formatHARHeaders(entry.Response.Headers, "Set-Cookie") + if err != nil { + return parsedHARExchange{}, fmt.Errorf("invalid response headers: %w", err) + } + if !hasRespSetCookie && len(entry.Response.Cookies) > 0 { + setCookies, err := formatHARResponseCookies(entry.Response.Cookies) + if err != nil { + return parsedHARExchange{}, fmt.Errorf("invalid response cookies: %w", err) + } + respHeaderText += setCookies + } + + var reqBody []byte + if entry.Request.PostData != nil { + if entry.Request.PostData.Text != "" || len(entry.Request.PostData.Params) == 0 { + reqBody, err = decodeHARBody(entry.Request.PostData.Text, entry.Request.PostData.Encoding) + if err != nil { + return parsedHARExchange{}, fmt.Errorf("invalid request postData: %w", err) + } + if reqCT == "" { + reqCT = strings.TrimSpace(entry.Request.PostData.MimeType) + } + } else { + reqBody = encodeHARFormParams(entry.Request.PostData.Params) + if reqCT == "" { + reqCT = strings.TrimSpace(entry.Request.PostData.MimeType) + if reqCT == "" { + reqCT = "application/x-www-form-urlencoded" + } + } + } + } + respBody, err := decodeHARBody(entry.Response.Content.Text, entry.Response.Content.Encoding) + if err != nil { + return parsedHARExchange{}, fmt.Errorf("invalid response content: %w", err) + } + + respCT := strings.TrimSpace(entry.Response.Content.MimeType) + if respCT == "" { + respCT = respHeaderCT + } + + reqProto := sanitizeHARProto(entry.Request.HTTPVersion) + respProto := sanitizeHARProto(entry.Response.HTTPVersion) + reqHead := fmt.Sprintf("%s %s %s\n%s", method, u.RequestURI(), reqProto, reqHeaderText) + + statusText := strings.TrimSpace(entry.Response.StatusText) + if strings.ContainsAny(statusText, "\r\n\x00") { + return parsedHARExchange{}, errors.New("response statusText contains control characters") + } + respHead := fmt.Sprintf("%s %d\n%s", respProto, entry.Response.Status, respHeaderText) + if statusText != "" { + respHead = fmt.Sprintf("%s %d %s\n%s", respProto, entry.Response.Status, statusText, respHeaderText) + } + + canonicalURL := u.String() + id := harExchangeID(ts, method, canonicalURL, entry.Response.Status, reqBody, respBody) + if preserved := strings.TrimSpace(entry.ArtexExchangeID); validArtexExchangeID(preserved) { + id = preserved + } + return parsedHARExchange{ + id: id, + ts: ts, + host: u.Hostname(), + method: method, + urlTemplate: db.TemplatePath(u.EscapedPath()), + rawURL: canonicalURL, + status: entry.Response.Status, + reqCT: reqCT, + respCT: respCT, + reqHead: reqHead, + reqBody: reqBody, + respHead: respHead, + respBody: respBody, + }, nil +} + +// harExchangeID derives a deterministic ID from the exchange's timestamp (Unix +// seconds), method, canonical URL, status code, and SHA-256 digests of both +// bodies. Using Unix seconds matches exchanges.ts so export -> re-import +// produces the exact same ID for external HARs. +func harExchangeID(ts int64, method, rawURL string, status int, reqBody, respBody []byte) string { + reqSum := sha256.Sum256(reqBody) + respSum := sha256.Sum256(respBody) + h := sha256.New() + fmt.Fprintf(h, "%d\x00%s\x00%s\x00%d\x00%x\x00%x", ts, method, rawURL, status, reqSum, respSum) + return "har-" + hex.EncodeToString(h.Sum(nil)) +} + +func validArtexExchangeID(id string) bool { + if id == "" || len(id) > maxArtexIDLen { + return false + } + for i := 0; i < len(id); i++ { + c := id[i] + if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || + c == '-' || c == '_' || c == '.' || c == ':' { + continue + } + return false + } + return true +} + +// redactURLUserinfo strips user:pass@ from both parseable and malformed URLs so +// credentials never leak into stored URLs or import error details. +func redactURLUserinfo(raw string) string { + s := strings.TrimSpace(raw) + if s == "" { + return "" + } + if u, err := url.Parse(s); err == nil && u.User != nil { + u.User = nil + return u.String() + } + schemeEnd := strings.Index(s, "://") + if schemeEnd < 0 { + return s + } + rest := s[schemeEnd+3:] + authEnd := strings.IndexAny(rest, "/?#") + auth := rest + tail := "" + if authEnd >= 0 { + auth = rest[:authEnd] + tail = rest[authEnd:] + } + if at := strings.LastIndexByte(auth, '@'); at >= 0 { + return s[:schemeEnd+3] + auth[at+1:] + tail + } + return s +} + +func formatHARHeaders(headers []HARHeader, checkHeader string) (formatted string, contentType string, hasChecked bool, err error) { + var b strings.Builder + for _, h := range headers { + name := strings.TrimSpace(h.Name) + if name == "" { + return "", "", false, errors.New("empty header name") + } + // Skip HTTP/2 pseudo-headers (:method, :authority, :scheme, :path, :status) + // emitted by browser DevTools HAR exports; their semantics live in the + // request/status line. + if strings.HasPrefix(name, ":") { + continue + } + if !validHeaderName(name) { + return "", "", false, fmt.Errorf("invalid header name %q", h.Name) + } + if strings.ContainsAny(h.Value, "\r\n\x00") { + return "", "", false, fmt.Errorf("header %s contains a line break or NUL byte", name) + } + if contentType == "" && strings.EqualFold(name, "Content-Type") { + contentType = strings.TrimSpace(h.Value) + } + if checkHeader != "" && strings.EqualFold(name, checkHeader) { + hasChecked = true + } + b.WriteString(name) + b.WriteString(": ") + b.WriteString(h.Value) + b.WriteByte('\n') + } + return b.String(), contentType, hasChecked, nil +} + +func formatHARRequestCookies(cookies []HARCookie) (string, error) { + parts := make([]string, 0, len(cookies)) + for _, c := range cookies { + name := strings.TrimSpace(c.Name) + if name == "" { + return "", errors.New("empty cookie name") + } + if strings.ContainsAny(name, " \t;=\r\n\x00") || strings.ContainsAny(c.Value, "\r\n\x00") { + return "", fmt.Errorf("invalid cookie %q", name) + } + parts = append(parts, name+"="+c.Value) + } + if len(parts) == 0 { + return "", nil + } + return "Cookie: " + strings.Join(parts, "; ") + "\n", nil +} + +func formatHARResponseCookies(cookies []HARCookie) (string, error) { + var b strings.Builder + for _, c := range cookies { + name := strings.TrimSpace(c.Name) + if name == "" { + return "", errors.New("empty cookie name") + } + if strings.ContainsAny(name, " \t;=\r\n\x00") || + strings.ContainsAny(c.Value, "\r\n\x00") || + strings.ContainsAny(c.Path, ";\r\n\x00") || + strings.ContainsAny(c.Domain, ";\r\n\x00") || + strings.ContainsAny(c.Expires, ";\r\n\x00") { + return "", fmt.Errorf("invalid response cookie %q", name) + } + b.WriteString("Set-Cookie: ") + b.WriteString(name) + b.WriteByte('=') + b.WriteString(c.Value) + if c.Path != "" { + b.WriteString("; Path=") + b.WriteString(c.Path) + } + if c.Domain != "" { + b.WriteString("; Domain=") + b.WriteString(c.Domain) + } + if c.Expires != "" { + b.WriteString("; Expires=") + b.WriteString(c.Expires) + } + if c.Secure { + b.WriteString("; Secure") + } + if c.HTTPOnly { + b.WriteString("; HttpOnly") + } + b.WriteByte('\n') + } + return b.String(), nil +} + +func encodeHARFormParams(params []HARParam) []byte { + parts := make([]string, 0, len(params)) + for _, p := range params { + parts = append(parts, url.QueryEscape(p.Name)+"="+url.QueryEscape(p.Value)) + } + return []byte(strings.Join(parts, "&")) +} + +func decodeHARBody(text, encoding string) ([]byte, error) { + enc := strings.ToLower(strings.TrimSpace(encoding)) + switch enc { + case "": + if text == "" { + return nil, nil + } + return []byte(text), nil + case "base64": + if text == "" { + return nil, nil + } + decoded, err := base64.StdEncoding.DecodeString(text) + if err != nil { + return nil, fmt.Errorf("invalid base64 body: %w", err) + } + return decoded, nil + default: + return nil, fmt.Errorf("unsupported body encoding %q", encoding) + } +} + +func sanitizeHARProto(v string) string { + v = strings.TrimSpace(v) + if v == "" || strings.ContainsAny(v, " \t\r\n\x00") || !strings.HasPrefix(strings.ToUpper(v), "HTTP/") { + return "HTTP/1.1" + } + return v +} + +// insertHARExchange inserts one HAR exchange idempotently (INSERT OR IGNORE) +// through the same spill/blob_refs/FTS path as the recorder and ImportArchive. +// It never writes to exchange_rewrites. +func (t *Traffic) insertHARExchange(ex parsedHARExchange) (bool, error) { + t.wmu.Lock() + defer t.wmu.Unlock() + + var exists int + if err := t.db.QueryRow(`SELECT 1 FROM exchanges WHERE id=?`, ex.id).Scan(&exists); err == nil { + return false, nil + } else if !errors.Is(err, sql.ErrNoRows) { + return false, err + } + + reqB := t.spill(ex.reqBody, ex.reqCT) + respB := t.spill(ex.respBody, ex.respCT) + + tx, err := t.db.Begin() + if err != nil { + return false, fmt.Errorf("beginning transaction: %w", err) + } + defer tx.Rollback() //nolint:errcheck + + res, err := tx.Exec(`INSERT OR IGNORE INTO exchanges(id,ts,host,method,url_template,url,status,content_type,req_len,resp_len,path) +VALUES(?,?,?,?,?,?,?,?,?,?,'')`, + ex.id, ex.ts, ex.host, ex.method, ex.urlTemplate, ex.rawURL, ex.status, ex.respCT, len(ex.reqBody), len(ex.respBody)) + if err != nil { + return false, fmt.Errorf("writing index: %w", err) + } + n, _ := res.RowsAffected() + if n == 0 { + return false, nil + } + var rowid int64 + if err := tx.QueryRow(`SELECT rowid FROM exchanges WHERE id=?`, ex.id).Scan(&rowid); err != nil { + return false, fmt.Errorf("fetching rowid: %w", err) + } + if _, err := tx.Exec(`INSERT INTO exchange_bodies(id,req_head,req_body,req_blob,resp_head,resp_body,resp_blob) +VALUES(?,?,?,?,?,?,?)`, + ex.id, ex.reqHead, reqB.inline, nullIfEmpty(reqB.hash), ex.respHead, respB.inline, nullIfEmpty(respB.hash)); err != nil { + return false, fmt.Errorf("writing body: %w", err) + } + for _, h := range []string{reqB.hash, respB.hash} { + if h == "" { + continue + } + if _, err := tx.Exec(`INSERT OR IGNORE INTO blob_refs(hash,exchange_id) VALUES(?,?)`, h, ex.id); err != nil { + return false, fmt.Errorf("registering blob reference: %w", err) + } + } + if t.fts { + idx := strings.Join([]string{ex.rawURL, ex.reqHead, reqB.index, ex.respHead, respB.index}, "\n") + if _, err := tx.Exec(`INSERT INTO ex_fts(rowid,content) VALUES(?,?)`, rowid, idx); err != nil { + return false, fmt.Errorf("writing full-text index: %w", err) + } + } + if err := tx.Commit(); err != nil { + return false, fmt.Errorf("committing: %w", err) + } + return true, nil +} + +// ExportHAR exports exchanges matching f as a valid HAR 1.2 document in stable +// chronological order (ts ASC, id ASC), capped by opts.MaxEntries, +// opts.MaxTotalBytes (raw headers + bodies), and opts.MaxJSONBytes (marshaled +// JSON size). Truncation is reported in both HARExportMeta and the HAR 1.2 +// custom fields _truncated / _truncatedReason / _totalMatched. +func (t *Traffic) ExportHAR(f PageQuery, opts HARExportOptions) (HAR, HARExportMeta, error) { + if t == nil { + return HAR{}, HARExportMeta{}, errors.New("traffic store is not available") + } + if opts.MaxEntries <= 0 { + opts.MaxEntries = DefaultHARMaxExportEntries + } + if opts.MaxTotalBytes <= 0 { + opts.MaxTotalBytes = DefaultHARMaxExportBytes + } + if opts.MaxJSONBytes <= 0 { + opts.MaxJSONBytes = DefaultHARMaxExportJSONBytes + } + creatorVer := strings.TrimSpace(opts.CreatorVersion) + if creatorVer == "" { + creatorVer = "dev" + } + + where, args := t.pageWhere(f) + var totalMatched int + if err := t.db.QueryRow(`SELECT COUNT(*) FROM exchanges`+where, args...).Scan(&totalMatched); err != nil { + return HAR{}, HARExportMeta{}, err + } + + type exRow struct { + id string + ts int64 + host string + method string + rawURL string + status int + contentType string + legacyPath string + } + + // Fetch at most MaxEntries+1 rows so we know whether the entry cap fired. + sel := `SELECT id,ts,host,method,url,status,content_type,path FROM exchanges` + + where + ` ORDER BY ts ASC, id ASC LIMIT ?` + qargs := append(append([]any{}, args...), opts.MaxEntries+1) + rows, err := t.db.Query(sel, qargs...) + if err != nil { + return HAR{}, HARExportMeta{}, err + } + var matched []exRow + for rows.Next() { + var r exRow + if err := rows.Scan(&r.id, &r.ts, &r.host, &r.method, &r.rawURL, &r.status, &r.contentType, &r.legacyPath); err != nil { + rows.Close() + return HAR{}, HARExportMeta{}, err + } + matched = append(matched, r) + } + if err := rows.Err(); err != nil { + rows.Close() + return HAR{}, HARExportMeta{}, err + } + rows.Close() + + meta := HARExportMeta{TotalMatched: totalMatched} + hitEntryCap := len(matched) > opts.MaxEntries + if hitEntryCap { + matched = matched[:opts.MaxEntries] + } + + // Reserve envelope overhead (~512 bytes) for the outer log object + metadata. + const harEnvelopeMargin int64 = 512 + var encodedJSONBytes int64 = harEnvelopeMargin + + entries := make([]HAREntry, 0, len(matched)) + for _, r := range matched { + reqHead, reqBytes, respHead, respBytes, err := t.loadFullExchange(r.id, r.legacyPath) + if err != nil { + return HAR{}, HARExportMeta{}, err + } + entryRawBytes := int64(len(reqHead) + len(reqBytes) + len(respHead) + len(respBytes)) + if meta.TotalBytes+entryRawBytes > opts.MaxTotalBytes { + meta.Truncated = true + meta.TruncatedReason = "max_bytes" + break + } + + reqProto, reqHeaders := parseStoredRequestHead(reqHead) + respProto, respStatusText, respHeaders := parseStoredResponseHead(respHead) + + harReq := HARRequest{ + Method: r.method, + URL: redactURLUserinfo(r.rawURL), + HTTPVersion: reqProto, + Cookies: []HARCookie{}, + Headers: reqHeaders, + QueryString: []HARParam{}, + HeadersSize: -1, + BodySize: len(reqBytes), + } + if len(reqBytes) > 0 { + text, enc := encodeHARBody(reqBytes) + harReq.PostData = &HARPostData{ + MimeType: findHeaderValue(reqHeaders, "Content-Type"), + Text: text, + Encoding: enc, + } + } + + harContent := HARContent{ + Size: len(respBytes), + MimeType: r.contentType, + } + if len(respBytes) > 0 { + harContent.Text, harContent.Encoding = encodeHARBody(respBytes) + } + + harResp := HARResponse{ + Status: r.status, + StatusText: respStatusText, + HTTPVersion: respProto, + Cookies: []HARCookie{}, + Headers: respHeaders, + Content: harContent, + RedirectURL: "", + HeadersSize: -1, + BodySize: len(respBytes), + } + + entry := HAREntry{ + StartedDateTime: time.Unix(r.ts, 0).UTC().Format(time.RFC3339), + Time: 0, + Request: harReq, + Response: harResp, + Cache: HARCache{}, + Timings: HARTimings{Send: -1, Wait: -1, Receive: -1}, + ArtexExchangeID: r.id, + } + + entryJSON, err := json.Marshal(entry) + if err != nil { + return HAR{}, HARExportMeta{}, err + } + // +1 for the separating comma inside the JSON array. + if encodedJSONBytes+int64(len(entryJSON))+1 > opts.MaxJSONBytes { + meta.Truncated = true + meta.TruncatedReason = "max_bytes" + break + } + encodedJSONBytes += int64(len(entryJSON)) + 1 + meta.TotalBytes += entryRawBytes + entries = append(entries, entry) + } + + if !meta.Truncated && hitEntryCap { + meta.Truncated = true + meta.TruncatedReason = "max_entries" + } + meta.Exported = len(entries) + + doc := HAR{ + Log: &HARLog{ + Version: HARVersion, + Creator: HARCreator{Name: "ARTEX", Version: creatorVer}, + Entries: entries, + Truncated: meta.Truncated, + TruncatedReason: meta.TruncatedReason, + }, + } + if meta.Truncated { + doc.Log.TotalMatched = meta.TotalMatched + } + return doc, meta, nil +} + +func (t *Traffic) loadFullExchange(id, legacyPath string) (reqHead string, reqBody []byte, respHead string, respBody []byte, err error) { + var reqBlob, respBlob sql.NullString + err = t.db.QueryRow(`SELECT req_head,req_body,req_blob,resp_head,resp_body,resp_blob +FROM exchange_bodies WHERE id=?`, id).Scan(&reqHead, &reqBody, &reqBlob, &respHead, &respBody, &respBlob) + if errors.Is(err, sql.ErrNoRows) && strings.TrimSpace(legacyPath) != "" { + rb, readErr := os.ReadFile(filepath.Join(t.dir, legacyPath, "request.http")) + if readErr != nil && !os.IsNotExist(readErr) { + return "", nil, "", nil, readErr + } + pb, readErr := os.ReadFile(filepath.Join(t.dir, legacyPath, "response.http")) + if readErr != nil && !os.IsNotExist(readErr) { + return "", nil, "", nil, readErr + } + reqHead, reqBody = splitLegacyHTTP(rb) + respHead, respBody = splitLegacyHTTP(pb) + return reqHead, reqBody, respHead, respBody, nil + } + if err != nil { + return "", nil, "", nil, err + } + if reqBlob.Valid && reqBlob.String != "" { + p, err := t.blobPath(reqBlob.String) + if err != nil { + return "", nil, "", nil, err + } + reqBody, err = os.ReadFile(p) + if err != nil { + return "", nil, "", nil, err + } + } + if respBlob.Valid && respBlob.String != "" { + p, err := t.blobPath(respBlob.String) + if err != nil { + return "", nil, "", nil, err + } + respBody, err = os.ReadFile(p) + if err != nil { + return "", nil, "", nil, err + } + } + return reqHead, reqBody, respHead, respBody, nil +} + +func splitLegacyHTTP(raw []byte) (string, []byte) { + if idx := bytes.Index(raw, []byte("\r\n\r\n")); idx >= 0 { + return string(raw[:idx]), raw[idx+4:] + } + if idx := bytes.Index(raw, []byte("\n\n")); idx >= 0 { + return string(raw[:idx]), raw[idx+2:] + } + return string(raw), nil +} + +// encodeHARBody returns plain text for valid NUL-free UTF-8 bodies, and base64 +// otherwise so binary payloads survive export and re-import bit-for-bit. +func encodeHARBody(body []byte) (text, encoding string) { + if utf8.Valid(body) && bytes.IndexByte(body, 0) < 0 { + return string(body), "" + } + return base64.StdEncoding.EncodeToString(body), "base64" +} + +func parseStoredRequestHead(raw string) (httpVersion string, headers []HARHeader) { + headers = []HARHeader{} + lines := strings.Split(strings.ReplaceAll(raw, "\r\n", "\n"), "\n") + if len(lines) == 0 { + return "", headers + } + first := strings.TrimSpace(lines[0]) + if parts := strings.SplitN(first, " ", 3); len(parts) == 3 && strings.HasPrefix(strings.ToUpper(parts[2]), "HTTP/") { + httpVersion = strings.TrimSpace(parts[2]) + } + headers = appendParsedHeaders(headers, lines[1:]) + return httpVersion, headers +} + +func parseStoredResponseHead(raw string) (httpVersion, statusText string, headers []HARHeader) { + headers = []HARHeader{} + lines := strings.Split(strings.ReplaceAll(raw, "\r\n", "\n"), "\n") + if len(lines) == 0 { + return "", "", headers + } + first := strings.TrimSpace(lines[0]) + if parts := strings.SplitN(first, " ", 3); len(parts) >= 2 && strings.HasPrefix(strings.ToUpper(parts[0]), "HTTP") { + if strings.HasPrefix(strings.ToUpper(parts[0]), "HTTP/") { + httpVersion = strings.TrimSpace(parts[0]) + } + if len(parts) == 3 { + statusText = strings.TrimSpace(parts[2]) + } + } + headers = appendParsedHeaders(headers, lines[1:]) + return httpVersion, statusText, headers +} + +func appendParsedHeaders(dst []HARHeader, lines []string) []HARHeader { + for _, line := range lines { + line = strings.TrimRight(line, "\r") + if strings.TrimSpace(line) == "" { + continue + } + colon := strings.IndexByte(line, ':') + if colon <= 0 { + continue + } + name := strings.TrimSpace(line[:colon]) + if name == "" || !validHeaderName(name) { + continue + } + val := strings.TrimSpace(line[colon+1:]) + dst = append(dst, HARHeader{Name: name, Value: val}) + } + return dst +} + +func findHeaderValue(headers []HARHeader, name string) string { + for _, h := range headers { + if strings.EqualFold(h.Name, name) { + return h.Value + } + } + return "" +} diff --git a/traffic/har_test.go b/traffic/har_test.go new file mode 100644 index 00000000..98f3d5b6 --- /dev/null +++ b/traffic/har_test.go @@ -0,0 +1,817 @@ +package traffic + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "errors" + "strings" + "testing" + + "github.com/Autumn-27/artex/traffic/rewrite" +) + +func TestHARRoundTripPlainBase64BinaryEmptyAndLargeBlob(t *testing.T) { + src, err := Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer src.Close() + + // Install an enabled capture rewrite rule to prove HAR import NEVER runs rules + // or writes exchange_rewrites rows. + set := rewrite.Compile([]rewrite.Rule{{ + ID: 42, Name: "should-not-apply-to-har", Enabled: true, Phase: rewrite.PhaseRequest, + Actions: []rewrite.Action{{Type: rewrite.ActionSetHeader, Name: "X-Injected", Value: "1"}}, + }}, rewrite.Options{}) + if len(set.LoadErrors()) != 0 { + t.Fatalf("compile rewrite rules: %v", set.LoadErrors()) + } + src.SetRewriteRules(set) + + binaryResp := []byte{0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0xff, 0xfe, 0x01} + binaryReq := []byte{0x00, 0x01, 0x02, 0x80, 0xff} + largeTextBody := "LARGE-HAR-NEEDLE-" + strings.Repeat("abcdefghij", (maxInlineBody/10)+50) // > 256 KiB -> blob! + + inputHAR := HAR{ + Log: &HARLog{ + Version: "1.2", + Creator: HARCreator{Name: "TestBrowser", Version: "1.0"}, + Entries: []HAREntry{ + { + StartedDateTime: "2026-05-01T10:00:00.789Z", + Request: HARRequest{ + Method: "POST", + URL: "https://app.example.com/api/v1/items/42?mode=full", + HTTPVersion: "HTTP/1.1", + Headers: []HARHeader{ + {Name: ":method", Value: "POST"}, + {Name: ":authority", Value: "app.example.com"}, + {Name: "Host", Value: "app.example.com"}, + {Name: "Content-Type", Value: "application/json"}, + {Name: "X-Trace", Value: "one"}, + {Name: "X-Trace", Value: "two"}, + }, + PostData: &HARPostData{ + MimeType: "application/json", + Text: `{"action":"create","needle":"plain-req-token"}`, + }, + }, + Response: HARResponse{ + Status: 201, + StatusText: "Created", + HTTPVersion: "HTTP/1.1", + Headers: []HARHeader{ + {Name: "Content-Type", Value: "application/json; charset=utf-8"}, + {Name: "X-Resp", Value: "ok"}, + }, + Content: HARContent{ + MimeType: "application/json; charset=utf-8", + Text: `{"id":42,"msg":"plain-resp-marker"}`, + }, + }, + }, + { + StartedDateTime: "2026-05-01T10:00:05Z", + Request: HARRequest{ + Method: "POST", + URL: "https://cdn.example.com/upload", + HTTPVersion: "HTTP/2.0", + Headers: []HARHeader{{Name: "Content-Type", Value: "application/octet-stream"}}, + PostData: &HARPostData{ + MimeType: "application/octet-stream", + Text: base64.StdEncoding.EncodeToString(binaryReq), + Encoding: "base64", + }, + }, + Response: HARResponse{ + Status: 200, + HTTPVersion: "HTTP/2.0", + Headers: []HARHeader{{Name: "Content-Type", Value: "image/png"}}, + Content: HARContent{ + MimeType: "image/png", + Text: base64.StdEncoding.EncodeToString(binaryResp), + Encoding: "base64", + }, + }, + }, + { + StartedDateTime: "2026-05-01T10:00:10Z", + Request: HARRequest{ + Method: "GET", + URL: "https://app.example.com/empty", + Headers: []HARHeader{{Name: "Accept", Value: "*/*"}}, + }, + Response: HARResponse{ + Status: 204, + Headers: []HARHeader{}, + Content: HARContent{}, + }, + }, + { + StartedDateTime: "2026-05-01T10:00:15Z", + Request: HARRequest{ + Method: "GET", + URL: "https://blob.example.com/big.txt", + Headers: []HARHeader{}, + }, + Response: HARResponse{ + Status: 200, + Headers: []HARHeader{{Name: "Content-Type", Value: "text/plain"}}, + Content: HARContent{ + MimeType: "text/plain", + Text: largeTextBody, + }, + }, + }, + }, + }, + } + + rawIn, err := json.Marshal(inputHAR) + if err != nil { + t.Fatal(err) + } + + res, err := src.ImportHAR(rawIn, HARImportOptions{}) + if err != nil { + t.Fatalf("ImportHAR: %v", err) + } + if res.Imported != 4 || res.Skipped != 0 || res.Failed != 0 || res.Truncated { + t.Fatalf("ImportHAR result = %+v, want 4/0/0/false", res) + } + + // Re-importing the exact same HAR must be idempotent (all skipped). + res2, err := src.ImportHAR(rawIn, HARImportOptions{}) + if err != nil { + t.Fatalf("re-import HAR: %v", err) + } + if res2.Imported != 0 || res2.Skipped != 4 || res2.Failed != 0 { + t.Fatalf("re-import result = %+v, want 0/4/0", res2) + } + + // Verify none of the imported exchanges are flagged rewritten or have exchange_rewrites rows. + var rwRows int + if err := src.DB().QueryRow(`SELECT COUNT(*) FROM exchange_rewrites`).Scan(&rwRows); err != nil || rwRows != 0 { + t.Fatalf("exchange_rewrites count = %d err=%v, want 0", rwRows, err) + } + allRows, total, err := src.Page(PageQuery{RespMin: -1, RespMax: -1}, 0, 20) + if err != nil || total != 4 || len(allRows) != 4 { + t.Fatalf("Page after import = (%d, %d, %v), want (4, 4, nil)", len(allRows), total, err) + } + for _, r := range allRows { + if !strings.HasPrefix(r.ID, "har-") { + t.Fatalf("expected har- prefix on id %q", r.ID) + } + if r.Rewritten { + t.Fatalf("imported exchange %s unexpectedly flagged rewritten", r.ID) + } + if rw, ids, err := src.RewriteInfo(r.ID); err != nil || rw || len(ids) != 0 { + t.Fatalf("RewriteInfo(%s) = (%v, %v, %v), want (false, nil, nil)", r.ID, rw, ids, err) + } + } + + // Verify searchable via FTS (both inline body and spilled large text body). + if rows, tot, err := src.Page(PageQuery{Body: "plain-resp-marker", RespMin: -1, RespMax: -1}, 0, 10); err != nil || tot != 1 || len(rows) != 1 { + t.Fatalf("FTS search inline body = (%d, %d, %v), want 1", len(rows), tot, err) + } + if rows, tot, err := src.Page(PageQuery{Body: "LARGE-HAR-NEEDLE", RespMin: -1, RespMax: -1}, 0, 10); err != nil || tot != 1 || len(rows) != 1 { + t.Fatalf("FTS search blob body = (%d, %d, %v), want 1", len(rows), tot, err) + } + + // Verify large body actually spilled to a blob and registered in blob_refs. + var blobHash string + var blobRefCount int + if err := src.DB().QueryRow(`SELECT resp_blob FROM exchange_bodies b JOIN exchanges e ON e.id=b.id WHERE e.host='blob.example.com'`).Scan(&blobHash); err != nil || blobHash == "" { + t.Fatalf("large body did not spill to blob: hash=%q err=%v", blobHash, err) + } + if err := src.DB().QueryRow(`SELECT COUNT(*) FROM blob_refs WHERE hash=?`, blobHash).Scan(&blobRefCount); err != nil || blobRefCount != 1 { + t.Fatalf("blob_refs count for %s = %d err=%v, want 1", blobHash, blobRefCount, err) + } + + // Export HAR from src. + exported, meta, err := src.ExportHAR(PageQuery{RespMin: -1, RespMax: -1}, HARExportOptions{CreatorVersion: "2.3.0"}) + if err != nil { + t.Fatalf("ExportHAR: %v", err) + } + if meta.Exported != 4 || meta.TotalMatched != 4 || meta.Truncated || meta.TruncatedReason != "" { + t.Fatalf("ExportHAR meta = %+v", meta) + } + if exported.Log.Version != "1.2" || exported.Log.Creator.Name != "ARTEX" || exported.Log.Creator.Version != "2.3.0" { + t.Fatalf("ExportHAR header = %+v", exported.Log) + } + if len(exported.Log.Entries) != 4 { + t.Fatalf("ExportHAR entries = %d, want 4", len(exported.Log.Entries)) + } + + // Verify HAR 1.2 required keys are present with explicit unknown placeholders + // and serverIPAddress is not fabricated. + rawExported, err := json.Marshal(exported) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(rawExported), `"serverIPAddress"`) { + t.Fatalf("exported HAR invented serverIPAddress: %s", string(rawExported)) + } + var rawDoc map[string]any + if err := json.Unmarshal(rawExported, &rawDoc); err != nil { + t.Fatal(err) + } + rawLog := rawDoc["log"].(map[string]any) + rawEntries := rawLog["entries"].([]any) + firstEntry := rawEntries[0].(map[string]any) + if got, ok := firstEntry["time"].(float64); !ok || got != 0 { + t.Fatalf("entry.time = %#v, want 0", firstEntry["time"]) + } + if cacheObj, ok := firstEntry["cache"].(map[string]any); !ok || len(cacheObj) != 0 { + t.Fatalf("entry.cache = %#v, want {}", firstEntry["cache"]) + } + timingsObj, ok := firstEntry["timings"].(map[string]any) + if !ok || timingsObj["send"] != float64(-1) || timingsObj["wait"] != float64(-1) || timingsObj["receive"] != float64(-1) { + t.Fatalf("entry.timings = %#v, want {send:-1 wait:-1 receive:-1}", firstEntry["timings"]) + } + reqObj := firstEntry["request"].(map[string]any) + if cookies, ok := reqObj["cookies"].([]any); !ok || len(cookies) != 0 { + t.Fatalf("request.cookies = %#v, want []", reqObj["cookies"]) + } + if qs, ok := reqObj["queryString"].([]any); !ok || len(qs) != 0 { + t.Fatalf("request.queryString = %#v, want []", reqObj["queryString"]) + } + if hs, ok := reqObj["headersSize"].(float64); !ok || hs != -1 { + t.Fatalf("request.headersSize = %#v, want -1", reqObj["headersSize"]) + } + if _, ok := reqObj["httpVersion"].(string); !ok { + t.Fatalf("request.httpVersion missing: %#v", reqObj) + } + respObj := firstEntry["response"].(map[string]any) + if cookies, ok := respObj["cookies"].([]any); !ok || len(cookies) != 0 { + t.Fatalf("response.cookies = %#v, want []", respObj["cookies"]) + } + if redir, ok := respObj["redirectURL"].(string); !ok || redir != "" { + t.Fatalf("response.redirectURL = %#v, want \"\"", respObj["redirectURL"]) + } + if hs, ok := respObj["headersSize"].(float64); !ok || hs != -1 { + t.Fatalf("response.headersSize = %#v, want -1", respObj["headersSize"]) + } + if _, ok := respObj["httpVersion"].(string); !ok { + t.Fatalf("response.httpVersion missing: %#v", respObj) + } + if _, ok := respObj["statusText"].(string); !ok { + t.Fatalf("response.statusText missing: %#v", respObj) + } + contentObj := respObj["content"].(map[string]any) + if _, ok := contentObj["mimeType"].(string); !ok { + t.Fatalf("response.content.mimeType missing: %#v", contentObj) + } + + // Verify stable chronological ordering & exact body encodings. + e0 := exported.Log.Entries[0] + if e0.Request.URL != "https://app.example.com/api/v1/items/42?mode=full" || e0.Response.Content.Encoding != "" || e0.Response.Content.Text != `{"id":42,"msg":"plain-resp-marker"}` { + t.Fatalf("entry 0 mismatch: %+v", e0) + } + e1 := exported.Log.Entries[1] + if e1.Response.Content.Encoding != "base64" || e1.Request.PostData == nil || e1.Request.PostData.Encoding != "base64" { + t.Fatalf("entry 1 binary encodings wrong: req=%+v resp=%+v", e1.Request.PostData, e1.Response.Content) + } + gotBinResp, err := base64.StdEncoding.DecodeString(e1.Response.Content.Text) + if err != nil || !bytes.Equal(gotBinResp, binaryResp) { + t.Fatalf("entry 1 binary resp mismatch: got=%x err=%v", gotBinResp, err) + } + gotBinReq, err := base64.StdEncoding.DecodeString(e1.Request.PostData.Text) + if err != nil || !bytes.Equal(gotBinReq, binaryReq) { + t.Fatalf("entry 1 binary req mismatch: got=%x err=%v", gotBinReq, err) + } + e2 := exported.Log.Entries[2] + if e2.Request.PostData != nil || e2.Response.Content.Size != 0 || e2.Response.Content.Text != "" { + t.Fatalf("entry 2 empty body mismatch: %+v", e2) + } + e3 := exported.Log.Entries[3] + if e3.Response.Content.Size != len(largeTextBody) || e3.Response.Content.Text != largeTextBody || e3.Response.Content.Encoding != "" { + t.Fatalf("entry 3 large blob body truncated or altered: size=%d len=%d", e3.Response.Content.Size, len(e3.Response.Content.Text)) + } + + // Re-importing the exported HAR into src must be 100% idempotent (same deterministic IDs!). + reimpSame, err := src.ImportHAR(rawExported, HARImportOptions{}) + if err != nil { + t.Fatalf("re-import exported HAR into src: %v", err) + } + if reimpSame.Imported != 0 || reimpSame.Skipped != 4 || reimpSame.Failed != 0 { + t.Fatalf("re-import exported HAR into src = %+v, want 0/4/0", reimpSame) + } + + // Re-importing the exported HAR into a fresh store must yield identical IDs, metadata, and bodies. + dst, err := Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer dst.Close() + + reimpFresh, err := dst.ImportHAR(rawExported, HARImportOptions{}) + if err != nil { + t.Fatalf("import exported HAR into dst: %v", err) + } + if reimpFresh.Imported != 4 || reimpFresh.Skipped != 0 || reimpFresh.Failed != 0 { + t.Fatalf("dst import = %+v, want 4/0/0", reimpFresh) + } + + exportedDst, _, err := dst.ExportHAR(PageQuery{RespMin: -1, RespMax: -1}, HARExportOptions{CreatorVersion: "2.3.0"}) + if err != nil { + t.Fatal(err) + } + rawDst, err := json.Marshal(exportedDst) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(rawExported, rawDst) { + t.Fatalf("dst round-trip HAR differs from src export") + } +} + +func TestHARImportValidationDuplicatesAndPartialErrors(t *testing.T) { + tr, err := Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer tr.Close() + + badDocs := []struct { + name string + raw string + want string + }{ + {"empty", "", "empty HAR"}, + {"malformed json", `{"log":`, "malformed JSON"}, + {"trailing garbage", `{"log":{"version":"1.2","entries":[]}} extra`, "trailing content"}, + {"missing log", `{}`, "missing log"}, + {"missing entries", `{"log":{"version":"1.2"}}`, "missing log.entries"}, + {"null entries", `{"log":{"version":"1.2","entries":null}}`, "missing log.entries"}, + {"unsupported version 1.1", `{"log":{"version":"1.1","entries":[]}}`, "unsupported HAR version"}, + {"unsupported version 2.0", `{"log":{"version":"2.0","entries":[]}}`, "unsupported HAR version"}, + {"empty version", `{"log":{"version":"","entries":[]}}`, "unsupported HAR version"}, + } + for _, tc := range badDocs { + t.Run(tc.name, func(t *testing.T) { + _, err := tr.ImportHAR([]byte(tc.raw), HARImportOptions{}) + if !errors.Is(err, ErrInvalidHAR) || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("ImportHAR(%s) err = %v, want ErrInvalidHAR containing %q", tc.name, err, tc.want) + } + }) + } + + // Duplicate entries inside one HAR + bad entries mixed with valid ones. + mixed := `{ + "log": { + "version": "1.2", + "entries": [ + { + "startedDateTime": "2026-05-01T12:00:00Z", + "request": {"method": "GET", "url": "https://dup.example/a", "headers": []}, + "response": {"status": 200, "headers": [], "content": {"text": "ok"}} + }, + { + "startedDateTime": "2026-05-01T12:00:00Z", + "request": {"method": "GET", "url": "https://dup.example/a", "headers": []}, + "response": {"status": 200, "headers": [], "content": {"text": "ok"}} + }, + { + "startedDateTime": "not-a-timestamp", + "request": {"method": "GET", "url": "https://bad.example/ts", "headers": []}, + "response": {"status": 200, "headers": [], "content": {}} + }, + { + "startedDateTime": "2026-05-01T12:00:01Z", + "request": {"method": "GET", "url": "https://bad.example/hdr", "headers": [{"name": "X-Bad", "value": "a\r\nb"}]}, + "response": {"status": 200, "headers": [], "content": {}} + }, + { + "startedDateTime": "2026-05-01T12:00:02Z", + "request": {"method": "GET", "url": "https://bad.example/b64", "headers": []}, + "response": {"status": 200, "headers": [], "content": {"text": "!!!not-base64!!!", "encoding": "base64"}} + }, + { + "startedDateTime": "2026-05-01T12:00:03Z", + "request": {"method": "GET", "url": "https://good.example/b", "headers": []}, + "response": {"status": 200, "headers": [], "content": {"text": "second"}} + } + ] + } + }` + res, err := tr.ImportHAR([]byte(mixed), HARImportOptions{}) + if err != nil { + t.Fatalf("mixed ImportHAR: %v", err) + } + if res.Imported != 2 || res.Skipped != 1 || res.Failed != 3 || len(res.Errors) != 3 { + t.Fatalf("mixed ImportHAR result = %+v, want imported=2 skipped=1 failed=3 errors=3", res) + } + + // Entry cap returns ErrInvalidHAR. + if _, err := tr.ImportHAR([]byte(mixed), HARImportOptions{MaxEntries: 2}); !errors.Is(err, ErrInvalidHAR) { + t.Fatalf("MaxEntries exceeded err = %v, want ErrInvalidHAR", err) + } + + // Byte cap truncates cleanly and reports remaining skipped. + byteCapHAR := `{ + "log": { + "version": "1.2", + "entries": [ + { + "startedDateTime": "2026-05-01T12:01:00Z", + "request": {"method": "GET", "url": "https://cap.example/1", "headers": []}, + "response": {"status": 200, "headers": [], "content": {"text": "1234567890"}} + }, + { + "startedDateTime": "2026-05-01T12:01:01Z", + "request": {"method": "GET", "url": "https://cap.example/2", "headers": []}, + "response": {"status": 200, "headers": [], "content": {"text": "1234567890"}} + } + ] + } + }` + capRes, err := tr.ImportHAR([]byte(byteCapHAR), HARImportOptions{MaxTotalBytes: 15}) + if err != nil { + t.Fatalf("byte-capped ImportHAR: %v", err) + } + if capRes.Imported != 1 || capRes.Skipped != 1 || !capRes.Truncated || len(capRes.Errors) != 1 { + t.Fatalf("byte-capped ImportHAR = %+v, want imported=1 skipped=1 truncated=true", capRes) + } +} + +func TestHARExportFiltersAndTruncationCaps(t *testing.T) { + tr, err := Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer tr.Close() + + insert := func(id string, ts int64, host string, status int, body string) { + t.Helper() + if _, err := tr.DB().Exec(`INSERT INTO exchanges(id,ts,host,method,url_template,url,status,content_type,req_len,resp_len,path) +VALUES(?,?,?,?,?,?,?,?,?,?,?)`, id, ts, host, "GET", "/"+id, "https://"+host+"/"+id, status, "text/plain", 0, len(body), ""); err != nil { + t.Fatal(err) + } + if _, err := tr.DB().Exec(`INSERT INTO exchange_bodies(id,req_head,req_body,resp_head,resp_body) +VALUES(?,?,?,?,?)`, id, "GET /"+id+" HTTP/1.1\nHost: "+host, []byte{}, "HTTP/1.1 200 OK", []byte(body)); err != nil { + t.Fatal(err) + } + } + + insert("e-2", 20, "alpha.example", 200, "bbbbbbbbbb") + insert("e-1", 10, "alpha.example", 404, "aaaaaaaaaa") + insert("e-3", 30, "beta.example", 200, "cccccccccc") + + // Filter by host + status, verify chronological order. + doc, meta, err := tr.ExportHAR(PageQuery{Host: "alpha.example", RespMin: -1, RespMax: -1}, HARExportOptions{}) + if err != nil { + t.Fatal(err) + } + if meta.Exported != 2 || meta.TotalMatched != 2 || meta.Truncated { + t.Fatalf("filtered export meta = %+v", meta) + } + if doc.Log.Entries[0].Request.URL != "https://alpha.example/e-1" || doc.Log.Entries[1].Request.URL != "https://alpha.example/e-2" { + t.Fatalf("export not in stable (ts,id) order: %+v", doc.Log.Entries) + } + + // Truncation by MaxEntries. + docEntryCap, metaEntryCap, err := tr.ExportHAR(PageQuery{RespMin: -1, RespMax: -1}, HARExportOptions{MaxEntries: 2}) + if err != nil { + t.Fatal(err) + } + if !metaEntryCap.Truncated || metaEntryCap.TruncatedReason != "max_entries" || metaEntryCap.Exported != 2 || metaEntryCap.TotalMatched != 3 { + t.Fatalf("entry-capped meta = %+v", metaEntryCap) + } + if !docEntryCap.Log.Truncated || docEntryCap.Log.TruncatedReason != "max_entries" || docEntryCap.Log.TotalMatched != 3 { + t.Fatalf("entry-capped log fields = %+v", docEntryCap.Log) + } + + // Truncation by MaxTotalBytes (note: raw cap counts both headers and bodies). + // Each row here has req_head (~46B) + resp_head (15B) + body (10B) ≈ 71B. + docByteCap, metaByteCap, err := tr.ExportHAR(PageQuery{RespMin: -1, RespMax: -1}, HARExportOptions{MaxTotalBytes: 100}) + if err != nil { + t.Fatal(err) + } + if !metaByteCap.Truncated || metaByteCap.TruncatedReason != "max_bytes" || metaByteCap.Exported != 1 || metaByteCap.TotalMatched != 3 { + t.Fatalf("byte-capped meta = %+v", metaByteCap) + } + if !docByteCap.Log.Truncated || docByteCap.Log.TruncatedReason != "max_bytes" || docByteCap.Log.TotalMatched != 3 { + t.Fatalf("byte-capped log fields = %+v", docByteCap.Log) + } +} + +func TestHARTwoIdenticalExchangesRoundTripPreservesBoth(t *testing.T) { + src, err := Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer src.Close() + + // Two distinct ARTEX exchanges recorded in the same second with identical + // method, URL, status, headers, and bodies. + for _, id := range []string{"dup-a", "dup-b"} { + if _, err := src.DB().Exec(`INSERT INTO exchanges(id,ts,host,method,url_template,url,status,content_type,req_len,resp_len,path) +VALUES(?,1700000000,'same.example','POST','/ping','https://same.example/ping',200,'application/json',2,2,'')`, id); err != nil { + t.Fatal(err) + } + if _, err := src.DB().Exec(`INSERT INTO exchange_bodies(id,req_head,req_body,resp_head,resp_body) +VALUES(?,'POST /ping HTTP/1.1\nHost: same.example\n',?,'HTTP/1.1 200 OK\n',?)`, id, []byte("{}"), []byte("{}")); err != nil { + t.Fatal(err) + } + } + + exported, meta, err := src.ExportHAR(PageQuery{RespMin: -1, RespMax: -1}, HARExportOptions{}) + if err != nil { + t.Fatal(err) + } + if meta.Exported != 2 || len(exported.Log.Entries) != 2 { + t.Fatalf("export = %+v, want 2 entries", meta) + } + if exported.Log.Entries[0].ArtexExchangeID != "dup-a" || exported.Log.Entries[1].ArtexExchangeID != "dup-b" { + t.Fatalf("exported _artexExchangeId = [%q %q], want [dup-a dup-b]", + exported.Log.Entries[0].ArtexExchangeID, exported.Log.Entries[1].ArtexExchangeID) + } + raw, err := json.Marshal(exported) + if err != nil { + t.Fatal(err) + } + + // Re-importing into src is idempotent (both skipped). + reimpSrc, err := src.ImportHAR(raw, HARImportOptions{}) + if err != nil { + t.Fatal(err) + } + if reimpSrc.Imported != 0 || reimpSrc.Skipped != 2 || reimpSrc.Failed != 0 { + t.Fatalf("re-import into src = %+v, want 0/2/0", reimpSrc) + } + + // Importing into a fresh store preserves BOTH dup-a and dup-b (no collapse!). + dst, err := Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer dst.Close() + + impDst, err := dst.ImportHAR(raw, HARImportOptions{}) + if err != nil { + t.Fatal(err) + } + if impDst.Imported != 2 || impDst.Skipped != 0 || impDst.Failed != 0 { + t.Fatalf("import into fresh dst = %+v, want 2/0/0", impDst) + } + if count, err := dst.Count(); err != nil || count != 2 { + t.Fatalf("dst.Count() = (%d, %v), want 2", count, err) + } + if _, _, err := dst.Get("dup-a"); err != nil { + t.Fatalf("dup-a missing in dst: %v", err) + } + if _, _, err := dst.Get("dup-b"); err != nil { + t.Fatalf("dup-b missing in dst: %v", err) + } + // Re-importing into dst is idempotent. + reimpDst, err := dst.ImportHAR(raw, HARImportOptions{}) + if err != nil { + t.Fatal(err) + } + if reimpDst.Imported != 0 || reimpDst.Skipped != 2 || reimpDst.Failed != 0 { + t.Fatalf("re-import into dst = %+v, want 0/2/0", reimpDst) + } +} + +func TestHARExportBinaryNearCapFitsUnderImportLimit(t *testing.T) { + src, err := Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer src.Close() + + // Binary body near the 20 MiB raw export cap (~19.5 MiB). After base64 + // expansion (4/3x ≈ 26 MiB) plus headers and JSON envelope, it must still + // marshal strictly under the 32 MiB HTTP import limit. + const bodySize = 19*1024*1024 + 512*1024 + binBody := make([]byte, bodySize) + for i := range binBody { + binBody[i] = byte((i*31 + 0x80) & 0xff) + } + binBody[0] = 0x00 // guarantee binary/base64 encoding + + respB := src.spill(binBody, "application/octet-stream") + reqHead := "GET /big.bin HTTP/1.1\nHost: cap.example\n" + strings.Repeat("X-Pad: 0123456789\n", 10) + respHead := "HTTP/1.1 200 OK\nContent-Type: application/octet-stream\n" + if err := src.insertExchange("bin-near-cap", 1700000100, "cap.example", "GET", "/big.bin", + "https://cap.example/big.bin", 200, "application/octet-stream", 0, len(binBody), reqHead, storedBody{}, respHead, respB); err != nil { + t.Fatal(err) + } + + doc, meta, err := src.ExportHAR(PageQuery{RespMin: -1, RespMax: -1}, HARExportOptions{}) + if err != nil { + t.Fatalf("ExportHAR near cap: %v", err) + } + if meta.Truncated || meta.Exported != 1 { + t.Fatalf("near-cap export meta = %+v, want Truncated=false Exported=1", meta) + } + // Verify headers were counted in TotalBytes alongside the body. + wantRaw := int64(len(reqHead) + len(respHead) + len(binBody)) + if meta.TotalBytes != wantRaw { + t.Fatalf("meta.TotalBytes = %d, want %d (headers + body)", meta.TotalBytes, wantRaw) + } + + rawJSON, err := json.Marshal(doc) + if err != nil { + t.Fatal(err) + } + const httpImportLimit = 32 << 20 + if len(rawJSON) >= httpImportLimit { + t.Fatalf("marshaled near-cap binary HAR = %d bytes, exceeds 32 MiB import limit (%d)", len(rawJSON), httpImportLimit) + } + + // Re-importing into a fresh store succeeds with exact bytes. + dst, err := Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer dst.Close() + imp, err := dst.ImportHAR(rawJSON, HARImportOptions{}) + if err != nil || imp.Imported != 1 || imp.Failed != 0 || imp.Truncated { + t.Fatalf("re-import near-cap binary HAR = (%+v, %v)", imp, err) + } + _, _, _, gotResp, err := dst.loadFullExchange("bin-near-cap", "") + if err != nil || !bytes.Equal(gotResp, binBody) { + t.Fatalf("near-cap binary round-trip mismatch: len=%d err=%v", len(gotResp), err) + } +} + +func TestHARImportPostDataParamsAndCookies(t *testing.T) { + tr, err := Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer tr.Close() + + // Entry 0: form body ONLY in postData.params, cookies ONLY in cookies arrays. + // Entry 1: Cookie and Set-Cookie already present in headers -> must NOT duplicate. + harJSON := `{ + "log": { + "version": "1.2", + "entries": [ + { + "startedDateTime": "2026-05-02T09:00:00Z", + "request": { + "method": "POST", + "url": "https://form.example/login", + "headers": [{"name": "Host", "value": "form.example"}], + "cookies": [ + {"name": "sid", "value": "abc123"}, + {"name": "theme", "value": "dark"} + ], + "postData": { + "mimeType": "application/x-www-form-urlencoded", + "params": [ + {"name": "user", "value": "alice"}, + {"name": "msg", "value": "hello world"} + ] + } + }, + "response": { + "status": 302, + "headers": [{"name": "Location", "value": "/home"}], + "cookies": [ + {"name": "session", "value": "xyz", "path": "/", "httpOnly": true, "secure": true} + ], + "content": {"size": 0, "mimeType": ""} + } + }, + { + "startedDateTime": "2026-05-02T09:00:05Z", + "request": { + "method": "GET", + "url": "https://form.example/home", + "headers": [{"name": "Cookie", "value": "existing=1"}], + "cookies": [{"name": "existing", "value": "1"}] + }, + "response": { + "status": 200, + "headers": [{"name": "Set-Cookie", "value": "kept=2; Path=/"}], + "cookies": [{"name": "kept", "value": "2", "path": "/"}], + "content": {"size": 2, "mimeType": "text/plain", "text": "ok"} + } + } + ] + } + }` + + res, err := tr.ImportHAR([]byte(harJSON), HARImportOptions{}) + if err != nil || res.Imported != 2 || res.Failed != 0 { + t.Fatalf("ImportHAR(params+cookies) = (%+v, %v)", res, err) + } + + rows, _, err := tr.Page(PageQuery{Host: "form.example", RespMin: -1, RespMax: -1, Sort: "ts", Order: "asc"}, 0, 10) + if err != nil || len(rows) != 2 { + t.Fatalf("Page = (%d, %v)", len(rows), err) + } + req0, resp0, err := tr.Get(rows[0].ID) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(req0, "Cookie: sid=abc123; theme=dark\n") { + t.Fatalf("entry 0 missing synthesized Cookie header: %q", req0) + } + if !strings.Contains(req0, "user=alice&msg=hello+world") { + t.Fatalf("entry 0 missing postData.params form body: %q", req0) + } + if !strings.Contains(resp0, "Set-Cookie: session=xyz; Path=/; Secure; HttpOnly\n") { + t.Fatalf("entry 0 missing synthesized Set-Cookie header: %q", resp0) + } + + req1, resp1, err := tr.Get(rows[1].ID) + if err != nil { + t.Fatal(err) + } + if strings.Count(req1, "Cookie:") != 1 { + t.Fatalf("entry 1 duplicated Cookie header: %q", req1) + } + if strings.Count(resp1, "Set-Cookie:") != 1 { + t.Fatalf("entry 1 duplicated Set-Cookie header: %q", resp1) + } +} + +func TestHARImportStripsAndRedactsURLUserinfo(t *testing.T) { + tr, err := Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer tr.Close() + + harJSON := `{ + "log": { + "version": "1.2", + "entries": [ + { + "startedDateTime": "2026-05-03T10:00:00Z", + "request": { + "method": "GET", + "url": "https://alice:supersecret@api.example.com/v1/items?k=1", + "headers": [] + }, + "response": { + "status": 200, + "headers": [], + "content": {"mimeType": "text/plain", "text": "ok"} + } + }, + { + "startedDateTime": "2026-05-03T10:00:01Z", + "request": { + "method": "BAD METHOD", + "url": "https://bob:topsecret@bad.example.com/fail", + "headers": [] + }, + "response": {"status": 200, "headers": [], "content": {}} + }, + { + "startedDateTime": "2026-05-03T10:00:02Z", + "request": { + "method": "GET", + "url": "https://carol:hiddenpass@bad host/x", + "headers": [] + }, + "response": {"status": 200, "headers": [], "content": {}} + } + ] + } + }` + + res, err := tr.ImportHAR([]byte(harJSON), HARImportOptions{}) + if err != nil { + t.Fatal(err) + } + if res.Imported != 1 || res.Failed != 2 || len(res.Errors) != 2 { + t.Fatalf("ImportHAR userinfo result = %+v, want 1 imported / 2 failed", res) + } + for _, e := range res.Errors { + for _, secret := range []string{"bob", "topsecret", "carol", "hiddenpass"} { + if strings.Contains(e.URL, secret) || strings.Contains(e.Reason, secret) { + t.Fatalf("import error leaked userinfo %q: %+v", secret, e) + } + } + } + + // Stored URL must have userinfo stripped. + rows, total, err := tr.Page(PageQuery{RespMin: -1, RespMax: -1}, 0, 10) + if err != nil || total != 1 || len(rows) != 1 { + t.Fatalf("Page = (%d, %d, %v)", len(rows), total, err) + } + if rows[0].URL != "https://api.example.com/v1/items?k=1" { + t.Fatalf("stored URL = %q, want userinfo stripped", rows[0].URL) + } + // FTS must NOT find the stripped password. + if found, tot, err := tr.Page(PageQuery{Query: "supersecret", RespMin: -1, RespMax: -1}, 0, 10); err != nil || tot != 0 || len(found) != 0 { + t.Fatalf("FTS leaked userinfo secret: %+v", found) + } + // Exported HAR must NOT contain the password. + doc, _, err := tr.ExportHAR(PageQuery{RespMin: -1, RespMax: -1}, HARExportOptions{}) + if err != nil { + t.Fatal(err) + } + raw, _ := json.Marshal(doc) + if strings.Contains(string(raw), "supersecret") || strings.Contains(string(raw), "alice") { + t.Fatalf("exported HAR leaked userinfo: %s", string(raw)) + } +} diff --git a/traffic/traffic.go b/traffic/traffic.go index f708d189..8444b831 100644 --- a/traffic/traffic.go +++ b/traffic/traffic.go @@ -1104,22 +1104,10 @@ func statusFilter(s string) (cond string, args []any, ok bool) { return "", nil, false } -// Page returns one page of exchange metadata for the traffic list, filtered by -// the criteria in f (all optional, combined with AND) and ordered by the -// requested column. Query is the broad search box (metadata columns OR, when the -// term is long enough for the trigram index, captured request/response text); -// Body narrows to exchanges whose captured text matches, via that same index. -// Also returns the total number of rows matching the filter (for the UI's -// pagination). Bodies are never included in the rows. -func (t *Traffic) Page(f PageQuery, page, size int) (rows []ExchangeMeta, total int, err error) { - if size <= 0 || size > 500 { - size = 100 - } - if page < 0 { - page = 0 - } - where := "" - var args []any +// pageWhere builds the SQL WHERE clause and bound arguments for PageQuery. +// Page and ExportHAR share this so list queries and HAR exports honor the exact +// same filter semantics. +func (t *Traffic) pageWhere(f PageQuery) (where string, args []any) { add := func(cond string, vs ...any) { if where == "" { where = " WHERE " @@ -1170,6 +1158,24 @@ func (t *Traffic) Page(f PageQuery, page, size int) (rows []ExchangeMeta, total add(cond, arg) } } + return where, args +} + +// Page returns one page of exchange metadata for the traffic list, filtered by +// the criteria in f (all optional, combined with AND) and ordered by the +// requested column. Query is the broad search box (metadata columns OR, when the +// term is long enough for the trigram index, captured request/response text); +// Body narrows to exchanges whose captured text matches, via that same index. +// Also returns the total number of rows matching the filter (for the UI's +// pagination). Bodies are never included in the rows. +func (t *Traffic) Page(f PageQuery, page, size int) (rows []ExchangeMeta, total int, err error) { + if size <= 0 || size > 500 { + size = 100 + } + if page < 0 { + page = 0 + } + where, args := t.pageWhere(f) if err = t.db.QueryRow(`SELECT COUNT(*) FROM exchanges`+where, args...).Scan(&total); err != nil { return nil, 0, err } diff --git a/web/src/app/(main)/function/traffic/page.tsx b/web/src/app/(main)/function/traffic/page.tsx index 74cb0ca8..4cbb009f 100644 --- a/web/src/app/(main)/function/traffic/page.tsx +++ b/web/src/app/(main)/function/traffic/page.tsx @@ -7,6 +7,7 @@ import { ArrowUpNarrowWideIcon, ChevronLeftIcon, ChevronRightIcon, + DownloadIcon, EraserIcon, FilterXIcon, ListChecksIcon, @@ -14,11 +15,14 @@ import { RadioTowerIcon, SearchIcon, Trash2Icon, + UploadIcon, + XIcon, } from "lucide-react"; import { toast } from "sonner"; import { HttpCodeBlock } from "@/components/http-code-block"; import { LinkTrafficDialog } from "@/components/link-traffic-dialog"; +import { Alert, AlertDescription } from "@/components/ui/alert"; import { AlertDialog, AlertDialogAction, @@ -44,7 +48,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip import { api } from "@/lib/api"; import { setVisibleInterval } from "@/lib/polling"; import { useStoredSortPreference } from "@/lib/sort-preference"; -import type { TrafficDetail, TrafficExchange, TrafficHost, TrafficResp } from "@/lib/types"; +import type { TrafficDetail, TrafficExchange, TrafficHARImportResult, TrafficHost, TrafficResp } from "@/lib/types"; import { cn } from "@/lib/utils"; import { intlLocale, t } from "@/i18n"; @@ -159,6 +163,13 @@ export default function TrafficPage() { const [deleting, setDeleting] = React.useState(false); const [reloadTick, setReloadTick] = React.useState(0); // manual refetch trigger + // HAR 1.2 import/export state + const harInputRef = React.useRef(null); + const [harImporting, setHarImporting] = React.useState(false); + const [harExporting, setHarExporting] = React.useState(false); + const [harSummary, setHarSummary] = React.useState(null); + const [harError, setHarError] = React.useState(null); + // Debounce both filters so we don't refetch on every keystroke. React.useEffect(() => { const t = setTimeout(() => setHostQ(host.trim()), 300); @@ -367,6 +378,76 @@ export default function TrafficPage() { : { field, direction: "desc" }, ); + const handleHarFileChange = async (event: React.ChangeEvent) => { + const file = event.target.files?.[0]; + event.target.value = ""; + if (!file) return; + setHarError(null); + setHarSummary(null); + if (file.size > 32 * 1024 * 1024) { + const msg = t("HAR file exceeds the 32 MiB limit"); + setHarError(msg); + toast.error(msg); + return; + } + setHarImporting(true); + try { + const raw = await file.text(); + const res = await api.trafficImportHAR(raw); + setHarSummary(res); + const summary = t("HAR import complete: {imported} imported, {skipped} skipped, {failed} failed", { + imported: res.imported, + skipped: res.skipped, + failed: res.failed, + }); + if (res.failed > 0 || res.truncated) { + toast.warning(summary); + } else { + toast.success(summary); + } + setPage(0); + setReloadTick((n) => n + 1); + } catch (e) { + const msg = t("HAR import failed: {error}", { error: (e as Error).message }); + setHarError(msg); + toast.error(msg); + } finally { + setHarImporting(false); + } + }; + + const handleHarExport = async () => { + setHarExporting(true); + try { + const meta = await api.trafficExportHAR({ + host: hostQ, + method, + q: queryQ, + body: bodyQ, + path: pathQ, + status: statusFilter, + rewritten: rewrittenFilter, + respMin: respMinQ, + respMax: respMaxQ, + }); + if (meta.truncated) { + toast.warning( + t("Exported {exported} of {matched} matching exchanges (truncated: {reason})", { + exported: meta.exported, + matched: meta.matched, + reason: meta.truncatedReason ?? "limit", + }), + ); + } else { + toast.success(t("Exported {count} exchanges to HAR", { count: meta.exported })); + } + } catch (e) { + toast.error((e as Error).message); + } finally { + setHarExporting(false); + } + }; + const exchanges = React.useMemo(() => traffic?.exchanges ?? [], [traffic]); const total = traffic?.total ?? exchanges.length; const pageCount = Math.max(1, Math.ceil(total / size)); @@ -396,9 +477,76 @@ export default function TrafficPage() { {t("{count} records", { count: traffic?.count ?? 0 })} + void handleHarFileChange(e)} + /> + + + {harError ? ( + + {harError} + + + ) : null} + + {harSummary ? ( + + +

+ {t("HAR import complete: {imported} imported, {skipped} skipped, {failed} failed", { + imported: harSummary.imported, + skipped: harSummary.skipped, + failed: harSummary.failed, + })} +

+ {harSummary.truncated ? ( +

+ {t("HAR import stopped early at the 32 MiB decoded body cap.")} +

+ ) : null} + {harSummary.errors && harSummary.errors.length > 0 ? ( +
    + {harSummary.errors.slice(0, 5).map((item) => ( +
  • + #{item.index}: {item.reason} +
  • + ))} +
+ ) : null} +
+ +
+ ) : null} + {/* Toolbar */}
diff --git a/web/src/i18n/locales/tr.json b/web/src/i18n/locales/tr.json index c3c3ae0a..e5deaed4 100644 --- a/web/src/i18n/locales/tr.json +++ b/web/src/i18n/locales/tr.json @@ -767,6 +767,7 @@ "Discovery time": "Keşif zamanı", "Discovery time currently ascending, click to toggle sort direction": "Keşif zamanı şu anda artan sırada, sıralama yönünü değiştirmek için tıklayın", "Discovery time currently descending, click to toggle sort direction": "Keşif zamanı şu anda azalan sırada, sıralama yönünü değiştirmek için tıklayın", + "Dismiss": "Kapat", "Dismiss update notice": "Güncelleme bildirimini kapat", "dismissed": "yok sayıldı", "Dismissed": "Yok sayıldı", @@ -925,9 +926,13 @@ "Export failed: {error}": "Dışa aktarma başarısız: {error}", "Export findings": "Bulguları dışa aktar", "Export format": "Dışa aktarma biçimi", + "Export HAR": "HAR dışa aktar", "Export scope": "Dışa aktarma kapsamı", "Export the {count} selected items": "Seçili {count} öğeyi dışa aktar", "Export the current filter results ({count} items)": "Mevcut süzgeç sonuçlarını dışa aktar ({count} öğe)", + "Exported {count} exchanges to HAR": "{count} değişim HAR olarak dışa aktarıldı", + "Exported {exported} of {matched} matching exchanges (truncated: {reason})": "Eşleşen {matched} değişimin {exported} tanesi dışa aktarıldı (kısaltıldı: {reason})", + "Exporting HAR…": "HAR dışa aktarılıyor…", "Exporting…": "Dışa aktarılıyor…", "External MCP tool servers · visibility granted per agent": "Harici MCP araç sunucuları · görünürlük ajan bazında verilir", "Fact": "Olgu", @@ -1070,6 +1075,13 @@ "greater than": "büyüktür", "greater than or equal": "büyük veya eşittir", "Handle automatically after the timeout instead of waiting": "Beklemek yerine zaman aşımından sonra otomatik olarak işle", + "HAR export failed: {error}": "HAR dışa aktarma başarısız: {error}", + "HAR export is not available in mock mode": "HAR dışa aktarma sahte modda kullanılamaz", + "HAR file exceeds the 32 MiB limit": "HAR dosyası 32 MiB sınırını aşıyor", + "HAR import complete: {imported} imported, {skipped} skipped, {failed} failed": "HAR içe aktarma tamamlandı: {imported} içe aktarıldı, {skipped} atlandı, {failed} başarısız", + "HAR import failed: {error}": "HAR içe aktarma başarısız: {error}", + "HAR import is not available in mock mode": "HAR içe aktarma sahte modda kullanılamaz", + "HAR import stopped early at the 32 MiB decoded body cap.": "HAR içe aktarma 32 MiB çözülmüş gövde sınırında erken durdu.", "Hard delete": "Kalıcı silme", "Header": "Başlık", "Header name": "Başlık adı", @@ -1112,6 +1124,8 @@ "Idle": "Boşta", "Ignored": "Yok sayıldı", "Implicit TLS": "Örtük TLS", + "Import HAR": "HAR içe aktar", + "Importing HAR…": "HAR içe aktarılıyor…", "In": "Girdi", "In {input} (incl. cache {cache}) · Out {output}": "Girdi {input} (önbellek {cache} dahil) · Çıktı {output}", "In flight": "Devam eden", diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index 53f14722..339d5419 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -102,6 +102,8 @@ import type { TrafficDetail, TrafficEvidenceRef, TrafficEvidenceRole, + TrafficHARExportMeta, + TrafficHARImportResult, TrafficHost, TrafficReplayRequest, TrafficReplayResult, @@ -886,6 +888,77 @@ export const api = { apply_rules: Boolean(req.apply_rules), }); }, + // Imports a raw HAR 1.2 JSON document into the traffic store. + trafficImportHAR: async (rawJSON: string): Promise => { + if (MOCK) throw new Error(t("HAR import is not available in mock mode")); + return http(`/traffic/import/har`, { + method: "POST", + body: rawJSON, + }); + }, + // Exports filtered traffic as a HAR 1.2 file download and returns truncation metadata. + trafficExportHAR: async ( + opts: { + host?: string; + method?: string; + q?: string; + body?: string; + path?: string; + status?: string; + rewritten?: string; + respMin?: string; + respMax?: string; + } = {}, + ): Promise => { + if (MOCK) throw new Error(t("HAR export is not available in mock mode")); + const qs = new URLSearchParams(); + if (opts.host) qs.set("host", opts.host); + if (opts.method && opts.method !== "all") qs.set("method", opts.method); + if (opts.q) qs.set("q", opts.q); + if (opts.body) qs.set("body", opts.body); + if (opts.path) qs.set("path", opts.path); + if (opts.status && opts.status !== "all") qs.set("status", opts.status); + if (opts.rewritten && opts.rewritten !== "all") qs.set("rewritten", opts.rewritten); + if (opts.respMin) qs.set("resp_min", opts.respMin); + if (opts.respMax) qs.set("resp_max", opts.respMax); + const suffix = qs.toString(); + const token = getToken(); + const r = await fetch(`/api/traffic/export/har${suffix ? `?${suffix}` : ""}`, { + headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}) }, + }); + if (r.status === 401) { + if (typeof window !== "undefined") { + localStorage.removeItem("artex_token"); + document.cookie = "artex_token=; path=/; max-age=0"; + window.location.href = "/login"; + } + throw new Error(t("Unauthorized")); + } + if (!r.ok) { + let msg = String(r.status); + try { + const payload = (await r.json()) as { error?: unknown }; + if (typeof payload.error === "string" && payload.error.trim()) msg = payload.error.trim(); + } catch { + // Keep status fallback. + } + throw new ApiError(t("HAR export failed: {error}", { error: msg }), r.status); + } + const blob = await r.blob(); + const exported = Number(r.headers.get("X-ARTEX-HAR-Exported") ?? "0") || 0; + const matched = Number(r.headers.get("X-ARTEX-HAR-Matched") ?? "0") || 0; + const truncated = r.headers.get("X-ARTEX-HAR-Truncated") === "true"; + const truncatedReason = r.headers.get("X-ARTEX-HAR-Truncated-Reason") ?? undefined; + const objectUrl = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = objectUrl; + a.download = "artex-traffic.har"; + document.body.appendChild(a); + a.click(); + a.remove(); + URL.revokeObjectURL(objectUrl); + return { exported, matched, truncated, truncatedReason }; + }, trafficHosts: () => get<{ hosts: TrafficHost[] }>(`/traffic/hosts`), trafficDeleteHost: (host: string) => del<{ deleted: number }>(`/traffic?host=${encodeURIComponent(host)}`), trafficDeleteHosts: (hosts: string[]) => del<{ deleted: number }>(`/traffic/hosts`, { hosts }), diff --git a/web/src/lib/types.ts b/web/src/lib/types.ts index 9f26e1df..10e6e03c 100644 --- a/web/src/lib/types.ts +++ b/web/src/lib/types.ts @@ -914,6 +914,27 @@ export interface TrafficRewriteStats { sweeps: number; } +export interface TrafficHARImportError { + index: number; + url?: string; + reason: string; +} + +export interface TrafficHARImportResult { + imported: number; + skipped: number; + failed: number; + truncated?: boolean; + errors?: TrafficHARImportError[]; +} + +export interface TrafficHARExportMeta { + exported: number; + matched: number; + truncated: boolean; + truncatedReason?: string; +} + export interface TrafficResp { enabled: boolean; proxy?: string;