Search in sources :

Example 1 with Priority

use of com.yahoo.athenz.common.server.cert.Priority in project athenz by yahoo.

the class ZTSImpl method postInstanceRegisterInformation.

@Override
public Response postInstanceRegisterInformation(ResourceContext ctx, InstanceRegisterInformation info) {
    final String caller = ctx.getApiName();
    final String principalDomain = logPrincipalAndGetDomain(ctx);
    if (readOnlyMode.get()) {
        throw requestError("Server in Maintenance Read-Only mode. Please try your request later", caller, ZTSConsts.ZTS_UNKNOWN_DOMAIN, principalDomain);
    }
    validateRequest(ctx.request(), principalDomain, caller);
    validate(info, TYPE_INSTANCE_REGISTER_INFO, principalDomain, caller);
    // for consistent handling of all requests, we're going to convert
    // all incoming object values into lower case (e.g. domain, role,
    // policy, service, etc name)
    AthenzObject.INSTANCE_REGISTER_INFO.convertToLowerCase(info);
    final String domain = info.getDomain().toLowerCase();
    setRequestDomain(ctx, domain);
    final String service = info.getService().toLowerCase();
    final String cn = ResourceUtils.serviceResourceName(domain, service);
    ((RsrcCtxWrapper) ctx).logPrincipal(cn);
    // before running any checks make sure it's coming from
    // an authorized ip address
    final String provider = info.getProvider();
    final String ipAddress = ServletRequestUtil.getRemoteAddress(ctx.request());
    if (!instanceCertManager.verifyInstanceCertIPAddress(provider, ipAddress)) {
        throw forbiddenError("Unknown IP: " + ipAddress + " for Provider: " + provider, caller, domain, principalDomain);
    }
    // get our domain object and validate the service is correctly registered
    DomainData domainData = dataStore.getDomainData(domain);
    if (domainData == null) {
        setRequestDomain(ctx, ZTSConsts.ZTS_UNKNOWN_DOMAIN);
        throw notFoundError("Domain not found: " + domain, caller, ZTSConsts.ZTS_UNKNOWN_DOMAIN, principalDomain);
    }
    validateInstanceServiceIdentity(domainData, cn, caller);
    // run the authorization checks to make sure the provider has been
    // authorized to launch instances in Athenz and the service has
    // authorized this provider to launch its instances
    Principal providerService = createPrincipalForName(provider);
    StringBuilder errorMsg = new StringBuilder(256);
    if (!instanceCertManager.authorizeLaunch(providerService, domain, service, errorMsg)) {
        throw forbiddenError(errorMsg.toString(), caller, domain, principalDomain);
    }
    // validate request/csr details
    X509ServiceCertRequest certReq;
    try {
        certReq = new X509ServiceCertRequest(info.getCsr());
    } catch (CryptoException ex) {
        throw requestError("unable to parse PKCS10 CSR: " + ex.getMessage(), caller, domain, principalDomain);
    }
    final String serviceDnsSuffix = domainData.getCertDnsDomain();
    final DataCache athenzSysDomainCache = dataStore.getDataCache(ATHENZ_SYS_DOMAIN);
    if (!certReq.validate(domain, service, provider, validCertSubjectOrgValues, athenzSysDomainCache, serviceDnsSuffix, info.getHostname(), info.getHostCnames(), hostnameResolver, errorMsg)) {
        throw requestError("CSR validation failed - " + errorMsg, caller, domain, principalDomain);
    }
    final String certReqInstanceId = certReq.getInstanceId();
    // validate attestation data is included in the request
    InstanceProvider instanceProvider = instanceProviderManager.getProvider(provider, hostnameResolver);
    if (instanceProvider == null) {
        throw requestError("unable to get instance for provider: " + provider, caller, domain, principalDomain);
    }
    // include instance details in the query access log to help
    // with debugging requests
    ctx.request().setAttribute(ACCESS_LOG_ADDL_QUERY, getInstanceRegisterQueryLog(provider, certReqInstanceId, info.getHostname()));
    InstanceConfirmation instance = newInstanceConfirmationForRegister(ctx, provider, domain, service, info.getAttestationData(), certReqInstanceId, info.getHostname(), certReq, instanceProvider.getProviderScheme());
    // Store sanIP from CSR in a variable since instance attributes go through bunch of manipulations.
    // This is used to derive workload information from identity
    String sanIpStrForWorkloadStore = InstanceUtils.getInstanceProperty(instance.getAttributes(), InstanceProvider.ZTS_INSTANCE_SAN_IP);
    // make sure to close our provider when its no longer needed
    Object timerProviderMetric = metric.startTiming("providerregister_timing", provider, principalDomain);
    try {
        instance = instanceProvider.confirmInstance(instance);
    } catch (com.yahoo.athenz.instance.provider.ResourceException ex) {
        metric.increment("providerconfirm_failure", domain, provider);
        int code = (ex.getCode() == ResourceException.GATEWAY_TIMEOUT) ? ResourceException.GATEWAY_TIMEOUT : ResourceException.FORBIDDEN;
        throw error(code, getExceptionMsg("unable to verify attestation data: ", ctx, ex, info.getHostname()), caller, domain, principalDomain);
    } catch (Exception ex) {
        metric.increment("providerconfirm_failure", domain, provider);
        throw forbiddenError(getExceptionMsg("unable to verify attestation data: ", ctx, ex, info.getHostname()), caller, domain, principalDomain);
    } finally {
        metric.stopTiming(timerProviderMetric, provider, principalDomain);
        instanceProvider.close();
    }
    metric.increment("providerconfirm_success", domain, provider);
    // determine what type of certificate the provider is authorizing
    // this instance to get - possible values are: server, client or
    // null (indicating both client and server). Additionally, we're
    // going to see if the provider wants to impose an expiry time
    // though the certificate signer might decide to ignore that
    // request and override it with its own value. Other optional
    // attributes we get back from the provider include whether or
    // not the certs can be refreshed or ssh certs can be requested
    String certUsage = null;
    String certSubjectOU = null;
    String instancePrivateIp = null;
    int certExpiryTime = 0;
    boolean certRefresh = true;
    boolean sshCertAllowed = false;
    Map<String, String> instanceAttrs = instance.getAttributes();
    if (instanceAttrs != null) {
        certUsage = instanceAttrs.remove(InstanceProvider.ZTS_CERT_USAGE);
        certSubjectOU = instanceAttrs.remove(InstanceProvider.ZTS_CERT_SUBJECT_OU);
        instancePrivateIp = instanceAttrs.remove(InstanceProvider.ZTS_INSTANCE_PRIVATE_IP);
        certExpiryTime = ZTSUtils.parseInt(instanceAttrs.remove(InstanceProvider.ZTS_CERT_EXPIRY_TIME), 0);
        certRefresh = ZTSUtils.parseBoolean(instanceAttrs.remove(InstanceProvider.ZTS_CERT_REFRESH), true);
        sshCertAllowed = ZTSUtils.parseBoolean(instanceAttrs.remove(InstanceProvider.ZTS_CERT_SSH), false);
    }
    if (verifyCertSubjectOU && !certReq.validateSubjectOUField(provider, certSubjectOU, validCertSubjectOrgUnitValues)) {
        throw requestError("CSR Subject OrgUnit validation failed", caller, domain, principalDomain);
    }
    // update the expiry time if one is provided in the request
    certExpiryTime = getServiceCertRequestExpiryTime(certExpiryTime, info.getExpiryTime());
    // generate certificate for the instance
    // Initial request from the workload gets highest priority
    Priority priority = Priority.High;
    Object timerX509CertMetric = metric.startTiming("certsignx509_timing", null, principalDomain);
    InstanceIdentity identity = instanceCertManager.generateIdentity(provider, null, info.getCsr(), cn, certUsage, certExpiryTime, priority);
    metric.stopTiming(timerX509CertMetric, null, principalDomain);
    if (identity == null) {
        throw serverError("unable to generate identity", caller, domain, principalDomain);
    }
    if (sshCertAllowed) {
        Object timerSSHCertMetric = metric.startTiming("certsignssh_timing", null, principalDomain);
        // generate a ssh object for recording
        SSHCertRecord certRecord = generateSSHCertRecord(ctx, cn, certReqInstanceId, instancePrivateIp);
        instanceCertManager.generateSSHIdentity(null, identity, info.getHostname(), info.getSsh(), info.getSshCertRequest(), certRecord, ZTSConsts.ZTS_SSH_HOST);
        metric.stopTiming(timerSSHCertMetric, null, principalDomain);
    }
    // set the other required attributes in the identity object
    identity.setAttributes(instanceAttrs);
    identity.setProvider(provider);
    identity.setInstanceId(certReqInstanceId);
    X509Certificate newCert = Crypto.loadX509Certificate(identity.getX509Certificate());
    final String certSerial = newCert.getSerialNumber().toString();
    if (certRefresh) {
        if (insertX509CertRecord(ctx, cn, provider, certReqInstanceId, certSerial, InstanceProvider.ZTS_CERT_USAGE_CLIENT.equalsIgnoreCase(certUsage), newCert.getNotAfter(), info.getHostname()) == null) {
            throw serverError("unable to update cert db", caller, domain, principalDomain);
        }
    }
    if (enableWorkloadStore && !athenzSysDomainCache.isWorkloadStoreExcludedProvider(provider)) {
        // insert into workloads store is on best-effort basis. No errors are thrown if the op is not successful.
        insertWorkloadRecord(cn, provider, certReqInstanceId, sanIpStrForWorkloadStore, info.getHostname(), newCert.getNotAfter());
    }
    if (info.getToken() == Boolean.TRUE) {
        PrincipalToken svcToken = new PrincipalToken.Builder("S1", domain, service).expirationWindow(svcTokenTimeout).keyId(privateKey.getId()).host(serverHostName).ip(ipAddress).keyService(ZTSConsts.ZTS_SERVICE).build();
        svcToken.sign(privateKey.getKey());
        identity.setServiceToken(svcToken.getSignedToken());
    }
    // log our certificate
    instanceCertManager.logX509Cert(null, ipAddress, provider, certReqInstanceId, newCert);
    final String location = "/zts/v1/instance/" + provider + "/" + domain + "/" + service + "/" + certReqInstanceId;
    return Response.status(ResourceException.CREATED).entity(identity).header("Location", location).build();
}
Also used : InstanceConfirmation(com.yahoo.athenz.instance.provider.InstanceConfirmation) DomainData(com.yahoo.athenz.zms.DomainData) InstanceProvider(com.yahoo.athenz.instance.provider.InstanceProvider) Priority(com.yahoo.athenz.common.server.cert.Priority) PrincipalToken(com.yahoo.athenz.auth.token.PrincipalToken) DataCache(com.yahoo.athenz.zts.cache.DataCache) StatusCheckException(com.yahoo.athenz.common.server.status.StatusCheckException) CryptoException(com.yahoo.athenz.auth.util.CryptoException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) CryptoException(com.yahoo.athenz.auth.util.CryptoException) SimplePrincipal(com.yahoo.athenz.auth.impl.SimplePrincipal) SSHCertRecord(com.yahoo.athenz.common.server.ssh.SSHCertRecord)

