model.go 9.65 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
20
21
22
23
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
65
66
67
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
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
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
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)
	Close()
}

// LDAPBackend is the interface to an LDAP-backed user database.
type LDAPBackend struct {
	conn                ldapConn
	userQuery           *queryConfig
	userResourceQueries []*queryConfig
}

// 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",
			}),
		},
	}
}

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

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

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
}

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
}

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
}

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
}

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
}

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
}

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