| 26 | } |
| 27 | |
| 28 | func (a *API) checkPasswordStrength(ctx context.Context, password string) error { |
| 29 | config := a.config |
| 30 | |
| 31 | if len(password) > MaxPasswordLength { |
| 32 | return apierrors.NewBadRequestError( |
| 33 | apierrors.ErrorCodeValidationFailed, |
| 34 | "Password cannot be longer than %v characters", |
| 35 | MaxPasswordLength, |
| 36 | ) |
| 37 | } |
| 38 | |
| 39 | var messages, reasons []string |
| 40 | |
| 41 | if len(password) < config.Password.MinLength { |
| 42 | reasons = append(reasons, "length") |
| 43 | messages = append(messages, fmt.Sprintf("Password should be at least %d characters.", config.Password.MinLength)) |
| 44 | } |
| 45 | |
| 46 | for _, characterSet := range config.Password.RequiredCharacters { |
| 47 | if characterSet != "" && !strings.ContainsAny(password, characterSet) { |
| 48 | reasons = append(reasons, "characters") |
| 49 | |
| 50 | messages = append(messages, fmt.Sprintf("Password should contain at least one character of each: %s.", strings.Join(config.Password.RequiredCharacters, ", "))) |
| 51 | |
| 52 | break |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | if config.Password.HIBP.Enabled { |
| 57 | pwned, err := a.hibpClient.Check(ctx, password) |
| 58 | if err != nil { |
| 59 | if config.Password.HIBP.FailClosed { |
| 60 | return apierrors.NewInternalServerError("Unable to perform password strength check with HaveIBeenPwned.org.").WithInternalError(err) |
| 61 | } else { |
| 62 | logrus.WithError(err).Warn("Unable to perform password strength check with HaveIBeenPwned.org, pwned passwords are being allowed") |
| 63 | } |
| 64 | } else if pwned { |
| 65 | reasons = append(reasons, "pwned") |
| 66 | messages = append(messages, "Password is known to be weak and easy to guess, please choose a different one.") |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | if len(reasons) > 0 { |
| 71 | return &WeakPasswordError{ |
| 72 | Message: strings.Join(messages, " "), |
| 73 | Reasons: reasons, |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | return nil |
| 78 | } |