Query Suites and Packs

Earn 25 points (50 with Pro) in two steps

  1. ① Read through the lesson — each section gets a ✓ as you scroll through it.
  2. ② When every section has a ✓, tap Complete lesson.

0 of 11 read · keep scrolling

✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro

Code Scanning Fundamentals: Mastering Query Suites and Packs

Introduction: Why Code Scanning Matters

In the modern software development lifecycle, the speed at which we deliver features often overshadows the inherent risks introduced by every line of code. Code scanning, often referred to as Static Analysis Security Testing (SAST), is the practice of automatically inspecting source code to identify potential security vulnerabilities, logic errors, and compliance violations before the code ever reaches a production environment. By integrating these checks into the developer workflow, teams can catch issues early—when they are cheapest and easiest to fix—rather than discovering them during a costly post-deployment security audit.

However, simply running "all the checks" is rarely a viable strategy. Modern codebases are massive, and running every possible security rule against every commit can lead to "alert fatigue," where developers become desensitized to warnings because the signal-to-noise ratio is too low. This is where Query Suites and Query Packs come into play. These organizational tools allow you to curate, bundle, and target specific security checks based on the language, framework, or risk profile of your project. Understanding how to configure these suites effectively is the difference between a security tool that provides actionable insights and one that simply adds noise to your build logs.

In this lesson, we will explore the architecture of query suites and packs, how to customize them to fit your unique development requirements, and how to maintain them as your codebase evolves. By the end of this guide, you will be able to move beyond default configurations and implement a tailored code scanning strategy that protects your applications without hindering developer productivity.


Not read yet

Understanding the Architecture: Queries, Suites, and Packs

To effectively configure code scanning, you must first understand the hierarchy of the tools involved. At the lowest level, we have individual queries. A query is a specific script or logic block designed to look for a particular pattern—such as a hardcoded credential, a potential SQL injection vulnerability, or an insecure cryptographic library usage.

What is a Query Suite?

A query suite is a collection of these individual queries, grouped together to serve a specific purpose. For example, you might create a "Critical Security Suite" that contains only the rules that detect high-impact vulnerabilities, or a "Compliance Suite" that focuses on industry-specific standards like OWASP Top 10 or CWE (Common Weakness Enumeration) compliance. Suites are typically defined in configuration files (often YAML) that specify which queries to include, exclude, or modify.

What is a Query Pack?

A query pack acts as a container for your queries and suites. It is essentially a distribution mechanism. If you are working in a large organization, you might maintain a central repository of security standards. By packaging these into a query pack, you can version, share, and distribute these standards across hundreds of different project repositories. When a developer runs a scan, they point their configuration to a specific pack, ensuring that every project in the organization is being evaluated against the same set of rules.

Callout: The Distinction Between Suites and Packs While the terms are sometimes used interchangeably in casual conversation, there is a technical distinction. A Pack is the distribution unit (the "box" containing the files), whereas a Suite is the logic (the "filter" or "selection criteria") used to decide which queries to run from within that pack. Think of a pack as a software package or library, and a suite as the configuration profile that tells the library what to do.


Not read yet

The Anatomy of a Query Suite Configuration

Most modern code scanning tools utilize a configuration file—commonly named codeql-config.yml or similar—to define how scans should behave. This file allows you to tell the scanner exactly which suites or individual queries to execute.

Defining Suites in YAML

When you define a suite, you are essentially providing a list of criteria to the scanning engine. Here is an example of what that configuration looks like in a practical environment:

name: "My Custom Security Profile"
disable-default-queries: true
queries:
  - name: "High Severity Vulnerabilities"
    uses: security-extended
  - name: "Custom Project Rules"
    uses: ./.github/queries/custom-rules.qls
  - name: "Specific Vulnerability Exclusion"
    exclude:
      id:
        - java/hardcoded-credentials
        - python/insecure-temp-file

In this example, we have performed three distinct actions:

  1. Disabled Default Queries: We told the engine not to run its "out of the box" checks, giving us full control.
  2. Included Suites: We imported a standard set of queries (security-extended) and a local file containing our own specialized logic.
  3. Excluded Specific Rules: We explicitly disabled two rules that were generating false positives in our specific environment.

Why Disable Default Queries?

It is tempting to simply run the default suite provided by your tool vendor. However, default suites are designed to be "one size fits all." They often include rules that do not apply to your language, framework, or architecture. By disabling the defaults and building your own suites, you eliminate irrelevant alerts, which builds trust with your engineering team. When developers know that a flagged issue is actually a problem, they are far more likely to fix it immediately.


Not read yet

Implementing and Managing Query Packs

Managing query packs is critical for scalability. If you have 50 different microservices, you do not want to manually manage 50 different configuration files. Instead, you create a central pack that defines the security standards for your organization.

