authserver_test.go 7.13 KB
Newer Older
ale's avatar
ale committed
1
2
3
4
5
6
7
8
9
10
11
12
13
package server

import (
	"context"
	"io/ioutil"
	"os"
	"path/filepath"
	"testing"
	"time"

	"github.com/pquerna/otp/totp"

	"git.autistici.org/id/auth"
ale's avatar
ale committed
14
	"git.autistici.org/id/auth/client"
ale's avatar
ale committed
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
)

type testServer struct {
	tmpdir string
	srv    *Server
}

func createTestServer(t testing.TB, configFiles map[string]string) *testServer {
	tmpdir, err := ioutil.TempDir("", "")
	if err != nil {
		t.Fatal(err)
	}

	for name, content := range configFiles {
		if err = ioutil.WriteFile(filepath.Join(tmpdir, name), []byte(content), 0600); err != nil {
			t.Fatal(err)
		}
	}

	config, err := LoadConfig(filepath.Join(tmpdir, "config.yml"))
	if err != nil {
		t.Fatal("LoadConfig():", err)
	}

39
	srv, err := NewServer(config)
ale's avatar
ale committed
40
41
42
43
44
45
46
47
48
49
50
	if err != nil {
		t.Fatal("NewServer():", err)
	}

	return &testServer{
		tmpdir: tmpdir,
		srv:    srv,
	}
}

func (s *testServer) Close() {
ale's avatar
ale committed
51
	s.srv.Close()
ale's avatar
ale committed
52
53
54
	_ = os.RemoveAll(s.tmpdir)
}

ale's avatar
ale committed
55
56
57
58
59
60
61
62
// A small adapter to make Server conform to the Client interface
// (Authenticate needs to return an error).
type clientAdapter struct {
	*Server
}

func (c *clientAdapter) Authenticate(ctx context.Context, req *auth.Request) (*auth.Response, error) {
	return c.Server.Authenticate(ctx, req), nil
ale's avatar
ale committed
63
64
65
66
67
68
}

var (
	testUsersFileStr = `---
- name: testuser
  email: testuser@example.com
ale's avatar
ale committed
69
  password: "$s$16384$8$1$c479e8eb722f1b071efea7826ccf9c20$96d63ebed0c64afb746026f56f71b2a1f8796c73141d2d6b1958d4ea26c60a0b"
ale's avatar
ale committed
70
71
72
73
74
75
  groups:
    - group1
    - group2

- name: 2fauser
  email: 2fauser@example.com
ale's avatar
ale committed
76
  shard: 42
ale's avatar
ale committed
77
  password: "$s$16384$8$1$c479e8eb722f1b071efea7826ccf9c20$96d63ebed0c64afb746026f56f71b2a1f8796c73141d2d6b1958d4ea26c60a0b"
ale's avatar
ale committed
78
  totp_secret: "O32OBVS5BL5EAPB5"
79
80
81
  u2f_registrations:
    - key_handle: "JcolXA6KaoihO8VuxSugtCT5jyh-6lFuWXLkFAPe8s9qszxTMvDAtJn8gmYg9uGO-kmjgap1h0llchlqqjCpKw"
      public_key: "0498ee4565cd348031cf36ee3549b63b5ea23b5e7ea6f297e7cccaeba99983d185110fb94fa6455c82d3e5c8d0be10be71308d76062fb5fa50d3ea8228048f0037"
ale's avatar
ale committed
82
83
84
85
86
87
`

	testConfigStr = `---
services:
  test:
    backends:
ale's avatar
ale committed
88
89
90
      - backend: file
        params:
          src: users.yml
ale's avatar
ale committed
91
92
93
  interactive:
    challenge_response: true
    backends:
ale's avatar
ale committed
94
95
96
      - backend: file
        params:
          src: users.yml
ale's avatar
ale committed
97
`
98
99
100
101
102

	testConfigStrWithRatelimit = `---
services:
  test:
    backends:
ale's avatar
ale committed
103
104
105
      - backend: file
        params:
          src: users.yml
106
107
108
109
110
111
112
113
114
115
    rate_limits:
      - failed_login_bl
rate_limits:
  failed_login_bl:
    limit: 10
    period: 300
    blacklist_for: 3600
    on_failure: true
    keys: [user]
`
ale's avatar
ale committed
116
117
)

