~bigbes/core-go

ref: 2624a28a52b29713f7ac13b95e0d43f969a1d47c core-go/auth/middleware_test.go -rw-r--r-- 5.9 KiB
2624a28a — Robin Jarry webhooks: do not crash when expire is NULL 1 year, 8 months 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
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
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/config"
	"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, _ = 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)
}

func TestInternal(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")
	internalAuth := InternalAuth{
		Name:            "jdoe",
		ClientID:        "",
		NodeID:          "test.node",
		OAuthClientUUID: "",
	}
	payload, err := json.Marshal(&internalAuth)
	assert.Nil(t, err)
	req.Header.Add("Authorization", "Internal "+
		string(crypto.Encrypt(payload)))
	req.RemoteAddr = "127.0.0.1"

	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_INTERNAL)
	assert.Equal(t, auth.UserID, 1337)
	assert.Equal(t, auth.Username, "jdoe")
	assert.Equal(t, auth.Email, "jdoe@example.org")

	// Expect failure when outside of internal IP network
	ctx, _ = 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.Header.Add("Authorization", "Internal "+
		string(crypto.Encrypt(payload)))
	req.RemoteAddr = "1.2.3.4"

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

	// Expect failure with invalid header
	ctx, _ = 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.Header.Add("Authorization", "Internal fakeauth")
	req.RemoteAddr = "127.0.0.1"

	*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 := config.Context(
		database.Context(context.Background(), db),
		nil, "git.sr.ht",
	)
	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
}