model_test.go 10.6 KB
Newer Older
1 2 3
package backend

import (
ale's avatar
ale committed
4
	"context"
5
	"fmt"
6
	"testing"
7
	"time"
8

ale's avatar
ale committed
9
	"github.com/go-test/deep"
10

11
	as "git.autistici.org/ai3/accountserver"
12
	"git.autistici.org/ai3/accountserver/ldaptest"
13 14
)

ale's avatar
ale committed
15 16 17 18
const (
	testLDAPPort = 42871
	testLDAPAddr = "ldap://127.0.0.1:42871"
	testUser1    = "uno@investici.org"
19 20
	testUser2    = "due@investici.org" // has encryption keys
	testUser3    = "tre@investici.org" // has OTP
21
	testBaseDN   = "dc=example,dc=com"
ale's avatar
ale committed
22
)
23

24
func startServerAndGetUser(t testing.TB) (func(), as.Backend, *as.RawUser) {
25 26 27
	return startServerAndGetUserWithName(t, testUser1)
}

28
func startServerAndGetUser2(t testing.TB) (func(), as.Backend, *as.RawUser) {
29 30 31
	return startServerAndGetUserWithName(t, testUser2)
}

32 33 34 35
func startServerAndGetUser3(t testing.TB) (func(), as.Backend, *as.RawUser) {
	return startServerAndGetUserWithName(t, testUser3)
}

36
func startServer(t testing.TB) (func(), as.Backend) {
37
	stop := ldaptest.StartServer(t, &ldaptest.Config{
38 39 40 41 42 43 44
		Dir:  "../ldaptest",
		Port: testLDAPPort,
		Base: "dc=example,dc=com",
		LDIFs: []string{
			"testdata/base.ldif",
			"testdata/test1.ldif",
			"testdata/test2.ldif",
45
			"testdata/test3.ldif",
46
		},
ale's avatar
ale committed
47 48 49 50 51 52
	})

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

54 55 56
	return stop, b
}

57
func startServerAndGetUserWithName(t testing.TB, username string) (func(), as.Backend, *as.RawUser) {
58 59
	stop, b := startServer(t)

ale's avatar
ale committed
60
	tx, _ := b.NewTransaction()
61
	user, err := tx.GetUser(context.Background(), username)
62
	if err != nil {
ale's avatar
ale committed
63 64 65
		t.Fatal("GetUser", err)
	}
	if user == nil {
66
		t.Fatalf("could not find test user %s", username)
ale's avatar
ale committed
67 68
	}

69 70 71
	return stop, b, user
}

72 73 74 75 76 77 78 79 80 81 82 83 84 85
func TestModel_GetUser_NotFound(t *testing.T) {
	stop, b := startServer(t)
	defer stop()

	tx, _ := b.NewTransaction()
	user, err := tx.GetUser(context.Background(), "wrong_user")
	if err != nil {
		t.Fatalf("GetUser(wrong_user) should have returned no error, got: %v", err)
	}
	if user != nil {
		t.Fatal("GetUser(wrong_user) returned non-nil user")
	}
}

