The most dangerous detection in your SIEM is the one somebody "tuned" eight months ago by adding an exclusion in the portal. Nobody reviewed it, there's no record of why, and it hasn't fired since. Detection-as-Code exists to make that failure impossible, or at least visible.

This isn't a post about why version control is good. You know that. It's about what a working setup looks like for a SOC running Microsoft Sentinel, Splunk, or both: the repo structure, the rule format, how to actually unit test KQL and SPL, the pipeline, and the queries that tell you when a detection has quietly died.

Weekly Intelligence Pack · $14.99/mo
A new production detection rule every Tuesday — CrowdStrike, Sentinel, or Splunk
Real incident case study, hunt hypothesis, career tip. Direct Q&A support included.
Join — $14.99/mo →

What Detection-as-Code actually means

Teams sometimes hear "Detection-as-Code" and think it means writing everything in Sigma. It doesn't. The useful definition is five properties:

  1. Git is the source of truth. If a rule differs between the repo and the SIEM, the SIEM is wrong.
  2. Every change is reviewed. Pull requests, with a second analyst approving logic and exclusions.
  3. Every rule has tests. At least one case that must fire and one that must not.
  4. Deployment is automated. Nobody clicks "Save" in the analytics blade for a production rule.
  5. Rules are measured. Fire rate, false positive rate, health failures and data source availability are tracked per rule.

You can get the first two in an afternoon. The tests are where most of the value is, and where most teams stop, so that's where I'll spend the most time.

Repo layout

Keep it boring and predictable. Group by data domain rather than by ATT&CK tactic, because analysts maintaining rules think in terms of data sources ("the Entra rules", "the EDR rules"), and the ATT&CK mapping lives in metadata anyway.

Repo layout
detections/
  sentinel/
    identity/
      aitm_session_multi_country.yaml
      aitm_new_asn_mfa_hosting.yaml
    email/
      suspicious_inbox_rule.yaml
    endpoint/
      ...
  splunk/
    savedsearches.conf
    macros.conf
tests/
  sentinel/
    identity/
      aitm_session_multi_country.test.yaml
      fixtures/
        aitm_session_multi_country_positive.kql
        aitm_session_multi_country_negative_mobile.kql
  splunk/
    suspicious_inbox_rule.test.spl
tools/
  validate_rules.py
  run_tests.py
  deploy.py
  drift_check.py
.github/workflows/detections.yml
CODEOWNERS

CODEOWNERS matters more than it looks. Put identity rules under the people who understand Entra, endpoint rules under the EDR people. Review quality goes up immediately when the reviewer actually knows the data.

The rule format

For Sentinel, use the YAML format from Microsoft's own Azure-Sentinel GitHub repo as your base. It maps cleanly to the analytics rule API, and anyone who's contributed a community rule already knows it. Then add your own metadata block that the deploy script strips before pushing. Here's the session replay rule from my AiTM detection post in that format:

YAML
id: 3f6d2a8e-6c1b-4f5e-9a3d-2b7c8e1f4a90
name: AiTM - Entra session used from multiple countries
description: |
  The same Entra ID SessionId was used successfully from more than one country
  within 24h. Strong indicator of session cookie theft and replay (AiTM phishing).
severity: High
requiredDataConnectors:
  - connectorId: AzureActiveDirectory
    dataTypes:
      - SigninLogs
      - AADNonInteractiveUserSignInLogs
queryFrequency: 1h
queryPeriod: 1d
triggerOperator: gt
triggerThreshold: 0
tactics:
  - CredentialAccess
  - DefenseEvasion
relevantTechniques:
  - T1557
  - T1539
  - T1550.004
