Search in sources :

Example 16 with ExceptionMetered

use of com.codahale.metrics.annotation.ExceptionMetered in project keywhiz by square.

the class AutomationGroupResource method createGroup.

/**
   * Create Group
   *
   * @param groupRequest the JSON group request used to formulate the Group
   * @excludeParams automationClient
   * @description Creates a Group with the name from a valid group request
   * @responseMessage 200 Successfully created Group
   * @responseMessage 409 Group with given name already exists
   */
@Timed
@ExceptionMetered
@POST
@Consumes(APPLICATION_JSON)
public Group createGroup(@Auth AutomationClient automationClient, @Valid CreateGroupRequest groupRequest) {
    Optional<Group> group = groupDAO.getGroup(groupRequest.name);
    if (group.isPresent()) {
        logger.info("Automation ({}) - Group {} already exists", automationClient.getName(), groupRequest.name);
        throw new ConflictException("Group name already exists.");
    }
    long id = groupDAO.createGroup(groupRequest.name, automationClient.getName(), nullToEmpty(groupRequest.description), groupRequest.metadata);
    Map<String, String> extraInfo = new HashMap<>();
    extraInfo.put("deprecated", "true");
    if (groupRequest.description != null) {
        extraInfo.put("description", groupRequest.description);
    }
    if (groupRequest.metadata != null) {
        extraInfo.put("metadata", groupRequest.metadata.toString());
    }
    auditLog.recordEvent(new Event(Instant.now(), EventTag.GROUP_CREATE, automationClient.getName(), groupRequest.name, extraInfo));
    return groupDAO.getGroupById(id).get();
}
Also used : Group(keywhiz.api.model.Group) ConflictException(keywhiz.service.exceptions.ConflictException) HashMap(java.util.HashMap) Event(keywhiz.log.Event) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Timed(com.codahale.metrics.annotation.Timed) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered)

Example 17 with ExceptionMetered

use of com.codahale.metrics.annotation.ExceptionMetered in project keywhiz by square.

the class AutomationGroupResource method getGroupByName.

/**
   * Retrieve Group by a specified name, or all Groups if no name given
   *
   * @param name the name of the Group to retrieve, if provided
   * @excludeParams automationClient
   * @optionalParams name
   * @description Returns a single Group or a set of all Groups
   * @responseMessage 200 Found and retrieved Group(s)
   * @responseMessage 404 Group with given name not found (if name provided)
   */
@Timed
@ExceptionMetered
@GET
public Response getGroupByName(@Auth AutomationClient automationClient, @QueryParam("name") Optional<String> name) {
    if (name.isPresent()) {
        Group group = groupDAO.getGroup(name.get()).orElseThrow(NotFoundException::new);
        ImmutableList<Client> clients = ImmutableList.copyOf(aclDAO.getClientsFor(group));
        ImmutableList<SanitizedSecret> sanitizedSecrets = ImmutableList.copyOf(aclDAO.getSanitizedSecretsFor(group));
        return Response.ok().entity(GroupDetailResponse.fromGroup(group, sanitizedSecrets, clients)).build();
    }
    ImmutableList<SanitizedSecret> emptySecrets = ImmutableList.of();
    ImmutableList<Client> emptyClients = ImmutableList.of();
    List<GroupDetailResponse> groups = groupDAO.getGroups().stream().map((g) -> GroupDetailResponse.fromGroup(g, emptySecrets, emptyClients)).collect(toList());
    return Response.ok().entity(groups).build();
}
Also used : PathParam(javax.ws.rs.PathParam) AclDAO(keywhiz.service.daos.AclDAO) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) Event(keywhiz.log.Event) Strings.nullToEmpty(com.google.common.base.Strings.nullToEmpty) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) Auth(io.dropwizard.auth.Auth) GroupDAOFactory(keywhiz.service.daos.GroupDAO.GroupDAOFactory) HashMap(java.util.HashMap) Inject(javax.inject.Inject) Valid(javax.validation.Valid) AutomationClient(keywhiz.api.model.AutomationClient) GroupResource(keywhiz.service.resources.automation.v2.GroupResource) QueryParam(javax.ws.rs.QueryParam) ImmutableList(com.google.common.collect.ImmutableList) Consumes(javax.ws.rs.Consumes) Map(java.util.Map) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered) Client(keywhiz.api.model.Client) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) GroupDAO(keywhiz.service.daos.GroupDAO) DELETE(javax.ws.rs.DELETE) AuditLog(keywhiz.log.AuditLog) Group(keywhiz.api.model.Group) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) AclDAOFactory(keywhiz.service.daos.AclDAO.AclDAOFactory) LongParam(io.dropwizard.jersey.params.LongParam) ConflictException(keywhiz.service.exceptions.ConflictException) Instant(java.time.Instant) NotFoundException(javax.ws.rs.NotFoundException) Timed(com.codahale.metrics.annotation.Timed) CreateGroupRequest(keywhiz.api.CreateGroupRequest) EventTag(keywhiz.log.EventTag) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) Response(javax.ws.rs.core.Response) Optional(java.util.Optional) SanitizedSecret(keywhiz.api.model.SanitizedSecret) VisibleForTesting(com.google.common.annotations.VisibleForTesting) GroupDetailResponse(keywhiz.api.GroupDetailResponse) Group(keywhiz.api.model.Group) SanitizedSecret(keywhiz.api.model.SanitizedSecret) GroupDetailResponse(keywhiz.api.GroupDetailResponse) NotFoundException(javax.ws.rs.NotFoundException) AutomationClient(keywhiz.api.model.AutomationClient) Client(keywhiz.api.model.Client) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered)