86 87 88
func TestModel_GetUser(t *testing.T) {
	stop, _, user := startServerAndGetUser(t)
	defer stop()
ale's avatar
ale committed
89 90

	if user.Name != testUser1 {
91
		t.Errorf("bad username: expected %s, got %s", testUser1, user.Name)
ale's avatar
ale committed
92
	}
93
	if len(user.Resources) != 5 {
94 95 96 97 98
		t.Errorf("expected 5 resources, got %d", len(user.Resources))
	}
	expectedPwChangeStamp := time.Date(2018, 11, 14, 0, 0, 0, 0, time.UTC)
	if user.LastPasswordChangeStamp != expectedPwChangeStamp {
		t.Errorf("bad last password change timestamp: expected %s, got %s", expectedPwChangeStamp, user.LastPasswordChangeStamp)
ale's avatar
ale committed
99 100 101
	}

	// Test a specific resource (the database).
102 103
	db := user.GetSingleResourceByType(as.ResourceTypeDatabase)
	expectedDB := &as.Resource{
104 105 106
		ID:            as.ResourceID("dbname=unodb,alias=uno,uid=uno@investici.org,ou=People,dc=example,dc=com"),
		Type:          as.ResourceTypeDatabase,
		ParentID:      as.ResourceID("alias=uno,uid=uno@investici.org,ou=People,dc=example,dc=com"),
ale's avatar
ale committed
107 108 109
		Name:          "unodb",
		Shard:         "host2",
		OriginalShard: "host2",
110 111
		Status:        as.ResourceStatusActive,
		Database: &as.Database{
ale's avatar
ale committed
112 113
			CleartextPassword: "password",
			DBUser:            "unodb",
114 115
		},
	}
ale's avatar
ale committed
116 117
	if err := deep.Equal(db, expectedDB); err != nil {
		t.Fatalf("returned database resource differs: %v", err)
118 119 120
	}
}

121
func TestModel_GetUser_HasEncryptionKeys(t *testing.T) {
122 123 124 125
	stop, _, user := startServerAndGetUser2(t)
	defer stop()

	if !user.HasEncryptionKeys {
126 127 128 129 130 131 132 133 134 135
		t.Errorf("user %s does not appear to have encryption keys", user.Name)
	}
}

func TestModel_GetUser_Has2FA(t *testing.T) {
	stop, _, user := startServerAndGetUser3(t)
	defer stop()

	if !user.Has2FA {
		t.Errorf("user %s does not appear to have 2FA enabled", user.Name)
136 137 138
	}
}

139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
func TestModel_GetUser_Resources(t *testing.T) {
	stop, b, user := startServerAndGetUser(t)
	defer stop()

	// Fetch individually all user resources, one by one, and
	// check that they match what we have already.
	tx2, _ := b.NewTransaction()
	for _, r := range user.Resources {
		fr, err := tx2.GetResource(context.Background(), r.ID)
		if err != nil {
			t.Errorf("could not fetch resource %s: %v", r.ID, err)
			continue
		}
		if fr == nil {
			t.Errorf("resource %s is missing", r.ID)
			continue
		}
		// It's ok if Group is unset in the GetResource response.
		rr := *r
		rr.Group = ""
159
		if err := deep.Equal(&fr.Resource, &rr); err != nil {
160 161 162 163 164 165
			t.Errorf("error in fetched resource %s: %v", r.ID, err)
			continue
		}
	}
}

166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
func TestModel_SearchUser(t *testing.T) {
	stop, b := startServer(t)
	defer stop()
	tx, _ := b.NewTransaction()
	users, err := tx.SearchUser(context.Background(), "uno")
	if err != nil {
		t.Fatal(err)
	}
	if len(users) != 1 {
		t.Fatalf("expected 1 user, got %d", len(users))
	}
	if users[0] != testUser1 {
		t.Fatalf("expected %s, got %s", testUser1, users[0])
	}
}

ale's avatar
ale committed
182
func TestModel_SetResourceStatus(t *testing.T) {
183 184
	stop := ldaptest.StartServer(t, &ldaptest.Config{
		Dir:   "../ldaptest",
ale's avatar
ale committed
185 186 187 188 189
		Port:  testLDAPPort,
		Base:  "dc=example,dc=com",
		LDIFs: []string{"testdata/base.ldif", "testdata/test1.ldif"},
	})
	defer stop()
190

ale's avatar
ale committed
191
	b, err := NewLDAPBackend(testLDAPAddr, "cn=manager,dc=example,dc=com", "password", "dc=example,dc=com")
192
	if err != nil {
ale's avatar
ale committed
193
		t.Fatal("NewLDAPBackend", err)
194 195
	}

ale's avatar
ale committed
196
	tx, _ := b.NewTransaction()
197 198
	rsrcID := as.ResourceID(fmt.Sprintf("mail=%s,uid=%s,ou=People,dc=example,dc=com", testUser1, testUser1))
	rr, err := tx.GetResource(context.Background(), rsrcID)
ale's avatar
ale committed
199 200
	if err != nil {
		t.Fatal("GetResource", err)
201
	}
202
	if rr == nil {
ale's avatar
ale committed
203 204 205
		t.Fatalf("could not find test resource %s", rsrcID)
	}

206 207
	rr.Status = as.ResourceStatusInactive
	if err := tx.UpdateResource(context.Background(), &rr.Resource); err != nil {
ale's avatar
ale committed
208 209 210 211
		t.Fatal("UpdateResource", err)
	}
	if err := tx.Commit(context.Background()); err != nil {
		t.Fatalf("commit error: %v", err)
212 213
	}
}
214

