Java Code Examples for org.eclipse.jgit.transport.CredentialItem#StringType

The following examples show how to use org.eclipse.jgit.transport.CredentialItem#StringType . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JGitCredentialsProvider.java    From mOrgAnd with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean get(URIish uri, CredentialItem... items)
        throws UnsupportedCredentialItem {
    for (CredentialItem item : items) {
        if (item instanceof CredentialItem.Username) {
            ((CredentialItem.Username) item).setValue(username);
        } else if (item instanceof CredentialItem.Password) {
            ((CredentialItem.Password) item).setValue(password.toCharArray());
        } else if (item instanceof CredentialItem.StringType) {
            ((CredentialItem.StringType) item).setValue(password);
        } else if (item instanceof CredentialItem.InformationalMessage) {
            throw new UnsupportedCredentialItem(uri, "Not supported");
        } else if (item instanceof CredentialItem.YesNoType) {
            // TODO handle strict host key checking here
            throw new UnsupportedCredentialItem(uri, "Not supported");
        } else {
            throw new UnsupportedCredentialItem(uri, "Not supported");
        }
    }
    return true;
}
 
Example 2
Source File: SmartCredentialsProviderTest.java    From git-client-plugin with MIT License 6 votes vote down vote up
@Before
public void setUp() {
    listener = StreamTaskListener.fromStdout();
    provider = new SmartCredentialsProvider(listener);
    username = new CredentialItem.Username();
    password = new CredentialItem.Password();

    maskedUsername = new StandardUsernameCredentialsCredentialItem(MASKED_USER_NAME_PROMPT, true);
    unmaskedUsername = new StandardUsernameCredentialsCredentialItem(UNMASKED_USER_NAME_PROMPT, false);

    maskedStringType = new CredentialItem.StringType(MASKED_STRING_TYPE_PROMPT, true);
    unmaskedStringType = new CredentialItem.StringType(UNMASKED_STRING_TYPE_PROMPT, false);
    specialStringType = new CredentialItem.StringType(SPECIAL_STRING_TYPE_PROMPT, false);

    assertNull(username.getValue());
    assertNull(password.getValue());
    assertNull(maskedUsername.getValue());
    assertNull(unmaskedUsername.getValue());
    assertNull(maskedStringType.getValue());
    assertNull(unmaskedStringType.getValue());
}
 
Example 3
Source File: TransportCommand.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public boolean get (URIish uriish, CredentialItem... items) throws UnsupportedCredentialItem {
    String user = uriish.getUser();
    if (user == null) {
        user = "";
    }
    String password = uriish.getPass();
    if (password == null) {
        password = "";
    }
    for (CredentialItem i : items) {
        if (i instanceof CredentialItem.Username) {
            ((CredentialItem.Username) i).setValue(user);
            continue;
        }
        if (i instanceof CredentialItem.Password) {
            ((CredentialItem.Password) i).setValue(password.toCharArray());
            continue;
        }
        if (i instanceof CredentialItem.StringType) {
            if (i.getPromptText().equals("Password: ")) { //NOI18N
                ((CredentialItem.StringType) i).setValue(password);
                continue;
            }
        }
        throw new UnsupportedCredentialItem(uriish, i.getClass().getName()
                + ":" + i.getPromptText()); //NOI18N
    }
    return true;
}
 
Example 4
Source File: JGitSshSessionFactory.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized RemoteSession getSession (URIish uri, CredentialsProvider credentialsProvider, FS fs, int tms) throws TransportException {
    boolean agentUsed = false;
    String host = uri.getHost();
    CredentialItem.StringType identityFile = null;
    if (credentialsProvider != null) {
        identityFile = new JGitCredentialsProvider.IdentityFileItem("Identity file for " + host, false);
        if (credentialsProvider.isInteractive() && credentialsProvider.get(uri, identityFile) && identityFile.getValue() != null) {
            LOG.log(Level.FINE, "Identity file for {0}: {1}", new Object[] { host, identityFile.getValue() }); //NOI18N
            agentUsed = setupJSch(fs, host, identityFile, uri, true);
            LOG.log(Level.FINE, "Setting cert auth for {0}, agent={1}", new Object[] { host, agentUsed }); //NOI18N
        }
    }
    try {
        LOG.log(Level.FINE, "Trying to connect to {0}, agent={1}", new Object[] { host, agentUsed }); //NOI18N
        return super.getSession(uri, credentialsProvider, fs, tms);
    } catch (Exception ex) {
        // catch rather all exceptions. In case jsch-agent-proxy is broken again we should
        // at least fall back on key/pasphrase
        if (agentUsed) {
            LOG.log(ex instanceof TransportException ? Level.FINE : Level.INFO, null, ex);
            setupJSch(fs, host, identityFile, uri, false);
            LOG.log(Level.FINE, "Trying to connect to {0}, agent={1}", new Object[] { host, false }); //NOI18N
            return super.getSession(uri, credentialsProvider, fs, tms);
        } else {
            LOG.log(Level.FINE, "Connection failed: {0}", host); //NOI18N
            throw ex;
        }
    }
}
 
