model.go 22.7 KB
Newer Older
ale's avatar
ale committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package backend

import (
	"context"
	"errors"
	"fmt"
	"os"
	"strings"

	ldaputil "git.autistici.org/ai3/go-common/ldap"
	"gopkg.in/ldap.v2"

	"git.autistici.org/ai3/accountserver"
)

// Generic interface to LDAP - allows us to stub out the LDAP client while
// testing.
type ldapConn interface {
	Search(context.Context, *ldap.SearchRequest) (*ldap.SearchResult, error)
20
21
	Add(context.Context, *ldap.AddRequest) error
	Modify(context.Context, *ldap.ModifyRequest) error
ale's avatar
ale committed
22
23
24
25
	Close()
}

// LDAPBackend is the interface to an LDAP-backed user database.
ale's avatar
ale committed
26
27
28
29
30
//
// We keep a set of LDAP queries for each resource type, each having a
// "resource" query to return a specific resource belonging to a user,
// and a "presence" query that checks for existence of a resource for
// all users.
ale's avatar
ale committed
31
32
33
34
type LDAPBackend struct {
	conn                ldapConn
	userQuery           *queryConfig
	userResourceQueries []*queryConfig
35
	resourceQueries     map[string]*queryConfig
ale's avatar
ale committed
36
	presenceQueries     map[string]*queryConfig
ale's avatar
ale committed
37
38
}

ale's avatar
ale committed
39
40
const ldapPoolSize = 20

ale's avatar
ale committed
41
42
// NewLDAPBackend initializes an LDAPBackend object with the given LDAP
// connection pool.
ale's avatar
ale committed
43
44
45
46
47
48
func NewLDAPBackend(uri, bindDN, bindPw, base string) (*LDAPBackend, error) {
	pool, err := ldaputil.NewConnectionPool(uri, bindDN, bindPw, ldapPoolSize)
	if err != nil {
		return nil, err
	}

ale's avatar
ale committed
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
	return &LDAPBackend{
		conn: pool,
		userQuery: mustCompileQueryConfig(&queryConfig{
			Base:  "uid=${user},ou=People," + base,
			Scope: "base",
		}),
		userResourceQueries: []*queryConfig{
			// Find all resources that are children of the main uid object.
			mustCompileQueryConfig(&queryConfig{
				Base:  "uid=${user},ou=People," + base,
				Scope: "sub",
			}),
			// Find mailing lists, which are nested under a different root.
			mustCompileQueryConfig(&queryConfig{
				Base:   "ou=Lists," + base,
				Filter: "(&(objectClass=mailingList)(listOwner=${user}))",
				Scope:  "one",
			}),
		},
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
		resourceQueries: map[string]*queryConfig{
			accountserver.ResourceTypeEmail: mustCompileQueryConfig(&queryConfig{
				Base:   "mail=${resource},uid=${user},ou=People," + base,
				Filter: "(objectClass=virtualMailUser)",
				Scope:  "base",
			}),
			accountserver.ResourceTypeWebsite: mustCompileQueryConfig(&queryConfig{
				Base:   "uid=${user},ou=People," + base,
				Filter: "(|(&(objectClass=subSite)(alias=${resource}))(&(objectClass=virtualHost)(cn=${resource})))",
				Scope:  "one",
			}),
			accountserver.ResourceTypeDAV: mustCompileQueryConfig(&queryConfig{
				Base:   "uid=${user},ou=People," + base,
				Filter: "(&(objectClass=ftpAccount)(ftpname=${resource}))",
				Scope:  "sub",
			}),
			accountserver.ResourceTypeDatabase: mustCompileQueryConfig(&queryConfig{
				Base:   "uid=${user},ou=People," + base,
				Filter: "(&(objectClass=dbMysql)(dbname=${resource}))",
				Scope:  "sub",
			}),
			accountserver.ResourceTypeMailingList: mustCompileQueryConfig(&queryConfig{
				Base:   "ou=Lists," + base,
				Filter: "(&(objectClass=mailingList)(listName=${resource}))",
				Scope:  "one",
			}),
		},
ale's avatar
ale committed
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
		presenceQueries: map[string]*queryConfig{
			accountserver.ResourceTypeEmail: mustCompileQueryConfig(&queryConfig{
				Base:   "ou=People," + base,
				Filter: "(&(objectClass=virtualMailUser)(mail=${resource}))",
				Scope:  "sub",
			}),
			accountserver.ResourceTypeWebsite: mustCompileQueryConfig(&queryConfig{
				Base:   "ou=People," + base,
				Filter: "(|(&(objectClass=subSite)(alias=${resource}))(&(objectClass=virtualHost)(cn=${resource})))",
				Scope:  "sub",
			}),
			accountserver.ResourceTypeDAV: mustCompileQueryConfig(&queryConfig{
				Base:   "ou=People," + base,
				Filter: "(&(objectClass=ftpAccount)(ftpname=${resource}))",
				Scope:  "sub",
			}),
			accountserver.ResourceTypeDatabase: mustCompileQueryConfig(&queryConfig{
				Base:   "ou=People," + base,
				Filter: "(&(objectClass=dbMysql)(dbname=${resource}))",
				Scope:  "sub",
			}),
			accountserver.ResourceTypeMailingList: mustCompileQueryConfig(&queryConfig{
				Base:   "ou=Lists," + base,
				Filter: "(&(objectClass=mailingList)(listName=${resource}))",
				Scope:  "one",
			}),
		},
ale's avatar
ale committed
122
	}, nil
ale's avatar
ale committed
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
}

