<commit_before>/**
 * Copyright (C) 2015 The Gravitee team (http://gravitee.io)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.gravitee.am.gateway.handler.certificate.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.gravitee.am.certificate.api.CertificateMetadata;
import io.gravitee.am.certificate.api.DefaultKey;
import io.gravitee.am.gateway.core.event.CertificateEvent;
import io.gravitee.am.gateway.handler.certificate.CertificateManager;
import io.gravitee.am.gateway.handler.certificate.CertificateProvider;
import io.gravitee.am.gateway.handler.jwt.impl.JJwtBuilder;
import io.gravitee.am.gateway.handler.jwt.impl.JJwtParser;
import io.gravitee.am.model.Certificate;
import io.gravitee.am.model.Domain;
import io.gravitee.am.model.common.event.Payload;
import io.gravitee.am.model.jose.JWK;
import io.gravitee.am.plugins.certificate.core.CertificatePluginManager;
import io.gravitee.am.repository.management.api.CertificateRepository;
import io.gravitee.common.event.Event;
import io.gravitee.common.event.EventListener;
import io.gravitee.common.event.EventManager;
import io.gravitee.common.service.AbstractService;
import io.jsonwebtoken.JwsHeader;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.JacksonDeserializer;
import io.jsonwebtoken.io.JacksonSerializer;
import io.jsonwebtoken.security.Keys;
import io.reactivex.Flowable;
import io.reactivex.Maybe;
import io.reactivex.Observable;
import io.reactivex.Single;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.security.Key;
import java.security.KeyPair;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;

/**
 * @author <NAME> (<EMAIL>.<EMAIL> at graviteesource.com)
 * @author GraviteeSource Team
 */
public class CertificateManagerImpl extends AbstractService implements CertificateManager, InitializingBean, EventListener<CertificateEvent, Payload> {

    private static final Logger logger = LoggerFactory.getLogger(CertificateManagerImpl.class);
    private static final String defaultDigestAlgorithm = "SHA-256";

    @Value("${jwt.secret:s3cR3t4grAv1t3310AMS1g1ingDftK3y}")
    private String signingKeySecret;

    @Value("${jwt.kid:default-gravitee-AM-key}")
    private String signingKeyId;

    @Autowired
    private Domain domain;

    @Autowired
    private CertificateRepository certificateRepository;

    @Autowired
    private CertificatePluginManager certificatePluginManager;

    @Autowired
    private EventManager eventManager;

    @Autowired
    private ObjectMapper objectMapper;

    private ConcurrentMap<String, Map<String, CertificateProvider>> domainsCertificateProviders = new ConcurrentHashMap<>();

    private CertificateProvider defaultCertificateProvider;

    @Override
    public Maybe<CertificateProvider> get(String id) {
        return id == null ? Maybe.empty() : findByDomainAndId(domain.getId(), id);
    }

    @Override
    public Maybe<CertificateProvider> findByDomainAndId(String domain, String id) {
        return id == null ? Maybe.empty() : Observable.fromIterable(domainsCertificateProviders.get(domain).entrySet())
                .filter(certificateProviderEntry -> certificateProviderEntry.getKey().equals(id))
                .firstElement()
                .map(Map.Entry::getValue);
    }

    @Override
    public Collection<CertificateProvider> providers() {
        return domainsCertificateProviders
                .entrySet()
                .stream()
                .flatMap(p -> p.getValue().entrySet().stream().map(Map.Entry::getValue))
                .collect(Collectors.toList());
    }

    @Override
    public CertificateProvider defaultCertificateProvider() {
        return defaultCertificateProvider;
    }

    @Override
    public void afterPropertiesSet() {
        logger.info("Initializing default certificate provider for domain {}", domain.getName());
        initDefaultCertificateProvider();

        logger.info("Initializing certificates for domain {}", domain.getName());
        certificateRepository.findAll()
                .subscribe(
                        certificates -> {
                            certificates.forEach(certificate -> {
                                if (certificate.getDomain().equals(domain.getId())) {
                                    logger.info("Initializing certificate: {} [{}]", certificate.getName(), certificate.getType());
                                }
                                updateCertificateProvider(certificate);
                            });
                            logger.info("Certificates loaded for domain {}", domain.getName());
                        },
                        error -> logger.error("Unable to initialize certificates for domain {}", domain.getName(), error));
    }

