Search in sources :

Example 1 with GatewayAuthResponse

use of com.jd.blockchain.setting.GatewayAuthResponse in project jdchain-core by blockchain-jd-com.

the class ManagementController method authenticateGateway.

/**
 * 接入认证;
 *
 * @param authRequest
 * @return
 */
@RequestMapping(path = URL_AUTH_GATEWAY, method = RequestMethod.POST, consumes = BinaryMessageConverter.CONTENT_TYPE_VALUE)
@Override
public GatewayAuthResponse authenticateGateway(@RequestBody GatewayAuthRequest authRequest) {
    if (ledgerPeers.size() == 0 || authRequest == null) {
        return null;
    }
    HashDigest[] authLedgers = authRequest.getLedgers();
    ClientCredential[] clientCredentialOfRequests = authRequest.getCredentials();
    if (authLedgers == null || authLedgers.length == 0 || clientCredentialOfRequests == null || clientCredentialOfRequests.length == 0) {
        return null;
    }
    GatewayAuthResponse gatewayAuthResponse = new GatewayAuthResponse();
    List<LedgerIncomingSettings> ledgerIncomingList = new ArrayList<LedgerIncomingSettings>();
    int i = -1;
    for (HashDigest ledgerHash : authLedgers) {
        i++;
        NodeServer peer = ledgerPeers.get(ledgerHash);
        if (peer == null) {
            continue;
        }
        String peerProviderName = peer.getProviderName();
        ConsensusProvider provider = ConsensusProviders.getProvider(peer.getProviderName());
        ClientIncomingSettings clientIncomingSettings = null;
        ClientCredential clientRedential = clientCredentialOfRequests[i];
        if (!peerProviderName.equalsIgnoreCase(clientRedential.getProviderName())) {
            // 忽略掉不匹配的“共识客户端提供者程序”认证信息;
            continue;
        }
        // 用户账户校验,必须为非移除状态的共识节点
        LedgerRepository ledgerRepo = (LedgerRepository) ledgerQuerys.get(ledgerHash);
        if (null == ledgerRepo) {
            continue;
        }
        boolean isParticipantNode = false;
        PubKey clientPubKey = clientRedential.getPubKey();
        for (ParticipantNode participantNode : ledgerRepo.getAdminInfo().getParticipants()) {
            if (participantNode.getPubKey().equals(clientPubKey) && participantNode.getParticipantNodeState() != ParticipantNodeState.DEACTIVATED) {
                isParticipantNode = true;
                break;
            }
        }
        if (!isParticipantNode) {
            continue;
        }
        try {
            UserAccount peerAccount = ledgerRepo.getUserAccountSet().getAccount(ledgerCurrNodes.get(ledgerHash).getAddress());
            if (peerAccount.getState() != AccountState.NORMAL) {
                LOGGER.error(String.format("Authenticate ledger[%s] error ! peer state is [%s]", ledgerHash.toBase58(), peerAccount.getState()));
                continue;
            }
            UserAccount gwAccount = ledgerRepo.getUserAccountSet().getAccount(AddressEncoding.generateAddress(clientPubKey));
            if (gwAccount.getState() != AccountState.NORMAL) {
                LOGGER.error(String.format("Authenticate ledger[%s] error ! gateway state is [%s]", ledgerHash.toBase58(), peerAccount.getState()));
                continue;
            }
            // 证书模式下认证校验
            if (ledgerIdMode.get(ledgerHash) == IdentityMode.CA) {
                // 当前Peer证书
                X509Certificate peerCA = CertificateUtils.parseCertificate(peerAccount.getCertificate());
                CertificateUtils.checkCertificateRole(peerCA, CertificateRole.PEER);
                CertificateUtils.checkValidity(peerCA);
                X509Certificate[] ledgerCAs = CertificateUtils.parseCertificates(ledgerRepo.getAdminInfo().getMetadata().getLedgerCertificates());
                Arrays.stream(ledgerCAs).forEach(issuer -> CertificateUtils.checkCACertificate(issuer));
                // 当前账本证书中当前节点证书发布者
                X509Certificate[] peerIssuers = CertificateUtils.findIssuers(peerCA, ledgerCAs);
                CertificateUtils.checkValidityAny(peerIssuers);
                // 接入网关CA
                X509Certificate gwCA = CertificateUtils.parseCertificate(gwAccount.getCertificate());
                CertificateUtils.checkCertificateRole(gwCA, CertificateRole.GW);
                CertificateUtils.checkValidity(gwCA);
                X509Certificate[] gwIssuers = CertificateUtils.findIssuers(gwCA, ledgerCAs);
                CertificateUtils.checkValidityAny(gwIssuers);
            }
            clientIncomingSettings = peer.getClientAuthencationService().authencateIncoming(clientRedential);
        } catch (Exception e) {
            // 个别账本的认证失败不应该影响其它账本的认证;
            LOGGER.error(String.format("Authenticate ledger[%s] error !", ledgerHash.toBase58()), e);
            continue;
        }
        byte[] clientIncomingBytes = provider.getSettingsFactory().getIncomingSettingsEncoder().encode(clientIncomingSettings);
        String base64ClientIncomingSettings = ByteArray.toBase64(clientIncomingBytes);
        LedgerIncomingSettings ledgerIncomingSetting = new LedgerIncomingSettings();
        ledgerIncomingSetting.setLedgerHash(ledgerHash);
        // 使用非代理对象,防止JSON序列化异常
        ledgerIncomingSetting.setCryptoSetting(new CryptoConfigInfo(ledgerCryptoSettings.get(ledgerHash)));
        ledgerIncomingSetting.setConsensusClientSettings(base64ClientIncomingSettings);
        ledgerIncomingSetting.setProviderName(peerProviderName);
        ledgerIncomingList.add(ledgerIncomingSetting);
    }
    gatewayAuthResponse.setLedgers(ledgerIncomingList.toArray(new LedgerIncomingSettings[ledgerIncomingList.size()]));
    return gatewayAuthResponse;
}
Also used : GatewayAuthResponse(com.jd.blockchain.setting.GatewayAuthResponse) LedgerIncomingSettings(com.jd.blockchain.setting.LedgerIncomingSettings) ServiceEndpoint(com.jd.httpservice.agent.ServiceEndpoint) X509Certificate(java.security.cert.X509Certificate) BusinessException(utils.BusinessException) CryptoConfigInfo(com.jd.blockchain.ledger.json.CryptoConfigInfo)