ale's avatar
ale committed
215
func TestModel_HasAnyResource(t *testing.T) {
216 217
	stop := ldaptest.StartServer(t, &ldaptest.Config{
		Dir:   "../ldaptest",
ale's avatar
ale committed
218
		Port:  testLDAPPort,
219
		Base:  "dc=example,dc=com",
ale's avatar
ale committed
220
		LDIFs: []string{"testdata/base.ldif", "testdata/test1.ldif"},
221 222 223
	})
	defer stop()

ale's avatar
ale committed
224
	b, err := NewLDAPBackend(testLDAPAddr, "cn=manager,dc=example,dc=com", "password", "dc=example,dc=com")
225 226 227
	if err != nil {
		t.Fatal("NewLDAPBackend", err)
	}
ale's avatar
ale committed
228 229 230 231

	tx, _ := b.NewTransaction()

	// Request that should succeed.
232 233 234
	ok, err := tx.HasAnyResource(context.Background(), []as.FindResourceRequest{
		{Type: as.ResourceTypeEmail, Name: "foo"},
		{Type: as.ResourceTypeEmail, Name: testUser1},
ale's avatar
ale committed
235 236 237 238 239
	})
	if err != nil {
		t.Fatal("HasAnyResource", err)
	}
	if !ok {
240
		t.Fatal("could not find test email resource")
ale's avatar
ale committed
241 242 243
	}

	// Request that should fail (bad resource type).
244 245
	ok, err = tx.HasAnyResource(context.Background(), []as.FindResourceRequest{
		{Type: as.ResourceTypeDatabase, Name: testUser1},
ale's avatar
ale committed
246 247 248 249 250 251 252
	})
	if err != nil {
		t.Fatal("HasAnyResource", err)
	}
	if ok {
		t.Fatal("oops, found non existing resource")
	}
253
}
254

ale's avatar
ale committed
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
func TestModel_SearchResource(t *testing.T) {
	stop, b := startServer(t)
	defer stop()

	for _, pattern := range []string{"uno@investici.org", "uno*"} {
		tx, _ := b.NewTransaction()
		resources, err := tx.SearchResource(context.Background(), "uno@investici.org")
		if err != nil {
			t.Fatalf("SearchUser(%s): %v", pattern, err)
		}
		if len(resources) != 1 {
			t.Fatalf("SearchUser(%s): expected 1 resource, got %d", pattern, len(resources))
		}
		if resources[0].Owner != "uno@investici.org" {
			t.Fatalf("SearchUser(%s): resource owner is %s, expected uno@investici.org", pattern, resources[0].Owner)
		}
	}
}

274 275 276 277 278 279 280
func TestModel_SetUserPassword(t *testing.T) {
	stop, b, user := startServerAndGetUser(t)
	defer stop()

	encPass := "encrypted password"

	tx, _ := b.NewTransaction()
281
	if err := tx.SetUserPassword(context.Background(), &user.User, encPass); err != nil {
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
		t.Fatal("SetUserPassword", err)
	}
	if err := tx.Commit(context.Background()); err != nil {
		t.Fatal("Commit", err)
	}

	// Verify that the new password is set.
	pwattr := tx.(*backendTX).readAttributeValues(
		context.Background(),
		"mail=uno@investici.org,uid=uno@investici.org,ou=People,dc=example,dc=com",
		"userPassword",
	)
	if len(pwattr) == 0 {
		t.Fatalf("no userPassword attribute on mail= object")
	}
	if len(pwattr) > 1 {
		t.Fatalf("more than one userPassword found on mail= object")
	}
	if pwattr[0] != encPass {
		t.Fatalf("bad userPassword, got %s, expected %s", pwattr[0], encPass)
	}
}

