-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauthhelper_test.go
278 lines (252 loc) · 6.95 KB
/
authhelper_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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
//go:build linux || darwin || freebsd || netbsd || openbsd || dragonfly
// +build linux darwin freebsd netbsd openbsd dragonfly
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/fsnotify/fsnotify"
"github.com/golang-jwt/jwt/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestAuthHelperJSON(t *testing.T) {
cases := []struct {
name string
want string
claims jwt.MapClaims
code int
}{
{
name: "sub over email",
want: "foosubject",
claims: jwt.MapClaims{
"email": "[email protected]",
"sub": "foosubject",
},
},
{
name: "username over sub",
want: "fooperson",
claims: jwt.MapClaims{
"username": "fooperson",
"email": "[email protected]",
"sub": "foosubject",
},
},
{
name: "no sub no username",
want: "",
claims: jwt.MapClaims{
"email": "[email protected]",
},
code: 400,
},
{
name: "no email",
want: "",
claims: jwt.MapClaims{
"username": "fooperson",
},
code: 400,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
testAuthHelper(t, "json", tc.code, tc.want, tc.claims)
})
}
}
func TestAuthHelperJWT(t *testing.T) {
testAuthHelper(t, "jwt", 0, "", jwt.MapClaims{
"email": "[email protected]",
"sub": "foo",
})
}
func TestAuthHelperDefault(t *testing.T) {
testAuthHelper(t, "", 0, "", jwt.MapClaims{
"email": "[email protected]",
"sub": "foo",
})
}
func testAuthHelper(t *testing.T, format string, httpError int, expectedUsername string, baseClaims jwt.MapClaims) {
dir, err := os.MkdirTemp("", "ahtest")
require.NoError(t, err, "mktmp")
defer os.RemoveAll(dir)
script := fmt.Sprintf(`#!/bin/sh
echo "$*" > %s/.args.$$
mv %s/.args.$$ %s/args.$$
`, dir, dir, dir)
err = os.WriteFile(dir+"/xdg-open", []byte(script), 0755)
require.NoError(t, err, "write script")
err = os.WriteFile(dir+"/open", []byte(script), 0755)
require.NoError(t, err, "write script")
os.Setenv("PATH", dir+":"+os.Getenv("PATH"))
watcher, err := fsnotify.NewWatcher()
require.NoError(t, err, "new watcher")
defer watcher.Close()
watchResults := make(chan error)
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
watchResults <- fmt.Errorf("watcher events closed")
return
}
if event.Op&fsnotify.Create == fsnotify.Create {
if strings.HasPrefix(filepath.Base(event.Name), ".") {
t.Logf("Watcher says file %s was created, but we're not intersted in that", event.Name)
continue
}
t.Logf("Watcher says file %s was created", event.Name)
raw, err := os.ReadFile(event.Name)
if err != nil {
watchResults <- err
} else {
watchResults <- fakeBrowser(t, string(raw), baseClaims, httpError)
}
return
}
case err := <-watcher.Errors:
if err != nil {
watchResults <- err
}
watchResults <- fmt.Errorf("watcher errors closed")
return
case <-time.After(10 * time.Second):
watchResults <- fmt.Errorf("no useful watcher event after 10 seconds")
return
}
}
}()
t.Logf("Watcher on %s started", dir)
err = watcher.Add(dir)
require.NoError(t, err, "add watcher directory")
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
t.Log("watch results wait finished")
assert.NoError(t, <-watchResults, "watch results error")
}()
go func() {
defer wg.Done()
t.Log("Starting auth helper")
var buf bytes.Buffer
var args []string
if format != "" {
args = append(args, "-o", format)
}
main2(&buf, lockedGetConfig(args...))
var output AuthHelperOutput
t.Log("auth helper output", buf.String())
if httpError == 0 {
var jwtString string
switch format {
case "json":
err = json.Unmarshal(buf.Bytes(), &output)
require.NoErrorf(t, err, "unmarshal output from helper")
assert.Equal(t, 1, output.ModelVersionNumber, "model version number")
if e, ok := baseClaims["email"]; ok {
assert.Equal(t, e.(string), output.Email, "email")
}
assert.Less(t, time.Now().Format(time.RFC3339), output.ExpiresAt, "expires")
assert.Equal(t, expectedUsername, output.Username, "username")
jwtString = output.PasswordToken
case "", "jwt":
jwtString = buf.String()
default:
assert.Fail(t, "unexpected format")
}
var mapClaims jwt.MapClaims
_, err := jwt.ParseWithClaims(jwtString, &mapClaims, func(token *jwt.Token) (interface{}, error) {
return []byte("a secret"), nil
})
if assert.NoError(t, err, "decode token in output") {
assert.Equal(t, "[email protected]", mapClaims["email"], "email in token")
}
} else {
if format == "json" {
assert.Equal(t, "{}\n", buf.String(), "empty JSON expected")
} else {
assert.Equal(t, "", buf.String(), "no output expected")
}
}
}()
wg.Wait()
}
var configLock sync.Mutex
// locked because we modify a global: os.Args
func lockedGetConfig(args ...string) configData {
configLock.Lock()
defer configLock.Unlock()
argsCopy := make([]string, len(os.Args))
copy(argsCopy, os.Args)
defer func() {
os.Args = argsCopy
}()
os.Args = append([]string{os.Args[0]}, args...)
return getConfig()
}
func fakeBrowser(t *testing.T, us string, claims jwt.MapClaims, httpError int) error {
us = strings.TrimSuffix(us, "\n")
t.Logf("Browser invoked with %s", us)
config := lockedGetConfig()
if !strings.HasPrefix(us, config.BaseURL) {
return fmt.Errorf("url does not start with base url: %s", us)
}
u, err := url.Parse(us)
if err != nil {
return fmt.Errorf("parse url %s: %w", us, err)
}
returnTo := u.Query().Get("returnTo")
if returnTo == "" {
return fmt.Errorf("no returnTo in URL %s", us)
}
claims["exp"] = time.Now().Add(time.Hour).Unix()
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString([]byte("a secret"))
if err != nil {
return fmt.Errorf("sign token %w", err)
}
t.Logf("POST token to %s", returnTo)
optionsRequest, err := http.NewRequest(http.MethodOptions, returnTo, strings.NewReader(""))
if err != nil {
return fmt.Errorf("OPTIONS NewRequest %s error: %w", returnTo, err)
}
optionsResponse, err := http.DefaultClient.Do(optionsRequest)
if err != nil {
return fmt.Errorf("OPTIONS response to %s error: %w", returnTo, err)
}
allow := optionsResponse.Header.Get("Allow")
if allow != http.MethodPost {
return fmt.Errorf("invalid OPTIONS response to %s: %s", returnTo, allow)
}
resp, err := http.Post(returnTo, "text/plain", strings.NewReader(tokenString))
if err != nil {
return fmt.Errorf("POST to %s error: %w", returnTo, err)
}
defer resp.Body.Close()
bod, _ := io.ReadAll(resp.Body)
if len(bod) != 0 {
t.Log("Recevied response:", string(bod))
}
if httpError != 0 {
if resp.StatusCode != httpError {
return fmt.Errorf("POST to %s response code %d", returnTo, resp.StatusCode)
}
} else if resp.StatusCode != 204 {
return fmt.Errorf("POST to %s response code %d", returnTo, resp.StatusCode)
}
return nil
}