query: |
  let window = 1d;
  union isfuzzy=true
      (SigninLogs
          | where TimeGenerated > ago(window)
          | where ResultType == "0"
          | project TimeGenerated, UserPrincipalName, SessionId, IPAddress,
                    AutonomousSystemNumber, Location, AppDisplayName),
      (AADNonInteractiveUserSignInLogs
          | where TimeGenerated > ago(window)
          | where ResultType == "0"
          | project TimeGenerated, UserPrincipalName, SessionId, IPAddress,
                    AutonomousSystemNumber, Location, AppDisplayName)
  | where isnotempty(SessionId)
  | summarize FirstSeen = min(TimeGenerated), LastSeen = max(TimeGenerated),
              IPs = make_set(IPAddress, 20), ASNs = make_set(AutonomousSystemNumber, 20),
              Countries = make_set(Location, 10), Apps = make_set(AppDisplayName, 20)
              by UserPrincipalName, SessionId
  | where array_length(Countries) > 1
  | extend FirstIP = tostring(IPs[0])
entityMappings:
  - entityType: Account
    fieldMappings:
      - identifier: FullName
        columnName: UserPrincipalName
  - entityType: IP
    fieldMappings:
      - identifier: Address
        columnName: FirstIP
version: 1.2.0
kind: Scheduled

# ---- house metadata: validated in CI, stripped before deploy ----
x-soca:
  owner: identity-detections
  status: production          # experimental | production | deprecated
  tests: tests/sentinel/identity/aitm_session_multi_country.test.yaml
  data_dependencies: [SigninLogs, AADNonInteractiveUserSignInLogs]
  false_positives: |
    Split-tunnel VPNs that egress some apps in another country.
  last_validated: 2026-11-09
  changelog:
    - 1.2.0: dropped UserAgent from summarize, was splitting sessions on browser updates
    - 1.1.0: added AADNonInteractiveUserSignInLogs
    - 1.0.0: initial

Two fields do a lot of work. status lets you deploy experimental rules with lower severity, or as hunting queries, without a separate branch. data_dependencies feeds the "is this rule blind?" check later. Your validate_rules.py should fail the build if owner, tests or data_dependencies are missing, if id isn't a GUID, or if the version wasn't bumped when the query changed.

Keep the GUID stable

Use the YAML id as the alert rule's resource name when you deploy. That makes deploys idempotent (PUT on the same ID updates the rule) and keeps incident history attached to the rule across versions. Generating a new ID on every deploy is the most common way teams lose their tuning history.

Unit testing KQL for real

This is where most Detection-as-Code programs stall, because "how do I test a KQL query without a production workspace?" sounds hard. It isn't, thanks to one KQL behaviour: a let statement can shadow a table name. If you prepend let SigninLogs = datatable(...) to the rule, the rule queries your fixture instead of the real table, with zero changes to the rule itself.

The one gotcha is time. Rules use ago(), so hardcoded timestamps in fixtures go stale. Store an offset instead and compute TimeGenerated at query time:

Sentinel KQL — tests/sentinel/identity/fixtures/aitm_session_multi_country_positive.kql
// Same session: Canadian residential ISP, then a DigitalOcean IP in NL 7 minutes later
let SigninLogs = datatable(Offset:timespan, UserPrincipalName:string, SessionId:string,
                           IPAddress:string, AutonomousSystemNumber:int, Location:string,
                           AppDisplayName:string, ResultType:string)
[
    120m, "alice@contoso.com", "sess-001", "203.0.113.10",  812,   "CA", "OfficeHome",      "0",
    113m, "alice@contoso.com", "sess-001", "198.51.100.77", 14061, "NL", "Exchange Online", "0"
]
| extend TimeGenerated = now() - Offset;
let AADNonInteractiveUserSignInLogs = SigninLogs | take 0;
Sentinel KQL — tests/sentinel/identity/fixtures/aitm_session_multi_country_negative_mobile.kql
// Same session switching from home Wi-Fi to mobile carrier, same country: must NOT fire
let SigninLogs = datatable(Offset:timespan, UserPrincipalName:string, SessionId:string,
                           IPAddress:string, AutonomousSystemNumber:int, Location:string,
                           AppDisplayName:string, ResultType:string)
