Format all Java files with google-java-format

Having a standard tool for formatting saves reviewers' valuable time.
google-java-format is Google's standard formatter and is somewhat
inspired by gofmt[1]. This commit formats everything using
google-java-format version 1.2.

The downside of this one-off formatting is breaking blame. This can be
somewhat hacked around with a tool like git-hyper-blame[2], but it's
definitely not optimal until/unless this kind of feature makes its way
to git core.

Not in this change:
* Tool support, e.g. Eclipse. The command must be run manually [3].
* Documentation of best practice, e.g. new 100-column default.

[1] https://talks.golang.org/2015/gofmt-en.slide#3
[2] https://commondatastorage.googleapis.com/chrome-infra-docs/flat/depot_tools/docs/html/git-hyper-blame.html
[3] git ls-files | grep java$ | xargs google-java-format -i

Change-Id: Id5f3c6de95ce0b68b41f0a478b5c99a93675aaa3
Signed-off-by: David Pursehouse <dpursehouse@collab.net>
This commit is contained in:
Dave Borowitz
2016-11-13 09:56:32 -08:00
committed by David Pursehouse
parent 6723b6d0fa
commit 292fa154c1
2443 changed files with 54816 additions and 57825 deletions

View File

@@ -52,7 +52,11 @@ import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Provider;
import com.google.inject.util.Providers;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.eclipse.jgit.internal.storage.dfs.DfsRepositoryDescription;
@@ -66,34 +70,21 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/** Unit tests for {@link GerritPublicKeyChecker}. */
public class GerritPublicKeyCheckerTest {
@Inject
private AccountCache accountCache;
@Inject private AccountCache accountCache;
@Inject
private AccountManager accountManager;
@Inject private AccountManager accountManager;
@Inject
private GerritPublicKeyChecker.Factory checkerFactory;
@Inject private GerritPublicKeyChecker.Factory checkerFactory;
@Inject
private IdentifiedUser.GenericFactory userFactory;
@Inject private IdentifiedUser.GenericFactory userFactory;
@Inject
private InMemoryDatabase schemaFactory;
@Inject private InMemoryDatabase schemaFactory;
@Inject
private SchemaCreator schemaCreator;
@Inject private SchemaCreator schemaCreator;
@Inject
private ThreadLocalRequestContext requestContext;
@Inject private ThreadLocalRequestContext requestContext;
private LifecycleManager lifecycle;
private ReviewDb db;
@@ -106,11 +97,14 @@ public class GerritPublicKeyCheckerTest {
public void setUpInjector() throws Exception {
Config cfg = InMemoryModule.newDefaultConfig();
cfg.setInt("receive", null, "maxTrustDepth", 2);
cfg.setStringList("receive", null, "trustedKey", ImmutableList.of(
Fingerprint.toString(keyB().getPublicKey().getFingerprint()),
Fingerprint.toString(keyD().getPublicKey().getFingerprint())));
Injector injector = Guice.createInjector(
new InMemoryModule(cfg, new TestNotesMigration()));
cfg.setStringList(
"receive",
null,
"trustedKey",
ImmutableList.of(
Fingerprint.toString(keyB().getPublicKey().getFingerprint()),
Fingerprint.toString(keyD().getPublicKey().getFingerprint())));
Injector injector = Guice.createInjector(new InMemoryModule(cfg, new TestNotesMigration()));
lifecycle = new LifecycleManager();
lifecycle.add(injector);
@@ -119,25 +113,25 @@ public class GerritPublicKeyCheckerTest {
db = schemaFactory.open();
schemaCreator.create(db);
userId =
accountManager.authenticate(AuthRequest.forUser("user")).getAccountId();
userId = accountManager.authenticate(AuthRequest.forUser("user")).getAccountId();
Account userAccount = db.accounts().get(userId);
// Note: does not match any key in TestKeys.
userAccount.setPreferredEmail("user@example.com");
db.accounts().update(ImmutableList.of(userAccount));
user = reloadUser();
requestContext.setContext(new RequestContext() {
@Override
public CurrentUser getUser() {
return user;
}
requestContext.setContext(
new RequestContext() {
@Override
public CurrentUser getUser() {
return user;
}
@Override
public Provider<ReviewDb> getReviewDbProvider() {
return Providers.of(db);
}
});
@Override
public Provider<ReviewDb> getReviewDbProvider() {
return Providers.of(db);
}
});
storeRepo = new InMemoryRepository(new DfsRepositoryDescription("repo"));
store = new PublicKeyStore(storeRepo);
@@ -175,86 +169,78 @@ public class GerritPublicKeyCheckerTest {
@Test
public void defaultGpgCertificationMatchesEmail() throws Exception {
TestKey key = validKeyWithSecondUserId();
PublicKeyChecker checker = checkerFactory.create(user, store)
.disableTrust();
PublicKeyChecker checker = checkerFactory.create(user, store).disableTrust();
assertProblems(
checker.check(key.getPublicKey()), Status.BAD,
checker.check(key.getPublicKey()),
Status.BAD,
"Key must contain a valid certification for one of the following "
+ "identities:\n"
+ " gerrit:user\n"
+ " username:user");
+ "identities:\n"
+ " gerrit:user\n"
+ " username:user");
addExternalId("test", "test", "test5@example.com");
checker = checkerFactory.create(user, store)
.disableTrust();
checker = checkerFactory.create(user, store).disableTrust();
assertNoProblems(checker.check(key.getPublicKey()));
}
@Test
public void defaultGpgCertificationDoesNotMatchEmail() throws Exception {
addExternalId("test", "test", "nobody@example.com");
PublicKeyChecker checker = checkerFactory.create(user, store)
.disableTrust();
PublicKeyChecker checker = checkerFactory.create(user, store).disableTrust();
assertProblems(
checker.check(validKeyWithSecondUserId().getPublicKey()), Status.BAD,
checker.check(validKeyWithSecondUserId().getPublicKey()),
Status.BAD,
"Key must contain a valid certification for one of the following "
+ "identities:\n"
+ " gerrit:user\n"
+ " nobody@example.com\n"
+ " test:test\n"
+ " username:user");
+ "identities:\n"
+ " gerrit:user\n"
+ " nobody@example.com\n"
+ " test:test\n"
+ " username:user");
}
@Test
public void manualCertificationMatchesExternalId() throws Exception {
addExternalId("foo", "myId", null);
PublicKeyChecker checker = checkerFactory.create(user, store)
.disableTrust();
PublicKeyChecker checker = checkerFactory.create(user, store).disableTrust();
assertNoProblems(checker.check(validKeyWithSecondUserId().getPublicKey()));
}
@Test
public void manualCertificationDoesNotMatchExternalId() throws Exception {
addExternalId("foo", "otherId", null);
PublicKeyChecker checker = checkerFactory.create(user, store)
.disableTrust();
PublicKeyChecker checker = checkerFactory.create(user, store).disableTrust();
assertProblems(
checker.check(validKeyWithSecondUserId().getPublicKey()), Status.BAD,
checker.check(validKeyWithSecondUserId().getPublicKey()),
Status.BAD,
"Key must contain a valid certification for one of the following "
+ "identities:\n"
+ " foo:otherId\n"
+ " gerrit:user\n"
+ " username:user");
+ "identities:\n"
+ " foo:otherId\n"
+ " gerrit:user\n"
+ " username:user");
}
@Test
public void noExternalIds() throws Exception {
db.accountExternalIds().delete(
db.accountExternalIds().byAccount(user.getAccountId()));
db.accountExternalIds().delete(db.accountExternalIds().byAccount(user.getAccountId()));
reloadUser();
TestKey key = validKeyWithSecondUserId();
PublicKeyChecker checker = checkerFactory.create(user, store)
.disableTrust();
PublicKeyChecker checker = checkerFactory.create(user, store).disableTrust();
assertProblems(
checker.check(key.getPublicKey()), Status.BAD,
"No identities found for user; check"
+ " http://test/#/settings/web-identities");
checker.check(key.getPublicKey()),
Status.BAD,
"No identities found for user; check" + " http://test/#/settings/web-identities");
checker = checkerFactory.create()
.setStore(store)
.disableTrust();
checker = checkerFactory.create().setStore(store).disableTrust();
assertProblems(
checker.check(key.getPublicKey()), Status.BAD,
"Key is not associated with any users");
checker.check(key.getPublicKey()), Status.BAD, "Key is not associated with any users");
db.accountExternalIds().insert(Collections.singleton(
new AccountExternalId(
user.getAccountId(), toExtIdKey(key.getPublicKey()))));
db.accountExternalIds()
.insert(
Collections.singleton(
new AccountExternalId(user.getAccountId(), toExtIdKey(key.getPublicKey()))));
reloadUser();
assertProblems(
checker.check(key.getPublicKey()), Status.BAD,
"No identities found for user");
assertProblems(checker.check(key.getPublicKey()), Status.BAD, "No identities found for user");
}
@Test
@@ -281,14 +267,11 @@ public class GerritPublicKeyCheckerTest {
// Checker for B, checking B. Trust chain and IDs are correct, so the only
// problem is with the key itself.
PublicKeyChecker checkerB = checkerFactory.create(userB, store);
assertProblems(
checkerB.check(keyB.getPublicKey()), Status.BAD,
"Key is expired");
assertProblems(checkerB.check(keyB.getPublicKey()), Status.BAD, "Key is expired");
}
@Test
public void checkWithValidKeyButWrongExpectedUserInChecker()
throws Exception {
public void checkWithValidKeyButWrongExpectedUserInChecker() throws Exception {
// A---Bx
// \
// \---C---D
@@ -307,7 +290,8 @@ public class GerritPublicKeyCheckerTest {
// Checker for A, checking B.
PublicKeyChecker checkerA = checkerFactory.create(user, store);
assertProblems(
checkerA.check(keyB.getPublicKey()), Status.BAD,
checkerA.check(keyB.getPublicKey()),
Status.BAD,
"Key is expired",
"Key must contain a valid certification for one of the following"
+ " identities:\n"
@@ -319,7 +303,8 @@ public class GerritPublicKeyCheckerTest {
// Checker for B, checking A.
PublicKeyChecker checkerB = checkerFactory.create(userB, store);
assertProblems(
checkerB.check(keyA.getPublicKey()), Status.BAD,
checkerB.check(keyA.getPublicKey()),
Status.BAD,
"Key must contain a valid certification for one of the following"
+ " identities:\n"
+ " gerrit:userB\n"
@@ -338,9 +323,11 @@ public class GerritPublicKeyCheckerTest {
PublicKeyChecker checker = checkerFactory.create(user, store);
assertProblems(
checker.check(keyA.getPublicKey()), Status.OK,
checker.check(keyA.getPublicKey()),
Status.OK,
"No path to a trusted key",
"Certification by " + keyToString(keyB.getPublicKey())
"Certification by "
+ keyToString(keyB.getPublicKey())
+ " is valid, but key is not trusted",
"Key D24FE467 used for certification is not in store");
}
@@ -363,16 +350,14 @@ public class GerritPublicKeyCheckerTest {
// This checker can check any key, so the only problems come from issues
// with the keys themselves, not having invalid user IDs.
PublicKeyChecker checker = checkerFactory.create()
.setStore(store);
PublicKeyChecker checker = checkerFactory.create().setStore(store);
assertNoProblems(checker.check(keyA.getPublicKey()));
assertProblems(
checker.check(keyB.getPublicKey()), Status.BAD,
"Key is expired");
assertProblems(checker.check(keyB.getPublicKey()), Status.BAD, "Key is expired");
assertNoProblems(checker.check(keyC.getPublicKey()));
assertNoProblems(checker.check(keyD.getPublicKey()));
assertProblems(
checker.check(keyE.getPublicKey()), Status.BAD,
checker.check(keyE.getPublicKey()),
Status.BAD,
"Key is expired",
"No path to a trusted key");
}
@@ -389,16 +374,16 @@ public class GerritPublicKeyCheckerTest {
PGPPublicKeyRing keyRingB = keyB().getPublicKeyRing();
PGPPublicKey keyB = keyRingB.getPublicKey();
keyB = PGPPublicKey.removeCertification(
keyB, (String) keyB.getUserIDs().next());
keyB = PGPPublicKey.removeCertification(keyB, (String) keyB.getUserIDs().next());
keyRingB = PGPPublicKeyRing.insertPublicKey(keyRingB, keyB);
add(keyRingB, addUser("userB"));
PublicKeyChecker checkerA = checkerFactory.create(user, store);
assertProblems(checkerA.check(keyA.getPublicKey()), Status.OK,
assertProblems(
checkerA.check(keyA.getPublicKey()),
Status.OK,
"No path to a trusted key",
"Certification by " + keyToString(keyB)
+ " is valid, but key is not trusted",
"Certification by " + keyToString(keyB) + " is valid, but key is not trusted",
"Key D24FE467 used for certification is not in store");
}
@@ -408,13 +393,12 @@ public class GerritPublicKeyCheckerTest {
newExtIds.add(new AccountExternalId(id, toExtIdKey(kr.getPublicKey())));
@SuppressWarnings("unchecked")
String userId = (String) Iterators.getOnlyElement(
kr.getPublicKey().getUserIDs(), null);
String userId = (String) Iterators.getOnlyElement(kr.getPublicKey().getUserIDs(), null);
if (userId != null) {
String email = PushCertificateIdent.parse(userId).getEmailAddress();
assertThat(email).contains("@");
AccountExternalId mailto = new AccountExternalId(
id, new AccountExternalId.Key(SCHEME_MAILTO, email));
AccountExternalId mailto =
new AccountExternalId(id, new AccountExternalId.Key(SCHEME_MAILTO, email));
mailto.setEmailAddress(email);
newExtIds.add(mailto);
}
@@ -435,15 +419,13 @@ public class GerritPublicKeyCheckerTest {
return k;
}
private void assertProblems(CheckResult result, Status expectedStatus,
String first, String... rest) throws Exception {
private void assertProblems(
CheckResult result, Status expectedStatus, String first, String... rest) throws Exception {
List<String> expectedProblems = new ArrayList<>();
expectedProblems.add(first);
expectedProblems.addAll(Arrays.asList(rest));
assertThat(result.getStatus()).isEqualTo(expectedStatus);
assertThat(result.getProblems())
.containsExactlyElementsIn(expectedProblems)
.inOrder();
assertThat(result.getProblems()).containsExactlyElementsIn(expectedProblems).inOrder();
}
private void assertNoProblems(CheckResult result) {
@@ -451,10 +433,9 @@ public class GerritPublicKeyCheckerTest {
assertThat(result.getProblems()).isEmpty();
}
private void addExternalId(String scheme, String id, String email)
throws Exception {
AccountExternalId extId = new AccountExternalId(user.getAccountId(),
new AccountExternalId.Key(scheme, id));
private void addExternalId(String scheme, String id, String email) throws Exception {
AccountExternalId extId =
new AccountExternalId(user.getAccountId(), new AccountExternalId.Key(scheme, id));
if (email != null) {
extId.setEmailAddress(email);
}

View File

@@ -38,7 +38,15 @@ import static org.bouncycastle.openpgp.PGPSignature.DIRECT_KEY;
import static org.junit.Assert.assertEquals;
import com.google.gerrit.gpg.testutil.TestKey;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPSignature;
@@ -53,19 +61,8 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class PublicKeyCheckerTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Rule public ExpectedException thrown = ExpectedException.none();
private InMemoryRepository repo;
private PublicKeyStore store;
@@ -97,8 +94,7 @@ public class PublicKeyCheckerTest {
public void keyExpiringInFuture() throws Exception {
TestKey k = validKeyWithExpiration();
PublicKeyChecker checker = new PublicKeyChecker()
.setStore(store);
PublicKeyChecker checker = new PublicKeyChecker().setStore(store);
assertNoProblems(checker, k);
checker.setEffectiveTime(parseDate("2015-07-10 12:00:00 -0400"));
@@ -115,8 +111,7 @@ public class PublicKeyCheckerTest {
@Test
public void selfRevokedKeyIsRevoked() throws Exception {
assertProblems(selfRevokedKey(),
"Key is revoked (key material has been compromised)");
assertProblems(selfRevokedKey(), "Key is revoked (key material has been compromised)");
}
// Test keys specific to this test are at the bottom of this class. Each test
@@ -165,8 +160,7 @@ public class PublicKeyCheckerTest {
save();
PublicKeyChecker checker = newChecker(1, kd);
assertProblems(checker, ka,
"No path to a trusted key", notTrusted(kb), notTrusted(kc));
assertProblems(checker, ka, "No path to a trusted key", notTrusted(kb), notTrusted(kc));
}
@Test
@@ -177,10 +171,8 @@ public class PublicKeyCheckerTest {
save();
PublicKeyChecker checker = newChecker(10, keyA());
assertProblems(checker, kf,
"No path to a trusted key", notTrusted(kg));
assertProblems(checker, kg,
"No path to a trusted key", notTrusted(kf));
assertProblems(checker, kf, "No path to a trusted key", notTrusted(kg));
assertProblems(checker, kg, "No path to a trusted key", notTrusted(kf));
}
@Test
@@ -196,8 +188,7 @@ public class PublicKeyCheckerTest {
// J trusts I to a depth of 1, so I itself is valid, but I's certification
// of K is not valid.
assertNoProblems(checker, ki);
assertProblems(checker, kh,
"No path to a trusted key", notTrusted(ki));
assertProblems(checker, kh, "No path to a trusted key", notTrusted(ki));
}
@Test
@@ -206,9 +197,7 @@ public class PublicKeyCheckerTest {
add(validKeyWithoutExpiration());
save();
assertProblems(k,
"Key is revoked (key material has been compromised):"
+ " test6 compromised");
assertProblems(k, "Key is revoked (key material has been compromised):" + " test6 compromised");
PGPPublicKeyRing kr = removeRevokers(k.getPublicKeyRing());
store.add(kr);
@@ -219,20 +208,17 @@ public class PublicKeyCheckerTest {
}
@Test
public void revokedKeyDueToCompromiseRevokesKeyRetroactively()
throws Exception {
public void revokedKeyDueToCompromiseRevokesKeyRetroactively() throws Exception {
TestKey k = add(revokedCompromisedKey());
add(validKeyWithoutExpiration());
save();
String problem =
"Key is revoked (key material has been compromised): test6 compromised";
String problem = "Key is revoked (key material has been compromised): test6 compromised";
assertProblems(k, problem);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
PublicKeyChecker checker = new PublicKeyChecker()
.setStore(store)
.setEffectiveTime(df.parse("2010-01-01 12:00:00"));
PublicKeyChecker checker =
new PublicKeyChecker().setStore(store).setEffectiveTime(df.parse("2010-01-01 12:00:00"));
assertProblems(checker, k, problem);
}
@@ -241,9 +227,7 @@ public class PublicKeyCheckerTest {
TestKey k = add(revokedCompromisedKey());
save();
assertProblems(k,
"Key is revoked (key material has been compromised):"
+ " test6 compromised");
assertProblems(k, "Key is revoked (key material has been compromised):" + " test6 compromised");
}
@Test
@@ -252,29 +236,26 @@ public class PublicKeyCheckerTest {
add(validKeyWithoutExpiration());
save();
assertProblems(k,
"Key is revoked (retired and no longer valid): test7 not used");
assertProblems(k, "Key is revoked (retired and no longer valid): test7 not used");
}
@Test
public void revokedKeyDueToNoLongerBeingUsedDoesNotRevokeKeyRetroactively()
throws Exception {
public void revokedKeyDueToNoLongerBeingUsedDoesNotRevokeKeyRetroactively() throws Exception {
TestKey k = add(revokedNoLongerUsedKey());
add(validKeyWithoutExpiration());
save();
assertProblems(k,
"Key is revoked (retired and no longer valid): test7 not used");
assertProblems(k, "Key is revoked (retired and no longer valid): test7 not used");
PublicKeyChecker checker = new PublicKeyChecker()
.setStore(store)
.setEffectiveTime(parseDate("2010-01-01 12:00:00 -0400"));
PublicKeyChecker checker =
new PublicKeyChecker()
.setStore(store)
.setEffectiveTime(parseDate("2010-01-01 12:00:00 -0400"));
assertNoProblems(checker, k);
}
@Test
public void keyRevokedByExpiredKeyAfterExpirationIsNotRevoked()
throws Exception {
public void keyRevokedByExpiredKeyAfterExpirationIsNotRevoked() throws Exception {
TestKey k = add(keyRevokedByExpiredKeyAfterExpiration());
add(expiredKey());
save();
@@ -284,15 +265,13 @@ public class PublicKeyCheckerTest {
}
@Test
public void keyRevokedByExpiredKeyBeforeExpirationIsRevoked()
throws Exception {
public void keyRevokedByExpiredKeyBeforeExpirationIsRevoked() throws Exception {
TestKey k = add(keyRevokedByExpiredKeyBeforeExpiration());
add(expiredKey());
save();
PublicKeyChecker checker = new PublicKeyChecker().setStore(store);
assertProblems(checker, k,
"Key is revoked (retired and no longer valid): test9 not used");
assertProblems(checker, k, "Key is revoked (retired and no longer valid): test9 not used");
// Set time between key creation and revocation.
checker.setEffectiveTime(parseDate("2005-08-01 13:00:00 -0400"));
@@ -318,9 +297,7 @@ public class PublicKeyCheckerTest {
Fingerprint fp = new Fingerprint(k.getPublicKey().getFingerprint());
fps.put(fp.getId(), fp);
}
return new PublicKeyChecker()
.enableTrust(maxTrustDepth, fps)
.setStore(store);
return new PublicKeyChecker().enableTrust(maxTrustDepth, fps).setStore(store);
}
private TestKey add(TestKey k) {
@@ -351,16 +328,13 @@ public class PublicKeyCheckerTest {
}
}
private void assertProblems(PublicKeyChecker checker, TestKey k,
String first, String... rest) {
CheckResult result = checker.setStore(store)
.check(k.getPublicKey());
private void assertProblems(PublicKeyChecker checker, TestKey k, String first, String... rest) {
CheckResult result = checker.setStore(store).check(k.getPublicKey());
assertEquals(list(first, rest), result.getProblems());
}
private void assertNoProblems(PublicKeyChecker checker, TestKey k) {
CheckResult result = checker.setStore(store)
.check(k.getPublicKey());
CheckResult result = checker.setStore(store).check(k.getPublicKey());
assertEquals(Collections.emptyList(), result.getProblems());
}
@@ -373,21 +347,18 @@ public class PublicKeyCheckerTest {
}
private void assertProblems(PGPPublicKey k, String first, String... rest) {
CheckResult result = new PublicKeyChecker()
.setStore(store)
.check(k);
CheckResult result = new PublicKeyChecker().setStore(store).check(k);
assertEquals(list(first, rest), result.getProblems());
}
private void assertNoProblems(PGPPublicKey k) {
CheckResult result = new PublicKeyChecker()
.setStore(store)
.check(k);
CheckResult result = new PublicKeyChecker().setStore(store).check(k);
assertEquals(Collections.emptyList(), result.getProblems());
}
private static String notTrusted(TestKey k) {
return "Certification by " + keyToString(k.getPublicKey())
return "Certification by "
+ keyToString(k.getPublicKey())
+ " is valid, but key is not trusted";
}

View File

@@ -27,7 +27,12 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import com.google.gerrit.gpg.testutil.TestKey;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPPublicKeyRingCollection;
@@ -43,21 +48,13 @@ import org.eclipse.jgit.revwalk.RevWalk;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class PublicKeyStoreTest {
private TestRepository<?> tr;
private PublicKeyStore store;
@Before
public void setUp() throws Exception {
tr = new TestRepository<>(new InMemoryRepository(
new DfsRepositoryDescription("pubkeys")));
tr = new TestRepository<>(new InMemoryRepository(new DfsRepositoryDescription("pubkeys")));
store = new PublicKeyStore(tr.getRepository());
}
@@ -70,8 +67,9 @@ public class PublicKeyStoreTest {
@Test
public void testKeyToString() throws Exception {
PGPPublicKey key = validKeyWithoutExpiration().getPublicKey();
assertEquals("46328A8C Testuser One <test1@example.com>"
+ " (04AE A7ED 2F82 1133 E5B1 28D1 ED06 25DC 4632 8A8C)",
assertEquals(
"46328A8C Testuser One <test1@example.com>"
+ " (04AE A7ED 2F82 1133 E5B1 28D1 ED06 25DC 4632 8A8C)",
keyToString(key));
}
@@ -80,8 +78,7 @@ public class PublicKeyStoreTest {
PGPPublicKey key = validKeyWithoutExpiration().getPublicKey();
String objId = keyObjectId(key.getKeyID()).name();
assertEquals("ed0625dc46328a8c000000000000000000000000", objId);
assertEquals(keyIdToString(key.getKeyID()).toLowerCase(),
objId.substring(8, 16));
assertEquals(keyIdToString(key.getKeyID()).toLowerCase(), objId.substring(8, 16));
}
@Test
@@ -89,14 +86,12 @@ public class PublicKeyStoreTest {
TestKey key1 = validKeyWithoutExpiration();
tr.branch(REFS_GPG_KEYS)
.commit()
.add(keyObjectId(key1.getKeyId()).name(),
key1.getPublicKeyArmored())
.add(keyObjectId(key1.getKeyId()).name(), key1.getPublicKeyArmored())
.create();
TestKey key2 = validKeyWithExpiration();
tr.branch(REFS_GPG_KEYS)
.commit()
.add(keyObjectId(key2.getKeyId()).name(),
key2.getPublicKeyArmored())
.add(keyObjectId(key2.getKeyId()).name(), key2.getPublicKeyArmored())
.create();
assertKeys(key1.getKeyId(), key1);
@@ -109,10 +104,11 @@ public class PublicKeyStoreTest {
TestKey key2 = validKeyWithExpiration();
tr.branch(REFS_GPG_KEYS)
.commit()
.add(keyObjectId(key1.getKeyId()).name(),
.add(
keyObjectId(key1.getKeyId()).name(),
key1.getPublicKeyArmored()
// Mismatched for this key ID, but we can still read it out.
+ key2.getPublicKeyArmored())
// Mismatched for this key ID, but we can still read it out.
+ key2.getPublicKeyArmored())
.create();
assertKeys(key1.getKeyId(), key1, key2);
}
@@ -147,12 +143,13 @@ public class PublicKeyStoreTest {
try (ObjectReader reader = tr.getRepository().newObjectReader();
RevWalk rw = new RevWalk(reader)) {
NoteMap notes = NoteMap.read(
reader, tr.getRevWalk().parseCommit(
tr.getRepository().exactRef(REFS_GPG_KEYS).getObjectId()));
String contents = new String(
reader.open(notes.get(keyObjectId(key1.getKeyId()))).getBytes(),
UTF_8);
NoteMap notes =
NoteMap.read(
reader,
tr.getRevWalk()
.parseCommit(tr.getRepository().exactRef(REFS_GPG_KEYS).getObjectId()));
String contents =
new String(reader.open(notes.get(keyObjectId(key1.getKeyId()))).getBytes(), UTF_8);
String header = "-----BEGIN PGP PUBLIC KEY BLOCK-----";
int i1 = contents.indexOf(header);
assertTrue(i1 >= 0);
@@ -169,7 +166,8 @@ public class PublicKeyStoreTest {
store.add(keyRing);
assertEquals(RefUpdate.Result.NEW, store.save(newCommitBuilder()));
assertUserIds(store.get(key5.getKeyId()).iterator().next(),
assertUserIds(
store.get(key5.getKeyId()).iterator().next(),
"Testuser Five <test5@example.com>",
"foo:myId");
@@ -218,8 +216,7 @@ public class PublicKeyStoreTest {
assertKeys(key1.getKeyId());
}
private void assertKeys(long keyId, TestKey... expected)
throws Exception {
private void assertKeys(long keyId, TestKey... expected) throws Exception {
Set<String> expectedStrings = new TreeSet<>();
for (TestKey k : expected) {
expectedStrings.add(keyToString(k.getPublicKey()));
@@ -232,12 +229,11 @@ public class PublicKeyStoreTest {
assertEquals(expectedStrings, actualStrings);
}
private void assertUserIds(PGPPublicKeyRing keyRing, String... expected)
throws Exception {
private void assertUserIds(PGPPublicKeyRing keyRing, String... expected) throws Exception {
List<String> actual = new ArrayList<>();
@SuppressWarnings("unchecked")
Iterator<String> userIds = store.get(keyRing.getPublicKey().getKeyID())
.iterator().next().getPublicKey().getUserIDs();
Iterator<String> userIds =
store.get(keyRing.getPublicKey().getKeyID()).iterator().next().getPublicKey().getUserIDs();
while (userIds.hasNext()) {
actual.add(userIds.next());
}

View File

@@ -23,7 +23,16 @@ import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals;
import com.google.gerrit.gpg.testutil.TestKey;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.bouncycastle.bcpg.ArmoredOutputStream;
import org.bouncycastle.bcpg.BCPGOutputStream;
import org.bouncycastle.openpgp.PGPSignature;
@@ -44,17 +53,6 @@ import org.eclipse.jgit.transport.SignedPushConfig;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public class PushCertificateCheckerTest {
private InMemoryRepository repo;
private PublicKeyStore store;
@@ -99,23 +97,20 @@ public class PushCertificateCheckerTest {
@Test
public void validCert() throws Exception {
PushCertificate cert =
newSignedCert(validNonce(), validKeyWithoutExpiration());
PushCertificate cert = newSignedCert(validNonce(), validKeyWithoutExpiration());
assertNoProblems(cert);
}
@Test
public void invalidNonce() throws Exception {
PushCertificate cert =
newSignedCert("invalid-nonce", validKeyWithoutExpiration());
PushCertificate cert = newSignedCert("invalid-nonce", validKeyWithoutExpiration());
assertProblems(cert, "Invalid nonce");
}
@Test
public void invalidNonceNotChecked() throws Exception {
checker = newChecker(false);
PushCertificate cert =
newSignedCert("invalid-nonce", validKeyWithoutExpiration());
PushCertificate cert = newSignedCert("invalid-nonce", validKeyWithoutExpiration());
assertNoProblems(cert);
}
@@ -123,57 +118,58 @@ public class PushCertificateCheckerTest {
public void missingKey() throws Exception {
TestKey key2 = validKeyWithExpiration();
PushCertificate cert = newSignedCert(validNonce(), key2);
assertProblems(cert,
"No public keys found for key ID " + keyIdToString(key2.getKeyId()));
assertProblems(cert, "No public keys found for key ID " + keyIdToString(key2.getKeyId()));
}
@Test
public void invalidKey() throws Exception {
TestKey key3 = expiredKey();
PushCertificate cert = newSignedCert(validNonce(), key3);
assertProblems(cert,
"Invalid public key " + keyToString(key3.getPublicKey())
+ ":\n Key is expired");
assertProblems(
cert, "Invalid public key " + keyToString(key3.getPublicKey()) + ":\n Key is expired");
}
@Test
public void signatureByExpiredKeyBeforeExpiration() throws Exception {
TestKey key3 = expiredKey();
Date now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z")
.parse("2005-07-10 12:00:00 -0400");
Date now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z").parse("2005-07-10 12:00:00 -0400");
PushCertificate cert = newSignedCert(validNonce(), key3, now);
assertNoProblems(cert);
}
private String validNonce() {
return signedPushConfig.getNonceGenerator()
return signedPushConfig
.getNonceGenerator()
.createNonce(repo, System.currentTimeMillis() / 1000);
}
private PushCertificate newSignedCert(String nonce, TestKey signingKey)
throws Exception {
private PushCertificate newSignedCert(String nonce, TestKey signingKey) throws Exception {
return newSignedCert(nonce, signingKey, null);
}
private PushCertificate newSignedCert(String nonce, TestKey signingKey,
Date now) throws Exception {
PushCertificateIdent ident = new PushCertificateIdent(
signingKey.getFirstUserId(), System.currentTimeMillis(), -7 * 60);
String payload = "certificate version 0.1\n"
+ "pusher " + ident.getRaw() + "\n"
+ "pushee test://localhost/repo.git\n"
+ "nonce " + nonce + "\n"
+ "\n"
+ "0000000000000000000000000000000000000000"
+ " deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"
+ " refs/heads/master\n";
PGPSignatureGenerator gen = new PGPSignatureGenerator(
new BcPGPContentSignerBuilder(
signingKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1));
private PushCertificate newSignedCert(String nonce, TestKey signingKey, Date now)
throws Exception {
PushCertificateIdent ident =
new PushCertificateIdent(signingKey.getFirstUserId(), System.currentTimeMillis(), -7 * 60);
String payload =
"certificate version 0.1\n"
+ "pusher "
+ ident.getRaw()
+ "\n"
+ "pushee test://localhost/repo.git\n"
+ "nonce "
+ nonce
+ "\n"
+ "\n"
+ "0000000000000000000000000000000000000000"
+ " deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"
+ " refs/heads/master\n";
PGPSignatureGenerator gen =
new PGPSignatureGenerator(
new BcPGPContentSignerBuilder(signingKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1));
if (now != null) {
PGPSignatureSubpacketGenerator subGen =
new PGPSignatureSubpacketGenerator();
PGPSignatureSubpacketGenerator subGen = new PGPSignatureSubpacketGenerator();
subGen.setSignatureCreationTime(false, now);
gen.setHashedSubpackets(subGen.generate());
}
@@ -183,21 +179,17 @@ public class PushCertificateCheckerTest {
PGPSignature sig = gen.generate();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
try (BCPGOutputStream out = new BCPGOutputStream(
new ArmoredOutputStream(bout))) {
try (BCPGOutputStream out = new BCPGOutputStream(new ArmoredOutputStream(bout))) {
sig.encode(out);
}
String cert = payload + new String(bout.toByteArray(), UTF_8);
Reader reader =
new InputStreamReader(new ByteArrayInputStream(cert.getBytes(UTF_8)));
PushCertificateParser parser =
new PushCertificateParser(repo, signedPushConfig);
Reader reader = new InputStreamReader(new ByteArrayInputStream(cert.getBytes(UTF_8)));
PushCertificateParser parser = new PushCertificateParser(repo, signedPushConfig);
return parser.parse(reader);
}
private void assertProblems(PushCertificate cert, String first,
String... rest) throws Exception {
private void assertProblems(PushCertificate cert, String first, String... rest) throws Exception {
List<String> expected = new ArrayList<>();
expected.add(first);
expected.addAll(Arrays.asList(rest));

View File

@@ -16,6 +16,8 @@ package com.google.gerrit.gpg.testutil;
import static com.google.gerrit.gpg.PublicKeyStore.keyIdToString;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.bouncycastle.bcpg.ArmoredInputStream;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPrivateKey;
@@ -28,9 +30,6 @@ import org.bouncycastle.openpgp.operator.bc.BcPBESecretKeyDecryptorBuilder;
import org.bouncycastle.openpgp.operator.bc.BcPGPDigestCalculatorProvider;
import org.eclipse.jgit.lib.Constants;
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class TestKey {
private final String pubArmored;
private final String secArmored;
@@ -82,15 +81,14 @@ public class TestKey {
}
public PGPPrivateKey getPrivateKey() throws PGPException {
return getSecretKey().extractPrivateKey(
new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider())
// All test keys have no passphrase.
.build(new char[0]));
return getSecretKey()
.extractPrivateKey(
new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider())
// All test keys have no passphrase.
.build(new char[0]));
}
private static ArmoredInputStream newStream(String armored)
throws IOException {
return new ArmoredInputStream(
new ByteArrayInputStream(Constants.encode(armored)));
private static ArmoredInputStream newStream(String armored) throws IOException {
return new ArmoredInputStream(new ByteArrayInputStream(Constants.encode(armored)));
}
}