Example 18 with ExceptionMetered

use of com.codahale.metrics.annotation.ExceptionMetered in project keywhiz by square.

the class AutomationSecretResource method readSecrets.

/**
   * Retrieve secret by a specified name, or all secrets if no name given
   * Note that retrieving all secrets could be an expensive query
   *
   * @excludeParams automationClient
   * @optionalParams name
   * @param name the name of the secret to retrieve, if provided
   *
   * @description Returns a single secret or a set of all secrets
   * @responseMessage 200 Found and retrieved secret(s)
   * @responseMessage 404 Secret with given name not found (if name provided)
   */
@Timed
@ExceptionMetered
@GET
public ImmutableList<AutomationSecretResponse> readSecrets(@Auth AutomationClient automationClient, @QueryParam("name") String name) {
    ImmutableList.Builder<AutomationSecretResponse> responseBuilder = ImmutableList.builder();
    if (name != null) {
        Optional<Secret> optionalSecret = secretController.getSecretByName(name);
        if (!optionalSecret.isPresent()) {
            throw new NotFoundException("Secret not found.");
        }
        Secret secret = optionalSecret.get();
        ImmutableList<Group> groups = ImmutableList.copyOf(aclDAO.getGroupsFor(secret));
        responseBuilder.add(AutomationSecretResponse.fromSecret(secret, groups));
    } else {
        List<SanitizedSecret> secrets = secretController.getSanitizedSecrets(null, null);
        for (SanitizedSecret sanitizedSecret : secrets) {
            Secret secret = secretController.getSecretById(sanitizedSecret.id()).orElseThrow(() -> new IllegalStateException(format("Cannot find record related to %s", sanitizedSecret)));
            ImmutableList<Group> groups = ImmutableList.copyOf(aclDAO.getGroupsFor(secret));
            responseBuilder.add(AutomationSecretResponse.fromSecret(secret, groups));
        }
    }
    return responseBuilder.build();
}
Also used : Secret(keywhiz.api.model.Secret) SanitizedSecret(keywhiz.api.model.SanitizedSecret) Group(keywhiz.api.model.Group) SanitizedSecret(keywhiz.api.model.SanitizedSecret) ImmutableList(com.google.common.collect.ImmutableList) AutomationSecretResponse(keywhiz.api.AutomationSecretResponse) NotFoundException(javax.ws.rs.NotFoundException) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered)

Example 19 with ExceptionMetered

use of com.codahale.metrics.annotation.ExceptionMetered in project keywhiz by square.

the class ClientResource method deleteClient.

/**
   * Delete a client
   *
   * @excludeParams automationClient
   * @param name Client name
   *
   * @responseMessage 204 Client deleted
   * @responseMessage 404 Client not found
   */
@Timed
@ExceptionMetered
@DELETE
@Path("{name}")
public Response deleteClient(@Auth AutomationClient automationClient, @PathParam("name") String name) {
    Client client = clientDAOReadWrite.getClient(name).orElseThrow(NotFoundException::new);
    // Group memberships are deleted automatically by DB cascading.
    clientDAOReadWrite.deleteClient(client);
    auditLog.recordEvent(new Event(Instant.now(), EventTag.CLIENT_DELETE, automationClient.getName(), client.getName()));
    return Response.noContent().build();
}
Also used : NotFoundException(javax.ws.rs.NotFoundException) Event(keywhiz.log.Event) AutomationClient(keywhiz.api.model.AutomationClient) Client(keywhiz.api.model.Client) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) Timed(com.codahale.metrics.annotation.Timed) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered)

Example 20 with ExceptionMetered

use of com.codahale.metrics.annotation.ExceptionMetered in project keywhiz by square.

the class ClientResource method modifyClientGroups.

/**
   * Modify groups a client has membership in
   *
   * @excludeParams automationClient
   * @param name Client name
   * @param request JSON request specifying which groups to add or remove
   * @return Listing of groups client has membership in
   *
   * @responseMessage 201 Client modified successfully
   * @responseMessage 404 Client not found
   */