[
    3h, "bob@contoso.com", "sess-002", "203.0.113.20", 812, "CA", "OfficeHome", "0"
]
| extend TimeGenerated = now() - Offset;
let AADNonInteractiveUserSignInLogs = datatable(Offset:timespan, UserPrincipalName:string,
                           SessionId:string, IPAddress:string, AutonomousSystemNumber:int,
                           Location:string, AppDisplayName:string, ResultType:string)
[
    1h, "bob@contoso.com", "sess-002", "192.0.2.44", 852, "CA", "Microsoft Teams", "0"
]
| extend TimeGenerated = now() - Offset;
YAML — tests/sentinel/identity/aitm_session_multi_country.test.yaml
rule: detections/sentinel/identity/aitm_session_multi_country.yaml
cases:
  - name: session replayed from another country fires
    fixture: tests/sentinel/identity/fixtures/aitm_session_multi_country_positive.kql
    expect_rows: 1
  - name: mobile network switch in same country does not fire
    fixture: tests/sentinel/identity/fixtures/aitm_session_multi_country_negative_mobile.kql
    expect_rows: 0

Where do the tests run? Microsoft publishes the Kusto emulator as a Docker image (kustainer), which is the real query engine running locally. No Azure subscription, no cost, and it runs fine as a CI service container. The runner is about 25 lines:

Python — tools/run_tests.py
import pathlib
import sys

import yaml
from azure.kusto.data import KustoClient, KustoConnectionStringBuilder

client = KustoClient(KustoConnectionStringBuilder.with_no_authentication("http://localhost:8080"))
failures = 0

for test_file in sorted(pathlib.Path("tests/sentinel").rglob("*.test.yaml")):
    spec = yaml.safe_load(test_file.read_text())
    rule = yaml.safe_load(pathlib.Path(spec["rule"]).read_text())
    for case in spec["cases"]:
        fixture = pathlib.Path(case["fixture"]).read_text()
        query = fixture + "\n" + rule["query"]
        try:
            rows = client.execute("NetDefaultDB", query).primary_results[0].rows
            got = len(rows)
        except Exception as exc:  # syntax errors fail the test, not the runner
            print(f"ERROR {rule['name']} :: {case['name']}\n      {exc}")
            failures += 1
            continue
        ok = got == case["expect_rows"]
        print(f"{'PASS ' if ok else 'FAIL '} {rule['name']} :: {case['name']} "
              f"(expected {case['expect_rows']}, got {got})")
        failures += 0 if ok else 1

sys.exit(1 if failures else 0)

Things the emulator won't have: Sentinel-specific functions like _GetWatchlist(), ASIM parsers, and your saved workspace functions. Stub them in the fixture the same way you stub tables, for example let _GetWatchlist = (alias:string) { datatable(SearchKey:string)["14061", "16509"] };. That's actually a feature: it forces you to write down exactly what the rule depends on.

What to test, at minimum, for each rule:

The Splunk side

Splunk doesn't have table shadowing, so structure the rule so the base search is separate from the logic. Put the logic in a macro, and both the production search and the test call the same macro.

