org.owasp.security.logging.SecurityMarkers Java Examples

The following examples show how to use org.owasp.security.logging.SecurityMarkers. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AlpineResource.java    From Alpine with Apache License 2.0 6 votes vote down vote up
/**
 * Logs a security event to the security audit log. Expects one of:
 * {@link SecurityMarkers#SECURITY_AUDIT}
 * {@link SecurityMarkers#SECURITY_SUCCESS}
 * {@link SecurityMarkers#SECURITY_FAILURE}
 * @param logger the logger to use
 * @param marker the marker to add to the event
 * @param message the initial content of the event
 * @since 1.0.0
 */
protected void logSecurityEvent(final Logger logger, final Marker marker, final String message) {
    if (!(SecurityMarkers.SECURITY_AUDIT == marker ||
          SecurityMarkers.SECURITY_SUCCESS == marker ||
          SecurityMarkers.SECURITY_FAILURE == marker)) {
        return;
    }
    final StringBuilder sb = new StringBuilder();
    sb.append(message).append(" ");
    if (getPrincipal() != null) {
        sb.append("by: ").append(getPrincipal().getName()).append(" ");
    }
    sb.append("/ IP Address: ").append(getRemoteAddress()).append(" ");
    sb.append("/ User Agent: ").append(getUserAgent());
    logger.info(marker, sb.toString());
}
 
Example #2
Source File: TeamResource.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
@DELETE
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
        value = "Deletes a team",
        code = 204
)
@ApiResponses(value = {
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 404, message = "The team could not be found")
})
@PermissionRequired(Permissions.Constants.ACCESS_MANAGEMENT)
public Response deleteTeam(Team jsonTeam) {
    try (QueryManager qm = new QueryManager()) {
        final Team team = qm.getObjectByUuid(Team.class, jsonTeam.getUuid(), Team.FetchGroup.ALL.name());
        if (team != null) {
            super.logSecurityEvent(LOGGER, SecurityMarkers.SECURITY_AUDIT, "Team deleted: " + team.getName());
            qm.delete(team.getApiKeys());
            qm.delete(team);
            return Response.status(Response.Status.NO_CONTENT).build();
        } else {
            return Response.status(Response.Status.NOT_FOUND).entity("The team could not be found.").build();
        }
    }
}
 
Example #3
Source File: TeamResource.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
        value = "Creates a new team along with an associated API key",
        response = Team.class,
        code = 201
)
@ApiResponses(value = {
        @ApiResponse(code = 401, message = "Unauthorized")
})
@PermissionRequired(Permissions.Constants.ACCESS_MANAGEMENT)
//public Response createTeam(String jsonRequest) {
public Response createTeam(Team jsonTeam) {
    //Team team = MapperUtil.readAsObjectOf(Team.class, jsonRequest);
    final Validator validator = super.getValidator();
    failOnValidationError(
            validator.validateProperty(jsonTeam, "name")
    );

    try (QueryManager qm = new QueryManager()) {
        final Team team = qm.createTeam(jsonTeam.getName(), true);
        super.logSecurityEvent(LOGGER, SecurityMarkers.SECURITY_AUDIT, "Team created: " + team.getName());
        return Response.status(Response.Status.CREATED).entity(team).build();
    }
}
 
Example #4
Source File: UserResource.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
@DELETE
@Path("oidc")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
        value = "Deletes an OpenID Connect user.",
        code = 204
)
@ApiResponses(value = {
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 404, message = "The user could not be found")
})
@PermissionRequired(Permissions.Constants.ACCESS_MANAGEMENT)
public Response deleteOidcUser(final OidcUser jsonUser) {
    try (QueryManager qm = new QueryManager()) {
        final OidcUser user = qm.getOidcUser(jsonUser.getUsername());
        if (user != null) {
            qm.delete(user);
            super.logSecurityEvent(LOGGER, SecurityMarkers.SECURITY_AUDIT, "OpenID Connect user deleted: " + jsonUser.getUsername());
            return Response.status(Response.Status.NO_CONTENT).build();
        } else {
            return Response.status(Response.Status.NOT_FOUND).entity("The user could not be found.").build();
        }
    }
}
 
