integration_test.go 16.8 KB
Newer Older
ale's avatar
ale committed
1
2
3
4
package integrationtest

import (
	"bytes"
5
	"context"
ale's avatar
ale committed
6
	"encoding/json"
ale's avatar
ale committed
7
	"errors"
ale's avatar
ale committed
8
9
10
11
12
13
14
15
16
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/http/httptest"
	"os"
	"testing"
	"time"

17
	as "git.autistici.org/ai3/accountserver"
ale's avatar
ale committed
18
19
20
	"git.autistici.org/ai3/accountserver/backend"
	"git.autistici.org/ai3/accountserver/ldaptest"
	"git.autistici.org/ai3/accountserver/server"
21
22
	"git.autistici.org/ai3/go-common/pwhash"
	"git.autistici.org/ai3/go-common/userenckey"
23
	"git.autistici.org/id/go-sso"
ale's avatar
ale committed
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
	"golang.org/x/crypto/ed25519"
)

const (
	testLDAPPort = 42872
	testLDAPAddr = "ldap://127.0.0.1:42872"

	testSSODomain  = "domain"
	testSSOService = "accountserver.domain/"
	testAdminUser  = "admin"
	testAdminGroup = "admins"
)

func withSSO(t testing.TB) (func(), sso.Signer, string) {
	tmpf, err := ioutil.TempFile("", "")
	if err != nil {
		t.Fatal(err)
	}

	pub, priv, err := ed25519.GenerateKey(nil)
	if err != nil {
		t.Fatal(err)
	}
	tmpf.Write(pub)
	tmpf.Close()

	signer, err := sso.NewSigner(priv)
	if err != nil {
		t.Fatal(err)
	}

	return func() {
		os.Remove(tmpf.Name())
	}, signer, tmpf.Name()
}

type testClient struct {
	srvURL string
	signer sso.Signer
}

65
66
func (c *testClient) ssoTicket(username string, groups ...string) string {
	if len(groups) == 0 && username == testAdminUser {
ale's avatar
ale committed
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
		groups = append(groups, testAdminGroup)
	}
	signed, err := c.signer.Sign(sso.NewTicket(username, testSSOService, testSSODomain, "", groups, 1*time.Hour))
	if err != nil {
		panic(err)
	}
	return signed
}

func (c *testClient) request(uri string, req, out interface{}) error {
	data, _ := json.Marshal(req)
	resp, err := http.Post(c.srvURL+uri, "application/json", bytes.NewReader(data))
	if err != nil {
		return err
	}
	defer resp.Body.Close()
ale's avatar
ale committed
83
84
85
86
87
88
	data, _ = ioutil.ReadAll(resp.Body)

	if resp.StatusCode >= 400 && resp.StatusCode < 500 {
		log.Printf("request error: %s", string(data))
		return errors.New(string(data))
	}
ale's avatar
ale committed
89
	if resp.StatusCode != 200 {
ale's avatar
ale committed
90
		log.Printf("remote error: %s", string(data))
ale's avatar
ale committed
91
92
93
94
95
96
		return fmt.Errorf("http status code %d", resp.StatusCode)
	}
	if resp.Header.Get("Content-Type") != "application/json" {
		return fmt.Errorf("unexpected content-type %s", resp.Header.Get("Content-Type"))
	}

ale's avatar
ale committed
97
	//log.Printf("response:\n%s\n", string(data))
ale's avatar
ale committed
98
99
100
101
102
103
104

	if out == nil {
		return nil
	}
	return json.Unmarshal(data, out)
}

