File size: 10,531 Bytes
ea775bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
package api

import (
	"encoding/base64"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/Resinat/Resin/internal/requestlog"
)

// HandleListRequestLogs handles GET /api/v1/request-logs.
// Query params: from, to (RFC3339Nano), limit, cursor,
// platform_id, platform_name, account, target_host, egress_ip, proxy_type, net_ok, http_status, fuzzy.
func HandleListRequestLogs(repo *requestlog.Repo) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Query().Get("offset") != "" {
			writeInvalidArgument(w, "offset: not supported for request-logs; use cursor")
			return
		}

		limit, ok := parseRequestLogLimitQuery(w, r)
		if !ok {
			return
		}

		cursor, ok := parseRequestLogCursorQuery(w, r)
		if !ok {
			return
		}

		q := r.URL.Query()
		f := requestlog.ListFilter{
			PlatformID:   q.Get("platform_id"),
			PlatformName: q.Get("platform_name"),
			Account:      q.Get("account"),
			TargetHost:   q.Get("target_host"),
			EgressIP:     q.Get("egress_ip"),
			Limit:        limit,
			Cursor:       cursor,
		}

		if v := q.Get("from"); v != "" {
			t, err := time.Parse(time.RFC3339Nano, v)
			if err != nil {
				writeInvalidArgument(w, "from: invalid RFC3339 timestamp")
				return
			}
			f.After = t.UnixNano()
		}
		if v := q.Get("to"); v != "" {
			t, err := time.Parse(time.RFC3339Nano, v)
			if err != nil {
				writeInvalidArgument(w, "to: invalid RFC3339 timestamp")
				return
			}
			f.Before = t.UnixNano()
		}
		if f.After > 0 && f.Before > 0 && f.After >= f.Before {
			writeInvalidArgument(w, "from: must be before to")
			return
		}

		proxyType, ok := parseBoundedIntQuery(w, r, "proxy_type", 1, 3, "proxy_type: must be 1, 2, or 3")
		if !ok {
			return
		}
		f.ProxyType = proxyType

		netOK, ok := parseStrictBoolQuery(w, r, "net_ok")
		if !ok {
			return
		}
		f.NetOK = netOK

		httpStatus, ok := parseBoundedIntQuery(w, r, "http_status", 100, 599, "http_status: must be in [100,599]")
		if !ok {
			return
		}
		f.HTTPStatus = httpStatus

		fuzzy, ok := parseStrictBoolQuery(w, r, "fuzzy")
		if !ok {
			return
		}
		if fuzzy != nil {
			f.Fuzzy = *fuzzy
		}

		rows, hasMore, nextCursor, err := repo.List(f)
		if err != nil {
			WriteError(w, http.StatusInternalServerError, "INTERNAL", err.Error())
			return
		}

		items := make([]logListItem, 0, len(rows))
		for _, row := range rows {
			items = append(items, toLogListItem(row))
		}

		resp := requestLogPageResponse{
			Items:   items,
			Limit:   limit,
			HasMore: hasMore,
		}
		if nextCursor != nil {
			resp.NextCursor = encodeRequestLogCursor(*nextCursor)
		}
		WriteJSON(w, http.StatusOK, resp)
	})
}

func parseRequestLogLimitQuery(w http.ResponseWriter, r *http.Request) (int, bool) {
	limit := defaultPageLimit
	v := r.URL.Query().Get("limit")
	if v == "" {
		return limit, true
	}
	n, err := strconv.Atoi(v)
	if err != nil || n < 0 {
		writeInvalidArgument(w, "limit: must be a non-negative integer")
		return 0, false
	}
	if n > maxPageLimit {
		writeInvalidArgument(w, "limit: must be <= "+strconv.Itoa(maxPageLimit))
		return 0, false
	}
	if n > 0 {
		limit = n
	}
	return limit, true
}