Example #5
Source File: UserResource.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
@DELETE
@Path("managed")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
        value = "Deletes a user.",
        code = 204
)
@ApiResponses(value = {
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 404, message = "The user could not be found")
})
@PermissionRequired(Permissions.Constants.ACCESS_MANAGEMENT)
public Response deleteManagedUser(ManagedUser jsonUser) {
    try (QueryManager qm = new QueryManager()) {
        final ManagedUser user = qm.getManagedUser(jsonUser.getUsername());
        if (user != null) {
            qm.delete(user);
            super.logSecurityEvent(LOGGER, SecurityMarkers.SECURITY_AUDIT, "Managed user deleted: " + jsonUser.getUsername());
            return Response.status(Response.Status.NO_CONTENT).build();
        } else {
            return Response.status(Response.Status.NOT_FOUND).entity("The user could not be found.").build();
        }
    }
}
 
Example #6
Source File: UserResource.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
@DELETE
@Path("ldap")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
        value = "Deletes a user.",
        code = 204
)
@ApiResponses(value = {
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 404, message = "The user could not be found")
})
@PermissionRequired(Permissions.Constants.ACCESS_MANAGEMENT)
public Response deleteLdapUser(LdapUser jsonUser) {
    try (QueryManager qm = new QueryManager()) {
        final LdapUser user = qm.getLdapUser(jsonUser.getUsername());
        if (user != null) {
            qm.delete(user);
            super.logSecurityEvent(LOGGER, SecurityMarkers.SECURITY_AUDIT, "LDAP user deleted: " + jsonUser.getUsername());
            return Response.status(Response.Status.NO_CONTENT).build();
        } else {
            return Response.status(Response.Status.NOT_FOUND).entity("The user could not be found.").build();
        }
    }
}
 
Example #7
Source File: OidcResource.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
@DELETE
@Path("/mapping/{uuid}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
        value = "Deletes a mapping",
        code = 204
)
@ApiResponses(value = {
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 404, message = "The UUID of the mapping could not be found"),
})
@PermissionRequired(Permissions.Constants.ACCESS_MANAGEMENT)
public Response deleteMappingByUuid(@ApiParam(value = "The UUID of the mapping to delete", required = true)
                                    @PathParam("uuid") final String uuid) {
    try (QueryManager qm = new QueryManager()) {
        final MappedOidcGroup mapping = qm.getObjectByUuid(MappedOidcGroup.class, uuid);
        if (mapping != null) {
            super.logSecurityEvent(LOGGER, SecurityMarkers.SECURITY_AUDIT, "Mapping for group " + mapping.getGroup().getName() + " and team " + mapping.getTeam().getName() + " deleted");
            qm.delete(mapping);
            return Response.status(Response.Status.NO_CONTENT).build();
        } else {
            return Response.status(Response.Status.NOT_FOUND).entity("The UUID of the mapping could not be found.").build();
        }
    }
}
 
Example #8
Source File: OidcResource.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
@DELETE
@Path("/group/{uuid}")
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(
        value = "Deletes a group",
        code = 204
)
@ApiResponses(value = {
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 404, message = "The group could not be found")
})
@PermissionRequired(Permissions.Constants.ACCESS_MANAGEMENT)
public Response deleteGroup(@ApiParam(value = "The UUID of the group to delete", required = true)
                            @PathParam("uuid") final String uuid) {
    try (QueryManager qm = new QueryManager()) {
        final OidcGroup group = qm.getObjectByUuid(OidcGroup.class, uuid);
        if (group != null) {
            qm.delete(qm.getMappedOidcGroups(group));
            qm.delete(group);
            super.logSecurityEvent(LOGGER, SecurityMarkers.SECURITY_AUDIT, "Group deleted: " + group.getName());
            return Response.status(Response.Status.NO_CONTENT).build();
        } else {
            return Response.status(Response.Status.NOT_FOUND).entity("An OpenID Connect group with the specified UUID could not be found.").build();
        }
    }
}
 
