~bigbes/sr-ht-spec

ref: b7d1bf89a0bba51749babd45ce9f9c14b72f2470 sr-ht-spec/web/tokens_test.go -rw-r--r-- 2.4 KiB
b7d1bf89 — Eugene Blikh login: decode the unified-login cookie through ecore 9 days ago
                                                                                
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
package web

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"sourcecraft.dev/bigbes/sr-ht-ecore/ecoretest"

	"sourcecraft.dev/bigbes/sr-ht-spec/authn"
)

// /tokens is a signpost now. spec.sr.ht mints no credential of its own, so the
// page that used to mint, list and revoke one points at the daemon that does.
func TestTokensRedirectsToTokensSrHt(t *testing.T) {
	h, _ := testServer(t)

	for name, user := range map[string]string{
		"owner":     "bigbes",
		"anonymous": "",
	} {
		t.Run(name, func(t *testing.T) {
			rec := get(t, h, "/tokens", user)
			assert.Equal(t, http.StatusSeeOther, rec.Code, "body: %s", rec.Body)
			// The external origin, because this is for a browser, and the page
			// SPEC ch. 7 puts the token UI on.
			assert.Equal(t, ecoretest.Origin("tokens.sr.ht")+"/tokens", rec.Header().Get("Location"))
		})
	}
}

// The POST routes went with the table behind them: nothing here mints or
// revokes any more, and a form posted at the old address must not answer as
// though it might have worked. It is now csrf.Require that refuses them — the
// guard runs before routing, so a POST to an address this surface does not
// serve is refused rather than 404'd.
func TestTokensAcceptsNoWrites(t *testing.T) {
	h, _ := testServer(t)

	for _, target := range []string{"/tokens", "/tokens/1/revoke"} {
		t.Run(target, func(t *testing.T) {
			req := httptest.NewRequest(http.MethodPost, target, nil)
			login(req, "bigbes")
			rec := httptest.NewRecorder()
			h.ServeHTTP(rec, req)
			assert.NotEqual(t, http.StatusOK, rec.Code)
			assert.NotEqual(t, http.StatusSeeOther, rec.Code)
		})
	}
}

// An instance with no [tokens.sr.ht] section has nowhere to send anybody, and
// says so instead of redirecting to a URL built out of an empty string.
func TestTokensWithoutTheSectionSaysSo(t *testing.T) {
	srv, err := New(Options{
		Conf:     ecoretest.Config(authn.ConfigSection, ecoretest.Delete("tokens.sr.ht")),
		Reader:   newFakeReader(),
		Searcher: &fakeSearcher{},
		Resolver: testResolver(t),
	})
	require.NoError(t, err)

	req := httptest.NewRequest(http.MethodGet, "/tokens", nil)
	login(req, "bigbes")
	rec := httptest.NewRecorder()
	srv.Handler().ServeHTTP(rec, req)

	assert.Equal(t, http.StatusServiceUnavailable, rec.Code)
	assert.Empty(t, rec.Header().Get("Location"), "there is no origin to redirect to")
	assert.Contains(t, rec.Body.String(), "tokens.sr.ht")
}