Skip to content

[Security] support voter attributes in is_granted and has_role security annotation #892 #1126

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

Merged
merged 1 commit into from
Dec 23, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions META-INF/plugin.xml
Original file line number Diff line number Diff line change
Expand Up @@ -582,6 +582,7 @@
<GotoCompletionRegistrar implementation="fr.adrienbrault.idea.symfony2plugin.translation.TranslationPlaceholderGotoCompletionRegistrar"/>
<GotoCompletionRegistrar implementation="fr.adrienbrault.idea.symfony2plugin.dic.TaggedParameterGotoCompletionRegistrar"/>
<GotoCompletionRegistrar implementation="fr.adrienbrault.idea.symfony2plugin.templating.RenderParameterGotoCompletionRegistrar"/>
<GotoCompletionRegistrar implementation="fr.adrienbrault.idea.symfony2plugin.security.AnnotationExpressionGotoCompletionRegistrar"/>

<TwigNamespaceExtension implementation="fr.adrienbrault.idea.symfony2plugin.templating.path.JsonFileIndexTwigNamespaces"/>
<TwigNamespaceExtension implementation="fr.adrienbrault.idea.symfony2plugin.templating.path.ConfigAddPathTwigNamespaces"/>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package fr.adrienbrault.idea.symfony2plugin.security;

