types.go 18.7 KB
Newer Older
ale's avatar
ale committed
1 2
package accountserver

ale's avatar
ale committed
3
import (
4
	"context"
5
	"encoding/json"
ale's avatar
ale committed
6
	"fmt"
ale's avatar
ale committed
7 8
	"strings"
	"time"
9

10
	"git.autistici.org/ai3/go-common/pwhash"
ale's avatar
ale committed
11
)
ale's avatar
ale committed
12

ale's avatar
ale committed
13 14 15 16 17 18
// Possible values for user status.
const (
	UserStatusActive   = "active"
	UserStatusInactive = "inactive"
)

19 20 21 22 23 24 25
// The password hashing algorithm to use when updating credentials.
var DefaultPasswordHash pwhash.PasswordHash

func init() {
	DefaultPasswordHash = pwhash.DefaultEncryptAlgorithm
}

ale's avatar
ale committed
26
// User information, public: includes data *about* credentials, but
ale's avatar
ale committed
27 28
// not the credentials themselves. Every user has a unique
// identifier, which may be an email address.
ale's avatar
ale committed
29 30 31 32 33 34 35
type User struct {
	// Name of the user. Also its email.
	Name string `json:"name"`

	// Preferred language.
	Lang string `json:"lang"`

ale's avatar
ale committed
36 37 38
	// UNIX user id.
	UID int `json:"uid"`

39 40 41 42
	// Timestamp of last password change. This is serialized as a
	// RFC3339 string in JSON.
	LastPasswordChangeStamp time.Time `json:"last_password_change_stamp"`

ale's avatar
ale committed
43 44 45 46 47 48
	// User status.
	Status string `json:"status"`

	// Shard for temporary resources (must match the email resources).
	Shard string `json:"shard"`

49 50 51 52 53 54 55 56 57
	// Has2FA is true if the user has a second-factor authentication
	// mechanism properly set up. In practice, this is the case if either
	// HasOTP is true, or len(U2FRegistrations) > 0.
	Has2FA bool `json:"has_2fa"`

	// HasOTP is true if TOTP is set up.
	HasOTP bool `json:"has_otp"`

	// HasEncryptionKeys is true if encryption keys are properly set up for
58
	// this user.
59 60
	HasEncryptionKeys bool `json:"has_encryption_keys"`

61
	// The recovery hint for this account (empty if unset).
62
	AccountRecoveryHint string `json:"account_recovery_hint"`
ale's avatar
ale committed
63

64
	// List of application-specific passwords (metadata only).
ale's avatar
ale committed
65 66
	AppSpecificPasswords []*AppSpecificPasswordInfo `json:"app_specific_passwords,omitempty"`

67
	// List of U2F registrations.
68
	U2FRegistrations []*U2FRegistration `json:"u2f_registrations,omitempty"`
69

70
	// All the resources owned by this user.
ale's avatar
ale committed
71
	Resources []*Resource `json:"resources,omitempty"`
ale's avatar
ale committed
72 73
}

ale's avatar
ale committed
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
// GetResourceByID returns the resource with the specified ID, or nil
// if not found.
func (u *User) GetResourceByID(id ResourceID) *Resource {
	for _, r := range u.Resources {
		if r.ID.Equal(id) {
			return r
		}
	}
	return nil
}

// GetResourcesByType returns all resources with the specified type.
func (u *User) GetResourcesByType(resourceType string) []*Resource {
	var out []*Resource
	for _, r := range u.Resources {
ale's avatar
ale committed
89
		if r.Type == resourceType {
ale's avatar
ale committed
90 91 92 93 94 95 96 97 98 99
			out = append(out, r)
		}
	}
	return out
}

// GetSingleResourceByType returns a single resource of the specified
// type. If there are none, returns nil.
func (u *User) GetSingleResourceByType(resourceType string) *Resource {
	for _, r := range u.Resources {
ale's avatar
ale committed
100
		if r.Type == resourceType {
ale's avatar
ale committed
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
			return r
		}
	}
	return nil
}

