Search in sources :

Example 16 with SafeRuntimeException

use of com.palantir.logsafe.exceptions.SafeRuntimeException in project tritium by palantir.

the class InstrumentationTest method testReturnNull_failure_compositeHandler.

@Test
@SuppressWarnings("unchecked")
void testReturnNull_failure_compositeHandler() {
    InvocationEventHandler<InvocationContext> handler = Mockito.mock(InvocationEventHandler.class);
    when(handler.isEnabled()).thenReturn(true);
    when(handler.preInvocation(any(), any(), any())).thenReturn(null);
    Runnable wrapped = Instrumentation.builder(Runnable.class, () -> {
        throw new SafeRuntimeException("expected");
    }).withHandler(handler).withTaggedMetrics(new DefaultTaggedMetricRegistry()).build();
    assertThatCode(wrapped::run).isExactlyInstanceOf(SafeRuntimeException.class).hasMessage("expected");
    verify(handler).isEnabled();
    verify(handler).preInvocation(any(), any(), any());
    verify(handler).onFailure(isNull(), any());
    verifyNoMoreInteractions(handler);
}
Also used : SafeRuntimeException(com.palantir.logsafe.exceptions.SafeRuntimeException) DefaultTaggedMetricRegistry(com.palantir.tritium.metrics.registry.DefaultTaggedMetricRegistry) InvocationContext(com.palantir.tritium.event.InvocationContext) DefaultInvocationContext(com.palantir.tritium.event.DefaultInvocationContext) Test(org.junit.jupiter.api.Test)

Example 17 with SafeRuntimeException

use of com.palantir.logsafe.exceptions.SafeRuntimeException in project tritium by palantir.

the class InstrumentationTest method testThrowingHandler_failure_composite.

@Test
@SuppressWarnings("unchecked")
void testThrowingHandler_failure_composite() {
    InvocationEventHandler<InvocationContext> handler = Mockito.mock(InvocationEventHandler.class);
    when(handler.isEnabled()).thenReturn(true);
    when(handler.preInvocation(any(), any(), any())).thenThrow(new RuntimeException());
    Runnable wrapped = Instrumentation.builder(Runnable.class, () -> {
        throw new SafeRuntimeException("expected");
    }).withHandler(handler).withTaggedMetrics(new DefaultTaggedMetricRegistry()).build();
    assertThatCode(wrapped::run).isExactlyInstanceOf(SafeRuntimeException.class).hasMessage("expected");
    verify(handler).isEnabled();
    verify(handler).preInvocation(any(), any(), any());
    verify(handler).onFailure(isNull(), any());
}
Also used : SafeRuntimeException(com.palantir.logsafe.exceptions.SafeRuntimeException) SafeRuntimeException(com.palantir.logsafe.exceptions.SafeRuntimeException) DefaultTaggedMetricRegistry(com.palantir.tritium.metrics.registry.DefaultTaggedMetricRegistry) InvocationContext(com.palantir.tritium.event.InvocationContext) DefaultInvocationContext(com.palantir.tritium.event.DefaultInvocationContext) Test(org.junit.jupiter.api.Test)

Example 18 with SafeRuntimeException

use of com.palantir.logsafe.exceptions.SafeRuntimeException in project metric-schema by palantir.

the class JavaGeneratorTest method assertThatFilesAreTheSame.

private void assertThatFilesAreTheSame(Path outputFile, String referenceFilesFolder) {
    Path relativized = outputDir.relativize(outputFile);
    Path expectedFile = Paths.get(referenceFilesFolder, relativized.toString());
    if (Boolean.parseBoolean(System.getProperty("recreate", "false"))) {
        try {
            Files.createDirectories(expectedFile.getParent());
            Files.deleteIfExists(expectedFile);
            Files.copy(outputFile, expectedFile);
        } catch (IOException e) {
            throw new SafeRuntimeException("Failed to recreate test data", e);
        }
    }
    assertThat(outputFile).hasSameTextualContentAs(expectedFile);
}
Also used : Path(java.nio.file.Path) SafeRuntimeException(com.palantir.logsafe.exceptions.SafeRuntimeException) IOException(java.io.IOException)

Example 19 with SafeRuntimeException

use of com.palantir.logsafe.exceptions.SafeRuntimeException in project conjure-java-runtime by palantir.

the class KeyStores method createKeyStoreFromPemDirectories.

/**
 * Returns a {@link KeyStore} created by loading the PEM files for keys and certificates from the directories at the
 * specified paths. Every visible file in the keyDirPath directory that ends with keyExtension will be read in as a
 * private key with a certificate chain that comes from a file in the certDirPath directory that consists of the
 * base name of the file concatenated with certExtension. The key files must contain an RSA private key in PKCS#1
 * format and the certificate files must contain X.509 certificates. Throws an exception if either path that is
 * provided is not a directory or if there is any key which does not have a corresponding certificate.
 *
 * @param keyDirPath path to the directory that contains the key files (PKCS#1 in PEM format)
 * @param keyExtension file extension for the files in the keyDirPath directory that should be considered keys. Is
 *     used to perform a suffix match. Case-sensitive and should include a period character if it is desired (for
 *     example, ".key", ".pem").
 * @param certDirPath path to the directory that contains the certificate files for the keys
 * @param certExtension file extension for the files in certDirPath directory that should be considered certificate
 *     files. For every key file, the file "fileName - keyExtension + certExtension" must exist in the certDirPath.
 *     Case-sensitive and should include a period character if it is desired (for example, ".cer", ".pem").
 * @return a new KeyStore of type {@link KeyStore#getDefaultType()} that contains the key entries specified by the
 *     arguments. The base name of the file used to create a key entry is used as the alias for the entry. The
 *     provided password is used to secure the key store and all of the key entries.
 */