105
func startServiceWithConfig(t testing.TB, svcConfig as.Config) (func(), as.Backend, *testClient) {
ale's avatar
ale committed
106
	stop := ldaptest.StartServer(t, &ldaptest.Config{
107
108
109
110
111
112
113
114
		Dir:  "../ldaptest",
		Port: testLDAPPort,
		Base: "dc=example,dc=com",
		LDIFs: []string{
			"testdata/base.ldif",
			"testdata/test1.ldif",
			"testdata/test2.ldif",
		},
ale's avatar
ale committed
115
116
117
118
119
120
121
122
123
124
125
126
127
	})

	be, err := backend.NewLDAPBackend(testLDAPAddr, "cn=manager,dc=example,dc=com", "password", "dc=example,dc=com")
	if err != nil {
		t.Fatal("NewLDAPBackend", err)
	}

	ssoStop, signer, ssoPubKeyFile := withSSO(t)

	svcConfig.SSO.PublicKeyFile = ssoPubKeyFile
	svcConfig.SSO.Domain = testSSODomain
	svcConfig.SSO.Service = testSSOService
	svcConfig.SSO.AdminGroup = testAdminGroup
ale's avatar
ale committed
128
	svcConfig.ForbiddenUsernames = []string{"forbidden"}
ale's avatar
ale committed
129
	svcConfig.AvailableDomains = map[string][]string{
130
		as.ResourceTypeEmail: []string{"example.com"},
ale's avatar
ale committed
131
	}
ale's avatar
ale committed
132
	shards := []string{"host1", "host2", "host3"}
ale's avatar
ale committed
133
	svcConfig.Shards.Available = map[string][]string{
134
135
136
137
138
		as.ResourceTypeEmail:    shards,
		as.ResourceTypeWebsite:  shards,
		as.ResourceTypeDomain:   shards,
		as.ResourceTypeDAV:      shards,
		as.ResourceTypeDatabase: shards,
ale's avatar
ale committed
139
140
	}
	svcConfig.Shards.Allowed = svcConfig.Shards.Available
ale's avatar
ale committed
141
	svcConfig.WebsiteRootDir = "/home/users/investici.org"
ale's avatar
ale committed
142

143
	service, err := as.NewAccountService(be, &svcConfig)
ale's avatar
ale committed
144
145
146
147
148
149
	if err != nil {
		stop()
		t.Fatal("NewAccountService", err)
	}

	as := server.New(service, be)
150
	srv := httptest.NewServer(as)
ale's avatar
ale committed
151
152
153
154
155
156
157
158
159
160

	c := &testClient{
		srvURL: srv.URL,
		signer: signer,
	}

	return func() {
		stop()
		srv.Close()
		ssoStop()
161
	}, be, c
ale's avatar
ale committed
162
163
}

164
165
166
167
func startService(t testing.TB) (func(), as.Backend, *testClient) {
	return startServiceWithConfig(t, as.Config{})
}

ale's avatar
ale committed
168
169
170
171
// Verify that authentication on GetUser works as expected:
// - users can fetch their own data but not other users'
// - admins can read everything.
func TestIntegration_GetUser_Auth(t *testing.T) {
172
	stop, _, c := startService(t)
ale's avatar
ale committed
173
174
175
176
	defer stop()

	testdata := []struct {
		authUser   string
177
		authGroup  string
ale's avatar
ale committed
178
179
		expectedOk bool
	}{
180
181
182
183
		{"uno@investici.org", "", true},
		{"uno@investici.org", "users", true},
		{"due@investici.org", "users", false},
		{testAdminUser, testAdminGroup, true},
ale's avatar
ale committed
184
185
186
	}

	for _, td := range testdata {
187
		var user as.User
188
189
190
191
		var groups []string
		if td.authGroup != "" {
			groups = append(groups, td.authGroup)
		}
192
193
194
195
196
		err := c.request("/api/user/get", &as.GetUserRequest{
			UserRequestBase: as.UserRequestBase{
				RequestBase: as.RequestBase{
					SSO: c.ssoTicket(td.authUser, groups...),
				},
ale's avatar
ale committed
197
198
199
200
201
202
203
204
205
206
207
				Username: "uno@investici.org",
			},
		}, &user)
		if td.expectedOk && err != nil {
			t.Errorf("access error for user %s: expected ok, got error: %v", td.authUser, err)
		} else if !td.expectedOk && err == nil {
			t.Errorf("access error for user %s: expected error, got ok", td.authUser)
		}
	}
}