Example 5
Source File: JGitSshSessionFactory.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean setupJSch (FS fs, String host, CredentialItem.StringType identityFile, URIish uri, boolean preferAgent) throws TransportException {
    boolean agentUsed;
    if (sshConfig == null) {
        sshConfig = OpenSshConfig.get(fs);
    }
    final OpenSshConfig.Host hc = sshConfig.lookup(host);
    try {
        JSch jsch = getJSch(hc, fs);
        agentUsed = setupJSchIdentityRepository(jsch, identityFile.getValue(), preferAgent);
    } catch (JSchException ex) {
        throw new TransportException(uri, ex.getMessage(), ex);
    }
    return agentUsed;
}
 
Example 6
Source File: HttpDelegatingCredentialsProvider.java    From gitflow-incremental-builder with MIT License 5 votes vote down vote up
@Override
public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem {

    // only handle HTTP(s)
    if (uri.getScheme() != null && !uri.getScheme().startsWith("http")) {
        return false;
    }

    CredentialsPair credentialsPair = credentials.computeIfAbsent(uri, u -> {
        try {
            return lookupCredentials(uri);
        } catch (IOException | InterruptedException | RuntimeException e) {
            logger.warn("Failed to look up credentials via 'git credential fill' for: " + uri, e);
            return null;
        }
    });
    if (credentialsPair == null) {
        return false;
    }

    // map extracted credentials to CredentialItems, see also: org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider
    for (CredentialItem item : items) {
        if (item instanceof CredentialItem.Username) {
            ((CredentialItem.Username) item).setValue(credentialsPair.username);
        } else if (item instanceof CredentialItem.Password) {
            ((CredentialItem.Password) item).setValue(credentialsPair.password);
        } else if (item instanceof CredentialItem.StringType && item.getPromptText().equals("Password: ")) {
            ((CredentialItem.StringType) item).setValue(new String(credentialsPair.password));
        } else {
            throw new UnsupportedCredentialItem(uri, item.getClass().getName() + ":" + item.getPromptText());
        }
    }

    return true;
}
 
Example 7
Source File: PassphraseCredentialsProvider.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean supports(CredentialItem... items) {
	for (final CredentialItem item : items) {
		if (item instanceof CredentialItem.StringType
				&& item.getPromptText().startsWith(PROMPT)) {
			continue;
		}
		else {
			return false;
		}
	}
	return true;
}
 
Example 8
Source File: PassphraseCredentialsProvider.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
/**
 * Ask for the credential items to be populated with the passphrase.
 * @param uri the URI of the remote resource that needs authentication.
 * @param items the items the application requires to complete authentication.
 * @return {@code true} if the request was successful and values were supplied;
 * {@code false} if the user canceled the request and did not supply all requested
 * values.
 * @throws UnsupportedCredentialItem if one of the items supplied is not supported.
 */
@Override
public boolean get(URIish uri, CredentialItem... items)
		throws UnsupportedCredentialItem {
	for (final CredentialItem item : items) {
		if (item instanceof CredentialItem.StringType
				&& item.getPromptText().startsWith(PROMPT)) {
			((CredentialItem.StringType) item).setValue(this.passphrase);
			continue;
		}
		throw new UnsupportedCredentialItem(uri,
				item.getClass().getName() + ":" + item.getPromptText());
	}
	return true;
}
 