static KeyStore createKeyStoreFromPemDirectories(Path keyDirPath, String keyExtension, Path certDirPath, String certExtension) {
    if (!keyDirPath.toFile().isDirectory()) {
        throw new IllegalStateException(String.format("keyDirPath is not a directory: \"%s\"", keyDirPath));
    } else if (!certDirPath.toFile().isDirectory()) {
        throw new IllegalStateException(String.format("certDirPath is not a directory: \"%s\"", certDirPath));
    }
    try {
        KeyStore keyStore = KeyStore.getInstance("pkcs12");
        keyStore.load(null, null);
        File[] keyFiles = getFilesForPath(keyDirPath);
        for (File currKeyFile : keyFiles) {
            // find key files based on extension
            String currKeyFileName = currKeyFile.getName();
            if (currKeyFileName.endsWith(keyExtension)) {
                // derive cert file based on key file
                String baseName = currKeyFileName.substring(0, currKeyFileName.length() - keyExtension.length());
                Path currCertPath = certDirPath.resolve(baseName + certExtension);
                KeyStore.PrivateKeyEntry privateKeyEntry = readKeyEntryFromPems(currKeyFile.toPath(), currCertPath);
                keyStore.setKeyEntry(baseName, privateKeyEntry.getPrivateKey(), null, privateKeyEntry.getCertificateChain());
            }
        }
        return keyStore;
    } catch (GeneralSecurityException | IOException e) {
        throw new SafeRuntimeException("Failed to create key store from PEM directories", e);
    }
}
Also used : Path(java.nio.file.Path) SafeRuntimeException(com.palantir.logsafe.exceptions.SafeRuntimeException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) KeyStore(java.security.KeyStore) File(java.io.File)

Example 20 with SafeRuntimeException

use of com.palantir.logsafe.exceptions.SafeRuntimeException in project conjure-java-runtime by palantir.

the class SslSocketFactories method createTrustManagerFactory.

private static TrustManagerFactory createTrustManagerFactory(Path trustStorePath, SslConfiguration.StoreType trustStoreType) {
    KeyStore keyStore;
    switch(trustStoreType) {
        case JKS:
        case PKCS12:
            keyStore = KeyStores.loadKeyStore(trustStoreType.name(), trustStorePath, Optional.empty());
            break;
        case PEM:
            keyStore = KeyStores.createTrustStoreFromCertificates(trustStorePath);
            break;
        case PUPPET:
            Path puppetCertsDir = trustStorePath.resolve("certs");
            if (!puppetCertsDir.toFile().isDirectory()) {
                throw new IllegalStateException(String.format("Puppet certs directory did not exist at path \"%s\"", puppetCertsDir));
            }
            keyStore = KeyStores.createTrustStoreFromCertificates(puppetCertsDir);
            break;
        default:
            throw new IllegalStateException("Unrecognized trust store type: " + trustStoreType);
    }
    // Add globally trusted root CAs
    DefaultCas.getCertificates().forEach((certAlias, cert) -> {
        try {
            keyStore.setCertificateEntry(certAlias, cert);
        } catch (KeyStoreException e) {
            throw new SafeRuntimeException("Unable to add certificate to store", e, SafeArg.of("certificateAlias", certAlias));
        }
    });
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        return trustManagerFactory;
    } catch (GeneralSecurityException e) {
        throw Throwables.propagate(e);
    }
}
Also used : Path(java.nio.file.Path) SafeRuntimeException(com.palantir.logsafe.exceptions.SafeRuntimeException) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) GeneralSecurityException(java.security.GeneralSecurityException) KeyStoreException(java.security.KeyStoreException) KeyStore(java.security.KeyStore)

Aggregations

SafeRuntimeException (com.palantir.logsafe.exceptions.SafeRuntimeException)43 IOException (java.io.IOException)13 Test (org.junit.jupiter.api.Test)7 Path (java.nio.file.Path)6 Response (com.palantir.dialogue.Response)5 ImmutableMap (com.google.common.collect.ImmutableMap)3 TestResponse (com.palantir.dialogue.TestResponse)3 DefaultInvocationContext (com.palantir.tritium.event.DefaultInvocationContext)3 InvocationContext (com.palantir.tritium.event.InvocationContext)3 File (java.io.File)3 InputStream (java.io.InputStream)3 ArrayList (java.util.ArrayList)3 Test (org.junit.Test)3 ImmutableList (com.google.common.collect.ImmutableList)2 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)2 Value (com.palantir.atlasdb.keyvalue.api.Value)2 DisableNamespacesResponse (com.palantir.atlasdb.timelock.api.DisableNamespacesResponse)2 SuccessfulDisableNamespacesResponse (com.palantir.atlasdb.timelock.api.SuccessfulDisableNamespacesResponse)2 UnsuccessfulDisableNamespacesResponse (com.palantir.atlasdb.timelock.api.UnsuccessfulDisableNamespacesResponse)2 Channel (com.palantir.dialogue.Channel)2