github / github/codeql

Java: `java/ineffective-annotation-present-check` should cover more cases

Open
#6,244 0 comments 0 reactions 0 assignees View on GitHub
Java question
Dominant language
CodeQL
Stars
10.1k
Forks
2.1k
Avg merge
2d 15h
Merged PRs (30d)
141

Description

Currently the query [`java/ineffective-annotation-present-check`](https://github.com/github/codeql/blob/main/java/ql/src/Likely%20Bugs/Reflection/AnnotationPresentCheck.ql) only covers calls to `isAnnotationPresent(Class)`.

It would be good to cover the other methods of [`AnnotatedElement`](https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/lang/reflect/AnnotatedElement.html) (and methods overriding them) taking an annotation class as parameter as well.

Note that [JLS 16 §9.6.3](https://docs.oracle.com/javase/specs/jls/se16/html/jls-9.html#jls-9.6.3) permits for the containing annotation interface to have a higher `RetentionPolicy`, e.g.:
```java
import java.util.*;
import java.lang.annotation.*;

public class AnnTest {
@Repeatable(AnnContainer.class)
// Only visible in source
@Retention(RetentionPolicy.SOURCE)
@interface Ann { String value(); }

// Visible during runtime
@Retention(RetentionPolicy.RUNTIME)
@interface AnnContainer { Ann[] value(); }

@AnnContainer({
@Ann("c1"),
@Ann("c2")
})
@Ann("s")
public static class Test { }

public static void main(String... args) throws Exception {
// Finds repeated annotations even though they have RetentionPolicy.SOURCE
System.out.println(Arrays.toString(Test.class.getAnnotationsByType(Ann.class)));
}
}
```

Though accounting for this special case when checking method calls which consider these 'indirect' annotations (e.g. `getAnnotationsByType(Class)`) is probably not worth it.

----

There is also [`AnnotatedConstruct`](https://docs.oracle.com/en/java/javase/16/docs/api/java.compiler/javax/lang/model/AnnotatedConstruct.html), but if I understand it correctly it is used for processing source code and therefore `Retention` restrictions do not apply.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.