Example #9
Source File: HomeController.java    From JavaSecurity with Apache License 2.0 6 votes vote down vote up
@PostMapping("login")
public String firstTask(Login login, Model model) {
    String username = login.getUsername();
    String password = login.getPassword();

    log.info(SecurityMarkers.CONFIDENTIAL, "User {} with password {} logged in", username, password);
    log.info(SecurityMarkers.EVENT_FAILURE, "User {} with password {} logged in", username, password);
    log.info(SecurityMarkers.EVENT_SUCCESS, "User {} with password {} logged in", username, password);
    log.info(SecurityMarkers.RESTRICTED, "User {} with password {} logged in", username, password);
    log.info(SecurityMarkers.SECRET, "User {} with password {} logged in", username, password);
    log.info(SecurityMarkers.SECURITY_AUDIT, "User {} with password {} logged in", username, password);
    log.info(SecurityMarkers.SECURITY_FAILURE, "User {} with password {} logged in", username, password);
    log.info(SecurityMarkers.SECURITY_SUCCESS, "User {} with password {} logged in", username, password);
    log.info(SecurityMarkers.TOP_SECRET, "User {} with password {} logged in", username, password);

    model.addAttribute("login", login);

    return "login";
}
 
Example #10
Source File: SecurityMarkerFilterTest.java    From owasp-security-logging with Apache License 2.0 6 votes vote down vote up
@Test
public void getMarkersTest() {
	Marker test1 = SecurityMarkers
			.getMarker(SecurityMarkers.SECURITY_AUDIT);
	System.out.println("getMarkers(): test1: " + test1);
	assertTrue(test1.contains(SecurityMarkers.SECURITY_AUDIT));
	assertFalse(test1.contains(SecurityMarkers.CONFIDENTIAL));

	Marker test2 = SecurityMarkers.getMarker(
			SecurityMarkers.SECURITY_AUDIT,
			SecurityMarkers.SECURITY_FAILURE);
	System.out.println("getMarkers(): test2: " + test2);
	assertTrue(test2.contains(SecurityMarkers.SECURITY_AUDIT));
	assertTrue(test2.contains(SecurityMarkers.SECURITY_FAILURE));

	Marker test3 = SecurityMarkers.getMarker(
			SecurityMarkers.SECURITY_AUDIT, SecurityMarkers.CONFIDENTIAL);
	System.out.println("getMarkers(): test3: " + test3);

	assertTrue(test3.contains(SecurityMarkers.SECURITY_AUDIT));
	assertTrue(test3.contains(SecurityMarkers.CONFIDENTIAL));
	assertFalse(test3.contains(SecurityMarkers.SECURITY_FAILURE));
}
 
Example #11
Source File: SecurityMarkerFilterTest.java    From owasp-security-logging with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppenderMultipleNonSecurityEvent() {
	Marker multi = SecurityMarkers.getMarker(SecurityMarkers.EVENT_SUCCESS,
			SecurityMarkers.CONFIDENTIAL);
	System.out.println("MARKER: " + multi);
	LOGGER.info(multi,
			"This statement contains multiple markers: event success and confidential");

	// Now verify our logging interactions
	verify(mockAppender).doAppend(captorLoggingEvent.capture());

	// Get the logging event from the captor
	LoggingEvent loggingEvent = captorLoggingEvent.getValue();
	System.out.println("testAppender(): loggingEvent: " + loggingEvent);

	// check the filter chain decision for this event
	assertEquals(FilterReply.DENY,
			mockAppender.getFilterChainDecision(loggingEvent));
}
 
Example #12
Source File: SecurityMarkerFilterTest.java    From owasp-security-logging with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppenderMultipleEvent() {
	Marker multi = SecurityMarkers.getMarker(
			SecurityMarkers.SECURITY_AUDIT, SecurityMarkers.CONFIDENTIAL);
	LOGGER.info(multi,
			"This statement contains multiple markers: security audit and confidential");

	// Now verify our logging interactions
	verify(mockAppender).doAppend(captorLoggingEvent.capture());

	// Get the logging event from the captor
	LoggingEvent loggingEvent = captorLoggingEvent.getValue();
	System.out.println("testAppender(): loggingEvent: " + loggingEvent);

	// check the filter chain decision for this event
	assertEquals(FilterReply.ACCEPT,
			mockAppender.getFilterChainDecision(loggingEvent));
}
 
