Skip to content

Commit d1a4997

Browse files
zeripathtechknowlogick
authored andcommitted
AuthorizedKeysCommand should not query db directly (#9371)
* AuthorizedKeysCommand should not query db directly * Update routers/private/internal.go * Fix import order
1 parent 1707f59 commit d1a4997

File tree

6 files changed

+93
-50
lines changed

6 files changed

+93
-50
lines changed

cmd/keys.go

+4-6
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import (
99
"fmt"
1010
"strings"
1111

12-
"code.gitea.io/gitea/models"
12+
"code.gitea.io/gitea/modules/private"
1313

1414
"github.com/urfave/cli"
1515
)
@@ -62,14 +62,12 @@ func runKeys(c *cli.Context) error {
6262
return errors.New("No key type and content provided")
6363
}
6464

65-
if err := initDBDisableConsole(true); err != nil {
66-
return err
67-
}
65+
setup("keys.log")
6866

69-
publicKey, err := models.SearchPublicKeyByContent(content)
67+
authorizedString, err := private.AuthorizedPublicKeyByContent(content)
7068
if err != nil {
7169
return err
7270
}
73-
fmt.Println(publicKey.AuthorizedString())
71+
fmt.Println(strings.TrimSpace(authorizedString))
7472
return nil
7573
}

docs/content/doc/usage/command-line.en-us.md

+1
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,7 @@ provided key. You should also set the value
281281
NB: opensshd requires the gitea program to be owned by root and not
282282
writable by group or others. The program must be specified by an absolute
283283
path.
284+
NB: Gitea must be running for this command to succeed.
284285

285286
#### migrate
286287
Migrates the database. This command can be used to run other commands before starting the server for the first time.

integrations/cmd_keys_test.go

+41-40
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"bytes"
99
"flag"
1010
"io"
11+
"net/url"
1112
"os"
1213
"testing"
1314

@@ -18,45 +19,45 @@ import (
1819
)
1920

