001/* 002 * The contents of this file are subject to the terms of the Common Development and 003 * Distribution License (the License). You may not use this file except in compliance with the 004 * License. 005 * 006 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the 007 * specific language governing permission and limitations under the License. 008 * 009 * When distributing Covered Software, include this CDDL Header Notice in each file and include 010 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL 011 * Header, with the fields enclosed by brackets [] replaced by your own identifying 012 * information: "Portions copyright [year] [name of copyright owner]". 013 * 014 * Copyright 2014 ForgeRock AS. 015 */ 016 017package org.forgerock.openig.security; 018 019import static java.lang.String.*; 020 021import java.security.KeyStore; 022 023import javax.net.ssl.TrustManager; 024import javax.net.ssl.TrustManagerFactory; 025 026import org.forgerock.json.JsonValue; 027import org.forgerock.openig.heap.GenericHeaplet; 028import org.forgerock.openig.heap.HeapException; 029 030/** 031 * Represents an SSL Java {@link TrustManager}. 032 * <pre> 033 * {@code 034 * { 035 * "name": "MyTrustManager", 036 * "type": "TrustManager", 037 * "config": { 038 * "keystore": "MyKeyStore", 039 * "alg": "SunX509" 040 * } 041 * } 042 * } 043 * </pre> 044 * <ul> 045 * <li>{@literal keystore}: Reference a KeyStore heap object (string, required).</li> 046 * <li>{@literal alg}: Trust manager algorithm (defaults to platform's default type) (string, optional).</li> 047 * </ul> 048 * @since 3.1 049 */ 050public class TrustManagerHeaplet extends GenericHeaplet { 051 052 @Override 053 public Object create() throws HeapException { 054 JsonValue storeRef = config.get("keystore").required(); 055 KeyStore keyStore = heap.resolve(storeRef, KeyStore.class); 056 String algorithm = config.get("alg").defaultTo(TrustManagerFactory.getDefaultAlgorithm()).asString(); 057 058 TrustManagerFactory factory; 059 try { 060 factory = TrustManagerFactory.getInstance(algorithm); 061 factory.init(keyStore); 062 } catch (Exception e) { 063 throw new HeapException(loadingError(algorithm, storeRef), e); 064 } 065 066 // Retrieve manager 067 TrustManager[] managers = factory.getTrustManagers(); 068 if (managers.length == 1) { 069 return managers[0]; 070 } else if (managers.length > 1) { 071 logger.warning("Only the first TrustManager will be selected"); 072 return managers[0]; 073 } 074 throw new HeapException(loadingError(algorithm, storeRef)); 075 076 } 077 078 private String loadingError(final String algorithm, final JsonValue reference) { 079 return format("Cannot build TrustManager[alg:%s] from KeyStore %s", 080 algorithm, 081 reference.asString()); 082 } 083}