// GetResourcesByGroup returns all resources belonging to the specified group.
func (u *User) GetResourcesByGroup(group string) []*Resource {
	var out []*Resource
	for _, r := range u.Resources {
		if r.Group == group {
			out = append(out, r)
		}
	}
	return out
}

ale's avatar
ale committed
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
// AllEmailAddrs is a convenience function that returns all
// (non-inactive) email addresses for this User.
func (u *User) AllEmailAddrs() []string {
	var addrs []string
	for _, r := range u.Resources {
		if r.Type == ResourceTypeEmail && r.Status != ResourceStatusInactive {
			addrs = append(addrs, r.Name)
			if r.Email != nil && len(r.Email.Aliases) > 0 {
				addrs = append(addrs, r.Email.Aliases...)
			}
		}
	}
	return addrs
}

133 134 135 136 137 138 139 140 141
// RawUser extends User with private information (as stored in the
// database) that we have a direct use for.
//
// Its methods manipulate authentication-related data and enforce its
// consistency, so they may have side effects such as maintaining
// encryption keys up to date, or disabling secondary authentication
// mechanisms. In any case both the database and the underlying User
// object are kept in sync.
//
ale's avatar
ale committed
142 143
// The separation between User and RawUser makes it easier to prevent
// private data from being served over the API.
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
type RawUser struct {
	User

	// Password for local authentication of privileged actions
	// (these are encrypted!).
	Password         string
	RecoveryPassword string

	// Encryption keys need to change whenever there is a change
	// in authentication parameters, so keep them around.
	Keys encryptedKeyList
}

// Disable 2FA for a user account.
func (u *RawUser) disable2FA(ctx context.Context, tx TX) error {
	// Disable OTP.
	if u.HasOTP {
		if err := tx.DeleteUserTOTPSecret(ctx, &u.User); err != nil {
			return newBackendError(err)
		}
		u.HasOTP = false
	}

	// Disable U2F.
	if len(u.U2FRegistrations) > 0 {
		u.U2FRegistrations = nil
		if err := tx.UpdateUser(ctx, &u.User); err != nil {
			return newBackendError(err)
		}
	}

	u.Has2FA = false
	return u.deleteAllApplicationSpecificPasswords(ctx, tx)
}

ale's avatar
ale committed
179
// Disable OTP.
180 181 182 183 184 185 186 187 188 189
func (u *RawUser) disableOTP(ctx context.Context, tx TX) error {
	if u.HasOTP {
		if err := tx.DeleteUserTOTPSecret(ctx, &u.User); err != nil {
			return newBackendError(err)
		}
		u.HasOTP = false
	}
	return u.check2FAState(ctx, tx)
}

ale's avatar
ale committed
190
// Enable OTP with the specified secret. Overwrites the current one, if set.
191 192 193 194 195 196 197 198 199
func (u *RawUser) setTOTPSecret(ctx context.Context, tx TX, totpSecret string) error {
	if err := tx.SetUserTOTPSecret(ctx, &u.User, totpSecret); err != nil {
		return err
	}
	u.HasOTP = true
	u.Has2FA = true
	return nil
}

ale's avatar
ale committed
200
// Update the list of U2F registrations for the user. The list may be empty.
201 202 203 204 205 206 207 208
func (u *RawUser) setU2FRegistrations(ctx context.Context, tx TX, regs []*U2FRegistration) error {
	u.U2FRegistrations = regs
	if err := tx.UpdateUser(ctx, &u.User); err != nil {
		return err
	}
	return u.check2FAState(ctx, tx)
}

ale's avatar
ale committed
209 210 211
// Whenever one of OTP or U2F is modified, we'd like to check if it was the
// last 2FA method available: in that case, 2FA has been disabled and we also
// want to clear all application-specific passwords.
212 213 214 215 216 217 218 219 220 221 222
func (u *RawUser) check2FAState(ctx context.Context, tx TX) error {
	if u.HasOTP || len(u.U2FRegistrations) > 0 {
		u.Has2FA = true
		return nil
	}

	// 2FA has been disabled, so drop all app-specific passwords along with it.
	u.Has2FA = false
	return u.deleteAllApplicationSpecificPasswords(ctx, tx)
}