Example 9
Source File: JGitEnvironmentRepositoryTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void passphraseShouldSetCredentials() throws Exception {
	final String passphrase = "mypassphrase";
	Git mockGit = mock(Git.class);
	MockCloneCommand mockCloneCommand = new MockCloneCommand(mockGit);

	JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(
			this.environment, new JGitEnvironmentProperties());
	envRepository.setGitFactory(new MockGitFactory(mockGit, mockCloneCommand));
	envRepository.setUri("git+ssh://git@somegitserver/somegitrepo");
	envRepository.setBasedir(new File("./mybasedir"));
	envRepository.setPassphrase(passphrase);
	envRepository.setCloneOnStart(true);
	envRepository.afterPropertiesSet();

	assertThat(mockCloneCommand.hasPassphraseCredentialsProvider()).isTrue();

	CredentialsProvider provider = mockCloneCommand.getCredentialsProvider();
	assertThat(provider.isInteractive()).isFalse();

	CredentialItem.StringType stringCredential = new CredentialItem.StringType(
			PassphraseCredentialsProvider.PROMPT, true);

	assertThat(provider.supports(stringCredential)).isTrue();
	provider.get(new URIish(), stringCredential);
	assertThat(passphrase).isEqualTo(stringCredential.getValue());
}
 
Example 10
Source File: JGitEnvironmentRepositoryTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void gitCredentialsProviderFactoryCreatesPassphraseProvider()
		throws Exception {
	final String passphrase = "mypassphrase";
	final String gitUri = "git+ssh://git@somegitserver/somegitrepo";
	Git mockGit = mock(Git.class);
	MockCloneCommand mockCloneCommand = new MockCloneCommand(mockGit);

	JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(
			this.environment, new JGitEnvironmentProperties());
	envRepository.setGitFactory(new MockGitFactory(mockGit, mockCloneCommand));
	envRepository.setUri(gitUri);
	envRepository.setBasedir(new File("./mybasedir"));
	envRepository.setPassphrase(passphrase);
	envRepository.setCloneOnStart(true);
	envRepository.afterPropertiesSet();

	assertThat(mockCloneCommand.hasPassphraseCredentialsProvider()).isTrue();

	CredentialsProvider provider = mockCloneCommand.getCredentialsProvider();
	assertThat(provider.isInteractive()).isFalse();

	CredentialItem.StringType stringCredential = new CredentialItem.StringType(
			PassphraseCredentialsProvider.PROMPT, true);

	assertThat(provider.supports(stringCredential)).isTrue();
	provider.get(new URIish(), stringCredential);
	assertThat(passphrase).isEqualTo(stringCredential.getValue());

}
 
Example 11
Source File: SmartCredentialsProvider.java    From git-client-plugin with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public synchronized boolean get(URIish uri, CredentialItem... credentialItems) throws UnsupportedCredentialItem {
    StandardCredentials c = specificCredentials.get(uri == null ? null : uri.toString());
    if (c == null) {
        c = defaultCredentials;
    }
    if (c == null) {
        return false;
    }
    for (CredentialItem i : credentialItems) {
        if (i instanceof StandardUsernameCredentialsCredentialItem && c instanceof StandardUsernameCredentials) {
            ((StandardUsernameCredentialsCredentialItem) i).setValue((StandardUsernameCredentials) c);
            continue;
        }
        if (i instanceof CredentialItem.Username && c instanceof UsernameCredentials) {
            ((CredentialItem.Username) i).setValue(((UsernameCredentials)c).getUsername());
            continue;
        }
        if (i instanceof CredentialItem.Password && c instanceof PasswordCredentials) {
            ((CredentialItem.Password) i).setValue(
                    ((PasswordCredentials) c).getPassword().getPlainText().toCharArray());
            continue;
        }
        if (i instanceof CredentialItem.StringType) {
            if (i.getPromptText().equals("Password: ") && c instanceof PasswordCredentials) {
                ((CredentialItem.StringType) i).setValue(((PasswordCredentials) c).getPassword().getPlainText());
                continue;
            }
        }
        throw new UnsupportedCredentialItem(uri, i.getClass().getName()
                + ":" + i.getPromptText());
    }
    return true;
}
 