208
209
210
// Verify that a user can't change someone else's password.
func TestIntegration_ChangeUserPassword_AuthFail(t *testing.T) {
	stop, _, c := startService(t)
ale's avatar
ale committed
211
212
	defer stop()

213
214
215
216
	err := c.request("/api/user/change_password", &as.ChangeUserPasswordRequest{
		PrivilegedRequestBase: as.PrivilegedRequestBase{
			UserRequestBase: as.UserRequestBase{
				RequestBase: as.RequestBase{
217
					SSO: c.ssoTicket("due@investici.org"),
218
				},
ale's avatar
ale committed
219
220
				Username: "uno@investici.org",
			},
221
			CurPassword: "password",
ale's avatar
ale committed
222
223
224
225
		},
		Password: "new_password",
	}, nil)

226
227
	if err == nil {
		t.Fatal("ChangePassword for another user succeeded")
ale's avatar
ale committed
228
229
	}
}
230

231
232
// Verify various attempts at changing the password (user has no encryption keys).
func TestIntegration_ChangeUserPassword(t *testing.T) {
233
234
235
236
237
	runChangeUserPasswordTest(t, "uno@investici.org", as.Config{})
}

// Verify various attempts at changing the password (user has no encryption keys).
func TestIntegration_ChangeUserPassword_WithOpportunisticEncryption(t *testing.T) {
238
	user := runChangeUserPasswordTest(t, "uno@investici.org", as.Config{
239
240
		EnableOpportunisticEncryption: true,
	})
241
242
243
	if !user.HasEncryptionKeys {
		t.Fatal("encryption keys were not created on password change")
	}
244
245
246
247
}

// Verify various attempts at changing the password (user with encryption keys).
func TestIntegration_ChangeUserPassword_WithEncryptionKeys(t *testing.T) {
248
	runChangeUserPasswordTest(t, "due@investici.org", as.Config{})
249
250
}

251
252
func runChangeUserPasswordTest(t *testing.T, username string, cfg as.Config) *as.RawUser {
	stop, be, c := startServiceWithConfig(t, cfg)
253
254
255
256
257
258
259
260
261
262
263
264
	defer stop()

	testdata := []struct {
		password    string
		newPassword string
		expectedOk  bool
	}{
		// Ordering is important as it is meant to emulate
		// setting the password, failing to reset it, then
		// succeeding.
		{"password", "new_password", true},
		{"BADPASS", "new_password_2", false},
265
		{"new_password", "password", true},
266
267
	}
	for _, td := range testdata {
268
269
270
271
		err := c.request("/api/user/change_password", &as.ChangeUserPasswordRequest{
			PrivilegedRequestBase: as.PrivilegedRequestBase{
				UserRequestBase: as.UserRequestBase{
					RequestBase: as.RequestBase{
272
						SSO: c.ssoTicket(username),
273
					},
274
					Username: username,
275
276
277
278
279
280
281
282
283
284
285
				},
				CurPassword: td.password,
			},
			Password: td.newPassword,
		}, nil)
		if err == nil && !td.expectedOk {
			t.Fatalf("ChangeUserPassword(old=%s new=%s) should have failed but didn't", td.password, td.newPassword)
		} else if err != nil && td.expectedOk {
			t.Fatalf("ChangeUserPassword(old=%s new=%s) failed: %v", td.password, td.newPassword, err)
		}
	}
286
287
288
289

	// The password that should work at the end of the above
	// series of checks is still "password".
	return checkUserInvariants(t, be, username, "password")
290
}
ale's avatar
ale committed
291
292

