implementation and unit tests

This commit is contained in:
Konstantin Schaper
2020-08-05 13:02:02 +02:00
parent 08a025ba81
commit 7072761ba1
18 changed files with 599 additions and 65 deletions

View File

@@ -26,27 +26,55 @@ package sonia.scm.security.gpg;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPKeyRingGenerator;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import sonia.scm.repository.Person;
import sonia.scm.security.PrivateKey;
import sonia.scm.security.PublicKey;
import sonia.scm.util.MockUtil;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.time.Instant;
import java.util.Collections;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class DefaultGPGTest {
private static void registerBouncyCastleProviderIfNecessary() {
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
Security.addProvider(new BouncyCastleProvider());
}
}
@Mock
private PublicKeyStore store;
private PublicKeyStore publicKeyStore;
@Mock
private PrivateKeyStore privateKeyStore;
@InjectMocks
private DefaultGPG gpg;
@@ -65,7 +93,7 @@ class DefaultGPGTest {
Person trillian = Person.toPerson("Trillian <tricia.mcmillan@hitchhiker.org>");
RawGpgKey key1 = new RawGpgKey("42", "key_42", "trillian", raw, ImmutableSet.of(trillian), Instant.now());
when(store.findById("42")).thenReturn(Optional.of(key1));
when(publicKeyStore.findById("42")).thenReturn(Optional.of(key1));
Optional<PublicKey> publicKey = gpg.findPublicKey("42");
@@ -83,7 +111,7 @@ class DefaultGPGTest {
RawGpgKey key1 = new RawGpgKey("1", "1", "trillian", raw, Collections.emptySet(), Instant.now());
RawGpgKey key2 = new RawGpgKey("2", "2", "trillian", raw2, Collections.emptySet(), Instant.now());
when(store.findByUsername("trillian")).thenReturn(ImmutableList.of(key1, key2));
when(publicKeyStore.findByUsername("trillian")).thenReturn(ImmutableList.of(key1, key2));
Iterable<PublicKey> keys = gpg.findPublicKeysByUsername("trillian");
@@ -92,4 +120,94 @@ class DefaultGPGTest {
assertThat(key.getOwner()).isPresent();
assertThat(key.getOwner().get()).contains("trillian");
}
@Test
void shouldGenerateKeyPair() throws NoSuchProviderException, NoSuchAlgorithmException, PGPException {
registerBouncyCastleProviderIfNecessary();
final PGPKeyRingGenerator keyRingGenerator = gpg.generateKeyPair();
assertThat(keyRingGenerator.generatePublicKeyRing().getPublicKey()).isNotNull();
assertThat(keyRingGenerator.generateSecretKeyRing().getSecretKey()).isNotNull();
}
@Test
void shouldExportGeneratedKeyPair() throws NoSuchProviderException, NoSuchAlgorithmException, PGPException, IOException {
registerBouncyCastleProviderIfNecessary();
final PGPKeyRingGenerator keyRingGenerator = gpg.generateKeyPair();
final String exportedPublicKey = gpg.exportKeyRing(keyRingGenerator.generatePublicKeyRing());
assertThat(exportedPublicKey).isNotBlank();
assertThat(exportedPublicKey).startsWith("-----BEGIN PGP PUBLIC KEY BLOCK-----");
assertThat(exportedPublicKey).contains("-----END PGP PUBLIC KEY BLOCK-----");
final String exportedPrivateKey = gpg.exportKeyRing(keyRingGenerator.generateSecretKeyRing());
assertThat(exportedPrivateKey).isNotBlank();
assertThat(exportedPrivateKey).startsWith("-----BEGIN PGP PRIVATE KEY BLOCK-----");
assertThat(exportedPrivateKey).contains("-----END PGP PRIVATE KEY BLOCK-----");
}
@Test
void shouldImportKeyPair() throws IOException, PGPException {
String raw = GPGTestHelper.readResourceAsString("private-key.asc");
final PGPPrivateKey privateKey = DefaultGPG.importPrivateKey(raw);
assertThat(privateKey).isNotNull();
}
@Test
void shouldImportExportedGeneratedPrivateKey() throws NoSuchProviderException, NoSuchAlgorithmException, PGPException, IOException {
registerBouncyCastleProviderIfNecessary();
final PGPKeyRingGenerator keyRingGenerator = gpg.generateKeyPair();
final String exportedPrivateKey = gpg.exportKeyRing(keyRingGenerator.generateSecretKeyRing());
final PGPPrivateKey privateKey = DefaultGPG.importPrivateKey(exportedPrivateKey);
assertThat(privateKey).isNotNull();
}
@Test
void shouldCreateSignature() throws IOException {
registerBouncyCastleProviderIfNecessary();
String raw = GPGTestHelper.readResourceAsString("private-key.asc");
final DefaultGPG.DefaultPrivateKey privateKey = new DefaultGPG.DefaultPrivateKey(raw);
assertThat(privateKey.getId()).contains(DefaultGPG.PRIVATE_KEY_ID);
final byte[] signature = privateKey.sign("This is a test commit".getBytes());
final String signatureString = new String(signature);
assertThat(signature).isNotEmpty();
assertThat(signatureString).startsWith("-----BEGIN PGP SIGNATURE-----");
assertThat(signatureString).contains("-----END PGP SIGNATURE-----");
}
@Test
void shouldReturnGeneratedPrivateKeyIfNoneStored() {
registerBouncyCastleProviderIfNecessary();
SecurityUtils.setSecurityManager(new DefaultSecurityManager());
Subject subjectUnderTest = MockUtil.createUserSubject(SecurityUtils.getSecurityManager());
ThreadContext.bind(subjectUnderTest);
final PrivateKey privateKey = gpg.getPrivateKey();
assertThat(privateKey).isNotNull();
verify(privateKeyStore, atLeastOnce()).setForUserId(eq(subjectUnderTest.getPrincipal().toString()), anyString());
verify(publicKeyStore, atLeastOnce()).add(eq("Default SCM-Manager Signing Key"), eq(subjectUnderTest.getPrincipal().toString()), anyString(), eq(true));
}
@Test
void shouldReturnStoredPrivateKey() throws IOException {
registerBouncyCastleProviderIfNecessary();
SecurityUtils.setSecurityManager(new DefaultSecurityManager());
Subject subjectUnderTest = MockUtil.createUserSubject(SecurityUtils.getSecurityManager());
ThreadContext.bind(subjectUnderTest);
String raw = GPGTestHelper.readResourceAsString("private-key.asc");
when(privateKeyStore.getForUserId(subjectUnderTest.getPrincipal().toString())).thenReturn(Optional.of(raw));
final PrivateKey privateKey = gpg.getPrivateKey();
assertThat(privateKey).isNotNull();
verify(privateKeyStore, never()).setForUserId(eq(subjectUnderTest.getPrincipal().toString()), anyString());
verify(publicKeyStore, never()).add(eq("Default SCM-Manager Signing Key"), eq(subjectUnderTest.getPrincipal().toString()), anyString(), eq(true));
}
}

View File

@@ -0,0 +1,67 @@
/*
* MIT License
*
* Copyright (c) 2020-present Cloudogu GmbH and Contributors
*
* 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 sonia.scm.security.gpg;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import sonia.scm.store.DataStoreFactory;
import sonia.scm.store.InMemoryDataStoreFactory;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;
@ExtendWith(MockitoExtension.class)
class PrivateKeyStoreTest {
private DataStoreFactory dataStoreFactory;
private PrivateKeyStore keyStore;
@BeforeEach
void setup() {
dataStoreFactory = new InMemoryDataStoreFactory();
keyStore = new PrivateKeyStore(dataStoreFactory);
}
@Test
void returnEmptyIfNotYetSet() {
final Optional<String> rawKey = keyStore.getForUserId("testId");
assertThat(rawKey).isEmpty();
}
@Test
void setForUserId() {
keyStore.setForUserId("testId", "Test Key");
final Optional<String> rawKey = keyStore.getForUserId("testId");
assertThat(rawKey).isNotEmpty();
assertThat(rawKey.get()).isEqualTo("Test Key");
}
}