diff options
Diffstat (limited to 'base/tps/src/org/dogtagpki/server/tps/rest')
9 files changed, 2568 insertions, 0 deletions
diff --git a/base/tps/src/org/dogtagpki/server/tps/rest/ActivityService.java b/base/tps/src/org/dogtagpki/server/tps/rest/ActivityService.java new file mode 100644 index 000000000..6002e7a94 --- /dev/null +++ b/base/tps/src/org/dogtagpki/server/tps/rest/ActivityService.java @@ -0,0 +1,177 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2013 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +package org.dogtagpki.server.tps.rest; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URLEncoder; +import java.util.Iterator; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.Request; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +import org.dogtagpki.server.tps.TPSSubsystem; +import org.dogtagpki.server.tps.dbs.ActivityDatabase; +import org.dogtagpki.server.tps.dbs.ActivityRecord; +import org.jboss.resteasy.plugins.providers.atom.Link; + +import com.netscape.certsrv.apps.CMS; +import com.netscape.certsrv.base.BadRequestException; +import com.netscape.certsrv.base.PKIException; +import com.netscape.certsrv.logging.ActivityCollection; +import com.netscape.certsrv.logging.ActivityData; +import com.netscape.certsrv.logging.ActivityResource; +import com.netscape.cms.servlet.base.PKIService; + +/** + * @author Endi S. Dewata + */ +public class ActivityService extends PKIService implements ActivityResource { + + @Context + private UriInfo uriInfo; + + @Context + private HttpHeaders headers; + + @Context + private Request request; + + @Context + private HttpServletRequest servletRequest; + + public ActivityService() { + CMS.debug("ActivityService.<init>()"); + } + + public ActivityData createActivityData(ActivityRecord activityRecord) { + + ActivityData activityData = new ActivityData(); + activityData.setID(activityRecord.getId()); + activityData.setTokenID(activityRecord.getTokenID()); + activityData.setUserID(activityRecord.getUserID()); + activityData.setIP(activityRecord.getIP()); + activityData.setOperation(activityRecord.getOperation()); + activityData.setResult(activityRecord.getResult()); + activityData.setMessage(activityRecord.getMessage()); + activityData.setDate(activityRecord.getDate()); + + String activityID = activityRecord.getId(); + try { + activityID = URLEncoder.encode(activityID, "UTF-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + + URI uri = uriInfo.getBaseUriBuilder().path(ActivityResource.class).path("{activityID}").build(activityID); + activityData.setLink(new Link("self", uri)); + + return activityData; + } + + public ActivityRecord createActivityRecord(ActivityData activityData) { + + ActivityRecord activityRecord = new ActivityRecord(); + activityRecord.setId(activityData.getID()); + activityRecord.setTokenID(activityData.getTokenID()); + activityRecord.setUserID(activityData.getUserID()); + activityRecord.setIP(activityData.getIP()); + activityRecord.setOperation(activityData.getOperation()); + activityRecord.setResult(activityData.getResult()); + activityRecord.setMessage(activityData.getMessage()); + activityRecord.setDate(activityData.getDate()); + + return activityRecord; + } + + @Override + public Response findActivities(String filter, Integer start, Integer size) { + + CMS.debug("ActivityService.findActivities()"); + + if (filter != null && filter.length() < MIN_FILTER_LENGTH) { + throw new BadRequestException("Filter is too short."); + } + + start = start == null ? 0 : start; + size = size == null ? DEFAULT_SIZE : size; + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + ActivityDatabase database = subsystem.getActivityDatabase(); + + Iterator<ActivityRecord> activities = database.findRecords(filter).iterator(); + + ActivityCollection response = new ActivityCollection(); + int i = 0; + + // skip to the start of the page + for ( ; i<start && activities.hasNext(); i++) activities.next(); + + // return entries up to the page size + for ( ; i<start+size && activities.hasNext(); i++) { + response.addEntry(createActivityData(activities.next())); + } + + // count the total entries + for ( ; activities.hasNext(); i++) activities.next(); + response.setTotal(i); + + if (start > 0) { + URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", Math.max(start-size, 0)).build(); + response.addLink(new Link("prev", uri)); + } + + if (start+size < i) { + URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", start+size).build(); + response.addLink(new Link("next", uri)); + } + + return createOKResponse(response); + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } + + @Override + public Response getActivity(String activityID) { + + if (activityID == null) throw new BadRequestException("Activity ID is null."); + + CMS.debug("ActivityService.getActivity(\"" + activityID + "\")"); + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + ActivityDatabase database = subsystem.getActivityDatabase(); + + return createOKResponse(createActivityData(database.getRecord(activityID))); + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } +} diff --git a/base/tps/src/org/dogtagpki/server/tps/rest/AuthenticatorService.java b/base/tps/src/org/dogtagpki/server/tps/rest/AuthenticatorService.java new file mode 100644 index 000000000..d862e261d --- /dev/null +++ b/base/tps/src/org/dogtagpki/server/tps/rest/AuthenticatorService.java @@ -0,0 +1,350 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2013 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +package org.dogtagpki.server.tps.rest; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URLEncoder; +import java.security.Principal; +import java.util.Iterator; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.Request; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +import org.dogtagpki.server.tps.TPSSubsystem; +import org.dogtagpki.server.tps.config.AuthenticatorDatabase; +import org.dogtagpki.server.tps.config.AuthenticatorRecord; +import org.jboss.resteasy.plugins.providers.atom.Link; + +import com.netscape.certsrv.apps.CMS; +import com.netscape.certsrv.base.BadRequestException; +import com.netscape.certsrv.base.ForbiddenException; +import com.netscape.certsrv.base.PKIException; +import com.netscape.certsrv.tps.authenticator.AuthenticatorCollection; +import com.netscape.certsrv.tps.authenticator.AuthenticatorData; +import com.netscape.certsrv.tps.authenticator.AuthenticatorResource; +import com.netscape.cms.servlet.base.PKIService; + +/** + * @author Endi S. Dewata + */ +public class AuthenticatorService extends PKIService implements AuthenticatorResource { + + @Context + private UriInfo uriInfo; + + @Context + private HttpHeaders headers; + + @Context + private Request request; + + @Context + private HttpServletRequest servletRequest; + + public AuthenticatorService() { + CMS.debug("AuthenticatorService.<init>()"); + } + + public AuthenticatorData createAuthenticatorData(AuthenticatorRecord authenticatorRecord) throws UnsupportedEncodingException { + + String authenticatorID = authenticatorRecord.getID(); + + AuthenticatorData authenticatorData = new AuthenticatorData(); + authenticatorData.setID(authenticatorID); + authenticatorData.setStatus(authenticatorRecord.getStatus()); + authenticatorData.setProperties(authenticatorRecord.getProperties()); + + authenticatorID = URLEncoder.encode(authenticatorID, "UTF-8"); + URI uri = uriInfo.getBaseUriBuilder().path(AuthenticatorResource.class).path("{authenticatorID}").build(authenticatorID); + authenticatorData.setLink(new Link("self", uri)); + + return authenticatorData; + } + + public AuthenticatorRecord createAuthenticatorRecord(AuthenticatorData authenticatorData) { + + AuthenticatorRecord authenticatorRecord = new AuthenticatorRecord(); + authenticatorRecord.setID(authenticatorData.getID()); + authenticatorRecord.setStatus(authenticatorData.getStatus()); + authenticatorRecord.setProperties(authenticatorData.getProperties()); + + return authenticatorRecord; + } + + @Override + public Response findAuthenticators(String filter, Integer start, Integer size) { + + CMS.debug("AuthenticatorService.findAuthenticators()"); + + if (filter != null && filter.length() < MIN_FILTER_LENGTH) { + throw new BadRequestException("Filter is too short."); + } + + start = start == null ? 0 : start; + size = size == null ? DEFAULT_SIZE : size; + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + AuthenticatorDatabase database = subsystem.getAuthenticatorDatabase(); + + Iterator<AuthenticatorRecord> authenticators = database.findRecords(filter).iterator(); + + AuthenticatorCollection response = new AuthenticatorCollection(); + int i = 0; + + // skip to the start of the page + for ( ; i<start && authenticators.hasNext(); i++) authenticators.next(); + + // return entries up to the page size + for ( ; i<start+size && authenticators.hasNext(); i++) { + response.addEntry(createAuthenticatorData(authenticators.next())); + } + + // count the total entries + for ( ; authenticators.hasNext(); i++) authenticators.next(); + response.setTotal(i); + + if (start > 0) { + URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", Math.max(start-size, 0)).build(); + response.addLink(new Link("prev", uri)); + } + + if (start+size < i) { + URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", start+size).build(); + response.addLink(new Link("next", uri)); + } + + return createOKResponse(response); + + } catch (PKIException e) { + throw e; + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } + + @Override + public Response getAuthenticator(String authenticatorID) { + + if (authenticatorID == null) throw new BadRequestException("Authenticator ID is null."); + + CMS.debug("AuthenticatorService.getAuthenticator(\"" + authenticatorID + "\")"); + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + AuthenticatorDatabase database = subsystem.getAuthenticatorDatabase(); + + return createOKResponse(createAuthenticatorData(database.getRecord(authenticatorID))); + + } catch (PKIException e) { + throw e; + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } + + @Override + public Response addAuthenticator(AuthenticatorData authenticatorData) { + + if (authenticatorData == null) throw new BadRequestException("Authenticator data is null."); + + CMS.debug("AuthenticatorService.addAuthenticator(\"" + authenticatorData.getID() + "\")"); + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + AuthenticatorDatabase database = subsystem.getAuthenticatorDatabase(); + + String status = authenticatorData.getStatus(); + Principal principal = servletRequest.getUserPrincipal(); + + if (status == null || database.requiresApproval() && !database.canApprove(principal)) { + // if status is unspecified or user doesn't have rights to approve, the entry is disabled + authenticatorData.setStatus("Disabled"); + } + + database.addRecord(authenticatorData.getID(), createAuthenticatorRecord(authenticatorData)); + authenticatorData = createAuthenticatorData(database.getRecord(authenticatorData.getID())); + + return createCreatedResponse(authenticatorData, authenticatorData.getLink().getHref()); + + } catch (PKIException e) { + throw e; + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } + + @Override + public Response updateAuthenticator(String authenticatorID, AuthenticatorData authenticatorData) { + + if (authenticatorID == null) throw new BadRequestException("Authenticator ID is null."); + if (authenticatorData == null) throw new BadRequestException("Authenticator data is null."); + + CMS.debug("AuthenticatorService.updateAuthenticator(\"" + authenticatorID + "\")"); + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + AuthenticatorDatabase database = subsystem.getAuthenticatorDatabase(); + + AuthenticatorRecord record = database.getRecord(authenticatorID); + + // only disabled authenticator can be updated + if (!"Disabled".equals(record.getStatus())) { + throw new ForbiddenException("Unable to update authenticator " + authenticatorID); + } + + // update status if specified + String status = authenticatorData.getStatus(); + if (status != null && !"Disabled".equals(status)) { + if (!"Enabled".equals(status)) { + throw new ForbiddenException("Invalid authenticator status: " + status); + } + + // if user doesn't have rights, set to pending + Principal principal = servletRequest.getUserPrincipal(); + if (database.requiresApproval() && !database.canApprove(principal)) { + status = "Pending_Approval"; + } + + // enable authenticator + record.setStatus(status); + } + + // update properties if specified + Map<String, String> properties = authenticatorData.getProperties(); + if (properties != null) { + record.setProperties(authenticatorData.getProperties()); + } + + database.updateRecord(authenticatorID, record); + + authenticatorData = createAuthenticatorData(database.getRecord(authenticatorID)); + + return createOKResponse(authenticatorData); + + } catch (PKIException e) { + throw e; + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } + + @Override + public Response changeAuthenticatorStatus(String authenticatorID, String action) { + + if (authenticatorID == null) throw new BadRequestException("Authenticator ID is null."); + if (action == null) throw new BadRequestException("Action is null."); + + CMS.debug("AuthenticatorService.changeAuthenticatorStatus(\"" + authenticatorID + "\")"); + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + AuthenticatorDatabase database = subsystem.getAuthenticatorDatabase(); + + AuthenticatorRecord record = database.getRecord(authenticatorID); + String status = record.getStatus(); + + if ("Disabled".equals(status)) { + if ("enable".equals(action)) { + status = "Enabled"; + } else { + throw new BadRequestException("Invalid action: " + action); + } + + } else if ("Enabled".equals(status)) { + if ("disable".equals(action)) { + status = "Disabled"; + } else { + throw new BadRequestException("Invalid action: " + action); + } + + } else if ("Pending_Approval".equals(status)) { + if ("approve".equals(action)) { + status = "Enabled"; + } else if ("reject".equals(action)) { + status = "Disabled"; + } else { + throw new BadRequestException("Invalid action: " + action); + } + + } else { + throw new PKIException("Invalid authenticator status: " + status); + } + + record.setStatus(status); + database.updateRecord(authenticatorID, record); + + AuthenticatorData authenticatorData = createAuthenticatorData(database.getRecord(authenticatorID)); + + return createOKResponse(authenticatorData); + + } catch (PKIException e) { + throw e; + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } + + @Override + public Response removeAuthenticator(String authenticatorID) { + + if (authenticatorID == null) throw new BadRequestException("Authenticator ID is null."); + + CMS.debug("AuthenticatorService.removeAuthenticator(\"" + authenticatorID + "\")"); + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + AuthenticatorDatabase database = subsystem.getAuthenticatorDatabase(); + + AuthenticatorRecord record = database.getRecord(authenticatorID); + String status = record.getStatus(); + + if (!"Disabled".equals(status)) { + throw new ForbiddenException("Unable to delete authenticator " + authenticatorID); + } + + database.removeRecord(authenticatorID); + + return createNoContentResponse(); + + } catch (PKIException e) { + throw e; + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } +} diff --git a/base/tps/src/org/dogtagpki/server/tps/rest/ConnectorService.java b/base/tps/src/org/dogtagpki/server/tps/rest/ConnectorService.java new file mode 100644 index 000000000..c281265ef --- /dev/null +++ b/base/tps/src/org/dogtagpki/server/tps/rest/ConnectorService.java @@ -0,0 +1,350 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2013 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +package org.dogtagpki.server.tps.rest; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URLEncoder; +import java.security.Principal; +import java.util.Iterator; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.Request; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +import org.dogtagpki.server.tps.TPSSubsystem; +import org.dogtagpki.server.tps.config.ConnectorDatabase; +import org.dogtagpki.server.tps.config.ConnectorRecord; +import org.jboss.resteasy.plugins.providers.atom.Link; + +import com.netscape.certsrv.apps.CMS; +import com.netscape.certsrv.base.BadRequestException; +import com.netscape.certsrv.base.ForbiddenException; +import com.netscape.certsrv.base.PKIException; +import com.netscape.certsrv.tps.connector.ConnectorCollection; +import com.netscape.certsrv.tps.connector.ConnectorData; +import com.netscape.certsrv.tps.connector.ConnectorResource; +import com.netscape.cms.servlet.base.PKIService; + +/** + * @author Endi S. Dewata + */ +public class ConnectorService extends PKIService implements ConnectorResource { + + @Context + private UriInfo uriInfo; + + @Context + private HttpHeaders headers; + + @Context + private Request request; + + @Context + private HttpServletRequest servletRequest; + + public ConnectorService() { + CMS.debug("ConnectorService.<init>()"); + } + + public ConnectorData createConnectorData(ConnectorRecord connectionRecord) throws UnsupportedEncodingException { + + String connectorID = connectionRecord.getID(); + + ConnectorData connectorData = new ConnectorData(); + connectorData.setID(connectorID); + connectorData.setStatus(connectionRecord.getStatus()); + connectorData.setProperties(connectionRecord.getProperties()); + + connectorID = URLEncoder.encode(connectorID, "UTF-8"); + URI uri = uriInfo.getBaseUriBuilder().path(ConnectorResource.class).path("{connectorID}").build(connectorID); + connectorData.setLink(new Link("self", uri)); + + return connectorData; + } + + public ConnectorRecord createConnectorRecord(ConnectorData connectorData) { + + ConnectorRecord connectorRecord = new ConnectorRecord(); + connectorRecord.setID(connectorData.getID()); + connectorRecord.setStatus(connectorData.getStatus()); + connectorRecord.setProperties(connectorData.getProperties()); + + return connectorRecord; + } + + @Override + public Response findConnectors(String filter, Integer start, Integer size) { + + CMS.debug("ConnectorService.findConnectors()"); + + if (filter != null && filter.length() < MIN_FILTER_LENGTH) { + throw new BadRequestException("Filter is too short."); + } + + start = start == null ? 0 : start; + size = size == null ? DEFAULT_SIZE : size; + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + ConnectorDatabase database = subsystem.getConnectorDatabase(); + + Iterator<ConnectorRecord> connections = database.findRecords(filter).iterator(); + + ConnectorCollection response = new ConnectorCollection(); + int i = 0; + + // skip to the start of the page + for ( ; i<start && connections.hasNext(); i++) connections.next(); + + // return entries up to the page size + for ( ; i<start+size && connections.hasNext(); i++) { + response.addEntry(createConnectorData(connections.next())); + } + + // count the total entries + for ( ; connections.hasNext(); i++) connections.next(); + response.setTotal(i); + + if (start > 0) { + URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", Math.max(start-size, 0)).build(); + response.addLink(new Link("prev", uri)); + } + + if (start+size < i) { + URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", start+size).build(); + response.addLink(new Link("next", uri)); + } + + return createOKResponse(response); + + } catch (PKIException e) { + throw e; + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } + + @Override + public Response getConnector(String connectorID) { + + if (connectorID == null) throw new BadRequestException("Connector ID is null."); + + CMS.debug("ConnectorService.getConnector(\"" + connectorID + "\")"); + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + ConnectorDatabase database = subsystem.getConnectorDatabase(); + + return createOKResponse(createConnectorData(database.getRecord(connectorID))); + + } catch (PKIException e) { + throw e; + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } + + @Override + public Response addConnector(ConnectorData connectorData) { + + if (connectorData == null) throw new BadRequestException("Connector data is null."); + + CMS.debug("ConnectorService.addConnector(\"" + connectorData.getID() + "\")"); + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + ConnectorDatabase database = subsystem.getConnectorDatabase(); + + String status = connectorData.getStatus(); + Principal principal = servletRequest.getUserPrincipal(); + + if (status == null || database.requiresApproval() && !database.canApprove(principal)) { + // if status is unspecified or user doesn't have rights to approve, the entry is disabled + connectorData.setStatus("Disabled"); + } + + database.addRecord(connectorData.getID(), createConnectorRecord(connectorData)); + connectorData = createConnectorData(database.getRecord(connectorData.getID())); + + return createCreatedResponse(connectorData, connectorData.getLink().getHref()); + + } catch (PKIException e) { + throw e; + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } + + @Override + public Response updateConnector(String connectorID, ConnectorData connectorData) { + + if (connectorID == null) throw new BadRequestException("Connector ID is null."); + if (connectorData == null) throw new BadRequestException("Connector data is null."); + + CMS.debug("ConnectorService.updateConnector(\"" + connectorID + "\")"); + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + ConnectorDatabase database = subsystem.getConnectorDatabase(); + + ConnectorRecord record = database.getRecord(connectorID); + + // only disabled connector can be updated + if (!"Disabled".equals(record.getStatus())) { + throw new ForbiddenException("Unable to update connector " + connectorID); + } + + // update status if specified + String status = connectorData.getStatus(); + if (status != null && !"Disabled".equals(status)) { + if (!"Enabled".equals(status)) { + throw new ForbiddenException("Invalid connector status: " + status); + } + + // if user doesn't have rights, set to pending + Principal principal = servletRequest.getUserPrincipal(); + if (database.requiresApproval() && !database.canApprove(principal)) { + status = "Pending_Approval"; + } + + // enable connector + record.setStatus(status); + } + + // update properties if specified + Map<String, String> properties = connectorData.getProperties(); + if (properties != null) { + record.setProperties(properties); + } + + database.updateRecord(connectorID, record); + + connectorData = createConnectorData(database.getRecord(connectorID)); + + return createOKResponse(connectorData); + + } catch (PKIException e) { + throw e; + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } + + @Override + public Response changeConnectorStatus(String connectorID, String action) { + + if (connectorID == null) throw new BadRequestException("Connector ID is null."); + if (action == null) throw new BadRequestException("Action is null."); + + CMS.debug("ConnectorService.changeConnectorStatus(\"" + connectorID + "\")"); + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + ConnectorDatabase database = subsystem.getConnectorDatabase(); + + ConnectorRecord record = database.getRecord(connectorID); + String status = record.getStatus(); + + if ("Disabled".equals(status)) { + if ("enable".equals(action)) { + status = "Enabled"; + } else { + throw new BadRequestException("Invalid action: " + action); + } + + } else if ("Enabled".equals(status)) { + if ("disable".equals(action)) { + status = "Disabled"; + } else { + throw new BadRequestException("Invalid action: " + action); + } + + } else if ("Pending_Approval".equals(status)) { + if ("approve".equals(action)) { + status = "Enabled"; + } else if ("reject".equals(action)) { + status = "Disabled"; + } else { + throw new BadRequestException("Invalid action: " + action); + } + + } else { + throw new PKIException("Invalid connector status: " + status); + } + + record.setStatus(status); + database.updateRecord(connectorID, record); + + ConnectorData connectorData = createConnectorData(database.getRecord(connectorID)); + + return createOKResponse(connectorData); + + } catch (PKIException e) { + throw e; + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } + + @Override + public Response removeConnector(String connectorID) { + + if (connectorID == null) throw new BadRequestException("Connector ID is null."); + + CMS.debug("ConnectorService.removeConnector(\"" + connectorID + "\")"); + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + ConnectorDatabase database = subsystem.getConnectorDatabase(); + + ConnectorRecord record = database.getRecord(connectorID); + String status = record.getStatus(); + + if (!"Disabled".equals(status)) { + throw new ForbiddenException("Unable to delete connector " + connectorID); + } + + database.removeRecord(connectorID); + + return createNoContentResponse(); + + } catch (PKIException e) { + throw e; + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } +} diff --git a/base/tps/src/org/dogtagpki/server/tps/rest/ProfileMappingService.java b/base/tps/src/org/dogtagpki/server/tps/rest/ProfileMappingService.java new file mode 100644 index 000000000..f3a6f2e38 --- /dev/null +++ b/base/tps/src/org/dogtagpki/server/tps/rest/ProfileMappingService.java @@ -0,0 +1,341 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2013 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +package org.dogtagpki.server.tps.rest; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URLEncoder; +import java.security.Principal; +import java.util.Iterator; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.Request; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +import org.dogtagpki.server.tps.TPSSubsystem; +import org.dogtagpki.server.tps.config.ProfileMappingDatabase; +import org.dogtagpki.server.tps.config.ProfileMappingRecord; +import org.jboss.resteasy.plugins.providers.atom.Link; + +import com.netscape.certsrv.apps.CMS; +import com.netscape.certsrv.base.BadRequestException; +import com.netscape.certsrv.base.ForbiddenException; +import com.netscape.certsrv.base.PKIException; +import com.netscape.certsrv.tps.profile.ProfileMappingCollection; +import com.netscape.certsrv.tps.profile.ProfileMappingData; +import com.netscape.certsrv.tps.profile.ProfileMappingResource; +import com.netscape.cms.servlet.base.PKIService; + +/** + * @author Endi S. Dewata + */ +public class ProfileMappingService extends PKIService implements ProfileMappingResource { + + @Context + private UriInfo uriInfo; + + @Context + private HttpHeaders headers; + + @Context + private Request request; + + @Context + private HttpServletRequest servletRequest; + + public ProfileMappingService() { + CMS.debug("ProfileMappingService.<init>()"); + } + + public ProfileMappingData createProfileMappingData(ProfileMappingRecord profileMappingRecord) throws UnsupportedEncodingException { + + String profileMappingID = profileMappingRecord.getID(); + + ProfileMappingData profileMappingData = new ProfileMappingData(); + profileMappingData.setID(profileMappingID); + profileMappingData.setStatus(profileMappingRecord.getStatus()); + profileMappingData.setProperties(profileMappingRecord.getProperties()); + + profileMappingID = URLEncoder.encode(profileMappingID, "UTF-8"); + URI uri = uriInfo.getBaseUriBuilder().path(ProfileMappingResource.class).path("{profileMappingID}").build(profileMappingID); + profileMappingData.setLink(new Link("self", uri)); + + return profileMappingData; + } + + public ProfileMappingRecord createProfileMappingRecord(ProfileMappingData profileMappingData) { + + ProfileMappingRecord profileMappingRecord = new ProfileMappingRecord(); + profileMappingRecord.setID(profileMappingData.getID()); + profileMappingRecord.setStatus(profileMappingData.getStatus()); + profileMappingRecord.setProperties(profileMappingData.getProperties()); + + return profileMappingRecord; + } + + @Override + public Response findProfileMappings(String filter, Integer start, Integer size) { + + CMS.debug("ProfileMappingService.findProfileMappings()"); + + if (filter != null && filter.length() < MIN_FILTER_LENGTH) { + throw new BadRequestException("Filter is too short."); + } + + start = start == null ? 0 : start; + size = size == null ? DEFAULT_SIZE : size; + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + ProfileMappingDatabase database = subsystem.getProfileMappingDatabase(); + + Iterator<ProfileMappingRecord> profileMappings = database.findRecords(filter).iterator(); + + ProfileMappingCollection response = new ProfileMappingCollection(); + int i = 0; + + // skip to the start of the page + for ( ; i<start && profileMappings.hasNext(); i++) profileMappings.next(); + + // return entries up to the page size + for ( ; i<start+size && profileMappings.hasNext(); i++) { + response.addEntry(createProfileMappingData(profileMappings.next())); + } + + // count the total entries + for ( ; profileMappings.hasNext(); i++) profileMappings.next(); + response.setTotal(i); + + if (start > 0) { + URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", Math.max(start-size, 0)).build(); + response.addLink(new Link("prev", uri)); + } + + if (start+size < i) { + URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", start+size).build(); + response.addLink(new Link("next", uri)); + } + + return createOKResponse(response); + + } catch (PKIException e) { + throw e; + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } + + @Override + public Response getProfileMapping(String profileMappingID) { + + CMS.debug("ProfileMappingService.getProfileMapping(\"" + profileMappingID + "\")"); + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + ProfileMappingDatabase database = subsystem.getProfileMappingDatabase(); + + return createOKResponse(createProfileMappingData(database.getRecord(profileMappingID))); + + } catch (PKIException e) { + throw e; + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } + + @Override + public Response addProfileMapping(ProfileMappingData profileMappingData) { + + CMS.debug("ProfileMappingService.addProfileMapping(\"" + profileMappingData.getID() + "\")"); + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + ProfileMappingDatabase database = subsystem.getProfileMappingDatabase(); + + String status = profileMappingData.getStatus(); + Principal principal = servletRequest.getUserPrincipal(); + + if (status == null || database.requiresApproval() && !database.canApprove(principal)) { + // if status is unspecified or user doesn't have rights to approve, the entry is disabled + profileMappingData.setStatus("Disabled"); + } + + database.addRecord(profileMappingData.getID(), createProfileMappingRecord(profileMappingData)); + profileMappingData = createProfileMappingData(database.getRecord(profileMappingData.getID())); + + return createCreatedResponse(profileMappingData, profileMappingData.getLink().getHref()); + + } catch (PKIException e) { + throw e; + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } + + @Override + public Response updateProfileMapping(String profileMappingID, ProfileMappingData profileMappingData) { + + CMS.debug("ProfileMappingService.updateProfileMapping(\"" + profileMappingID + "\")"); + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + ProfileMappingDatabase database = subsystem.getProfileMappingDatabase(); + + ProfileMappingRecord record = database.getRecord(profileMappingID); + + // only disabled profile mapping can be updated + if (!"Disabled".equals(record.getStatus())) { + throw new ForbiddenException("Unable to update profile mapping " + profileMappingID); + } + + // update status if specified + String status = profileMappingData.getStatus(); + if (status != null && !"Disabled".equals(status)) { + if (!"Enabled".equals(status)) { + throw new ForbiddenException("Invalid profile mapping status: " + status); + } + + // if user doesn't have rights, set to pending + Principal principal = servletRequest.getUserPrincipal(); + if (database.requiresApproval() && !database.canApprove(principal)) { + status = "Pending_Approval"; + } + + // enable profile mapping + record.setStatus(status); + } + + // update properties if specified + Map<String, String> properties = profileMappingData.getProperties(); + if (properties != null) { + record.setProperties(properties); + } + + database.updateRecord(profileMappingID, record); + + profileMappingData = createProfileMappingData(database.getRecord(profileMappingID)); + + return createOKResponse(profileMappingData); + + } catch (PKIException e) { + throw e; + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } + + @Override + public Response changeProfileMappingStatus(String profileMappingID, String action) { + + if (profileMappingID == null) throw new BadRequestException("Profile mapping ID is null."); + if (action == null) throw new BadRequestException("Action is null."); + + CMS.debug("ProfileMappingService.changeProfileMappingStatus(\"" + profileMappingID + "\")"); + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + ProfileMappingDatabase database = subsystem.getProfileMappingDatabase(); + + ProfileMappingRecord record = database.getRecord(profileMappingID); + String status = record.getStatus(); + + if ("Disabled".equals(status)) { + if ("enable".equals(action)) { + status = "Enabled"; + } else { + throw new BadRequestException("Invalid action: " + action); + } + + } else if ("Enabled".equals(status)) { + if ("disable".equals(action)) { + status = "Disabled"; + } else { + throw new BadRequestException("Invalid action: " + action); + } + + } else if ("Pending_Approval".equals(status)) { + if ("approve".equals(action)) { + status = "Enabled"; + } else if ("reject".equals(action)) { + status = "Disabled"; + } else { + throw new BadRequestException("Invalid action: " + action); + } + + } else { + throw new PKIException("Invalid profile mapping status: " + status); + } + + record.setStatus(status); + database.updateRecord(profileMappingID, record); + + ProfileMappingData profileMappingData = createProfileMappingData(database.getRecord(profileMappingID)); + + return createOKResponse(profileMappingData); + + } catch (PKIException e) { + throw e; + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } + + @Override + public Response removeProfileMapping(String profileMappingID) { + + CMS.debug("ProfileMappingService.removeProfileMapping(\"" + profileMappingID + "\")"); + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + ProfileMappingDatabase database = subsystem.getProfileMappingDatabase(); + + ProfileMappingRecord record = database.getRecord(profileMappingID); + String status = record.getStatus(); + + if (!"Disabled".equals(status)) { + throw new ForbiddenException("Unable to delete profile mapping " + profileMappingID); + } + + database.removeRecord(profileMappingID); + + return createNoContentResponse(); + + } catch (PKIException e) { + throw e; + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } +} diff --git a/base/tps/src/org/dogtagpki/server/tps/rest/ProfileService.java b/base/tps/src/org/dogtagpki/server/tps/rest/ProfileService.java new file mode 100644 index 000000000..e5bfd4663 --- /dev/null +++ b/base/tps/src/org/dogtagpki/server/tps/rest/ProfileService.java @@ -0,0 +1,351 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2013 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +package org.dogtagpki.server.tps.rest; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URLEncoder; +import java.security.Principal; +import java.util.Iterator; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.Request; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +import org.dogtagpki.server.tps.TPSSubsystem; +import org.dogtagpki.server.tps.config.ProfileDatabase; +import org.dogtagpki.server.tps.config.ProfileRecord; +import org.jboss.resteasy.plugins.providers.atom.Link; + +import com.netscape.certsrv.apps.CMS; +import com.netscape.certsrv.base.BadRequestException; +import com.netscape.certsrv.base.ForbiddenException; +import com.netscape.certsrv.base.PKIException; +import com.netscape.certsrv.tps.profile.ProfileCollection; +import com.netscape.certsrv.tps.profile.ProfileData; +import com.netscape.certsrv.tps.profile.ProfileResource; +import com.netscape.cms.servlet.base.PKIService; + +/** + * @author Endi S. Dewata + */ +public class ProfileService extends PKIService implements ProfileResource { + + @Context + private UriInfo uriInfo; + + @Context + private HttpHeaders headers; + + @Context + private Request request; + + @Context + private HttpServletRequest servletRequest; + + public ProfileService() { + CMS.debug("ProfileService.<init>()"); + } + + public ProfileData createProfileData(ProfileRecord profileRecord) throws UnsupportedEncodingException { + + String profileID = profileRecord.getID(); + + ProfileData profileData = new ProfileData(); + profileData.setID(profileID); + profileData.setStatus(profileRecord.getStatus()); + profileData.setProperties(profileRecord.getProperties()); + + profileID = URLEncoder.encode(profileID, "UTF-8"); + URI uri = uriInfo.getBaseUriBuilder().path(ProfileResource.class).path("{profileID}").build(profileID); + profileData.setLink(new Link("self", uri)); + + return profileData; + } + + public ProfileRecord createProfileRecord(ProfileData profileData) { + + ProfileRecord profileRecord = new ProfileRecord(); + profileRecord.setID(profileData.getID()); + profileRecord.setStatus(profileData.getStatus()); + profileRecord.setProperties(profileData.getProperties()); + + return profileRecord; + } + + @Override + public Response findProfiles(String filter, Integer start, Integer size) { + + CMS.debug("ProfileService.findProfiles()"); + + if (filter != null && filter.length() < MIN_FILTER_LENGTH) { + throw new BadRequestException("Filter is too short."); + } + + start = start == null ? 0 : start; + size = size == null ? DEFAULT_SIZE : size; + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + ProfileDatabase database = subsystem.getProfileDatabase(); + + Iterator<ProfileRecord> profiles = database.findRecords(filter).iterator(); + + ProfileCollection response = new ProfileCollection(); + int i = 0; + + // skip to the start of the page + for ( ; i<start && profiles.hasNext(); i++) profiles.next(); + + // return entries up to the page size + for ( ; i<start+size && profiles.hasNext(); i++) { + response.addEntry(createProfileData(profiles.next())); + } + + // count the total entries + for ( ; profiles.hasNext(); i++) profiles.next(); + response.setTotal(i); + + if (start > 0) { + URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", Math.max(start-size, 0)).build(); + response.addLink(new Link("prev", uri)); + } + + if (start+size < i) { + URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", start+size).build(); + response.addLink(new Link("next", uri)); + } + + return createOKResponse(response); + + } catch (PKIException e) { + throw e; + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } + + @Override + public Response getProfile(String profileID) { + + if (profileID == null) throw new BadRequestException("Profile ID is null."); + + CMS.debug("ProfileService.getProfile(\"" + profileID + "\")"); + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + ProfileDatabase database = subsystem.getProfileDatabase(); + + return createOKResponse(createProfileData(database.getRecord(profileID))); + + } catch (PKIException e) { + throw e; + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } + + @Override + public Response addProfile(ProfileData profileData) { + + if (profileData == null) throw new BadRequestException("Profile data is null."); + + CMS.debug("ProfileService.addProfile(\"" + profileData.getID() + "\")"); + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + ProfileDatabase database = subsystem.getProfileDatabase(); + + String status = profileData.getStatus(); + Principal principal = servletRequest.getUserPrincipal(); + + if (status == null || database.requiresApproval() && !database.canApprove(principal)) { + // if status is unspecified or user doesn't have rights to approve, the entry is disabled + profileData.setStatus("Disabled"); + } + + database.addRecord(profileData.getID(), createProfileRecord(profileData)); + + profileData = createProfileData(database.getRecord(profileData.getID())); + + return createCreatedResponse(profileData, profileData.getLink().getHref()); + + } catch (PKIException e) { + throw e; + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } + + @Override + public Response updateProfile(String profileID, ProfileData profileData) { + + if (profileID == null) throw new BadRequestException("Profile ID is null."); + if (profileData == null) throw new BadRequestException("Profile data is null."); + + CMS.debug("ProfileService.updateProfile(\"" + profileID + "\")"); + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + ProfileDatabase database = subsystem.getProfileDatabase(); + + ProfileRecord record = database.getRecord(profileID); + + // only disabled profile can be updated + if (!"Disabled".equals(record.getStatus())) { + throw new ForbiddenException("Unable to update profile " + profileID); + } + + // update status if specified + String status = profileData.getStatus(); + if (status != null && !"Disabled".equals(status)) { + if (!"Enabled".equals(status)) { + throw new ForbiddenException("Invalid profile status: " + status); + } + + // if user doesn't have rights, set to pending + Principal principal = servletRequest.getUserPrincipal(); + if (database.requiresApproval() && !database.canApprove(principal)) { + status = "Pending_Approval"; + } + + // enable profile + record.setStatus(status); + } + + // update properties if specified + Map<String, String> properties = profileData.getProperties(); + if (properties != null) { + record.setProperties(properties); + } + + database.updateRecord(profileID, record); + + profileData = createProfileData(database.getRecord(profileID)); + + return createOKResponse(profileData); + + } catch (PKIException e) { + throw e; + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } + + @Override + public Response changeProfileStatus(String profileID, String action) { + + if (profileID == null) throw new BadRequestException("Profile ID is null."); + if (action == null) throw new BadRequestException("Action is null."); + + CMS.debug("ProfileService.changeProfileStatus(\"" + profileID + "\")"); + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + ProfileDatabase database = subsystem.getProfileDatabase(); + + ProfileRecord record = database.getRecord(profileID); + String status = record.getStatus(); + + if ("Disabled".equals(status)) { + if ("enable".equals(action)) { + status = "Enabled"; + } else { + throw new BadRequestException("Invalid action: " + action); + } + + } else if ("Enabled".equals(status)) { + if ("disable".equals(action)) { + status = "Disabled"; + } else { + throw new BadRequestException("Invalid action: " + action); + } + + } else if ("Pending_Approval".equals(status)) { + if ("approve".equals(action)) { + status = "Enabled"; + } else if ("reject".equals(action)) { + status = "Disabled"; + } else { + throw new BadRequestException("Invalid action: " + action); + } + + } else { + throw new PKIException("Invalid profile status: " + status); + } + + record.setStatus(status); + database.updateRecord(profileID, record); + + ProfileData profileData = createProfileData(database.getRecord(profileID)); + + return createOKResponse(profileData); + + } catch (PKIException e) { + throw e; + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } + + @Override + public Response removeProfile(String profileID) { + + if (profileID == null) throw new BadRequestException("Profile ID is null."); + + CMS.debug("ProfileService.removeProfile(\"" + profileID + "\")"); + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + ProfileDatabase database = subsystem.getProfileDatabase(); + + ProfileRecord record = database.getRecord(profileID); + String status = record.getStatus(); + + if (!"Disabled".equals(status)) { + throw new ForbiddenException("Unable to delete profile " + profileID); + } + + database.removeRecord(profileID); + + return createNoContentResponse(); + + } catch (PKIException e) { + throw e; + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } +} diff --git a/base/tps/src/org/dogtagpki/server/tps/rest/TPSApplication.java b/base/tps/src/org/dogtagpki/server/tps/rest/TPSApplication.java new file mode 100644 index 000000000..70c8afd02 --- /dev/null +++ b/base/tps/src/org/dogtagpki/server/tps/rest/TPSApplication.java @@ -0,0 +1,105 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2013 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package org.dogtagpki.server.tps.rest; + +import java.util.LinkedHashSet; +import java.util.Set; + +import javax.ws.rs.core.Application; + +import org.dogtagpki.server.rest.ACLInterceptor; +import org.dogtagpki.server.rest.AccountService; +import org.dogtagpki.server.rest.AuditService; +import org.dogtagpki.server.rest.AuthMethodInterceptor; +import org.dogtagpki.server.rest.GroupService; +import org.dogtagpki.server.rest.PKIExceptionMapper; +import org.dogtagpki.server.rest.MessageFormatInterceptor; +import org.dogtagpki.server.rest.SelfTestService; +import org.dogtagpki.server.rest.SystemCertService; +import org.dogtagpki.server.rest.UserService; +import org.dogtagpki.server.tps.config.ConfigService; + +/** + * @author Endi S. Dewata <edewata@redhat.com> + */ +public class TPSApplication extends Application { + + private Set<Object> singletons = new LinkedHashSet<Object>(); + private Set<Class<?>> classes = new LinkedHashSet<Class<?>>(); + + public TPSApplication() { + + // account + classes.add(AccountService.class); + + // audit + classes.add(AuditService.class); + + // installer + classes.add(TPSInstallerService.class); + + // user and group management + classes.add(GroupService.class); + classes.add(UserService.class); + + // system certs + classes.add(SystemCertService.class); + + // activities + classes.add(ActivityService.class); + + // authenticators + classes.add(AuthenticatorService.class); + + // certificates + classes.add(TPSCertService.class); + + // config + classes.add(ConfigService.class); + + // connections + classes.add(ConnectorService.class); + + // profiles + classes.add(ProfileService.class); + classes.add(ProfileMappingService.class); + + // selftests + classes.add(SelfTestService.class); + + // tokens + classes.add(TokenService.class); + + // exception mapper + classes.add(PKIExceptionMapper.class); + + // interceptors + singletons.add(new AuthMethodInterceptor()); + singletons.add(new ACLInterceptor()); + singletons.add(new MessageFormatInterceptor()); + } + + public Set<Class<?>> getClasses() { + return classes; + } + + public Set<Object> getSingletons() { + return singletons; + } + +} diff --git a/base/tps/src/org/dogtagpki/server/tps/rest/TPSCertService.java b/base/tps/src/org/dogtagpki/server/tps/rest/TPSCertService.java new file mode 100644 index 000000000..75314cd5d --- /dev/null +++ b/base/tps/src/org/dogtagpki/server/tps/rest/TPSCertService.java @@ -0,0 +1,179 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2013 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +package org.dogtagpki.server.tps.rest; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URLEncoder; +import java.util.Iterator; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.Request; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +import org.dogtagpki.server.tps.TPSSubsystem; +import org.dogtagpki.server.tps.dbs.TPSCertDatabase; +import org.dogtagpki.server.tps.dbs.TPSCertRecord; +import org.jboss.resteasy.plugins.providers.atom.Link; + +import com.netscape.certsrv.apps.CMS; +import com.netscape.certsrv.base.BadRequestException; +import com.netscape.certsrv.base.PKIException; +import com.netscape.certsrv.tps.cert.TPSCertCollection; +import com.netscape.certsrv.tps.cert.TPSCertData; +import com.netscape.certsrv.tps.cert.TPSCertResource; +import com.netscape.cms.servlet.base.PKIService; + +/** + * @author Endi S. Dewata + */ +public class TPSCertService extends PKIService implements TPSCertResource { + + @Context + private UriInfo uriInfo; + + @Context + private HttpHeaders headers; + + @Context + private Request request; + + @Context + private HttpServletRequest servletRequest; + + public TPSCertService() { + System.out.println("TPSCertService.<init>()"); + } + + public TPSCertData createCertData(TPSCertRecord certRecord) { + + TPSCertData certData = new TPSCertData(); + certData.setID(certRecord.getId()); + certData.setSerialNumber(certRecord.getSerialNumber()); + certData.setSubject(certRecord.getSubject()); + certData.setTokenID(certRecord.getTokenID()); + certData.setKeyType(certRecord.getKeyType()); + certData.setStatus(certRecord.getStatus()); + certData.setUserID(certRecord.getUserID()); + certData.setCreateTime(certRecord.getCreateTime()); + certData.setModifyTime(certRecord.getModifyTime()); + + String certID = certRecord.getId(); + try { + certID = URLEncoder.encode(certID, "UTF-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + + URI uri = uriInfo.getBaseUriBuilder().path(TPSCertResource.class).path("{certID}").build(certID); + certData.setLink(new Link("self", uri)); + + return certData; + } + + public TPSCertRecord createCertRecord(TPSCertData certData) { + + TPSCertRecord certRecord = new TPSCertRecord(); + certRecord.setId(certData.getID()); + certRecord.setSerialNumber(certData.getSerialNumber()); + certRecord.setSubject(certData.getSubject()); + certRecord.setTokenID(certData.getTokenID()); + certRecord.setKeyType(certData.getKeyType()); + certRecord.setStatus(certData.getStatus()); + certRecord.setUserID(certData.getUserID()); + certRecord.setCreateTime(certData.getCreateTime()); + certRecord.setModifyTime(certData.getModifyTime()); + + return certRecord; + } + + @Override + public Response findCerts(String filter, Integer start, Integer size) { + + System.out.println("TPSCertService.findCerts()"); + + if (filter != null && filter.length() < MIN_FILTER_LENGTH) { + throw new BadRequestException("Filter is too short."); + } + + start = start == null ? 0 : start; + size = size == null ? DEFAULT_SIZE : size; + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + TPSCertDatabase database = subsystem.getCertDatabase(); + + Iterator<TPSCertRecord> activities = database.findRecords(filter).iterator(); + + TPSCertCollection response = new TPSCertCollection(); + int i = 0; + + // skip to the start of the page + for ( ; i<start && activities.hasNext(); i++) activities.next(); + + // return entries up to the page size + for ( ; i<start+size && activities.hasNext(); i++) { + response.addEntry(createCertData(activities.next())); + } + + // count the total entries + for ( ; activities.hasNext(); i++) activities.next(); + response.setTotal(i); + + if (start > 0) { + URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", Math.max(start-size, 0)).build(); + response.addLink(new Link("prev", uri)); + } + + if (start+size < i) { + URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", start+size).build(); + response.addLink(new Link("next", uri)); + } + + return createOKResponse(response); + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } + + @Override + public Response getCert(String certID) { + + if (certID == null) throw new BadRequestException("Certificate ID is null."); + + System.out.println("TPSCertService.getCert(\"" + certID + "\")"); + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + TPSCertDatabase database = subsystem.getCertDatabase(); + + return createOKResponse(createCertData(database.getRecord(certID))); + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } +} diff --git a/base/tps/src/org/dogtagpki/server/tps/rest/TPSInstallerService.java b/base/tps/src/org/dogtagpki/server/tps/rest/TPSInstallerService.java new file mode 100644 index 000000000..9c4943b9f --- /dev/null +++ b/base/tps/src/org/dogtagpki/server/tps/rest/TPSInstallerService.java @@ -0,0 +1,153 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2014 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package org.dogtagpki.server.tps.rest; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Collection; + +import org.dogtagpki.server.rest.SystemConfigService; +import org.dogtagpki.server.tps.installer.TPSInstaller; + +import com.netscape.certsrv.apps.CMS; +import com.netscape.certsrv.base.BadRequestException; +import com.netscape.certsrv.base.EBaseException; +import com.netscape.certsrv.base.PKIException; +import com.netscape.certsrv.system.ConfigurationRequest; +import com.netscape.certsrv.system.SystemCertData; +import com.netscape.cms.servlet.csadmin.ConfigurationUtils; + +/** + * @author alee + * + */ +public class TPSInstallerService extends SystemConfigService { + + + public TPSInstallerService() throws EBaseException { + } + + @Override + public void configureSubsystem(ConfigurationRequest request, + Collection<String> certList, String token, String domainXML) { + + super.configureSubsystem(request, certList, token, domainXML); + + // get subsystem certificate nickname + String nickname = null; + for (SystemCertData cert : request.getSystemCerts()) { + if (cert.getTag().equals("subsystem")) { + nickname = cert.getNickname(); + break; + } + } + + if (nickname == null || nickname.isEmpty()) { + throw new BadRequestException("No nickname provided for subsystem certificate"); + } + + // CA Info Panel + configureCAConnector(request, nickname); + + // TKS Info Panel + configureTKSConnector(request, nickname); + + //DRM Info Panel + configureKRAConnector(request, nickname); + + //AuthDBPanel + ConfigurationUtils.updateAuthdbInfo(request.getAuthdbBaseDN(), + request.getAuthdbHost(), request.getAuthdbPort(), + request.getAuthdbSecureConn()); + } + + public void configureCAConnector(ConfigurationRequest request, String nickname) { + + // TODO: get installer from session + TPSInstaller installer = new TPSInstaller(); + installer.configureCAConnector(request.getCaUri(), nickname); + } + + public void configureTKSConnector(ConfigurationRequest request, String nickname) { + + // TODO: get installer from session + TPSInstaller installer = new TPSInstaller(); + installer.configureTKSConnector(request.getTksUri(), nickname); + } + + public void configureKRAConnector(ConfigurationRequest request, String nickname) { + + boolean keygen = request.getEnableServerSideKeyGen().equalsIgnoreCase("true"); + + // TODO: get installer from session + TPSInstaller installer = new TPSInstaller(); + installer.configureKRAConnector(keygen, request.getKraUri(), nickname); + } + + @Override + public void configureDatabase(ConfigurationRequest request) { + + super.configureDatabase(request); + + cs.putString("tokendb.activityBaseDN", "ou=Activities," + request.getBaseDN()); + cs.putString("tokendb.baseDN", "ou=Tokens," + request.getBaseDN()); + cs.putString("tokendb.certBaseDN", "ou=Certificates," + request.getBaseDN()); + cs.putString("tokendb.userBaseDN", request.getBaseDN()); + cs.putString("tokendb.hostport", request.getDsHost() + ":" + request.getDsPort()); + } + + @Override + public void finalizeConfiguration(ConfigurationRequest request) { + + super.finalizeConfiguration(request); + + try { + ConfigurationUtils.addProfilesToTPSUser(request.getAdminUID()); + + URI secdomainURI = new URI(request.getSecurityDomainUri()); + + // register TPS with CA + URI caURI = request.getCaUri(); + ConfigurationUtils.registerUser(secdomainURI, caURI, "ca"); + + // register TPS with TKS + URI tksURI = request.getTksUri(); + ConfigurationUtils.registerUser(secdomainURI, tksURI, "tks"); + + if (request.getEnableServerSideKeyGen().equalsIgnoreCase("true")) { + URI kraURI = request.getKraUri(); + ConfigurationUtils.registerUser(secdomainURI, kraURI, "kra"); + String transportCert = ConfigurationUtils.getTransportCert(secdomainURI, kraURI); + ConfigurationUtils.exportTransportCert(secdomainURI, tksURI, transportCert); + } + + // generate shared secret from the tks + ConfigurationUtils.getSharedSecret( + tksURI.getHost(), + tksURI.getPort(), + Boolean.getBoolean(request.getImportSharedSecret())); + + } catch (URISyntaxException e) { + throw new BadRequestException("Invalid URI for CA, TKS or KRA"); + + } catch (Exception e) { + CMS.debug(e); + throw new PKIException("Errors in registering TPS to CA, TKS or KRA: " + e); + } + } +} diff --git a/base/tps/src/org/dogtagpki/server/tps/rest/TokenService.java b/base/tps/src/org/dogtagpki/server/tps/rest/TokenService.java new file mode 100644 index 000000000..a58447089 --- /dev/null +++ b/base/tps/src/org/dogtagpki/server/tps/rest/TokenService.java @@ -0,0 +1,562 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2013 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +package org.dogtagpki.server.tps.rest; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URLEncoder; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.Request; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +import org.dogtagpki.server.tps.TPSSubsystem; +import org.dogtagpki.server.tps.dbs.ActivityDatabase; +import org.dogtagpki.server.tps.dbs.TokenDatabase; +import org.dogtagpki.server.tps.dbs.TokenRecord; +import org.jboss.resteasy.plugins.providers.atom.Link; + +import com.netscape.certsrv.apps.CMS; +import com.netscape.certsrv.base.BadRequestException; +import com.netscape.certsrv.base.IConfigStore; +import com.netscape.certsrv.base.PKIException; +import com.netscape.certsrv.tps.token.TokenCollection; +import com.netscape.certsrv.tps.token.TokenData; +import com.netscape.certsrv.tps.token.TokenResource; +import com.netscape.certsrv.tps.token.TokenStatus; +import com.netscape.cms.servlet.base.PKIService; + +/** + * @author Endi S. Dewata + */ +public class TokenService extends PKIService implements TokenResource { + + @Context + private UriInfo uriInfo; + + @Context + private HttpHeaders headers; + + @Context + private Request request; + + @Context + private HttpServletRequest servletRequest; + + public Map<TokenStatus, Collection<TokenStatus>> transitions = new HashMap<TokenStatus, Collection<TokenStatus>>(); + + public TokenService() throws Exception { + CMS.debug("TokenService.<init>()"); + IConfigStore configStore = CMS.getConfigStore(); + + // load allowed token state transitions + CMS.debug("TokenService: allowed transitions:"); + + for (String transition : configStore.getString("tokendb.allowedTransitions").split(",")) { + String states[] = transition.split(":"); + TokenStatus fromState = TokenStatus.fromInt(Integer.valueOf(states[0])); + TokenStatus toState = TokenStatus.fromInt(Integer.valueOf(states[1])); + CMS.debug("TokenService: - " + fromState + " to " + toState); + + Collection<TokenStatus> nextStates = transitions.get(fromState); + if (nextStates == null) { + nextStates = new HashSet<TokenStatus>(); + transitions.put(fromState, nextStates); + } + nextStates.add(toState); + } + + } + + public TokenStatus getTokenStatus(TokenRecord tokenRecord) { + String status = tokenRecord.getStatus(); + + if ("uninitialized".equals(status)) { + return TokenStatus.UNINITIALIZED; + + } else if ("active".equals(status)) { + return TokenStatus.ACTIVE; + + } else if ("lost".equals(status)) { + String reason = tokenRecord.getReason(); + + if ("keyCompromise".equals(reason)) { + return TokenStatus.PERM_LOST; + + } else if ("destroyed".equals(reason)) { + return TokenStatus.DAMAGED; + + } else if ("onHold".equals(reason)) { + return TokenStatus.TEMP_LOST; + } + + } else if ("terminated".equals(status)) { + return TokenStatus.TERMINATED; + } + + return TokenStatus.PERM_LOST; + } + + public void setTokenStatus(TokenRecord tokenRecord, TokenStatus tokenState) throws Exception { + TPSSubsystem tps = (TPSSubsystem) CMS.getSubsystem(TPSSubsystem.ID); + + switch (tokenState) { + case UNINITIALIZED: + tokenRecord.setStatus("uninitialized"); + tokenRecord.setReason(null); + break; + case ACTIVE: + String origStatus = tokenRecord.getStatus(); + String origReason = tokenRecord.getReason(); + if (origStatus.equalsIgnoreCase("lost") && + origReason.equalsIgnoreCase("onHold")) { + //unrevoke certs + tps.tdb.unRevokeCertsByCUID(tokenRecord.getId()); + } + + tokenRecord.setStatus("active"); + tokenRecord.setReason(null); + break; + case PERM_LOST: + case TEMP_LOST_PERM_LOST: + tokenRecord.setStatus("lost"); + tokenRecord.setReason("keyCompromise"); + + //revoke certs + tps.tdb.revokeCertsByCUID(tokenRecord.getId(), "keyCompromise"); + break; + case DAMAGED: + tokenRecord.setStatus("lost"); + tokenRecord.setReason("destroyed"); + + //revoke certs + tps.tdb.revokeCertsByCUID(tokenRecord.getId(), "destroyed"); + + break; + case TEMP_LOST: + tokenRecord.setStatus("lost"); + tokenRecord.setReason("onHold"); + + // put certs onHold + tps.tdb.revokeCertsByCUID(tokenRecord.getId(), "onHold"); + break; + case TERMINATED: + String reason = "keyCompromise"; + String origStatus2 = tokenRecord.getStatus(); + String origReason2 = tokenRecord.getReason(); + // temp token looks at "onHold" + if (origStatus2.equalsIgnoreCase("lost") && + origReason2.equalsIgnoreCase("onHold")) { + reason = "onHold"; + } + tokenRecord.setStatus("terminated"); + tokenRecord.setReason(reason); + + //revoke certs + tps.tdb.revokeCertsByCUID(tokenRecord.getId(), reason) ; + break; + default: + throw new PKIException("Unsupported token state: " + tokenState); + } + + } + + public TokenData createTokenData(TokenRecord tokenRecord) { + + TokenData tokenData = new TokenData(); + tokenData.setID(tokenRecord.getId()); + tokenData.setTokenID(tokenRecord.getId()); + tokenData.setUserID(tokenRecord.getUserID()); + tokenData.setType(tokenRecord.getType()); + tokenData.setStatus(getTokenStatus(tokenRecord)); + tokenData.setAppletID(tokenRecord.getAppletID()); + tokenData.setKeyInfo(tokenRecord.getKeyInfo()); + tokenData.setPolicy(tokenRecord.getPolicy()); + tokenData.setCreateTimestamp(tokenRecord.getCreateTimestamp()); + tokenData.setModifyTimestamp(tokenRecord.getModifyTimestamp()); + + String tokenID = tokenRecord.getId(); + try { + tokenID = URLEncoder.encode(tokenID, "UTF-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + + URI uri = uriInfo.getBaseUriBuilder().path(TokenResource.class).path("{tokenID}").build(tokenID); + tokenData.setLink(new Link("self", uri)); + + return tokenData; + } + + public TokenRecord createTokenRecord(TokenData tokenData) throws Exception { + + TokenRecord tokenRecord = new TokenRecord(); + tokenRecord.setId(tokenData.getID()); + tokenRecord.setUserID(tokenData.getUserID()); + tokenRecord.setType(tokenData.getType()); + setTokenStatus(tokenRecord, tokenData.getStatus()); + tokenRecord.setAppletID(tokenData.getAppletID()); + tokenRecord.setKeyInfo(tokenData.getKeyInfo()); + tokenRecord.setPolicy(tokenData.getPolicy()); + tokenRecord.setCreateTimestamp(tokenData.getCreateTimestamp()); + tokenRecord.setModifyTimestamp(tokenData.getModifyTimestamp()); + + return tokenRecord; + } + + @Override + public Response findTokens(String filter, Integer start, Integer size) { + + CMS.debug("TokenService.findTokens()"); + + if (filter != null && filter.length() < MIN_FILTER_LENGTH) { + throw new BadRequestException("Filter is too short."); + } + + start = start == null ? 0 : start; + size = size == null ? DEFAULT_SIZE : size; + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + TokenDatabase database = subsystem.getTokenDatabase(); + + Iterator<TokenRecord> tokens = database.findRecords(filter).iterator(); + + TokenCollection response = new TokenCollection(); + int i = 0; + + // skip to the start of the page + for ( ; i<start && tokens.hasNext(); i++) tokens.next(); + + // return entries up to the page size + for ( ; i<start+size && tokens.hasNext(); i++) { + response.addEntry(createTokenData(tokens.next())); + } + + // count the total entries + for ( ; tokens.hasNext(); i++) tokens.next(); + response.setTotal(i); + + if (start > 0) { + URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", Math.max(start-size, 0)).build(); + response.addLink(new Link("prev", uri)); + } + + if (start+size < i) { + URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", start+size).build(); + response.addLink(new Link("next", uri)); + } + + return createOKResponse(response); + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } + + @Override + public Response getToken(String tokenID) { + + if (tokenID == null) throw new BadRequestException("Token ID is null."); + + CMS.debug("TokenService.getToken(\"" + tokenID + "\")"); + + try { + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + TokenDatabase database = subsystem.getTokenDatabase(); + + return createOKResponse(createTokenData(database.getRecord(tokenID))); + + } catch (Exception e) { + e.printStackTrace(); + throw new PKIException(e.getMessage()); + } + } + + @Override + public Response addToken(TokenData tokenData) { + + if (tokenData == null) throw new BadRequestException("Token data is null."); + + String tokenID = tokenData.getTokenID(); + CMS.debug("TokenService.addToken(\"" + tokenID + "\")"); + + String remoteUser = servletRequest.getRemoteUser(); + String ipAddress = servletRequest.getRemoteAddr(); + + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + TokenRecord tokenRecord = null; + String msg = "add token"; + + try { + TokenDatabase database = subsystem.getTokenDatabase(); + + // new tokens are uninitialized when created + tokenData.setStatus(TokenStatus.UNINITIALIZED); + + tokenRecord = createTokenRecord(tokenData); + tokenRecord.setId(tokenID); + database.addRecord(tokenID, tokenRecord); + subsystem.tdb.tdbActivity(ActivityDatabase.OP_ADD, tokenRecord, + ipAddress, msg, "success", remoteUser); + tokenData = createTokenData(database.getRecord(tokenID)); + + return createCreatedResponse(tokenData, tokenData.getLink().getHref()); + + } catch (Exception e) { + e.printStackTrace(); + subsystem.tdb.tdbActivity(ActivityDatabase.OP_ADD, tokenRecord, + ipAddress, msg, "failure", remoteUser); + msg = msg + ":" + e; + + throw new PKIException(msg); + } + } + + @Override + public Response replaceToken(String tokenID, TokenData tokenData) { + + if (tokenID == null) throw new BadRequestException("Token ID is null."); + if (tokenData == null) throw new BadRequestException("Token data is null."); + + CMS.debug("TokenService.replaceToken(\"" + tokenID + "\")"); + + String remoteUser = servletRequest.getRemoteUser(); + String ipAddress = servletRequest.getRemoteAddr(); + + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + TokenRecord tokenRecord = null; + String msg = "replace token"; + try { + TokenDatabase database = subsystem.getTokenDatabase(); + + tokenRecord = database.getRecord(tokenID); + tokenRecord.setUserID(remoteUser); + tokenRecord.setType(tokenData.getType()); + tokenRecord.setAppletID(tokenData.getAppletID()); + tokenRecord.setKeyInfo(tokenData.getKeyInfo()); + tokenRecord.setPolicy(tokenData.getPolicy()); + database.updateRecord(tokenID, tokenRecord); + subsystem.tdb.tdbActivity(ActivityDatabase.OP_DO_TOKEN, tokenRecord, + ipAddress, msg, "success", remoteUser); + + tokenData = createTokenData(database.getRecord(tokenID)); + + return createOKResponse(tokenData); + + } catch (Exception e) { + e.printStackTrace(); + subsystem.tdb.tdbActivity(ActivityDatabase.OP_DO_TOKEN, tokenRecord, + ipAddress, msg, "failure", + remoteUser); + msg = msg + ":" + e; + + throw new PKIException(msg); + } + } + + @Override + public Response modifyToken(String tokenID, TokenData tokenData) { + + if (tokenID == null) throw new BadRequestException("Token ID is null."); + if (tokenData == null) throw new BadRequestException("Token data is null."); + + CMS.debug("TokenService.modifyToken(\"" + tokenID + "\")"); + + String remoteUser = servletRequest.getRemoteUser(); + String ipAddress = servletRequest.getRemoteAddr(); + + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + TokenRecord tokenRecord = null; + String msg = "modify token"; + try { + TokenDatabase database = subsystem.getTokenDatabase(); + + // get existing record + tokenRecord = database.getRecord(tokenID); + + // update user ID if specified + String userID = tokenData.getUserID(); + if (userID != null) { + if (userID.equals("")) { // remove value if empty + tokenRecord.setUserID(null); + } else { // otherwise replace value + tokenRecord.setUserID(userID); + } + } + + // update type if specified + String type = tokenData.getType(); + if (type != null) { + if (type.equals("")) { // remove value if empty + tokenRecord.setType(null); + } else { // otherwise replace value + tokenRecord.setType(type); + } + } + + // update applet ID if specified + String appletID = tokenData.getAppletID(); + if (appletID != null) { + if (appletID.equals("")) { // remove value if empty + tokenRecord.setAppletID(null); + } else { // otherwise replace value + tokenRecord.setAppletID(appletID); + } + } + + // update key info if specified + String keyInfo = tokenData.getKeyInfo(); + if (keyInfo != null) { + if (keyInfo.equals("")) { // remove value if empty + tokenRecord.setKeyInfo(null); + } else { // otherwise replace value + tokenRecord.setKeyInfo(keyInfo); + } + } + + // update policy if specified + String policy = tokenData.getPolicy(); + if (policy != null) { + if (policy.equals("")) { // remove value if empty + tokenRecord.setPolicy(null); + } else { //otherwise replace value + tokenRecord.setPolicy(policy); + } + } + + database.updateRecord(tokenID, tokenRecord); + subsystem.tdb.tdbActivity(ActivityDatabase.OP_DO_TOKEN, tokenRecord, + ipAddress, msg, "success", remoteUser); + + tokenData = createTokenData(database.getRecord(tokenID)); + + return createOKResponse(tokenData); + + } catch (Exception e) { + e.printStackTrace(); + subsystem.tdb.tdbActivity(ActivityDatabase.OP_DO_TOKEN, tokenRecord, + ipAddress, msg, "failure", + remoteUser); + msg = msg + ":" + e; + + throw new PKIException(msg); + } + } + + @Override + public Response changeTokenStatus(String tokenID, TokenStatus tokenStatus) { + + if (tokenID == null) throw new BadRequestException("Token ID is null."); + if (tokenStatus == null) throw new BadRequestException("Token state is null."); + + CMS.debug("TokenService.changeTokenStatus(\"" + tokenID + "\", \"" + tokenStatus + "\")"); + + String remoteUser = servletRequest.getRemoteUser(); + String ipAddress = servletRequest.getRemoteAddr(); + + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + TokenRecord tokenRecord = null; + String msg = ""; + try { + TokenDatabase database = subsystem.getTokenDatabase(); + + tokenRecord = database.getRecord(tokenID); + TokenStatus currentTokenStatus = getTokenStatus(tokenRecord); + CMS.debug("TokenService.changeTokenStatus(): current status: " + currentTokenStatus); + msg = "change token status from " + currentTokenStatus + " to " + tokenStatus; + + // make sure transition is allowed + Collection<TokenStatus> nextStatuses = transitions.get(currentTokenStatus); + CMS.debug("TokenService.changeTokenStatus(): allowed next statuses: " + nextStatuses); + if (nextStatuses == null || !nextStatuses.contains(tokenStatus)) { + CMS.debug("TokenService.changeTokenStatus(): next status not allowed: " + tokenStatus); + msg = msg + ": Invalid token status transition"; + subsystem.tdb.tdbActivity(ActivityDatabase.OP_DO_TOKEN, tokenRecord, + ipAddress, msg, + "failure", + remoteUser); + throw new BadRequestException(msg); + } + + CMS.debug("TokenService.changeTokenStatus(): next status allowed: " + tokenStatus); + setTokenStatus(tokenRecord, tokenStatus); + database.updateRecord(tokenID, tokenRecord); + subsystem.tdb.tdbActivity(ActivityDatabase.OP_DO_TOKEN, tokenRecord, + ipAddress, msg, "success", + remoteUser); + + TokenData tokenData = createTokenData(database.getRecord(tokenID)); + + return createOKResponse(tokenData); + + } catch (Exception e) { + e.printStackTrace(); + msg = msg + e; + subsystem.tdb.tdbActivity(ActivityDatabase.OP_DO_TOKEN, tokenRecord, + ipAddress, msg, "failure", + remoteUser); + + throw new PKIException(msg); + } + } + + @Override + public Response removeToken(String tokenID) { + + if (tokenID == null) throw new BadRequestException("Token ID is null."); + + CMS.debug("TokenService.removeToken(\"" + tokenID + "\")"); + + String remoteUser = servletRequest.getRemoteUser(); + String ipAddress = servletRequest.getRemoteAddr(); + + TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID); + TokenRecord tokenRecord = null; + String msg = "remove token"; + try { + TokenDatabase database = subsystem.getTokenDatabase(); + tokenRecord = database.getRecord(tokenID); + database.removeRecord(tokenID); + subsystem.tdb.tdbActivity(ActivityDatabase.OP_DELETE, tokenRecord, + ipAddress, msg, "success", remoteUser); + + return createNoContentResponse(); + + } catch (Exception e) { + e.printStackTrace(); + subsystem.tdb.tdbActivity(ActivityDatabase.OP_DELETE, tokenRecord, + ipAddress, msg, "failure", + remoteUser); + msg = msg + ":" + e; + + throw new PKIException(msg); + } + } +} |