Example 2 with Priority

use of com.yahoo.athenz.common.server.cert.Priority in project athenz by yahoo.

the class ZTSImpl method processProviderX509RefreshRequest.

InstanceIdentity processProviderX509RefreshRequest(ResourceContext ctx, DomainData domainData, final Principal principal, final String domain, final String service, final String provider, final String instanceId, InstanceRefreshInformation info, X509Certificate cert, final String caller) {
    // parse and validate our CSR
    final String principalDomain = principal.getDomain();
    X509ServiceCertRequest certReq;
    try {
        certReq = new X509ServiceCertRequest(info.getCsr());
    } catch (CryptoException ex) {
        throw requestError("unable to parse PKCS10 CSR", caller, domain, principalDomain);
    }
    final String serviceDnsSuffix = domainData.getCertDnsDomain();
    final DataCache athenzSysDomainCache = dataStore.getDataCache(ATHENZ_SYS_DOMAIN);
    StringBuilder errorMsg = new StringBuilder(256);
    if (!certReq.validate(domain, service, provider, validCertSubjectOrgValues, athenzSysDomainCache, serviceDnsSuffix, info.getHostname(), info.getHostCnames(), hostnameResolver, errorMsg)) {
        throw requestError("CSR validation failed - " + errorMsg, caller, domain, principalDomain);
    }
    if (!certReq.validateInstanceId(instanceId, cert)) {
        throw requestError("CSR validation failed - instance id mismatch", caller, domain, principalDomain);
    }
    // Extract Hostname in the certificate to be passed onto the provider
    String certHostname = X509CertUtils.extractItemFromURI(Crypto.extractX509CertURIs(cert), ZTSConsts.ZTS_CERT_HOSTNAME_URI);
    // validate attestation data is included in the request
    InstanceProvider instanceProvider = instanceProviderManager.getProvider(provider, hostnameResolver);
    if (instanceProvider == null) {
        throw requestError("unable to get instance for provider: " + provider, caller, domain, principalDomain);
    }
    InstanceConfirmation instance = generateInstanceConfirmObject(ctx, provider, domain, service, info.getAttestationData(), instanceId, info.getHostname(), certHostname, certReq, instanceProvider.getProviderScheme());
    // Store sanIP from CSR in a variable since instance attributes go through bunch of manipulations.
    // This is used to derive workload information from identity
    String sanIpStrForWorkloadStore = InstanceUtils.getInstanceProperty(instance.getAttributes(), InstanceProvider.ZTS_INSTANCE_SAN_IP);
    // make sure to close our provider when its no longer needed
    Object timerProviderMetric = metric.startTiming("providerrefresh_timing", provider, principalDomain);
    try {
        instance = instanceProvider.refreshInstance(instance);
    } catch (com.yahoo.athenz.instance.provider.ResourceException ex) {
        metric.increment("providerconfirm_failure", domain, provider);
        int code = (ex.getCode() == ResourceException.GATEWAY_TIMEOUT) ? ResourceException.GATEWAY_TIMEOUT : ResourceException.FORBIDDEN;
        throw error(code, getExceptionMsg("unable to verify attestation data: ", ctx, ex, info.getHostname()), caller, domain, principalDomain);
    } catch (Exception ex) {
        metric.increment("providerconfirm_failure", domain, provider);
        throw forbiddenError(getExceptionMsg("unable to verify attestation data: ", ctx, ex, info.getHostname()), caller, domain, principalDomain);
    } finally {
        metric.stopTiming(timerProviderMetric, provider, principalDomain);
        instanceProvider.close();
    }
    metric.increment("providerconfirm_success", domain, provider);
    // determine what type of certificate the provider is authorizing
    // this instance to refresh - possible values are: server, client or
    // null (indicating both client and server). Additionally, we're
    // going to see if the provider wants to impose an expiry time
    // though the certificate signer might decide to ignore that
    // request and override it with its own value. Other optional
    // attributes we get back from the provider include whether or
    // not the certs can be refreshed or ssh certs can be requested
    String certUsage = null;
    String certSubjectOU = null;
    String instancePrivateIp = null;
    int certExpiryTime = 0;
    boolean sshCertAllowed = false;
    boolean certRefreshCheck = true;
    Map<String, String> instanceAttrs = instance.getAttributes();
    if (instanceAttrs != null) {
        certUsage = instanceAttrs.remove(InstanceProvider.ZTS_CERT_USAGE);
        instancePrivateIp = instanceAttrs.remove(InstanceProvider.ZTS_INSTANCE_PRIVATE_IP);
        certExpiryTime = ZTSUtils.parseInt(instanceAttrs.remove(InstanceProvider.ZTS_CERT_EXPIRY_TIME), 0);
        certRefreshCheck = ZTSUtils.parseBoolean(instanceAttrs.remove(InstanceProvider.ZTS_CERT_REFRESH), true);
        certSubjectOU = instanceAttrs.remove(InstanceProvider.ZTS_CERT_SUBJECT_OU);
        sshCertAllowed = ZTSUtils.parseBoolean(instanceAttrs.remove(InstanceProvider.ZTS_CERT_SSH), false);
    }
    if (verifyCertSubjectOU && !certReq.validateSubjectOUField(provider, certSubjectOU, validCertSubjectOrgUnitValues)) {
        throw requestError("CSR Subject OrgUnit validation failed", caller, domain, principalDomain);
    }
    // validate that the tenant domain/service matches to the values
    // in the cert record when it was initially issued
    final String principalName = principal.getFullName();
    // if the provider allows the certs to be refreshed then we need
    // to extract our instance certificate record to make sure it
    // hasn't been revoked already
    X509CertRecord x509CertRecord = null;
    if (certRefreshCheck) {
        x509CertRecord = getValidatedX509CertRecord(ctx, provider, instanceId, principalName, cert, caller, domain, principalDomain, info.getHostname());
    }
    if (x509CertRecord != null && x509CertRecord.getClientCert()) {
        certUsage = InstanceProvider.ZTS_CERT_USAGE_CLIENT;
    }
    // update the expiry time if one is provided in the request
    certExpiryTime = getServiceCertRequestExpiryTime(certExpiryTime, info.getExpiryTime());
    // generate identity with the certificate
    Priority priority = ZTSUtils.getCertRequestPriority(cert.getNotBefore(), cert.getNotAfter());
    Object timerX509CertMetric = metric.startTiming("certsignx509_timing", null, principalDomain);
    InstanceIdentity identity = instanceCertManager.generateIdentity(provider, null, info.getCsr(), principalName, certUsage, certExpiryTime, priority);
    metric.stopTiming(timerX509CertMetric, null, principalDomain);
    if (identity == null) {
        throw serverError("unable to generate identity", caller, domain, principalDomain);
    }
    if (sshCertAllowed) {
        Object timerSSHCertMetric = metric.startTiming("certsignssh_timing", null, principalDomain);
        // generate an ssh object for recording
        SSHCertRecord certRecord = generateSSHCertRecord(ctx, domain + "." + service, instanceId, instancePrivateIp);
        instanceCertManager.generateSSHIdentity(principal, identity, info.getHostname(), info.getSsh(), info.getSshCertRequest(), certRecord, ZTSConsts.ZTS_SSH_HOST);
        metric.stopTiming(timerSSHCertMetric, null, principalDomain);
    }
    // set the other required attributes in the identity object
    identity.setAttributes(instanceAttrs);
    identity.setProvider(provider);
    identity.setInstanceId(instanceId);
    // need to update our cert record with new certificate details
    X509Certificate newCert = Crypto.loadX509Certificate(identity.getX509Certificate());
    final String certSerialNumber = newCert.getSerialNumber().toString();
    final String reqIp = ServletRequestUtil.getRemoteAddress(ctx.request());
    if (x509CertRecord != null) {
        // if our current IP or hostname has changed, we'll mark
        // the record as svc data updated
        processCertRecordChange(x509CertRecord, reqIp, info.getHostname());
        // now let's update our record
        x509CertRecord.setCurrentSerial(certSerialNumber);
        x509CertRecord.setCurrentIP(reqIp);
        x509CertRecord.setCurrentTime(new Date());
        x509CertRecord.setExpiryTime(newCert.getNotAfter());
        x509CertRecord.setHostName(info.getHostname());
        if (!instanceCertManager.updateX509CertRecord(x509CertRecord)) {
            throw serverError("unable to update cert db", caller, domain, principalDomain);
        }
    }
    if (enableWorkloadStore && !athenzSysDomainCache.isWorkloadStoreExcludedProvider(provider)) {
        // workloads store update is on best-effort basis. No errors are thrown if the op is not successful.
        updateWorkloadRecord(AthenzUtils.getPrincipalName(domain, service), provider, instanceId, sanIpStrForWorkloadStore, info.getHostname(), newCert.getNotAfter());
    }
    // log our certificate
    instanceCertManager.logX509Cert(principal, reqIp, provider, instanceId, newCert);
    if (info.getToken() == Boolean.TRUE) {
        PrincipalToken svcToken = new PrincipalToken.Builder("S1", domain, service).expirationWindow(svcTokenTimeout).keyId(privateKey.getId()).host(serverHostName).ip(ServletRequestUtil.getRemoteAddress(ctx.request())).keyService(ZTSConsts.ZTS_SERVICE).build();
        svcToken.sign(privateKey.getKey());
        identity.setServiceToken(svcToken.getSignedToken());
    }
    return identity;
}
Also used : InstanceConfirmation(com.yahoo.athenz.instance.provider.InstanceConfirmation) Priority(com.yahoo.athenz.common.server.cert.Priority) PrincipalToken(com.yahoo.athenz.auth.token.PrincipalToken) DataCache(com.yahoo.athenz.zts.cache.DataCache) StatusCheckException(com.yahoo.athenz.common.server.status.StatusCheckException) CryptoException(com.yahoo.athenz.auth.util.CryptoException) IOException(java.io.IOException) X509CertRecord(com.yahoo.athenz.common.server.cert.X509CertRecord) X509Certificate(java.security.cert.X509Certificate) CryptoException(com.yahoo.athenz.auth.util.CryptoException) InstanceProvider(com.yahoo.athenz.instance.provider.InstanceProvider) SSHCertRecord(com.yahoo.athenz.common.server.ssh.SSHCertRecord)

