-
Notifications
You must be signed in to change notification settings - Fork 80
MOSIP-30573: test case coverage for zkservice #483
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
Conversation
Signed-off-by: nagendra0721 <nagendra0718@gmail.com>
Signed-off-by: nagendra0721 <nagendra0718@gmail.com>
WalkthroughAdds three new/expanded test suites: controller tests for ZKCryptoManager endpoints, comprehensive unit tests for ZKCryptoManager service implementation, and expanded signature service tests with additional trust/certificate and error-path scenarios. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Tip 📝 Customizable high-level summaries are now available in beta!You can now customize how CodeRabbit generates the high-level summary in your pull requests — including its content, structure, tone, and formatting.
Example instruction:
Note: This feature is currently in beta for Pro-tier users, and pricing will be announced later. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (5)
kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/zkcryptoservice/test/ZKCryptoManagerControlerTest.java (2)
35-38: Class name typo and possibly redundant test configurationThe test class name
ZKCryptoManagerControlerTest(singlel) is inconsistent withZKCryptoManagerControllerand may reduce discoverability; consider renaming toZKCryptoManagerControllerTest.Also,
@WebMvcTest(ZKCryptoManagerController.class)already slices the context around this controller. The additional@ContextConfigurationwith a@SpringBootApplication+@ComponentScanTestConfigmay be redundant and can pull in more beans than needed, slowing tests and blurring the slice boundary. Unless you need that broader scan, you can likely dropTestConfigand@ContextConfigurationand rely on@WebMvcTestplus the existing@MockBeans.Also applies to: 156-159
52-154: Consider adding authorization negative-path testsThe controller tests cover successful calls and a validation failure for a user with role
ZONAL_ADMIN, but there are no tests asserting behavior for unauthorized roles (e.g., missing role or different role leading to 403/401). Adding at least one negative-path test (e.g.,@WithMockUser(roles = "OTHER_ROLE")expecting forbidden) would strengthen coverage of the security configuration around these endpoints.kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/zkcryptoservice/test/ZKCryptoManagerServiceTest.java (3)
721-745: Tests encodingNullPointerExceptionbehavior may lock in undesirable contracts
testZkReEncryptRandomKeyWithNullKeyAliasesInMapandtestGetKeyAliasWithNullInMapintentionally drive the implementation intoNullPointerException(or accept either NPE orNoUniqueAliasException) when key-alias maps containnullvalues. That effectively codifies NPEs as acceptable behavior of the service.If the long-term intention is to harden this code, it would be preferable for the implementation to detect these invalid states and throw domain-specific exceptions (e.g.,
NoUniqueAliasException/ZKCryptoException) rather than NPEs, and for the tests to assert those instead. Right now these tests will fail if you later improve null handling, which may discourage such fixes.Also applies to: 1151-1178
680-717: Strengthen assertion for multi-reference-id encrypted random keyIn
testEncryptRandomKeyWithMultipleReferenceIds, the assertionassertTrue(response.getEncryptedRandomKey().contains(".") || response.getEncryptedRandomKey().length() > 0);will pass for any non-empty string, even if the expected dot separator for multiple keys is missing. If the intended behavior is that multiple reference IDs yield a dot-separated value, you can tighten this to:
assertTrue(response.getEncryptedRandomKey().contains("."));(or even assert exact structure) so the test actually protects the multi-key formatting contract.
110-137: Redundant manual field restoration and tight coupling to private implementation detailsSeveral tests modify private configuration fields via
ReflectionTestUtils.setField(e.g.,aesGCMTransformation,aesECBTransformation,pubKeyReferenceId,keyAliases) and then manually restore them at the end of the test. Given JUnit 4’s per-test-instance model and the@Before setUp()method that resets these fields before each test, the explicit “restore” steps are redundant and add noise.Additionally, the heavy reliance on private field names (and magic strings like
"REF1,REF2") makes these tests tightly coupled to implementation details, which will make refactoring the service harder.Consider:
- Dropping the explicit “restore” calls and relying on
setUp()for a clean baseline.- Where feasible, pushing configuration into constructor/setters so that tests can set it via public API rather than reflection. This will reduce brittleness while keeping the same coverage.
Also applies to: 381-403, 507-549, 848-880, 882-922, 1338-1385, 1423-1456
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/zkcryptoservice/test/ZKCryptoManagerControlerTest.java(1 hunks)kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/zkcryptoservice/test/ZKCryptoManagerServiceTest.java(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/zkcryptoservice/test/ZKCryptoManagerServiceTest.java (4)
kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/cryptomanager/constant/CryptomanagerConstant.java (1)
CryptomanagerConstant(10-67)kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/keymanagerservice/exception/NoUniqueAliasException.java (1)
NoUniqueAliasException(12-29)kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/exception/ZKCryptoException.java (1)
ZKCryptoException(12-38)kernel/kernel-keymanager-service/src/main/java/io/mosip/kernel/zkcryptoservice/exception/ZKKeyDerivationException.java (1)
ZKKeyDerivationException(12-38)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: build-kernel / maven-build
Signed-off-by: nagendra0721 <nagendra0718@gmail.com>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/signature/test/service/SignatureServiceTest.java (1)
7-38: JUnit Jupiter static imports will fail to compile—missingjunit-jupiter-apidependencyThe code imports
org.junit.jupiter.api.Assertions.assertEqualsandorg.junit.jupiter.api.Assertions.assertThrows, but the pom.xml declares onlyjunit:junit:4.12(which does not includeassertThrowsinorg.junit.Assert) and does not includejunit-jupiter-apias a dependency. Even thoughjunit-vintage-engineis present, it does not provide the Jupiter assertions API.JUnit 4.13+ provides
Assert.assertThrows, and JUnit 5 Jupiter providesorg.junit.jupiter.api.Assertions.assertThrows.Action: Either:
- Add
junit-jupiter-apito test dependencies in pom.xml and statically importorg.junit.jupiter.api.Assertions.*.- Upgrade to
junit:junit:4.13.2and useorg.junit.Assert.assertThrowsinstead.- Rewrite exception assertions using JUnit 4 patterns (try/catch or
@Test(expected = ...)).Without this fix, test compilation will fail.
♻️ Duplicate comments (5)
kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/signature/test/service/SignatureServiceTest.java (5)
791-805: Exception-path test is good; relies onassertThrowscomment above
testJsonParsingErroris a solid addition: it checks that malformed JWS/JWT input leads toRequestExceptionwithINVALID_VERIFY_INPUTfor both v1 and v2 verify.Note that it depends on
org.junit.jupiter.api.Assertions.assertThrowsandassertEquals; this shares the same JUnit version concern mentioned for the imports.
807-817: Empty data JWS/JWT sign test is correct; JUnit concern applies
testJWSsignEmptyDataExceptioncorrectly enforces that an emptydataToSigntriggersINVALID_INPUT.Again, this uses
assertThrows/assertEqualsfrom JUnit Jupiter; please align with the chosen JUnit version as noted earlier.
819-835: SignV2 invalid app and empty data behavior well captured
testSignV2EmptyDataExceptiondistinguishes:
INVALID_APP_ID→SIGN_NOT_ALLOWED.- Valid app
"TEST"but missing data →INVALID_INPUT.The logic looks consistent. This test also relies on Jupiter assertions, so it’s subject to the same JUnit version alignment comment.
875-896: JWT sign v2 negative-paths are appropriate
testJWTSignV2Exceptionchecks:
- Invalid appId →
SIGN_NOT_ALLOWED.- Valid appId but missing data →
INVALID_INPUT.- Non‑JSON payload →
INVALID_JSON.The flow is clear and enforces the expected error codes. Same JUnit Jupiter assertion caveat applies.
898-921: JWS sign v2 negative-paths mirror JWT v2 and look consistent
testJWSsignV2Exceptionmirrors JWT v2 for JWS:
- Invalid appId →
SIGN_NOT_ALLOWED.- Valid appId but missing data →
INVALID_INPUT.- Non‑JSON data with
validateJson=true→INVALID_JSON.This symmetry is good for maintenance. It also shares the same JUnit 5 assertion dependency.
🧹 Nitpick comments (4)
kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/signature/test/service/SignatureServiceTest.java (4)
57-58: Field injection forKeymanagerUtilis consistent but could be made privateAutowiring
KeymanagerUtilmatches the rest of the class usage and enables the new trust-validation tests. For consistency with the other fields, consider making itprivateas well, but that’s purely cosmetic.
322-333: Good extra JWS coverage; consider separating scenarios for readabilityThe added calls in
testJwsSign(emptyapplicationIdandED25519_SIGN) broaden coverage of default app handling and ED25519 keys.To reduce coupling between scenarios, you might optionally:
- Create a fresh
JWSSignatureRequestDtoper distinct scenario, or- Explicitly reset all relevant fields before each sign call.
Not required, but it would make the test intent clearer.
654-663: Trust v2 tests are clear; minor collection simplification possibleThe new
testValidateTrustV2scenarios verify:
validateTrust=truewithout domain →TRUST_NOT_VERIFIED_NO_DOMAIN.- With domain set and a single certificate →
TRUST_CERT_PATH_NOT_VALID.That’s good coverage. You could simplify the list creation as:
List<Certificate> certificateList = Collections.singletonList(keymanagerUtil.convertToCertificate(pemCertificate));instead of wrapping
Collections.singleton(...)in anArrayList<>, unless mutability is required.
752-764: JwsSignV2 ED25519 and default app scenarioThe extra calls in
testJwsSignV2give coverage for:
- Empty
applicationIdwith existingKERNEL/SIGNmaster key.- ED25519 signing via
ED25519_SIGNreference.Behaviorally this looks good. As with earlier tests, consider separate DTO instances per scenario if you later find these tests hard to maintain.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/signature/test/service/SignatureServiceTest.java(10 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: build-kernel / maven-build
🔇 Additional comments (7)
kernel/kernel-keymanager-service/src/test/java/io/mosip/kernel/signature/test/service/SignatureServiceTest.java (7)
217-225: Nice additional ED25519 verification pathExtending
testJwtVerifyto cover theED25519_SIGNreference increases confidence that the verify flow works across key types. The reuse of existing request objects keeps the test compact and looks fine.
395-404: Sign v2 default-application behavior well coveredThe new block in
testSignv2that generates aKERNEL/SIGNkey and then signs withapplicationIdset to""nicely validates the default appId behavior on v2 signing. Assertions on non-null signature and timestamp are appropriate here.
483-500: JwtSignV2: default app/ref and header variations well testedThe extra flows in
testJwtSignV2(nullapplicationId/referenceId, then updated additional headers includingkidandaud) give good coverage of:
- Default key selection when identifiers are omitted.
- Robustness to different header combinations.
The assertions on
jwtSignedDatapresence are sufficient for this level.
694-708: JwtVerifyV2: default app/ref behavior thoroughly exercisedThe added part of
testJwtVerifyV2that:
- Generates a
KERNEL/SIGNkey,- Signs with empty app/ref and no certificate chain,
- Verifies with empty
applicationId,nicely validates fallback behavior for v2 verify. The assertions on validity and message are appropriate.
766-788: New default appId/refId verify test is useful
testJwtVerifyDefaultAppIDAndRefIDcleanly asserts that:
- Signing without explicit app/ref,
- Then verifying without app/ref,
still succeeds (assuming the default
KERNEL/SIGNkey exists). This is a valuable regression test for defaulting logic.
837-872: Raw sign negative-path coverage is strong; also subject to JUnit setup
rawSignExceptionnicely chains multiple scenarios:
- Invalid appId →
SIGN_NOT_ALLOWED.- Valid appId with missing data →
INVALID_INPUT.- Default app (null) with invalid response format →
KeymanagerServiceException+INVALID_FORMAT_ERROR.- Then a successful
base64urlresponse path.The structure and asserted error codes look good. Just ensure the use of
assertThrowsis supported by your JUnit configuration as already discussed.
923-933: JWT verify v2 empty-signature guard is correct
testJWTVerifyV2EmptySignDatavalidates that an emptyjwtSignatureDataleads toINVALID_INPUT. The behavior is correct; just ensureassertThrowsis available under your chosen JUnit version.
Summary by CodeRabbit
✏️ Tip: You can customize this high-level summary in your review settings.