func parseRequestLogCursorQuery(w http.ResponseWriter, r *http.Request) (*requestlog.ListCursor, bool) {
	v := r.URL.Query().Get("cursor")
	if v == "" {
		return nil, true
	}
	raw, err := base64.RawURLEncoding.DecodeString(v)
	if err != nil {
		writeInvalidArgument(w, "cursor: invalid format")
		return nil, false
	}
	parts := strings.SplitN(string(raw), ":", 2)
	if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
		writeInvalidArgument(w, "cursor: invalid format")
		return nil, false
	}
	tsNs, err := strconv.ParseInt(parts[0], 10, 64)
	if err != nil {
		writeInvalidArgument(w, "cursor: invalid format")
		return nil, false
	}
	return &requestlog.ListCursor{
		TsNs: tsNs,
		ID:   parts[1],
	}, true
}

func encodeRequestLogCursor(c requestlog.ListCursor) string {
	raw := strconv.FormatInt(c.TsNs, 10) + ":" + c.ID
	return base64.RawURLEncoding.EncodeToString([]byte(raw))
}

type requestLogPageResponse struct {
	Items      []logListItem `json:"items"`
	Limit      int           `json:"limit"`
	HasMore    bool          `json:"has_more"`
	NextCursor string        `json:"next_cursor,omitempty"`
}

// HandleGetRequestLog handles GET /api/v1/request-logs/{log_id}.
func HandleGetRequestLog(repo *requestlog.Repo) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		logID := r.PathValue("log_id")
		if logID == "" {
			writeInvalidArgument(w, "log_id: is required")
			return
		}

		row, err := repo.GetByID(logID)
		if err != nil {
			WriteError(w, http.StatusInternalServerError, "INTERNAL", err.Error())
			return
		}
		if row == nil {
			WriteError(w, http.StatusNotFound, "NOT_FOUND", "not found")
			return
		}

		WriteJSON(w, http.StatusOK, toLogListItem(*row))
	})
}

// HandleGetRequestLogPayloads handles GET /api/v1/request-logs/{log_id}/payloads.
// Returns base64-encoded payloads with truncation metadata.
func HandleGetRequestLogPayloads(repo *requestlog.Repo) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		logID := r.PathValue("log_id")
		if logID == "" {
			writeInvalidArgument(w, "log_id: is required")
			return
		}

		logRow, err := repo.GetByID(logID)
		if err != nil {
			WriteError(w, http.StatusInternalServerError, "INTERNAL", err.Error())
			return
		}
		if logRow == nil {
			WriteError(w, http.StatusNotFound, "NOT_FOUND", "not found")
			return
		}

		payload, err := repo.GetPayloads(logID)
		if err != nil {
			WriteError(w, http.StatusInternalServerError, "INTERNAL", err.Error())
			return
		}

		resp := payloadResponse{
			Truncated: truncatedInfo{
				ReqHeaders:  logRow.ReqHeadersTruncated,
				ReqBody:     logRow.ReqBodyTruncated,
				RespHeaders: logRow.RespHeadersTruncated,
				RespBody:    logRow.RespBodyTruncated,
			},
		}
		if payload != nil {
			resp.ReqHeadersB64 = base64.StdEncoding.EncodeToString(payload.ReqHeaders)
			resp.ReqBodyB64 = base64.StdEncoding.EncodeToString(payload.ReqBody)
			resp.RespHeadersB64 = base64.StdEncoding.EncodeToString(payload.RespHeaders)
			resp.RespBodyB64 = base64.StdEncoding.EncodeToString(payload.RespBody)
		}

		WriteJSON(w, http.StatusOK, resp)
	})
}

func parseBoundedIntQuery(
	w http.ResponseWriter,
	r *http.Request,
	key string,
	min int,
	max int,
	errMsg string,
) (*int, bool) {
	v := r.URL.Query().Get(key)
	if v == "" {
		return nil, true
	}
	n, err := strconv.Atoi(v)
	if err != nil || n < min || n > max {
		writeInvalidArgument(w, errMsg)
		return nil, false
	}
	return &n, true
}

func parseStrictBoolQuery(w http.ResponseWriter, r *http.Request, key string) (*bool, bool) {
	v := r.URL.Query().Get(key)
	if v == "" {
		return nil, true
	}
	switch v {
	case "true":
		b := true
		return &b, true
	case "false":
		b := false
		return &b, true
	default:
		writeInvalidArgument(w, key+": must be true or false")
		return nil, false
	}
}

// --- Response types ---

