Skip to content

test: add Jwt, SM2Encryption and SM3Password util test.#310

Merged
chilingling merged 2 commits intoopentiny:developfrom
msslulu:feat/dev_ut
Apr 30, 2026
Merged

test: add Jwt, SM2Encryption and SM3Password util test.#310
chilingling merged 2 commits intoopentiny:developfrom
msslulu:feat/dev_ut

Conversation

@msslulu
Copy link
Copy Markdown
Contributor

@msslulu msslulu commented Apr 30, 2026

feat: jwtutil,SM2EncryptionUtil,SM3PasswordUtil UT

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced input validation in authentication and cryptographic utilities to reject null parameters and prevent potential runtime errors.
  • Tests

    • Added comprehensive test suites covering authentication token handling, encryption/decryption workflows, and password hashing with edge cases, malformed inputs, and concurrency scenarios.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 30, 2026

Walkthrough

Defensive null-argument validation is added to JWT token generation/validation and SM3 password hashing utilities. Comprehensive test suites are introduced for JWT utilities, SM2 encryption, and SM3 password operations, covering token lifecycle, cryptographic operations, edge cases, and failure scenarios.

Changes

Cohort / File(s) Summary
JWT Utilities
base/src/main/java/.../JwtUtil.java, base/src/test/java/.../JwtUtilTest.java
Added null-argument guards to generateToken() and validateToken() methods. New test suite with 352 lines covers token generation/validation round-trips, null/empty inputs, expired tokens (via helper), blacklisted tokens, signature/algorithm/claims tampering, and secret configuration validation across dev and non-dev profiles.
SM3 Password Utilities
base/src/main/java/.../SM3PasswordUtil.java, base/src/test/java/.../SM3PasswordUtilTest.java
Added null-argument validation for sm3Hash() and verifyPassword() methods. New 493-line test suite validates hash formatting, salt sensitivity, determinism, Unicode/special characters, very long/large inputs, tamper detection, password verification workflows, concurrent access, and performance scenarios.
SM2 Encryption Tests
base/src/test/java/.../SM2EncryptionUtilTest.java
New 337-line integration test suite for SM2EncryptionUtil covering successful keypair generation, encrypt/decrypt for normal/Unicode/special-character/binary/very-large plaintexts, Base64 key conversions, and failure modes including null inputs, empty/corrupted data, and decryption with invalid keys.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 With null guards standing firm and brave,
Our tokens and hashes we now save!
Encryption tested, corner to corner—
No edge case left for any mourner! 🔐✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 51.22% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title accurately describes the main change: adding unit tests for JWT, SM2Encryption, and SM3Password utilities, matching the file summaries and PR objectives.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

chilingling
chilingling previously approved these changes Apr 30, 2026
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

🧹 Nitpick comments (1)
base/src/test/java/com/tinyengine/it/login/utils/SM2EncryptionUtilTest.java (1)

228-239: ⚡ Quick win

These cases don't actually validate raw binary or “non-UTF8” support.

Both tests first coerce bytes into a Java String with ISO-8859-1, so the utility is still just encrypting text. If byte fidelity matters, add byte-array based APIs/tests; otherwise rename these cases to reflect that they are ISO-8859-1 text fixtures.

