Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ES-1640] added schema validation for claims query parameter (#887) #1112

Merged
merged 2 commits into from
Jan 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 28 additions & 4 deletions esignet-core/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
<java.version>11</java.version>
<jackson.version>2.9.5</jackson.version>
<jackson.datatype.version>2.9.8</jackson.datatype.version>
<jackson.databind>2.15.0</jackson.databind>
<fasterxml.jackson.module.jsr310.version>2.15.0</fasterxml.jackson.module.jsr310.version>
<fasterxml.jackson.module.afterburner.version>2.15.0</fasterxml.jackson.module.afterburner.version>
<kernel.keymanager.version>1.2.1.0</kernel.keymanager.version>
Expand Down Expand Up @@ -100,20 +99,44 @@
<artifactId>micrometer-registry-prometheus</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.networknt</groupId>
<artifactId>json-schema-validator</artifactId>
<version>1.5.1</version>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-afterburner</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.databind}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.databind}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.databind}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
Expand Down Expand Up @@ -181,4 +204,5 @@
</dependency>
</dependencies>


</project>
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,5 @@ public class ErrorConstants {
public static final String INVALID_VERIFICATION = "invalid_verification";
public static final String INVALID_VERIFIED_CLAIMS = "invalid_verified_claims";
public static final String INVALID_PURPOSE="invalid_purpose";

public static final String VERIFICATION_INCOMPLETE = "verification_incomplete";
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,11 @@
*/
package io.mosip.esignet.core.dto;

import io.mosip.esignet.api.dto.claim.Claims;
import io.mosip.esignet.api.dto.claim.ClaimsV2;
import io.mosip.esignet.core.validator.OIDCDisplay;
import io.mosip.esignet.core.validator.OIDCPrompt;
import io.mosip.esignet.core.validator.OIDCResponseType;
import io.mosip.esignet.core.validator.OIDCScope;
import io.mosip.esignet.core.constants.ErrorConstants;
import io.mosip.esignet.core.validator.*;
import lombok.Data;

import io.mosip.esignet.core.validator.RedirectURL;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

Expand Down Expand Up @@ -76,6 +71,7 @@ public class OAuthDetailRequest {
* names of the individual Claims being requested as the member names.
*/
@Valid
@ClaimsSchema(message = ErrorConstants.INVALID_CLAIM)
private ClaimsV2 claims;

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package io.mosip.esignet.core.validator;


import io.mosip.esignet.core.constants.ErrorConstants;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Target({FIELD, TYPE_USE})
@Retention(RUNTIME)
@Constraint(validatedBy = ClaimsSchemaValidator.class)
@Documented
public @interface ClaimsSchema {

String message() default ErrorConstants.INVALID_CLAIM;

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package io.mosip.esignet.core.validator;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.networknt.schema.JsonSchema;
import com.networknt.schema.JsonSchemaFactory;
import com.networknt.schema.SpecVersion;
import com.networknt.schema.ValidationMessage;
import io.mosip.esignet.api.dto.claim.ClaimsV2;
import io.mosip.esignet.core.exception.EsignetException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Set;
import java.util.stream.Collectors;


@Slf4j
public class ClaimsSchemaValidator implements ConstraintValidator<ClaimsSchema, ClaimsV2> {


@Value("${mosip.esignet.claims.schema.url}")
private String schemaUrl;

private volatile JsonSchema cachedSchema;

@Autowired
private ObjectMapper objectMapper;

@Autowired
private ResourceLoader resourceLoader;


@Override
public boolean isValid(ClaimsV2 claims, ConstraintValidatorContext context) {
Set<ValidationMessage> errors = null;
try {
JsonNode jsonNode = objectMapper.valueToTree(claims);
errors = getCachedSchema().validate(jsonNode);
if(errors.isEmpty())return true;
} catch (Exception e) {
log.error("Error validating claims schema", e);
}
log.error("Validation failed for claims: {}", errors);
return false;
}

private JsonSchema getCachedSchema() throws EsignetException {
if(cachedSchema!=null ) return cachedSchema;
synchronized (this) {
if (cachedSchema == null) {
InputStream schemaResponse = getResource(schemaUrl);
JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V202012);
cachedSchema = jsonSchemaFactory.getSchema(schemaResponse);
}
}
return cachedSchema;
}

private InputStream getResource(String url) {
try{
Resource resource = resourceLoader.getResource(url);
return resource.getInputStream();
}catch (IOException e){
log.error("Failed to parse data: {}", url, e);
}
throw new EsignetException("invalid_configuration");
}
}

140 changes: 138 additions & 2 deletions esignet-core/src/test/java/io/mosip/esignet/core/ValidatorTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
*/
package io.mosip.esignet.core;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.mosip.esignet.api.dto.claim.ClaimDetail;
import io.mosip.esignet.api.dto.claim.ClaimsV2;
import io.mosip.esignet.api.spi.Authenticator;
import io.mosip.esignet.core.dto.OAuthDetailRequestV2;
import io.mosip.esignet.core.exception.EsignetException;
Expand All @@ -15,11 +19,16 @@
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.test.util.ReflectionTestUtils;

import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
Expand All @@ -28,12 +37,16 @@
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import static org.mockito.Mockito.when;


@SpringBootTest
@RunWith(MockitoJUnitRunner.class)
public class ValidatorTest {

@InjectMocks
ClaimsSchemaValidator claimSchemaValidator;

@Mock
AuthenticationContextClassRefUtil authenticationContextClassRefUtil;

Expand All @@ -43,6 +56,17 @@ public class ValidatorTest {
@Mock
Environment environment;


@Mock
RestTemplate restTemplate;


ResourceLoader resourceLoader= new DefaultResourceLoader();

ObjectMapper mapper= new ObjectMapper();



private Map<String, Object> discoveryMap = new HashMap<>();

@Before
Expand Down Expand Up @@ -647,4 +671,116 @@ public void test_ClientNameLangValidator_WithInValidDetail_thenFail(){
Assert.assertFalse(validator.isValid("abc", null));
}

// =============================ClaimSchemaValidator=============================//

@Test
public void claimSchemaValidator_withValidDetails_thenPass() throws IOException {

ReflectionTestUtils.setField(claimSchemaValidator,"resourceLoader",resourceLoader);
ReflectionTestUtils.setField(claimSchemaValidator,"objectMapper",mapper);
ReflectionTestUtils.setField(claimSchemaValidator,"schemaUrl","classpath:/verified_claims_request_schema_test.json");

String address="{\"essential\":true}";
String verifiedClaims="[{\"verification\":{\"trust_framework\":{\"value\":\"income-tax\"}},\"claims\":{\"name\":null,\"email\":{\"essential\":true}}},{\"verification\":{\"trust_framework\":{\"value\":\"pwd\"}},\"claims\":{\"birthdate\":{\"essential\":true},\"address\":null}},{\"verification\":{\"trust_framework\":{\"value\":\"kaif\"}},\"claims\":{\"gender\":{\"essential\":true},\"email\":{\"essential\":true}}}]";

JsonNode addressNode = mapper.readValue(address, JsonNode.class);
JsonNode verifiedClaimNode = mapper.readValue(verifiedClaims, JsonNode.class);

Map<String, JsonNode> userinfoMap = new HashMap<>();
userinfoMap.put("address", addressNode);
userinfoMap.put("verified_claims", verifiedClaimNode);
Map<String, ClaimDetail> idTokenMap = new HashMap<>();

ClaimDetail claimDetail = new ClaimDetail("claim_value", null, true, "secondary");
idTokenMap.put("some_claim", claimDetail);

ClaimsV2 claimsV2 = new ClaimsV2();
claimsV2.setUserinfo(userinfoMap);
claimsV2.setId_token(idTokenMap);

Assert.assertTrue(claimSchemaValidator.isValid(claimsV2, null));
}

@Test
public void claimSchemaValidator_withTrustFrameWorkAsNull_thenFail() throws IOException {

ReflectionTestUtils.setField(claimSchemaValidator,"resourceLoader",resourceLoader);
ReflectionTestUtils.setField(claimSchemaValidator,"objectMapper",mapper);
ReflectionTestUtils.setField(claimSchemaValidator,"schemaUrl","classpath:/verified_claims_request_schema_test.json");

String address="{\"essential\":true}";
String verifiedClaims="[{\"verification\":{\"trust_framework\":{\"value\":null}},\"claims\":{\"name\":null,\"email\":{\"essential\":true}}},{\"verification\":{\"trust_framework\":{\"value\":\"pwd\"}},\"claims\":{\"birthdate\":{\"essential\":true},\"address\":null}},{\"verification\":{\"trust_framework\":{\"value\":\"kaif\"}},\"claims\":{\"gender\":{\"essential\":true},\"email\":{\"essential\":true}}}]";

JsonNode addressNode = mapper.readValue(address, JsonNode.class);
JsonNode verifiedClaimNode = mapper.readValue(verifiedClaims, JsonNode.class);

Map<String, JsonNode> userinfoMap = new HashMap<>();
userinfoMap.put("address", addressNode);
userinfoMap.put("verified_claims", verifiedClaimNode);
Map<String, ClaimDetail> idTokenMap = new HashMap<>();
ClaimDetail claimDetail = new ClaimDetail("claim_value", null, true, "secondary");

idTokenMap.put("some_claim", claimDetail);
ClaimsV2 claimsV2 = new ClaimsV2();
claimsV2.setUserinfo(userinfoMap);
claimsV2.setId_token(idTokenMap);

Assert.assertFalse(claimSchemaValidator.isValid(claimsV2, null));

}

@Test
public void claimSchemaValidator_withEssentialAsNonBoolean_thenFail() throws IOException {

ReflectionTestUtils.setField(claimSchemaValidator,"resourceLoader",resourceLoader);
ReflectionTestUtils.setField(claimSchemaValidator,"objectMapper",mapper);
ReflectionTestUtils.setField(claimSchemaValidator,"schemaUrl","classpath:/verified_claims_request_schema_test.json");

String address="{\"essential\":true}";
String verifiedClaims="[{\"verification\":{\"trust_framework\":{\"value\":\"pwd\"}},\"claims\":{\"name\":null,\"email\":{\"essential\":1}}},{\"verification\":{\"trust_framework\":{\"value\":\"pwd\"}},\"claims\":{\"birthdate\":{\"essential\":true},\"address\":null}},{\"verification\":{\"trust_framework\":{\"value\":\"kaif\"}},\"claims\":{\"gender\":{\"essential\":true},\"email\":{\"essential\":true}}}]";

JsonNode addressNode = mapper.readValue(address, JsonNode.class);
JsonNode verifiedClaimNode = mapper.readValue(verifiedClaims, JsonNode.class);

Map<String, JsonNode> userinfoMap = new HashMap<>();
userinfoMap.put("address", addressNode);
userinfoMap.put("verified_claims", verifiedClaimNode);
Map<String, ClaimDetail> idTokenMap = new HashMap<>();

ClaimDetail claimDetail = new ClaimDetail("claim_value", null, true, "secondary");

idTokenMap.put("some_claim", claimDetail);
ClaimsV2 claimsV2 = new ClaimsV2();
claimsV2.setUserinfo(userinfoMap);
claimsV2.setId_token(idTokenMap);

Assert.assertFalse(claimSchemaValidator.isValid(claimsV2, null));
}

@Test
public void test_ClaimSchemaValidator_withInvalidValue_thenFail() throws IOException {

ReflectionTestUtils.setField(claimSchemaValidator,"resourceLoader",resourceLoader);
ReflectionTestUtils.setField(claimSchemaValidator,"objectMapper",mapper);
ReflectionTestUtils.setField(claimSchemaValidator,"schemaUrl","classpath:/verified_claims_request_schema_test.json");

String address="{\"essential\":true}";
String verifiedClaims="[{\"verification\":{\"trust_framework\":{\"value\":\"pwd\"}},\"claims\":{\"name\":null,\"email\":{\"essential\":1}}},{\"verification\":{\"trust_framework\":{\"value\":\"pwd\"}},\"claims\":{\"birthdate\":{\"essential\":true},\"address\":null}},{\"verification\":{\"trust_framework\":{\"value\":\"kf\"}},\"claims\":{\"gender\":{\"essential\":true},\"email\":{\"essential\":true}}}]";

JsonNode addressNode = mapper.readValue(address, JsonNode.class);
JsonNode verifiedClaimNode = mapper.readValue(verifiedClaims, JsonNode.class);

Map<String, JsonNode> userinfoMap = new HashMap<>();
userinfoMap.put("address", addressNode);
userinfoMap.put("verified_claims", verifiedClaimNode);
Map<String, ClaimDetail> idTokenMap = new HashMap<>();
ClaimDetail claimDetail = new ClaimDetail("claim_value", null, true, "secondary");

idTokenMap.put("some_claim", claimDetail);
ClaimsV2 claimsV2 = new ClaimsV2();
claimsV2.setUserinfo(userinfoMap);
claimsV2.setId_token(idTokenMap);

Assert.assertFalse(claimSchemaValidator.isValid(claimsV2, null));
}
}
Loading
Loading