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