func replaceVars(s string, vars map[string]string) string {
	return os.Expand(s, func(k string) string {
		return ldap.EscapeFilter(vars[k])
	})
}

// queryConfig holds the parameters for a single LDAP query.
type queryConfig struct {
	Base        string
	Filter      string
	Scope       string
	parsedScope int
}

func (q *queryConfig) validate() error {
	if q.Base == "" {
		return errors.New("empty search base")
	}
	// An empty filter is equivalent to objectClass=*.
	if q.Filter == "" {
		q.Filter = "(objectClass=*)"
	}
	q.parsedScope = ldap.ScopeWholeSubtree
	if q.Scope != "" {
		s, err := ldaputil.ParseScope(q.Scope)
		if err != nil {
			return err
		}
		q.parsedScope = s
	}
	return nil
}

func (q *queryConfig) searchRequest(vars map[string]string, attrs []string) *ldap.SearchRequest {
	return ldap.NewSearchRequest(
		replaceVars(q.Base, vars),
		q.parsedScope,
		ldap.NeverDerefAliases,
		0,
		0,
		false,
		replaceVars(q.Filter, vars),
		attrs,
		nil,
	)
}

func mustCompileQueryConfig(q *queryConfig) *queryConfig {
	if err := q.validate(); err != nil {
		panic(err)
	}
	return q
}

func s2b(s string) bool {
	switch s {
	case "yes", "y", "on", "enabled", "true":
		return true
	default:
		return false
	}
}

188
189
190
191
192
193
194
func b2s(b bool) string {
	if b {
		return "yes"
	}
	return "no"
}

ale's avatar
ale committed
195
196
197
198
199
200
201
202
203
204
205
206
func newResourceFromLDAP(entry *ldap.Entry, resourceType, nameAttr string) *accountserver.Resource {
	name := entry.GetAttributeValue(nameAttr)
	return &accountserver.Resource{
		ID:            fmt.Sprintf("%s/%s", resourceType, name),
		Name:          name,
		Type:          resourceType,
		Status:        entry.GetAttributeValue("status"),
		Shard:         entry.GetAttributeValue("host"),
		OriginalShard: entry.GetAttributeValue("originalHost"),
	}
}

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
// Convert a string to a []string with a single item, or nil if the
// string is empty. Useful for optional single-valued LDAP attributes.
func s2l(s string) []string {
	if s == "" {
		return nil
	}
	return []string{s}
}

func resourceToLDAP(r *accountserver.Resource) []ldap.PartialAttribute {
	// Assemble LDAP attributes for this resource. Use a type-specific
	// method to get attributes, then add the resource-generic ones if
	// necessary. Note that it is very important that the "objectClass"
	// attribute is returned first, or ldap.Add will fail.

	var attrs []ldap.PartialAttribute
	switch r.Type {
	case accountserver.ResourceTypeEmail:
		attrs = emailResourceToLDAP(r)
	case accountserver.ResourceTypeWebsite:
		attrs = websiteResourceToLDAP(r)
	case accountserver.ResourceTypeDAV:
		attrs = webDAVResourceToLDAP(r)
	case accountserver.ResourceTypeDatabase:
		attrs = databaseResourceToLDAP(r)
	case accountserver.ResourceTypeMailingList:
		attrs = mailingListResourceToLDAP(r)
	}

	attrs = append(attrs, []ldap.PartialAttribute{
		{Type: "status", Vals: s2l(r.Status)},
		{Type: "host", Vals: s2l(r.Shard)},
		{Type: "originalHost", Vals: s2l(r.OriginalShard)},
	}...)

	return attrs
}

