Skip to content

Commit 0fe1c7f

Browse files
committed
authhelper: SAST (SonarLint) Fixes
Signed-off-by: kingthorin <[email protected]>
1 parent d41b452 commit 0fe1c7f

19 files changed

+212
-215
lines changed

addOns/authhelper/CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
1414
- Tweaked the auth report summary keys.
1515
- Only check URLs and methods once for being good verification requests.
1616
- Added API support to the browser based auth method proxy.
17+
- Maintenance changes.
1718

1819
### Fixed
1920
- Correctly read the API parameters when setting up Browser Based Authentication.

addOns/authhelper/src/main/java/org/zaproxy/addon/authhelper/AuthDiagnosticCollector.java

+8-8
Original file line numberDiff line numberDiff line change
@@ -205,8 +205,8 @@ protected JSONObject sanitiseJson(JSONObject jsonObject) {
205205
JSONObject sanObj = new JSONObject();
206206
for (Object key : jsonObject.keySet()) {
207207
Object val = jsonObject.get(key);
208-
if (val instanceof String) {
209-
sanObj.put(key, getSanitizedToken((String) val));
208+
if (val instanceof String valStr) {
209+
sanObj.put(key, getSanitizedToken(valStr));
210210
} else {
211211
sanObj.put(key, val);
212212
}
@@ -215,17 +215,17 @@ protected JSONObject sanitiseJson(JSONObject jsonObject) {
215215
}
216216

217217
protected Object sanitiseJson(Object obj) {
218-
if (obj instanceof JSONObject) {
219-
return sanitiseJson((JSONObject) obj);
220-
} else if (obj instanceof JSONArray) {
218+
if (obj instanceof JSONObject jObj) {
219+
return sanitiseJson(jObj);
220+
} else if (obj instanceof JSONArray jArr) {
221221
JSONArray sanArr = new JSONArray();
222-
Object[] oa = ((JSONArray) obj).toArray();
222+
Object[] oa = jArr.toArray();
223223
for (int i = 0; i < oa.length; i++) {
224224
sanArr.add(sanitiseJson(oa[i]));
225225
}
226226
return sanArr;
227-
} else if (obj instanceof String) {
228-
return getSanitizedToken((String) obj);
227+
} else if (obj instanceof String objStr) {
228+
return getSanitizedToken(objStr);
229229

230230
} else {
231231
return obj;

addOns/authhelper/src/main/java/org/zaproxy/addon/authhelper/AuthTestDialog.java

+5-6
Original file line numberDiff line numberDiff line change
@@ -168,11 +168,10 @@ public AuthTestDialog(ExtensionAuthhelper ext, Frame owner) {
168168
JButton copyButton =
169169
new JButton(Constant.messages.getString("authhelper.auth.test.dialog.button.copy"));
170170
copyButton.addActionListener(
171-
l -> {
172-
Toolkit.getDefaultToolkit()
173-
.getSystemClipboard()
174-
.setContents(new StringSelection(diagnosticField.getText()), null);
175-
});
171+
l ->
172+
Toolkit.getDefaultToolkit()
173+
.getSystemClipboard()
174+
.setContents(new StringSelection(diagnosticField.getText()), null));
176175

177176
buttonPanel.add(new JLabel(), LayoutHelper.getGBC(0, 0, 1, 0.3D));
178177
buttonPanel.add(copyButton, LayoutHelper.getGBC(1, 0, 1, 0.3D));
@@ -496,7 +495,7 @@ public JButton[] getExtraButtons() {
496495
@Override
497496
public void save() {
498497
resetResultsPanel();
499-
Thread t = new Thread(() -> authenticate(), "ZAP-auth-tester");
498+
Thread t = new Thread(this::authenticate, "ZAP-auth-tester");
500499
t.start();
501500
// Save the values for next time
502501
this.saveDetails();

addOns/authhelper/src/main/java/org/zaproxy/addon/authhelper/AuthUtils.java

+20-23
Original file line numberDiff line numberDiff line change
@@ -469,7 +469,7 @@ private static boolean internalAuthenticateAsUser(
469469
boolean pwdAdded = false;
470470

471471
Iterator<AuthenticationStep> it = steps.stream().sorted().iterator();
472-
for (; it.hasNext(); ) {
472+
while (it.hasNext()) {
473473
AuthenticationStep step = it.next();
474474
if (!step.isEnabled()) {
475475
continue;
@@ -537,7 +537,7 @@ private static boolean internalAuthenticateAsUser(
537537
sendReturn(diags, wd, pwdField);
538538
}
539539

540-
for (; it.hasNext(); ) {
540+
while (it.hasNext()) {
541541
AuthenticationStep step = it.next();
542542
if (!step.isEnabled()) {
543543
continue;
@@ -555,18 +555,15 @@ private static boolean internalAuthenticateAsUser(
555555
incStatsCounter(loginPageUrl, AUTH_BROWSER_PASSED_STATS);
556556
AuthUtils.sleep(TimeUnit.SECONDS.toMillis(waitInSecs));
557557

558-
if (context != null) {
559-
if (context.getAuthenticationMethod().getPollUrl() == null) {
560-
// We failed to identify a suitable URL for polling.
561-
// This can happen for more traditional apps - refresh the current one in case
562-
// its a good option.
563-
wd.get(wd.getCurrentUrl());
564-
AuthUtils.sleep(TimeUnit.SECONDS.toMillis(1));
565-
diags.recordStep(
566-
wd,
567-
Constant.messages.getString(
568-
"authhelper.auth.method.diags.steps.refresh"));
569-
}
558+
if (context != null && context.getAuthenticationMethod().getPollUrl() == null) {
559+
// We failed to identify a suitable URL for polling.
560+
// This can happen for more traditional apps - refresh the current one in case
561+
// its a good option.
562+
wd.get(wd.getCurrentUrl());
563+
AuthUtils.sleep(TimeUnit.SECONDS.toMillis(1));
564+
diags.recordStep(
565+
wd,
566+
Constant.messages.getString("authhelper.auth.method.diags.steps.refresh"));
570567
}
571568
return true;
572569
}
@@ -755,7 +752,7 @@ public static Map<String, SessionToken> getResponseSessionTokens(HttpMessage msg
755752
} catch (JSONException e) {
756753
LOGGER.debug(
757754
"Unable to parse authentication response body from {} as JSON: {} ",
758-
msg.getRequestHeader().getURI().toString(),
755+
msg.getRequestHeader().getURI(),
759756
responseData,
760757
e);
761758
}
@@ -784,7 +781,7 @@ public static List<Pair<String, String>> getHeaderTokens(
784781
String hv =
785782
header.getValue()
786783
.replace(token.getValue(), "{%" + token.getToken() + "%}");
787-
list.add(new Pair<String, String>(header.getName(), hv));
784+
list.add(new Pair<>(header.getName(), hv));
788785
}
789786
}
790787
}
@@ -817,7 +814,7 @@ protected static Map<String, SessionToken> getAllTokens(
817814
} catch (JSONException e) {
818815
LOGGER.debug(
819816
"Unable to parse authentication response body from {} as JSON: {}",
820-
msg.getRequestHeader().getURI().toString(),
817+
msg.getRequestHeader().getURI(),
821818
responseData);
822819
}
823820
}
@@ -949,15 +946,15 @@ public static void extractJsonTokens(
949946

950947
private static void extractJsonTokens(
951948
Object obj, String parent, Map<String, SessionToken> tokens) {
952-
if (obj instanceof JSONObject) {
953-
extractJsonTokens((JSONObject) obj, parent, tokens);
954-
} else if (obj instanceof JSONArray) {
955-
Object[] oa = ((JSONArray) obj).toArray();
949+
if (obj instanceof JSONObject jsonObj) {
950+
extractJsonTokens(jsonObj, parent, tokens);
951+
} else if (obj instanceof JSONArray jsonArr) {
952+
Object[] oa = (jsonArr.toArray());
956953
for (int i = 0; i < oa.length; i++) {
957954
extractJsonTokens(oa[i], parent + "[" + i + "]", tokens);
958955
}
959-
} else if (obj instanceof String) {
960-
addToMap(tokens, new SessionToken(SessionToken.JSON_SOURCE, parent, (String) obj));
956+
} else if (obj instanceof String str) {
957+
addToMap(tokens, new SessionToken(SessionToken.JSON_SOURCE, parent, str));
961958
}
962959
}
963960

addOns/authhelper/src/main/java/org/zaproxy/addon/authhelper/AuthenticationDetectionScanRule.java

+9-11
Original file line numberDiff line numberDiff line change
@@ -249,23 +249,21 @@ private static HtmlParameter getMatchingParam(
249249
}
250250

251251
void extractJsonStrings(JSON json, String parent, TreeSet<HtmlParameter> params) {
252-
if (json instanceof JSONObject) {
253-
JSONObject jsonObject = (JSONObject) json;
254-
for (Object key : jsonObject.keySet()) {
255-
Object obj = jsonObject.get(key);
256-
if (obj instanceof JSONObject) {
257-
extractJsonStrings(
258-
(JSONObject) obj, normalisedKey(parent, (String) key), params);
259-
} else if (obj instanceof String) {
252+
if (json instanceof JSONObject jsonObj) {
253+
for (Object key : jsonObj.keySet()) {
254+
Object obj = jsonObj.get(key);
255+
if (obj instanceof JSONObject jsonObj2) {
256+
extractJsonStrings(jsonObj2, normalisedKey(parent, (String) key), params);
257+
} else if (obj instanceof String objStr) {
260258
params.add(
261259
new HtmlParameter(
262260
HtmlParameter.Type.form,
263261
normalisedKey(parent, (String) key),
264-
(String) obj));
262+
objStr));
265263
}
266264
}
267-
} else if (json instanceof JSONArray) {
268-
Object[] oa = ((JSONArray) json).toArray();
265+
} else if (json instanceof JSONArray jsonArr) {
266+
Object[] oa = jsonArr.toArray();
269267
for (int i = 0; i < oa.length; i++) {
270268
extractJsonStrings((JSONArray) json, parent + "[" + i + "]", params);
271269
}

addOns/authhelper/src/main/java/org/zaproxy/addon/authhelper/AuthenticationRequestDetails.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ public class AuthenticationRequestDetails {
2929
public enum AuthDataType {
3030
FORM,
3131
JSON
32-
};
32+
}
3333

3434
private final URI uri;
3535
private final HtmlParameter userParam;

addOns/authhelper/src/main/java/org/zaproxy/addon/authhelper/AutoDetectAuthenticationMethodType.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ public AuthMethodApiResponseRepresentation(Map<String, T> values) {
222222
@Override
223223
public JSON toJSON() {
224224
JSONObject response = new JSONObject();
225-
response.put(getName(), super.toJSON());
225+
response.put(super.getName(), super.toJSON());
226226
return response;
227227
}
228228
}

addOns/authhelper/src/main/java/org/zaproxy/addon/authhelper/AutoDetectSessionManagementMethodType.java

+4-3
Original file line numberDiff line numberDiff line change
@@ -92,9 +92,10 @@ public SessionManagementMethod clone() {
9292

9393
@Override
9494
public boolean equals(Object obj) {
95-
if (obj == null) return false;
96-
if (getClass() != obj.getClass()) return false;
97-
return true;
95+
if (obj == null) {
96+
return false;
97+
}
98+
return getClass() == obj.getClass();
9899
}
99100

100101
@Override

addOns/authhelper/src/main/java/org/zaproxy/addon/authhelper/BrowserBasedAuthenticationMethodType.java

+33-40
Original file line numberDiff line numberDiff line change
@@ -160,10 +160,10 @@ public Object getCookieStore() {
160160
HttpSender temp = getHttpSender();
161161
Object obj = MethodUtils.invokeMethod(temp, true, "getContext");
162162

163-
if (obj instanceof HttpSenderContextApache) {
163+
if (obj instanceof HttpSenderContextApache hsca) {
164164
return FieldUtils.readField(
165165
HttpSenderContextApache.class.getDeclaredField("localCookieStore"),
166-
(HttpSenderContextApache) obj,
166+
hsca,
167167
true);
168168
}
169169
} catch (Exception e) {
@@ -792,43 +792,36 @@ public BrowserBasedAuthenticationMethodOptionsPanel(Context context) {
792792

793793
// Add behaviour for Node Select dialog
794794
selectButton.addActionListener(
795-
new java.awt.event.ActionListener() {
796-
@Override
797-
public void actionPerformed(java.awt.event.ActionEvent e) {
798-
NodeSelectDialog nsd =
799-
new NodeSelectDialog(View.getSingleton().getMainFrame());
800-
// Try to pre-select the node according to what has been inserted in the
801-
// fields
802-
SiteNode node = null;
803-
if (loginUrlField.getText().trim().length() > 0)
804-
try {
805-
node =
806-
Model.getSingleton()
807-
.getSession()
808-
.getSiteTree()
809-
.findNode(
810-
new URI(
811-
loginUrlField.getText(),
812-
false));
813-
} catch (Exception e2) {
814-
// Ignore. It means we could not properly get a node for the
815-
// existing
816-
// value and does not have any harmful effects
817-
}
818-
819-
// Show the dialog and wait for input
820-
node = nsd.showDialog(node);
821-
if (node != null && node.getHistoryReference() != null) {
822-
try {
823-
LOGGER.debug(
824-
"Selected Browser Based Auth Login URL via dialog: {}",
825-
node.getHistoryReference().getURI());
826-
827-
loginUrlField.setText(
828-
node.getHistoryReference().getURI().toString());
829-
} catch (Exception e1) {
830-
LOGGER.error(e1.getMessage(), e1);
831-
}
795+
e -> {
796+
NodeSelectDialog nsd =
797+
new NodeSelectDialog(View.getSingleton().getMainFrame());
798+
// Try to pre-select the node according to what has been inserted in the
799+
// fields
800+
SiteNode node = null;
801+
if (!loginUrlField.getText().trim().isEmpty())
802+
try {
803+
node =
804+
Model.getSingleton()
805+
.getSession()
806+
.getSiteTree()
807+
.findNode(new URI(loginUrlField.getText(), false));
808+
} catch (Exception e2) {
809+
// Ignore. It means we could not properly get a node for the
810+
// existing value and does not have any harmful effects
811+
}
812+
813+
// Show the dialog and wait for input
814+
node = nsd.showDialog(node);
815+
if (node != null && node.getHistoryReference() != null) {
816+
try {
817+
LOGGER.debug(
818+
"Selected Browser Based Auth Login URL via dialog: {}",
819+
node.getHistoryReference().getURI());
820+
821+
loginUrlField.setText(
822+
node.getHistoryReference().getURI().toString());
823+
} catch (Exception e1) {
824+
LOGGER.error(e1.getMessage(), e1);
832825
}
833826
}
834827
});
@@ -924,7 +917,7 @@ public AuthMethodApiResponseRepresentation(Map<String, T> values) {
924917
@Override
925918
public JSON toJSON() {
926919
JSONObject response = new JSONObject();
927-
response.put(getName(), super.toJSON());
920+
response.put(super.getName(), super.toJSON());
928921
return response;
929922
}
930923
}

addOns/authhelper/src/main/java/org/zaproxy/addon/authhelper/HeaderBasedSessionManagementMethodType.java

+6-8
Original file line numberDiff line numberDiff line change
@@ -199,8 +199,7 @@ public ApiResponse getApiResponseRepresentation() {
199199
@Override
200200
public void processMessageToMatchSession(HttpMessage message, WebSession session)
201201
throws UnsupportedWebSessionException {
202-
if (session instanceof HttpHeaderBasedSession) {
203-
HttpHeaderBasedSession hbSession = (HttpHeaderBasedSession) session;
202+
if (session instanceof HttpHeaderBasedSession hbSession) {
204203
LOGGER.debug(
205204
"processMessageToMatchSession {} # headers {} ",
206205
message.getRequestHeader().getURI(),
@@ -211,9 +210,7 @@ public void processMessageToMatchSession(HttpMessage message, WebSession session
211210
}
212211
Context context = Model.getSingleton().getSession().getContext(contextId);
213212
AuthenticationMethod am = context.getAuthenticationMethod();
214-
if (am instanceof BrowserBasedAuthenticationMethod) {
215-
BrowserBasedAuthenticationMethod bbam = (BrowserBasedAuthenticationMethod) am;
216-
213+
if (am instanceof BrowserBasedAuthenticationMethod bbam) {
217214
try {
218215
Method method =
219216
LegacyUtils.class.getMethod(
@@ -258,9 +255,10 @@ public SessionManagementMethod clone() {
258255

259256
@Override
260257
public boolean equals(Object obj) {
261-
if (obj == null) return false;
262-
if (getClass() != obj.getClass()) return false;
263-
return true;
258+
if (obj == null) {
259+
return false;
260+
}
261+
return getClass() == obj.getClass();
264262
}
265263

266264
@Override

addOns/authhelper/src/main/java/org/zaproxy/addon/authhelper/SessionDetectionScanRule.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) {
154154
LOGGER.debug(
155155
"Failed to find source of session management tokens in {}:",
156156
msg.getRequestHeader().getURI());
157-
requestTokens.forEach((st) -> LOGGER.debug("Missed token {}", st.getToken()));
157+
requestTokens.forEach(st -> LOGGER.debug("Missed token {}", st.getToken()));
158158
}
159159
}
160160
}

addOns/authhelper/src/main/java/org/zaproxy/addon/authhelper/VerificationRequestDetails.java

+5-8
Original file line numberDiff line numberDiff line change
@@ -66,14 +66,11 @@ public VerificationRequestDetails(HttpMessage msg, String token, Context context
6666
break;
6767
}
6868
AuthenticationCredentials creds = user.getAuthenticationCredentials();
69-
if (creds instanceof UsernamePasswordAuthenticationCredentials) {
70-
UsernamePasswordAuthenticationCredentials upCreds =
71-
(UsernamePasswordAuthenticationCredentials) creds;
72-
if (responseBody.contains(upCreds.getUsername())) {
73-
containsUserDetails = true;
74-
this.setEvidence(upCreds.getUsername());
75-
break;
76-
}
69+
if (creds instanceof UsernamePasswordAuthenticationCredentials upCreds
70+
&& responseBody.contains(upCreds.getUsername())) {
71+
containsUserDetails = true;
72+
this.setEvidence(upCreds.getUsername());
73+
break;
7774
}
7875
}
7976
}

0 commit comments

Comments
 (0)