ブログ

Automatically Adding a Private Constructor with Sensei

12月 14, 2020
アラン・リチャードソン

Automatically Adding a Private Constructor with Sensei


In a utility class, when the fields and methods are static,  there is no obvious reason why I would ever instantiate it.

e.g. UtilityClass utility = new UtilityClass();

The code below is a simple implementation of a Utility class.

public class UtilityClass {
    public static final Boolean ULTIMATE_TRUTH = true;
    public static boolean getTrue(){
        return ULTIMATE_TRUTH;
    }
}


This is the type of coding pattern that Static Analysis tools can pick up, but they often don't supply the ability to fix the issue.

I can use Sensei to identify the coding pattern, and automatically generate a private constructor to make it impossible for me to instantiate the class.

Searching for the Class

I will add a new recipe on the Utility class called:

  •  Static Classes: create private constructor.


General Settings For Static Classes


And initially, I'll create a simple matcher to search for a class.

search:

  class: {}


This will match any class, which is good enough to let me get started writing a Quick Fix. Once I have a Quick Fix that works, I'll refine the search to make it highlight when there is more likely to be a class that requires a private constructor.

Quick Fix

For the Quick Fix, I will want to generate a private constructor.

In the example class this would look like:

   private UtilityClass(){}

To add the above code to my class, my Quick Fix will add a Method, and the name of the method will be a Mustache template that uses the name of the class.

availableFixes:

- name: "add private constructor"
  actions:
  - addMethod:
      method: "private {{{ name }}}(){}"


In the GUI Editor, I use the Show Variables to create the Mustache template and then edit the field to add the private modifier, brackets, and braces to make it syntactically correct.

Add Private Constructor

This would now allow me to add a private constructor to any class.

The QuickFix preview helps me because I can see the generated code as I write the Mustache template.

Utility Class Add Private Constructor

Now that I know I can fix the problem. I'll refine the search conditions to show the recipe when it is most appropriate.

Search for Missing Constructors

Ideally, I don't want to create a recipe that flags an error against every class. So I'll add some additional conditions in the search so that we only match on classes that do not have a constructor.

search:

  class:
    without:
      child:
        method:
          constructor: true


The YAML is slightly different from the GUI.

In the GUI I configure it to look for a class without a child method which is a constructor 'yes'. We use 'yes' in the GUI instead of 'true' to make the GUI a little more human friendly.


Search for class in code


This recipe will now only reveal itself for any class without a constructor.

Narrow Search for Likely Culprits

So I might want to go further and look for the presence of static methods or fields.

I look for any class without a constructor and which has either all public static fields or all public static methods.

search:

  class:
    with:
      anyOf:
      - child:
          method:
            allOf:
            - modifier: "public"
            - modifier: "static"
      - child:
          field:
            allOf:
            - modifier: "static"
            - modifier: "public"
    without:
      child:
        method:
          constructor: true


Since Sensei is used to help me, as a  programmer, in the IDE, rather than to statically analyze the code and report all errors, this filter is good enough to rule out most classes in my code base where I might have a good reason to have a default public constructor.

In some projects, this might be a step too far because the utility classes could have private methods, so I might choose to look for the presence of 'any' public static methods, rather than 'all'.

       - child:
           field:
              anyOf:
                - modifier: "static"
                - modifier: "public"


Hints

Sensei is not designed to replace a Static Analysis tool. Sensei can augment a Static Analysis tool for common issues associated with your coding process, or technology. By replicating enough of the matching to highlight an issue, and supporting the development process by generating the QuickFix code.

What I'm trying to do is create a simple enough recipe that includes all the situations I need it, but filter it so that it doesn't get suggested in every class.

When working on recipes I try to de-risk them, in this case, I wasn't sure if I could create the private constructor so I created the QuickFix first. Then refactored the search conditions to make them more specific.

Sometimes when working on recipes I'm not sure how to perform the search, so I work on that first.

I find recipes easier to create when I build them incrementally, switching between refactoring of the QuickFix and the search.

---


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 can be found in the `sensei-blog-examples` repository in the Secure Code Warrior GitHub account, in the `pojoexamples` module.

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

‍

タグライン

AI主導の開発をリリース前にガバナンスする

AIを活用したリスク測定、コミット時のセキュアコーディングポリシーの強制、そしてSDLC全体を通じたセキュアなデリバリーの加速を実現します。

デモを予約する
リソースライブラリ

他のブログ記事を見る

セキュアコーディング、AIガバナンス、ソフトウェアリスク管理に関する専門的なコンテンツをご覧ください。

すべて表示
導入事例
フィルターラベル
これはdivブロック内のテキストです。

セキュリティ文化の統一:Sageはいかにしてチャンピオンプログラムを構築したか

Sageがどのようにして柔軟かつ関係性を重視したアプローチでセキュリティを強化し、200名以上のセキュリティチャンピオンを育成して、目に見えるリスク低減を実現したのかをご紹介します。

詳細はこちら
グラデーションのかかった青い背景に、太字で「KVK」と書かれ、その下に2本の青い水平線が引かれたブラウザウィンドウのアイコン。
導入事例
フィルターラベル
これはdivブロック内のテキストです。

Kamer van Koophandel:開発者主導のセキュリティを大規模に展開

Kamer van Koophandelは、役割に応じた認定制度、Trust Scoreによるベンチマーク、そしてセキュリティを全員で担う文化を通じて、セキュアコーディングを日々の開発プロセスにどのように組み込んだのかを紹介します。

詳細はこちら
Webブラウザのウィンドウ内に表示された、青とグレーのテキストとアイコンによるInsurance Australia Groupのロゴ。
導入事例
フィルターラベル
これはdivブロック内のテキストです。

「Game of Codes」が導く、IAGグループのより安全なコーディングの未来

IAGグループは、アジア太平洋地域をリードする数多くの保険会社を傘下に持ち、数百万ものお客様に保険を提供しています。その年間保険料収入は約114億豪ドルにのぼります。

詳細はこちら
ブログ
フィルターラベル
これはdivブロック内のテキストです。

イネーブラー10:キャリアアップに直結するトレーニング

トレーニングは、キャリア上の価値が明確な場合にのみ優先されます。イネーブラー10では、セキュアコーディングを業績目標と結びつけることで、いかに継続的な参加を促せるかを解説します。

詳細はこちら
ブログ
フィルターラベル
これはdivブロック内のテキストです。

モデルがセキュリティの最小のレバーであるならば、AI生成コードを実際に安全にするものは何でしょうか?

今年初め、当社は「SCW AI Trust Index」を公開しました。RMIT大学との共同調査において、OpenAI、Anthropic、Googleをはじめとする主要な16のAIモデルを評価し、生成された1,760のコードベースから、1件あたり平均15件の脆弱性を特定しました。独自の測定手法に基づくこのデータにより、セキュリティリスクはモデルやフレームワークごとに予測可能であることを突き止めるに至りました。 

‍

詳細はこちら
ブログ
フィルターラベル
これはdivブロック内のテキストです。

AIツールからセキュアコーディングプログラムを実行する

MCP対応のAIツールから、SCWセキュアコーディングプログラムのトレーニング進捗の追跡、クエストのドラフト作成、レポート作成が可能になりました。すべてのSCWプランに含まれています。

詳細はこちら

AIを活用した開発をリリース前にセキュアに

開発者のリスクを可視化し、ポリシーを適用することで、ソフトウェア開発ライフサイクル全体における脆弱性を未然に防ぎます。

デモを予約する
該当する項目が見つかりません。