ale's avatar
ale committed
245
246
247
248
249
250
251
252
253
func newEmailResource(entry *ldap.Entry) (*accountserver.Resource, error) {
	r := newResourceFromLDAP(entry, accountserver.ResourceTypeEmail, "mail")
	r.Email = &accountserver.Email{
		Aliases: entry.GetAttributeValues("mailAlternateAddr"),
		Maildir: entry.GetAttributeValue("mailMessageStore"),
	}
	return r, nil
}

254
255
256
257
258
259
260
261
262
func emailResourceToLDAP(r *accountserver.Resource) []ldap.PartialAttribute {
	return []ldap.PartialAttribute{
		{Type: "objectClass", Vals: []string{"top", "virtualMailUser"}},
		{Type: "mail", Vals: s2l(r.Name)},
		{Type: "mailAlternateAddr", Vals: r.Email.Aliases},
		{Type: "mailMessageStore", Vals: s2l(r.Email.Maildir)},
	}
}

ale's avatar
ale committed
263
264
265
266
267
268
269
270
271
func newMailingListResource(entry *ldap.Entry) (*accountserver.Resource, error) {
	r := newResourceFromLDAP(entry, accountserver.ResourceTypeMailingList, "listName")
	r.List = &accountserver.MailingList{
		Public: s2b(entry.GetAttributeValue("public")),
		Admins: entry.GetAttributeValues("listOwner"),
	}
	return r, nil
}

272
273
274
275
276
277
278
279
280
func mailingListResourceToLDAP(r *accountserver.Resource) []ldap.PartialAttribute {
	return []ldap.PartialAttribute{
		{Type: "objectClass", Vals: []string{"top", "mailingList"}},
		{Type: "listName", Vals: s2l(r.Name)},
		{Type: "public", Vals: s2l(b2s(r.List.Public))},
		{Type: "listOwner", Vals: r.List.Admins},
	}
}

ale's avatar
ale committed
281
282
283
284
285
286
287
288
func newWebDAVResource(entry *ldap.Entry) (*accountserver.Resource, error) {
	r := newResourceFromLDAP(entry, accountserver.ResourceTypeDAV, "ftpname")
	r.DAV = &accountserver.WebDAV{
		Homedir: entry.GetAttributeValue("homeDirectory"),
	}
	return r, nil
}

289
290
291
292
293
294
295
296
func webDAVResourceToLDAP(r *accountserver.Resource) []ldap.PartialAttribute {
	return []ldap.PartialAttribute{
		{Type: "objectClass", Vals: []string{"top", "person", "posixAccount", "shadowAccount", "organizationalPerson", "inetOrgPerson", "ftpAccount"}},
		{Type: "ftpname", Vals: s2l(r.Name)},
		{Type: "homeDirectory", Vals: s2l(r.DAV.Homedir)},
	}
}

ale's avatar
ale committed
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
func newWebsiteResource(entry *ldap.Entry) (*accountserver.Resource, error) {
	var r *accountserver.Resource
	if isObjectClass(entry, "subSite") {
		r = newResourceFromLDAP(entry, accountserver.ResourceTypeWebsite, "alias")
		r.Website = &accountserver.Website{
			URL:         fmt.Sprintf("https://www.%s/%s/", entry.GetAttributeValue("parentSite"), r.Name),
			DisplayName: fmt.Sprintf("%s/%s", entry.GetAttributeValue("parentSite"), r.Name),
		}
	} else {
		r = newResourceFromLDAP(entry, accountserver.ResourceTypeWebsite, "cn")
		r.Website = &accountserver.Website{
			URL:         fmt.Sprintf("https://%s/", r.Name),
			DisplayName: r.Name,
		}
	}
	r.Website.Options = entry.GetAttributeValues("option")
	r.Website.DocumentRoot = entry.GetAttributeValue("documentRoot")
	r.Website.AcceptMail = s2b(entry.GetAttributeValue("acceptMail"))
	return r, nil
}

