Skip to content

Make AuthenticationType an enum#424

Open
jmendeza wants to merge 2 commits intocraftercms:developfrom
jmendeza:feature/6061
Open

Make AuthenticationType an enum#424
jmendeza wants to merge 2 commits intocraftercms:developfrom
jmendeza:feature/6061

Conversation

@jmendeza
Copy link
Copy Markdown
Member

@jmendeza jmendeza commented Mar 30, 2026

Make AuthenticationType an enum
craftercms/craftercms#6061

Summary by CodeRabbit

  • Refactor

    • Stronger type safety for Git authentication configuration, reducing misconfiguration risk and improving validation.
  • New Features

    • JSON parsing now accepts enum-like values case-insensitively, making integrations more tolerant of input casing.
  • Tests

    • Unit tests updated to align with the new authentication typing and parsing behavior.

@jmendeza
Copy link
Copy Markdown
Member Author

This is interdependent with craftercms/studio#3906

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 30, 2026

Walkthrough

Refactors git auth types from a String-constants interface to a typed AuthenticationType enum, updates factory, builder, and tests to use the enum, and adds a new Jackson CaseInsensitiveEnumDeserializer for case-insensitive enum deserialization.

Changes

Cohort / File(s) Summary
Auth type definition
git/src/main/java/org/craftercms/commons/git/utils/AuthenticationType.java
Replaced a String-constants interface with a public enum AuthenticationType holding string values and a getValue() accessor.
Factory & Builder
git/src/main/java/org/craftercms/commons/git/utils/AuthConfiguratorFactory.java, git/src/main/java/org/craftercms/commons/git/utils/TypeBasedAuthConfiguratorBuilder.java
Method/constructor signatures changed to accept AuthenticationType instead of String; internal switch/flow updated to use enum values.
Tests
git/src/test/java/org/craftercms/commons/git/utils/TypeBasedAuthConfiguratorBuilderTest.java
Test helper and usages updated to pass AuthenticationType enum constants.
Jackson utility
utilities/src/main/java/org/craftercms/commons/jackson/CaseInsensitiveEnumDeserializer.java
Added new contextual deserializer that maps JSON string values to enum constants case-insensitively and throws InvalidFormatException on no-match.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: converting AuthenticationType from an interface with constants to an enum.
Description check ✅ Passed The description includes a ticket reference as required by the template, but lacks detail on what the PR accomplishes beyond the title.

✏️ 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.

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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
git/src/main/java/org/craftercms/commons/git/utils/TypeBasedAuthConfiguratorBuilder.java (1)

49-66: ⚠️ Potential issue | 🔴 Critical

Use unqualified enum constants in switch cases (current code will not compile).

The enum switch statement uses qualified labels like case AuthenticationType.NONE: which is invalid Java syntax. All four case statements must use unqualified constants: case NONE:, case BASIC:, case TOKEN:, and case PRIVATE_KEY:.

