model.go 15.6 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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
}

// NewLDAPBackend initializes an LDAPBackend object with the given LDAP
// connection pool.
func NewLDAPBackend(pool *ldaputil.ConnectionPool, base string) *LDAPBackend {
	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",
			}),
		},
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
		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
82
83
84
85
86
87
88
89
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
	}
}

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

148
149
150
151
152
153
154
func b2s(b bool) string {
	if b {
		return "yes"
	}
	return "no"
}

ale's avatar
ale committed
155
156
157
158
159
160
161
162
163
164
165
166
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"),
	}
}

167
168
169
170
171
172
173
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
// 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
205
206
207
208
209
210
211
212
213
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
}

214
215
216
217
218
219
220
221
222
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
223
224
225
226
227
228
229
230
231
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
}

232
233
234
235
236
237
238
239
240
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
241
242
243
244
245
246
247
248
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
}

249
250
251
252
253
254
255
256
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
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
}

278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
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
}

314
315
316
317
318
319
320
321
322
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
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
379
380
381
382
func newUser(entry *ldap.Entry) (*accountserver.User, error) {
	user := &accountserver.User{
		Name:   entry.GetAttributeValue("uid"),
		Lang:   entry.GetAttributeValue("preferredLanguage"),
		Has2FA: (entry.GetAttributeValue("totpSecret") != ""),
		//PasswordRecoveryHint: entry.GetAttributeValue("recoverQuestion"),
	}
	if user.Lang == "" {
		user.Lang = "en"
	}
	return user, nil
}

// 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")
				setAppSpecificPasswords(user, entry.GetAttributeValues("appSpecificPassword"))
			}
			// 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
}

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

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

	r.SetBackendHandle(&ldapObjectData{
		dn:       result.Entries[0].DN,
		original: r.Copy(),
	})

	return r, nil
}

// UpdateResource updates a LDAP-backed resource that was obtained by a previous GetResource call.
func (b *LDAPBackend) UpdateResource(ctx context.Context, username string, r *accountserver.Resource) error {
	lo, ok := r.GetBackendHandle().(*ldapObjectData)
	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
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
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
func parseLdapResource(entry *ldap.Entry) (*accountserver.Resource, error) {
	switch {
	case isObjectClass(entry, "virtualMailUser"):
		return newEmailResource(entry)
	case isObjectClass(entry, "ftpAccount"):
		return newWebDAVResource(entry)
	case isObjectClass(entry, "mailingList"):
		return newMailingListResource(entry)
	case isObjectClass(entry, "dbMysql"):
		return newDatabaseResource(entry)
	case isObjectClass(entry, "subSite") || isObjectClass(entry, "virtualHost"):
		return newWebsiteResource(entry)
	}
	return nil, errors.New("unknown LDAP resource")
}

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

func parseAppSpecificPassword(asp string) (*accountserver.AppSpecificPasswordInfo, error) {
	parts := strings.Split(asp, ":")
	if len(parts) != 3 {
		return nil, errors.New("badly encoded app-specific password")
	}
	return &accountserver.AppSpecificPasswordInfo{
		Service: parts[0],
		Comment: parts[2],
	}, nil
}

func setAppSpecificPasswords(user *accountserver.User, asps []string) {
	for _, asp := range asps {
		if ainfo, err := parseAppSpecificPassword(asp); err == nil {
			user.AppSpecificPasswords = append(user.AppSpecificPasswords, ainfo)
		}
	}
}

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