ZTSImpl implements KeyStore, ZTSHandler { @Override public RoleToken postRoleCertificateRequest(ResourceContext ctx, String domainName, String roleName, RoleCertificateRequest req) { final String caller = ctx.getApiName(); final String principalDomain = logPrincipalAndGetDomain(ctx); if (readOnlyMode) { 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(domainName, TYPE_DOMAIN_NAME, principalDomain, caller); validate(roleName, TYPE_ENTITY_NAME, principalDomain, caller); validate(req, TYPE_ROLE_CERTIFICATE_REQUEST, principalDomain, caller); final Principal principal = ((RsrcCtxWrapper) ctx).principal(); validatePrincipalNotRoleIdentity(principal, caller); String proxyForPrincipal = req.getProxyForPrincipal(); if (proxyForPrincipal != null) { proxyForPrincipal = normalizeDomainAliasUser(proxyForPrincipal.toLowerCase()); } domainName = domainName.toLowerCase(); setRequestDomain(ctx, domainName); roleName = roleName.toLowerCase(); if (isAuthorizedServicePrincipal(principal)) { throw forbiddenError("Authorized Service Principals not allowed", caller, domainName, principalDomain); } String principalName = principal.getFullName(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("postRoleCertificateRequest(domain: {}, principal: {}, role: {}, proxy-for: {})", domainName, principalName, roleName, proxyForPrincipal); } if (proxyForPrincipal != null && !isAuthorizedProxyUser(authorizedProxyUsers, principalName)) { LOGGER.error("postRoleCertificateRequest: Principal: " + principalName + " not authorized for proxy role certificate request"); throw forbiddenError("postRoleCertificateRequest: Principal: " + principalName + " not authorized for proxy role certificate request", caller, domainName, domainName); } DataCache data = dataStore.getDataCache(domainName); if (data == null) { setRequestDomain(ctx, ZTSConsts.ZTS_UNKNOWN_DOMAIN); throw notFoundError("postRoleCertificateRequest: No such domain: " + domainName, caller, ZTSConsts.ZTS_UNKNOWN_DOMAIN, principalDomain); } String[] requestedRoleList = { roleName }; Set<String> roles = new HashSet<>(); dataStore.getAccessibleRoles(data, domainName, principalName, requestedRoleList, roles, false); if (roles.isEmpty()) { throw forbiddenError("postRoleCertificateRequest: No access to any roles in domain: " + domainName, caller, domainName, principalDomain); } 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("postRoleCertificateRequest: No access to any roles by User and Proxy Principals", caller, domainName, principalDomain); } proxyUser = principalName; principalName = proxyForPrincipal; } X509Certificate cert = principal.getX509Certificate(); final String ipAddress = ServletRequestUtil.getRemoteAddress(ctx.request()); if (!validateRoleCertificateRequest(req.getCsr(), domainName, roles, principalName, proxyUser, cert, ipAddress)) { throw requestError("postRoleCertificateRequest: Unable to validate cert request", caller, domainName, principalDomain); } int expiryTime = determineRoleCertTimeout(data, roles, (int) req.getExpiryTime()); final String x509Cert = instanceCertManager.generateX509Certificate(req.getCsr(), InstanceProvider.ZTS_CERT_USAGE_CLIENT, expiryTime); if (null == x509Cert || x509Cert.isEmpty()) { throw serverError("postRoleCertificateRequest: Unable to create certificate from the cert signer", caller, domainName, principalDomain); } final X509Certificate roleCert = Crypto.loadX509Certificate(x509Cert); RoleToken roleToken = new RoleToken().setToken(x509Cert) .setExpiryTime(roleCert.getNotAfter().getTime() / 1000); instanceCertManager.logX509Cert(principal, ipAddress, ZTSConsts.ZTS_SERVICE, null, roleCert); return roleToken; } ZTSImpl();  ZTSImpl(CloudStore implCloudStore, DataStore implDataStore); @Override String getPublicKey(String domain, String service, String keyId); ServiceIdentity getServiceIdentity(ResourceContext ctx, String domainName, String serviceName); PublicKeyEntry getPublicKeyEntry(ResourceContext ctx, String domainName,
            String serviceName, String keyId); ServiceIdentityList getServiceIdentityList(ResourceContext ctx, String domainName); HostServices getHostServices(ResourceContext ctx, String host); Response getDomainSignedPolicyData(ResourceContext ctx, String domainName, String matchingTag); TenantDomains getTenantDomains(ResourceContext ctx, String providerDomainName,
            String userName, String roleName, String serviceName); @Override RoleToken getRoleToken(ResourceContext ctx, String domainName, String roleNames,
            Integer minExpiryTime, Integer maxExpiryTime, String proxyForPrincipal); @Override AccessTokenResponse postAccessTokenRequest(ResourceContext ctx, String request); RoleAccess getRoleAccess(ResourceContext ctx, String domainName, String principal); @Override RoleToken postRoleCertificateRequest(ResourceContext ctx, String domainName,
            String roleName, RoleCertificateRequest req); @Override RoleCertificate postRoleCertificateRequestExt(ResourceContext ctx, RoleCertificateRequest req); AWSTemporaryCredentials getAWSTemporaryCredentials(ResourceContext ctx, String domainName,
            String roleName, Integer durationSeconds, String externalId); @Override Response postInstanceRegisterInformation(ResourceContext ctx, InstanceRegisterInformation info); @Override InstanceIdentity postInstanceRefreshInformation(ResourceContext ctx, String provider,
            String domain, String service, String instanceId, InstanceRefreshInformation info); @Override void deleteInstanceIdentity(ResourceContext ctx, String provider,
            String domain, String service, String instanceId); @Deprecated @Override Identity postInstanceRefreshRequest(ResourceContext ctx, String domain,
            String service, InstanceRefreshRequest req); @Override Response postSSHCertRequest(ResourceContext ctx, SSHCertRequest certRequest); @Override JWKList getJWKList(ResourceContext ctx, Boolean rfc); @Deprecated @Override Identity postOSTKInstanceRefreshRequest(ResourceContext ctx, String domain,
            String service, OSTKInstanceRefreshRequest req); @Override ResourceAccess getResourceAccessExt(ResourceContext ctx, String action, String resource,
            String trustDomain, String checkPrincipal); @Override ResourceAccess getResourceAccess(ResourceContext ctx, String action, String resource,
            String trustDomain, String checkPrincipal); @Override Access getAccess(ResourceContext ctx, String domainName, String roleName,
            String principal); CertificateAuthorityBundle getCertificateAuthorityBundle(ResourceContext ctx, String name); @Override DomainMetrics postDomainMetrics(ResourceContext ctx, String domainName,
            DomainMetrics domainMetrics); @Override Status getStatus(ResourceContext ctx); @Override Schema getRdlSchema(ResourceContext context); ResourceContext newResourceContext(HttpServletRequest request,
                                              HttpServletResponse response,
                                              String apiName); static String getRootDir(); void recordMetrics(ResourceContext ctx, int httpStatus);  }
