summaryrefslogtreecommitdiffstats
path: root/internal/submit/types_test.go
blob: 16a2b849bfc5a98c0a2147d47ee9cf4f0b71e3c3 (plain) (blame)
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
package submit

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"
	"testing/fstest"
	"time"

	"n2usenet/internal/config"
	"n2usenet/internal/storage"
)

func newTestApp(t *testing.T) *App {
	t.Helper()
	app, err := NewApp(config.Config{}, nil, nil, storage.NewReplayCache(time.Minute), fstest.MapFS{}, "<!doctype html>")
	if err != nil {
		t.Fatalf("NewApp returned error: %v", err)
	}
	return app
}

func TestCSRFCookieHasNoElapsedTimeLimit(t *testing.T) {
	app := newTestApp(t)
	req := httptest.NewRequest(http.MethodGet, "/", nil)
	rec := httptest.NewRecorder()

	app.handleIndex(rec, req)

	cookies := rec.Result().Cookies()
	if len(cookies) != 1 {
		t.Fatalf("unexpected cookie count: got %d want 1", len(cookies))
	}
	cookie := cookies[0]
	if cookie.Name != "m2u_csrf" {
		t.Fatalf("unexpected cookie name: %q", cookie.Name)
	}
	if cookie.MaxAge != 0 || !cookie.Expires.IsZero() {
		t.Fatalf("CSRF cookie has an elapsed-time expiry: MaxAge=%d Expires=%v", cookie.MaxAge, cookie.Expires)
	}
	if !cookie.HttpOnly || cookie.SameSite != http.SameSiteStrictMode {
		t.Fatal("CSRF cookie security attributes were weakened")
	}
}

func TestCSRFRefreshIssuesValidToken(t *testing.T) {
	app := newTestApp(t)
	req := httptest.NewRequest(http.MethodGet, "/csrf", nil)
	rec := httptest.NewRecorder()

	app.handleCSRF(rec, req)

	if got := rec.Header().Get("Cache-Control"); got != "no-store" {
		t.Fatalf("unexpected Cache-Control: %q", got)
	}
	var body map[string]string
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("decode CSRF response: %v", err)
	}
	token := body["token"]
	if token == "" {
		t.Fatal("CSRF refresh returned an empty token")
	}
	cookies := rec.Result().Cookies()
	if len(cookies) != 1 {
		t.Fatalf("unexpected cookie count: got %d want 1", len(cookies))
	}

	form := url.Values{"csrf_token": {token}}
	post := httptest.NewRequest(http.MethodPost, "/submit", strings.NewReader(form.Encode()))
	post.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	post.AddCookie(cookies[0])
	if err := post.ParseForm(); err != nil {
		t.Fatalf("parse form: %v", err)
	}
	if !app.verifyCSRF(post) {
		t.Fatal("refreshed CSRF token did not verify")
	}
}

func TestCSRFCookieSurvivesRestartWithPersistentKey(t *testing.T) {
	cfg := config.Config{Security: config.SecurityConfig{CSRFKey: []byte(strings.Repeat("k", 32))}}
	newApp := func() *App {
		app, err := NewApp(cfg, nil, nil, storage.NewReplayCache(time.Minute), fstest.MapFS{}, "<!doctype html>")
		if err != nil {
			t.Fatalf("NewApp returned error: %v", err)
		}
		return app
	}

	first := httptest.NewRecorder()
	newApp().handleCSRF(first, httptest.NewRequest(http.MethodGet, "/csrf", nil))
	var firstBody map[string]string
	if err := json.Unmarshal(first.Body.Bytes(), &firstBody); err != nil {
		t.Fatalf("decode first CSRF response: %v", err)
	}
	cookies := first.Result().Cookies()
	if len(cookies) != 1 {
		t.Fatalf("unexpected cookie count: %d", len(cookies))
	}

	requestAfterRestart := httptest.NewRequest(http.MethodGet, "/csrf", nil)
	requestAfterRestart.AddCookie(cookies[0])
	second := httptest.NewRecorder()
	newApp().handleCSRF(second, requestAfterRestart)
	var secondBody map[string]string
	if err := json.Unmarshal(second.Body.Bytes(), &secondBody); err != nil {
		t.Fatalf("decode second CSRF response: %v", err)
	}
	if secondBody["token"] != firstBody["token"] {
		t.Fatal("restart rotated a still-valid session token")
	}
	if got := len(second.Result().Cookies()); got != 0 {
		t.Fatalf("valid session unexpectedly rotated %d cookies", got)
	}
}