Example #13
Source File: SecurityMarkerFilterTest.java    From owasp-security-logging with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppenderSecurityAudit() {
	LOGGER.info(SecurityMarkers.SECURITY_AUDIT,
			"This statement is a security audit");

	// Now verify our logging interactions
	verify(mockAppender).doAppend(captorLoggingEvent.capture());

	// Get the logging event from the captor
	LoggingEvent loggingEvent = captorLoggingEvent.getValue();
	System.out.println("testAppender(): loggingEvent: " + loggingEvent);

	// check the filter chain decision for this event
	assertEquals(FilterReply.ACCEPT,
			mockAppender.getFilterChainDecision(loggingEvent));
}
 
Example #14
Source File: SecurityMarkerFilterTest.java    From owasp-security-logging with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppenderSecurityFailure() {
	LOGGER.info(SecurityMarkers.SECURITY_FAILURE,
			"This statement is a security failure");

	// Now verify our logging interactions
	verify(mockAppender).doAppend(captorLoggingEvent.capture());

	// Get the logging event from the captor
	LoggingEvent loggingEvent = captorLoggingEvent.getValue();
	System.out.println("testAppender(): loggingEvent: " + loggingEvent);

	// check the filter chain decision for this event
	assertEquals(FilterReply.ACCEPT,
			mockAppender.getFilterChainDecision(loggingEvent));
}
 
Example #15
Source File: ExcludeClassifiedMarkerFilterTest.java    From owasp-security-logging with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppenderMultipleEvent() {
	Marker multi = SecurityMarkers.getMarker(
			SecurityMarkers.SECURITY_AUDIT, SecurityMarkers.CONFIDENTIAL);
	LOGGER.info(multi,
			"This statement contains multiple markers: audit and confidential");

	// Now verify our logging interactions
	verify(mockAppender).doAppend(captorLoggingEvent.capture());

	// Get the logging event from the captor
	LoggingEvent loggingEvent = captorLoggingEvent.getValue();
	System.out.println("testAppender(): loggingEvent: " + loggingEvent);

	// check the filter chain decision for this event
	assertEquals(FilterReply.DENY,
			mockAppender.getFilterChainDecision(loggingEvent));
}
 
Example #16
Source File: SecurityMarkerFilterTest.java    From owasp-security-logging with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppenderSecuritySuccess() {
	LOGGER.info(SecurityMarkers.SECURITY_SUCCESS,
			"This statement is a security success");

	// Now verify our logging interactions
	verify(mockAppender).doAppend(captorLoggingEvent.capture());

	// Get the logging event from the captor
	LoggingEvent loggingEvent = captorLoggingEvent.getValue();
	System.out.println("testAppender(): loggingEvent: " + loggingEvent);

	// check the filter chain decision for this event
	assertEquals(FilterReply.ACCEPT,
			mockAppender.getFilterChainDecision(loggingEvent));
}
 
Example #17
Source File: MaskingConverter.java    From owasp-security-logging with Apache License 2.0 6 votes vote down vote up
@Override
public String convert(ILoggingEvent event) {
	Marker eventMarker = event.getMarker();

	Object[] args = event.getArgumentArray();
	if (eventMarker != null
			&& eventMarker.contains(SecurityMarkers.CONFIDENTIAL)) {
		for (int i = 0; i < args.length; i++) {
			args[i] = MASKED_PASSWORD;
		}
	}

	String maskedMessage = MessageFormatter.arrayFormat(event.getMessage(),
			args).getMessage();

	return maskedMessage;
}
 
Example #18
Source File: ExcludeClassifiedMarkerFilterTest.java    From owasp-security-logging with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppenderConfidentialEvent() {
	LOGGER.info(SecurityMarkers.CONFIDENTIAL,
			"This statement is confidential");

	// Now verify our logging interactions
	verify(mockAppender).doAppend(captorLoggingEvent.capture());

	// Get the logging event from the captor
	LoggingEvent loggingEvent = captorLoggingEvent.getValue();
	System.out.println("testAppender(): loggingEvent: " + loggingEvent);

	// check the filter chain decision for this event
	assertEquals(FilterReply.DENY,
			mockAppender.getFilterChainDecision(loggingEvent));
}
 