func TestModel_SetUserEncryptionKeys_Add(t *testing.T) {
	stop, b, user := startServerAndGetUser(t)
	defer stop()

	tx, _ := b.NewTransaction()
310
	keys := []*as.UserEncryptionKey{
311
		{
312
			ID:  as.UserEncryptionKeyMainID,
313 314 315
			Key: []byte("very secret key"),
		},
	}
316
	if err := tx.SetUserEncryptionKeys(context.Background(), &user.User, keys); err != nil {
317 318 319 320 321 322 323 324 325 326 327 328
		t.Fatal("SetUserEncryptionKeys", err)
	}
	if err := tx.Commit(context.Background()); err != nil {
		t.Fatal("Commit", err)
	}
}

func TestModel_SetUserEncryptionKeys_Replace(t *testing.T) {
	stop, b, user := startServerAndGetUser2(t)
	defer stop()

	tx, _ := b.NewTransaction()
329
	keys := []*as.UserEncryptionKey{
330
		{
331
			ID:  as.UserEncryptionKeyMainID,
332 333 334
			Key: []byte("very secret key"),
		},
	}
335
	if err := tx.SetUserEncryptionKeys(context.Background(), &user.User, keys); err != nil {
336 337 338 339 340 341
		t.Fatal("SetUserEncryptionKeys", err)
	}
	if err := tx.Commit(context.Background()); err != nil {
		t.Fatal("Commit", err)
	}
}
ale's avatar
ale committed
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378

func TestModel_NextUID(t *testing.T) {
	stop, b, user := startServerAndGetUser(t)
	defer stop()
	tx, _ := b.NewTransaction()

	// User UID should not be available.
	ok, err := tx.(*backendTX).isUIDAvailable(context.Background(), user.UID)
	if err != nil {
		t.Fatal("isUIDAvailable", err)
	}
	if ok {
		t.Fatalf("oops, the uid of the existing user (%d) appears to be available", user.UID)
	}

	// Check a UID that should be available instead.
	freeUID := 4096
	ok, err = tx.(*backendTX).isUIDAvailable(context.Background(), freeUID)
	if err != nil {
		t.Fatal("isUIDAvailable", err)
	}
	if !ok {
		t.Fatalf("oops, a supposedly free uid (%d) appears to be unavailable", freeUID)
	}

	// Generate a new UID.
	uid, err := tx.NextUID(context.Background())
	if err != nil {
		t.Fatal("NextUID", err)
	}
	if uid == 0 {
		t.Fatal("uid is 0")
	}
	if uid == user.UID { // not that it's likely
		t.Fatalf("uid is the same as the existing user ID (%d)", user.UID)
	}
}
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407

func TestSortResources(t *testing.T) {
	rsrcs := []*as.Resource{
		&as.Resource{
			ID:       "id1",
			ParentID: "id4",
		},
		&as.Resource{
			ID:       "id2",
			ParentID: "id4",
		},
		&as.Resource{
			ID: "id3",
		},
		&as.Resource{
			ID:       "id4",
			ParentID: "id3",
		},
	}
	expected := []string{"id3", "id4", "id1", "id2"}

	var ids []string
	for _, r := range sortResourcesByDepth(rsrcs) {
		ids = append(ids, r.ID.String())
	}
	if diff := deep.Equal(ids, expected); diff != nil {
		t.Fatalf("bad ordering: got %v, expected %v", ids, expected)
	}
}