Secure Gradle Microservices with Custom OpenAPI Templates
Secure Gradle Microservices with Custom OpenAPI Templates

Customizing OpenAPI Generator’s ApiClient in a Gradle Microservices Project

Resolve CodeQL alerts by customizing OpenAPI Generator templates, securely fixing TrustManager issues in Gradle microservices.6 min


When developing a Gradle-based microservices application, you may have encountered CodeQL security alerts related to unsafe implementations within generated code from OpenAPI Generator. One common alert involves insecure use of TrustManager within the automatically generated ApiClient.java. Resolving these alerts means understanding how OpenAPI Generator creates these classes and how you can effectively customize this generation process.

OpenAPI Generator is a widely used tool for quickly generating client libraries, stubs, documentation, and configuration from your OpenAPI Specification files. Its main aim: reducing repetitive manual coding and keeping APIs consistent across your services. However, by design, the generator creates default implementation code, such as the ApiClient.java, which sometimes can introduce vulnerabilities or unwanted behaviors flagged by security analysis tools like CodeQL.

One such alert—related to insecure usage of TrustManager—signals potential security issues like improper SSL certificate validation. If left unchecked, this could leave your microservices vulnerable to man-in-the-middle attacks. To secure your projects and ensure compliance, you’ll need to adjust the generation process or modify the source templates of OpenAPI Generator.

How OpenAPI Generator Works Behind the Scenes

To grasp why this issue arises, let’s step back and understand OpenAPI Generator’s internals. The tool works like a code factory, taking your API definitions written in YAML or JSON and outputting ready-to-use code. The heart of this process is template-driven—meaning it leverages built-in or custom templates to generate output code according to specified languages and frameworks.

Each generated client library contains a default ApiClient that simplifies interactions with your API endpoints. Specifically, ApiClient.java sets up HTTP calls using libraries like Apache HttpClient or OkHttp, often with basic implementations that make assumptions suitable for a quick start but potentially vulnerable in production scenarios.

Digging into YAML Templates for Clues

The generator relies heavily on Mustache-based templates, stored within YAML or Mustache files, that dictate how classes like ApiClient are structured. You can find default templates in the generator’s official GitHub repository under the resources directory.

To better understand why your generated ApiClient.java includes potentially unsafe SSL implementations, it pays to review the Mustache templates themselves. Often, the default implementation aims for simplicity—assuming developers will override implementations before deploying securely into the production environment.

Is the TrustManager Alert a Default Behavior?

Indeed, many developers find themselves asking: “Is this TrustManager code generated intentionally?”—the answer usually being “Yes.” The default implementations generated by OpenAPI Generator are commonly designed as ready-to-use examples or quick-start templates rather than production-ready security-aware code.

For instance, a default-generated ApiClient.java snippet might look familiar like this, causing CodeQL to flag it:


// Example insecure TrustManager setup
TrustManager[] trustAllCerts = new TrustManager[] {
  new X509TrustManager() {
    public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
    public void checkClientTrusted(X509Certificate[] certs, String authType) {}
    public void checkServerTrusted(X509Certificate[] certs, String authType) {}
  }
};

While convenient, this snippet disables SSL verification, immediately triggering security scanners such as CodeQL.

Taking Control: Customizing the Generation Process

Fortunately, OpenAPI Generator allows extensive customization, giving you full command over how ApiClient.java gets generated. You have three primary paths to achieve the customization you need:

  • Override default Mustache templates with secure implementations.
  • Provide your own custom templates at generation time using configuration options.
  • Modify the generated Java files post-generation (least optimal since regeneration overwrites changes).

The best choice, clearly, is providing custom Mustache templates with proper SSL handling implemented. Here’s how you can go about customizing templates in your Gradle project:

  1. Copy the default Mustache templates from OpenAPI Generator’s GitHub repository into your Gradle project’s directory structure (usually under src/main/resources/templates).
  2. Adjust ApiClient.mustache to reflect proper SSL management, removing any insecure default TrustManager setups.
  3. Specify the path to the custom templates when invoking the generator:

// build.gradle configuration snippet
openApiGenerate {
    generatorName = 'java'
    inputSpec = "$rootDir/swagger.yaml".toString()
    outputDir = "$buildDir/generated-code"
    
    // custom templates
    templateDir = file("$projectDir/src/main/resources/templates")

    configOptions = [
        library: 'okhttp-gson'
    ]
}

With such setup, the generated ApiClient adopts your secure configurations, eliminating insecure SSL practices from generated code and resolving CodeQL alerts effectively.

Analyzing Gradle Dependencies for Clarity

To fully understand your customization capabilities, explore these dependencies in your build.gradle file:

  • org.springdoc:springdoc-openapi-gradle-plugin:1.9.0: Simplifies building OpenAPI documentation from your Spring Boot apps—ideal for documenting microservices clearly.
  • org.openapitools:openapi-generator-cli:7.10.0: Command-line interface providing easy generation of API clients from OpenAPI specs. It encapsulates everything needed by the generator itself, ensuring consistency and easy integration into a Gradle-based process.

The springdoc-openapi-gradle-plugin primarily assists with generating accurate OpenAPI definitions from your Java Spring Boot microservices, while openapi-generator-cli transforms these definitions into usable Java classes like ApiClient.java, directly affecting potential vulnerabilities.

Knowing which dependencies do what helps streamline your workflow, keeping your microservices secure, maintainable, and compliant with your organization’s policies.

Why This Matters in Your Microservices Project

Having full transparency over generated code isn’t optional; it’s essential. Generated code significantly impacts your project’s maintainability, scalability, security, and readiness for a production environment. This knowledge helps prevent accidental introduction of security vulnerabilities like insecure SSL implementations flagged by automated scanners, saving your applications from costly fixes down the line.

Adopting custom templates to control your generated ApiClient ensures security isn’t compromised for convenience. Plus, it boosts confidence among stakeholders about your proactive stance toward quality and security within the software development lifecycle.

In summary, customizing OpenAPI Generator templates in Gradle-based microservices ensures you’re producing secure, maintainable code every time. Take advantage of customizations to eliminate security alerts early, securing your workflows and improving peace of mind.

Now, here’s something to consider—how closely are you reviewing your generated code, and do you have a robust strategy for managing auto-generated resources securely? If you haven’t started yet, there’s no better time than now to revisit your generation process and OWASP top ten guidelines as you fortify your microservices infrastructure.


Like it? Share with your friends!

Shivateja Keerthi
Hey there! I'm Shivateja Keerthi, a full-stack developer who loves diving deep into code, fixing tricky bugs, and figuring out why things break. I mainly work with JavaScript and Python, and I enjoy sharing everything I learn - especially about debugging, troubleshooting errors, and making development smoother. If you've ever struggled with weird bugs or just want to get better at coding, you're in the right place. Through my blog, I share tips, solutions, and insights to help you code smarter and debug faster. Let’s make coding less frustrating and more fun! My LinkedIn Follow Me on X

0 Comments

Your email address will not be published. Required fields are marked *