@Timed
@ExceptionMetered
@PUT
@Path("{name}/groups")
@Produces(APPLICATION_JSON)
public Iterable<String> modifyClientGroups(@Auth AutomationClient automationClient, @PathParam("name") String name, @Valid ModifyGroupsRequestV2 request) {
    Client client = clientDAOReadWrite.getClient(name).orElseThrow(NotFoundException::new);
    String user = automationClient.getName();
    long clientId = client.getId();
    Set<String> oldGroups = aclDAOReadWrite.getGroupsFor(client).stream().map(Group::getName).collect(toSet());
    Set<String> groupsToAdd = Sets.difference(request.addGroups(), oldGroups);
    Set<String> groupsToRemove = Sets.intersection(request.removeGroups(), oldGroups);
    // TODO: should optimize AclDAO to use names and return only name column
    groupsToGroupIds(groupsToAdd).forEach((maybeGroupId) -> maybeGroupId.ifPresent((groupId) -> aclDAOReadWrite.findAndEnrollClient(clientId, groupId, auditLog, user, new HashMap<>())));
    groupsToGroupIds(groupsToRemove).forEach((maybeGroupId) -> maybeGroupId.ifPresent((groupId) -> aclDAOReadWrite.findAndEvictClient(clientId, groupId, auditLog, user, new HashMap<>())));
    return aclDAOReadWrite.getGroupsFor(client).stream().map(Group::getName).collect(toSet());
}
Also used : NotImplementedException(org.apache.commons.lang3.NotImplementedException) PathParam(javax.ws.rs.PathParam) AclDAO(keywhiz.service.daos.AclDAO) Produces(javax.ws.rs.Produces) ClientDAO(keywhiz.service.daos.ClientDAO) GET(javax.ws.rs.GET) ClientDetailResponseV2(keywhiz.api.automation.v2.ClientDetailResponseV2) Event(keywhiz.log.Event) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) Auth(io.dropwizard.auth.Auth) GroupDAOFactory(keywhiz.service.daos.GroupDAO.GroupDAOFactory) HashMap(java.util.HashMap) Inject(javax.inject.Inject) Valid(javax.validation.Valid) AutomationClient(keywhiz.api.model.AutomationClient) ClientDAOFactory(keywhiz.service.daos.ClientDAO.ClientDAOFactory) Consumes(javax.ws.rs.Consumes) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered) ModifyGroupsRequestV2(keywhiz.api.automation.v2.ModifyGroupsRequestV2) UriBuilder(javax.ws.rs.core.UriBuilder) URI(java.net.URI) Client(keywhiz.api.model.Client) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) GroupDAO(keywhiz.service.daos.GroupDAO) Collectors.toSet(java.util.stream.Collectors.toSet) DELETE(javax.ws.rs.DELETE) CreateClientRequestV2(keywhiz.api.automation.v2.CreateClientRequestV2) AuditLog(keywhiz.log.AuditLog) ModifyClientRequestV2(keywhiz.api.automation.v2.ModifyClientRequestV2) Group(keywhiz.api.model.Group) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) Set(java.util.Set) AclDAOFactory(keywhiz.service.daos.AclDAO.AclDAOFactory) ConflictException(keywhiz.service.exceptions.ConflictException) Instant(java.time.Instant) Sets(com.google.common.collect.Sets) NotFoundException(javax.ws.rs.NotFoundException) String.format(java.lang.String.format) Timed(com.codahale.metrics.annotation.Timed) EventTag(keywhiz.log.EventTag) Stream(java.util.stream.Stream) Response(javax.ws.rs.core.Response) Optional(java.util.Optional) SanitizedSecret(keywhiz.api.model.SanitizedSecret) PUT(javax.ws.rs.PUT) NotFoundException(javax.ws.rs.NotFoundException) AutomationClient(keywhiz.api.model.AutomationClient) Client(keywhiz.api.model.Client) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) Timed(com.codahale.metrics.annotation.Timed) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered) PUT(javax.ws.rs.PUT)

Aggregations

ExceptionMetered (com.codahale.metrics.annotation.ExceptionMetered)54 Timed (com.codahale.metrics.annotation.Timed)53 Path (javax.ws.rs.Path)36 Event (keywhiz.log.Event)29 HashMap (java.util.HashMap)28 NotFoundException (javax.ws.rs.NotFoundException)27 POST (javax.ws.rs.POST)25 Consumes (javax.ws.rs.Consumes)20 Produces (javax.ws.rs.Produces)20 DELETE (javax.ws.rs.DELETE)18 GET (javax.ws.rs.GET)17 Group (keywhiz.api.model.Group)16 SanitizedSecret (keywhiz.api.model.SanitizedSecret)16 Response (javax.ws.rs.core.Response)12 AutomationClient (keywhiz.api.model.AutomationClient)12 ConflictException (keywhiz.service.exceptions.ConflictException)12 Client (keywhiz.api.model.Client)11 Secret (keywhiz.api.model.Secret)11 URI (java.net.URI)9 PUT (javax.ws.rs.PUT)9