From ad8a92d60b33a9c4e4364e2bc26c1b28a7b33245 Mon Sep 17 00:00:00 2001 From: Pierre Penhouet Date: Tue, 1 Dec 2026 14:39:03 +0100 Subject: [PATCH 1/3] feat(playbooks): add a contribution guide and a CI check for playbook templates - playbooks/README.md: how to contribute a template (build and run it in Sekoia, export it with the API, complete it, check it, open a pull request), what makes a good template, what the check verifies. - playbooks/tools/check_templates.py: checks every template against the production branch of automation-library. Errors are what the platform refuses when it loads a template, or what makes every run fail; on a pull request only the files it touches can block it. - playbooks/tools/export_template.py: turns a playbook into a template file through the public API (GET /v1/symphony/playbooks/{uuid}), without the accounts of the community. - .github: workflow running the check on pull requests, on main and weekly; pull request template; issue forms for template ideas and broken templates. - Remove playbooks/templates/playbooks.json: the platform has listed templates from its own API since July 2024 and skips this file. Co-Authored-By: Claude Opus 5.5 --- .github/ISSUE_TEMPLATE/config.yml | 5 + .../ISSUE_TEMPLATE/playbook-template-bug.yml | 22 + .../playbook-template-request.yml | 42 ++ .github/pull_request_template.md | 13 + .github/workflows/playbook-templates.yml | 60 ++ README.md | 11 +- playbooks/README.md | 61 ++ playbooks/templates/playbooks.json | 486 --------------- playbooks/tools/.gitignore | 1 + playbooks/tools/builtin_catalogue.json | 37 ++ playbooks/tools/check_templates.py | 562 ++++++++++++++++++ playbooks/tools/export_template.py | 105 ++++ 12 files changed, 911 insertions(+), 494 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/playbook-template-bug.yml create mode 100644 .github/ISSUE_TEMPLATE/playbook-template-request.yml create mode 100644 .github/pull_request_template.md create mode 100644 .github/workflows/playbook-templates.yml create mode 100644 playbooks/README.md delete mode 100644 playbooks/templates/playbooks.json create mode 100644 playbooks/tools/.gitignore create mode 100644 playbooks/tools/builtin_catalogue.json create mode 100644 playbooks/tools/check_templates.py create mode 100644 playbooks/tools/export_template.py diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..98810df --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: true +contact_links: + - name: Sekoia support + url: https://docs.sekoia.io/getting_started/support_and_resources/ + about: For a problem with your Sekoia account or data, contact support rather than opening a public issue. diff --git a/.github/ISSUE_TEMPLATE/playbook-template-bug.yml b/.github/ISSUE_TEMPLATE/playbook-template-bug.yml new file mode 100644 index 0000000..5e5493e --- /dev/null +++ b/.github/ISSUE_TEMPLATE/playbook-template-bug.yml @@ -0,0 +1,22 @@ +name: Broken playbook template +description: A template from the playbook editor fails or does not do what it says +labels: ["playbook-template", "bug"] +body: + - type: input + id: template + attributes: + label: Template + description: Its name in the editor, or its file under playbooks/templates/. + validations: + required: true + - type: textarea + id: what-happens + attributes: + label: What happens + description: The node that fails and its error message. Remove any customer data before posting. + validations: + required: true + - type: textarea + id: expected + attributes: + label: What you expected diff --git a/.github/ISSUE_TEMPLATE/playbook-template-request.yml b/.github/ISSUE_TEMPLATE/playbook-template-request.yml new file mode 100644 index 0000000..8661764 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/playbook-template-request.yml @@ -0,0 +1,42 @@ +name: Playbook template idea +description: Suggest a playbook template, or tell us you are building one +labels: ["playbook-template", "idea"] +body: + - type: markdown + attributes: + value: | + Templates appear in the Sekoia playbook editor under **Start from a template**, for every customer. + Ideas with a clear use case and the integrations they need are the easiest to pick up, by us or by anyone in the community. + - type: textarea + id: use-case + attributes: + label: Use case + description: 'What should happen, when, and for whom? Example: "When an alert on a phishing rule is created, check the sender''s domain and comment the verdict."' + validations: + required: true + - type: input + id: integrations + attributes: + label: Integrations + description: The products the playbook talks to (e.g. Microsoft Entra ID, Jira, VirusTotal). + - type: dropdown + id: trigger + attributes: + label: Trigger + options: + - Manual, from an alert + - Alert created or updated + - Case created or updated + - Scheduled (cron) + - Webhook + - Not sure + - type: dropdown + id: contribution + attributes: + label: Will you build it? + options: + - Yes, I will open a pull request + - I can help test it + - No, it is an idea for someone else + validations: + required: true diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..c6fc146 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,13 @@ +## What this adds or fixes + + + +## If you add or change a playbook template + +- [ ] I built and ran this playbook in a Sekoia community, then exported it with `playbooks/tools/export_template.py` +- [ ] The description says what the playbook does and what it needs (integration, account, licence, fields in the events) +- [ ] The trigger is right for the use case (manual from an alert, alert created, cron, webhook) +- [ ] `python playbooks/tools/check_templates.py --automation-library ` passes locally +- [ ] A screenshot of the playbook, or of a successful run, is attached below + + diff --git a/.github/workflows/playbook-templates.yml b/.github/workflows/playbook-templates.yml new file mode 100644 index 0000000..df2ee1b --- /dev/null +++ b/.github/workflows/playbook-templates.yml @@ -0,0 +1,60 @@ +name: Playbook templates + +on: + pull_request: + paths: + - "playbooks/**" + - ".github/workflows/playbook-templates.yml" + push: + branches: [main] + paths: + - "playbooks/**" + # An action can be removed or changed in automation-library after a template was merged + schedule: + - cron: "23 6 * * 1" # Monday, 06:23 UTC + workflow_dispatch: + +permissions: + contents: read + +jobs: + check: + name: Check playbook templates + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Check out the repository + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Set up Python + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.12" + + - name: Install the checker dependencies + run: pip install "jsonschema==4.26.0" "jinja2==3.1.6" + + # The catalogue the platform runs: the production branch of automation-library, manifests only + - name: Fetch the automation-library manifests + run: | + git clone --quiet --depth 1 --filter=blob:none --sparse --branch production \ + https://github.com/SEKOIA-IO/automation-library.git "$RUNNER_TEMP/automation-library" + git -C "$RUNNER_TEMP/automation-library" sparse-checkout set --no-cone \ + '/*/manifest.json' '/*/action_*.json' '/*/trigger_*.json' + + - name: Check the templates + env: + EVENT_NAME: ${{ github.event_name }} + BASE_REF: ${{ github.base_ref }} + run: | + set -euo pipefail + if [ "$EVENT_NAME" = "pull_request" ]; then + # Only the files of the pull request block it: an older bug on main is reported as a warning + python playbooks/tools/check_templates.py --automation-library "$RUNNER_TEMP/automation-library" \ + --base "origin/${BASE_REF}" + else + python playbooks/tools/check_templates.py --automation-library "$RUNNER_TEMP/automation-library" + fi diff --git a/README.md b/README.md index 474c82f..4ed9b84 100644 --- a/README.md +++ b/README.md @@ -5,12 +5,7 @@ playbooks and much more to help you make the most of the capabilities of the Sek For questions and feedback, please contact support@sekoia.io -## Playbook template +## Playbook templates -You can add playbook template in the folder: "playbooks/templates". -Your template must NOT contain the fields: - "trigger_configuration_uuid" - "module_configuration_uuid" - "community_uuid" -Your need to add your new template file to the list of template in the file: - "playbooks/templates/playbooks.json" +Playbook templates appear in the Sekoia playbook editor under **Start from a template**, for every customer. +To contribute one, read [playbooks/README.md](playbooks/README.md): build and run it in Sekoia, export it, check it, open a pull request. diff --git a/playbooks/README.md b/playbooks/README.md new file mode 100644 index 0000000..1dba34e --- /dev/null +++ b/playbooks/README.md @@ -0,0 +1,61 @@ +# Playbook templates + +The templates in [`templates/`](templates/) appear in the Sekoia playbook editor, under **Start from a template** on a new playbook, for every customer in every region. They are the fastest way to share a playbook that works: an enrichment, a notification, a response to a type of alert. + +A template merged on `main` is published with the next release of the Sekoia playbook service. Removing a file removes the template from the editor. Playbooks already created from it keep their own copy and are not affected. + +## Contribute a template + +1. **Build and run the playbook in your Sekoia community.** A template that never ran is not accepted. +2. **Export it into this repository.** The UUID of the playbook is the last part of its address in Sekoia (`.../playbooks/`). + + ```bash + SEKOIA_API_KEY= python playbooks/tools/export_template.py enrich_alert_with_example.json + ``` + + The API key needs the **View playbooks** permission. Outside FRA1, add `--base-url` with the API URL of your region (listed in the script and in the [API documentation](https://docs.sekoia.io/developer/api/)). The script removes the accounts of your community (module and trigger configurations), as Sekoia does when it turns a playbook into a template, and gives the file a new UUID. +3. **Complete the file.** Write the description, add tags, and replace every value specific to your environment (URL, project key, IOC collection...) with `_to_update_`. +4. **Check it.** + + ```bash + pip install "jsonschema==4.26.0" "jinja2==3.1.6" + git clone --depth 1 --filter=blob:none --sparse --branch production \ + https://github.com/SEKOIA-IO/automation-library.git /tmp/automation-library + git -C /tmp/automation-library sparse-checkout set --no-cone '/*/manifest.json' '/*/action_*.json' '/*/trigger_*.json' + python playbooks/tools/check_templates.py --automation-library /tmp/automation-library + ``` +5. **Open a pull request** and fill in the checklist. The same check runs on the pull request. + +Not ready to build it? [Open an idea](https://github.com/SEKOIA-IO/Community/issues/new?template=playbook-template-request.yml): someone else may pick it up. + +## What makes a good template + +- **One use case, named by what it does.** "Enrich an alert with AbuseIPDB", not "AbuseIPDB playbook". +- **A description that says what it does and what it needs**: the integration and its account, a licence if any, the event fields it reads. +- **Published actions only.** Every action and trigger must exist on the `production` branch of [automation-library](https://github.com/SEKOIA-IO/automation-library). If your integration is not released yet, open the template pull request after its release. +- **Event fields that exist.** Read fields of the Sekoia event taxonomy (`source.ip`, `url.original`, `file.hash.sha256`...). A field no intake produces makes every run fail. +- **Nothing private.** No account, API key, URL or name from your environment. Mark what the reader must change with `_to_update_` and say so in the description. +- **Tags readers filter on.** Reuse existing tags, start them with a capital letter, and add the vendor name (e.g. `Alerts`, `Enrichment`, `Jira`). + +## What the check verifies + +Errors block the merge. They are what the platform refuses when it loads the template, or what makes every run fail: + +- the file is valid JSON with a `uuid` (unique in the repository), a `name` and `nodes`; +- no node carries a module or trigger configuration; +- node ids are plain numbers, and every output leads to a node that exists; +- every action and trigger exists in automation-library (or is built into the platform, see [`tools/builtin_catalogue.json`](tools/builtin_catalogue.json)), with its own module; +- the arguments of each action match its definition, required arguments included (a Jinja value such as `{{ node.1.uuid }}` is accepted for any type); +- operators are well formed, Jinja is valid, and every `node.N` a field reads exists. + +Warnings do not block: empty description, unreachable node, a branch that matches no case or no output of its action, a field read from a node that its action does not declare in its result (`node.1.first_seen` instead of `first_seen_at`), tag spelling. In a pull request, an error in a file the pull request does not touch is shown as a warning. + +The check is a pre-flight. The platform runs its own validation when it loads the templates. + +## Review + +Pull requests on `playbooks/` are reviewed by the Sekoia playbook team. Reviewers look at what the check cannot see: does the playbook do what its description says, for a real use case? + +## Change or remove a template + +Open a pull request on the file. Keep its `uuid`: the platform updates the published template in place. A file that no longer passes the platform validation is removed from the editor at the next deployment, which is why the check runs on every change. diff --git a/playbooks/templates/playbooks.json b/playbooks/templates/playbooks.json deleted file mode 100644 index 269005f..0000000 --- a/playbooks/templates/playbooks.json +++ /dev/null @@ -1,486 +0,0 @@ -[ - { - "file": "add_destination_ips_to_ioc_collection.json", - "name": "Add Destination IP address to IOC Collection", - "tags": [ - "Alerts", - "IOC Collection", - "Blocklist" - ], - "workspace": "Operation Center", - "description": "Add the destination ip addresses from the events linked to the alert to an IOC collection" - }, - { - "file": "add_source_ips_to_ioc_collection.json", - "name": "Add Source IP address to IOC Collection", - "tags": [ - "Alerts", - "IOC Collection", - "Blocklist" - ], - "workspace": "Operation Center", - "description": "Add the source ip addresses from the events linked to the alert to an IOC collection" - }, - { - "file": "add_domains_to_ioc_collection.json", - "name": "Add Domain to blocklist", - "tags": [ - "Alerts", - "IOC Collection", - "Blocklist" - ], - "workspace": "Operation Center", - "description": "Add the domains from the events linked to the alert to an IOC collection" - }, - { - "file": "create_jira_ticket_on_alert.json", - "name": "Jira ticket on alert", - "tags": [ - "Alerts", - "Notifications", - "Jira" - ], - "description": "Create Jira ticket when new alerts are created.", - "workspace": [ - "Operation Center" - ] - }, - { - "file": "msteams_notification.json", - "name": "MS Teams notification on alert", - "tags": [ - "Alerts", - "Notifications", - "MS Teams" - ], - "description": "Notify by Microsoft Teams when new alerts are created.", - "workspace": [ - "Operation Center" - ] - }, - { - "file": "URL_scan_VirusTotal_Enrichement.json", - "name": "[Training usecase] Scan for url on VirusTotal", - "description": "Enrich to check if this url.domain is known from VirusTotal, directly from Sekoia.io", - "tags": [ - "Alerts", - "Enrichment" - ], - "workspace": [ - "Operation Center" - ] - }, - { - "file": "HTTP_request_Remediation.json", - "name": "[Training usecase] Post an HTTP request based on alert information", - "description": "Send HTTP request to an external service based on alert data", - "tags": [ - "Alerts", - "Webhook" - ], - "workspace": [ - "Operation Center" - ] - }, - { - "file": "email_notification_on_alert_webhook.json", - "name": "Mail Webhook notification on alert", - "description": "Send an email about an alert when receiving a webhook event", - "tags": [ - "Alerts", - "Notifications", - "Webhook" - ], - "workspace": [ - "Operation Center" - ] - }, - { - "file": "mattermost_notification_on_alert.json", - "name": "Mattermost notification on alert", - "description": "Notify by mattermost when new alerts are created", - "tags": [ - "Alerts", - "Notifications" - ], - "workspace": [ - "Operation Center" - ] - }, - { - "file": "alert_webhook_internet_scan.json", - "name": "Qualify Internet Scan webhook", - "description": "Qualify an Internet scan alert on webhook", - "tags": [ - "Alerts", - "Webhook" - ], - "workspace": [ - "Operation Center" - ] - }, - { - "file": "playbook_adware.json", - "name": "Playbook adware", - "description": "Automatic validation of alerts with predefined adware domains", - "tags": [ - "Alerts" - ], - "workspace": [ - "Operation Center" - ] - }, - { - "file": "urgency_to_0_on_rejected.json", - "name": "Alert urgency to 0 when rejected", - "description": "Put the urgency of an alert to 0 when it is rejected", - "tags": [ - "Alerts" - ], - "workspace": [ - "Operation Center" - ] - }, - { - "file": "VirusTotal_Enrichement.json", - "name": "Enhance network alerts with VirusTotal", - "description": "Enhance network alerts with VirusTotal informations (Only for IP-v4, domain-name, and url)", - "tags": [ - "Alerts", - "Enrichment" - ], - "workspace": [ - "Operation Center" - ] - }, - { - "file": "Enrich_alerts_with_VirusTotal_Hash.json", - "name": "Scan for hash on VirusTotal", - "workspace": [ - "Operation Center" - ], - "description": "Enrich to check if this file.hash.sha1 is known from VirusTotal, directly from SEKOIA.IO.", - "tags": [ - "Alerts", - "Enrichment" - ] - }, - { - "file": "Reject_old_alerts.json", - "name": "Reject old alerts (1 year)", - "description": "Reject old alerts not updated for 1 year.", - "tags": [ - "Alerts", - "Cron" - ], - "workspace": [ - "Operation Center" - ] - }, - { - "file": "Enrich_with_IKnow_What_You_Download.json", - "name": "Enrich with IKnowWhatYouDownload", - "description": "Enrich with IKnowWhatYouDownload to check if the IP is known from this service, directly from SEKOIA.IO.", - "tags": [ - "Alerts", - "Webhook", - "Enrichment" - ], - "workspace": [ - "Operation Center" - ] - }, - { - "file": "Enrich_alerts_with_hostnames.json", - "name": "Enrich alerts with hostnames", - "description": "[Training usecase] Enrich alerts with hostnames coming from initial events.", - "tags": [ - "Alerts", - "Enrichment" - ], - "workspace": [ - "Operation Center" - ] - }, - { - "file": "Shodan_search_to_observables.json", - "name": "Shodan search to observables", - "workspace": [ - "Intelligence Center" - ], - "description": "Get IP addresses from a shodan search and add it to Observable data base with a tag", - "tags": [ - "Observables", - "Shodan", - "TIP" - ] - }, - { - "file": "OSINT_to_observables.json", - "name": "Generic Fetch OSINT to observable", - "workspace": [ - "Intelligence Center" - ], - "description": "Retrieve observables from an OSINT to add it to observable database with a tag (eg: https://github.com/MISP/misp-warninglists/tree/main/lists)", - "tags": [ - "Observables", - "OSINT", - "TIP" - ] - }, - { - "file": "create_alert_on_the_hive_automatic.json", - "name": "Automatically create an alert on TheHive", - "workspace": [ - "Operation Center" - ], - "description": "Automatically create an alert on TheHive when a new alert is raised in SEKOIA.IO.", - "tags": [ - "Alerts", - "TheHive" - ] - }, - { - "file": "create_alert_on_the_hive_manual.json", - "name": "Manually create an Alert on TheHive", - "workspace": [ - "Operation Center" - ], - "description": "Create an alert on TheHive via the alert page.", - "tags": [ - "Alerts", - "TheHive" - ] - }, - { - "file": "DigitalShadows_SearchLight_fetch_alerts.json", - "name": "Fetch alerts from Digital Shadows SearchLight", - "workspace": [ - "Operation Center" - ], - "description": "Synchronise alerts from Digital Shadows SearchLight to SEKOIA.IO events", - "tags": [ - "Alerts" - ] - }, - { - "file": "forward_panda_security_events.json", - "name": "Forward Panda Security Events to SEKOIA.IO", - "workspace": [ - "Operation Center" - ], - "description": "This playbook pulls security events from the Panda Security Aether platform then push them to SEKOIA.IO", - "tags": [ - "Events" - ] - }, - { - "file": "imperva_waf_fetch_logs.json", - "name": "Imperva WAF fetch logs", - "workspace": [ - "Operation Center" - ], - "description": "Fetch events from Imperva Web Application Firewall and forward them to SEKOIA.IO intake", - "tags": [ - "Events" - ] - }, - { - "file": "forward_vadesecure_records.json", - "name": "Forward Vade M365 email Events to SEKOIA.IO", - "workspace": [ - "Operation Center" - ], - "description": "This playbook collect logs from 'Vade for M365' then push them to SEKOIA.IO", - "tags": [ - "Events" - ] - }, - { - "file": "Tranco_top_domains_to_observables.json", - "name": "Tranco top domains to observables", - "workspace": [ - "Intelligence Center" - ], - "tags": [ - "Observables", - "Tranco", - "TIP" - ], - "description": "Automatically import Tranco's top 1 000 000 domain names to observable database" - }, - { - "file": "forward_google_pubsub_events.json", - "name": "Forward Google Pubsub records to SEKOIA.IO", - "workspace": [ - "Operation Center" - ], - "description": "This playbook consumes records from Google Pubsub and push them to SEKOIA.IO", - "tags": [ - "Google", - "Events" - ] - }, - { - "file": "Enrich_alerts_with_AbuseIPDB.json", - "name": "Enrich alerts with AbuseIPDB", - "workspace": [ - "Operation Center" - ], - "description": "Enrich with AbuseIPDB to check if the IP is known from this service, directly from SEKOIA.IO.", - "tags": [ - "Alerts", - "Enrichment" - ] - }, - { - "file": "Alerts_Shodan_Enrichment.json", - "name": "Enrich with Shodan", - "workspace": [ - "Operation Center" - ], - "description": "Enrich with Shodan to check if the IP is known from this service, directly from SEKOIA.IO.", - "tags": [ - "Alerts", - "Enrichment" - ] - }, - { - "file": "slack_notification_on_alert.json", - "name": "Slack notification on alert", - "description": "Notify by Slack when new alerts are created. If the target is defined, it is used in the notification, otherwise the hostnames from events are used.", - "tags": [ - "Alerts", - "Notifications" - ], - "workspace": [ - "Operation Center" - ] - }, - { - "file": "get_data_and_enrich_with_cloudflare.json", - "name": "Get data from OSINT and enrich DNS names with cloudflare DNS over HTTPs API", - "description": "Playbook to get data from OSINT and enrich it with CloudFlare DNS over HTTPs API. The playbook then upload observables to database.\n\nPlease configure 'Fetch Osint' node and 'Get domains from Fetch OSINT' jpath to get domains.", - "tags": [ - "Observables", - "Cloudflare", - "OSINT", - "Enrichment", - "TIP" - ], - "workspace": [ - "Intelligence Center" - ] - }, - { - "file": "CrowdSec_alert_enrichment.json", - "name": "Enrich with CrowdSec Smoke database", - "description": "Enrich with CrowdSec Smoke DB to check if the IP is known from this service direclty from SEKOIA.IO.", - "tags": [ - "CrowdSec", - "Alerts", - "Enrichment" - ], - "workspace": [ - "Operation Center" - ] - }, - { - "file": "Crowdstrike_dissemination.json", - "name": "Disseminate IOCs to CrowdStrike Falcon", - "description": "Disseminate Sekoia.io IOCs as a detection source for CrowdStrike Falcon EDR", - "tags": [ - "CrowdStrike", - "Dissemination" - ], - "workspace": [ - "Operation Center", - "Intelligence Center" - ] - }, - { - "file": "create_incident_on_cortex_xsoar.json", - "name": "Automatically create an incident on Palo Alto Cortex XSOAR", - "description": "Create an incident on Palo Alto Cortex XSOAR when a new alert is raised on Sekoia.io", - "tags": [ - "Alerts", - "XSOAR" - ], - "workspace": [ - "Operation Center" - ] - }, - { - "file": "send_alert_to_nybble_hub.json", - "name": "Automatically send an alert to Nybble Hub", - "workspace": [ - "Operation Center" - ], - "description": "Automatically send an alert to Nybble Hub when a new alert is raised in SEKOIA.IO.", - "tags": [ - "Alerts", - "Nybble" - ] - }, - { - "file": "get_additional_harfang_telemetry.json", - "name": "HarfangLab telemetry events", - "workspace": [ - "Operation Center" - ], - "description": "Retrieve additional telemetry when an HarfangLab alert is raised", - "tags": [ - "Alerts", - "Enrichment", - "Events" - ] - }, - { - "file": "push_iocs_to_xsiam.json", - "name": "Push Sekoia.io IOCs to Palo Alto XSIAM Collection", - "workspace": [ - "Intelligence Center" - ], - "tags": [ - "Observables", - "XSIAM", - "Dissemination" - ], - "description": "Add Sekoia active IOCs in Palo Alto XSIAM Collection for detection" - }, - { - "file": "cascade_alert_status_on_harfang.json", - "name": "Cascade an alert based on HarfangLab events to Harfang console", - "workspace": ["Operation Center"], - "description": "Cascade an alert based on HarfangLab events to Harfang console based on ThreatId", - "tags": ["Alerts", "HarfangLab", "Events"] - }, - { - "file": "auto_action_on_roy_analysis.json", - "name": "Auto action based on Roy analysis", - "workspace": ["Operation Center"], - "description": "Automate actions based on Roy auto-investigation verdict and confidence level: auto-close high-confidence false positives, flag the others for manual review. To be adapted (custom status & global logic). In multi-tenant environment, child communities needs AI terms to be accepted for the playbook to work.)", - "tags": ["Alerts", "Roy", "Automation"] - }, - { - "file": "roy_auto_analysis_night_shift.json", - "name": "Roy auto-analysis during night-shift", - "workspace": ["Operation Center"], - "description": "Automatically assign new alerts to Roy when they are created during the night-shift. Covered hours are evaluated in UTC on the alert creation date: from 18:00 to 05:59 UTC (i.e. 20:00-07:59 Paris time in summer / UTC+2, 19:00-06:59 in winter / UTC+1). Adjust the hours in the condition regex to match your timezone and shift. To also cover weekends (Saturday and Sunday, 00:00-23:59 UTC), replace the condition left value with: {{ (node.0['created_at'] | timestamp_to_iso8601 | regex_match('.*T(18|19|20|21|22|23|0[0-5]):.*')) or (((node.0['created_at'] | int) // 86400 + 3) % 7 >= 5) }}", - "tags": ["Alerts", "Roy", "Automation"] - }, - { - "file": "disable_user_accounts_in_microsoft_entra_id.json", - "name": "Disable user accounts in Microsoft Entra ID", - "description": "Manually disable Microsoft Entra ID accounts associated with an alert. Comment after each successful disablement, or when no eligible account was found. Requires Sekoia Reveal, a configured Microsoft Entra ID asset connector, and a Microsoft Entra ID action account with permissions to disable users.", - "tags": [ - "alerts", - "assets", - "microsoft entra id", - "remediation" - ], - "workspace": [ - "Operation Center" - ] - } -] diff --git a/playbooks/tools/.gitignore b/playbooks/tools/.gitignore new file mode 100644 index 0000000..c18dd8d --- /dev/null +++ b/playbooks/tools/.gitignore @@ -0,0 +1 @@ +__pycache__/ diff --git a/playbooks/tools/builtin_catalogue.json b/playbooks/tools/builtin_catalogue.json new file mode 100644 index 0000000..5843605 --- /dev/null +++ b/playbooks/tools/builtin_catalogue.json @@ -0,0 +1,37 @@ +{ + "_comment": "Modules, triggers and actions built into the Sekoia playbook engine. They are not in SEKOIA-IO/automation-library, so the template check cannot find them there. Update this file when the platform adds a built-in.", + "modules": [ + { + "uuid": "1ad1b7ce-e335-4532-83ce-1d43c864720c", + "name": "Built-in triggers", + "triggers": [ + { "uuid": "5039c9fe-b2d8-40b3-a11b-d2a810ddbf91", "name": "Cron" }, + { "uuid": "f7e1c3d0-4b8a-4f5e-9c6b-2e1f3a5b6c7d", "name": "Webhook" } + ], + "actions": [] + }, + { + "uuid": "5fdf8838-1529-4243-8fbc-e6bfa7b52e30", + "name": "STIX", + "triggers": [], + "actions": [ + { "uuid": "d608959a-d644-4112-a484-d9302bfbf817", "name": "Add Source" }, + { "uuid": "270f4582-575c-4b8d-a884-73a3ccd6a97c", "name": "Add Tags" }, + { "uuid": "61dc06df-656a-4894-9dfd-c3da9d75a1c0", "name": "Create Relationships" }, + { "uuid": "b1ea7fe2-bf66-4b43-a45d-1326543a8734", "name": "Cryptolaemus To STIX" }, + { "uuid": "5bbc06fd-8a8f-4863-b770-29f58c11b8dd", "name": "CVE to STIX" }, + { "uuid": "0dc508da-ae83-47a3-8e41-14ab19e16a10", "name": "Filter bundle" }, + { "uuid": "7b0ff5ef-70c2-4457-80ca-482283de8baf", "name": "Json objects to Observables" }, + { "uuid": "9d95a711-ec89-47bb-a1f5-af80d4bc245d", "name": "VirusTotal LiveHunt to Observables" }, + { "uuid": "542a0462-4d9c-42be-a07e-7e8cae862da3", "name": "MISP to STIX" }, + { "uuid": "1f051d4a-fb3b-4310-af41-897dff1235e3", "name": "Observables to Contextualized Indicators" }, + { "uuid": "78be91eb-5e01-4195-a21e-e3c67887de29", "name": "Observables to Indicators" }, + { "uuid": "57e21032-669c-4cdc-ade6-5a55eba657bb", "name": "Remove Orphan Objects" }, + { "uuid": "4fefc65c-cd02-483f-bdad-91daf1203772", "name": "Split bundle" }, + { "uuid": "b21983b4-b6ca-453c-9ab1-6671e67ea4f8", "name": "STIX to MISP" }, + { "uuid": "3b7ae40a-2fb8-451f-9ede-7f7a906c7132", "name": "Strings to Observables" }, + { "uuid": "00bbb94c-f521-4d66-84b3-5c60914d213a", "name": "fetch_taxii2_collection" } + ] + } + ] +} diff --git a/playbooks/tools/check_templates.py b/playbooks/tools/check_templates.py new file mode 100644 index 0000000..43d378e --- /dev/null +++ b/playbooks/tools/check_templates.py @@ -0,0 +1,562 @@ +#!/usr/bin/env python3 +"""Check the playbook templates of this repository before they reach the Sekoia platform. + +Every template merged on `main` is loaded into every Sekoia region at the next deployment of the +playbook service. The platform skips a template it refuses, and removes it if it was already +published. This script runs the same checks earlier, on the pull request. + +Errors fail the check. They are what the platform refuses, or what makes every run of the +template fail. Warnings point at things to fix without blocking the merge. + +Usage: + python playbooks/tools/check_templates.py --automation-library [--changed FILE ...] + + --automation-library A checkout of SEKOIA-IO/automation-library (branch `production`). + Only the JSON manifests are read. + --changed The template files a pull request touches. Errors in other files are + reported as warnings, so a contributor is never blocked by someone else's bug. + --base The git ref a pull request targets (e.g. origin/main): --changed is read from git. + +Requires Python 3.11+, `jsonschema` and `jinja2`. +""" + +from __future__ import annotations + +import argparse +import difflib +import functools +import json +import os +import re +import subprocess +import sys +import uuid as uuidlib +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +from jinja2 import Environment, TemplateSyntaxError +from jinja2.lexer import TOKEN_BLOCK_BEGIN, TOKEN_BLOCK_END, TOKEN_VARIABLE_BEGIN, TOKEN_VARIABLE_END +from jsonschema.exceptions import ValidationError +from jsonschema.validators import Draft202012Validator, extend + +ROOT = Path(__file__).resolve().parents[2] +TEMPLATES_DIR = ROOT / "playbooks" / "templates" +BUILTIN_FILE = Path(__file__).resolve().parent / "builtin_catalogue.json" +# Files of this folder that are not templates (the platform skips them too) +NOT_TEMPLATES = {"playbooks.json", "template.json"} + +# The accounts of a community, removed by the platform when it turns a playbook into a template +CONFIGURATION_KEYS = ( + "module_configuration_uuid", + "module_configuration_uuids", + "trigger_configuration_uuid", + "trigger_configuration_uuids", +) +OPERATOR_SUBTYPES = {"condition", "store", "foreach", "all", "any", "subplaybook", "return", "ask"} +COMPARISONS = {"==", "!=", "<", "<=", ">", ">=", "in", "not in", "range"} +STORE_TYPES = {"set", "append", "unset", "remove"} +# Fields of a node the engine renders with Jinja +RENDERED_FIELDS = ("arguments", "cases", "modifications", "items", "title", "message", "result_template") + +JINJA = Environment() +# The first field read from a node's result: node.1.short_id, node.1['short_id'], node[1].short_id +NODE_FIELD = re.compile( + r"\bnode\s*(?:\.\s*(\d+)|\[\s*['\"]?(\d+)['\"]?\s*\])\s*(?:\.\s*([A-Za-z_]\w*)|\[\s*['\"]([^'\"]+)['\"]\s*\])" +) +DICT_METHODS = {"get", "keys", "items", "values"} +NODE_REF = re.compile(r"\bnode\s*(?:\.\s*(\d+)\b|\[\s*(\d+)\s*\]|\[\s*['\"](\d+)['\"]\s*\])") + + +# --------------------------------------------------------------------------- findings + + +@dataclass +class Report: + errors: dict[str, list[str]] = field(default_factory=dict) + warnings: dict[str, list[str]] = field(default_factory=dict) + + def error(self, file: str, message: str) -> None: + if message not in self.errors.setdefault(file, []): + self.errors[file].append(message) + + def warning(self, file: str, message: str) -> None: + if message not in self.warnings.setdefault(file, []): + self.warnings[file].append(message) + + +# --------------------------------------------------------------------------- catalogue + + +@dataclass +class Item: + uuid: str + name: str + module_uuid: str + module_name: str + arguments: dict | None = None + outputs: set[str] | None = None + #: The top-level fields of the result, when the manifest declares them + results: set[str] | None = None + + +@dataclass +class Catalogue: + actions: dict[str, Item] = field(default_factory=dict) + triggers: dict[str, Item] = field(default_factory=dict) + + +def load_catalogue(library: Path) -> Catalogue: + catalogue = Catalogue() + for manifest_path in sorted(library.glob("*/manifest.json")): + try: + module = json.loads(manifest_path.read_text(encoding="utf-8")) + except (OSError, ValueError): + continue + module_uuid, module_name = module.get("uuid"), module.get("name", manifest_path.parent.name) + for kind, target in (("action", catalogue.actions), ("trigger", catalogue.triggers)): + for path in sorted(manifest_path.parent.glob(f"{kind}_*.json")): + try: + item = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + continue + if not item.get("uuid"): + continue + outputs = item.get("outputs") + target[item["uuid"]] = Item( + uuid=item["uuid"], + name=item.get("name", path.stem), + module_uuid=module_uuid, + module_name=module_name, + arguments=item.get("arguments") if kind == "action" else None, + outputs=set(outputs) if isinstance(outputs, dict) else None, + results=_result_fields(item), + ) + builtin = json.loads(BUILTIN_FILE.read_text(encoding="utf-8")) + for module in builtin["modules"]: + for kind, target in (("actions", catalogue.actions), ("triggers", catalogue.triggers)): + for item in module[kind]: + target.setdefault(item["uuid"], Item(item["uuid"], item["name"], module["uuid"], module["name"])) + return catalogue + + +def _result_fields(item: dict) -> set[str] | None: + results = item.get("results") + if not isinstance(results, dict) or not isinstance(results.get("properties"), dict): + return None + if results.get("additionalProperties") is True: + return None + return set(results["properties"]) or None + + +# --------------------------------------------------------------------------- Jinja-aware JSON schema +# Same rule as the platform: a value that is a Jinja template is accepted for any type or constraint, +# because it is only known once rendered by the run. + + +def is_template(value: Any) -> bool: + if not isinstance(value, str): + return False + try: + tokens = {token_type for _, token_type, _ in JINJA.lex(value)} + except TemplateSyntaxError: + return False + return {TOKEN_BLOCK_BEGIN, TOKEN_BLOCK_END} <= tokens or {TOKEN_VARIABLE_BEGIN, TOKEN_VARIABLE_END} <= tokens + + +@functools.cache +def _template_aware_validator() -> type: + base = Draft202012Validator + checker = base.TYPE_CHECKER.redefine_many( + { + name: (lambda check: lambda c, instance: check(c, instance) or is_template(instance))(check) + for name, check in base.TYPE_CHECKER._type_checkers.items() + } + ) + validators = { + key: ( + lambda v: lambda validator, value, instance, schema: ( + iter(()) if is_template(instance) else v(validator, value, instance, schema) + ) + )(v) + for key, v in base.VALIDATORS.items() + } + return extend(base, validators=validators, type_checker=checker) + + +def first_argument_error(schema: dict, arguments: dict) -> ValidationError | None: + cls = _template_aware_validator() + try: + cls(schema, format_checker=cls.FORMAT_CHECKER).validate(arguments) + except ValidationError as error: + return error + return None + + +# --------------------------------------------------------------------------- checks + + +def strings(value: Any): + if isinstance(value, str): + yield value + elif isinstance(value, dict): + for item in value.values(): + yield from strings(item) + elif isinstance(value, list): + for item in value: + yield from strings(item) + + +def targets(channel: Any) -> list[str]: + return [str(t) for t in channel] if isinstance(channel, list) else [] + + +def reachable(nodes: dict[str, dict]) -> set[str]: + seen: set[str] = set() + stack = [nid for nid, node in nodes.items() if node.get("type") == "trigger"] + while stack: + nid = stack.pop() + if nid in seen or nid not in nodes: + continue + seen.add(nid) + node = nodes[nid] + outputs = node.get("outputs") if isinstance(node.get("outputs"), dict) else {} + for channel in outputs.values(): + stack.extend(targets(channel)) + stack.extend(targets(node.get("loop"))) + return seen + + +def check_header(file: str, template: Any, report: Report) -> bool: + """The fields the platform reads when it loads a template.""" + if not isinstance(template, dict): + report.error(file, "The file must hold a JSON object.") + return False + value = template.get("uuid") + if not isinstance(value, str): + report.error(file, '"uuid" is missing. Add a new random UUID (python -c "import uuid; print(uuid.uuid4())").') + else: + try: + uuidlib.UUID(value) + except ValueError: + report.error(file, f'"uuid" is not a valid UUID: {value!r}.') + if not isinstance(template.get("name"), str) or not template.get("name", "").strip(): + report.error(file, '"name" is missing or empty.') + if "description" in template and not isinstance(template["description"], str): + report.error(file, '"description" must be a string (null is refused).') + elif not template.get("description"): + report.warning(file, '"description" is empty: say what the playbook does and what it needs.') + tags = template.get("tags") + if "tags" in template and not (isinstance(tags, list) and all(isinstance(t, str) for t in tags)): + report.error(file, '"tags" must be a list of strings.') + if not isinstance(template.get("nodes"), dict) or not template["nodes"]: + report.error(file, '"nodes" must be a non-empty object.') + return False + return True + + +def check_nodes(file: str, nodes: dict, catalogue: Catalogue, report: Report) -> None: + node_ids = set(nodes) + reached = reachable(nodes) + # What each action or trigger node returns, when its manifest says so + returns: dict[str, Item] = {} + for nid, node in nodes.items(): + if not isinstance(node, dict): + continue + item = ( + catalogue.actions.get(node.get("action_uuid")) + if node.get("type") == "action" + else catalogue.triggers.get(node.get("trigger_uuid")) + if node.get("type") == "trigger" + else None + ) + if item is not None and item.results: + returns[str(nid)] = item + + if not any(isinstance(n, dict) and n.get("type") == "trigger" for n in nodes.values()): + report.error(file, "The playbook has no trigger.") + + for nid, node in nodes.items(): + where = f"node {nid}" + if not isinstance(node, dict): + report.error(file, f"{where}: must be an object.") + continue + where = f"node {nid} '{node.get('name', '')}'" + + if str(nid) != str(_as_int(nid)): + report.error(file, f"{where}: node ids must be plain numbers ('{nid}' is not).") + + for key in CONFIGURATION_KEYS: + if node.get(key): + report.error(file, f"{where}: remove {key}. It points to an account in your community, not in the reader's.") + elif key in node: + report.warning(file, f"{where}: remove the empty {key} field.") + + outputs = node.get("outputs") + if outputs is not None and not isinstance(outputs, dict): + report.error(file, f"{where}: \"outputs\" must be an object.") + outputs = {} + for channel, channel_targets in (outputs or {}).items(): + missing = sorted(set(targets(channel_targets)) - node_ids) + if missing: + report.error(file, f"{where}: the '{channel}' output leads to nodes that do not exist: {', '.join(missing)}.") + missing_loop = sorted(set(targets(node.get("loop"))) - node_ids) + if missing_loop: + report.error(file, f"{where}: the loop leads to nodes that do not exist: {', '.join(missing_loop)}.") + + if nid not in reached and node.get("type") != "trigger": + report.warning(file, f"{where}: no trigger reaches this node, so it never runs.") + + kind = node.get("type") + if kind == "action": + check_action(file, where, node, catalogue, report) + elif kind == "trigger": + check_trigger(file, where, node, catalogue, report) + elif kind == "operator": + check_operator(file, where, node, report) + else: + report.error(file, f"{where}: unknown node type {kind!r}.") + + for name in RENDERED_FIELDS: + for text in strings(node.get(name)): + check_jinja(file, where, text, node_ids, report) + check_result_fields(file, where, text, returns, report) + + +def _as_int(value: str) -> int | None: + try: + return int(value) + except (TypeError, ValueError): + return None + + +def check_action(file: str, where: str, node: dict, catalogue: Catalogue, report: Report) -> None: + action = catalogue.actions.get(node.get("action_uuid")) + if action is None: + report.error( + file, + f"{where}: action {node.get('action_uuid')} does not exist in automation-library (branch production). " + "Use an action that is published, or wait for its integration to be released.", + ) + return + if node.get("module_uuid") != action.module_uuid: + report.error( + file, + f"{where}: module_uuid {node.get('module_uuid')} is not the module of action '{action.name}' " + f"({action.module_name}, {action.module_uuid}).", + ) + if action.arguments: + arguments = node.get("arguments", {}) + error = first_argument_error(action.arguments, arguments if isinstance(arguments, dict) else {}) + if error is not None: + path = ".".join(str(p) for p in error.absolute_path) + subject = f"argument '{path}' does not" if path else "the arguments do not" + report.error(file, f"{where}: {subject} match action '{action.name}': {error.message}") + if action.outputs is not None: + declared = action.outputs | {"default", "error"} + for channel, channel_targets in (node.get("outputs") or {}).items(): + if targets(channel_targets) and channel not in declared: + report.warning( + file, + f"{where}: action '{action.name}' has no '{channel}' output " + f"(declared: {', '.join(sorted(action.outputs))}), so this branch never runs.", + ) + + +def check_trigger(file: str, where: str, node: dict, catalogue: Catalogue, report: Report) -> None: + trigger = catalogue.triggers.get(node.get("trigger_uuid")) + if trigger is None: + report.error(file, f"{where}: trigger {node.get('trigger_uuid')} does not exist in automation-library (branch production).") + elif node.get("module_uuid") != trigger.module_uuid: + report.error( + file, + f"{where}: module_uuid {node.get('module_uuid')} is not the module of trigger '{trigger.name}' " + f"({trigger.module_name}, {trigger.module_uuid}).", + ) + + +def check_operator(file: str, where: str, node: dict, report: Report) -> None: + subtype = node.get("subtype") + if subtype not in OPERATOR_SUBTYPES: + report.error(file, f"{where}: unknown operator subtype {subtype!r}.") + return + if subtype == "condition": + cases = node.get("cases") + if not isinstance(cases, list): + report.error(file, f"{where}: a condition needs a list of cases.") + return + names = set() + for i, case in enumerate(cases): + if not isinstance(case, dict) or not isinstance(case.get("name"), str): + report.error(file, f"{where}: case {i} needs a name.") + continue + names.add(case["name"]) + if case.get("comparison") not in COMPARISONS: + report.error(file, f"{where}: case '{case['name']}' has an unknown comparison {case.get('comparison')!r}.") + for side in ("left", "right"): + if side not in case: + report.error(file, f"{where}: case '{case['name']}' has no '{side}'.") + for channel, channel_targets in (node.get("outputs") or {}).items(): + if targets(channel_targets) and channel not in names | {"else", "error"}: + report.warning(file, f"{where}: output '{channel}' matches no case, so this branch never runs.") + elif subtype == "store": + for i, mod in enumerate(node.get("modifications") or []): + if not isinstance(mod, dict) or not isinstance(mod.get("key"), str) or mod.get("type") not in STORE_TYPES: + report.error(file, f"{where}: modification {i} needs a key and a type in {sorted(STORE_TYPES)}.") + elif subtype == "foreach": + if not isinstance(node.get("loop"), list): + report.error(file, f"{where}: a foreach needs a 'loop' list.") + elif subtype == "ask": + if not node.get("title"): + report.error(file, f"{where}: an ask operator needs a title.") + if not (isinstance(node.get("choices"), list) and len(node["choices"]) == 2): + report.error(file, f"{where}: an ask operator needs exactly two choices.") + + +def check_result_fields(file: str, where: str, text: str, returns: dict[str, "Item"], report: Report) -> None: + """Warn when a field read from a node is not among the fields its action or trigger declares. + + Only a warning: some manifests do not declare every field the integration returns.""" + if "{{" not in text and "{%" not in text: + return + unknown: dict[str, list[str]] = {} + for match in NODE_FIELD.finditer(text): + ref = match.group(1) or match.group(2) + name = match.group(3) or match.group(4) + item = returns.get(ref) + if item is None or name in DICT_METHODS or name in item.results: + continue + if name not in unknown.setdefault(ref, []): + unknown[ref].append(name) + for ref, names in unknown.items(): + item = returns[ref] + hints = [] + for name in names: + close = difflib.get_close_matches(name, sorted(item.results), n=1, cutoff=0.75) + hints.append(f"'{name}' (did you mean '{close[0]}'?)" if close else f"'{name}'") + report.warning( + file, + f"{where}: reads {', '.join(hints)} from node {ref}, which '{item.name}' does not declare in its result. " + "Check the name: an unknown field is empty at run time. Ignore this if the integration returns it anyway.", + ) + + +def check_jinja(file: str, where: str, text: str, node_ids: set[str], report: Report) -> None: + if "{{" not in text and "{%" not in text: + return + try: + JINJA.parse(text) + except TemplateSyntaxError as error: + report.error(file, f"{where}: Jinja syntax error ({error.message}) in: {text[:80]}") + return + for match in NODE_REF.finditer(text): + ref = next(g for g in match.groups() if g) + if match.group(3): + report.error(file, f"{where}: write node.{ref}, not {match.group(0)}. The engine reads node ids as numbers.") + if ref not in node_ids: + report.error(file, f"{where}: reads node {ref}, which does not exist. Every run will fail on this node.") + + +# --------------------------------------------------------------------------- repository-wide checks + + +def check_uniqueness(templates: dict[str, dict], report: Report) -> None: + by_uuid: dict[str, list[str]] = {} + for name, template in templates.items(): + if isinstance(template.get("uuid"), str): + by_uuid.setdefault(template["uuid"].lower(), []).append(name) + for value, names in by_uuid.items(): + if len(names) > 1: + for name in names: + report.error(name, f"uuid {value} is also used by {', '.join(n for n in names if n != name)}.") + + +def check_tags(templates: dict[str, dict], report: Report) -> None: + spellings: dict[str, set[str]] = {} + for template in templates.values(): + for tag in template.get("tags") or []: + if isinstance(tag, str): + spellings.setdefault(tag.lower(), set()).add(tag) + for name, template in templates.items(): + for tag in template.get("tags") or []: + if not isinstance(tag, str): + continue + if tag[:1] != tag[:1].upper(): + report.warning(name, f"tag '{tag}' should start with a capital letter (tags are case sensitive in the template picker).") + others = spellings.get(tag.lower(), set()) - {tag} + if others: + report.warning(name, f"tag '{tag}' is also spelt {', '.join(sorted(others))} in other templates.") + + +# --------------------------------------------------------------------------- main + + +def annotate(level: str, file: str, message: str) -> None: + if os.environ.get("GITHUB_ACTIONS") == "true": + path = f"playbooks/templates/{file}" + print(f"::{level} file={path},title=Playbook template::{message}") + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--automation-library", required=True, type=Path) + parser.add_argument("--changed", nargs="*", default=None, help="Template files touched by the pull request") + parser.add_argument("--base", help="Git ref the pull request targets (e.g. origin/main): sets --changed from git") + args = parser.parse_args() + if args.base: + diff = subprocess.run( + ["git", "diff", "--name-only", f"{args.base}...HEAD", "--", "playbooks/templates"], + cwd=ROOT, capture_output=True, text=True, check=True, + ) + args.changed = (args.changed or []) + diff.stdout.split("\n") + args.changed = [c for c in args.changed if c] + + catalogue = load_catalogue(args.automation_library) + if not catalogue.actions: + print(f"No action found under {args.automation_library}: is it a checkout of automation-library?") + return 2 + + report = Report() + files = sorted(p.name for p in TEMPLATES_DIR.glob("*.json") if p.name not in NOT_TEMPLATES) + templates: dict[str, dict] = {} + for name in files: + try: + template = json.loads((TEMPLATES_DIR / name).read_text(encoding="utf-8")) + except ValueError as error: + report.error(name, f"Invalid JSON: {error}") + continue + if check_header(name, template, report): + check_nodes(name, template["nodes"], catalogue, report) + if isinstance(template, dict): + templates[name] = template + check_uniqueness(templates, report) + check_tags(templates, report) + + changed = None if args.changed is None else {Path(c).name for c in args.changed} + blocking = {f: m for f, m in report.errors.items() if changed is None or f in changed} + inherited = {f: m for f, m in report.errors.items() if f not in blocking} + + for file in sorted(set(report.errors) | set(report.warnings)): + if changed is not None and file not in changed and file not in inherited: + continue + lines = [("error", m) for m in blocking.get(file, [])] + lines += [("warning", f"(already on main) {m}") for m in inherited.get(file, [])] + lines += [("warning", m) for m in report.warnings.get(file, [])] + if not lines: + continue + print(f"\n{file}") + for level, message in lines: + print(f" {'x' if level == 'error' else '!'} {message}") + annotate(level, file, message) + + errors = sum(len(m) for m in blocking.values()) + warnings = sum(len(m) for m in report.warnings.values()) + sum(len(m) for m in inherited.values()) + print( + f"\n{len(files)} templates checked against {len(catalogue.actions)} actions and " + f"{len(catalogue.triggers)} triggers: {errors} error(s), {warnings} warning(s)." + ) + return 1 if errors else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/playbooks/tools/export_template.py b/playbooks/tools/export_template.py new file mode 100644 index 0000000..b2b8de3 --- /dev/null +++ b/playbooks/tools/export_template.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Turn a playbook you built in Sekoia into a template file for this repository. + +1. Open the playbook in Sekoia. Its UUID is the last part of the address: .../playbooks/ +2. Run: + SEKOIA_API_KEY= python playbooks/tools/export_template.py .json + +The API key needs the "View playbooks" permission. Outside FRA1, pass the API URL of your +region with --base-url: + FRA1 https://api.sekoia.io FRA2 https://api.fra2.sekoia.io/api + MCO1 https://api.mco1.sekoia.io/api UAE1 https://api.uae1.sekoia.io/api + USA1 https://api.usa1.sekoia.io SGP1 https://api.sgp1.sekoia.io + +The script reads the playbook with GET /v1/symphony/playbooks/{uuid}, keeps its nodes, and removes +the accounts of your community (module and trigger configurations), as the platform does when it +turns a playbook into a template. The file gets a new random UUID. +Only the standard library is used. +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request +import uuid +from pathlib import Path + +TEMPLATES_DIR = Path(__file__).resolve().parents[1] / "templates" +# The attributes the platform removes when it turns a playbook into a template +CONFIGURATION_KEYS = ( + "module_configuration_uuid", + "module_configuration_uuids", + "trigger_configuration_uuid", + "trigger_configuration_uuids", +) + + +def fetch_playbook(base_url: str, playbook_uuid: str, api_key: str) -> dict: + request = urllib.request.Request( + f"{base_url.rstrip('/')}/v1/symphony/playbooks/{playbook_uuid}", + headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def to_template(playbook: dict) -> dict: + nodes = (playbook.get("content") or {}).get("nodes") or {} + for node in nodes.values(): + for key in CONFIGURATION_KEYS: + node.pop(key, None) + return { + "uuid": str(uuid.uuid4()), + "name": (playbook.get("name") or "").strip(), + "description": (playbook.get("description") or "").strip(), + "tags": [], + "nodes": nodes, + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("playbook_uuid", help="UUID of the playbook, from its address in Sekoia") + parser.add_argument("file_name", help="File to write under playbooks/templates/, e.g. enrich_alert_with_x.json") + parser.add_argument("--base-url", default="https://api.sekoia.io", help="API URL of your region (default: FRA1)") + args = parser.parse_args() + + api_key = os.environ.get("SEKOIA_API_KEY") + if not api_key: + print('Set SEKOIA_API_KEY to an API key with the "View playbooks" permission.') + return 2 + name = Path(args.file_name).name + if not name.endswith(".json") or name != name.lower() or " " in name: + print("Use a lower case file name with underscores, ending in .json (e.g. enrich_alert_with_x.json).") + return 2 + target = TEMPLATES_DIR / name + if target.exists(): + print(f"{target} already exists. Edit it, or choose another name.") + return 2 + + try: + playbook = fetch_playbook(args.base_url, args.playbook_uuid, api_key) + except urllib.error.HTTPError as error: + print(f"The API answered {error.code} for playbook {args.playbook_uuid}: {error.reason}") + return 1 + except urllib.error.URLError as error: + print(f"Cannot reach {args.base_url}: {error.reason}") + return 1 + + template = to_template(playbook) + if not template["nodes"]: + print("The playbook has no nodes: check the UUID.") + return 1 + target.write_text(json.dumps(template, indent=4, ensure_ascii=False) + "\n", encoding="utf-8") + print(f"Wrote {target.relative_to(TEMPLATES_DIR.parents[1])}.") + print("Next: write the description (what the playbook does and what it needs), add tags, then run") + print(" python playbooks/tools/check_templates.py --automation-library ") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From 0128d480a8273c57bfee96320792227f3a6dfba1 Mon Sep 17 00:00:00 2001 From: Pierre Penhouet Date: Tue, 1 Dec 2026 14:40:48 +0100 Subject: [PATCH 2/3] fix(playbooks): warn only on the template whose tag spelling differs The tag check warned on every template using the usual spelling as well. Co-Authored-By: Claude Opus 5.5 --- playbooks/tools/check_templates.py | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/playbooks/tools/check_templates.py b/playbooks/tools/check_templates.py index 43d378e..ca185ec 100644 --- a/playbooks/tools/check_templates.py +++ b/playbooks/tools/check_templates.py @@ -472,20 +472,23 @@ def check_uniqueness(templates: dict[str, dict], report: Report) -> None: def check_tags(templates: dict[str, dict], report: Report) -> None: - spellings: dict[str, set[str]] = {} + """Warn on a tag spelt differently from the spelling most templates use.""" + counts: dict[str, dict[str, int]] = {} for template in templates.values(): for tag in template.get("tags") or []: if isinstance(tag, str): - spellings.setdefault(tag.lower(), set()).add(tag) + spellings = counts.setdefault(tag.lower(), {}) + spellings[tag] = spellings.get(tag, 0) + 1 for name, template in templates.items(): for tag in template.get("tags") or []: if not isinstance(tag, str): continue - if tag[:1] != tag[:1].upper(): - report.warning(name, f"tag '{tag}' should start with a capital letter (tags are case sensitive in the template picker).") - others = spellings.get(tag.lower(), set()) - {tag} - if others: - report.warning(name, f"tag '{tag}' is also spelt {', '.join(sorted(others))} in other templates.") + spellings = counts[tag.lower()] + usual = max(spellings, key=lambda s: (spellings[s], s[:1].isupper())) + if tag != usual: + report.warning(name, f"tag '{tag}' is spelt '{usual}' in the other templates (tags are case sensitive).") + elif tag[:1] != tag[:1].upper(): + report.warning(name, f"tag '{tag}' should start with a capital letter (tags are case sensitive).") # --------------------------------------------------------------------------- main From 67159d1025d157fb97259ae1eaf7f85a1a6b6770 Mon Sep 17 00:00:00 2001 From: Pierre Penhouet Date: Tue, 1 Dec 2026 14:46:29 +0100 Subject: [PATCH 3/3] fix(playbooks): report in detail only the files a pull request touches Problems already on main in other files are summed up in one line and are no longer annotated, so a contributor only sees what is theirs to fix. Co-Authored-By: Claude Opus 5.5 --- playbooks/README.md | 2 +- playbooks/tools/check_templates.py | 35 +++++++++++++++++------------- 2 files changed, 21 insertions(+), 16 deletions(-) diff --git a/playbooks/README.md b/playbooks/README.md index 1dba34e..625b960 100644 --- a/playbooks/README.md +++ b/playbooks/README.md @@ -48,7 +48,7 @@ Errors block the merge. They are what the platform refuses when it loads the tem - the arguments of each action match its definition, required arguments included (a Jinja value such as `{{ node.1.uuid }}` is accepted for any type); - operators are well formed, Jinja is valid, and every `node.N` a field reads exists. -Warnings do not block: empty description, unreachable node, a branch that matches no case or no output of its action, a field read from a node that its action does not declare in its result (`node.1.first_seen` instead of `first_seen_at`), tag spelling. In a pull request, an error in a file the pull request does not touch is shown as a warning. +Warnings do not block: empty description, unreachable node, a branch that matches no case or no output of its action, a field read from a node that its action does not declare in its result (`node.1.first_seen` instead of `first_seen_at`), tag spelling. In a pull request, only the files it touches are reported in detail: a problem already on `main` in another file is summed up in one line and does not block it. The check is a pre-flight. The platform runs its own validation when it loads the templates. diff --git a/playbooks/tools/check_templates.py b/playbooks/tools/check_templates.py index ca185ec..f55583f 100644 --- a/playbooks/tools/check_templates.py +++ b/playbooks/tools/check_templates.py @@ -13,8 +13,8 @@ --automation-library A checkout of SEKOIA-IO/automation-library (branch `production`). Only the JSON manifests are read. - --changed The template files a pull request touches. Errors in other files are - reported as warnings, so a contributor is never blocked by someone else's bug. + --changed The template files a pull request touches. Only they are reported in detail; + errors in other files are summed up and never block the pull request. --base The git ref a pull request targets (e.g. origin/main): --changed is read from git. Requires Python 3.11+, `jsonschema` and `jinja2`. @@ -536,28 +536,33 @@ def main() -> int: check_tags(templates, report) changed = None if args.changed is None else {Path(c).name for c in args.changed} - blocking = {f: m for f, m in report.errors.items() if changed is None or f in changed} - inherited = {f: m for f, m in report.errors.items() if f not in blocking} - - for file in sorted(set(report.errors) | set(report.warnings)): - if changed is not None and file not in changed and file not in inherited: - continue - lines = [("error", m) for m in blocking.get(file, [])] - lines += [("warning", f"(already on main) {m}") for m in inherited.get(file, [])] + # On a pull request, only its own files are reported in detail and annotated: the problems + # already on main are summed up in one line, so a contributor sees what is theirs to fix + shown = sorted( + f for f in set(report.errors) | set(report.warnings) if changed is None or f in changed + ) + for file in shown: + lines = [("error", m) for m in report.errors.get(file, [])] lines += [("warning", m) for m in report.warnings.get(file, [])] - if not lines: - continue print(f"\n{file}") for level, message in lines: print(f" {'x' if level == 'error' else '!'} {message}") annotate(level, file, message) - errors = sum(len(m) for m in blocking.values()) - warnings = sum(len(m) for m in report.warnings.values()) + sum(len(m) for m in inherited.values()) + errors = sum(len(report.errors.get(f, [])) for f in shown) + warnings = sum(len(report.warnings.get(f, [])) for f in shown) + scope = "" if changed is None else f" ({sum(1 for f in files if f in changed)} in this pull request)" print( - f"\n{len(files)} templates checked against {len(catalogue.actions)} actions and " + f"\n{len(files)} templates{scope} checked against {len(catalogue.actions)} actions and " f"{len(catalogue.triggers)} triggers: {errors} error(s), {warnings} warning(s)." ) + if changed is not None: + elsewhere = sorted(f for f in report.errors if f not in changed) + if elsewhere: + print( + f"Already on main, in files this pull request does not touch: errors in {len(elsewhere)} " + f"template(s) ({', '.join(elsewhere)}). They do not block this pull request." + ) return 1 if errors else 0