import com.intellij.codeInsight.completion.CompletionResultSet;
import com.intellij.patterns.PatternCondition;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.PsiElement;
import com.intellij.util.ProcessingContext;
import com.jetbrains.php.lang.documentation.phpdoc.lexer.PhpDocTokenTypes;
import com.jetbrains.php.lang.documentation.phpdoc.parser.PhpDocElementTypes;
import com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocTag;
import com.jetbrains.php.lang.psi.elements.StringLiteralExpression;
import de.espend.idea.php.annotation.util.AnnotationUtil;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionProvider;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionProviderLookupArguments;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionRegistrar;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionRegistrarParameter;
import fr.adrienbrault.idea.symfony2plugin.security.utils.VoterUtil;
import fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil;
import org.jetbrains.annotations.NotNull;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class AnnotationExpressionGotoCompletionRegistrar implements GotoCompletionRegistrar {

private static final String SECURITY_ANNOTATION = "Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Security";

@Override
public void register(@NotNull GotoCompletionRegistrarParameter registrar) {
// "@Security("is_granted('POST_SHOW', post) and has_role('ROLE_ADMIN')")"
registrar.register(
PlatformPatterns.psiElement(PhpDocTokenTypes.DOC_STRING)
.withParent(PlatformPatterns.psiElement(StringLiteralExpression.class)
.withParent(PlatformPatterns.psiElement(PhpDocElementTypes.phpDocAttributeList)
.withParent(PlatformPatterns.psiElement(PhpDocTag.class)
.with(PhpDocInstancePatternCondition.INSTANCE)
)
)
),
MyGotoCompletionProvider::new
);
}

/**
* "@Security("has_role('ROLE_FOOBAR')")"
* "@Security("is_granted('POST_SHOW', post) and has_role('ROLE_ADMIN')")"
*/
private static class MyGotoCompletionProvider extends GotoCompletionProvider {
MyGotoCompletionProvider(@NotNull PsiElement psiElement) {
super(psiElement);
}

@Override
public void getLookupElements(@NotNull GotoCompletionProviderLookupArguments arguments) {
final CompletionResultSet resultSet = arguments.getResultSet();
String blockNamePrefix = resultSet.getPrefixMatcher().getPrefix();

// find caret position:
// - "has_role('"
// - "has_role('YAML_ROLE_"
if(!blockNamePrefix.matches("^.*(has_role|is_granted)\\s*\\(\\s*'[\\w-]*$")) {
return;
}

// clear prefix caret string; for a clean completion independent from inside content
CompletionResultSet myResultSet = resultSet.withPrefixMatcher("");

VoterUtil.LookupElementPairConsumer consumer = new VoterUtil.LookupElementPairConsumer();
VoterUtil.visitAttribute(getProject(), consumer);
myResultSet.addAllElements(consumer.getLookupElements());
}

@NotNull
@Override
public Collection<PsiElement> getPsiTargets(PsiElement element) {
if(getElement().getNode().getElementType() != PhpDocTokenTypes.DOC_STRING) {
return Collections.emptyList();
}

PsiElement parent = getElement().getParent();
if(!(parent instanceof StringLiteralExpression)) {
return Collections.emptyList();
}

String contents = ((StringLiteralExpression) parent).getContents();

Collection<String> roles = new HashSet<>();
for (String regex : new String[]{"is_granted\\s*\\(\\s*['|\"]([^'\"]+)['|\"]\\s*[\\)|,]", "has_role\\s*\\(\\s*['|\"]([^'\"]+)['|\"]\\s*\\)"}) {
Matcher matcher = Pattern.compile(regex).matcher(contents);
while(matcher.find()){
roles.add(matcher.group(1));
}
}

if(roles.size() == 0) {
return Collections.emptyList();
}

Collection<PsiElement> targets = new HashSet<>();

VoterUtil.visitAttribute(getProject(), pair -> {
if(roles.contains(pair.getFirst())) {
targets.add(pair.getSecond());
}
});

return targets;
}
}

/**
* Check if given PhpDocTag is instance of given Annotation class
*/
private static class PhpDocInstancePatternCondition extends PatternCondition<PsiElement> {
private static PhpDocInstancePatternCondition INSTANCE = new PhpDocInstancePatternCondition();

PhpDocInstancePatternCondition() {
super("PhpDoc Annotation Instance");
}

@Override
public boolean accepts(@NotNull PsiElement psiElement, ProcessingContext processingContext) {
return psiElement instanceof PhpDocTag
&& PhpElementsUtil.isEqualClassName(AnnotationUtil.getAnnotationReference((PhpDocTag) psiElement), SECURITY_ANNOTATION);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,25 +1,22 @@
package fr.adrienbrault.idea.symfony2plugin.security;

import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiTreeUtil;
import com.jetbrains.php.lang.PhpLanguage;
import com.jetbrains.php.lang.psi.elements.PhpClass;
import com.jetbrains.php.lang.psi.elements.StringLiteralExpression;
import fr.adrienbrault.idea.symfony2plugin.Symfony2Icons;
import fr.adrienbrault.idea.symfony2plugin.templating.TwigPattern;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionProvider;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionRegistrar;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.GotoCompletionRegistrarParameter;
import fr.adrienbrault.idea.symfony2plugin.codeInsight.utils.GotoCompletionUtil;
import fr.adrienbrault.idea.symfony2plugin.security.utils.VoterUtil;
import fr.adrienbrault.idea.symfony2plugin.templating.TwigPattern;
import fr.adrienbrault.idea.symfony2plugin.util.MethodMatcher;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.util.*;
import java.util.Collection;
import java.util.Collections;

/**
* @author Daniel Espendiller <daniel@espendiller.net>
Expand Down Expand Up @@ -84,25 +81,9 @@ private static class MyVisitorGotoCompletionProvider extends GotoCompletionProvi
@NotNull
@Override
public Collection<LookupElement> getLookupElements() {
Collection<LookupElement> lookupElements = new ArrayList<>();

Set<String> elements = new HashSet<>();

VoterUtil.visitAttribute(getProject(), pair -> {
String name = pair.getFirst();
if(!elements.contains(name)) {
LookupElementBuilder lookupElement = LookupElementBuilder.create(name).withIcon(Symfony2Icons.SYMFONY);
PhpClass phpClass = PsiTreeUtil.getParentOfType(pair.getSecond(), PhpClass.class);
if(phpClass != null) {
lookupElement = lookupElement.withTypeText(phpClass.getName(), true);
}

lookupElements.add(lookupElement);
elements.add(name);
}
});

return lookupElements;
VoterUtil.LookupElementPairConsumer consumer = new VoterUtil.LookupElementPairConsumer();
VoterUtil.visitAttribute(getProject(), consumer);
return consumer.getLookupElements();
}

@NotNull
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package fr.adrienbrault.idea.symfony2plugin.security.utils;

import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.PsiElement;
Expand All @@ -13,6 +15,7 @@
import com.jetbrains.php.lang.lexer.PhpTokenTypes;
import com.jetbrains.php.lang.parser.PhpElementTypes;
import com.jetbrains.php.lang.psi.elements.*;
import fr.adrienbrault.idea.symfony2plugin.Symfony2Icons;
import fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil;
import fr.adrienbrault.idea.symfony2plugin.util.PsiElementUtils;
import fr.adrienbrault.idea.symfony2plugin.util.yaml.YamlHelper;
Expand All @@ -22,6 +25,8 @@
import org.jetbrains.yaml.YAMLUtil;
import org.jetbrains.yaml.psi.*;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;
Expand Down Expand Up @@ -213,6 +218,36 @@ public Set<PsiElement> getValues() {
}
}

public static class LookupElementPairConsumer implements Consumer<Pair<String, PsiElement>> {
@NotNull
private final Set<String> elements = new HashSet<>();

@NotNull
public Collection<LookupElement> getLookupElements() {
return lookupElements;
}

@Override
public void accept(Pair<String, PsiElement> pair) {
String name = pair.getFirst();
if (!elements.contains(name)) {
LookupElementBuilder lookupElement = LookupElementBuilder.create(name).withIcon(Symfony2Icons.SYMFONY);

PhpClass phpClass = PsiTreeUtil.getParentOfType(pair.getSecond(), PhpClass.class);
if (phpClass != null) {
lookupElement = lookupElement.withTypeText(phpClass.getName(), true);
}

lookupElements.add(lookupElement);

elements.add(name);
}
}

@NotNull
private final Collection<LookupElement> lookupElements = new ArrayList<>();
}

/**
* Find security roles on Voter implementation and security roles in Yaml
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
package fr.adrienbrault.idea.symfony2plugin.tests.security;

import com.intellij.patterns.PlatformPatterns;
import fr.adrienbrault.idea.symfony2plugin.tests.SymfonyLightCodeInsightFixtureTestCase;

import java.io.File;

/**
* @author Daniel Espendiller <daniel@espendiller.net>
*
* @see fr.adrienbrault.idea.symfony2plugin.security.AnnotationExpressionGotoCompletionRegistrar
*/
public class AnnotationExpressionGotoCompletionRegistrarTest extends SymfonyLightCodeInsightFixtureTestCase {
public void setUp() throws Exception {
super.setUp();

myFixture.copyFileToProject("security.yml");
myFixture.copyFileToProject("classes.php");
}

protected String getTestDataPath() {
return new File(this.getClass().getResource("fixtures").getFile()).getAbsolutePath();
}

public void testSecurityAnnotationProvidesCompletion() {
assertCompletionContains(
"test.php",
"<?php\n" +
"use Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Security;\n" +
"" +
"/**\n" +
"* @Security(\"has_role('<caret>')\")\n" +
"*/\n" +
"function test() {};\n" +
"",
"YAML_ROLE_USER_FOOBAR"
);

assertCompletionContains(
"test.php",
"<?php\n" +
"use Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Security;\n" +
"" +
"/**\n" +
"* @Security(\"has_role('YAML_ROLE_<caret>')\")\n" +
"*/\n" +
"function test() {};\n" +
"",
"YAML_ROLE_USER_FOOBAR"
);

assertCompletionContains(
"test.php",
"<?php\n" +
"use Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Security;\n" +
"" +
"/**\n" +
"* @Security(\"is_granted('<caret>')\")\n" +
"*/\n" +
"function test() {};\n" +
"",
"YAML_ROLE_USER_FOOBAR"
);

assertCompletionContains(
"test.php",
"<?php\n" +
"use Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Security;\n" +
"" +
"/**\n" +
"* @Security(\"is_granted('<caret>', foo)\")\n" +
"*/\n" +
"function test() {};\n" +
"",
"YAML_ROLE_USER_FOOBAR"
);
}

public void testSecurityAnnotationProvidesRoleNavigation() {
assertNavigationMatch(
"test.php",
"<?php\n" +
"use Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Security;\n" +
"/**\n" +
"* @Security(\"has_role('YAML_ROLE<caret>_USER_FOOBAR')\")\n" +
"*/\n" +
"function test() {};\n" +
"",
PlatformPatterns.psiElement()
);

assertNavigationMatch(
"test.php",
"<?php\n" +
"use Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Security;\n" +
"/**\n" +
"* @Security(\"has_role ( 'YAML_ROLE<caret>_USER_FOOBAR' ) \")\n" +
"*/\n" +
"function test() {};\n" +
"",
PlatformPatterns.psiElement()
);

assertNavigationMatch(
"test.php",
"<?php\n" +
"use Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Security;\n" +
"/**\n" +
"* @Security(\"is_granted('YAML_ROLE<caret>_USER_FOOBAR')\")\n" +
"*/\n" +
"function test() {};\n" +
"",
PlatformPatterns.psiElement()
);

assertNavigationMatch(
"test.php",
"<?php\n" +
"use Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Security;\n" +
"/**\n" +
"* @Security(\"is_granted('YAML_ROLE<caret>_USER_FOOBAR', post)\")\n" +
"*/\n" +
"function test() {};\n" +
"",
PlatformPatterns.psiElement()
);
}
}
Loading