You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ssh_key_principals.go 1.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package asymkey
  4. import (
  5. "context"
  6. "fmt"
  7. "strings"
  8. "code.gitea.io/gitea/models/db"
  9. user_model "code.gitea.io/gitea/models/user"
  10. "code.gitea.io/gitea/modules/setting"
  11. "code.gitea.io/gitea/modules/util"
  12. )
  13. // CheckPrincipalKeyString strips spaces and returns an error if the given principal contains newlines
  14. func CheckPrincipalKeyString(ctx context.Context, user *user_model.User, content string) (_ string, err error) {
  15. if setting.SSH.Disabled {
  16. return "", db.ErrSSHDisabled{}
  17. }
  18. content = strings.TrimSpace(content)
  19. if strings.ContainsAny(content, "\r\n") {
  20. return "", util.NewInvalidArgumentErrorf("only a single line with a single principal please")
  21. }
  22. // check all the allowed principals, email, username or anything
  23. // if any matches, return ok
  24. for _, v := range setting.SSH.AuthorizedPrincipalsAllow {
  25. switch v {
  26. case "anything":
  27. return content, nil
  28. case "email":
  29. emails, err := user_model.GetEmailAddresses(ctx, user.ID)
  30. if err != nil {
  31. return "", err
  32. }
  33. for _, email := range emails {
  34. if !email.IsActivated {
  35. continue
  36. }
  37. if content == email.Email {
  38. return content, nil
  39. }
  40. }
  41. case "username":
  42. if content == user.Name {
  43. return content, nil
  44. }
  45. }
  46. }
  47. return "", fmt.Errorf("didn't match allowed principals: %s", setting.SSH.AuthorizedPrincipalsAllow)
  48. }