oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1package docs_test
2
3import (
4 "html"
5 "net/http"
6 "net/http/httptest"
7 "strings"
8 "testing"
9
10 "github.com/carlosframework/docs/internal/docs"
11)
12
13// TestSignInRequiredForEverything is the brief's own literal test,
14// extended per fix round 1: a create endpoint reachable without a
15// session is the entire problem this task exists to solve, and a
16// "does the list require sign-in?" GET-only check reads straight
17// past it — a route moved out of the RequireSession group by a
18// future refactor would go undetected here otherwise. POST
19// /documents is sent with Sec-Fetch-Site: same-origin so csrf.Protect
20// (mounted above RequireSession in the middleware chain) lets it
21// through, isolating what actually refuses it: RequireSession itself,
22// not the CSRF check. A signed-out GET/HEAD redirects to sign-in;
23// anything else — POST included — 403s (rastrillo/auth's own
24// refuseSession, docs/site's own contract).
25func TestSignInRequiredForEverything(t *testing.T) {
26 app, err := docs.NewForTest(t)
27 if err != nil {
28 t.Fatal(err)
29 }
30 for _, path := range []string{"/", "/d/anything"} {
31 req := httptest.NewRequest(http.MethodGet, path, nil)
32 rec := httptest.NewRecorder()
33 app.Handler().ServeHTTP(rec, req)
34 if rec.Code != http.StatusSeeOther && rec.Code != http.StatusFound {
35 t.Errorf("GET %s signed out: status %d, want a redirect to sign-in", path, rec.Code)
36 }
37 }
38
39 form := strings.NewReader("title=Should+not+be+created")
40 req := httptest.NewRequest(http.MethodPost, "/documents", form)
41 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
42 req.Header.Set("Sec-Fetch-Site", "same-origin")
43 rec := httptest.NewRecorder()
44 app.Handler().ServeHTTP(rec, req)
45 if rec.Code != http.StatusForbidden {
46 t.Errorf("POST /documents signed out: status %d, want %d (RequireSession's own refusal, not a redirect)", rec.Code, http.StatusForbidden)
47 }
48}
49
50// TestMagicLinkSignsSomebodyIn is the brief's own literal test:
51// TestSignIn mints a link without sending real mail, and following it
52// must establish a real session (a cookie), not merely 200.
53func TestMagicLinkSignsSomebodyIn(t *testing.T) {
54 app, err := docs.NewForTest(t)
55 if err != nil {
56 t.Fatal(err)
57 }
58 link, err := app.TestSignIn(t, "reader@example.com")
59 if err != nil {
60 t.Fatalf("TestSignIn: %v", err)
61 }
62 // Following the link must establish a session.
63 req := app.TestConfirmRequest(link)
64 rec := httptest.NewRecorder()
65 app.Handler().ServeHTTP(rec, req)
66 if len(rec.Result().Cookies()) == 0 {
67 t.Fatal("following the magic link set no session cookie")
68 }
69}
70
71// TestMagicLinkThenSignedInRouteWorks proves the session the previous
72// test only checked for the shape of is actually usable: the cookie
73// following the link sets must let a subsequent request reach a
74// RequireSession route — the whole point of Task 1, not just "a
75// cookie was set".
76func TestMagicLinkThenSignedInRouteWorks(t *testing.T) {
77 app, err := docs.NewForTest(t)
78 if err != nil {
79 t.Fatal(err)
80 }
81 link, err := app.TestSignIn(t, "reader@example.com")
82 if err != nil {
83 t.Fatalf("TestSignIn: %v", err)
84 }
85
86 verifyReq := app.TestConfirmRequest(link)
87 verifyRec := httptest.NewRecorder()
88 app.Handler().ServeHTTP(verifyRec, verifyReq)
89 cookies := verifyRec.Result().Cookies()
90 if len(cookies) == 0 {
91 t.Fatal("following the magic link set no session cookie")
92 }
93
94 req := httptest.NewRequest(http.MethodGet, "/", nil)
95 for _, c := range cookies {
96 req.AddCookie(c)
97 }
98 rec := httptest.NewRecorder()
99 app.Handler().ServeHTTP(rec, req)
100 if rec.Code != http.StatusOK {
101 t.Fatalf("GET / signed in: status %d, want 200", rec.Code)
102 }
103}
104
105// TestSignInPageRendersSignedOut proves the sign-in form itself is
106// reachable signed out — it has to be, or nobody could ever sign in.
107func TestSignInPageRendersSignedOut(t *testing.T) {
108 app, err := docs.NewForTest(t)
109 if err != nil {
110 t.Fatal(err)
111 }
112 req := httptest.NewRequest(http.MethodGet, "/signin", nil)
113 rec := httptest.NewRecorder()
114 app.Handler().ServeHTTP(rec, req)
115 if rec.Code != http.StatusOK {
116 t.Fatalf("GET /signin: status %d, want 200", rec.Code)
117 }
118 body := rec.Body.String()
119 if !strings.Contains(body, `<label rst-field-label for="rst-signin-email">Email</label>`) {
120 t.Error("email input has no persistent associated translated label")
121 }
122 if !strings.Contains(body, `type="email" id="rst-signin-email" name="address" required autofocus autocomplete="email"`) {
123 t.Error("label target must remain the required, focused email input with email autocomplete")
124 }
125
126}
127
128// TestSignOutEndsTheSession proves POST /signout is real revocation,
129// not merely clearing a cookie the client could ignore: the session
130// must stop working for a RequireSession route even if a client
131// somehow kept presenting the old cookie value.
132func TestSignOutEndsTheSession(t *testing.T) {
133 app, err := docs.NewForTest(t)
134 if err != nil {
135 t.Fatal(err)
136 }
137 link, err := app.TestSignIn(t, "reader@example.com")
138 if err != nil {
139 t.Fatalf("TestSignIn: %v", err)
140 }
141 verifyReq := app.TestConfirmRequest(link)
142 verifyRec := httptest.NewRecorder()
143 app.Handler().ServeHTTP(verifyRec, verifyReq)
144 cookies := verifyRec.Result().Cookies()
145 if len(cookies) == 0 {
146 t.Fatal("following the magic link set no session cookie")
147 }
148
149 signoutReq := httptest.NewRequest(http.MethodPost, "/signout", nil)
150 signoutReq.Header.Set("Sec-Fetch-Site", "same-origin")
151 for _, c := range cookies {
152 signoutReq.AddCookie(c)
153 }
154 signoutRec := httptest.NewRecorder()
155 app.Handler().ServeHTTP(signoutRec, signoutReq)
156 if signoutRec.Code != http.StatusSeeOther {
157 t.Fatalf("POST /signout: status %d, want %d", signoutRec.Code, http.StatusSeeOther)
158 }
159
160 req := httptest.NewRequest(http.MethodGet, "/", nil)
161 for _, c := range cookies {
162 req.AddCookie(c)
163 }
164 rec := httptest.NewRecorder()
165 app.Handler().ServeHTTP(rec, req)
166 if rec.Code != http.StatusSeeOther && rec.Code != http.StatusFound {
167 t.Errorf("GET / with a signed-out session's old cookie: status %d, want a redirect to sign-in", rec.Code)
168 }
169}
170
171// TestNewRefusesMissingInstanceKeyOutsideDevelopment is the same
172// fail-closed shape as Origin's own startup refusal (app_test.go):
173// InstanceKey seals auth's pending-link blob, and an empty one is
174// dangerous, not merely inconvenient (rauth.Config.InstanceKey's own
175// doc comment) — so it must refuse to start rather than default
176// outside development.
177func TestNewRefusesMissingInstanceKeyOutsideDevelopment(t *testing.T) {
178 _, err := docs.New(docs.Config{
179 Env: "production",
180 Origin: "https://docs.example.com",
181 })
182 if err == nil {
183 t.Fatal("New must refuse a missing InstanceKey outside development")
184 }
185}
186
187// TestNewRefusesMissingMailOutsideDevelopment: a sign-in that cannot
188// send its link is not sign-in — the same fail-closed shape as the
189// origin check, per the brief.
190func TestNewRefusesMissingMailOutsideDevelopment(t *testing.T) {
191 _, err := docs.New(docs.Config{
192 Env: "production",
193 Origin: "https://docs.example.com",
194 InstanceKey: "some-real-key",
195 })
196 if err == nil {
197 t.Fatal("New must refuse to start outside development with no mail configured")
198 }
199}
200
201// TestSecondClickOfTheSameMagicLinkOffersRecovery is fix round 1 on
202// Task 3's own regression test: rauth.Auth's Verify handler
203// deliberately gives one error for "unknown, used and expired alike"
204// (its own doc comment), which means a magic link clicked a second
205// time — the ordinary case of someone opening an old sign-in email —
206// lands on the exact same ?err=expired outcome as a link that was
207// never valid at all. Confirmed directly against this app's own
208// router, not assumed: the first click consumes the link and sets a
209// session; the second click, with no cookie attached (a fresh tab, or
210// the same old email opened again after the first session already
211// expired), must redirect back to /signin with the specific "expired
212// or already used... enter your email for a new one" copy — never a
213// bare, uninformative dead end.
214func TestSecondClickOfTheSameMagicLinkOffersRecovery(t *testing.T) {
215 app, err := docs.NewForTest(t)
216 if err != nil {
217 t.Fatal(err)
218 }
219 link, err := app.TestSignIn(t, "clicktwice@example.com")
220 if err != nil {
221 t.Fatalf("TestSignIn: %v", err)
222 }
223
224 firstReq := app.TestConfirmRequest(link)
225 firstRec := httptest.NewRecorder()
226 app.Handler().ServeHTTP(firstRec, firstReq)
227 if len(firstRec.Result().Cookies()) == 0 {
228 t.Fatal("first click set no session cookie")
229 }
230
231 secondReq := app.TestConfirmRequest(link)
232 secondRec := httptest.NewRecorder()
233 app.Handler().ServeHTTP(secondRec, secondReq)
234 loc := secondRec.Header().Get("Location")
235 if !strings.Contains(loc, "err=expired") {
236 t.Fatalf("second click redirected to %q, want an err=expired outcome", loc)
237 }
238
239 signinReq := httptest.NewRequest(http.MethodGet, loc, nil)
240 signinRec := httptest.NewRecorder()
241 app.Handler().ServeHTTP(signinRec, signinReq)
242 // The words are rastrillo's sign-in screen's (the smart door), from its
243 // own English catalog: the expired problem, with the email field to
244 // send a new link.
245 body := html.UnescapeString(signinRec.Body.String())
246 if !strings.Contains(body, "That link has expired or was already used. Send a new one.") || !strings.Contains(body, `name="address"`) {
247 t.Errorf("signin page after a second click does not say the link expired, with the field; body: %s", body)
248 }
249 if strings.Contains(body, "docs.error.generic") {
250 t.Errorf("signin page after a second click fell back to the app-wide docs.error.generic instead of the sign-in-specific expired copy")
251 }
252}
253
254// TestSigninUnrecognizedErrorUsesSigninSpecificFallback is fix round
255// 1 on Task 3's own finding: GET /signin's switch on ?err= had a
256// default: branch falling back to docs.error.generic ("Something went
257// wrong.") — the app-wide string written for a render failure with
258// nowhere styled to land, not for this page's own ordinary outcomes.
259// ?err=keymail (a failed keymail callback, rastrillo/auth's own
260// Callback handler) and ?err=1 (a raw Begin failure, logged
261// server-side) both reach that default branch in real use — this
262// pins both directly against the handler, without depending on
263// rastrillo internals staying exactly as they are today, and checks
264// the fallback is sign-in-specific rather than the app-wide string.
265func TestSigninUnrecognizedErrorUsesSigninSpecificFallback(t *testing.T) {
266 app, err := docs.NewForTest(t)
267 if err != nil {
268 t.Fatal(err)
269 }
270 // See TestSecondClickOfTheSameMagicLinkOffersRecovery's own comment
271 // on why the raw catalog key, not the resolved English copy, is
272 // what this handler-level test can observe and correctly should
273 // assert on.
274 for _, errParam := range []string{"keymail", "1", "some-future-value-nobody-has-written-a-case-for-yet"} {
275 req := httptest.NewRequest(http.MethodGet, "/signin?err="+errParam, nil)
276 rec := httptest.NewRecorder()
277 app.Handler().ServeHTTP(rec, req)
278 // rastrillo's screen answers keymail with its own problem, and any
279 // other err (a raw Begin failure, or one nobody has written yet)
280 // with its generic sign-in problem, never Docs' app-wide string.
281 body := html.UnescapeString(rec.Body.String())
282 want := "Something went wrong. Try again."
283 if errParam == "keymail" {
284 want = "We couldn't confirm it's you." // rastrillo v0.45.0 never names Keymail
285 }
286 if !strings.Contains(body, want) || !strings.Contains(body, `name="address"`) {
287 t.Errorf("err=%q: signin page does not say %q with the field; body: %s", errParam, want, body)
288 }
289 if strings.Contains(body, "docs.error.generic") {
290 t.Errorf("err=%q: signin page fell back to the app-wide docs.error.generic instead of the sign-in-specific fallback", errParam)
291 }
292 }
293}
294