318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
func websiteResourceToLDAP(r *accountserver.Resource) []ldap.PartialAttribute {
	// Subsites and vhosts have a different RDN.
	var mainRDN, mainOC string
	if strings.Contains(r.Website.DisplayName, "/") {
		mainRDN = "alias"
		mainOC = "subSite"
	} else {
		mainRDN = "cn"
		mainOC = "virtualHost"
	}
	return []ldap.PartialAttribute{
		{Type: "objectClass", Vals: []string{"top", mainOC}},
		{Type: mainRDN, Vals: s2l(r.Name)},
		{Type: "option", Vals: r.Website.Options},
		{Type: "documentRoot", Vals: s2l(r.Website.DocumentRoot)},
		{Type: "acceptMail", Vals: s2l(b2s(r.Website.AcceptMail))},
	}
}

ale's avatar
ale committed
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
func newDatabaseResource(entry *ldap.Entry) (*accountserver.Resource, error) {
	r := newResourceFromLDAP(entry, accountserver.ResourceTypeDatabase, "dbname")
	r.Database = &accountserver.Database{
		DBUser:            entry.GetAttributeValue("dbuser"),
		CleartextPassword: entry.GetAttributeValue("clearPassword"),
	}

	// Databases are nested below websites, so we set the ParentID by
	// looking at the LDAP DN.
	if dn, err := ldap.ParseDN(entry.DN); err == nil {
		parentRDN := dn.RDNs[1]
		r.ParentID = fmt.Sprintf("%s/%s", accountserver.ResourceTypeWebsite, parentRDN.Attributes[0].Value)
	}

	return r, nil
}

354
355
356
357
358
359
360
361
362
func databaseResourceToLDAP(r *accountserver.Resource) []ldap.PartialAttribute {
	return []ldap.PartialAttribute{
		{Type: "objectClass", Vals: []string{"top", "dbMysql"}},
		{Type: "dbname", Vals: s2l(r.Name)},
		{Type: "dbuser", Vals: s2l(r.Database.DBUser)},
		{Type: "clearPassword", Vals: s2l(r.Database.CleartextPassword)},
	}
}

ale's avatar
ale committed
363
364
365
366
type ldapUserData struct {
	dn string
}

ale's avatar
ale committed
367
368
func newUser(entry *ldap.Entry) (*accountserver.User, error) {
	user := &accountserver.User{
369
370
371
372
		Name:              entry.GetAttributeValue("uid"),
		Lang:              entry.GetAttributeValue("preferredLanguage"),
		Has2FA:            (entry.GetAttributeValue("totpSecret") != ""),
		HasEncryptionKeys: (len(entry.GetAttributeValues("storageEncryptionKey")) > 0),
ale's avatar
ale committed
373
374
375
376
377
		//PasswordRecoveryHint: entry.GetAttributeValue("recoverQuestion"),
	}
	if user.Lang == "" {
		user.Lang = "en"
	}
ale's avatar
ale committed
378
	user.Opaque = &ldapUserData{dn: entry.DN}
ale's avatar
ale committed
379
380
381
	return user, nil
}

ale's avatar
ale committed
382
383
384
385
386
387
388
389
func getUserDN(user *accountserver.User) string {
	lu, ok := user.Opaque.(*ldapUserData)
	if !ok {
		panic("no ldap user data")
	}
	return lu.dn
}

ale's avatar
ale committed
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
// GetUser returns a user.
func (b *LDAPBackend) GetUser(ctx context.Context, username string) (*accountserver.User, error) {
	// First of all, find the main user object, and just that one.
	vars := map[string]string{"user": username}
	result, err := b.conn.Search(ctx, b.userQuery.searchRequest(vars, nil))
	if err != nil {
		if ldap.IsErrorWithCode(err, ldap.LDAPResultNoSuchObject) {
			return nil, nil
		}
		return nil, err
	}

	user, err := newUser(result.Entries[0])
	if err != nil {
		return nil, err
	}

	// Now run the resource queries, and accumulate results on the User
	// object we just created.
	// TODO: parallelize.
	// TODO: add support for non-LDAP resource queries.
	for _, query := range b.userResourceQueries {
		result, err = b.conn.Search(ctx, query.searchRequest(vars, nil))
		if err != nil {
			continue
		}

		for _, entry := range result.Entries {
			// Some user-level attributes are actually stored on the email
			// object, a shortcoming of the legacy A/I database model. Set
			// them on the main User object.
			if isObjectClass(entry, "virtualMailUser") {
				user.PasswordRecoveryHint = entry.GetAttributeValue("recoverQuestion")
ale's avatar
ale committed
423
				user.AppSpecificPasswords = getASPInfo(decodeAppSpecificPasswords(entry.GetAttributeValues("appSpecificPassword")))
ale's avatar
ale committed
424
425
426
427
428
429
430
431
432
433
434
435
436
			}
			// Parse the resource and add it to the User.
			if r, err := parseLdapResource(entry); err == nil {
				user.Resources = append(user.Resources, r)
			}
		}
	}

	groupWebResourcesByHomedir(user.Resources)

	return user, nil
}