Splunk SPL — macros.conf
[soca_inbox_rule_logic]
definition = eval move_to=replace(mvindex(mvfilter(match(pairs, "^MoveToFolder=")), 0), "^MoveToFolder=", "") \
| eval rule_name=replace(mvindex(mvfilter(match(pairs, "^Name=")), 0), "^Name=", "") \
| eval delete_msg=if(isnotnull(mvfind(pairs, "^DeleteMessage=True")), 1, 0) \
| eval hides_mail=if(match(move_to, "(?i)rss|conversation history|archive") OR delete_msg=1, 1, 0) \
| eval short_name=if(len(trim(rule_name)) <= 3, 1, 0) \
| where hides_mail=1 OR short_name=1 \
| table _time UserId ClientIP rule_name move_to delete_msg hides_mail short_name
Splunk SPL — savedsearches.conf
[SOCA - O365 Suspicious Inbox Rule]
search = index=o365 sourcetype="o365:management:activity" Workload=Exchange Operation IN ("New-InboxRule","Set-InboxRule") \
| eval pairs=mvzip('Parameters{}.Name', 'Parameters{}.Value', "=") \
| `soca_inbox_rule_logic`
enableSched = 1
cron_schedule = */15 * * * *
dispatch.earliest_time = -20m
dispatch.latest_time = -5m
counttype = number of events
relation = greater than
quantity = 0
alert.suppress = 1
alert.suppress.fields = UserId,rule_name
alert.suppress.period = 4h

The test replaces the base search with makeresults and feeds the macro the normalised pairs field:

Splunk SPL — unit test fixture
| makeresults count=1
| eval UserId="alice@contoso.com", ClientIP="203.0.113.10:51234",
       pairs=split("Name=..|MoveToFolder=RSS Subscriptions|DeleteMessage=False", "|")
| `soca_inbox_rule_logic`
| stats count AS hits
| eval result=if(hits=1, "PASS", "FAIL")

Run tests through the REST API (/services/search/jobs with exec_mode=oneshot) against a dev Splunk instance or a container, and fail the pipeline on any FAIL. If you're on Splunk ES and want the full-fat version, Splunk's own contentctl tooling (what they use for the security_content repo) can replay real attack data into a test instance. It's heavier, but it tests the whole pipeline including sourcetype parsing, which the macro approach doesn't.

The pipeline

Validate and test on every pull request. Deploy only on merge to main, using a federated identity so there's no client secret sitting in the repo settings.

YAML — .github/workflows/detections.yml
name: detections
on:
  pull_request:
    paths: ["detections/**", "tests/**", "tools/**"]
  push:
    branches: [main]
    paths: ["detections/**"]

jobs:
  validate:
    runs-on: ubuntu-latest
    services:
      kusto:
        image: mcr.microsoft.com/azuredataexplorer/kustainer-linux:latest
        env:
          ACCEPT_EULA: "Y"
        ports:
          - 8080:8080
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install pyyaml jsonschema azure-kusto-data
      - name: Schema and metadata checks
        run: python tools/validate_rules.py detections/sentinel
      - name: Wait for Kusto emulator
        run: |
          for i in $(seq 1 30); do
            curl -sf -X POST http://localhost:8080/v1/rest/mgmt \
              -H "Content-Type: application/json" \
              -d '{"csl":".show cluster"}' && break
            sleep 5
          done
      - name: Unit tests
        run: python tools/run_tests.py

  deploy:
    needs: validate
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    environment: production        # require approval here if you want a gate
    permissions:
      id-token: write
      contents: read
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 2
      - uses: azure/login@v2
        with:
          client-id: ${{ secrets.AZURE_CLIENT_ID }}
          tenant-id: ${{ secrets.AZURE_TENANT_ID }}
          subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
      - run: pip install pyyaml
      - name: Deploy changed rules
        run: |
          python tools/deploy.py \
            --changed-only \
            --resource-group "${{ vars.SENTINEL_RG }}" \
            --workspace "${{ vars.SENTINEL_WORKSPACE }}"

For the deploy step itself you have three reasonable options:

Last step of the rollout: take write access on analytics rules away from humans. The pipeline's service principal gets Microsoft Sentinel Contributor; analysts get Responder. Emergency edits still happen, so allow them through a break-glass group and let the drift check (below) open a PR to bring the repo back in line.

Drift detection

Even with RBAC locked down, run a nightly job that lists deployed rules through the API, normalises them, and diffs against the repo. Anything enabled in the workspace that isn't in git, or differs from git, opens an issue. This also catches content hub updates that overwrite rules you'd customised from a template.

Measuring rules once they're live