    @Override
    protected void doStart() throws Exception {
        super.doStart();<commit_msg>fix(oidc): JWKS endpoint should not display all domains keys<commit_after>/**
 * Copyright (C) 2015 The Gravitee team (http://gravitee.io)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.gravitee.am.gateway.handler.certificate.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.gravitee.am.certificate.api.CertificateMetadata;
import io.gravitee.am.certificate.api.DefaultKey;
import io.gravitee.am.gateway.core.event.CertificateEvent;
import io.gravitee.am.gateway.handler.certificate.CertificateManager;
import io.gravitee.am.gateway.handler.certificate.CertificateProvider;
import io.gravitee.am.gateway.handler.jwt.impl.JJwtBuilder;
import io.gravitee.am.gateway.handler.jwt.impl.JJwtParser;
import io.gravitee.am.model.Certificate;
import io.gravitee.am.model.Domain;
import io.gravitee.am.model.common.event.Payload;
import io.gravitee.am.model.jose.JWK;
import io.gravitee.am.plugins.certificate.core.CertificatePluginManager;
import io.gravitee.am.repository.management.api.CertificateRepository;
import io.gravitee.common.event.Event;
import io.gravitee.common.event.EventListener;
import io.gravitee.common.event.EventManager;
import io.gravitee.common.service.AbstractService;
import io.jsonwebtoken.JwsHeader;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.JacksonDeserializer;
import io.jsonwebtoken.io.JacksonSerializer;
import io.jsonwebtoken.security.Keys;
import io.reactivex.Flowable;
import io.reactivex.Maybe;
import io.reactivex.Observable;
import io.reactivex.Single;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.security.Key;
import java.security.KeyPair;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;

/**
 * @author <NAME> (titouan.compiegne at graviteesource.com)
 * @author GraviteeSource Team
 */
public class CertificateManagerImpl extends AbstractService implements CertificateManager, InitializingBean, EventListener<CertificateEvent, Payload> {

    private static final Logger logger = LoggerFactory.getLogger(CertificateManagerImpl.class);
    private static final String defaultDigestAlgorithm = "SHA-256";

    @Value("${jwt.secret:s3cR3t4grAv1t3310AMS1g1ingDftK3y}")
    private String signingKeySecret;

    @Value("${jwt.kid:default-gravitee-AM-key}")
    private String signingKeyId;

    @Autowired
    private Domain domain;

    @Autowired
    private CertificateRepository certificateRepository;

    @Autowired
    private CertificatePluginManager certificatePluginManager;

    @Autowired
    private EventManager eventManager;

    @Autowired
    private ObjectMapper objectMapper;

    private ConcurrentMap<String, Map<String, CertificateProvider>> domainsCertificateProviders = new ConcurrentHashMap<>();

    private CertificateProvider defaultCertificateProvider;

    @Override
    public Maybe<CertificateProvider> get(String id) {
        return id == null ? Maybe.empty() : findByDomainAndId(domain.getId(), id);
    }

    @Override
    public Maybe<CertificateProvider> findByDomainAndId(String domain, String id) {
        return id == null ? Maybe.empty() : Observable.fromIterable(domainsCertificateProviders.get(domain).entrySet())
                .filter(certificateProviderEntry -> certificateProviderEntry.getKey().equals(id))
                .firstElement()
                .map(Map.Entry::getValue);
    }

    @Override
    public Collection<CertificateProvider> providers() {
        if (!domainsCertificateProviders.containsKey(domain.getId())) {
            return Collections.emptyList();
        }

        return domainsCertificateProviders
                .get(domain.getId())
                .entrySet()
                .stream()
                .map(p -> p.getValue())
                .collect(Collectors.toList());
    }

    @Override
    public CertificateProvider defaultCertificateProvider() {
        return defaultCertificateProvider;
    }

    @Override
    public void afterPropertiesSet() {
        logger.info("Initializing default certificate provider for domain {}", domain.getName());
        initDefaultCertificateProvider();

        logger.info("Initializing certificates for domain {}", domain.getName());
        certificateRepository.findAll()
                .subscribe(
                        certificates -> {
                            certificates.forEach(certificate -> {
                                if (certificate.getDomain().equals(domain.getId())) {
                                    logger.info("Initializing certificate: {} [{}]", certificate.getName(), certificate.getType());
                                }
                                updateCertificateProvider(certificate);
                            });
                            logger.info("Certificates loaded for domain {}", domain.getName());
                        },
                        error -> logger.error("Unable to initialize certificates for domain {}", domain.getName(), error));
    }

    @Override
    protected void doStart() throws Exception {
        super.doStart();
{'fraction_non_alphanumeric': 0.0988013698630137, 'fraction_numerical': 0.00410958904109589, 'mean_word_length': 3.4145880574452003, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 31, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6726917', 'n_tokens_mistral': 3130, 'n_tokens_neox': 3039, 'n_words': 674}