actions_user.go 12.1 KB
Newer Older
1 2 3 4 5 6 7 8 9
package accountserver

import (
	"errors"

	"git.autistici.org/ai3/go-common/pwhash"
	umdb "git.autistici.org/id/usermetadb"
)

10
// GetUserRequest retrieves a specific User.
11 12
type GetUserRequest struct {
	UserRequestBase
13 14 15

	// Whether to return an inactive user.
	IncludeInactive bool `json:"include_inactive"`
16 17 18 19
}

// Serve the request.
func (r *GetUserRequest) Serve(rctx *RequestContext) (interface{}, error) {
20 21 22 23
	if !r.IncludeInactive && rctx.User.Status != UserStatusActive {
		return nil, ErrUserNotFound
	}

24 25 26 27
	// Return the public User object contained within the RawUser.
	return &rctx.User.User, nil
}

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
// SearchUserRequest searches the database for users with names
// matching a given pattern. The actual pattern semantics are
// backend-specific (for LDAP, this is a prefix string search).
type SearchUserRequest struct {
	AdminRequestBase

	Pattern string `json:"pattern"`
}

// Validate the request.
func (r *SearchUserRequest) Validate(rctx *RequestContext) error {
	if r.Pattern == "" {
		return errors.New("empty pattern")
	}
	return nil
}

// SearchUserResponse is the response type for SearchUserRequest.
type SearchUserResponse struct {
	Usernames []string `json:"usernames"`
}

// Serve the request.
func (r *SearchUserRequest) Serve(rctx *RequestContext) (interface{}, error) {
	usernames, err := rctx.TX.SearchUser(rctx.Context, r.Pattern)
	if err != nil {
		return nil, err
	}
	return &SearchUserResponse{Usernames: usernames}, nil
}

59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
// ChangeUserPasswordRequest updates a user's password. It will also take
// care of re-encrypting the user encryption key, if present.
type ChangeUserPasswordRequest struct {
	PrivilegedRequestBase
	Password string `json:"password"`
}

// Sanitize the request.
func (r *ChangeUserPasswordRequest) Sanitize() {
	r.PrivilegedRequestBase.Sanitize()
	if r.Password != "" {
		r.Password = sanitizedValue
	}
}

// Validate the request.
func (r *ChangeUserPasswordRequest) Validate(rctx *RequestContext) error {
	if err := rctx.fieldValidators.password(rctx.Context, r.Password); err != nil {
		return newValidationError(nil, "password", err.Error())
	}
79 80 81
	if r.Password == r.CurPassword {
		return newValidationError(nil, "password", "The new password can't be the same as the old one")
	}
82 83 84 85 86
	return r.PrivilegedRequestBase.Validate(rctx)
}

// Serve the request.
func (r *ChangeUserPasswordRequest) Serve(rctx *RequestContext) (interface{}, error) {
87 88 89 90 91
	err := rctx.User.setPrimaryPassword(rctx.Context, rctx.TX, r.CurPassword, r.Password, rctx.enableOpportunisticEncryption)
	if err != nil {
		return nil, err
	}

92
	rctx.audit.Log(rctx, nil, "password changed (user)")
93 94 95 96
	rctx.logUserAction(&rctx.User.User, umdb.LogTypePasswordChange, "password changed (user)")
	return nil, err
}

97
// AccountRecoveryRequest lets users reset their password by providing
98 99 100 101
// secondary credentials, which we authenticate ourselves. It is not
// authenticated with SSO.
//
// Two-factor authentication is disabled on successful recovery.
102
type AccountRecoveryRequest struct {
103 104 105 106 107 108
	Username         string `json:"username"`
	RecoveryPassword string `json:"recovery_password"`
	Password         string `json:"password"`
	// TODO: add DeviceInfo
}

109 110
// AccountRecoveryResponse is the response type for AccountRecoveryRequest.
type AccountRecoveryResponse struct {
111 112 113 114
	Hint string `json:"hint,optional"`
}

// Sanitize the request.
115
func (r *AccountRecoveryRequest) Sanitize() {
116 117 118 119 120 121 122 123 124
	if r.RecoveryPassword != "" {
		r.RecoveryPassword = sanitizedValue
	}
	if r.Password != "" {
		r.Password = sanitizedValue
	}
}

// Validate the request.
125 126 127 128 129 130
func (r *AccountRecoveryRequest) Validate(rctx *RequestContext) error {
	// Only validate the password if attempting recovery.
	if r.RecoveryPassword != "" {
		if err := rctx.fieldValidators.password(rctx.Context, r.Password); err != nil {
			return newValidationError(nil, "password", err.Error())
		}
131 132 133 134 135 136
	}
	return nil
}

// PopulateContext extracts information from the request and stores it
// into the RequestContext.
137
func (r *AccountRecoveryRequest) PopulateContext(rctx *RequestContext) error {
138 139 140 141 142 143 144 145 146
	user, err := getUserOrDie(rctx.Context, rctx.TX, r.Username)
	if err != nil {
		return err
	}
	rctx.User = user
	return nil
}