ale's avatar
ale committed
223 224
// Set the primary password for the user. When encryption keys are present,
// requires a valid unlockPassword.
225
func (u *RawUser) setPrimaryPassword(ctx context.Context, tx TX, unlockPassword, password string, enableOpportunisticEncryption bool) error {
226 227 228 229 230 231 232 233 234
	if u.HasEncryptionKeys {
		l, err := u.Keys.add(UserEncryptionKeyMainID, unlockPassword, password)
		if err != nil {
			return err
		}
		u.Keys = l
		if err := tx.SetUserEncryptionKeys(ctx, &u.User, u.Keys); err != nil {
			return err
		}
235 236 237 238
	} else if enableOpportunisticEncryption {
		if err := u.initEncryption(ctx, tx, password); err != nil {
			return err
		}
239 240
	}

241
	enc := DefaultPasswordHash.Encrypt(password)
242 243 244 245
	u.Password = enc
	return tx.SetUserPassword(ctx, &u.User, enc)
}

ale's avatar
ale committed
246 247
// Set the password recovery hint for the user. When encryption keys are
// present, requires a valid unlockPassword.
248
func (u *RawUser) setAccountRecoveryHint(ctx context.Context, tx TX, unlockPassword, hint, response string) error {
249 250 251 252 253 254 255 256 257 258 259
	if u.HasEncryptionKeys {
		l, err := u.Keys.add(UserEncryptionKeyRecoveryID, unlockPassword, response)
		if err != nil {
			return err
		}
		u.Keys = l
		if err := tx.SetUserEncryptionKeys(ctx, &u.User, u.Keys); err != nil {
			return err
		}
	}

260
	enc := DefaultPasswordHash.Encrypt(response)
261
	u.RecoveryPassword = enc
262
	return tx.SetAccountRecoveryHint(ctx, &u.User, hint, enc)
263 264
}

ale's avatar
ale committed
265 266 267 268 269 270 271 272 273 274 275 276
// Initialize encryption keys for this user, given the primary authentication
// password. If encryption keys are already present, they are discarded. All
// secondary authentication tokens are cleared.
func (u *RawUser) initEncryption(ctx context.Context, tx TX, password string) error {
	// Disable all secondary credentials, as we only have the
	// primary password to initialize encryption so all other
	// credentials would not be able to unlock the keys.
	for _, asp := range u.AppSpecificPasswords {
		if err := tx.DeleteApplicationSpecificPassword(ctx, &u.User, asp.ID); err != nil {
			return err
		}
	}
277 278
	if u.AccountRecoveryHint != "" {
		if err := tx.DeleteAccountRecoveryHint(ctx, &u.User); err != nil {
ale's avatar
ale committed
279 280
			return err
		}
281
		u.AccountRecoveryHint = ""
ale's avatar
ale committed
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
	}

	// Initialize a new key storage with the given primary password.
	pub, keys, err := newEncryptionKeys(password)
	if err != nil {
		return err
	}
	if err := tx.SetUserEncryptionPublicKey(ctx, &u.User, pub); err != nil {
		return err
	}
	u.Keys = keys
	u.HasEncryptionKeys = true
	return tx.SetUserEncryptionKeys(ctx, &u.User, keys)
}

// Reset the primary password for the user. When encryption keys are present,
// this will disable all other secondary authentication mechanisms (including
// recovery), as keys would be unreadable otherwise.
func (u *RawUser) resetPassword(ctx context.Context, tx TX, password string) error {
	// If a user has associated encryption keys, we need to
	// disable all secondary authentication credentials as we are
	// going to wipe the existing keys clean.
	if u.HasEncryptionKeys {
		if err := u.initEncryption(ctx, tx, password); err != nil {
			return err
		}
	}

310
	enc := DefaultPasswordHash.Encrypt(password)
ale's avatar
ale committed
311 312 313 314
	return tx.SetUserPassword(ctx, &u.User, enc)
}