2021
func Test_CmdKeys(t *testing.T) {
21-
defer prepareTestEnv(t)()
22+
onGiteaRun(t, func(*testing.T, *url.URL) {
23+
tests := []struct {
24+
name string
25+
args []string
26+
wantErr bool
27+
expectedOutput string
28+
}{
29+
{"test_empty_1", []string{"keys", "--username=git", "--type=test", "--content=test"}, true, ""},
30+
{"test_empty_2", []string{"keys", "-e", "git", "-u", "git", "-t", "test", "-k", "test"}, true, ""},
31+
{"with_key",
32+
[]string{"keys", "-e", "git", "-u", "git", "-t", "ssh-rsa", "-k", "AAAAB3NzaC1yc2EAAAADAQABAAABgQDWVj0fQ5N8wNc0LVNA41wDLYJ89ZIbejrPfg/avyj3u/ZohAKsQclxG4Ju0VirduBFF9EOiuxoiFBRr3xRpqzpsZtnMPkWVWb+akZwBFAx8p+jKdy4QXR/SZqbVobrGwip2UjSrri1CtBxpJikojRIZfCnDaMOyd9Jp6KkujvniFzUWdLmCPxUE9zhTaPu0JsEP7MW0m6yx7ZUhHyfss+NtqmFTaDO+QlMR7L2QkDliN2Jl3Xa3PhuWnKJfWhdAq1Cw4oraKUOmIgXLkuiuxVQ6mD3AiFupkmfqdHq6h+uHHmyQqv3gU+/sD8GbGAhf6ftqhTsXjnv1Aj4R8NoDf9BS6KRkzkeun5UisSzgtfQzjOMEiJtmrep2ZQrMGahrXa+q4VKr0aKJfm+KlLfwm/JztfsBcqQWNcTURiCFqz+fgZw0Ey/de0eyMzldYTdXXNRYCKjs9bvBK+6SSXRM7AhftfQ0ZuoW5+gtinPrnmoOaSCEJbAiEiTO/BzOHgowiM="},
33+
false,
34+
"# gitea public key\ncommand=\"" + setting.AppPath + " --config='" + setting.CustomConf + "' serv key-1\",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDWVj0fQ5N8wNc0LVNA41wDLYJ89ZIbejrPfg/avyj3u/ZohAKsQclxG4Ju0VirduBFF9EOiuxoiFBRr3xRpqzpsZtnMPkWVWb+akZwBFAx8p+jKdy4QXR/SZqbVobrGwip2UjSrri1CtBxpJikojRIZfCnDaMOyd9Jp6KkujvniFzUWdLmCPxUE9zhTaPu0JsEP7MW0m6yx7ZUhHyfss+NtqmFTaDO+QlMR7L2QkDliN2Jl3Xa3PhuWnKJfWhdAq1Cw4oraKUOmIgXLkuiuxVQ6mD3AiFupkmfqdHq6h+uHHmyQqv3gU+/sD8GbGAhf6ftqhTsXjnv1Aj4R8NoDf9BS6KRkzkeun5UisSzgtfQzjOMEiJtmrep2ZQrMGahrXa+q4VKr0aKJfm+KlLfwm/JztfsBcqQWNcTURiCFqz+fgZw0Ey/de0eyMzldYTdXXNRYCKjs9bvBK+6SSXRM7AhftfQ0ZuoW5+gtinPrnmoOaSCEJbAiEiTO/BzOHgowiM= user2@localhost\n",
35+
},
36+
{"invalid", []string{"keys", "--not-a-flag=git"}, true, "Incorrect Usage: flag provided but not defined: -not-a-flag\n\n"},
37+
}
38+
for _, tt := range tests {
39+
t.Run(tt.name, func(t *testing.T) {
40+
realStdout := os.Stdout //Backup Stdout
41+
r, w, _ := os.Pipe()
42+
os.Stdout = w
2243

23-
tests := []struct {
24-
name string
25-
args []string
26-
wantErr bool
27-
expectedOutput string
28-
}{
29-
{"test_empty_1", []string{"keys", "--username=git", "--type=test", "--content=test"}, true, ""},
30-
{"test_empty_2", []string{"keys", "-e", "git", "-u", "git", "-t", "test", "-k", "test"}, true, ""},
31-
{"with_key",
32-
[]string{"keys", "-e", "git", "-u", "git", "-t", "ssh-rsa", "-k", "AAAAB3NzaC1yc2EAAAADAQABAAABgQDWVj0fQ5N8wNc0LVNA41wDLYJ89ZIbejrPfg/avyj3u/ZohAKsQclxG4Ju0VirduBFF9EOiuxoiFBRr3xRpqzpsZtnMPkWVWb+akZwBFAx8p+jKdy4QXR/SZqbVobrGwip2UjSrri1CtBxpJikojRIZfCnDaMOyd9Jp6KkujvniFzUWdLmCPxUE9zhTaPu0JsEP7MW0m6yx7ZUhHyfss+NtqmFTaDO+QlMR7L2QkDliN2Jl3Xa3PhuWnKJfWhdAq1Cw4oraKUOmIgXLkuiuxVQ6mD3AiFupkmfqdHq6h+uHHmyQqv3gU+/sD8GbGAhf6ftqhTsXjnv1Aj4R8NoDf9BS6KRkzkeun5UisSzgtfQzjOMEiJtmrep2ZQrMGahrXa+q4VKr0aKJfm+KlLfwm/JztfsBcqQWNcTURiCFqz+fgZw0Ey/de0eyMzldYTdXXNRYCKjs9bvBK+6SSXRM7AhftfQ0ZuoW5+gtinPrnmoOaSCEJbAiEiTO/BzOHgowiM="},
33-
false,
34-
"# gitea public key\ncommand=\"" + setting.AppPath + " --config='" + setting.CustomConf + "' serv key-1\",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDWVj0fQ5N8wNc0LVNA41wDLYJ89ZIbejrPfg/avyj3u/ZohAKsQclxG4Ju0VirduBFF9EOiuxoiFBRr3xRpqzpsZtnMPkWVWb+akZwBFAx8p+jKdy4QXR/SZqbVobrGwip2UjSrri1CtBxpJikojRIZfCnDaMOyd9Jp6KkujvniFzUWdLmCPxUE9zhTaPu0JsEP7MW0m6yx7ZUhHyfss+NtqmFTaDO+QlMR7L2QkDliN2Jl3Xa3PhuWnKJfWhdAq1Cw4oraKUOmIgXLkuiuxVQ6mD3AiFupkmfqdHq6h+uHHmyQqv3gU+/sD8GbGAhf6ftqhTsXjnv1Aj4R8NoDf9BS6KRkzkeun5UisSzgtfQzjOMEiJtmrep2ZQrMGahrXa+q4VKr0aKJfm+KlLfwm/JztfsBcqQWNcTURiCFqz+fgZw0Ey/de0eyMzldYTdXXNRYCKjs9bvBK+6SSXRM7AhftfQ0ZuoW5+gtinPrnmoOaSCEJbAiEiTO/BzOHgowiM= user2@localhost\n\n",
35-
},
36-
{"invalid", []string{"keys", "--not-a-flag=git"}, true, "Incorrect Usage: flag provided but not defined: -not-a-flag\n\n"},
37-
}
38-
for _, tt := range tests {
39-
t.Run(tt.name, func(t *testing.T) {
40-
realStdout := os.Stdout //Backup Stdout
41-
r, w, _ := os.Pipe()
42-
os.Stdout = w
43-
44-
set := flag.NewFlagSet("keys", 0)
45-
_ = set.Parse(tt.args)
46-
context := cli.NewContext(&cli.App{Writer: os.Stdout}, set, nil)
47-
err := cmd.CmdKeys.Run(context)
48-
if (err != nil) != tt.wantErr {
49-
t.Errorf("CmdKeys.Run() error = %v, wantErr %v", err, tt.wantErr)
50-
}
51-
w.Close()
52-
var buf bytes.Buffer
53-
io.Copy(&buf, r)
54-
commandOutput := buf.String()
55-
if tt.expectedOutput != commandOutput {
56-
t.Errorf("expectedOutput: %#v, commandOutput: %#v", tt.expectedOutput, commandOutput)
57-
}
58-
//Restore stdout
59-
os.Stdout = realStdout
60-
})
61-
}
44+
set := flag.NewFlagSet("keys", 0)
45+
_ = set.Parse(tt.args)
46+
context := cli.NewContext(&cli.App{Writer: os.Stdout}, set, nil)
47+
err := cmd.CmdKeys.Run(context)
48+
if (err != nil) != tt.wantErr {
49+
t.Errorf("CmdKeys.Run() error = %v, wantErr %v", err, tt.wantErr)
50+
}
51+
w.Close()
52+
var buf bytes.Buffer
53+
io.Copy(&buf, r)
54+
commandOutput := buf.String()
55+
if tt.expectedOutput != commandOutput {
56+
t.Errorf("expectedOutput: %#v, commandOutput: %#v", tt.expectedOutput, commandOutput)
57+
}
58+
//Restore stdout
59+
os.Stdout = realStdout
60+
})
61+
}
62+
})
6263
}