Example 12
Source File: CredentialsProviderImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * If username/password is given, use it for HTTP auth.
 */
@Override
public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem {
    if (!(cred instanceof StandardUsernamePasswordCredentials))
        return false;
    StandardUsernamePasswordCredentials _cred = (StandardUsernamePasswordCredentials) cred;

    for (CredentialItem i : items) {
        if (i instanceof CredentialItem.Username) {
            ((CredentialItem.Username) i).setValue(_cred.getUsername());
            continue;
        }
        if (i instanceof CredentialItem.Password) {
            ((CredentialItem.Password) i).setValue(
                    _cred.getPassword().getPlainText().toCharArray());
            continue;
        }
        if (i instanceof CredentialItem.StringType) {
            if (i.getPromptText().equals("Password: ")) {
                ((CredentialItem.StringType) i).setValue(
                        _cred.getPassword().getPlainText());
                continue;
            }
        }
        throw new UnsupportedCredentialItem(uri, i.getClass().getName()
                + ":" + i.getPromptText());
    }
    return true;
}
 
Example 13
Source File: CredentialsProviderImplTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void testSupportsSpecialStringType() {
    CredentialItem.StringType specialStringType = new CredentialItem.StringType("Password: ", false);
    assertNull(specialStringType.getValue());

    /* The supports() method does not know about the "special" StringType
     * which can be used to return the password plaintext.  Passing a
     * StringType with the prompt text "Password: " will return the plain
     * text password.
     */
    assertFalse(provider.supports(specialStringType));
    assertTrue(provider.get(uri, specialStringType));
    assertEquals(SECRET_VALUE, specialStringType.getValue());
}
 
Example 14
Source File: CredentialsProviderImplTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void testSpecialStringTypeThrowsException() {
    CredentialItem.StringType specialStringType = new CredentialItem.StringType("Bad Password: ", false);
    assertFalse(provider.supports(specialStringType));
    assertThrows(UnsupportedCredentialItem.class,
                 () -> {
                     provider.get(uri, specialStringType);
                 });
}
 
Example 15
Source File: GitCredentialsProvider.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem {
	for (CredentialItem item : items) {
		if (item instanceof CredentialItem.Username || item instanceof CredentialItem.Password) {
			if ((this.privateKey == null || this.privateKey.length == 0) && (this.publicKey == null || this.publicKey.length == 0) && (this.passphrase == null || this.passphrase.length == 0)) {
				CredentialItem.Username u = new CredentialItem.Username();
				CredentialItem.Password p = new CredentialItem.Password();
				super.get(uri, u, p);
				if ((u.getValue() == null || u.getValue().length() == 0) && (p.getValue() == null || p.getValue().length == 0)) {
					if (uri != null) {
						if (this.remoteUser != null) {
							/* see if a user token is available */
							String uriString = uri.toString();
							IGitHubToken token = tokenCache.get(uriString);
							if (token != null && token.getExpiry() != 0 && token.getExpiry() < System.currentTimeMillis()) {
								token = null;
							}
							if (token == null) {
								for (int i = 0; token == null && i < GithubTokenProviders.size(); i++) {
									token = GithubTokenProviders.get(i).getToken(uriString, remoteUser);
								}
							}
							if (token != null) {
								if (item instanceof CredentialItem.Username) {
									((CredentialItem.Username)item).setValue(token.getUsername());
								} else {
									((CredentialItem.Password)item).setValue(token.getPassword());
								}
								tokenCache.put(uriString, token);
								continue;
							}
						}
					}
				}
			}
		}
		if (super.supports(item)) {
			super.get(uri, item);
		} else if (item instanceof CredentialItem.StringType) {
			if (item.getPromptText().toLowerCase(Locale.ENGLISH).contains("passphrase") && passphrase != null && passphrase.length > 0) {
				((CredentialItem.StringType) item).setValue(new String(passphrase));
			} else {
				((CredentialItem.StringType) item).setValue("");
			}
		} else if (item instanceof CredentialItem.CharArrayType) {
			((CredentialItem.CharArrayType) item).setValue(new char[0]);
		} else {
			throw new UnsupportedCredentialItem(uri, item.getPromptText());
		}
	}
	return true; // we assume that user provided all credentials that are needed
}