Example 2 with GatewayAuthResponse

use of com.jd.blockchain.setting.GatewayAuthResponse in project jdchain-core by blockchain-jd-com.

the class LedgerPeerConnectionManager method authTask.

/**
 * 认证
 */
private synchronized void authTask() {
    logger.debug("Auth {}-{}", ledger, peerAddress);
    try {
        GatewayAuthResponse authResponse = auth();
        Set<HashDigest> ledgers = Arrays.stream(authResponse.getLedgers()).map(LedgerIncomingSettings::getLedgerHash).collect(Collectors.toSet());
        if (ledgers.contains(ledger)) {
            state = State.AVAILABLE;
        } else {
            logger.warn("Auth {}-{} response no ledger", ledger, peerAddress);
            state = State.UnAuthorized;
        }
        if (accessibleLedgers.size() != ledgers.size() || !accessibleLedgers.containsAll(ledgers)) {
            if (isAvailable()) {
                // 重新建立连接信息
                try {
                    logger.info("Auth {}-{} recreate connection", ledger, peerAddress);
                    blockchainServiceFactory.close();
                    blockchainServiceFactory = PeerBlockchainServiceFactory.create(context.getKeyPair(), peerAddress, context.getManageSslSecurity(), context.getConsensusSslSecurity(), authResponse.getLedgers(), context.getSessionCredentialProvider(), context.getClientManager());
                } catch (Exception e) {
                    logger.warn("Auth {}-{} recreate connection", ledger, peerAddress, e);
                }
            }
            // 触发账本变化处理
            notifyLedgersChange(ledgers);
            accessibleLedgers = ledgers;
        }
    } catch (Exception e) {
        state = State.UNAVAILABLE;
        logger.error("Auth {}-{} error", ledger, peerAddress, e);
    }
}
Also used : GatewayAuthResponse(com.jd.blockchain.setting.GatewayAuthResponse) HashDigest(com.jd.blockchain.crypto.HashDigest)

Aggregations

GatewayAuthResponse (com.jd.blockchain.setting.GatewayAuthResponse)2 HashDigest (com.jd.blockchain.crypto.HashDigest)1 CryptoConfigInfo (com.jd.blockchain.ledger.json.CryptoConfigInfo)1 LedgerIncomingSettings (com.jd.blockchain.setting.LedgerIncomingSettings)1 ServiceEndpoint (com.jd.httpservice.agent.ServiceEndpoint)1 X509Certificate (java.security.cert.X509Certificate)1 BusinessException (utils.BusinessException)1