Detection-as-Code without measurement just means your noisy rules are now version-controlled. Three queries I'd run weekly.

Which rules waste analyst time? Incident classification by rule over 90 days:

Sentinel KQL — False positive rate by analytics rule (closed incidents, last 90 days)
SecurityIncident
| where TimeGenerated > ago(90d)
| summarize arg_max(TimeGenerated, *) by IncidentNumber
| where Status == "Closed"
| summarize
    Total         = count(),
    TruePositive  = countif(Classification == "TruePositive"),
    BenignPositive = countif(Classification == "BenignPositive"),
    FalsePositive = countif(Classification == "FalsePositive"),
    Undetermined  = countif(Classification == "Undetermined")
    by Title
| extend FPRate = round(100.0 * FalsePositive / Total, 1),
         UndeterminedRate = round(100.0 * Undetermined / Total, 1)
| order by FalsePositive desc

A high UndeterminedRate is its own finding: analysts can't work out what the alert means, which usually means bad entity mapping or no context in the description. Fix the rule, not the analysts.

Which rules are failing to run? Enable Sentinel health monitoring, then:

Sentinel KQL — Analytics rules with failed or degraded runs in the last 7 days
SentinelHealth
| where TimeGenerated > ago(7d)
| where SentinelResourceType == "Analytics Rule"
| where Status != "Success"
| summarize Failures = count(), LastFailure = max(TimeGenerated),
            Reasons = make_set(Description, 5)
            by SentinelResourceName, Status
| order by Failures desc

Which rules are blind? A rule that hasn't fired in 90 days is either watching for something rare or watching an empty table. The data_dependencies field in the metadata lets you generate this check per rule; the core of it is just ingestion freshness per table:

Sentinel KQL — Data source freshness for tables your rules depend on
union withsource = SourceTable SigninLogs, AADNonInteractiveUserSignInLogs, OfficeActivity, AuditLogs
| where TimeGenerated > ago(1d)
| summarize LastEvent = max(TimeGenerated), Events = count() by SourceTable
| extend MinutesSinceLast = datetime_diff('minute', now(), LastEvent)
| order by MinutesSinceLast desc

A table that drops out of that result entirely hasn't sent anything in 24 hours. Every rule that lists it in data_dependencies is blind, and nothing in the SIEM will tell you so unless you ask.

Where Sigma fits

Sigma is worth it if you run more than one SIEM, share detections with other teams, or consume a lot of community content. pySigma has backends for KQL (Sentinel and Defender) and SPL. It's less useful when you live in one platform and your best detections rely on joins, baselines and make_set logic like the AiTM rules above, which don't round-trip through Sigma cleanly. A reasonable split: write simple single-event detections in Sigma so they're portable, and keep correlation logic native. Both live in the same repo and go through the same tests.

A realistic rollout

  1. Week 1: export every enabled analytics rule (or saved search) into the repo as-is. No refactoring. Turn on branch protection and CODEOWNERS.
  2. Weeks 2 to 3: stand up the pipeline with schema validation only. Start requiring PRs for changes, even if deploys are still manual.
  3. Weeks 3 to 6: write tests for your top 10 rules by incident volume, and your top 10 by severity. Those 20 rules are most of your real coverage.
  4. Week 6 onward: automate deploy, remove portal write access, turn on drift detection, start the weekly metrics review.

The thing that makes it stick isn't the tooling. It's the first time a PR review catches an exclusion that would have blinded a rule, or a test fails because someone changed a field name. After that, nobody on the team wants to go back to editing rules in the portal.

Weekly Intelligence Pack
Production detections like these, every Tuesday

Every issue includes a full detection rule for Sentinel, CrowdStrike or Splunk, with investigation steps, false positive guidance and MITRE mapping. Platforms rotate so you get broad coverage over time.

Join — $14.99/mo See a Sample Issue
Founding member pricing locked for life · 30-day money back