func TestIntegration_CreateResource(t *testing.T) {
293
	stop, _, c := startService(t)
ale's avatar
ale committed
294
295
	defer stop()

ale's avatar
ale committed
296
	testdata := []struct {
297
		resource   *as.Resource
ale's avatar
ale committed
298
299
300
301
		expectedOk bool
	}{
		// Create a domain resource.
		{
302
303
			&as.Resource{
				ID:            as.NewResourceID(as.ResourceTypeDomain, "uno@investici.org", "example2.com"),
ale's avatar
ale committed
304
				Name:          "example2.com",
305
				Status:        as.ResourceStatusActive,
ale's avatar
ale committed
306
307
				Shard:         "host2",
				OriginalShard: "host2",
308
				Website: &as.Website{
ale's avatar
ale committed
309
					URL:          "https://example2.com",
ale's avatar
ale committed
310
					DocumentRoot: "/home/users/investici.org/uno/html-example2.com",
ale's avatar
ale committed
311
312
313
					AcceptMail:   true,
				},
			},
ale's avatar
ale committed
314
315
316
317
318
			true,
		},

		// Duplicate of the above request, should fail due to conflict.
		{
319
320
			&as.Resource{
				ID:            as.NewResourceID(as.ResourceTypeDomain, "uno@investici.org", "example2.com"),
ale's avatar
ale committed
321
				Name:          "example2.com",
322
				Status:        as.ResourceStatusActive,
ale's avatar
ale committed
323
324
				Shard:         "host2",
				OriginalShard: "host2",
325
				Website: &as.Website{
ale's avatar
ale committed
326
327
328
329
330
331
332
					URL:          "https://example2.com",
					DocumentRoot: "/home/users/investici.org/uno/html-example2.com",
				},
			},
			false,
		},

ale's avatar
ale committed
333
		// Empty document root will be fixed by templating.
ale's avatar
ale committed
334
		{
335
336
			&as.Resource{
				ID:            as.NewResourceID(as.ResourceTypeDomain, "uno@investici.org", "example3.com"),
ale's avatar
ale committed
337
				Name:          "example3.com",
338
				Status:        as.ResourceStatusActive,
ale's avatar
ale committed
339
340
				Shard:         "host2",
				OriginalShard: "host2",
341
				Website:       &as.Website{},
ale's avatar
ale committed
342
			},
ale's avatar
ale committed
343
			true,
ale's avatar
ale committed
344
345
346
347
		},

		// Malformed resource metadata (name fails validation).
		{
348
349
			&as.Resource{
				ID:            as.NewResourceID(as.ResourceTypeDomain, "uno@investici.org", "example$.com"),
ale's avatar
ale committed
350
				Name:          "example$.com",
351
				Status:        as.ResourceStatusActive,
ale's avatar
ale committed
352
353
				Shard:         "host2",
				OriginalShard: "host2",
354
				Website: &as.Website{
ale's avatar
ale committed
355
356
357
358
359
360
361
362
363
					URL:          "https://example$.com",
					DocumentRoot: "/home/users/investici.org/uno/html-example3.com",
				},
			},
			false,
		},

		// Bad shard.
		{
364
365
			&as.Resource{
				ID:            as.NewResourceID(as.ResourceTypeDomain, "uno@investici.org", "example3.com"),
ale's avatar
ale committed
366
				Name:          "example4.com",
367
				Status:        as.ResourceStatusActive,
ale's avatar
ale committed
368
369
				Shard:         "zebra",
				OriginalShard: "zebra",
370
				Website: &as.Website{
ale's avatar
ale committed
371
372
					URL:          "https://example4.com",
					DocumentRoot: "/home/users/investici.org/uno/html-example4.com",
ale's avatar
ale committed
373
374
375
376
377
378
379
				},
			},
			false,
		},

		// The document root has no associated DAV account.
		{
380
381
			&as.Resource{
				ID:            as.NewResourceID(as.ResourceTypeDomain, "uno@investici.org", "example3.com"),
ale's avatar
ale committed
382
				Name:          "example5.com",
383
				Status:        as.ResourceStatusActive,
ale's avatar
ale committed
384
385
				Shard:         "host2",
				OriginalShard: "host2",
386
				Website: &as.Website{
ale's avatar
ale committed
387
388
					URL:          "https://example5.com",
					DocumentRoot: "/home/users/investici.org/nonexisting",
ale's avatar
ale committed
389
390
391
392
393
394
395
				},
			},
			false,
		},
	}

	for _, td := range testdata {
396
397
398
399
400
401
402
		err := c.request("/api/resource/create", &as.CreateResourcesRequest{
			AdminRequestBase: as.AdminRequestBase{
				RequestBase: as.RequestBase{
					SSO: c.ssoTicket(testAdminUser),
				},
			},
			Resources: []*as.Resource{td.resource},
ale's avatar
ale committed
403
404
405
406
407
408
409
410
411
		}, nil)
		if err == nil && !td.expectedOk {
			t.Errorf("CreateResource(%s) should have failed but didn't", td.resource.ID)
		} else if err != nil && td.expectedOk {
			t.Errorf("CreateResource(%s) failed: %v", td.resource.ID, err)
		}
	}
}

