Skip to content

armgit / ARTEX

Public Imported from GitHub
0

ARTEX - AI autonomous penetration testing system (English translation; upstream: Autumn-27/ARTEX, AGPL-3.0)

fix(traffic): HAR 1.2 compliance, round-trip IDs, aligned caps, params/cookies, userinfo redaction

BaaRai61d567a771bf
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3154e93..4d8b5c3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,7 +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 <zip> --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-<sha256>` IDs for idempotent re-imports, base64 decoding, 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 HAR 1.2 document in stable `(ts, id)` order, encoding UTF-8 bodies as text and binary bodies as base64, capped at 1,000 entries / 32 MiB 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`.
+- **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-<sha256>` 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
index 648d061..76587cb 100644
--- a/docs/traffic-har.md
+++ b/docs/traffic-har.md
@@ -20,7 +20,7 @@ curl -X POST \
http://127.0.0.1:8787/api/traffic/import/har
```
-The Traffic page also provides an **Import HAR** file picker that reads a `.har` / `.json` file, posts it to this endpoint, displays loading/error state and a count summary, and refreshes the table.
+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
@@ -32,7 +32,7 @@ The request is rejected with `400 Bad Request` naming the reason when:
- `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 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.
+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
@@ -48,21 +48,23 @@ Individual malformed entries (invalid `startedDateTime`, non-HTTP(S) URL, invali
}
```
-### Deterministic IDs & idempotence
+### Deterministic IDs, round-trip fidelity, & idempotence
-Each imported entry is assigned a deterministic ID:
+- **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-<hex(sha256(ts_unix_seconds + NUL + METHOD + NUL + canonical_url + NUL + status + NUL + sha256(req_body) + NUL + sha256(resp_body)))>
```
-- `ts_unix_seconds` is `startedDateTime` parsed as RFC 3339 and truncated to UTC Unix seconds (matching `exchanges.ts`).
-- Existing rows are never overwritten (`INSERT OR IGNORE`): re-importing the same HAR (or an exported HAR from ARTEX) skips existing IDs and increments `skipped`. Duplicate entries inside the same HAR file are likewise deduplicated into `skipped`.
+ `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, and base64
+### 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.
-- `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"`.
+- **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`.
@@ -91,19 +93,29 @@ It reuses the same filter parser and SQL predicate builder as `GET /api/traffic`
- `host`, `method`, `path`, `status`, `q`, `body`, `rewritten` (`all` | `rewritten` | `original` | `true` | `false`), `resp_min`, `resp_max`.
-### Mapping & fidelity
+### HAR 1.2 compliance & unknown placeholders
- `log.version` is `"1.2"` and `log.creator` is `{"name": "ARTEX", "version": "<build-version>"}`.
-- `startedDateTime` is formatted from `exchanges.ts` as UTC RFC 3339.
-- Request and response headers are parsed from the stored raw heads (`req_head` / `resp_head`). ARTEX does **not** invent `time`, `serverIPAddress`, or headers that are not present in the store.
+- `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 & truncation reporting
+### Export limits, import-compatibility invariant, & truncation reporting
| Limit | Default | `truncatedReason` |
|---|---|---|
| Exported entries | 1,000 | `max_entries` |
-| Total raw request + response body bytes | 32 MiB | `max_bytes` |
+| 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:
diff --git a/server/traffic_har_test.go b/server/traffic_har_test.go
index 1036d51..1b49837 100644
--- a/server/traffic_har_test.go
+++ b/server/traffic_har_test.go
@@ -197,3 +197,60 @@ func TestTrafficHAREndpointsRequireAuth(t *testing.T) {
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
index 70cd799..98681b0 100644
--- a/traffic/har.go
+++ b/traffic/har.go
@@ -32,19 +32,28 @@ const (
// DefaultHARMaxExportEntries caps how many exchanges a single HAR export emits.
DefaultHARMaxExportEntries = 1000
- // DefaultHARMaxExportBytes caps total raw request+response body bytes emitted
- // in a single HAR export.
- DefaultHARMaxExportBytes int64 = 32 << 20
+ // 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 minimal HAR 1.2 envelope. Only fields backed by the traffic store
-// are populated on export; timings, serverIPAddress, and synthetic headers are
-// never invented.
+// 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"`
}
@@ -63,39 +72,75 @@ type HARCreator struct {
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,omitempty"`
+ 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"`
- Text string `json:"text,omitempty"`
- Encoding string `json:"encoding,omitempty"`
+ 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,omitempty"`
- HTTPVersion string `json:"httpVersion,omitempty"`
+ 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,omitempty"`
+ MimeType string `json:"mimeType"`
Text string `json:"text,omitempty"`
Encoding string `json:"encoding,omitempty"`
}
@@ -132,22 +177,27 @@ type HARImportResult struct {
type HARExportOptions struct {
CreatorVersion string
MaxEntries int
- MaxTotalBytes int64
+ 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
+ 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. Entries receive a deterministic ID so re-importing the same
-// HAR is idempotent and skips existing rows. Imported traffic is never passed
-// through capture rewrite rules and never gains exchange_rewrites rows.
+// 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")
@@ -170,7 +220,11 @@ func (t *Traffic) ImportHAR(raw []byte, opts HARImportOptions) (HARImportResult,
var res HARImportResult
addErr := func(idx int, rawURL, reason string) {
if len(res.Errors) < maxHARImportErrors {
- res.Errors = append(res.Errors, HARImportError{Index: idx, URL: rawURL, Reason: reason})
+ res.Errors = append(res.Errors, HARImportError{
+ Index: idx,
+ URL: redactURLUserinfo(rawURL),
+ Reason: reason,
+ })
}
}
@@ -262,8 +316,12 @@ func parseHAREntry(entry HAREntry) (parsedHARExchange, error) {
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", entry.Request.URL)
+ 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)
@@ -272,23 +330,48 @@ func parseHAREntry(entry HAREntry) (parsedHARExchange, error) {
return parsedHARExchange{}, fmt.Errorf("invalid response status %d", entry.Response.Status)
}
- reqHeaderText, reqCT, err := formatHARHeaders(entry.Request.Headers)
+ reqHeaderText, reqCT, hasReqCookie, err := formatHARHeaders(entry.Request.Headers, "Cookie")
if err != nil {
return parsedHARExchange{}, fmt.Errorf("invalid request headers: %w", err)
}
- respHeaderText, respHeaderCT, err := formatHARHeaders(entry.Response.Headers)
+ 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 {
- 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)
+ 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)
@@ -316,6 +399,9 @@ func parseHAREntry(entry HAREntry) (parsedHARExchange, error) {
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,
@@ -336,7 +422,7 @@ func parseHAREntry(entry HAREntry) (parsedHARExchange, error) {
// 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.
+// 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)
@@ -345,12 +431,56 @@ func harExchangeID(ts int64, method, rawURL string, status int, reqBody, respBod
return "har-" + hex.EncodeToString(h.Sum(nil))
}
-func formatHARHeaders(headers []HARHeader) (formatted string, contentType string, err error) {
+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 "", "", errors.New("empty header 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
@@ -359,20 +489,90 @@ func formatHARHeaders(headers []HARHeader) (formatted string, contentType string
continue
}
if !validHeaderName(name) {
- return "", "", fmt.Errorf("invalid header name %q", h.Name)
+ return "", "", false, fmt.Errorf("invalid header name %q", h.Name)
}
if strings.ContainsAny(h.Value, "\r\n\x00") {
- return "", "", fmt.Errorf("header %s contains a line break or NUL byte", name)
+ 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, nil
+ 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) {
@@ -467,10 +667,11 @@ VALUES(?,?,?,?,?,?,?)`,
return true, nil
}
-// ExportHAR exports exchanges matching f as a HAR 1.2 document in stable
-// chronological order (ts ASC, id ASC), capped by opts.MaxEntries and
-// opts.MaxTotalBytes. Truncation is reported in both HARExportMeta and the
-// HAR 1.2 custom fields _truncated / _truncatedReason / _totalMatched.
+// 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")
@@ -481,6 +682,9 @@ func (t *Traffic) ExportHAR(f PageQuery, opts HARExportOptions) (HAR, HARExportM
if opts.MaxTotalBytes <= 0 {
opts.MaxTotalBytes = DefaultHARMaxExportBytes
}
+ if opts.MaxJSONBytes <= 0 {
+ opts.MaxJSONBytes = DefaultHARMaxExportJSONBytes
+ }
creatorVer := strings.TrimSpace(opts.CreatorVersion)
if creatorVer == "" {
creatorVer = "dev"
@@ -532,28 +736,34 @@ func (t *Traffic) ExportHAR(f PageQuery, opts HARExportOptions) (HAR, HARExportM
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
}
- entryBytes := int64(len(reqBytes) + len(respBytes))
- if meta.TotalBytes+entryBytes > opts.MaxTotalBytes {
+ entryRawBytes := int64(len(reqHead) + len(reqBytes) + len(respHead) + len(respBytes))
+ if meta.TotalBytes+entryRawBytes > opts.MaxTotalBytes {
meta.Truncated = true
meta.TruncatedReason = "max_bytes"
break
}
- meta.TotalBytes += entryBytes
reqProto, reqHeaders := parseStoredRequestHead(reqHead)
respProto, respStatusText, respHeaders := parseStoredResponseHead(respHead)
harReq := HARRequest{
Method: r.method,
- URL: r.rawURL,
+ URL: redactURLUserinfo(r.rawURL),
HTTPVersion: reqProto,
+ Cookies: []HARCookie{},
Headers: reqHeaders,
+ QueryString: []HARParam{},
+ HeadersSize: -1,
BodySize: len(reqBytes),
}
if len(reqBytes) > 0 {
@@ -577,16 +787,37 @@ func (t *Traffic) ExportHAR(f PageQuery, opts HARExportOptions) (HAR, HARExportM
Status: r.status,
StatusText: respStatusText,
HTTPVersion: respProto,
+ Cookies: []HARCookie{},
Headers: respHeaders,
Content: harContent,
+ RedirectURL: "",
+ HeadersSize: -1,
BodySize: len(respBytes),
}
- entries = append(entries, HAREntry{
+ 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 {
diff --git a/traffic/har_test.go b/traffic/har_test.go
index 375ce77..98f3d5b 100644
--- a/traffic/har_test.go
+++ b/traffic/har_test.go
@@ -204,13 +204,64 @@ func TestHARRoundTripPlainBase64BinaryEmptyAndLargeBlob(t *testing.T) {
t.Fatalf("ExportHAR entries = %d, want 4", len(exported.Log.Entries))
}
- // Verify no invented fields (time, serverIPAddress) in marshaled HAR JSON.
+ // 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"`) || strings.Contains(string(rawExported), `"time":`) {
- t.Fatalf("exported HAR invented prohibited fields: %s", string(rawExported))
+ 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.
@@ -432,8 +483,9 @@ VALUES(?,?,?,?,?)`, id, "GET /"+id+" HTTP/1.1\nHost: "+host, []byte{}, "HTTP/1.1
t.Fatalf("entry-capped log fields = %+v", docEntryCap.Log)
}
- // Truncation by MaxTotalBytes.
- docByteCap, metaByteCap, err := tr.ExportHAR(PageQuery{RespMin: -1, RespMax: -1}, HARExportOptions{MaxTotalBytes: 15})
+ // 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)
}
@@ -444,3 +496,322 @@ VALUES(?,?,?,?,?)`, id, "GET /"+id+" HTTP/1.1\nHost: "+host, []byte{}, "HTTP/1.1
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:[email protected]/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:[email protected]/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))
+ }
+}