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