modules/private/key.go

+25
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ package private
66

77
import (
88
"fmt"
9+
"io/ioutil"
10+
"net/http"
911

1012
"code.gitea.io/gitea/modules/setting"
1113
)
@@ -27,3 +29,26 @@ func UpdatePublicKeyInRepo(keyID, repoID int64) error {
2729
}
2830
return nil
2931
}
32+
33+
// AuthorizedPublicKeyByContent searches content as prefix (leak e-mail part)
34+
// and returns public key found.
35+
func AuthorizedPublicKeyByContent(content string) (string, error) {
36+
// Ask for running deliver hook and test pull request tasks.
37+
reqURL := setting.LocalURL + fmt.Sprintf("api/internal/ssh/authorized_keys")
38+
req := newInternalRequest(reqURL, "POST")
39+
req.Param("content", content)
40+
resp, err := req.Response()
41+
if err != nil {
42+
return "", err
43+
}
44+
45+
defer resp.Body.Close()
46+
47+
// All 2XX status codes are accepted and others will return an error
48+
if resp.StatusCode != http.StatusOK {
49+
return "", fmt.Errorf("Failed to update public key: %s", decodeJSONError(resp).Err)
50+
}
51+
bs, err := ioutil.ReadAll(resp.Body)
52+
53+
return string(bs), err
54+
}

routers/private/internal.go

+1
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ func CheckUnitUser(ctx *macaron.Context) {
7676
// These APIs will be invoked by internal commands for example `gitea serv` and etc.
7777
func RegisterRoutes(m *macaron.Macaron) {
7878
m.Group("/", func() {
79+
m.Post("/ssh/authorized_keys", AuthorizedPublicKeyByContent)
7980
m.Post("/ssh/:id/update/:repoid", UpdatePublicKeyInRepo)
8081
m.Get("/hook/pre-receive/:owner/:repo", HookPreReceive)
8182
m.Get("/hook/post-receive/:owner/:repo", HookPostReceive)

routers/private/key.go

+21-4
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
package private
77

88
import (
9+
"net/http"
10+
911
"code.gitea.io/gitea/models"
1012
"code.gitea.io/gitea/modules/timeutil"
1113

@@ -17,7 +19,7 @@ func UpdatePublicKeyInRepo(ctx *macaron.Context) {
1719
keyID := ctx.ParamsInt64(":id")
1820
repoID := ctx.ParamsInt64(":repoid")
1921
if err := models.UpdatePublicKeyUpdated(keyID); err != nil {
20-
ctx.JSON(500, map[string]interface{}{
22+
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
2123
"err": err.Error(),
2224
})
2325
return
@@ -29,18 +31,33 @@ func UpdatePublicKeyInRepo(ctx *macaron.Context) {
2931
ctx.PlainText(200, []byte("success"))
3032
return
3133
}
32-
ctx.JSON(500, map[string]interface{}{
34+
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
3335
"err": err.Error(),
3436
})
3537
return
3638
}
3739
deployKey.UpdatedUnix = timeutil.TimeStampNow()
3840
if err = models.UpdateDeployKeyCols(deployKey, "updated_unix"); err != nil {
39-
ctx.JSON(500, map[string]interface{}{
41+
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
4042
"err": err.Error(),
4143
})
4244
return
4345
}
4446

45-
ctx.PlainText(200, []byte("success"))
47+
ctx.PlainText(http.StatusOK, []byte("success"))
48+
}
49+
50+
// AuthorizedPublicKeyByContent searches content as prefix (leak e-mail part)
51+
// and returns public key found.
52+
func AuthorizedPublicKeyByContent(ctx *macaron.Context) {
53+
content := ctx.Query("content")
54+
55+
publicKey, err := models.SearchPublicKeyByContent(content)
56+
if err != nil {
57+
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
58+
"err": err.Error(),
59+
})
60+
return
61+
}
62+
ctx.PlainText(http.StatusOK, []byte(publicKey.AuthorizedString()))
4663
}

0 commit comments

Comments
 (0)