// Add a new application-specific password.
315 316 317 318 319 320 321 322 323 324 325 326
func (u *RawUser) addApplicationSpecificPassword(ctx context.Context, tx TX, unlockPassword, password string, asp *AppSpecificPasswordInfo) error {
	if u.HasEncryptionKeys {
		l, err := u.Keys.add(aspKeyID(asp.ID), unlockPassword, password)
		if err != nil {
			return err
		}
		u.Keys = l
		if err := tx.SetUserEncryptionKeys(ctx, &u.User, u.Keys); err != nil {
			return err
		}
	}

327
	enc := DefaultPasswordHash.Encrypt(password)
328 329 330
	return tx.SetApplicationSpecificPassword(ctx, &u.User, asp, enc)
}

ale's avatar
ale committed
331
// Delete an existing application-specific password.
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
func (u *RawUser) deleteApplicationSpecificPassword(ctx context.Context, tx TX, aspID string) error {
	if u.HasEncryptionKeys {
		u.Keys = u.Keys.deleteByID(aspKeyID(aspID))
		if err := tx.SetUserEncryptionKeys(ctx, &u.User, u.Keys); err != nil {
			return err
		}
	}

	return tx.DeleteApplicationSpecificPassword(ctx, &u.User, aspID)
}

// Wipe all app-specific passwords and their associated encryption keys.
func (u *RawUser) deleteAllApplicationSpecificPasswords(ctx context.Context, tx TX) error {
	for _, asp := range u.AppSpecificPasswords {
		if err := tx.DeleteApplicationSpecificPassword(ctx, &u.User, asp.ID); err != nil {
			return err
		}
		if u.HasEncryptionKeys {
			u.Keys = u.Keys.deleteByID(aspKeyID(asp.ID))
		}
	}
	u.AppSpecificPasswords = nil
	if u.HasEncryptionKeys {
		if err := tx.SetUserEncryptionKeys(ctx, &u.User, u.Keys); err != nil {
			return err
		}
	}
	return nil
}

ale's avatar
ale committed
362 363 364
// AppSpecificPasswordInfo stores public information about an
// app-specific password.
type AppSpecificPasswordInfo struct {
ale's avatar
ale committed
365
	ID      string `json:"id"`
ale's avatar
ale committed
366 367 368 369
	Service string `json:"service"`
	Comment string `json:"comment"`
}

ale's avatar
ale committed
370 371
// Well-known user encryption key types, corresponding to primary and
// secondary passwords.
ale's avatar
ale committed
372 373 374 375 376
const (
	UserEncryptionKeyMainID     = "main"
	UserEncryptionKeyRecoveryID = "recovery"
)

ale's avatar
ale committed
377
// Resource types.
ale's avatar
ale committed
378 379 380 381
const (
	ResourceTypeEmail       = "email"
	ResourceTypeMailingList = "list"
	ResourceTypeWebsite     = "web"
ale's avatar
ale committed
382
	ResourceTypeDomain      = "domain"
ale's avatar
ale committed
383 384 385 386
	ResourceTypeDAV         = "dav"
	ResourceTypeDatabase    = "db"
)

ale's avatar
ale committed
387
// Resource status values.
ale's avatar
ale committed
388 389 390
const (
	ResourceStatusActive   = "active"
	ResourceStatusInactive = "inactive"
ale's avatar
ale committed
391
	ResourceStatusReadonly = "readonly"
ale's avatar
ale committed
392
	ResourceStatusArchived = "archived"
ale's avatar
ale committed
393 394
)

395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
// Returns true if the given status is valid for the given resource type.
func isValidStatusByResourceType(rtype, rstatus string) bool {
	switch rtype {
	case ResourceTypeEmail, ResourceTypeMailingList:
		switch rstatus {
		case ResourceStatusActive, ResourceStatusInactive, ResourceStatusReadonly:
			return true
		}
	case ResourceTypeWebsite, ResourceTypeDomain, ResourceTypeDAV, ResourceTypeDatabase:
		switch rstatus {
		case ResourceStatusActive, ResourceStatusInactive, ResourceStatusReadonly, ResourceStatusArchived:
			return true
		}
	}
	return false
}

ale's avatar
ale committed
412 413
// ResourceID is an opaque ID that uniquely identifies a resource in
// the backend database. These should normally not be visible to users.
ale's avatar
ale committed
414
type ResourceID string
415