ale's avatar
ale committed
437
438
439
440
441
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
func singleAttributeQuery(dn, attribute string) *ldap.SearchRequest {
	return ldap.NewSearchRequest(
		dn,
		ldap.ScopeBaseObject,
		ldap.NeverDerefAliases,
		0,
		0,
		false,
		"(objectClass=*)",
		[]string{attribute},
		nil,
	)
}

func (b *LDAPBackend) readAttributeValues(ctx context.Context, dn, attribute string) []string {
	req := singleAttributeQuery(dn, attribute)
	result, err := b.conn.Search(ctx, req)
	if err != nil {
		return nil
	}
	if len(result.Entries) < 1 {
		return nil
	}
	return result.Entries[0].GetAttributeValues(attribute)
}

func (b *LDAPBackend) readAttributeValue(ctx context.Context, dn, attribute string) string {
	req := singleAttributeQuery(dn, attribute)
	result, err := b.conn.Search(ctx, req)
	if err != nil {
		return ""
	}
	if len(result.Entries) < 1 {
		return ""
	}
	return result.Entries[0].GetAttributeValue(attribute)
}

func (b *LDAPBackend) SetUserPassword(ctx context.Context, user *accountserver.User, encryptedPassword string) error {
	mod := ldap.NewModifyRequest(getUserDN(user))
	mod.Replace("userPassword", []string{encryptedPassword})
	return b.conn.Modify(ctx, mod)
}

func (b *LDAPBackend) GetUserEncryptionKeys(ctx context.Context, user *accountserver.User) ([]*accountserver.UserEncryptionKey, error) {
	rawKeys := b.readAttributeValues(ctx, getUserDN(user), "storageEncryptionKey")
	return accountserver.DecodeUserEncryptionKeys(rawKeys), nil
}

func (b *LDAPBackend) SetUserEncryptionKeys(ctx context.Context, user *accountserver.User, keys []*accountserver.UserEncryptionKey) error {
	mod := ldap.NewModifyRequest(getUserDN(user))
	if user.HasEncryptionKeys {
		mod.Replace("storageEncryptionKey", accountserver.EncodeUserEncryptionKeys(keys))
	} else {
		mod.Add("storageEncryptionKey", accountserver.EncodeUserEncryptionKeys(keys))
	}
	return b.conn.Modify(ctx, mod)
}

496
497
498
499
500
501
502
503
504
505
func (b *LDAPBackend) SetUserEncryptionPublicKey(ctx context.Context, user *accountserver.User, pub []byte) error {
	mod := ldap.NewModifyRequest(getUserDN(user))
	if user.HasEncryptionKeys {
		mod.Replace("storageEncryptionPublicKey", []string{string(pub)})
	} else {
		mod.Add("storageEncryptionPublicKey", []string{string(pub)})
	}
	return b.conn.Modify(ctx, mod)
}

ale's avatar
ale committed
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
func (b *LDAPBackend) SetApplicationSpecificPassword(ctx context.Context, user *accountserver.User, info *accountserver.AppSpecificPasswordInfo, encryptedPassword string) error {
	emailRsrc := user.GetSingleResourceByType(accountserver.ResourceTypeEmail)
	if emailRsrc == nil {
		return errors.New("no email resource")
	}
	emailDN := getResourceDN(emailRsrc)

	asps := decodeAppSpecificPasswords(b.readAttributeValues(ctx, emailDN, "appSpecificPassword"))
	var outASPs []*appSpecificPassword
	for _, asp := range asps {
		if asp.ID != info.ID {
			outASPs = append(outASPs, asp)
		}
	}
	outASPs = append(outASPs, newAppSpecificPassword(*info, encryptedPassword))

	mod := ldap.NewModifyRequest(emailDN)
	if len(asps) > 0 {
		mod.Replace("appSpecificPassword", encodeAppSpecificPasswords(outASPs))
	} else {
		mod.Add("appSpecificPassword", encodeAppSpecificPasswords(outASPs))
	}
	return b.conn.Modify(ctx, mod)
}