Example 3 with Priority

use of com.yahoo.athenz.common.server.cert.Priority in project athenz by yahoo.

the class ZTSImpl method processRoleCertificateRequest.

String processRoleCertificateRequest(ResourceContext ctx, final Principal principal, final String principalDomain, X509RoleCertRequest certReq, final String ipAddress, RoleCertificateRequest req) {
    final String caller = ctx.getApiName();
    final String domainName = certReq.getReqRoleDomain();
    final String roleName = certReq.getReqRoleName();
    // validate principal object to make sure we're not
    // processing a role identity and instead we require
    // a service identity
    validatePrincipalNotRoleIdentity(principal, caller);
    // for consistent handling of all requests, we're going to convert
    // all incoming object values into lower case since ZMS Server
    // saves all of its object names in lower case
    String proxyForPrincipal = req.getProxyForPrincipal();
    if (proxyForPrincipal != null) {
        proxyForPrincipal = normalizeDomainAliasUser(proxyForPrincipal.toLowerCase());
    }
    if (isAuthorizedServicePrincipal(principal)) {
        throw forbiddenError("Authorized Service Principals not allowed", caller, domainName, principalDomain);
    }
    // get our principal's name
    String principalName = principal.getFullName();
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("processRoleCertificateRequest(domain: {}, principal: {}, role: {}, proxy-for: {})", domainName, principalName, roleName, proxyForPrincipal);
    }
    if (proxyForPrincipal != null && !isAuthorizedProxyUser(authorizedProxyUsers, principalName)) {
        throw forbiddenError("Principal: " + principalName + " not authorized for proxy role certificate request", caller, domainName, principalDomain);
    }
    // first retrieve our domain data object from the cache
    DataCache data = dataStore.getDataCache(domainName);
    if (data == null) {
        setRequestDomain(ctx, ZTSConsts.ZTS_UNKNOWN_DOMAIN);
        throw notFoundError("No such domain: " + domainName, caller, ZTSConsts.ZTS_UNKNOWN_DOMAIN, principalDomain);
    }
    // process our request and retrieve the roles for the principal
    String[] requestedRoleList = { roleName };
    Set<String> roles = new HashSet<>();
    dataStore.getAccessibleRoles(data, domainName, principalName, requestedRoleList, roles, false);
    if (roles.isEmpty()) {
        throw forbiddenError(tokenErrorMessage(caller, principalName, domainName, requestedRoleList), caller, domainName, principalDomain);
    }
    // if this is proxy for operation then we want to make sure that
    // both principals have access to the same set of roles so we'll
    // remove any roles that are authorized by only one of the principals
    String proxyUser = null;
    if (proxyForPrincipal != null) {
        Set<String> rolesForProxy = new HashSet<>();
        dataStore.getAccessibleRoles(data, domainName, proxyForPrincipal, requestedRoleList, rolesForProxy, false);
        roles.retainAll(rolesForProxy);
        if (roles.isEmpty()) {
            throw forbiddenError(tokenErrorMessage(caller, proxyForPrincipal, domainName, requestedRoleList), caller, domainName, principalDomain);
        }
        // we need to switch our principal
        proxyUser = principalName;
        principalName = proxyForPrincipal;
    }
    // validate request/csr details
    X509Certificate cert = principal.getX509Certificate();
    if (!validateRoleCertificateRequest(certReq, principalName, proxyUser, cert, ipAddress)) {
        throw requestError("Unable to validate cert request", caller, domainName, principalDomain);
    }
    // If no previous cert before / after specified, process in high priority.
    // Otherwise, priority depends on the duration of the previous certificate.
    Priority priority = Priority.High;
    if (req.getPrevCertNotAfter() != null && req.getPrevCertNotBefore() != null) {
        priority = ZTSUtils.getCertRequestPriority(req.getPrevCertNotBefore().toDate(), req.getPrevCertNotAfter().toDate());
    }
    int expiryTime = determineRoleCertTimeout(data, roles, (int) req.getExpiryTime());
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Role Certificate Priority: {}, expiryTime: {}", priority, expiryTime);
    }
    final String x509Cert = instanceCertManager.generateX509Certificate(null, null, req.getCsr(), InstanceProvider.ZTS_CERT_USAGE_CLIENT, expiryTime, priority);
    if (null == x509Cert || x509Cert.isEmpty()) {
        throw serverError("Unable to create certificate from the cert signer", caller, domainName, principalDomain);
    }
    return x509Cert;
}
Also used : Priority(com.yahoo.athenz.common.server.cert.Priority) DataCache(com.yahoo.athenz.zts.cache.DataCache) X509Certificate(java.security.cert.X509Certificate)

