aboutsummaryrefslogtreecommitdiffstats
path: root/integrations/deploy_key_push_test.go
blob: 8b3d6656293a2c55d797da31902b8445973cea8e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
// Copyright 2019 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package integrations

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"path/filepath"
	"testing"
	"time"

	"code.gitea.io/git"

	"code.gitea.io/gitea/modules/setting"
	api "code.gitea.io/sdk/gitea"
	"github.com/stretchr/testify/assert"
)

func createEmptyRepository(username, reponame string) func(*testing.T) {
	return func(t *testing.T) {
		session := loginUser(t, username)
		token := getTokenForLoggedInUser(t, session)
		req := NewRequestWithJSON(t, "POST", "/api/v1/user/repos?token="+token, &api.CreateRepoOption{
			AutoInit:    false,
			Description: "Temporary empty repo",
			Name:        reponame,
			Private:     false,
		})
		session.MakeRequest(t, req, http.StatusCreated)
	}
}

func createDeployKey(username, reponame, keyname, keyFile string, readOnly bool) func(*testing.T) {
	return func(t *testing.T) {
		session := loginUser(t, username)
		token := getTokenForLoggedInUser(t, session)
		urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/keys?token=%s", username, reponame, token)

		dataPubKey, err := ioutil.ReadFile(keyFile + ".pub")
		assert.NoError(t, err)
		req := NewRequestWithJSON(t, "POST", urlStr, api.CreateKeyOption{
			Title:    keyname,
			Key:      string(dataPubKey),
			ReadOnly: readOnly,
		})
		session.MakeRequest(t, req, http.StatusCreated)
	}
}

func initTestRepository(dstPath string) func(*testing.T) {
	return func(t *testing.T) {
		// Init repository in dstPath
		assert.NoError(t, git.InitRepository(dstPath, false))
		assert.NoError(t, ioutil.WriteFile(filepath.Join(dstPath, "README.md"), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s", dstPath)), 0644))
		assert.NoError(t, git.AddChanges(dstPath, true))
		signature := git.Signature{
			Email: "test@example.com",
			Name:  "test",
			When:  time.Now(),
		}
		assert.NoError(t, git.CommitChanges(dstPath, git.CommitChangesOptions{
			Committer: &signature,
			Author:    &signature,
			Message:   "Initial Commit",
		}))
	}
}

func pushTestRepository(dstPath, username, reponame string, u url.URL, keyFile string) func(*testing.T) {
	return func(t *testing.T) {
		//Setup remote link
		u.Scheme = "ssh"
		u.User = url.User("git")
		u.Host = fmt.Sprintf("%s:%d", setting.SSH.ListenHost, setting.SSH.ListenPort)

		//Setup ssh wrapper
		os.Setenv("GIT_SSH_COMMAND",
			"ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i "+
				filepath.Join(setting.AppWorkPath, keyFile))
		os.Setenv("GIT_SSH_VARIANT", "ssh")

		log.Printf("Adding remote: %s\n", u.String())
		_, err := git.NewCommand("remote", "add", "origin", u.String()).RunInDir(dstPath)
		assert.NoError(t, err)

		log.Printf("Pushing to: %s\n", u.String())
		_, err = git.NewCommand("push", "-u", "origin", "master").RunInDir(dstPath)
		assert.NoError(t, err)
	}
}

func checkRepositoryEmptyStatus(username, reponame string, isEmpty bool) func(*testing.T) {
	return func(t *testing.T) {
		session := loginUser(t, username)
		token := getTokenForLoggedInUser(t, session)
		urlStr := fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", username, reponame, token)

		req := NewRequest(t, "GET", urlStr)
		resp := session.MakeRequest(t, req, http.StatusOK)

		var repository api.Repository
		DecodeJSON(t, resp, &repository)

		assert.Equal(t, isEmpty, repository.Empty)
	}
}

func deleteRepository(username, reponame string) func(*testing.T) {
	return func(t *testing.T) {
		session := loginUser(t, username)
		token := getTokenForLoggedInUser(t, session)
		urlStr := fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", username, reponame, token)

		req := NewRequest(t, "DELETE", urlStr)
		session.MakeRequest(t, req, http.StatusNoContent)
	}
}

func TestPushDeployKeyOnEmptyRepo(t *testing.T) {
	onGiteaRun(t, testPushDeployKeyOnEmptyRepo)
}

func testPushDeployKeyOnEmptyRepo(t *testing.T, u *url.URL) {
	reponame := "deploy-key-empty-repo-1"
	username := "user2"
	u.Path = fmt.Sprintf("%s/%s.git", username, reponame)
	keyname := fmt.Sprintf("%s-push", reponame)

	t.Run("CreateEmptyRepository", createEmptyRepository(username, reponame))
	t.Run("CheckIsEmpty", checkRepositoryEmptyStatus(username, reponame, true))

	//Setup the push deploy key file
	keyFile := filepath.Join(setting.AppDataPath, keyname)
	err := exec.Command("ssh-keygen", "-f", keyFile, "-t", "rsa", "-N", "").Run()
	assert.NoError(t, err)
	defer os.RemoveAll(keyFile)
	defer os.RemoveAll(keyFile + ".pub")

	t.Run("CreatePushDeployKey", createDeployKey(username, reponame, keyname, keyFile, false))

	// Setup the testing repository
	dstPath, err := ioutil.TempDir("", "repo-tmp-deploy-key-empty-repo-1")
	assert.NoError(t, err)
	defer os.RemoveAll(dstPath)

	t.Run("InitTestRepository", initTestRepository(dstPath))
	t.Run("SSHPushTestRepository", pushTestRepository(dstPath, username, reponame, *u, keyFile))

	log.Println("Done Push")
	t.Run("CheckIsNotEmpty", checkRepositoryEmptyStatus(username, reponame, false))

	t.Run("DeleteRepository", deleteRepository(username, reponame))
}