ale's avatar
ale committed
412
func TestIntegration_CreateMultipleResources_WithTemplate(t *testing.T) {
413
	stop, _, c := startService(t)
ale's avatar
ale committed
414
415
	defer stop()

ale's avatar
ale committed
416
417
	// The create request is very bare, most values will be filled
	// in by the server using resource templates.
418
419
420
421
422
423
424
425
426
	err := c.request("/api/resource/create", &as.CreateResourcesRequest{
		AdminRequestBase: as.AdminRequestBase{
			RequestBase: as.RequestBase{
				SSO: c.ssoTicket(testAdminUser),
			},
		},
		Resources: []*as.Resource{
			&as.Resource{
				ID:   as.NewResourceID(as.ResourceTypeDomain, "uno@investici.org", "example3.com"),
ale's avatar
ale committed
427
				Name: "example3.com",
ale's avatar
ale committed
428
			},
429
430
			&as.Resource{
				ID:   as.NewResourceID(as.ResourceTypeDAV, "uno@investici.org", "example3dav"),
ale's avatar
ale committed
431
432
				Name: "example3dav",
			},
433
434
435
			&as.Resource{
				ID:       as.NewResourceID(as.ResourceTypeDatabase, "uno@investici.org", "cn=example3.com", "example3"),
				ParentID: as.NewResourceID(as.ResourceTypeDomain, "uno@investici.org", "example3.com"),
ale's avatar
ale committed
436
				Name:     "example3",
ale's avatar
ale committed
437
			},
ale's avatar
ale committed
438
439
440
		},
	}, nil)
	if err != nil {
ale's avatar
ale committed
441
		t.Errorf("CreateResources failed: %v", err)
ale's avatar
ale committed
442
443
	}
}
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539

func TestIntegration_CreateUser(t *testing.T) {
	stop, be, c := startService(t)
	defer stop()

	// The create request is very bare, most values will be filled
	// in by the server using resource templates.
	var resp as.CreateUserResponse
	err := c.request("/api/user/create", &as.CreateUserRequest{
		AdminRequestBase: as.AdminRequestBase{
			RequestBase: as.RequestBase{
				SSO: c.ssoTicket(testAdminUser),
			},
		},
		User: &as.User{
			Name: "newuser@example.com",
			Resources: []*as.Resource{
				&as.Resource{
					ID:   as.NewResourceID(as.ResourceTypeEmail, "newuser@example.com", "newuser@example.com"),
					Name: "newuser@example.com",
				},
			},
		},
	}, &resp)
	if err != nil {
		t.Fatalf("CreateUser failed: %v", err)
	}

	if resp.Password == "" {
		t.Fatalf("no password in response (%v)", resp)
	}

	// Verify that the new password works.
	checkUserInvariants(t, be, "newuser@example.com", resp.Password)
}

func TestIntegration_AccountRecovery(t *testing.T) {
	runAccountRecoveryTest(t, "uno@investici.org")
}

func TestIntegration_AccountRecovery_WithEncryptionKeys(t *testing.T) {
	user := runAccountRecoveryTest(t, "due@investici.org")
	if !user.HasEncryptionKeys {
		t.Fatalf("encryption keys not enabled after account recovery")
	}
}