Also applies to: 257-268

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@base/src/test/java/com/tinyengine/it/login/utils/SM2EncryptionUtilTest.java`
around lines 228 - 239, The test encryptAndDecryptWithNonUTF8Characters (and the
similar case at lines 257-268) mischaracterizes ISO-8859-1 fixtures as
"non-UTF8" raw-binary tests: they convert raw bytes into a Java String before
calling SM2EncryptionUtil.encrypt/decrypt, so the utility is still operating on
text. Fix by either (A) adding byte-array based APIs and tests that call new
SM2EncryptionUtil.encrypt(byte[]) / decrypt(byte[]) and assert byte-array
fidelity, or (B) if byte-level support is not needed, rename the test methods
and update their descriptions to indicate they are ISO-8859-1 text fixtures
(e.g., encryptAndDecryptWithIso88591Characters) and keep using
SM2EncryptionUtil.encrypt/decrypt as-is.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@base/src/main/java/com/tinyengine/it/login/utils/JwtUtil.java`:
- Around line 133-138: The username null-check belongs in the shared
implementation: move the guard into the public generateToken(String username,
String roles, String userId, Object tenants, Integer platformId) so it validates
username before any Claims are built (throw IllegalArgumentException("Username
must not be null") if null); remove the duplicate check from the List<Tenant>
overload generateToken(String, String, String, List<Tenant>, Integer) so both
call paths use the same validation and behavior.

In `@base/src/main/java/com/tinyengine/it/login/utils/SM3PasswordUtil.java`:
- Around line 59-62: The current verifyPassword method throws
IllegalArgumentException when any of inputPassword, storedHash, or salt are
null, which turns upstream decryption failures into exceptions; change
verifyPassword(String inputPassword, String storedHash, String salt) to treat
nulls as authentication failures by returning false instead of throwing for null
inputs, preserving thrown exceptions only for genuine crypto errors, or
alternatively ensure LoginController.authenticate checks the decrypted salt for
null and returns a normal auth-failure path; locate the verifyPassword method in
SM3PasswordUtil and update the null-check branch to return false (and keep other
exception handling intact).

In `@base/src/test/java/com/tinyengine/it/login/utils/JwtUtilTest.java`:
- Around line 47-64: The tests for validateSecretConfiguration rely on
environment state but call System.setProperty which doesn't affect System.getenv
used by jwtUtil; make the tests deterministic by mocking or injecting the secret
source instead of relying on process env: update JwtUtilTest to stub the value
read by validateSecretConfiguration (either by injecting a SecretsProvider or by
setting jwtUtil.cachedSecret directly) and keep using the mocked Environment
(environment.getActiveProfiles()) to simulate "dev" vs "prod"; ensure the
invalid-secret test sets the cachedSecret to a short value (or inject a mock
that returns "short") so validateSecretConfiguration exercises the
invalid-secret branch rather than relying on System.setProperty.
- Around line 256-325: Tests like
validateTokenReturnsFalseForTokenWithMissingClaims,
validateTokenHandlesTokenWithExtraClaims,
validateTokenHandlesTokenWithInvalidExpirationDate,
validateTokenHandlesTokenWithNullClaims,
validateTokenHandlesTokenWithEmptyClaims and
validateTokenHandlesTokenWithInvalidAlgorithm currently produce false positives
because they stub tokenBlacklistService.isTokenBlacklisted(token) and use naive
String.replace on a Base64URL compact JWT; instead remove the blacklist stub in
these parsing-focused tests and construct truly malformed tokens by splitting
the generated token on '.', Base64URL-decoding the header or payload part,
mutating the JSON (e.g., remove the "claims" key, add extra fields, change "exp"
value to non-numeric, set claims to null or {} , or change "alg" in the decoded
header), then Base64URL-encode the modified part and reassemble the token (leave
signature unchanged or corrupt it if needed) and pass that to
jwtUtil.validateToken to exercise parsing/claim validation rather than the
blacklist branch.

In `@base/src/test/java/com/tinyengine/it/login/utils/SM2EncryptionUtilTest.java`:
- Around line 140-145: The test decryptWithInvalidCipherText (and the similar
assertions at the other locations) uses assertThrows(Exception.class, ...) which
is too broad; change these to assert the specific exception class that
SM2EncryptionUtil.decrypt actually throws (for example IllegalArgumentException,
BadPaddingException, or the custom SM2-related exception) or assert the
exception message/root cause to verify it failed due to invalid cipher text.
Locate the failing assertions in SM2EncryptionUtilTest (method
decryptWithInvalidCipherText and the two other assertions around lines 209-210
and 252-253) and replace assertThrows(Exception.class, ...) with
assertThrows(TheConcreteException.class, ...) and/or add assertions on
ex.getMessage() or ex.getCause() to validate the invalid-cipher reason.

In `@base/src/test/java/com/tinyengine/it/login/utils/SM3PasswordUtilTest.java`:
- Around line 407-418: The test's worker Runnable in SM3PasswordUtilTest catches
only Exception so AssertionError from assertTrue can slip by; update the task to
catch Throwable (or specifically AssertionError) and assign it to the shared
exceptions[0], or refactor the concurrent test to use an ExecutorService and
submit Callables and call Future.get() so any AssertionError/Throwable from
createPassword/verifyPassword propagates to the main thread; reference the
Runnable task, the exceptions array, assertTrue calls, and
SM3PasswordUtil.createPassword/verifyPassword when making the change.
- Around line 149-176: Update the tests for SM3PasswordUtil to reflect the new
exception contract: change the `@DisplayName` strings that currently mention
NullPointerException to say IllegalArgumentException, update the three
assertThrows calls in sm3HashWithNullData_ThrowsNullPointerException,
sm3HashWithNullSalt_ThrowsNullPointerException and
verifyPasswordWithNullParams_ThrowsException to
assertThrows(IllegalArgumentException.class, ...) when calling
SM3PasswordUtil.sm3Hash(...) and SM3PasswordUtil.verifyPassword(...), and
optionally rename the test method names to end with
ThrowsIllegalArgumentException to keep names consistent with the assertions.
- Around line 265-275: The `@Timeout` values in SM3PasswordUtilTest (notably the
performance_BatchCreateAndVerify test) are too tight for CI and should be
loosened or moved to a perf suite; change the annotation on
performance_BatchCreateAndVerify from `@Timeout`(2) to a much larger value (e.g.,
`@Timeout`(30)) or remove the timeout and annotate the test as `@Disabled` while
moving the scenario to a dedicated benchmark; apply the same treatment to the
other slow test referenced (lines 477-491) so both tests either use relaxed
timeouts or are migrated to a performance test suite.

---

Nitpick comments:
In `@base/src/test/java/com/tinyengine/it/login/utils/SM2EncryptionUtilTest.java`:
- Around line 228-239: The test encryptAndDecryptWithNonUTF8Characters (and the
similar case at lines 257-268) mischaracterizes ISO-8859-1 fixtures as
"non-UTF8" raw-binary tests: they convert raw bytes into a Java String before
calling SM2EncryptionUtil.encrypt/decrypt, so the utility is still operating on
text. Fix by either (A) adding byte-array based APIs and tests that call new
SM2EncryptionUtil.encrypt(byte[]) / decrypt(byte[]) and assert byte-array
fidelity, or (B) if byte-level support is not needed, rename the test methods
and update their descriptions to indicate they are ISO-8859-1 text fixtures
(e.g., encryptAndDecryptWithIso88591Characters) and keep using
SM2EncryptionUtil.encrypt/decrypt as-is.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: cffe2758-3b1c-4c12-abab-eef9489ab198

📥 Commits

Reviewing files that changed from the base of the PR and between 36730b1 and e3c817f.

📒 Files selected for processing (5)
  • base/src/main/java/com/tinyengine/it/login/utils/JwtUtil.java
  • base/src/main/java/com/tinyengine/it/login/utils/SM3PasswordUtil.java
  • base/src/test/java/com/tinyengine/it/login/utils/JwtUtilTest.java
  • base/src/test/java/com/tinyengine/it/login/utils/SM2EncryptionUtilTest.java
  • base/src/test/java/com/tinyengine/it/login/utils/SM3PasswordUtilTest.java

Comment thread base/src/main/java/com/tinyengine/it/login/utils/JwtUtil.java
Comment thread base/src/test/java/com/tinyengine/it/login/utils/JwtUtilTest.java
Comment thread base/src/test/java/com/tinyengine/it/login/utils/JwtUtilTest.java
@chilingling chilingling changed the title feat: ut test: ut Apr 30, 2026
@chilingling chilingling changed the title test: ut test: add Jwt, SM2Encryption and SM3Password util test. Apr 30, 2026
@chilingling chilingling merged commit ee9d024 into opentiny:develop Apr 30, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants