model.go 19.8 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
26
27
28
29
	Close()
}

// LDAPBackend is the interface to an LDAP-backed user database.
type LDAPBackend struct {
	conn                ldapConn
	userQuery           *queryConfig
	userResourceQueries []*queryConfig
30
	resourceQueries     map[string]*queryConfig
ale's avatar
ale committed
31
32
}

ale's avatar
ale committed
33
34
const ldapPoolSize = 20

ale's avatar
ale committed
35
36
// NewLDAPBackend initializes an LDAPBackend object with the given LDAP
// connection pool.
ale's avatar
ale committed
37
38
39
40
41
42
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
	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",
			}),
		},
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
		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
89
	}, nil
ale's avatar
ale committed
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
}

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
	}
}

155
156
157
158
159
160
161
func b2s(b bool) string {
	if b {
		return "yes"
	}
	return "no"
}

ale's avatar
ale committed
162
163
164
165
166
167
168
169
170
171
172
173
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"),
	}
}

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
// 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
212
213
214
215
216
217
218
219
220
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
}

221
222
223
224
225
226
227
228
229
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
230
231
232
233
234
235
236
237
238
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
}

239
240
241
242
243
244
245
246
247
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
248
249
250
251
252
253
254
255
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
}

256
257
258
259
260
261
262
263
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
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
}

285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
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
}

321
322
323
324
325
326
327
328
329
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
330
331
332
333
type ldapUserData struct {
	dn string
}

ale's avatar
ale committed
334
335
func newUser(entry *ldap.Entry) (*accountserver.User, error) {
	user := &accountserver.User{
336
337
338
339
		Name:              entry.GetAttributeValue("uid"),
		Lang:              entry.GetAttributeValue("preferredLanguage"),
		Has2FA:            (entry.GetAttributeValue("totpSecret") != ""),
		HasEncryptionKeys: (len(entry.GetAttributeValues("storageEncryptionKey")) > 0),
ale's avatar
ale committed
340
341
342
343
344
		//PasswordRecoveryHint: entry.GetAttributeValue("recoverQuestion"),
	}
	if user.Lang == "" {
		user.Lang = "en"
	}
ale's avatar
ale committed
345
	user.Opaque = &ldapUserData{dn: entry.DN}
ale's avatar
ale committed
346
347
348
	return user, nil
}

ale's avatar
ale committed
349
350
351
352
353
354
355
356
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
// 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
390
				user.AppSpecificPasswords = getASPInfo(decodeAppSpecificPasswords(entry.GetAttributeValues("appSpecificPassword")))
ale's avatar
ale committed
391
392
393
394
395
396
397
398
399
400
401
402
403
			}
			// 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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
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
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)
}

463
464
465
466
467
468
469
470
471
472
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
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
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)
}

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)
}

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
func parseResourceID(resourceID string) (string, string) {
	parts := strings.SplitN(resourceID, "/", 2)
	return parts[0], parts[1]
}

// 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
555
	return parseLdapResource(result.Entries[0])
556
557
558
}

// UpdateResource updates a LDAP-backed resource that was obtained by a previous GetResource call.
ale's avatar
ale committed
559
560
func (b *LDAPBackend) UpdateResource(ctx context.Context, _ string, r *accountserver.Resource) error {
	lo, ok := r.Opaque.(*ldapObjectData)
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
	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
578
579
580
581
582
583
584
585
586
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
587
588
	switch {
	case isObjectClass(entry, "virtualMailUser"):
ale's avatar
ale committed
589
		r, err = newEmailResource(entry)
ale's avatar
ale committed
590
	case isObjectClass(entry, "ftpAccount"):
ale's avatar
ale committed
591
		r, err = newWebDAVResource(entry)
ale's avatar
ale committed
592
	case isObjectClass(entry, "mailingList"):
ale's avatar
ale committed
593
		r, err = newMailingListResource(entry)
ale's avatar
ale committed
594
	case isObjectClass(entry, "dbMysql"):
ale's avatar
ale committed
595
		r, err = newDatabaseResource(entry)
ale's avatar
ale committed
596
	case isObjectClass(entry, "subSite") || isObjectClass(entry, "virtualHost"):
ale's avatar
ale committed
597
598
599
600
601
602
		r, err = newWebsiteResource(entry)
	default:
		return nil, errors.New("unknown LDAP resource")
	}
	if err != nil {
		return
ale's avatar
ale committed
603
	}
ale's avatar
ale committed
604
605
606
607
608
	r.Opaque = &ldapObjectData{
		dn:       entry.DN,
		original: r.Copy(),
	}
	return
ale's avatar
ale committed
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
}

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
		}
	}
}