-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_test.go
227 lines (182 loc) · 6.34 KB
/
main_test.go
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
package main
import (
"archiiv/fs"
"bytes"
"encoding/base64"
"encoding/json"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func newTestServer(t *testing.T) http.Handler {
return newTestServerWithUsers(t, map[string][64]byte{})
}
func newTestServerWithUsers(t *testing.T, users map[string][64]byte) http.Handler {
log := slog.New(slog.NewJSONHandler(io.Discard, nil))
dir := t.TempDir()
rootID, err := fs.InitFsDir(dir, users)
if err != nil {
t.Error(err)
}
secret := generateSecret()
srv, _, err := createServer(log, []string{
"--data_dir", dir,
"--root_id", rootID.String(),
}, func(s string) string {
if s == "ARCHIIV_SECRET" {
return secret
}
return ""
})
if err != nil {
t.Fatalf("newTestServer: %v", err)
}
return srv
}
func decodeResponse[T any](t *testing.T, r *http.Response) (v T) {
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
err := dec.Decode(&v)
assert.NoError(t, err)
_, err = dec.Token()
if assert.Error(t, err) {
assert.Equal(t, err, io.EOF)
}
return
}
func getBody(t *testing.T, res *http.Response) string {
b, err := io.ReadAll(res.Body)
assert.NoError(t, err)
return string(b)
}
func expectFail(t *testing.T, res *http.Response, statusCode int, errorMessage string) {
assert.Equal(t, statusCode, res.StatusCode)
b := decodeResponse[responseError](t, res)
assert.Equal(t, false, b.Ok, false)
assert.Equal(t, errorMessage, b.Error)
}
func expectStringLooksLikeToken(t *testing.T, token string) {
data, err := base64.URLEncoding.DecodeString(token)
if err != nil {
t.Errorf("string does not look like token: base64 decode: %v", err)
}
ft, err := gobDecode[fullToken](data)
if err != nil {
t.Errorf("string does not look like token: gob decode %v", err)
}
_, err = payloadToBytes(ft.Data)
if err != nil {
t.Errorf("string does not look like token: payload to bytes: %v", err)
}
}
func hit(srv http.Handler, method, target, token string, body io.Reader) *http.Response {
req := httptest.NewRequest(method, target, body)
if token != "" {
req.Header.Add("Authorization", token)
}
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
return w.Result()
}
func hitPost(t *testing.T, srv http.Handler, target, token string, body any) *http.Response {
var buf bytes.Buffer
err := json.NewEncoder(&buf).Encode(body)
if err != nil {
t.Errorf("failed to encode post body: %v", err)
}
return hit(srv, http.MethodPost, target, token, &buf)
}
func hitGet(srv http.Handler, target, token string) *http.Response {
return hit(srv, http.MethodGet, target, token, strings.NewReader(""))
}
type loginRequest struct {
Username string `json:"username"`
Password [64]byte `json:"password"`
}
func loginHelper(t *testing.T, srv http.Handler, username, pwd string) string {
res := hitPost(t, srv, "/api/v1/login", "", loginRequest{Username: username, Password: hashPassword(pwd)})
type LoginResponse struct {
Ok bool `json:"ok"`
Data struct {
Token string `json:"token"`
ExpireDate time.Time `json:"expireDate"`
} `json:"data"`
}
lr := decodeResponse[LoginResponse](t, res)
return lr.Data.Token
}
func TestWhoamiNeedsLogin(t *testing.T) {
t.Parallel()
srv := newTestServer(t)
res := hitGet(srv, "/api/v1/whoami", "")
expectFail(t, res, http.StatusUnauthorized, "401 unauthorized")
}
func TestRootReturnsNotFound(t *testing.T) {
t.Parallel()
srv := newTestServer(t)
res := hitGet(srv, "/", "")
assert.Equal(t, http.StatusNotFound, res.StatusCode)
assert.Equal(t, "404 page not found\n", getBody(t, res))
}
func TestLogin(t *testing.T) {
t.Parallel()
srv := newTestServerWithUsers(t, map[string][64]byte{
"prokop": hashPassword("catboy123"),
})
expectFail(t, hitPost(t, srv, "/api/v1/login", "", loginRequest{Username: "prokop", Password: hashPassword("eek")}), http.StatusForbidden, "wrong name or password")
expectFail(t, hitPost(t, srv, "/api/v1/login", "", loginRequest{Username: "prokop", Password: hashPassword("uuhk")}), http.StatusForbidden, "wrong name or password")
expectFail(t, hitPost(t, srv, "/api/v1/login", "", loginRequest{Username: "marek", Password: hashPassword("catboy123")}), http.StatusForbidden, "wrong name or password")
res := hitPost(t, srv, "/api/v1/login", "", loginRequest{Username: "prokop", Password: hashPassword("catboy123")})
assert.Equal(t, http.StatusOK, res.StatusCode)
response := decodeResponse[struct {
Ok bool `json:"ok"`
Data struct {
Token string `json:"token"`
ExpireDate time.Time `json:"expireDate"`
} `json:"data"`
}](t, res)
assert.Equal(t, true, response.Ok)
expectStringLooksLikeToken(t, response.Data.Token)
}
func bodylessRequest(t *testing.T, srv http.Handler, method, target, token string) *http.Response {
req := httptest.NewRequest(http.MethodGet, target, strings.NewReader(""))
if token != "" {
req.Header.Add("Authorization", token)
}
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
return w.Result()
}
func TestWhoami(t *testing.T) {
t.Parallel()
srv := newTestServerWithUsers(t, map[string][64]byte{"matuush": hashPassword("kadit")})
token := loginHelper(t, srv, "matuush", "kadit")
res := bodylessRequest(t, srv, http.MethodGet, "/api/v1/whoami", token)
assert.Equal(t, http.StatusOK, res.StatusCode)
assert.Equal(t, "{\"ok\":true,\"data\":{\"name\":\"matuush\"}}\n", getBody(t, res))
}
func TestDelete(t *testing.T) {
t.Parallel()
srv := newTestServerWithUsers(t, map[string][64]byte{
"matuush": hashPassword("kadit"),
"admin": hashPassword("heslo123")})
token := loginHelper(t, srv, "matuush", "kadit")
res := hitGet(srv, "/api/v1/whoami", token)
assert.Equal(t, http.StatusOK, res.StatusCode)
assert.Equal(t, "{\"ok\":true,\"data\":{\"name\":\"matuush\"}}\n", getBody(t, res))
adminToken := loginHelper(t, srv, "admin", "heslo123")
res = hitGet(srv, "/api/v1/whoami", adminToken)
assert.Equal(t, http.StatusOK, res.StatusCode)
assert.Equal(t, "{\"ok\":true,\"data\":{\"name\":\"admin\"}}\n", getBody(t, res))
res = hitPost(t, srv, "/api/v1/delete/matuush", token, strings.NewReader(""))
assert.Equal(t, http.StatusUnauthorized, res.StatusCode)
assert.Equal(t, "{\"ok\":false,\"error\":\"401 unauthorized\"}\n", getBody(t, res))
res = hitPost(t, srv, "/api/v1/delete/matuush", adminToken, strings.NewReader(""))
assert.Equal(t, http.StatusOK, res.StatusCode)
assert.Equal(t, "{\"ok\":true}\n", getBody(t, res))
}