OPS-212: add forbidden some methods in service (#21)

This commit is contained in:
malkoas 2022-10-20 17:35:15 +03:00 committed by GitHub
parent d3d68ad688
commit bb6963ba6c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 41 additions and 1 deletions

View File

@ -11,6 +11,7 @@ import org.springframework.stereotype.Service;
public class RoleAccessService {
private static final String ROLE_DELIMITER = ":";
private static final String FORBIDDEN_MARK = "!";
public void checkRolesAccess(AccessData accessData) {
if (accessData.getTokenRoles().isEmpty()) {
@ -18,6 +19,14 @@ public class RoleAccessService {
String.format("User %s don't have roles", accessData.getUserEmail()));
}
if (isRoleContainsForbiddenServiceAndMethodName(accessData)) {
throw new AuthorizationException(
String.format("User %s don't have access to %s in service %s",
accessData.getUserEmail(),
accessData.getMethodName(),
accessData.getServiceName()));
}
for (String role : accessData.getTokenRoles()) {
if (role.equalsIgnoreCase(getServiceAndMethodName(accessData))) {
log.info("Rights allowed in service {} and method {} for user {}",
@ -52,4 +61,17 @@ public class RoleAccessService {
accessData.getMethodName());
}
private boolean isRoleContainsForbiddenServiceAndMethodName(AccessData accessData) {
return accessData.getTokenRoles()
.stream()
.anyMatch(getForbiddenServiceAndMethodName(accessData)::equalsIgnoreCase);
}
private String getForbiddenServiceAndMethodName(AccessData accessData) {
return FORBIDDEN_MARK + String.join(
ROLE_DELIMITER,
accessData.getServiceName(),
accessData.getMethodName());
}
}

View File

@ -30,7 +30,8 @@ public abstract class AbstractKeycloakOpenIdAsWiremockConfig {
}
protected String generateSimpleJwtWithRoles() {
return keycloakOpenIdStub.generateJwt("Deanonimus", "unknown", "Domain", "messages:methodName");
return keycloakOpenIdStub.generateJwt("Deanonimus", "unknown", "Domain", "messages:methodName",
"DominantCache", "!DominantCache:methodName");
}

View File

@ -120,4 +120,21 @@ class ErrorControllerTest extends AbstractKeycloakOpenIdAsWiremockConfig {
" to methodName in service Invoicing",
result.getResolvedException().getMessage()));
}
@Test
@SneakyThrows
void requestWithForbiddenMethod() {
mvc.perform(post("/wachter")
.header("Authorization", "Bearer " + generateSimpleJwtWithRoles())
.header("X-Request-ID", randomUUID())
.header("Service", "DominantCache")
.header("X-Request-Deadline", Instant.now().plus(1, ChronoUnit.DAYS).toString())
.content(TMessageUtil.createTMessage(protocolFactory)))
.andDo(print())
.andExpect(status().is4xxClientError())
.andExpect(result -> assertTrue(result.getResolvedException() instanceof AuthorizationException))
.andExpect(result -> assertEquals("User darkside-the-best@mail.com don't have access" +
" to methodName in service DominantCache",
result.getResolvedException().getMessage()));
}
}