gitea源码

keys.go 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright 2018 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package cmd
  4. import (
  5. "context"
  6. "errors"
  7. "fmt"
  8. "strings"
  9. "code.gitea.io/gitea/modules/log"
  10. "code.gitea.io/gitea/modules/private"
  11. "github.com/urfave/cli/v3"
  12. )
  13. // CmdKeys represents the available keys sub-command
  14. var CmdKeys = &cli.Command{
  15. Name: "keys",
  16. Usage: "(internal) Should only be called by SSH server",
  17. Hidden: true, // internal commands shouldn't not be visible
  18. Description: "Queries the Gitea database to get the authorized command for a given ssh key fingerprint",
  19. Before: PrepareConsoleLoggerLevel(log.FATAL),
  20. Action: runKeys,
  21. Flags: []cli.Flag{
  22. &cli.StringFlag{
  23. Name: "expected",
  24. Aliases: []string{"e"},
  25. Value: "git",
  26. Usage: "Expected user for whom provide key commands",
  27. },
  28. &cli.StringFlag{
  29. Name: "username",
  30. Aliases: []string{"u"},
  31. Value: "",
  32. Usage: "Username trying to log in by SSH",
  33. },
  34. &cli.StringFlag{
  35. Name: "type",
  36. Aliases: []string{"t"},
  37. Value: "",
  38. Usage: "Type of the SSH key provided to the SSH Server (requires content to be provided too)",
  39. },
  40. &cli.StringFlag{
  41. Name: "content",
  42. Aliases: []string{"k"},
  43. Value: "",
  44. Usage: "Base64 encoded content of the SSH key provided to the SSH Server (requires type to be provided too)",
  45. },
  46. },
  47. }
  48. func runKeys(ctx context.Context, c *cli.Command) error {
  49. if !c.IsSet("username") {
  50. return errors.New("No username provided")
  51. }
  52. // Check username matches the expected username
  53. if strings.TrimSpace(c.String("username")) != strings.TrimSpace(c.String("expected")) {
  54. return nil
  55. }
  56. content := ""
  57. if c.IsSet("type") && c.IsSet("content") {
  58. content = fmt.Sprintf("%s %s", strings.TrimSpace(c.String("type")), strings.TrimSpace(c.String("content")))
  59. }
  60. if content == "" {
  61. return errors.New("No key type and content provided")
  62. }
  63. setup(ctx, c.Bool("debug"))
  64. authorizedString, extra := private.AuthorizedPublicKeyByContent(ctx, content)
  65. // do not use handleCliResponseExtra or cli.NewExitError, if it exists immediately, it breaks some tests like Test_CmdKeys
  66. if extra.Error != nil {
  67. return extra.Error
  68. }
  69. _, _ = fmt.Fprintln(c.Root().Writer, strings.TrimSpace(authorizedString.Text))
  70. return nil
  71. }