Example #19
Source File: MaskingConverterTest.java    From owasp-security-logging with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
	String userid = "myId";
	String password = "secret";
	LOGGER.info(SecurityMarkers.CONFIDENTIAL, "userid={}, password='{}'",
			userid, password);

	// Now verify our logging interactions
	verify(mockAppender).doAppend(captorLoggingEvent.capture());

	// Get the logging event from the captor
	final LoggingEvent loggingEvent = captorLoggingEvent.getValue();

	// Check log level is correct
	assertThat(loggingEvent.getLevel(), is(Level.INFO));

	// Check the message being logged is correct
	String layoutMessage = encoder.getLayout().doLayout(loggingEvent);
	assertTrue(layoutMessage.contains("userid="
			+ MaskingConverter.MASKED_PASSWORD + ", password='"
			+ MaskingConverter.MASKED_PASSWORD + "'"));
	assertFalse(layoutMessage.contains("secret"));
}
 
Example #20
Source File: ExcludeClassifiedMarkerFilterTest.java    From owasp-security-logging with Apache License 2.0 6 votes vote down vote up
@Test
public void testAppenderSecurityEvent() {
	LOGGER.info(SecurityMarkers.SECURITY_SUCCESS,
			"This statement is a security event");

	// Now verify our logging interactions
	verify(mockAppender).doAppend(captorLoggingEvent.capture());

	// Get the logging event from the captor
	LoggingEvent loggingEvent = captorLoggingEvent.getValue();
	System.out.println("testAppender(): loggingEvent: " + loggingEvent);

	// check the filter chain decision for this event
	assertEquals(FilterReply.NEUTRAL,
			mockAppender.getFilterChainDecision(loggingEvent));
}
 
Example #21
Source File: MaskingConverterTest.java    From owasp-security-logging with Apache License 2.0 6 votes vote down vote up
/**
 * Test that masking works for combinations of markers and not just
 * SecurityMarkers.CONFIDENTIAL
 *
 * @see https://github.com/javabeanz/owasp-security-logging/issues/19
 */
@Test
public void markerTest() {
    Marker multiMarker = SecurityMarkers.getMarker(SecurityMarkers.CONFIDENTIAL, SecurityMarkers.SECURITY_FAILURE);

    String ssn = "123-45-6789";
    LOGGER.info(multiMarker, "ssn={}", ssn);

    // Now verify our logging interactions
    verify(mockAppender).doAppend(captorLoggingEvent.capture());

    // Get the logging event from the captor
    final LoggingEvent loggingEvent = captorLoggingEvent.getValue();

    // Check the message being logged is correct
    String layoutMessage = encoder.getLayout().doLayout(loggingEvent);
    assertTrue(layoutMessage.contains("ssn=" + MaskingConverter.MASKED_PASSWORD));
}
 
Example #22
Source File: PermissionResource.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
@POST
@Path("/{permission}/team/{uuid}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
        value = "Adds the permission to the specified username.",
        notes = "Requires 'manage users' permission.",
        response = Team.class
)
@ApiResponses(value = {
        @ApiResponse(code = 304, message = "The team already has the specified permission assigned"),
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 404, message = "The team could not be found")
})
@PermissionRequired(Permissions.Constants.ACCESS_MANAGEMENT)
public Response addPermissionToTeam(
        @ApiParam(value = "A valid team uuid", required = true)
        @PathParam("uuid") String uuid,
        @ApiParam(value = "A valid permission", required = true)
        @PathParam("permission") String permissionName) {
    try (QueryManager qm = new QueryManager()) {
        Team team = qm.getObjectByUuid(Team.class, uuid);
        if (team == null) {
            return Response.status(Response.Status.NOT_FOUND).entity("The team could not be found.").build();
        }
        final Permission permission = qm.getPermission(permissionName);
        if (permission == null) {
            return Response.status(Response.Status.NOT_FOUND).entity("The permission could not be found.").build();
        }
        final List<Permission> permissions = team.getPermissions();
        if (permissions != null && !permissions.contains(permission)) {
            permissions.add(permission);
            team.setPermissions(permissions);
            team = qm.persist(team);
            super.logSecurityEvent(LOGGER, SecurityMarkers.SECURITY_AUDIT, "Added permission for team: " + team.getName() + " / permission: " + permission.getName());
            return Response.ok(team).build();
        }
        return Response.status(Response.Status.NOT_MODIFIED).build();
    }
}
 