// Authorize the request.
147
func (r *AccountRecoveryRequest) Authorize(rctx *RequestContext) error {
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
	// Anyone can request the hint (rate-limit above this layer).
	if r.RecoveryPassword == "" {
		return nil
	}

	// TODO: call out to auth-server for rate limiting and other features.
	// Authenticate the secret recovery password.
	if !pwhash.ComparePassword(rctx.User.RecoveryPassword, r.RecoveryPassword) {
		return errors.New("bad password")
	}

	return nil
}

// Serve the request.
163 164 165
func (r *AccountRecoveryRequest) Serve(rctx *RequestContext) (interface{}, error) {
	resp := AccountRecoveryResponse{
		Hint: rctx.User.AccountRecoveryHint,
166 167 168 169 170 171 172 173
	}

	// Only attempt to authenticate if the recovery password is
	// set in the request, otherwise just return the hint.
	if r.RecoveryPassword == "" {
		return &resp, nil
	}

174
	if err := rctx.User.setPrimaryPassword(rctx.Context, rctx.TX, r.RecoveryPassword, r.Password, rctx.enableOpportunisticEncryption); err != nil {
175 176 177 178 179
		return nil, err
	}
	if err := rctx.User.disable2FA(rctx.Context, rctx.TX); err != nil {
		return nil, err
	}
180
	rctx.audit.Log(rctx, nil, "password changed (account recovery)")
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
	rctx.logUserAction(&rctx.User.User, umdb.LogTypePasswordReset, "password changed (account recovery)")

	return nil, nil
}

// ResetPasswordRequest is an admin operation to forcefully reset the password
// for an account. The user will lose access to all stored email (because the
// encryption keys will be reset) and to 2FA.
type ResetPasswordRequest struct {
	AdminUserRequestBase
	Password string `json:"password"`
}

// Sanitize the request.
func (r *ResetPasswordRequest) Sanitize() {
	r.AdminUserRequestBase.Sanitize()
	if r.Password != "" {
		r.Password = sanitizedValue
	}
}

// Validate the request.
func (r *ResetPasswordRequest) Validate(rctx *RequestContext) error {
	if err := rctx.fieldValidators.password(rctx.Context, r.Password); err != nil {
		return newValidationError(nil, "password", err.Error())
	}
	return nil
}

// Serve the request.
func (r *ResetPasswordRequest) Serve(rctx *RequestContext) (interface{}, error) {
	if err := rctx.User.resetPassword(rctx.Context, rctx.TX, r.Password); err != nil {
		return nil, err
	}
	if err := rctx.User.disable2FA(rctx.Context, rctx.TX); err != nil {
		return nil, err
	}
218
	rctx.audit.Log(rctx, nil, "password changed (admin)")
219 220 221 222
	rctx.logUserAction(&rctx.User.User, umdb.LogTypePasswordReset, "password changed (admin)")
	return nil, nil
}

223
// SetAccountRecoveryHintRequest lets users set the password recovery hint
224
// and expected response (secondary password).
225
type SetAccountRecoveryHintRequest struct {
226 227 228 229 230 231
	PrivilegedRequestBase
	Hint     string `json:"recovery_hint"`
	Response string `json:"recovery_response"`
}

// Validate the request.
232
func (r *SetAccountRecoveryHintRequest) Validate(rctx *RequestContext) error {
233 234 235 236 237 238 239
	var err *validationError
	if r.Hint == "" {
		err = newValidationError(err, "recovery_hint", "mandatory field")
	}
	if verr := rctx.fieldValidators.password(rctx.Context, r.Response); verr != nil {
		err = newValidationError(err, "recovery_response", verr.Error())
	}
240
	return err.orNil()
241 242 243
}

// Serve the request.
244 245
func (r *SetAccountRecoveryHintRequest) Serve(rctx *RequestContext) (interface{}, error) {
	return nil, rctx.User.setAccountRecoveryHint(rctx.Context, rctx.TX, r.CurPassword, r.Hint, r.Response)
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
}

// CreateApplicationSpecificPasswordRequest lets users create their own ASPs.
type CreateApplicationSpecificPasswordRequest struct {
	PrivilegedRequestBase
	Service string `json:"service"`
	Notes   string `json:"notes"`
}

// CreateApplicationSpecificPasswordResponse is the response type for
// CreateApplicationSpecificPasswordRequest.
type CreateApplicationSpecificPasswordResponse struct {
	Password string `json:"password"`
}

// Sanitize the response.
func (r *CreateApplicationSpecificPasswordResponse) Sanitize() {
	if r.Password != "" {
		r.Password = sanitizedValue
	}
}