Step-by-Step: Creating a Query Pack

  1. Initialize the Pack: Create a directory structure that follows the naming conventions required by your scanning engine. This usually involves a qlpack.yml file that declares the name, version, and dependencies of the pack.
  2. Organize Queries: Place your .ql or equivalent query files into logical subdirectories within the pack.
  3. Define Suites: Create .qls (Query Suite) files within the pack. These files serve as the "menus" that developers can select from.
  4. Version Control: Treat your query pack like any other software product. Use semantic versioning (e.g., v1.2.4). If you update a query, bump the version so that teams can opt-in to the new ruleset when they are ready.

Distributing the Pack

Once your pack is ready, you can publish it to a registry or a private repository. Your CI/CD pipelines can then reference this pack by version number:

# Example CI configuration
jobs:
  code-scanning:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v3
      - name: Initialize Code Scanning
        uses: github/codeql-action/init@v2
        with:
          queries: my-org/security-pack@v2.1.0:suites/production-ready.qls

By pinning the version (@v2.1.0), you ensure that your security checks are deterministic. You won't have a situation where a security rule is updated overnight and suddenly breaks your build because of a new, unexpected alert.

Note: The Importance of Determinism In automated environments, consistency is paramount. Always pin your query packs to a specific version. Allowing your CI/CD pipeline to pull the "latest" version can lead to "flaky" builds where a scan passes on Monday but fails on Tuesday despite no changes to the application code.


Not read yet

Best Practices for Query Selection

Selecting the right queries is an iterative process. You cannot simply "set it and forget it." Follow these guidelines to keep your scanning effective and your developer experience positive.

1. Start with the OWASP Top 10

If you are unsure where to begin, focus your query suites on the OWASP Top 10. These are the most common and impactful security risks. By ensuring your queries cover these areas, you address the most significant threats to your application immediately.

2. Implement a "Gradual Rollout" Strategy

Do not enable every possible rule at once. Start by enabling a small set of high-confidence rules. Once the team has cleared the backlog of existing issues, add a new set of rules. This prevents developers from being overwhelmed by hundreds of "legacy" alerts that have existed in the code for years.

3. Treat Security Rules as Code

Your query suites and packs should live in a repository with the same rigor as your application code. Use Pull Requests (PRs) to propose changes to a query suite. Require reviews from both the security team and senior developers. This ensures that when a new rule is added, the team understands why it is being added and what it expects to find.

4. Categorize by Risk

Group your queries into tiers.

  • Tier 1 (Critical): Immediate build failure. High-confidence rules like SQL injection or hardcoded API keys.
  • Tier 2 (Warning): Does not break the build but logs a warning. Useful for code style, deprecated library usage, or minor performance issues.
  • Tier 3 (Informational): Only visible in the security dashboard. Used for tracking technical debt or audit requirements.

Not read yet

Common Pitfalls and How to Avoid Them

Even with the best intentions, it is easy to fall into traps that render code scanning ineffective. Here are the most common mistakes I see in the field.

Pitfall 1: Over-Reliance on "Default" Suites

Many teams use the default configuration and then spend months complaining about false positives. If a tool is flagging a pattern that isn't a risk in your specific context (e.g., a "dangerous" function that you have wrapped in a secure internal library), you must suppress it. Use the configuration file to exclude these patterns. A tool that cries "wolf" too often will eventually be ignored.

Pitfall 2: Neglecting the "False Positive" Feedback Loop

When a developer encounters a false positive, they should be able to flag it or fix the query. If there is no mechanism to feed this information back to the security team, the false positive will remain in the suite forever. Establish a simple process: if a rule produces a false positive, create an issue in the security pack repository, and update the exclusion list or the query logic.

Pitfall 3: Ignoring Performance

Some queries are computationally expensive. If you run a deep-dive data flow analysis on every single commit, your CI/CD pipeline time will skyrocket.

  • Tip: Run "Fast" queries (simple pattern matching) on every pull request. Run "Slow" queries (deep data flow analysis) only on the main branch or on a nightly schedule.

Pitfall 4: Lack of Documentation

If a developer gets an alert, they need to know why it is an alert and how to fix it. Ensure your custom queries have clear documentation or links to internal wikis. A cryptic error message like CodeQL Error: 1042 is useless; a message like Security Alert: Potential SQL Injection in user-input field. See: [Internal Link to Secure Coding Guidelines] is actionable.


Not read yet

Comparison Table: Default vs. Custom Query Configurations

Feature Default Configuration Custom Query Suite
Setup Time Instant Requires initial effort
Relevance Low (Generic) High (Context-aware)
Maintenance None Requires ongoing updates
Alert Noise High Low (Optimized)
Flexibility Rigid Fully Configurable
Ownership Vendor-driven Team-driven

Advanced Customization: Refining Query Logic

Sometimes, you need to go beyond simply including or excluding queries. You might need to write your own custom queries to detect patterns specific to your business logic. For example, if your company has a proprietary authentication service, you need to ensure that every developer is using the AuthService.login() method rather than the standard bcrypt.compare() function.

Writing a Custom Query

Most scanning engines use a logic-based language (like CodeQL). Here is a conceptual example of a query that flags the use of an insecure library:

import javascript

// Find all calls to the insecure 'legacy_crypto' library
from CallExpr call
where call.getCalleeName() = "legacy_crypto_hash"
select call, "This library is deprecated. Please use the new 'secure_crypto' module."

By packaging this logic into a custom .ql file and adding it to your query suite, you can enforce organizational standards that generic scanners would never catch. This is the ultimate level of security maturity: moving from "detecting common vulnerabilities" to "enforcing secure architecture."

Callout: The Power of Context-Aware Scanning Generic scanners do not know your business logic. They know what a SQL injection looks like, but they do not know that MyCompany.internal.query() is a safe wrapper for database access. By writing custom queries, you teach the scanner the "shape" of your application, drastically reducing false positives and focusing the team on actual security risks.


Not read yet

Integrating with the Developer Workflow

The most effective query suites are those that developers interact with daily. If the scanning only happens at the very end of the release process, it is too late.

IDE Integration

Many code scanning tools offer IDE plugins. These plugins allow developers to run the same query suites locally that are used in the CI/CD pipeline. Encourage your team to install these plugins. If a developer can see the security alert while they are still writing the code, the cost of fixing it is effectively zero.

The Pull Request Experience

The primary interface for code scanning should be the Pull Request. When a developer submits code, the CI pipeline should run the selected query suite and post comments directly onto the lines of code that triggered an alert. This creates a tight feedback loop.

  • Best Practice: When a scan fails, provide clear instructions.
    • "This code violates our security policy (Reference: SEC-001)."
    • "Click here to see the remediation guide."
    • "If you believe this is a false positive, follow this link to request an exception."

Not read yet

Maintaining Your Security Posture

Security is not a static state; it is a moving target. New vulnerabilities are discovered daily, and your application code is constantly changing. Your query suites must evolve accordingly.

Quarterly Reviews

Set aside time every three months to review your query suites.

  • Are there rules that have never triggered? (Maybe they are too broad or the codebase has matured.)
  • Are there new types of vulnerabilities that your current suite is missing?
  • Are there common coding patterns that your team is repeating that could be enforced via a new custom rule?

Communicating Changes

When you update a query pack, communicate it to the engineering team. "We have added a new rule to detect usage of insecure JSON parsing libraries. Please check your PRs for new alerts." Transparency prevents frustration. When developers understand that security rules are being updated to protect them and the company, they are much more likely to support the initiative.


Not read yet

Common Questions (FAQ)

Q: How do I know if a query is a false positive? A: A false positive occurs when the code is technically compliant with security standards but is being flagged by the scanner. If you see an alert, examine the data flow. If the user input is sanitized or validated elsewhere, and the scanner is not "smart" enough to see that, it is a false positive. You should suppress it via the configuration file or, better yet, refactor the code to be more "obvious" to the scanner.

Q: Should I run all queries on every branch? A: No. It is best practice to run a subset of "quick" queries on feature branches to keep feedback fast. Run the full, comprehensive suite on the main branch or during nightly builds to ensure full coverage without slowing down the development process.

Q: What happens if a security rule breaks the build? A: This is a design choice. For critical vulnerabilities (like hardcoded secrets), the build should break. For stylistic or lower-risk issues, the build should pass, but a warning should be generated. Use your query suite definitions to set these thresholds.

Q: Can I use multiple packs? A: Yes. You can combine multiple packs in your configuration file. This is useful if you want to use a standard "industry" pack (like the OWASP pack) alongside your own "internal" pack that defines company-specific security standards.


Not read yet

Key Takeaways

  1. Prioritize Signal Over Noise: The goal of a code scanning suite is not to find every possible issue, but to find the important ones. Use query suites to filter out noise and focus on what matters to your application.
  2. Version Everything: Treat your query packs like software. Versioning them ensures that your security infrastructure remains stable, predictable, and reproducible across different projects and environments.
  3. Automate the Feedback Loop: Move security checks into the developer's IDE and the Pull Request process. The faster a developer receives feedback, the more likely they are to act on it without friction.
  4. Customization is Essential: Generic tools are a good starting point, but they will never understand your unique business logic. Invest the time to write custom queries that reflect your company’s specific secure coding standards.
  5. Iterate and Evolve: Security is a continuous process. Regularly review your suites, remove ineffective rules, and add new ones as your codebase changes and new threats emerge.
  6. Foster Collaboration: Security should not be a "policing" function. Work with your developers to refine rules, address false positives, and ensure that the security tools you implement actually make their lives easier, not harder.
  7. Document the "Why": Every security rule should have a clear purpose and a path to remediation. If a developer doesn't understand why a rule exists, they will likely find a way to bypass it rather than fixing the underlying issue.

By mastering query suites and packs, you transform code scanning from a passive security check into an active part of your engineering culture. You move from being a team that "hopes" the code is secure to a team that "knows" the code meets specific, enforced standards. This is the foundation of a mature, resilient, and high-velocity software organization.

Not read yet

Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.