func runAccountRecoveryTest(t *testing.T, username string) *as.RawUser {
	stop, be, c := startService(t)
	defer stop()

	hint := "secret code?"
	secondaryPw := "open sesame!"
	err := c.request("/api/user/set_account_recovery_hint", &as.SetAccountRecoveryHintRequest{
		PrivilegedRequestBase: as.PrivilegedRequestBase{
			UserRequestBase: as.UserRequestBase{
				RequestBase: as.RequestBase{
					SSO: c.ssoTicket(username),
				},
				Username: username,
			},
			CurPassword: "password",
		},
		Hint:     hint,
		Response: secondaryPw,
	}, nil)
	if err != nil {
		t.Fatalf("SetAccountRecoveryHint failed: %v", err)
	}

	// The first request just fetches the recovery hint.
	var resp as.AccountRecoveryResponse
	err = c.request("/api/recover_account", &as.AccountRecoveryRequest{
		Username: username,
	}, &resp)
	if err != nil {
		t.Fatalf("AccountRecovery (hint only) failed: %v", err)
	}
	if resp.Hint != hint {
		t.Fatalf("bad AccountRecovery hint, got '%s' expected '%s'", resp.Hint, hint)
	}

	// Now recover the account and set a new password.
	newPw := "new password"
	err = c.request("/api/recover_account", &as.AccountRecoveryRequest{
		Username:         username,
		RecoveryPassword: secondaryPw,
		Password:         newPw,
	}, &resp)
	if err != nil {
		t.Fatalf("AccountRecovery failed: %v", err)
	}

	return checkUserInvariants(t, be, username, newPw)
}

ale's avatar
ale committed
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
func TestIntegration_AddEmailAlias(t *testing.T) {
	stop, _, c := startService(t)
	defer stop()

	// The following are basically checks for email validation.
	testdata := []struct {
		addr       string
		expectedOk bool
	}{
		{"alias@example.com", false},     // already taken
		{"alias@otherdomain.com", false}, // bad domain
		{"x@example.com", false},         // too short
		{"........@example.com", false},  // malformed
		{"due@investici.org", false},     // already taken
		{"forbidden@example.com", false}, // reserved
		{"alias1@example.com", true},
		{"alias2@example.com", true},
		{"alias3@example.com", true},
		{"alias4@example.com", true},
		{"alias5@example.com", false}, // limit of 5 aliases reached
	}

	for _, td := range testdata {
		err := c.request("/api/resource/email/add_alias", &as.AddEmailAliasRequest{
			ResourceRequestBase: as.ResourceRequestBase{
				RequestBase: as.RequestBase{
					SSO: c.ssoTicket("uno@investici.org"),
				},
				ResourceID: as.NewResourceID(as.ResourceTypeEmail, "uno@investici.org", "uno@investici.org"),
			},
			Addr: td.addr,
		}, nil)
		if err == nil && !td.expectedOk {
			t.Errorf("AddEmailAlias(%s) should have failed but didn't", td.addr)
		} else if err != nil && td.expectedOk {
			t.Errorf("AddEmailAlias(%s) failed: %v", td.addr, err)
		}
	}
}

580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
// Verify that some user authentication invariants are true. Returns
// the RawUser for further checks.
func checkUserInvariants(t *testing.T, be as.Backend, username, primaryPassword string) *as.RawUser {
	tx, _ := be.NewTransaction()
	user, err := tx.GetUser(context.Background(), username)
	if err != nil {
		t.Fatalf("GetUser(%s): %v", username, err)
	}

	// Verify that the password is correct.
	if !pwhash.ComparePassword(user.Password, primaryPassword) {
		t.Fatalf("password for user %s is not %s", username, primaryPassword)
	}

	// Verify that we can successfully encrypt keys.
	if user.HasEncryptionKeys {
		if _, err := userenckey.Decrypt(keysToBytes(user.Keys), []byte(primaryPassword)); err != nil {
			t.Fatalf("password for user %s can't decrypt keys", username)
		}
	}

	return user
}

func keysToBytes(keys []*as.UserEncryptionKey) [][]byte {
	var rawKeys [][]byte
	for _, k := range keys {
		rawKeys = append(rawKeys, k.Key)
	}
	return rawKeys
}