id: alertmanager-silence-safety-gate
namespace: company.team
description: |
Find active Alertmanager silences that are too long or too broad.
Save an audit report. Fail the flow if any silence breaks the policy.
inputs:
- id: max_silence_hours
type: INT
defaults: 24
description: Maximum start-to-end duration for an active silence, in hours (1-720).
- id: scope_labels
type: STRING
defaults: "alertname,service,namespace,job"
description: Comma-separated label names. An active silence must contain an
exact positive matcher on at least one of these labels.
triggers:
- id: check_silences
type: io.kestra.plugin.core.trigger.Schedule
cron: "*/15 * * * *"
disabled: true
description: Enable this schedule after the API, alert route, and policy tests pass.
tasks:
- id: download_silences
type: io.kestra.plugin.core.http.Download
description: Read all Alertmanager silences. Reject redirects and non-success responses.
uri: "{{ secret('ALERTMANAGER_URL') }}/api/v2/silences"
method: GET
headers:
Accept: application/json
Authorization: "Bearer {{ secret('ALERTMANAGER_TOKEN') }}"
options:
followRedirects: false
allowFailed: false
saveAs: silences.json
- id: inspect_silences
type: io.kestra.plugin.scripts.node.Script
description: Check active silence duration, label scope, and response integrity.
containerImage: node:22-alpine
env:
MAX_HOURS: "{{ inputs.max_silence_hours }}"
SCOPE_LABELS: "{{ inputs.scope_labels }}"
inputFiles:
silences.json: "{{ outputs.download_silences.uri }}"
outputFiles:
- alertmanager-silence-report.json
script: |
function inspect(items,cfg,now){
const findings=[],records=[];
if(!Array.isArray(items))throw Error("Alertmanager response must be an array");
if(items.length>10000)throw Error("Silence count exceeds audit limit");
const seenIds=new Set();
for(let i=0;i<items.length;i++){
const s=items[i], reasons=[];
if(!s||typeof s!=="object"||Array.isArray(s)){findings.push({id:"index-"+i,reasons:["Silence record is not an object"]});continue;}
const id=typeof s.id==="string"&&s.id.length>0?s.id:"index-"+i;
if(typeof s.id!=="string"||s.id.trim()==="")reasons.push("Silence ID is missing or invalid");
if(seenIds.has(id))reasons.push("Silence ID appears more than once");
seenIds.add(id);
const state=s.status&&s.status.state;
const timestamp=x=>typeof x==="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(x)?Date.parse(x):NaN;
const start=timestamp(s.startsAt),end=timestamp(s.endsAt);
if(!["active","pending","expired"].includes(state))reasons.push("Silence state is invalid");
if(!Number.isFinite(start)||!Number.isFinite(end)||end<=start)reasons.push("Silence timestamps are invalid");
if(!Array.isArray(s.matchers)||s.matchers.length===0)reasons.push("Silence has no matchers");
else if(s.matchers.some(m=>!m||typeof m.name!=="string"||!m.name||typeof m.value!=="string"||typeof m.isRegex!=="boolean"||(m.isEqual!==undefined&&typeof m.isEqual!=="boolean")))reasons.push("Silence matcher fields are invalid");
if(reasons.length){findings.push({id,reasons});continue;}
if(state==="active"){
const duration=(end-start)/3600000;
if(now<start||now>=end)reasons.push("Active state does not match the time window");
if(duration>cfg.max_hours)reasons.push("Silence exceeds the maximum duration");
const exact=s.matchers.some(m=>!m.isRegex&&(m.isEqual===undefined||m.isEqual===true)&&m.value.trim()!==""&&cfg.scope_labels.includes(m.name));
if(!exact)reasons.push("Silence has no approved exact scope matcher");
records.push({id,duration_hours:Math.round(duration*100)/100,status:reasons.length?"BLOCK":"PASS"});
} else if(state==="pending"&&start<=now)reasons.push("Pending silence has already started");
else if(state==="expired"&&end>now)reasons.push("Expired state does not match the end time");
if(reasons.length)findings.push({id,reasons});
}
return {status:findings.length?"BLOCK":"PASS",total_silences:items.length,active_silences:records.length,unsafe_silences:findings.length,findings:findings.slice(0,100),findings_truncated:findings.length>100};
}
const fs=require("fs");
const path=require("path");
const env=process.env;
if(!env.WORKING_DIR)throw Error("Kestra working directory is not set");
const max=Number(env.MAX_HOURS);
const scope=(env.SCOPE_LABELS||"").split(",").map(x=>x.trim()).filter(Boolean);
if(!Number.isSafeInteger(max)||max<1||max>720||!scope.length||scope.some(x=>!/^[A-Za-z_][A-Za-z0-9_]*$/.test(x)))throw Error("Invalid policy inputs");
const raw=fs.readFileSync(path.join(env.WORKING_DIR,"silences.json"),"utf8");
if(Buffer.byteLength(raw,"utf8")>2097152)throw Error("Silence response is larger than 2 MiB");
const result=inspect(JSON.parse(raw),{max_hours:max,scope_labels:scope},Date.now());
fs.writeFileSync(path.join(env.WORKING_DIR,"alertmanager-silence-report.json"),JSON.stringify(result,null,2));
console.log("::"+JSON.stringify({outputs:{status:result.status,unsafe_silences:result.unsafe_silences,active_silences:result.active_silences}})+"::");
console.log("Alertmanager silence policy: "+result.status);
- id: publish_report
type: io.kestra.plugin.core.output.OutputValues
description: Make the audit report available before the final gate.
values:
result: "{{ outputs.inspect_silences.vars.status }}"
report_uri: "{{
outputs.inspect_silences.outputFiles['alertmanager-silence-report.json']
}}"
unsafe_count: "{{ outputs.inspect_silences.vars.unsafe_silences }}"
- id: enforce_policy
type: io.kestra.plugin.core.flow.If
description: Send an alert and fail if a silence violates the policy.
condition: "{{ outputs.inspect_silences.vars.status == 'BLOCK' }}"
then:
- id: notify_silence_risk
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{"text":"Alertmanager silence policy BLOCK. Unsafe silences: {{ outputs.inspect_silences.vars.unsafe_silences }}. Execution: {{ execution.id }}. Check the report at outputs.publish_report.values.report_uri."}
- id: block_unsafe_silences
type: io.kestra.plugin.core.execution.Fail
errorMessage: "An active silence violates the policy. Review
alertmanager-silence-report.json."
else:
- id: log_silence_policy
type: io.kestra.plugin.core.log.Log
message: "Alertmanager silence policy PASS for {{
outputs.inspect_silences.vars.active_silences }} active silences."
errors:
- id: alert_probe_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{"text":"Alertmanager silence audit execution FAILED. This may follow an intentional policy BLOCK or a probe error. Execution: {{ execution.id }}. Check the saved report (if present) and task logs."}
- id: log_probe_failure
type: io.kestra.plugin.core.log.Log
message: "Alertmanager silence audit failed. No PASS verdict was issued.
Execution: {{ execution.id }}."