ale's avatar
ale committed
416
// Equal returns true if the two IDs are the same.
ale's avatar
ale committed
417
func (i ResourceID) Equal(other ResourceID) bool { return i == other }
ale's avatar
ale committed
418

ale's avatar
ale committed
419
// Empty returns true if the ResourceID has the nil value.
ale's avatar
ale committed
420
func (i ResourceID) Empty() bool { return i == "" }
421

ale's avatar
ale committed
422
func (i ResourceID) String() string { return string(i) }
423

ale's avatar
ale committed
424
// MarshalJSON serializes a resource ID to JSON.
425
func (i ResourceID) MarshalJSON() ([]byte, error) {
ale's avatar
ale committed
426
	return json.Marshal(string(i))
427 428
}

ale's avatar
ale committed
429
// UnmarshalJSON deserializes a resource ID from JSON.
430 431 432 433 434 435
func (i *ResourceID) UnmarshalJSON(data []byte) error {
	var s string
	err := json.Unmarshal(data, &s)
	if err != nil {
		return err
	}
ale's avatar
ale committed
436 437
	*i = ResourceID(s)
	return nil
438 439
}

ale's avatar
ale committed
440
// ParseResourceID parses a string representation of a ResourceID.
441
func ParseResourceID(s string) (ResourceID, error) {
ale's avatar
ale committed
442
	return ResourceID(s), nil
443 444
}

ale's avatar
ale committed
445 446 447 448 449
// Resource represents a somewhat arbitrary resource, identified by a
// unique name/type combination (a.k.a. its ID). A resource contains
// some common properties related to sharding and state, plus
// type-specific attributes.
type Resource struct {
ale's avatar
ale committed
450 451 452 453 454
	// ID is a unique primary key in the resources space, with a
	// path-like representation. It must make sense to the
	// database backend and be reversible (i.e. there must be a
	// bidirectional mapping between database objects and resource
	// IDs).
455
	ID ResourceID `json:"id"`
ale's avatar
ale committed
456

ale's avatar
ale committed
457
	// Resource type.
ale's avatar
ale committed
458 459
	Type string `json:"type"`

460
	// Name of the resource, used for display purposes.
ale's avatar
ale committed
461 462 463
	Name string `json:"name"`

	// Optional attribute for hierarchical resources.
464
	ParentID ResourceID `json:"parent_id,omitempty"`
ale's avatar
ale committed
465 466 467 468 469 470 471 472 473

	// Optional attribute for resources that have a status.
	Status string `json:"status,omitempty"`

	// Optional attributes for sharded resources.
	Shard         string `json:"shard,omitempty"`
	OriginalShard string `json:"original_shard,omitempty"`

	// Resources can be 'grouped' together, for various reasons
ale's avatar
ale committed
474 475
	// (display purposes, service integrity). All resources in the
	// same group should have the same Shard. Group names can be
ale's avatar
ale committed
476 477 478 479 480 481 482 483 484 485
	// arbitrary strings.
	Group string `json:"group,omitempty"`

	// Details about the specific type (only one of these can be
	// set, depending on the value of 'type').
	Email    *Email       `json:"email,omitempty"`
	List     *MailingList `json:"list,omitempty"`
	Website  *Website     `json:"website,omitempty"`
	DAV      *WebDAV      `json:"dav,omitempty"`
	Database *Database    `json:"database,omitempty"`
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
}

// Copy the resource (makes a deep copy).
func (r *Resource) Copy() *Resource {
	rr := *r
	switch {
	case r.Email != nil:
		e := *r.Email
		rr.Email = &e
	case r.Website != nil:
		w := *r.Website
		rr.Website = &w
	case r.List != nil:
		l := *r.List
		rr.List = &l
	case r.DAV != nil:
		d := *r.DAV
		rr.DAV = &d
	case r.Database != nil:
		d := *r.Database
		rr.Database = &d
	}
	return &rr
ale's avatar
ale committed
509 510
}

ale's avatar
ale committed
511 512 513 514 515 516 517 518 519 520 521 522
// String returns a short handle for the resource, useful for debugging.
func (r *Resource) String() string {
	s := fmt.Sprintf("%s/%s", r.Type, r.Name)
	if !r.ID.Empty() {
		s += fmt.Sprintf("(%s)", r.ID.String())
	}
	return s
}