type logListItem struct {
	ID                   string `json:"id"`
	Ts                   string `json:"ts"`
	ProxyType            int    `json:"proxy_type"`
	ClientIP             string `json:"client_ip"`
	PlatformID           string `json:"platform_id"`
	PlatformName         string `json:"platform_name"`
	Account              string `json:"account"`
	TargetHost           string `json:"target_host"`
	TargetURL            string `json:"target_url"`
	NodeHash             string `json:"node_hash"`
	NodeTag              string `json:"node_tag"`
	EgressIP             string `json:"egress_ip"`
	DurationMs           int64  `json:"duration_ms"`
	NetOK                bool   `json:"net_ok"`
	HTTPMethod           string `json:"http_method"`
	HTTPStatus           int    `json:"http_status"`
	ResinError           string `json:"resin_error"`
	UpstreamStage        string `json:"upstream_stage"`
	UpstreamErrKind      string `json:"upstream_err_kind"`
	UpstreamErrno        string `json:"upstream_errno"`
	UpstreamErrMsg       string `json:"upstream_err_msg"`
	IngressBytes         int64  `json:"ingress_bytes"`
	EgressBytes          int64  `json:"egress_bytes"`
	PayloadPresent       bool   `json:"payload_present"`
	ReqHeadersLen        int    `json:"req_headers_len"`
	ReqBodyLen           int    `json:"req_body_len"`
	RespHeadersLen       int    `json:"resp_headers_len"`
	RespBodyLen          int    `json:"resp_body_len"`
	ReqHeadersTruncated  bool   `json:"req_headers_truncated"`
	ReqBodyTruncated     bool   `json:"req_body_truncated"`
	RespHeadersTruncated bool   `json:"resp_headers_truncated"`
	RespBodyTruncated    bool   `json:"resp_body_truncated"`
}

func toLogListItem(s requestlog.LogSummary) logListItem {
	return logListItem{
		ID:                   s.ID,
		Ts:                   time.Unix(0, s.TsNs).UTC().Format(time.RFC3339Nano),
		ProxyType:            s.ProxyType,
		ClientIP:             s.ClientIP,
		PlatformID:           s.PlatformID,
		PlatformName:         s.PlatformName,
		Account:              s.Account,
		TargetHost:           s.TargetHost,
		TargetURL:            s.TargetURL,
		NodeHash:             s.NodeHash,
		NodeTag:              s.NodeTag,
		EgressIP:             s.EgressIP,
		DurationMs:           s.DurationNs / 1e6,
		NetOK:                s.NetOK,
		HTTPMethod:           s.HTTPMethod,
		HTTPStatus:           s.HTTPStatus,
		ResinError:           s.ResinError,
		UpstreamStage:        s.UpstreamStage,
		UpstreamErrKind:      s.UpstreamErrKind,
		UpstreamErrno:        s.UpstreamErrno,
		UpstreamErrMsg:       s.UpstreamErrMsg,
		IngressBytes:         s.IngressBytes,
		EgressBytes:          s.EgressBytes,
		PayloadPresent:       s.PayloadPresent,
		ReqHeadersLen:        s.ReqHeadersLen,
		ReqBodyLen:           s.ReqBodyLen,
		RespHeadersLen:       s.RespHeadersLen,
		RespBodyLen:          s.RespBodyLen,
		ReqHeadersTruncated:  s.ReqHeadersTruncated,
		ReqBodyTruncated:     s.ReqBodyTruncated,
		RespHeadersTruncated: s.RespHeadersTruncated,
		RespBodyTruncated:    s.RespBodyTruncated,
	}
}

type payloadResponse struct {
	ReqHeadersB64  string        `json:"req_headers_b64"`
	ReqBodyB64     string        `json:"req_body_b64"`
	RespHeadersB64 string        `json:"resp_headers_b64"`
	RespBodyB64    string        `json:"resp_body_b64"`
	Truncated      truncatedInfo `json:"truncated"`
}

type truncatedInfo struct {
	ReqHeaders  bool `json:"req_headers"`
	ReqBody     bool `json:"req_body"`
	RespHeaders bool `json:"resp_headers"`
	RespBody    bool `json:"resp_body"`
}