Skip to content

Commit

Permalink
Add recipe for rule: HttpSessionInvalidate (#392)
Browse files Browse the repository at this point in the history
* Add recipe for rule: HttpSessionInvalidate

* Add javaee6 recipe to javaee7 recipeList

* Use custom recipe to modify invalidate to logout

* Fix copyright year

* Minor formatting fixes for tests

* Resolve automated code review comments

* Address code review comments

* Move javax.servlet-3.0 jar from src/test to src/main

* Fix test failure

* Trigger another automated review

We're testing internally, sorry about the noise!

* Clean up unused import to trigger new automated review

* Trigger another PR review

* Clean up whitespace

* Apply suggestions from code review

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* Apply suggestions from code review

* Add preconditions and inline formerly public visitor

---------

Co-authored-by: Tim te Beek <[email protected]>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
  • Loading branch information
3 people authored Feb 6, 2024
1 parent ea28828 commit bcf5804
Show file tree
Hide file tree
Showing 5 changed files with 239 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/*
* Copyright 2024 the original author or authors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openrewrite.java.migrate.javax;

import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Preconditions;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.java.*;
import org.openrewrite.java.search.UsesMethod;
import org.openrewrite.java.search.UsesType;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;

import java.util.List;

@Value
@EqualsAndHashCode(callSuper = false)
public class HttpSessionInvalidate extends Recipe {
@Override
public String getDisplayName() {
return "Use HttpServletRequest `logout` method for programmatic security logout in Servlet 3.0";
}

@Override
public String getDescription() {
return "Do not rely on HttpSession `invalidate` method for programmatic security logout. Add the HttpServletRequest `logout` method which was introduced in Java EE 6 as part of the Servlet 3.0 specification.";
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
MethodMatcher invalidateMethodMatcher = new MethodMatcher("javax.servlet.http.HttpSession invalidate()", false);
TypeMatcher httpServletRequestTypeMatcher = new TypeMatcher("javax.servlet.http.HttpServletRequest");
return Preconditions.check(
Preconditions.or(
new UsesMethod<>(invalidateMethodMatcher),
new UsesType<>("javax.servlet.http.HttpServletRequest", true)),
new JavaIsoVisitor<ExecutionContext>() {
@Override
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
if (invalidateMethodMatcher.matches(method)) {
// Get index of param for HttpServletRequest, from the encapsulating method declaration TODO: would like to make this cleaner...
J.MethodDeclaration parentMethod = getCursor().dropParentUntil(parent -> parent instanceof J.MethodDeclaration).getValue();
Integer servletReqParamIndex = getServletRequestIndex(parentMethod);

// Failed to find HttpServletRequest from parent MethodDeclaration
if (servletReqParamIndex == null) {
return method;
}

// Get the HttpServletRequest param
J.VariableDeclarations httpServletRequestDeclaration = (J.VariableDeclarations) parentMethod.getParameters().get(servletReqParamIndex);

// Replace HttpSession.invalidate() with HttpServletRequest.logout()
final JavaTemplate logoutTemplate =
JavaTemplate.builder("#{any(javax.servlet.http.HttpServletRequest)}.logout()")
.imports("javax.servlet.http.HttpServletRequest")
.javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, "javax.servlet-3.0"))
.build();
method = logoutTemplate.apply(
getCursor(),
method.getCoordinates().replace(),
httpServletRequestDeclaration.getVariables().get(0)
);
}
return super.visitMethodInvocation(method, ctx);
}

/**
* @return the param index position of the HttpServletRequest parameter object
*/
@Nullable
private Integer getServletRequestIndex(J.MethodDeclaration parentMethod) {
List<JavaType> params = parentMethod.getMethodType().getParameterTypes();
for (int i = 0; i < params.size(); ++i) {
if (httpServletRequestTypeMatcher.matches(params.get(i))) {
return i;
}
}
return null;
}
}
);
}
}
25 changes: 25 additions & 0 deletions src/main/resources/META-INF/rewrite/java-ee-6.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#
# Copyright 2024 the original author or authors.
# <p>
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# <p>
# https://www.apache.org/licenses/LICENSE-2.0
# <p>
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
---
type: specs.openrewrite.org/v1beta/recipe
name: org.openrewrite.java.migrate.javaee6
displayName: Migrate to JavaEE6
description: These recipes help with the Migration to Java EE 6, flagging and updating deprecated methods.
tags:
- javaee6
- deprecated
recipeList:
- org.openrewrite.java.migrate.javax.HttpSessionInvalidate
1 change: 1 addition & 0 deletions src/main/resources/META-INF/rewrite/java-ee-7.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ tags:
- javaee7
- deprecated
recipeList:
- org.openrewrite.java.migrate.javaee6
- org.openrewrite.java.migrate.javaee7.OpenJPAPersistenceProvider
- org.openrewrite.java.migrate.JpaCacheProperties
- org.openrewrite.java.migrate.BeansXmlNamespace
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/*
* Copyright 2024 the original author or authors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openrewrite.java.migrate.javaee;

import org.junit.jupiter.api.Test;
import org.openrewrite.DocumentExample;
import org.openrewrite.InMemoryExecutionContext;
import org.openrewrite.java.JavaParser;
import org.openrewrite.java.migrate.javax.HttpSessionInvalidate;
import org.openrewrite.test.RecipeSpec;
import org.openrewrite.test.RewriteTest;

import static org.openrewrite.java.Assertions.java;

class HttpSessionInvalidateTest implements RewriteTest {
@Override
public void defaults(RecipeSpec spec) {
spec.parser(JavaParser.fromJavaVersion().classpathFromResources(new InMemoryExecutionContext(), "javax.servlet-3.0"))
.recipe(new HttpSessionInvalidate());
}

@Test
void noChangeNeeded() {
rewriteRun(
//language=java
java(
"""
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
class Foo {
void logOut(HttpServletRequest req, HttpServletResponse res) {
HttpSession session = req.getSession();
req.logout();
res.sendRedirect("login.html");
}
}
"""
)
);
}

@Test
void noChangeCannotFindServletRequest() {
rewriteRun(
//language=java
java(
"""
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
class Foo {
void logOut(HttpSession session, HttpServletResponse res) {
session.invalidate();
res.sendRedirect("login.html");
}
}
"""
)
);
}

@DocumentExample
@Test
void useLogoutWhenHttpServletRequestExistsInScope() {
rewriteRun(
//language=java
java(
"""
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
class Foo {
void logOut(HttpServletRequest req, HttpServletResponse res) {
HttpSession session = req.getSession(false);
session.invalidate();
res.sendRedirect("login.html");
}
}
""",
"""
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
class Foo {
void logOut(HttpServletRequest req, HttpServletResponse res) {
HttpSession session = req.getSession(false);
req.logout();
res.sendRedirect("login.html");
}
}
"""
)
);
}
}

0 comments on commit bcf5804

Please sign in to comment.