func (b *LDAPBackend) DeleteApplicationSpecificPassword(ctx context.Context, user *accountserver.User, id string) error {
	emailRsrc := user.GetSingleResourceByType(accountserver.ResourceTypeEmail)
	if emailRsrc == nil {
		return errors.New("no email resource")
	}
	emailDN := getResourceDN(emailRsrc)

	asps := decodeAppSpecificPasswords(b.readAttributeValues(ctx, emailDN, "appSpecificPassword"))
	var outASPs []*appSpecificPassword
	for _, asp := range asps {
		if asp.ID != id {
			outASPs = append(outASPs, asp)
		}
	}

	mod := ldap.NewModifyRequest(emailDN)
	if len(outASPs) == 0 {
		mod.Delete("appSpecificPassword", encodeAppSpecificPasswords(asps))
	} else if len(asps) > 0 {
		mod.Replace("appSpecificPassword", encodeAppSpecificPasswords(outASPs))
	} else {
		mod.Add("appSpecificPassword", encodeAppSpecificPasswords(outASPs))
	}
	return b.conn.Modify(ctx, mod)
}

ale's avatar
ale committed
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
func (b *LDAPBackend) SetUserTOTPSecret(ctx context.Context, user *accountserver.User, secret string) error {
	mod := ldap.NewModifyRequest(getUserDN(user))
	if b.readAttributeValue(ctx, getUserDN(user), "totpSecret") == "" {
		mod.Add("totpSecret", []string{secret})
	} else {
		mod.Replace("totpSecret", []string{secret})
	}
	return b.conn.Modify(ctx, mod)
}

func (b *LDAPBackend) DeleteUserTOTPSecret(ctx context.Context, user *accountserver.User) error {
	mod := ldap.NewModifyRequest(getUserDN(user))
	mod.Delete("totpSecret", nil)
	return b.conn.Modify(ctx, mod)
}

ale's avatar
ale committed
573
574
575
576
577
578
func (b *LDAPBackend) SetResourcePassword(ctx context.Context, _ string, r *accountserver.Resource, encryptedPassword string) error {
	mod := ldap.NewModifyRequest(getResourceDN(r))
	mod.Replace("userPassword", []string{encryptedPassword})
	return b.conn.Modify(ctx, mod)
}

579
580
581
582
583
func parseResourceID(resourceID string) (string, string) {
	parts := strings.SplitN(resourceID, "/", 2)
	return parts[0], parts[1]
}

ale's avatar
ale committed
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
611
612
613
614
615
616
617
618
func (b *LDAPBackend) hasResource(ctx context.Context, resourceID string) (bool, error) {
	resourceType, resourceName := parseResourceID(resourceID)
	query, ok := b.presenceQueries[resourceType]
	if !ok {
		return false, errors.New("unsupported resource type")
	}

	// Make a quick LDAP search that only fetches the DN attribute.
	result, err := b.conn.Search(ctx, query.searchRequest(map[string]string{
		"resource": resourceName,
		"type":     resourceType,
	}, []string{"dn"}))
	if err != nil {
		if ldap.IsErrorWithCode(err, ldap.LDAPResultNoSuchObject) {
			return false, nil
		}
		return false, err
	}
	if len(result.Entries) == 0 {
		return false, nil
	}
	return true, nil
}

// HasAnyResource returns true if any of the specified resources exists.
func (b *LDAPBackend) HasAnyResource(ctx context.Context, resourceIDs []string) (bool, error) {
	for _, resourceID := range resourceIDs {
		has, err := b.hasResource(ctx, resourceID)
		if err != nil || has {
			return has, err
		}
	}
	return false, nil
}