type transportStateStub struct {
	ready bool
}

func (s *transportStateStub) Ready() bool       { return s.ready }
func (s *transportStateStub) MarkSuccess()      { s.ready = true }
func (s *transportStateStub) MarkFailure(error) { s.ready = false }

func TestReadinessUsesCachedTransportState(t *testing.T) {
	app := newTestApp(t)
	state := &transportStateStub{}
	app.transport = state

	recorder := httptest.NewRecorder()
	app.handleReadiness(recorder, httptest.NewRequest(http.MethodGet, "/readyz", nil))
	if recorder.Code != http.StatusServiceUnavailable {
		t.Fatalf("unready status = %d, want %d", recorder.Code, http.StatusServiceUnavailable)
	}

	state.ready = true
	recorder = httptest.NewRecorder()
	app.handleReadiness(recorder, httptest.NewRequest(http.MethodGet, "/readyz", nil))
	if recorder.Code != http.StatusOK {
		t.Fatalf("ready status = %d, want %d", recorder.Code, http.StatusOK)
	}
}

func TestSuccessResponseJSONNoStore(t *testing.T) {
	app := newTestApp(t)
	req := httptest.NewRequest(http.MethodPost, "/submit", nil)
	req.Header.Set("Accept", "application/json")
	rec := httptest.NewRecorder()

	app.successResponse(rec, req, "<test@example.net>")

	if rec.Code != http.StatusOK {
		t.Fatalf("unexpected status: got %d want %d", rec.Code, http.StatusOK)
	}
	if got := rec.Header().Get("Cache-Control"); got != "no-store" {
		t.Fatalf("unexpected Cache-Control: %q", got)
	}
	if got := rec.Header().Get("Clear-Site-Data"); got != "\"storage\"" {
		t.Fatalf("unexpected Clear-Site-Data: %q", got)
	}
	if got := rec.Header().Get("Content-Type"); !strings.Contains(got, "application/json") {
		t.Fatalf("unexpected Content-Type: %q", got)
	}
	var body map[string]string
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("failed to decode response body: %v", err)
	}
	if body["messageId"] != "<test@example.net>" {
		t.Fatalf("unexpected messageId: %q", body["messageId"])
	}
}

func TestErrorResponseJSONNoStore(t *testing.T) {
	app := newTestApp(t)
	req := httptest.NewRequest(http.MethodPost, "/submit", nil)
	req.Header.Set("Accept", "application/json")
	rec := httptest.NewRecorder()

	app.errorResponse(rec, req, http.StatusBadRequest, "Validation failed.")

	if rec.Code != http.StatusBadRequest {
		t.Fatalf("unexpected status: got %d want %d", rec.Code, http.StatusBadRequest)
	}
	if got := rec.Header().Get("Cache-Control"); got != "no-store" {
		t.Fatalf("unexpected Cache-Control: %q", got)
	}
	if got := rec.Header().Get("Content-Type"); !strings.Contains(got, "application/json") {
		t.Fatalf("unexpected Content-Type: %q", got)
	}
	var body map[string]string
	if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
		t.Fatalf("failed to decode response body: %v", err)
	}
	if body["error"] != "Validation failed." {
		t.Fatalf("unexpected error body: %q", body["error"])
	}
}