블로그

How to catch and fix a Guice dependency injection issue using Sensei

1월 25, 2021
앨런 리처드슨

The Sensei project itself has its own set of recipes that have built up over time. This blog post is an example of one of the scenarios the Sensei team built a recipe for. A misconfiguration of Guice, which led to a NullPointerException being reported at runtime during testing.

This can be generalized to many Dependency Injection scenarios where code is syntactically correct, but because the wiring configuration was incorrect, an error slips through.

This often happens when we are learning the technology, and we keep making the simple mistake of forgetting to wire things up. But this also happens to experienced professionals because, well... we all make mistakes, and we may not have Unit Tests to cover everything.

 

RunTime Exceptions from Incorrect Dependency Injection Wiring

The code below fails at runtime with a NullPointerException.

‍

injector = Guice.createInjector(new SystemOutModule());
CountReporter reporter = injector.getInstance(CountReporter.class);
String [] lines5 = {"1: line", "2: line", "3: line", "4: line", "5: line"};
reporter.reportThisMany(Arrays.asList(lines5));
Assertions.assertEquals(5, reporter.getCount());


The code is syntactically correct but fails because we missed out a requestStaticInjection in our SystemOutModule configuration.

‍

public class SystemOutModule extends AbstractModule {
    @Override
    protected void configure() {
        binder().bind(ILineReporter.class).to(SystemOutReporter.class);
    }
}


When we try to use the reporter, created using the Injector, it is not fully instantiated and we receive a NullPointerException when we call reportThisMany.

We may well have missed that in our code review, or we didn't have unit tests that triggered the dependency injection, and it slipped out into our build.

‍

Warning Signs

In this case, there is a warning sign, the CountReporter has a static field annotated with @Inject but... the CountReporter class itself is package private.

In a complicated code base this could be a warning sign that the code is incorrect because the Module class configuring the bindings needs to be in the same package for this to work.

‍

class CountReporter {
    @Inject
    private static ILineReporter reporter;


Another error that we made, which we might have picked up in a code review, is that we forgot to actually bind the fields in the SystemOutModule configure method.

binder().requestStaticInjection(CountReporter.class);


Had we written the requestStaticInjection code then the Syntax Error generated when trying to use the CountReporter would have alerted us to the simple error.

> 'reporters.CountReporter' is not public in 'reporters'. Cannot be accessed from outside package

‍

Sadly. We forgot, and there were no syntactic warning signs in the code.

How could Sensei help?

We probably wouldn't use Sensei to pick up the missing requestStaticInjection since all our Guice configuration wiring would need to use that method, and we can't guarantee that all wiring is going to be as simple as this use-case.

We could write a Sensei rule to look for some warning signs that our code is not up to scratch.

In this case that would mean:

  • Find any classes with @Inject annotated fields
  • Where the classes are not public.

The above was the warning sign that they were unlikely to have been wired up.

By creating a recipe, then we will have a warning sign early, during the coding, and reduce the reliance on our pull requests or resolving our tech debt to allow us to add Unit Tests.

How to create a recipe?

The task I want to complete is:

  • Create a recipe that matches fields annotated with @Inject which are in protected private classes

That should hopefully give us enough warning to identify any Modules using it and add the missing wiring code.

In my CountReporter class, I will use Alt+Enter to Create a new Recipe and I will start from scratch

I will name this and add a description:

Name: Guice: Injected Field Not Public
Description: If the Injected field is not public then the code might not be wired up
Level: Warning


The search I write looks for a class with a field annotated as Inject but which has not been scoped as public.

search:
  field:
    with:
      annotation:
        type: "com.google.inject.Inject"
    in:
      class:
        without:
          modifier: "public"

Fix

The QuickFix in the recipe will amend the injected class by changing the scope. But that is not the only code I have to change.

availableFixes:

- name: "Change class to public. Remember to also request injection on this class"
  actions:
  - changeModifiers:
      visibility: "public"
      target: "parentClass"
Sensei edit recipe QuickFix settings

When the recipe is triggered I still have a manual step to perform in my code, adding the line containing requestStaticInjection to fully instantiate the object.

public class SystemOutModule extends AbstractModule {
    @Override
    protected void configure() {
        binder().bind(ILineReporter.class).to(SystemOutReporter.class);
        // instantiate via dependency injection
        binder().requestStaticInjection(CountReporter.class);
    }
}


I could potentially write another recipe to pick this up. I probably wouldn't do that unless forgetting to add the static injection became a semi-regular error that I made when coding.

‍

Summary

If we ever find ourselves making a mistake with a common root pattern, then Sensei can help codify the knowledge around detecting and fixing the issue, and then hopefully, it won't slip through code reviews and into production.

Sometimes the recipes we write identify heuristic patterns i.e. matching them doesn't guarantee that there is a problem, but is likely that there is a problem.

Also, the recipes and QuickFixes that we write, don't have to be fully comprehensive, they need to be good enough that they help us identify and fix problems without being overcomplicated. Because when they become overcomplicated they become harder to understand and harder to maintain.

---


You can install Sensei from within IntelliJ using "Preferences \ Plugins" (Mac) or "Settings \ Plugins" (Windows) then just search for "sensei secure code".


The source code and recipes for this post can be found in the `sensei-blog-examples` repository in the Secure Code Warrior GitHub account, in the `guiceexamples` module.


https://github.com/securecodewarrior/sensei-blog-examples

Learn more about Sensei



태그라인

배포 전 AI 기반 개발 거버넌스 확보

AI 기반 위험을 측정하고, 커밋 시점에 보안 코딩 정책을 적용하며, SDLC 전반에 걸쳐 안전한 소프트웨어 제공 속도를 높이세요.

데모 예약하기
리소스 라이브러리

더 많은 블로그 살펴보기

보안 코딩, AI 거버넌스, 소프트웨어 리스크 관리에 관한 전문가 콘텐츠를 확인해 보세요.

전체 보기
사례 연구
필터 라벨
div 블록 내부의 텍스트입니다.

하나의 보안 문화: Sage는 어떻게 챔피언 프로그램을 구축했는가

Sage가 유연하고 관계 중심적인 접근 방식을 통해 보안을 강화하고, 200명 이상의 보안 챔피언을 양성하며 실질적인 위험 감소를 달성한 사례를 확인해 보세요.

더 알아보기
그라데이션 블루 배경 위에 굵은 KVK 글자와 그 아래 두 개의 파란색 가로선이 있는 브라우저 창 아이콘.
사례 연구
필터 라벨
div 블록 내부의 텍스트입니다.

Kamer van Koophandel: 대규모 개발자 주도 보안

Kamer van Koophandel은 역할 기반 인증, Trust Score 벤치마킹, 그리고 보안에 대한 공동 책임 문화를 통해 일상적인 개발 과정에 안전한 코딩을 어떻게 내재화했는지 공유합니다.

더 알아보기
웹 브라우저 창 디자인 안에 파란색과 회색 텍스트 및 아이콘으로 구성된 Insurance Australia Group의 로고.
사례 연구
필터 라벨
div 블록 내부의 텍스트입니다.

‘Game of Codes’가 이끄는 IAG 그룹의 더 안전한 코딩 미래

IAG 그룹은 아시아 태평양 지역의 주요 보험사들을 이끄는 기업으로, 매년 약 114억 호주 달러 규모의 보험료를 인수하며 수백만 고객의 보험을 책임지고 있습니다.

더 알아보기
블로그
필터 라벨
div 블록 내부의 텍스트입니다.

인에이블러 10: 커리어 성장과 연계된 교육

교육은 실질적인 커리어 가치가 있을 때 비로소 우선순위가 됩니다. 인에이블러 10은 보안 코딩을 성과 목표와 연계하는 것이 어떻게 지속적인 참여를 이끌어내는지 보여줍니다.

더 알아보기
블로그
필터 라벨
div 블록 내부의 텍스트입니다.

모델이 가장 작은 보안 레버라면, 실제로 AI 생성 코드를 더 안전하게 만드는 요소는 무엇일까요?

올해 초 당사는 SCW AI 신뢰 지수(SCW AI Trust Index)를 발표하고, RMIT 대학교와 협력하여 OpenAI, Anthropic, Google 등의 주요 AI 모델 16개를 평가했습니다. 총 1,760개의 코드베이스를 생성하여 분석한 결과, 각 코드베이스에서 평균 15개의 취약점이 발견되었습니다. 독자적인 방법론을 적용한 이 데이터를 통해 당사는 모델과 프레임워크에 따라 보안 위험을 예측할 수 있다는 사실을 마침내 규명해 냈습니다. 

‍

더 알아보기
블로그
필터 라벨
div 블록 내부의 텍스트입니다.

AI 도구에서 바로 보안 코딩 프로그램을 운영하세요

MCP 호환 AI 도구를 사용하여 SCW 보안 코딩 프로그램의 교육 진행 상황을 추적하고, 퀘스트를 초안으로 작성하며, 보고서를 생성하세요. 모든 SCW 플랜에 포함되어 있습니다.

더 알아보기

배포 전 AI 기반 개발 보안 확보

소프트웨어 개발 수명 주기 전반에서 개발자 리스크를 파악하고, 정책을 시행하며, 취약점을 예방하세요.

데모 예약하기
항목이 없습니다.