Example #23
Source File: PermissionResource.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
@DELETE
@Path("/{permission}/team/{uuid}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
        value = "Removes the permission from the team.",
        response = Team.class
)
@ApiResponses(value = {
        @ApiResponse(code = 304, message = "The team already has the specified permission assigned"),
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 404, message = "The team could not be found")
})
@PermissionRequired(Permissions.Constants.ACCESS_MANAGEMENT)
public Response removePermissionFromTeam(
        @ApiParam(value = "A valid team uuid", required = true)
        @PathParam("uuid") String uuid,
        @ApiParam(value = "A valid permission", required = true)
        @PathParam("permission") String permissionName) {
    try (QueryManager qm = new QueryManager()) {
        Team team = qm.getObjectByUuid(Team.class, uuid);
        if (team == null) {
            return Response.status(Response.Status.NOT_FOUND).entity("The team could not be found.").build();
        }
        final Permission permission = qm.getPermission(permissionName);
        if (permission == null) {
            return Response.status(Response.Status.NOT_FOUND).entity("The permission could not be found.").build();
        }
        final List<Permission> permissions = team.getPermissions();
        if (permissions != null && permissions.contains(permission)) {
            permissions.remove(permission);
            team.setPermissions(permissions);
            team = qm.persist(team);
            super.logSecurityEvent(LOGGER, SecurityMarkers.SECURITY_AUDIT, "Removed permission for team: " + team.getName() + " / permission: " + permission.getName());
            return Response.ok(team).build();
        }
        return Response.status(Response.Status.NOT_MODIFIED).build();
    }
}
 
Example #24
Source File: OidcResource.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
@PUT
@Path("/group")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(
        value = "Creates group",
        response = OidcGroup.class,
        code = 201
)
@ApiResponses(value = {
        @ApiResponse(code = 401, message = "Unauthorized")
})
@PermissionRequired(Permissions.Constants.ACCESS_MANAGEMENT)
public Response createGroup(final OidcGroup jsonGroup) {
    final Validator validator = super.getValidator();
    failOnValidationError(
            validator.validateProperty(jsonGroup, "name")
    );

    try (QueryManager qm = new QueryManager()) {
        if (qm.getOidcGroup(jsonGroup.getName()) == null) {
            final OidcGroup group = qm.createOidcGroup(jsonGroup.getName());
            super.logSecurityEvent(LOGGER, SecurityMarkers.SECURITY_AUDIT, "Group created: " + group.getName());
            return Response.status(Response.Status.CREATED).entity(group).build();
        } else {
            return Response.status(Response.Status.CONFLICT).entity("A group with the same name already exists. Cannot create new group").build();
        }
    }
}
 
Example #25
Source File: OidcResource.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
@PUT
@Path("/mapping")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
        value = "Adds a mapping",
        response = MappedOidcGroup.class
)
@ApiResponses(value = {
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 404, message = "The UUID of the team or group could not be found"),
        @ApiResponse(code = 409, message = "A mapping with the same team and group name already exists")
})
@PermissionRequired(Permissions.Constants.ACCESS_MANAGEMENT)
public Response addMapping(final MappedOidcGroupRequest request) {
    final Validator validator = super.getValidator();
    failOnValidationError(
            validator.validateProperty(request, "team"),
            validator.validateProperty(request, "group")
    );

    try (QueryManager qm = new QueryManager()) {
        final Team team = qm.getObjectByUuid(Team.class, request.getTeam());
        if (team == null) {
            return Response.status(Response.Status.NOT_FOUND).entity("A team with the specified UUID could not be found.").build();
        }

        final OidcGroup group = qm.getObjectByUuid(OidcGroup.class, request.getGroup());
        if (group == null) {
            return Response.status(Response.Status.NOT_FOUND).entity("A group with the specified UUID could not be found.").build();
        }

        if (!qm.isOidcGroupMapped(team, group)) {
            final MappedOidcGroup mappedOidcGroup = qm.createMappedOidcGroup(team, group);
            super.logSecurityEvent(LOGGER, SecurityMarkers.SECURITY_AUDIT, "Mapping created for group " + group.getName() + " and team " + team.getName());
            return Response.ok(mappedOidcGroup).build();
        } else {
            return Response.status(Response.Status.CONFLICT).entity("A mapping for the same team and group already exists.").build();
        }
    }
}
 
