// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.athenz.impl;

import com.google.inject.Inject;
import com.yahoo.athenz.auth.Principal;
import com.yahoo.athenz.auth.impl.PrincipalAuthority;
import com.yahoo.athenz.auth.impl.SimplePrincipal;
import com.yahoo.athenz.auth.impl.SimpleServiceIdentityProvider;
import com.yahoo.athenz.auth.token.PrincipalToken;
import com.yahoo.athenz.auth.util.Crypto;
import com.yahoo.athenz.zms.ZMSClient;
import com.yahoo.athenz.zts.ZTSClient;
import com.yahoo.container.jdisc.Ckms;
import com.yahoo.vespa.athenz.api.NToken;
import com.yahoo.vespa.athenz.utils.AthenzIdentities;
import com.yahoo.vespa.hosted.controller.api.integration.athenz.AthenzClientFactory;
import com.yahoo.vespa.hosted.controller.api.integration.athenz.ZmsClient;
import com.yahoo.vespa.hosted.controller.api.integration.athenz.ZtsClient;
import com.yahoo.vespa.hosted.controller.athenz.config.AthenzConfig;

import java.security.PrivateKey;
import java.time.Duration;

/**
 * @author bjorncs
 */
// TODO Use SiaIdentityProvider
public class AthenzClientFactoryImpl implements AthenzClientFactory {

    private final Ckms ckms;
    private final AthenzConfig config;
    private final AthenzPrincipalAuthority athenzPrincipalAuthority;

    @Inject
    public AthenzClientFactoryImpl(Ckms ckms, AthenzConfig config) {
        this.ckms = ckms;
        this.config = config;
        this.athenzPrincipalAuthority = new AthenzPrincipalAuthority(config.principalHeaderName());
    }

    /**
     * @return A ZMS client instance with the service identity as principal.
     */
    @Override
    public ZmsClient createZmsClientWithServicePrincipal() {
        return new ZmsClientImpl(new ZMSClient(config.zmsUrl(), createServicePrincipal()), config);
    }

    /**
     * @return A ZTS client instance with the service identity as principal.
     */
    @Override
    public ZtsClient createZtsClientWithServicePrincipal() {
        return new ZtsClientImpl(new ZTSClient(config.ztsUrl(), createServicePrincipal()), getServicePrivateKey(), config);
    }

    /**
     * @return A ZMS client created with a dual principal representing both the tenant admin and the service identity.
     */
    @Override
    public ZmsClient createZmsClientWithAuthorizedServiceToken(NToken authorizedServiceToken) {
        PrincipalToken signedToken = new PrincipalToken(authorizedServiceToken.getRawToken());
        AthenzConfig.Service service = config.service();
        signedToken.signForAuthorizedService(
                config.domain() + "." + service.name(), service.publicKeyId(), getServicePrivateKey());

        Principal dualPrincipal = SimplePrincipal.create(
                AthenzIdentities.USER_PRINCIPAL_DOMAIN.getName(), signedToken.getName(), signedToken.getSignedToken(), athenzPrincipalAuthority);
        return new ZmsClientImpl(new ZMSClient(config.zmsUrl(), dualPrincipal), config);

    }

    private Principal createServicePrincipal() {
        AthenzConfig.Service service = config.service();
        // TODO bjorncs: Cache principal token
        SimpleServiceIdentityProvider identityProvider =
                new SimpleServiceIdentityProvider(
                        athenzPrincipalAuthority,
                        config.domain(),
                        service.name(),
                        getServicePrivateKey(),
                        service.publicKeyId(),
                        Duration.ofMinutes(service.credentialsExpiryMinutes()).getSeconds());
        return identityProvider.getIdentity(config.domain(), service.name());
    }

    private PrivateKey getServicePrivateKey() {
        AthenzConfig.Service service = config.service();
        String privateKey = ckms.getSecret(service.privateKeySecretName(), service.privateKeyVersion()).trim();
        return Crypto.loadPrivateKey(privateKey);
    }

    private static class AthenzPrincipalAuthority extends PrincipalAuthority {
        private final String principalHeaderName;

        public AthenzPrincipalAuthority(String principalHeaderName) {
            this.principalHeaderName = principalHeaderName;
        }

        @Override
        public String getHeader() {
            return principalHeaderName;
        }
    }


}

@@ -350,73 +350,8 @@
 al;%0A
-import com.yahoo.athenz.auth.impl.SimpleServiceIdentityProvider;%0A
 impo
@@ -556,16 +556,80 @@
 c.Ckms;%0A
+import com.yahoo.container.jdisc.athenz.AthenzIdentityProvider;%0A
 import c
@@ -1057,35 +1057,8 @@
 Key;
-%0Aimport java.time.Duration;
 %0A%0A/*
@@ -1086,40 +1086,8 @@
  */%0A
-// TODO Use SiaIdentityProvider%0A
 publ
@@ -1289,16 +1289,75 @@
 thority;
+%0A    private final AthenzIdentityProvider identityProvider;
 %0A%0A    @I
@@ -1418,49 +1418,140 @@
 henz
-Config config) %7B%0A        this.ckms = ckms
+IdentityProvider identityProvider, AthenzConfig config) %7B%0A        this.ckms = ckms;%0A        this.identityProvider = identityProvider
 ;%0A  
@@ -1917,38 +1917,54 @@
 sUrl(), 
-createServicePrincipal
+identityProvider.getIdentitySslContext
 ()), con
@@ -2208,38 +2208,54 @@
 sUrl(), 
-createServicePrincipal
+identityProvider.getIdentitySslContext
 ()), get
@@ -3144,674 +3144,8 @@
  %7D%0A%0A
-    private Principal createServicePrincipal() %7B%0A        AthenzConfig.Service service = config.service();%0A        // TODO bjorncs: Cache principal token%0A        SimpleServiceIdentityProvider identityProvider =%0A                new SimpleServiceIdentityProvider(%0A                        athenzPrincipalAuthority,%0A                        config.domain(),%0A                        service.name(),%0A                        getServicePrivateKey(),%0A                        service.publicKeyId(),%0A                        Duration.ofMinutes(service.credentialsExpiryMinutes()).getSeconds());%0A        return identityProvider.getIdentity(config.domain(), service.name());%0A    %7D%0A%0A
     

Use AthenzIdentityProvider unless authorized service token required