~bigbes/core-go

ref: b335efbdb6606f4af3ae128b45d2876e4fd4c715 core-go/auth/middleware_test.go -rw-r--r-- 3.9 KiB
b335efbd — Drew DeVault auth/middleware_test: test invalid auth cookie 5 years 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
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
package auth

import (
	"context"
	"encoding/json"
	"net/http"
	"strings"
	"testing"
	"time"

	"github.com/DATA-DOG/go-sqlmock"
	"github.com/stretchr/testify/assert"
	"github.com/vaughan0/go-ini"

	"git.sr.ht/~sircmpwn/core-go/crypto"
	"git.sr.ht/~sircmpwn/core-go/database"
)

func TestNoAuthorization(t *testing.T) {
	mw, _, next := middleware()
	req, err := http.NewRequestWithContext(context.Background(), "POST",
		"https://example.org/query",
		strings.NewReader(`{"query": "query { me { id } }"}`))
	assert.Nil(t, err)
	req.Header.Add("Content-Type", "application/json")
	resp := &TestResponse{T: t}
	mw(resp, req)
	assert.False(t, *next)
	assert.Equal(t, http.StatusUnauthorized, resp.StatusCode)
}

func TestCookie(t *testing.T) {
	mw, subctx, next := middleware()
	ctx, mock := dbctx()
	mockUserLookup(mock)

	req, err := http.NewRequestWithContext(ctx, "POST",
		"https://example.org/query",
		strings.NewReader(`{"query": "query { me { id } }"}`))
	assert.Nil(t, err)
	req.Header.Add("Content-Type", "application/json")

	cookie := AuthCookie{
		Name: "jdoe",
	}
	payload, err := json.Marshal(&cookie)
	assert.Nil(t, err)

	req.AddCookie(&http.Cookie{
		Name:  "sr.ht.unified-login.v1",
		Value: string(crypto.Encrypt(payload)),
	})

	resp := &TestResponse{T: t}
	mw(resp, req)
	assert.True(t, *next)
	assert.Nil(t, mock.ExpectationsWereMet())

	auth := ForContext(*subctx)
	assert.Equal(t, auth.AuthMethod, AUTH_COOKIE)
	assert.Equal(t, auth.UserID, 1337)
	assert.Equal(t, auth.Username, "jdoe")
	assert.Equal(t, auth.Email, "jdoe@example.org")

	// Test that invalid cookie fails
	ctx, mock = dbctx()
	req, err = http.NewRequestWithContext(ctx, "POST",
		"https://example.org/query",
		strings.NewReader(`{"query": "query { me { id } }"}`))
	assert.Nil(t, err)
	req.Header.Add("Content-Type", "application/json")

	req.AddCookie(&http.Cookie{
		Name:  "sr.ht.unified-login.v1",
		Value: string("Invalid auth cookie"),
	})

	*next = false
	resp = &TestResponse{T: t}
	mw(resp, req)
	assert.False(t, *next)
	assert.Equal(t, http.StatusForbidden, resp.StatusCode)
}

var conf ini.File

func init() {
	var err error
	conf, err = ini.Load(strings.NewReader(`
[webhooks]
private-key=ebzsjPaN6E13ln/FeNWly1C92q6bVMVdOnDo1HPl5fc=

[sr.ht]
network-key=tbuG-7Vh44vrDq1L_HKWkHnWrDOtJhEkPKPiauaLeuk=

[test::api]
internal-ipnet=127.0.0.1/24,::1/64`))
	if err != nil {
		panic(err)
	}
	crypto.InitCrypto(conf)
}

func middleware() (http.HandlerFunc, *context.Context, *bool) {
	called := false
	var ctx context.Context
	next := (func(called *bool, ctx *context.Context) http.HandlerFunc {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			*called = true
			*ctx = r.Context()
		})
	})(&called, &ctx)
	return Middleware(conf, "test::api")(next).ServeHTTP, &ctx, &called
}

func dbctx() (context.Context, sqlmock.Sqlmock) {
	db, mock, err := sqlmock.New()
	if err != nil {
		panic(err)
	}
	ctx := database.Context(context.Background(), db)
	return ctx, mock
}

func mockUserLookup(mock sqlmock.Sqlmock) {
	mock.ExpectBegin()
	mock.ExpectQuery(`SELECT`).
		WithArgs("jdoe").
		WillReturnRows(sqlmock.NewRows([]string{
			"id", "username", "created", "updated", "email", "user_type",
			"url", "location", "bio", "suspension_notice",
		}).
			AddRow(1337, "jdoe", time.Now().UTC(), time.Now().UTC(),
				"jdoe@example.org", "active_paying",
				"https://example.org", nil, nil, nil))
	mock.ExpectCommit()
}

type TestResponse struct {
	T *testing.T

	RespHeader http.Header
	Payload    []byte
	StatusCode int
}

func (tr *TestResponse) Header() http.Header {
	if tr.RespHeader == nil {
		tr.RespHeader = make(http.Header)
	}
	return tr.RespHeader
}

func (tr *TestResponse) Write(payload []byte) (int, error) {
	if tr.StatusCode == 0 {
		tr.WriteHeader(http.StatusOK)
	}

	assert.Nil(tr.T, tr.Payload)
	tr.Payload = payload
	return len(payload), nil
}

func (tr *TestResponse) WriteHeader(statusCode int) {
	assert.Zero(tr.T, tr.StatusCode)
	tr.StatusCode = statusCode
}