// A RawResource associates a Resource with its (optional) owner.
type RawResource struct {
	Resource
ale's avatar
ale committed
523
	Owner string `json:"owner"`
ale's avatar
ale committed
524 525
}

ale's avatar
ale committed
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
// Email resource attributes.
type Email struct {
	Aliases    []string `json:"aliases,omitempty"`
	Maildir    string   `json:"maildir"`
	QuotaLimit int      `json:"quota_limit"`
	QuotaUsage int      `json:"quota_usage"`
}

// MailingList resource attributes.
type MailingList struct {
	Admins []string `json:"admins"`
	Public bool     `json:"public"`
}

// WebDAV represents a hosting account.
type WebDAV struct {
ale's avatar
ale committed
542
	UID     int    `json:"uid"`
ale's avatar
ale committed
543 544 545 546 547
	Homedir string `json:"homedir"`
}

// Website resource attributes.
type Website struct {
ale's avatar
ale committed
548
	URL          string            `json:"url,omitempty"`
ale's avatar
ale committed
549
	UID          int               `json:"uid"`
ale's avatar
ale committed
550
	ParentDomain string            `json:"parent_domain,omitempty"`
ale's avatar
ale committed
551
	AcceptMail   bool              `json:"accept_mail"`
ale's avatar
ale committed
552
	Options      []string          `json:"options,omitempty"`
ale's avatar
ale committed
553 554 555 556 557 558 559 560 561 562 563
	Categories   []string          `json:"categories,omitempty"`
	Description  map[string]string `json:"description,omitempty"`
	QuotaUsage   int               `json:"quota_usage"`
	DocumentRoot string            `json:"document_root"`

	CMSInfo           map[string]*CMSInfo  `json:"cms_info,omitempty"`
	VulnerabilityInfo map[string]*VulnInfo `json:"vulnerability_info,omitempty"`
}

// Database resource attributes.
type Database struct {
564
	DBUser string `json:"db_user"`
ale's avatar
ale committed
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
}

// CMSInfo holds CMS-specific information.
type CMSInfo struct {
	Name    string `json:"name"`
	Version string `json:"version"`
	Status  string `json:"status"`
}

// VulnInfo stores information about vulnerabilities detected by our
// automated scanners.
type VulnInfo struct {
	Name       string    `json:"name"`
	Path       string    `json:"path"`
	DetectedAt time.Time `json:"detected_at"`
}

// Blog resource attributes.
type Blog struct {
	Name string `json:"name"`
	URL  string `json:"url"`
}
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602

const hardcodedWebRoot = "/home/users/investici.org"

// Group web-related resources into groups.
//
// 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.
//
// TODO: Ideally we should be able to do this without hard-coding the webroot.
func (u *User) groupWebResources() {
	// 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]*Resource)
	for _, r := range u.Resources {
ale's avatar
ale committed
603
		switch r.Type {
604 605 606 607 608 609 610 611 612
		case ResourceTypeWebsite, ResourceTypeDomain:
			r.Group = getHostingDir(r.Website.DocumentRoot, hardcodedWebRoot)
			webs[r.ID.String()] = r
		case ResourceTypeDAV:
			r.Group = getHostingDir(r.DAV.Homedir, hardcodedWebRoot)
		}
	}
	// Fix databases in a second pass.
	for _, r := range u.Resources {
ale's avatar
ale committed
613
		if r.Type == ResourceTypeDatabase && !r.ParentID.Empty() {
614 615 616 617 618 619 620 621 622 623 624 625 626 627
			r.Group = webs[r.ParentID.String()].Group
		}
	}
}

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

629 630
// U2FRegistration stores information on a single U2F device registration.
//
631 632 633
// This mirrors closely compositetypes.U2FRegistration, with the very
// important difference that the data here is base64-encoded! Can't
// reliably push arbitrary binary data through JSON otherwise.
634
type U2FRegistration struct {
635 636
	KeyHandle string `json:"key_handle"`
	PublicKey string `json:"public_key"`
637
}