// Validate the request.
func (r *CreateApplicationSpecificPasswordRequest) Validate(_ *RequestContext) error {
	var err *validationError
	if r.Service == "" {
		err = newValidationError(err, "service", "mandatory field")
	}
274
	return err.orNil()
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
}

// Serve the request.
func (r *CreateApplicationSpecificPasswordRequest) Serve(rctx *RequestContext) (interface{}, error) {
	if !rctx.User.Has2FA {
		return nil, errors.New("2FA is not enabled for this user")
	}

	// Create a new application-specific password metadata.
	asp := &AppSpecificPasswordInfo{
		ID:      randomAppSpecificPasswordID(),
		Service: r.Service,
		Comment: r.Notes,
	}
	pw := randomAppSpecificPassword()

	if err := rctx.User.addApplicationSpecificPassword(rctx.Context, rctx.TX, r.CurPassword, pw, asp); err != nil {
		return nil, err
	}

	return &CreateApplicationSpecificPasswordResponse{
		Password: pw,
	}, nil
}

// DeleteApplicationSpecificPasswordRequest deletes an application-specific
// password, identified by its unique ID.
type DeleteApplicationSpecificPasswordRequest struct {
	UserRequestBase
	AspID string `json:"asp_id"`
}

// Serve the request.
func (r *DeleteApplicationSpecificPasswordRequest) Serve(rctx *RequestContext) (interface{}, error) {
	return nil, rctx.User.deleteApplicationSpecificPassword(rctx.Context, rctx.TX, r.AspID)
}

// EnableOTPRequest enables OTP-based two-factor authentication for a
// user. The caller can generate the TOTP secret itself if needed (useful for
// UX that confirms that the user is able to login first), or it can let the
// server generate a new secret by passing an empty totp_secret.
type EnableOTPRequest struct {
	UserRequestBase
	TOTPSecret string `json:"totp_secret"`
}

// Sanitize the request.
func (r *EnableOTPRequest) Sanitize() {
	r.UserRequestBase.Sanitize()
	if r.TOTPSecret != "" {
		r.TOTPSecret = sanitizedValue
	}
}

// Validate the request.
func (r *EnableOTPRequest) Validate(_ *RequestContext) error {
	var err *validationError
	// Only check if the client-side secret is set, skip otherwise.
ale's avatar
ale committed
333
	if r.TOTPSecret == "" && len(r.TOTPSecret) != 16 {
334 335
		err = newValidationError(err, "totp_secret", "bad value")
	}
336
	return err.orNil()
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
}

// EnableOTPResponse is the response type for AccountService.EnableOTP().
type EnableOTPResponse struct {
	TOTPSecret string `json:"totp_secret"`
}

// Sanitize the response.
func (r *EnableOTPResponse) Sanitize() {
	if r.TOTPSecret != "" {
		r.TOTPSecret = sanitizedValue
	}
}

// Serve the request.
func (r *EnableOTPRequest) Serve(rctx *RequestContext) (interface{}, error) {
	// Replace or initialize the TOTP secret.
	secret := r.TOTPSecret
	if secret == "" {
		var err error
		secret, err = generateTOTPSecret()
		if err != nil {
			return nil, err
		}
	}

	if err := rctx.User.setTOTPSecret(rctx.Context, rctx.TX, secret); err != nil {
		return nil, err
	}

367
	rctx.audit.Log(rctx, nil, "totp enabled")
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383

	return &EnableOTPResponse{
		TOTPSecret: secret,
	}, nil
}

// DisableOTPRequest disables two-factor authentication for a user.
type DisableOTPRequest struct {
	UserRequestBase
}

// Serve the request.
func (r *DisableOTPRequest) Serve(rctx *RequestContext) (interface{}, error) {
	if err := rctx.User.disableOTP(rctx.Context, rctx.TX); err != nil {
		return nil, err
	}
384
	rctx.audit.Log(rctx, nil, "totp disabled")
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
	return nil, nil
}

// UpdateUserRequest allows the caller to update a (very limited) selected set
// of fields on a User object. It is a catch-all function for very simple
// changes that don't justify their own specialized method.
type UpdateUserRequest struct {
	UserRequestBase
	Lang             string             `json:"lang,omitempty"`
	U2FRegistrations []*U2FRegistration `json:"u2f_registrations,omitempty"`
}

const maxU2FRegistrations = 20

// Validate the request.
func (r *UpdateUserRequest) Validate(rctx *RequestContext) error {
	if len(r.U2FRegistrations) > maxU2FRegistrations {
		return errors.New("too many U2F registrations")
	}

	// TODO: better validation of the language code!
	if len(r.Lang) > 2 {
		return errors.New("invalid language code")
	}

	return nil
}

// Serve the request.
func (r *UpdateUserRequest) Serve(rctx *RequestContext) (interface{}, error) {
	if r.Lang != "" {
		rctx.User.Lang = r.Lang
	}

	return nil, rctx.User.setU2FRegistrations(rctx.Context, rctx.TX, r.U2FRegistrations)
}