Example #26
Source File: OidcResource.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
@DELETE
@Path("/group/{groupUuid}/team/{teamUuid}/mapping")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
        value = "Deletes a mapping",
        code = 204
)
@ApiResponses(value = {
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 404, message = "The UUID of the mapping could not be found"),
})
@PermissionRequired(Permissions.Constants.ACCESS_MANAGEMENT)
public Response deleteMapping(@ApiParam(value = "The UUID of the group to delete a mapping for", required = true)
                              @PathParam("groupUuid") final String groupUuid,
                              @ApiParam(value = "The UUID of the team to delete a mapping for", required = true)
                              @PathParam("teamUuid") final String teamUuid) {
    try (QueryManager qm = new QueryManager()) {
        final Team team = qm.getObjectByUuid(Team.class, teamUuid);
        if (team == null) {
            return Response.status(Response.Status.NOT_FOUND).entity("The UUID of the team could not be found.").build();
        }

        final OidcGroup group = qm.getObjectByUuid(OidcGroup.class, groupUuid);
        if (group == null) {
            return Response.status(Response.Status.NOT_FOUND).entity("The UUID of the group could not be found.").build();
        }

        final MappedOidcGroup mapping = qm.getMappedOidcGroup(team, group);
        if (mapping != null) {
            qm.delete(mapping);
            super.logSecurityEvent(LOGGER, SecurityMarkers.SECURITY_AUDIT, "Mapping for group " + group.getName() + " and team " + team.getName() + " deleted");
            return Response.status(Response.Status.NO_CONTENT).build();
        } else {
            return Response.status(Response.Status.NOT_FOUND).entity("A mapping for the group " + group.getName() + " and team " + team.getName() + " does not exist.").build();
        }
    }
}
 
Example #27
Source File: UserResource.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
@POST
@Path("login")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_PLAIN)
@ApiOperation(
        value = "Assert login credentials",
        notes = "Upon a successful login, a JSON Web Token will be returned in the response body. This functionality requires authentication to be enabled.",
        response = String.class
)
@ApiResponses(value = {
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 403, message = "Forbidden")
})
@AuthenticationNotRequired
public Response validateCredentials(@FormParam("username") String username, @FormParam("password") String password) {
    final Authenticator auth = new Authenticator(username, password);
    try (QueryManager qm = new QueryManager()) {
        final Principal principal = auth.authenticate();
        super.logSecurityEvent(LOGGER, SecurityMarkers.SECURITY_SUCCESS, "Successful user login / username: " + username);
        final List<Permission> permissions = qm.getEffectivePermissions((UserPrincipal) principal);
        final KeyManager km = KeyManager.getInstance();
        final JsonWebToken jwt = new JsonWebToken(km.getSecretKey());
        final String token = jwt.createToken(principal, permissions);
        return Response.ok(token).build();
    } catch (AlpineAuthenticationException e) {
        super.logSecurityEvent(LOGGER, SecurityMarkers.SECURITY_FAILURE, "Unauthorized login attempt / username: " + username);
        if (AlpineAuthenticationException.CauseType.SUSPENDED == e.getCauseType() || AlpineAuthenticationException.CauseType.UNMAPPED_ACCOUNT == e.getCauseType()) {
            return Response.status(Response.Status.FORBIDDEN).entity(e.getCauseType().name()).build();
        } else {
            return Response.status(Response.Status.UNAUTHORIZED).entity(e.getCauseType().name()).build();
        }
    }
}
 
