下面列出了hudson.model.ModelObject#hudson.util.Secret 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Issue("JENKINS-27389")
@Test public void grabEnv() {
story.addStep(new Statement() {
@Override public void evaluate() throws Throwable {
String credentialsId = "creds";
String secret = "s3cr3t";
CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, "sample", Secret.fromString(secret)));
WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition(""
+ "def extract(id) {\n"
+ " def v\n"
+ " withCredentials([string(credentialsId: id, variable: 'temp')]) {\n"
+ " v = env.temp\n"
+ " }\n"
+ " v\n"
+ "}\n"
+ "node {\n"
+ " echo \"got: ${extract('" + credentialsId + "')}\"\n"
+ "}", true));
story.j.assertLogContains("got: " + secret, story.j.assertBuildStatusSuccess(p.scheduleBuild2(0).get()));
}
});
}
@Ignore
@Test
public void testHtml() throws Exception {
List<JsonParameterVariables> jsonParameterVariables = new ArrayList<JsonParameterVariables>();
jsonParameterVariables.add(new JsonParameterVariables("KEY", "value"));
LambdaInvokeBuildStepVariables variables = new LambdaInvokeBuildStepVariables(false, "accessKeyId", Secret.fromString("secretKey"), "eu-west-1", "function", "payload", true, jsonParameterVariables);
FreeStyleProject p = j.createFreeStyleProject();
LambdaInvokeBuildStep before = new LambdaInvokeBuildStep(variables);
p.getBuildersList().add(before);
j.submit(j.createWebClient().getPage(p, "configure").getFormByName("config"));
LambdaInvokeBuildStep after = p.getBuildersList().get(LambdaInvokeBuildStep.class);
assertEquals(before, after);
}
private UsernamePasswordCredentials withValidCredentials() {
final List<StandardUsernamePasswordCredentials> all =
CredentialsProvider.lookupCredentials(
StandardUsernamePasswordCredentials.class,
(Item) null,
ACL.SYSTEM,
Collections.emptyList());
StandardUsernamePasswordCredentials jenkinsCredentials =
CredentialsMatchers.firstOrNull(all,
CredentialsMatchers.withId(credentialsId));
if (jenkinsCredentials == null) {
throw new ParsingException("Could not find the credentials for " + credentialsId);
}
return new UsernamePasswordCredentials(
jenkinsCredentials.getUsername(),
Secret.toString(jenkinsCredentials.getPassword()));
}
@Override
public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
url = (String) json.get("url");
email = (String) json.get("email");
apiKey = Secret.fromString((String) json.get("apiKey"));
stream = (String) json.get("stream");
topic = (String) json.get("topic");
jenkinsUrl = (String) json.get("jenkinsUrl");
smartNotify = Boolean.TRUE.equals(json.get("smartNotify"));
save();
// Cleanup the configuration file from previous plugin id - humbug
File oldConfig = new File(Jenkins.getInstance().getRootDir(), OLD_CONFIG_FILE_NAME);
if (oldConfig.exists()) {
if (oldConfig.delete()) {
logger.log(Level.INFO, "Old humbug configuration file successfully cleaned up.");
} else {
logger.log(Level.WARNING, "Failed to cleanup old humbug configuration file.");
}
}
return super.configure(req, json);
}
@Test
@ConfiguredWithCode("Proxy.yml")
public void describeProxyConfig() throws Exception {
ConfiguratorRegistry registry = ConfiguratorRegistry.get();
ConfigurationContext context = new ConfigurationContext(registry);
final CNode configNode = getProxyNode(context);
Secret password = requireNonNull(Secret.decrypt(getProxyNode(context).getScalarValue("secretPassword")));
final String yamlConfig = Util.toYamlString(configNode);
assertEquals(String.join("\n",
"name: \"proxyhost\"",
"noProxyHost: \"externalhost\"",
"port: 80",
"secretPassword: \"" + password.getEncryptedValue() + "\"",
"testUrl: \"http://google.com\"",
"userName: \"login\"",
""
), yamlConfig);
}
@Test
@Ignore
public void testHtml() throws Exception {
LambdaUploadVariables variables = new LambdaUploadVariables(false, "accessKeyId", Secret.fromString("secretKey"), "eu-west-1", "ziplocation", "description", "function", "handler", "1024", "role", "nodejs", "30", true, false, "full", null, false, "", "");
List<LambdaUploadVariables> variablesList = new ArrayList<>();
variablesList.add(variables);
FreeStyleProject p = j.createFreeStyleProject();
LambdaUploadPublisher before = new LambdaUploadPublisher(variablesList);
p.getPublishersList().add(before);
j.submit(j.createWebClient().getPage(p,"configure").getFormByName("config"));
LambdaUploadPublisher after = p.getPublishersList().get(LambdaUploadPublisher.class);
assertEquals(before, after);
}
@Test
public void testClearCredentialsItem() {
String expectedUsername = "expected-add-credentials-username";
String secretValue = "secret-value";
Secret secret = Secret.fromString(secretValue);
StandardUsernamePasswordCredentials credentials = new StandardUsernamePasswordCredentialsImpl(expectedUsername, secret);
maskedUsername.setValue(credentials);
assertEquals(credentials, maskedUsername.getValue());
maskedUsername.clear();
assertNull(maskedUsername.getValue());
}
public static String migrateCredentials(final String username, final String password) {
String credentialsId = null;
final DomainRequirement domainRequirement = null;
final List<StandardUsernamePasswordCredentials> credentials =
CredentialsMatchers.filter(
CredentialsProvider.lookupCredentials(
StandardUsernamePasswordCredentials.class,
Jenkins.getInstance(),
ACL.SYSTEM,
domainRequirement),
CredentialsMatchers.withUsername(username));
for (final StandardUsernamePasswordCredentials cred : credentials) {
if (StringUtils.equals(password, Secret.toString(cred.getPassword()))) {
// If some credentials have the same username/password, use those.
credentialsId = cred.getId();
break;
}
}
if (StringUtils.isBlank(credentialsId)) {
// If we couldn't find any existing credentials,
// create new credentials with the principal and secret and use it.
final StandardUsernamePasswordCredentials newCredentials =
new UsernamePasswordCredentialsImpl(
CredentialsScope.SYSTEM,
null,
"Migrated by Violation comments to bitbucket plugin",
username,
password);
SystemCredentialsProvider.getInstance().getCredentials().add(newCredentials);
credentialsId = newCredentials.getId();
}
if (StringUtils.isNotEmpty(credentialsId)) {
return credentialsId;
} else {
return null;
}
}
private void setupCredentials(String credentialId, String secret) throws Exception {
final CredentialsStore credentialsStore =
CredentialsProvider.lookupStores(jRule.jenkins).iterator().next();
final Domain domain = Domain.global();
final Credentials credentials =
new StringCredentialsImpl(
CredentialsScope.GLOBAL, credentialId, "", Secret.fromString(secret));
credentialsStore.addCredentials(domain, credentials);
}
public void setUp() throws IOException, InterruptedException, ReflectiveOperationException {
MockitoAnnotations.initMocks(this);
jobId = UUID.randomUUID().toString();
jobNonce = UUID.randomUUID().toString();
// Override the secret key so that we can test this class without {@link jenkins.model.Jenkins}.
Field field = Secret.class.getDeclaredField("SECRET");
field.setAccessible(true);
field.set(null, RandomStringUtils.random(16));
}
public AWSCodePipelineSCM(
final String projectName,
final boolean clear,
final String region,
final String awsAccessKey,
final String awsSecretKey,
final String proxyHost,
final String proxyPort,
final String category,
final String provider,
final String version,
final AWSClientFactory awsClientFactory) {
clearWorkspace = clear;
this.region = Validation.sanitize(region.trim());
this.awsAccessKey = Validation.sanitize(awsAccessKey.trim());
this.awsSecretKey = Secret.fromString(Validation.sanitize(awsSecretKey.trim()));
this.proxyHost = Validation.sanitize(proxyHost.trim());
this.projectName = null;
actionTypeCategory = Validation.sanitize(category.trim());
actionTypeProvider = Validation.sanitize(provider.trim());
actionTypeVersion = Validation.sanitize(version.trim());
this.awsClientFactory = awsClientFactory;
if (proxyPort != null && !proxyPort.isEmpty()) {
this.proxyPort = Integer.parseInt(proxyPort);
}
else {
this.proxyPort = 0;
}
}
@DataBoundConstructor
public AppCenterRecorder(@Nullable String apiToken, @Nullable String ownerName, @Nullable String appName, @Nullable String pathToApp, @Nullable String distributionGroups) {
this.apiToken = Secret.fromString(apiToken);
this.ownerName = Util.fixNull(ownerName);
this.appName = Util.fixNull(appName);
this.pathToApp = Util.fixNull(pathToApp);
this.distributionGroups = Util.fixNull(distributionGroups);
}
@Issue("JENKINS-41760")
@Test public void emptySecret() throws Exception {
CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), new StringCredentialsImpl(CredentialsScope.GLOBAL, "creds", null, Secret.fromString("")));
FreeStyleProject p = r.createFreeStyleProject();
p.getBuildWrappersList().add(new SecretBuildWrapper(Collections.singletonList(new StringBinding("SECRET", "creds"))));
p.getBuildersList().add(Functions.isWindows() ? new BatchFile("echo PASSES") : new Shell("echo PASSES"));
r.assertLogContains("PASSES", r.buildAndAssertSuccess(p));
}
@Test
public void testGetInvokeConfig() throws Exception {
List<JsonParameterVariables> jsonParameterVariables = new ArrayList<JsonParameterVariables>();
jsonParameterVariables.add(new JsonParameterVariables("ENV_NAME", "$.path"));
LambdaInvokeBuildStepVariables variables = new LambdaInvokeBuildStepVariables(false, "ID", Secret.fromString("SECRET}"), "eu-west-1", "FUNCTION", "${\"payload\":\"hello\"", true, jsonParameterVariables);
InvokeConfig invokeConfig = variables.getInvokeConfig();
assertEquals(variables.getFunctionName(), invokeConfig.getFunctionName());
assertEquals(variables.getPayload(), invokeConfig.getPayload());
assertEquals(variables.getSynchronous(), invokeConfig.isSynchronous());
assertEquals(variables.getJsonParameters().get(0).getEnvVarName(), invokeConfig.getJsonParameters().get(0).getEnvVarName());
assertEquals(variables.getJsonParameters().get(0).getJsonPath(), invokeConfig.getJsonParameters().get(0).getJsonPath());
}
@Before
public void setUp() {
baseRequest = new UploadRequest.Builder()
.setOwnerName("owner-name")
.setAppName("app-name")
.build();
given(mockTaskListener.getLogger()).willReturn(mockLogger);
final AppCenterServiceFactory factory = new AppCenterServiceFactory(Secret.fromString("secret-token"), mockWebServer.url("/").toString(), mockProxyConfig);
task = new CreateUploadResourceTask(mockTaskListener, factory);
}
@Test
public void testGetLambdaClientConfig() throws Exception {
LambdaPublishBuildStepVariables variables = new LambdaPublishBuildStepVariables(false, "ID", Secret.fromString("SECRET}"), "eu-west-1", "ARN", "ALIAS", "DESCRIPTION");
variables.expandVariables(new EnvVars());
LambdaClientConfig lambdaClientConfig = variables.getLambdaClientConfig();
AWSLambda lambda = lambdaClientConfig.getClient();
assertNotNull(lambda);
}
/**
* @deprecated use {@link #DockerServerCredentials(CredentialsScope, String, String, Secret, String, String)}
*/
@Deprecated
public DockerServerCredentials(CredentialsScope scope, String id, String description,
@CheckForNull String clientKey, @CheckForNull String clientCertificate,
@CheckForNull String serverCaCertificate) {
this(scope, id, description, Util.fixEmptyAndTrim(clientKey) == null ? null : Secret.fromString(clientKey),
clientCertificate, serverCaCertificate);
}
@DataBoundConstructor
public DockerServerCredentials(CredentialsScope scope, String id, String description,
@CheckForNull Secret clientKeySecret, @CheckForNull String clientCertificate,
@CheckForNull String serverCaCertificate) {
super(scope, id, description);
this.clientKey = clientKeySecret;
this.clientCertificate = Util.fixEmptyAndTrim(clientCertificate);
this.serverCaCertificate = Util.fixEmptyAndTrim(serverCaCertificate);
}
@Test
public void testValuesForGlobalConfig() throws Exception {
stepExecution.listener = taskListenerMock;
Jenkins mock = mock(Jenkins.class);
when(Jenkins.getInstanceOrNull()).thenReturn(mock);
PowerMockito.mockStatic(ConfidentialStore.class);
ConfidentialStore csMock = mock(ConfidentialStore.class);
when(ConfidentialStore.get()).thenReturn(csMock);
when(csMock.randomBytes(Matchers.anyInt()))
.thenAnswer(it -> new byte[(Integer) (it.getArguments()[0])]);
Secret encryptedEndpoint = Secret.fromString("globalEndpoint");
when(mattermostDescMock.getEndpoint()).thenReturn(encryptedEndpoint);
when(mattermostDescMock.getIcon()).thenReturn("globalIcon");
when(mattermostDescMock.getRoom()).thenReturn("globalChannel");
when(taskListenerMock.getLogger()).thenReturn(printStreamMock);
doNothing().when(printStreamMock).println();
when(stepExecution.getMattermostService(anyString(), anyString(), anyString()))
.thenReturn(mattermostServiceMock);
stepExecution.run();
verify(stepExecution, times(1))
.getMattermostService("globalEndpoint", "globalChannel", "globalIcon");
verify(mattermostServiceMock, times(1)).publish("message", "", "");
assertNull(stepExecution.step.getEndpoint());
assertNull(stepExecution.step.getIcon());
assertNull(stepExecution.step.getChannel());
assertNull(stepExecution.step.getColor());
assertNull(stepExecution.step.getText());
}
@Test
public void testGetInvokeConfig() throws Exception {
List<JsonParameterVariables> jsonParameterVariables = new ArrayList<JsonParameterVariables>();
jsonParameterVariables.add(new JsonParameterVariables("ENV_NAME", "$.path"));
LambdaInvokeVariables variables = new LambdaInvokeVariables(false, "ID", Secret.fromString("SECRET}"), "eu-west-1", "FUNCTION", "${\"payload\":\"hello\"", true, true, jsonParameterVariables);
InvokeConfig invokeConfig = variables.getInvokeConfig();
assertEquals(variables.getFunctionName(), invokeConfig.getFunctionName());
assertEquals(variables.getPayload(), invokeConfig.getPayload());
assertEquals(variables.getSynchronous(), invokeConfig.isSynchronous());
assertEquals(variables.getJsonParameters().get(0).getEnvVarName(), invokeConfig.getJsonParameters().get(0).getEnvVarName());
assertEquals(variables.getJsonParameters().get(0).getJsonPath(), invokeConfig.getJsonParameters().get(0).getJsonPath());
}
@Deprecated
public LambdaInvokeVariables(boolean useInstanceCredentials, String awsAccessKeyId, Secret awsSecretKey, String awsRegion, String functionName, String payload, boolean synchronous, boolean successOnly, List<JsonParameterVariables> jsonParameters) {
this.useInstanceCredentials = useInstanceCredentials;
this.awsAccessKeyId = awsAccessKeyId;
this.awsSecretKey = awsSecretKey != null ? awsSecretKey.getEncryptedValue() : null;
this.awsRegion = awsRegion;
this.functionName = functionName;
this.payload = payload;
this.synchronous = synchronous;
this.successOnly = successOnly;
this.jsonParameters = jsonParameters;
}
/**
* Constructor.
*
* @param scope the credentials scope.
* @param id the credentials id.
* @param description the description of the token.
* @param token the token itself (will be passed through {@link Secret#fromString(String)})
*/
@DataBoundConstructor
public PersonalAccessTokenImpl(
@CheckForNull CredentialsScope scope,
@CheckForNull String id,
@CheckForNull String description,
@NonNull String token) {
super(scope, id, description);
this.token = Secret.fromString(token);
}
@DataBoundConstructor
public ConduitCredentialsImpl(
@CheckForNull String id,
@NonNull @CheckForNull String url,
@Nullable String gateway,
@CheckForNull String description,
@CheckForNull String token) {
super(id, description);
this.url = url;
this.gateway = gateway;
this.token = Secret.fromString(token);
}
@Before
public void setUp() {
Secret secret = Secret.fromString(SECRET_VALUE);
listener = StreamTaskListener.fromStdout();
StandardUsernameCredentials cred = new StandardUsernamePasswordCredentialsImpl(USER_NAME, secret);
provider = new CredentialsProviderImpl(listener, cred);
}
@DataBoundConstructor
public VaultAppRoleCredential(@CheckForNull CredentialsScope scope, @CheckForNull String id,
@CheckForNull String description, @NonNull String roleId, @NonNull Secret secretId,
String path) {
super(scope, id, description);
this.secretId = secretId;
this.roleId = roleId;
if (path == null) {
this.path = "approle";
} else {
this.path = path;
}
}
public void expandVariables(EnvVars env) {
awsAccessKeyId = ExpansionUtils.expand(awsAccessKeyId, env);
clearTextAwsSecretKey = ExpansionUtils.expand(Secret.toString(Secret.fromString(awsSecretKey)), env);
awsRegion = ExpansionUtils.expand(awsRegion, env);
functionName = ExpansionUtils.expand(functionName, env);
payload = ExpansionUtils.expand(payload, env);
if(jsonParameters != null) {
for (JsonParameterVariables jsonParameter : jsonParameters) {
jsonParameter.expandVariables(env);
}
}
}
@Deprecated
public LambdaEventSourceBuildStepVariables(boolean useInstanceCredentials, String awsAccessKeyId, Secret awsSecretKey, String awsRegion, String functionName, String functionAlias, String eventSourceArn) {
this.useInstanceCredentials = useInstanceCredentials;
this.awsAccessKeyId = awsAccessKeyId;
this.awsSecretKey = awsSecretKey != null ? awsSecretKey.getEncryptedValue() : null;
this.awsRegion = awsRegion;
this.functionName = functionName;
this.functionAlias = functionAlias;
this.eventSourceArn = eventSourceArn;
}
static void setupGitLabConnections(JenkinsRule jenkins, MockServerRule mockServer) throws IOException {
GitLabConnectionConfig connectionConfig = jenkins.get(GitLabConnectionConfig.class);
String apiTokenId = "apiTokenId";
for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) {
if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) {
List<Domain> domains = credentialsStore.getDomains();
credentialsStore.addCredentials(domains.get(0),
new StringCredentialsImpl(CredentialsScope.SYSTEM, apiTokenId, "GitLab API Token", Secret.fromString(TestUtility.API_TOKEN)));
}
}
connectionConfig.addConnection(new GitLabConnection(TestUtility.GITLAB_CONNECTION_V3, "http://localhost:" + mockServer.getPort() + "/gitlab", apiTokenId, new V3GitLabClientBuilder(), false, 10, 10));
connectionConfig.addConnection(new GitLabConnection(TestUtility.GITLAB_CONNECTION_V4, "http://localhost:" + mockServer.getPort() + "/gitlab", apiTokenId, new V4GitLabClientBuilder(), false, 10, 10));
}
@Override
public String getToken(Vault vault) {
try {
return vault.auth().loginByGithub(Secret.toString(accessToken)).getAuthClientToken();
} catch (VaultException e) {
throw new VaultPluginException("could not log in into vault", e);
}
}
/**
* Validate top level configuration values.
*
* @param log Destination Task Log
* @return Whether or not the configuration is valid.
*/
private boolean validateConfiguration(@Nonnull PrintStream log) {
String roleArn = getRoleArn();
String akid = Secret.toString(getAkid());
String skid = Secret.toString(getSkid());
// [Required]: Auth Credentials
if ((roleArn == null || roleArn.isEmpty()) && (akid == null || akid.isEmpty() || skid == null || skid.isEmpty())) {
writeToLog(log, "Either IAM Role ARN or AKID/SKID must be set.");
return false;
}
// [Required]: Project
if (projectName == null || projectName.isEmpty()) {
writeToLog(log, "Project must be set.");
return false;
}
// [Required]: DevicePool
if (devicePoolName == null || devicePoolName.isEmpty()) {
writeToLog(log, "DevicePool must be set.");
return false;
}
// [Required]: App Artifact
if (!ifWebApp && (appArtifact == null || appArtifact.isEmpty())) {
writeToLog(log, "Application Artifact must be set.");
return false;
}
// [Required]: At least one test.
if (testToRun == null || stringToTestType(testToRun) == null) {
writeToLog(log, "A test type must be set.");
return false;
}
return true;
}