619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
// GetResource returns a ResourceWrapper, as part of a read-modify-update transaction.
func (b *LDAPBackend) GetResource(ctx context.Context, username, resourceID string) (*accountserver.Resource, error) {
	resourceType, resourceName := parseResourceID(resourceID)
	query, ok := b.resourceQueries[resourceType]
	if !ok {
		return nil, errors.New("unsupported resource type")
	}

	result, err := b.conn.Search(ctx, query.searchRequest(map[string]string{
		"user":     username,
		"resource": resourceName,
		"type":     resourceType,
	}, nil))
	if err != nil {
		if ldap.IsErrorWithCode(err, ldap.LDAPResultNoSuchObject) {
			return nil, nil
		}
		return nil, err
	}

ale's avatar
ale committed
639
	return parseLdapResource(result.Entries[0])
640
641
642
}

// UpdateResource updates a LDAP-backed resource that was obtained by a previous GetResource call.
ale's avatar
ale committed
643
644
func (b *LDAPBackend) UpdateResource(ctx context.Context, _ string, r *accountserver.Resource) error {
	lo, ok := r.Opaque.(*ldapObjectData)
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
	if !ok || lo == nil {
		return errors.New("resource did not come from GetResource")
	}

	modRequest := createModifyRequest(lo.dn, lo.original, r)
	if modRequest == nil {
		return nil
	}

	return b.conn.Modify(ctx, modRequest)
}

type ldapObjectData struct {
	dn       string
	original *accountserver.Resource
}

ale's avatar
ale committed
662
663
664
665
666
667
668
669
670
func getResourceDN(r *accountserver.Resource) string {
	lo, ok := r.Opaque.(*ldapObjectData)
	if !ok {
		panic("no ldap resource data")
	}
	return lo.dn
}

func parseLdapResource(entry *ldap.Entry) (r *accountserver.Resource, err error) {
ale's avatar
ale committed
671
672
	switch {
	case isObjectClass(entry, "virtualMailUser"):
ale's avatar
ale committed
673
		r, err = newEmailResource(entry)
ale's avatar
ale committed
674
	case isObjectClass(entry, "ftpAccount"):
ale's avatar
ale committed
675
		r, err = newWebDAVResource(entry)
ale's avatar
ale committed
676
	case isObjectClass(entry, "mailingList"):
ale's avatar
ale committed
677
		r, err = newMailingListResource(entry)
ale's avatar
ale committed
678
	case isObjectClass(entry, "dbMysql"):
ale's avatar
ale committed
679
		r, err = newDatabaseResource(entry)
ale's avatar
ale committed
680
	case isObjectClass(entry, "subSite") || isObjectClass(entry, "virtualHost"):
ale's avatar
ale committed
681
682
683
684
685
686
		r, err = newWebsiteResource(entry)
	default:
		return nil, errors.New("unknown LDAP resource")
	}
	if err != nil {
		return
ale's avatar
ale committed
687
	}
ale's avatar
ale committed
688
689
690
691
692
	r.Opaque = &ldapObjectData{
		dn:       entry.DN,
		original: r.Copy(),
	}
	return
ale's avatar
ale committed
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
}

func isObjectClass(entry *ldap.Entry, class string) bool {
	classes := entry.GetAttributeValues("objectClass")
	for _, c := range classes {
		if c == class {
			return true
		}
	}
	return false
}

var siteRoot = "/home/users/investici.org/"

// The hosting directory for a website is the path component immediately after
// siteRoot. This works also for sites with nested documentRoots.
func getHostingDir(path string) string {
	path = strings.TrimPrefix(path, siteRoot)
	if i := strings.Index(path, "/"); i > 0 {
		return path[:i]
	}
	return path
}

// This is a very specific function meant to address a peculiar characteristic
// of the A/I legacy data model, where DAV accounts and websites do not have an
// explicit relation.
func groupWebResourcesByHomedir(resources []*accountserver.Resource) {
	// Set the group name to be the 'hostingDir' for sites and DAV
	// accounts. Keep a reference of websites by ID so we can later fix the
	// group for databases too, via their ParentID.
	webs := make(map[string]*accountserver.Resource)
	for _, r := range resources {
		switch r.Type {
		case accountserver.ResourceTypeWebsite:
			r.Group = getHostingDir(r.Website.DocumentRoot)
			webs[r.ID] = r
		case accountserver.ResourceTypeDAV:
			r.Group = getHostingDir(r.DAV.Homedir)
		}
	}
	// Fix databases in a second pass.
	for _, r := range resources {
		if r.Type == accountserver.ResourceTypeDatabase && r.ParentID != "" {
			r.Group = webs[r.ParentID].Group
		}
	}
}