Example #28
Source File: UserResource.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
@PUT
@Path("ldap")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
        value = "Creates a new user that references an existing LDAP object.",
        response = LdapUser.class,
        code = 201
)
@ApiResponses(value = {
        @ApiResponse(code = 400, message = "Username cannot be null or blank."),
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 409, message = "A user with the same username already exists. Cannot create new user")
})
@PermissionRequired(Permissions.Constants.ACCESS_MANAGEMENT)
public Response createLdapUser(LdapUser jsonUser) {
    try (QueryManager qm = new QueryManager()) {
        if (StringUtils.isBlank(jsonUser.getUsername())) {
            return Response.status(Response.Status.BAD_REQUEST).entity("Username cannot be null or blank.").build();
        }
        LdapUser user = qm.getLdapUser(jsonUser.getUsername());
        if (user == null) {
            user = qm.createLdapUser(jsonUser.getUsername());
            super.logSecurityEvent(LOGGER, SecurityMarkers.SECURITY_AUDIT, "LDAP user created: " + jsonUser.getUsername());
            return Response.status(Response.Status.CREATED).entity(user).build();
        } else {
            return Response.status(Response.Status.CONFLICT).entity("A user with the same username already exists. Cannot create new user.").build();
        }
    }
}
 
Example #29
Source File: UserResource.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
@PUT
@Path("oidc")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
        value = "Creates a new user that references an existing OpenID Connect user.",
        response = OidcUser.class,
        code = 201
)
@ApiResponses(value = {
        @ApiResponse(code = 400, message = "Username cannot be null or blank."),
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 409, message = "A user with the same username already exists. Cannot create new user")
})
@PermissionRequired(Permissions.Constants.ACCESS_MANAGEMENT)
public Response createOidcUser(final OidcUser jsonUser) {
    try (QueryManager qm = new QueryManager()) {
        if (StringUtils.isBlank(jsonUser.getUsername())) {
            return Response.status(Response.Status.BAD_REQUEST).entity("Username cannot be null or blank.").build();
        }
        OidcUser user = qm.getOidcUser(jsonUser.getUsername());
        if (user == null) {
            user = qm.createOidcUser(jsonUser.getUsername());
            super.logSecurityEvent(LOGGER, SecurityMarkers.SECURITY_AUDIT, "OpenID Connect user created: " + jsonUser.getUsername());
            return Response.status(Response.Status.CREATED).entity(user).build();
        } else {
            return Response.status(Response.Status.CONFLICT).entity("A user with the same username already exists. Cannot create new user.").build();
        }
    }
}
 
Example #30
Source File: UserResource.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
@POST
@Path("/{username}/membership")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
        value = "Adds the username to the specified team.",
        response = UserPrincipal.class
)
@ApiResponses(value = {
        @ApiResponse(code = 304, message = "The user is already a member of the specified team"),
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 404, message = "The user or team could not be found")
})
@PermissionRequired(Permissions.Constants.ACCESS_MANAGEMENT)
public Response addTeamToUser(
        @ApiParam(value = "A valid username", required = true)
        @PathParam("username") String username,
        @ApiParam(value = "The UUID of the team to associate username with", required = true)
                IdentifiableObject identifiableObject) {
    try (QueryManager qm = new QueryManager()) {
        final Team team = qm.getObjectByUuid(Team.class, identifiableObject.getUuid());
        if (team == null) {
            return Response.status(Response.Status.NOT_FOUND).entity("The team could not be found.").build();
        }
        UserPrincipal principal = qm.getUserPrincipal(username);
        if (principal == null) {
            return Response.status(Response.Status.NOT_FOUND).entity("The user could not be found.").build();
        }
        final boolean modified = qm.addUserToTeam(principal, team);
        principal = qm.getObjectById(principal.getClass(), principal.getId());
        if (modified) {
            super.logSecurityEvent(LOGGER, SecurityMarkers.SECURITY_AUDIT, "Added team membership for: " + principal.getName() + " / team: " + team.getName());
            return Response.ok(principal).build();
        } else {
            return Response.status(Response.Status.NOT_MODIFIED).entity("The user is already a member of the specified team.").build();
        }
    }
}