Example 4 with Priority

use of com.yahoo.athenz.common.server.cert.Priority in project athenz by yahoo.

the class ZTSUtilsTest method testGetCertRequestPriority.

@Test
public void testGetCertRequestPriority() {
    Date currentDate = new Date();
    Priority certRequestPriority = ZTSUtils.getCertRequestPriority(Date.from(currentDate.toInstant().minus(1, ChronoUnit.DAYS)), Date.from(currentDate.toInstant().plus(29, ChronoUnit.DAYS)));
    assertEquals(certRequestPriority, Priority.Low);
    certRequestPriority = ZTSUtils.getCertRequestPriority(Date.from(currentDate.toInstant().minus(10, ChronoUnit.DAYS)), Date.from(currentDate.toInstant().plus(20, ChronoUnit.DAYS)));
    assertEquals(certRequestPriority, Priority.Medium);
    certRequestPriority = ZTSUtils.getCertRequestPriority(Date.from(currentDate.toInstant().minus(20, ChronoUnit.DAYS)), Date.from(currentDate.toInstant().plus(10, ChronoUnit.DAYS)));
    assertEquals(certRequestPriority, Priority.Medium);
    certRequestPriority = ZTSUtils.getCertRequestPriority(Date.from(currentDate.toInstant().minus(25, ChronoUnit.DAYS)), Date.from(currentDate.toInstant().plus(5, ChronoUnit.DAYS)));
    assertEquals(certRequestPriority, Priority.High);
    // Cert expired, return High priority
    certRequestPriority = ZTSUtils.getCertRequestPriority(Date.from(currentDate.toInstant().minus(33, ChronoUnit.DAYS)), Date.from(currentDate.toInstant().minus(3, ChronoUnit.DAYS)));
    assertEquals(certRequestPriority, Priority.High);
}
Also used : Priority(com.yahoo.athenz.common.server.cert.Priority) Date(java.util.Date) Test(org.testng.annotations.Test)

Aggregations

Priority (com.yahoo.athenz.common.server.cert.Priority)4 DataCache (com.yahoo.athenz.zts.cache.DataCache)3 X509Certificate (java.security.cert.X509Certificate)3 PrincipalToken (com.yahoo.athenz.auth.token.PrincipalToken)2 CryptoException (com.yahoo.athenz.auth.util.CryptoException)2 SSHCertRecord (com.yahoo.athenz.common.server.ssh.SSHCertRecord)2 StatusCheckException (com.yahoo.athenz.common.server.status.StatusCheckException)2 InstanceConfirmation (com.yahoo.athenz.instance.provider.InstanceConfirmation)2 InstanceProvider (com.yahoo.athenz.instance.provider.InstanceProvider)2 IOException (java.io.IOException)2 SimplePrincipal (com.yahoo.athenz.auth.impl.SimplePrincipal)1 X509CertRecord (com.yahoo.athenz.common.server.cert.X509CertRecord)1 DomainData (com.yahoo.athenz.zms.DomainData)1 Date (java.util.Date)1 Test (org.testng.annotations.Test)1