@Test public void testPostRoleCertificateRequest() { long expiry = 3600; RoleCertificateRequest req = new RoleCertificateRequest() .setCsr(ROLE_CERT_CORETECH_REQUEST).setExpiryTime(expiry); SignedDomain signedDomain = createSignedDomain("coretech", "weather", "storage", true); store.processDomain(signedDomain, false); CloudStore cloudStore = new MockCloudStore(); store.setCloudStore(cloudStore); zts.cloudStore = cloudStore; Principal principal = SimplePrincipal.create("user_domain", "user1", "v=U1;d=user_domain;n=user;s=signature", 0, null); ResourceContext context = createResourceContext(principal); RoleToken roleToken = zts.postRoleCertificateRequest(context, "coretech", "readers", req); assertNotNull(roleToken); long diffExpiryTime = roleToken.getExpiryTime() - System.currentTimeMillis() / 1000; assertTrue(Math.abs(diffExpiryTime - expiry * 60) < 10); }
@Test public void testPostRoleCertificateProxyUserRequest() throws IOException { Path path = Paths.get("src/test/resources/coretech_readers_proxy_role_uri.csr"); String csr = new String(Files.readAllBytes(path)); RoleCertificateRequest req = new RoleCertificateRequest() .setCsr(csr).setExpiryTime(3600L) .setProxyForPrincipal("user_domain.user1"); List<RoleMember> writers = new ArrayList<>(); writers.add(new RoleMember().setMemberName("user_domain.proxy-user1")); writers.add(new RoleMember().setMemberName("user_domain.user1")); List<RoleMember> readers = new ArrayList<>(); readers.add(new RoleMember().setMemberName("user_domain.proxy-user1")); readers.add(new RoleMember().setMemberName("user_domain.user4")); readers.add(new RoleMember().setMemberName("user_domain.user1")); SignedDomain signedDomain = createSignedDomain("coretech", "weather", "storage", writers, readers, true); store.processDomain(signedDomain, false); CloudStore cloudStore = new MockCloudStore(); store.setCloudStore(cloudStore); zts.cloudStore = cloudStore; Principal principal = SimplePrincipal.create("user_domain", "proxy-user1", "v=U1;d=user_domain;n=proxy-user1;s=signature", 0, null); ResourceContext context = createResourceContext(principal); RoleToken roleToken = zts.postRoleCertificateRequest(context, "coretech", "readers", req); assertNotNull(roleToken); }
@Test public void testPostRoleCertificateProxyUserRequestAccessMismatch() throws IOException { Path path = Paths.get("src/test/resources/coretech_readers_proxy_role_uri.csr"); String csr = new String(Files.readAllBytes(path)); RoleCertificateRequest req = new RoleCertificateRequest() .setCsr(csr).setExpiryTime(3600L) .setProxyForPrincipal("user_domain.user1"); List<RoleMember> writers = new ArrayList<>(); writers.add(new RoleMember().setMemberName("user_domain.user1")); List<RoleMember> readers = new ArrayList<>(); readers.add(new RoleMember().setMemberName("user_domain.user4")); readers.add(new RoleMember().setMemberName("user_domain.proxy-user1")); SignedDomain signedDomain = createSignedDomain("coretech", "weather", "storage", writers, readers, true); store.processDomain(signedDomain, false); CloudStore cloudStore = new MockCloudStore(); store.setCloudStore(cloudStore); zts.cloudStore = cloudStore; Principal principal = SimplePrincipal.create("user_domain", "proxy-user1", "v=U1;d=user_domain;n=proxy-user1;s=signature", 0, null); ResourceContext context = createResourceContext(principal); try { zts.postRoleCertificateRequest(context, "coretech", "readers", req); fail(); } catch (ResourceException ex) { assertTrue(ex.getMessage().contains("No access to any roles by User and Proxy Principals")); } }
@Test public void testPostRoleCertificateInvalidProxyUserRequest() throws IOException { Path path = Paths.get("src/test/resources/coretech_readers_proxy_role_uri.csr"); String csr = new String(Files.readAllBytes(path)); RoleCertificateRequest req = new RoleCertificateRequest() .setCsr(csr).setExpiryTime(3600L) .setProxyForPrincipal("user_domain.user1"); List<RoleMember> writers = new ArrayList<>(); writers.add(new RoleMember().setMemberName("user_domain.proxy-user19")); writers.add(new RoleMember().setMemberName("user_domain.user1")); List<RoleMember> readers = new ArrayList<>(); readers.add(new RoleMember().setMemberName("user_domain.proxy-user19")); readers.add(new RoleMember().setMemberName("user_domain.user4")); readers.add(new RoleMember().setMemberName("user_domain.user1")); SignedDomain signedDomain = createSignedDomain("coretech", "weather", "storage", writers, readers, true); store.processDomain(signedDomain, false); CloudStore cloudStore = new MockCloudStore(); store.setCloudStore(cloudStore); zts.cloudStore = cloudStore; Principal principal = SimplePrincipal.create("user_domain", "proxy-user19", "v=U1;d=user_domain;n=proxy-user1;s=signature", 0, null); ResourceContext context = createResourceContext(principal); try { zts.postRoleCertificateRequest(context, "coretech", "readers", req); fail(); } catch (ResourceException ex) { assertTrue(ex.getMessage().contains("not authorized for proxy role certificate request")); } }
@Test public void testPostRoleCertificateRequestNullCertReturn() { RoleCertificateRequest req = new RoleCertificateRequest() .setCsr(ROLE_CERT_CORETECH_REQUEST).setExpiryTime(3600L); SignedDomain signedDomain = createSignedDomain("coretech", "weather", "storage", true); store.processDomain(signedDomain, false); CloudStore cloudStore = new MockCloudStore(); store.setCloudStore(cloudStore); zts.cloudStore = cloudStore; Principal principal = SimplePrincipal.create("user_domain", "user1", "v=U1;d=user_domain;n=user;s=signature", 0, null); ResourceContext context = createResourceContext(principal); InstanceCertManager certManager = Mockito.mock(InstanceCertManager.class); Mockito.when(certManager.generateIdentity(ROLE_CERT_CORETECH_REQUEST, "coretech.weathers", "client", 3600)).thenReturn(null); zts.instanceCertManager = certManager; try { zts.postRoleCertificateRequest(context, "coretech", "readers", req); fail(); } catch (ResourceException ex) { assertEquals(ex.getCode(), 500); assertTrue(ex.getMessage().contains("Unable to create certificate from the cert signer")); } }
@Test public void testPostRoleCertificateRequestInvalidRequests() { RoleCertificateRequest req = new RoleCertificateRequest() .setCsr(ROLE_CERT_CORETECH_REQUEST).setExpiryTime(3600L); SignedDomain signedDomain = createSignedDomain("coretech", "weather", "storage", true); store.processDomain(signedDomain, false); Principal principal = SimplePrincipal.create("user_domain", "user1", "v=U1;d=user_domain;n=user;s=signature", 0, null); ResourceContext context = createResourceContext(principal); try { zts.postRoleCertificateRequest(context, "coretech", "unknownrole", req); fail(); } catch (ResourceException ex) { assertEquals(ex.getCode(), 403); } try { zts.postRoleCertificateRequest(context, "coretech", "writers", req); fail(); } catch (ResourceException ex) { assertEquals(ex.getCode(), 400); } try { zts.postRoleCertificateRequest(context, "unknown-domain", "readers", req); fail(); } catch (ResourceException ex) { assertEquals(ex.getCode(), 404); } }
@Test public void testPostRoleCertificateRequestMismatchDomain() { RoleCertificateRequest req = new RoleCertificateRequest() .setCsr(ROLE_CERT_DB_REQUEST).setExpiryTime(3600L); SignedDomain signedDomain = createSignedDomain("coretech", "weather", "storage", true); store.processDomain(signedDomain, false); Principal principal = SimplePrincipal.create("user_domain", "user1", "v=U1;d=user_domain;n=user;s=signature", 0, null); ResourceContext context = createResourceContext(principal); try { zts.postRoleCertificateRequest(context, "coretech", "readers", req); fail(); } catch (ResourceException ex) { assertEquals(ex.getCode(), 400); } }
@Test public void testPostRoleCertificateRequestAuthorizedPrincipal() { RoleCertificateRequest req = new RoleCertificateRequest() .setCsr(ROLE_CERT_DB_REQUEST).setExpiryTime(3600L); SignedDomain signedDomain = createSignedDomain("coretech", "weather", "storage", true); store.processDomain(signedDomain, false); SimplePrincipal principal = (SimplePrincipal) SimplePrincipal.create("user_domain", "user1", "v=U1;d=user_domain;n=user;s=signature", 0, null); principal.setAuthorizedService("athenz.api"); ResourceContext context = createResourceContext(principal); try { zts.postRoleCertificateRequest(context, "coretech", "readers", req); fail(); } catch (ResourceException ex) { assertEquals(ex.getCode(), 403); assertTrue(ex.getMessage().contains("Authorized Service Principals not allowed")); } }