ale's avatar
ale committed
118
func runAuthenticationTest(t *testing.T, client client.Client) {
ale's avatar
ale committed
119
120
121
122
123
124
125
126
127
128
129
130
	// Test a number of simple password logins.
	testdata := []struct {
		service, username, password string
		expectedStatus              auth.Status
	}{
		{"test", "testuser", "password", auth.StatusOK},
		{"bad_service", "testuser", "password", auth.StatusError},
		{"test", "bad_user", "password", auth.StatusError},
		{"test", "testuser", "bad_password", auth.StatusError},
		{"test", "2fauser", "password", auth.StatusError},
	}
	for _, td := range testdata {
ale's avatar
ale committed
131
		resp, err := client.Authenticate(context.Background(), &auth.Request{
ale's avatar
ale committed
132
133
134
135
			Service:  td.service,
			Username: td.username,
			Password: []byte(td.password),
		})
ale's avatar
ale committed
136
137
138
139
		if err != nil {
			t.Errorf("transport error: %v", err)
			continue
		}
ale's avatar
ale committed
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
		if resp.Status != td.expectedStatus {
			t.Errorf("authentication error: s=%s u=%s p=%s, expected=%v got=%v", td.service, td.username, td.password, td.expectedStatus, resp.Status)
		}
	}

	// Test OTP access to an interactive service.
	validOTP, _ := totp.GenerateCode("O32OBVS5BL5EAPB5", time.Now())
	testdata2 := []struct {
		username, password, otp string
		expectedStatus          auth.Status
		expectedTFAMethod       auth.TFAMethod
	}{
		{"testuser", "password", "", auth.StatusOK, auth.TFAMethodNone},
		{"2fauser", "bad_password", "", auth.StatusError, auth.TFAMethodNone},
		{"2fauser", "bad_password", validOTP, auth.StatusError, auth.TFAMethodNone},
		{"2fauser", "password", "", auth.StatusInsufficientCredentials, auth.TFAMethodOTP},
		{"2fauser", "password", validOTP, auth.StatusOK, auth.TFAMethodNone},
157
		{"2fauser", "password", validOTP, auth.StatusError, auth.TFAMethodNone}, // fails due to replay protection
ale's avatar
ale committed
158
159
160
		{"2fauser", "password", "123456", auth.StatusError, auth.TFAMethodNone},
	}
	for _, td := range testdata2 {
ale's avatar
ale committed
161
		resp, err := client.Authenticate(context.Background(), &auth.Request{
ale's avatar
ale committed
162
163
164
165
166
			Service:  "interactive",
			Username: td.username,
			OTP:      td.otp,
			Password: []byte(td.password),
		})
ale's avatar
ale committed
167
168
169
170
		if err != nil {
			t.Errorf("transport error: %v", err)
			continue
		}
ale's avatar
ale committed
171
172
173
		if resp.Status != td.expectedStatus {
			t.Errorf("authentication error: s=interactive u=%s p=%s, expected=%v got=%v", td.username, td.password, td.expectedStatus, resp.Status)
		}
174
175
176
177
178
179
180
181
182
183
184
		if td.expectedTFAMethod != auth.TFAMethodNone {
			found := false
			for _, m := range resp.TFAMethods {
				if m == td.expectedTFAMethod {
					found = true
					break
				}
			}
			if !found {
				t.Errorf("mismatch in TFAMethod hint in authentication response: s=interactive u=%s p=%s, expected=%v got=%v", td.username, td.password, td.expectedTFAMethod, resp.TFAMethods)
			}
ale's avatar
ale committed
185
186
187
188
189
190
191
192
193
194
		}
	}
}

func TestAuthServer(t *testing.T) {
	s := createTestServer(t, map[string]string{
		"users.yml":  testUsersFileStr,
		"config.yml": testConfigStr,
	})
	defer s.Close()
ale's avatar
ale committed
195
	runAuthenticationTest(t, &clientAdapter{s.srv})
ale's avatar
ale committed
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

func TestAuthServer_Blacklist(t *testing.T) {
	s := createTestServer(t, map[string]string{
		"users.yml":  testUsersFileStr,
		"config.yml": testConfigStrWithRatelimit,
	})
	defer s.Close()
	c := &clientAdapter{s.srv}

	// Trigger the failed login blacklist, then verify that the
	// user is blacklisted even when trying with the right password.
	for i := 0; i < 100; i++ {
		c.Authenticate(context.Background(), &auth.Request{
			Service:  "test",
			Username: "testuser",
			Password: []byte("bad_password"),
		})
	}
	resp, _ := c.Authenticate(context.Background(), &auth.Request{
		Service:  "test",
		Username: "testuser",
		Password: []byte("password"),
	})
	if resp.Status != auth.StatusError {
		t.Fatalf("user was not blacklisted: %v", resp)
	}
}

func TestAuthServer_Blacklist_BelowLimit(t *testing.T) {
	s := createTestServer(t, map[string]string{
		"users.yml":  testUsersFileStr,
		"config.yml": testConfigStrWithRatelimit,
	})
	defer s.Close()
	c := &clientAdapter{s.srv}

	// A small number of failures should not trigger the blacklist.
	for i := 0; i < 8; i++ {
		c.Authenticate(context.Background(), &auth.Request{
			Service:  "test",
			Username: "testuser",
			Password: []byte("bad_password"),
		})
	}
	resp, _ := c.Authenticate(context.Background(), &auth.Request{
		Service:  "test",
		Username: "testuser",
		Password: []byte("password"),
	})
	if resp.Status != auth.StatusOK {
ale's avatar
ale committed
247
		t.Fatal("user was incorrectly blacklisted")
248
249
	}
}
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267

func TestAuthServer_File_HasU2F(t *testing.T) {
	s := createTestServer(t, map[string]string{
		"users.yml":  testUsersFileStr,
		"config.yml": testConfigStr,
	})
	defer s.Close()

	// Check that the user U2F registrations were decoded successfully.
	svc, _ := s.srv.getService("test")
	u, ok := s.srv.getUser(context.Background(), svc, "2fauser")
	if !ok {
		t.Fatal("user not found")
	}
	if len(u.U2FRegistrations) != 1 {
		t.Fatalf("found %d u2f registrations, expecting 1", len(u.U2FRegistrations))
	}
}