-
Notifications
You must be signed in to change notification settings - Fork 526
/
GitReadSaveTest.java
430 lines (371 loc) · 18.8 KB
/
GitReadSaveTest.java
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
/*
* The MIT License
*
* Copyright (c) 2017, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package io.jenkins.blueocean.blueocean_git_pipeline;
import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.CredentialsScope;
import com.cloudbees.plugins.credentials.CredentialsStore;
import com.cloudbees.plugins.credentials.SystemCredentialsProvider;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.KeyPair;
import hudson.Functions;
import hudson.model.User;
import io.jenkins.blueocean.commons.MapsHelper;
import io.jenkins.blueocean.rest.impl.pipeline.PipelineBaseTest;
import io.jenkins.blueocean.ssh.UserSSHKeyManager;
import io.jenkins.blueocean.test.ssh.SSHServer;
import jenkins.model.Jenkins;
import jenkins.plugins.git.AbstractGitSCMSource;
import jenkins.plugins.git.GitSCMSource;
import jenkins.plugins.git.GitSampleRepoRule;
import jenkins.scm.impl.mock.AbstractSampleDVCSRepoRule;
import jenkins.scm.impl.mock.AbstractSampleRepoRule;
import org.apache.commons.io.FileUtils;
import org.jenkinsci.plugins.scriptsecurity.scripts.ScriptApproval;
import org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject;
import org.junit.After;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Logger;
import static org.junit.Assert.*;
/**
* Testing the git load/save backend
* @author kzantow
*/
public class GitReadSaveTest extends PipelineBaseTest {
@Rule
public GitSampleRepoRule repoWithJenkinsfiles = new GitSampleRepoRule();
@Rule
public GitSampleRepoRule repoNoJenkinsfile = new GitSampleRepoRule();
@Rule
public GitSampleRepoRule repoForSSH = new GitSampleRepoRule();
private final Logger logger = Logger.getLogger(getClass().getName());
private SSHServer sshd;
public GitReadSaveTest() {
}
@Before
@Override
public void setup() throws Exception {
super.setup();
setupUserCredentials();
setupScm();
}
private String getOrgName() {
return "jenkins";
}
private static final String masterPipelineScript = "pipeline { stage('Build 1') { steps { echo 'build' } } }";
private static final String branchPipelineScript = "pipeline { stage('Build 2') { steps { echo 'build' } } }";
private static final String newPipelineScript = "pipeline { stage('Build 3') { steps { echo 'build' } } }";
private void setupUserCredentials() throws Exception {
User user = login();
UserSSHKeyManager.getOrCreate(user);
}
private void setupScm() throws Exception {
// create git repo
repoWithJenkinsfiles.init();
repoWithJenkinsfiles.write("Jenkinsfile", masterPipelineScript);
repoWithJenkinsfiles.write("file", "initial content");
repoWithJenkinsfiles.git("add", "Jenkinsfile");
repoWithJenkinsfiles.git("commit", "--all", "--message=flow");
//create feature branch
repoWithJenkinsfiles.git("checkout", "-b", "feature/ux-1");
repoWithJenkinsfiles.write("Jenkinsfile", branchPipelineScript);
ScriptApproval.get().approveSignature("method java.lang.String toUpperCase");
repoWithJenkinsfiles.write("file", "subsequent content1");
repoWithJenkinsfiles.git("commit", "--all", "--message=tweaked1");
// we're using this to test push/pull, allow pushes to current branch, we reset it to match
repoWithJenkinsfiles.git("config", "--local", "--add", "receive.denyCurrentBranch", "false");
repoNoJenkinsfile.init();
repoNoJenkinsfile.write("file", "nearly empty file");
repoNoJenkinsfile.git("add", "file");
repoNoJenkinsfile.git("commit", "--all", "--message=initialize the repo");
// we're using this to test push/pull, allow pushes to current branch, we reset it to match
repoNoJenkinsfile.git("config", "--local", "--add", "receive.denyCurrentBranch", "false");
String gitRoot = System.getProperty("TEST_SSH_SERVER_GIT_ROOT", null);
boolean createRepoForSSH = true;
if (gitRoot != null) {
Field f = AbstractSampleRepoRule.class.getDeclaredField("tmp");
f.setAccessible(true);
Object tmpFolder = f.get(repoForSSH);
f = TemporaryFolder.class.getDeclaredField("folder");
f.setAccessible(true);
File dir = new File(gitRoot);
if (!dir.exists()) {
dir.mkdirs();
} else {
createRepoForSSH = false;
}
f.set(tmpFolder, dir);
f = AbstractSampleDVCSRepoRule.class.getDeclaredField("sampleRepo");
f.setAccessible(true);
f.set(repoForSSH, dir);
}
if (createRepoForSSH) {
repoForSSH.init();
repoForSSH.write("Jenkinsfile", masterPipelineScript);
repoForSSH.git("add", "Jenkinsfile");
repoForSSH.git("commit", "--all", "--message=initialize the repo");
// we're using this to test push/pull, allow pushes to current branch, we reset it to match
repoForSSH.git("config", "--local", "--add", "receive.denyCurrentBranch", "false");
}
}
private void startSSH() throws Exception {
startSSH(null);
}
private void startSSH(@Nullable User u) throws Exception {
if (sshd == null) {
// Set up an SSH server with access to a git repo
User user;
if(u == null) {
user = login();
} else {
user = u;
}
final BasicSSHUserPrivateKey key = UserSSHKeyManager.getOrCreate(user);
final JSch jsch = new JSch();
final KeyPair pair = KeyPair.load(jsch, key.getPrivateKey().getBytes(), null);
File keyFile = new File(System.getProperty("TEST_SSH_SERVER_KEY_FILE", File.createTempFile("hostkey", "ser").getCanonicalPath()));
int port = Integer.parseInt(System.getProperty("TEST_SSH_SERVER_PORT", "0"));
boolean allowLocalUser = Boolean.getBoolean("TEST_SSH_SERVER_ALLOW_LOCAL");
String userPublicKey = Base64.getEncoder().encodeToString(pair.getPublicKeyBlob());
sshd = new SSHServer( repoForSSH.getRoot(), keyFile, port, allowLocalUser, MapsHelper.of("bob", userPublicKey), true);
// Go, go, go
sshd.start();
}
}
@After
public void stopSSHServer() throws InterruptedException, IOException {
if (sshd != null) {
String ssh = "ssh -p " + sshd.getPort() + " bob@127.0.0.1";
String remote = "ssh://bob@127.0.0.1:" + sshd.getPort() + "" + repoForSSH.getRoot().getCanonicalPath();
logger.fine(ssh + " // remote: " + remote);
sshd.stop();
sshd = null;
}
}
@Test
public void testRepositoryCallbackToFSFunctionAdapter() throws IOException, InterruptedException {
final boolean[] called = { false };
new GitBareRepoReadSaveRequest.RepositoryCallbackToFSFunctionAdapter<>( repository -> {
called[0] = true;
return null;
} ).invoke( null, null);
Assert.assertTrue(called[0]);
}
@Test
public void testBareRepoReadWrite() throws Exception {
testGitReadWrite(GitReadSaveService.ReadSaveType.CACHE_BARE, repoWithJenkinsfiles, masterPipelineScript);
testGitReadWrite(GitReadSaveService.ReadSaveType.CACHE_BARE, repoNoJenkinsfile, null);
}
@Test
public void testGitScmValidate() throws Exception {
Assume.assumeFalse(Functions.isWindows()); // can't really run this on windows
startSSH();
String userHostPort = "bob@127.0.0.1:" + sshd.getPort();
String remote = "ssh://" + userHostPort + "" + repoForSSH.getRoot().getCanonicalPath();
User bob = login();
// Validate bob via repositoryUrl
Map r = new RequestBuilder(baseUrl)
.status(200)
.crumb( crumb )
.jwtToken(getJwtToken(j.jenkins, bob.getId(), bob.getId()))
.post("/organizations/" + getOrgName() + "/scm/git/validate/")
.data(MapsHelper.of(
"repositoryUrl", remote,
"credentialId", UserSSHKeyManager.getOrCreate(bob).getId()
)).build(Map.class);
assertNull(r.get("error"));
// Create a job
String jobName = "test-token-validation";
r = new RequestBuilder(baseUrl)
.status(201)
.crumb( crumb )
.jwtToken(getJwtToken(j.jenkins, bob.getId(), bob.getId()))
.post("/organizations/" + getOrgName() + "/pipelines/")
.data(MapsHelper.of(
"name", jobName,
"$class", "io.jenkins.blueocean.blueocean_git_pipeline.GitPipelineCreateRequest",
"scmConfig", MapsHelper.of(
"uri", remote,
"credentialId", UserSSHKeyManager.getOrCreate(bob).getId())
)).build(Map.class);
assertEquals(jobName, r.get("name"));
// Test for existing pipeline/job
r = new RequestBuilder(baseUrl)
.status(200)
.crumb( crumb )
.jwtToken(getJwtToken(j.jenkins, bob.getId(), bob.getId()))
.post("/organizations/" + getOrgName() + "/scm/git/validate/")
.data(MapsHelper.of(
"pipeline", MapsHelper.of("fullName", jobName),
"credentialId", UserSSHKeyManager.getOrCreate(bob).getId()
)).build(Map.class);
User alice = login("alice", "Alice Cooper", "alice@jenkins-ci.org");
// Test alice fails
new RequestBuilder(baseUrl)
.status(428)
.crumb( crumb )
.jwtToken(getJwtToken(j.jenkins, alice.getId(), alice.getId()))
.post("/organizations/" + getOrgName() + "/scm/git/validate/")
.data(MapsHelper.of(
"repositoryUrl", remote,
"credentialId", UserSSHKeyManager.getOrCreate(alice).getId()
)).build(String.class);
new RequestBuilder(baseUrl)
.status(428)
.crumb( crumb )
.jwtToken(getJwtToken(j.jenkins, alice.getId(), alice.getId()))
.post("/organizations/" + getOrgName() + "/scm/git/validate/")
.data(MapsHelper.of(
"pipeline", MapsHelper.of("fullName", jobName),
"credentialId", UserSSHKeyManager.getOrCreate(alice).getId()
)).build(String.class);
}
@Ignore("TODO no longer works due to `Unable to negotiate key exchange for server host key algorithms`; https://github.com/jenkinsci/blueocean-test-ssh-server/blob/blueocean-test-ssh-server-0.0.2/pom.xml#L147 is pretty old, and shaded")
@Test
public void bareRepoReadWriteOverSSH() throws Exception {
Assume.assumeFalse(Functions.isWindows()); // can't really run this on windows
startSSH();
String userHostPort = "bob@127.0.0.1:" + sshd.getPort();
String remote = "ssh://" + userHostPort + "" + repoForSSH.getRoot().getCanonicalPath() + "/.git";
testGitReadWrite(GitReadSaveService.ReadSaveType.CACHE_BARE, remote, repoForSSH, masterPipelineScript);
}
@Ignore("TODO as above")
@Test
public void bareRepoReadWriteNoEmail() throws Exception {
Assume.assumeFalse(Functions.isWindows()); // can't really run this on windows
User user = login("bob", "Bob Smith", null);
startSSH(user);
String userHostPort = "bob@127.0.0.1:" + sshd.getPort();
String remote = "ssh://" + userHostPort + "" + repoForSSH.getRoot().getCanonicalPath() + "/.git";
testGitReadWrite(GitReadSaveService.ReadSaveType.CACHE_BARE, remote, repoForSSH, masterPipelineScript, user);
}
private void testGitReadWrite(final @NonNull GitReadSaveService.ReadSaveType type, @NonNull GitSampleRepoRule repo, @Nullable String startPipelineScript) throws Exception {
testGitReadWrite(type, repo.getRoot().getCanonicalPath(), repo, startPipelineScript);
}
private void testGitReadWrite(final @NonNull GitReadSaveService.ReadSaveType type, @NonNull String remote, @NonNull GitSampleRepoRule repo, @Nullable String startPipelineScript) throws Exception {
testGitReadWrite(type,remote,repo,startPipelineScript, login());
}
private void testGitReadWrite(final @NonNull GitReadSaveService.ReadSaveType type, @NonNull String remote, @NonNull GitSampleRepoRule repo, @Nullable String startPipelineScript, @Nullable User user) throws Exception {
GitReadSaveService.setType(type);
String jobName = repo.getRoot().getName();
Map r = new RequestBuilder(baseUrl)
.status(201)
.jwtToken(getJwtToken(j.jenkins, user.getId(), user.getId()))
.crumb( crumb )
.post("/organizations/" + getOrgName() + "/pipelines/")
.data(MapsHelper.of(
"name", jobName,
"$class", "io.jenkins.blueocean.blueocean_git_pipeline.GitPipelineCreateRequest",
"scmConfig", MapsHelper.of(
"uri", remote,
"credentialId", UserSSHKeyManager.getOrCreate(user).getId())
)).build(Map.class);
assertEquals(jobName, r.get("name"));
// here we have an automatic ssh key authz being created for the user
// we copy this credentials at system level and tell the job to use it
BasicSSHUserPrivateKey sshUserPrivateKey = UserSSHKeyManager.getOrCreate(user);
BasicSSHUserPrivateKey.DirectEntryPrivateKeySource keySource =
new BasicSSHUserPrivateKey.DirectEntryPrivateKeySource(sshUserPrivateKey.getPrivateKey());
String id = UUID.randomUUID().toString();
BasicSSHUserPrivateKey key = new BasicSSHUserPrivateKey( CredentialsScope.SYSTEM, id, user.getId(), keySource,
null, id);
Iterable<CredentialsStore> stores = CredentialsProvider.lookupStores(Jenkins.get());
stores.forEach( credentialsStore -> {
if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) {
SystemCredentialsProvider.StoreImpl sysStore = (SystemCredentialsProvider.StoreImpl)credentialsStore;
try {
sysStore.addCredentials(null, key);
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
});
WorkflowMultiBranchProject item = (WorkflowMultiBranchProject) Jenkins.get().getItem( jobName);
item.getSCMSources().stream().forEach( scmSource -> {
String credId = ((AbstractGitSCMSource)scmSource).getCredentialsId();
LOGGER.debug( "credId: {}", credId );
((GitSCMSource)scmSource).setCredentialsId(key.getId());
});
String urlJobPrefix = "/organizations/" + getOrgName() + "/pipelines/" + jobName;
r = new RequestBuilder(baseUrl)
.status(200)
.jwtToken(getJwtToken(j.jenkins, user.getId(), user.getId()))
.crumb( crumb )
.get(urlJobPrefix + "/scm/content/?branch=master&path=Jenkinsfile&type="+type.name())
.build(Map.class);
String base64Data = (String)((Map)r.get("content")).get("base64Data");
assertEquals(startPipelineScript, base64Data == null ? null : new String( Base64.getDecoder().
decode(base64Data),
StandardCharsets.UTF_8));
// Update the remote
String newBase64Data = Base64.getEncoder().encodeToString(newPipelineScript.getBytes(StandardCharsets.UTF_8));
Map<String,String> content = new HashMap<>();
content.put("message", "Save Jenkinsfile");
content.put("path", "Jenkinsfile");
content.put("branch", "master");
content.put("sourceBranch", "master");
content.put("repo", jobName); // if no repo, this is not in an org folder
content.put("sha", "");
content.put("base64Data", newBase64Data);
content.put("type", type.name());
new RequestBuilder(baseUrl)
.status(200)
.jwtToken(getJwtToken(j.jenkins, user.getId(), user.getId()))
.crumb( crumb )
.put(urlJobPrefix + "/scm/content/")
.data(MapsHelper.of("content", content))
.build(Map.class);
// Check to make sure the remote was actually updated:
// refs udpated in our sample repo, not working tree, update it to get contents:
repo.git("reset", "--hard", "refs/heads/master");
String remoteJenkinsfile = FileUtils.readFileToString(new File(repo.getRoot(), "Jenkinsfile"));
Assert.assertEquals(newPipelineScript, remoteJenkinsfile);
// check to make sure we get the same thing from the service
r = new RequestBuilder(baseUrl)
.status(200)
.crumb( crumb )
.jwtToken(getJwtToken(j.jenkins, user.getId(), user.getId()))
.get(urlJobPrefix + "/scm/content/?branch=master&path=Jenkinsfile&type="+type.name())
.build(Map.class);
base64Data = (String)((Map)r.get("content")).get("base64Data");
Assert.assertEquals(base64Data, newBase64Data);
}
}