✅ Suggested fix
 	switch (authType) {
-		case AuthenticationType.NONE:
+		case NONE:
 			logger.debug("No authentication will be used");
 			return new NoopAuthConfigurator();
-		case AuthenticationType.BASIC:
+		case BASIC:
 			if (isEmpty(username) && isEmpty(password)) {
 				throw new IllegalStateException("basic auth requires a username or password");
 			}
 			logger.debug("Username/password authentication will be used");
 			return new BasicUsernamePasswordAuthConfigurator(username, password);
-		case AuthenticationType.TOKEN:
+		case TOKEN:
 			if (isEmpty(username)) {
 				throw new IllegalStateException("token auth requires a username");
 			}
 			logger.debug("Token authentication will be used");
 			return new BasicUsernamePasswordAuthConfigurator(username, StringUtils.EMPTY);
-		case AuthenticationType.PRIVATE_KEY:
+		case PRIVATE_KEY:
 			logger.debug("SSH private key authentication will be used");
 			return new SshPrivateKeyAuthConfigurator(sshConfig, privateKeyPath, privateKeyPassphrase);
 		default:
 			throw new IllegalStateException("Unsupported auth type " + authType);
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@git/src/main/java/org/craftercms/commons/git/utils/TypeBasedAuthConfiguratorBuilder.java`
around lines 49 - 66, The switch in TypeBasedAuthConfiguratorBuilder uses
fully-qualified enum labels which don't compile; update the switch cases in the
method handling authType to use unqualified enum constants (replace
AuthenticationType.NONE/BASIC/TOKEN/PRIVATE_KEY with
NONE/BASIC/TOKEN/PRIVATE_KEY) so the cases match Java syntax, leaving
surrounding logic (checks for username/password, returned configurator classes
NoopAuthConfigurator, BasicUsernamePasswordAuthConfigurator, and related logger
messages) unchanged.
🧹 Nitpick comments (1)
git/src/main/java/org/craftercms/commons/git/utils/TypeBasedAuthConfiguratorBuilder.java (1)

42-44: Fail fast on null authType in constructor.

A null authType will fail later during switch; validating in constructor gives a clearer error path.

💡 Suggested hardening
+import java.util.Objects;
+
 public TypeBasedAuthConfiguratorBuilder(File sshConfig, AuthenticationType authType) {
 	super(sshConfig);
-	this.authType = authType;
+	this.authType = Objects.requireNonNull(authType, "authType must not be null");
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@git/src/main/java/org/craftercms/commons/git/utils/TypeBasedAuthConfiguratorBuilder.java`
around lines 42 - 44, Validate the constructor argument authType in
TypeBasedAuthConfiguratorBuilder(File sshConfig, AuthenticationType authType)
and fail fast: if authType is null throw an IllegalArgumentException (or
NullPointerException) with a clear message (e.g., "authType must not be null")
before assigning this.authType, so downstream switch logic in this class won't
encounter a null and will produce a clearer error path.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In
`@git/src/main/java/org/craftercms/commons/git/utils/TypeBasedAuthConfiguratorBuilder.java`:
- Around line 49-66: The switch in TypeBasedAuthConfiguratorBuilder uses
fully-qualified enum labels which don't compile; update the switch cases in the
method handling authType to use unqualified enum constants (replace
AuthenticationType.NONE/BASIC/TOKEN/PRIVATE_KEY with
NONE/BASIC/TOKEN/PRIVATE_KEY) so the cases match Java syntax, leaving
surrounding logic (checks for username/password, returned configurator classes
NoopAuthConfigurator, BasicUsernamePasswordAuthConfigurator, and related logger
messages) unchanged.

---

Nitpick comments:
In
`@git/src/main/java/org/craftercms/commons/git/utils/TypeBasedAuthConfiguratorBuilder.java`:
- Around line 42-44: Validate the constructor argument authType in
TypeBasedAuthConfiguratorBuilder(File sshConfig, AuthenticationType authType)
and fail fast: if authType is null throw an IllegalArgumentException (or
NullPointerException) with a clear message (e.g., "authType must not be null")
before assigning this.authType, so downstream switch logic in this class won't
encounter a null and will produce a clearer error path.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 379739bb-f051-4658-acb7-9c0a558671bf

📥 Commits

Reviewing files that changed from the base of the PR and between 093c249 and 5e54eee.

📒 Files selected for processing (4)
  • git/src/main/java/org/craftercms/commons/git/utils/AuthConfiguratorFactory.java
  • git/src/main/java/org/craftercms/commons/git/utils/AuthenticationType.java
  • git/src/main/java/org/craftercms/commons/git/utils/TypeBasedAuthConfiguratorBuilder.java
  • git/src/test/java/org/craftercms/commons/git/utils/TypeBasedAuthConfiguratorBuilderTest.java

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: 1

🧹 Nitpick comments (2)
utilities/src/main/java/org/craftercms/commons/jackson/CaseInsensitiveEnumDeserializer.java (2)

32-32: Add generic type parameter to JsonDeserializer.

Using the raw type JsonDeserializer loses type safety and generates compiler warnings. Specify the generic parameter to match the deserialize return type.

♻️ Proposed fix
-public class CaseInsensitiveEnumDeserializer extends JsonDeserializer implements ContextualDeserializer {
+public class CaseInsensitiveEnumDeserializer extends JsonDeserializer<Enum<?>> implements ContextualDeserializer {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@utilities/src/main/java/org/craftercms/commons/jackson/CaseInsensitiveEnumDeserializer.java`
at line 32, The class CaseInsensitiveEnumDeserializer currently extends the raw
JsonDeserializer which loses type safety; update its declaration to use a
matching generic parameter (e.g., JsonDeserializer<T> or
JsonDeserializer<Enum<?>>) so the generic matches the deserialize method's
return type, adjust the class signature and any type parameters accordingly, and
ensure the deserialize(...) and createContextual(...) method signatures use the
same generic type to eliminate raw-type warnings and restore compile-time type
checking.

54-65: Add @SuppressWarnings for unchecked cast and consider handling JSON null.

The unchecked cast on line 57 is unavoidable due to type erasure. Adding @SuppressWarnings("unchecked") documents this intentional cast and suppresses compiler warnings.

Also, if fieldType is null (before the createContextual fix), this will throw NPE. After the fix, consider whether JSON null should return null or throw.

♻️ Proposed fix
 	`@Override`
+	`@SuppressWarnings`("unchecked")
 	public Enum<?> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JacksonException {
 		String value = p.getText();
+		if (value == null) {
+			return null;
+		}
 		Class<Enum<?>> enumClass = (Class<Enum<?>>) fieldType.getRawClass();
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@utilities/src/main/java/org/craftercms/commons/jackson/CaseInsensitiveEnumDeserializer.java`
around lines 54 - 65, The deserialize method performs an unavoidable unchecked
cast of fieldType.getRawClass() to Class<Enum<?>> and needs an explicit
`@SuppressWarnings`("unchecked") to document/silence it; add that annotation to
the deserialize method (or immediately above the cast) and keep the cast as-is.
Also guard against JSON null by checking the parser token (e.g.,
JsonToken.VALUE_NULL) at the start of deserialize and return null (or handle per
desired behavior) instead of proceeding, and ensure you still reference
fieldType (set via createContextual) when doing the enumClass lookup.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@utilities/src/main/java/org/craftercms/commons/jackson/CaseInsensitiveEnumDeserializer.java`:
- Around line 42-52: createContextual currently returns "this" when property is
null leaving CaseInsensitiveEnumDeserializer.fieldType unset and causing an NPE
in deserialize(); change createContextual to use ctxt.getContextualType() as a
fallback: if property != null use property.getType(), else try JavaType ctxType
= ctxt.getContextualType(); if ctxType != null return new
CaseInsensitiveEnumDeserializer(ctxType); otherwise fall back to returning this
— this ensures fieldType is initialized for root-level enum deserialization and
prevents the NPE in deserialize().

---

Nitpick comments:
In
`@utilities/src/main/java/org/craftercms/commons/jackson/CaseInsensitiveEnumDeserializer.java`:
- Line 32: The class CaseInsensitiveEnumDeserializer currently extends the raw
JsonDeserializer which loses type safety; update its declaration to use a
matching generic parameter (e.g., JsonDeserializer<T> or
JsonDeserializer<Enum<?>>) so the generic matches the deserialize method's
return type, adjust the class signature and any type parameters accordingly, and
ensure the deserialize(...) and createContextual(...) method signatures use the
same generic type to eliminate raw-type warnings and restore compile-time type
checking.
- Around line 54-65: The deserialize method performs an unavoidable unchecked
cast of fieldType.getRawClass() to Class<Enum<?>> and needs an explicit
`@SuppressWarnings`("unchecked") to document/silence it; add that annotation to
the deserialize method (or immediately above the cast) and keep the cast as-is.
Also guard against JSON null by checking the parser token (e.g.,
JsonToken.VALUE_NULL) at the start of deserialize and return null (or handle per
desired behavior) instead of proceeding, and ensure you still reference
fieldType (set via createContextual) when doing the enumClass lookup.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 42b2b5af-dbf5-424f-828b-b70afbce5286

📥 Commits

Reviewing files that changed from the base of the PR and between 5e54eee and bb3ea88.

📒 Files selected for processing (1)
  • utilities/src/main/java/org/craftercms/commons/jackson/CaseInsensitiveEnumDeserializer.java

@jmendeza jmendeza marked this pull request as ready for review March 30, 2026 21:00
@jmendeza jmendeza requested a review from sumerjabri as a code owner March 30, 2026 21:00
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.

1 participant