summaryrefslogtreecommitdiff
path: root/internal/store/har.go
blob: 047300a53fe513997153dabeefbf88ae964cb40f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
package store

import (
	"encoding/json"
	"fmt"
	"net"
	"net/http"
	"net/url"
	"strings"
	"time"
)

// HAR 1.2 — https://w3c.github.io/web-performance/specs/HAR/Overview.html

type HAR struct {
	Log HARLog `json:"log"`
}

type HARLog struct {
	Version string     `json:"version"`
	Creator HARCreator `json:"creator"`
	Entries []HAREntry `json:"entries"`
}

type HARCreator struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

type HAREntry struct {
	StartedDateTime string      `json:"startedDateTime"`
	Time            int64       `json:"time"`
	Request         HARRequest  `json:"request"`
	Response        HARResponse `json:"response"`
	Timings         HARTimings  `json:"timings"`
}

type HARRequest struct {
	Method      string         `json:"method"`
	URL         string         `json:"url"`
	HTTPVersion string         `json:"httpVersion"`
	Headers     []HARNameValue `json:"headers"`
	QueryString []HARNameValue `json:"queryString"`
	PostData    *HARPostData   `json:"postData,omitempty"`
	HeadersSize int            `json:"headersSize"`
	BodySize    int            `json:"bodySize"`
}

type HARResponse struct {
	Status      int            `json:"status"`
	StatusText  string         `json:"statusText"`
	HTTPVersion string         `json:"httpVersion"`
	Headers     []HARNameValue `json:"headers"`
	Content     HARContent     `json:"content"`
	RedirectURL string         `json:"redirectURL"`
	HeadersSize int            `json:"headersSize"`
	BodySize    int            `json:"bodySize"`
}

type HARNameValue struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

type HARPostData struct {
	MimeType string `json:"mimeType"`
	Text     string `json:"text"`
}

type HARContent struct {
	Size     int    `json:"size"`
	MimeType string `json:"mimeType"`
	Text     string `json:"text,omitempty"`
}

type HARTimings struct {
	Send    int64 `json:"send"`
	Wait    int64 `json:"wait"`
	Receive int64 `json:"receive"`
}

// ExportHAR serialises the given transactions into a HAR 1.2 JSON byte slice.
// Pass only the transactions you want exported — scope and out-of-scope
// filtering is the caller's responsibility.
func ExportHAR(txs []Transaction) ([]byte, error) {
	har := HAR{
		Log: HARLog{
			Version: "1.2",
			Creator: HARCreator{
				Name:    "Shiv",
				Version: "1.0",
			},
			Entries: make([]HAREntry, 0, len(txs)),
		},
	}

	for _, tx := range txs {
		entry := HAREntry{
			StartedDateTime: tx.Timestamp.UTC().Format(time.RFC3339),
			Time:            tx.DurationMs,
			Request:         buildHARRequest(tx),
			Response:        buildHARResponse(tx),
			Timings: HARTimings{
				Send:    0,
				Wait:    tx.DurationMs,
				Receive: 0,
			},
		}
		har.Log.Entries = append(har.Log.Entries, entry)
	}

	data, err := json.MarshalIndent(har, "", "  ")
	if err != nil {
		return nil, fmt.Errorf("har: marshal: %w", err)
	}
	return data, nil
}

func stripDefaultPort(rawURL string) string {
	for _, prefix := range []string{"https://", "http://"} {
		if !strings.HasPrefix(rawURL, prefix) {
			continue
		}
		rest := rawURL[len(prefix):]
		slash := strings.Index(rest, "/")
		if slash < 0 {
			slash = len(rest)
		}
		host := rest[:slash]
		path := rest[slash:]
		h, port, err := net.SplitHostPort(host)
		if err != nil {
			return rawURL
		}
		if (prefix == "https://" && port == "443") || (prefix == "http://" && port == "80") {
			return prefix + h + path
		}
		return rawURL
	}
	return rawURL
}

func buildHARRequest(tx Transaction) HARRequest {
	headers := make([]HARNameValue, 0, len(tx.ReqHeaders))
	for k, vals := range tx.ReqHeaders {
		for _, v := range vals {
			headers = append(headers, HARNameValue{Name: k, Value: v})
		}
	}

	httpVersion := tx.Proto
	if httpVersion == "" {
		httpVersion = "HTTP/1.1"
	}

	req := HARRequest{
		Method:      tx.Method,
		URL:         stripDefaultPort(tx.URL),
		HTTPVersion: httpVersion,
		Headers:     headers,
		QueryString: extractQueryString(tx.URL),
		HeadersSize: -1,
		BodySize:    len(tx.ReqBody),
	}

	if len(tx.ReqBody) > 0 {
		mimeType := tx.ReqHeaders.Get("Content-Type")
		if mimeType == "" {
			mimeType = "application/octet-stream"
		}
		req.PostData = &HARPostData{
			MimeType: mimeType,
			Text:     string(tx.ReqBody),
		}
	}

	return req
}

func buildHARResponse(tx Transaction) HARResponse {
	headers := make([]HARNameValue, 0, len(tx.RespHeaders))
	for k, vals := range tx.RespHeaders {
		for _, v := range vals {
			headers = append(headers, HARNameValue{Name: k, Value: v})
		}
	}

	httpVersion := tx.Proto
	if httpVersion == "" {
		httpVersion = "HTTP/1.1"
	}

	mimeType := tx.RespHeaders.Get("Content-Type")
	if mimeType == "" {
		mimeType = "application/octet-stream"
	}

	redirectURL := tx.RespHeaders.Get("Location")

	return HARResponse{
		Status:      tx.StatusCode,
		StatusText:  statusText(tx.StatusCode),
		HTTPVersion: httpVersion,
		Headers:     headers,
		Content: HARContent{
			Size:     len(tx.RespBody),
			MimeType: mimeType,
			Text:     string(tx.RespBody),
		},
		RedirectURL: redirectURL,
		HeadersSize: -1,
		BodySize:    len(tx.RespBody),
	}
}

func extractQueryString(rawURL string) []HARNameValue {
	idx := strings.Index(rawURL, "?")
	if idx < 0 {
		return []HARNameValue{}
	}
	parsed, err := url.ParseQuery(rawURL[idx+1:])
	if err != nil || len(parsed) == 0 {
		return []HARNameValue{}
	}
	pairs := make([]HARNameValue, 0, len(parsed))
	for k, vals := range parsed {
		for _, v := range vals {
			pairs = append(pairs, HARNameValue{Name: k, Value: v})
		}
	}
	return pairs
}

func statusText(code int) string {
	if t := http.StatusText(code); t != "" {
		return t
	}
	return fmt.Sprintf("%d", code)
}